@cortexkit/opencode-magic-context 0.44.2 → 0.44.3
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/{conflict-warning-hook-1msyvb51.js → conflict-warning-hook-hmpzxep6.js} +3 -3
- package/dist/{derive-budgets-gd2270s0.js → derive-budgets-vjmvh6pz.js} +3 -1
- package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/hidden-single-shot.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/lease.d.ts +1 -1
- package/dist/features/magic-context/dreamer/lease.d.ts.map +1 -1
- package/dist/features/magic-context/memory/project-identity.d.ts +3 -0
- package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
- package/dist/features/magic-context/message-index-async.d.ts +1 -1
- package/dist/features/magic-context/message-index-async.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/features/magic-context/session-project-storage.d.ts +5 -5
- package/dist/features/magic-context/session-project-storage.d.ts.map +1 -1
- package/dist/features/magic-context/storage-embedding-measurements.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -1
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-types.d.ts +1 -0
- package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
- package/dist/hooks/magic-context/derive-budgets.d.ts +4 -0
- package/dist/hooks/magic-context/derive-budgets.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-host-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-persist.d.ts +1 -4
- package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
- package/dist/hooks/magic-context/producer-window-guard.d.ts +4 -1
- package/dist/hooks/magic-context/producer-window-guard.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts +1 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/storage-busy-refusal.d.ts +6 -0
- package/dist/hooks/magic-context/storage-busy-refusal.d.ts.map +1 -1
- package/dist/{index-r9vkp4n9.js → index-33q7s9y2.js} +1 -1
- package/dist/{index-egkfvhms.js → index-4an2p8qa.js} +80 -14
- package/dist/{index-18tjha8g.js → index-638hf49n.js} +1 -1
- package/dist/{index-stb5fg12.js → index-9y5p0d50.js} +31 -1
- package/dist/{index-esxfcz5z.js → index-dgg5y7er.js} +1 -1
- package/dist/{index-3x9caerx.js → index-nf9sk8sh.js} +3 -3
- package/dist/{index-gtzcmv90.js → index-q5p1aqvv.js} +5 -5
- package/dist/{index-40s1xz22.js → index-rdsaxnf2.js} +1 -1
- package/dist/{index-ttdn47aq.js → index-yhm60r53.js} +134 -49
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +453 -226
- package/dist/plugin/dream-timer.d.ts.map +1 -1
- package/dist/plugin/embedding-bootstrap.d.ts.map +1 -1
- package/dist/plugin/messages-transform.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/{read-session-chunk-wmvgnd24.js → read-session-chunk-n072mcq4.js} +2 -2
- package/dist/{recomp-orchestrator-rk40ff15.js → recomp-orchestrator-19tr6zya.js} +6 -6
- package/dist/{send-session-notification-6xsrcxnp.js → send-session-notification-04hvd54c.js} +2 -2
- package/dist/shared/run-token-log.d.ts +13 -0
- package/dist/shared/run-token-log.d.ts.map +1 -0
- package/dist/shared/sqlite.d.ts +7 -0
- package/dist/shared/sqlite.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-t7xgdhdf.js → transform-postprocess-phase-z2mfc5w1.js} +6 -6
- package/dist/v2/hidden-completion.d.ts +7 -1
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/hidden-terminal-error.d.ts +8 -0
- package/dist/v2/hooks/hidden-terminal-error.d.ts.map +1 -0
- package/dist/v2/hooks/tools.d.ts +1 -1
- package/dist/v2/hooks/tools.d.ts.map +1 -1
- package/dist/v2/server.js +584 -153
- package/dist/{wrapup-orchestrator-h8tr10c6.js → wrapup-orchestrator-sy4m56a7.js} +7 -7
- package/package.json +1 -1
- package/src/config/latch-permanence-guard.test.ts +4 -0
- package/src/shared/data-path.test.ts +1 -1
- package/src/shared/models-dev-cache.test.ts +30 -1
- package/src/shared/run-token-log.test.ts +65 -0
- package/src/shared/run-token-log.ts +39 -0
- package/src/shared/sqlite-acquisition-routing.test.ts +19 -11
- package/src/shared/sqlite-pass-scope.test.ts +115 -144
- package/src/shared/sqlite.ts +123 -20
- package/src/shared/storage-busy.test.ts +34 -57
- package/src/shared/write-transaction-attribution.test.ts +13 -11
package/dist/index.js
CHANGED
|
@@ -23,6 +23,9 @@ import {
|
|
|
23
23
|
isDreamerRunnable,
|
|
24
24
|
isHistorianRunnable,
|
|
25
25
|
isCompactionEnabled,
|
|
26
|
+
cortexKitUserConfigBasePath,
|
|
27
|
+
cortexKitProjectConfigBasePath,
|
|
28
|
+
resolveLegacyConfigSources,
|
|
26
29
|
migrateMagicContextConfigLocations,
|
|
27
30
|
string,
|
|
28
31
|
unknown,
|
|
@@ -60,6 +63,8 @@ import {
|
|
|
60
63
|
recordHookInitFailure,
|
|
61
64
|
clearHookInitFailure,
|
|
62
65
|
getLastHookInitFailure,
|
|
66
|
+
setHomeProjectPermission,
|
|
67
|
+
shouldSkipHomeProjectMemory,
|
|
63
68
|
ProjectIdentityError,
|
|
64
69
|
resolveProjectIdentityStrict,
|
|
65
70
|
takeDubiousOwnershipProjectIdentityWarning,
|
|
@@ -397,6 +402,8 @@ import {
|
|
|
397
402
|
readGitFileChangeTimesSince,
|
|
398
403
|
verificationFileExists,
|
|
399
404
|
normalizeVerificationFiles,
|
|
405
|
+
runTokenLog,
|
|
406
|
+
formatRunTokenLog,
|
|
400
407
|
resolveHiddenCompletionExecutor,
|
|
401
408
|
createV1HiddenCompletionExecutor,
|
|
402
409
|
USER_MEMORY_CANDIDATE_TTL_MS,
|
|
@@ -452,7 +459,7 @@ import {
|
|
|
452
459
|
snapRangeToCompartments,
|
|
453
460
|
getActiveCompartmentRun,
|
|
454
461
|
startCompartmentAgent
|
|
455
|
-
} from "./index-
|
|
462
|
+
} from "./index-yhm60r53.js";
|
|
456
463
|
import"./index-sd3egckz.js";
|
|
457
464
|
import {
|
|
458
465
|
canonicalModelIdentity,
|
|
@@ -476,8 +483,9 @@ import {
|
|
|
476
483
|
deriveTriggerBudget2,
|
|
477
484
|
deriveHistorianChunkTokens2,
|
|
478
485
|
resolveKnownHistorianContextLimit2,
|
|
486
|
+
resolveHistorianProducerLimits2,
|
|
479
487
|
resolveHistorianContextLimit2
|
|
480
|
-
} from "./index-
|
|
488
|
+
} from "./index-9y5p0d50.js";
|
|
481
489
|
import {
|
|
482
490
|
resolveOpenCodeDbPath,
|
|
483
491
|
assertOpenCodeStoreGeneration,
|
|
@@ -491,11 +499,12 @@ import {
|
|
|
491
499
|
claimOpenCodeDbDiagnosticOnce,
|
|
492
500
|
Database,
|
|
493
501
|
getSqliteMemoryStats,
|
|
502
|
+
withSqliteBackgroundWriter,
|
|
494
503
|
withSqliteTransformPass,
|
|
495
504
|
withoutSqliteTransformPass,
|
|
496
505
|
isTransientSqliteError,
|
|
497
506
|
SqliteAcquisitionBusyError,
|
|
498
|
-
|
|
507
|
+
withAsyncPrivilegedWriter,
|
|
499
508
|
closeQuietly,
|
|
500
509
|
openCodeDbExists,
|
|
501
510
|
withReadOnlySessionDb,
|
|
@@ -504,7 +513,7 @@ import {
|
|
|
504
513
|
assistantAwaitingTools,
|
|
505
514
|
latestPersistedMessageForRecovery,
|
|
506
515
|
findLastAssistantModelFromOpenCodeDb
|
|
507
|
-
} from "./index-
|
|
516
|
+
} from "./index-4an2p8qa.js";
|
|
508
517
|
import {
|
|
509
518
|
hasMeaningfulUserText2,
|
|
510
519
|
extractTexts2,
|
|
@@ -575,7 +584,7 @@ import {
|
|
|
575
584
|
readRawSessionMessageById2,
|
|
576
585
|
readSessionChunk2,
|
|
577
586
|
readRawSessionSeedTail2
|
|
578
|
-
} from "./index-
|
|
587
|
+
} from "./index-dgg5y7er.js";
|
|
579
588
|
import"./index-kwe03yde.js";
|
|
580
589
|
import {
|
|
581
590
|
getErrorMessage,
|
|
@@ -585,13 +594,13 @@ import {
|
|
|
585
594
|
clearIgnoredMessages2,
|
|
586
595
|
observeIgnoredNotificationEvent2,
|
|
587
596
|
sendStatusNotification2
|
|
588
|
-
} from "./index-
|
|
597
|
+
} from "./index-33q7s9y2.js";
|
|
589
598
|
import {
|
|
590
599
|
detectConflicts,
|
|
591
600
|
resolveCompactionForBoot,
|
|
592
601
|
sendConflictWarning2,
|
|
593
602
|
cleanupConflictWarnings2
|
|
594
|
-
} from "./index-
|
|
603
|
+
} from "./index-638hf49n.js";
|
|
595
604
|
import {
|
|
596
605
|
resolveModelCalibration,
|
|
597
606
|
calibrateBuckets
|
|
@@ -672,12 +681,12 @@ import {
|
|
|
672
681
|
abortSessionFailClosed2,
|
|
673
682
|
evaluateEmergencyFailClosed2,
|
|
674
683
|
runPostTransformPhase2
|
|
675
|
-
} from "./index-
|
|
684
|
+
} from "./index-q5p1aqvv.js";
|
|
676
685
|
import {
|
|
677
686
|
setRecompStarting2,
|
|
678
687
|
setRecompTerminal2,
|
|
679
688
|
runManagedRecomp2
|
|
680
|
-
} from "./index-
|
|
689
|
+
} from "./index-rdsaxnf2.js";
|
|
681
690
|
import {
|
|
682
691
|
isValidSemver,
|
|
683
692
|
compareSemverCore,
|
|
@@ -692,7 +701,7 @@ import {
|
|
|
692
701
|
} from "./index-fmsr7v69.js";
|
|
693
702
|
import {
|
|
694
703
|
runManagedWrapup2
|
|
695
|
-
} from "./index-
|
|
704
|
+
} from "./index-nf9sk8sh.js";
|
|
696
705
|
import {
|
|
697
706
|
logSlowWriteTransaction
|
|
698
707
|
} from "./index-kr5qehbd.js";
|
|
@@ -11244,7 +11253,7 @@ function startLeaseHeartbeat(db, holderId, leaseKey, onLost, intervalOrAcquisiti
|
|
|
11244
11253
|
}
|
|
11245
11254
|
};
|
|
11246
11255
|
beat();
|
|
11247
|
-
const timer = lost ? undefined : setInterval(beat, intervalMs);
|
|
11256
|
+
const timer = lost ? undefined : setInterval(() => withSqliteBackgroundWriter(beat), intervalMs);
|
|
11248
11257
|
return {
|
|
11249
11258
|
stop: () => {
|
|
11250
11259
|
if (timer)
|
|
@@ -12618,8 +12627,10 @@ async function runHiddenSingleShotPrompt(args) {
|
|
|
12618
12627
|
callContext: args.callContext,
|
|
12619
12628
|
fetchOutput: () => args.executor.collect(handle, 50),
|
|
12620
12629
|
validateOutput: (completion) => {
|
|
12630
|
+
const tokens = completion.tokenLog ?? runTokenLog(undefined);
|
|
12631
|
+
sessionLog(args.parentSessionId ?? "dreamer", `${args.callContext} response_chars=${(completion.text ?? completion.reasoning ?? "").length} ${formatRunTokenLog(tokens)}`);
|
|
12621
12632
|
if (completion.lengthCapped) {
|
|
12622
|
-
throw new Error(completion.reasoning && !completion.text ? `${args.callContext} ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text) — set dreamer.maxTokens or use a low-reasoning model` : `${args.callContext} returned length-capped output`);
|
|
12633
|
+
throw new Error(completion.reasoning && !completion.text ? `${args.callContext} ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text; ${formatRunTokenLog(tokens)}) — set dreamer.maxTokens or use a low-reasoning model` : `${args.callContext} returned length-capped output; ${formatRunTokenLog(tokens)}`);
|
|
12623
12634
|
}
|
|
12624
12635
|
const text = completion.text;
|
|
12625
12636
|
if (!text && !args.allowEmpty)
|
|
@@ -13273,8 +13284,10 @@ async function classifyOneChunk(args, chunk, anchors, sliceMs, signal) {
|
|
|
13273
13284
|
fetchOutput: () => executor.collect(opened, 50),
|
|
13274
13285
|
validateOutput: (completion) => {
|
|
13275
13286
|
const messages = completion.messages ?? [];
|
|
13287
|
+
const tokens = completion.tokenLog ?? runTokenLog(undefined);
|
|
13288
|
+
sessionLog(args.parentSessionId ?? "dreamer", `dreamer:classify response_chars=${(completion.text ?? completion.reasoning ?? "").length} ${formatRunTokenLog(tokens)}`);
|
|
13276
13289
|
if (completion.lengthCapped) {
|
|
13277
|
-
throw new Error(completion.reasoning && !completion.text ? `classify ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text) — set dreamer.maxTokens or use a low-reasoning model` :
|
|
13290
|
+
throw new Error(completion.reasoning && !completion.text ? `classify ran out of output budget while reasoning (length-capped at ${completion.usage.output} tokens, no text; ${formatRunTokenLog(tokens)}) — set dreamer.maxTokens or use a low-reasoning model` : `classify returned length-capped output; ${formatRunTokenLog(tokens)}`);
|
|
13278
13291
|
}
|
|
13279
13292
|
const text = completion.text;
|
|
13280
13293
|
if (!text)
|
|
@@ -20050,6 +20063,205 @@ function clearDreamerTickFailure(db) {
|
|
|
20050
20063
|
db.prepare("DELETE FROM schema_migrations_meta WHERE key = ?").run(DREAMER_TICK_FAILURE_KEY);
|
|
20051
20064
|
}
|
|
20052
20065
|
|
|
20066
|
+
// src/hooks/magic-context/lkg-persist.ts
|
|
20067
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
20068
|
+
function parseStringArray(value) {
|
|
20069
|
+
if (typeof value !== "string")
|
|
20070
|
+
return null;
|
|
20071
|
+
let parsed;
|
|
20072
|
+
try {
|
|
20073
|
+
parsed = JSON.parse(value);
|
|
20074
|
+
} catch {
|
|
20075
|
+
return null;
|
|
20076
|
+
}
|
|
20077
|
+
if (!Array.isArray(parsed))
|
|
20078
|
+
return null;
|
|
20079
|
+
const result = [];
|
|
20080
|
+
for (const entry of parsed) {
|
|
20081
|
+
if (typeof entry !== "string" || entry.length === 0)
|
|
20082
|
+
return null;
|
|
20083
|
+
result.push(entry);
|
|
20084
|
+
}
|
|
20085
|
+
return result;
|
|
20086
|
+
}
|
|
20087
|
+
function parseNullableString(value) {
|
|
20088
|
+
if (value === null || value === undefined)
|
|
20089
|
+
return null;
|
|
20090
|
+
return typeof value === "string" ? value : undefined;
|
|
20091
|
+
}
|
|
20092
|
+
function parseNullableInteger(value) {
|
|
20093
|
+
if (value === null || value === undefined)
|
|
20094
|
+
return;
|
|
20095
|
+
return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
|
|
20096
|
+
}
|
|
20097
|
+
function parsePersistedLkgSlot(row) {
|
|
20098
|
+
if (!row || typeof row !== "object")
|
|
20099
|
+
return;
|
|
20100
|
+
const record = row;
|
|
20101
|
+
const jsonPrefix = record.json_prefix;
|
|
20102
|
+
const lastInputMessageId = record.last_input_message_id;
|
|
20103
|
+
const capturedAt = record.captured_at;
|
|
20104
|
+
let inputIdsRaw = record.input_id_seq;
|
|
20105
|
+
let piOutputEntryIds;
|
|
20106
|
+
if (typeof inputIdsRaw === "string") {
|
|
20107
|
+
try {
|
|
20108
|
+
const metadata = JSON.parse(inputIdsRaw);
|
|
20109
|
+
if (metadata && !Array.isArray(metadata) && metadata.version === 1 && Array.isArray(metadata.piOutputEntryIds)) {
|
|
20110
|
+
if (!metadata.piOutputEntryIds.every((id) => id === null || typeof id === "string" && id.length > 0))
|
|
20111
|
+
return;
|
|
20112
|
+
piOutputEntryIds = metadata.piOutputEntryIds;
|
|
20113
|
+
inputIdsRaw = JSON.stringify(metadata.inputIds);
|
|
20114
|
+
}
|
|
20115
|
+
} catch {
|
|
20116
|
+
return;
|
|
20117
|
+
}
|
|
20118
|
+
}
|
|
20119
|
+
const inputIdSeq = parseStringArray(inputIdsRaw);
|
|
20120
|
+
const inputContentDigests = parseStringArray(record.input_content_digests);
|
|
20121
|
+
const modelKey = parseNullableString(record.model_key);
|
|
20122
|
+
const providerKey = parseNullableString(record.provider_key);
|
|
20123
|
+
if (typeof jsonPrefix !== "string" || typeof lastInputMessageId !== "string" || lastInputMessageId.length === 0 || typeof capturedAt !== "number" || !Number.isFinite(capturedAt) || inputIdSeq === null || inputContentDigests === null || inputContentDigests.length !== inputIdSeq.length || modelKey === undefined || providerKey === undefined) {
|
|
20124
|
+
return;
|
|
20125
|
+
}
|
|
20126
|
+
if (piOutputEntryIds) {
|
|
20127
|
+
try {
|
|
20128
|
+
const output = JSON.parse(jsonPrefix);
|
|
20129
|
+
const inputs = new Set(inputIdSeq);
|
|
20130
|
+
if (!Array.isArray(output) || output.length !== piOutputEntryIds.length || piOutputEntryIds.some((id) => id !== null && !inputs.has(id)))
|
|
20131
|
+
return;
|
|
20132
|
+
} catch {
|
|
20133
|
+
return;
|
|
20134
|
+
}
|
|
20135
|
+
}
|
|
20136
|
+
let inputContentSignatures;
|
|
20137
|
+
if (record.input_content_signatures !== null && record.input_content_signatures !== undefined) {
|
|
20138
|
+
const parsed = parseStringArray(record.input_content_signatures);
|
|
20139
|
+
if (parsed === null || parsed.length !== inputIdSeq.length)
|
|
20140
|
+
return;
|
|
20141
|
+
inputContentSignatures = parsed;
|
|
20142
|
+
}
|
|
20143
|
+
const slot = {
|
|
20144
|
+
jsonPrefix,
|
|
20145
|
+
inputIdSeq,
|
|
20146
|
+
inputContentDigests,
|
|
20147
|
+
lastInputMessageId,
|
|
20148
|
+
modelKey,
|
|
20149
|
+
providerKey,
|
|
20150
|
+
capturedAt
|
|
20151
|
+
};
|
|
20152
|
+
if (inputContentSignatures)
|
|
20153
|
+
slot.inputContentSignatures = inputContentSignatures;
|
|
20154
|
+
if (piOutputEntryIds)
|
|
20155
|
+
slot.piOutputEntryIds = piOutputEntryIds;
|
|
20156
|
+
const rowVersion = parseNullableInteger(record.row_version);
|
|
20157
|
+
if (rowVersion !== undefined)
|
|
20158
|
+
slot.rowVersion = rowVersion;
|
|
20159
|
+
const captureSequence = parseNullableInteger(record.capture_sequence);
|
|
20160
|
+
if (captureSequence !== undefined)
|
|
20161
|
+
slot.captureSequence = captureSequence;
|
|
20162
|
+
return slot;
|
|
20163
|
+
}
|
|
20164
|
+
var persistedFingerprints = new WeakMap;
|
|
20165
|
+
function saveLkgSlotToDb(db, sessionId, slot) {
|
|
20166
|
+
const fingerprint = createHash10("sha256").update(JSON.stringify([
|
|
20167
|
+
slot.jsonPrefix,
|
|
20168
|
+
slot.inputIdSeq,
|
|
20169
|
+
slot.inputContentDigests,
|
|
20170
|
+
slot.inputContentSignatures,
|
|
20171
|
+
slot.piOutputEntryIds,
|
|
20172
|
+
slot.lastInputMessageId,
|
|
20173
|
+
slot.modelKey,
|
|
20174
|
+
slot.providerKey,
|
|
20175
|
+
slot.rowVersion,
|
|
20176
|
+
slot.captureSequence
|
|
20177
|
+
])).digest("hex");
|
|
20178
|
+
let saved = persistedFingerprints.get(db);
|
|
20179
|
+
if (saved?.get(sessionId) === fingerprint)
|
|
20180
|
+
return true;
|
|
20181
|
+
try {
|
|
20182
|
+
db.prepare(`INSERT INTO lkg_slots (
|
|
20183
|
+
session_id, json_prefix, input_id_seq, input_content_digests,
|
|
20184
|
+
input_content_signatures, last_input_message_id, model_key, provider_key,
|
|
20185
|
+
captured_at, row_version, capture_sequence
|
|
20186
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
20187
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
20188
|
+
json_prefix = excluded.json_prefix,
|
|
20189
|
+
input_id_seq = excluded.input_id_seq,
|
|
20190
|
+
input_content_digests = excluded.input_content_digests,
|
|
20191
|
+
input_content_signatures = excluded.input_content_signatures,
|
|
20192
|
+
last_input_message_id = excluded.last_input_message_id,
|
|
20193
|
+
model_key = excluded.model_key,
|
|
20194
|
+
provider_key = excluded.provider_key,
|
|
20195
|
+
captured_at = excluded.captured_at,
|
|
20196
|
+
row_version = excluded.row_version,
|
|
20197
|
+
capture_sequence = excluded.capture_sequence`).run(sessionId, slot.jsonPrefix, JSON.stringify(slot.piOutputEntryIds ? {
|
|
20198
|
+
version: 1,
|
|
20199
|
+
inputIds: slot.inputIdSeq,
|
|
20200
|
+
piOutputEntryIds: slot.piOutputEntryIds
|
|
20201
|
+
} : slot.inputIdSeq), JSON.stringify(slot.inputContentDigests), slot.inputContentSignatures ? JSON.stringify(slot.inputContentSignatures) : null, slot.lastInputMessageId, slot.modelKey, slot.providerKey, slot.capturedAt, slot.rowVersion ?? null, slot.captureSequence ?? null);
|
|
20202
|
+
if (!saved) {
|
|
20203
|
+
saved = new Map;
|
|
20204
|
+
persistedFingerprints.set(db, saved);
|
|
20205
|
+
}
|
|
20206
|
+
if (saved.size >= 1000) {
|
|
20207
|
+
const oldest = saved.keys().next().value;
|
|
20208
|
+
if (oldest !== undefined)
|
|
20209
|
+
saved.delete(oldest);
|
|
20210
|
+
}
|
|
20211
|
+
saved.set(sessionId, fingerprint);
|
|
20212
|
+
return true;
|
|
20213
|
+
} catch (error) {
|
|
20214
|
+
sessionLog(sessionId, "LKG snapshot persistence failed (in-memory slot retained):", error);
|
|
20215
|
+
return false;
|
|
20216
|
+
}
|
|
20217
|
+
}
|
|
20218
|
+
function clearPersistedLkgSlot(db, sessionId) {
|
|
20219
|
+
try {
|
|
20220
|
+
db.prepare("DELETE FROM lkg_slots WHERE session_id = ?").run(sessionId);
|
|
20221
|
+
persistedFingerprints.get(db)?.delete(sessionId);
|
|
20222
|
+
} catch (error) {
|
|
20223
|
+
sessionLog(sessionId, "LKG snapshot durable clear failed:", error);
|
|
20224
|
+
}
|
|
20225
|
+
}
|
|
20226
|
+
function loadPersistedLkgSlot(db, sessionId) {
|
|
20227
|
+
let row;
|
|
20228
|
+
try {
|
|
20229
|
+
row = db.prepare("SELECT * FROM lkg_slots WHERE session_id = ?").get(sessionId);
|
|
20230
|
+
} catch (error) {
|
|
20231
|
+
sessionLog(sessionId, "LKG snapshot durable load failed:", error);
|
|
20232
|
+
return;
|
|
20233
|
+
}
|
|
20234
|
+
if (!row)
|
|
20235
|
+
return;
|
|
20236
|
+
const slot = parsePersistedLkgSlot(row);
|
|
20237
|
+
if (!slot) {
|
|
20238
|
+
clearPersistedLkgSlot(db, sessionId);
|
|
20239
|
+
return;
|
|
20240
|
+
}
|
|
20241
|
+
return slot;
|
|
20242
|
+
}
|
|
20243
|
+
function pruneStaleLkgSlots(db, now = Date.now()) {
|
|
20244
|
+
const previousTimeout = db.prepare("PRAGMA busy_timeout").get();
|
|
20245
|
+
try {
|
|
20246
|
+
db.exec("PRAGMA busy_timeout = 0");
|
|
20247
|
+
const result = db.prepare(`DELETE FROM lkg_slots WHERE captured_at < ? AND NOT EXISTS (
|
|
20248
|
+
SELECT 1 FROM session_projects sp
|
|
20249
|
+
WHERE sp.session_id = lkg_slots.session_id AND sp.updated_at >= ?
|
|
20250
|
+
)`).run(now - 7 * 24 * 60 * 60 * 1000, now - 7 * 24 * 60 * 60 * 1000);
|
|
20251
|
+
if (result.changes)
|
|
20252
|
+
persistedFingerprints.delete(db);
|
|
20253
|
+
return result.changes;
|
|
20254
|
+
} finally {
|
|
20255
|
+
db.exec(`PRAGMA busy_timeout = ${Number(previousTimeout.timeout) || 0}`);
|
|
20256
|
+
}
|
|
20257
|
+
}
|
|
20258
|
+
function createDbLkgPersistence(db) {
|
|
20259
|
+
return {
|
|
20260
|
+
load: (sessionId) => loadPersistedLkgSlot(db, sessionId),
|
|
20261
|
+
clear: (sessionId) => clearPersistedLkgSlot(db, sessionId)
|
|
20262
|
+
};
|
|
20263
|
+
}
|
|
20264
|
+
|
|
20053
20265
|
// src/plugin/dream-timer.ts
|
|
20054
20266
|
var DREAM_TIMER_INTERVAL_MS = 15 * 60 * 1000;
|
|
20055
20267
|
var GIT_COMMIT_BACKLOG_DRAIN_MAX_MS = 5 * 60 * 1000;
|
|
@@ -20212,6 +20424,11 @@ function persistTickOutcome(db, failure) {
|
|
|
20212
20424
|
}
|
|
20213
20425
|
}
|
|
20214
20426
|
async function runMessageHistoryMaintenance(db) {
|
|
20427
|
+
try {
|
|
20428
|
+
pruneStaleLkgSlots(db);
|
|
20429
|
+
} catch (error) {
|
|
20430
|
+
log("[magic-context] LKG pruning deferred:", error);
|
|
20431
|
+
}
|
|
20215
20432
|
const cleanup = retryPendingSessionCleanups(db);
|
|
20216
20433
|
if (cleanup.cleared > 0 || cleanup.failedSessionIds.length > 0) {
|
|
20217
20434
|
log(`[message-index] pending session cleanup: cleared=${cleanup.cleared} failed=${cleanup.failedSessionIds.length}`);
|
|
@@ -20489,8 +20706,11 @@ function createDreamTimerModuleClient(moduleClient) {
|
|
|
20489
20706
|
};
|
|
20490
20707
|
}
|
|
20491
20708
|
|
|
20709
|
+
// src/plugin/embedding-bootstrap.ts
|
|
20710
|
+
import { readFileSync as readFileSync7, statSync as statSync4 } from "node:fs";
|
|
20711
|
+
|
|
20492
20712
|
// src/plugin/embedding-bootstrap-helpers.ts
|
|
20493
|
-
import { createHash as
|
|
20713
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
20494
20714
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
20495
20715
|
"embedding.api_key",
|
|
20496
20716
|
"embedding.endpoint",
|
|
@@ -20538,7 +20758,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
20538
20758
|
];
|
|
20539
20759
|
var loggedFailureSignatures = new Map;
|
|
20540
20760
|
function sha256Prefix(value, length = 16) {
|
|
20541
|
-
return
|
|
20761
|
+
return createHash11("sha256").update(value).digest("hex").slice(0, length);
|
|
20542
20762
|
}
|
|
20543
20763
|
function warningLooksEmbeddingRelated(message) {
|
|
20544
20764
|
const lower = message.toLowerCase();
|
|
@@ -20733,12 +20953,41 @@ async function resolveEmbeddingRouting(args) {
|
|
|
20733
20953
|
}
|
|
20734
20954
|
|
|
20735
20955
|
// src/plugin/embedding-bootstrap.ts
|
|
20736
|
-
|
|
20956
|
+
var configCache = new Map;
|
|
20957
|
+
function loadRegistrationConfig(directory) {
|
|
20958
|
+
const legacy = resolveLegacyConfigSources(directory);
|
|
20959
|
+
const paths = [cortexKitUserConfigBasePath(), cortexKitProjectConfigBasePath(directory)].flatMap((base) => [`${base}.jsonc`, `${base}.json`]).concat(legacy.user.map((source) => source.path), legacy.project.map((source) => source.path));
|
|
20960
|
+
const key = paths.map((path) => {
|
|
20961
|
+
const stat = statSync4(path, { throwIfNoEntry: false });
|
|
20962
|
+
return `${path}:${stat?.mtimeMs ?? "missing"}:${stat?.size ?? 0}`;
|
|
20963
|
+
}).join("|");
|
|
20964
|
+
const cached = configCache.get(directory);
|
|
20965
|
+
if (cached?.key === key)
|
|
20966
|
+
return cached.detailed;
|
|
20737
20967
|
const detailed = loadPluginConfigDetailed(directory);
|
|
20968
|
+
const dynamic = paths.some((path) => {
|
|
20969
|
+
try {
|
|
20970
|
+
return /\{(?:env|file):/.test(readFileSync7(path, "utf8"));
|
|
20971
|
+
} catch {
|
|
20972
|
+
return false;
|
|
20973
|
+
}
|
|
20974
|
+
});
|
|
20975
|
+
if (!dynamic) {
|
|
20976
|
+
if (configCache.size >= 64) {
|
|
20977
|
+
const oldest = configCache.keys().next().value;
|
|
20978
|
+
if (oldest !== undefined)
|
|
20979
|
+
configCache.delete(oldest);
|
|
20980
|
+
}
|
|
20981
|
+
configCache.set(directory, { key, detailed });
|
|
20982
|
+
} else
|
|
20983
|
+
configCache.delete(directory);
|
|
20984
|
+
return detailed;
|
|
20985
|
+
}
|
|
20986
|
+
async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db) {
|
|
20987
|
+
const detailed = loadRegistrationConfig(directory);
|
|
20738
20988
|
const projectIdentity = resolveProjectIdentityForSession(directory, detailed.config.allow_home_project);
|
|
20739
20989
|
if (!projectIdentity)
|
|
20740
20990
|
return;
|
|
20741
|
-
invalidateProject(projectIdentity);
|
|
20742
20991
|
if (isConfigLoadUntrusted(detailed)) {
|
|
20743
20992
|
handleUntrustedLoad(db, projectIdentity, directory, detailed);
|
|
20744
20993
|
return;
|
|
@@ -20755,7 +21004,10 @@ async function ensureProjectRegisteredFromOpenCodeDirectory(directory, db) {
|
|
|
20755
21004
|
memoryEnabled: detailed.config.memory.enabled,
|
|
20756
21005
|
gitCommitEnabled: detailed.config.memory.git_commit_indexing.enabled
|
|
20757
21006
|
};
|
|
20758
|
-
|
|
21007
|
+
const before = getProjectEmbeddingSnapshot(projectIdentity);
|
|
21008
|
+
const registered = registerProjectEmbedding(db, projectIdentity, routing.primary, features, directory);
|
|
21009
|
+
if (!before || before.providerIdentity !== registered.providerIdentity || before.runtimeFingerprint !== registered.runtimeFingerprint)
|
|
21010
|
+
invalidateProject(projectIdentity);
|
|
20759
21011
|
if (routing.shadow) {
|
|
20760
21012
|
registerProjectShadowEmbedding(db, projectIdentity, routing.shadow, directory);
|
|
20761
21013
|
} else {
|
|
@@ -21323,7 +21575,7 @@ async function reconcileSessionIndex(db, sessionId, readMessages) {
|
|
|
21323
21575
|
const messages = readMessages.readPage ? readMessages.readPage(sessionId, cursor, RECONCILIATION_BATCH_SIZE, finalWatermark) : (fallbackSnapshot ?? []).filter((message) => message.ordinal > cursor && message.ordinal <= pageEnd);
|
|
21324
21576
|
const retainedMessages = fallbackSnapshot ?? messages;
|
|
21325
21577
|
heapHolder.activeReconcilerBuffers.set(sessionId, retainedMessages);
|
|
21326
|
-
indexMessagesAfterOrdinal(db, sessionId, messages, cursor, pageEnd);
|
|
21578
|
+
withSqliteBackgroundWriter(() => indexMessagesAfterOrdinal(db, sessionId, messages, cursor, pageEnd));
|
|
21327
21579
|
const nextCursor = getMessageIndexReconciliationStartOrdinal(db, sessionId);
|
|
21328
21580
|
if (nextCursor <= cursor)
|
|
21329
21581
|
break;
|
|
@@ -21349,6 +21601,8 @@ function scheduleReconciliation(db, sessionId, readMessages) {
|
|
|
21349
21601
|
defer(() => {
|
|
21350
21602
|
reconcileSessionIndex(db, sessionId, readMessages).catch((error) => {
|
|
21351
21603
|
logIndexingError(sessionId, "reconciliation", error);
|
|
21604
|
+
if (isDatabaseLockedError(error))
|
|
21605
|
+
setTimeout(() => scheduleReconciliation(db, sessionId, readMessages), 1000).unref();
|
|
21352
21606
|
}).finally(() => {
|
|
21353
21607
|
heapHolder.reconciliationScheduledSessions.delete(sessionId);
|
|
21354
21608
|
});
|
|
@@ -21378,7 +21632,7 @@ function scheduleIncrementalIndex(db, sessionId, messageId, messageSource) {
|
|
|
21378
21632
|
return;
|
|
21379
21633
|
}
|
|
21380
21634
|
const wasReconciled = heapHolder.reconciledSessions.delete(sessionId);
|
|
21381
|
-
indexSingleMessage(db, sessionId, message);
|
|
21635
|
+
withSqliteBackgroundWriter(() => indexSingleMessage(db, sessionId, message));
|
|
21382
21636
|
const finalWatermark = getLastIndexedOrdinal(db, sessionId);
|
|
21383
21637
|
if (wasReconciled && isMessageIndexReconciledThrough(db, sessionId, finalWatermark)) {
|
|
21384
21638
|
heapHolder.reconciledSessions.add(sessionId);
|
|
@@ -21387,6 +21641,8 @@ function scheduleIncrementalIndex(db, sessionId, messageId, messageSource) {
|
|
|
21387
21641
|
}).catch((error) => {
|
|
21388
21642
|
heapHolder.reconciledSessions.delete(sessionId);
|
|
21389
21643
|
logIndexingError(sessionId, `incremental index for ${messageId}`, error);
|
|
21644
|
+
if (isDatabaseLockedError(error))
|
|
21645
|
+
setTimeout(() => scheduleIncrementalIndex(db, sessionId, messageId, messageSource), 1000).unref();
|
|
21390
21646
|
}).finally(() => {
|
|
21391
21647
|
heapHolder.pendingIncrementalKeys.delete(schedulingKey);
|
|
21392
21648
|
});
|
|
@@ -26023,11 +26279,14 @@ function buildSidebarSnapshot(db, sessionId, directory, liveSessionState, inject
|
|
|
26023
26279
|
};
|
|
26024
26280
|
return applyStickySnapshotCache(sessionId, fresh);
|
|
26025
26281
|
} catch (err) {
|
|
26026
|
-
|
|
26282
|
+
if (!(err instanceof ProjectIdentityError && err.errorClass === "home_project_disabled"))
|
|
26283
|
+
log("[rpc] sidebar-snapshot error:", err);
|
|
26027
26284
|
throw err;
|
|
26028
26285
|
}
|
|
26029
26286
|
}
|
|
26030
26287
|
function buildSidebarSnapshotRpcResponse(db, sessionId, directory, liveSessionState, injectionBudgetTokens, config, moduleStatus, compactionEnabled = true) {
|
|
26288
|
+
if (shouldSkipHomeProjectMemory(directory))
|
|
26289
|
+
return { sessionId, disabled: true };
|
|
26031
26290
|
try {
|
|
26032
26291
|
return buildSidebarSnapshot(db, sessionId, directory, liveSessionState, injectionBudgetTokens, config, moduleStatus, compactionEnabled);
|
|
26033
26292
|
} catch {
|
|
@@ -26044,7 +26303,7 @@ function safeTickFailure(db) {
|
|
|
26044
26303
|
function buildStatusDetail(db, sessionId, directory, modelKey, config, liveSessionState, injectionBudgetTokens, moduleStatus, compactionEnabled = true) {
|
|
26045
26304
|
const base = buildSidebarSnapshot(db, sessionId, directory, liveSessionState, injectionBudgetTokens, config, moduleStatus, compactionEnabled);
|
|
26046
26305
|
const rustMode = config?.transform_mode === "rust";
|
|
26047
|
-
const projectIdentity = rustMode ? resolveProjectIdentity(directory) : null;
|
|
26306
|
+
const projectIdentity = rustMode && !shouldSkipHomeProjectMemory(directory) ? resolveProjectIdentity(directory) : null;
|
|
26048
26307
|
const moduleMemoryAuthority = moduleStatus?.authority?.memories;
|
|
26049
26308
|
const moduleMemoryState = moduleMemoryAuthority?.state;
|
|
26050
26309
|
const moduleFeedHead = moduleStatus?.memory_mirror?.feed_head;
|
|
@@ -26487,6 +26746,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26487
26746
|
rpcServer.handle("status-detail", async (params) => {
|
|
26488
26747
|
const sessionId = String(params.sessionId ?? "");
|
|
26489
26748
|
const dir = String(params.directory ?? directory);
|
|
26749
|
+
if (shouldSkipHomeProjectMemory(dir))
|
|
26750
|
+
return { sessionId, disabled: true };
|
|
26490
26751
|
const modelKey = params.modelKey ? String(params.modelKey) : undefined;
|
|
26491
26752
|
const db = readDatabase();
|
|
26492
26753
|
if (!db || !sessionId)
|
|
@@ -26507,6 +26768,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26507
26768
|
rpcServer.handle("embed-detail", async (params) => {
|
|
26508
26769
|
const sessionId = String(params.sessionId ?? "");
|
|
26509
26770
|
const dir = String(params.directory ?? directory);
|
|
26771
|
+
if (shouldSkipHomeProjectMemory(dir))
|
|
26772
|
+
return { sessionId, disabled: true };
|
|
26510
26773
|
const db = readDatabase();
|
|
26511
26774
|
if (!db || !sessionId)
|
|
26512
26775
|
return { error: "unavailable" };
|
|
@@ -26534,7 +26797,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26534
26797
|
return { count: buildCompartmentCount(db, sessionId, moduleStatus) };
|
|
26535
26798
|
});
|
|
26536
26799
|
const buildManagedCtx = async (db) => {
|
|
26537
|
-
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await import("./derive-budgets-
|
|
26800
|
+
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await import("./derive-budgets-vjmvh6pz.js");
|
|
26538
26801
|
const { resolveHistorianModel } = await import("./model-resolution-dxatzjde.js");
|
|
26539
26802
|
const { userMemoryCollectionEnabled } = await import("./task-config-2bm68628.js");
|
|
26540
26803
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 600000;
|
|
@@ -26568,8 +26831,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26568
26831
|
const db = readDatabase();
|
|
26569
26832
|
if (!db)
|
|
26570
26833
|
return { ok: false, error: "db unavailable" };
|
|
26571
|
-
const { runManagedRecomp } = await import("./recomp-orchestrator-
|
|
26572
|
-
const { sendIgnoredMessage } = await import("./send-session-notification-
|
|
26834
|
+
const { runManagedRecomp } = await import("./recomp-orchestrator-19tr6zya.js");
|
|
26835
|
+
const { sendIgnoredMessage } = await import("./send-session-notification-04hvd54c.js");
|
|
26573
26836
|
log(`[rpc] recomp requested for session ${sessionId}`);
|
|
26574
26837
|
const ctx = await buildManagedCtx(db);
|
|
26575
26838
|
runManagedRecomp(ctx, sessionId).then((message) => {
|
|
@@ -26627,7 +26890,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26627
26890
|
const db = readDatabase();
|
|
26628
26891
|
if (!db)
|
|
26629
26892
|
return { ok: false, error: "db unavailable" };
|
|
26630
|
-
const { runManagedWrapup } = await import("./wrapup-orchestrator-
|
|
26893
|
+
const { runManagedWrapup } = await import("./wrapup-orchestrator-sy4m56a7.js");
|
|
26631
26894
|
const model = liveSessionState.liveModelBySession.get(sessionId);
|
|
26632
26895
|
const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
|
|
26633
26896
|
const ctx = {
|
|
@@ -27493,162 +27756,6 @@ class EmergencyFailClosedError extends Error {
|
|
|
27493
27756
|
}
|
|
27494
27757
|
}
|
|
27495
27758
|
|
|
27496
|
-
// src/hooks/magic-context/lkg-persist.ts
|
|
27497
|
-
function parseStringArray(value) {
|
|
27498
|
-
if (typeof value !== "string")
|
|
27499
|
-
return null;
|
|
27500
|
-
let parsed;
|
|
27501
|
-
try {
|
|
27502
|
-
parsed = JSON.parse(value);
|
|
27503
|
-
} catch {
|
|
27504
|
-
return null;
|
|
27505
|
-
}
|
|
27506
|
-
if (!Array.isArray(parsed))
|
|
27507
|
-
return null;
|
|
27508
|
-
const result = [];
|
|
27509
|
-
for (const entry of parsed) {
|
|
27510
|
-
if (typeof entry !== "string" || entry.length === 0)
|
|
27511
|
-
return null;
|
|
27512
|
-
result.push(entry);
|
|
27513
|
-
}
|
|
27514
|
-
return result;
|
|
27515
|
-
}
|
|
27516
|
-
function parseNullableString(value) {
|
|
27517
|
-
if (value === null || value === undefined)
|
|
27518
|
-
return null;
|
|
27519
|
-
return typeof value === "string" ? value : undefined;
|
|
27520
|
-
}
|
|
27521
|
-
function parseNullableInteger(value) {
|
|
27522
|
-
if (value === null || value === undefined)
|
|
27523
|
-
return;
|
|
27524
|
-
return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
|
|
27525
|
-
}
|
|
27526
|
-
function parsePersistedLkgSlot(row) {
|
|
27527
|
-
if (!row || typeof row !== "object")
|
|
27528
|
-
return;
|
|
27529
|
-
const record = row;
|
|
27530
|
-
const jsonPrefix = record.json_prefix;
|
|
27531
|
-
const lastInputMessageId = record.last_input_message_id;
|
|
27532
|
-
const capturedAt = record.captured_at;
|
|
27533
|
-
let inputIdsRaw = record.input_id_seq;
|
|
27534
|
-
let piOutputEntryIds;
|
|
27535
|
-
if (typeof inputIdsRaw === "string") {
|
|
27536
|
-
try {
|
|
27537
|
-
const metadata = JSON.parse(inputIdsRaw);
|
|
27538
|
-
if (metadata && !Array.isArray(metadata) && metadata.version === 1 && Array.isArray(metadata.piOutputEntryIds)) {
|
|
27539
|
-
if (!metadata.piOutputEntryIds.every((id) => id === null || typeof id === "string" && id.length > 0))
|
|
27540
|
-
return;
|
|
27541
|
-
piOutputEntryIds = metadata.piOutputEntryIds;
|
|
27542
|
-
inputIdsRaw = JSON.stringify(metadata.inputIds);
|
|
27543
|
-
}
|
|
27544
|
-
} catch {
|
|
27545
|
-
return;
|
|
27546
|
-
}
|
|
27547
|
-
}
|
|
27548
|
-
const inputIdSeq = parseStringArray(inputIdsRaw);
|
|
27549
|
-
const inputContentDigests = parseStringArray(record.input_content_digests);
|
|
27550
|
-
const modelKey = parseNullableString(record.model_key);
|
|
27551
|
-
const providerKey = parseNullableString(record.provider_key);
|
|
27552
|
-
if (typeof jsonPrefix !== "string" || typeof lastInputMessageId !== "string" || lastInputMessageId.length === 0 || typeof capturedAt !== "number" || !Number.isFinite(capturedAt) || inputIdSeq === null || inputContentDigests === null || inputContentDigests.length !== inputIdSeq.length || modelKey === undefined || providerKey === undefined) {
|
|
27553
|
-
return;
|
|
27554
|
-
}
|
|
27555
|
-
if (piOutputEntryIds) {
|
|
27556
|
-
try {
|
|
27557
|
-
const output = JSON.parse(jsonPrefix);
|
|
27558
|
-
const inputs = new Set(inputIdSeq);
|
|
27559
|
-
if (!Array.isArray(output) || output.length !== piOutputEntryIds.length || piOutputEntryIds.some((id) => id !== null && !inputs.has(id)))
|
|
27560
|
-
return;
|
|
27561
|
-
} catch {
|
|
27562
|
-
return;
|
|
27563
|
-
}
|
|
27564
|
-
}
|
|
27565
|
-
let inputContentSignatures;
|
|
27566
|
-
if (record.input_content_signatures !== null && record.input_content_signatures !== undefined) {
|
|
27567
|
-
const parsed = parseStringArray(record.input_content_signatures);
|
|
27568
|
-
if (parsed === null || parsed.length !== inputIdSeq.length)
|
|
27569
|
-
return;
|
|
27570
|
-
inputContentSignatures = parsed;
|
|
27571
|
-
}
|
|
27572
|
-
const slot = {
|
|
27573
|
-
jsonPrefix,
|
|
27574
|
-
inputIdSeq,
|
|
27575
|
-
inputContentDigests,
|
|
27576
|
-
lastInputMessageId,
|
|
27577
|
-
modelKey,
|
|
27578
|
-
providerKey,
|
|
27579
|
-
capturedAt
|
|
27580
|
-
};
|
|
27581
|
-
if (inputContentSignatures)
|
|
27582
|
-
slot.inputContentSignatures = inputContentSignatures;
|
|
27583
|
-
if (piOutputEntryIds)
|
|
27584
|
-
slot.piOutputEntryIds = piOutputEntryIds;
|
|
27585
|
-
const rowVersion = parseNullableInteger(record.row_version);
|
|
27586
|
-
if (rowVersion !== undefined)
|
|
27587
|
-
slot.rowVersion = rowVersion;
|
|
27588
|
-
const captureSequence = parseNullableInteger(record.capture_sequence);
|
|
27589
|
-
if (captureSequence !== undefined)
|
|
27590
|
-
slot.captureSequence = captureSequence;
|
|
27591
|
-
return slot;
|
|
27592
|
-
}
|
|
27593
|
-
function saveLkgSlotToDb(db, sessionId, slot) {
|
|
27594
|
-
try {
|
|
27595
|
-
db.prepare(`INSERT INTO lkg_slots (
|
|
27596
|
-
session_id, json_prefix, input_id_seq, input_content_digests,
|
|
27597
|
-
input_content_signatures, last_input_message_id, model_key, provider_key,
|
|
27598
|
-
captured_at, row_version, capture_sequence
|
|
27599
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
27600
|
-
ON CONFLICT(session_id) DO UPDATE SET
|
|
27601
|
-
json_prefix = excluded.json_prefix,
|
|
27602
|
-
input_id_seq = excluded.input_id_seq,
|
|
27603
|
-
input_content_digests = excluded.input_content_digests,
|
|
27604
|
-
input_content_signatures = excluded.input_content_signatures,
|
|
27605
|
-
last_input_message_id = excluded.last_input_message_id,
|
|
27606
|
-
model_key = excluded.model_key,
|
|
27607
|
-
provider_key = excluded.provider_key,
|
|
27608
|
-
captured_at = excluded.captured_at,
|
|
27609
|
-
row_version = excluded.row_version,
|
|
27610
|
-
capture_sequence = excluded.capture_sequence`).run(sessionId, slot.jsonPrefix, JSON.stringify(slot.piOutputEntryIds ? {
|
|
27611
|
-
version: 1,
|
|
27612
|
-
inputIds: slot.inputIdSeq,
|
|
27613
|
-
piOutputEntryIds: slot.piOutputEntryIds
|
|
27614
|
-
} : slot.inputIdSeq), JSON.stringify(slot.inputContentDigests), slot.inputContentSignatures ? JSON.stringify(slot.inputContentSignatures) : null, slot.lastInputMessageId, slot.modelKey, slot.providerKey, slot.capturedAt, slot.rowVersion ?? null, slot.captureSequence ?? null);
|
|
27615
|
-
return true;
|
|
27616
|
-
} catch (error) {
|
|
27617
|
-
sessionLog(sessionId, "LKG snapshot persistence failed (in-memory slot retained):", error);
|
|
27618
|
-
return false;
|
|
27619
|
-
}
|
|
27620
|
-
}
|
|
27621
|
-
function clearPersistedLkgSlot(db, sessionId) {
|
|
27622
|
-
try {
|
|
27623
|
-
db.prepare("DELETE FROM lkg_slots WHERE session_id = ?").run(sessionId);
|
|
27624
|
-
} catch (error) {
|
|
27625
|
-
sessionLog(sessionId, "LKG snapshot durable clear failed:", error);
|
|
27626
|
-
}
|
|
27627
|
-
}
|
|
27628
|
-
function loadPersistedLkgSlot(db, sessionId) {
|
|
27629
|
-
let row;
|
|
27630
|
-
try {
|
|
27631
|
-
row = db.prepare("SELECT * FROM lkg_slots WHERE session_id = ?").get(sessionId);
|
|
27632
|
-
} catch (error) {
|
|
27633
|
-
sessionLog(sessionId, "LKG snapshot durable load failed:", error);
|
|
27634
|
-
return;
|
|
27635
|
-
}
|
|
27636
|
-
if (!row)
|
|
27637
|
-
return;
|
|
27638
|
-
const slot = parsePersistedLkgSlot(row);
|
|
27639
|
-
if (!slot) {
|
|
27640
|
-
clearPersistedLkgSlot(db, sessionId);
|
|
27641
|
-
return;
|
|
27642
|
-
}
|
|
27643
|
-
return slot;
|
|
27644
|
-
}
|
|
27645
|
-
function createDbLkgPersistence(db) {
|
|
27646
|
-
return {
|
|
27647
|
-
load: (sessionId) => loadPersistedLkgSlot(db, sessionId),
|
|
27648
|
-
clear: (sessionId) => clearPersistedLkgSlot(db, sessionId)
|
|
27649
|
-
};
|
|
27650
|
-
}
|
|
27651
|
-
|
|
27652
27759
|
// src/hooks/magic-context/openai-compat-adjacency.ts
|
|
27653
27760
|
function assertOpenAiCompatAdjacency(messages) {
|
|
27654
27761
|
const violations = [];
|
|
@@ -28210,7 +28317,7 @@ function createPassOutcome() {
|
|
|
28210
28317
|
}
|
|
28211
28318
|
|
|
28212
28319
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
28213
|
-
import { createHash as
|
|
28320
|
+
import { createHash as createHash13, randomUUID as randomUUID6 } from "node:crypto";
|
|
28214
28321
|
|
|
28215
28322
|
// src/features/magic-context/memory/mirror-reembed.ts
|
|
28216
28323
|
async function reembedMirrorInvalidatedMemories(db) {
|
|
@@ -28674,13 +28781,16 @@ class HistorianHostRunner {
|
|
|
28674
28781
|
this.log(`producer window unknown for ${key}: sending unguarded`);
|
|
28675
28782
|
}
|
|
28676
28783
|
const output = provider && parts.length ? getSdkOutputLimit(provider, parts.join("/")) : undefined;
|
|
28677
|
-
const
|
|
28784
|
+
const producerLimits = resolveHistorianProducerLimits2(key);
|
|
28785
|
+
const context = producerLimits.context ?? (producerLimits.input === undefined ? window : undefined);
|
|
28786
|
+
const reserve = historianProducerReserve(context, undefined, output);
|
|
28678
28787
|
const failure = producerPromptFailureReason({
|
|
28679
28788
|
sourceLocal: estimateTokens(claim.user),
|
|
28680
28789
|
systemLocal: estimateTokens(claim.system),
|
|
28681
28790
|
toolsLocal: 0,
|
|
28682
28791
|
modelKey: key,
|
|
28683
|
-
contextLimitTokens:
|
|
28792
|
+
contextLimitTokens: context,
|
|
28793
|
+
inputLimitTokens: producerLimits.input,
|
|
28684
28794
|
maxOutputTokens: reserve
|
|
28685
28795
|
});
|
|
28686
28796
|
if (failure)
|
|
@@ -28790,6 +28900,16 @@ class RawFallbackContextLimitError extends Error {
|
|
|
28790
28900
|
|
|
28791
28901
|
// src/hooks/magic-context/storage-busy-refusal.ts
|
|
28792
28902
|
var STORAGE_BUSY_MESSAGE = "Magic Context's database is busy (another process held it too long); send your message again.";
|
|
28903
|
+
function describeStorageBusyCause(cause) {
|
|
28904
|
+
let original = cause;
|
|
28905
|
+
for (let depth = 0;original instanceof SqliteAcquisitionBusyError && depth < 5; depth++) {
|
|
28906
|
+
original = original.cause;
|
|
28907
|
+
}
|
|
28908
|
+
if (!(original instanceof Error))
|
|
28909
|
+
return String(original);
|
|
28910
|
+
return original.stack ? `${original.message}
|
|
28911
|
+
${original.stack}` : original.message;
|
|
28912
|
+
}
|
|
28793
28913
|
|
|
28794
28914
|
class StorageBusyRefusalError extends Error {
|
|
28795
28915
|
code = "STORAGE_BUSY_REFUSAL";
|
|
@@ -28797,8 +28917,7 @@ class StorageBusyRefusalError extends Error {
|
|
|
28797
28917
|
constructor(cause, stage) {
|
|
28798
28918
|
super(STORAGE_BUSY_MESSAGE, { cause });
|
|
28799
28919
|
this.name = "StorageBusyRefusalError";
|
|
28800
|
-
const
|
|
28801
|
-
const detail = original instanceof Error ? original.stack ?? original.message : String(original);
|
|
28920
|
+
const detail = describeStorageBusyCause(cause);
|
|
28802
28921
|
log(`[magic-context] storage-busy refusal stage=${stage}${cause instanceof SqliteAcquisitionBusyError ? ` acquisition=${cause.stage}` : ""}: ${detail}`);
|
|
28803
28922
|
}
|
|
28804
28923
|
}
|
|
@@ -29087,10 +29206,10 @@ function messageCacheSignature(message) {
|
|
|
29087
29206
|
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
29088
29207
|
const serializedParts = JSON.stringify(parts) ?? "null";
|
|
29089
29208
|
const serializedMessage = JSON.stringify(message) ?? "null";
|
|
29090
|
-
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${
|
|
29209
|
+
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash13("sha256").update(serializedMessage).digest("hex")}`;
|
|
29091
29210
|
}
|
|
29092
29211
|
function advanceWireFingerprint(previous, encoded) {
|
|
29093
|
-
return
|
|
29212
|
+
return createHash13("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
|
|
29094
29213
|
}
|
|
29095
29214
|
function buildWireFingerprint(encoded) {
|
|
29096
29215
|
let fingerprint = "rust-wire-v1";
|
|
@@ -29446,7 +29565,7 @@ function canonicalizeForChecksum(value) {
|
|
|
29446
29565
|
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalizeForChecksum(value[key])]));
|
|
29447
29566
|
}
|
|
29448
29567
|
function checksumSeedRows(rows) {
|
|
29449
|
-
return
|
|
29568
|
+
return createHash13("sha256").update(JSON.stringify(rows.map(canonicalizeForChecksum))).digest("hex");
|
|
29450
29569
|
}
|
|
29451
29570
|
function authoritySeedRows(db, projectPath, domain) {
|
|
29452
29571
|
const snapshots = domain === "memories" ? db.prepare("SELECT * FROM memories WHERE project_path = ? ORDER BY id ASC").all(projectPath) : db.prepare(`SELECT n.*
|
|
@@ -29674,13 +29793,15 @@ function resolvedHistorianModelLimits(chain) {
|
|
|
29674
29793
|
return Object.fromEntries(chain.map((key) => {
|
|
29675
29794
|
const [provider, ...parts] = key.split("/");
|
|
29676
29795
|
const output = provider && parts.length ? getSdkOutputLimit(provider, parts.join("/")) : undefined;
|
|
29677
|
-
const
|
|
29796
|
+
const producerLimits = resolveHistorianProducerLimits2(key);
|
|
29797
|
+
const known = producerLimits.input === undefined ? resolveKnownHistorianContextLimit2(key) : undefined;
|
|
29678
29798
|
const learned = provider && parts.length ? getSdkWindowGeometry(provider, parts.join("/"))?.derivation.window : undefined;
|
|
29679
|
-
const context = known === undefined ? learned : learned === undefined ? known : Math.min(known, learned);
|
|
29799
|
+
const context = producerLimits.context ?? (known === undefined ? learned : learned === undefined ? known : Math.min(known, learned));
|
|
29680
29800
|
return [
|
|
29681
29801
|
key,
|
|
29682
29802
|
{
|
|
29683
29803
|
...context !== undefined ? { context } : {},
|
|
29804
|
+
...producerLimits.input !== undefined ? { input: producerLimits.input } : {},
|
|
29684
29805
|
...output !== undefined ? { output } : {}
|
|
29685
29806
|
}
|
|
29686
29807
|
];
|
|
@@ -31083,6 +31204,16 @@ function createRustModeTransform(deps, options) {
|
|
|
31083
31204
|
}
|
|
31084
31205
|
pendingWireCache.nativeOutput = moduleMessages;
|
|
31085
31206
|
if (!replayedFrozenRepresentation) {
|
|
31207
|
+
if (materializedBoundary && !deps.compactionOff) {
|
|
31208
|
+
try {
|
|
31209
|
+
await withAsyncPrivilegedWriter(deps.db, () => {
|
|
31210
|
+
return;
|
|
31211
|
+
});
|
|
31212
|
+
} catch (error) {
|
|
31213
|
+
if (!isTransientSqliteError(error))
|
|
31214
|
+
throw error;
|
|
31215
|
+
}
|
|
31216
|
+
}
|
|
31086
31217
|
const postprocess = runRustModePostprocess2({
|
|
31087
31218
|
db: deps.db,
|
|
31088
31219
|
sessionId,
|
|
@@ -31307,7 +31438,7 @@ function createRustModeTransform(deps, options) {
|
|
|
31307
31438
|
if (mirrorDrain.rowsApplied > 0) {
|
|
31308
31439
|
await reembedMirrorInvalidatedMemories(deps.db);
|
|
31309
31440
|
}
|
|
31310
|
-
await drainSingleStoreEmbeddingWatermarks(deps.db);
|
|
31441
|
+
await withSqliteBackgroundWriter(() => drainSingleStoreEmbeddingWatermarks(deps.db));
|
|
31311
31442
|
if (mirrorDrain.complete) {
|
|
31312
31443
|
state.memoryMirrorProjectionKey = projectionKey;
|
|
31313
31444
|
} else if (mirrorDrain.budgetExhausted) {
|
|
@@ -34241,7 +34372,7 @@ function createTextCompleteHandler() {
|
|
|
34241
34372
|
}
|
|
34242
34373
|
|
|
34243
34374
|
// src/hooks/magic-context/system-prompt-hash.ts
|
|
34244
|
-
import { createHash as
|
|
34375
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
34245
34376
|
var MAGIC_CONTEXT_MARKER = "## Magic Context";
|
|
34246
34377
|
var SYSTEM_PROMPT_GUIDANCE_SEPARATOR = `
|
|
34247
34378
|
|
|
@@ -34338,7 +34469,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
34338
34469
|
}
|
|
34339
34470
|
const stickyDate = stickyDateBySession.get(sessionId);
|
|
34340
34471
|
const stableCandidate = currentDate && stickyDate && currentDate !== stickyDate ? liveSystemContent.replace(DATE_PATTERN_ALL, stickyDate) : liveSystemContent;
|
|
34341
|
-
const stableCandidateHash =
|
|
34472
|
+
const stableCandidateHash = createHash14("md5").update(promptSurfaceHashMaterial(stableCandidate, promptSurface.preset)).digest("hex");
|
|
34342
34473
|
const contentOrPresetChanged = hasPersistedHash && stableCandidateHash !== previousHash;
|
|
34343
34474
|
const dateMayAdvance = isCacheBusting || contentOrPresetChanged;
|
|
34344
34475
|
if (currentDate && !stickyDate) {
|
|
@@ -34358,7 +34489,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
34358
34489
|
`);
|
|
34359
34490
|
if (!availability.frozen || !modelKey)
|
|
34360
34491
|
return;
|
|
34361
|
-
const currentHash =
|
|
34492
|
+
const currentHash = createHash14("md5").update(promptSurfaceHashMaterial(systemContent, promptSurface.preset)).digest("hex");
|
|
34362
34493
|
if (!sessionMetaEarly) {
|
|
34363
34494
|
return;
|
|
34364
34495
|
}
|
|
@@ -35283,6 +35414,13 @@ function createMessagesTransformHandler(args) {
|
|
|
35283
35414
|
}
|
|
35284
35415
|
})() : null;
|
|
35285
35416
|
try {
|
|
35417
|
+
if (!args.compactionOff && magicContext) {
|
|
35418
|
+
const admissionDb = openDatabase();
|
|
35419
|
+
if (admissionDb)
|
|
35420
|
+
await withAsyncPrivilegedWriter(admissionDb, () => {
|
|
35421
|
+
return;
|
|
35422
|
+
});
|
|
35423
|
+
}
|
|
35286
35424
|
await magicContext?.["experimental.chat.messages.transform"]?.(input, output);
|
|
35287
35425
|
return output.messages;
|
|
35288
35426
|
} catch (error) {
|
|
@@ -37433,7 +37571,7 @@ Keep: user messages (never stamp one for its directive), your own conversation t
|
|
|
37433
37571
|
|
|
37434
37572
|
Look at each tag before stamping it; never blanket-stamp a range like "1-50". Many small targeted stamps beat one sweep. \`drop\` accepts "3-5", "1,2,9", "1-5,8,12-15".`;
|
|
37435
37573
|
// src/tools/ctx-reduce/tools.ts
|
|
37436
|
-
import { createHash as
|
|
37574
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
37437
37575
|
import { tool as tool4 } from "@opencode-ai/plugin";
|
|
37438
37576
|
|
|
37439
37577
|
// src/features/magic-context/range-parser.ts
|
|
@@ -37503,11 +37641,11 @@ function createCtxReduceTool(deps) {
|
|
|
37503
37641
|
const stableId = `oc-${sessionId}-${callId}`;
|
|
37504
37642
|
if (Buffer.byteLength(stableId) <= 128)
|
|
37505
37643
|
return stableId;
|
|
37506
|
-
return `oc-${
|
|
37644
|
+
return `oc-${createHash15("sha256").update(stableId).digest("hex")}`;
|
|
37507
37645
|
}
|
|
37508
37646
|
fallbackCommandSequence += 1;
|
|
37509
37647
|
const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
|
|
37510
|
-
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${
|
|
37648
|
+
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash15("sha256").update(monotonicId).digest("hex")}`;
|
|
37511
37649
|
};
|
|
37512
37650
|
return tool4({
|
|
37513
37651
|
description: CTX_REDUCE_DESCRIPTION,
|
|
@@ -38071,7 +38209,7 @@ import {
|
|
|
38071
38209
|
chmodSync as chmodSync2,
|
|
38072
38210
|
mkdirSync as mkdirSync5,
|
|
38073
38211
|
readdirSync as readdirSync2,
|
|
38074
|
-
readFileSync as
|
|
38212
|
+
readFileSync as readFileSync8,
|
|
38075
38213
|
renameSync as renameSync5,
|
|
38076
38214
|
rmSync as rmSync5,
|
|
38077
38215
|
unlinkSync,
|
|
@@ -38218,7 +38356,7 @@ class MagicContextRpcServer {
|
|
|
38218
38356
|
for (const entry of readdirSync2(this.portDir)) {
|
|
38219
38357
|
if (!entry.startsWith("port-") || !entry.endsWith(".json"))
|
|
38220
38358
|
continue;
|
|
38221
|
-
const record = parseRpcPortFile(
|
|
38359
|
+
const record = parseRpcPortFile(readFileSync8(`${this.portDir}/${entry}`, "utf-8"));
|
|
38222
38360
|
if (!record || record.pid === process.pid)
|
|
38223
38361
|
continue;
|
|
38224
38362
|
const processes = await inspectProcessesAsync();
|
|
@@ -38534,8 +38672,8 @@ function hostMediaAsset(data, mediaType) {
|
|
|
38534
38672
|
}
|
|
38535
38673
|
|
|
38536
38674
|
// src/v2/fold/owner.ts
|
|
38537
|
-
import { createHash as
|
|
38538
|
-
var foldDigest = (value) =>
|
|
38675
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
38676
|
+
var foldDigest = (value) => createHash16("sha256").update(value).digest("hex");
|
|
38539
38677
|
|
|
38540
38678
|
class FoldOwner {
|
|
38541
38679
|
storage;
|
|
@@ -38838,7 +38976,7 @@ ${data.output?.output ?? ""}`
|
|
|
38838
38976
|
}
|
|
38839
38977
|
|
|
38840
38978
|
// src/v2/host-service.ts
|
|
38841
|
-
import { readdirSync as readdirSync3, readFileSync as
|
|
38979
|
+
import { readdirSync as readdirSync3, readFileSync as readFileSync9 } from "node:fs";
|
|
38842
38980
|
import { homedir as homedir3 } from "node:os";
|
|
38843
38981
|
import { join as join11 } from "node:path";
|
|
38844
38982
|
|
|
@@ -39254,7 +39392,7 @@ class HostServiceUnavailable extends Error {
|
|
|
39254
39392
|
function parseRegistration(path) {
|
|
39255
39393
|
let text;
|
|
39256
39394
|
try {
|
|
39257
|
-
text =
|
|
39395
|
+
text = readFileSync9(path, "utf8");
|
|
39258
39396
|
} catch {
|
|
39259
39397
|
return;
|
|
39260
39398
|
}
|
|
@@ -39368,8 +39506,8 @@ var POLL_INTERVAL_MS = 200;
|
|
|
39368
39506
|
var REMOVAL_SPACING_MS = 250;
|
|
39369
39507
|
var RETIRED_CHILDREN_LIMIT = 200;
|
|
39370
39508
|
var LEGACY_CLEANUP_BOOT_LIMIT = 5;
|
|
39371
|
-
function hiddenChildrenMetaKey(projectIdentity) {
|
|
39372
|
-
return `${META_PREFIX}${projectIdentity}`;
|
|
39509
|
+
function hiddenChildrenMetaKey(projectIdentity, directory) {
|
|
39510
|
+
return directory === undefined ? `${META_PREFIX}${projectIdentity}` : `${META_PREFIX}${JSON.stringify([projectIdentity, directory])}`;
|
|
39373
39511
|
}
|
|
39374
39512
|
function emptyMeta() {
|
|
39375
39513
|
return { version: 1, active: {}, retired_children: [] };
|
|
@@ -39431,9 +39569,49 @@ function parseMeta(value) {
|
|
|
39431
39569
|
class HiddenChildStateStore {
|
|
39432
39570
|
db;
|
|
39433
39571
|
key;
|
|
39434
|
-
constructor(db, projectIdentity) {
|
|
39572
|
+
constructor(db, projectIdentity, directory) {
|
|
39435
39573
|
this.db = db;
|
|
39436
|
-
this.key = hiddenChildrenMetaKey(projectIdentity);
|
|
39574
|
+
this.key = hiddenChildrenMetaKey(projectIdentity, directory);
|
|
39575
|
+
this.legacyKey = hiddenChildrenMetaKey(projectIdentity);
|
|
39576
|
+
}
|
|
39577
|
+
legacyKey;
|
|
39578
|
+
migrateStale(isStale) {
|
|
39579
|
+
this.db.transaction(() => {
|
|
39580
|
+
const legacyRow = this.db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(this.legacyKey);
|
|
39581
|
+
if (!legacyRow)
|
|
39582
|
+
return;
|
|
39583
|
+
const legacy = parseMeta(legacyRow.value);
|
|
39584
|
+
const scoped = this.read();
|
|
39585
|
+
for (const role of ["historian", "dreamer"]) {
|
|
39586
|
+
const child = legacy.active[role];
|
|
39587
|
+
if (!child || !isStale(child))
|
|
39588
|
+
continue;
|
|
39589
|
+
scoped.retired_children.push({
|
|
39590
|
+
...child,
|
|
39591
|
+
retired_at: Date.now(),
|
|
39592
|
+
reason: "legacy-directory-scope"
|
|
39593
|
+
});
|
|
39594
|
+
delete legacy.active[role];
|
|
39595
|
+
}
|
|
39596
|
+
const remaining = [];
|
|
39597
|
+
for (const child of legacy.retired_children) {
|
|
39598
|
+
if (isStale(child))
|
|
39599
|
+
scoped.retired_children.push(child);
|
|
39600
|
+
else
|
|
39601
|
+
remaining.push(child);
|
|
39602
|
+
}
|
|
39603
|
+
legacy.retired_children = remaining;
|
|
39604
|
+
const excess = scoped.retired_children.length - RETIRED_CHILDREN_LIMIT;
|
|
39605
|
+
if (excess > 0)
|
|
39606
|
+
scoped.retired_children.splice(0, excess);
|
|
39607
|
+
this.db.prepare(`INSERT INTO schema_migrations_meta (key, value) VALUES (?, ?)
|
|
39608
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(this.key, JSON.stringify(scoped));
|
|
39609
|
+
if (Object.keys(legacy.active).length === 0 && legacy.retired_children.length === 0) {
|
|
39610
|
+
this.db.prepare("DELETE FROM schema_migrations_meta WHERE key = ?").run(this.legacyKey);
|
|
39611
|
+
} else {
|
|
39612
|
+
this.db.prepare("UPDATE schema_migrations_meta SET value = ? WHERE key = ?").run(JSON.stringify(legacy), this.legacyKey);
|
|
39613
|
+
}
|
|
39614
|
+
}).immediate();
|
|
39437
39615
|
}
|
|
39438
39616
|
read() {
|
|
39439
39617
|
const row = this.db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(this.key);
|
|
@@ -39660,6 +39838,12 @@ async function sleepUntilPoll(signal, deadline) {
|
|
|
39660
39838
|
}, delay);
|
|
39661
39839
|
});
|
|
39662
39840
|
}
|
|
39841
|
+
function isProviderFailure(error) {
|
|
39842
|
+
if (!error || typeof error !== "object")
|
|
39843
|
+
return false;
|
|
39844
|
+
const type = error.type;
|
|
39845
|
+
return typeof type === "string" && (type.startsWith("provider.") || type.toLowerCase().includes("provider"));
|
|
39846
|
+
}
|
|
39663
39847
|
async function awaitAssistantRow(openReader, readSessionError, stepLimit, childID, afterSeq, deadline, signal) {
|
|
39664
39848
|
for (;; ) {
|
|
39665
39849
|
const { assistant, idle } = withReader(openReader, (reader) => ({
|
|
@@ -39680,7 +39864,7 @@ async function awaitAssistantRow(openReader, readSessionError, stepLimit, childI
|
|
|
39680
39864
|
`terminal_row=${errorText(newIdle)}`,
|
|
39681
39865
|
`session_error=${sessionError === undefined ? "unavailable" : errorText(sessionError)}`
|
|
39682
39866
|
];
|
|
39683
|
-
throw sessionError === undefined ? new Error(`Hidden completion failed
|
|
39867
|
+
throw sessionError === undefined || !isProviderFailure(sessionError) ? new Error(`Hidden completion failed: ${details.join("; ")}`) : new HiddenProviderError(details.join("; "));
|
|
39684
39868
|
}
|
|
39685
39869
|
if (outcome === "succeeded" && newAssistant)
|
|
39686
39870
|
return newAssistant;
|
|
@@ -39694,7 +39878,7 @@ async function awaitAssistantRow(openReader, readSessionError, stepLimit, childI
|
|
|
39694
39878
|
`terminal_row=${errorText(newAssistant)}`,
|
|
39695
39879
|
`session_error=${sessionError === undefined ? "unavailable" : errorText(sessionError)}`
|
|
39696
39880
|
];
|
|
39697
|
-
throw sessionError === undefined ? new Error(`Hidden completion failed
|
|
39881
|
+
throw sessionError === undefined || !isProviderFailure(sessionError) ? new Error(`Hidden completion failed: ${details.join("; ")}`) : new HiddenProviderError(details.join("; "));
|
|
39698
39882
|
}
|
|
39699
39883
|
if (newAssistant.data.error !== undefined) {
|
|
39700
39884
|
throw new HiddenProviderError(errorText(newAssistant.data.error), {
|
|
@@ -39734,9 +39918,35 @@ function createLateHiddenExecutor(current) {
|
|
|
39734
39918
|
}
|
|
39735
39919
|
async function createV2HiddenCompletionExecutor(host, options) {
|
|
39736
39920
|
const runs = new WeakMap;
|
|
39737
|
-
const store = new HiddenChildStateStore(options.db, options.projectIdentity);
|
|
39921
|
+
const store = new HiddenChildStateStore(options.db, options.projectIdentity, options.directory);
|
|
39738
39922
|
const generation = options.generation ?? "opencode2";
|
|
39739
39923
|
const roleTails = new Map;
|
|
39924
|
+
const legacy = options.db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(hiddenChildrenMetaKey(options.projectIdentity));
|
|
39925
|
+
if (legacy) {
|
|
39926
|
+
const children = parseMeta(legacy.value);
|
|
39927
|
+
const statuses = new Map;
|
|
39928
|
+
for (const child of [...Object.values(children.active), ...children.retired_children]) {
|
|
39929
|
+
if (!child || !host.status)
|
|
39930
|
+
continue;
|
|
39931
|
+
const directory = child.directory ?? options.directory;
|
|
39932
|
+
if (!statuses.has(directory)) {
|
|
39933
|
+
try {
|
|
39934
|
+
statuses.set(directory, await host.status({ directory }));
|
|
39935
|
+
} catch {
|
|
39936
|
+
statuses.set(directory, undefined);
|
|
39937
|
+
}
|
|
39938
|
+
}
|
|
39939
|
+
}
|
|
39940
|
+
store.migrateStale((child) => {
|
|
39941
|
+
const directory = child.directory ?? options.directory;
|
|
39942
|
+
const state = statuses.get(directory);
|
|
39943
|
+
if (host.status && (!state || state[child.id]?.type === "busy" || state[child.id]?.type === "retry"))
|
|
39944
|
+
return false;
|
|
39945
|
+
const last = Math.max(child.created_at, withReader(options.openReader, (reader) => Math.max(reader.latestAssistant(child.id)?.data.time?.created ?? 0, reader.latestIdle(child.id)?.data.time?.created ?? 0)));
|
|
39946
|
+
const staleMs = child.role === "historian" ? historianOrphanStaleMs(20 * 60000, 3) : retrospectiveOrphanStaleMs(undefined);
|
|
39947
|
+
return Date.now() - last > staleMs;
|
|
39948
|
+
});
|
|
39949
|
+
}
|
|
39740
39950
|
const persisted = store.read();
|
|
39741
39951
|
for (const child of [...Object.values(persisted.active), ...persisted.retired_children]) {
|
|
39742
39952
|
if (child)
|
|
@@ -40106,6 +40316,7 @@ async function createV2HiddenCompletionExecutor(host, options) {
|
|
|
40106
40316
|
}
|
|
40107
40317
|
run.completion = {
|
|
40108
40318
|
text,
|
|
40319
|
+
tokenLog: runTokenLog(tokens, run.identity.maxOutputTokens, row.data.finish),
|
|
40109
40320
|
...hiddenToolLoop(run.identity) ? { messages: toolLoopMessages(attempt) } : {},
|
|
40110
40321
|
reasoning: text ? null : assistantReasoning(row),
|
|
40111
40322
|
usage: reportedInput !== undefined || reportedOutput !== undefined ? {
|
|
@@ -40479,10 +40690,19 @@ function startDreamTrigger(context, args) {
|
|
|
40479
40690
|
};
|
|
40480
40691
|
}
|
|
40481
40692
|
|
|
40693
|
+
// src/v2/hooks/hidden-terminal-error.ts
|
|
40694
|
+
function hiddenTerminalError(event) {
|
|
40695
|
+
if (event.type === "session.execution.failed")
|
|
40696
|
+
return event.data?.error;
|
|
40697
|
+
if (event.type === "session.error")
|
|
40698
|
+
return getSessionErrorInfo(event.data)?.error;
|
|
40699
|
+
return;
|
|
40700
|
+
}
|
|
40701
|
+
|
|
40482
40702
|
// src/v2/hooks/lkg-system.ts
|
|
40483
|
-
import { createHash as
|
|
40703
|
+
import { createHash as createHash17 } from "node:crypto";
|
|
40484
40704
|
function identity(slot) {
|
|
40485
|
-
return
|
|
40705
|
+
return createHash17("sha256").update(JSON.stringify({
|
|
40486
40706
|
capturedAt: slot.capturedAt,
|
|
40487
40707
|
captureSequence: slot.captureSequence,
|
|
40488
40708
|
rowVersion: slot.rowVersion,
|
|
@@ -41413,6 +41633,10 @@ async function registerTools(context, db, config, rustToolBackends) {
|
|
|
41413
41633
|
input: tool7.schema.toJSONSchema(tool7.schema.object(definition.args)),
|
|
41414
41634
|
options: { codemode: false },
|
|
41415
41635
|
async execute(input, call) {
|
|
41636
|
+
if (name === "ctx_memory" || name === "ctx_note" || name === "ctx_reduce")
|
|
41637
|
+
await withAsyncPrivilegedWriter(db, () => {
|
|
41638
|
+
return;
|
|
41639
|
+
});
|
|
41416
41640
|
const result = await definition.execute(tool7.schema.object(definition.args).parse(input), {
|
|
41417
41641
|
sessionID: call.sessionID,
|
|
41418
41642
|
messageID: call.messageID,
|
|
@@ -41645,6 +41869,7 @@ async function applyV2SystemPrompt(systemPrompt, draft) {
|
|
|
41645
41869
|
async function registerContext(context) {
|
|
41646
41870
|
const directory = context.location.directory;
|
|
41647
41871
|
const config = loadPluginConfigDetailed(directory).config;
|
|
41872
|
+
setHomeProjectPermission(config.allow_home_project);
|
|
41648
41873
|
if (!config.enabled)
|
|
41649
41874
|
return;
|
|
41650
41875
|
const liveConfigReader = pluginConfigReader(directory, config);
|
|
@@ -41753,6 +41978,7 @@ async function registerContext(context) {
|
|
|
41753
41978
|
}, {
|
|
41754
41979
|
db: database,
|
|
41755
41980
|
projectIdentity: resolveProjectIdentityForSession(directory, config.allow_home_project) ?? "",
|
|
41981
|
+
directory,
|
|
41756
41982
|
hook: hiddenChildHook,
|
|
41757
41983
|
keepSubagents: config.keep_subagents === true,
|
|
41758
41984
|
ensureAgent: () => hiddenAgentsReady ??= context.agent.reload(),
|
|
@@ -41955,8 +42181,8 @@ async function registerContext(context) {
|
|
|
41955
42181
|
if (!event.data?.sessionID)
|
|
41956
42182
|
continue;
|
|
41957
42183
|
const sessionID = event.data.sessionID;
|
|
41958
|
-
if (event.type === "session.error") {
|
|
41959
|
-
const error =
|
|
42184
|
+
if (event.type === "session.error" || event.type === "session.execution.failed") {
|
|
42185
|
+
const error = hiddenTerminalError(event);
|
|
41960
42186
|
if (error !== undefined)
|
|
41961
42187
|
hiddenSessionErrors.set(sessionID, error);
|
|
41962
42188
|
continue;
|
|
@@ -42079,7 +42305,7 @@ async function registerContext(context) {
|
|
|
42079
42305
|
try {
|
|
42080
42306
|
const admissionDb = db ?? storage.current();
|
|
42081
42307
|
if (!compactionOff && admissionDb)
|
|
42082
|
-
|
|
42308
|
+
await withAsyncPrivilegedWriter(admissionDb, () => {
|
|
42083
42309
|
return;
|
|
42084
42310
|
});
|
|
42085
42311
|
recordV2ToolDefinitions(draft);
|
|
@@ -42465,14 +42691,14 @@ ${baseline}
|
|
|
42465
42691
|
}
|
|
42466
42692
|
|
|
42467
42693
|
// src/v2/hooks/update-check.ts
|
|
42468
|
-
import { existsSync as existsSync12, readFileSync as
|
|
42694
|
+
import { existsSync as existsSync12, readFileSync as readFileSync10 } from "node:fs";
|
|
42469
42695
|
import { dirname as dirname6, join as join12 } from "node:path";
|
|
42470
42696
|
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
42471
42697
|
function packageInfo() {
|
|
42472
42698
|
let directory = dirname6(fileURLToPath3(import.meta.url));
|
|
42473
42699
|
for (;; ) {
|
|
42474
42700
|
try {
|
|
42475
|
-
const pkg = JSON.parse(
|
|
42701
|
+
const pkg = JSON.parse(readFileSync10(join12(directory, "package.json"), "utf8"));
|
|
42476
42702
|
if (pkg.name === "@cortexkit/opencode-magic-context" && typeof pkg.version === "string") {
|
|
42477
42703
|
return {
|
|
42478
42704
|
version: pkg.version,
|
|
@@ -42570,6 +42796,7 @@ var server = async (ctx) => {
|
|
|
42570
42796
|
});
|
|
42571
42797
|
const loadedPluginConfig = loadPluginConfigDetailed(ctx.directory);
|
|
42572
42798
|
const pluginConfig = loadedPluginConfig.config;
|
|
42799
|
+
setHomeProjectPermission(pluginConfig.allow_home_project);
|
|
42573
42800
|
const liveConfigReader = pluginConfigReader(ctx.directory, pluginConfig);
|
|
42574
42801
|
const dreamerCap = createDreamerOutputCapSampler(pluginConfig, () => liveConfigReader.poll().effective);
|
|
42575
42802
|
reloadWindowOverlay(pluginConfig.models?.window_overlay_path);
|
|
@@ -42603,7 +42830,7 @@ var server = async (ctx) => {
|
|
|
42603
42830
|
if (hasBannerEntries)
|
|
42604
42831
|
setTimeout(async () => {
|
|
42605
42832
|
try {
|
|
42606
|
-
const { sendStatusNotification } = await import("./send-session-notification-
|
|
42833
|
+
const { sendStatusNotification } = await import("./send-session-notification-04hvd54c.js");
|
|
42607
42834
|
const clientWithSessions = ctx.client;
|
|
42608
42835
|
const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
|
|
42609
42836
|
const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
|
|
@@ -42620,7 +42847,7 @@ var server = async (ctx) => {
|
|
|
42620
42847
|
log(`[magic-context] opencode_db_missing path=${openCodeDbResolution.path} source=${openCodeDbResolution.source}`);
|
|
42621
42848
|
setTimeout(async () => {
|
|
42622
42849
|
try {
|
|
42623
|
-
const { sendStatusNotification } = await import("./send-session-notification-
|
|
42850
|
+
const { sendStatusNotification } = await import("./send-session-notification-04hvd54c.js");
|
|
42624
42851
|
const clientWithSessions = ctx.client;
|
|
42625
42852
|
const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
|
|
42626
42853
|
const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
|
|
@@ -42894,12 +43121,12 @@ var server = async (ctx) => {
|
|
|
42894
43121
|
{
|
|
42895
43122
|
const fence = getSchemaFenceRejection();
|
|
42896
43123
|
if (fence) {
|
|
42897
|
-
import("./conflict-warning-hook-
|
|
43124
|
+
import("./conflict-warning-hook-hmpzxep6.js").then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence));
|
|
42898
43125
|
}
|
|
42899
43126
|
}
|
|
42900
43127
|
const serverUrl = ctx.serverUrl;
|
|
42901
43128
|
const serverUrlStr = serverUrl instanceof URL ? serverUrl.toString().replace(/\/$/, "") : typeof serverUrl === "string" ? serverUrl.replace(/\/$/, "") : undefined;
|
|
42902
|
-
import("./send-session-notification-
|
|
43129
|
+
import("./send-session-notification-04hvd54c.js").then(({ setNotificationServerUrl }) => {
|
|
42903
43130
|
setNotificationServerUrl(serverUrlStr);
|
|
42904
43131
|
});
|
|
42905
43132
|
if (conflictResult?.hasConflict) {
|
|
@@ -42922,7 +43149,7 @@ var server = async (ctx) => {
|
|
|
42922
43149
|
}) => {
|
|
42923
43150
|
if (!shouldShowAnnouncement())
|
|
42924
43151
|
return;
|
|
42925
|
-
return import("./conflict-warning-hook-
|
|
43152
|
+
return import("./conflict-warning-hook-hmpzxep6.js").then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION, ANNOUNCEMENT_FEATURES, ANNOUNCEMENT_FOOTER, markAnnouncementSeen));
|
|
42926
43153
|
}).catch(() => {});
|
|
42927
43154
|
}, 8000);
|
|
42928
43155
|
}
|
|
@@ -42991,8 +43218,8 @@ var server = async (ctx) => {
|
|
|
42991
43218
|
internalChildSessions: liveSessionState.internalChildSessions,
|
|
42992
43219
|
tryReopenStorage,
|
|
42993
43220
|
onStorageBusyRefusal: async (sessionId, message) => {
|
|
42994
|
-
const { sendStatusNotification } = await import("./send-session-notification-
|
|
42995
|
-
const { abortSessionFailClosed } = await import("./transform-postprocess-phase-
|
|
43221
|
+
const { sendStatusNotification } = await import("./send-session-notification-04hvd54c.js");
|
|
43222
|
+
const { abortSessionFailClosed } = await import("./transform-postprocess-phase-z2mfc5w1.js");
|
|
42996
43223
|
await sendStatusNotification(ctx.client, sessionId, message, {
|
|
42997
43224
|
toastDurationMs: 15000
|
|
42998
43225
|
});
|