@cortexkit/opencode-magic-context 0.39.0 → 0.40.1
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/README.md +20 -0
- package/dist/agents/permissions.d.ts +5 -3
- package/dist/agents/permissions.d.ts.map +1 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/profiles.d.ts +22 -0
- package/dist/config/profiles.d.ts.map +1 -0
- package/dist/config/project-security.d.ts +3 -0
- package/dist/config/project-security.d.ts.map +1 -1
- package/dist/config/schema/magic-context.d.ts +400 -0
- package/dist/config/schema/magic-context.d.ts.map +1 -1
- package/dist/features/magic-context/fail-closed-block.d.ts +11 -1
- package/dist/features/magic-context/fail-closed-block.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-failure.d.ts +11 -0
- package/dist/features/magic-context/memory/embedding-failure.d.ts.map +1 -0
- package/dist/features/magic-context/memory/embedding-local.d.ts +19 -0
- package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-openai.d.ts +5 -0
- package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-provider.d.ts +3 -0
- package/dist/features/magic-context/memory/embedding-provider.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts +2 -0
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/features/magic-context/storage-db.d.ts +1 -1
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
- package/dist/hooks/magic-context/format-embed-failure.d.ts +3 -0
- package/dist/hooks/magic-context/format-embed-failure.d.ts.map +1 -0
- package/dist/hooks/magic-context/inject-compartments.d.ts +4 -3
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
- package/dist/hooks/magic-context/strip-content.d.ts +6 -0
- package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
- package/dist/hooks/magic-context/temporal-awareness.d.ts +1 -1
- package/dist/hooks/magic-context/temporal-awareness.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +1 -0
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/{index-k2ts0wk1.js → index-x64cmpej.js} +507 -89
- package/dist/index.js +128 -166
- package/dist/plugin/hooks/create-session-hooks.d.ts +2 -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-2pncxee7.js → recomp-orchestrator-dtgww0f0.js} +1 -1
- package/dist/shared/rpc-types.d.ts +2 -0
- package/dist/shared/rpc-types.d.ts.map +1 -1
- package/dist/shared/rpc-utils.d.ts +12 -1
- package/dist/shared/rpc-utils.d.ts.map +1 -1
- package/dist/shared/status-detail-text.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 +2 -1
- package/src/agents/permissions.ts +14 -4
- package/src/config/index.test.ts +361 -2
- package/src/config/index.ts +29 -10
- package/src/config/profiles.ts +106 -0
- package/src/config/project-security.hostile-matrix.test.ts +9 -0
- package/src/config/project-security.test.ts +17 -0
- package/src/config/project-security.ts +10 -0
- package/src/config/schema/magic-context.test.ts +128 -0
- package/src/config/schema/magic-context.ts +89 -0
- package/src/shared/rpc-types.ts +2 -0
- package/src/shared/rpc-utils.test.ts +32 -0
- package/src/shared/rpc-utils.ts +38 -13
- package/src/shared/status-detail-text.test.ts +2 -0
- package/src/shared/status-detail-text.ts +1 -0
- package/src/tui/data/context-db.ts +1 -0
- package/src/tui-compiled/data/context-db.ts +1 -0
|
@@ -398,9 +398,163 @@ function buildPrimaryLanguageDirective(language) {
|
|
|
398
398
|
return `Use ${target} for your natural-language replies to the user unless the user explicitly asks for another language. Keep code, identifiers, file paths, commands, logs, and quoted text verbatim.`;
|
|
399
399
|
}
|
|
400
400
|
|
|
401
|
+
// src/shared/redaction.ts
|
|
402
|
+
import { homedir, userInfo } from "node:os";
|
|
403
|
+
function escapeRegex(value) {
|
|
404
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
405
|
+
}
|
|
406
|
+
var SECRET_WORDS = [
|
|
407
|
+
"key",
|
|
408
|
+
"token",
|
|
409
|
+
"secret",
|
|
410
|
+
"password",
|
|
411
|
+
"auth",
|
|
412
|
+
"authorization",
|
|
413
|
+
"bearer",
|
|
414
|
+
"credential"
|
|
415
|
+
];
|
|
416
|
+
var SECRET_SEGMENT_PATTERN = new RegExp(`^(?:${SECRET_WORDS.map((w) => `${w}s?`).join("|")})$`, "i");
|
|
417
|
+
var TRAILING_DESCRIPTORS = new Set(["id", "ids", "value", "values", "header", "headers"]);
|
|
418
|
+
function redactionTypeForKey(key) {
|
|
419
|
+
const normalized = key.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, "_");
|
|
420
|
+
const suffix = normalized.split(".").filter(Boolean).at(-1) ?? normalized;
|
|
421
|
+
return suffix || "secret";
|
|
422
|
+
}
|
|
423
|
+
function isNonSecretScalarValue(value) {
|
|
424
|
+
const v = value.trim();
|
|
425
|
+
if (v === "true" || v === "false" || v === "null" || v === "undefined")
|
|
426
|
+
return true;
|
|
427
|
+
return /^[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(v);
|
|
428
|
+
}
|
|
429
|
+
var SECRET_QUALIFIERS = new Set([
|
|
430
|
+
"api",
|
|
431
|
+
"access",
|
|
432
|
+
"private",
|
|
433
|
+
"client",
|
|
434
|
+
"auth",
|
|
435
|
+
"authorization",
|
|
436
|
+
"secret",
|
|
437
|
+
"bearer",
|
|
438
|
+
"session",
|
|
439
|
+
"refresh",
|
|
440
|
+
"service",
|
|
441
|
+
"x",
|
|
442
|
+
"openai",
|
|
443
|
+
"anthropic",
|
|
444
|
+
"google",
|
|
445
|
+
"github",
|
|
446
|
+
"huggingface",
|
|
447
|
+
"aws",
|
|
448
|
+
"azure"
|
|
449
|
+
]);
|
|
450
|
+
function sanitizePathString(value) {
|
|
451
|
+
const home = homedir();
|
|
452
|
+
const username = userInfo().username;
|
|
453
|
+
let sanitized = value;
|
|
454
|
+
if (home) {
|
|
455
|
+
sanitized = sanitized.replace(new RegExp(escapeRegex(home), "g"), "~");
|
|
456
|
+
}
|
|
457
|
+
sanitized = sanitized.replace(/\/Users\/[^/]+\//g, "/Users/<USER>/");
|
|
458
|
+
sanitized = sanitized.replace(/\/home\/[^/]+\//g, "/home/<USER>/");
|
|
459
|
+
sanitized = sanitized.replace(/C:\\Users\\[^\\]+\\/g, "C:\\Users\\<USER>\\");
|
|
460
|
+
if (username) {
|
|
461
|
+
sanitized = sanitized.replace(new RegExp(escapeRegex(username), "g"), "<USER>");
|
|
462
|
+
}
|
|
463
|
+
return sanitized;
|
|
464
|
+
}
|
|
465
|
+
var SECRET_TEXT_PATTERNS = [
|
|
466
|
+
{
|
|
467
|
+
pattern: /\bsk-ant-(?:api03-)?[A-Za-z0-9_-]{32,}/g,
|
|
468
|
+
replacement: "<ANTHROPIC_API_KEY_REDACTED>"
|
|
469
|
+
},
|
|
470
|
+
{
|
|
471
|
+
pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/g,
|
|
472
|
+
replacement: "<OPENAI_API_KEY_REDACTED>"
|
|
473
|
+
},
|
|
474
|
+
{
|
|
475
|
+
pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
476
|
+
replacement: "<GITHUB_PAT_REDACTED>"
|
|
477
|
+
},
|
|
478
|
+
{
|
|
479
|
+
pattern: /\b(?:gh[opsu]|ghr)_[A-Za-z0-9]{30,}/g,
|
|
480
|
+
replacement: "<GITHUB_TOKEN_REDACTED>"
|
|
481
|
+
},
|
|
482
|
+
{
|
|
483
|
+
pattern: /\bhf_[A-Za-z0-9]{30,}/g,
|
|
484
|
+
replacement: "<HUGGINGFACE_TOKEN_REDACTED>"
|
|
485
|
+
},
|
|
486
|
+
{
|
|
487
|
+
pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
|
|
488
|
+
replacement: "<AWS_ACCESS_KEY_ID_REDACTED>"
|
|
489
|
+
},
|
|
490
|
+
{
|
|
491
|
+
pattern: /\bxox[abprsuvc]-[A-Za-z0-9-]{10,}/g,
|
|
492
|
+
replacement: "<SLACK_TOKEN_REDACTED>"
|
|
493
|
+
},
|
|
494
|
+
{
|
|
495
|
+
pattern: /\bAIza[A-Za-z0-9_-]{35}\b/g,
|
|
496
|
+
replacement: "<GOOGLE_API_KEY_REDACTED>"
|
|
497
|
+
},
|
|
498
|
+
{
|
|
499
|
+
pattern: /\b(Authorization\s*:\s*Bearer\s+)([A-Za-z0-9._~+/=-]{8,})/gi,
|
|
500
|
+
replacement: (_full, prefix) => `${prefix}<REDACTED:bearer>`
|
|
501
|
+
},
|
|
502
|
+
{
|
|
503
|
+
pattern: /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,
|
|
504
|
+
replacement: "<JWT_REDACTED>"
|
|
505
|
+
},
|
|
506
|
+
{
|
|
507
|
+
pattern: /(["'])([^"']*(?:key|token|secret|password|auth|bearer|credential)[^"']*)\1(\s*:\s*)(["'])([^"']*)\4/gi,
|
|
508
|
+
replacement: (full, quote, key, separator, valueQuote, value) => isNonSecretScalarValue(value) ? full : `${quote}${key}${quote}${separator}${valueQuote}<REDACTED:${redactionTypeForKey(key)}>${valueQuote}`
|
|
509
|
+
},
|
|
510
|
+
{
|
|
511
|
+
pattern: /\b([A-Za-z0-9_.-]*(?:key|token|secret|password|auth|bearer|credential)[A-Za-z0-9_.-]*)\s*=\s*([^\s'"`]+)/gi,
|
|
512
|
+
replacement: (full, key, value) => isNonSecretScalarValue(value) ? full : `${key}=<REDACTED:${redactionTypeForKey(key)}>`
|
|
513
|
+
}
|
|
514
|
+
];
|
|
515
|
+
function redactSecretText(value) {
|
|
516
|
+
let redacted = value;
|
|
517
|
+
for (const { pattern, replacement } of SECRET_TEXT_PATTERNS) {
|
|
518
|
+
if (typeof replacement === "string") {
|
|
519
|
+
redacted = redacted.replace(pattern, replacement);
|
|
520
|
+
} else {
|
|
521
|
+
redacted = redacted.replace(pattern, replacement);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return redacted;
|
|
525
|
+
}
|
|
526
|
+
function sanitizeDiagnosticText(value) {
|
|
527
|
+
return redactSecretText(sanitizePathString(value));
|
|
528
|
+
}
|
|
529
|
+
var SHAREABILITY_SENSITIVE_PATTERNS = [
|
|
530
|
+
/\bC:\/Users\/[^/\s]+/i,
|
|
531
|
+
/(?:^|\s)~\/[^\s]+/,
|
|
532
|
+
/\b(?:api[_-]?key|secret|token|password|passwd|pwd|client[_-]?secret|access[_-]?key)\b\s*[:=]\s*\S+/i,
|
|
533
|
+
/\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\b/i,
|
|
534
|
+
/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,
|
|
535
|
+
/\b192\.168\.\d{1,3}\.\d{1,3}\b/,
|
|
536
|
+
/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/
|
|
537
|
+
];
|
|
538
|
+
function hasShareabilitySensitiveText(text) {
|
|
539
|
+
try {
|
|
540
|
+
if (sanitizeDiagnosticText(text) !== text)
|
|
541
|
+
return true;
|
|
542
|
+
return SHAREABILITY_SENSITIVE_PATTERNS.some((pattern) => pattern.test(text));
|
|
543
|
+
} catch {
|
|
544
|
+
return true;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
401
548
|
// src/features/magic-context/fail-closed-block.ts
|
|
402
549
|
var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
|
|
403
550
|
var FAIL_CLOSED_REPROBE_EVERY_N = 5;
|
|
551
|
+
function attachFailClosedBlockingProcessEvidence(process2, evidence) {
|
|
552
|
+
Object.defineProperties(process2, {
|
|
553
|
+
startTime: { configurable: true, value: evidence.startTime },
|
|
554
|
+
commandLine: { configurable: true, value: evidence.commandLine }
|
|
555
|
+
});
|
|
556
|
+
return process2;
|
|
557
|
+
}
|
|
404
558
|
|
|
405
559
|
class FailClosedBlockingError extends Error {
|
|
406
560
|
code = "FAIL_CLOSED_BLOCKING";
|
|
@@ -423,6 +577,7 @@ function isMagicContextHiddenAgentName(agent) {
|
|
|
423
577
|
return false;
|
|
424
578
|
}
|
|
425
579
|
var MAX_FORMATTED_BLOCKING_PROCESSES = 8;
|
|
580
|
+
var MAX_FORMATTED_COMMAND_LINE_LENGTH = 80;
|
|
426
581
|
function normalizeFailClosedProcessKind(process2) {
|
|
427
582
|
switch (process2.kind) {
|
|
428
583
|
case "OpenCode server":
|
|
@@ -445,13 +600,61 @@ function normalizeFailClosedProcessKind(process2) {
|
|
|
445
600
|
return "process";
|
|
446
601
|
}
|
|
447
602
|
}
|
|
603
|
+
function formatFailClosedProcessStartTime(startTime) {
|
|
604
|
+
if (!Number.isFinite(startTime) || startTime <= 0)
|
|
605
|
+
return "unverified";
|
|
606
|
+
try {
|
|
607
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
608
|
+
day: "numeric",
|
|
609
|
+
hour: "2-digit",
|
|
610
|
+
minute: "2-digit",
|
|
611
|
+
month: "short",
|
|
612
|
+
hour12: false
|
|
613
|
+
}).formatToParts(new Date(startTime));
|
|
614
|
+
const values = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
|
|
615
|
+
if (!values.month || !values.day || !values.hour || !values.minute)
|
|
616
|
+
return "unverified";
|
|
617
|
+
return `${values.month} ${values.day} ${values.hour}:${values.minute}`;
|
|
618
|
+
} catch {
|
|
619
|
+
return "unverified";
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
function formatFailClosedCommandLine(commandLine) {
|
|
623
|
+
if (typeof commandLine !== "string" || commandLine.trim().length === 0)
|
|
624
|
+
return "unverified";
|
|
625
|
+
try {
|
|
626
|
+
const normalized = commandLine.replaceAll("\x00", " ").replace(/\s+/g, " ").trim();
|
|
627
|
+
if (normalized.length === 0)
|
|
628
|
+
return "unverified";
|
|
629
|
+
const sanitized = sanitizeDiagnosticText(normalized).trim();
|
|
630
|
+
if (sanitized.length === 0)
|
|
631
|
+
return "unverified";
|
|
632
|
+
return sanitized.length > MAX_FORMATTED_COMMAND_LINE_LENGTH ? `${sanitized.slice(0, MAX_FORMATTED_COMMAND_LINE_LENGTH - 3)}...` : sanitized;
|
|
633
|
+
} catch {
|
|
634
|
+
return "unverified";
|
|
635
|
+
}
|
|
636
|
+
}
|
|
448
637
|
function formatFailClosedBlockingProcesses(processes) {
|
|
449
638
|
const uniqueProcesses = new Map;
|
|
450
639
|
for (const process2 of processes) {
|
|
451
640
|
if (!Number.isInteger(process2.pid) || process2.pid <= 0)
|
|
452
641
|
continue;
|
|
453
|
-
const
|
|
454
|
-
|
|
642
|
+
const candidate = {
|
|
643
|
+
kind: normalizeFailClosedProcessKind(process2),
|
|
644
|
+
pid: process2.pid,
|
|
645
|
+
startTime: process2.startTime,
|
|
646
|
+
commandLine: process2.commandLine
|
|
647
|
+
};
|
|
648
|
+
const previous = uniqueProcesses.get(process2.pid);
|
|
649
|
+
if (!previous || previous.kind === "process" && candidate.kind !== "process") {
|
|
650
|
+
uniqueProcesses.set(process2.pid, candidate);
|
|
651
|
+
} else {
|
|
652
|
+
uniqueProcesses.set(process2.pid, {
|
|
653
|
+
...previous,
|
|
654
|
+
startTime: previous.startTime ?? candidate.startTime,
|
|
655
|
+
commandLine: previous.commandLine ?? candidate.commandLine
|
|
656
|
+
});
|
|
657
|
+
}
|
|
455
658
|
}
|
|
456
659
|
const entries = [...uniqueProcesses.values()];
|
|
457
660
|
const visible = entries.slice(0, MAX_FORMATTED_BLOCKING_PROCESSES);
|
|
@@ -461,10 +664,12 @@ function formatFailClosedBlockingProcesses(processes) {
|
|
|
461
664
|
rendered.push(`${omitted} more blocking process(es)`);
|
|
462
665
|
if (rendered.length === 0)
|
|
463
666
|
return "a live process";
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
return `${
|
|
667
|
+
const summary = rendered.length === 1 ? rendered[0] : `${rendered.slice(0, -1).join(", ")}, and ${rendered.at(-1)}`;
|
|
668
|
+
const evidence = entries.map(({ kind, pid, startTime, commandLine }) => `- PID ${pid}: ${kind}, started ${formatFailClosedProcessStartTime(startTime)}, cmd: ${formatFailClosedCommandLine(commandLine)}`).join(`
|
|
669
|
+
`);
|
|
670
|
+
return `${summary}
|
|
671
|
+
Blocking process evidence:
|
|
672
|
+
${evidence}`;
|
|
468
673
|
}
|
|
469
674
|
function formatFailClosedBlockingMessage(reason) {
|
|
470
675
|
if (reason.kind === "migration_guard") {
|
|
@@ -687,6 +892,17 @@ function readPsProcessStartTime(pid) {
|
|
|
687
892
|
return null;
|
|
688
893
|
}
|
|
689
894
|
}
|
|
895
|
+
function readProcessStartTime(pid) {
|
|
896
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
897
|
+
return null;
|
|
898
|
+
return rpcIdentityPlatform === "linux" ? readLinuxProcessStartTime(pid) : rpcIdentityPlatform === "win32" ? null : readPsProcessStartTime(pid);
|
|
899
|
+
}
|
|
900
|
+
function readProcessProbeEvidence(pid) {
|
|
901
|
+
return {
|
|
902
|
+
startTime: readProcessStartTime(pid),
|
|
903
|
+
commandLine: readProcessCommand(pid)
|
|
904
|
+
};
|
|
905
|
+
}
|
|
690
906
|
function parseCsvLine(line) {
|
|
691
907
|
const fields = [];
|
|
692
908
|
let field = "";
|
|
@@ -819,16 +1035,16 @@ function commandLooksLikeOpenCode(command) {
|
|
|
819
1035
|
const normalized = command.toLowerCase();
|
|
820
1036
|
return OPEN_CODE_COMMAND_MARKERS.some((marker) => normalized.includes(marker));
|
|
821
1037
|
}
|
|
822
|
-
function isPidIdentityPlausible(record) {
|
|
1038
|
+
function isPidIdentityPlausible(record, evidence) {
|
|
823
1039
|
if (!Number.isInteger(record.pid) || record.pid <= 0)
|
|
824
1040
|
return "implausible";
|
|
825
1041
|
if (Number.isFinite(record.started_at) && record.started_at > 0) {
|
|
826
|
-
const processStartTime =
|
|
1042
|
+
const processStartTime = evidence ? evidence.startTime : readProcessStartTime(record.pid);
|
|
827
1043
|
if (processStartTime === null)
|
|
828
1044
|
return "inconclusive";
|
|
829
1045
|
return processStartTime <= record.started_at + RPC_IDENTITY_SKEW_TOLERANCE_MS ? "plausible" : "implausible";
|
|
830
1046
|
}
|
|
831
|
-
const command = rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : rpcIdentityPlatform === "win32" ? readWindowsProcess(record.pid).command ?? null : readPsProcessCommand(record.pid);
|
|
1047
|
+
const command = evidence ? evidence.commandLine : rpcIdentityPlatform === "linux" ? readLinuxProcessCommand(record.pid) : rpcIdentityPlatform === "win32" ? readWindowsProcess(record.pid).command ?? null : readPsProcessCommand(record.pid);
|
|
832
1048
|
if (command === null)
|
|
833
1049
|
return "inconclusive";
|
|
834
1050
|
return commandLooksLikeOpenCode(command) ? "plausible" : "implausible";
|
|
@@ -2407,7 +2623,7 @@ var CATEGORY_DEFAULT_TTL = {
|
|
|
2407
2623
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
2408
2624
|
import { createHash as createHash3 } from "node:crypto";
|
|
2409
2625
|
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
2410
|
-
import { homedir } from "node:os";
|
|
2626
|
+
import { homedir as homedir2 } from "node:os";
|
|
2411
2627
|
import path from "node:path";
|
|
2412
2628
|
var GIT_TIMEOUT_MS = 5000;
|
|
2413
2629
|
var TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
|
|
@@ -2421,7 +2637,7 @@ var dubiousOwnershipLoggedDirectories = new Set;
|
|
|
2421
2637
|
var dubiousOwnershipWarnedDirectories = new Set;
|
|
2422
2638
|
var transientGitIdentityReuseLoggedDirectories = new Set;
|
|
2423
2639
|
var execFileSyncForIdentity = execFileSync2;
|
|
2424
|
-
var userHomeDirectoryForIdentity = () =>
|
|
2640
|
+
var userHomeDirectoryForIdentity = () => homedir2();
|
|
2425
2641
|
var nowMs = () => Date.now();
|
|
2426
2642
|
|
|
2427
2643
|
class ProjectIdentityError extends Error {
|
|
@@ -5308,7 +5524,7 @@ import { createHash as createHash5 } from "node:crypto";
|
|
|
5308
5524
|
// src/hooks/magic-context/read-session-formatting.ts
|
|
5309
5525
|
import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
5310
5526
|
import { createRequire } from "node:module";
|
|
5311
|
-
import { homedir as
|
|
5527
|
+
import { homedir as homedir3 } from "node:os";
|
|
5312
5528
|
import { dirname, join as join2, resolve } from "node:path";
|
|
5313
5529
|
import { pathToFileURL } from "node:url";
|
|
5314
5530
|
|
|
@@ -5425,7 +5641,7 @@ var tokenizerLoadPromise;
|
|
|
5425
5641
|
var tokenizerWarningSent = false;
|
|
5426
5642
|
function tokenizerPackageRoots() {
|
|
5427
5643
|
const cwd = process.cwd();
|
|
5428
|
-
const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(
|
|
5644
|
+
const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(homedir3(), ".cache"), "opencode");
|
|
5429
5645
|
const roots = [cwd, openCodeCache];
|
|
5430
5646
|
const candidates = [];
|
|
5431
5647
|
for (const root of roots) {
|
|
@@ -6159,8 +6375,8 @@ function classifyDiscoveryRecordKind(record) {
|
|
|
6159
6375
|
}
|
|
6160
6376
|
return null;
|
|
6161
6377
|
}
|
|
6162
|
-
function classifyRpcProcess(record) {
|
|
6163
|
-
return classifyDiscoveryRecordKind(record) ?? classifyProcessKind(
|
|
6378
|
+
function classifyRpcProcess(record, commandLine) {
|
|
6379
|
+
return classifyDiscoveryRecordKind(record) ?? classifyProcessKind(commandLine === undefined ? readProcessProbeEvidence(record.pid).commandLine : commandLine);
|
|
6164
6380
|
}
|
|
6165
6381
|
function classifyJunkDiscovery(portFile, raw, staleFiles) {
|
|
6166
6382
|
let mtimeMs;
|
|
@@ -6237,18 +6453,23 @@ function inspectRpcServerDiscovery(storageDir) {
|
|
|
6237
6453
|
continue;
|
|
6238
6454
|
}
|
|
6239
6455
|
const liveness = isPidAlive(record.pid);
|
|
6240
|
-
|
|
6241
|
-
|
|
6456
|
+
if (liveness === "dead") {
|
|
6457
|
+
staleFiles.push(portFile);
|
|
6458
|
+
continue;
|
|
6459
|
+
}
|
|
6460
|
+
const evidence = readProcessProbeEvidence(record.pid);
|
|
6461
|
+
const identity = isPidIdentityPlausible(record, evidence);
|
|
6462
|
+
if (identity === "plausible") {
|
|
6242
6463
|
pids.add(record.pid);
|
|
6243
|
-
const detected = {
|
|
6244
|
-
kind: classifyRpcProcess(record),
|
|
6464
|
+
const detected = attachFailClosedBlockingProcessEvidence({
|
|
6465
|
+
kind: classifyRpcProcess(record, evidence.commandLine),
|
|
6245
6466
|
pid: record.pid
|
|
6246
|
-
};
|
|
6467
|
+
}, evidence);
|
|
6247
6468
|
const previous = processByPid.get(record.pid);
|
|
6248
6469
|
if (!previous || previous.kind === "process" && detected.kind !== "process") {
|
|
6249
6470
|
processByPid.set(record.pid, detected);
|
|
6250
6471
|
}
|
|
6251
|
-
} else if (
|
|
6472
|
+
} else if (identity === "implausible") {
|
|
6252
6473
|
staleFiles.push(portFile);
|
|
6253
6474
|
} else {
|
|
6254
6475
|
inconclusivePids.add(record.pid);
|
|
@@ -6281,6 +6502,9 @@ function inspectRpcServerDiscovery(storageDir) {
|
|
|
6281
6502
|
}
|
|
6282
6503
|
return { state: "stale", serverPids: [], staleFiles };
|
|
6283
6504
|
}
|
|
6505
|
+
function createPiBlockingProcess(pid) {
|
|
6506
|
+
return attachFailClosedBlockingProcessEvidence({ kind: "Pi", pid }, readProcessProbeEvidence(pid));
|
|
6507
|
+
}
|
|
6284
6508
|
function formatInconclusiveOpenCodeMigrationWarning(dbPath, pids) {
|
|
6285
6509
|
return `[magic-context] storage warning: continuing migration for ${dbPath}; OpenCode server PID ${pids.join(", ")} was not confirmed because its liveness or identity check could not run. This commonly means an OS sandbox denied kill(0) or ps. No live OpenCode server was confirmed.`;
|
|
6286
6510
|
}
|
|
@@ -6322,10 +6546,7 @@ function enforceMigrationOnOpenGuard(db, dbPath, dbDir, latestSupportedVersion)
|
|
|
6322
6546
|
const piDiscovery = inspectLivePiProcesses();
|
|
6323
6547
|
const piPids = migrationBlockingPiPids(dbPath, discovery, piDiscovery.processIds);
|
|
6324
6548
|
const serverProcesses = discovery.serverProcesses ?? (discovery.state === "live" ? discovery.serverPids.map((pid) => ({ kind: "process", pid })) : []);
|
|
6325
|
-
const blockingProcesses = [
|
|
6326
|
-
...serverProcesses,
|
|
6327
|
-
...piPids.map((pid) => ({ kind: "Pi", pid }))
|
|
6328
|
-
];
|
|
6549
|
+
const blockingProcesses = [...serverProcesses, ...piPids.map(createPiBlockingProcess)];
|
|
6329
6550
|
if ((discovery.state === "absent" || discovery.state === "stale" || discovery.state === "inconclusive") && piPids.length === 0) {
|
|
6330
6551
|
lastMigrationOnOpenRefusal = null;
|
|
6331
6552
|
logInconclusiveMigrationProbes(dbPath, discovery, piDiscovery.state);
|
|
@@ -6930,8 +7151,6 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
6930
7151
|
updated_at INTEGER NOT NULL,
|
|
6931
7152
|
harness TEXT NOT NULL DEFAULT 'opencode'
|
|
6932
7153
|
);
|
|
6933
|
-
CREATE INDEX IF NOT EXISTS idx_message_history_index_orphan_sweep
|
|
6934
|
-
ON message_history_index(harness, session_id, updated_at);
|
|
6935
7154
|
|
|
6936
7155
|
CREATE TABLE IF NOT EXISTS message_history_source (
|
|
6937
7156
|
session_id TEXT NOT NULL,
|
|
@@ -7518,6 +7737,10 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
7518
7737
|
ensureColumn(db, "recomp_compartments", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
|
|
7519
7738
|
ensureColumn(db, "recomp_facts", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
|
|
7520
7739
|
ensureColumn(db, "message_history_index", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
|
|
7740
|
+
db.exec(`
|
|
7741
|
+
CREATE INDEX IF NOT EXISTS idx_message_history_index_orphan_sweep
|
|
7742
|
+
ON message_history_index(harness, session_id, updated_at);
|
|
7743
|
+
`);
|
|
7521
7744
|
ensureColumn(db, "workspaces", "share_categories", `TEXT NOT NULL DEFAULT '["CONSTRAINTS"]'`);
|
|
7522
7745
|
}
|
|
7523
7746
|
var CHANNEL2_CLAIM_TTL_MS = 10 * 60000;
|
|
@@ -14380,15 +14603,15 @@ import {
|
|
|
14380
14603
|
unlinkSync as unlinkSync2,
|
|
14381
14604
|
writeFileSync
|
|
14382
14605
|
} from "node:fs";
|
|
14383
|
-
import { homedir as
|
|
14606
|
+
import { homedir as homedir4 } from "node:os";
|
|
14384
14607
|
import { basename as basename2, dirname as dirname3, isAbsolute, join as join5 } from "node:path";
|
|
14385
14608
|
var CONFIG_FILE_BASENAME = "magic-context";
|
|
14386
14609
|
var MOVED_MARKER_SUFFIX = ".MOVED_READPLEASE";
|
|
14387
14610
|
function homeDir() {
|
|
14388
14611
|
if (process.platform === "win32") {
|
|
14389
|
-
return process.env.USERPROFILE || process.env.HOME ||
|
|
14612
|
+
return process.env.USERPROFILE || process.env.HOME || homedir4();
|
|
14390
14613
|
}
|
|
14391
|
-
return process.env.HOME ||
|
|
14614
|
+
return process.env.HOME || homedir4();
|
|
14392
14615
|
}
|
|
14393
14616
|
function configHome() {
|
|
14394
14617
|
const xdg = process.env.XDG_CONFIG_HOME;
|
|
@@ -16927,7 +17150,7 @@ function countSessionCompartmentEmbedCoverage(db, projectPath, sessionId, modelI
|
|
|
16927
17150
|
import { createHash as createHash14, randomUUID as randomUUID2 } from "node:crypto";
|
|
16928
17151
|
|
|
16929
17152
|
// src/config/schema/magic-context.ts
|
|
16930
|
-
import { homedir as
|
|
17153
|
+
import { homedir as homedir5 } from "node:os";
|
|
16931
17154
|
|
|
16932
17155
|
// ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
|
|
16933
17156
|
var exports_external = {};
|
|
@@ -17554,7 +17777,7 @@ __export(exports_util, {
|
|
|
17554
17777
|
createTransparentProxy: () => createTransparentProxy,
|
|
17555
17778
|
defineLazy: () => defineLazy,
|
|
17556
17779
|
esc: () => esc,
|
|
17557
|
-
escapeRegex: () =>
|
|
17780
|
+
escapeRegex: () => escapeRegex2,
|
|
17558
17781
|
explicitlyAborted: () => explicitlyAborted,
|
|
17559
17782
|
extend: () => extend,
|
|
17560
17783
|
finalizeIssue: () => finalizeIssue,
|
|
@@ -17831,7 +18054,7 @@ var primitiveTypes = /* @__PURE__ */ new Set([
|
|
|
17831
18054
|
"symbol",
|
|
17832
18055
|
"undefined"
|
|
17833
18056
|
]);
|
|
17834
|
-
function
|
|
18057
|
+
function escapeRegex2(str) {
|
|
17835
18058
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
17836
18059
|
}
|
|
17837
18060
|
function clone(inst, def, params) {
|
|
@@ -18541,7 +18764,7 @@ function emoji() {
|
|
|
18541
18764
|
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
|
|
18542
18765
|
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
|
|
18543
18766
|
var mac = (delimiter) => {
|
|
18544
|
-
const escapedDelim =
|
|
18767
|
+
const escapedDelim = escapeRegex2(delimiter ?? ":");
|
|
18545
18768
|
return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
|
|
18546
18769
|
};
|
|
18547
18770
|
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
|
|
@@ -19042,7 +19265,7 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins
|
|
|
19042
19265
|
});
|
|
19043
19266
|
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
|
|
19044
19267
|
$ZodCheck.init(inst, def);
|
|
19045
|
-
const escapedRegex =
|
|
19268
|
+
const escapedRegex = escapeRegex2(def.includes);
|
|
19046
19269
|
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
|
|
19047
19270
|
def.pattern = pattern;
|
|
19048
19271
|
inst._zod.onattach.push((inst2) => {
|
|
@@ -19066,7 +19289,7 @@ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst,
|
|
|
19066
19289
|
});
|
|
19067
19290
|
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
|
|
19068
19291
|
$ZodCheck.init(inst, def);
|
|
19069
|
-
const pattern = new RegExp(`^${
|
|
19292
|
+
const pattern = new RegExp(`^${escapeRegex2(def.prefix)}.*`);
|
|
19070
19293
|
def.pattern ?? (def.pattern = pattern);
|
|
19071
19294
|
inst._zod.onattach.push((inst2) => {
|
|
19072
19295
|
const bag = inst2._zod.bag;
|
|
@@ -19089,7 +19312,7 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i
|
|
|
19089
19312
|
});
|
|
19090
19313
|
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
|
|
19091
19314
|
$ZodCheck.init(inst, def);
|
|
19092
|
-
const pattern = new RegExp(`.*${
|
|
19315
|
+
const pattern = new RegExp(`.*${escapeRegex2(def.suffix)}$`);
|
|
19093
19316
|
def.pattern ?? (def.pattern = pattern);
|
|
19094
19317
|
inst._zod.onattach.push((inst2) => {
|
|
19095
19318
|
const bag = inst2._zod.bag;
|
|
@@ -20736,7 +20959,7 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
|
|
|
20736
20959
|
const values = getEnumValues(def.entries);
|
|
20737
20960
|
const valuesSet = new Set(values);
|
|
20738
20961
|
inst._zod.values = valuesSet;
|
|
20739
|
-
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ?
|
|
20962
|
+
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex2(o) : o.toString()).join("|")})$`);
|
|
20740
20963
|
inst._zod.parse = (payload, _ctx) => {
|
|
20741
20964
|
const input = payload.value;
|
|
20742
20965
|
if (valuesSet.has(input)) {
|
|
@@ -20758,7 +20981,7 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
|
|
|
20758
20981
|
}
|
|
20759
20982
|
const values = new Set(def.values);
|
|
20760
20983
|
inst._zod.values = values;
|
|
20761
|
-
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ?
|
|
20984
|
+
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex2(o) : o ? escapeRegex2(o.toString()) : String(o)).join("|")})$`);
|
|
20762
20985
|
inst._zod.parse = (payload, _ctx) => {
|
|
20763
20986
|
const input = payload.value;
|
|
20764
20987
|
if (values.has(input)) {
|
|
@@ -21123,7 +21346,7 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i
|
|
|
21123
21346
|
const end = source.endsWith("$") ? source.length - 1 : source.length;
|
|
21124
21347
|
regexParts.push(source.slice(start, end));
|
|
21125
21348
|
} else if (part === null || primitiveTypes.has(typeof part)) {
|
|
21126
|
-
regexParts.push(
|
|
21349
|
+
regexParts.push(escapeRegex2(`${part}`));
|
|
21127
21350
|
} else {
|
|
21128
21351
|
throw new Error(`Invalid template literal part: ${part}`);
|
|
21129
21352
|
}
|
|
@@ -31492,6 +31715,37 @@ var DreamerPiHarnessBlockSchema = exports_external.object({
|
|
|
31492
31715
|
thinking_level: PiThinkingLevelSchema.describe("Pi thinking level for the primary entry when it declares none. Fallback entries declare thinking levels per-entry."),
|
|
31493
31716
|
tasks: exports_external.record(exports_external.string(), PiTaskExecutionSchema).optional().describe("Pi task execution overrides. Each named task accepts only model, fallback_models, thinking_level, and timeout_minutes.")
|
|
31494
31717
|
}).strict().describe("Strict Pi dreamer model-resolution block. It accepts no OpenCode vocabulary.");
|
|
31718
|
+
var ProfileOpenCodeModelBlockSchema = exports_external.object({
|
|
31719
|
+
model: OcEntrySchema.optional().describe("Primary OpenCode model entry."),
|
|
31720
|
+
fallback_models: exports_external.array(OcEntrySchema).optional().describe("Ordered fallback OpenCode model entries."),
|
|
31721
|
+
variant: exports_external.string().optional().describe("OpenCode reasoning variant for the primary model entry.")
|
|
31722
|
+
}).strict().describe("Strict profile-only OpenCode model-selection block.");
|
|
31723
|
+
var ProfilePiModelBlockSchema = exports_external.object({
|
|
31724
|
+
model: PiEntrySchema.optional().describe("Primary Pi model entry."),
|
|
31725
|
+
fallback_models: exports_external.array(PiEntrySchema).optional().describe("Ordered fallback Pi model entries."),
|
|
31726
|
+
thinking_level: PiThinkingLevelSchema.describe("Pi thinking level for the primary model entry.")
|
|
31727
|
+
}).strict().describe("Strict profile-only Pi model-selection block.");
|
|
31728
|
+
var ProfileHistorianSchema = exports_external.object({
|
|
31729
|
+
opencode: ProfileOpenCodeModelBlockSchema.optional(),
|
|
31730
|
+
pi: ProfilePiModelBlockSchema.optional()
|
|
31731
|
+
}).strict();
|
|
31732
|
+
var ProfileDreamerSchema = exports_external.object({
|
|
31733
|
+
opencode: ProfileOpenCodeModelBlockSchema.optional(),
|
|
31734
|
+
pi: ProfilePiModelBlockSchema.optional()
|
|
31735
|
+
}).strict();
|
|
31736
|
+
var ProfileSidekickSchema = AgentOverrideConfigSchema.pick({
|
|
31737
|
+
model: true,
|
|
31738
|
+
fallback_models: true,
|
|
31739
|
+
variant: true
|
|
31740
|
+
}).extend({
|
|
31741
|
+
thinking_level: PiThinkingLevelSchema.describe("Pi thinking level for the sidekick model selection.")
|
|
31742
|
+
}).strict();
|
|
31743
|
+
var ConfigProfileSchema = exports_external.object({
|
|
31744
|
+
historian: ProfileHistorianSchema.optional(),
|
|
31745
|
+
dreamer: ProfileDreamerSchema.optional(),
|
|
31746
|
+
sidekick: ProfileSidekickSchema.optional()
|
|
31747
|
+
}).strict().describe("User-owned model-selection overlay. Only historian/dreamer harness model blocks and sidekick model-selection fields are allowed.");
|
|
31748
|
+
var ConfigProfilesSchema = exports_external.record(exports_external.string().trim().min(1, "Profile names must not be empty or whitespace-only."), ConfigProfileSchema);
|
|
31495
31749
|
var CronScheduleSchema = exports_external.string().refine((s) => s.trim() === "" || isValidCron(s), {
|
|
31496
31750
|
message: 'Invalid schedule: use a 5-field cron expression (e.g. "0 3 * * *" for 3am daily, "0 3 * * 0" for Sunday 3am, "0 */6 * * *" every 6h) or "" to disable.'
|
|
31497
31751
|
}).describe('5-field cron schedule (e.g. "0 3 * * *"), or "" to disable this task.');
|
|
@@ -31579,9 +31833,9 @@ var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-co
|
|
|
31579
31833
|
function expandConfigPath(value) {
|
|
31580
31834
|
const trimmed = value.trim();
|
|
31581
31835
|
if (trimmed === "~")
|
|
31582
|
-
return
|
|
31836
|
+
return homedir5();
|
|
31583
31837
|
if (trimmed.startsWith("~/"))
|
|
31584
|
-
return `${
|
|
31838
|
+
return `${homedir5()}/${trimmed.slice(2)}`;
|
|
31585
31839
|
return trimmed;
|
|
31586
31840
|
}
|
|
31587
31841
|
var BaseEmbeddingConfigSchema = exports_external.object({
|
|
@@ -31682,6 +31936,8 @@ var MagicContextConfigSchema = exports_external.object({
|
|
|
31682
31936
|
transform_mode: exports_external.enum(["ts", "rust"]).default("ts").describe('Experimental: routes the entire Magic Context runtime for the project through the ck-mc Rust module over subc (requires user-level `subc` config); "ts" is the current TypeScript pipeline.'),
|
|
31683
31937
|
auto_update: exports_external.boolean().optional().describe("Enable automatic npm self-update checks for the OpenCode plugin. Security: USER-only in config loader, so hostile project configs cannot suppress updates."),
|
|
31684
31938
|
language: exports_external.string().trim().toLowerCase().refine((s) => isValidLanguageCode(s), 'language must be a 2-letter ISO 639-1 code (e.g. "tr", "es", "de")').optional().describe("Output language for Magic Context's generated content and guidance, as a " + '2-letter ISO 639-1 code (e.g. "tr", "es", "de", "ja", "pt"). When set, the ' + "historian, dreamer, sidekick, and the agent-guidance block instruct the model to " + "write its PROSE in this language while keeping all structural tokens (XML tags, " + "the five memory category names, code identifiers, file paths) in English. " + "USER-LEVEL ONLY (ignored in project config for security). Unset = today's " + "behavior (model mirrors the conversation; English scaffolding). Changing it " + "triggers one cache re-materialization; existing compartments/memories keep their " + "original language until naturally rewritten."),
|
|
31939
|
+
profile: exports_external.string().trim().min(1).optional().describe("Select a named user-owned model profile. A valid project name overrides this user default; an empty string, null, or other non-string project value is ignored with a warning so the user selection still applies. Unknown names warn and use the base configuration."),
|
|
31940
|
+
profiles: ConfigProfilesSchema.optional().describe("User-level named model profiles. A profile may contain only historian/dreamer model, fallback_models, OpenCode variant, and Pi thinking_level fields plus sidekick model-selection fields; task execution policy (including timeout_minutes) is excluded. Project configs may select a name but cannot define profiles."),
|
|
31685
31941
|
historian: HistorianConfigSchema.describe("Historian metadata plus independent strict OpenCode and Pi execution blocks. Retained metadata stays at historian; model, fallback_models, variant, and thinking_level belong only in historian.opencode or historian.pi."),
|
|
31686
31942
|
dreamer: DreamerConfigSchema.optional().describe("Dreamer metadata and scheduling plus independent strict OpenCode and Pi execution blocks. schedule and promotion_threshold stay at dreamer.tasks; model, fallback_models, variant, thinking_level, and timeout_minutes belong only in the matching harness block."),
|
|
31687
31943
|
smart_notes: exports_external.object({
|
|
@@ -32098,6 +32354,25 @@ function releaseGitSweepLease(db, projectPath, holderId) {
|
|
|
32098
32354
|
});
|
|
32099
32355
|
}
|
|
32100
32356
|
|
|
32357
|
+
// src/features/magic-context/memory/embedding-failure.ts
|
|
32358
|
+
function dominantEmbeddingFailure(failures) {
|
|
32359
|
+
const counts = new Map;
|
|
32360
|
+
for (const failure of failures) {
|
|
32361
|
+
const key = `${failure.class}\x00${failure.reason}`;
|
|
32362
|
+
const current = counts.get(key);
|
|
32363
|
+
if (current)
|
|
32364
|
+
current.count += 1;
|
|
32365
|
+
else
|
|
32366
|
+
counts.set(key, { failure, count: 1 });
|
|
32367
|
+
}
|
|
32368
|
+
let dominant;
|
|
32369
|
+
for (const candidate of counts.values()) {
|
|
32370
|
+
if (!dominant || candidate.count > dominant.count)
|
|
32371
|
+
dominant = candidate;
|
|
32372
|
+
}
|
|
32373
|
+
return dominant?.failure;
|
|
32374
|
+
}
|
|
32375
|
+
|
|
32101
32376
|
// src/features/magic-context/memory/embedding-synapse.ts
|
|
32102
32377
|
import { createHash as createHash13 } from "node:crypto";
|
|
32103
32378
|
|
|
@@ -34046,33 +34321,123 @@ function startLockHeartbeat(lockPath) {
|
|
|
34046
34321
|
timer.unref?.();
|
|
34047
34322
|
return () => clearInterval(timer);
|
|
34048
34323
|
}
|
|
34049
|
-
|
|
34050
|
-
|
|
34324
|
+
var localEmbeddingRuntimeMode = "native";
|
|
34325
|
+
var wasmRuntimeInjected = false;
|
|
34326
|
+
var isElectronForRuntime = () => typeof process !== "undefined" && Boolean(process.versions?.electron);
|
|
34327
|
+
var importWasmOrtForRuntime = async () => {
|
|
34328
|
+
const ortWebSpec = `onnxruntime-${"web"}`;
|
|
34329
|
+
return await import(ortWebSpec);
|
|
34330
|
+
};
|
|
34331
|
+
var importTransformersForRuntime = async () => {
|
|
34332
|
+
const transformersSpec = "@huggingface/transformers";
|
|
34333
|
+
return await import(transformersSpec);
|
|
34334
|
+
};
|
|
34335
|
+
var importTransformersWasmFallbackForRuntime = async () => {
|
|
34336
|
+
const { createRequire: createRequireFn } = await import("node:module");
|
|
34337
|
+
const requireFn = createRequireFn(import.meta.url);
|
|
34338
|
+
const nodeEntry = requireFn.resolve("@huggingface/transformers");
|
|
34339
|
+
const webEntry = pathToFileURL2(join6(dirname5(nodeEntry), "transformers.web.js")).href;
|
|
34340
|
+
return await import(webEntry);
|
|
34341
|
+
};
|
|
34342
|
+
var modelCacheDirForRuntime = () => join6(getMagicContextStorageDir(), "models");
|
|
34343
|
+
var logForRuntime = log;
|
|
34344
|
+
var injectWasmOrtForRuntime = injectWasmOrt;
|
|
34345
|
+
async function ensureWasmOrtInjected() {
|
|
34346
|
+
if (wasmRuntimeInjected)
|
|
34347
|
+
return true;
|
|
34348
|
+
if (!await injectWasmOrtForRuntime())
|
|
34051
34349
|
return false;
|
|
34052
|
-
|
|
34350
|
+
wasmRuntimeInjected = true;
|
|
34351
|
+
return true;
|
|
34352
|
+
}
|
|
34353
|
+
async function injectWasmOrt() {
|
|
34354
|
+
if (wasmRuntimeInjected)
|
|
34355
|
+
return true;
|
|
34053
34356
|
try {
|
|
34054
|
-
const
|
|
34055
|
-
const ortWeb = await import(ortWebSpec);
|
|
34357
|
+
const ortWeb = await importWasmOrtForRuntime();
|
|
34056
34358
|
try {
|
|
34057
34359
|
const { createRequire: createRequireFn } = await import("node:module");
|
|
34058
34360
|
const requireFn = createRequireFn(import.meta.url);
|
|
34059
34361
|
const mainEntry = requireFn.resolve("onnxruntime-web");
|
|
34060
34362
|
const distDir = dirname5(mainEntry);
|
|
34061
|
-
const wasmPathsPrefix = `${pathToFileURL2(distDir).href}/`;
|
|
34062
34363
|
if (ortWeb.env?.wasm) {
|
|
34063
|
-
ortWeb.env.wasm.wasmPaths =
|
|
34364
|
+
ortWeb.env.wasm.wasmPaths = `${pathToFileURL2(distDir).href}/`;
|
|
34064
34365
|
}
|
|
34065
34366
|
} catch (pathError) {
|
|
34066
34367
|
log("[magic-context] could not resolve local onnxruntime-web/dist, falling back to default WASM paths:", pathError instanceof Error ? pathError.message : String(pathError));
|
|
34067
34368
|
}
|
|
34068
34369
|
globalThis[Symbol.for("onnxruntime")] = ortWeb;
|
|
34069
|
-
|
|
34370
|
+
wasmRuntimeInjected = true;
|
|
34070
34371
|
return true;
|
|
34071
34372
|
} catch (error51) {
|
|
34072
|
-
log("[magic-context] failed to inject onnxruntime-web
|
|
34373
|
+
log("[magic-context] failed to inject onnxruntime-web:", error51 instanceof Error ? error51.message : String(error51));
|
|
34073
34374
|
return false;
|
|
34074
34375
|
}
|
|
34075
34376
|
}
|
|
34377
|
+
function likelyMuslHint() {
|
|
34378
|
+
if (process.platform !== "linux" || typeof process.report?.getReport !== "function")
|
|
34379
|
+
return "";
|
|
34380
|
+
try {
|
|
34381
|
+
const report = process.report.getReport();
|
|
34382
|
+
return typeof report.header?.glibcVersionRuntime === "string" ? "" : " Linux process report has no glibc runtime version (musl likely).";
|
|
34383
|
+
} catch {
|
|
34384
|
+
return "";
|
|
34385
|
+
}
|
|
34386
|
+
}
|
|
34387
|
+
function localEmbeddingRuntimeIsDisabled() {
|
|
34388
|
+
return localEmbeddingRuntimeMode === "disabled";
|
|
34389
|
+
}
|
|
34390
|
+
function disableLocalEmbeddingsAfterRuntimeFailure(detail) {
|
|
34391
|
+
localEmbeddingRuntimeMode = "disabled";
|
|
34392
|
+
logForRuntime(`[magic-context] local embeddings are disabled because both the onnxruntime-node native binding and the onnxruntime-web (WASM) fallback failed to load. Native failure: ${detail}. Run \`npx @cortexkit/magic-context@latest doctor\` for repair guidance (use \`doctor --force\` to reinstall cached plugin packages), or configure an \`openai-compatible\` embedding HTTP endpoint. Existing memories are unaffected.`);
|
|
34393
|
+
}
|
|
34394
|
+
async function loadTransformersForLocalEmbedding() {
|
|
34395
|
+
if (localEmbeddingRuntimeMode === "disabled") {
|
|
34396
|
+
throw new Error("local embedding runtime is disabled");
|
|
34397
|
+
}
|
|
34398
|
+
if (localEmbeddingRuntimeMode === "wasm") {
|
|
34399
|
+
if (!await ensureWasmOrtInjected()) {
|
|
34400
|
+
disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime is unavailable");
|
|
34401
|
+
throw new Error("onnxruntime-web failed to load");
|
|
34402
|
+
}
|
|
34403
|
+
try {
|
|
34404
|
+
return { module: await importTransformersWasmFallbackForRuntime(), usesWasm: true };
|
|
34405
|
+
} catch (wasmError) {
|
|
34406
|
+
disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime failed to load");
|
|
34407
|
+
throw wasmError;
|
|
34408
|
+
}
|
|
34409
|
+
}
|
|
34410
|
+
const electron = isElectronForRuntime();
|
|
34411
|
+
if (electron) {
|
|
34412
|
+
const wasInjected = wasmRuntimeInjected;
|
|
34413
|
+
if (await ensureWasmOrtInjected()) {
|
|
34414
|
+
if (!wasInjected) {
|
|
34415
|
+
logForRuntime("[magic-context] Electron detected — using onnxruntime-web (WASM) for embeddings (bypasses onnxruntime-node native load)");
|
|
34416
|
+
}
|
|
34417
|
+
return { module: await importTransformersForRuntime(), usesWasm: true };
|
|
34418
|
+
}
|
|
34419
|
+
}
|
|
34420
|
+
try {
|
|
34421
|
+
return { module: await importTransformersForRuntime(), usesWasm: false };
|
|
34422
|
+
} catch (nativeError) {
|
|
34423
|
+
if (!isNativeRuntimeMissingError(nativeError) || electron) {
|
|
34424
|
+
throw nativeError;
|
|
34425
|
+
}
|
|
34426
|
+
if (!await ensureWasmOrtInjected()) {
|
|
34427
|
+
disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
|
|
34428
|
+
throw nativeError;
|
|
34429
|
+
}
|
|
34430
|
+
localEmbeddingRuntimeMode = "wasm";
|
|
34431
|
+
try {
|
|
34432
|
+
const module = await importTransformersWasmFallbackForRuntime();
|
|
34433
|
+
logForRuntime("[magic-context] onnxruntime-node failed to load; using onnxruntime-web (WASM) for local embeddings. WASM inference is slower than native; a remote `openai-compatible` provider may be faster." + likelyMuslHint());
|
|
34434
|
+
return { module, usesWasm: true };
|
|
34435
|
+
} catch (wasmError) {
|
|
34436
|
+
disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
|
|
34437
|
+
throw wasmError;
|
|
34438
|
+
}
|
|
34439
|
+
}
|
|
34440
|
+
}
|
|
34076
34441
|
var DEFAULT_LOCAL_DTYPE = "fp32";
|
|
34077
34442
|
async function withQuietConsole(fn) {
|
|
34078
34443
|
const origWarn = console.warn;
|
|
@@ -34090,7 +34455,6 @@ async function withQuietConsole(fn) {
|
|
|
34090
34455
|
console.error = origError;
|
|
34091
34456
|
}
|
|
34092
34457
|
}
|
|
34093
|
-
var nativeRuntimeMissing = false;
|
|
34094
34458
|
function isNativeRuntimeMissingError(error51) {
|
|
34095
34459
|
const message = error51 instanceof Error ? error51.message : String(error51 ?? "");
|
|
34096
34460
|
const lower = message.toLowerCase();
|
|
@@ -34174,7 +34538,7 @@ class LocalEmbeddingProvider {
|
|
|
34174
34538
|
if (this.pipeline) {
|
|
34175
34539
|
return true;
|
|
34176
34540
|
}
|
|
34177
|
-
if (
|
|
34541
|
+
if (localEmbeddingRuntimeMode === "disabled") {
|
|
34178
34542
|
return false;
|
|
34179
34543
|
}
|
|
34180
34544
|
if (this.initPromise) {
|
|
@@ -34186,15 +34550,13 @@ class LocalEmbeddingProvider {
|
|
|
34186
34550
|
if (this.disposing) {
|
|
34187
34551
|
return;
|
|
34188
34552
|
}
|
|
34189
|
-
const
|
|
34190
|
-
const transformersSpec = "@huggingface/transformers";
|
|
34191
|
-
const transformersModule = await import(transformersSpec);
|
|
34553
|
+
const { module: transformersModule, usesWasm } = await loadTransformersForLocalEmbedding();
|
|
34192
34554
|
const env = transformersModule.env;
|
|
34193
34555
|
const LogLevel = transformersModule.LogLevel;
|
|
34194
34556
|
if (LogLevel && "ERROR" in LogLevel) {
|
|
34195
34557
|
env.logLevel = LogLevel.ERROR;
|
|
34196
34558
|
}
|
|
34197
|
-
const modelCacheDir =
|
|
34559
|
+
const modelCacheDir = modelCacheDirForRuntime();
|
|
34198
34560
|
try {
|
|
34199
34561
|
if (shouldEnforcePrivateStoragePermissions()) {
|
|
34200
34562
|
mkdirSync3(modelCacheDir, { recursive: true, mode: 448 });
|
|
@@ -34221,7 +34583,7 @@ class LocalEmbeddingProvider {
|
|
|
34221
34583
|
try {
|
|
34222
34584
|
const pipeline = await withQuietConsole(() => createPipeline("feature-extraction", this.model, {
|
|
34223
34585
|
dtype: this.dtype,
|
|
34224
|
-
...
|
|
34586
|
+
...usesWasm ? { device: "auto" } : {}
|
|
34225
34587
|
}));
|
|
34226
34588
|
if (this.disposing) {
|
|
34227
34589
|
await pipeline.dispose?.();
|
|
@@ -34253,10 +34615,9 @@ class LocalEmbeddingProvider {
|
|
|
34253
34615
|
await releaseLock();
|
|
34254
34616
|
}
|
|
34255
34617
|
} catch (error51) {
|
|
34256
|
-
if (isNativeRuntimeMissingError(error51)) {
|
|
34257
|
-
|
|
34258
|
-
|
|
34259
|
-
} else {
|
|
34618
|
+
if (!localEmbeddingRuntimeIsDisabled() && isNativeRuntimeMissingError(error51)) {
|
|
34619
|
+
disableLocalEmbeddingsAfterRuntimeFailure(error51 instanceof Error ? error51.message : String(error51));
|
|
34620
|
+
} else if (!localEmbeddingRuntimeIsDisabled()) {
|
|
34260
34621
|
log("[magic-context] embedding model failed to load:", error51);
|
|
34261
34622
|
}
|
|
34262
34623
|
this.pipeline = null;
|
|
@@ -34477,6 +34838,7 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
34477
34838
|
circuitOpenUntil = 0;
|
|
34478
34839
|
openLogged = false;
|
|
34479
34840
|
modelMismatchLogged = false;
|
|
34841
|
+
lastFailureReason = null;
|
|
34480
34842
|
halfOpenProbeInFlight = false;
|
|
34481
34843
|
constructor(options) {
|
|
34482
34844
|
this.endpoint = normalizeEndpoint2(options.endpoint);
|
|
@@ -34566,41 +34928,59 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
34566
34928
|
signal: internalController.signal
|
|
34567
34929
|
});
|
|
34568
34930
|
if (!response.ok) {
|
|
34569
|
-
|
|
34570
|
-
this.
|
|
34931
|
+
const excerpt = await response.text().catch(() => "");
|
|
34932
|
+
const failure = this.failure("http_error", `HTTP ${response.status} from endpoint${this.bodyExcerpt(excerpt)}`, response.status >= 500 || response.status === 408 || response.status === 429);
|
|
34933
|
+
log(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
|
|
34934
|
+
this.recordFailure(isProbe, failure);
|
|
34571
34935
|
return Array.from({ length: texts.length }, () => null);
|
|
34572
34936
|
}
|
|
34573
34937
|
const rawBody = await response.text();
|
|
34574
34938
|
if (rawBody.trim().length === 0) {
|
|
34575
|
-
|
|
34576
|
-
|
|
34939
|
+
const failure = this.failure("invalid_envelope", "response body was empty", false);
|
|
34940
|
+
log(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
|
|
34941
|
+
this.recordFailure(isProbe, failure);
|
|
34577
34942
|
return Array.from({ length: texts.length }, () => null);
|
|
34578
34943
|
}
|
|
34579
34944
|
let body;
|
|
34580
34945
|
try {
|
|
34581
34946
|
body = JSON.parse(rawBody);
|
|
34582
|
-
} catch
|
|
34583
|
-
const
|
|
34584
|
-
log(`[magic-context] openai-compatible embedding
|
|
34585
|
-
this.recordFailure(isProbe);
|
|
34947
|
+
} catch {
|
|
34948
|
+
const failure = this.failure("invalid_envelope", `response body was not valid JSON${this.bodyExcerpt(rawBody)}`, false);
|
|
34949
|
+
log(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
|
|
34950
|
+
this.recordFailure(isProbe, failure);
|
|
34586
34951
|
return Array.from({ length: texts.length }, () => null);
|
|
34587
34952
|
}
|
|
34588
34953
|
const servedModel = typeof body.model === "string" ? body.model : "";
|
|
34589
34954
|
if (this.model && servedModel && !embeddingModelsMatch(servedModel, this.model)) {
|
|
34590
34955
|
if (!this.modelMismatchLogged) {
|
|
34591
|
-
log(`[magic-context] embedding endpoint served a DIFFERENT model than requested — refusing the substituted vectors (they have the wrong dimensions/space). requested="${this.model}" served="${servedModel}". Check that the endpoint serves the requested model; variant suffixes and vendor prefixes are matched automatically.`);
|
|
34956
|
+
log(`[magic-context] embedding endpoint served a DIFFERENT model than requested — refusing the substituted vectors (they have the wrong dimensions/space). requested="${sanitizeDiagnosticText(this.model)}" served="${sanitizeDiagnosticText(servedModel)}". Check that the endpoint serves the requested model; variant suffixes and vendor prefixes are matched automatically.`);
|
|
34592
34957
|
this.modelMismatchLogged = true;
|
|
34593
34958
|
}
|
|
34594
|
-
this.recordFailure(isProbe);
|
|
34959
|
+
this.recordFailure(isProbe, this.failure("substitution_rejected", `served model '${sanitizeDiagnosticText(servedModel)}' does not match requested '${sanitizeDiagnosticText(this.model)}' (substitution guard)`, false));
|
|
34960
|
+
return Array.from({ length: texts.length }, () => null);
|
|
34961
|
+
}
|
|
34962
|
+
const responseKeys = Object.keys(body).sort();
|
|
34963
|
+
if (!Array.isArray(body.data)) {
|
|
34964
|
+
const failure = this.failure("invalid_envelope", `response had keys [${responseKeys.join(", ")}] but data[] was absent`, false);
|
|
34965
|
+
log(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
|
|
34966
|
+
this.recordFailure(isProbe, failure);
|
|
34967
|
+
return Array.from({ length: texts.length }, () => null);
|
|
34968
|
+
}
|
|
34969
|
+
if (body.data.length === 0) {
|
|
34970
|
+
const failure = this.failure("empty_result", "response data[] was empty", true);
|
|
34971
|
+
log(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
|
|
34972
|
+
this.recordFailure(isProbe, failure);
|
|
34595
34973
|
return Array.from({ length: texts.length }, () => null);
|
|
34596
34974
|
}
|
|
34597
|
-
const items =
|
|
34975
|
+
const items = body.data;
|
|
34598
34976
|
const results = Array.from({ length: texts.length }, (_, index) => {
|
|
34599
34977
|
const embedding = items[index]?.embedding;
|
|
34600
34978
|
return Array.isArray(embedding) ? Float32Array.from(embedding) : null;
|
|
34601
34979
|
});
|
|
34602
34980
|
if (results.every((r) => r === null)) {
|
|
34603
|
-
this.
|
|
34981
|
+
const failure = this.failure("invalid_envelope", `response had keys [${responseKeys.join(", ")}] but data[].embedding was absent`, false);
|
|
34982
|
+
log(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
|
|
34983
|
+
this.recordFailure(isProbe, failure);
|
|
34604
34984
|
} else {
|
|
34605
34985
|
this.recordSuccess();
|
|
34606
34986
|
}
|
|
@@ -34610,11 +34990,14 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
34610
34990
|
if (isAbort) {
|
|
34611
34991
|
if (signal?.aborted) {} else {
|
|
34612
34992
|
log(`[magic-context] openai-compatible embedding request timed out after ${FETCH_TIMEOUT_MS}ms`);
|
|
34613
|
-
this.
|
|
34993
|
+
const failure = this.failure("transport_error", `request timed out after ${FETCH_TIMEOUT_MS}ms`, true);
|
|
34994
|
+
this.recordFailure(isProbe, failure);
|
|
34614
34995
|
}
|
|
34615
34996
|
} else {
|
|
34616
|
-
|
|
34617
|
-
this.
|
|
34997
|
+
const detail = error51 instanceof Error ? error51.message : String(error51);
|
|
34998
|
+
const failure = this.failure("transport_error", `transport error: ${sanitizeDiagnosticText(detail)}`, true);
|
|
34999
|
+
log(`[magic-context] openai-compatible embedding request failed: ${failure.reason}`);
|
|
35000
|
+
this.recordFailure(isProbe, failure);
|
|
34618
35001
|
}
|
|
34619
35002
|
return Array.from({ length: texts.length }, () => null);
|
|
34620
35003
|
} finally {
|
|
@@ -34646,14 +35029,23 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
34646
35029
|
return "short_circuit";
|
|
34647
35030
|
}
|
|
34648
35031
|
this.halfOpenProbeInFlight = true;
|
|
34649
|
-
log(
|
|
35032
|
+
log(`[magic-context] openai-compatible embedding: circuit half-open, probing endpoint after ${this.lastFailureReason?.reason ?? "unknown failure"}`);
|
|
34650
35033
|
return "probe";
|
|
34651
35034
|
}
|
|
34652
|
-
|
|
35035
|
+
failure(failureClass, reason, retryable) {
|
|
35036
|
+
return { class: failureClass, reason, retryable };
|
|
35037
|
+
}
|
|
35038
|
+
bodyExcerpt(body) {
|
|
35039
|
+
const excerpt = sanitizeDiagnosticText(body).replace(/\s+/g, " ").trim().slice(0, 200);
|
|
35040
|
+
return excerpt ? `: ${excerpt}` : "";
|
|
35041
|
+
}
|
|
35042
|
+
recordFailure(isProbe, failure) {
|
|
35043
|
+
if (failure)
|
|
35044
|
+
this.lastFailureReason = failure;
|
|
34653
35045
|
if (isProbe) {
|
|
34654
35046
|
this.circuitOpenUntil = Date.now() + OPEN_DURATION_MS;
|
|
34655
35047
|
if (!this.openLogged) {
|
|
34656
|
-
log(`[magic-context] openai-compatible embedding: probe failed, re-opening circuit for ${OPEN_DURATION_MS / 60000}min`);
|
|
35048
|
+
log(`[magic-context] openai-compatible embedding: probe failed (${failure?.reason ?? this.lastFailureReason?.reason ?? "unknown failure"}), re-opening circuit for ${OPEN_DURATION_MS / 60000}min`);
|
|
34657
35049
|
this.openLogged = true;
|
|
34658
35050
|
}
|
|
34659
35051
|
this.failureTimes = [];
|
|
@@ -34666,7 +35058,7 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
34666
35058
|
if (this.failureTimes.length >= FAILURE_THRESHOLD) {
|
|
34667
35059
|
this.circuitOpenUntil = now + OPEN_DURATION_MS;
|
|
34668
35060
|
if (!this.openLogged) {
|
|
34669
|
-
log(`[magic-context] openai-compatible embedding: opening circuit for ${OPEN_DURATION_MS / 60000}min after ${this.failureTimes.length} failures in ${FAILURE_WINDOW_MS / 1000}s`);
|
|
35061
|
+
log(`[magic-context] openai-compatible embedding: opening circuit for ${OPEN_DURATION_MS / 60000}min after ${this.failureTimes.length} failures in ${FAILURE_WINDOW_MS / 1000}s (${failure?.reason ?? this.lastFailureReason?.reason ?? "unknown failure"})`);
|
|
34670
35062
|
this.openLogged = true;
|
|
34671
35063
|
}
|
|
34672
35064
|
this.failureTimes = [];
|
|
@@ -34679,6 +35071,10 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
34679
35071
|
this.failureTimes = [];
|
|
34680
35072
|
this.circuitOpenUntil = 0;
|
|
34681
35073
|
this.openLogged = false;
|
|
35074
|
+
this.lastFailureReason = null;
|
|
35075
|
+
}
|
|
35076
|
+
getLastFailureReason() {
|
|
35077
|
+
return this.lastFailureReason;
|
|
34682
35078
|
}
|
|
34683
35079
|
_getCircuitState() {
|
|
34684
35080
|
if (this.circuitOpenUntil === 0)
|
|
@@ -34696,6 +35092,7 @@ class OpenAICompatibleEmbeddingProvider {
|
|
|
34696
35092
|
this.circuitOpenUntil = 0;
|
|
34697
35093
|
this.openLogged = false;
|
|
34698
35094
|
this.halfOpenProbeInFlight = false;
|
|
35095
|
+
this.lastFailureReason = null;
|
|
34699
35096
|
}
|
|
34700
35097
|
}
|
|
34701
35098
|
|
|
@@ -35945,11 +36342,16 @@ async function drainCommitBacklogForProject(db, projectIdentity, deadline) {
|
|
|
35945
36342
|
}
|
|
35946
36343
|
return total;
|
|
35947
36344
|
}
|
|
36345
|
+
function getLastEmbeddingFailureForProject(projectIdentity) {
|
|
36346
|
+
const registration = projectRegistrations.get(projectIdentity);
|
|
36347
|
+
return registration?.provider?.getLastFailureReason?.() ?? null;
|
|
36348
|
+
}
|
|
35948
36349
|
async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates, signal) {
|
|
35949
36350
|
const noWork = [];
|
|
35950
36351
|
const failed = [];
|
|
36352
|
+
const failureReasons = [];
|
|
35951
36353
|
if (candidates.length === 0)
|
|
35952
|
-
return { embedded: 0, noWork, failed };
|
|
36354
|
+
return { embedded: 0, noWork, failed, failureReasons };
|
|
35953
36355
|
const maxInputTokens = getProjectEmbeddingMaxInputTokens(projectIdentity);
|
|
35954
36356
|
const prepared = [];
|
|
35955
36357
|
for (const candidate of candidates) {
|
|
@@ -35966,7 +36368,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
|
|
|
35966
36368
|
prepared.push({ candidate, windows });
|
|
35967
36369
|
}
|
|
35968
36370
|
if (prepared.length === 0)
|
|
35969
|
-
return { embedded: 0, noWork, failed };
|
|
36371
|
+
return { embedded: 0, noWork, failed, failureReasons };
|
|
35970
36372
|
let embedded = 0;
|
|
35971
36373
|
let i = 0;
|
|
35972
36374
|
while (i < prepared.length) {
|
|
@@ -35998,6 +36400,11 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
|
|
|
35998
36400
|
}
|
|
35999
36401
|
if (signal?.aborted)
|
|
36000
36402
|
break;
|
|
36403
|
+
if (!result || result.vectors.size === 0) {
|
|
36404
|
+
const failure = getLastEmbeddingFailureForProject(projectIdentity);
|
|
36405
|
+
if (failure)
|
|
36406
|
+
failureReasons.push(failure);
|
|
36407
|
+
}
|
|
36001
36408
|
if (result) {
|
|
36002
36409
|
for (const item of slice) {
|
|
36003
36410
|
if (persistedIds.has(item.candidate.id))
|
|
@@ -36039,7 +36446,7 @@ async function embedCandidateChunkBatch(db, projectIdentity, modelId, candidates
|
|
|
36039
36446
|
}
|
|
36040
36447
|
}
|
|
36041
36448
|
}
|
|
36042
|
-
return { embedded, noWork, failed };
|
|
36449
|
+
return { embedded, noWork, failed, failureReasons };
|
|
36043
36450
|
}
|
|
36044
36451
|
async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, options) {
|
|
36045
36452
|
const snapshot2 = getProjectEmbeddingSnapshot(projectIdentity);
|
|
@@ -36077,6 +36484,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
|
|
|
36077
36484
|
let aborted2 = false;
|
|
36078
36485
|
let providerDown = false;
|
|
36079
36486
|
let consecutiveFailedBatches = 0;
|
|
36487
|
+
const failureReasons = [];
|
|
36080
36488
|
try {
|
|
36081
36489
|
options?.onProgress?.({ embedded, total });
|
|
36082
36490
|
for (;; ) {
|
|
@@ -36090,7 +36498,8 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
|
|
|
36090
36498
|
const {
|
|
36091
36499
|
embedded: n,
|
|
36092
36500
|
noWork,
|
|
36093
|
-
failed
|
|
36501
|
+
failed,
|
|
36502
|
+
failureReasons: batchFailureReasons
|
|
36094
36503
|
} = await embedCandidateChunkBatch(db, projectIdentity, snapshot2.chunkModelId, candidates, drainAbort.signal);
|
|
36095
36504
|
if (leaseLost || !renewGitSweepLease(db, projectIdentity, holderId)) {
|
|
36096
36505
|
leaseLost = true;
|
|
@@ -36098,6 +36507,7 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
|
|
|
36098
36507
|
aborted2 = true;
|
|
36099
36508
|
break;
|
|
36100
36509
|
}
|
|
36510
|
+
failureReasons.push(...batchFailureReasons);
|
|
36101
36511
|
for (const id of noWork)
|
|
36102
36512
|
skipIds.push(id);
|
|
36103
36513
|
for (const id of failed)
|
|
@@ -36129,7 +36539,14 @@ async function embedSessionCompartmentChunks(db, projectIdentity, sessionId, opt
|
|
|
36129
36539
|
if (providerDown || failedIds.length > 0) {
|
|
36130
36540
|
const remaining = Math.max(0, countUnembeddedSessionCompartments(db, projectIdentity, sessionId, snapshot2.chunkModelId) - skipIds.length);
|
|
36131
36541
|
if (remaining > 0) {
|
|
36132
|
-
return {
|
|
36542
|
+
return {
|
|
36543
|
+
status: "stalled",
|
|
36544
|
+
embedded,
|
|
36545
|
+
total,
|
|
36546
|
+
remaining,
|
|
36547
|
+
failed: failedIds.length,
|
|
36548
|
+
failure: dominantEmbeddingFailure(failureReasons)
|
|
36549
|
+
};
|
|
36133
36550
|
}
|
|
36134
36551
|
}
|
|
36135
36552
|
return { status: "done", embedded, total, failed: failedIds.length };
|
|
@@ -40270,7 +40687,8 @@ function injectTemporalMarkers(messages) {
|
|
|
40270
40687
|
continue;
|
|
40271
40688
|
const msg = raw;
|
|
40272
40689
|
const role = msg.info?.role;
|
|
40273
|
-
|
|
40690
|
+
const authoredUser = role === "user" && Array.isArray(msg.parts) && hasMeaningfulUserText(msg.parts);
|
|
40691
|
+
if (prev !== null && authoredUser) {
|
|
40274
40692
|
const prevTime = prev.info?.time;
|
|
40275
40693
|
const currTime = msg.info?.time;
|
|
40276
40694
|
if (prevTime?.created !== undefined && currTime?.created !== undefined) {
|
|
@@ -41072,7 +41490,7 @@ function mustMaterialize(args) {
|
|
|
41072
41490
|
}
|
|
41073
41491
|
const liveToolSetHash = hard.toolSetHash ?? "";
|
|
41074
41492
|
const toolSetHashComparison = liveToolSetHash !== "" ? {
|
|
41075
|
-
m0ToolSetHashPrev: args.state.cachedM0ToolSetHash
|
|
41493
|
+
m0ToolSetHashPrev: args.state.cachedM0ToolSetHash,
|
|
41076
41494
|
m0ToolSetHashNew: liveToolSetHash
|
|
41077
41495
|
} : null;
|
|
41078
41496
|
const withToolSetHashComparison = (decision) => toolSetHashComparison ? { ...decision, ...toolSetHashComparison } : decision;
|
|
@@ -46467,4 +46885,4 @@ async function runUpgradeMemoryMigration(ctx, sessionId, migrationDirectory) {
|
|
|
46467
46885
|
}
|
|
46468
46886
|
}
|
|
46469
46887
|
|
|
46470
|
-
export { withContentLanguageDirective, buildPrimaryLanguageDirective, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, exports_external, DEFAULT_PROTECTED_TAGS, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, MagicContextConfigSchema, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, getMirrorCursor, applyMirroredNoteCompileFields, applyMirrorPage, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, isRecord, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, getSessionsWithPendingMarker, setSessionWorkMetrics, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, buildChannel2Reminder, shouldUseStickyChannel1Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, updateTagMessageId, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, createChildSessionWithFence, detectOverflow, resolveFallbackChain, modelBodyField, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, shouldKeepSubagents, recordChildInvocation, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, StaleRouteHandleError, SocketClosedError, SocketTimeoutError, SubcClient, isConsumerReconnectTransient, connectionFileExists, getCompartmentEvents, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, SYNAPSE_DEFAULT_MODEL, SynapseEmbeddingProvider, computeNormalizedHash, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getSlot, dropSlot, noteEntry, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, extractM0Block, resolveMuralWire, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, injectM0M1, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure, isRecompSkip, isRecompComplete, extractRecompReason, contextualizeUpgradeReason, setRecompStarting, setRecompNote, setRecompTerminal, runManagedRecomp, runManagedUpgrade };
|
|
46888
|
+
export { withContentLanguageDirective, buildPrimaryLanguageDirective, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, exports_external, DEFAULT_PROTECTED_TAGS, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, ConfigProfilesSchema, MagicContextConfigSchema, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, hasShareabilitySensitiveText, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, getMirrorCursor, applyMirroredNoteCompileFields, applyMirrorPage, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, isRecord, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, getSessionsWithPendingMarker, setSessionWorkMetrics, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, buildChannel2Reminder, shouldUseStickyChannel1Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, updateTagMessageId, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, createChildSessionWithFence, detectOverflow, resolveFallbackChain, modelBodyField, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, shouldKeepSubagents, recordChildInvocation, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, StaleRouteHandleError, SocketClosedError, SocketTimeoutError, SubcClient, isConsumerReconnectTransient, connectionFileExists, getCompartmentEvents, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, SYNAPSE_DEFAULT_MODEL, SynapseEmbeddingProvider, computeNormalizedHash, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getSlot, dropSlot, noteEntry, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, extractM0Block, resolveMuralWire, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, injectM0M1, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure, isRecompSkip, isRecompComplete, extractRecompReason, contextualizeUpgradeReason, setRecompStarting, setRecompNote, setRecompTerminal, runManagedRecomp, runManagedUpgrade };
|