@cortexkit/opencode-magic-context 0.36.1 → 0.37.0
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/config/index.d.ts.map +1 -1
- package/dist/config/project-security.d.ts +2 -1
- package/dist/config/project-security.d.ts.map +1 -1
- package/dist/config/schema/magic-context.d.ts +10 -0
- package/dist/config/schema/magic-context.d.ts.map +1 -1
- package/dist/{conflict-warning-hook-mt0ttc4x.js → conflict-warning-hook-an4fxhwf.js} +3 -3
- package/dist/{derive-budgets-88mxk2w1.js → derive-budgets-0f8xpyw2.js} +3 -2
- package/dist/features/magic-context/context-authority.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-openai.d.ts +3 -1
- package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
- package/dist/features/magic-context/memory/project-identity.d.ts +6 -0
- package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
- package/dist/features/magic-context/migrations.d.ts.map +1 -1
- package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
- package/dist/features/magic-context/smart-notes/runner.d.ts.map +1 -1
- package/dist/features/magic-context/smart-notes/wake-plane.d.ts +21 -0
- package/dist/features/magic-context/smart-notes/wake-plane.d.ts.map +1 -0
- package/dist/features/magic-context/storage-db.d.ts +13 -2
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts +22 -0
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-shared.d.ts.map +1 -1
- package/dist/features/magic-context/storage-primers.d.ts +11 -0
- package/dist/features/magic-context/storage-primers.d.ts.map +1 -1
- package/dist/features/magic-context/storage-schema-helpers.d.ts.map +1 -1
- package/dist/features/magic-context/user-memory/storage-user-memory.d.ts +7 -0
- package/dist/features/magic-context/user-memory/storage-user-memory.d.ts.map +1 -1
- package/dist/features/magic-context/window-report-ledger.d.ts +70 -0
- package/dist/features/magic-context/window-report-ledger.d.ts.map +1 -0
- package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-resolvers.d.ts +4 -0
- package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
- package/dist/hooks/magic-context/execute-status.d.ts +2 -1
- package/dist/hooks/magic-context/execute-status.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-slot.d.ts +20 -0
- package/dist/hooks/magic-context/lkg-slot.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-state-sync.d.ts +8 -0
- package/dist/hooks/magic-context/module-state-sync.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-wire.d.ts +6 -1
- package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts +17 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/strip-content.d.ts +25 -0
- package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
- package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +11 -3
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts +10 -0
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/wrapup-orchestrator.d.ts.map +1 -1
- package/dist/{index-1skzp4dc.js → index-0ze9p983.js} +572 -92
- package/dist/{index-nsx2n9eg.js → index-4cz5nfxf.js} +3 -3
- package/dist/{index-f1tnb3vm.js → index-8pqfcghm.js} +21 -9
- package/dist/{index-zp6x6s6a.js → index-cae89eas.js} +25 -6
- package/dist/index-cgyfn1s2.js +53 -0
- package/dist/{index-3zqcdwqr.js → index-crke4z5j.js} +7 -4
- package/dist/{index-tsgs7td8.js → index-pck9vadr.js} +1 -1
- package/dist/index-q0t189ay.js +741 -0
- package/dist/{index-3tnkymva.js → index-sw8gnq34.js} +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1172 -287
- package/dist/plugin/hooks/create-session-hooks.d.ts +3 -0
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/{recomp-orchestrator-a0g9b52q.js → recomp-orchestrator-c3ff16k7.js} +7 -6
- package/dist/{safe-notification-target-c11fdda2.js → safe-notification-target-b693f9x3.js} +2 -2
- package/dist/{send-session-notification-bgtf4853.js → send-session-notification-dxske5zm.js} +3 -3
- package/dist/shared/conflict-detector.d.ts +63 -0
- package/dist/shared/conflict-detector.d.ts.map +1 -1
- package/dist/shared/harness-provider-map.d.ts +8 -0
- package/dist/shared/harness-provider-map.d.ts.map +1 -1
- package/dist/shared/logger.d.ts +8 -0
- package/dist/shared/logger.d.ts.map +1 -1
- package/dist/shared/models-dev-cache.d.ts +5 -0
- package/dist/shared/models-dev-cache.d.ts.map +1 -1
- package/dist/shared/prompt-surface-runtime.d.ts.map +1 -1
- package/dist/shared/prompt-surface.d.ts +2 -0
- package/dist/shared/prompt-surface.d.ts.map +1 -1
- package/dist/shared/rpc-client.d.ts.map +1 -1
- package/dist/shared/rpc-types.d.ts +14 -0
- package/dist/shared/rpc-types.d.ts.map +1 -1
- package/dist/shared/rpc-utils.d.ts +19 -9
- package/dist/shared/rpc-utils.d.ts.map +1 -1
- package/dist/shared/window-geometry.d.ts +89 -0
- package/dist/shared/window-geometry.d.ts.map +1 -0
- package/dist/{storage-meta-session-df9tstzr.js → storage-meta-session-mk4gsnke.js} +4 -3
- package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
- package/dist/tools/ctx-note/tools.d.ts.map +1 -1
- package/dist/tui/data/context-db.d.ts.map +1 -1
- package/dist/tui-compiled/data/context-db.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/config/index.ts +2 -0
- package/src/config/latch-permanence-guard.test.ts +218 -0
- package/src/config/project-security.ts +10 -1
- package/src/config/schema/magic-context.ts +10 -0
- package/src/shared/__fixtures__/window-overlay.v1.json +337 -0
- package/src/shared/conflict-detector.test.ts +176 -1
- package/src/shared/conflict-detector.ts +126 -3
- package/src/shared/harness-provider-map.test.ts +20 -0
- package/src/shared/harness-provider-map.ts +19 -0
- package/src/shared/logger.test.ts +119 -0
- package/src/shared/logger.ts +33 -15
- package/src/shared/models-dev-cache.test.ts +17 -0
- package/src/shared/models-dev-cache.ts +58 -6
- package/src/shared/prompt-surface-runtime.ts +5 -3
- package/src/shared/prompt-surface.test.ts +38 -0
- package/src/shared/prompt-surface.ts +15 -2
- package/src/shared/rpc-client.ts +4 -2
- package/src/shared/rpc-types.ts +14 -0
- package/src/shared/rpc-utils.test.ts +137 -13
- package/src/shared/rpc-utils.ts +144 -31
- package/src/shared/window-geometry.test.ts +309 -0
- package/src/shared/window-geometry.ts +629 -0
- package/src/tui/data/context-db.ts +5 -0
- package/src/tui/index.tsx +22 -0
- package/src/tui-compiled/data/context-db.ts +5 -0
- package/src/tui-compiled/index.tsx +319 -255
- package/dist/index-wgvxkqpx.js +0 -342
package/dist/index.js
CHANGED
|
@@ -53,9 +53,11 @@ import {
|
|
|
53
53
|
acquireCompartmentLease,
|
|
54
54
|
acquireGitSweepLease,
|
|
55
55
|
acquireWrapupInProgress,
|
|
56
|
+
addMergedReasoningStrippedIds,
|
|
56
57
|
addNote,
|
|
57
58
|
addProcessedImageStrippedIds,
|
|
58
59
|
addStaleReduceStrippedIds,
|
|
60
|
+
addTrailingBlankDecisions,
|
|
59
61
|
adoptNullOwnerToolTag,
|
|
60
62
|
appendAutoSearchHintDecision,
|
|
61
63
|
applyDeferredCompactionMarker,
|
|
@@ -94,6 +96,7 @@ import {
|
|
|
94
96
|
computeCueContentHash,
|
|
95
97
|
computeNormalizedHash,
|
|
96
98
|
computeWorkspaceEpochFingerprint,
|
|
99
|
+
connectionFileExists,
|
|
97
100
|
contentSha256,
|
|
98
101
|
cortexKitProjectConfigBasePath,
|
|
99
102
|
cortexKitUserConfigBasePath,
|
|
@@ -174,6 +177,7 @@ import {
|
|
|
174
177
|
getMemoryCountsByStatus,
|
|
175
178
|
getMemoryMutationsForRenderByProjects,
|
|
176
179
|
getMemoryVerifications,
|
|
180
|
+
getMergedReasoningStrippedIds,
|
|
177
181
|
getMigrationOnOpenRefusal,
|
|
178
182
|
getMirrorCursor,
|
|
179
183
|
getModuleNoteEvaluationBridge,
|
|
@@ -215,6 +219,7 @@ import {
|
|
|
215
219
|
getTagsByNumbers,
|
|
216
220
|
getTagsBySession,
|
|
217
221
|
getToolTagNumberByOwner,
|
|
222
|
+
getTrailingBlankDecisions,
|
|
218
223
|
getTriggerTagTokenUpperBound,
|
|
219
224
|
getUnclassifiedMemoryIds,
|
|
220
225
|
getUnmappedMemoryIds,
|
|
@@ -226,6 +231,7 @@ import {
|
|
|
226
231
|
hasMemoryShareableColumn,
|
|
227
232
|
hasMuralCueColumns,
|
|
228
233
|
hasRunnableCompartmentWindow,
|
|
234
|
+
incrementalLkgContentDigests,
|
|
229
235
|
injectM0M1,
|
|
230
236
|
injectTemporalMarkers,
|
|
231
237
|
insertMemory,
|
|
@@ -240,10 +246,10 @@ import {
|
|
|
240
246
|
isEmbeddingEnabled,
|
|
241
247
|
isEmergencyRecoveryArmed,
|
|
242
248
|
isFailClosedBlockingError,
|
|
249
|
+
isLinkedGitWorktree,
|
|
243
250
|
isPidAlive,
|
|
244
251
|
isProviderOverflowReconfirmed,
|
|
245
252
|
lkgContentDigest,
|
|
246
|
-
lkgContentDigestFromFields,
|
|
247
253
|
loadCompartmentChunkEmbeddingsForSearch,
|
|
248
254
|
loadPersistedUsage,
|
|
249
255
|
loadProjectCommitEmbeddings,
|
|
@@ -333,6 +339,7 @@ import {
|
|
|
333
339
|
resolveLegacyConfigSources,
|
|
334
340
|
resolveLegacyConfigSourcesForHarness,
|
|
335
341
|
resolveModelConfigOrDefault,
|
|
342
|
+
resolveMuralWire,
|
|
336
343
|
resolveOpenCodeProtectedTailBoundary,
|
|
337
344
|
resolveProjectIdentity,
|
|
338
345
|
resolveProjectIdentityForSession,
|
|
@@ -400,19 +407,22 @@ import {
|
|
|
400
407
|
upsertCommits,
|
|
401
408
|
verificationFileExists,
|
|
402
409
|
withContentLanguageDirective
|
|
403
|
-
} from "./index-
|
|
410
|
+
} from "./index-0ze9p983.js";
|
|
404
411
|
import {
|
|
405
412
|
deriveHistorianChunkTokens,
|
|
406
413
|
deriveTriggerBudget,
|
|
414
|
+
formatWindowDerivationLine,
|
|
407
415
|
getSdkContextLimit,
|
|
416
|
+
getSdkWindowGeometry,
|
|
408
417
|
isSaneLimit,
|
|
409
418
|
refreshModelLimitsAfterAuthOnce,
|
|
410
419
|
refreshModelLimitsFromApi,
|
|
411
420
|
resolveHistorianContextLimit,
|
|
412
421
|
setOutputReserveConfig,
|
|
413
422
|
setStoragePrivatePermissionEnforcement,
|
|
423
|
+
setWindowOverlayPath,
|
|
414
424
|
shouldEnforcePrivateStoragePermissions
|
|
415
|
-
} from "./index-
|
|
425
|
+
} from "./index-q0t189ay.js";
|
|
416
426
|
import {
|
|
417
427
|
modelBodyField,
|
|
418
428
|
resolveFallbackChain
|
|
@@ -424,7 +434,7 @@ import {
|
|
|
424
434
|
getErrorMessage,
|
|
425
435
|
sendIgnoredMessage,
|
|
426
436
|
sendUserPrompt
|
|
427
|
-
} from "./index-
|
|
437
|
+
} from "./index-4cz5nfxf.js";
|
|
428
438
|
import {
|
|
429
439
|
ToolMutationBatch,
|
|
430
440
|
advanceToolReclaimWatermark,
|
|
@@ -482,7 +492,11 @@ import {
|
|
|
482
492
|
textMentionsRecentCommit,
|
|
483
493
|
updateSessionMeta,
|
|
484
494
|
withRawSessionMessageCache
|
|
485
|
-
} from "./index-
|
|
495
|
+
} from "./index-crke4z5j.js";
|
|
496
|
+
import {
|
|
497
|
+
modelRefLookupOrder,
|
|
498
|
+
piModelRefToCanonical
|
|
499
|
+
} from "./index-cgyfn1s2.js";
|
|
486
500
|
import {
|
|
487
501
|
Database,
|
|
488
502
|
closeQuietly,
|
|
@@ -491,12 +505,13 @@ import {
|
|
|
491
505
|
isMidTurn,
|
|
492
506
|
openCodeDbExists,
|
|
493
507
|
withReadOnlySessionDb
|
|
494
|
-
} from "./index-
|
|
508
|
+
} from "./index-sw8gnq34.js";
|
|
495
509
|
import {
|
|
496
510
|
cleanupConflictWarnings,
|
|
497
511
|
detectConflicts,
|
|
512
|
+
resolveCompactionForBoot,
|
|
498
513
|
sendConflictWarning
|
|
499
|
-
} from "./index-
|
|
514
|
+
} from "./index-cae89eas.js";
|
|
500
515
|
import {
|
|
501
516
|
detectConfigFile,
|
|
502
517
|
isPrototypePollutionKey,
|
|
@@ -519,11 +534,12 @@ import {
|
|
|
519
534
|
pushNotification,
|
|
520
535
|
registerNotificationSink
|
|
521
536
|
} from "./index-d62ypazr.js";
|
|
522
|
-
import"./index-
|
|
537
|
+
import"./index-pck9vadr.js";
|
|
523
538
|
import {
|
|
539
|
+
getLoggerDiagnostics,
|
|
524
540
|
log,
|
|
525
541
|
sessionLog
|
|
526
|
-
} from "./index-
|
|
542
|
+
} from "./index-8pqfcghm.js";
|
|
527
543
|
import {
|
|
528
544
|
getDataDir,
|
|
529
545
|
getHarness,
|
|
@@ -9125,6 +9141,11 @@ function stripUnsafeProjectConfigFields(projectRaw) {
|
|
|
9125
9141
|
delete projectRaw.output_reserve;
|
|
9126
9142
|
warnings.push("Ignoring output_reserve from project config (security: output-token reservation only honors user-level config).");
|
|
9127
9143
|
}
|
|
9144
|
+
const models = projectRaw.models;
|
|
9145
|
+
if (isPlainObject(models) && "window_overlay_path" in models) {
|
|
9146
|
+
delete models.window_overlay_path;
|
|
9147
|
+
warnings.push("Ignoring models.window_overlay_path from project config (security: only user-level config may select model geometry metadata).");
|
|
9148
|
+
}
|
|
9128
9149
|
if ("language" in projectRaw) {
|
|
9129
9150
|
delete projectRaw.language;
|
|
9130
9151
|
warnings.push("Ignoring language from project config (security: output language is a user-level setting).");
|
|
@@ -9787,6 +9808,7 @@ function loadPluginConfigDetailed(directory) {
|
|
|
9787
9808
|
const recoveredTopLevelKeys = [];
|
|
9788
9809
|
const config = parsePluginConfig(mergedRaw, recoveredTopLevelKeys);
|
|
9789
9810
|
setOutputReserveConfig(config.output_reserve);
|
|
9811
|
+
setWindowOverlayPath(config.models?.window_overlay_path);
|
|
9790
9812
|
if (config.configWarnings?.length) {
|
|
9791
9813
|
allWarnings.push(...config.configWarnings.map((w) => {
|
|
9792
9814
|
if (userLoaded && projectLoaded)
|
|
@@ -11566,6 +11588,7 @@ class SubcModuleTransport {
|
|
|
11566
11588
|
return error;
|
|
11567
11589
|
}
|
|
11568
11590
|
async beforeDeadline(operation, deadlineMs, detail) {
|
|
11591
|
+
operation.catch(() => {});
|
|
11569
11592
|
const remainingMs = deadlineMs - Date.now();
|
|
11570
11593
|
if (remainingMs <= 0)
|
|
11571
11594
|
throw this.deadlineError(detail);
|
|
@@ -15327,6 +15350,63 @@ function backoffMs(failureCount) {
|
|
|
15327
15350
|
return minutes * 60 * 1000;
|
|
15328
15351
|
}
|
|
15329
15352
|
|
|
15353
|
+
// src/features/magic-context/smart-notes/wake-plane.ts
|
|
15354
|
+
import { join as join5 } from "node:path";
|
|
15355
|
+
var WAKE_PLANE_CAPABILITY = "wake.create";
|
|
15356
|
+
var WAKE_PLANE_STATUS_TTL_MS = 5 * 60 * 1000;
|
|
15357
|
+
var WAKE_PLANE_HANDSHAKE_TIMEOUT_MS = 2000;
|
|
15358
|
+
var cachedStatus = null;
|
|
15359
|
+
var inFlightProbe = null;
|
|
15360
|
+
var catalogProbe = probeWakePlaneCatalog;
|
|
15361
|
+
var now = () => Date.now();
|
|
15362
|
+
function connectionFile() {
|
|
15363
|
+
return join5(getDataDir(), "cortexkit", "run", "subc-connection.json");
|
|
15364
|
+
}
|
|
15365
|
+
async function probeWakePlaneCatalog() {
|
|
15366
|
+
const file = connectionFile();
|
|
15367
|
+
if (!await connectionFileExists(file)) {
|
|
15368
|
+
throw new Error("subc connection is not configured");
|
|
15369
|
+
}
|
|
15370
|
+
const client = await SubcClient.connect({
|
|
15371
|
+
connectionFile: file,
|
|
15372
|
+
handshakeTimeoutMs: WAKE_PLANE_HANDSHAKE_TIMEOUT_MS
|
|
15373
|
+
});
|
|
15374
|
+
try {
|
|
15375
|
+
return await client.catalogList();
|
|
15376
|
+
} finally {
|
|
15377
|
+
client.close();
|
|
15378
|
+
}
|
|
15379
|
+
}
|
|
15380
|
+
function catalogHasWakePlane(entries) {
|
|
15381
|
+
return entries.some((entry) => Array.isArray(entry.control_ops) && entry.control_ops.includes(WAKE_PLANE_CAPABILITY));
|
|
15382
|
+
}
|
|
15383
|
+
async function probeStatus() {
|
|
15384
|
+
try {
|
|
15385
|
+
return catalogHasWakePlane(await catalogProbe()) ? "present" : "absent";
|
|
15386
|
+
} catch {
|
|
15387
|
+
return "unknown";
|
|
15388
|
+
}
|
|
15389
|
+
}
|
|
15390
|
+
async function wakePlaneStatus() {
|
|
15391
|
+
const cached = cachedStatus;
|
|
15392
|
+
if (cached && now() < cached.expiresAt)
|
|
15393
|
+
return cached.status;
|
|
15394
|
+
if (inFlightProbe)
|
|
15395
|
+
return await inFlightProbe;
|
|
15396
|
+
const startedAt = now();
|
|
15397
|
+
const probe = probeStatus().then((status) => {
|
|
15398
|
+
cachedStatus = { status, expiresAt: startedAt + WAKE_PLANE_STATUS_TTL_MS };
|
|
15399
|
+
return status;
|
|
15400
|
+
});
|
|
15401
|
+
inFlightProbe = probe;
|
|
15402
|
+
try {
|
|
15403
|
+
return await probe;
|
|
15404
|
+
} finally {
|
|
15405
|
+
if (inFlightProbe === probe)
|
|
15406
|
+
inFlightProbe = null;
|
|
15407
|
+
}
|
|
15408
|
+
}
|
|
15409
|
+
|
|
15330
15410
|
// src/features/magic-context/smart-notes/runner.ts
|
|
15331
15411
|
function inferEvaluateSmartNotesLeaseHeld(db, projectIdentity) {
|
|
15332
15412
|
const leaseKey = leaseKeyFor("evaluate-smart-notes", projectIdentity);
|
|
@@ -15339,9 +15419,12 @@ var DEFAULT_MAX_CHECKS = 10;
|
|
|
15339
15419
|
var DEFAULT_SWEEP_BUDGET_MS = 15000;
|
|
15340
15420
|
var MAX_FAILURES_BEFORE_REAUTHOR = 3;
|
|
15341
15421
|
async function runDueCompiledSmartNoteChecks(args) {
|
|
15422
|
+
if (await wakePlaneStatus() === "present") {
|
|
15423
|
+
return { ran: 0, surfaced: 0, failed: 0, networkFailed: 0 };
|
|
15424
|
+
}
|
|
15342
15425
|
const startedAt = Date.now();
|
|
15343
|
-
const
|
|
15344
|
-
const due = getDueCompiledSmartNoteChecks(args.db, args.projectIdentity,
|
|
15426
|
+
const now2 = args.now ?? startedAt;
|
|
15427
|
+
const due = getDueCompiledSmartNoteChecks(args.db, args.projectIdentity, now2, args.maxChecks ?? DEFAULT_MAX_CHECKS, args.retinaHandoff);
|
|
15345
15428
|
let ran = 0;
|
|
15346
15429
|
let surfaced = 0;
|
|
15347
15430
|
let failed = 0;
|
|
@@ -15468,6 +15551,11 @@ function createPromptAbortSignal(parent, timeoutMs, timeoutMessage) {
|
|
|
15468
15551
|
};
|
|
15469
15552
|
}
|
|
15470
15553
|
async function evaluateSmartNotes(args) {
|
|
15554
|
+
if (await wakePlaneStatus() === "present") {
|
|
15555
|
+
const pending = getPendingSmartNotes(args.db, args.projectIdentity).length;
|
|
15556
|
+
log("[dreamer] evaluate-smart-notes: skipped (wake plane active)");
|
|
15557
|
+
return { surfaced: 0, pending, ran: false };
|
|
15558
|
+
}
|
|
15471
15559
|
const projectRoot = args.sessionDirectory ?? args.projectIdentity;
|
|
15472
15560
|
const moduleBridge = getModuleNoteEvaluationBridge(args.projectIdentity);
|
|
15473
15561
|
await moduleBridge?.sync();
|
|
@@ -15559,7 +15647,7 @@ async function evaluateSmartNotes(args) {
|
|
|
15559
15647
|
assertLeaseHeld("fallback start");
|
|
15560
15648
|
didWork = true;
|
|
15561
15649
|
const met = await confirmReadOnly(args, note.id, note.content, note.surfaceCondition, leaseAbortController.signal);
|
|
15562
|
-
const
|
|
15650
|
+
const now2 = Date.now();
|
|
15563
15651
|
assertLeaseHeld("fallback commit");
|
|
15564
15652
|
const committed = commitSmartNoteState(args.db, {
|
|
15565
15653
|
phase: "fallback",
|
|
@@ -15570,7 +15658,7 @@ async function evaluateSmartNotes(args) {
|
|
|
15570
15658
|
markNoteReady(args.db, note.id, `Smart note #${note.id}: read-only confirmation evaluator returned met=true`);
|
|
15571
15659
|
} else {
|
|
15572
15660
|
markNoteChecked(args.db, note.id);
|
|
15573
|
-
markSmartNoteCheckStatus(args.db, note.id, "fallback",
|
|
15661
|
+
markSmartNoteCheckStatus(args.db, note.id, "fallback", now2);
|
|
15574
15662
|
}
|
|
15575
15663
|
}
|
|
15576
15664
|
});
|
|
@@ -15601,7 +15689,7 @@ async function compileNote(args, note, projectRoot, assertLeaseHeld, leaseHeld,
|
|
|
15601
15689
|
model: args.model,
|
|
15602
15690
|
fallbackModels: args.fallbackModels
|
|
15603
15691
|
});
|
|
15604
|
-
const
|
|
15692
|
+
const now2 = Date.now();
|
|
15605
15693
|
assertLeaseHeld("compile commit");
|
|
15606
15694
|
if (!result.ok) {
|
|
15607
15695
|
if (result.cancelled)
|
|
@@ -15612,13 +15700,13 @@ async function compileNote(args, note, projectRoot, assertLeaseHeld, leaseHeld,
|
|
|
15612
15700
|
expected: sourceRevisionExpectation(note),
|
|
15613
15701
|
leaseHeld,
|
|
15614
15702
|
write: () => {
|
|
15615
|
-
markSmartNoteCompilationFailure(args.db, note.id,
|
|
15703
|
+
markSmartNoteCompilationFailure(args.db, note.id, now2, MAX_COMPILATION_FAILURES);
|
|
15616
15704
|
}
|
|
15617
15705
|
});
|
|
15618
15706
|
return false;
|
|
15619
15707
|
}
|
|
15620
15708
|
const nextDueAt = nextSmartNoteCheckDueAt(result.checkCron, {
|
|
15621
|
-
now,
|
|
15709
|
+
now: now2,
|
|
15622
15710
|
noteId: note.id,
|
|
15623
15711
|
hash: result.checkHash
|
|
15624
15712
|
});
|
|
@@ -15634,12 +15722,12 @@ async function compileNote(args, note, projectRoot, assertLeaseHeld, leaseHeld,
|
|
|
15634
15722
|
checkHash: result.checkHash,
|
|
15635
15723
|
checkCron: result.checkCron,
|
|
15636
15724
|
nextDueAt,
|
|
15637
|
-
now
|
|
15725
|
+
now: now2
|
|
15638
15726
|
});
|
|
15639
15727
|
if (result.dryRun.met) {
|
|
15640
15728
|
markNoteReady(args.db, note.id, `Smart note #${note.id}: compiled check returned met=true`);
|
|
15641
15729
|
} else {
|
|
15642
|
-
markCompiledCheckFalse(args.db, note.id, nextDueAt,
|
|
15730
|
+
markCompiledCheckFalse(args.db, note.id, nextDueAt, now2);
|
|
15643
15731
|
}
|
|
15644
15732
|
}
|
|
15645
15733
|
});
|
|
@@ -15660,9 +15748,9 @@ async function runLivenessCheck(args, note, projectRoot, assertLeaseHeld, leaseH
|
|
|
15660
15748
|
});
|
|
15661
15749
|
if (!result.ok && result.cancelled)
|
|
15662
15750
|
return false;
|
|
15663
|
-
const
|
|
15751
|
+
const now2 = Date.now();
|
|
15664
15752
|
const nextDueAt = result.ok && !result.result.met ? nextSmartNoteCheckDueAt(note.checkCron, {
|
|
15665
|
-
now,
|
|
15753
|
+
now: now2,
|
|
15666
15754
|
noteId: note.id,
|
|
15667
15755
|
hash: note.checkHash
|
|
15668
15756
|
}) : null;
|
|
@@ -15672,13 +15760,13 @@ async function runLivenessCheck(args, note, projectRoot, assertLeaseHeld, leaseH
|
|
|
15672
15760
|
expected: compiledCheckExpectation(note, compiledCheck),
|
|
15673
15761
|
leaseHeld,
|
|
15674
15762
|
write: () => {
|
|
15675
|
-
markSmartNoteLivenessChecked(args.db, note.id,
|
|
15763
|
+
markSmartNoteLivenessChecked(args.db, note.id, now2);
|
|
15676
15764
|
if (result.ok && result.result.met) {
|
|
15677
15765
|
markNoteReady(args.db, note.id, `Smart note #${note.id}: max-staleness liveness check returned met=true`);
|
|
15678
15766
|
} else if (result.ok && nextDueAt !== null) {
|
|
15679
|
-
markCompiledCheckFalse(args.db, note.id, nextDueAt,
|
|
15767
|
+
markCompiledCheckFalse(args.db, note.id, nextDueAt, now2);
|
|
15680
15768
|
} else if (!result.ok && !result.network) {
|
|
15681
|
-
markSmartNoteCheckStatus(args.db, note.id, "failing",
|
|
15769
|
+
markSmartNoteCheckStatus(args.db, note.id, "failing", now2);
|
|
15682
15770
|
}
|
|
15683
15771
|
}
|
|
15684
15772
|
});
|
|
@@ -15804,7 +15892,7 @@ Output exactly JSON: {"met": false}`;
|
|
|
15804
15892
|
|
|
15805
15893
|
// src/features/magic-context/dreamer/maintain-docs-protected-enforcement.ts
|
|
15806
15894
|
import { existsSync as existsSync7, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "node:fs";
|
|
15807
|
-
import { join as
|
|
15895
|
+
import { join as join6 } from "node:path";
|
|
15808
15896
|
|
|
15809
15897
|
// src/features/magic-context/dreamer/protected-regions.ts
|
|
15810
15898
|
var PROTECTED_START_TOKEN = "mc:protected START";
|
|
@@ -15905,7 +15993,7 @@ var MAINTAIN_DOCS_SNAPSHOT_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
|
15905
15993
|
function snapshotMaintainDocsFiles(docsDir) {
|
|
15906
15994
|
const snapshot = new Map;
|
|
15907
15995
|
for (const name of MAINTAIN_DOCS_SNAPSHOT_FILES) {
|
|
15908
|
-
const path3 =
|
|
15996
|
+
const path3 = join6(docsDir, name);
|
|
15909
15997
|
try {
|
|
15910
15998
|
if (existsSync7(path3)) {
|
|
15911
15999
|
snapshot.set(name, readFileSync5(path3, "utf8"));
|
|
@@ -15916,7 +16004,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
15916
16004
|
}
|
|
15917
16005
|
function enforceMaintainDocsProtectedRegions(args) {
|
|
15918
16006
|
for (const [fileName, original] of args.snapshot) {
|
|
15919
|
-
const path3 =
|
|
16007
|
+
const path3 = join6(args.docsDir, fileName);
|
|
15920
16008
|
try {
|
|
15921
16009
|
const current = readFileSync5(path3, "utf8");
|
|
15922
16010
|
const { text, violated } = enforceProtectedRegions(original, current);
|
|
@@ -16212,10 +16300,10 @@ async function applyBatchMappings(args, batch, manifestText) {
|
|
|
16212
16300
|
}
|
|
16213
16301
|
return { mapped, independent };
|
|
16214
16302
|
}
|
|
16215
|
-
const
|
|
16303
|
+
const now2 = Date.now();
|
|
16216
16304
|
runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
|
|
16217
16305
|
for (const item of planned) {
|
|
16218
|
-
recordMemoryMapping(args.db, item.id, item.files,
|
|
16306
|
+
recordMemoryMapping(args.db, item.id, item.files, now2);
|
|
16219
16307
|
item.independent ? independent += 1 : mapped += 1;
|
|
16220
16308
|
}
|
|
16221
16309
|
});
|
|
@@ -16387,7 +16475,7 @@ async function embedMissingCandidates(args, assertLeaseHeld) {
|
|
|
16387
16475
|
updatePrimerCandidateEmbedding(args.db, candidates[i].id, vector, batch.modelId);
|
|
16388
16476
|
}
|
|
16389
16477
|
}
|
|
16390
|
-
function pruneExpiredPrimerCandidatesForProject(db, projectIdentity,
|
|
16478
|
+
function pruneExpiredPrimerCandidatesForProject(db, projectIdentity, now2 = Date.now(), ttlMs = PRIMER_CANDIDATE_TTL_MS, maxAgeMs = PRIMER_CANDIDATE_MAX_AGE_MS) {
|
|
16391
16479
|
const protectedIds = new Set;
|
|
16392
16480
|
for (const primer of getActivePrimers(db, projectIdentity)) {
|
|
16393
16481
|
for (const id of primer.sourceCandidateIds)
|
|
@@ -16395,8 +16483,8 @@ function pruneExpiredPrimerCandidatesForProject(db, projectIdentity, now = Date.
|
|
|
16395
16483
|
}
|
|
16396
16484
|
const oldRows = db.prepare(`SELECT id, source_message_time
|
|
16397
16485
|
FROM primer_candidates
|
|
16398
|
-
WHERE project_path = ? AND source_message_time < ?`).all(projectIdentity,
|
|
16399
|
-
const toDelete = oldRows.filter((row) => !protectedIds.has(row.id) || row.source_message_time <
|
|
16486
|
+
WHERE project_path = ? AND source_message_time < ?`).all(projectIdentity, now2 - ttlMs);
|
|
16487
|
+
const toDelete = oldRows.filter((row) => !protectedIds.has(row.id) || row.source_message_time < now2 - maxAgeMs).map((row) => row.id);
|
|
16400
16488
|
if (toDelete.length === 0)
|
|
16401
16489
|
return 0;
|
|
16402
16490
|
const stmt = db.prepare("DELETE FROM primer_candidates WHERE id = ? AND project_path = ?");
|
|
@@ -17511,7 +17599,7 @@ async function applyVerifyManifest(args, batch, manifestText) {
|
|
|
17511
17599
|
const batchIds = new Set(batch.map((m) => m.id));
|
|
17512
17600
|
const parsed = parseVerifyManifest(manifestText);
|
|
17513
17601
|
assertManifestCoversExactly([...parsed.verified, ...parsed.updated, ...parsed.archived].map((entry) => entry.id), batchIds, "verify");
|
|
17514
|
-
const
|
|
17602
|
+
const now2 = Date.now();
|
|
17515
17603
|
const writes = [];
|
|
17516
17604
|
for (const v of parsed.verified) {
|
|
17517
17605
|
const files = await normalizeFiles(args, v.files);
|
|
@@ -17598,7 +17686,7 @@ async function applyVerifyManifest(args, batch, manifestText) {
|
|
|
17598
17686
|
if (!isPrimaryMutable(memory))
|
|
17599
17687
|
continue;
|
|
17600
17688
|
if (w.kind === "verify") {
|
|
17601
|
-
recordMemoryVerifications(args.db, w.id, w.files,
|
|
17689
|
+
recordMemoryVerifications(args.db, w.id, w.files, now2);
|
|
17602
17690
|
verified += 1;
|
|
17603
17691
|
} else if (w.kind === "update") {
|
|
17604
17692
|
rewriteMemoryContent(args.db, memory, w.content, w.hash);
|
|
@@ -18431,17 +18519,17 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
18431
18519
|
|
|
18432
18520
|
// src/features/magic-context/dreamer/task-scheduler.ts
|
|
18433
18521
|
var MAX_TASK_RETRIES = 3;
|
|
18434
|
-
function ensureSeeded(db, projectIdentity, config,
|
|
18522
|
+
function ensureSeeded(db, projectIdentity, config, now2) {
|
|
18435
18523
|
if (getTaskScheduleState(db, projectIdentity, config.task))
|
|
18436
18524
|
return;
|
|
18437
18525
|
const legacy = getDreamState(db, `last_dream_at:${projectIdentity}`);
|
|
18438
18526
|
const legacyLastRun = legacy ? Number(legacy) : null;
|
|
18439
18527
|
const lastRunAt = legacyLastRun && Number.isFinite(legacyLastRun) ? legacyLastRun : null;
|
|
18440
|
-
const nextDueAt = nextDueAtMs(config.schedule,
|
|
18528
|
+
const nextDueAt = nextDueAtMs(config.schedule, now2);
|
|
18441
18529
|
seedTaskScheduleState(db, projectIdentity, config.task, nextDueAt, lastRunAt, config.schedule);
|
|
18442
18530
|
}
|
|
18443
|
-
function reconcileSchedule(db, projectIdentity, config,
|
|
18444
|
-
ensureSeeded(db, projectIdentity, config,
|
|
18531
|
+
function reconcileSchedule(db, projectIdentity, config, now2) {
|
|
18532
|
+
ensureSeeded(db, projectIdentity, config, now2);
|
|
18445
18533
|
const stored = getTaskScheduleState(db, projectIdentity, config.task);
|
|
18446
18534
|
if (!stored || stored.schedule === config.schedule)
|
|
18447
18535
|
return;
|
|
@@ -18456,22 +18544,22 @@ function reconcileSchedule(db, projectIdentity, config, now) {
|
|
|
18456
18544
|
writeTaskScheduleState(db, {
|
|
18457
18545
|
...stored,
|
|
18458
18546
|
schedule: config.schedule,
|
|
18459
|
-
nextDueAt: nextDueAtMs(config.schedule,
|
|
18547
|
+
nextDueAt: nextDueAtMs(config.schedule, now2),
|
|
18460
18548
|
retryCount: 0
|
|
18461
18549
|
});
|
|
18462
18550
|
}
|
|
18463
|
-
function planDueTasks(db, projectIdentity, tasks,
|
|
18551
|
+
function planDueTasks(db, projectIdentity, tasks, now2) {
|
|
18464
18552
|
const pruned = pruneNonCanonicalTaskRows(db, projectIdentity, tasks.map((t) => t.task));
|
|
18465
18553
|
if (pruned > 0) {
|
|
18466
18554
|
log(`[dreamer] pruned ${pruned} retired task row(s) for ${projectIdentity}`);
|
|
18467
18555
|
}
|
|
18468
18556
|
const due = [];
|
|
18469
18557
|
for (const config of tasks) {
|
|
18470
|
-
reconcileSchedule(db, projectIdentity, config,
|
|
18558
|
+
reconcileSchedule(db, projectIdentity, config, now2);
|
|
18471
18559
|
const state = getTaskScheduleState(db, projectIdentity, config.task);
|
|
18472
18560
|
if (!state || state.nextDueAt === null)
|
|
18473
18561
|
continue;
|
|
18474
|
-
if (
|
|
18562
|
+
if (now2 >= state.nextDueAt) {
|
|
18475
18563
|
due.push({ config, scheduledAt: state.nextDueAt });
|
|
18476
18564
|
}
|
|
18477
18565
|
}
|
|
@@ -18593,7 +18681,7 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
18593
18681
|
}
|
|
18594
18682
|
}
|
|
18595
18683
|
async function runManualDream(deps) {
|
|
18596
|
-
const
|
|
18684
|
+
const now2 = Date.now();
|
|
18597
18685
|
const result = {
|
|
18598
18686
|
ran: [],
|
|
18599
18687
|
skippedNoWork: [],
|
|
@@ -18620,8 +18708,8 @@ async function runManualDream(deps) {
|
|
|
18620
18708
|
result.backlogBefore = getDreamTaskBacklogs(deps.db, deps.projectIdentity, selectedTaskNames);
|
|
18621
18709
|
result.backlogAfter = { ...result.backlogBefore };
|
|
18622
18710
|
for (const cfg of selected)
|
|
18623
|
-
ensureSeeded(deps.db, deps.projectIdentity, cfg,
|
|
18624
|
-
const dueAll = selected.map((config) => ({ config, scheduledAt:
|
|
18711
|
+
ensureSeeded(deps.db, deps.projectIdentity, cfg, now2);
|
|
18712
|
+
const dueAll = selected.map((config) => ({ config, scheduledAt: now2 }));
|
|
18625
18713
|
const gated = [];
|
|
18626
18714
|
for (const d of dueAll) {
|
|
18627
18715
|
if (forceGate) {
|
|
@@ -18666,8 +18754,8 @@ async function runManualDream(deps) {
|
|
|
18666
18754
|
return result;
|
|
18667
18755
|
}
|
|
18668
18756
|
async function runDueTasksForProject(deps) {
|
|
18669
|
-
const
|
|
18670
|
-
const due = planDueTasks(deps.db, deps.projectIdentity, deps.tasks,
|
|
18757
|
+
const now2 = deps.now ?? Date.now();
|
|
18758
|
+
const due = planDueTasks(deps.db, deps.projectIdentity, deps.tasks, now2);
|
|
18671
18759
|
if (due.length === 0)
|
|
18672
18760
|
return 0;
|
|
18673
18761
|
const gated = [];
|
|
@@ -18682,7 +18770,7 @@ async function runDueTasksForProject(deps) {
|
|
|
18682
18770
|
if (pass) {
|
|
18683
18771
|
gated.push(d);
|
|
18684
18772
|
} else {
|
|
18685
|
-
advanceAfterRun(deps.db, deps.projectIdentity, d,
|
|
18773
|
+
advanceAfterRun(deps.db, deps.projectIdentity, d, now2, "skipped", null);
|
|
18686
18774
|
}
|
|
18687
18775
|
}
|
|
18688
18776
|
if (gated.length === 0)
|
|
@@ -19669,6 +19757,26 @@ function createCompactionHandler() {
|
|
|
19669
19757
|
|
|
19670
19758
|
// src/hooks/magic-context/event-resolvers.ts
|
|
19671
19759
|
var DEFAULT_CONTEXT_LIMIT = 128000;
|
|
19760
|
+
function resolveContextWindowGeometry(providerID, modelID, ctx) {
|
|
19761
|
+
if (!providerID || !modelID)
|
|
19762
|
+
return;
|
|
19763
|
+
const modelKey = resolveModelKey(providerID, modelID);
|
|
19764
|
+
let detected;
|
|
19765
|
+
let detectedLimitProvenance = "unknown";
|
|
19766
|
+
if (ctx?.db && ctx.sessionID) {
|
|
19767
|
+
try {
|
|
19768
|
+
const overflow = getOverflowState(ctx.db, ctx.sessionID, modelKey);
|
|
19769
|
+
if (overflow.detectedContextLimit > 0) {
|
|
19770
|
+
detected = overflow.detectedContextLimit;
|
|
19771
|
+
detectedLimitProvenance = overflow.detectedContextLimitProvenance;
|
|
19772
|
+
}
|
|
19773
|
+
} catch {}
|
|
19774
|
+
}
|
|
19775
|
+
return getSdkWindowGeometry(providerID, modelID, detected, {
|
|
19776
|
+
detectedLimitProvenance,
|
|
19777
|
+
harness: "opencode"
|
|
19778
|
+
});
|
|
19779
|
+
}
|
|
19672
19780
|
function resolveContextLimit(providerID, modelID, ctx) {
|
|
19673
19781
|
const modelKey = resolveModelKey(providerID, modelID);
|
|
19674
19782
|
let detected;
|
|
@@ -19711,7 +19819,7 @@ function resolveTrustedContextLimit(providerID, modelID, ctx) {
|
|
|
19711
19819
|
if (modelKey && ctx?.db && ctx.sessionID) {
|
|
19712
19820
|
try {
|
|
19713
19821
|
const persisted = loadPersistedUsage(ctx.db, ctx.sessionID);
|
|
19714
|
-
if (persisted
|
|
19822
|
+
if (persisted !== null && piModelRefToCanonical(persisted.lastObservedModelKey ?? "") === piModelRefToCanonical(modelKey) && isSaneLimit(persisted.lastUsageContextLimit)) {
|
|
19715
19823
|
return persisted.lastUsageContextLimit;
|
|
19716
19824
|
}
|
|
19717
19825
|
} catch {}
|
|
@@ -19730,11 +19838,13 @@ function isFinitePositive(v) {
|
|
|
19730
19838
|
}
|
|
19731
19839
|
function* modelKeyLookupOrder(modelKey) {
|
|
19732
19840
|
const slash = modelKey.indexOf("/");
|
|
19733
|
-
const
|
|
19841
|
+
const providerRefs = slash >= 0 ? modelRefLookupOrder(modelKey) : [];
|
|
19734
19842
|
let modelId = slash >= 0 ? modelKey.slice(slash + 1) : modelKey;
|
|
19735
19843
|
while (modelId.length > 0) {
|
|
19736
|
-
|
|
19737
|
-
|
|
19844
|
+
for (const providerRef of providerRefs) {
|
|
19845
|
+
const providerSlash = providerRef.indexOf("/");
|
|
19846
|
+
yield `${providerRef.slice(0, providerSlash)}/${modelId}`;
|
|
19847
|
+
}
|
|
19738
19848
|
yield modelId;
|
|
19739
19849
|
const lastDash = modelId.lastIndexOf("-");
|
|
19740
19850
|
if (lastDash <= 0)
|
|
@@ -19852,7 +19962,7 @@ function resolveModelKey(providerID, modelID) {
|
|
|
19852
19962
|
if (!providerID || !modelID) {
|
|
19853
19963
|
return;
|
|
19854
19964
|
}
|
|
19855
|
-
return `${providerID}/${modelID}
|
|
19965
|
+
return piModelRefToCanonical(`${providerID}/${modelID}`);
|
|
19856
19966
|
}
|
|
19857
19967
|
function resolveSessionId(properties) {
|
|
19858
19968
|
if (typeof properties?.sessionID === "string") {
|
|
@@ -20688,7 +20798,7 @@ function formatExecuteThreshold(detail, contextLimit) {
|
|
|
20688
20798
|
}
|
|
20689
20799
|
return `${percentage}%${clampNote}`;
|
|
20690
20800
|
}
|
|
20691
|
-
function executeStatus(db, sessionId, protectedTags, executeThresholdPercentageConfig = DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, liveModelKey, historyBudgetPercentage, commitClusterTrigger, executeThresholdTokens, contextLimit, dreamer) {
|
|
20801
|
+
function executeStatus(db, sessionId, protectedTags, executeThresholdPercentageConfig = DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, liveModelKey, historyBudgetPercentage, commitClusterTrigger, executeThresholdTokens, contextLimit, dreamer, windowGeometry) {
|
|
20692
20802
|
const thresholdDetail = resolveExecuteThresholdDetail(executeThresholdPercentageConfig, liveModelKey, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, {
|
|
20693
20803
|
tokensConfig: executeThresholdTokens,
|
|
20694
20804
|
contextLimit,
|
|
@@ -20749,7 +20859,7 @@ function executeStatus(db, sessionId, protectedTags, executeThresholdPercentageC
|
|
|
20749
20859
|
] : [], ...formatDreamTaskBacklogs(dreamer.backlog).split("\\n"));
|
|
20750
20860
|
}
|
|
20751
20861
|
if (meta.lastContextPercentage > 0 || meta.lastInputTokens > 0) {
|
|
20752
|
-
lines.push("", "### Context Usage", `- Last percentage: ${meta.lastContextPercentage.toFixed(1)}%`, `- Last input tokens: ${meta.lastInputTokens.toLocaleString()}`, `- Resolved context limit: ${displayContextLimit > 0 ? displayContextLimit.toLocaleString() : "unknown"}`, `- Proactive compartment evaluation: ${proactiveCompartmentTrigger}%`, `- Post-drop target for historian: ${(executeThresholdPercentage * POST_DROP_TARGET_RATIO).toFixed(0)}% (${executeThresholdPercentage}% * ${POST_DROP_TARGET_RATIO})`, `- Commit cluster trigger: ${commitClusterTrigger?.enabled !== false ? `enabled (min ${commitClusterTrigger?.min_clusters ?? 3} clusters)` : "disabled"}, tail-size trigger: > 3x compartment budget`);
|
|
20862
|
+
lines.push("", "### Context Usage", `- Last percentage: ${meta.lastContextPercentage.toFixed(1)}%`, `- Last input tokens: ${meta.lastInputTokens.toLocaleString()}`, `- Resolved context limit: ${displayContextLimit > 0 ? displayContextLimit.toLocaleString() : "unknown"}`, ...windowGeometry ? [`- ${formatWindowDerivationLine(meta.lastInputTokens, windowGeometry)}`] : [], `- Proactive compartment evaluation: ${proactiveCompartmentTrigger}%`, `- Post-drop target for historian: ${(executeThresholdPercentage * POST_DROP_TARGET_RATIO).toFixed(0)}% (${executeThresholdPercentage}% * ${POST_DROP_TARGET_RATIO})`, `- Commit cluster trigger: ${commitClusterTrigger?.enabled !== false ? `enabled (min ${commitClusterTrigger?.min_clusters ?? 3} clusters)` : "disabled"}, tail-size trigger: > 3x compartment budget`);
|
|
20753
20863
|
}
|
|
20754
20864
|
const compartments = getCompartments(db, sessionId);
|
|
20755
20865
|
let historyBlockTokens = 0;
|
|
@@ -20907,6 +21017,10 @@ ${summary || "Nothing to compact."}`;
|
|
|
20907
21017
|
return `## Magic Wrapup — Skipped
|
|
20908
21018
|
|
|
20909
21019
|
/ctx-wrapup is already running for this session${rounds > 0 ? ` (${rounds} round${rounds === 1 ? "" : "s"} complete)` : ""}. Wait for it to finish, then run /ctx-wrapup again if more history remains.`;
|
|
21020
|
+
case "retryable":
|
|
21021
|
+
return `## Magic Wrapup — Partial
|
|
21022
|
+
|
|
21023
|
+
${summary || "Wrapup made progress but stopped before the keep watermark."} Run /ctx-wrapup again to continue.`;
|
|
20910
21024
|
default:
|
|
20911
21025
|
return `## Magic Wrapup — Failed
|
|
20912
21026
|
|
|
@@ -21213,10 +21327,12 @@ Embedding status is unavailable.`;
|
|
|
21213
21327
|
}
|
|
21214
21328
|
const liveModelKey = deps.getLiveModelKey?.(sessionId);
|
|
21215
21329
|
const liveContextLimit = deps.getContextLimit?.(sessionId);
|
|
21330
|
+
const modelSlash = liveModelKey?.indexOf("/") ?? -1;
|
|
21331
|
+
const windowGeometry = liveModelKey && modelSlash > 0 ? resolveContextWindowGeometry(liveModelKey.slice(0, modelSlash), liveModelKey.slice(modelSlash + 1), { db: deps.db, sessionID: sessionId }) : undefined;
|
|
21216
21332
|
const statusOutput = executeStatus(deps.db, sessionId, deps.protectedTags, deps.executeThresholdPercentage, liveModelKey, deps.historyBudgetPercentage, deps.commitClusterTrigger, deps.executeThresholdTokens, liveContextLimit, deps.dreamer ? {
|
|
21217
21333
|
backlog: readDreamTaskBacklogsSafely(deps.db, deps.dreamer.projectPath, CANONICAL_DREAM_TASKS),
|
|
21218
21334
|
progress: deps.getDreamerProgress?.() ?? null
|
|
21219
|
-
} : undefined);
|
|
21335
|
+
} : undefined, windowGeometry);
|
|
21220
21336
|
const moduleStatus = rustStatus ? `
|
|
21221
21337
|
|
|
21222
21338
|
${formatRustStatusText(rustStatus)}` : "";
|
|
@@ -21239,7 +21355,7 @@ ${combinedStatus}` : combinedStatus;
|
|
|
21239
21355
|
|
|
21240
21356
|
${parsed.message}`;
|
|
21241
21357
|
} else if (rustMode) {
|
|
21242
|
-
const keep =
|
|
21358
|
+
const keep = parsed.messagesToKeep;
|
|
21243
21359
|
await deps.sendNotification(sessionId, `## Magic Wrapup
|
|
21244
21360
|
|
|
21245
21361
|
Starting wrapup…`, {});
|
|
@@ -21300,8 +21416,8 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
21300
21416
|
} else {
|
|
21301
21417
|
const argsKey = parsedArgs.kind === "partial" ? `${parsedArgs.range.start}-${parsedArgs.range.end}` : "";
|
|
21302
21418
|
const lastConfirmation = recompConfirmationBySession.get(sessionId);
|
|
21303
|
-
const
|
|
21304
|
-
const confirmationValid = lastConfirmation &&
|
|
21419
|
+
const now2 = Date.now();
|
|
21420
|
+
const confirmationValid = lastConfirmation && now2 - lastConfirmation.timestamp < RECOMP_CONFIRMATION_WINDOW_MS && lastConfirmation.argsKey === argsKey;
|
|
21305
21421
|
if (confirmationValid) {
|
|
21306
21422
|
recompConfirmationBySession.delete(sessionId);
|
|
21307
21423
|
if (parsedArgs.kind === "partial") {
|
|
@@ -21319,7 +21435,7 @@ Historian recomp started. Rebuilding compartments and facts from raw session his
|
|
|
21319
21435
|
}
|
|
21320
21436
|
} else {
|
|
21321
21437
|
recompConfirmationBySession.set(sessionId, {
|
|
21322
|
-
timestamp:
|
|
21438
|
+
timestamp: now2,
|
|
21323
21439
|
argsKey
|
|
21324
21440
|
});
|
|
21325
21441
|
const compartments = getCompartments(deps.db, sessionId);
|
|
@@ -21974,6 +22090,277 @@ function writeTransformDecisionRowOnDatabase(db, row, configureBusyTimeout) {
|
|
|
21974
22090
|
)`).run(row.sessionId, row.harness, row.sessionId, row.harness, retentionOverrideForTests ?? TRANSFORM_DECISIONS_RETENTION);
|
|
21975
22091
|
}
|
|
21976
22092
|
|
|
22093
|
+
// src/features/magic-context/window-report-ledger.ts
|
|
22094
|
+
import * as fs from "node:fs";
|
|
22095
|
+
import * as path5 from "node:path";
|
|
22096
|
+
var WINDOW_REPORTS_FILE = "window-reports.jsonl";
|
|
22097
|
+
var ROTATED_WINDOW_REPORTS_FILE = `${WINDOW_REPORTS_FILE}.1`;
|
|
22098
|
+
var WINDOW_REPORTS_ROTATION_BYTES = 16 * 1024 * 1024;
|
|
22099
|
+
var FORWARDING_PROVIDER_IDS = new Set([
|
|
22100
|
+
"302ai",
|
|
22101
|
+
"abacus",
|
|
22102
|
+
"ai-router",
|
|
22103
|
+
"aiand",
|
|
22104
|
+
"aihubmix",
|
|
22105
|
+
"alibaba-cn",
|
|
22106
|
+
"alibaba-coding-plan",
|
|
22107
|
+
"alibaba-coding-plan-cn",
|
|
22108
|
+
"alibaba-token-plan",
|
|
22109
|
+
"alibaba-token-plan-cn",
|
|
22110
|
+
"ambient",
|
|
22111
|
+
"anyapi",
|
|
22112
|
+
"auriko",
|
|
22113
|
+
"azure",
|
|
22114
|
+
"azure-cognitive-services",
|
|
22115
|
+
"baseten",
|
|
22116
|
+
"berget",
|
|
22117
|
+
"blueclaw",
|
|
22118
|
+
"chutes",
|
|
22119
|
+
"clarifai",
|
|
22120
|
+
"cline-pass",
|
|
22121
|
+
"cloudferro-sherlock",
|
|
22122
|
+
"cloudflare-ai-gateway",
|
|
22123
|
+
"cloudflare-workers-ai",
|
|
22124
|
+
"coralbricks",
|
|
22125
|
+
"cortecs",
|
|
22126
|
+
"crof",
|
|
22127
|
+
"crossmodel",
|
|
22128
|
+
"daoxe",
|
|
22129
|
+
"deepinfra",
|
|
22130
|
+
"digitalocean",
|
|
22131
|
+
"dinference",
|
|
22132
|
+
"drun",
|
|
22133
|
+
"empiriolabs",
|
|
22134
|
+
"evroc",
|
|
22135
|
+
"fastrouter",
|
|
22136
|
+
"fireworks-ai",
|
|
22137
|
+
"freemodel",
|
|
22138
|
+
"friendli",
|
|
22139
|
+
"frogbot",
|
|
22140
|
+
"github-copilot",
|
|
22141
|
+
"gmicloud",
|
|
22142
|
+
"google-vertex",
|
|
22143
|
+
"greenpt",
|
|
22144
|
+
"groq",
|
|
22145
|
+
"helicone",
|
|
22146
|
+
"hetzner",
|
|
22147
|
+
"hpc-ai",
|
|
22148
|
+
"huggingface",
|
|
22149
|
+
"hyper",
|
|
22150
|
+
"iflowcn",
|
|
22151
|
+
"impossibl",
|
|
22152
|
+
"inceptron",
|
|
22153
|
+
"inference",
|
|
22154
|
+
"inferx",
|
|
22155
|
+
"infomaniak",
|
|
22156
|
+
"io-net",
|
|
22157
|
+
"jiekou",
|
|
22158
|
+
"kenari",
|
|
22159
|
+
"kilo",
|
|
22160
|
+
"lilac",
|
|
22161
|
+
"llmgateway",
|
|
22162
|
+
"lmstudio",
|
|
22163
|
+
"meganova",
|
|
22164
|
+
"merge-gateway",
|
|
22165
|
+
"mixlayer",
|
|
22166
|
+
"modal",
|
|
22167
|
+
"model-oracle-ai",
|
|
22168
|
+
"modelis",
|
|
22169
|
+
"modelscope",
|
|
22170
|
+
"moonshotai-cn",
|
|
22171
|
+
"nano-gpt",
|
|
22172
|
+
"nearai",
|
|
22173
|
+
"nebius",
|
|
22174
|
+
"neon",
|
|
22175
|
+
"neuralwatt",
|
|
22176
|
+
"novita-ai",
|
|
22177
|
+
"nvidia",
|
|
22178
|
+
"ofox",
|
|
22179
|
+
"opencode",
|
|
22180
|
+
"opencode-go",
|
|
22181
|
+
"openrouter",
|
|
22182
|
+
"orcarouter",
|
|
22183
|
+
"ovhcloud",
|
|
22184
|
+
"perplexity-agent",
|
|
22185
|
+
"pioneer",
|
|
22186
|
+
"poe",
|
|
22187
|
+
"poolside",
|
|
22188
|
+
"privatemode-ai",
|
|
22189
|
+
"qihang-ai",
|
|
22190
|
+
"qiniu-ai",
|
|
22191
|
+
"qvac",
|
|
22192
|
+
"regolo-ai",
|
|
22193
|
+
"requesty",
|
|
22194
|
+
"routing-run",
|
|
22195
|
+
"salad-cloud",
|
|
22196
|
+
"sap-ai-core",
|
|
22197
|
+
"scaleway",
|
|
22198
|
+
"siliconflow",
|
|
22199
|
+
"siliconflow-cn",
|
|
22200
|
+
"snowflake-cortex",
|
|
22201
|
+
"stackit",
|
|
22202
|
+
"subconscious",
|
|
22203
|
+
"submodel",
|
|
22204
|
+
"synthetic",
|
|
22205
|
+
"tencent-coding-plan",
|
|
22206
|
+
"tensorx",
|
|
22207
|
+
"thinkingmachines",
|
|
22208
|
+
"tinfoil",
|
|
22209
|
+
"togetherai",
|
|
22210
|
+
"unorouter",
|
|
22211
|
+
"venice",
|
|
22212
|
+
"vercel",
|
|
22213
|
+
"vivgrid",
|
|
22214
|
+
"vultr",
|
|
22215
|
+
"wandb",
|
|
22216
|
+
"watsonx",
|
|
22217
|
+
"xpersona",
|
|
22218
|
+
"zai",
|
|
22219
|
+
"zai-coding-plan",
|
|
22220
|
+
"zenifra",
|
|
22221
|
+
"zenmux",
|
|
22222
|
+
"zhipuai",
|
|
22223
|
+
"zhipuai-coding-plan"
|
|
22224
|
+
]);
|
|
22225
|
+
var swallowedWriteCount = 0;
|
|
22226
|
+
var lastErrorMessage = null;
|
|
22227
|
+
function getWindowReportsPath() {
|
|
22228
|
+
return path5.join(getMagicContextStorageDir(), WINDOW_REPORTS_FILE);
|
|
22229
|
+
}
|
|
22230
|
+
function recordSwallowedWrite(error) {
|
|
22231
|
+
try {
|
|
22232
|
+
swallowedWriteCount++;
|
|
22233
|
+
lastErrorMessage = error instanceof Error ? error.message : String(error);
|
|
22234
|
+
log("[magic-context] window report ledger write failed:", error);
|
|
22235
|
+
} catch {}
|
|
22236
|
+
}
|
|
22237
|
+
function positiveFiniteNumber(value) {
|
|
22238
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
22239
|
+
}
|
|
22240
|
+
function observedStatus(error) {
|
|
22241
|
+
if (!error || typeof error !== "object")
|
|
22242
|
+
return;
|
|
22243
|
+
const candidate = error;
|
|
22244
|
+
for (const value of [candidate.status, candidate.statusCode]) {
|
|
22245
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599) {
|
|
22246
|
+
return value;
|
|
22247
|
+
}
|
|
22248
|
+
}
|
|
22249
|
+
const nested = candidate.response;
|
|
22250
|
+
if (nested && typeof nested === "object") {
|
|
22251
|
+
return observedStatus(nested);
|
|
22252
|
+
}
|
|
22253
|
+
return;
|
|
22254
|
+
}
|
|
22255
|
+
function observedHeaderHint(headers) {
|
|
22256
|
+
if (!headers || typeof headers !== "object")
|
|
22257
|
+
return;
|
|
22258
|
+
const values = headers;
|
|
22259
|
+
for (const key of ["x-served-by", "x-upstream", "x-backend"]) {
|
|
22260
|
+
const fromGet = typeof values.get === "function" ? values.get(key) : undefined;
|
|
22261
|
+
const value = fromGet ?? values[key] ?? values[key.toUpperCase()];
|
|
22262
|
+
if (typeof value === "string" && value.trim())
|
|
22263
|
+
return value.trim();
|
|
22264
|
+
}
|
|
22265
|
+
return;
|
|
22266
|
+
}
|
|
22267
|
+
function observedErrorBodyHint(error) {
|
|
22268
|
+
if (!error || typeof error !== "object")
|
|
22269
|
+
return;
|
|
22270
|
+
const message = error.message;
|
|
22271
|
+
const body = typeof message === "string" ? message : undefined;
|
|
22272
|
+
const match = body?.match(/(?:served by|upstream|backend)\s*[:=]?\s*([a-z0-9._-]+)/i);
|
|
22273
|
+
return match?.[1];
|
|
22274
|
+
}
|
|
22275
|
+
function observedErrorHint(error) {
|
|
22276
|
+
if (!error || typeof error !== "object")
|
|
22277
|
+
return;
|
|
22278
|
+
const candidate = error;
|
|
22279
|
+
const direct = candidate.served_by ?? candidate.servedBy ?? candidate.upstream ?? candidate.backend;
|
|
22280
|
+
if (typeof direct === "string" && direct.trim())
|
|
22281
|
+
return direct.trim();
|
|
22282
|
+
const headerHint = observedHeaderHint(candidate.headers);
|
|
22283
|
+
if (headerHint)
|
|
22284
|
+
return headerHint;
|
|
22285
|
+
const bodyHint = observedErrorBodyHint(error);
|
|
22286
|
+
if (bodyHint)
|
|
22287
|
+
return bodyHint;
|
|
22288
|
+
const response = candidate.response;
|
|
22289
|
+
if (response && typeof response === "object")
|
|
22290
|
+
return observedErrorHint(response);
|
|
22291
|
+
return;
|
|
22292
|
+
}
|
|
22293
|
+
function observedModelVendorHint(modelID) {
|
|
22294
|
+
if (!modelID)
|
|
22295
|
+
return;
|
|
22296
|
+
const slash = modelID.indexOf("/");
|
|
22297
|
+
return slash > 0 ? modelID.slice(0, slash) : undefined;
|
|
22298
|
+
}
|
|
22299
|
+
function readLargestSuccess(db, sessionId, providerID, modelID) {
|
|
22300
|
+
if (!sessionId || !providerID || !modelID)
|
|
22301
|
+
return;
|
|
22302
|
+
const meta = getOrCreateSessionMeta(db, sessionId);
|
|
22303
|
+
return piModelRefToCanonical(meta.lastObservedModelKey ?? "") === piModelRefToCanonical(`${providerID}/${modelID}`) ? positiveFiniteNumber(meta.observedSafeInputTokens) : undefined;
|
|
22304
|
+
}
|
|
22305
|
+
function buildWindowReport(input) {
|
|
22306
|
+
const report = {
|
|
22307
|
+
access_path: "api",
|
|
22308
|
+
geometry: input.reportedLimitProvenance ?? "unknown",
|
|
22309
|
+
observed_at_ms: input.observedAtMs ?? Date.now(),
|
|
22310
|
+
...input.providerID && FORWARDING_PROVIDER_IDS.has(input.providerID) ? { path_may_forward: true } : {}
|
|
22311
|
+
};
|
|
22312
|
+
if (input.providerID)
|
|
22313
|
+
report.provider_id = input.providerID;
|
|
22314
|
+
if (input.modelID)
|
|
22315
|
+
report.model_id = input.modelID;
|
|
22316
|
+
if (input.matchedPattern)
|
|
22317
|
+
report.matched_pattern = input.matchedPattern;
|
|
22318
|
+
const limit = positiveFiniteNumber(input.reportedLimit);
|
|
22319
|
+
if (limit) {
|
|
22320
|
+
report.extracted_limit = limit;
|
|
22321
|
+
report.extracted_limit_units = "provider";
|
|
22322
|
+
}
|
|
22323
|
+
const attempted = positiveFiniteNumber(input.attemptedTokens);
|
|
22324
|
+
if (attempted) {
|
|
22325
|
+
report.attempted_tokens = attempted;
|
|
22326
|
+
report.attempted_tokens_units = "estimate";
|
|
22327
|
+
}
|
|
22328
|
+
const status = observedStatus(input.error);
|
|
22329
|
+
if (status)
|
|
22330
|
+
report.status = status;
|
|
22331
|
+
const largestSuccess = readLargestSuccess(input.db, input.sessionID, input.providerID, input.modelID);
|
|
22332
|
+
if (largestSuccess) {
|
|
22333
|
+
report.largest_success = largestSuccess;
|
|
22334
|
+
report.largest_success_units = "estimate";
|
|
22335
|
+
}
|
|
22336
|
+
const servedByHint = observedErrorHint(input.error) ?? observedModelVendorHint(input.modelID);
|
|
22337
|
+
if (servedByHint)
|
|
22338
|
+
report.served_by_hint = servedByHint;
|
|
22339
|
+
return report;
|
|
22340
|
+
}
|
|
22341
|
+
function appendWindowReport(report) {
|
|
22342
|
+
try {
|
|
22343
|
+
const reportPath = getWindowReportsPath();
|
|
22344
|
+
fs.mkdirSync(path5.dirname(reportPath), { recursive: true });
|
|
22345
|
+
if (fs.existsSync(reportPath) && fs.statSync(reportPath).size > WINDOW_REPORTS_ROTATION_BYTES) {
|
|
22346
|
+
const rotatedPath = path5.join(path5.dirname(reportPath), ROTATED_WINDOW_REPORTS_FILE);
|
|
22347
|
+
fs.rmSync(rotatedPath, { force: true });
|
|
22348
|
+
fs.renameSync(reportPath, rotatedPath);
|
|
22349
|
+
}
|
|
22350
|
+
fs.appendFileSync(reportPath, `${JSON.stringify(report)}
|
|
22351
|
+
`);
|
|
22352
|
+
} catch (error) {
|
|
22353
|
+
recordSwallowedWrite(error);
|
|
22354
|
+
}
|
|
22355
|
+
}
|
|
22356
|
+
function captureWindowReport(input) {
|
|
22357
|
+
try {
|
|
22358
|
+
appendWindowReport(buildWindowReport(input));
|
|
22359
|
+
} catch (error) {
|
|
22360
|
+
recordSwallowedWrite(error);
|
|
22361
|
+
}
|
|
22362
|
+
}
|
|
22363
|
+
|
|
21977
22364
|
// src/hooks/magic-context/channel2-delivery.ts
|
|
21978
22365
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
21979
22366
|
|
|
@@ -22755,7 +23142,7 @@ function replayCavemanCompression(sessionId, db, targets, tags) {
|
|
|
22755
23142
|
}
|
|
22756
23143
|
|
|
22757
23144
|
// src/hooks/magic-context/compaction-off-transition.ts
|
|
22758
|
-
import { existsSync as
|
|
23145
|
+
import { existsSync as existsSync11 } from "node:fs";
|
|
22759
23146
|
var loggedUnverifiedMarkerCleanupRetry = false;
|
|
22760
23147
|
var COMPACTION_OFF_FLIP_NOTICE = [
|
|
22761
23148
|
"## Magic Context — compaction-off mode is now active",
|
|
@@ -22790,7 +23177,7 @@ function clearCachedM0Baseline(db, sessionId) {
|
|
|
22790
23177
|
return (result.changes ?? 0) > 0;
|
|
22791
23178
|
}
|
|
22792
23179
|
function cleanupOffMarkers(sessionId) {
|
|
22793
|
-
if (!
|
|
23180
|
+
if (!existsSync11(getOpenCodeDbPath())) {
|
|
22794
23181
|
return { verified: true, removedLineages: 0, removedRows: 0, retainedLineages: 0 };
|
|
22795
23182
|
}
|
|
22796
23183
|
return removeMcOwnedCompactionMarkers(sessionId, MARKER_SUMMARY_TEXT);
|
|
@@ -23433,6 +23820,14 @@ function assertOpenAiCompatAdjacency(messages) {
|
|
|
23433
23820
|
}
|
|
23434
23821
|
|
|
23435
23822
|
// src/hooks/magic-context/lkg-replay.ts
|
|
23823
|
+
function canonicalLkgModelKeys(modelKey, providerKey) {
|
|
23824
|
+
const canonicalModelKey = modelKey ? piModelRefToCanonical(modelKey) : null;
|
|
23825
|
+
const slash = canonicalModelKey?.indexOf("/") ?? -1;
|
|
23826
|
+
return {
|
|
23827
|
+
modelKey: canonicalModelKey,
|
|
23828
|
+
providerKey: slash > 0 && canonicalModelKey ? canonicalModelKey.slice(0, slash) : providerKey
|
|
23829
|
+
};
|
|
23830
|
+
}
|
|
23436
23831
|
function resolveLkgModelKeys(messages) {
|
|
23437
23832
|
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
23438
23833
|
const info = messages[index]?.info;
|
|
@@ -23441,13 +23836,13 @@ function resolveLkgModelKeys(messages) {
|
|
|
23441
23836
|
const provider2 = nested.providerID;
|
|
23442
23837
|
const model2 = nested.modelID;
|
|
23443
23838
|
if (typeof provider2 === "string" && typeof model2 === "string") {
|
|
23444
|
-
return
|
|
23839
|
+
return canonicalLkgModelKeys(`${provider2}/${model2}`, provider2);
|
|
23445
23840
|
}
|
|
23446
23841
|
}
|
|
23447
23842
|
const provider = info?.providerID;
|
|
23448
23843
|
const model = info?.modelID;
|
|
23449
23844
|
if (info?.role === "assistant" && typeof provider === "string" && typeof model === "string") {
|
|
23450
|
-
return
|
|
23845
|
+
return canonicalLkgModelKeys(`${provider}/${model}`, provider);
|
|
23451
23846
|
}
|
|
23452
23847
|
}
|
|
23453
23848
|
return { modelKey: null, providerKey: null };
|
|
@@ -23643,13 +24038,14 @@ function captureLkgSlot(args) {
|
|
|
23643
24038
|
const built = buildLkgPrefix(args.input, args.output);
|
|
23644
24039
|
if (!built)
|
|
23645
24040
|
return false;
|
|
24041
|
+
const modelKeys = canonicalLkgModelKeys(args.modelKey, args.providerKey);
|
|
23646
24042
|
return captureSlot(args.sessionId, {
|
|
23647
24043
|
jsonPrefix: built.jsonPrefix,
|
|
23648
24044
|
inputIdSeq: built.inputIdSeq,
|
|
23649
24045
|
inputContentDigests: built.inputContentDigests,
|
|
23650
24046
|
lastInputMessageId: built.anchorMessageId,
|
|
23651
|
-
modelKey:
|
|
23652
|
-
providerKey:
|
|
24047
|
+
modelKey: modelKeys.modelKey,
|
|
24048
|
+
providerKey: modelKeys.providerKey,
|
|
23653
24049
|
capturedAt: args.capturedAt ?? Date.now()
|
|
23654
24050
|
});
|
|
23655
24051
|
}
|
|
@@ -23830,7 +24226,9 @@ function replayLkg(args) {
|
|
|
23830
24226
|
const slot = getSlot(args.sessionId);
|
|
23831
24227
|
if (!slot)
|
|
23832
24228
|
return { ok: false, reason: "lkg_invalidated_reshape" };
|
|
23833
|
-
|
|
24229
|
+
const requestedModelKeys = canonicalLkgModelKeys(args.modelKey, args.providerKey);
|
|
24230
|
+
const capturedModelKeys = canonicalLkgModelKeys(slot.modelKey, slot.providerKey);
|
|
24231
|
+
if (capturedModelKeys.modelKey !== requestedModelKeys.modelKey || capturedModelKeys.providerKey !== requestedModelKeys.providerKey) {
|
|
23834
24232
|
dropSlot(args.sessionId, "lkg_model_mismatch");
|
|
23835
24233
|
return { ok: false, reason: "lkg_model_mismatch" };
|
|
23836
24234
|
}
|
|
@@ -23858,13 +24256,13 @@ function replayLkg(args) {
|
|
|
23858
24256
|
dropSlot(args.sessionId, "lkg_unsafe_seam");
|
|
23859
24257
|
return { ok: false, reason: "lkg_unsafe_seam" };
|
|
23860
24258
|
}
|
|
23861
|
-
if (!validateLkgSeam(prefix, entry.pristineTail,
|
|
24259
|
+
if (!validateLkgSeam(prefix, entry.pristineTail, requestedModelKeys.providerKey)) {
|
|
23862
24260
|
dropSlot(args.sessionId, "lkg_seam_invalid");
|
|
23863
24261
|
return { ok: false, reason: "lkg_seam_invalid" };
|
|
23864
24262
|
}
|
|
23865
24263
|
}
|
|
23866
24264
|
const replayed = [...prefix, ...entry.pristineTail];
|
|
23867
|
-
if (
|
|
24265
|
+
if (requestedModelKeys.providerKey === "anthropic" && !validateAnthropicReasoningRuns(replayed)) {
|
|
23868
24266
|
dropSlot(args.sessionId, "lkg_anthropic_reasoning_run_invalid");
|
|
23869
24267
|
return { ok: false, reason: "lkg_anthropic_reasoning_run_invalid" };
|
|
23870
24268
|
}
|
|
@@ -24076,8 +24474,9 @@ function moduleWireBodyBytes(payload) {
|
|
|
24076
24474
|
return Buffer.byteLength(JSON.stringify(toFlatModuleWireBody(payload)));
|
|
24077
24475
|
}
|
|
24078
24476
|
function buildPagedModuleTransformPayloads(body) {
|
|
24079
|
-
|
|
24080
|
-
|
|
24477
|
+
const unpagedBytes = Buffer.byteLength(JSON.stringify(body));
|
|
24478
|
+
if (unpagedBytes <= MODULE_PAGE_MAX_BYTES)
|
|
24479
|
+
return [{ page: body, bytes: unpagedBytes }];
|
|
24081
24480
|
const arrayFields = [
|
|
24082
24481
|
"input",
|
|
24083
24482
|
"messages",
|
|
@@ -24111,7 +24510,7 @@ function buildPagedModuleTransformPayloads(body) {
|
|
|
24111
24510
|
};
|
|
24112
24511
|
if (args.complete)
|
|
24113
24512
|
Object.assign(page, scalarFields);
|
|
24114
|
-
return page;
|
|
24513
|
+
return { page, bytes: Buffer.byteLength(JSON.stringify(page)) };
|
|
24115
24514
|
};
|
|
24116
24515
|
const hasItems = (arrays) => Object.values(arrays).some((values) => values.length > 0);
|
|
24117
24516
|
const serializedItemBytes = (value) => Buffer.byteLength(JSON.stringify(value) ?? "null");
|
|
@@ -24213,12 +24612,7 @@ function buildPagedModuleTransformPayloads(body) {
|
|
|
24213
24612
|
complete: true,
|
|
24214
24613
|
arrays: current
|
|
24215
24614
|
});
|
|
24216
|
-
if (
|
|
24217
|
-
index: pages.length,
|
|
24218
|
-
total: assumedTotal,
|
|
24219
|
-
complete: true,
|
|
24220
|
-
arrayBytes: currentBytes
|
|
24221
|
-
}) > MODULE_PAGE_MAX_BYTES) {
|
|
24615
|
+
if (finalPage.bytes > MODULE_PAGE_MAX_BYTES) {
|
|
24222
24616
|
if (!hasItems(current)) {
|
|
24223
24617
|
throw new Error("module transform scalar tail exceeds the 512 KiB page limit");
|
|
24224
24618
|
}
|
|
@@ -24236,12 +24630,7 @@ function buildPagedModuleTransformPayloads(body) {
|
|
|
24236
24630
|
complete: true,
|
|
24237
24631
|
arrays: current
|
|
24238
24632
|
});
|
|
24239
|
-
if (
|
|
24240
|
-
index: pages.length,
|
|
24241
|
-
total: assumedTotal,
|
|
24242
|
-
complete: true,
|
|
24243
|
-
arrayBytes: currentBytes
|
|
24244
|
-
}) > MODULE_PAGE_MAX_BYTES) {
|
|
24633
|
+
if (finalPage.bytes > MODULE_PAGE_MAX_BYTES) {
|
|
24245
24634
|
throw new Error("module transform scalar tail exceeds the 512 KiB page limit");
|
|
24246
24635
|
}
|
|
24247
24636
|
}
|
|
@@ -24272,7 +24661,7 @@ function moduleRawBlockMappings(message) {
|
|
|
24272
24661
|
blockIndex += 1;
|
|
24273
24662
|
continue;
|
|
24274
24663
|
}
|
|
24275
|
-
if (
|
|
24664
|
+
if (["reasoning", "thinking", "redacted_thinking"].includes(type)) {
|
|
24276
24665
|
mappings.push({ blockIndex, partIndex, kind: "reasoning" });
|
|
24277
24666
|
blockIndex += 1;
|
|
24278
24667
|
continue;
|
|
@@ -24332,12 +24721,31 @@ function encodeOpenCodeMessagesToCk(messages) {
|
|
|
24332
24721
|
content.push({
|
|
24333
24722
|
kind: { type: "text", text: typeof part.text === "string" ? part.text : "" }
|
|
24334
24723
|
});
|
|
24335
|
-
} else if (type === "reasoning") {
|
|
24724
|
+
} else if (type === "reasoning" || type === "thinking") {
|
|
24725
|
+
const signature = typeof part.signature === "string" ? part.signature : undefined;
|
|
24336
24726
|
content.push({
|
|
24337
24727
|
kind: {
|
|
24338
24728
|
type: "reasoning",
|
|
24339
|
-
text: typeof part.text === "string" ? part.text : typeof part.thinking === "string" ? part.thinking : ""
|
|
24340
|
-
|
|
24729
|
+
text: typeof part.text === "string" ? part.text : typeof part.thinking === "string" ? part.thinking : "",
|
|
24730
|
+
...signature ? { signature } : {}
|
|
24731
|
+
},
|
|
24732
|
+
...part.cache_control !== undefined ? {
|
|
24733
|
+
provider_extras: {
|
|
24734
|
+
opencode: { cache_control: part.cache_control }
|
|
24735
|
+
}
|
|
24736
|
+
} : {}
|
|
24737
|
+
});
|
|
24738
|
+
} else if (type === "redacted_thinking") {
|
|
24739
|
+
content.push({
|
|
24740
|
+
kind: {
|
|
24741
|
+
type: "redacted_reasoning",
|
|
24742
|
+
data: typeof part.data === "string" ? part.data : typeof part.redacted === "string" ? part.redacted : ""
|
|
24743
|
+
},
|
|
24744
|
+
...part.cache_control !== undefined ? {
|
|
24745
|
+
provider_extras: {
|
|
24746
|
+
opencode: { cache_control: part.cache_control }
|
|
24747
|
+
}
|
|
24748
|
+
} : {}
|
|
24341
24749
|
});
|
|
24342
24750
|
} else if (type === "tool") {
|
|
24343
24751
|
const state = part.state !== null && typeof part.state === "object" ? part.state : {};
|
|
@@ -24393,21 +24801,54 @@ function encodeOpenCodeMessagesToCk(messages) {
|
|
|
24393
24801
|
}
|
|
24394
24802
|
|
|
24395
24803
|
// src/hooks/magic-context/module-state-sync.ts
|
|
24396
|
-
|
|
24804
|
+
var compartmentMirrorCursors = new Map;
|
|
24805
|
+
function clearCompartmentMirrorCursor(sessionId) {
|
|
24806
|
+
compartmentMirrorCursors.delete(sessionId);
|
|
24807
|
+
}
|
|
24808
|
+
function validateMirrorRow(compartment, afterSequence, maxSequence) {
|
|
24809
|
+
if (!Number.isSafeInteger(compartment.sequence) || compartment.sequence <= afterSequence || compartment.sequence > maxSequence || !Number.isSafeInteger(compartment.start_message) || !Number.isSafeInteger(compartment.end_message) || typeof compartment.start_message_id !== "string" || typeof compartment.end_message_id !== "string" || typeof compartment.title !== "string" || typeof compartment.content !== "string") {
|
|
24810
|
+
throw new Error("module compartment mirror returned an invalid authoritative row");
|
|
24811
|
+
}
|
|
24812
|
+
}
|
|
24813
|
+
function validateMirrorPage(published, maxSequence) {
|
|
24814
|
+
if (!Number.isSafeInteger(published.max_sequence) || published.max_sequence < -1 || maxSequence !== null && published.max_sequence !== maxSequence) {
|
|
24815
|
+
throw new Error("module compartment mirror changed while its authoritative set was read");
|
|
24816
|
+
}
|
|
24817
|
+
}
|
|
24818
|
+
function compartmentMirrorSetChanged(published, cursor) {
|
|
24819
|
+
if (published.set_changed === true)
|
|
24820
|
+
return true;
|
|
24821
|
+
if (published.revert_epoch !== undefined && cursor.lastRevertEpoch !== undefined && published.revert_epoch !== cursor.lastRevertEpoch) {
|
|
24822
|
+
return true;
|
|
24823
|
+
}
|
|
24824
|
+
if (published.compartment_count === 0 && cursor.lastMaxSequence >= 0 && published.compartments.length === 0) {
|
|
24825
|
+
return true;
|
|
24826
|
+
}
|
|
24827
|
+
if (published.compartment_count !== undefined && published.compartments.length === 0 && published.max_sequence === cursor.lastMaxSequence && published.compartment_count !== (cursor.lastCompartmentCount ?? cursor.lastMaxSequence)) {
|
|
24828
|
+
return true;
|
|
24829
|
+
}
|
|
24830
|
+
return false;
|
|
24831
|
+
}
|
|
24832
|
+
function rememberCompartmentMirrorCursor(sessionId, maxSequence, published, authoritativeCount) {
|
|
24833
|
+
compartmentMirrorCursors.set(sessionId, {
|
|
24834
|
+
lastMaxSequence: maxSequence,
|
|
24835
|
+
lastCompartmentCount: published.compartment_count ?? authoritativeCount,
|
|
24836
|
+
lastRevertEpoch: published.revert_epoch
|
|
24837
|
+
});
|
|
24838
|
+
}
|
|
24839
|
+
async function resyncModuleCompartmentsFromAuthoritative(args) {
|
|
24397
24840
|
const authoritative = [];
|
|
24398
24841
|
let afterSequence = -1;
|
|
24399
24842
|
let maxSequence = null;
|
|
24843
|
+
let lastPublished;
|
|
24400
24844
|
for (;; ) {
|
|
24401
24845
|
const published = await args.reader.getCompartmentsAfter(args.sessionId, afterSequence);
|
|
24402
|
-
|
|
24403
|
-
throw new Error("module compartment mirror changed while its authoritative set was read");
|
|
24404
|
-
}
|
|
24846
|
+
validateMirrorPage(published, maxSequence);
|
|
24405
24847
|
maxSequence ??= published.max_sequence;
|
|
24848
|
+
lastPublished = published;
|
|
24406
24849
|
let pageAdvanced = false;
|
|
24407
24850
|
for (const compartment of published.compartments) {
|
|
24408
|
-
|
|
24409
|
-
throw new Error("module compartment mirror returned an invalid authoritative row");
|
|
24410
|
-
}
|
|
24851
|
+
validateMirrorRow(compartment, afterSequence, maxSequence);
|
|
24411
24852
|
authoritative.push(compartment);
|
|
24412
24853
|
afterSequence = compartment.sequence;
|
|
24413
24854
|
pageAdvanced = true;
|
|
@@ -24446,17 +24887,36 @@ async function mirrorModuleCompartments(args) {
|
|
|
24446
24887
|
legacy = excluded.legacy,
|
|
24447
24888
|
created_at = excluded.created_at,
|
|
24448
24889
|
harness = excluded.harness`);
|
|
24449
|
-
const
|
|
24890
|
+
const now2 = Date.now();
|
|
24450
24891
|
args.db.transaction(() => {
|
|
24451
24892
|
if (divergentSequence !== undefined) {
|
|
24452
24893
|
args.db.prepare("DELETE FROM compartments WHERE session_id = ? AND sequence >= ?").run(args.sessionId, divergentSequence);
|
|
24453
24894
|
}
|
|
24454
24895
|
for (const compartment of authoritative) {
|
|
24455
|
-
upsert.run(args.sessionId, compartment.sequence, compartment.start_message, compartment.end_message, compartment.start_message_id, compartment.end_message_id, compartment.title, compartment.content, compartment.p1 ?? null, compartment.p2 ?? null, compartment.p3 ?? null, compartment.p4 ?? null, compartment.importance ?? 50, compartment.episode_type ?? null, compartment.legacy ?? (compartment.p1 ? 0 : 1), compartment.created_at ??
|
|
24896
|
+
upsert.run(args.sessionId, compartment.sequence, compartment.start_message, compartment.end_message, compartment.start_message_id, compartment.end_message_id, compartment.title, compartment.content, compartment.p1 ?? null, compartment.p2 ?? null, compartment.p3 ?? null, compartment.p4 ?? null, compartment.importance ?? 50, compartment.episode_type ?? null, compartment.legacy ?? (compartment.p1 ? 0 : 1), compartment.created_at ?? now2, getHarness());
|
|
24456
24897
|
}
|
|
24457
24898
|
})();
|
|
24899
|
+
rememberCompartmentMirrorCursor(args.sessionId, maxSequence, lastPublished ?? { max_sequence: maxSequence, compartments: [] }, authoritative.length);
|
|
24458
24900
|
return maxSequence;
|
|
24459
24901
|
}
|
|
24902
|
+
async function mirrorModuleCompartments(args) {
|
|
24903
|
+
const cursor = compartmentMirrorCursors.get(args.sessionId);
|
|
24904
|
+
if (cursor !== undefined) {
|
|
24905
|
+
const published = await args.reader.getCompartmentsAfter(args.sessionId, cursor.lastMaxSequence);
|
|
24906
|
+
validateMirrorPage(published, null);
|
|
24907
|
+
for (const compartment of published.compartments) {
|
|
24908
|
+
validateMirrorRow(compartment, cursor.lastMaxSequence, published.max_sequence);
|
|
24909
|
+
}
|
|
24910
|
+
const firstNew = published.compartments[0];
|
|
24911
|
+
const hasGap = firstNew !== undefined && firstNew.sequence !== cursor.lastMaxSequence + 1;
|
|
24912
|
+
const regressed = published.max_sequence < cursor.lastMaxSequence;
|
|
24913
|
+
const setChanged = compartmentMirrorSetChanged(published, cursor);
|
|
24914
|
+
if (!regressed && !hasGap && !setChanged && published.compartments.length === 0 && published.max_sequence === cursor.lastMaxSequence) {
|
|
24915
|
+
return published.max_sequence;
|
|
24916
|
+
}
|
|
24917
|
+
}
|
|
24918
|
+
return resyncModuleCompartmentsFromAuthoritative(args);
|
|
24919
|
+
}
|
|
24460
24920
|
function stableHash(value) {
|
|
24461
24921
|
return createHmac("sha256", "magic-context-shadow-watermark").update(value).digest("hex");
|
|
24462
24922
|
}
|
|
@@ -27784,10 +28244,8 @@ var REASONING_IGNORED_PART_TYPES = new Set([
|
|
|
27784
28244
|
"compaction"
|
|
27785
28245
|
]);
|
|
27786
28246
|
var REASONING_PART_TYPES = new Set(["reasoning", "thinking", "redacted_thinking"]);
|
|
27787
|
-
function
|
|
27788
|
-
|
|
27789
|
-
return 0;
|
|
27790
|
-
let stripped = 0;
|
|
28247
|
+
function planMergedAssistantReasoningStrip(messages, mutationExemptMessage) {
|
|
28248
|
+
const plan = [];
|
|
27791
28249
|
let prevRole;
|
|
27792
28250
|
let keptReasoningInRun = false;
|
|
27793
28251
|
for (const message of messages) {
|
|
@@ -27800,7 +28258,7 @@ function stripReasoningFromMergedAssistants(messages, providerID, options) {
|
|
|
27800
28258
|
const firstInRun = prevRole !== "assistant";
|
|
27801
28259
|
if (firstInRun)
|
|
27802
28260
|
keptReasoningInRun = false;
|
|
27803
|
-
if (message ===
|
|
28261
|
+
if (message === mutationExemptMessage) {
|
|
27804
28262
|
prevRole = role;
|
|
27805
28263
|
continue;
|
|
27806
28264
|
}
|
|
@@ -27817,27 +28275,135 @@ function stripReasoningFromMergedAssistants(messages, providerID, options) {
|
|
|
27817
28275
|
continue;
|
|
27818
28276
|
if (isSentinel(part))
|
|
27819
28277
|
continue;
|
|
28278
|
+
if (partType === "text" && typeof part.text === "string" && part.text.trim() === "") {
|
|
28279
|
+
continue;
|
|
28280
|
+
}
|
|
27820
28281
|
if (REASONING_PART_TYPES.has(partType)) {
|
|
27821
28282
|
keepIndex = i;
|
|
27822
28283
|
}
|
|
27823
28284
|
break;
|
|
27824
28285
|
}
|
|
27825
28286
|
}
|
|
28287
|
+
const stripIndices = [];
|
|
27826
28288
|
for (let i = 0;i < message.parts.length; i++) {
|
|
27827
28289
|
const part = message.parts[i];
|
|
27828
28290
|
if (!isRecord(part))
|
|
27829
28291
|
continue;
|
|
27830
28292
|
if (!REASONING_PART_TYPES.has(part.type))
|
|
27831
28293
|
continue;
|
|
28294
|
+
if (part.cache_control !== undefined)
|
|
28295
|
+
continue;
|
|
27832
28296
|
if (i === keepIndex) {
|
|
27833
28297
|
keptReasoningInRun = true;
|
|
27834
28298
|
continue;
|
|
27835
28299
|
}
|
|
27836
|
-
|
|
27837
|
-
stripped++;
|
|
28300
|
+
stripIndices.push(i);
|
|
27838
28301
|
}
|
|
28302
|
+
if (stripIndices.length > 0)
|
|
28303
|
+
plan.push({ message, stripIndices });
|
|
27839
28304
|
prevRole = role;
|
|
27840
28305
|
}
|
|
28306
|
+
return plan;
|
|
28307
|
+
}
|
|
28308
|
+
var CANONICAL_BLANK_PART = { type: "text", text: "" };
|
|
28309
|
+
function isSentinelInvisibleTextPart(part) {
|
|
28310
|
+
return isRecord(part) && part.type === "text" && typeof part.text === "string" && part.text.trim() === "";
|
|
28311
|
+
}
|
|
28312
|
+
function isCanonicalBlankPart(part) {
|
|
28313
|
+
return isRecord(part) && Object.keys(part).length === 2 && part.type === "text" && part.text === "";
|
|
28314
|
+
}
|
|
28315
|
+
function findTrailingBlankDecisionCandidates(messages, frozenDecisions) {
|
|
28316
|
+
const decisions = [];
|
|
28317
|
+
for (const message of messages) {
|
|
28318
|
+
const id = message.info.id;
|
|
28319
|
+
if (message.info.role !== "assistant" || typeof id !== "string" || id.length === 0 || frozenDecisions.has(id)) {
|
|
28320
|
+
continue;
|
|
28321
|
+
}
|
|
28322
|
+
const last = message.parts.at(-1);
|
|
28323
|
+
decisions.push([
|
|
28324
|
+
id,
|
|
28325
|
+
message.parts.length === 0 || isSentinelInvisibleTextPart(last) ? "keep" : "strip"
|
|
28326
|
+
]);
|
|
28327
|
+
}
|
|
28328
|
+
return decisions;
|
|
28329
|
+
}
|
|
28330
|
+
function applyFrozenTrailingBlankDecisions(messages, newestAssistantId, frozenDecisions) {
|
|
28331
|
+
let mutations = 0;
|
|
28332
|
+
for (let messageIndex = 0;messageIndex < messages.length; messageIndex += 1) {
|
|
28333
|
+
let message = messages[messageIndex];
|
|
28334
|
+
const id = message.info.id;
|
|
28335
|
+
if (message.info.role !== "assistant" || typeof id !== "string")
|
|
28336
|
+
continue;
|
|
28337
|
+
const decision = frozenDecisions.get(id);
|
|
28338
|
+
if (!decision)
|
|
28339
|
+
continue;
|
|
28340
|
+
let lastMeaningfulIndex = message.parts.length - 1;
|
|
28341
|
+
while (lastMeaningfulIndex >= 0 && isSentinelInvisibleTextPart(message.parts[lastMeaningfulIndex])) {
|
|
28342
|
+
lastMeaningfulIndex -= 1;
|
|
28343
|
+
}
|
|
28344
|
+
const replaceParts = (start, deleteCount, insertBlank) => {
|
|
28345
|
+
message = { ...message, parts: [...message.parts] };
|
|
28346
|
+
messages[messageIndex] = message;
|
|
28347
|
+
message.parts.splice(start, deleteCount, ...insertBlank ? [{ ...CANONICAL_BLANK_PART }] : []);
|
|
28348
|
+
};
|
|
28349
|
+
if (lastMeaningfulIndex < 0) {
|
|
28350
|
+
if (message.parts.length !== 1 || !isCanonicalBlankPart(message.parts[0])) {
|
|
28351
|
+
mutations += Math.max(1, message.parts.length);
|
|
28352
|
+
replaceParts(0, message.parts.length, true);
|
|
28353
|
+
}
|
|
28354
|
+
continue;
|
|
28355
|
+
}
|
|
28356
|
+
const trailingCount = message.parts.length - lastMeaningfulIndex - 1;
|
|
28357
|
+
if (decision === "keep") {
|
|
28358
|
+
const blankIndex = lastMeaningfulIndex + 1;
|
|
28359
|
+
if (trailingCount !== 1 || !isCanonicalBlankPart(message.parts[blankIndex])) {
|
|
28360
|
+
mutations += Math.max(1, trailingCount);
|
|
28361
|
+
replaceParts(blankIndex, trailingCount, true);
|
|
28362
|
+
}
|
|
28363
|
+
continue;
|
|
28364
|
+
}
|
|
28365
|
+
if (id === newestAssistantId || trailingCount === 0)
|
|
28366
|
+
continue;
|
|
28367
|
+
const lastMeaningfulPart = message.parts[lastMeaningfulIndex];
|
|
28368
|
+
if (isRecord(lastMeaningfulPart) && REASONING_PART_TYPES.has(lastMeaningfulPart.type)) {
|
|
28369
|
+
const blankIndex = lastMeaningfulIndex + 1;
|
|
28370
|
+
if (trailingCount !== 1 || !isCanonicalBlankPart(message.parts[blankIndex])) {
|
|
28371
|
+
mutations += Math.max(1, trailingCount);
|
|
28372
|
+
replaceParts(blankIndex, trailingCount, true);
|
|
28373
|
+
}
|
|
28374
|
+
continue;
|
|
28375
|
+
}
|
|
28376
|
+
mutations += trailingCount;
|
|
28377
|
+
replaceParts(lastMeaningfulIndex + 1, trailingCount, false);
|
|
28378
|
+
}
|
|
28379
|
+
return mutations;
|
|
28380
|
+
}
|
|
28381
|
+
function findMergedReasoningStripCandidateIds(messages, providerID, options) {
|
|
28382
|
+
if (providerID !== "anthropic")
|
|
28383
|
+
return [];
|
|
28384
|
+
const ids = new Set;
|
|
28385
|
+
for (const entry of planMergedAssistantReasoningStrip(messages, options?.mutationExemptMessage)) {
|
|
28386
|
+
const id = entry.message.info.id;
|
|
28387
|
+
if (typeof id === "string" && id.length > 0)
|
|
28388
|
+
ids.add(id);
|
|
28389
|
+
}
|
|
28390
|
+
return [...ids];
|
|
28391
|
+
}
|
|
28392
|
+
function stripReasoningFromMergedAssistants(messages, providerID, options) {
|
|
28393
|
+
if (providerID !== "anthropic")
|
|
28394
|
+
return 0;
|
|
28395
|
+
let stripped = 0;
|
|
28396
|
+
for (const entry of planMergedAssistantReasoningStrip(messages, options?.mutationExemptMessage)) {
|
|
28397
|
+
if (options?.frozenMessageIds) {
|
|
28398
|
+
const id = entry.message.info.id;
|
|
28399
|
+
if (typeof id !== "string" || !options.frozenMessageIds.has(id))
|
|
28400
|
+
continue;
|
|
28401
|
+
}
|
|
28402
|
+
for (const index of entry.stripIndices) {
|
|
28403
|
+
entry.message.parts[index] = makeSentinel(entry.message.parts[index]);
|
|
28404
|
+
stripped++;
|
|
28405
|
+
}
|
|
28406
|
+
}
|
|
27841
28407
|
return stripped;
|
|
27842
28408
|
}
|
|
27843
28409
|
function stripProcessedImages(messages, frozenIds, options) {
|
|
@@ -28629,8 +29195,6 @@ function resetDegradedCacheCount(sessionId) {
|
|
|
28629
29195
|
degradedCacheCountBySession.delete(sessionId);
|
|
28630
29196
|
}
|
|
28631
29197
|
function isSyntheticHeadMessage(message) {
|
|
28632
|
-
if (message.info.syntheticHead !== true)
|
|
28633
|
-
return false;
|
|
28634
29198
|
if (message.info.id !== undefined)
|
|
28635
29199
|
return false;
|
|
28636
29200
|
if (message.info.role !== "user")
|
|
@@ -28747,11 +29311,17 @@ async function applyTodoSynthesis(args) {
|
|
|
28747
29311
|
return 0;
|
|
28748
29312
|
}
|
|
28749
29313
|
function runRustModePostprocess(args) {
|
|
28750
|
-
if (!args.fullFeatureMode)
|
|
29314
|
+
if (!args.fullFeatureMode || args.compactionOff)
|
|
28751
29315
|
return;
|
|
28752
29316
|
if (args.messages.some((message) => !message || typeof message !== "object" || !isRecord(message.info))) {
|
|
28753
29317
|
return;
|
|
28754
29318
|
}
|
|
29319
|
+
reconcileMarkerRepresentation(args.messages, getPersistedCompactionMarkerState(args.db, args.sessionId), {
|
|
29320
|
+
db: args.db,
|
|
29321
|
+
sessionId: args.sessionId,
|
|
29322
|
+
tagger: args.tagger,
|
|
29323
|
+
ctxReduceAvailability: args.ctxReduceAvailability
|
|
29324
|
+
});
|
|
28755
29325
|
for (const anchor of getNoteNudgeAnchors(args.db, args.sessionId)) {
|
|
28756
29326
|
appendReminderToUserMessageById(args.messages, anchor.messageId, anchor.text);
|
|
28757
29327
|
}
|
|
@@ -28898,9 +29468,23 @@ function finalizeMessageRepresentation(messages, resolvedProviderID, options) {
|
|
|
28898
29468
|
clearedParts = stripClearedReasoning(targetedMessages);
|
|
28899
29469
|
}
|
|
28900
29470
|
}
|
|
28901
|
-
|
|
28902
|
-
|
|
29471
|
+
let newestAssistant = options?.reasoningMutationExemptMessage;
|
|
29472
|
+
if (!newestAssistant) {
|
|
29473
|
+
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
29474
|
+
const message = messages[index];
|
|
29475
|
+
if (message.info.role !== "assistant")
|
|
29476
|
+
continue;
|
|
29477
|
+
newestAssistant = message;
|
|
29478
|
+
break;
|
|
29479
|
+
}
|
|
29480
|
+
}
|
|
29481
|
+
const mergedReasoningParts = options?.skipMergedReasoningStrip ? 0 : stripReasoningFromMergedAssistants(messages, resolvedProviderID, {
|
|
29482
|
+
mutationExemptMessage: options?.reasoningMutationExemptMessage,
|
|
29483
|
+
frozenMessageIds: options?.mergedReasoningStrippedIds
|
|
28903
29484
|
});
|
|
29485
|
+
if (!options?.skipTrailingWhitespaceStrip && modelAcceptsEmptyContent(resolvedProviderID)) {
|
|
29486
|
+
applyFrozenTrailingBlankDecisions(messages, typeof newestAssistant?.info.id === "string" ? newestAssistant.info.id : undefined, options?.trailingBlankDecisions ?? new Map);
|
|
29487
|
+
}
|
|
28904
29488
|
return { clearedParts, mergedReasoningParts };
|
|
28905
29489
|
}
|
|
28906
29490
|
async function runPostTransformPhase(args) {
|
|
@@ -29444,7 +30028,7 @@ async function runPostTransformPhase(args) {
|
|
|
29444
30028
|
}
|
|
29445
30029
|
const materializeReason = m0MaterializeReason ?? (explicitMaterializedSuccessfully ? "explicit_flush" : null);
|
|
29446
30030
|
const materialized = m0RematerializedThisPass || explicitMaterializedSuccessfully || deferredMaterializedSuccessfully;
|
|
29447
|
-
|
|
30031
|
+
let bustedThisPass = args.didMutateFromFlushedStatuses || pendingOpsDidMutate || heuristicOrReasoningDidMutate || autoReclaimDidMutateThisPass || m0RematerializedThisPass || m0M1InjectedThisPass && historyWasConsumedThisPass || historyWasConsumedThisPass;
|
|
29448
30032
|
if (reasoningMutationTargetUnknown) {
|
|
29449
30033
|
const reasoningCandidates = args.reasoningByMessage.size > 0 ? args.reasoningByMessage.keys() : args.messages;
|
|
29450
30034
|
for (const message of reasoningCandidates) {
|
|
@@ -29460,12 +30044,80 @@ async function runPostTransformPhase(args) {
|
|
|
29460
30044
|
reasoningMutatedMessages.add(message);
|
|
29461
30045
|
}
|
|
29462
30046
|
}
|
|
30047
|
+
const mergedReasoningStrippedIds = new Set;
|
|
30048
|
+
if (canUseEmptySentinels && !compactionOff) {
|
|
30049
|
+
try {
|
|
30050
|
+
for (const id of getMergedReasoningStrippedIds(args.db, args.sessionId)) {
|
|
30051
|
+
mergedReasoningStrippedIds.add(id);
|
|
30052
|
+
}
|
|
30053
|
+
if (isCacheBustingPass) {
|
|
30054
|
+
const candidates = findMergedReasoningStripCandidateIds(args.messages, args.resolvedProviderID, { mutationExemptMessage: reasoningMutationExemptMessage });
|
|
30055
|
+
const newlyDetectedIds = candidates.filter((id) => !mergedReasoningStrippedIds.has(id));
|
|
30056
|
+
if (newlyDetectedIds.length > 0) {
|
|
30057
|
+
const persisted = addMergedReasoningStrippedIds(args.db, args.sessionId, newlyDetectedIds);
|
|
30058
|
+
if (persisted) {
|
|
30059
|
+
for (const id of newlyDetectedIds)
|
|
30060
|
+
mergedReasoningStrippedIds.add(id);
|
|
30061
|
+
bustedThisPass = true;
|
|
30062
|
+
} else {
|
|
30063
|
+
args.passOutcome?.record("merged-reasoning-strip-persistence-failure");
|
|
30064
|
+
sessionLog(args.sessionId, "merged reasoning strip: persistence failed; leaving newly detected assistants intact");
|
|
30065
|
+
}
|
|
30066
|
+
}
|
|
30067
|
+
}
|
|
30068
|
+
} catch (error) {
|
|
30069
|
+
args.passOutcome?.record("merged-reasoning-strip-exception");
|
|
30070
|
+
sessionLog(args.sessionId, "transform failed freezing merged reasoning strip:", error);
|
|
30071
|
+
}
|
|
30072
|
+
}
|
|
30073
|
+
const trailingBlankDecisions = new Map;
|
|
30074
|
+
if (canUseEmptySentinels && !compactionOff) {
|
|
30075
|
+
try {
|
|
30076
|
+
for (const [id, decision] of getTrailingBlankDecisions(args.db, args.sessionId)) {
|
|
30077
|
+
trailingBlankDecisions.set(id, decision);
|
|
30078
|
+
}
|
|
30079
|
+
} catch (error) {
|
|
30080
|
+
args.passOutcome?.record("trailing-blank-decision-load-exception");
|
|
30081
|
+
sessionLog(args.sessionId, "transform failed loading trailing blank decisions:", error);
|
|
30082
|
+
}
|
|
30083
|
+
}
|
|
29463
30084
|
const tFinalRepresentation = performance.now();
|
|
29464
30085
|
const finalRepresentation = finalizeMessageRepresentation(args.messages, args.resolvedProviderID, {
|
|
29465
30086
|
prependedMessageCount,
|
|
29466
30087
|
reasoningMutatedMessages,
|
|
29467
|
-
reasoningMutationExemptMessage
|
|
30088
|
+
reasoningMutationExemptMessage,
|
|
30089
|
+
mergedReasoningStrippedIds,
|
|
30090
|
+
trailingBlankDecisions,
|
|
30091
|
+
skipMergedReasoningStrip: compactionOff,
|
|
30092
|
+
skipTrailingWhitespaceStrip: compactionOff
|
|
29468
30093
|
});
|
|
30094
|
+
if (canUseEmptySentinels && !compactionOff && isCacheBustingPass) {
|
|
30095
|
+
const candidates = findTrailingBlankDecisionCandidates(args.messages, trailingBlankDecisions);
|
|
30096
|
+
if (candidates.length > 0) {
|
|
30097
|
+
try {
|
|
30098
|
+
const persisted = addTrailingBlankDecisions(args.db, args.sessionId, candidates);
|
|
30099
|
+
if (persisted) {
|
|
30100
|
+
const committed = getTrailingBlankDecisions(args.db, args.sessionId);
|
|
30101
|
+
const newlyFrozen = new Map;
|
|
30102
|
+
for (const [id] of candidates) {
|
|
30103
|
+
const decision = committed.get(id);
|
|
30104
|
+
if (!decision)
|
|
30105
|
+
continue;
|
|
30106
|
+
trailingBlankDecisions.set(id, decision);
|
|
30107
|
+
newlyFrozen.set(id, decision);
|
|
30108
|
+
}
|
|
30109
|
+
applyFrozenTrailingBlankDecisions(args.messages, typeof reasoningMutationExemptMessage?.info.id === "string" ? reasoningMutationExemptMessage.info.id : undefined, newlyFrozen);
|
|
30110
|
+
bustedThisPass = true;
|
|
30111
|
+
} else {
|
|
30112
|
+
args.passOutcome?.record("trailing-blank-decision-persistence-failure");
|
|
30113
|
+
sessionLog(args.sessionId, "trailing blank decision: persistence failed; leaving newly observed assistants intact");
|
|
30114
|
+
}
|
|
30115
|
+
} catch (error) {
|
|
30116
|
+
args.passOutcome?.record("trailing-blank-decision-exception");
|
|
30117
|
+
sessionLog(args.sessionId, "transform failed freezing trailing blank decision:", error);
|
|
30118
|
+
}
|
|
30119
|
+
}
|
|
30120
|
+
}
|
|
29469
30121
|
sessionLog(args.sessionId, `final representation: clearedParts=${finalRepresentation.clearedParts} mergedReasoningParts=${finalRepresentation.mergedReasoningParts}`);
|
|
29470
30122
|
logTransformTiming(args.sessionId, "finalizeMessageRepresentation", tFinalRepresentation, `clearedParts=${finalRepresentation.clearedParts} mergedReasoningParts=${finalRepresentation.mergedReasoningParts}`);
|
|
29471
30123
|
return {
|
|
@@ -29506,6 +30158,29 @@ var RUST_PARK_RETRY_INTERVAL = 5;
|
|
|
29506
30158
|
var RUST_EMERGENCY_WALL_PCT = 95;
|
|
29507
30159
|
var RUST_PARK_PROBE_PRESSURE_BYPASS_PCT = 90;
|
|
29508
30160
|
var RUST_SEND_TIMEOUT_MS = 15000;
|
|
30161
|
+
function activeAgentFromMessages(messages) {
|
|
30162
|
+
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
30163
|
+
const info = messages[index]?.info;
|
|
30164
|
+
if (info?.role !== "user")
|
|
30165
|
+
continue;
|
|
30166
|
+
return typeof info.agent === "string" && info.agent.length > 0 ? info.agent : undefined;
|
|
30167
|
+
}
|
|
30168
|
+
return;
|
|
30169
|
+
}
|
|
30170
|
+
async function resolveCombinedTodowriteVerdict(deps, sessionId, messages, availability) {
|
|
30171
|
+
if (!availability.frozen || !availability.callable || deps.compactionOff === true)
|
|
30172
|
+
return false;
|
|
30173
|
+
let permissionDenied = cachedToolPermissionDenied(sessionId, "todowrite") ?? getPersistedTodoPermissionDenied(deps.db, sessionId) ?? false;
|
|
30174
|
+
if (deps.client) {
|
|
30175
|
+
try {
|
|
30176
|
+
permissionDenied = await todowritePermissionDenied(deps.client, sessionId, activeAgentFromMessages(messages));
|
|
30177
|
+
setPersistedTodoPermissionDenied(deps.db, sessionId, permissionDenied);
|
|
30178
|
+
} catch (error) {
|
|
30179
|
+
sessionLog(sessionId, "todowrite permission read failed; retaining the last successful verdict:", error);
|
|
30180
|
+
}
|
|
30181
|
+
}
|
|
30182
|
+
return !permissionDenied;
|
|
30183
|
+
}
|
|
29509
30184
|
var RAW_FALLBACK_BYTES_PER_CONTEXT_TOKEN = 4;
|
|
29510
30185
|
function rawFallbackSerializedBytes(messages) {
|
|
29511
30186
|
try {
|
|
@@ -29700,7 +30375,9 @@ function emptyRustPassTimings() {
|
|
|
29700
30375
|
transportPages: 0,
|
|
29701
30376
|
transportBytes: 0,
|
|
29702
30377
|
apply: 0,
|
|
29703
|
-
lkgSnapshot: 0
|
|
30378
|
+
lkgSnapshot: 0,
|
|
30379
|
+
mirrorPull: 0,
|
|
30380
|
+
compartmentMirror: 0
|
|
29704
30381
|
};
|
|
29705
30382
|
}
|
|
29706
30383
|
function formatRustPassLog(args) {
|
|
@@ -29708,7 +30385,7 @@ function formatRustPassLog(args) {
|
|
|
29708
30385
|
const measured = timings.prefixGuard + timings.ordinalResolve + timings.stateSync + timings.clone + timings.wireBuild + timings.transport + timings.apply + timings.lkgSnapshot;
|
|
29709
30386
|
const unattributed = Math.max(0, args.elapsedMs - measured);
|
|
29710
30387
|
const rowVersion = Number.isSafeInteger(args.rowVersion) ? args.rowVersion : 0;
|
|
29711
|
-
return `rust pass: decision=${args.decision} reason=${args.reason} served_from=${args.servedFrom} in=${args.inputCount} out=${args.outputCount} applied=${args.applied} row_version=${rowVersion} elapsed=${args.elapsedMs.toFixed(1)} ms module=${args.moduleElapsedMs.toFixed(1)} ms stages=prefix_guard:${timings.prefixGuard.toFixed(1)} ordinal_resolve:${timings.ordinalResolve.toFixed(1)} state_sync:${timings.stateSync.toFixed(1)} clone:${timings.clone.toFixed(1)} wire_build:${timings.wireBuild.toFixed(1)} wire_messages:${timings.wireMessages} transport:${timings.transport.toFixed(1)} transport_pages:${timings.transportPages} transport_bytes:${timings.transportBytes} apply:${timings.apply.toFixed(1)} lkg_snapshot:${timings.lkgSnapshot.toFixed(1)} other:${unattributed.toFixed(1)}`;
|
|
30388
|
+
return `rust pass: decision=${args.decision} reason=${args.reason} served_from=${args.servedFrom} in=${args.inputCount} out=${args.outputCount} applied=${args.applied} row_version=${rowVersion} elapsed=${args.elapsedMs.toFixed(1)} ms module=${args.moduleElapsedMs.toFixed(1)} ms stages=prefix_guard:${timings.prefixGuard.toFixed(1)} ordinal_resolve:${timings.ordinalResolve.toFixed(1)} state_sync:${timings.stateSync.toFixed(1)} clone:${timings.clone.toFixed(1)} wire_build:${timings.wireBuild.toFixed(1)} wire_messages:${timings.wireMessages} transport:${timings.transport.toFixed(1)} transport_pages:${timings.transportPages} transport_bytes:${timings.transportBytes} apply:${timings.apply.toFixed(1)} lkg_snapshot:${timings.lkgSnapshot.toFixed(1)} mirror_pull:${timings.mirrorPull.toFixed(1)} compartment_mirror:${timings.compartmentMirror.toFixed(1)} other:${unattributed.toFixed(1)}`;
|
|
29712
30389
|
}
|
|
29713
30390
|
function isSyntheticUserMessage(message) {
|
|
29714
30391
|
if (!message || messageInfo2(message).role !== "user" || !Array.isArray(message.parts)) {
|
|
@@ -29738,7 +30415,13 @@ function assertNativeBoundary(output, sessionId, boundaryId) {
|
|
|
29738
30415
|
const synthetic = parts.length > 0 && parts.every((part) => isRecord3(part) && part.synthetic === true);
|
|
29739
30416
|
if (info.role === "user" && info.sessionID === sessionId && synthetic)
|
|
29740
30417
|
return;
|
|
29741
|
-
|
|
30418
|
+
const headSummary = output.slice(0, 3).map((message) => {
|
|
30419
|
+
const mi = messageInfo2(message);
|
|
30420
|
+
const mParts = isRecord3(message) && Array.isArray(message.parts) ? message.parts : [];
|
|
30421
|
+
const partDesc = mParts.slice(0, 5).map((part) => isRecord3(part) ? `${String(part.type)}${part.synthetic === true ? "" : "!"}` : "?").join(",");
|
|
30422
|
+
return `role=${String(mi.role)} sid=${mi.sessionID === sessionId ? "ok" : String(mi.sessionID ?? "absent")} id=${String(mi.id ?? "-").slice(0, 24)} parts=[${partDesc}]`;
|
|
30423
|
+
});
|
|
30424
|
+
throw new Error(`rust transform wire invariant failed: boundary=${boundaryId} expected a synthetic m0 user message scoped to session ${sessionId}; head: ${headSummary.join(" | ")}`);
|
|
29742
30425
|
}
|
|
29743
30426
|
function responseValue(response) {
|
|
29744
30427
|
if (isRecord3(response) && isRecord3(response.result))
|
|
@@ -29747,6 +30430,20 @@ function responseValue(response) {
|
|
|
29747
30430
|
return response;
|
|
29748
30431
|
throw new Error("module transform returned a non-object response");
|
|
29749
30432
|
}
|
|
30433
|
+
function isTransformPageAttemptMismatch(error) {
|
|
30434
|
+
let current = error;
|
|
30435
|
+
const seen = new Set;
|
|
30436
|
+
while (isRecord3(current) && !seen.has(current)) {
|
|
30437
|
+
seen.add(current);
|
|
30438
|
+
const code = typeof current.code === "string" ? current.code : "";
|
|
30439
|
+
const message = typeof current.message === "string" ? current.message : "";
|
|
30440
|
+
if (code === "attempt_mismatch" || code === "authority_transform_page_attempt_mismatch" || /\b(?:authority_transform_page_)?attempt_mismatch\b/.test(message)) {
|
|
30441
|
+
return true;
|
|
30442
|
+
}
|
|
30443
|
+
current = current.cause;
|
|
30444
|
+
}
|
|
30445
|
+
return false;
|
|
30446
|
+
}
|
|
29750
30447
|
function mirrorRustRenderedMemoryIds(args) {
|
|
29751
30448
|
if (!("rendered_memory_ids" in args.response))
|
|
29752
30449
|
return;
|
|
@@ -29856,6 +30553,27 @@ function passUsage(usage, limit) {
|
|
|
29856
30553
|
context_limit_tokens: limit
|
|
29857
30554
|
};
|
|
29858
30555
|
}
|
|
30556
|
+
function transformGeometryForWire(geometry) {
|
|
30557
|
+
if (!geometry)
|
|
30558
|
+
return;
|
|
30559
|
+
const { window, reserve } = geometry.derivation;
|
|
30560
|
+
let derivation;
|
|
30561
|
+
if (geometry.geometry === "separate" && geometry.usableSoft < geometry.usableHard) {
|
|
30562
|
+
derivation = `s1-pre-carve/input=${geometry.usableSoft}`;
|
|
30563
|
+
} else if (geometry.geometry === "separate") {
|
|
30564
|
+
derivation = `s1-separate/context=${window}`;
|
|
30565
|
+
} else {
|
|
30566
|
+
derivation = `s1-shared/context-output/context=${window}/output=${reserve}` + `/mode=${geometry.geometry}/usable-hard=${geometry.usableHard}`;
|
|
30567
|
+
}
|
|
30568
|
+
return {
|
|
30569
|
+
usable_soft: geometry.usableSoft,
|
|
30570
|
+
usable_hard: geometry.usableHard,
|
|
30571
|
+
derivation
|
|
30572
|
+
};
|
|
30573
|
+
}
|
|
30574
|
+
function hardWallUsagePercentage(usage, geometry) {
|
|
30575
|
+
return geometry && geometry.usable_hard > 0 && usage.inputTokens > 0 ? usage.inputTokens / geometry.usable_hard * 100 : usage.percentage;
|
|
30576
|
+
}
|
|
29859
30577
|
function shouldDisarmRustEmergencyRecovery(input) {
|
|
29860
30578
|
if (input.finalWireEstimate?.trusted === true && input.providerProvenLimitTokens > 0 && input.finalWireEstimate.tokens < input.providerProvenLimitTokens * 0.8) {
|
|
29861
30579
|
return "trusted-final-wire";
|
|
@@ -30068,6 +30786,17 @@ function applyNativeMessagesVerbatim(output, response) {
|
|
|
30068
30786
|
}
|
|
30069
30787
|
return replaceMessagesInPlace(output, nativeMessages);
|
|
30070
30788
|
}
|
|
30789
|
+
function muralInputForWire(mural) {
|
|
30790
|
+
if (!mural?.enabled || !mural.supportsVision || typeof mural.dataUrl !== "string" || mural.dataUrl.length === 0) {
|
|
30791
|
+
return;
|
|
30792
|
+
}
|
|
30793
|
+
return {
|
|
30794
|
+
enabled: true,
|
|
30795
|
+
supports_vision: true,
|
|
30796
|
+
data_url: mural.dataUrl,
|
|
30797
|
+
content_hash: mural.contentHash
|
|
30798
|
+
};
|
|
30799
|
+
}
|
|
30071
30800
|
function buildTransformBody(args) {
|
|
30072
30801
|
return {
|
|
30073
30802
|
method: "transform",
|
|
@@ -30096,6 +30825,7 @@ function buildTransformBody(args) {
|
|
|
30096
30825
|
}
|
|
30097
30826
|
} : {},
|
|
30098
30827
|
usage: args.usage,
|
|
30828
|
+
...args.geometry ? { geometry: args.geometry } : {},
|
|
30099
30829
|
provider_error: args.passInputs.provider_error,
|
|
30100
30830
|
mid_turn: args.midTurn,
|
|
30101
30831
|
prev_response_completed_at_ms: args.prevResponseCompletedAtMs,
|
|
@@ -30113,7 +30843,12 @@ function buildTransformBody(args) {
|
|
|
30113
30843
|
prompt_surface_model_key: args.passInputs.prompt_surface_model_key,
|
|
30114
30844
|
prompt_surface_config_identity: args.passInputs.prompt_surface_config_identity,
|
|
30115
30845
|
prompt_surface_tool_descriptions: args.passInputs.prompt_surface_tool_descriptions ?? {},
|
|
30846
|
+
prompt_surface_guidance_override: args.passInputs.prompt_surface_guidance_override,
|
|
30847
|
+
mural: args.passInputs.mural,
|
|
30116
30848
|
effective_execute_threshold: args.passInputs.effective_execute_threshold,
|
|
30849
|
+
auto_search_enabled: args.passInputs.auto_search_enabled === true,
|
|
30850
|
+
auto_search_score_threshold: args.passInputs.auto_search_score_threshold,
|
|
30851
|
+
auto_search_min_prompt_chars: args.passInputs.auto_search_min_prompt_chars,
|
|
30117
30852
|
history_budget_tokens: args.passInputs.history_budget_tokens,
|
|
30118
30853
|
clear_reasoning_age: args.passInputs.clear_reasoning_age,
|
|
30119
30854
|
caveman_enabled: args.passInputs.caveman_enabled === true,
|
|
@@ -30280,11 +31015,22 @@ function createRustModeTransform(deps, options) {
|
|
|
30280
31015
|
if (states.get(plan.sessionId) !== state || plan.captureSequence !== state.lkgCaptureSequence || plan.rowVersion < state.lkgLastCapturedRowVersion) {
|
|
30281
31016
|
return "superseded";
|
|
30282
31017
|
}
|
|
30283
|
-
const
|
|
31018
|
+
const prior = getSlot(plan.sessionId);
|
|
31019
|
+
const inputContentSignatures = plan.inputSnapshots.map((snapshot) => snapshot.signature);
|
|
31020
|
+
const { digests: inputContentDigests } = incrementalLkgContentDigests(plan.inputIds.map((id, index) => ({
|
|
31021
|
+
id,
|
|
31022
|
+
signature: inputContentSignatures[index] ?? "",
|
|
31023
|
+
fields: plan.inputSnapshots[index]?.fields ?? []
|
|
31024
|
+
})), prior?.inputContentSignatures ? {
|
|
31025
|
+
ids: prior.inputIdSeq,
|
|
31026
|
+
signatures: prior.inputContentSignatures,
|
|
31027
|
+
digests: prior.inputContentDigests
|
|
31028
|
+
} : undefined);
|
|
30284
31029
|
const captured = captureSlot(plan.sessionId, {
|
|
30285
31030
|
jsonPrefix: plan.jsonPrefix,
|
|
30286
31031
|
inputIdSeq: plan.inputIds,
|
|
30287
31032
|
inputContentDigests,
|
|
31033
|
+
inputContentSignatures,
|
|
30288
31034
|
lastInputMessageId: plan.inputIds[plan.inputIds.length - 1],
|
|
30289
31035
|
modelKey: plan.modelKey,
|
|
30290
31036
|
providerKey: plan.providerKey,
|
|
@@ -30330,14 +31076,16 @@ function createRustModeTransform(deps, options) {
|
|
|
30330
31076
|
preflightError = error;
|
|
30331
31077
|
}
|
|
30332
31078
|
}
|
|
30333
|
-
const modelKey = model ? resolveModelKey(model.providerID, model.modelID) : null;
|
|
31079
|
+
const modelKey = model ? piModelRefToCanonical(resolveModelKey(model.providerID, model.modelID) ?? "") : null;
|
|
30334
31080
|
let resolvedContextLimit;
|
|
31081
|
+
let resolvedWindowGeometry;
|
|
30335
31082
|
if (model) {
|
|
30336
31083
|
try {
|
|
30337
31084
|
resolvedContextLimit = resolveTrustedContextLimit(model.providerID, model.modelID, {
|
|
30338
31085
|
db: deps.db,
|
|
30339
31086
|
sessionID: sessionId
|
|
30340
31087
|
});
|
|
31088
|
+
resolvedWindowGeometry = resolveContextWindowGeometry(model.providerID, model.modelID, { db: deps.db, sessionID: sessionId });
|
|
30341
31089
|
} catch (error) {
|
|
30342
31090
|
preflightError ??= error;
|
|
30343
31091
|
}
|
|
@@ -30348,14 +31096,16 @@ function createRustModeTransform(deps, options) {
|
|
|
30348
31096
|
} catch (error) {
|
|
30349
31097
|
preflightError ??= error;
|
|
30350
31098
|
}
|
|
30351
|
-
|
|
31099
|
+
const transformGeometry = transformGeometryForWire(resolvedWindowGeometry);
|
|
31100
|
+
const hasTrustedEmergencyWall = transformGeometry ? transformGeometry.usable_hard > 0 : resolvedContextLimit !== undefined && resolvedContextLimit > 0;
|
|
31101
|
+
emergencyFailClosed = hardWallUsagePercentage(passUsageSnapshot, transformGeometry) >= RUST_EMERGENCY_WALL_PCT && hasTrustedEmergencyWall;
|
|
30352
31102
|
if (overflowState) {
|
|
30353
|
-
const detectedLimitMatchesModel = overflowState.detectedContextLimitModelKey === null || overflowState.detectedContextLimitModelKey === modelKey;
|
|
31103
|
+
const detectedLimitMatchesModel = overflowState.detectedContextLimitModelKey === null || piModelRefToCanonical(overflowState.detectedContextLimitModelKey) === piModelRefToCanonical(modelKey ?? "");
|
|
30354
31104
|
const hasProviderProof = overflowState.detectedContextLimit > 0 && detectedLimitMatchesModel || isProviderOverflowReconfirmed(sessionId);
|
|
30355
31105
|
emergencyFailClosed ||= overflowState.needsEmergencyRecovery && overflowState.emergencyRecoveryOrigin === "provider_overflow" && hasProviderProof;
|
|
30356
31106
|
}
|
|
30357
31107
|
const serveRawFallback = (cause) => {
|
|
30358
|
-
const contextLimit = resolvedContextLimit ?? (overflowState && overflowState.detectedContextLimit > 0 ? overflowState.detectedContextLimit : undefined);
|
|
31108
|
+
const contextLimit = transformGeometry?.usable_hard ?? resolvedContextLimit ?? (overflowState && overflowState.detectedContextLimit > 0 ? overflowState.detectedContextLimit : undefined);
|
|
30359
31109
|
if (contextLimit !== undefined) {
|
|
30360
31110
|
let estimate;
|
|
30361
31111
|
try {
|
|
@@ -30448,7 +31198,7 @@ function createRustModeTransform(deps, options) {
|
|
|
30448
31198
|
resolveTodowriteAvailabilityFromMessages(sessionId, messages);
|
|
30449
31199
|
const todoAvailability = resolveTodowriteAvailability(sessionId);
|
|
30450
31200
|
const toolPresent = reduceAvailability.frozen && reduceAvailability.callable;
|
|
30451
|
-
const todoToolPresent =
|
|
31201
|
+
const todoToolPresent = await resolveCombinedTodowriteVerdict(deps, sessionId, messages, todoAvailability);
|
|
30452
31202
|
try {
|
|
30453
31203
|
if (preflightError)
|
|
30454
31204
|
throw preflightError;
|
|
@@ -30465,13 +31215,20 @@ function createRustModeTransform(deps, options) {
|
|
|
30465
31215
|
const midTurn = isMidTurn(deps, sessionId);
|
|
30466
31216
|
const requestObservedAtMs = Date.now();
|
|
30467
31217
|
const recoveryNoHeadEscape = overflowState.needsEmergencyRecovery && loadProtectedTailMeta(deps.db, sessionId).recoveryNoEligibleHeadCount >= RECOVERY_NO_HEAD_LIMIT;
|
|
30468
|
-
const
|
|
31218
|
+
const promptSurfaceGuidance = deps.promptSurfaceRuntime?.resolveGuidance(deps.promptSurface, modelKey ?? undefined);
|
|
31219
|
+
const promptSurface = promptSurfaceGuidance ?? resolvePromptSurface(deps.promptSurface, modelKey ?? undefined);
|
|
31220
|
+
const resolvedMural = !sessionMeta.isSubagent && deps.muralEnabled === true ? resolveMuralWire(deps.db, deps.projectPath, modelKey ?? undefined, true, deps.memoryConfig?.injectionBudgetTokens) : undefined;
|
|
31221
|
+
const mural = muralInputForWire(resolvedMural);
|
|
30469
31222
|
const passInputs = {
|
|
30470
31223
|
now_ms: requestObservedAtMs,
|
|
30471
31224
|
model_key: modelKey,
|
|
30472
31225
|
provider_id: model?.providerID ?? null,
|
|
30473
31226
|
usage: passUsage(usage, contextLimit),
|
|
31227
|
+
geometry: transformGeometry,
|
|
30474
31228
|
effective_execute_threshold: threshold,
|
|
31229
|
+
auto_search_enabled: deps.autoSearch?.enabled ?? true,
|
|
31230
|
+
auto_search_score_threshold: deps.autoSearch?.scoreThreshold ?? 0.6,
|
|
31231
|
+
auto_search_min_prompt_chars: deps.autoSearch?.minPromptChars ?? 20,
|
|
30475
31232
|
history_budget_tokens: historyBudgetTokens,
|
|
30476
31233
|
clear_reasoning_age: deps.clearReasoningAge,
|
|
30477
31234
|
caveman_enabled: !sessionMeta.isSubagent && deps.cavemanTextCompression?.enabled === true,
|
|
@@ -30487,6 +31244,8 @@ function createRustModeTransform(deps, options) {
|
|
|
30487
31244
|
prompt_surface_model_key: modelKey,
|
|
30488
31245
|
prompt_surface_config_identity: promptSurfaceConfigIdentity(deps.promptSurface),
|
|
30489
31246
|
prompt_surface_tool_descriptions: deps.promptSurface?.tool_descriptions ?? {},
|
|
31247
|
+
prompt_surface_guidance_override: promptSurfaceGuidance?.primaryOverride,
|
|
31248
|
+
mural,
|
|
30490
31249
|
protected_tags: deps.protectedTags ?? DEFAULT_PROTECTED_TAGS,
|
|
30491
31250
|
temporal_awareness: deps.experimentalTemporalAwareness === true,
|
|
30492
31251
|
channel2_nudge_state: getChannel2NudgeState(deps.db, sessionId),
|
|
@@ -30702,6 +31461,7 @@ function createRustModeTransform(deps, options) {
|
|
|
30702
31461
|
final_wire_input_tokens: finalWireEstimate?.tokens ?? 0,
|
|
30703
31462
|
final_wire_trusted: finalWireEstimate?.trusted === true
|
|
30704
31463
|
},
|
|
31464
|
+
geometry: transformGeometry,
|
|
30705
31465
|
modelKey: modelKey ?? null,
|
|
30706
31466
|
providerId: model?.providerID ?? null,
|
|
30707
31467
|
systemPromptHash: sessionMeta.systemPromptHash ?? "",
|
|
@@ -30712,24 +31472,75 @@ function createRustModeTransform(deps, options) {
|
|
|
30712
31472
|
channel2NudgeState: String(passInputs.channel2_nudge_state ?? ""),
|
|
30713
31473
|
emergencyRecoveryArmed: passInputs.emergency_recovery_armed === true
|
|
30714
31474
|
});
|
|
30715
|
-
const pages = buildPagedModuleTransformPayloads(body);
|
|
30716
31475
|
logStage(sessionId, "wireBuild", wireBuildStartedAt, timings, wireDelta ? `mode=tail_delta input=${encodedInput.length}` : "mode=full");
|
|
30717
|
-
|
|
31476
|
+
const sendTransformSeries = async (payload, detail = "") => {
|
|
31477
|
+
const pages = buildPagedModuleTransformPayloads(payload);
|
|
31478
|
+
const paged = pages.some((entry) => typeof entry.page.transform_page_id === "string");
|
|
31479
|
+
let response2;
|
|
31480
|
+
for (const [index, { page, bytes }] of pages.entries()) {
|
|
31481
|
+
const transportStartedAt = performance.now();
|
|
31482
|
+
let moduleResponse;
|
|
31483
|
+
try {
|
|
31484
|
+
moduleResponse = await callModule({
|
|
31485
|
+
sessionId,
|
|
31486
|
+
projectRoot,
|
|
31487
|
+
method: "transform",
|
|
31488
|
+
body: page,
|
|
31489
|
+
generationSensitive: paged && index > 0
|
|
31490
|
+
});
|
|
31491
|
+
} catch (error) {
|
|
31492
|
+
if (paged && isTransformPageAttemptMismatch(error)) {
|
|
31493
|
+
return {
|
|
31494
|
+
restart: {
|
|
31495
|
+
reason: "attempt_mismatch",
|
|
31496
|
+
pages: pages.length,
|
|
31497
|
+
atPage: index
|
|
31498
|
+
}
|
|
31499
|
+
};
|
|
31500
|
+
}
|
|
31501
|
+
throw error;
|
|
31502
|
+
}
|
|
31503
|
+
if (paged && isModuleTransportGenerationChangedResult(moduleResponse)) {
|
|
31504
|
+
return {
|
|
31505
|
+
restart: { reason: "reconnect", pages: pages.length, atPage: index }
|
|
31506
|
+
};
|
|
31507
|
+
}
|
|
31508
|
+
if (paged && isTransformPageAttemptMismatch(moduleResponse)) {
|
|
31509
|
+
return {
|
|
31510
|
+
restart: {
|
|
31511
|
+
reason: "attempt_mismatch",
|
|
31512
|
+
pages: pages.length,
|
|
31513
|
+
atPage: index
|
|
31514
|
+
}
|
|
31515
|
+
};
|
|
31516
|
+
}
|
|
31517
|
+
response2 = responseValue(moduleResponse);
|
|
31518
|
+
timings.transportBytes += bytes;
|
|
31519
|
+
timings.transportPages += 1;
|
|
31520
|
+
logStage(sessionId, "transport", transportStartedAt, timings, `page=${index + 1}/${pages.length}${detail}`);
|
|
31521
|
+
}
|
|
31522
|
+
if (!response2)
|
|
31523
|
+
throw new Error("rust module returned no transform response");
|
|
31524
|
+
return { response: response2 };
|
|
31525
|
+
};
|
|
31526
|
+
let transformSeriesRestarted = false;
|
|
31527
|
+
const sendTransformSeriesWithSingleRestart = async (payload, detail = "") => {
|
|
31528
|
+
let result = await sendTransformSeries(payload, detail);
|
|
31529
|
+
if (!("restart" in result))
|
|
31530
|
+
return result.response;
|
|
31531
|
+
if (transformSeriesRestarted) {
|
|
31532
|
+
throw new Error(`rust transform page series restart exhausted: reason=${result.restart.reason}`);
|
|
31533
|
+
}
|
|
31534
|
+
transformSeriesRestarted = true;
|
|
31535
|
+
sessionLog(sessionId, `transform_series_restart reason=${result.restart.reason} pages=${result.restart.pages} at_page=${result.restart.atPage}`);
|
|
31536
|
+
result = await sendTransformSeries(payload, `${detail} restart=series`);
|
|
31537
|
+
if ("restart" in result) {
|
|
31538
|
+
throw new Error(`rust transform page series restart exhausted: reason=${result.restart.reason}`);
|
|
31539
|
+
}
|
|
31540
|
+
return result.response;
|
|
31541
|
+
};
|
|
31542
|
+
let response = await sendTransformSeriesWithSingleRestart(body);
|
|
30718
31543
|
let servedFinalWireEstimate;
|
|
30719
|
-
for (const [index, page] of pages.entries()) {
|
|
30720
|
-
timings.transportBytes += Buffer.byteLength(JSON.stringify(page));
|
|
30721
|
-
const transportStartedAt = performance.now();
|
|
30722
|
-
response = responseValue(await callModule({
|
|
30723
|
-
sessionId,
|
|
30724
|
-
projectRoot,
|
|
30725
|
-
method: "transform",
|
|
30726
|
-
body: page
|
|
30727
|
-
}));
|
|
30728
|
-
timings.transportPages += 1;
|
|
30729
|
-
logStage(sessionId, "transport", transportStartedAt, timings, `page=${index + 1}/${pages.length}`);
|
|
30730
|
-
}
|
|
30731
|
-
if (!response)
|
|
30732
|
-
throw new Error("rust module returned no transform response");
|
|
30733
31544
|
captureResponseTelemetry(response);
|
|
30734
31545
|
if (isNeedFullSync(response)) {
|
|
30735
31546
|
options.moduleClient.invalidateStateSyncCapabilities?.();
|
|
@@ -30798,6 +31609,7 @@ function createRustModeTransform(deps, options) {
|
|
|
30798
31609
|
final_wire_input_tokens: finalWireEstimate?.tokens ?? 0,
|
|
30799
31610
|
final_wire_trusted: finalWireEstimate?.trusted === true
|
|
30800
31611
|
},
|
|
31612
|
+
geometry: transformGeometry,
|
|
30801
31613
|
modelKey: modelKey ?? null,
|
|
30802
31614
|
providerId: model?.providerID ?? null,
|
|
30803
31615
|
systemPromptHash: sessionMeta.systemPromptHash ?? "",
|
|
@@ -30810,24 +31622,9 @@ function createRustModeTransform(deps, options) {
|
|
|
30810
31622
|
});
|
|
30811
31623
|
logStage(sessionId, "wireBuild", retryWireBuildStartedAt2, timings, "retry=full");
|
|
30812
31624
|
}
|
|
30813
|
-
response = undefined;
|
|
30814
31625
|
const retryWireBuildStartedAt = performance.now();
|
|
30815
|
-
|
|
31626
|
+
response = await sendTransformSeriesWithSingleRestart(body, " retry=full");
|
|
30816
31627
|
logStage(sessionId, "wireBuild", retryWireBuildStartedAt, timings, "retry=full");
|
|
30817
|
-
for (const [index, page] of retryPages.entries()) {
|
|
30818
|
-
timings.transportBytes += Buffer.byteLength(JSON.stringify(page));
|
|
30819
|
-
const transportStartedAt = performance.now();
|
|
30820
|
-
response = responseValue(await callModule({
|
|
30821
|
-
sessionId,
|
|
30822
|
-
projectRoot,
|
|
30823
|
-
method: "transform",
|
|
30824
|
-
body: page
|
|
30825
|
-
}));
|
|
30826
|
-
timings.transportPages += 1;
|
|
30827
|
-
logStage(sessionId, "transport", transportStartedAt, timings, `page=${index + 1}/${retryPages.length} retry=full`);
|
|
30828
|
-
}
|
|
30829
|
-
if (!response)
|
|
30830
|
-
throw new Error("rust module returned no retry transform response");
|
|
30831
31628
|
captureResponseTelemetry(response);
|
|
30832
31629
|
if (isNeedFullSync(response)) {
|
|
30833
31630
|
throw new Error("rust module still requires full sync after a full-array send");
|
|
@@ -30861,7 +31658,10 @@ function createRustModeTransform(deps, options) {
|
|
|
30861
31658
|
sessionId,
|
|
30862
31659
|
messages: appliedMessages,
|
|
30863
31660
|
projectPath: memoryProjectPath,
|
|
30864
|
-
fullFeatureMode: !sessionMeta.isSubagent
|
|
31661
|
+
fullFeatureMode: !sessionMeta.isSubagent,
|
|
31662
|
+
compactionOff: deps.compactionOff,
|
|
31663
|
+
tagger: deps.tagger,
|
|
31664
|
+
ctxReduceAvailability: reduceAvailability
|
|
30865
31665
|
});
|
|
30866
31666
|
const boundaryId = response.boundary_id;
|
|
30867
31667
|
if (typeof boundaryId === "string" && boundaryId.length > 0) {
|
|
@@ -30983,7 +31783,26 @@ function createRustModeTransform(deps, options) {
|
|
|
30983
31783
|
sessionLog(sessionId, "rust channel2 pending-intent CAS failed (ignored):", error);
|
|
30984
31784
|
}
|
|
30985
31785
|
}
|
|
31786
|
+
const currentOverflowState = getOverflowState(deps.db, sessionId, modelKey);
|
|
31787
|
+
const disarmEvidence = currentOverflowState.needsEmergencyRecovery ? shouldDisarmRustEmergencyRecovery({
|
|
31788
|
+
materialized: materializeReason !== "none",
|
|
31789
|
+
usagePercentage: passUsageSnapshot.percentage,
|
|
31790
|
+
recoveryOrigin: currentOverflowState.emergencyRecoveryOrigin,
|
|
31791
|
+
recoveryArmedAt: getEmergencyRecoveryArmedAt(sessionId),
|
|
31792
|
+
usageEntry: deps.contextUsageMap.get(sessionId),
|
|
31793
|
+
finalWireEstimate: servedFinalWireEstimate,
|
|
31794
|
+
providerProvenLimitTokens: currentOverflowState.detectedContextLimit
|
|
31795
|
+
}) : null;
|
|
31796
|
+
if (disarmEvidence) {
|
|
31797
|
+
try {
|
|
31798
|
+
clearEmergencyRecovery(deps.db, sessionId);
|
|
31799
|
+
sessionLog(sessionId, `rust pass disarmed emergency recovery via ${disarmEvidence} after ${materializeReason} at ${passUsageSnapshot.percentage.toFixed(1)}% usage`);
|
|
31800
|
+
} catch {}
|
|
31801
|
+
}
|
|
31802
|
+
wireCaches.set(sessionId, pendingWireCache);
|
|
31803
|
+
appliedAt = performance.now();
|
|
30986
31804
|
if (options.moduleClient.mirrorPull) {
|
|
31805
|
+
const mirrorPullStartedAt = performance.now();
|
|
30987
31806
|
try {
|
|
30988
31807
|
await pullMemoryMirrorOnce({
|
|
30989
31808
|
db: deps.db,
|
|
@@ -30991,10 +31810,13 @@ function createRustModeTransform(deps, options) {
|
|
|
30991
31810
|
});
|
|
30992
31811
|
} catch (error) {
|
|
30993
31812
|
sessionLog(sessionId, "rust memory mirror-back failed (ignored):", error);
|
|
31813
|
+
} finally {
|
|
31814
|
+
logStage(sessionId, "mirrorPull", mirrorPullStartedAt, timings);
|
|
30994
31815
|
}
|
|
30995
31816
|
}
|
|
30996
31817
|
const getCompartmentsAfter = options.moduleClient.getCompartmentsAfter;
|
|
30997
31818
|
if (getCompartmentsAfter) {
|
|
31819
|
+
const compartmentMirrorStartedAt = performance.now();
|
|
30998
31820
|
try {
|
|
30999
31821
|
await mirrorModuleCompartments({
|
|
31000
31822
|
db: deps.db,
|
|
@@ -31005,26 +31827,10 @@ function createRustModeTransform(deps, options) {
|
|
|
31005
31827
|
});
|
|
31006
31828
|
} catch (error) {
|
|
31007
31829
|
sessionLog(sessionId, "rust compartment mirror-back failed (ignored):", error);
|
|
31830
|
+
} finally {
|
|
31831
|
+
logStage(sessionId, "compartmentMirror", compartmentMirrorStartedAt, timings);
|
|
31008
31832
|
}
|
|
31009
31833
|
}
|
|
31010
|
-
const currentOverflowState = getOverflowState(deps.db, sessionId, modelKey);
|
|
31011
|
-
const disarmEvidence = currentOverflowState.needsEmergencyRecovery ? shouldDisarmRustEmergencyRecovery({
|
|
31012
|
-
materialized: materializeReason !== "none",
|
|
31013
|
-
usagePercentage: passUsageSnapshot.percentage,
|
|
31014
|
-
recoveryOrigin: currentOverflowState.emergencyRecoveryOrigin,
|
|
31015
|
-
recoveryArmedAt: getEmergencyRecoveryArmedAt(sessionId),
|
|
31016
|
-
usageEntry: deps.contextUsageMap.get(sessionId),
|
|
31017
|
-
finalWireEstimate: servedFinalWireEstimate,
|
|
31018
|
-
providerProvenLimitTokens: currentOverflowState.detectedContextLimit
|
|
31019
|
-
}) : null;
|
|
31020
|
-
if (disarmEvidence) {
|
|
31021
|
-
try {
|
|
31022
|
-
clearEmergencyRecovery(deps.db, sessionId);
|
|
31023
|
-
sessionLog(sessionId, `rust pass disarmed emergency recovery via ${disarmEvidence} after ${materializeReason} at ${passUsageSnapshot.percentage.toFixed(1)}% usage`);
|
|
31024
|
-
} catch {}
|
|
31025
|
-
}
|
|
31026
|
-
wireCaches.set(sessionId, pendingWireCache);
|
|
31027
|
-
appliedAt = performance.now();
|
|
31028
31834
|
finishPass(true);
|
|
31029
31835
|
} catch (error) {
|
|
31030
31836
|
if (error instanceof Error && error.message.startsWith("rust transform wire invariant failed")) {
|
|
@@ -31061,6 +31867,7 @@ function createRustModeTransform(deps, options) {
|
|
|
31061
31867
|
dropSlot(sessionId, "session-deleted");
|
|
31062
31868
|
states.delete(sessionId);
|
|
31063
31869
|
wireCaches.delete(sessionId);
|
|
31870
|
+
clearCompartmentMirrorCursor(sessionId);
|
|
31064
31871
|
if (projectRoot && options.moduleClient.deleteSession) {
|
|
31065
31872
|
options.moduleClient.deleteSession(sessionId, projectRoot).catch((error) => {
|
|
31066
31873
|
sessionLog(sessionId, "rust module session deletion failed:", error);
|
|
@@ -31306,7 +32113,7 @@ function clearMessageTokensCache(sessionId, messageId2) {
|
|
|
31306
32113
|
cache.delete(messageId2);
|
|
31307
32114
|
}
|
|
31308
32115
|
var recordedSessionProjectIdentity = new BoundedSessionMap(MESSAGE_TOKENS_CACHE_MAX);
|
|
31309
|
-
function
|
|
32116
|
+
function activeAgentFromMessages2(messages) {
|
|
31310
32117
|
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
31311
32118
|
const info = messages[index]?.info;
|
|
31312
32119
|
if (info?.role !== "user")
|
|
@@ -31321,7 +32128,7 @@ function deriveTaggerLoadFloor(messages, sessionId, db) {
|
|
|
31321
32128
|
yield message.info?.id;
|
|
31322
32129
|
}());
|
|
31323
32130
|
}
|
|
31324
|
-
function computeHardCacheExpired(cacheTtl, lastResponseTime,
|
|
32131
|
+
function computeHardCacheExpired(cacheTtl, lastResponseTime, now2, onInvalid) {
|
|
31325
32132
|
let ttlMs;
|
|
31326
32133
|
try {
|
|
31327
32134
|
ttlMs = parseCacheTtl(cacheTtl);
|
|
@@ -31329,7 +32136,7 @@ function computeHardCacheExpired(cacheTtl, lastResponseTime, now, onInvalid) {
|
|
|
31329
32136
|
onInvalid?.(error);
|
|
31330
32137
|
ttlMs = 5 * 60 * 1000;
|
|
31331
32138
|
}
|
|
31332
|
-
return lastResponseTime > 0 &&
|
|
32139
|
+
return lastResponseTime > 0 && now2 - lastResponseTime > ttlMs;
|
|
31333
32140
|
}
|
|
31334
32141
|
function findLastAssistantModel(messages) {
|
|
31335
32142
|
for (let i = messages.length - 1;i >= 0; i--) {
|
|
@@ -31421,6 +32228,8 @@ async function recoverTsAuthorityProject(args) {
|
|
|
31421
32228
|
function scheduleTsAuthorityRecovery(args) {
|
|
31422
32229
|
if (!getAuthorityManagedMarker(args.db, args.projectPath))
|
|
31423
32230
|
return;
|
|
32231
|
+
if ((args.isLinkedWorktree ?? isLinkedGitWorktree)(args.projectRoot))
|
|
32232
|
+
return;
|
|
31424
32233
|
if (tsAuthorityRecoveryStateByProject.has(args.projectPath))
|
|
31425
32234
|
return;
|
|
31426
32235
|
const module = args.module;
|
|
@@ -31483,7 +32292,7 @@ function createTransform(deps) {
|
|
|
31483
32292
|
}
|
|
31484
32293
|
const tUserMsg = performance.now();
|
|
31485
32294
|
const currentTurnId = findLastUserMessageId(messages);
|
|
31486
|
-
const activeAgent =
|
|
32295
|
+
const activeAgent = activeAgentFromMessages2(messages);
|
|
31487
32296
|
logTransformTiming(sessionId, "findLastUserMessageId", tUserMsg);
|
|
31488
32297
|
const tMeta = performance.now();
|
|
31489
32298
|
let sessionMeta;
|
|
@@ -31541,8 +32350,6 @@ function createTransform(deps) {
|
|
|
31541
32350
|
sessionLog(sessionId, "compaction mode transition failed (retrying next pass):", error);
|
|
31542
32351
|
}
|
|
31543
32352
|
if (deps.transformMode === "rust") {
|
|
31544
|
-
if (compactionOff)
|
|
31545
|
-
return;
|
|
31546
32353
|
if (!rustModeTransform) {
|
|
31547
32354
|
sessionLog(sessionId, "rust transform unavailable; using raw passthrough");
|
|
31548
32355
|
return;
|
|
@@ -31589,7 +32396,7 @@ function createTransform(deps) {
|
|
|
31589
32396
|
deps.liveModelBySession.set(sessionId, currentOutgoingModel);
|
|
31590
32397
|
const outgoingModelKey = resolveModelKey(currentOutgoingModel.providerID, currentOutgoingModel.modelID);
|
|
31591
32398
|
const lastUsageModelKey = persistedUsageBeforeResets?.lastObservedModelKey ?? null;
|
|
31592
|
-
if (lastUsageModelKey != null && outgoingModelKey != null && lastUsageModelKey !== outgoingModelKey) {
|
|
32399
|
+
if (lastUsageModelKey != null && outgoingModelKey != null && piModelRefToCanonical(lastUsageModelKey) !== piModelRefToCanonical(outgoingModelKey)) {
|
|
31593
32400
|
dropSlot(sessionId, "model-change");
|
|
31594
32401
|
sessionLog(sessionId, `transform: model change since last usage (${lastUsageModelKey} -> ${outgoingModelKey}), clearing stale per-model state`);
|
|
31595
32402
|
updateSessionMeta(db, sessionId, {
|
|
@@ -31647,7 +32454,7 @@ function createTransform(deps) {
|
|
|
31647
32454
|
const lastMeasuredInput = armSnapshot?.usage.inputTokens ?? sessionMeta?.lastInputTokens ?? 0;
|
|
31648
32455
|
const lastMeasuredModelKey = armSnapshot?.lastObservedModelKey ?? null;
|
|
31649
32456
|
const armCatalogLimit = armModel ? getSdkContextLimit(armModel.providerID, armModel.modelID) : undefined;
|
|
31650
|
-
if (!sessionMeta?.isSubagent && armModel && typeof armCatalogLimit === "number" && armCatalogLimit > 0 && lastMeasuredInput > armCatalogLimit && lastMeasuredModelKey != null && armModelKey != null && lastMeasuredModelKey !== armModelKey && !getOverflowState(db, sessionId).needsEmergencyRecovery) {
|
|
32457
|
+
if (!sessionMeta?.isSubagent && armModel && typeof armCatalogLimit === "number" && armCatalogLimit > 0 && lastMeasuredInput > armCatalogLimit && lastMeasuredModelKey != null && armModelKey != null && piModelRefToCanonical(lastMeasuredModelKey) !== piModelRefToCanonical(armModelKey) && !getOverflowState(db, sessionId).needsEmergencyRecovery) {
|
|
31651
32458
|
sessionLog(sessionId, `transform: last input ${lastMeasuredInput} (model ${lastMeasuredModelKey}) exceeds new model ${armModelKey} catalog limit ${armCatalogLimit}; arming overflow recovery proactively for the shrinking switch`);
|
|
31652
32459
|
dropSlot(sessionId, "overflow-recovery-arm");
|
|
31653
32460
|
recordOverflowDetected(db, sessionId, undefined, armModelKey, "proactive_model_shrink");
|
|
@@ -31691,6 +32498,11 @@ function createTransform(deps) {
|
|
|
31691
32498
|
db,
|
|
31692
32499
|
sessionID: sessionId
|
|
31693
32500
|
}) : undefined;
|
|
32501
|
+
const windowGeometry = modelForBudget ? resolveContextWindowGeometry(modelForBudget.providerID, modelForBudget.modelID, {
|
|
32502
|
+
db,
|
|
32503
|
+
sessionID: sessionId
|
|
32504
|
+
}) : undefined;
|
|
32505
|
+
const emergencyUsagePercentageEarly = usagePercentageSynthetic ? Math.max(95, contextUsageEarly.percentage) : windowGeometry?.usableHard && contextUsageEarly.inputTokens > 0 ? contextUsageEarly.inputTokens / windowGeometry.usableHard * 100 : contextUsageEarly.percentage;
|
|
31694
32506
|
const currentModelKeyForBoundary = deps.getModelKey?.(sessionId);
|
|
31695
32507
|
const thresholdContextLimit = resolvedContextLimit && resolvedContextLimit > 0 ? resolvedContextLimit : contextUsageEarly.percentage > 0 ? contextUsageEarly.inputTokens / (contextUsageEarly.percentage / 100) : undefined;
|
|
31696
32508
|
const effectiveExecuteThresholdPercentage = resolveExecuteThreshold(deps.executeThresholdPercentage ?? 65, currentModelKeyForBoundary, 65, {
|
|
@@ -31699,7 +32511,7 @@ function createTransform(deps) {
|
|
|
31699
32511
|
sessionId
|
|
31700
32512
|
});
|
|
31701
32513
|
const { forceMaterializationPercentage } = escalationBands(effectiveExecuteThresholdPercentage);
|
|
31702
|
-
const persistedUsageFreshForBoundary = persistedUsageBeforeResets && Date.now() - persistedUsageBeforeResets.updatedAt <= 10 * 60 * 1000 && (persistedUsageBeforeResets.lastObservedModelKey === null || currentModelKeyForBoundary === undefined || persistedUsageBeforeResets.lastObservedModelKey === currentModelKeyForBoundary) && (resolvedContextLimit === undefined || persistedUsageBeforeResets.lastUsageContextLimit === 0 || persistedUsageBeforeResets.lastUsageContextLimit === resolvedContextLimit) ? persistedUsageBeforeResets.usage : null;
|
|
32514
|
+
const persistedUsageFreshForBoundary = persistedUsageBeforeResets && Date.now() - persistedUsageBeforeResets.updatedAt <= 10 * 60 * 1000 && (persistedUsageBeforeResets.lastObservedModelKey === null || currentModelKeyForBoundary === undefined || piModelRefToCanonical(persistedUsageBeforeResets.lastObservedModelKey) === piModelRefToCanonical(currentModelKeyForBoundary)) && (resolvedContextLimit === undefined || persistedUsageBeforeResets.lastUsageContextLimit === 0 || persistedUsageBeforeResets.lastUsageContextLimit === resolvedContextLimit) ? persistedUsageBeforeResets.usage : null;
|
|
31703
32515
|
const boundaryUsageForProtectedTail = persistedUsageFreshForBoundary ?? contextUsageEarly;
|
|
31704
32516
|
const boundaryUsageSource = persistedUsageFreshForBoundary ? "persisted" : "live";
|
|
31705
32517
|
const historyBudgetTokens = resolveHistoryBudgetTokens(deps.historyBudgetPercentage, contextUsageEarly, deps.executeThresholdPercentage, deps.getModelKey?.(sessionId), deps.executeThresholdTokens, resolvedContextLimit);
|
|
@@ -31776,7 +32588,7 @@ function createTransform(deps) {
|
|
|
31776
32588
|
};
|
|
31777
32589
|
let skipCompartmentAwaitForThisPass = false;
|
|
31778
32590
|
const startRecoveryRun = () => {
|
|
31779
|
-
const scale =
|
|
32591
|
+
const scale = emergencyUsagePercentageEarly >= 95 ? 0.25 : 0.5;
|
|
31780
32592
|
let boundarySnapshot = getRunnableBoundaryForCompartment();
|
|
31781
32593
|
if (!boundarySnapshot || !hasRunnableCompartmentWindow(boundarySnapshot)) {
|
|
31782
32594
|
boundarySnapshot = getRunnableBoundaryForCompartment(scale);
|
|
@@ -31817,12 +32629,12 @@ function createTransform(deps) {
|
|
|
31817
32629
|
skipCompartmentAwaitForThisPass = true;
|
|
31818
32630
|
return true;
|
|
31819
32631
|
};
|
|
31820
|
-
if (fullFeatureMode && !compactionOff && historianFailureState.failureCount > 0 &&
|
|
32632
|
+
if (fullFeatureMode && !compactionOff && historianFailureState.failureCount > 0 && emergencyUsagePercentageEarly >= 95 && !recoveryNoHeadEscapeActive) {
|
|
31821
32633
|
skipCompartmentAwaitForThisPass = true;
|
|
31822
32634
|
const emergencyPercentage = contextUsageEarly.percentage.toFixed(1);
|
|
31823
32635
|
const recoveryStarted = startRecoveryRun();
|
|
31824
32636
|
if (!recoveryStarted && !getEligibleHistoryForCompartment()) {
|
|
31825
|
-
const noHeadSnapshot = getRunnableBoundaryForCompartment(
|
|
32637
|
+
const noHeadSnapshot = getRunnableBoundaryForCompartment(emergencyUsagePercentageEarly >= 95 ? 0.25 : 0.5) ?? getRunnableBoundaryForCompartment();
|
|
31826
32638
|
if (noHeadSnapshot) {
|
|
31827
32639
|
recordHighPressureNoEligibleHead(db, noHeadSnapshot);
|
|
31828
32640
|
}
|
|
@@ -32131,7 +32943,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
32131
32943
|
const finalWireTail = describeFinalWireTail(messages);
|
|
32132
32944
|
let finalWireEstimate;
|
|
32133
32945
|
if (!compactionOff) {
|
|
32134
|
-
|
|
32946
|
+
const emergencyUsagePercentage = usagePercentageSynthetic ? Math.max(95, contextUsage.percentage) : windowGeometry?.usableHard && contextUsage.inputTokens > 0 ? contextUsage.inputTokens / windowGeometry.usableHard * 100 : contextUsage.percentage;
|
|
32947
|
+
finalWireEstimate = emergencyUsagePercentage >= 95 ? estimateFinalWireInputTokens({
|
|
32135
32948
|
messages,
|
|
32136
32949
|
systemPromptTokens: sessionMeta.systemPromptTokens,
|
|
32137
32950
|
providerID: modelForBudget?.providerID,
|
|
@@ -32143,9 +32956,9 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
|
|
|
32143
32956
|
}
|
|
32144
32957
|
const currentModelKeyForRecovery = deps.getModelKey?.(sessionId);
|
|
32145
32958
|
const overflowStateForFinalWire = getOverflowState(db, sessionId, currentModelKeyForRecovery);
|
|
32146
|
-
const providerProvenLimitTokens = typeof currentModelKeyForRecovery === "string" && currentModelKeyForRecovery.length > 0 && overflowStateForFinalWire.detectedContextLimit > 0 && overflowStateForFinalWire.detectedContextLimitModelKey === currentModelKeyForRecovery ? overflowStateForFinalWire.detectedContextLimit : undefined;
|
|
32959
|
+
const providerProvenLimitTokens = typeof currentModelKeyForRecovery === "string" && currentModelKeyForRecovery.length > 0 && overflowStateForFinalWire.detectedContextLimit > 0 && piModelRefToCanonical(overflowStateForFinalWire.detectedContextLimitModelKey ?? "") === piModelRefToCanonical(currentModelKeyForRecovery) ? overflowStateForFinalWire.detectedContextLimit : undefined;
|
|
32147
32960
|
const emergencyFailClosed = evaluateEmergencyFailClosed({
|
|
32148
|
-
usagePercentage:
|
|
32961
|
+
usagePercentage: emergencyUsagePercentage,
|
|
32149
32962
|
emergencyRecoveryArmed,
|
|
32150
32963
|
emergencyRecoveryOrigin,
|
|
32151
32964
|
foldMaterializedThisPass: postTransformResult.historianFoldMaterializedThisPass,
|
|
@@ -32361,9 +33174,9 @@ function formatTokens(value) {
|
|
|
32361
33174
|
return value.toLocaleString();
|
|
32362
33175
|
}
|
|
32363
33176
|
function evictExpiredUsageEntries(contextUsageMap) {
|
|
32364
|
-
const
|
|
33177
|
+
const now2 = Date.now();
|
|
32365
33178
|
for (const [sessionId, entry] of contextUsageMap) {
|
|
32366
|
-
if (
|
|
33179
|
+
if (now2 - entry.updatedAt > CONTEXT_USAGE_TTL_MS) {
|
|
32367
33180
|
contextUsageMap.delete(sessionId);
|
|
32368
33181
|
}
|
|
32369
33182
|
}
|
|
@@ -32453,6 +33266,14 @@ function createEventHandler2(deps) {
|
|
|
32453
33266
|
if (!detection.isOverflow) {
|
|
32454
33267
|
return;
|
|
32455
33268
|
}
|
|
33269
|
+
captureWindowReport({
|
|
33270
|
+
db: deps.db,
|
|
33271
|
+
sessionID: errInfo.sessionID,
|
|
33272
|
+
matchedPattern: detection.matchedPattern,
|
|
33273
|
+
reportedLimit: detection.reportedLimit,
|
|
33274
|
+
reportedLimitProvenance: detection.reportedLimitProvenance,
|
|
33275
|
+
error: errInfo.error
|
|
33276
|
+
});
|
|
32456
33277
|
const sessionMeta = getOrCreateSessionMeta(deps.db, errInfo.sessionID);
|
|
32457
33278
|
if (sessionMeta.isSubagent) {
|
|
32458
33279
|
if (typeof detection.reportedLimit === "number" && detection.reportedLimit > 0) {
|
|
@@ -32509,6 +33330,17 @@ function createEventHandler2(deps) {
|
|
|
32509
33330
|
if (detection.isOverflow) {
|
|
32510
33331
|
messageHadOverflowError = true;
|
|
32511
33332
|
try {
|
|
33333
|
+
captureWindowReport({
|
|
33334
|
+
db: deps.db,
|
|
33335
|
+
sessionID: info.sessionID,
|
|
33336
|
+
providerID: info.providerID,
|
|
33337
|
+
modelID: info.modelID,
|
|
33338
|
+
matchedPattern: detection.matchedPattern,
|
|
33339
|
+
reportedLimit: detection.reportedLimit,
|
|
33340
|
+
reportedLimitProvenance: detection.reportedLimitProvenance,
|
|
33341
|
+
attemptedTokens: (info.tokens?.input ?? 0) + (info.tokens?.cache?.read ?? 0) + (info.tokens?.cache?.write ?? 0),
|
|
33342
|
+
error: info.error
|
|
33343
|
+
});
|
|
32512
33344
|
const overflowModelKey = resolveModelKey(info.providerID, info.modelID);
|
|
32513
33345
|
const metaForOverflow = getOrCreateSessionMeta(deps.db, info.sessionID);
|
|
32514
33346
|
if (metaForOverflow.isSubagent) {
|
|
@@ -32532,7 +33364,7 @@ function createEventHandler2(deps) {
|
|
|
32532
33364
|
}
|
|
32533
33365
|
}
|
|
32534
33366
|
}
|
|
32535
|
-
const
|
|
33367
|
+
const now2 = Date.now();
|
|
32536
33368
|
const usageTokens = [
|
|
32537
33369
|
info.tokens?.input,
|
|
32538
33370
|
info.tokens?.cache?.read,
|
|
@@ -32557,7 +33389,7 @@ function createEventHandler2(deps) {
|
|
|
32557
33389
|
try {
|
|
32558
33390
|
const modelKey = resolveModelKey(info.providerID, info.modelID);
|
|
32559
33391
|
const updates = {
|
|
32560
|
-
lastResponseTime:
|
|
33392
|
+
lastResponseTime: now2
|
|
32561
33393
|
};
|
|
32562
33394
|
if (typeof deps.config.cache_ttl === "string") {
|
|
32563
33395
|
updates.cacheTtl = resolveCacheTtl(deps.config.cache_ttl, modelKey);
|
|
@@ -32603,8 +33435,8 @@ function createEventHandler2(deps) {
|
|
|
32603
33435
|
percentage,
|
|
32604
33436
|
inputTokens: totalInputTokens
|
|
32605
33437
|
},
|
|
32606
|
-
updatedAt:
|
|
32607
|
-
lastResponseTime:
|
|
33438
|
+
updatedAt: now2,
|
|
33439
|
+
lastResponseTime: now2,
|
|
32608
33440
|
hasUsageTokens: true
|
|
32609
33441
|
});
|
|
32610
33442
|
updates.lastContextPercentage = percentage;
|
|
@@ -32907,6 +33739,7 @@ async function runOneWrapupIteration(args) {
|
|
|
32907
33739
|
historianTwoPass: ctx.historianTwoPass,
|
|
32908
33740
|
memoryEnabled: ctx.memoryEnabled,
|
|
32909
33741
|
autoPromote: ctx.autoPromote,
|
|
33742
|
+
experimentalUserMemories: ctx.userMemoriesEnabled,
|
|
32910
33743
|
ensureProjectRegistered: ctx.ensureProjectRegistered,
|
|
32911
33744
|
getNotificationParams: () => ctx.getNotificationParams(sessionId),
|
|
32912
33745
|
preserveInjectionCacheUntilConsumed: true,
|
|
@@ -33129,16 +33962,16 @@ var MAX_CACHED_SESSIONS = 100;
|
|
|
33129
33962
|
var STALE_SNAPSHOT_AGE_MS = 5 * 60 * 1000;
|
|
33130
33963
|
var cache = new BoundedSessionMap(MAX_CACHED_SESSIONS);
|
|
33131
33964
|
function applyStickySnapshotCache(sessionId, fresh) {
|
|
33132
|
-
const
|
|
33965
|
+
const now2 = Date.now();
|
|
33133
33966
|
if (fresh.inputTokens > 0) {
|
|
33134
|
-
cache.set(sessionId, { snapshot: fresh, cachedAt:
|
|
33967
|
+
cache.set(sessionId, { snapshot: fresh, cachedAt: now2 });
|
|
33135
33968
|
return fresh;
|
|
33136
33969
|
}
|
|
33137
33970
|
const cached = cache.peek(sessionId);
|
|
33138
33971
|
if (!cached) {
|
|
33139
33972
|
return fresh;
|
|
33140
33973
|
}
|
|
33141
|
-
if (
|
|
33974
|
+
if (now2 - cached.cachedAt > STALE_SNAPSHOT_AGE_MS) {
|
|
33142
33975
|
cache.delete(sessionId);
|
|
33143
33976
|
return fresh;
|
|
33144
33977
|
}
|
|
@@ -33618,7 +34451,7 @@ function createSystemPromptHashHandler(deps) {
|
|
|
33618
34451
|
const skipGuidanceForDisabledSubagent = isSubagentSession2 && !ctxReduceCallable;
|
|
33619
34452
|
const inputModel = input.model;
|
|
33620
34453
|
const liveModel = inputModel?.providerID && inputModel.modelID ? { providerID: inputModel.providerID, modelID: inputModel.modelID } : deps.resolveModel?.(sessionId);
|
|
33621
|
-
const modelKey = liveModel?.providerID && liveModel.modelID ? `${liveModel.providerID}/${liveModel.modelID}` : undefined;
|
|
34454
|
+
const modelKey = liveModel?.providerID && liveModel.modelID ? piModelRefToCanonical(`${liveModel.providerID}/${liveModel.modelID}`) : undefined;
|
|
33622
34455
|
const promptSurface = guidanceEpochs.resolve(sessionId, deps.promptSurface, modelKey);
|
|
33623
34456
|
const fullPrompt = output.system.join(`
|
|
33624
34457
|
`);
|
|
@@ -33793,8 +34626,8 @@ async function maybeSendUpgradeReminder(deps, sessionId) {
|
|
|
33793
34626
|
remindedThisProcess.add(sessionId);
|
|
33794
34627
|
return;
|
|
33795
34628
|
}
|
|
33796
|
-
const
|
|
33797
|
-
if (meta.upgradeReminderCount >= MAX_UPGRADE_REMINDERS_PER_SESSION || meta.upgradeReminderLastSentAt !== null &&
|
|
34629
|
+
const now2 = Date.now();
|
|
34630
|
+
if (meta.upgradeReminderCount >= MAX_UPGRADE_REMINDERS_PER_SESSION || meta.upgradeReminderLastSentAt !== null && now2 - meta.upgradeReminderLastSentAt < UPGRADE_REMINDER_COOLDOWN_MS) {
|
|
33798
34631
|
remindedThisProcess.add(sessionId);
|
|
33799
34632
|
return;
|
|
33800
34633
|
}
|
|
@@ -33803,7 +34636,7 @@ async function maybeSendUpgradeReminder(deps, sessionId) {
|
|
|
33803
34636
|
const recordDelivery = () => {
|
|
33804
34637
|
try {
|
|
33805
34638
|
updateSessionMeta(deps.db, sessionId, {
|
|
33806
|
-
upgradeReminderLastSentAt:
|
|
34639
|
+
upgradeReminderLastSentAt: now2,
|
|
33807
34640
|
upgradeReminderCount: meta.upgradeReminderCount + 1
|
|
33808
34641
|
});
|
|
33809
34642
|
} catch {}
|
|
@@ -34217,7 +35050,15 @@ function createMagicContextHook(deps) {
|
|
|
34217
35050
|
const record = value && typeof value === "object" ? value : {};
|
|
34218
35051
|
const compartments = "compartments" in record && Array.isArray(record.compartments) ? record.compartments : [];
|
|
34219
35052
|
const maxSequence = "max_sequence" in record && typeof record.max_sequence === "number" ? record.max_sequence : afterSequence;
|
|
34220
|
-
|
|
35053
|
+
const compartmentCount = "compartment_count" in record && typeof record.compartment_count === "number" ? record.compartment_count : undefined;
|
|
35054
|
+
const revertEpoch = "revert_epoch" in record && typeof record.revert_epoch === "number" ? record.revert_epoch : undefined;
|
|
35055
|
+
return {
|
|
35056
|
+
max_sequence: maxSequence,
|
|
35057
|
+
compartments,
|
|
35058
|
+
...compartmentCount !== undefined ? { compartment_count: compartmentCount } : {},
|
|
35059
|
+
...revertEpoch !== undefined ? { revert_epoch: revertEpoch } : {},
|
|
35060
|
+
..."set_changed" in record && record.set_changed === true ? { set_changed: true } : {}
|
|
35061
|
+
};
|
|
34221
35062
|
}
|
|
34222
35063
|
};
|
|
34223
35064
|
return client;
|
|
@@ -34454,13 +35295,13 @@ function createMagicContextHook(deps) {
|
|
|
34454
35295
|
historianTwoPass: deps.config.historian?.two_pass === true,
|
|
34455
35296
|
liveModelBySession,
|
|
34456
35297
|
sessionDirectoryBySession,
|
|
34457
|
-
autoSearch:
|
|
34458
|
-
enabled: true,
|
|
34459
|
-
scoreThreshold: deps.config.memory?.auto_search.
|
|
34460
|
-
minPromptChars: deps.config.memory?.auto_search
|
|
35298
|
+
autoSearch: {
|
|
35299
|
+
enabled: deps.config.memory?.auto_search?.enabled ?? true,
|
|
35300
|
+
scoreThreshold: deps.config.memory?.auto_search?.score_threshold ?? 0.6,
|
|
35301
|
+
minPromptChars: deps.config.memory?.auto_search?.min_prompt_chars ?? 20,
|
|
34461
35302
|
directory: deps.directory,
|
|
34462
35303
|
ensureProjectRegistered: ensureProjectRegisteredFromOpenCodeDirectory
|
|
34463
|
-
}
|
|
35304
|
+
},
|
|
34464
35305
|
cavemanTextCompression: compactionOff ? undefined : deps.config.caveman_text_compression?.enabled === true ? {
|
|
34465
35306
|
enabled: true,
|
|
34466
35307
|
minChars: deps.config.caveman_text_compression.min_chars ?? 500
|
|
@@ -34468,6 +35309,7 @@ function createMagicContextHook(deps) {
|
|
|
34468
35309
|
maybeAutoEmbedSession,
|
|
34469
35310
|
transformMode: deps.config.transform_mode,
|
|
34470
35311
|
promptSurface: deps.config.prompt_surface,
|
|
35312
|
+
promptSurfaceRuntime: deps.promptSurfaceRuntime,
|
|
34471
35313
|
rustModeModuleClient,
|
|
34472
35314
|
tsAuthorityRecoveryModuleClient: authorityRecoveryModuleClient,
|
|
34473
35315
|
rustMemorySyncRequestedSessions,
|
|
@@ -34528,11 +35370,11 @@ function createMagicContextHook(deps) {
|
|
|
34528
35370
|
if (!dreaming || dreaming.disable === true) {
|
|
34529
35371
|
return;
|
|
34530
35372
|
}
|
|
34531
|
-
const
|
|
34532
|
-
if (
|
|
35373
|
+
const now2 = Date.now();
|
|
35374
|
+
if (now2 - lastScheduleCheckMs < DREAM_SCHEDULE_CHECK_INTERVAL_MS) {
|
|
34533
35375
|
return;
|
|
34534
35376
|
}
|
|
34535
|
-
lastScheduleCheckMs =
|
|
35377
|
+
lastScheduleCheckMs = now2;
|
|
34536
35378
|
const runtimeConfigs = buildDreamTaskRuntimeConfigs(dreaming, deps.config.language);
|
|
34537
35379
|
const executor = createDreamTaskExecutor({
|
|
34538
35380
|
client: deps.client,
|
|
@@ -34804,9 +35646,9 @@ async function createSessionHooksAsync(args) {
|
|
|
34804
35646
|
}
|
|
34805
35647
|
|
|
34806
35648
|
// src/plugin/instance-disposal.ts
|
|
34807
|
-
import
|
|
35649
|
+
import path6 from "node:path";
|
|
34808
35650
|
function isDisposedInstanceDirectory(ownDirectory, disposedDirectory) {
|
|
34809
|
-
return
|
|
35651
|
+
return path6.resolve(disposedDirectory) === path6.resolve(ownDirectory);
|
|
34810
35652
|
}
|
|
34811
35653
|
|
|
34812
35654
|
// src/plugin/messages-transform.ts
|
|
@@ -35432,6 +36274,7 @@ function buildStatusDetail(db, sessionId, directory, modelKey, config, liveSessi
|
|
|
35432
36274
|
compressionUsage: null,
|
|
35433
36275
|
toastDurationMs: 5000,
|
|
35434
36276
|
mural: undefined,
|
|
36277
|
+
loggerDiagnostics: getLoggerDiagnostics(),
|
|
35435
36278
|
storage_versions: {
|
|
35436
36279
|
context_db_schema_version: null,
|
|
35437
36280
|
plugin_supported_version: LATEST_SUPPORTED_VERSION
|
|
@@ -35470,6 +36313,10 @@ function buildStatusDetail(db, sessionId, directory, modelKey, config, liveSessi
|
|
|
35470
36313
|
const ops = db.prepare("SELECT tag_id, operation FROM pending_ops WHERE session_id = ? LIMIT 100").all(sessionId);
|
|
35471
36314
|
detail.pendingOps = ops.map((o) => ({ tagId: o.tag_id, operation: o.operation }));
|
|
35472
36315
|
} catch {}
|
|
36316
|
+
const modelSlash = modelKey?.indexOf("/") ?? -1;
|
|
36317
|
+
if (modelKey && modelSlash > 0) {
|
|
36318
|
+
detail.windowGeometry = resolveContextWindowGeometry(modelKey.slice(0, modelSlash), modelKey.slice(modelSlash + 1), { db, sessionID: sessionId });
|
|
36319
|
+
}
|
|
35473
36320
|
const contextLimitForTokens = base.contextLimit > 0 ? base.contextLimit : base.usagePercentage > 0 ? Math.round(base.inputTokens / (base.usagePercentage / 100)) : 0;
|
|
35474
36321
|
if (config) {
|
|
35475
36322
|
const pctCfg = config.execute_threshold_percentage;
|
|
@@ -35600,7 +36447,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
35600
36447
|
}
|
|
35601
36448
|
});
|
|
35602
36449
|
const buildManagedCtx = async (db) => {
|
|
35603
|
-
const { deriveHistorianChunkTokens: deriveHistorianChunkTokens2, resolveHistorianContextLimit: resolveHistorianContextLimit2 } = await import("./derive-budgets-
|
|
36450
|
+
const { deriveHistorianChunkTokens: deriveHistorianChunkTokens2, resolveHistorianContextLimit: resolveHistorianContextLimit2 } = await import("./derive-budgets-0f8xpyw2.js");
|
|
35604
36451
|
const { resolveFallbackChain: resolveFallbackChain2 } = await import("./resolve-fallbacks-5n5tvge1.js");
|
|
35605
36452
|
const { userMemoryCollectionEnabled: userMemoryCollectionEnabled2 } = await import("./task-config-gbp7r23g.js");
|
|
35606
36453
|
const DEFAULT_HISTORIAN_TIMEOUT_MS2 = 600000;
|
|
@@ -35627,8 +36474,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
35627
36474
|
const db = getDb();
|
|
35628
36475
|
if (!db)
|
|
35629
36476
|
return { ok: false, error: "db unavailable" };
|
|
35630
|
-
const { runManagedRecomp: runManagedRecomp2 } = await import("./recomp-orchestrator-
|
|
35631
|
-
const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-
|
|
36477
|
+
const { runManagedRecomp: runManagedRecomp2 } = await import("./recomp-orchestrator-c3ff16k7.js");
|
|
36478
|
+
const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-dxske5zm.js");
|
|
35632
36479
|
log(`[rpc] recomp requested for session ${sessionId}`);
|
|
35633
36480
|
const ctx = await buildManagedCtx(db);
|
|
35634
36481
|
runManagedRecomp2(ctx, sessionId).then((message) => {
|
|
@@ -35643,8 +36490,8 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
35643
36490
|
const db = getDb();
|
|
35644
36491
|
if (!db)
|
|
35645
36492
|
return { ok: false, error: "db unavailable" };
|
|
35646
|
-
const { runManagedUpgrade: runManagedUpgrade2 } = await import("./recomp-orchestrator-
|
|
35647
|
-
const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-
|
|
36493
|
+
const { runManagedUpgrade: runManagedUpgrade2 } = await import("./recomp-orchestrator-c3ff16k7.js");
|
|
36494
|
+
const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-dxske5zm.js");
|
|
35648
36495
|
log(`[rpc] session-upgrade requested for session ${sessionId}`);
|
|
35649
36496
|
const ctx = await buildManagedCtx(db);
|
|
35650
36497
|
runManagedUpgrade2(ctx, sessionId).then((message) => {
|
|
@@ -35660,7 +36507,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
35660
36507
|
if (!db)
|
|
35661
36508
|
return { ok: false, error: "db unavailable" };
|
|
35662
36509
|
try {
|
|
35663
|
-
const { updateSessionMeta: updateSessionMeta2 } = await import("./storage-meta-session-
|
|
36510
|
+
const { updateSessionMeta: updateSessionMeta2 } = await import("./storage-meta-session-mk4gsnke.js");
|
|
35664
36511
|
updateSessionMeta2(db, sessionId, { upgradeRemindedAt: Date.now() });
|
|
35665
36512
|
return { ok: true };
|
|
35666
36513
|
} catch (error) {
|
|
@@ -36059,13 +36906,22 @@ function normalizeCategory(category) {
|
|
|
36059
36906
|
const trimmed = category?.trim();
|
|
36060
36907
|
return trimmed ? trimmed : undefined;
|
|
36061
36908
|
}
|
|
36062
|
-
function
|
|
36909
|
+
function memoryAuthorityRefusal(args) {
|
|
36910
|
+
const readiness = "Rust memory authority is not ready.";
|
|
36911
|
+
if ((args.action === "write" || args.action === "update" || args.action === "merge") && typeof args.content === "string") {
|
|
36912
|
+
return `Error: ${readiness} Write REFUSED and NOT saved; RESEND after authority is ready.
|
|
36913
|
+
Content to resend:
|
|
36914
|
+
${args.content}`;
|
|
36915
|
+
}
|
|
36916
|
+
return `Error: ${readiness} Request REFUSED and NOT applied; RESEND after authority is ready.`;
|
|
36917
|
+
}
|
|
36918
|
+
function moduleMemoryText(response, args) {
|
|
36063
36919
|
let value = response;
|
|
36064
36920
|
if (value !== null && typeof value === "object" && "result" in value) {
|
|
36065
36921
|
value = value.result;
|
|
36066
36922
|
}
|
|
36067
36923
|
if (isRustAuthorityDrainingError(value)) {
|
|
36068
|
-
return
|
|
36924
|
+
return memoryAuthorityRefusal(args);
|
|
36069
36925
|
}
|
|
36070
36926
|
if (typeof value === "string")
|
|
36071
36927
|
return value;
|
|
@@ -36298,17 +37154,17 @@ function createCtxMemoryTool(deps) {
|
|
|
36298
37154
|
category: args.category,
|
|
36299
37155
|
ids: args.ids,
|
|
36300
37156
|
reason: args.reason
|
|
36301
|
-
}));
|
|
37157
|
+
}), args);
|
|
36302
37158
|
return text ?? "Error: Rust module returned an invalid ctx_memory response.";
|
|
36303
37159
|
} catch (error) {
|
|
36304
37160
|
if (isRustAuthorityDrainingError(error)) {
|
|
36305
|
-
return
|
|
37161
|
+
return memoryAuthorityRefusal(args);
|
|
36306
37162
|
}
|
|
36307
37163
|
return `Error: Rust module ctx_memory failed. ${error instanceof Error ? error.message : String(error)}`;
|
|
36308
37164
|
}
|
|
36309
37165
|
}
|
|
36310
37166
|
if (marker || authorityState === "PREPARING" || authorityState === "DRAINING") {
|
|
36311
|
-
return
|
|
37167
|
+
return memoryAuthorityRefusal(args);
|
|
36312
37168
|
}
|
|
36313
37169
|
}
|
|
36314
37170
|
const workspaceIdentitySet = resolveWorkspaceIdentitySet(deps.db, projectPath);
|
|
@@ -36618,13 +37474,13 @@ Example: ctx_note(action="write", content="Re-run the perf benchmark once the bo
|
|
|
36618
37474
|
import { tool as tool3 } from "@opencode-ai/plugin";
|
|
36619
37475
|
|
|
36620
37476
|
// src/features/magic-context/smart-notes/condition-compiler.ts
|
|
36621
|
-
import { existsSync as
|
|
37477
|
+
import { existsSync as existsSync12 } from "node:fs";
|
|
36622
37478
|
import { isAbsolute as isAbsolute4 } from "node:path";
|
|
36623
37479
|
|
|
36624
37480
|
// ../retina-local-fs/src/path-fence.ts
|
|
36625
37481
|
import { lstat as lstat2, readlink, realpath as realpath2 } from "node:fs/promises";
|
|
36626
37482
|
import { homedir as homedir4 } from "node:os";
|
|
36627
|
-
import { basename, dirname as
|
|
37483
|
+
import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join8, relative, resolve as resolve3, sep } from "node:path";
|
|
36628
37484
|
|
|
36629
37485
|
// ../retina-local-fs/src/errors.ts
|
|
36630
37486
|
class ProviderError extends Error {
|
|
@@ -36639,7 +37495,7 @@ class ProviderError extends Error {
|
|
|
36639
37495
|
// ../retina-local-fs/src/path-fence.ts
|
|
36640
37496
|
async function resolveAndFenceProviderPath(configuredPath, options) {
|
|
36641
37497
|
const { home, dataDirectory } = await resolveFenceRoots(options);
|
|
36642
|
-
const expanded = configuredPath.startsWith("~/") ?
|
|
37498
|
+
const expanded = configuredPath.startsWith("~/") ? join8(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
|
|
36643
37499
|
const absolute = isAbsolute3(expanded) ? resolve3(expanded) : resolve3(options.cwd ?? process.cwd(), expanded);
|
|
36644
37500
|
const canonical = await canonicalPath(absolute, options.allowMissing);
|
|
36645
37501
|
if (isFencedPath(canonical, home, dataDirectory)) {
|
|
@@ -36655,50 +37511,50 @@ async function resolveFenceRoots(options) {
|
|
|
36655
37511
|
} catch (error) {
|
|
36656
37512
|
throw fsError(configuredHomePath, error);
|
|
36657
37513
|
}
|
|
36658
|
-
const configuredDataDirectory = resolve3(options.dataDirectory ?? process.env.XDG_DATA_HOME ??
|
|
37514
|
+
const configuredDataDirectory = resolve3(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join8(home, ".local", "share"));
|
|
36659
37515
|
const dataDirectory = await canonicalPath(configuredDataDirectory, true);
|
|
36660
37516
|
return { home, dataDirectory };
|
|
36661
37517
|
}
|
|
36662
|
-
async function canonicalPath(
|
|
37518
|
+
async function canonicalPath(path7, allowMissing) {
|
|
36663
37519
|
try {
|
|
36664
|
-
return await realpath2(
|
|
37520
|
+
return await realpath2(path7);
|
|
36665
37521
|
} catch (error) {
|
|
36666
37522
|
if (!allowMissing || !isMissingError(error)) {
|
|
36667
|
-
throw fsError(
|
|
37523
|
+
throw fsError(path7, error);
|
|
36668
37524
|
}
|
|
36669
37525
|
const suffix = [];
|
|
36670
|
-
let candidate =
|
|
37526
|
+
let candidate = path7;
|
|
36671
37527
|
while (true) {
|
|
36672
37528
|
try {
|
|
36673
37529
|
const metadata = await lstat2(candidate);
|
|
36674
37530
|
if (metadata.isSymbolicLink()) {
|
|
36675
37531
|
const target = await readlink(candidate);
|
|
36676
|
-
const resolvedTarget = resolve3(
|
|
36677
|
-
return canonicalPath(
|
|
37532
|
+
const resolvedTarget = resolve3(dirname5(candidate), target);
|
|
37533
|
+
return canonicalPath(join8(resolvedTarget, ...suffix), true);
|
|
36678
37534
|
}
|
|
36679
37535
|
} catch (candidateError) {
|
|
36680
37536
|
if (!isMissingError(candidateError)) {
|
|
36681
|
-
throw fsError(
|
|
37537
|
+
throw fsError(path7, candidateError);
|
|
36682
37538
|
}
|
|
36683
37539
|
}
|
|
36684
|
-
const parent =
|
|
37540
|
+
const parent = dirname5(candidate);
|
|
36685
37541
|
if (parent === candidate) {
|
|
36686
|
-
throw fsError(
|
|
37542
|
+
throw fsError(path7, error);
|
|
36687
37543
|
}
|
|
36688
37544
|
suffix.unshift(basename(candidate));
|
|
36689
37545
|
candidate = parent;
|
|
36690
37546
|
try {
|
|
36691
|
-
return
|
|
37547
|
+
return join8(await realpath2(candidate), ...suffix);
|
|
36692
37548
|
} catch (parentError) {
|
|
36693
37549
|
if (!isMissingError(parentError)) {
|
|
36694
|
-
throw fsError(
|
|
37550
|
+
throw fsError(path7, parentError);
|
|
36695
37551
|
}
|
|
36696
37552
|
}
|
|
36697
37553
|
}
|
|
36698
37554
|
}
|
|
36699
37555
|
}
|
|
36700
|
-
function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ??
|
|
36701
|
-
const cortexkitRoot =
|
|
37556
|
+
function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join8(resolve3(homeDirectory), ".local", "share")) {
|
|
37557
|
+
const cortexkitRoot = join8(resolve3(dataDirectory), "cortexkit");
|
|
36702
37558
|
const relativeToCortexkit = relative(cortexkitRoot, canonicalPath2);
|
|
36703
37559
|
const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute3(relativeToCortexkit);
|
|
36704
37560
|
const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
|
|
@@ -36716,9 +37572,9 @@ function isFencedPath(canonicalPath2, homeDirectory, dataDirectory = process.env
|
|
|
36716
37572
|
const plexusStore = insideCortexkit && parts[0] === "plexus" && name.startsWith("store.db");
|
|
36717
37573
|
return inFencedRoot || fencedBasename || plexusStore;
|
|
36718
37574
|
}
|
|
36719
|
-
function fsError(
|
|
37575
|
+
function fsError(path7, error) {
|
|
36720
37576
|
const message = error instanceof Error ? error.message : String(error);
|
|
36721
|
-
return new ProviderError("unreadable_path", `Could not read ${
|
|
37577
|
+
return new ProviderError("unreadable_path", `Could not read ${path7}: ${message}`);
|
|
36722
37578
|
}
|
|
36723
37579
|
function isMissingError(error) {
|
|
36724
37580
|
return error !== null && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
|
|
@@ -36867,20 +37723,20 @@ async function compileSurfaceCondition(surfaceCondition, options) {
|
|
|
36867
37723
|
const parsed = parseCondition(surfaceCondition, options.projectPath);
|
|
36868
37724
|
if (parsed === null)
|
|
36869
37725
|
return { status: "plain" };
|
|
36870
|
-
const
|
|
36871
|
-
const resolvePath = options.resolvePath ?? (async (
|
|
36872
|
-
const resolved = await resolveAndFenceProviderPath(
|
|
37726
|
+
const now2 = (options.now ?? Date.now)();
|
|
37727
|
+
const resolvePath = options.resolvePath ?? (async (path7) => {
|
|
37728
|
+
const resolved = await resolveAndFenceProviderPath(path7, {
|
|
36873
37729
|
allowMissing: true,
|
|
36874
37730
|
homeDirectory: options.homeDirectory,
|
|
36875
37731
|
cwd: options.projectPath
|
|
36876
37732
|
});
|
|
36877
|
-
return { path: resolved, exists:
|
|
37733
|
+
return { path: resolved, exists: existsSync12(resolved) };
|
|
36878
37734
|
});
|
|
36879
37735
|
let predicates;
|
|
36880
37736
|
try {
|
|
36881
37737
|
predicates = [];
|
|
36882
37738
|
for (const predicate of parsed) {
|
|
36883
|
-
predicates.push(await resolvePredicate(predicate, resolvePath,
|
|
37739
|
+
predicates.push(await resolvePredicate(predicate, resolvePath, now2));
|
|
36884
37740
|
}
|
|
36885
37741
|
} catch (error) {
|
|
36886
37742
|
const code = error !== null && typeof error === "object" && "code" in error ? error.code : undefined;
|
|
@@ -36901,7 +37757,7 @@ async function compileSurfaceCondition(surfaceCondition, options) {
|
|
|
36901
37757
|
status: "compiled",
|
|
36902
37758
|
provider: RETINA_LOCAL_FS_PROVIDER,
|
|
36903
37759
|
config: validation.config,
|
|
36904
|
-
compiledAt:
|
|
37760
|
+
compiledAt: now2
|
|
36905
37761
|
};
|
|
36906
37762
|
}
|
|
36907
37763
|
function conditionCompileStorageFields(result) {
|
|
@@ -36947,13 +37803,13 @@ function parseCondition(surfaceCondition, projectPath) {
|
|
|
36947
37803
|
function parseAtomicCondition(text, projectPath) {
|
|
36948
37804
|
const fileContains = text.match(new RegExp(`^(?:when\\s+)?file\\s+(${VALUE})\\s+(no longer contains|contains)\\s+(${VALUE})$`, "i"));
|
|
36949
37805
|
if (fileContains) {
|
|
36950
|
-
const
|
|
37806
|
+
const path7 = unquote(fileContains[1]);
|
|
36951
37807
|
const needle = unquote(fileContains[3].trim());
|
|
36952
|
-
if (
|
|
37808
|
+
if (path7 === null || needle === null)
|
|
36953
37809
|
return null;
|
|
36954
37810
|
return {
|
|
36955
37811
|
kind: "file_contains",
|
|
36956
|
-
path:
|
|
37812
|
+
path: path7,
|
|
36957
37813
|
needle,
|
|
36958
37814
|
...fileContains[2].toLowerCase() === "no longer contains" ? { absent: true } : {}
|
|
36959
37815
|
};
|
|
@@ -36985,28 +37841,28 @@ function parseAtomicCondition(text, projectPath) {
|
|
|
36985
37841
|
}
|
|
36986
37842
|
const mtime = text.match(new RegExp(`^(?:when\\s+)?(?:file\\s+)?(${VALUE})\\s+(changes|is rebuilt|mtime moves)$`, "i"));
|
|
36987
37843
|
if (mtime) {
|
|
36988
|
-
const
|
|
36989
|
-
if (
|
|
37844
|
+
const path7 = unquote(mtime[1]);
|
|
37845
|
+
if (path7 === null)
|
|
36990
37846
|
return null;
|
|
36991
37847
|
return {
|
|
36992
37848
|
kind: "mtime_after",
|
|
36993
|
-
path:
|
|
37849
|
+
path: path7
|
|
36994
37850
|
};
|
|
36995
37851
|
}
|
|
36996
37852
|
const pathExists = text.match(new RegExp(`^(?:when\\s+)?(?:path\\s+)?(${VALUE})\\s+(exists|is gone)$`, "i"));
|
|
36997
37853
|
if (pathExists) {
|
|
36998
|
-
const
|
|
36999
|
-
if (
|
|
37854
|
+
const path7 = unquote(pathExists[1]);
|
|
37855
|
+
if (path7 === null)
|
|
37000
37856
|
return null;
|
|
37001
37857
|
return {
|
|
37002
37858
|
kind: "path_exists",
|
|
37003
|
-
path:
|
|
37859
|
+
path: path7,
|
|
37004
37860
|
...pathExists[2].toLowerCase() === "is gone" ? { gone: true } : {}
|
|
37005
37861
|
};
|
|
37006
37862
|
}
|
|
37007
37863
|
return null;
|
|
37008
37864
|
}
|
|
37009
|
-
async function resolvePredicate(predicate, resolvePath,
|
|
37865
|
+
async function resolvePredicate(predicate, resolvePath, now2) {
|
|
37010
37866
|
const configuredPath = "repo_path" in predicate ? predicate.repo_path : predicate.path;
|
|
37011
37867
|
const resolved = await resolvePath(configuredPath);
|
|
37012
37868
|
const sourceIsResolvable = isAbsolute4(configuredPath) || configuredPath === "~" || configuredPath.startsWith("~/");
|
|
@@ -37017,7 +37873,7 @@ async function resolvePredicate(predicate, resolvePath, now) {
|
|
|
37017
37873
|
case "path_exists":
|
|
37018
37874
|
return { ...predicate, path: resolved.path, ...audit };
|
|
37019
37875
|
case "mtime_after":
|
|
37020
|
-
return { kind: predicate.kind, path: resolved.path, since_ms:
|
|
37876
|
+
return { kind: predicate.kind, path: resolved.path, since_ms: now2, ...audit };
|
|
37021
37877
|
case "git_commit_after":
|
|
37022
37878
|
return { ...predicate, repo_path: resolved.path, ...audit };
|
|
37023
37879
|
case "git_tag_matching":
|
|
@@ -37207,13 +38063,22 @@ ${footer}` : ""}`);
|
|
|
37207
38063
|
}
|
|
37208
38064
|
return sections;
|
|
37209
38065
|
}
|
|
37210
|
-
function
|
|
38066
|
+
function noteAuthorityRefusal(args, action) {
|
|
38067
|
+
const readiness = "Rust notes authority is not ready.";
|
|
38068
|
+
if ((action === "write" || action === "update") && typeof args.content === "string") {
|
|
38069
|
+
return `Error: ${readiness} Write REFUSED and NOT saved; RESEND after authority is ready.
|
|
38070
|
+
Content to resend:
|
|
38071
|
+
${args.content}`;
|
|
38072
|
+
}
|
|
38073
|
+
return `Error: ${readiness} Request REFUSED and NOT applied; RESEND after authority is ready.`;
|
|
38074
|
+
}
|
|
38075
|
+
function moduleNoteText(response, args, action) {
|
|
37211
38076
|
let value = response;
|
|
37212
38077
|
if (value !== null && typeof value === "object" && "result" in value) {
|
|
37213
38078
|
value = value.result;
|
|
37214
38079
|
}
|
|
37215
38080
|
if (isRustAuthorityDrainingError(value)) {
|
|
37216
|
-
return
|
|
38081
|
+
return noteAuthorityRefusal(args, action);
|
|
37217
38082
|
}
|
|
37218
38083
|
if (typeof value === "string")
|
|
37219
38084
|
return value;
|
|
@@ -37264,6 +38129,8 @@ function createCtxNoteTool(deps) {
|
|
|
37264
38129
|
});
|
|
37265
38130
|
const sessionId = toolContext.sessionID;
|
|
37266
38131
|
const action = args.action ?? (args.content?.trim() ? "write" : "read");
|
|
38132
|
+
const wakePlaneActive = action === "write" && Boolean(args.surface_condition?.trim()) && await wakePlaneStatus() === "present";
|
|
38133
|
+
const surfaceCondition = wakePlaneActive ? undefined : args.surface_condition?.trim();
|
|
37267
38134
|
const projectIdentity = deps.resolveProjectPath?.(toolContext.directory);
|
|
37268
38135
|
const marker = projectIdentity ? getAuthorityManagedMarker(deps.db, projectIdentity) : null;
|
|
37269
38136
|
let notesAuthority = null;
|
|
@@ -37285,7 +38152,6 @@ function createCtxNoteTool(deps) {
|
|
|
37285
38152
|
if (!rustNote || !projectIdentity) {
|
|
37286
38153
|
return "Error: Rust notes authority is active, but this module transport does not support ctx_note.";
|
|
37287
38154
|
}
|
|
37288
|
-
const surfaceCondition = args.surface_condition?.trim();
|
|
37289
38155
|
let compilation;
|
|
37290
38156
|
if ((action === "write" || action === "update") && surfaceCondition) {
|
|
37291
38157
|
if (deps.rustToolBackends?.noteEvaluationAvailable?.(projectIdentity) !== true) {
|
|
@@ -37312,23 +38178,28 @@ function createCtxNoteTool(deps) {
|
|
|
37312
38178
|
noteId: args.note_id
|
|
37313
38179
|
};
|
|
37314
38180
|
try {
|
|
37315
|
-
const text = moduleNoteText(await rustNote(request2));
|
|
38181
|
+
const text = moduleNoteText(await rustNote(request2), args, action);
|
|
37316
38182
|
if (text === null) {
|
|
37317
38183
|
return "Error: Rust module returned an invalid ctx_note response.";
|
|
37318
38184
|
}
|
|
37319
|
-
if (
|
|
37320
|
-
return text
|
|
38185
|
+
if (text.startsWith("Error:"))
|
|
38186
|
+
return text;
|
|
38187
|
+
if (wakePlaneActive) {
|
|
38188
|
+
return `${text}
|
|
38189
|
+
wake plane active — create a scheduled wake instead; stored as a plain note.`;
|
|
37321
38190
|
}
|
|
38191
|
+
if (compilation)
|
|
38192
|
+
return text + conditionCompileReplySuffix(compilation);
|
|
37322
38193
|
return text;
|
|
37323
38194
|
} catch (error) {
|
|
37324
38195
|
if (isRustAuthorityDrainingError(error)) {
|
|
37325
|
-
return
|
|
38196
|
+
return noteAuthorityRefusal(args, action);
|
|
37326
38197
|
}
|
|
37327
38198
|
return `Error: Rust module ctx_note failed. ${error instanceof Error ? error.message : String(error)}`;
|
|
37328
38199
|
}
|
|
37329
38200
|
}
|
|
37330
38201
|
if (marker || notesAuthority === "PREPARING" || notesAuthority === "DRAINING") {
|
|
37331
|
-
return
|
|
38202
|
+
return noteAuthorityRefusal(args, action);
|
|
37332
38203
|
}
|
|
37333
38204
|
if (action === "write") {
|
|
37334
38205
|
const content = args.content?.trim();
|
|
@@ -37337,27 +38208,36 @@ function createCtxNoteTool(deps) {
|
|
|
37337
38208
|
}
|
|
37338
38209
|
const anchorOrdinal = captureAnchorOrdinal(deps.db, sessionId);
|
|
37339
38210
|
if (args.surface_condition?.trim()) {
|
|
38211
|
+
if (wakePlaneActive) {
|
|
38212
|
+
const note3 = addNote(deps.db, "session", {
|
|
38213
|
+
sessionId,
|
|
38214
|
+
content,
|
|
38215
|
+
anchorOrdinal
|
|
38216
|
+
});
|
|
38217
|
+
return `Saved session note #${note3.id}.
|
|
38218
|
+
wake plane active — create a scheduled wake instead; stored as a plain note.`;
|
|
38219
|
+
}
|
|
37340
38220
|
if (!deps.dreamerEnabled) {
|
|
37341
38221
|
return "Error: Smart notes require dreamer to be enabled. Enable dreamer in magic-context.jsonc to use surface_condition.";
|
|
37342
38222
|
}
|
|
37343
38223
|
if (!projectIdentity) {
|
|
37344
38224
|
return "Error: Could not resolve project identity for smart note.";
|
|
37345
38225
|
}
|
|
37346
|
-
const
|
|
37347
|
-
const compilation = await compileSurfaceCondition(
|
|
38226
|
+
const smartSurfaceCondition = args.surface_condition.trim();
|
|
38227
|
+
const compilation = await compileSurfaceCondition(smartSurfaceCondition, {
|
|
37348
38228
|
projectPath: toolContext.directory
|
|
37349
38229
|
});
|
|
37350
38230
|
const note2 = addNote(deps.db, "smart", {
|
|
37351
38231
|
content,
|
|
37352
38232
|
projectPath: projectIdentity,
|
|
37353
38233
|
sessionId,
|
|
37354
|
-
surfaceCondition,
|
|
38234
|
+
surfaceCondition: smartSurfaceCondition,
|
|
37355
38235
|
anchorOrdinal,
|
|
37356
38236
|
...conditionCompileStorageFields(compilation)
|
|
37357
38237
|
});
|
|
37358
38238
|
return `Created smart note #${note2.id}. Dreamer will evaluate the condition during nightly runs:
|
|
37359
38239
|
- Content: ${content}
|
|
37360
|
-
- Condition: ${
|
|
38240
|
+
- Condition: ${smartSurfaceCondition}${conditionCompileReplySuffix(compilation)}`;
|
|
37361
38241
|
}
|
|
37362
38242
|
const note = addNote(deps.db, "session", { sessionId, content, anchorOrdinal });
|
|
37363
38243
|
return `Saved session note #${note.id}.`;
|
|
@@ -37386,9 +38266,9 @@ function createCtxNoteTool(deps) {
|
|
|
37386
38266
|
updates.content = args.content.trim();
|
|
37387
38267
|
let compilation;
|
|
37388
38268
|
if (args.surface_condition?.trim()) {
|
|
37389
|
-
const
|
|
37390
|
-
updates.surfaceCondition =
|
|
37391
|
-
compilation = await compileSurfaceCondition(
|
|
38269
|
+
const surfaceCondition2 = args.surface_condition.trim();
|
|
38270
|
+
updates.surfaceCondition = surfaceCondition2;
|
|
38271
|
+
compilation = await compileSurfaceCondition(surfaceCondition2, {
|
|
37392
38272
|
projectPath: toolContext.directory
|
|
37393
38273
|
});
|
|
37394
38274
|
Object.assign(updates, conditionCompileStorageFields(compilation));
|
|
@@ -37609,9 +38489,9 @@ function createCtxReduceTool(deps) {
|
|
|
37609
38489
|
}
|
|
37610
38490
|
try {
|
|
37611
38491
|
deps.db.transaction(() => {
|
|
37612
|
-
const
|
|
38492
|
+
const now2 = Date.now();
|
|
37613
38493
|
for (const id of dropIds) {
|
|
37614
|
-
queuePendingOp(deps.db, sessionId, id, "drop",
|
|
38494
|
+
queuePendingOp(deps.db, sessionId, id, "drop", now2);
|
|
37615
38495
|
}
|
|
37616
38496
|
})();
|
|
37617
38497
|
} catch (error) {
|
|
@@ -37974,15 +38854,15 @@ function unregisterExitAbort(controller) {
|
|
|
37974
38854
|
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
37975
38855
|
import {
|
|
37976
38856
|
chmodSync,
|
|
37977
|
-
mkdirSync as
|
|
38857
|
+
mkdirSync as mkdirSync3,
|
|
37978
38858
|
readdirSync,
|
|
37979
38859
|
readFileSync as readFileSync6,
|
|
37980
|
-
renameSync as
|
|
37981
|
-
rmSync as
|
|
38860
|
+
renameSync as renameSync4,
|
|
38861
|
+
rmSync as rmSync3,
|
|
37982
38862
|
unlinkSync,
|
|
37983
38863
|
writeFileSync as writeFileSync4
|
|
37984
38864
|
} from "node:fs";
|
|
37985
|
-
import { dirname as
|
|
38865
|
+
import { dirname as dirname6 } from "node:path";
|
|
37986
38866
|
var MAX_BODY_BYTES = 1048576;
|
|
37987
38867
|
var WS_AUTH_TIMEOUT_MS = 5000;
|
|
37988
38868
|
var WS_CLOSE_UNAUTHORIZED = 4401;
|
|
@@ -38056,19 +38936,19 @@ class MagicContextRpcServer {
|
|
|
38056
38936
|
this.port = server.port ?? 0;
|
|
38057
38937
|
try {
|
|
38058
38938
|
this.warnIfOtherLiveInstance();
|
|
38059
|
-
const dir =
|
|
38939
|
+
const dir = dirname6(this.portFilePath);
|
|
38060
38940
|
const enforcePrivatePermissions = shouldEnforcePrivateStoragePermissions();
|
|
38061
38941
|
if (enforcePrivatePermissions) {
|
|
38062
|
-
|
|
38942
|
+
mkdirSync3(dir, { recursive: true, mode: 448 });
|
|
38063
38943
|
try {
|
|
38064
38944
|
chmodSync(dir, 448);
|
|
38065
38945
|
} catch {}
|
|
38066
38946
|
} else {
|
|
38067
|
-
|
|
38947
|
+
mkdirSync3(dir, { recursive: true });
|
|
38068
38948
|
}
|
|
38069
38949
|
const tmpPath = `${this.portFilePath}.tmp`;
|
|
38070
38950
|
try {
|
|
38071
|
-
|
|
38951
|
+
rmSync3(tmpPath, { force: true });
|
|
38072
38952
|
} catch {}
|
|
38073
38953
|
writeFileSync4(tmpPath, JSON.stringify({
|
|
38074
38954
|
port: this.port,
|
|
@@ -38077,7 +38957,7 @@ class MagicContextRpcServer {
|
|
|
38077
38957
|
token: this.token,
|
|
38078
38958
|
instance_id: this.instanceId
|
|
38079
38959
|
}), enforcePrivatePermissions ? { encoding: "utf-8", mode: 384 } : { encoding: "utf-8" });
|
|
38080
|
-
|
|
38960
|
+
renameSync4(tmpPath, this.portFilePath);
|
|
38081
38961
|
if (enforcePrivatePermissions) {
|
|
38082
38962
|
try {
|
|
38083
38963
|
chmodSync(this.portFilePath, 384);
|
|
@@ -38289,7 +39169,7 @@ var server = async (ctx) => {
|
|
|
38289
39169
|
`);
|
|
38290
39170
|
setTimeout(async () => {
|
|
38291
39171
|
try {
|
|
38292
|
-
const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-
|
|
39172
|
+
const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-dxske5zm.js");
|
|
38293
39173
|
const clientWithSessions = ctx.client;
|
|
38294
39174
|
const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
|
|
38295
39175
|
const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
|
|
@@ -38302,8 +39182,13 @@ var server = async (ctx) => {
|
|
|
38302
39182
|
}
|
|
38303
39183
|
let conflictResult = null;
|
|
38304
39184
|
if (pluginConfig.enabled) {
|
|
39185
|
+
const resolvedCompaction = await resolveCompactionForBoot(ctx.client);
|
|
39186
|
+
if (resolvedCompaction === null) {
|
|
39187
|
+
log("[magic-context] resolved-config fetch failed; using file-based compaction detection (the running server's resolved config may differ — `opencode debug config` is authoritative)");
|
|
39188
|
+
}
|
|
38305
39189
|
conflictResult = detectConflicts(ctx.directory, {
|
|
38306
|
-
compactionEnabled: isCompactionEnabled(pluginConfig)
|
|
39190
|
+
compactionEnabled: isCompactionEnabled(pluginConfig),
|
|
39191
|
+
resolvedCompaction: resolvedCompaction ?? undefined
|
|
38307
39192
|
});
|
|
38308
39193
|
if (conflictResult.hasConflict) {
|
|
38309
39194
|
pluginConfig.enabled = false;
|
|
@@ -38471,7 +39356,7 @@ var server = async (ctx) => {
|
|
|
38471
39356
|
{
|
|
38472
39357
|
const fence = getSchemaFenceRejection();
|
|
38473
39358
|
if (fence) {
|
|
38474
|
-
import("./conflict-warning-hook-
|
|
39359
|
+
import("./conflict-warning-hook-an4fxhwf.js").then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence));
|
|
38475
39360
|
}
|
|
38476
39361
|
}
|
|
38477
39362
|
if (conflictResult?.hasConflict) {
|
|
@@ -38492,7 +39377,7 @@ var server = async (ctx) => {
|
|
|
38492
39377
|
} = await import("./announcement-6c1g4es4.js");
|
|
38493
39378
|
if (shouldShowAnnouncement2()) {
|
|
38494
39379
|
setTimeout(() => {
|
|
38495
|
-
import("./conflict-warning-hook-
|
|
39380
|
+
import("./conflict-warning-hook-an4fxhwf.js").then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION2, ANNOUNCEMENT_FEATURES2, ANNOUNCEMENT_FOOTER2, markAnnouncementSeen2)).catch(() => {});
|
|
38496
39381
|
}, 8000);
|
|
38497
39382
|
}
|
|
38498
39383
|
} catch {}
|