@cortexkit/pi-magic-context 0.49.0 → 0.49.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-search-worker.js +3 -3
- package/dist/{embedding-backfill-b71dvfs8.js → embedding-backfill-scywarbn.js} +7 -7
- package/dist/embedding-worker-process.js +29 -0
- package/dist/embedding-worker.js +5 -5
- package/dist/index-0j0zqb4t.js +712 -0
- package/dist/{index-hwqb3s7f.js → index-0rasmwm8.js} +5 -5
- package/dist/{index-bejpsj10.js → index-27jh224p.js} +1 -1
- package/dist/{index-ehybv5nr.js → index-28vnkyy7.js} +1129 -2990
- package/dist/{index-r024r8da.js → index-4gfq5t09.js} +16 -1
- package/dist/{index-vf38qhee.js → index-81nthk8j.js} +44 -1
- package/dist/{index-yzcjxnt2.js → index-b2anqqad.js} +422 -6
- package/dist/{index-1evzceyw.js → index-cyrnv16r.js} +314 -1072
- package/dist/index-fqb1bddn.js +4947 -0
- package/dist/{index-041ex0cj.js → index-g7hndmqm.js} +20 -34
- package/dist/index-gc2749rx.js +1168 -0
- package/dist/{index-t7xfqtg6.js → index-p5zesr4e.js} +22 -718
- package/dist/{index-yarjn32j.js → index-r874cgmv.js} +38 -36
- package/dist/{index-3mgf68pn.js → index-rd53pk0h.js} +1 -1
- package/dist/{index-904reqtg.js → index-rdtgp48t.js} +6 -4
- package/dist/index.js +1637 -1126
- package/dist/{message-index-bounded-qz5dz2se.js → message-index-bounded-110sb4fm.js} +6 -5
- package/dist/migration-worker.js +6 -5
- package/dist/{project-embedding-registry-ky7wrkr1.js → project-embedding-registry-64t0mw8y.js} +6 -6
- package/dist/raw-ordinal-warmup-worker.js +1 -1
- package/dist/{read-session-chunk-24sd89tf.js → read-session-chunk-rvmc25n5.js} +3 -2
- package/dist/{search-jbh28nwy.js → search-7z3w8pmz.js} +15 -14
- package/dist/subagent-entry.js +17 -16
- package/package.json +3 -3
- package/dist/index-3rea6zd9.js +0 -2396
- package/dist/index-bgmv2kaf.js +0 -290
- /package/dist/{index-5prbx026.js → index-2pp04pmg.js} +0 -0
|
@@ -9,6 +9,8 @@ import {
|
|
|
9
9
|
sessionLog2
|
|
10
10
|
} from "./index-x3dcnxh0.js";
|
|
11
11
|
import {
|
|
12
|
+
piModelRefToCanonical,
|
|
13
|
+
modelRefLookupOrder,
|
|
12
14
|
buildPrimaryLanguageDirective,
|
|
13
15
|
resolvePromptSurface,
|
|
14
16
|
DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
|
|
@@ -17,17 +19,40 @@ import {
|
|
|
17
19
|
PER_HARNESS_MIGRATION_INVENTORY,
|
|
18
20
|
PER_HARNESS_MODEL_KEYS,
|
|
19
21
|
ConfigProfilesSchema,
|
|
20
|
-
MagicContextConfigSchema
|
|
21
|
-
|
|
22
|
-
} from "./index-1evzceyw.js";
|
|
22
|
+
MagicContextConfigSchema
|
|
23
|
+
} from "./index-cyrnv16r.js";
|
|
23
24
|
import {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
MERGED_REASONING_PARTS_PREFIX,
|
|
26
|
+
decodeMergedReasoningParts,
|
|
27
|
+
SESSION_META_SELECT_COLUMNS,
|
|
28
|
+
META_COLUMNS,
|
|
29
|
+
BOOLEAN_META_KEYS,
|
|
30
|
+
NULL_BIND_META_KEYS,
|
|
31
|
+
isSessionMetaRow,
|
|
32
|
+
getDefaultSessionMeta,
|
|
33
|
+
ensureSessionMetaRow,
|
|
34
|
+
toSessionMeta,
|
|
35
|
+
isRustMarkerAdmissionFenced,
|
|
36
|
+
readReplayEnvelope,
|
|
37
|
+
readReplayDocument,
|
|
38
|
+
updateReplayDocument,
|
|
39
|
+
writeReplayDocument,
|
|
40
|
+
setNoteLastReadAt,
|
|
41
|
+
getPersistedCompactionMarkerState,
|
|
42
|
+
setPersistedCompactionMarkerState,
|
|
43
|
+
parseStrippedPlaceholderState,
|
|
44
|
+
serializeStrippedPlaceholderState,
|
|
45
|
+
THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
|
|
46
|
+
THINKING_BINDING_STRIP_ORDER_END_MARKER,
|
|
47
|
+
withReadOnlySessionDb,
|
|
48
|
+
expandToolPart,
|
|
49
|
+
hasRawMessageProvider2,
|
|
50
|
+
setRawMessageProvider2,
|
|
51
|
+
visitRawSessionMessages2,
|
|
52
|
+
readRawSessionMessageById2,
|
|
53
|
+
readSessionChunk2
|
|
54
|
+
} from "./index-fqb1bddn.js";
|
|
27
55
|
import {
|
|
28
|
-
resolveDecisionCalibration,
|
|
29
|
-
calibrationForModelKey,
|
|
30
|
-
protectedToolTagNumbers,
|
|
31
56
|
isRecord,
|
|
32
57
|
providerVisibleMessage,
|
|
33
58
|
TODO_STATUSES,
|
|
@@ -38,7 +63,6 @@ import {
|
|
|
38
63
|
updateTagStatus2,
|
|
39
64
|
getInertWhitespaceAssistantTagsByNumbers2,
|
|
40
65
|
getTagNumberByMessageId2,
|
|
41
|
-
TAG_SELECT_COLUMNS2,
|
|
42
66
|
getTagsBySession2,
|
|
43
67
|
getTagById2
|
|
44
68
|
} from "./index-kjd1fj55.js";
|
|
@@ -47,7 +71,6 @@ import {
|
|
|
47
71
|
} from "./index-r56xgha8.js";
|
|
48
72
|
import {
|
|
49
73
|
Database2,
|
|
50
|
-
prepareCachedStatement2,
|
|
51
74
|
withSqliteBackgroundWriter2,
|
|
52
75
|
withoutSqliteTransformPass2
|
|
53
76
|
} from "./index-3cgbv47m.js";
|
|
@@ -64,14 +87,17 @@ import {
|
|
|
64
87
|
noteRawSessionSummaryRowWritten2
|
|
65
88
|
} from "./index-vakawmbc.js";
|
|
66
89
|
import {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
90
|
+
piHarnessKindFromExecutable,
|
|
91
|
+
isPidAlive
|
|
92
|
+
} from "./index-0j0zqb4t.js";
|
|
93
|
+
import {
|
|
94
|
+
BoundedSessionMap,
|
|
95
|
+
clearLkgFenceProcessState,
|
|
96
|
+
commitLkgWithRecoveryFence,
|
|
97
|
+
clearLkgRecoveryFence,
|
|
98
|
+
deleteSessionScopedRows,
|
|
99
|
+
getLastIndexedOrdinal
|
|
100
|
+
} from "./index-b2anqqad.js";
|
|
75
101
|
import {
|
|
76
102
|
SubcClient,
|
|
77
103
|
connectionFileExists,
|
|
@@ -80,34 +106,33 @@ import {
|
|
|
80
106
|
SynapseEmbeddingProvider
|
|
81
107
|
} from "./index-21v1kfs7.js";
|
|
82
108
|
import {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
} from "./index-yzcjxnt2.js";
|
|
109
|
+
sameProjectDirectory
|
|
110
|
+
} from "./index-4gfq5t09.js";
|
|
86
111
|
import {
|
|
87
|
-
piHarnessKindFromExecutable,
|
|
88
|
-
isPidAlive,
|
|
89
112
|
getErrorMessage
|
|
90
|
-
} from "./index-
|
|
113
|
+
} from "./index-p5zesr4e.js";
|
|
91
114
|
import {
|
|
92
115
|
V2_MEMORY_CATEGORIES,
|
|
93
116
|
CATEGORY_PRIORITY,
|
|
94
117
|
getMemoryCategoryOrder
|
|
95
118
|
} from "./index-135e8hvg.js";
|
|
96
119
|
import {
|
|
120
|
+
layoutLkgPrefix,
|
|
121
|
+
assembleLkgPrefix,
|
|
97
122
|
resolveWorkspaceShareCategories,
|
|
98
123
|
resolveWorkspaceIdentitySet,
|
|
99
124
|
expandWorkspaceIdentitySetWithAliases,
|
|
100
125
|
resolveStoredPathWorkspaceIdentity,
|
|
101
126
|
storedPathBelongsToWorkspace
|
|
102
|
-
} from "./index-
|
|
127
|
+
} from "./index-rd53pk0h.js";
|
|
103
128
|
import {
|
|
104
|
-
sameProjectDirectory,
|
|
105
129
|
directoryHasGitMetadata,
|
|
106
130
|
resolveProjectIdentityForSession,
|
|
107
131
|
normalizeStoredProjectPath,
|
|
108
132
|
storedPathBelongsToIdentity
|
|
109
|
-
} from "./index-
|
|
133
|
+
} from "./index-g7hndmqm.js";
|
|
110
134
|
import {
|
|
135
|
+
drainBackgroundBatches,
|
|
111
136
|
markProjectLoadUntrusted2,
|
|
112
137
|
drainProjectEmbeddingIdentityMaintenance2,
|
|
113
138
|
registerProjectEmbedding2,
|
|
@@ -117,7 +142,7 @@ import {
|
|
|
117
142
|
unregisterProjectEmbedding2,
|
|
118
143
|
getProjectEmbeddingSnapshot2,
|
|
119
144
|
embedTextForProject2
|
|
120
|
-
} from "./index-
|
|
145
|
+
} from "./index-r874cgmv.js";
|
|
121
146
|
import {
|
|
122
147
|
getNoteByIdInScope,
|
|
123
148
|
getNotes,
|
|
@@ -133,7 +158,7 @@ import {
|
|
|
133
158
|
resolveMemoriesByIdsForSearch2,
|
|
134
159
|
unifiedSearch2,
|
|
135
160
|
formatSearchResults2
|
|
136
|
-
} from "./index-
|
|
161
|
+
} from "./index-0rasmwm8.js";
|
|
137
162
|
import {
|
|
138
163
|
saveEmbedding,
|
|
139
164
|
invalidateMemory2
|
|
@@ -163,7 +188,7 @@ import {
|
|
|
163
188
|
import {
|
|
164
189
|
ensureStorageDirectorySync,
|
|
165
190
|
writeStorageFileAtomicSync
|
|
166
|
-
} from "./index-
|
|
191
|
+
} from "./index-81nthk8j.js";
|
|
167
192
|
|
|
168
193
|
// ../plugin/src/config/agent-disable.ts
|
|
169
194
|
var COMPACTION_ENABLED_PATH = `compaction${"."}enabled`;
|
|
@@ -1817,13 +1842,10 @@ function detectConfigFile(basePath) {
|
|
|
1817
1842
|
}
|
|
1818
1843
|
|
|
1819
1844
|
// ../plugin/src/shared/models-dev-cache.ts
|
|
1820
|
-
import { readFileSync as readFileSync3 } from "node:fs";
|
|
1821
|
-
import { join as join2 } from "node:path";
|
|
1822
|
-
|
|
1823
|
-
// ../plugin/src/shared/window-geometry.ts
|
|
1824
1845
|
import { readFileSync as readFileSync2 } from "node:fs";
|
|
1825
1846
|
import { join } from "node:path";
|
|
1826
|
-
|
|
1847
|
+
|
|
1848
|
+
// ../plugin/src/shared/window-geometry.ts
|
|
1827
1849
|
var PROMPT_WALL_MARGIN = 4096;
|
|
1828
1850
|
var PI_OUTPUT_FLOOR = 4096;
|
|
1829
1851
|
var OPENCODE_OUTPUT_CAP = 32000;
|
|
@@ -1838,241 +1860,10 @@ var PROVIDER_GEOMETRY = {
|
|
|
1838
1860
|
google: "separate",
|
|
1839
1861
|
"google-antigravity": "separate"
|
|
1840
1862
|
};
|
|
1841
|
-
var GRADES = new Set([
|
|
1842
|
-
"provider_asserted_runtime",
|
|
1843
|
-
"measured",
|
|
1844
|
-
"provider_asserted_doc",
|
|
1845
|
-
"catalog",
|
|
1846
|
-
"unknown"
|
|
1847
|
-
]);
|
|
1848
|
-
var UNITS = new Set(["provider", "estimate"]);
|
|
1849
|
-
var BOUNDARIES = new Set(["Observed", "Asserted", "Corrected"]);
|
|
1850
|
-
var UNKNOWN_REASONS = new Set([
|
|
1851
|
-
"placeholder_output_equals_context",
|
|
1852
|
-
"placeholder_zero",
|
|
1853
|
-
"never_measured",
|
|
1854
|
-
"not_single_valued_at_key",
|
|
1855
|
-
"retracted"
|
|
1856
|
-
]);
|
|
1857
|
-
var NUMERIC_FACT_KEYS = new Set([
|
|
1858
|
-
"window.advertised",
|
|
1859
|
-
"window.enforced",
|
|
1860
|
-
"output.advertised",
|
|
1861
|
-
"output.enforced",
|
|
1862
|
-
"output.default"
|
|
1863
|
-
]);
|
|
1864
|
-
var configuredOverlayPath;
|
|
1865
|
-
var loadedOverlayPath;
|
|
1866
|
-
var loadedOverlay;
|
|
1867
1863
|
var geometryClampLogSeen = new Set;
|
|
1868
|
-
function isRecord2(value) {
|
|
1869
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1870
|
-
}
|
|
1871
1864
|
function isFinitePositive(value) {
|
|
1872
1865
|
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
1873
1866
|
}
|
|
1874
|
-
function scalarizeFact(value) {
|
|
1875
|
-
if (value.kind === "stated")
|
|
1876
|
-
return isFinitePositive(value.value) ? value.value : undefined;
|
|
1877
|
-
if (value.kind === "bracket") {
|
|
1878
|
-
return isFinitePositive(value.at_least) ? value.at_least : undefined;
|
|
1879
|
-
}
|
|
1880
|
-
return;
|
|
1881
|
-
}
|
|
1882
|
-
function parseFactValue(value) {
|
|
1883
|
-
if (!isRecord2(value) || typeof value.kind !== "string")
|
|
1884
|
-
return;
|
|
1885
|
-
if (value.kind === "stated") {
|
|
1886
|
-
if ((typeof value.value !== "number" || !Number.isFinite(value.value)) && typeof value.value !== "string") {
|
|
1887
|
-
return;
|
|
1888
|
-
}
|
|
1889
|
-
return { kind: "stated", value: value.value };
|
|
1890
|
-
}
|
|
1891
|
-
if (value.kind === "bracket") {
|
|
1892
|
-
const atLeast = value.at_least;
|
|
1893
|
-
const below = value.below;
|
|
1894
|
-
if (atLeast === undefined && below === undefined)
|
|
1895
|
-
return { kind: "bracket" };
|
|
1896
|
-
if (atLeast !== undefined && !isFinitePositive(atLeast))
|
|
1897
|
-
return;
|
|
1898
|
-
if (below !== undefined && !isFinitePositive(below))
|
|
1899
|
-
return;
|
|
1900
|
-
if (isFinitePositive(atLeast) && isFinitePositive(below) && below <= atLeast) {
|
|
1901
|
-
return;
|
|
1902
|
-
}
|
|
1903
|
-
return {
|
|
1904
|
-
kind: "bracket",
|
|
1905
|
-
...isFinitePositive(atLeast) ? { at_least: atLeast } : {},
|
|
1906
|
-
...isFinitePositive(below) ? { below } : {}
|
|
1907
|
-
};
|
|
1908
|
-
}
|
|
1909
|
-
if (value.kind === "unknown" && UNKNOWN_REASONS.has(value.why)) {
|
|
1910
|
-
return { kind: "unknown", why: value.why };
|
|
1911
|
-
}
|
|
1912
|
-
return;
|
|
1913
|
-
}
|
|
1914
|
-
function parseFact(key, value) {
|
|
1915
|
-
if (!isRecord2(value))
|
|
1916
|
-
return;
|
|
1917
|
-
const parsedValue = parseFactValue(value.value);
|
|
1918
|
-
if (!parsedValue || !GRADES.has(value.grade) || !UNITS.has(value.units) || !BOUNDARIES.has(value.boundary) || typeof value.source_ref !== "string" || value.source_ref.length === 0 || typeof value.observed_at !== "string" || value.observed_at.length === 0) {
|
|
1919
|
-
return;
|
|
1920
|
-
}
|
|
1921
|
-
if (NUMERIC_FACT_KEYS.has(key) && parsedValue.kind === "stated" && !isFinitePositive(parsedValue.value)) {
|
|
1922
|
-
return;
|
|
1923
|
-
}
|
|
1924
|
-
if (key === "geometry" && parsedValue.kind === "stated" && !["shared_upfront", "shared_truncating", "separate"].includes(String(parsedValue.value))) {
|
|
1925
|
-
return;
|
|
1926
|
-
}
|
|
1927
|
-
return {
|
|
1928
|
-
...value,
|
|
1929
|
-
value: parsedValue,
|
|
1930
|
-
grade: value.grade,
|
|
1931
|
-
units: value.units,
|
|
1932
|
-
boundary: value.boundary,
|
|
1933
|
-
source_ref: value.source_ref,
|
|
1934
|
-
observed_at: value.observed_at
|
|
1935
|
-
};
|
|
1936
|
-
}
|
|
1937
|
-
function parseWindowOverlay(value) {
|
|
1938
|
-
if (!isRecord2(value)) {
|
|
1939
|
-
return { badCells: 0, refusal: "overlay root is not an object" };
|
|
1940
|
-
}
|
|
1941
|
-
if (value.schema !== WINDOW_OVERLAY_SCHEMA) {
|
|
1942
|
-
return {
|
|
1943
|
-
badCells: 0,
|
|
1944
|
-
refusal: `unrecognized schema ${JSON.stringify(value.schema)}`
|
|
1945
|
-
};
|
|
1946
|
-
}
|
|
1947
|
-
if (typeof value.generated_at !== "string" || !Array.isArray(value.minted_provider_ids) || !value.minted_provider_ids.every((id) => typeof id === "string" && id.length > 0) || !Array.isArray(value.cells)) {
|
|
1948
|
-
return { badCells: 0, refusal: "invalid v1 envelope" };
|
|
1949
|
-
}
|
|
1950
|
-
const cells = [];
|
|
1951
|
-
let badCells = 0;
|
|
1952
|
-
for (const rawCell of value.cells) {
|
|
1953
|
-
if (!isRecord2(rawCell) || typeof rawCell.provider_id !== "string" || rawCell.provider_id.length === 0 || typeof rawCell.model_id !== "string" || rawCell.model_id.length === 0 || !isRecord2(rawCell.facts)) {
|
|
1954
|
-
badCells++;
|
|
1955
|
-
continue;
|
|
1956
|
-
}
|
|
1957
|
-
const facts = {};
|
|
1958
|
-
let valid = true;
|
|
1959
|
-
for (const [key, rawFact] of Object.entries(rawCell.facts)) {
|
|
1960
|
-
const fact = parseFact(key, rawFact);
|
|
1961
|
-
if (!fact) {
|
|
1962
|
-
valid = false;
|
|
1963
|
-
break;
|
|
1964
|
-
}
|
|
1965
|
-
facts[key] = fact;
|
|
1966
|
-
}
|
|
1967
|
-
if (!valid) {
|
|
1968
|
-
badCells++;
|
|
1969
|
-
continue;
|
|
1970
|
-
}
|
|
1971
|
-
cells.push({
|
|
1972
|
-
provider_id: rawCell.provider_id,
|
|
1973
|
-
model_id: rawCell.model_id,
|
|
1974
|
-
facts
|
|
1975
|
-
});
|
|
1976
|
-
}
|
|
1977
|
-
return {
|
|
1978
|
-
overlay: {
|
|
1979
|
-
schema: WINDOW_OVERLAY_SCHEMA,
|
|
1980
|
-
generated_at: value.generated_at,
|
|
1981
|
-
minted_provider_ids: [...value.minted_provider_ids],
|
|
1982
|
-
cells
|
|
1983
|
-
},
|
|
1984
|
-
badCells
|
|
1985
|
-
};
|
|
1986
|
-
}
|
|
1987
|
-
function defaultWindowOverlayPath() {
|
|
1988
|
-
return join(getDataDir(), "fusiform", "window-overlay.json");
|
|
1989
|
-
}
|
|
1990
|
-
function readWindowOverlayFile(path, log = (message) => sessionLog2("global", message)) {
|
|
1991
|
-
let raw;
|
|
1992
|
-
try {
|
|
1993
|
-
raw = readFileSync2(path, "utf8");
|
|
1994
|
-
} catch (error) {
|
|
1995
|
-
if (error.code === "ENOENT")
|
|
1996
|
-
return;
|
|
1997
|
-
log(`window-overlay: unable to read ${path}; overlay ignored`);
|
|
1998
|
-
return;
|
|
1999
|
-
}
|
|
2000
|
-
let decoded;
|
|
2001
|
-
try {
|
|
2002
|
-
decoded = JSON.parse(raw);
|
|
2003
|
-
} catch {
|
|
2004
|
-
log(`window-overlay: invalid JSON in ${path}; overlay ignored`);
|
|
2005
|
-
return;
|
|
2006
|
-
}
|
|
2007
|
-
const parsed = parseWindowOverlay(decoded);
|
|
2008
|
-
if (parsed.refusal) {
|
|
2009
|
-
log(`window-overlay: ${parsed.refusal} in ${path}; entire overlay ignored`);
|
|
2010
|
-
return;
|
|
2011
|
-
}
|
|
2012
|
-
if (parsed.badCells > 0) {
|
|
2013
|
-
log(`window-overlay: skipped ${parsed.badCells} invalid cell(s) from ${path}`);
|
|
2014
|
-
}
|
|
2015
|
-
return parsed.overlay;
|
|
2016
|
-
}
|
|
2017
|
-
function setWindowOverlayPath(path) {
|
|
2018
|
-
if (configuredOverlayPath === path)
|
|
2019
|
-
return;
|
|
2020
|
-
reloadWindowOverlay(path);
|
|
2021
|
-
}
|
|
2022
|
-
function reloadWindowOverlay(path) {
|
|
2023
|
-
configuredOverlayPath = path;
|
|
2024
|
-
loadedOverlayPath = undefined;
|
|
2025
|
-
loadedOverlay = undefined;
|
|
2026
|
-
}
|
|
2027
|
-
function getWindowOverlay() {
|
|
2028
|
-
const path = configuredOverlayPath ?? defaultWindowOverlayPath();
|
|
2029
|
-
if (loadedOverlayPath === path && loadedOverlay !== undefined) {
|
|
2030
|
-
return loadedOverlay ?? undefined;
|
|
2031
|
-
}
|
|
2032
|
-
loadedOverlayPath = path;
|
|
2033
|
-
loadedOverlay = readWindowOverlayFile(path) ?? null;
|
|
2034
|
-
return loadedOverlay ?? undefined;
|
|
2035
|
-
}
|
|
2036
|
-
function resolveWindowOverlayFacts(providerID, modelID, overlay = getWindowOverlay()) {
|
|
2037
|
-
if (!overlay)
|
|
2038
|
-
return;
|
|
2039
|
-
const modelRefs = modelRefLookupOrder(`${providerID}/${modelID}`);
|
|
2040
|
-
const providerCandidates = new Set(modelRefs.map((ref) => ref.slice(0, ref.indexOf("/"))));
|
|
2041
|
-
const modelCandidates = new Set([
|
|
2042
|
-
modelID,
|
|
2043
|
-
...modelRefs.map((ref) => ref.slice(ref.indexOf("/") + 1))
|
|
2044
|
-
]);
|
|
2045
|
-
const colon = modelID.lastIndexOf(":");
|
|
2046
|
-
if (colon > 0)
|
|
2047
|
-
modelCandidates.add(modelID.slice(0, colon));
|
|
2048
|
-
const wildcardFacts = {};
|
|
2049
|
-
const specificFacts = {};
|
|
2050
|
-
for (const cell of overlay.cells) {
|
|
2051
|
-
if (!providerCandidates.has(cell.provider_id))
|
|
2052
|
-
continue;
|
|
2053
|
-
if (cell.model_id === "*")
|
|
2054
|
-
Object.assign(wildcardFacts, cell.facts);
|
|
2055
|
-
else if (modelCandidates.has(cell.model_id))
|
|
2056
|
-
Object.assign(specificFacts, cell.facts);
|
|
2057
|
-
}
|
|
2058
|
-
const facts = { ...wildcardFacts, ...specificFacts };
|
|
2059
|
-
return Object.keys(facts).length > 0 ? { facts } : undefined;
|
|
2060
|
-
}
|
|
2061
|
-
function numericOverlayFact(overlay, key) {
|
|
2062
|
-
const fact = overlay?.facts[key];
|
|
2063
|
-
return fact ? scalarizeFact(fact.value) : undefined;
|
|
2064
|
-
}
|
|
2065
|
-
function overlayGeometry(overlay) {
|
|
2066
|
-
const fact = overlay?.facts.geometry;
|
|
2067
|
-
if (fact === undefined)
|
|
2068
|
-
return;
|
|
2069
|
-
if (fact.value.kind === "unknown")
|
|
2070
|
-
return { kind: "unknown" };
|
|
2071
|
-
if (fact.value.kind !== "stated")
|
|
2072
|
-
return;
|
|
2073
|
-
const value = fact.value.value;
|
|
2074
|
-
return value === "shared_upfront" || value === "shared_truncating" || value === "separate" ? { kind: "stated", value } : undefined;
|
|
2075
|
-
}
|
|
2076
1867
|
function placeholderFilteredOutput(output, context) {
|
|
2077
1868
|
if (!isFinitePositive(output))
|
|
2078
1869
|
return;
|
|
@@ -2080,8 +1871,8 @@ function placeholderFilteredOutput(output, context) {
|
|
|
2080
1871
|
return;
|
|
2081
1872
|
return output;
|
|
2082
1873
|
}
|
|
2083
|
-
function mergePositive(
|
|
2084
|
-
return isFinitePositive(providerValue) ? providerValue :
|
|
1874
|
+
function mergePositive(catalogValue, providerValue) {
|
|
1875
|
+
return isFinitePositive(providerValue) ? providerValue : catalogValue;
|
|
2085
1876
|
}
|
|
2086
1877
|
function logGeometryClampOnce(key, message, log) {
|
|
2087
1878
|
if (geometryClampLogSeen.has(key))
|
|
@@ -2095,10 +1886,8 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
|
|
|
2095
1886
|
const providerLimit = options.providerLimit;
|
|
2096
1887
|
const catalogContext = isFinitePositive(catalogLimit?.context) ? catalogLimit.context : undefined;
|
|
2097
1888
|
const providerContext = isFinitePositive(providerLimit?.context) ? providerLimit.context : undefined;
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
let softContext = mergePositive(enforced ?? advertised ?? catalogContext, providerContext);
|
|
2101
|
-
let hardContext = mergePositive(enforced ?? softContext, providerContext);
|
|
1889
|
+
let softContext = mergePositive(catalogContext, providerContext);
|
|
1890
|
+
let hardContext = mergePositive(softContext, providerContext);
|
|
2102
1891
|
const contextCap = isFinitePositive(options.contextCap) ? options.contextCap : undefined;
|
|
2103
1892
|
const hasContextCap = contextCap !== undefined;
|
|
2104
1893
|
if (contextCap !== undefined) {
|
|
@@ -2108,13 +1897,10 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
|
|
|
2108
1897
|
const input = mergePositive(isFinitePositive(catalogLimit?.input) ? catalogLimit.input : undefined, providerLimit?.input);
|
|
2109
1898
|
if (!isFinitePositive(softContext) && !isFinitePositive(input))
|
|
2110
1899
|
return;
|
|
2111
|
-
const catalogOutput = options.
|
|
2112
|
-
const overlayOutput = placeholderFilteredOutput(numericOverlayFact(options.overlay, "output.enforced") ?? numericOverlayFact(options.overlay, "output.default") ?? numericOverlayFact(options.overlay, "output.advertised"), softContext);
|
|
1900
|
+
const catalogOutput = options.providerLimit === undefined ? isFinitePositive(catalogLimit?.output) ? catalogLimit.output : undefined : placeholderFilteredOutput(catalogLimit?.output, softContext);
|
|
2113
1901
|
const providerOutput = placeholderFilteredOutput(providerLimit?.output, softContext);
|
|
2114
|
-
const output = providerOutput ??
|
|
2115
|
-
const
|
|
2116
|
-
const geometry = geometryFact?.kind === "stated" ? geometryFact.value : geometryFact?.kind === "unknown" ? "shared_upfront" : PROVIDER_GEOMETRY[providerID] ?? "shared_upfront";
|
|
2117
|
-
const geometryOverride = geometryFact?.kind === "stated" ? geometryFact.value : undefined;
|
|
1902
|
+
const output = providerOutput ?? catalogOutput;
|
|
1903
|
+
const geometry = PROVIDER_GEOMETRY[providerID] ?? "shared_upfront";
|
|
2118
1904
|
const preCarvedInput = isFinitePositive(input) && (!isFinitePositive(softContext) || input < softContext);
|
|
2119
1905
|
const outputReserveOverride = typeof options.outputReserveOverride === "number" && Number.isFinite(options.outputReserveOverride) && options.outputReserveOverride >= 0 ? options.outputReserveOverride : undefined;
|
|
2120
1906
|
let derivationWindow = softContext ?? input;
|
|
@@ -2142,14 +1928,14 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
|
|
|
2142
1928
|
reserveSource = "output_catalog";
|
|
2143
1929
|
}
|
|
2144
1930
|
} else if (isFinitePositive(softContext)) {
|
|
2145
|
-
if (geometry === "separate"
|
|
1931
|
+
if (geometry === "separate") {
|
|
2146
1932
|
softReserve = 0;
|
|
2147
1933
|
reserveSource = "none";
|
|
2148
1934
|
} else {
|
|
2149
1935
|
softReserve = output ?? 0;
|
|
2150
1936
|
reserveSource = output === undefined ? "none" : "output_catalog";
|
|
2151
1937
|
const cap = softContext * OUTPUT_RESERVE_CAP_RATIO;
|
|
2152
|
-
softReserve = Math.min(softReserve,
|
|
1938
|
+
softReserve = Math.min(softReserve, cap);
|
|
2153
1939
|
}
|
|
2154
1940
|
const floor = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, softContext * 0.5);
|
|
2155
1941
|
const flooredReserve = Math.min(softReserve, Math.max(0, softContext - floor));
|
|
@@ -2164,7 +1950,7 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
|
|
|
2164
1950
|
const hardWindow = hardContext ?? softContext ?? input;
|
|
2165
1951
|
if (!isFinitePositive(hardWindow))
|
|
2166
1952
|
return;
|
|
2167
|
-
const windowSource = hasContextCap ? "detected" : providerContext !== undefined ? "provider" :
|
|
1953
|
+
const windowSource = hasContextCap ? "detected" : providerContext !== undefined ? "provider" : "catalog";
|
|
2168
1954
|
let usableHard;
|
|
2169
1955
|
if (geometry === "separate") {
|
|
2170
1956
|
usableHard = hardWindow;
|
|
@@ -2180,7 +1966,7 @@ function deriveWindowGeometry(providerID, modelID, catalogLimit, options = {}) {
|
|
|
2180
1966
|
}
|
|
2181
1967
|
usableHard = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, Math.floor(usableHard));
|
|
2182
1968
|
if (usableHard < usableSoft) {
|
|
2183
|
-
logGeometryClampOnce(`${providerID}/${modelID}|${usableSoft}|${usableHard}`, `usable hard limit clamped for ${providerID}/${modelID}: ${usableHard} → ${usableSoft} (
|
|
1969
|
+
logGeometryClampOnce(`${providerID}/${modelID}|${usableSoft}|${usableHard}`, `usable hard limit clamped for ${providerID}/${modelID}: ${usableHard} → ${usableSoft} (window limit inversion)`, options.log);
|
|
2184
1970
|
usableHard = usableSoft;
|
|
2185
1971
|
}
|
|
2186
1972
|
const resolvedWindow = derivationWindow ?? usableSoft;
|
|
@@ -2262,14 +2048,14 @@ var reserveClampLogSeen = new Set;
|
|
|
2262
2048
|
var apiCache = null;
|
|
2263
2049
|
var persistSeedLoaded = false;
|
|
2264
2050
|
function persistFilePath() {
|
|
2265
|
-
return
|
|
2051
|
+
return join(getMagicContextStorageDir(), `model-context-limits-${getHarness2()}.json`);
|
|
2266
2052
|
}
|
|
2267
2053
|
function loadPersistedApiCacheOnce() {
|
|
2268
2054
|
if (persistSeedLoaded || apiCache !== null)
|
|
2269
2055
|
return;
|
|
2270
2056
|
persistSeedLoaded = true;
|
|
2271
2057
|
try {
|
|
2272
|
-
const raw =
|
|
2058
|
+
const raw = readFileSync2(persistFilePath(), "utf-8");
|
|
2273
2059
|
const obj = JSON.parse(raw);
|
|
2274
2060
|
const map = new Map;
|
|
2275
2061
|
for (const [key, persisted] of Object.entries(obj)) {
|
|
@@ -2370,7 +2156,6 @@ function getSdkWindowGeometry(providerID, modelID, detectedContextLimit, options
|
|
|
2370
2156
|
input: metadata.inputLimit,
|
|
2371
2157
|
output: metadata.outputLimit
|
|
2372
2158
|
}, {
|
|
2373
|
-
overlay: resolveWindowOverlayFacts(providerID, modelID, getWindowOverlay()),
|
|
2374
2159
|
outputReserveOverride: resolveOutputReserve(providerID, modelID),
|
|
2375
2160
|
harness: options?.harness ?? "opencode",
|
|
2376
2161
|
contextCap: promptOnlyDetected === undefined && isFinitePositive2(detectedContextLimit) ? detectedContextLimit : undefined
|
|
@@ -2447,10 +2232,26 @@ function lookupMetadataWithTagFallback(cache, providerID, modelID) {
|
|
|
2447
2232
|
return;
|
|
2448
2233
|
}
|
|
2449
2234
|
|
|
2235
|
+
// ../plugin/src/config/deprecated-config.ts
|
|
2236
|
+
var MURAL_MODEL_DEPRECATION_WARNING = "mural.model is deprecated and ignored; compress-cues now uses the dreamer model for each harness, like every other dreamer task. To override it, set dreamer.opencode.tasks.compress-cues.model (or the pi/omp equivalent). This key no longer does anything; remove it.";
|
|
2237
|
+
var WINDOW_OVERLAY_PATH_DEPRECATION_WARNING = "models.window_overlay_path is deprecated and ignored; Fusiform no longer publishes window-overlay data, so this setting no longer changes model window geometry. Remove this key.";
|
|
2238
|
+
function warnDeprecatedMuralModel(config, warnings) {
|
|
2239
|
+
const mural = config.mural;
|
|
2240
|
+
if (typeof mural === "object" && mural !== null && Object.hasOwn(mural, "model")) {
|
|
2241
|
+
warnings.push(MURAL_MODEL_DEPRECATION_WARNING);
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
function warnDeprecatedWindowOverlayPath(config, warnings) {
|
|
2245
|
+
const models = config.models;
|
|
2246
|
+
if (typeof models === "object" && models !== null && Object.hasOwn(models, "window_overlay_path") && !warnings.includes(WINDOW_OVERLAY_PATH_DEPRECATION_WARNING)) {
|
|
2247
|
+
warnings.push(WINDOW_OVERLAY_PATH_DEPRECATION_WARNING);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2450
2251
|
// ../plugin/src/config/migrate-config-location.ts
|
|
2451
|
-
import { existsSync as existsSync2, readFileSync as
|
|
2252
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3, rmSync, statSync, unlinkSync } from "node:fs";
|
|
2452
2253
|
import { homedir } from "node:os";
|
|
2453
|
-
import { basename, dirname, isAbsolute, join as
|
|
2254
|
+
import { basename, dirname, isAbsolute, join as join2 } from "node:path";
|
|
2454
2255
|
|
|
2455
2256
|
// ../plugin/src/shared/jsonc-edit.ts
|
|
2456
2257
|
var TOKEN_COMMA = 5;
|
|
@@ -2563,13 +2364,13 @@ function configHome() {
|
|
|
2563
2364
|
const xdg = process.env.XDG_CONFIG_HOME;
|
|
2564
2365
|
if (xdg && isAbsolute(xdg))
|
|
2565
2366
|
return xdg;
|
|
2566
|
-
return
|
|
2367
|
+
return join2(homeDir(), ".config");
|
|
2567
2368
|
}
|
|
2568
2369
|
function cortexKitUserConfigBasePath() {
|
|
2569
|
-
return
|
|
2370
|
+
return join2(configHome(), "cortexkit", CONFIG_FILE_BASENAME);
|
|
2570
2371
|
}
|
|
2571
2372
|
function cortexKitProjectConfigBasePath(directory) {
|
|
2572
|
-
return
|
|
2373
|
+
return join2(directory, ".cortexkit", CONFIG_FILE_BASENAME);
|
|
2573
2374
|
}
|
|
2574
2375
|
function resolveCortexKitUserConfigPath() {
|
|
2575
2376
|
return `${cortexKitUserConfigBasePath()}.jsonc`;
|
|
@@ -2587,38 +2388,38 @@ function userScopeConfigPaths() {
|
|
|
2587
2388
|
return new Set([
|
|
2588
2389
|
`${cortexKitUserConfigBasePath()}.jsonc`,
|
|
2589
2390
|
`${cortexKitUserConfigBasePath()}.json`,
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2391
|
+
join2(configHome(), "opencode", `${CONFIG_FILE_BASENAME}.jsonc`),
|
|
2392
|
+
join2(configHome(), "opencode", `${CONFIG_FILE_BASENAME}.json`),
|
|
2393
|
+
join2(homeDir(), ".pi", "agent", `${CONFIG_FILE_BASENAME}.jsonc`),
|
|
2394
|
+
join2(homeDir(), ".pi", "agent", `${CONFIG_FILE_BASENAME}.json`)
|
|
2594
2395
|
]);
|
|
2595
2396
|
}
|
|
2596
2397
|
function resolveLegacyConfigSources(directory) {
|
|
2597
2398
|
const userPaths = userScopeConfigPaths();
|
|
2598
2399
|
return {
|
|
2599
2400
|
user: [
|
|
2600
|
-
...legacySourcesForBase(
|
|
2601
|
-
...legacySourcesForBase(
|
|
2401
|
+
...legacySourcesForBase(join2(configHome(), "opencode", CONFIG_FILE_BASENAME), "OpenCode user"),
|
|
2402
|
+
...legacySourcesForBase(join2(homeDir(), ".pi", "agent", CONFIG_FILE_BASENAME), "Pi user")
|
|
2602
2403
|
],
|
|
2603
2404
|
project: [
|
|
2604
|
-
...legacySourcesForBase(
|
|
2605
|
-
...legacySourcesForBase(
|
|
2606
|
-
...legacySourcesForBase(
|
|
2405
|
+
...legacySourcesForBase(join2(directory, CONFIG_FILE_BASENAME), "project root"),
|
|
2406
|
+
...legacySourcesForBase(join2(directory, ".opencode", CONFIG_FILE_BASENAME), "OpenCode project"),
|
|
2407
|
+
...legacySourcesForBase(join2(directory, ".pi", CONFIG_FILE_BASENAME), "Pi project")
|
|
2607
2408
|
].filter((source) => !userPaths.has(source.path))
|
|
2608
2409
|
};
|
|
2609
2410
|
}
|
|
2610
2411
|
function resolveLegacyConfigSourcesForHarness(directory, harness) {
|
|
2611
2412
|
if (harness === "pi") {
|
|
2612
2413
|
return {
|
|
2613
|
-
user: legacySourcesForBase(
|
|
2614
|
-
project: legacySourcesForBase(
|
|
2414
|
+
user: legacySourcesForBase(join2(homeDir(), ".pi", "agent", CONFIG_FILE_BASENAME), "Pi user"),
|
|
2415
|
+
project: legacySourcesForBase(join2(directory, ".pi", CONFIG_FILE_BASENAME), "Pi project")
|
|
2615
2416
|
};
|
|
2616
2417
|
}
|
|
2617
2418
|
return {
|
|
2618
|
-
user: legacySourcesForBase(
|
|
2419
|
+
user: legacySourcesForBase(join2(configHome(), "opencode", CONFIG_FILE_BASENAME), "OpenCode user"),
|
|
2619
2420
|
project: [
|
|
2620
|
-
...legacySourcesForBase(
|
|
2621
|
-
...legacySourcesForBase(
|
|
2421
|
+
...legacySourcesForBase(join2(directory, CONFIG_FILE_BASENAME), "project root"),
|
|
2422
|
+
...legacySourcesForBase(join2(directory, ".opencode", CONFIG_FILE_BASENAME), "OpenCode project")
|
|
2622
2423
|
]
|
|
2623
2424
|
};
|
|
2624
2425
|
}
|
|
@@ -2777,7 +2578,7 @@ function markLegacySourcesMovedAside(sources, targetPath, logger) {
|
|
|
2777
2578
|
for (const source of sources) {
|
|
2778
2579
|
const markerPath = `${source.path}${MOVED_MARKER_SUFFIX}`;
|
|
2779
2580
|
try {
|
|
2780
|
-
const original =
|
|
2581
|
+
const original = readFileSync3(source.path, "utf-8");
|
|
2781
2582
|
atomicWriteConfigFile(markerPath, movedMarkerContent(targetPath, basename(source.path), original));
|
|
2782
2583
|
unlinkSync(source.path);
|
|
2783
2584
|
info?.(`Moved legacy Magic Context config ${source.path} aside to ${markerPath}; now reading ${targetPath}`);
|
|
@@ -2809,10 +2610,10 @@ function migrateConfigFile(opts) {
|
|
|
2809
2610
|
try {
|
|
2810
2611
|
const sources = existingSources.map((source) => ({
|
|
2811
2612
|
...source,
|
|
2812
|
-
content:
|
|
2613
|
+
content: readFileSync3(source.path, "utf-8")
|
|
2813
2614
|
}));
|
|
2814
2615
|
if (existsSync2(opts.targetPath)) {
|
|
2815
|
-
const targetContent =
|
|
2616
|
+
const targetContent = readFileSync3(opts.targetPath, "utf-8");
|
|
2816
2617
|
const differing = sources.filter((source) => !fileSemanticsMatch(source.content, targetContent));
|
|
2817
2618
|
if (differing.length > 0) {
|
|
2818
2619
|
const message = visibleConfigMigrationWarning(opts.scope, opts.targetPath, differing.map((source) => source.path), "the CortexKit target already exists with different settings");
|
|
@@ -3200,15 +3001,6 @@ function migrateLegacyExperimental(rawConfig, warnings) {
|
|
|
3200
3001
|
return patched;
|
|
3201
3002
|
}
|
|
3202
3003
|
|
|
3203
|
-
// ../plugin/src/config/mural-model-deprecation.ts
|
|
3204
|
-
var MURAL_MODEL_DEPRECATION_WARNING = "mural.model is deprecated and ignored; compress-cues now uses the dreamer model for each harness, like every other dreamer task. To override it, set dreamer.opencode.tasks.compress-cues.model (or the pi/omp equivalent). This key no longer does anything; remove it.";
|
|
3205
|
-
function warnDeprecatedMuralModel(config, warnings) {
|
|
3206
|
-
const mural = config.mural;
|
|
3207
|
-
if (typeof mural === "object" && mural !== null && Object.hasOwn(mural, "model")) {
|
|
3208
|
-
warnings.push(MURAL_MODEL_DEPRECATION_WARNING);
|
|
3209
|
-
}
|
|
3210
|
-
}
|
|
3211
|
-
|
|
3212
3004
|
// ../plugin/src/config/profiles.ts
|
|
3213
3005
|
function withoutProfileFields(raw) {
|
|
3214
3006
|
const copy = { ...raw };
|
|
@@ -3470,7 +3262,7 @@ function stripUnsafeProjectConfigFields(projectRaw) {
|
|
|
3470
3262
|
const models = projectRaw.models;
|
|
3471
3263
|
if (isPlainObject(models) && "window_overlay_path" in models) {
|
|
3472
3264
|
delete models.window_overlay_path;
|
|
3473
|
-
warnings.push("Ignoring models.window_overlay_path from project config (
|
|
3265
|
+
warnings.push("Ignoring models.window_overlay_path from project config (deprecated; this setting no longer changes model window geometry).");
|
|
3474
3266
|
}
|
|
3475
3267
|
if ("language" in projectRaw) {
|
|
3476
3268
|
delete projectRaw.language;
|
|
@@ -3857,26 +3649,26 @@ import {
|
|
|
3857
3649
|
existsSync as existsSync3,
|
|
3858
3650
|
linkSync,
|
|
3859
3651
|
openSync,
|
|
3860
|
-
readFileSync as
|
|
3652
|
+
readFileSync as readFileSync4,
|
|
3861
3653
|
realpathSync,
|
|
3862
3654
|
renameSync,
|
|
3863
3655
|
statSync as statSync2,
|
|
3864
3656
|
unlinkSync as unlinkSync2,
|
|
3865
3657
|
writeFileSync
|
|
3866
3658
|
} from "node:fs";
|
|
3867
|
-
import { basename as basename2, dirname as dirname2, join as
|
|
3659
|
+
import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
|
|
3868
3660
|
var MODEL_FIELDS = ["model", "fallback_models"];
|
|
3869
3661
|
var QUALIFIER_FIELDS = ["variant", "thinking_level"];
|
|
3870
3662
|
var TASK_MODEL_FIELDS = [...MODEL_FIELDS, ...QUALIFIER_FIELDS, "timeout_minutes"];
|
|
3871
3663
|
var PRE_PER_HARNESS_BACKUP_SUFFIX = ".pre-per-harness.bak";
|
|
3872
3664
|
var temporaryFileSequence = 0;
|
|
3873
|
-
function
|
|
3665
|
+
function isRecord2(value) {
|
|
3874
3666
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3875
3667
|
}
|
|
3876
3668
|
function asDocument(text) {
|
|
3877
3669
|
try {
|
|
3878
3670
|
const document = parseJsonc(text.startsWith("\uFEFF") ? text.slice(1) : text);
|
|
3879
|
-
return
|
|
3671
|
+
return isRecord2(document) ? document : null;
|
|
3880
3672
|
} catch {
|
|
3881
3673
|
return null;
|
|
3882
3674
|
}
|
|
@@ -3884,7 +3676,7 @@ function asDocument(text) {
|
|
|
3884
3676
|
function getAtPath(document, path) {
|
|
3885
3677
|
let current = document;
|
|
3886
3678
|
for (const part of path) {
|
|
3887
|
-
if (!
|
|
3679
|
+
if (!isRecord2(current) || !Object.hasOwn(current, part))
|
|
3888
3680
|
return;
|
|
3889
3681
|
current = current[part];
|
|
3890
3682
|
}
|
|
@@ -3893,7 +3685,7 @@ function getAtPath(document, path) {
|
|
|
3893
3685
|
function stableJson(value) {
|
|
3894
3686
|
if (Array.isArray(value))
|
|
3895
3687
|
return `[${value.map(stableJson).join(",")}]`;
|
|
3896
|
-
if (!
|
|
3688
|
+
if (!isRecord2(value))
|
|
3897
3689
|
return JSON.stringify(value);
|
|
3898
3690
|
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
|
|
3899
3691
|
}
|
|
@@ -3906,7 +3698,7 @@ function valueForDiagnostic(value) {
|
|
|
3906
3698
|
function migrateEntryForHarness(value, harness) {
|
|
3907
3699
|
if (Array.isArray(value))
|
|
3908
3700
|
return value.map((entry) => migrateEntryForHarness(entry, harness));
|
|
3909
|
-
if (!
|
|
3701
|
+
if (!isRecord2(value) || !Object.hasOwn(value, "model"))
|
|
3910
3702
|
return value;
|
|
3911
3703
|
const entry = { model: value.model };
|
|
3912
3704
|
if (harness === "opencode" && Object.hasOwn(value, "variant")) {
|
|
@@ -3927,11 +3719,11 @@ function canCreateAtPath(document, path) {
|
|
|
3927
3719
|
for (const part of path) {
|
|
3928
3720
|
if (current === undefined)
|
|
3929
3721
|
return true;
|
|
3930
|
-
if (!
|
|
3722
|
+
if (!isRecord2(current))
|
|
3931
3723
|
return false;
|
|
3932
3724
|
current = current[part];
|
|
3933
3725
|
}
|
|
3934
|
-
return current === undefined ||
|
|
3726
|
+
return current === undefined || isRecord2(current);
|
|
3935
3727
|
}
|
|
3936
3728
|
function flatFieldPath(parts) {
|
|
3937
3729
|
return parts.join(".");
|
|
@@ -3972,7 +3764,7 @@ function updateDocumentForFlatFields(text) {
|
|
|
3972
3764
|
};
|
|
3973
3765
|
const migrateAgentFields = (agentName) => {
|
|
3974
3766
|
const agent = document[agentName];
|
|
3975
|
-
if (!
|
|
3767
|
+
if (!isRecord2(agent))
|
|
3976
3768
|
return;
|
|
3977
3769
|
for (const field of MODEL_FIELDS) {
|
|
3978
3770
|
if (!Object.hasOwn(agent, field))
|
|
@@ -4003,11 +3795,11 @@ function updateDocumentForFlatFields(text) {
|
|
|
4003
3795
|
migrateAgentFields("historian");
|
|
4004
3796
|
migrateAgentFields("dreamer");
|
|
4005
3797
|
const dreamer = document.dreamer;
|
|
4006
|
-
const tasks =
|
|
4007
|
-
if (
|
|
3798
|
+
const tasks = isRecord2(dreamer) ? dreamer.tasks : undefined;
|
|
3799
|
+
if (isRecord2(tasks)) {
|
|
4008
3800
|
for (const taskName of Object.keys(tasks).sort()) {
|
|
4009
3801
|
const task = tasks[taskName];
|
|
4010
|
-
if (!
|
|
3802
|
+
if (!isRecord2(task))
|
|
4011
3803
|
continue;
|
|
4012
3804
|
for (const field of TASK_MODEL_FIELDS) {
|
|
4013
3805
|
if (!Object.hasOwn(task, field))
|
|
@@ -4063,7 +3855,7 @@ function writeExclusiveBackup(backupPath, bytes, mode) {
|
|
|
4063
3855
|
if (error.code !== "EEXIST")
|
|
4064
3856
|
throw error;
|
|
4065
3857
|
}
|
|
4066
|
-
const existingBytes =
|
|
3858
|
+
const existingBytes = readFileSync4(backupPath);
|
|
4067
3859
|
if (existingBytes.equals(bytes))
|
|
4068
3860
|
return;
|
|
4069
3861
|
if (bytes.subarray(0, existingBytes.length).equals(existingBytes)) {
|
|
@@ -4081,7 +3873,7 @@ function writeTemporaryCandidate(configPath, bytes, mode) {
|
|
|
4081
3873
|
const stem = basename2(configPath);
|
|
4082
3874
|
for (let attempt = 0;attempt < 32; attempt++) {
|
|
4083
3875
|
temporaryFileSequence += 1;
|
|
4084
|
-
const path =
|
|
3876
|
+
const path = join3(directory, `.${stem}.per-harness-${process.pid}-${temporaryFileSequence}.tmp`);
|
|
4085
3877
|
let descriptor;
|
|
4086
3878
|
try {
|
|
4087
3879
|
descriptor = openSync(path, "wx", mode);
|
|
@@ -4111,7 +3903,7 @@ function loadRawConfigFile(options) {
|
|
|
4111
3903
|
return null;
|
|
4112
3904
|
let observedBytes;
|
|
4113
3905
|
try {
|
|
4114
|
-
observedBytes =
|
|
3906
|
+
observedBytes = readFileSync4(options.configPath);
|
|
4115
3907
|
} catch (error) {
|
|
4116
3908
|
throw new Error(`failed to read config: ${error instanceof Error ? error.message : String(error)}`);
|
|
4117
3909
|
}
|
|
@@ -4156,7 +3948,7 @@ function loadRawConfigFile(options) {
|
|
|
4156
3948
|
writeExclusiveBackup(backupPath, observedBytes, mode);
|
|
4157
3949
|
temporaryPath = writeTemporaryCandidate(writePath, migration.bytes, mode);
|
|
4158
3950
|
options.afterTemporaryWrite?.();
|
|
4159
|
-
const currentBytes =
|
|
3951
|
+
const currentBytes = readFileSync4(options.configPath);
|
|
4160
3952
|
if (!hasFlatKeys(currentBytes)) {
|
|
4161
3953
|
unlinkSync2(temporaryPath);
|
|
4162
3954
|
return {
|
|
@@ -4238,7 +4030,7 @@ function stripRemovedAgentConfig(rawConfig, warnings) {
|
|
|
4238
4030
|
}
|
|
4239
4031
|
|
|
4240
4032
|
// ../plugin/src/config/variable.ts
|
|
4241
|
-
import { existsSync as existsSync4, readFileSync as
|
|
4033
|
+
import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
|
|
4242
4034
|
import { homedir as homedir2 } from "node:os";
|
|
4243
4035
|
import { dirname as dirname3, isAbsolute as isAbsolute2, resolve } from "node:path";
|
|
4244
4036
|
var ENV_PATTERN = /\{env:([^}]+)\}/g;
|
|
@@ -4321,7 +4113,7 @@ function substituteConfigVariables(input) {
|
|
|
4321
4113
|
}
|
|
4322
4114
|
let contents;
|
|
4323
4115
|
try {
|
|
4324
|
-
contents =
|
|
4116
|
+
contents = readFileSync5(filePath, "utf-8").trim();
|
|
4325
4117
|
} catch (error) {
|
|
4326
4118
|
const message = error instanceof Error ? error.message : String(error);
|
|
4327
4119
|
warnings.push(`Failed to read file for ${token} (${filePath}): ${message}; using empty string`);
|
|
@@ -4332,2436 +4124,67 @@ function substituteConfigVariables(input) {
|
|
|
4332
4124
|
output += text.slice(cursor);
|
|
4333
4125
|
return { text: output, warnings };
|
|
4334
4126
|
}
|
|
4127
|
+
// ../plugin/src/features/magic-context/storage-meta-session.ts
|
|
4128
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
4335
4129
|
|
|
4336
|
-
// ../plugin/src/shared/
|
|
4337
|
-
|
|
4338
|
-
|
|
4339
|
-
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
var MAX_EXECUTE_THRESHOLD = 90;
|
|
4345
|
-
var ABSOLUTE_EMERGENCY_PERCENTAGE = 95;
|
|
4346
|
-
function escalationBands(effectiveThresholdPercentage) {
|
|
4347
|
-
const threshold = Number.isFinite(effectiveThresholdPercentage) ? Math.min(effectiveThresholdPercentage, MAX_EXECUTE_THRESHOLD) : 65;
|
|
4348
|
-
return {
|
|
4349
|
-
forceMaterializationPercentage: Math.max(85, threshold + 2),
|
|
4350
|
-
emergencyPercentage: ABSOLUTE_EMERGENCY_PERCENTAGE
|
|
4351
|
-
};
|
|
4352
|
-
}
|
|
4353
|
-
|
|
4354
|
-
// ../plugin/src/features/magic-context/merged-reasoning-decisions.ts
|
|
4355
|
-
var MERGED_REASONING_PARTS_PREFIX = "__merged_reasoning_parts_v1__:";
|
|
4356
|
-
var decodedDecisions = new Map;
|
|
4357
|
-
var decodedDecisionBytes = 0;
|
|
4358
|
-
var MAX_DECODED_DECISION_BYTES = 32 * 1024 * 1024;
|
|
4359
|
-
function decodeMergedReasoningParts(value) {
|
|
4360
|
-
if (!value.startsWith(MERGED_REASONING_PARTS_PREFIX))
|
|
4361
|
-
return null;
|
|
4362
|
-
try {
|
|
4363
|
-
const record = JSON.parse(value.slice(MERGED_REASONING_PARTS_PREFIX.length));
|
|
4364
|
-
if (!Array.isArray(record) || record.length !== 2)
|
|
4365
|
-
return null;
|
|
4366
|
-
const [id, parts] = record;
|
|
4367
|
-
if (typeof id !== "string" || id.length === 0 || !Array.isArray(parts) || parts.length === 0)
|
|
4368
|
-
return null;
|
|
4369
|
-
if (!parts.every((part) => typeof part === "string" && part.length > 0 || typeof part === "number" && Number.isSafeInteger(part) && part >= 0))
|
|
4370
|
-
return null;
|
|
4371
|
-
return [id, parts];
|
|
4372
|
-
} catch {
|
|
4373
|
-
return null;
|
|
4374
|
-
}
|
|
4375
|
-
}
|
|
4376
|
-
function readFrozenMergedReasoningParts(ids) {
|
|
4377
|
-
const decisions = new Map;
|
|
4378
|
-
for (const value of ids) {
|
|
4379
|
-
let record = decodedDecisions.get(value);
|
|
4380
|
-
if (record === undefined) {
|
|
4381
|
-
record = decodeMergedReasoningParts(value);
|
|
4382
|
-
const bytes = 2 * value.length + 128;
|
|
4383
|
-
if (bytes <= MAX_DECODED_DECISION_BYTES) {
|
|
4384
|
-
while (decodedDecisions.size >= 1e5 || decodedDecisionBytes + bytes > MAX_DECODED_DECISION_BYTES) {
|
|
4385
|
-
const oldest = decodedDecisions.keys().next().value;
|
|
4386
|
-
if (oldest === undefined)
|
|
4387
|
-
break;
|
|
4388
|
-
decodedDecisionBytes -= 2 * oldest.length + 128;
|
|
4389
|
-
decodedDecisions.delete(oldest);
|
|
4390
|
-
}
|
|
4391
|
-
decodedDecisions.set(value, record);
|
|
4392
|
-
decodedDecisionBytes += bytes;
|
|
4393
|
-
}
|
|
4394
|
-
}
|
|
4395
|
-
if (record && !decisions.has(record[0]))
|
|
4396
|
-
decisions.set(record[0], [...record[1]]);
|
|
4130
|
+
// ../plugin/src/shared/auto-search-lifecycle.ts
|
|
4131
|
+
var pending = new Map;
|
|
4132
|
+
var unpublishedNoHints = new Map;
|
|
4133
|
+
function rememberUnpublishedAutoSearchNoHint(sessionId, messageId, reason) {
|
|
4134
|
+
let messages = unpublishedNoHints.get(sessionId);
|
|
4135
|
+
if (!messages) {
|
|
4136
|
+
messages = new Map;
|
|
4137
|
+
unpublishedNoHints.set(sessionId, messages);
|
|
4397
4138
|
}
|
|
4398
|
-
|
|
4139
|
+
if (!messages.has(messageId))
|
|
4140
|
+
messages.set(messageId, reason);
|
|
4399
4141
|
}
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
var CALIBRATION_STATE_KEY = "magicContextTokenizerCalibration";
|
|
4403
|
-
var HYGIENE_PROVIDER_UNITS_VERSION = 2;
|
|
4404
|
-
function finitePositive(value) {
|
|
4405
|
-
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
4142
|
+
function getUnpublishedAutoSearchNoHint(sessionId, messageId) {
|
|
4143
|
+
return unpublishedNoHints.get(sessionId)?.get(messageId);
|
|
4406
4144
|
}
|
|
4407
|
-
function
|
|
4408
|
-
|
|
4409
|
-
|
|
4410
|
-
|
|
4411
|
-
|
|
4412
|
-
return null;
|
|
4413
|
-
}
|
|
4414
|
-
return {
|
|
4415
|
-
revision: candidate.revision,
|
|
4416
|
-
providerId: candidate.providerId,
|
|
4417
|
-
modelId: candidate.modelId,
|
|
4418
|
-
systemRatio: candidate.systemRatio,
|
|
4419
|
-
toolsRatio: candidate.toolsRatio,
|
|
4420
|
-
proseRatio: candidate.proseRatio,
|
|
4421
|
-
source: candidate.source
|
|
4422
|
-
};
|
|
4145
|
+
function forgetUnpublishedAutoSearchNoHint(sessionId, messageId) {
|
|
4146
|
+
const messages = unpublishedNoHints.get(sessionId);
|
|
4147
|
+
messages?.delete(messageId);
|
|
4148
|
+
if (messages?.size === 0)
|
|
4149
|
+
unpublishedNoHints.delete(sessionId);
|
|
4423
4150
|
}
|
|
4424
|
-
function
|
|
4425
|
-
if (
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? { ...parsed } : {};
|
|
4430
|
-
} catch {
|
|
4431
|
-
return {};
|
|
4432
|
-
}
|
|
4151
|
+
function clearUnpublishedAutoSearchNoHints(sessionId) {
|
|
4152
|
+
if (sessionId === undefined)
|
|
4153
|
+
unpublishedNoHints.clear();
|
|
4154
|
+
else
|
|
4155
|
+
unpublishedNoHints.delete(sessionId);
|
|
4433
4156
|
}
|
|
4434
|
-
function
|
|
4435
|
-
const
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
|
|
4439
|
-
const active = parseFrozenCalibration(namespace.active);
|
|
4157
|
+
function registerAutoSearchWork(sessionId) {
|
|
4158
|
+
const controller = new AbortController;
|
|
4159
|
+
const work = pending.get(sessionId) ?? new Set;
|
|
4160
|
+
pending.set(sessionId, work);
|
|
4161
|
+
work.add(controller);
|
|
4440
4162
|
return {
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
try {
|
|
4447
|
-
return db.prepare("SELECT COALESCE(NULLIF(cached_m0_model_key, ''), last_observed_model_key) AS model_key, deferred_execute_state, last_nudge_undropped, last_nudge_level FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
4448
|
-
} catch {
|
|
4449
|
-
try {
|
|
4450
|
-
return db.prepare("SELECT COALESCE(NULLIF(cached_m0_model_key, ''), last_observed_model_key) AS model_key, deferred_execute_state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
4451
|
-
} catch {
|
|
4452
|
-
return;
|
|
4163
|
+
signal: controller.signal,
|
|
4164
|
+
done: () => {
|
|
4165
|
+
work.delete(controller);
|
|
4166
|
+
if (pending.get(sessionId) === work && work.size === 0)
|
|
4167
|
+
pending.delete(sessionId);
|
|
4453
4168
|
}
|
|
4454
|
-
}
|
|
4455
|
-
}
|
|
4456
|
-
function splitCanonicalModelKey(modelKey) {
|
|
4457
|
-
const slash = modelKey.indexOf("/");
|
|
4458
|
-
return slash > 0 ? { providerId: modelKey.slice(0, slash), modelId: modelKey.slice(slash + 1) } : { providerId: "unknown", modelId: "unknown" };
|
|
4459
|
-
}
|
|
4460
|
-
function freezeCalibration(calibration) {
|
|
4461
|
-
const identity = splitCanonicalModelKey(calibration.modelKey);
|
|
4462
|
-
return {
|
|
4463
|
-
revision: calibration.revision,
|
|
4464
|
-
providerId: identity.providerId,
|
|
4465
|
-
modelId: identity.modelId,
|
|
4466
|
-
systemRatio: calibration.systemRatio,
|
|
4467
|
-
toolsRatio: calibration.toolsRatio,
|
|
4468
|
-
proseRatio: calibration.proseRatio,
|
|
4469
|
-
source: calibration.source
|
|
4470
4169
|
};
|
|
4471
4170
|
}
|
|
4472
|
-
function
|
|
4473
|
-
const
|
|
4474
|
-
|
|
4475
|
-
|
|
4476
|
-
|
|
4477
|
-
|
|
4478
|
-
|
|
4479
|
-
systemRatio: frozen.systemRatio,
|
|
4480
|
-
toolsRatio: frozen.toolsRatio,
|
|
4481
|
-
proseRatio: frozen.proseRatio
|
|
4482
|
-
});
|
|
4483
|
-
}
|
|
4484
|
-
function sameCalibration(left, right) {
|
|
4485
|
-
return left.revision === right.revision && left.providerId === right.providerId && left.modelId === right.modelId && left.systemRatio === right.systemRatio && left.toolsRatio === right.toolsRatio && left.proseRatio === right.proseRatio && left.source === right.source;
|
|
4486
|
-
}
|
|
4487
|
-
function persistNamespace(db, sessionId, root, namespace) {
|
|
4488
|
-
root[CALIBRATION_STATE_KEY] = namespace;
|
|
4489
|
-
db.prepare("UPDATE session_meta SET deferred_execute_state = ? WHERE session_id = ?").run(JSON.stringify(root), sessionId);
|
|
4490
|
-
}
|
|
4491
|
-
function sessionDecisionCalibration(db, sessionId, pass) {
|
|
4492
|
-
const row = readSessionRow(db, sessionId);
|
|
4493
|
-
const root = parseStateRoot(row?.deferred_execute_state);
|
|
4494
|
-
const namespace = parseNamespace(root);
|
|
4495
|
-
if (!pass?.bustPermitted) {
|
|
4496
|
-
return namespace.active ? thawCalibration(namespace.active) : resolveDecisionCalibration(undefined, undefined);
|
|
4497
|
-
}
|
|
4498
|
-
const key = piModelRefToCanonical(pass.modelKey ?? row?.model_key ?? "");
|
|
4499
|
-
const candidate = freezeCalibration(calibrationForModelKey(key));
|
|
4500
|
-
if (!namespace.active || !sameCalibration(namespace.active, candidate)) {
|
|
4501
|
-
const previousRevision = namespace.active?.revision ?? "unfrozen";
|
|
4502
|
-
persistNamespace(db, sessionId, root, { ...namespace, active: candidate });
|
|
4503
|
-
if (namespace.active) {
|
|
4504
|
-
pass.onAdopt?.(`calibration revision ${previousRevision} → ${candidate.revision} adopted (bust=${pass.bustReason ?? "unknown"})`);
|
|
4505
|
-
}
|
|
4506
|
-
}
|
|
4507
|
-
return thawCalibration(candidate);
|
|
4508
|
-
}
|
|
4509
|
-
function sessionHygieneUnitsVersion(db, sessionId) {
|
|
4510
|
-
const row = readSessionRow(db, sessionId);
|
|
4511
|
-
return parseNamespace(parseStateRoot(row?.deferred_execute_state)).hygieneUnitsVersion ?? 1;
|
|
4512
|
-
}
|
|
4513
|
-
function parseNudgeLevelState(raw) {
|
|
4514
|
-
if (!raw)
|
|
4515
|
-
return null;
|
|
4516
|
-
try {
|
|
4517
|
-
const parsed = JSON.parse(raw);
|
|
4518
|
-
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? { ...parsed } : null;
|
|
4519
|
-
} catch {
|
|
4520
|
-
return null;
|
|
4171
|
+
function cancelAutoSearchWork(sessionId) {
|
|
4172
|
+
for (const [id, work] of pending) {
|
|
4173
|
+
if (sessionId !== undefined && id !== sessionId)
|
|
4174
|
+
continue;
|
|
4175
|
+
pending.delete(id);
|
|
4176
|
+
for (const controller of work)
|
|
4177
|
+
controller.abort();
|
|
4521
4178
|
}
|
|
4522
4179
|
}
|
|
4523
|
-
function scaledWatermark(value, ratio) {
|
|
4524
|
-
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.round(value * ratio)) : null;
|
|
4525
|
-
}
|
|
4526
|
-
function transitionSessionHygieneUnits(db, sessionId, bustPermitted, calibration) {
|
|
4527
|
-
const before = sessionHygieneUnitsVersion(db, sessionId);
|
|
4528
|
-
if (before >= HYGIENE_PROVIDER_UNITS_VERSION || !bustPermitted)
|
|
4529
|
-
return before;
|
|
4530
|
-
return db.transaction(() => {
|
|
4531
|
-
const row = readSessionRow(db, sessionId);
|
|
4532
|
-
const root = parseStateRoot(row?.deferred_execute_state);
|
|
4533
|
-
const namespace = parseNamespace(root);
|
|
4534
|
-
if ((namespace.hygieneUnitsVersion ?? 1) >= HYGIENE_PROVIDER_UNITS_VERSION) {
|
|
4535
|
-
return HYGIENE_PROVIDER_UNITS_VERSION;
|
|
4536
|
-
}
|
|
4537
|
-
const lastNudge = scaledWatermark(row?.last_nudge_undropped, calibration.toolsRatio);
|
|
4538
|
-
const nudgeLevel = parseNudgeLevelState(row?.last_nudge_level);
|
|
4539
|
-
if (nudgeLevel) {
|
|
4540
|
-
const grace = scaledWatermark(nudgeLevel.postReduceGraceBaselineU, calibration.toolsRatio);
|
|
4541
|
-
if (grace !== null)
|
|
4542
|
-
nudgeLevel.postReduceGraceBaselineU = grace;
|
|
4543
|
-
}
|
|
4544
|
-
db.prepare("UPDATE session_meta SET last_nudge_undropped = COALESCE(?, last_nudge_undropped), last_nudge_level = COALESCE(?, last_nudge_level) WHERE session_id = ?").run(lastNudge, nudgeLevel ? JSON.stringify(nudgeLevel) : null, sessionId);
|
|
4545
|
-
persistNamespace(db, sessionId, root, {
|
|
4546
|
-
...namespace,
|
|
4547
|
-
hygieneUnitsVersion: HYGIENE_PROVIDER_UNITS_VERSION
|
|
4548
|
-
});
|
|
4549
|
-
return HYGIENE_PROVIDER_UNITS_VERSION;
|
|
4550
|
-
}).immediate();
|
|
4551
|
-
}
|
|
4552
4180
|
|
|
4553
|
-
// ../plugin/src/
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
return
|
|
4560
|
-
}
|
|
4561
|
-
function getRowKind(row) {
|
|
4562
|
-
return (row.kind ?? row.type ?? "").toLowerCase();
|
|
4563
|
-
}
|
|
4564
|
-
function getRowTagNumber(row) {
|
|
4565
|
-
const num = row.tag_number ?? row.tagNumber;
|
|
4566
|
-
if (typeof num === "number" && Number.isFinite(num)) {
|
|
4567
|
-
return num;
|
|
4568
|
-
}
|
|
4569
|
-
return 0;
|
|
4570
|
-
}
|
|
4571
|
-
function getRowIdentity(row) {
|
|
4572
|
-
const id = row.row_identity ?? row.id;
|
|
4573
|
-
if (id !== undefined && id !== null) {
|
|
4574
|
-
return id;
|
|
4575
|
-
}
|
|
4576
|
-
return getRowTagNumber(row);
|
|
4577
|
-
}
|
|
4578
|
-
function rowKey(row) {
|
|
4579
|
-
return `${getRowTagNumber(row)}:${getRowIdentity(row)}`;
|
|
4580
|
-
}
|
|
4581
|
-
function compareRowsAscending(a, b) {
|
|
4582
|
-
const tagDiff = getRowTagNumber(a) - getRowTagNumber(b);
|
|
4583
|
-
if (tagDiff !== 0)
|
|
4584
|
-
return tagDiff;
|
|
4585
|
-
const idA = getRowIdentity(a);
|
|
4586
|
-
const idB = getRowIdentity(b);
|
|
4587
|
-
if (typeof idA === "number" && typeof idB === "number") {
|
|
4588
|
-
return idA - idB;
|
|
4589
|
-
}
|
|
4590
|
-
return String(idA).localeCompare(String(idB));
|
|
4591
|
-
}
|
|
4592
|
-
function computeProtectionWindow(rows, floor, toolsRatio = 1) {
|
|
4593
|
-
const toolRows = rows.filter((r) => getRowKind(r) === "tool");
|
|
4594
|
-
if (toolRows.length === 0) {
|
|
4595
|
-
return {
|
|
4596
|
-
memberRows: [],
|
|
4597
|
-
memberRowKeys: new Set,
|
|
4598
|
-
tagNumberSet: { coordinateSpace: "tag-number", tagNumbers: new Set },
|
|
4599
|
-
rowIdentitySet: {
|
|
4600
|
-
coordinateSpace: "row-identity",
|
|
4601
|
-
rowIdentities: new Set
|
|
4602
|
-
},
|
|
4603
|
-
ordinalCutoff: { coordinateSpace: "tag-number", cutoff: null },
|
|
4604
|
-
cutoff: null,
|
|
4605
|
-
protectedTagNumbers: new Set,
|
|
4606
|
-
protectedRowIdentities: new Set,
|
|
4607
|
-
status: {
|
|
4608
|
-
floor,
|
|
4609
|
-
protectedCount: 0,
|
|
4610
|
-
protectedMass: 0
|
|
4611
|
-
},
|
|
4612
|
-
isProtected: () => false
|
|
4613
|
-
};
|
|
4614
|
-
}
|
|
4615
|
-
const sortedAsc = [...toolRows].sort(compareRowsAscending);
|
|
4616
|
-
const tieGroupsDescending = [];
|
|
4617
|
-
let currentGroup = [];
|
|
4618
|
-
let currentTagNumber = null;
|
|
4619
|
-
for (let i = sortedAsc.length - 1;i >= 0; i--) {
|
|
4620
|
-
const row = sortedAsc[i];
|
|
4621
|
-
const tagNum = getRowTagNumber(row);
|
|
4622
|
-
if (currentTagNumber === null || tagNum === currentTagNumber) {
|
|
4623
|
-
currentGroup.push(row);
|
|
4624
|
-
currentTagNumber = tagNum;
|
|
4625
|
-
} else {
|
|
4626
|
-
tieGroupsDescending.push(currentGroup);
|
|
4627
|
-
currentGroup = [row];
|
|
4628
|
-
currentTagNumber = tagNum;
|
|
4629
|
-
}
|
|
4630
|
-
}
|
|
4631
|
-
if (currentGroup.length > 0) {
|
|
4632
|
-
tieGroupsDescending.push(currentGroup);
|
|
4633
|
-
}
|
|
4634
|
-
const massWindowRows = [];
|
|
4635
|
-
let cumulativeMass = 0;
|
|
4636
|
-
for (const group of tieGroupsDescending) {
|
|
4637
|
-
for (const row of group) {
|
|
4638
|
-
massWindowRows.push(row);
|
|
4639
|
-
cumulativeMass += rowWindowMass(row);
|
|
4640
|
-
}
|
|
4641
|
-
if (Math.ceil(cumulativeMass * toolsRatio) >= floor) {
|
|
4642
|
-
break;
|
|
4643
|
-
}
|
|
4644
|
-
}
|
|
4645
|
-
const mass_cutoff = massWindowRows.length > 0 ? getRowTagNumber(massWindowRows[massWindowRows.length - 1]) : null;
|
|
4646
|
-
const distinctToolTagNumbers = tieGroupsDescending.map((g) => getRowTagNumber(g[0]));
|
|
4647
|
-
const minCount = Math.min(3, distinctToolTagNumbers.length);
|
|
4648
|
-
const newest3_cutoff = minCount > 0 ? distinctToolTagNumbers[minCount - 1] : null;
|
|
4649
|
-
const cutoff = mass_cutoff !== null && newest3_cutoff !== null ? Math.min(mass_cutoff, newest3_cutoff) : mass_cutoff ?? newest3_cutoff;
|
|
4650
|
-
const memberRows = cutoff !== null ? sortedAsc.filter((row) => getRowTagNumber(row) >= cutoff) : [];
|
|
4651
|
-
const memberRowKeys = new Set(memberRows.map(rowKey));
|
|
4652
|
-
const protectedTagNumbers = new Set(memberRows.map(getRowTagNumber));
|
|
4653
|
-
const protectedRowIdentities = new Set(memberRows.map(getRowIdentity));
|
|
4654
|
-
const protectedCount = memberRows.length;
|
|
4655
|
-
const protectedMass = Math.ceil(memberRows.reduce((sum, row) => sum + rowWindowMass(row), 0) * toolsRatio);
|
|
4656
|
-
const isProtected = (row) => {
|
|
4657
|
-
return getRowKind(row) === "tool" && cutoff !== null && getRowTagNumber(row) >= cutoff;
|
|
4658
|
-
};
|
|
4659
|
-
return {
|
|
4660
|
-
memberRows,
|
|
4661
|
-
memberRowKeys,
|
|
4662
|
-
tagNumberSet: {
|
|
4663
|
-
coordinateSpace: "tag-number",
|
|
4664
|
-
tagNumbers: protectedTagNumbers
|
|
4665
|
-
},
|
|
4666
|
-
rowIdentitySet: {
|
|
4667
|
-
coordinateSpace: "row-identity",
|
|
4668
|
-
rowIdentities: protectedRowIdentities
|
|
4669
|
-
},
|
|
4670
|
-
ordinalCutoff: {
|
|
4671
|
-
coordinateSpace: "tag-number",
|
|
4672
|
-
cutoff
|
|
4673
|
-
},
|
|
4674
|
-
cutoff,
|
|
4675
|
-
protectedTagNumbers,
|
|
4676
|
-
protectedRowIdentities,
|
|
4677
|
-
status: {
|
|
4678
|
-
floor,
|
|
4679
|
-
protectedCount,
|
|
4680
|
-
protectedMass
|
|
4681
|
-
},
|
|
4682
|
-
isProtected
|
|
4683
|
-
};
|
|
4684
|
-
}
|
|
4685
|
-
function readEpochFloorSnapshot(db, sessionId) {
|
|
4686
|
-
try {
|
|
4687
|
-
const row = db.prepare("SELECT protected_tokens_effective FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
4688
|
-
if (row && typeof row.protected_tokens_effective === "number" && Number.isFinite(row.protected_tokens_effective)) {
|
|
4689
|
-
return row.protected_tokens_effective;
|
|
4690
|
-
}
|
|
4691
|
-
} catch {}
|
|
4692
|
-
return null;
|
|
4693
|
-
}
|
|
4694
|
-
function getProtectionWindowForSession(db, sessionId, floor) {
|
|
4695
|
-
const effectiveFloor = typeof floor === "number" && Number.isFinite(floor) ? floor : readEpochFloorSnapshot(db, sessionId) ?? 0;
|
|
4696
|
-
const toolsRatio = sessionDecisionCalibration(db, sessionId).toolsRatio;
|
|
4697
|
-
const pageSize = 256;
|
|
4698
|
-
const projection = `SELECT ${TAG_SELECT_COLUMNS2} FROM tags
|
|
4699
|
-
WHERE session_id = ? AND +type = 'tool'`;
|
|
4700
|
-
const order = `ORDER BY tag_number DESC, id DESC LIMIT ${pageSize}`;
|
|
4701
|
-
let page = db.prepare(`${projection} ${order}`).all(sessionId);
|
|
4702
|
-
const rows = [];
|
|
4703
|
-
let mass = 0;
|
|
4704
|
-
let distinctTags = 0;
|
|
4705
|
-
let currentTag = null;
|
|
4706
|
-
while (page.length > 0) {
|
|
4707
|
-
for (const row of page) {
|
|
4708
|
-
const tagNumber = getRowTagNumber(row);
|
|
4709
|
-
if (tagNumber !== currentTag) {
|
|
4710
|
-
if (distinctTags >= 3 && Math.ceil(mass * toolsRatio) >= effectiveFloor) {
|
|
4711
|
-
return computeProtectionWindow(rows, effectiveFloor, toolsRatio);
|
|
4712
|
-
}
|
|
4713
|
-
distinctTags++;
|
|
4714
|
-
currentTag = tagNumber;
|
|
4715
|
-
}
|
|
4716
|
-
rows.push(row);
|
|
4717
|
-
mass += rowWindowMass(row);
|
|
4718
|
-
}
|
|
4719
|
-
if (page.length < pageSize)
|
|
4720
|
-
break;
|
|
4721
|
-
const last = page[page.length - 1];
|
|
4722
|
-
page = db.prepare(`${projection} AND (tag_number, id) < (?, ?) ${order}`).all(sessionId, getRowTagNumber(last), getRowIdentity(last));
|
|
4723
|
-
}
|
|
4724
|
-
return computeProtectionWindow(rows, effectiveFloor, toolsRatio);
|
|
4725
|
-
}
|
|
4726
|
-
|
|
4727
|
-
// ../plugin/src/features/magic-context/storage-meta-shared.ts
|
|
4728
|
-
import { Buffer as Buffer2 } from "node:buffer";
|
|
4729
|
-
var SESSION_META_SELECT_COLUMNS = [
|
|
4730
|
-
"session_id",
|
|
4731
|
-
"last_response_time",
|
|
4732
|
-
"cache_ttl",
|
|
4733
|
-
"counter",
|
|
4734
|
-
"last_nudge_tokens",
|
|
4735
|
-
"last_nudge_band",
|
|
4736
|
-
"last_transform_error",
|
|
4737
|
-
"is_subagent",
|
|
4738
|
-
"last_context_percentage",
|
|
4739
|
-
"last_input_tokens",
|
|
4740
|
-
"observed_safe_input_tokens",
|
|
4741
|
-
"cache_alert_sent",
|
|
4742
|
-
"times_execute_threshold_reached",
|
|
4743
|
-
"compartment_in_progress",
|
|
4744
|
-
"system_prompt_hash",
|
|
4745
|
-
"system_prompt_tokens",
|
|
4746
|
-
"conversation_tokens",
|
|
4747
|
-
"tool_call_tokens",
|
|
4748
|
-
"cleared_reasoning_through_tag",
|
|
4749
|
-
"tool_reclaim_watermark",
|
|
4750
|
-
"last_todo_state",
|
|
4751
|
-
"cached_m0_bytes",
|
|
4752
|
-
"cached_m0_mural_data_url",
|
|
4753
|
-
"cached_m0_mural_hash",
|
|
4754
|
-
"cached_m1_bytes",
|
|
4755
|
-
"cached_m0_project_memory_epoch",
|
|
4756
|
-
"cached_m0_workspace_fingerprint",
|
|
4757
|
-
"cached_m0_project_user_profile_version",
|
|
4758
|
-
"cached_m0_max_compartment_seq",
|
|
4759
|
-
"cached_m0_max_memory_id",
|
|
4760
|
-
"cached_m0_max_mutation_id",
|
|
4761
|
-
"cached_m0_max_memory_mutation_id",
|
|
4762
|
-
"cached_m0_project_docs_hash",
|
|
4763
|
-
"cached_m0_materialized_at",
|
|
4764
|
-
"cached_m0_session_facts_version",
|
|
4765
|
-
"cached_m0_upgrade_state",
|
|
4766
|
-
"cached_m0_system_hash",
|
|
4767
|
-
"cached_m0_tool_set_hash",
|
|
4768
|
-
"cached_m0_model_key",
|
|
4769
|
-
"cached_m0_project_identity",
|
|
4770
|
-
"last_observed_model_key",
|
|
4771
|
-
"last_usage_context_limit",
|
|
4772
|
-
"prior_boundary_ordinal",
|
|
4773
|
-
"protected_tail_policy_version",
|
|
4774
|
-
"protected_tail_drain_window_started_at",
|
|
4775
|
-
"protected_tail_drain_tokens",
|
|
4776
|
-
"recovery_no_eligible_head_count",
|
|
4777
|
-
"force_emergency_bypass_window_start",
|
|
4778
|
-
"force_emergency_bypass_used",
|
|
4779
|
-
"emergency_drain_active",
|
|
4780
|
-
"historian_drain_failure_at",
|
|
4781
|
-
"upgrade_reminded_at",
|
|
4782
|
-
"upgrade_reminder_last_sent_at",
|
|
4783
|
-
"upgrade_reminder_count",
|
|
4784
|
-
"pi_stable_id_scheme"
|
|
4785
|
-
];
|
|
4786
|
-
var META_COLUMNS = {
|
|
4787
|
-
lastResponseTime: "last_response_time",
|
|
4788
|
-
cacheTtl: "cache_ttl",
|
|
4789
|
-
counter: "counter",
|
|
4790
|
-
lastNudgeTokens: "last_nudge_tokens",
|
|
4791
|
-
lastNudgeBand: "last_nudge_band",
|
|
4792
|
-
lastTransformError: "last_transform_error",
|
|
4793
|
-
isSubagent: "is_subagent",
|
|
4794
|
-
lastContextPercentage: "last_context_percentage",
|
|
4795
|
-
lastInputTokens: "last_input_tokens",
|
|
4796
|
-
observedSafeInputTokens: "observed_safe_input_tokens",
|
|
4797
|
-
cacheAlertSent: "cache_alert_sent",
|
|
4798
|
-
timesExecuteThresholdReached: "times_execute_threshold_reached",
|
|
4799
|
-
compartmentInProgress: "compartment_in_progress",
|
|
4800
|
-
systemPromptHash: "system_prompt_hash",
|
|
4801
|
-
systemPromptTokens: "system_prompt_tokens",
|
|
4802
|
-
conversationTokens: "conversation_tokens",
|
|
4803
|
-
toolCallTokens: "tool_call_tokens",
|
|
4804
|
-
clearedReasoningThroughTag: "cleared_reasoning_through_tag",
|
|
4805
|
-
toolReclaimWatermark: "tool_reclaim_watermark",
|
|
4806
|
-
lastTodoState: "last_todo_state",
|
|
4807
|
-
cachedM0Bytes: "cached_m0_bytes",
|
|
4808
|
-
cachedM0MuralDataUrl: "cached_m0_mural_data_url",
|
|
4809
|
-
cachedM0MuralHash: "cached_m0_mural_hash",
|
|
4810
|
-
cachedM1Bytes: "cached_m1_bytes",
|
|
4811
|
-
cachedM0ProjectMemoryEpoch: "cached_m0_project_memory_epoch",
|
|
4812
|
-
cachedM0WorkspaceFingerprint: "cached_m0_workspace_fingerprint",
|
|
4813
|
-
cachedM0ProjectUserProfileVersion: "cached_m0_project_user_profile_version",
|
|
4814
|
-
cachedM0MaxCompartmentSeq: "cached_m0_max_compartment_seq",
|
|
4815
|
-
cachedM0MaxMemoryId: "cached_m0_max_memory_id",
|
|
4816
|
-
cachedM0MaxMutationId: "cached_m0_max_mutation_id",
|
|
4817
|
-
cachedM0MaxMemoryMutationId: "cached_m0_max_memory_mutation_id",
|
|
4818
|
-
cachedM0ProjectDocsHash: "cached_m0_project_docs_hash",
|
|
4819
|
-
cachedM0MaterializedAt: "cached_m0_materialized_at",
|
|
4820
|
-
cachedM0SessionFactsVersion: "cached_m0_session_facts_version",
|
|
4821
|
-
cachedM0UpgradeState: "cached_m0_upgrade_state",
|
|
4822
|
-
cachedM0SystemHash: "cached_m0_system_hash",
|
|
4823
|
-
cachedM0ToolSetHash: "cached_m0_tool_set_hash",
|
|
4824
|
-
cachedM0ModelKey: "cached_m0_model_key",
|
|
4825
|
-
cachedM0ProjectIdentity: "cached_m0_project_identity",
|
|
4826
|
-
lastObservedModelKey: "last_observed_model_key",
|
|
4827
|
-
lastUsageContextLimit: "last_usage_context_limit",
|
|
4828
|
-
priorBoundaryOrdinal: "prior_boundary_ordinal",
|
|
4829
|
-
protectedTailPolicyVersion: "protected_tail_policy_version",
|
|
4830
|
-
protectedTailDrainWindowStartedAt: "protected_tail_drain_window_started_at",
|
|
4831
|
-
protectedTailDrainTokens: "protected_tail_drain_tokens",
|
|
4832
|
-
recoveryNoEligibleHeadCount: "recovery_no_eligible_head_count",
|
|
4833
|
-
forceEmergencyBypassWindowStart: "force_emergency_bypass_window_start",
|
|
4834
|
-
forceEmergencyBypassUsed: "force_emergency_bypass_used",
|
|
4835
|
-
emergencyDrainActive: "emergency_drain_active",
|
|
4836
|
-
historianDrainFailureAt: "historian_drain_failure_at",
|
|
4837
|
-
upgradeRemindedAt: "upgrade_reminded_at",
|
|
4838
|
-
upgradeReminderLastSentAt: "upgrade_reminder_last_sent_at",
|
|
4839
|
-
upgradeReminderCount: "upgrade_reminder_count",
|
|
4840
|
-
piStableIdScheme: "pi_stable_id_scheme"
|
|
4841
|
-
};
|
|
4842
|
-
var BOOLEAN_META_KEYS = new Set(["isSubagent", "compartmentInProgress", "cacheAlertSent"]);
|
|
4843
|
-
var NULL_BIND_META_KEYS = new Set([
|
|
4844
|
-
"cachedM0Bytes",
|
|
4845
|
-
"cachedM0MuralDataUrl",
|
|
4846
|
-
"cachedM0MuralHash",
|
|
4847
|
-
"cachedM1Bytes",
|
|
4848
|
-
"cachedM0ProjectMemoryEpoch",
|
|
4849
|
-
"cachedM0WorkspaceFingerprint",
|
|
4850
|
-
"cachedM0ProjectUserProfileVersion",
|
|
4851
|
-
"cachedM0MaxCompartmentSeq",
|
|
4852
|
-
"cachedM0MaxMemoryId",
|
|
4853
|
-
"cachedM0MaxMutationId",
|
|
4854
|
-
"cachedM0MaxMemoryMutationId",
|
|
4855
|
-
"cachedM0ProjectDocsHash",
|
|
4856
|
-
"cachedM0MaterializedAt",
|
|
4857
|
-
"cachedM0SessionFactsVersion",
|
|
4858
|
-
"cachedM0UpgradeState",
|
|
4859
|
-
"cachedM0ProjectIdentity",
|
|
4860
|
-
"lastObservedModelKey",
|
|
4861
|
-
"upgradeRemindedAt",
|
|
4862
|
-
"upgradeReminderLastSentAt",
|
|
4863
|
-
"piStableIdScheme"
|
|
4864
|
-
]);
|
|
4865
|
-
function isStringOrNull(value) {
|
|
4866
|
-
return value === null || typeof value === "string";
|
|
4867
|
-
}
|
|
4868
|
-
function isNumberOrNull(value) {
|
|
4869
|
-
return value === null || typeof value === "number";
|
|
4870
|
-
}
|
|
4871
|
-
function isBlobOrNull(value) {
|
|
4872
|
-
return value === null || Buffer2.isBuffer(value) || value instanceof Uint8Array;
|
|
4873
|
-
}
|
|
4874
|
-
function toBufferOrNull(value) {
|
|
4875
|
-
if (value === null)
|
|
4876
|
-
return null;
|
|
4877
|
-
if (Buffer2.isBuffer(value))
|
|
4878
|
-
return value;
|
|
4879
|
-
return Buffer2.from(value.buffer, value.byteOffset, value.byteLength);
|
|
4880
|
-
}
|
|
4881
|
-
function isSessionMetaRow(row) {
|
|
4882
|
-
if (row === null || typeof row !== "object")
|
|
4883
|
-
return false;
|
|
4884
|
-
const r = row;
|
|
4885
|
-
return typeof r.session_id === "string" && isNumberOrNull(r.last_response_time) && isStringOrNull(r.cache_ttl) && typeof r.counter === "number" && typeof r.last_nudge_tokens === "number" && isStringOrNull(r.last_nudge_band) && isStringOrNull(r.last_transform_error) && typeof r.is_subagent === "number" && typeof r.last_context_percentage === "number" && typeof r.last_input_tokens === "number" && isNumberOrNull(r.observed_safe_input_tokens) && isNumberOrNull(r.cache_alert_sent) && isNumberOrNull(r.times_execute_threshold_reached) && isNumberOrNull(r.compartment_in_progress) && (r.system_prompt_hash === null || typeof r.system_prompt_hash === "string" || typeof r.system_prompt_hash === "number") && isNumberOrNull(r.system_prompt_tokens) && isNumberOrNull(r.conversation_tokens) && isNumberOrNull(r.tool_call_tokens) && isNumberOrNull(r.cleared_reasoning_through_tag) && isStringOrNull(r.last_todo_state) && isBlobOrNull(r.cached_m0_bytes) && isStringOrNull(r.cached_m0_mural_data_url) && isStringOrNull(r.cached_m0_mural_hash) && isBlobOrNull(r.cached_m1_bytes) && isNumberOrNull(r.cached_m0_project_memory_epoch) && isStringOrNull(r.cached_m0_workspace_fingerprint) && isNumberOrNull(r.cached_m0_project_user_profile_version) && isNumberOrNull(r.cached_m0_max_compartment_seq) && isNumberOrNull(r.cached_m0_max_memory_id) && isNumberOrNull(r.cached_m0_max_mutation_id) && isNumberOrNull(r.cached_m0_max_memory_mutation_id) && isStringOrNull(r.cached_m0_project_docs_hash) && isNumberOrNull(r.cached_m0_materialized_at) && isNumberOrNull(r.cached_m0_session_facts_version) && isStringOrNull(r.cached_m0_upgrade_state) && isStringOrNull(r.cached_m0_system_hash) && isStringOrNull(r.cached_m0_tool_set_hash) && isStringOrNull(r.cached_m0_model_key) && isStringOrNull(r.cached_m0_project_identity) && isStringOrNull(r.last_observed_model_key) && isNumberOrNull(r.last_usage_context_limit) && isNumberOrNull(r.prior_boundary_ordinal) && isNumberOrNull(r.protected_tail_policy_version) && isNumberOrNull(r.protected_tail_drain_window_started_at) && isNumberOrNull(r.protected_tail_drain_tokens) && isNumberOrNull(r.recovery_no_eligible_head_count) && isNumberOrNull(r.force_emergency_bypass_window_start) && isNumberOrNull(r.force_emergency_bypass_used) && isNumberOrNull(r.upgrade_reminded_at) && isNumberOrNull(r.upgrade_reminder_last_sent_at) && isNumberOrNull(r.upgrade_reminder_count) && isNumberOrNull(r.pi_stable_id_scheme) && isNumberOrNull(r.tool_reclaim_watermark);
|
|
4886
|
-
}
|
|
4887
|
-
function getDefaultSessionMeta(sessionId) {
|
|
4888
|
-
return {
|
|
4889
|
-
sessionId,
|
|
4890
|
-
lastResponseTime: 0,
|
|
4891
|
-
cacheTtl: "5m",
|
|
4892
|
-
counter: 0,
|
|
4893
|
-
lastNudgeTokens: 0,
|
|
4894
|
-
lastNudgeBand: null,
|
|
4895
|
-
lastTransformError: null,
|
|
4896
|
-
isSubagent: false,
|
|
4897
|
-
lastContextPercentage: 0,
|
|
4898
|
-
lastInputTokens: 0,
|
|
4899
|
-
observedSafeInputTokens: 0,
|
|
4900
|
-
cacheAlertSent: false,
|
|
4901
|
-
timesExecuteThresholdReached: 0,
|
|
4902
|
-
compartmentInProgress: false,
|
|
4903
|
-
systemPromptHash: "",
|
|
4904
|
-
systemPromptTokens: 0,
|
|
4905
|
-
conversationTokens: 0,
|
|
4906
|
-
toolCallTokens: 0,
|
|
4907
|
-
clearedReasoningThroughTag: 0,
|
|
4908
|
-
toolReclaimWatermark: 0,
|
|
4909
|
-
lastTodoState: "",
|
|
4910
|
-
cachedM0Bytes: null,
|
|
4911
|
-
cachedM0MuralDataUrl: null,
|
|
4912
|
-
cachedM0MuralHash: null,
|
|
4913
|
-
cachedM1Bytes: null,
|
|
4914
|
-
cachedM0ProjectMemoryEpoch: null,
|
|
4915
|
-
cachedM0WorkspaceFingerprint: null,
|
|
4916
|
-
cachedM0ProjectUserProfileVersion: null,
|
|
4917
|
-
cachedM0MaxCompartmentSeq: null,
|
|
4918
|
-
cachedM0MaxMemoryId: null,
|
|
4919
|
-
cachedM0MaxMutationId: null,
|
|
4920
|
-
cachedM0MaxMemoryMutationId: null,
|
|
4921
|
-
cachedM0ProjectDocsHash: null,
|
|
4922
|
-
cachedM0MaterializedAt: null,
|
|
4923
|
-
cachedM0SessionFactsVersion: null,
|
|
4924
|
-
cachedM0UpgradeState: null,
|
|
4925
|
-
cachedM0SystemHash: null,
|
|
4926
|
-
cachedM0ToolSetHash: null,
|
|
4927
|
-
cachedM0ModelKey: null,
|
|
4928
|
-
cachedM0ProjectIdentity: null,
|
|
4929
|
-
lastObservedModelKey: null,
|
|
4930
|
-
lastUsageContextLimit: 0,
|
|
4931
|
-
priorBoundaryOrdinal: 1,
|
|
4932
|
-
protectedTailPolicyVersion: 0,
|
|
4933
|
-
protectedTailDrainWindowStartedAt: 0,
|
|
4934
|
-
protectedTailDrainTokens: 0,
|
|
4935
|
-
recoveryNoEligibleHeadCount: 0,
|
|
4936
|
-
forceEmergencyBypassWindowStart: 0,
|
|
4937
|
-
forceEmergencyBypassUsed: 0,
|
|
4938
|
-
upgradeRemindedAt: null,
|
|
4939
|
-
upgradeReminderLastSentAt: null,
|
|
4940
|
-
upgradeReminderCount: 0,
|
|
4941
|
-
piStableIdScheme: null
|
|
4942
|
-
};
|
|
4943
|
-
}
|
|
4944
|
-
var sessionMetaExistsStatements = new WeakMap;
|
|
4945
|
-
function ensureSessionMetaRow(db, sessionId, initialIsSubagent = false) {
|
|
4946
|
-
let exists = sessionMetaExistsStatements.get(db);
|
|
4947
|
-
if (!exists) {
|
|
4948
|
-
exists = prepareCachedStatement2(db, "SELECT 1 FROM session_meta WHERE session_id = ?");
|
|
4949
|
-
sessionMetaExistsStatements.set(db, exists);
|
|
4950
|
-
}
|
|
4951
|
-
if (exists.get(sessionId))
|
|
4952
|
-
return;
|
|
4953
|
-
const defaults = getDefaultSessionMeta(sessionId);
|
|
4954
|
-
db.prepare("INSERT OR IGNORE INTO session_meta (session_id, harness, last_response_time, cache_ttl, counter, last_nudge_tokens, last_nudge_band, last_transform_error, is_subagent, last_context_percentage, last_input_tokens, observed_safe_input_tokens, cache_alert_sent, times_execute_threshold_reached, compartment_in_progress, system_prompt_hash, cleared_reasoning_through_tag) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(sessionId, getHarness2(), defaults.lastResponseTime, defaults.cacheTtl, defaults.counter, defaults.lastNudgeTokens, defaults.lastNudgeBand ?? "", defaults.lastTransformError ?? "", initialIsSubagent ? 1 : 0, defaults.lastContextPercentage, defaults.lastInputTokens, defaults.observedSafeInputTokens, defaults.cacheAlertSent ? 1 : 0, defaults.timesExecuteThresholdReached, defaults.compartmentInProgress ? 1 : 0, defaults.systemPromptHash ?? "", defaults.clearedReasoningThroughTag);
|
|
4955
|
-
}
|
|
4956
|
-
function toSessionMeta(row) {
|
|
4957
|
-
const nudgeBandRaw = typeof row.last_nudge_band === "string" ? row.last_nudge_band : "";
|
|
4958
|
-
const transformErrorRaw = typeof row.last_transform_error === "string" ? row.last_transform_error : "";
|
|
4959
|
-
const cacheTtlRaw = typeof row.cache_ttl === "string" && row.cache_ttl.length > 0 ? row.cache_ttl : "5m";
|
|
4960
|
-
const systemPromptHashRaw = row.system_prompt_hash == null ? "" : row.system_prompt_hash;
|
|
4961
|
-
const lastTodoStateRaw = typeof row.last_todo_state === "string" ? row.last_todo_state : "";
|
|
4962
|
-
const numOrZero = (value) => typeof value === "number" ? value : 0;
|
|
4963
|
-
const numOrNull = (value) => typeof value === "number" ? value : null;
|
|
4964
|
-
const stringOrNull = (value) => typeof value === "string" ? value : null;
|
|
4965
|
-
return {
|
|
4966
|
-
sessionId: row.session_id,
|
|
4967
|
-
lastResponseTime: numOrZero(row.last_response_time),
|
|
4968
|
-
cacheTtl: cacheTtlRaw,
|
|
4969
|
-
counter: row.counter,
|
|
4970
|
-
lastNudgeTokens: row.last_nudge_tokens,
|
|
4971
|
-
lastNudgeBand: nudgeBandRaw.length > 0 ? nudgeBandRaw : null,
|
|
4972
|
-
lastTransformError: transformErrorRaw.length > 0 ? transformErrorRaw : null,
|
|
4973
|
-
isSubagent: row.is_subagent === 1,
|
|
4974
|
-
lastContextPercentage: row.last_context_percentage,
|
|
4975
|
-
lastInputTokens: row.last_input_tokens,
|
|
4976
|
-
observedSafeInputTokens: numOrZero(row.observed_safe_input_tokens),
|
|
4977
|
-
cacheAlertSent: numOrZero(row.cache_alert_sent) === 1,
|
|
4978
|
-
timesExecuteThresholdReached: numOrZero(row.times_execute_threshold_reached),
|
|
4979
|
-
compartmentInProgress: row.compartment_in_progress === 1,
|
|
4980
|
-
systemPromptHash: String(systemPromptHashRaw),
|
|
4981
|
-
systemPromptTokens: numOrZero(row.system_prompt_tokens),
|
|
4982
|
-
conversationTokens: numOrZero(row.conversation_tokens),
|
|
4983
|
-
toolCallTokens: numOrZero(row.tool_call_tokens),
|
|
4984
|
-
clearedReasoningThroughTag: numOrZero(row.cleared_reasoning_through_tag),
|
|
4985
|
-
toolReclaimWatermark: numOrZero(row.tool_reclaim_watermark),
|
|
4986
|
-
lastTodoState: lastTodoStateRaw,
|
|
4987
|
-
cachedM0Bytes: toBufferOrNull(row.cached_m0_bytes),
|
|
4988
|
-
cachedM0MuralDataUrl: stringOrNull(row.cached_m0_mural_data_url),
|
|
4989
|
-
cachedM0MuralHash: stringOrNull(row.cached_m0_mural_hash),
|
|
4990
|
-
cachedM1Bytes: toBufferOrNull(row.cached_m1_bytes),
|
|
4991
|
-
cachedM0ProjectMemoryEpoch: numOrNull(row.cached_m0_project_memory_epoch),
|
|
4992
|
-
cachedM0WorkspaceFingerprint: stringOrNull(row.cached_m0_workspace_fingerprint),
|
|
4993
|
-
cachedM0ProjectUserProfileVersion: numOrNull(row.cached_m0_project_user_profile_version),
|
|
4994
|
-
cachedM0MaxCompartmentSeq: numOrNull(row.cached_m0_max_compartment_seq),
|
|
4995
|
-
cachedM0MaxMemoryId: numOrNull(row.cached_m0_max_memory_id),
|
|
4996
|
-
cachedM0MaxMutationId: numOrNull(row.cached_m0_max_mutation_id),
|
|
4997
|
-
cachedM0MaxMemoryMutationId: numOrNull(row.cached_m0_max_memory_mutation_id),
|
|
4998
|
-
cachedM0ProjectDocsHash: stringOrNull(row.cached_m0_project_docs_hash),
|
|
4999
|
-
cachedM0MaterializedAt: numOrNull(row.cached_m0_materialized_at),
|
|
5000
|
-
cachedM0SessionFactsVersion: numOrNull(row.cached_m0_session_facts_version),
|
|
5001
|
-
cachedM0UpgradeState: stringOrNull(row.cached_m0_upgrade_state),
|
|
5002
|
-
cachedM0SystemHash: stringOrNull(row.cached_m0_system_hash),
|
|
5003
|
-
cachedM0ToolSetHash: stringOrNull(row.cached_m0_tool_set_hash),
|
|
5004
|
-
cachedM0ModelKey: stringOrNull(row.cached_m0_model_key),
|
|
5005
|
-
cachedM0ProjectIdentity: stringOrNull(row.cached_m0_project_identity),
|
|
5006
|
-
lastObservedModelKey: stringOrNull(row.last_observed_model_key),
|
|
5007
|
-
lastUsageContextLimit: numOrZero(row.last_usage_context_limit),
|
|
5008
|
-
priorBoundaryOrdinal: Math.max(1, numOrZero(row.prior_boundary_ordinal) || 1),
|
|
5009
|
-
protectedTailPolicyVersion: numOrZero(row.protected_tail_policy_version),
|
|
5010
|
-
protectedTailDrainWindowStartedAt: numOrZero(row.protected_tail_drain_window_started_at),
|
|
5011
|
-
protectedTailDrainTokens: numOrZero(row.protected_tail_drain_tokens),
|
|
5012
|
-
recoveryNoEligibleHeadCount: numOrZero(row.recovery_no_eligible_head_count),
|
|
5013
|
-
forceEmergencyBypassWindowStart: numOrZero(row.force_emergency_bypass_window_start),
|
|
5014
|
-
forceEmergencyBypassUsed: numOrZero(row.force_emergency_bypass_used),
|
|
5015
|
-
upgradeRemindedAt: numOrNull(row.upgrade_reminded_at),
|
|
5016
|
-
upgradeReminderLastSentAt: numOrNull(row.upgrade_reminder_last_sent_at),
|
|
5017
|
-
upgradeReminderCount: numOrZero(row.upgrade_reminder_count),
|
|
5018
|
-
piStableIdScheme: numOrNull(row.pi_stable_id_scheme)
|
|
5019
|
-
};
|
|
5020
|
-
}
|
|
5021
|
-
function persistCachedM0(db, sessionId, payload) {
|
|
5022
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5023
|
-
db.prepare(`UPDATE session_meta SET
|
|
5024
|
-
cached_m0_bytes = ?,
|
|
5025
|
-
cached_m0_mural_data_url = ?,
|
|
5026
|
-
cached_m0_mural_hash = ?,
|
|
5027
|
-
cached_m0_project_memory_epoch = ?,
|
|
5028
|
-
cached_m0_workspace_fingerprint = ?,
|
|
5029
|
-
cached_m0_project_user_profile_version = ?,
|
|
5030
|
-
cached_m0_max_compartment_seq = ?,
|
|
5031
|
-
cached_m0_max_memory_id = ?,
|
|
5032
|
-
cached_m0_max_mutation_id = ?,
|
|
5033
|
-
cached_m0_max_memory_mutation_id = ?,
|
|
5034
|
-
cached_m1_bytes = ?,
|
|
5035
|
-
cached_m0_project_docs_hash = ?,
|
|
5036
|
-
cached_m0_materialized_at = ?,
|
|
5037
|
-
cached_m0_session_facts_version = ?,
|
|
5038
|
-
cached_m0_upgrade_state = ?,
|
|
5039
|
-
cached_m0_system_hash = ?,
|
|
5040
|
-
cached_m0_tool_set_hash = ?,
|
|
5041
|
-
cached_m0_model_key = ?,
|
|
5042
|
-
cached_m0_project_identity = ?
|
|
5043
|
-
WHERE session_id = ?`).run(Buffer2.from(payload.m0Bytes), payload.muralDataUrl ?? null, payload.muralHash ?? null, payload.projectMemoryEpoch, payload.workspaceFingerprint ?? null, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer2.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.toolSetHash ?? "", payload.modelKey ? piModelRefToCanonical(payload.modelKey) : "", payload.projectIdentity ?? null, sessionId);
|
|
5044
|
-
}
|
|
5045
|
-
function clearCachedM0M1(db, sessionId) {
|
|
5046
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5047
|
-
const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
|
|
5048
|
-
const clears = [
|
|
5049
|
-
["cached_m0_bytes", null],
|
|
5050
|
-
["cached_m0_mural_data_url", null],
|
|
5051
|
-
["cached_m0_mural_hash", null],
|
|
5052
|
-
["cached_m1_bytes", null],
|
|
5053
|
-
["cached_m0_project_memory_epoch", null],
|
|
5054
|
-
["cached_m0_workspace_fingerprint", null],
|
|
5055
|
-
["cached_m0_project_user_profile_version", null],
|
|
5056
|
-
["cached_m0_max_compartment_seq", null],
|
|
5057
|
-
["cached_m0_max_memory_id", null],
|
|
5058
|
-
["cached_m0_max_mutation_id", null],
|
|
5059
|
-
["cached_m0_max_memory_mutation_id", null],
|
|
5060
|
-
["cached_m0_project_docs_hash", null],
|
|
5061
|
-
["cached_m0_materialized_at", null],
|
|
5062
|
-
["cached_m0_session_facts_version", null],
|
|
5063
|
-
["cached_m0_upgrade_state", null],
|
|
5064
|
-
["cached_m0_system_hash", null],
|
|
5065
|
-
["cached_m0_tool_set_hash", null],
|
|
5066
|
-
["cached_m0_model_key", null],
|
|
5067
|
-
["cached_m0_project_identity", null],
|
|
5068
|
-
["cached_m0_last_baseline_end_message_id", null],
|
|
5069
|
-
["memory_block_cache", ""],
|
|
5070
|
-
["memory_block_count", 0],
|
|
5071
|
-
["memory_block_ids", ""]
|
|
5072
|
-
];
|
|
5073
|
-
const setClauses = [];
|
|
5074
|
-
const values = [];
|
|
5075
|
-
for (const [column, value] of clears) {
|
|
5076
|
-
if (!existingColumns.has(column))
|
|
5077
|
-
continue;
|
|
5078
|
-
setClauses.push(`${column} = ?`);
|
|
5079
|
-
values.push(value);
|
|
5080
|
-
}
|
|
5081
|
-
if (setClauses.length === 0)
|
|
5082
|
-
return;
|
|
5083
|
-
db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
|
|
5084
|
-
}
|
|
5085
|
-
|
|
5086
|
-
// ../plugin/src/features/magic-context/storage-replay-document.ts
|
|
5087
|
-
var CAS_RETRY_LIMIT = 5;
|
|
5088
|
-
var MISSING_REPLAY_DOCUMENT_COLUMN = Symbol("missing replay document column");
|
|
5089
|
-
function isRustMarkerAdmissionFenced(db, sessionId) {
|
|
5090
|
-
const row = db.prepare("SELECT COALESCE(json_extract(NULLIF(trailing_blank_decisions, ''), '$.rustMarkerAdmissionFence'), 0) AS fenced FROM session_meta WHERE session_id=?").get(sessionId);
|
|
5091
|
-
return row?.fenced === 1;
|
|
5092
|
-
}
|
|
5093
|
-
function isPersistedTrailingBlankDecision(value) {
|
|
5094
|
-
if (value === "keep" || value === "strip")
|
|
5095
|
-
return true;
|
|
5096
|
-
if (typeof value !== "string" || !value.startsWith("keep:"))
|
|
5097
|
-
return false;
|
|
5098
|
-
const countText = value.slice("keep:".length);
|
|
5099
|
-
if (!/^[1-9]\d*$/.test(countText))
|
|
5100
|
-
return false;
|
|
5101
|
-
const count = Number(countText);
|
|
5102
|
-
return Number.isSafeInteger(count) && count > 1 && count <= 1e4;
|
|
5103
|
-
}
|
|
5104
|
-
|
|
5105
|
-
class ReplayDocumentError extends Error {
|
|
5106
|
-
constructor(reason) {
|
|
5107
|
-
super(`invalid persisted replay document: ${reason}`);
|
|
5108
|
-
this.name = "ReplayDocumentError";
|
|
5109
|
-
}
|
|
5110
|
-
}
|
|
5111
|
-
function invalidReplayDocument(reason) {
|
|
5112
|
-
return new ReplayDocumentError(reason);
|
|
5113
|
-
}
|
|
5114
|
-
function parseTrailingBlank(value, mode) {
|
|
5115
|
-
if (!isRecord(value)) {
|
|
5116
|
-
throw invalidReplayDocument("trailingBlank must be an object");
|
|
5117
|
-
}
|
|
5118
|
-
const entries = [];
|
|
5119
|
-
for (const [id, decision] of Object.entries(value)) {
|
|
5120
|
-
if (id.length === 0 || !isPersistedTrailingBlankDecision(decision)) {
|
|
5121
|
-
if (mode === "read")
|
|
5122
|
-
continue;
|
|
5123
|
-
throw invalidReplayDocument("trailingBlank contains an invalid decision");
|
|
5124
|
-
}
|
|
5125
|
-
entries.push([id, decision]);
|
|
5126
|
-
}
|
|
5127
|
-
return Object.fromEntries(entries);
|
|
5128
|
-
}
|
|
5129
|
-
function parseV2ReplayDocument(parsed, mode) {
|
|
5130
|
-
if (parsed.version !== 2) {
|
|
5131
|
-
throw invalidReplayDocument("unknown envelope version");
|
|
5132
|
-
}
|
|
5133
|
-
if (!Object.hasOwn(parsed, "trailingBlank")) {
|
|
5134
|
-
throw invalidReplayDocument("version 2 is missing trailingBlank");
|
|
5135
|
-
}
|
|
5136
|
-
return {
|
|
5137
|
-
...parsed,
|
|
5138
|
-
version: 2,
|
|
5139
|
-
trailingBlank: parseTrailingBlank(parsed.trailingBlank, mode)
|
|
5140
|
-
};
|
|
5141
|
-
}
|
|
5142
|
-
function parseReplayDocument(raw, mode = "strict") {
|
|
5143
|
-
if (raw === null || raw === undefined || raw === "") {
|
|
5144
|
-
return { version: 1, trailingBlank: {} };
|
|
5145
|
-
}
|
|
5146
|
-
if (typeof raw !== "string") {
|
|
5147
|
-
throw invalidReplayDocument("stored value is not text");
|
|
5148
|
-
}
|
|
5149
|
-
let parsed;
|
|
5150
|
-
try {
|
|
5151
|
-
parsed = JSON.parse(raw);
|
|
5152
|
-
} catch {
|
|
5153
|
-
throw invalidReplayDocument("stored value is not JSON");
|
|
5154
|
-
}
|
|
5155
|
-
if (!isRecord(parsed)) {
|
|
5156
|
-
throw invalidReplayDocument("stored value is not an object");
|
|
5157
|
-
}
|
|
5158
|
-
if (Object.hasOwn(parsed, "version") && !isPersistedTrailingBlankDecision(parsed.version))
|
|
5159
|
-
return parseV2ReplayDocument(parsed, mode);
|
|
5160
|
-
return {
|
|
5161
|
-
version: 1,
|
|
5162
|
-
trailingBlank: parseTrailingBlank(parsed, mode)
|
|
5163
|
-
};
|
|
5164
|
-
}
|
|
5165
|
-
function serializeReplayDocument(doc) {
|
|
5166
|
-
const trailingBlank = parseTrailingBlank(doc.trailingBlank, "strict");
|
|
5167
|
-
if (doc.version === 1)
|
|
5168
|
-
return JSON.stringify(trailingBlank);
|
|
5169
|
-
if (doc.version !== 2) {
|
|
5170
|
-
throw invalidReplayDocument("unknown document version");
|
|
5171
|
-
}
|
|
5172
|
-
return JSON.stringify({
|
|
5173
|
-
...doc,
|
|
5174
|
-
version: 2,
|
|
5175
|
-
trailingBlank
|
|
5176
|
-
});
|
|
5177
|
-
}
|
|
5178
|
-
function isMissingReplayDocumentColumn(error) {
|
|
5179
|
-
return error instanceof Error && /no such column: trailing_blank_decisions/i.test(error.message);
|
|
5180
|
-
}
|
|
5181
|
-
var decisionTablePresent = new WeakMap;
|
|
5182
|
-
function hasReplayDecisionTable(db) {
|
|
5183
|
-
if (decisionTablePresent.has(db))
|
|
5184
|
-
return true;
|
|
5185
|
-
const row = db.prepare("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'session_replay_decisions'").get();
|
|
5186
|
-
if (row?.present !== 1)
|
|
5187
|
-
return false;
|
|
5188
|
-
decisionTablePresent.set(db, true);
|
|
5189
|
-
return true;
|
|
5190
|
-
}
|
|
5191
|
-
function readDecisionRows(db, sessionId, messageIds) {
|
|
5192
|
-
if (messageIds === undefined) {
|
|
5193
|
-
return db.prepare("SELECT message_id, decision FROM session_replay_decisions WHERE session_id = ?").all(sessionId);
|
|
5194
|
-
}
|
|
5195
|
-
if (messageIds.length === 0)
|
|
5196
|
-
return [];
|
|
5197
|
-
return db.prepare(`SELECT message_id, decision FROM session_replay_decisions
|
|
5198
|
-
WHERE session_id = ? AND message_id IN (SELECT value FROM json_each(?))`).all(sessionId, JSON.stringify(messageIds));
|
|
5199
|
-
}
|
|
5200
|
-
function readRawReplayDocument(db, sessionId) {
|
|
5201
|
-
try {
|
|
5202
|
-
const row = db.prepare("SELECT trailing_blank_decisions FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5203
|
-
const raw = row?.trailing_blank_decisions;
|
|
5204
|
-
if (raw === null || raw === undefined || typeof raw === "string")
|
|
5205
|
-
return raw;
|
|
5206
|
-
throw invalidReplayDocument("stored value is not text");
|
|
5207
|
-
} catch (error) {
|
|
5208
|
-
if (isMissingReplayDocumentColumn(error))
|
|
5209
|
-
return MISSING_REPLAY_DOCUMENT_COLUMN;
|
|
5210
|
-
throw error;
|
|
5211
|
-
}
|
|
5212
|
-
}
|
|
5213
|
-
var trailingBlankReadCache = new WeakMap;
|
|
5214
|
-
var TRAILING_BLANK_CACHE_MAX_CHARS = 4 * 1024 * 1024;
|
|
5215
|
-
function readReplayEnvelope(db, sessionId, mode = "strict") {
|
|
5216
|
-
const raw = readRawReplayDocument(db, sessionId);
|
|
5217
|
-
if (raw === MISSING_REPLAY_DOCUMENT_COLUMN) {
|
|
5218
|
-
return { version: 1, trailingBlank: {} };
|
|
5219
|
-
}
|
|
5220
|
-
return parseReplayDocument(raw, mode);
|
|
5221
|
-
}
|
|
5222
|
-
function readReplayDocument(db, sessionId, mode = "strict") {
|
|
5223
|
-
const doc = readReplayEnvelope(db, sessionId, mode);
|
|
5224
|
-
if (!hasReplayDecisionTable(db))
|
|
5225
|
-
return doc;
|
|
5226
|
-
const rows = readDecisionRows(db, sessionId);
|
|
5227
|
-
if (rows.length === 0)
|
|
5228
|
-
return doc;
|
|
5229
|
-
const merged = new Map(Object.entries(doc.trailingBlank));
|
|
5230
|
-
for (const row of rows) {
|
|
5231
|
-
if (!isPersistedTrailingBlankDecision(row.decision)) {
|
|
5232
|
-
if (mode === "read")
|
|
5233
|
-
continue;
|
|
5234
|
-
throw invalidReplayDocument("trailingBlank contains an invalid decision");
|
|
5235
|
-
}
|
|
5236
|
-
merged.set(row.message_id, row.decision);
|
|
5237
|
-
}
|
|
5238
|
-
return { ...doc, trailingBlank: Object.fromEntries(merged) };
|
|
5239
|
-
}
|
|
5240
|
-
function updateReplayDocument(db, sessionId, mutate) {
|
|
5241
|
-
let initial;
|
|
5242
|
-
try {
|
|
5243
|
-
initial = readRawReplayDocument(db, sessionId);
|
|
5244
|
-
} catch (error) {
|
|
5245
|
-
if (error instanceof ReplayDocumentError)
|
|
5246
|
-
return false;
|
|
5247
|
-
throw error;
|
|
5248
|
-
}
|
|
5249
|
-
if (initial === MISSING_REPLAY_DOCUMENT_COLUMN)
|
|
5250
|
-
return false;
|
|
5251
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5252
|
-
for (let attempt = 0;attempt < CAS_RETRY_LIMIT; attempt += 1) {
|
|
5253
|
-
let raw;
|
|
5254
|
-
try {
|
|
5255
|
-
raw = readRawReplayDocument(db, sessionId);
|
|
5256
|
-
} catch (error) {
|
|
5257
|
-
if (error instanceof ReplayDocumentError)
|
|
5258
|
-
return false;
|
|
5259
|
-
throw error;
|
|
5260
|
-
}
|
|
5261
|
-
if (raw === MISSING_REPLAY_DOCUMENT_COLUMN)
|
|
5262
|
-
return false;
|
|
5263
|
-
let doc;
|
|
5264
|
-
try {
|
|
5265
|
-
doc = parseReplayDocument(raw);
|
|
5266
|
-
} catch (error) {
|
|
5267
|
-
if (error instanceof ReplayDocumentError)
|
|
5268
|
-
return false;
|
|
5269
|
-
throw error;
|
|
5270
|
-
}
|
|
5271
|
-
if (!mutate(doc))
|
|
5272
|
-
return true;
|
|
5273
|
-
const next = serializeReplayDocument(doc);
|
|
5274
|
-
if (next === raw)
|
|
5275
|
-
return true;
|
|
5276
|
-
const result = db.prepare("UPDATE session_meta SET trailing_blank_decisions = ? WHERE session_id = ? AND trailing_blank_decisions IS ?").run(next, sessionId, raw);
|
|
5277
|
-
if (result.changes > 0)
|
|
5278
|
-
return true;
|
|
5279
|
-
}
|
|
5280
|
-
sessionLog2(sessionId, `trailing_blank_decisions CAS: ${CAS_RETRY_LIMIT} retries exhausted`);
|
|
5281
|
-
return false;
|
|
5282
|
-
}
|
|
5283
|
-
var DECISION_CONFLICT = Symbol("replay decision changed concurrently");
|
|
5284
|
-
function writeReplayDocument(db, sessionId, doc) {
|
|
5285
|
-
if (!hasReplayDecisionTable(db)) {
|
|
5286
|
-
db.prepare("UPDATE session_meta SET trailing_blank_decisions = ? WHERE session_id = ?").run(serializeReplayDocument(doc), sessionId);
|
|
5287
|
-
return;
|
|
5288
|
-
}
|
|
5289
|
-
const decisions = parseTrailingBlank(doc.trailingBlank, "strict");
|
|
5290
|
-
db.prepare("UPDATE session_meta SET trailing_blank_decisions = ? WHERE session_id = ?").run(doc.version === 1 ? "" : serializeReplayDocument({ ...doc, trailingBlank: {} }), sessionId);
|
|
5291
|
-
db.prepare("DELETE FROM session_replay_decisions WHERE session_id = ?").run(sessionId);
|
|
5292
|
-
const insert = db.prepare("INSERT INTO session_replay_decisions (session_id, message_id, decision) VALUES (?, ?, ?)");
|
|
5293
|
-
for (const [id, decision] of Object.entries(decisions))
|
|
5294
|
-
insert.run(sessionId, id, decision);
|
|
5295
|
-
}
|
|
5296
|
-
|
|
5297
|
-
// ../plugin/src/features/magic-context/storage-meta-persisted.ts
|
|
5298
|
-
var emergencyRecoveryArmedSessions = new Set;
|
|
5299
|
-
var emergencyRecoveryArmedAtBySession = new Map;
|
|
5300
|
-
var providerOverflowReconfirmedSessions = new Set;
|
|
5301
|
-
var providerOverflowKnownLimitSessions = new Set;
|
|
5302
|
-
function isProviderOverflowFailClosedProven(sessionId) {
|
|
5303
|
-
return providerOverflowKnownLimitSessions.has(sessionId) || providerOverflowReconfirmedSessions.has(sessionId);
|
|
5304
|
-
}
|
|
5305
|
-
function describeProtectedTailDrainBudgetSkip(result) {
|
|
5306
|
-
const state = result.budgetState;
|
|
5307
|
-
if (!state)
|
|
5308
|
-
return "historian skip: internal drain budget spent";
|
|
5309
|
-
const resetMinutes = Math.max(1, Math.ceil(state.resetInMs / 60000));
|
|
5310
|
-
return `historian skip: internal drain budget spent (${state.spentTokens}/${state.limitTokens} tokens; resets in ${resetMinutes}m)`;
|
|
5311
|
-
}
|
|
5312
|
-
var CAS_RETRY_LIMIT2 = 5;
|
|
5313
|
-
var AUTO_SEARCH_NO_HINT_REASONS = new Set([
|
|
5314
|
-
"below-threshold",
|
|
5315
|
-
"timeout",
|
|
5316
|
-
"empty",
|
|
5317
|
-
"error",
|
|
5318
|
-
"stacked",
|
|
5319
|
-
"too-short"
|
|
5320
|
-
]);
|
|
5321
|
-
function isPersistedNoteNudgeRow(row) {
|
|
5322
|
-
if (row === null || typeof row !== "object")
|
|
5323
|
-
return false;
|
|
5324
|
-
const r = row;
|
|
5325
|
-
return typeof r.note_nudge_trigger_pending === "number" && typeof r.note_nudge_trigger_message_id === "string" && typeof r.note_nudge_sticky_text === "string" && typeof r.note_nudge_sticky_message_id === "string";
|
|
5326
|
-
}
|
|
5327
|
-
function isValidNoteNudgeAnchor(value) {
|
|
5328
|
-
if (value === null || typeof value !== "object")
|
|
5329
|
-
return false;
|
|
5330
|
-
const row = value;
|
|
5331
|
-
return typeof row.messageId === "string" && row.messageId.length > 0 && typeof row.text === "string" && row.text.length > 0;
|
|
5332
|
-
}
|
|
5333
|
-
function isValidAutoSearchHintDecision(value) {
|
|
5334
|
-
if (value === null || typeof value !== "object")
|
|
5335
|
-
return false;
|
|
5336
|
-
const row = value;
|
|
5337
|
-
if (typeof row.messageId !== "string" || row.messageId.length === 0)
|
|
5338
|
-
return false;
|
|
5339
|
-
if (row.decision === "hint") {
|
|
5340
|
-
return typeof row.text === "string" && row.text.length > 0;
|
|
5341
|
-
}
|
|
5342
|
-
if (row.decision === "no-hint") {
|
|
5343
|
-
return typeof row.reason === "string" && AUTO_SEARCH_NO_HINT_REASONS.has(row.reason);
|
|
5344
|
-
}
|
|
5345
|
-
return false;
|
|
5346
|
-
}
|
|
5347
|
-
function parseJsonArray(json, validator) {
|
|
5348
|
-
if (!json)
|
|
5349
|
-
return [];
|
|
5350
|
-
try {
|
|
5351
|
-
const parsed = JSON.parse(json);
|
|
5352
|
-
if (!Array.isArray(parsed))
|
|
5353
|
-
return [];
|
|
5354
|
-
return parsed.filter(validator);
|
|
5355
|
-
} catch {
|
|
5356
|
-
return [];
|
|
5357
|
-
}
|
|
5358
|
-
}
|
|
5359
|
-
function isPersistedTodoSyntheticAnchorRow(row) {
|
|
5360
|
-
if (row === null || typeof row !== "object")
|
|
5361
|
-
return false;
|
|
5362
|
-
const r = row;
|
|
5363
|
-
return typeof r.todo_synthetic_call_id === "string" && typeof r.todo_synthetic_anchor_message_id === "string" && typeof r.todo_synthetic_state_json === "string";
|
|
5364
|
-
}
|
|
5365
|
-
function isPersistedHistorianFailureRow(row) {
|
|
5366
|
-
if (row === null || typeof row !== "object")
|
|
5367
|
-
return false;
|
|
5368
|
-
const r = row;
|
|
5369
|
-
return typeof r.historian_failure_count === "number" && (typeof r.historian_last_error === "string" || r.historian_last_error === null) && (typeof r.historian_last_failure_at === "number" || r.historian_last_failure_at === null);
|
|
5370
|
-
}
|
|
5371
|
-
function getDefaultPersistedNoteNudge() {
|
|
5372
|
-
return {
|
|
5373
|
-
triggerPending: false,
|
|
5374
|
-
triggerMessageId: null,
|
|
5375
|
-
stickyText: null,
|
|
5376
|
-
stickyMessageId: null
|
|
5377
|
-
};
|
|
5378
|
-
}
|
|
5379
|
-
function getDefaultHistorianFailureState() {
|
|
5380
|
-
return {
|
|
5381
|
-
failureCount: 0,
|
|
5382
|
-
lastError: null,
|
|
5383
|
-
lastFailureAt: null
|
|
5384
|
-
};
|
|
5385
|
-
}
|
|
5386
|
-
function parseHistorianFailureState(result) {
|
|
5387
|
-
if (!isPersistedHistorianFailureRow(result))
|
|
5388
|
-
return getDefaultHistorianFailureState();
|
|
5389
|
-
return {
|
|
5390
|
-
failureCount: result.historian_failure_count,
|
|
5391
|
-
lastError: typeof result.historian_last_error === "string" && result.historian_last_error.length > 0 ? result.historian_last_error : null,
|
|
5392
|
-
lastFailureAt: typeof result.historian_last_failure_at === "number" ? result.historian_last_failure_at : null
|
|
5393
|
-
};
|
|
5394
|
-
}
|
|
5395
|
-
var DEFAULT_PROTECTED_TAIL_META = {
|
|
5396
|
-
priorBoundaryOrdinal: 1,
|
|
5397
|
-
protectedTailPolicyVersion: 0,
|
|
5398
|
-
protectedTailDrainWindowStartedAt: 0,
|
|
5399
|
-
protectedTailDrainTokens: 0,
|
|
5400
|
-
recoveryNoEligibleHeadCount: 0,
|
|
5401
|
-
forceEmergencyBypassWindowStart: 0,
|
|
5402
|
-
forceEmergencyBypassUsed: 0,
|
|
5403
|
-
emergencyDrainActive: 0,
|
|
5404
|
-
historianDrainFailureAt: 0
|
|
5405
|
-
};
|
|
5406
|
-
function toProtectedTailMeta(row) {
|
|
5407
|
-
if (row === null || typeof row !== "object")
|
|
5408
|
-
return { ...DEFAULT_PROTECTED_TAIL_META };
|
|
5409
|
-
const r = row;
|
|
5410
|
-
const numberOr = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
5411
|
-
return {
|
|
5412
|
-
priorBoundaryOrdinal: Math.max(1, numberOr(r.prior_boundary_ordinal, 1)),
|
|
5413
|
-
protectedTailPolicyVersion: numberOr(r.protected_tail_policy_version, 0),
|
|
5414
|
-
protectedTailDrainWindowStartedAt: numberOr(r.protected_tail_drain_window_started_at, 0),
|
|
5415
|
-
protectedTailDrainTokens: numberOr(r.protected_tail_drain_tokens, 0),
|
|
5416
|
-
recoveryNoEligibleHeadCount: numberOr(r.recovery_no_eligible_head_count, 0),
|
|
5417
|
-
forceEmergencyBypassWindowStart: numberOr(r.force_emergency_bypass_window_start, 0),
|
|
5418
|
-
forceEmergencyBypassUsed: numberOr(r.force_emergency_bypass_used, 0),
|
|
5419
|
-
emergencyDrainActive: numberOr(r.emergency_drain_active, 0),
|
|
5420
|
-
historianDrainFailureAt: numberOr(r.historian_drain_failure_at, 0)
|
|
5421
|
-
};
|
|
5422
|
-
}
|
|
5423
|
-
function loadProtectedTailMeta(db, sessionId) {
|
|
5424
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5425
|
-
const row = db.prepare(`SELECT prior_boundary_ordinal, protected_tail_policy_version,
|
|
5426
|
-
protected_tail_drain_window_started_at, protected_tail_drain_tokens,
|
|
5427
|
-
recovery_no_eligible_head_count, force_emergency_bypass_window_start,
|
|
5428
|
-
force_emergency_bypass_used, emergency_drain_active, historian_drain_failure_at
|
|
5429
|
-
FROM session_meta WHERE session_id = ?`).get(sessionId);
|
|
5430
|
-
return toProtectedTailMeta(row);
|
|
5431
|
-
}
|
|
5432
|
-
function markProtectedTailPolicyV3Seeded(db, sessionId, priorBoundaryOrdinal) {
|
|
5433
|
-
let seeded = false;
|
|
5434
|
-
db.transaction(() => {
|
|
5435
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5436
|
-
const existing = loadProtectedTailMeta(db, sessionId);
|
|
5437
|
-
if (existing.protectedTailPolicyVersion < 3) {
|
|
5438
|
-
db.prepare(`UPDATE session_meta
|
|
5439
|
-
SET prior_boundary_ordinal = ?, protected_tail_policy_version = 3
|
|
5440
|
-
WHERE session_id = ? AND protected_tail_policy_version < 3`).run(Math.max(1, Math.floor(priorBoundaryOrdinal)), sessionId);
|
|
5441
|
-
seeded = true;
|
|
5442
|
-
}
|
|
5443
|
-
}).immediate();
|
|
5444
|
-
return { ...loadProtectedTailMeta(db, sessionId), seeded };
|
|
5445
|
-
}
|
|
5446
|
-
function recordProtectedTailPublicationFloor(db, sessionId, floorOrdinal) {
|
|
5447
|
-
db.transaction(() => {
|
|
5448
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5449
|
-
db.prepare(`UPDATE session_meta
|
|
5450
|
-
SET prior_boundary_ordinal = MAX(COALESCE(prior_boundary_ordinal, 1), ?),
|
|
5451
|
-
recovery_no_eligible_head_count = 0
|
|
5452
|
-
WHERE session_id = ?`).run(Math.max(1, Math.floor(floorOrdinal)), sessionId);
|
|
5453
|
-
}).immediate();
|
|
5454
|
-
}
|
|
5455
|
-
function recordProtectedTailNoEligibleHead(db, sessionId) {
|
|
5456
|
-
db.transaction(() => {
|
|
5457
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5458
|
-
db.prepare(`UPDATE session_meta
|
|
5459
|
-
SET recovery_no_eligible_head_count = COALESCE(recovery_no_eligible_head_count, 0) + 1
|
|
5460
|
-
WHERE session_id = ?`).run(sessionId);
|
|
5461
|
-
}).immediate();
|
|
5462
|
-
return loadProtectedTailMeta(db, sessionId).recoveryNoEligibleHeadCount;
|
|
5463
|
-
}
|
|
5464
|
-
var DRAIN_WINDOW_MS = 10 * 60 * 1000;
|
|
5465
|
-
var WRAPUP_IN_PROGRESS_TTL_MS = 5 * 60 * 1000;
|
|
5466
|
-
function parseWrapupState(value) {
|
|
5467
|
-
if (typeof value !== "string" || value.trim().length === 0)
|
|
5468
|
-
return null;
|
|
5469
|
-
try {
|
|
5470
|
-
const parsed = JSON.parse(value);
|
|
5471
|
-
if (!parsed || typeof parsed !== "object")
|
|
5472
|
-
return null;
|
|
5473
|
-
if (typeof parsed.holderId !== "string" || parsed.holderId.length === 0)
|
|
5474
|
-
return null;
|
|
5475
|
-
const numberFields = [
|
|
5476
|
-
"acquiredAt",
|
|
5477
|
-
"expiresAt",
|
|
5478
|
-
"messagesToKeep",
|
|
5479
|
-
"anchorRawMessageCount",
|
|
5480
|
-
"targetEligibleEndOrdinal",
|
|
5481
|
-
"lastCompartmentEnd",
|
|
5482
|
-
"chunkIndex",
|
|
5483
|
-
"expectedChunks",
|
|
5484
|
-
"updatedAt"
|
|
5485
|
-
];
|
|
5486
|
-
for (const field of numberFields) {
|
|
5487
|
-
if (typeof parsed[field] !== "number" || !Number.isFinite(parsed[field]))
|
|
5488
|
-
return null;
|
|
5489
|
-
}
|
|
5490
|
-
return parsed;
|
|
5491
|
-
} catch {
|
|
5492
|
-
return null;
|
|
5493
|
-
}
|
|
5494
|
-
}
|
|
5495
|
-
function readRawWrapupState(db, sessionId) {
|
|
5496
|
-
const row = db.prepare("SELECT wrapup_in_progress_state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5497
|
-
return parseWrapupState(row?.wrapup_in_progress_state);
|
|
5498
|
-
}
|
|
5499
|
-
function getWrapupInProgressState(db, sessionId, now = Date.now()) {
|
|
5500
|
-
const state = readRawWrapupState(db, sessionId);
|
|
5501
|
-
if (!state)
|
|
5502
|
-
return null;
|
|
5503
|
-
if (state.expiresAt > now)
|
|
5504
|
-
return state;
|
|
5505
|
-
try {
|
|
5506
|
-
db.exec("BEGIN IMMEDIATE");
|
|
5507
|
-
} catch {
|
|
5508
|
-
return null;
|
|
5509
|
-
}
|
|
5510
|
-
const transactionStartedAt = performance.now();
|
|
5511
|
-
let finished = false;
|
|
5512
|
-
try {
|
|
5513
|
-
const current = readRawWrapupState(db, sessionId);
|
|
5514
|
-
if (current && current.expiresAt <= now) {
|
|
5515
|
-
db.prepare("UPDATE session_meta SET wrapup_in_progress_state = NULL WHERE session_id = ?").run(sessionId);
|
|
5516
|
-
}
|
|
5517
|
-
db.exec("COMMIT");
|
|
5518
|
-
finished = true;
|
|
5519
|
-
logSlowWriteTransaction("storage_meta_wrapup_expiry_cleanup", transactionStartedAt);
|
|
5520
|
-
} finally {
|
|
5521
|
-
if (!finished) {
|
|
5522
|
-
try {
|
|
5523
|
-
db.exec("ROLLBACK");
|
|
5524
|
-
} catch {}
|
|
5525
|
-
}
|
|
5526
|
-
}
|
|
5527
|
-
return null;
|
|
5528
|
-
}
|
|
5529
|
-
function isWrapupInProgress(db, sessionId, now = Date.now()) {
|
|
5530
|
-
return getWrapupInProgressState(db, sessionId, now) !== null;
|
|
5531
|
-
}
|
|
5532
|
-
function acquireWrapupInProgress(db, sessionId, state, now = Date.now()) {
|
|
5533
|
-
const acquiredAt = now;
|
|
5534
|
-
const next = {
|
|
5535
|
-
...state,
|
|
5536
|
-
acquiredAt,
|
|
5537
|
-
expiresAt: acquiredAt + WRAPUP_IN_PROGRESS_TTL_MS,
|
|
5538
|
-
updatedAt: acquiredAt
|
|
5539
|
-
};
|
|
5540
|
-
db.exec("BEGIN IMMEDIATE");
|
|
5541
|
-
const transactionStartedAt = performance.now();
|
|
5542
|
-
let finished = false;
|
|
5543
|
-
try {
|
|
5544
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5545
|
-
const current = readRawWrapupState(db, sessionId);
|
|
5546
|
-
if (current && current.expiresAt > now && current.holderId !== state.holderId) {
|
|
5547
|
-
db.exec("COMMIT");
|
|
5548
|
-
finished = true;
|
|
5549
|
-
logSlowWriteTransaction("storage_meta_wrapup_acquire", transactionStartedAt);
|
|
5550
|
-
return { ok: false, state: current };
|
|
5551
|
-
}
|
|
5552
|
-
db.prepare("UPDATE session_meta SET wrapup_in_progress_state = ? WHERE session_id = ?").run(stableStringify(next), sessionId);
|
|
5553
|
-
db.exec("COMMIT");
|
|
5554
|
-
finished = true;
|
|
5555
|
-
logSlowWriteTransaction("storage_meta_wrapup_acquire", transactionStartedAt);
|
|
5556
|
-
return { ok: true, state: next };
|
|
5557
|
-
} finally {
|
|
5558
|
-
if (!finished) {
|
|
5559
|
-
try {
|
|
5560
|
-
db.exec("ROLLBACK");
|
|
5561
|
-
} catch {}
|
|
5562
|
-
}
|
|
5563
|
-
}
|
|
5564
|
-
}
|
|
5565
|
-
function updateWrapupInProgress(db, sessionId, holderId, updates, now = Date.now()) {
|
|
5566
|
-
db.exec("BEGIN IMMEDIATE");
|
|
5567
|
-
const transactionStartedAt = performance.now();
|
|
5568
|
-
let finished = false;
|
|
5569
|
-
try {
|
|
5570
|
-
const current = readRawWrapupState(db, sessionId);
|
|
5571
|
-
if (!current || current.holderId !== holderId || current.expiresAt <= now) {
|
|
5572
|
-
db.exec("ROLLBACK");
|
|
5573
|
-
finished = true;
|
|
5574
|
-
return null;
|
|
5575
|
-
}
|
|
5576
|
-
const next = {
|
|
5577
|
-
...current,
|
|
5578
|
-
...updates,
|
|
5579
|
-
holderId,
|
|
5580
|
-
expiresAt: now + WRAPUP_IN_PROGRESS_TTL_MS,
|
|
5581
|
-
updatedAt: now
|
|
5582
|
-
};
|
|
5583
|
-
db.prepare("UPDATE session_meta SET wrapup_in_progress_state = ? WHERE session_id = ?").run(stableStringify(next), sessionId);
|
|
5584
|
-
db.exec("COMMIT");
|
|
5585
|
-
finished = true;
|
|
5586
|
-
logSlowWriteTransaction("storage_meta_wrapup_update", transactionStartedAt);
|
|
5587
|
-
return next;
|
|
5588
|
-
} finally {
|
|
5589
|
-
if (!finished) {
|
|
5590
|
-
try {
|
|
5591
|
-
db.exec("ROLLBACK");
|
|
5592
|
-
} catch {}
|
|
5593
|
-
}
|
|
5594
|
-
}
|
|
5595
|
-
}
|
|
5596
|
-
function releaseWrapupInProgress(db, sessionId, holderId) {
|
|
5597
|
-
db.exec("BEGIN IMMEDIATE");
|
|
5598
|
-
const transactionStartedAt = performance.now();
|
|
5599
|
-
let finished = false;
|
|
5600
|
-
try {
|
|
5601
|
-
const current = readRawWrapupState(db, sessionId);
|
|
5602
|
-
if (current?.holderId === holderId) {
|
|
5603
|
-
db.prepare("UPDATE session_meta SET wrapup_in_progress_state = NULL WHERE session_id = ?").run(sessionId);
|
|
5604
|
-
}
|
|
5605
|
-
db.exec("COMMIT");
|
|
5606
|
-
finished = true;
|
|
5607
|
-
logSlowWriteTransaction("storage_meta_wrapup_release", transactionStartedAt);
|
|
5608
|
-
} finally {
|
|
5609
|
-
if (!finished) {
|
|
5610
|
-
try {
|
|
5611
|
-
db.exec("ROLLBACK");
|
|
5612
|
-
} catch {}
|
|
5613
|
-
}
|
|
5614
|
-
}
|
|
5615
|
-
}
|
|
5616
|
-
var COMPACTION_MODE_RECORD_VALUES = new Set([
|
|
5617
|
-
"on",
|
|
5618
|
-
"off",
|
|
5619
|
-
"on_notice_pending",
|
|
5620
|
-
"off_notice_pending",
|
|
5621
|
-
"off_cleanup_pending"
|
|
5622
|
-
]);
|
|
5623
|
-
function normalizeCompactionModeRecord(value) {
|
|
5624
|
-
if (value === null || value === undefined)
|
|
5625
|
-
return null;
|
|
5626
|
-
if (typeof value === "string" && COMPACTION_MODE_RECORD_VALUES.has(value)) {
|
|
5627
|
-
return value;
|
|
5628
|
-
}
|
|
5629
|
-
return null;
|
|
5630
|
-
}
|
|
5631
|
-
function resolveCompactionModeRecord(record) {
|
|
5632
|
-
switch (record) {
|
|
5633
|
-
case "on":
|
|
5634
|
-
case "on_notice_pending":
|
|
5635
|
-
return "on";
|
|
5636
|
-
case "off":
|
|
5637
|
-
case "off_notice_pending":
|
|
5638
|
-
case "off_cleanup_pending":
|
|
5639
|
-
return "off";
|
|
5640
|
-
default:
|
|
5641
|
-
return null;
|
|
5642
|
-
}
|
|
5643
|
-
}
|
|
5644
|
-
function getCompactionModeRecord(db, sessionId) {
|
|
5645
|
-
const row = db.prepare("SELECT compaction_mode_record FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5646
|
-
return normalizeCompactionModeRecord(row?.compaction_mode_record);
|
|
5647
|
-
}
|
|
5648
|
-
function setCompactionModeRecord(db, sessionId, value) {
|
|
5649
|
-
if (value !== null && !COMPACTION_MODE_RECORD_VALUES.has(value)) {
|
|
5650
|
-
throw new Error(`Invalid compaction_mode_record value: ${String(value)} (expected a supported compaction mode record or null)`);
|
|
5651
|
-
}
|
|
5652
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5653
|
-
db.prepare("UPDATE session_meta SET compaction_mode_record = ? WHERE session_id = ?").run(value, sessionId);
|
|
5654
|
-
}
|
|
5655
|
-
function protectedTailWindowBudget(usagePercentage, usable, perRunCap) {
|
|
5656
|
-
if (usagePercentage >= 95)
|
|
5657
|
-
return Math.min(1e6, Math.max(4 * perRunCap, Math.round(0.5 * usable)));
|
|
5658
|
-
if (usagePercentage >= 80)
|
|
5659
|
-
return Math.min(750000, Math.max(3 * perRunCap, Math.round(0.35 * usable)));
|
|
5660
|
-
return Math.min(500000, Math.max(perRunCap, Math.round(0.2 * usable)));
|
|
5661
|
-
}
|
|
5662
|
-
var EMERGENCY_DRAIN_EXIT_MARGIN = 10;
|
|
5663
|
-
var EMERGENCY_DRAIN_FALLBACK_EXIT_PERCENTAGE = 55;
|
|
5664
|
-
var EMERGENCY_DRAIN_FAILURE_BACKOFF_MS = 60000;
|
|
5665
|
-
var EMERGENCY_DRAIN_MAX_LATCH_MS = 30 * 60 * 1000;
|
|
5666
|
-
function emergencyDrainExitThreshold(executeThresholdPercentage) {
|
|
5667
|
-
if (!Number.isFinite(executeThresholdPercentage) || executeThresholdPercentage <= 0) {
|
|
5668
|
-
return EMERGENCY_DRAIN_FALLBACK_EXIT_PERCENTAGE;
|
|
5669
|
-
}
|
|
5670
|
-
return Math.max(0, executeThresholdPercentage - EMERGENCY_DRAIN_EXIT_MARGIN);
|
|
5671
|
-
}
|
|
5672
|
-
function resolvedEmergencyDrainLatch(meta, usagePercentage, executeThresholdPercentage, now) {
|
|
5673
|
-
const { forceMaterializationPercentage } = escalationBands(executeThresholdPercentage);
|
|
5674
|
-
if (usagePercentage >= forceMaterializationPercentage)
|
|
5675
|
-
return meta.emergencyDrainActive > 0 ? meta.emergencyDrainActive : now;
|
|
5676
|
-
if (usagePercentage < emergencyDrainExitThreshold(executeThresholdPercentage) || now - meta.emergencyDrainActive > EMERGENCY_DRAIN_MAX_LATCH_MS)
|
|
5677
|
-
return 0;
|
|
5678
|
-
return meta.emergencyDrainActive;
|
|
5679
|
-
}
|
|
5680
|
-
function drainFailureBackoffActive(meta, now) {
|
|
5681
|
-
return meta.historianDrainFailureAt > 0 && meta.historianDrainFailureAt <= now && now - meta.historianDrainFailureAt < EMERGENCY_DRAIN_FAILURE_BACKOFF_MS;
|
|
5682
|
-
}
|
|
5683
|
-
function getProtectedTailDrainBudgetSkip(args) {
|
|
5684
|
-
const now = args.now ?? Date.now();
|
|
5685
|
-
const meta = loadProtectedTailMeta(args.db, args.sessionId);
|
|
5686
|
-
const latch = resolvedEmergencyDrainLatch(meta, args.usagePercentage, args.executeThresholdPercentage, now);
|
|
5687
|
-
if (latch !== meta.emergencyDrainActive) {
|
|
5688
|
-
args.db.prepare("UPDATE session_meta SET emergency_drain_active = ? WHERE session_id = ? AND emergency_drain_active = ?").run(latch, args.sessionId, meta.emergencyDrainActive);
|
|
5689
|
-
}
|
|
5690
|
-
const startedAt = meta.protectedTailDrainWindowStartedAt;
|
|
5691
|
-
if (startedAt <= 0 || startedAt > now || now - startedAt >= DRAIN_WINDOW_MS)
|
|
5692
|
-
return null;
|
|
5693
|
-
const limitTokens = protectedTailWindowBudget(args.usagePercentage, args.usable, args.perRunCap);
|
|
5694
|
-
if (meta.protectedTailDrainTokens < limitTokens)
|
|
5695
|
-
return null;
|
|
5696
|
-
if (latch > 0 && !drainFailureBackoffActive(meta, now))
|
|
5697
|
-
return null;
|
|
5698
|
-
return {
|
|
5699
|
-
windowStartedAt: startedAt,
|
|
5700
|
-
resetsAt: startedAt + DRAIN_WINDOW_MS,
|
|
5701
|
-
nextEligibleAt: latch > 0 ? Math.min(startedAt + DRAIN_WINDOW_MS, meta.historianDrainFailureAt + EMERGENCY_DRAIN_FAILURE_BACKOFF_MS) : startedAt + DRAIN_WINDOW_MS,
|
|
5702
|
-
resetInMs: startedAt + DRAIN_WINDOW_MS - now,
|
|
5703
|
-
spentTokens: meta.protectedTailDrainTokens,
|
|
5704
|
-
limitTokens
|
|
5705
|
-
};
|
|
5706
|
-
}
|
|
5707
|
-
function reserveProtectedTailDrainTokens(args) {
|
|
5708
|
-
const now = args.now ?? Date.now();
|
|
5709
|
-
const requested = Math.max(0, Math.floor(args.trueRawTokens));
|
|
5710
|
-
if (requested === 0) {
|
|
5711
|
-
return {
|
|
5712
|
-
ok: true,
|
|
5713
|
-
reservedTokens: 0,
|
|
5714
|
-
overQuotaBypass: false,
|
|
5715
|
-
reservation: null,
|
|
5716
|
-
budgetState: null
|
|
5717
|
-
};
|
|
5718
|
-
}
|
|
5719
|
-
let result = {
|
|
5720
|
-
ok: false,
|
|
5721
|
-
reservedTokens: 0,
|
|
5722
|
-
overQuotaBypass: false,
|
|
5723
|
-
reservation: null,
|
|
5724
|
-
budgetState: null,
|
|
5725
|
-
skippedReason: "internal drain budget spent"
|
|
5726
|
-
};
|
|
5727
|
-
args.db.transaction(() => {
|
|
5728
|
-
ensureSessionMetaRow(args.db, args.sessionId);
|
|
5729
|
-
let meta = loadProtectedTailMeta(args.db, args.sessionId);
|
|
5730
|
-
const windowStartedAt = meta.protectedTailDrainWindowStartedAt;
|
|
5731
|
-
const windowExpired = windowStartedAt <= 0 || windowStartedAt > now || now - windowStartedAt >= DRAIN_WINDOW_MS;
|
|
5732
|
-
if (windowExpired) {
|
|
5733
|
-
args.db.prepare(`UPDATE session_meta
|
|
5734
|
-
SET protected_tail_drain_window_started_at = ?, protected_tail_drain_tokens = 0
|
|
5735
|
-
WHERE session_id = ?`).run(now, args.sessionId);
|
|
5736
|
-
meta = loadProtectedTailMeta(args.db, args.sessionId);
|
|
5737
|
-
}
|
|
5738
|
-
const latchActiveSince = resolvedEmergencyDrainLatch(meta, args.usagePercentage, args.executeThresholdPercentage, now);
|
|
5739
|
-
if (latchActiveSince !== meta.emergencyDrainActive) {
|
|
5740
|
-
args.db.prepare("UPDATE session_meta SET emergency_drain_active = ? WHERE session_id = ?").run(latchActiveSince, args.sessionId);
|
|
5741
|
-
}
|
|
5742
|
-
const latchActive = latchActiveSince > 0;
|
|
5743
|
-
const budget = protectedTailWindowBudget(args.usagePercentage, args.usable, args.perRunCap);
|
|
5744
|
-
const remaining = Math.max(0, budget - meta.protectedTailDrainTokens);
|
|
5745
|
-
let reserved = Math.min(requested, args.perRunCap, remaining);
|
|
5746
|
-
let bypass = false;
|
|
5747
|
-
const inFailureBackoff = drainFailureBackoffActive(meta, now);
|
|
5748
|
-
if (reserved <= 0 && latchActive && !inFailureBackoff) {
|
|
5749
|
-
reserved = Math.min(requested, args.perRunCap);
|
|
5750
|
-
bypass = true;
|
|
5751
|
-
}
|
|
5752
|
-
const activeWindowStartedAt = meta.protectedTailDrainWindowStartedAt;
|
|
5753
|
-
const budgetState = (spentTokens) => ({
|
|
5754
|
-
windowStartedAt: activeWindowStartedAt,
|
|
5755
|
-
resetsAt: activeWindowStartedAt + DRAIN_WINDOW_MS,
|
|
5756
|
-
resetInMs: Math.max(0, activeWindowStartedAt + DRAIN_WINDOW_MS - now),
|
|
5757
|
-
spentTokens,
|
|
5758
|
-
limitTokens: budget
|
|
5759
|
-
});
|
|
5760
|
-
if (reserved <= 0) {
|
|
5761
|
-
result = {
|
|
5762
|
-
...result,
|
|
5763
|
-
budgetState: budgetState(meta.protectedTailDrainTokens)
|
|
5764
|
-
};
|
|
5765
|
-
return;
|
|
5766
|
-
}
|
|
5767
|
-
args.db.prepare(`UPDATE session_meta
|
|
5768
|
-
SET protected_tail_drain_tokens = COALESCE(protected_tail_drain_tokens, 0) + ?
|
|
5769
|
-
WHERE session_id = ?`).run(reserved, args.sessionId);
|
|
5770
|
-
result = {
|
|
5771
|
-
ok: true,
|
|
5772
|
-
reservedTokens: reserved,
|
|
5773
|
-
overQuotaBypass: bypass,
|
|
5774
|
-
reservation: {
|
|
5775
|
-
sessionId: args.sessionId,
|
|
5776
|
-
runId: args.runId,
|
|
5777
|
-
tokens: reserved,
|
|
5778
|
-
windowStartedAt: activeWindowStartedAt
|
|
5779
|
-
},
|
|
5780
|
-
budgetState: budgetState(meta.protectedTailDrainTokens + reserved)
|
|
5781
|
-
};
|
|
5782
|
-
}).immediate();
|
|
5783
|
-
return result;
|
|
5784
|
-
}
|
|
5785
|
-
function clearEmergencyDrainLatch(db, sessionId) {
|
|
5786
|
-
db.transaction(() => {
|
|
5787
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5788
|
-
db.prepare("UPDATE session_meta SET emergency_drain_active = 0 WHERE session_id = ?").run(sessionId);
|
|
5789
|
-
}).immediate();
|
|
5790
|
-
}
|
|
5791
|
-
function recordHistorianDrainFailure(db, sessionId, now) {
|
|
5792
|
-
const ts = now ?? Date.now();
|
|
5793
|
-
db.transaction(() => {
|
|
5794
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5795
|
-
db.prepare("UPDATE session_meta SET historian_drain_failure_at = ? WHERE session_id = ?").run(ts, sessionId);
|
|
5796
|
-
}).immediate();
|
|
5797
|
-
}
|
|
5798
|
-
function clearHistorianDrainFailure(db, sessionId) {
|
|
5799
|
-
db.transaction(() => {
|
|
5800
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5801
|
-
db.prepare("UPDATE session_meta SET historian_drain_failure_at = 0 WHERE session_id = ?").run(sessionId);
|
|
5802
|
-
}).immediate();
|
|
5803
|
-
}
|
|
5804
|
-
function rollbackProtectedTailDrainReservation(db, reservation) {
|
|
5805
|
-
if (!reservation || reservation.tokens <= 0)
|
|
5806
|
-
return;
|
|
5807
|
-
db.transaction(() => {
|
|
5808
|
-
ensureSessionMetaRow(db, reservation.sessionId);
|
|
5809
|
-
db.prepare(`UPDATE session_meta
|
|
5810
|
-
SET protected_tail_drain_tokens = MAX(0, COALESCE(protected_tail_drain_tokens, 0) - ?)
|
|
5811
|
-
WHERE session_id = ? AND protected_tail_drain_window_started_at = ?`).run(reservation.tokens, reservation.sessionId, reservation.windowStartedAt);
|
|
5812
|
-
}).immediate();
|
|
5813
|
-
}
|
|
5814
|
-
function setPersistedReasoningWatermark(db, sessionId, tagNumber) {
|
|
5815
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5816
|
-
db.prepare("UPDATE session_meta SET cleared_reasoning_through_tag = ? WHERE session_id = ?").run(tagNumber, sessionId);
|
|
5817
|
-
}
|
|
5818
|
-
function clearPersistedReasoningWatermark(db, sessionId) {
|
|
5819
|
-
setPersistedReasoningWatermark(db, sessionId, 0);
|
|
5820
|
-
}
|
|
5821
|
-
function isEmergencyInputSampleRow(row) {
|
|
5822
|
-
return typeof row === "object" && row !== null && typeof row.last_emergency_input_sample === "number";
|
|
5823
|
-
}
|
|
5824
|
-
function getEmergencyInputSample(db, sessionId) {
|
|
5825
|
-
const result = db.prepare("SELECT last_emergency_input_sample FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5826
|
-
return isEmergencyInputSampleRow(result) ? result.last_emergency_input_sample : 0;
|
|
5827
|
-
}
|
|
5828
|
-
function setEmergencyDropSample(db, sessionId, inputSample) {
|
|
5829
|
-
db.transaction(() => {
|
|
5830
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5831
|
-
db.prepare("UPDATE session_meta SET last_emergency_input_sample = ? WHERE session_id = ?").run(Math.max(0, Math.round(inputSample)), sessionId);
|
|
5832
|
-
}).immediate();
|
|
5833
|
-
}
|
|
5834
|
-
function clearEmergencyDropSample(db, sessionId) {
|
|
5835
|
-
db.transaction(() => {
|
|
5836
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5837
|
-
db.prepare("UPDATE session_meta SET last_emergency_input_sample = 0 WHERE session_id = ?").run(sessionId);
|
|
5838
|
-
}).immediate();
|
|
5839
|
-
}
|
|
5840
|
-
var EMPTY_CHANNEL1_NUDGE_STATE = { level: "", ordinal: 0 };
|
|
5841
|
-
function isLastNudgeUndroppedRow(row) {
|
|
5842
|
-
return typeof row === "object" && row !== null && typeof row.last_nudge_undropped === "number";
|
|
5843
|
-
}
|
|
5844
|
-
function isLastNudgeLevelRow(row) {
|
|
5845
|
-
return typeof row === "object" && row !== null && typeof row.last_nudge_level === "string";
|
|
5846
|
-
}
|
|
5847
|
-
function normalizeLastNudgeLevel(value) {
|
|
5848
|
-
return value === "gentle" || value === "firm" || value === "urgent" ? value : "";
|
|
5849
|
-
}
|
|
5850
|
-
function parseChannel1NudgeState(raw) {
|
|
5851
|
-
try {
|
|
5852
|
-
const parsed = JSON.parse(raw);
|
|
5853
|
-
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
5854
|
-
const state = {
|
|
5855
|
-
level: normalizeLastNudgeLevel(parsed.level),
|
|
5856
|
-
ordinal: typeof parsed.ordinal === "number" ? Math.max(0, Math.round(parsed.ordinal)) : 0
|
|
5857
|
-
};
|
|
5858
|
-
if (parsed.postReduceGracePending === true)
|
|
5859
|
-
state.postReduceGracePending = true;
|
|
5860
|
-
if (typeof parsed.postReduceGraceBaselineU === "number" && Number.isFinite(parsed.postReduceGraceBaselineU)) {
|
|
5861
|
-
state.postReduceGraceBaselineU = Math.max(0, Math.round(parsed.postReduceGraceBaselineU));
|
|
5862
|
-
}
|
|
5863
|
-
const preLevel = normalizeLastNudgeLevel(parsed.postReduceGracePreLevel);
|
|
5864
|
-
if (preLevel !== "" || parsed.postReduceGracePreLevel === "") {
|
|
5865
|
-
state.postReduceGracePreLevel = preLevel;
|
|
5866
|
-
}
|
|
5867
|
-
return state;
|
|
5868
|
-
}
|
|
5869
|
-
} catch {}
|
|
5870
|
-
return { level: normalizeLastNudgeLevel(raw), ordinal: 0 };
|
|
5871
|
-
}
|
|
5872
|
-
function serializeChannel1NudgeState(value) {
|
|
5873
|
-
const serialized = {
|
|
5874
|
-
level: normalizeLastNudgeLevel(value.level),
|
|
5875
|
-
ordinal: Math.max(0, Math.round(value.ordinal))
|
|
5876
|
-
};
|
|
5877
|
-
if (value.postReduceGracePending === true)
|
|
5878
|
-
serialized.postReduceGracePending = true;
|
|
5879
|
-
if (value.postReduceGraceBaselineU !== undefined) {
|
|
5880
|
-
serialized.postReduceGraceBaselineU = Math.max(0, Math.round(value.postReduceGraceBaselineU));
|
|
5881
|
-
}
|
|
5882
|
-
if (value.postReduceGracePreLevel !== undefined) {
|
|
5883
|
-
serialized.postReduceGracePreLevel = normalizeLastNudgeLevel(value.postReduceGracePreLevel);
|
|
5884
|
-
}
|
|
5885
|
-
return JSON.stringify(serialized);
|
|
5886
|
-
}
|
|
5887
|
-
function getLastNudgeUndropped(db, sessionId) {
|
|
5888
|
-
const result = db.prepare("SELECT last_nudge_undropped FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5889
|
-
return isLastNudgeUndroppedRow(result) ? result.last_nudge_undropped : 0;
|
|
5890
|
-
}
|
|
5891
|
-
function setLastNudgeUndropped(db, sessionId, value) {
|
|
5892
|
-
db.transaction(() => {
|
|
5893
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5894
|
-
db.prepare("UPDATE session_meta SET last_nudge_undropped = ? WHERE session_id = ?").run(Math.max(0, Math.round(value)), sessionId);
|
|
5895
|
-
}).immediate();
|
|
5896
|
-
}
|
|
5897
|
-
function getChannel1NudgeState(db, sessionId) {
|
|
5898
|
-
const result = db.prepare("SELECT last_nudge_level FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5899
|
-
return isLastNudgeLevelRow(result) ? parseChannel1NudgeState(result.last_nudge_level) : EMPTY_CHANNEL1_NUDGE_STATE;
|
|
5900
|
-
}
|
|
5901
|
-
function setChannel1NudgeState(db, sessionId, value) {
|
|
5902
|
-
db.transaction(() => {
|
|
5903
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5904
|
-
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
|
|
5905
|
-
}).immediate();
|
|
5906
|
-
}
|
|
5907
|
-
function markChannel1PostReduceGracePending(db, sessionId) {
|
|
5908
|
-
return db.transaction(() => {
|
|
5909
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5910
|
-
const current = getChannel1NudgeState(db, sessionId);
|
|
5911
|
-
const next = {
|
|
5912
|
-
level: current.level,
|
|
5913
|
-
ordinal: current.ordinal,
|
|
5914
|
-
postReduceGracePending: true,
|
|
5915
|
-
postReduceGracePreLevel: current.level
|
|
5916
|
-
};
|
|
5917
|
-
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
|
|
5918
|
-
return next;
|
|
5919
|
-
}).immediate();
|
|
5920
|
-
}
|
|
5921
|
-
function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped) {
|
|
5922
|
-
return db.transaction(() => {
|
|
5923
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5924
|
-
const current = getChannel1NudgeState(db, sessionId);
|
|
5925
|
-
if (current.postReduceGracePending !== true)
|
|
5926
|
-
return current;
|
|
5927
|
-
const baselineU = Math.max(0, Math.round(measuredUndropped));
|
|
5928
|
-
const next = {
|
|
5929
|
-
level: current.level,
|
|
5930
|
-
ordinal: current.ordinal,
|
|
5931
|
-
postReduceGraceBaselineU: baselineU,
|
|
5932
|
-
postReduceGracePreLevel: current.postReduceGracePreLevel ?? current.level
|
|
5933
|
-
};
|
|
5934
|
-
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
|
|
5935
|
-
return next;
|
|
5936
|
-
}).immediate();
|
|
5937
|
-
}
|
|
5938
|
-
function isChannel2StateRow(row) {
|
|
5939
|
-
return typeof row === "object" && row !== null && typeof row.channel2_nudge_state === "string";
|
|
5940
|
-
}
|
|
5941
|
-
function getChannel2NudgeState(db, sessionId) {
|
|
5942
|
-
const result = db.prepare("SELECT channel2_nudge_state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5943
|
-
if (!isChannel2StateRow(result))
|
|
5944
|
-
return "";
|
|
5945
|
-
const raw = result.channel2_nudge_state;
|
|
5946
|
-
return raw === "pending" || raw === "claimed" || raw === "delivered" ? raw : "";
|
|
5947
|
-
}
|
|
5948
|
-
function getChannel2NudgeClaim(db, sessionId) {
|
|
5949
|
-
const result = db.prepare("SELECT channel2_nudge_state, channel2_nudge_claimed_at, channel2_nudge_claim_token FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5950
|
-
const rawState = typeof result?.channel2_nudge_state === "string" ? result.channel2_nudge_state : "";
|
|
5951
|
-
const state = rawState === "pending" || rawState === "claimed" || rawState === "delivered" ? rawState : "";
|
|
5952
|
-
return {
|
|
5953
|
-
state,
|
|
5954
|
-
claimedAt: typeof result?.channel2_nudge_claimed_at === "number" ? result.channel2_nudge_claimed_at : 0,
|
|
5955
|
-
claimToken: typeof result?.channel2_nudge_claim_token === "string" ? result.channel2_nudge_claim_token : ""
|
|
5956
|
-
};
|
|
5957
|
-
}
|
|
5958
|
-
function setChannel2NudgeState(db, sessionId, state) {
|
|
5959
|
-
db.transaction(() => {
|
|
5960
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5961
|
-
const claimedAt = state === "claimed" ? Date.now() : 0;
|
|
5962
|
-
db.prepare("UPDATE session_meta SET channel2_nudge_state = ?, channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = '' WHERE session_id = ?").run(state, claimedAt, sessionId);
|
|
5963
|
-
}).immediate();
|
|
5964
|
-
}
|
|
5965
|
-
function casChannel2NudgeState(db, sessionId, from, to) {
|
|
5966
|
-
let changed = false;
|
|
5967
|
-
db.transaction(() => {
|
|
5968
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5969
|
-
const claimedAt = to === "claimed" ? Date.now() : 0;
|
|
5970
|
-
const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = ?, channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = '' WHERE session_id = ? AND channel2_nudge_state = ?").run(to, claimedAt, sessionId, from);
|
|
5971
|
-
changed = (result.changes ?? 0) > 0;
|
|
5972
|
-
}).immediate();
|
|
5973
|
-
return changed;
|
|
5974
|
-
}
|
|
5975
|
-
function claimChannel2NudgeState(db, sessionId, claimToken) {
|
|
5976
|
-
let changed = false;
|
|
5977
|
-
db.transaction(() => {
|
|
5978
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5979
|
-
const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = 'claimed', channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = ? WHERE session_id = ? AND channel2_nudge_state = 'pending'").run(Date.now(), claimToken, sessionId);
|
|
5980
|
-
changed = (result.changes ?? 0) > 0;
|
|
5981
|
-
}).immediate();
|
|
5982
|
-
return changed;
|
|
5983
|
-
}
|
|
5984
|
-
function casChannel2NudgeClaim(db, sessionId, to, claimToken) {
|
|
5985
|
-
let changed = false;
|
|
5986
|
-
db.transaction(() => {
|
|
5987
|
-
ensureSessionMetaRow(db, sessionId);
|
|
5988
|
-
const claimedAt = to === "claimed" ? Date.now() : 0;
|
|
5989
|
-
const nextClaimToken = to === "claimed" ? claimToken : "";
|
|
5990
|
-
const result = db.prepare("UPDATE session_meta SET channel2_nudge_state = ?, channel2_nudge_claimed_at = ?, channel2_nudge_claim_token = ? WHERE session_id = ? AND channel2_nudge_state = 'claimed' AND channel2_nudge_claim_token = ?").run(to, claimedAt, nextClaimToken, sessionId, claimToken);
|
|
5991
|
-
changed = (result.changes ?? 0) > 0;
|
|
5992
|
-
}).immediate();
|
|
5993
|
-
return changed;
|
|
5994
|
-
}
|
|
5995
|
-
function getPersistedNoteNudge(db, sessionId) {
|
|
5996
|
-
const result = db.prepare("SELECT note_nudge_trigger_pending, note_nudge_trigger_message_id, note_nudge_sticky_text, note_nudge_sticky_message_id FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
5997
|
-
if (!isPersistedNoteNudgeRow(result)) {
|
|
5998
|
-
return getDefaultPersistedNoteNudge();
|
|
5999
|
-
}
|
|
6000
|
-
return {
|
|
6001
|
-
triggerPending: result.note_nudge_trigger_pending === 1,
|
|
6002
|
-
triggerMessageId: result.note_nudge_trigger_message_id.length > 0 ? result.note_nudge_trigger_message_id : null,
|
|
6003
|
-
stickyText: result.note_nudge_sticky_text.length > 0 ? result.note_nudge_sticky_text : null,
|
|
6004
|
-
stickyMessageId: result.note_nudge_sticky_message_id.length > 0 ? result.note_nudge_sticky_message_id : null
|
|
6005
|
-
};
|
|
6006
|
-
}
|
|
6007
|
-
function setPersistedNoteNudgeTrigger(db, sessionId, triggerMessageId = "") {
|
|
6008
|
-
db.transaction(() => {
|
|
6009
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6010
|
-
db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 1, note_nudge_trigger_message_id = ? WHERE session_id = ?").run(triggerMessageId, sessionId);
|
|
6011
|
-
}).immediate();
|
|
6012
|
-
}
|
|
6013
|
-
function setPersistedNoteNudgeTriggerMessageId(db, sessionId, triggerMessageId) {
|
|
6014
|
-
db.transaction(() => {
|
|
6015
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6016
|
-
db.prepare("UPDATE session_meta SET note_nudge_trigger_message_id = ? WHERE session_id = ?").run(triggerMessageId, sessionId);
|
|
6017
|
-
}).immediate();
|
|
6018
|
-
}
|
|
6019
|
-
function getNoteNudgeAnchors(db, sessionId) {
|
|
6020
|
-
const row = db.prepare("SELECT note_nudge_anchors FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6021
|
-
return parseJsonArray(row?.note_nudge_anchors, isValidNoteNudgeAnchor);
|
|
6022
|
-
}
|
|
6023
|
-
function getAutoSearchHintDecisions(db, sessionId) {
|
|
6024
|
-
const row = db.prepare("SELECT auto_search_hint_decisions FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6025
|
-
return parseJsonArray(row?.auto_search_hint_decisions, isValidAutoSearchHintDecision);
|
|
6026
|
-
}
|
|
6027
|
-
function casUpdateJsonArrayColumn(db, sessionId, column, validator, mutate, options) {
|
|
6028
|
-
if (column !== "note_nudge_anchors" && column !== "auto_search_hint_decisions") {
|
|
6029
|
-
throw new Error(`casUpdateJsonArrayColumn: refusing unknown column "${column}"`);
|
|
6030
|
-
}
|
|
6031
|
-
if (options?.ensureRow === false) {
|
|
6032
|
-
const exists = db.prepare("SELECT 1 FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6033
|
-
if (!exists)
|
|
6034
|
-
return true;
|
|
6035
|
-
} else {
|
|
6036
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6037
|
-
}
|
|
6038
|
-
for (let attempt = 0;attempt < CAS_RETRY_LIMIT2; attempt += 1) {
|
|
6039
|
-
const row = db.prepare(`SELECT ${column} FROM session_meta WHERE session_id = ?`).get(sessionId);
|
|
6040
|
-
const rawCurrent = row?.[column] ?? null;
|
|
6041
|
-
const currentBlob = rawCurrent ?? "[]";
|
|
6042
|
-
const current = parseJsonArray(currentBlob, validator);
|
|
6043
|
-
const next = mutate(current);
|
|
6044
|
-
if (next === null)
|
|
6045
|
-
return true;
|
|
6046
|
-
const nextBlob = stableStringify(next);
|
|
6047
|
-
if (nextBlob === currentBlob)
|
|
6048
|
-
return true;
|
|
6049
|
-
const result = db.prepare(`UPDATE session_meta SET ${column} = ? WHERE session_id = ? AND ${column} IS ?`).run(nextBlob, sessionId, rawCurrent);
|
|
6050
|
-
if (result.changes > 0)
|
|
6051
|
-
return true;
|
|
6052
|
-
}
|
|
6053
|
-
sessionLog2(sessionId, `${column} CAS: ${CAS_RETRY_LIMIT2} retries exhausted`);
|
|
6054
|
-
return false;
|
|
6055
|
-
}
|
|
6056
|
-
function deliverNoteNudgeAtomic(db, sessionId, messageId, text) {
|
|
6057
|
-
let plan = null;
|
|
6058
|
-
const casOk = casUpdateJsonArrayColumn(db, sessionId, "note_nudge_anchors", isValidNoteNudgeAnchor, (current) => {
|
|
6059
|
-
if (current.some((anchor) => anchor.messageId === messageId && anchor.text === text)) {
|
|
6060
|
-
plan = { kind: "already-present" };
|
|
6061
|
-
return null;
|
|
6062
|
-
}
|
|
6063
|
-
if (current.some((anchor) => anchor.messageId === messageId)) {
|
|
6064
|
-
plan = { kind: "conflict" };
|
|
6065
|
-
sessionLog2(sessionId, "note-nudge: messageId conflict, refusing append");
|
|
6066
|
-
return null;
|
|
6067
|
-
}
|
|
6068
|
-
plan = { kind: "appended" };
|
|
6069
|
-
return [...current, { messageId, text }];
|
|
6070
|
-
});
|
|
6071
|
-
if (!casOk) {
|
|
6072
|
-
sessionLog2(sessionId, `note-nudge: CAS exhausted for ${messageId}; skipping wire append`);
|
|
6073
|
-
return { ok: false, kind: "cas-exhausted" };
|
|
6074
|
-
}
|
|
6075
|
-
const committedPlan = plan;
|
|
6076
|
-
if (!committedPlan) {
|
|
6077
|
-
sessionLog2(sessionId, "note-nudge: CAS reported success with no plan staged; treating as failure");
|
|
6078
|
-
return { ok: false, kind: "cas-exhausted" };
|
|
6079
|
-
}
|
|
6080
|
-
if (committedPlan.kind === "conflict") {
|
|
6081
|
-
return { ok: false, kind: "conflict" };
|
|
6082
|
-
}
|
|
6083
|
-
db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
|
|
6084
|
-
return { ok: true, kind: committedPlan.kind };
|
|
6085
|
-
}
|
|
6086
|
-
function appendAutoSearchHintDecision(db, sessionId, entry) {
|
|
6087
|
-
if (!entry.messageId)
|
|
6088
|
-
return { ok: false, kind: "cas-exhausted" };
|
|
6089
|
-
let staged = null;
|
|
6090
|
-
const casOk = casUpdateJsonArrayColumn(db, sessionId, "auto_search_hint_decisions", isValidAutoSearchHintDecision, (current) => {
|
|
6091
|
-
const existing = current.find((decision) => decision.messageId === entry.messageId);
|
|
6092
|
-
if (existing) {
|
|
6093
|
-
staged = { kind: "already-present", decision: existing };
|
|
6094
|
-
return null;
|
|
6095
|
-
}
|
|
6096
|
-
staged = { kind: "appended", decision: entry };
|
|
6097
|
-
return [...current, entry];
|
|
6098
|
-
});
|
|
6099
|
-
if (!casOk)
|
|
6100
|
-
return { ok: false, kind: "cas-exhausted" };
|
|
6101
|
-
const committed = staged;
|
|
6102
|
-
if (!committed) {
|
|
6103
|
-
sessionLog2(sessionId, "auto-search: CAS reported success with no staged outcome");
|
|
6104
|
-
return { ok: false, kind: "cas-exhausted" };
|
|
6105
|
-
}
|
|
6106
|
-
return { ok: true, kind: committed.kind, decision: committed.decision };
|
|
6107
|
-
}
|
|
6108
|
-
function pruneNoteNudgeAnchors(db, sessionId, visibleMessageIds) {
|
|
6109
|
-
let pruned = 0;
|
|
6110
|
-
casUpdateJsonArrayColumn(db, sessionId, "note_nudge_anchors", isValidNoteNudgeAnchor, (current) => {
|
|
6111
|
-
const next = current.filter((anchor) => visibleMessageIds.has(anchor.messageId));
|
|
6112
|
-
pruned = current.length - next.length;
|
|
6113
|
-
return pruned > 0 ? next : null;
|
|
6114
|
-
});
|
|
6115
|
-
return pruned;
|
|
6116
|
-
}
|
|
6117
|
-
var pendingAutoSearchRetirements = new WeakMap;
|
|
6118
|
-
var AUTO_SEARCH_DECISION_SOFT_LIMIT = 2000;
|
|
6119
|
-
function queueAutoSearchHintDecisionRetirement(db, sessionId, messageIds) {
|
|
6120
|
-
if (messageIds.size === 0)
|
|
6121
|
-
return;
|
|
6122
|
-
let sessions = pendingAutoSearchRetirements.get(db);
|
|
6123
|
-
if (!sessions) {
|
|
6124
|
-
sessions = new Map;
|
|
6125
|
-
pendingAutoSearchRetirements.set(db, sessions);
|
|
6126
|
-
}
|
|
6127
|
-
let retired = sessions.get(sessionId);
|
|
6128
|
-
if (!retired) {
|
|
6129
|
-
retired = new Set;
|
|
6130
|
-
sessions.set(sessionId, retired);
|
|
6131
|
-
}
|
|
6132
|
-
for (const id of messageIds)
|
|
6133
|
-
retired.add(id);
|
|
6134
|
-
}
|
|
6135
|
-
function flushAutoSearchHintDecisionRetirement(db, sessionId, visibleMessageIds) {
|
|
6136
|
-
const sessions = pendingAutoSearchRetirements.get(db);
|
|
6137
|
-
const retired = sessions?.get(sessionId) ?? new Set;
|
|
6138
|
-
const outcome = updateAutoSearchHintRetirement(db, sessionId, retired, visibleMessageIds);
|
|
6139
|
-
if (outcome.ok)
|
|
6140
|
-
sessions?.delete(sessionId);
|
|
6141
|
-
return outcome.pruned;
|
|
6142
|
-
}
|
|
6143
|
-
function updateAutoSearchHintRetirement(db, sessionId, retiredMessageIds, visibleMessageIds) {
|
|
6144
|
-
let pruned = 0;
|
|
6145
|
-
const ok = casUpdateJsonArrayColumn(db, sessionId, "auto_search_hint_decisions", isValidAutoSearchHintDecision, (current) => {
|
|
6146
|
-
let next = current.filter((decision) => !retiredMessageIds.has(decision.messageId) || visibleMessageIds?.has(decision.messageId));
|
|
6147
|
-
let excess = next.length - AUTO_SEARCH_DECISION_SOFT_LIMIT;
|
|
6148
|
-
if (visibleMessageIds && excess > 0) {
|
|
6149
|
-
next = next.filter((decision) => {
|
|
6150
|
-
if (excess > 0 && decision.decision === "no-hint" && !visibleMessageIds.has(decision.messageId)) {
|
|
6151
|
-
excess--;
|
|
6152
|
-
return false;
|
|
6153
|
-
}
|
|
6154
|
-
return true;
|
|
6155
|
-
});
|
|
6156
|
-
}
|
|
6157
|
-
pruned = current.length - next.length;
|
|
6158
|
-
return pruned > 0 ? next : null;
|
|
6159
|
-
}, { ensureRow: false });
|
|
6160
|
-
return { ok, pruned: ok ? pruned : 0 };
|
|
6161
|
-
}
|
|
6162
|
-
function parsePersistedTodoSyntheticAnchor(result) {
|
|
6163
|
-
if (!isPersistedTodoSyntheticAnchorRow(result))
|
|
6164
|
-
return null;
|
|
6165
|
-
if (result.todo_synthetic_call_id.length === 0 || result.todo_synthetic_anchor_message_id.length === 0) {
|
|
6166
|
-
return null;
|
|
6167
|
-
}
|
|
6168
|
-
return {
|
|
6169
|
-
callId: result.todo_synthetic_call_id,
|
|
6170
|
-
messageId: result.todo_synthetic_anchor_message_id,
|
|
6171
|
-
stateJson: result.todo_synthetic_state_json
|
|
6172
|
-
};
|
|
6173
|
-
}
|
|
6174
|
-
function getPersistedTodoSyntheticAnchor(db, sessionId) {
|
|
6175
|
-
const result = db.prepare("SELECT todo_synthetic_call_id, todo_synthetic_anchor_message_id, todo_synthetic_state_json FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6176
|
-
return parsePersistedTodoSyntheticAnchor(result);
|
|
6177
|
-
}
|
|
6178
|
-
function setPersistedTodoSyntheticAnchor(db, sessionId, callId, messageId, stateJson) {
|
|
6179
|
-
db.transaction(() => {
|
|
6180
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6181
|
-
db.prepare("UPDATE session_meta SET todo_synthetic_call_id = ?, todo_synthetic_anchor_message_id = ?, todo_synthetic_state_json = ? WHERE session_id = ?").run(callId, messageId, stateJson, sessionId);
|
|
6182
|
-
}).immediate();
|
|
6183
|
-
}
|
|
6184
|
-
function clearPersistedTodoSyntheticAnchor(db, sessionId) {
|
|
6185
|
-
db.prepare("UPDATE session_meta SET todo_synthetic_call_id = '', todo_synthetic_anchor_message_id = '', todo_synthetic_state_json = '' WHERE session_id = ?").run(sessionId);
|
|
6186
|
-
}
|
|
6187
|
-
function getNoteLastReadAt(db, sessionId) {
|
|
6188
|
-
try {
|
|
6189
|
-
const result = db.prepare("SELECT note_last_read_at FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6190
|
-
if (!result || typeof result !== "object")
|
|
6191
|
-
return 0;
|
|
6192
|
-
const value = result.note_last_read_at;
|
|
6193
|
-
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
6194
|
-
} catch {
|
|
6195
|
-
return 0;
|
|
6196
|
-
}
|
|
6197
|
-
}
|
|
6198
|
-
function setNoteLastReadAt(db, sessionId, at = Date.now()) {
|
|
6199
|
-
db.transaction(() => {
|
|
6200
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6201
|
-
db.prepare("UPDATE session_meta SET note_last_read_at = ? WHERE session_id = ?").run(at, sessionId);
|
|
6202
|
-
}).immediate();
|
|
6203
|
-
}
|
|
6204
|
-
function getHistorianFailureState(db, sessionId) {
|
|
6205
|
-
const result = db.prepare("SELECT historian_failure_count, historian_last_error, historian_last_failure_at FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6206
|
-
return parseHistorianFailureState(result);
|
|
6207
|
-
}
|
|
6208
|
-
function incrementHistorianFailure(db, sessionId, error) {
|
|
6209
|
-
let nextCount = 1;
|
|
6210
|
-
db.transaction(() => {
|
|
6211
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6212
|
-
const current = getHistorianFailureState(db, sessionId);
|
|
6213
|
-
nextCount = current.failureCount + 1;
|
|
6214
|
-
db.prepare("UPDATE session_meta SET historian_failure_count = ?, historian_last_error = ?, historian_last_failure_at = ? WHERE session_id = ?").run(nextCount, error, Date.now(), sessionId);
|
|
6215
|
-
const reason = error.replace(/\s+/g, " ").trim().slice(0, 300);
|
|
6216
|
-
sessionLog2(sessionId, `historian failure recorded: count=${nextCount} reason="${reason}"`);
|
|
6217
|
-
}).immediate();
|
|
6218
|
-
return nextCount;
|
|
6219
|
-
}
|
|
6220
|
-
function clearHistorianFailureState(db, sessionId) {
|
|
6221
|
-
db.transaction(() => {
|
|
6222
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6223
|
-
db.prepare("UPDATE session_meta SET historian_failure_count = 0, historian_last_error = NULL, historian_last_failure_at = NULL WHERE session_id = ?").run(sessionId);
|
|
6224
|
-
}).immediate();
|
|
6225
|
-
}
|
|
6226
|
-
function normalizeDetectedLimitModelKey(modelKey) {
|
|
6227
|
-
return typeof modelKey === "string" && modelKey.length > 0 ? piModelRefToCanonical(modelKey) : null;
|
|
6228
|
-
}
|
|
6229
|
-
function normalizeEmergencyRecoveryOrigin(value) {
|
|
6230
|
-
return value === "provider_overflow" || value === "proactive_model_shrink" ? value : null;
|
|
6231
|
-
}
|
|
6232
|
-
function parseOverflowState(result, modelKey) {
|
|
6233
|
-
if (!result) {
|
|
6234
|
-
return {
|
|
6235
|
-
detectedContextLimit: 0,
|
|
6236
|
-
detectedContextLimitModelKey: null,
|
|
6237
|
-
detectedContextLimitProvenance: "unknown",
|
|
6238
|
-
needsEmergencyRecovery: false,
|
|
6239
|
-
emergencyRecoveryOrigin: null
|
|
6240
|
-
};
|
|
6241
|
-
}
|
|
6242
|
-
const storedModelKey = normalizeDetectedLimitModelKey(result.detected_context_limit_model_key);
|
|
6243
|
-
const requestedModelKey = normalizeDetectedLimitModelKey(modelKey);
|
|
6244
|
-
const provenance = normalizeContextLimitProvenance(result.detected_context_limit_provenance);
|
|
6245
|
-
const limit = typeof result.detected_context_limit === "number" && result.detected_context_limit > 0 ? result.detected_context_limit : 0;
|
|
6246
|
-
const modelMatches = requestedModelKey ? storedModelKey !== null && requestedModelKey === storedModelKey : true;
|
|
6247
|
-
const needs = typeof result.needs_emergency_recovery === "number" && result.needs_emergency_recovery > 0;
|
|
6248
|
-
const persistedOrigin = normalizeEmergencyRecoveryOrigin(result.emergency_recovery_origin);
|
|
6249
|
-
const recoveryOrigin = needs ? persistedOrigin ?? (limit > 0 ? "provider_overflow" : null) : null;
|
|
6250
|
-
return {
|
|
6251
|
-
detectedContextLimit: modelMatches ? limit : 0,
|
|
6252
|
-
detectedContextLimitModelKey: storedModelKey,
|
|
6253
|
-
detectedContextLimitProvenance: provenance,
|
|
6254
|
-
needsEmergencyRecovery: needs,
|
|
6255
|
-
emergencyRecoveryOrigin: recoveryOrigin
|
|
6256
|
-
};
|
|
6257
|
-
}
|
|
6258
|
-
function getOverflowState(db, sessionId, modelKey) {
|
|
6259
|
-
const result = db.prepare("SELECT detected_context_limit, detected_context_limit_model_key, detected_context_limit_provenance, needs_emergency_recovery, emergency_recovery_origin FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6260
|
-
return parseOverflowState(result, modelKey);
|
|
6261
|
-
}
|
|
6262
|
-
function recordOverflowDetected(db, sessionId, reportedLimit, modelKey, origin = "provider_overflow", provenance = "unknown", reportedInputTokens) {
|
|
6263
|
-
emergencyRecoveryArmedSessions.add(sessionId);
|
|
6264
|
-
emergencyRecoveryArmedAtBySession.set(sessionId, Date.now());
|
|
6265
|
-
if (origin === "provider_overflow" && typeof reportedLimit === "number" && reportedLimit > 0) {
|
|
6266
|
-
providerOverflowKnownLimitSessions.add(sessionId);
|
|
6267
|
-
}
|
|
6268
|
-
db.transaction(() => {
|
|
6269
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6270
|
-
const prior = db.prepare("SELECT needs_emergency_recovery, detected_context_limit FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6271
|
-
if (origin === "provider_overflow" && typeof prior?.needs_emergency_recovery === "number" && prior.needs_emergency_recovery > 0) {
|
|
6272
|
-
providerOverflowReconfirmedSessions.add(sessionId);
|
|
6273
|
-
}
|
|
6274
|
-
if (typeof reportedLimit === "number" && reportedLimit > 0) {
|
|
6275
|
-
db.prepare("UPDATE session_meta SET detected_context_limit = ?, detected_context_limit_model_key = ?, detected_context_limit_provenance = ?, needs_emergency_recovery = 1, emergency_recovery_origin = ?, observed_safe_input_tokens = 0, cache_alert_sent = 0 WHERE session_id = ?").run(reportedLimit, normalizeDetectedLimitModelKey(modelKey), normalizeContextLimitProvenance(provenance), origin, sessionId);
|
|
6276
|
-
} else {
|
|
6277
|
-
db.prepare("UPDATE session_meta SET needs_emergency_recovery = 1, emergency_recovery_origin = ?, observed_safe_input_tokens = 0, cache_alert_sent = 0 WHERE session_id = ?").run(origin, sessionId);
|
|
6278
|
-
}
|
|
6279
|
-
if (origin === "provider_overflow" && typeof reportedInputTokens === "number" && Number.isFinite(reportedInputTokens) && reportedInputTokens > 0) {
|
|
6280
|
-
const effectiveLimit = typeof reportedLimit === "number" && reportedLimit > 0 ? reportedLimit : prior?.detected_context_limit ?? 0;
|
|
6281
|
-
const percentage = effectiveLimit > 0 ? reportedInputTokens / effectiveLimit * 100 : 100;
|
|
6282
|
-
db.prepare("UPDATE session_meta SET last_input_tokens = ?, last_context_percentage = MAX(last_context_percentage, ?) WHERE session_id = ?").run(reportedInputTokens, percentage, sessionId);
|
|
6283
|
-
}
|
|
6284
|
-
}).immediate();
|
|
6285
|
-
}
|
|
6286
|
-
function clearEmergencyRecovery(db, sessionId) {
|
|
6287
|
-
db.transaction(() => {
|
|
6288
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6289
|
-
try {
|
|
6290
|
-
db.prepare("UPDATE session_meta SET needs_emergency_recovery = 0, emergency_recovery_origin = '', recovery_no_eligible_head_count = 0 WHERE session_id = ?").run(sessionId);
|
|
6291
|
-
} catch {
|
|
6292
|
-
db.prepare("UPDATE session_meta SET needs_emergency_recovery = 0, emergency_recovery_origin = '' WHERE session_id = ?").run(sessionId);
|
|
6293
|
-
}
|
|
6294
|
-
}).immediate();
|
|
6295
|
-
emergencyRecoveryArmedSessions.delete(sessionId);
|
|
6296
|
-
emergencyRecoveryArmedAtBySession.delete(sessionId);
|
|
6297
|
-
providerOverflowReconfirmedSessions.delete(sessionId);
|
|
6298
|
-
providerOverflowKnownLimitSessions.delete(sessionId);
|
|
6299
|
-
}
|
|
6300
|
-
function clearDetectedContextLimit(db, sessionId) {
|
|
6301
|
-
db.transaction(() => {
|
|
6302
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6303
|
-
db.prepare("UPDATE session_meta SET detected_context_limit = 0, detected_context_limit_model_key = NULL, detected_context_limit_provenance = 'unknown' WHERE session_id = ?").run(sessionId);
|
|
6304
|
-
}).immediate();
|
|
6305
|
-
}
|
|
6306
|
-
function parsePersistedCompactionMarkerState(raw, storedTargetEndMessageId) {
|
|
6307
|
-
if (!raw || raw.length === 0)
|
|
6308
|
-
return null;
|
|
6309
|
-
try {
|
|
6310
|
-
const parsed = JSON.parse(raw);
|
|
6311
|
-
if (parsed && typeof parsed === "object" && typeof parsed.boundaryMessageId === "string" && typeof parsed.summaryMessageId === "string" && typeof parsed.compactionPartId === "string" && typeof parsed.summaryPartId === "string" && typeof parsed.boundaryOrdinal === "number") {
|
|
6312
|
-
const targetEndMessageId = typeof storedTargetEndMessageId === "string" && storedTargetEndMessageId.length > 0 ? storedTargetEndMessageId : typeof parsed.targetEndMessageId === "string" && parsed.targetEndMessageId.length > 0 ? parsed.targetEndMessageId : null;
|
|
6313
|
-
return {
|
|
6314
|
-
...parsed,
|
|
6315
|
-
targetEndMessageId
|
|
6316
|
-
};
|
|
6317
|
-
}
|
|
6318
|
-
} catch {}
|
|
6319
|
-
return null;
|
|
6320
|
-
}
|
|
6321
|
-
function getPersistedCompactionMarkerState(db, sessionId) {
|
|
6322
|
-
const row = db.prepare("SELECT compaction_marker_state, compaction_marker_target_end_message_id FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6323
|
-
return parsePersistedCompactionMarkerState(row?.compaction_marker_state, row?.compaction_marker_target_end_message_id);
|
|
6324
|
-
}
|
|
6325
|
-
function setPersistedCompactionMarkerState(db, sessionId, state) {
|
|
6326
|
-
db.transaction(() => {
|
|
6327
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6328
|
-
const previous = state === null ? getPersistedCompactionMarkerState(db, sessionId) ?? getDeferredClearedCompactionMarkerState(db, sessionId) : null;
|
|
6329
|
-
const json = state ? JSON.stringify(state) : previous ? JSON.stringify({ deferredClear: previous }) : "";
|
|
6330
|
-
db.prepare("UPDATE session_meta SET compaction_marker_state = ?, compaction_marker_target_end_message_id = ? WHERE session_id = ?").run(json, state?.targetEndMessageId ?? null, sessionId);
|
|
6331
|
-
}).immediate();
|
|
6332
|
-
}
|
|
6333
|
-
function getDeferredClearedCompactionMarkerState(db, sessionId) {
|
|
6334
|
-
const row = db.prepare("SELECT compaction_marker_state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6335
|
-
try {
|
|
6336
|
-
const parsed = JSON.parse(row?.compaction_marker_state || "null");
|
|
6337
|
-
return parsePersistedCompactionMarkerState(JSON.stringify(parsed?.deferredClear));
|
|
6338
|
-
} catch {
|
|
6339
|
-
return null;
|
|
6340
|
-
}
|
|
6341
|
-
}
|
|
6342
|
-
var MAX_STRIPPED_PLACEHOLDER_IDS = 4096;
|
|
6343
|
-
function parseStrippedPlaceholderState(raw) {
|
|
6344
|
-
if (!raw || raw.length === 0)
|
|
6345
|
-
return { ids: [], hiddenSeamIds: [] };
|
|
6346
|
-
try {
|
|
6347
|
-
const parsed = JSON.parse(raw);
|
|
6348
|
-
if (Array.isArray(parsed)) {
|
|
6349
|
-
return {
|
|
6350
|
-
ids: parsed.filter((value) => typeof value === "string"),
|
|
6351
|
-
hiddenSeamIds: []
|
|
6352
|
-
};
|
|
6353
|
-
}
|
|
6354
|
-
if (parsed && typeof parsed === "object") {
|
|
6355
|
-
const state = parsed;
|
|
6356
|
-
return {
|
|
6357
|
-
ids: Array.isArray(state.ids) ? state.ids.filter((value) => typeof value === "string") : [],
|
|
6358
|
-
hiddenSeamIds: Array.isArray(state.hiddenSeamIds) ? state.hiddenSeamIds.filter((value) => typeof value === "string") : []
|
|
6359
|
-
};
|
|
6360
|
-
}
|
|
6361
|
-
} catch {}
|
|
6362
|
-
return { ids: [], hiddenSeamIds: [] };
|
|
6363
|
-
}
|
|
6364
|
-
function parseStrippedBlob(raw) {
|
|
6365
|
-
if (!raw || raw.length === 0)
|
|
6366
|
-
return [];
|
|
6367
|
-
try {
|
|
6368
|
-
const parsed = JSON.parse(raw);
|
|
6369
|
-
return Array.isArray(parsed) ? parsed.filter((value) => typeof value === "string") : [];
|
|
6370
|
-
} catch {
|
|
6371
|
-
return [];
|
|
6372
|
-
}
|
|
6373
|
-
}
|
|
6374
|
-
function serializeStrippedPlaceholderState(state) {
|
|
6375
|
-
if (state.ids.length === 0)
|
|
6376
|
-
return "";
|
|
6377
|
-
if (state.hiddenSeamIds.length === 0)
|
|
6378
|
-
return JSON.stringify(state.ids);
|
|
6379
|
-
return JSON.stringify(state);
|
|
6380
|
-
}
|
|
6381
|
-
function getStrippedPlaceholderIds(db, sessionId) {
|
|
6382
|
-
const row = db.prepare("SELECT stripped_placeholder_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6383
|
-
return new Set(parseStrippedPlaceholderState(row?.stripped_placeholder_ids).ids);
|
|
6384
|
-
}
|
|
6385
|
-
function applyStrippedPlaceholderDelta(db, sessionId, delta) {
|
|
6386
|
-
const add = delta.add ? [...delta.add] : [];
|
|
6387
|
-
const remove = delta.remove ? [...delta.remove] : [];
|
|
6388
|
-
const hiddenSeamAdd = delta.hiddenSeamAdd ? [...delta.hiddenSeamAdd] : [];
|
|
6389
|
-
if (add.length === 0 && remove.length === 0 && hiddenSeamAdd.length === 0)
|
|
6390
|
-
return true;
|
|
6391
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6392
|
-
for (let attempt = 0;attempt < CAS_RETRY_LIMIT2; attempt += 1) {
|
|
6393
|
-
const row = db.prepare("SELECT stripped_placeholder_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6394
|
-
const rawStored = row ? row.stripped_placeholder_ids ?? null : null;
|
|
6395
|
-
const parsed = parseStrippedPlaceholderState(rawStored);
|
|
6396
|
-
const current = new Set(parsed.ids);
|
|
6397
|
-
const hiddenSeamIds = new Set(parsed.hiddenSeamIds);
|
|
6398
|
-
for (const id of add)
|
|
6399
|
-
current.add(id);
|
|
6400
|
-
for (const id of hiddenSeamAdd) {
|
|
6401
|
-
current.add(id);
|
|
6402
|
-
hiddenSeamIds.add(id);
|
|
6403
|
-
}
|
|
6404
|
-
for (const id of remove) {
|
|
6405
|
-
current.delete(id);
|
|
6406
|
-
hiddenSeamIds.delete(id);
|
|
6407
|
-
}
|
|
6408
|
-
const boundedIds = [...current].slice(-MAX_STRIPPED_PLACEHOLDER_IDS);
|
|
6409
|
-
const boundedSet = new Set(boundedIds);
|
|
6410
|
-
const nextBlob = serializeStrippedPlaceholderState({
|
|
6411
|
-
ids: boundedIds,
|
|
6412
|
-
hiddenSeamIds: [...hiddenSeamIds].filter((id) => boundedSet.has(id))
|
|
6413
|
-
});
|
|
6414
|
-
if (nextBlob === (rawStored ?? ""))
|
|
6415
|
-
return true;
|
|
6416
|
-
const result = db.prepare("UPDATE session_meta SET stripped_placeholder_ids = ? WHERE session_id = ? AND stripped_placeholder_ids IS ?").run(nextBlob, sessionId, rawStored);
|
|
6417
|
-
if (result.changes > 0)
|
|
6418
|
-
return true;
|
|
6419
|
-
}
|
|
6420
|
-
sessionLog2(sessionId, `stripped_placeholder_ids CAS: ${CAS_RETRY_LIMIT2} retries exhausted`);
|
|
6421
|
-
return false;
|
|
6422
|
-
}
|
|
6423
|
-
var THINKING_BINDING_RECOVERY_ALL_ASSISTANTS = "all_reasoning_bearing_assistants";
|
|
6424
|
-
var THINKING_BINDING_RECOVERY_FROZEN_PREFIX = "binding_mismatch:";
|
|
6425
|
-
var THINKING_BINDING_STRIP_ORDER_END_MARKER = "binding_mismatch_order:end";
|
|
6426
|
-
function thinkingBindingRecoveryFrozenId(messageId) {
|
|
6427
|
-
return `${THINKING_BINDING_RECOVERY_FROZEN_PREFIX}${messageId}`;
|
|
6428
|
-
}
|
|
6429
|
-
function getThinkingBindingRecoveryTarget(db, sessionId) {
|
|
6430
|
-
const row = db.prepare("SELECT thinking_binding_recovery_target FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6431
|
-
const target = row?.thinking_binding_recovery_target;
|
|
6432
|
-
return typeof target === "string" && target.length > 0 ? target : null;
|
|
6433
|
-
}
|
|
6434
|
-
function armThinkingBindingRecovery(db, sessionId) {
|
|
6435
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6436
|
-
db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = ? WHERE session_id = ?").run(THINKING_BINDING_RECOVERY_ALL_ASSISTANTS, sessionId);
|
|
6437
|
-
}
|
|
6438
|
-
function clearThinkingBindingRecoveryIf(db, sessionId, expectedTarget) {
|
|
6439
|
-
const result = db.prepare("UPDATE session_meta SET thinking_binding_recovery_target = '' WHERE session_id = ? AND thinking_binding_recovery_target = ?").run(sessionId, expectedTarget);
|
|
6440
|
-
return result.changes > 0;
|
|
6441
|
-
}
|
|
6442
|
-
function getMergedReasoningStrippedIds(db, sessionId) {
|
|
6443
|
-
const row = db.prepare("SELECT merged_reasoning_stripped_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6444
|
-
return new Set(parseStrippedBlob(row?.merged_reasoning_stripped_ids));
|
|
6445
|
-
}
|
|
6446
|
-
function addMergedReasoningStrippedIds(db, sessionId, ids) {
|
|
6447
|
-
const add = [...ids];
|
|
6448
|
-
if (add.length === 0)
|
|
6449
|
-
return true;
|
|
6450
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6451
|
-
for (let attempt = 0;attempt < CAS_RETRY_LIMIT2; attempt += 1) {
|
|
6452
|
-
const row = db.prepare("SELECT merged_reasoning_stripped_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6453
|
-
const rawStored = row ? row.merged_reasoning_stripped_ids ?? null : null;
|
|
6454
|
-
const current = new Set(parseStrippedBlob(rawStored));
|
|
6455
|
-
const frozenParts = readFrozenMergedReasoningParts(current);
|
|
6456
|
-
let changed = false;
|
|
6457
|
-
for (const id of add) {
|
|
6458
|
-
const decision = decodeMergedReasoningParts(id);
|
|
6459
|
-
if (decision && frozenParts.has(decision[0]))
|
|
6460
|
-
continue;
|
|
6461
|
-
if (!current.has(id)) {
|
|
6462
|
-
current.add(id);
|
|
6463
|
-
if (decision)
|
|
6464
|
-
frozenParts.set(...decision);
|
|
6465
|
-
changed = true;
|
|
6466
|
-
}
|
|
6467
|
-
}
|
|
6468
|
-
if (!changed)
|
|
6469
|
-
return true;
|
|
6470
|
-
const nextBlob = JSON.stringify([...current]);
|
|
6471
|
-
const result = db.prepare("UPDATE session_meta SET merged_reasoning_stripped_ids = ? WHERE session_id = ? AND merged_reasoning_stripped_ids IS ?").run(nextBlob, sessionId, rawStored);
|
|
6472
|
-
if (result.changes > 0)
|
|
6473
|
-
return true;
|
|
6474
|
-
}
|
|
6475
|
-
sessionLog2(sessionId, `merged_reasoning_stripped_ids CAS: ${CAS_RETRY_LIMIT2} retries exhausted`);
|
|
6476
|
-
return false;
|
|
6477
|
-
}
|
|
6478
|
-
function getProcessedImageStrippedIds(db, sessionId) {
|
|
6479
|
-
const row = db.prepare("SELECT processed_image_stripped_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6480
|
-
return new Set(parseStrippedBlob(row?.processed_image_stripped_ids));
|
|
6481
|
-
}
|
|
6482
|
-
function addProcessedImageStrippedIds(db, sessionId, ids) {
|
|
6483
|
-
const add = [...ids];
|
|
6484
|
-
if (add.length === 0)
|
|
6485
|
-
return true;
|
|
6486
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6487
|
-
for (let attempt = 0;attempt < CAS_RETRY_LIMIT2; attempt += 1) {
|
|
6488
|
-
const row = db.prepare("SELECT processed_image_stripped_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6489
|
-
const rawStored = row ? row.processed_image_stripped_ids ?? null : null;
|
|
6490
|
-
const current = new Set(parseStrippedBlob(rawStored));
|
|
6491
|
-
let changed = false;
|
|
6492
|
-
for (const id of add) {
|
|
6493
|
-
if (!current.has(id)) {
|
|
6494
|
-
current.add(id);
|
|
6495
|
-
changed = true;
|
|
6496
|
-
}
|
|
6497
|
-
}
|
|
6498
|
-
if (!changed)
|
|
6499
|
-
return true;
|
|
6500
|
-
const nextBlob = JSON.stringify([...current]);
|
|
6501
|
-
const result = db.prepare("UPDATE session_meta SET processed_image_stripped_ids = ? WHERE session_id = ? AND processed_image_stripped_ids IS ?").run(nextBlob, sessionId, rawStored);
|
|
6502
|
-
if (result.changes > 0)
|
|
6503
|
-
return true;
|
|
6504
|
-
}
|
|
6505
|
-
sessionLog2(sessionId, `processed_image_stripped_ids CAS: ${CAS_RETRY_LIMIT2} retries exhausted`);
|
|
6506
|
-
return false;
|
|
6507
|
-
}
|
|
6508
|
-
function isPendingCompactionMarker(value) {
|
|
6509
|
-
return typeof value === "object" && value !== null && typeof value.ordinal === "number" && typeof value.endMessageId === "string" && typeof value.publishedAt === "number" && (value.injectAttempts === undefined || typeof value.injectAttempts === "number" && Number.isSafeInteger(value.injectAttempts) && value.injectAttempts >= 0) && (value.lastInjectError === undefined || value.lastInjectError === null || typeof value.lastInjectError === "string") && (value.firstInjectFailedAt === undefined || value.firstInjectFailedAt === null || typeof value.firstInjectFailedAt === "number");
|
|
6510
|
-
}
|
|
6511
|
-
function parsePendingCompactionMarkerState(raw) {
|
|
6512
|
-
if (raw === null || raw === undefined || raw === "")
|
|
6513
|
-
return null;
|
|
6514
|
-
try {
|
|
6515
|
-
const parsed = JSON.parse(raw);
|
|
6516
|
-
if (isPendingCompactionMarker(parsed))
|
|
6517
|
-
return parsed;
|
|
6518
|
-
} catch {}
|
|
6519
|
-
return null;
|
|
6520
|
-
}
|
|
6521
|
-
function getPendingCompactionMarkerState(db, sessionId) {
|
|
6522
|
-
const row = db.prepare("SELECT pending_compaction_marker_state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6523
|
-
return parsePendingCompactionMarkerState(row?.pending_compaction_marker_state);
|
|
6524
|
-
}
|
|
6525
|
-
var COMPACTION_MARKER_ATTEMPT_BUDGET = 3;
|
|
6526
|
-
var COMPACTION_MARKER_PENDING_BUDGET_MS = 5 * 60000;
|
|
6527
|
-
function getCompactionMarkerHealth(db, sessionId, now = Date.now()) {
|
|
6528
|
-
const pending = getPendingCompactionMarkerState(db, sessionId);
|
|
6529
|
-
const attempts = pending?.injectAttempts ?? 0;
|
|
6530
|
-
const firstFailedAt = pending?.firstInjectFailedAt ?? null;
|
|
6531
|
-
const exhausted = attempts >= COMPACTION_MARKER_ATTEMPT_BUDGET || firstFailedAt !== null && now - firstFailedAt >= COMPACTION_MARKER_PENDING_BUDGET_MS;
|
|
6532
|
-
return {
|
|
6533
|
-
code: exhausted ? "MC-C11" : null,
|
|
6534
|
-
attempts,
|
|
6535
|
-
lastError: pending?.lastInjectError ?? null,
|
|
6536
|
-
pendingSinceMs: firstFailedAt
|
|
6537
|
-
};
|
|
6538
|
-
}
|
|
6539
|
-
function clearPendingCompactionMarkerStateIf(db, sessionId, expected) {
|
|
6540
|
-
const expectedBlob = stableStringify(expected);
|
|
6541
|
-
const result = db.prepare(`UPDATE session_meta SET pending_compaction_marker_state = NULL
|
|
6542
|
-
WHERE session_id = ? AND pending_compaction_marker_state = ?`).run(sessionId, expectedBlob);
|
|
6543
|
-
return result.changes > 0;
|
|
6544
|
-
}
|
|
6545
|
-
function isPendingPiCompactionMarker(value) {
|
|
6546
|
-
return typeof value === "object" && value !== null && (value.firstKeptEntryId === null || typeof value.firstKeptEntryId === "string") && typeof value.endMessageId === "string" && typeof value.ordinal === "number" && typeof value.tokensBefore === "number" && typeof value.summary === "string" && typeof value.publishedAt === "number";
|
|
6547
|
-
}
|
|
6548
|
-
function getPendingPiCompactionMarkerState(db, sessionId) {
|
|
6549
|
-
const row = db.prepare("SELECT pending_pi_compaction_marker_state FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6550
|
-
const raw = row?.pending_pi_compaction_marker_state;
|
|
6551
|
-
if (raw === null || raw === undefined || raw === "")
|
|
6552
|
-
return null;
|
|
6553
|
-
try {
|
|
6554
|
-
const parsed = JSON.parse(raw);
|
|
6555
|
-
if (isPendingPiCompactionMarker(parsed)) {
|
|
6556
|
-
return parsed;
|
|
6557
|
-
}
|
|
6558
|
-
} catch {}
|
|
6559
|
-
db.prepare("UPDATE session_meta SET pending_pi_compaction_marker_state = NULL WHERE session_id = ? AND pending_pi_compaction_marker_state = ?").run(sessionId, raw);
|
|
6560
|
-
return null;
|
|
6561
|
-
}
|
|
6562
|
-
function setPendingPiCompactionMarkerState(db, sessionId, state) {
|
|
6563
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6564
|
-
const blob = state ? stableStringify(state) : null;
|
|
6565
|
-
db.prepare("UPDATE session_meta SET pending_pi_compaction_marker_state = ? WHERE session_id = ?").run(blob, sessionId);
|
|
6566
|
-
}
|
|
6567
|
-
function clearPendingPiCompactionMarkerStateIf(db, sessionId, expected) {
|
|
6568
|
-
const expectedBlob = stableStringify(expected);
|
|
6569
|
-
const result = db.prepare(`UPDATE session_meta SET pending_pi_compaction_marker_state = NULL
|
|
6570
|
-
WHERE session_id = ? AND pending_pi_compaction_marker_state = ?`).run(sessionId, expectedBlob);
|
|
6571
|
-
return result.changes > 0;
|
|
6572
|
-
}
|
|
6573
|
-
function getSessionsWithPendingPiMarker(db) {
|
|
6574
|
-
const rows = db.prepare(`SELECT session_id FROM session_meta
|
|
6575
|
-
WHERE pending_pi_compaction_marker_state IS NOT NULL
|
|
6576
|
-
AND pending_pi_compaction_marker_state != ''`).all();
|
|
6577
|
-
return rows.map((r) => r.session_id);
|
|
6578
|
-
}
|
|
6579
|
-
function setSessionWorkMetrics(db, sessionId, newWorkTokens, totalInputTokens) {
|
|
6580
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6581
|
-
db.prepare(`UPDATE session_meta
|
|
6582
|
-
SET new_work_tokens = ?, total_input_tokens = ?
|
|
6583
|
-
WHERE session_id = ?`).run(Math.max(0, Math.floor(newWorkTokens)), Math.max(0, Math.floor(totalInputTokens)), sessionId);
|
|
6584
|
-
}
|
|
6585
|
-
function getSessionWorkMetrics(db, sessionId) {
|
|
6586
|
-
const row = db.prepare("SELECT new_work_tokens, total_input_tokens FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6587
|
-
return {
|
|
6588
|
-
newWorkTokens: typeof row?.new_work_tokens === "number" ? row.new_work_tokens : 0,
|
|
6589
|
-
totalInputTokens: typeof row?.total_input_tokens === "number" ? row.total_input_tokens : 0
|
|
6590
|
-
};
|
|
6591
|
-
}
|
|
6592
|
-
var preSnapshotSessions = new Map;
|
|
6593
|
-
var warnedProtectedTokenTierOverrides = new WeakSet;
|
|
6594
|
-
function isPreSnapshotMemo(value) {
|
|
6595
|
-
if (typeof value !== "object" || value === null)
|
|
6596
|
-
return false;
|
|
6597
|
-
const memo = value;
|
|
6598
|
-
return (memo.configuredOverride === undefined || typeof memo.configuredOverride === "number" && Number.isFinite(memo.configuredOverride)) && typeof memo.usableSoft === "number" && Number.isFinite(memo.usableSoft) && typeof memo.floor === "number" && Number.isFinite(memo.floor) && memo.floor >= 0 && (memo.provenance === "override" || memo.provenance === "derived");
|
|
6599
|
-
}
|
|
6600
|
-
function readPreSnapshotMemo(db, sessionId) {
|
|
6601
|
-
const row = db.prepare("SELECT protected_tokens_pre_snapshot FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
6602
|
-
const raw = row?.protected_tokens_pre_snapshot;
|
|
6603
|
-
if (!raw)
|
|
6604
|
-
return null;
|
|
6605
|
-
try {
|
|
6606
|
-
const parsed = JSON.parse(raw);
|
|
6607
|
-
if (isPreSnapshotMemo(parsed))
|
|
6608
|
-
return parsed;
|
|
6609
|
-
} catch {}
|
|
6610
|
-
db.prepare(`UPDATE session_meta SET protected_tokens_pre_snapshot = NULL
|
|
6611
|
-
WHERE session_id = ? AND protected_tokens_pre_snapshot = ?`).run(sessionId, raw);
|
|
6612
|
-
return null;
|
|
6613
|
-
}
|
|
6614
|
-
function writePreSnapshotMemo(db, sessionId, memo) {
|
|
6615
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6616
|
-
db.prepare(`UPDATE session_meta SET protected_tokens_pre_snapshot = ?
|
|
6617
|
-
WHERE session_id = ? AND protected_tokens_pre_snapshot IS NULL`).run(JSON.stringify(memo), sessionId);
|
|
6618
|
-
return readPreSnapshotMemo(db, sessionId) ?? memo;
|
|
6619
|
-
}
|
|
6620
|
-
function clearPreSnapshotMemo(db, sessionId) {
|
|
6621
|
-
db.prepare("UPDATE session_meta SET protected_tokens_pre_snapshot = NULL WHERE session_id = ?").run(sessionId);
|
|
6622
|
-
preSnapshotSessions.delete(sessionId);
|
|
6623
|
-
}
|
|
6624
|
-
function preSnapshotResult(memo, inputs) {
|
|
6625
|
-
const overrideMoved = memo.configuredOverride !== inputs.configuredOverride;
|
|
6626
|
-
const geometryMoved = memo.usableSoft !== inputs.usableSoft;
|
|
6627
|
-
return {
|
|
6628
|
-
floor: memo.floor,
|
|
6629
|
-
isSnapshotPersisted: false,
|
|
6630
|
-
provenance: memo.provenance,
|
|
6631
|
-
snapshotChanged: false,
|
|
6632
|
-
preSnapshotInputChanged: overrideMoved || geometryMoved,
|
|
6633
|
-
preSnapshotBustReason: overrideMoved ? "config-re-read" : geometryMoved ? "live-geometry" : undefined
|
|
6634
|
-
};
|
|
6635
|
-
}
|
|
6636
|
-
function persistEpochFloorSnapshot(db, sessionId, floor) {
|
|
6637
|
-
ensureSessionMetaRow(db, sessionId);
|
|
6638
|
-
const rounded = Math.max(0, Math.round(floor));
|
|
6639
|
-
db.prepare(`UPDATE session_meta
|
|
6640
|
-
SET protected_tokens_effective = ?, protected_tokens_pre_snapshot = NULL
|
|
6641
|
-
WHERE session_id = ?`).run(rounded, sessionId);
|
|
6642
|
-
preSnapshotSessions.delete(sessionId);
|
|
6643
|
-
}
|
|
6644
|
-
function getPersistedEpochFloor(db, sessionId) {
|
|
6645
|
-
return readEpochFloorSnapshot(db, sessionId);
|
|
6646
|
-
}
|
|
6647
|
-
function resolveEpochFloorForPass(db, sessionId, inputs) {
|
|
6648
|
-
const derived = deriveDefaultProtectedTokens(inputs.usableSoft);
|
|
6649
|
-
let configuredOverride = inputs.configuredOverride;
|
|
6650
|
-
const tierOverrides = inputs.tierOverrides;
|
|
6651
|
-
if (tierOverrides) {
|
|
6652
|
-
const userOrDerived = tierOverrides.user ?? derived;
|
|
6653
|
-
configuredOverride = tierOverrides.user;
|
|
6654
|
-
if (tierOverrides.project !== undefined) {
|
|
6655
|
-
if (tierOverrides.project >= userOrDerived) {
|
|
6656
|
-
configuredOverride = tierOverrides.project;
|
|
6657
|
-
} else if (inputs.onRejectedProjectOverride && !warnedProtectedTokenTierOverrides.has(tierOverrides)) {
|
|
6658
|
-
warnedProtectedTokenTierOverrides.add(tierOverrides);
|
|
6659
|
-
inputs.onRejectedProjectOverride(`Ignoring project protected_tokens=${tierOverrides.project}; it cannot lower resolved user/default floor ${userOrDerived}.`);
|
|
6660
|
-
}
|
|
6661
|
-
}
|
|
6662
|
-
}
|
|
6663
|
-
const resolvedInputs = { ...inputs, configuredOverride };
|
|
6664
|
-
const persisted = getPersistedEpochFloor(db, sessionId);
|
|
6665
|
-
if (!inputs.isCacheBustingPass && persisted !== null) {
|
|
6666
|
-
return {
|
|
6667
|
-
floor: persisted,
|
|
6668
|
-
isSnapshotPersisted: true,
|
|
6669
|
-
provenance: "persisted",
|
|
6670
|
-
snapshotChanged: false
|
|
6671
|
-
};
|
|
6672
|
-
}
|
|
6673
|
-
const hasValidOverride = typeof configuredOverride === "number" && Number.isInteger(configuredOverride) && configuredOverride >= 4000 && configuredOverride <= 1e6;
|
|
6674
|
-
const floor = hasValidOverride && typeof configuredOverride === "number" ? configuredOverride : derived;
|
|
6675
|
-
const provenance = hasValidOverride ? "override" : "derived";
|
|
6676
|
-
if (inputs.isCacheBustingPass) {
|
|
6677
|
-
const snapshotChanged = persisted !== floor;
|
|
6678
|
-
if (snapshotChanged)
|
|
6679
|
-
persistEpochFloorSnapshot(db, sessionId, floor);
|
|
6680
|
-
else
|
|
6681
|
-
clearPreSnapshotMemo(db, sessionId);
|
|
6682
|
-
return {
|
|
6683
|
-
floor,
|
|
6684
|
-
isSnapshotPersisted: true,
|
|
6685
|
-
provenance,
|
|
6686
|
-
snapshotChanged
|
|
6687
|
-
};
|
|
6688
|
-
}
|
|
6689
|
-
const existing = preSnapshotSessions.get(sessionId) ?? readPreSnapshotMemo(db, sessionId);
|
|
6690
|
-
if (existing !== null && existing !== undefined) {
|
|
6691
|
-
preSnapshotSessions.set(sessionId, existing);
|
|
6692
|
-
return preSnapshotResult(existing, resolvedInputs);
|
|
6693
|
-
}
|
|
6694
|
-
const memo = {
|
|
6695
|
-
configuredOverride,
|
|
6696
|
-
usableSoft: inputs.usableSoft,
|
|
6697
|
-
floor,
|
|
6698
|
-
provenance
|
|
6699
|
-
};
|
|
6700
|
-
const firstObservedMemo = writePreSnapshotMemo(db, sessionId, memo);
|
|
6701
|
-
preSnapshotSessions.set(sessionId, firstObservedMemo);
|
|
6702
|
-
return preSnapshotResult(firstObservedMemo, resolvedInputs);
|
|
6703
|
-
}
|
|
6704
|
-
// ../plugin/src/features/magic-context/storage-meta-session.ts
|
|
6705
|
-
import { Buffer as Buffer3 } from "node:buffer";
|
|
6706
|
-
|
|
6707
|
-
// ../plugin/src/shared/auto-search-lifecycle.ts
|
|
6708
|
-
var pending = new Map;
|
|
6709
|
-
var unpublishedNoHints = new Map;
|
|
6710
|
-
function rememberUnpublishedAutoSearchNoHint(sessionId, messageId, reason) {
|
|
6711
|
-
let messages = unpublishedNoHints.get(sessionId);
|
|
6712
|
-
if (!messages) {
|
|
6713
|
-
messages = new Map;
|
|
6714
|
-
unpublishedNoHints.set(sessionId, messages);
|
|
6715
|
-
}
|
|
6716
|
-
if (!messages.has(messageId))
|
|
6717
|
-
messages.set(messageId, reason);
|
|
6718
|
-
}
|
|
6719
|
-
function getUnpublishedAutoSearchNoHint(sessionId, messageId) {
|
|
6720
|
-
return unpublishedNoHints.get(sessionId)?.get(messageId);
|
|
6721
|
-
}
|
|
6722
|
-
function forgetUnpublishedAutoSearchNoHint(sessionId, messageId) {
|
|
6723
|
-
const messages = unpublishedNoHints.get(sessionId);
|
|
6724
|
-
messages?.delete(messageId);
|
|
6725
|
-
if (messages?.size === 0)
|
|
6726
|
-
unpublishedNoHints.delete(sessionId);
|
|
6727
|
-
}
|
|
6728
|
-
function clearUnpublishedAutoSearchNoHints(sessionId) {
|
|
6729
|
-
if (sessionId === undefined)
|
|
6730
|
-
unpublishedNoHints.clear();
|
|
6731
|
-
else
|
|
6732
|
-
unpublishedNoHints.delete(sessionId);
|
|
6733
|
-
}
|
|
6734
|
-
function registerAutoSearchWork(sessionId) {
|
|
6735
|
-
const controller = new AbortController;
|
|
6736
|
-
const work = pending.get(sessionId) ?? new Set;
|
|
6737
|
-
pending.set(sessionId, work);
|
|
6738
|
-
work.add(controller);
|
|
6739
|
-
return {
|
|
6740
|
-
signal: controller.signal,
|
|
6741
|
-
done: () => {
|
|
6742
|
-
work.delete(controller);
|
|
6743
|
-
if (pending.get(sessionId) === work && work.size === 0)
|
|
6744
|
-
pending.delete(sessionId);
|
|
6745
|
-
}
|
|
6746
|
-
};
|
|
6747
|
-
}
|
|
6748
|
-
function cancelAutoSearchWork(sessionId) {
|
|
6749
|
-
for (const [id, work] of pending) {
|
|
6750
|
-
if (sessionId !== undefined && id !== sessionId)
|
|
6751
|
-
continue;
|
|
6752
|
-
pending.delete(id);
|
|
6753
|
-
for (const controller of work)
|
|
6754
|
-
controller.abort();
|
|
6755
|
-
}
|
|
6756
|
-
}
|
|
6757
|
-
|
|
6758
|
-
// ../plugin/src/v2/store-reader.ts
|
|
6759
|
-
import { createHash } from "node:crypto";
|
|
6760
|
-
import { statSync as statSync3 } from "node:fs";
|
|
6761
|
-
import { hostname } from "node:os";
|
|
6762
|
-
import { resolve as resolve2 } from "node:path";
|
|
6763
|
-
function gaDatabasePath(dataHome, channel = "latest", env = process.env) {
|
|
6764
|
-
return resolveOpenCodeDbPath("v2", { dataHome, channel, env }).path;
|
|
4181
|
+
// ../plugin/src/v2/store-reader.ts
|
|
4182
|
+
import { createHash } from "node:crypto";
|
|
4183
|
+
import { statSync as statSync3 } from "node:fs";
|
|
4184
|
+
import { hostname } from "node:os";
|
|
4185
|
+
import { resolve as resolve2 } from "node:path";
|
|
4186
|
+
function gaDatabasePath(dataHome, channel = "latest", env = process.env) {
|
|
4187
|
+
return resolveOpenCodeDbPath("v2", { dataHome, channel, env }).path;
|
|
6765
4188
|
}
|
|
6766
4189
|
var RAW_MESSAGE_TYPES = [
|
|
6767
4190
|
"user",
|
|
@@ -7407,7 +4830,7 @@ function updateSessionMeta(db, sessionId, updates) {
|
|
|
7407
4830
|
values.push(NULL_BIND_META_KEYS.has(key) ? null : "");
|
|
7408
4831
|
} else if ((key === "cachedM0Bytes" || key === "cachedM1Bytes") && value instanceof Uint8Array) {
|
|
7409
4832
|
setClauses.push(`${column} = ?`);
|
|
7410
|
-
values.push(
|
|
4833
|
+
values.push(Buffer2.from(value.buffer, value.byteOffset, value.byteLength));
|
|
7411
4834
|
} else if (BOOLEAN_META_KEYS.has(key)) {
|
|
7412
4835
|
setClauses.push(`${column} = ?`);
|
|
7413
4836
|
values.push(value ? 1 : 0);
|
|
@@ -7848,7 +5271,7 @@ function isPartialCompartmentEnd(db, sessionId, messageId) {
|
|
|
7848
5271
|
}
|
|
7849
5272
|
// ../plugin/src/features/magic-context/project-docs-hash.ts
|
|
7850
5273
|
import { createHash as createHash2 } from "node:crypto";
|
|
7851
|
-
import { lstatSync, readFileSync as
|
|
5274
|
+
import { lstatSync, readFileSync as readFileSync6, statSync as statSync4 } from "node:fs";
|
|
7852
5275
|
import path from "node:path";
|
|
7853
5276
|
var PROJECT_DOC_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
7854
5277
|
var PROJECT_DOCS_DELIMITER = `
|
|
@@ -7865,179 +5288,918 @@ function canonicalizeDocContent(raw) {
|
|
|
7865
5288
|
`).map((line) => line.replace(/[ \t]+$/, "")).join(`
|
|
7866
5289
|
`).replace(/\n+$/, "");
|
|
7867
5290
|
}
|
|
7868
|
-
function fingerprintFile(filePath) {
|
|
5291
|
+
function fingerprintFile(filePath) {
|
|
5292
|
+
try {
|
|
5293
|
+
const stat = lstatSync(filePath);
|
|
5294
|
+
const isReadableDoc = stat.isFile() && stat.size <= MAX_PROJECT_DOC_BYTES;
|
|
5295
|
+
return {
|
|
5296
|
+
exists: isReadableDoc,
|
|
5297
|
+
mtimeMs: stat.mtimeMs,
|
|
5298
|
+
size: stat.size
|
|
5299
|
+
};
|
|
5300
|
+
} catch {
|
|
5301
|
+
return { exists: false, mtimeMs: 0, size: 0 };
|
|
5302
|
+
}
|
|
5303
|
+
}
|
|
5304
|
+
function readDirectoryMtimeMs(projectDirectory) {
|
|
5305
|
+
try {
|
|
5306
|
+
return statSync4(projectDirectory).mtimeMs;
|
|
5307
|
+
} catch {
|
|
5308
|
+
return 0;
|
|
5309
|
+
}
|
|
5310
|
+
}
|
|
5311
|
+
function fingerprintsEqual(a, b) {
|
|
5312
|
+
return a?.exists === b.exists && a.mtimeMs === b.mtimeMs && a.size === b.size;
|
|
5313
|
+
}
|
|
5314
|
+
function cacheFilesEqual(cachedFiles, currentFiles) {
|
|
5315
|
+
for (const [filePath, current] of currentFiles) {
|
|
5316
|
+
if (!fingerprintsEqual(cachedFiles.get(filePath), current)) {
|
|
5317
|
+
return false;
|
|
5318
|
+
}
|
|
5319
|
+
}
|
|
5320
|
+
return true;
|
|
5321
|
+
}
|
|
5322
|
+
function readCurrentFingerprints(projectDirectory) {
|
|
5323
|
+
const files = new Map;
|
|
5324
|
+
for (const filename of PROJECT_DOC_FILES) {
|
|
5325
|
+
const filePath = path.join(projectDirectory, filename);
|
|
5326
|
+
files.set(filePath, fingerprintFile(filePath));
|
|
5327
|
+
}
|
|
5328
|
+
return { directoryMtimeMs: readDirectoryMtimeMs(projectDirectory), files };
|
|
5329
|
+
}
|
|
5330
|
+
function readCanonicalPieces(projectDirectory, files) {
|
|
5331
|
+
const hashPieces = [];
|
|
5332
|
+
const renderedSections = [];
|
|
5333
|
+
for (const filename of PROJECT_DOC_FILES) {
|
|
5334
|
+
const filePath = path.join(projectDirectory, filename);
|
|
5335
|
+
const fingerprint = files.get(filePath);
|
|
5336
|
+
if (!fingerprint?.exists) {
|
|
5337
|
+
continue;
|
|
5338
|
+
}
|
|
5339
|
+
let safeToRead = false;
|
|
5340
|
+
try {
|
|
5341
|
+
const st = lstatSync(filePath);
|
|
5342
|
+
safeToRead = st.isFile() && st.size <= MAX_PROJECT_DOC_BYTES;
|
|
5343
|
+
} catch {
|
|
5344
|
+
safeToRead = false;
|
|
5345
|
+
}
|
|
5346
|
+
if (!safeToRead) {
|
|
5347
|
+
continue;
|
|
5348
|
+
}
|
|
5349
|
+
const canonicalContent = canonicalizeDocContent(readFileSync6(filePath, "utf8"));
|
|
5350
|
+
hashPieces.push(`file:${filename}
|
|
5351
|
+
${canonicalContent}`);
|
|
5352
|
+
renderedSections.push(`<file name="${escapeXmlAttr(filename)}">
|
|
5353
|
+
${escapeXmlContent(canonicalContent)}
|
|
5354
|
+
</file>`);
|
|
5355
|
+
}
|
|
5356
|
+
return { hashPieces, renderedSections };
|
|
5357
|
+
}
|
|
5358
|
+
function buildRenderedBlock(renderedSections) {
|
|
5359
|
+
if (renderedSections.length === 0) {
|
|
5360
|
+
return "";
|
|
5361
|
+
}
|
|
5362
|
+
return `<project-docs>
|
|
5363
|
+
${renderedSections.join(`
|
|
5364
|
+
|
|
5365
|
+
`)}
|
|
5366
|
+
</project-docs>`;
|
|
5367
|
+
}
|
|
5368
|
+
function hashCanonicalPieces(hashPieces) {
|
|
5369
|
+
if (hashPieces.length === 0) {
|
|
5370
|
+
return "";
|
|
5371
|
+
}
|
|
5372
|
+
return createHash2("sha256").update(hashPieces.join(PROJECT_DOCS_DELIMITER), "utf8").digest("hex");
|
|
5373
|
+
}
|
|
5374
|
+
function readProjectDocsCanonical(projectDirectory) {
|
|
5375
|
+
canonicalReadCountForTests += 1;
|
|
5376
|
+
const canonicalDirectory = path.resolve(projectDirectory);
|
|
5377
|
+
const current = readCurrentFingerprints(canonicalDirectory);
|
|
5378
|
+
const cached = docsCache.get(canonicalDirectory);
|
|
5379
|
+
if (cached && cacheFilesEqual(cached.files, current.files)) {
|
|
5380
|
+
cached.directoryMtimeMs = current.directoryMtimeMs;
|
|
5381
|
+
return {
|
|
5382
|
+
renderedBlock: cached.cachedRendered,
|
|
5383
|
+
canonicalHash: cached.cachedHash
|
|
5384
|
+
};
|
|
5385
|
+
}
|
|
5386
|
+
const { hashPieces, renderedSections } = readCanonicalPieces(canonicalDirectory, current.files);
|
|
5387
|
+
const canonicalHash = hashCanonicalPieces(hashPieces);
|
|
5388
|
+
const renderedBlock = buildRenderedBlock(renderedSections);
|
|
5389
|
+
docsCache.set(canonicalDirectory, {
|
|
5390
|
+
directoryMtimeMs: current.directoryMtimeMs,
|
|
5391
|
+
files: current.files,
|
|
5392
|
+
cachedHash: canonicalHash,
|
|
5393
|
+
cachedRendered: renderedBlock
|
|
5394
|
+
});
|
|
5395
|
+
return { renderedBlock, canonicalHash };
|
|
5396
|
+
}
|
|
5397
|
+
// ../plugin/src/hooks/magic-context/lkg-slot.ts
|
|
5398
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
5399
|
+
|
|
5400
|
+
// ../plugin/src/shared/provider-response-completion.ts
|
|
5401
|
+
function providerResponseFailed(input) {
|
|
5402
|
+
if (input.error !== undefined && input.error !== null && input.error !== "")
|
|
5403
|
+
return true;
|
|
5404
|
+
const finish = typeof input.finish === "string" ? input.finish.trim().toLowerCase() : "";
|
|
5405
|
+
return ["error", "failed", "abort", "aborted", "interrupted", "cancelled", "canceled"].includes(finish);
|
|
5406
|
+
}
|
|
5407
|
+
function isSuccessfulProviderCompletion(input) {
|
|
5408
|
+
if (providerResponseFailed(input))
|
|
5409
|
+
return false;
|
|
5410
|
+
return typeof input.completedAt === "number" && Number.isFinite(input.completedAt) && input.completedAt > 0 || typeof input.finish === "string" && input.finish.trim().length > 0;
|
|
5411
|
+
}
|
|
5412
|
+
|
|
5413
|
+
// ../plugin/src/hooks/magic-context/pending-materialization.ts
|
|
5414
|
+
var origins = new WeakMap;
|
|
5415
|
+
var causes = new WeakMap;
|
|
5416
|
+
function requestPendingMaterialization(sessions, sessionId, origin) {
|
|
5417
|
+
let reasons = origins.get(sessions);
|
|
5418
|
+
if (!reasons)
|
|
5419
|
+
origins.set(sessions, reasons = new Map);
|
|
5420
|
+
let sessionCauses = causes.get(sessions);
|
|
5421
|
+
if (!sessionCauses)
|
|
5422
|
+
causes.set(sessions, sessionCauses = new Map);
|
|
5423
|
+
let pendingCauses = sessionCauses.get(sessionId);
|
|
5424
|
+
if (!sessions.has(sessionId) || !pendingCauses) {
|
|
5425
|
+
pendingCauses = new Set;
|
|
5426
|
+
sessionCauses.set(sessionId, pendingCauses);
|
|
5427
|
+
}
|
|
5428
|
+
pendingCauses.add(origin);
|
|
5429
|
+
if (!sessions.has(sessionId) || !reasons.has(sessionId) || origin === "fit_retry")
|
|
5430
|
+
reasons.set(sessionId, origin);
|
|
5431
|
+
sessions.add(sessionId);
|
|
5432
|
+
}
|
|
5433
|
+
function pendingMaterializationOrigin(sessions, sessionId) {
|
|
5434
|
+
return sessions.has(sessionId) ? origins.get(sessions)?.get(sessionId) ?? "pending_materialization" : "pending_materialization";
|
|
5435
|
+
}
|
|
5436
|
+
function clearPendingMaterialization(sessions, sessionId) {
|
|
5437
|
+
sessions.delete(sessionId);
|
|
5438
|
+
origins.get(sessions)?.delete(sessionId);
|
|
5439
|
+
causes.get(sessions)?.delete(sessionId);
|
|
5440
|
+
}
|
|
5441
|
+
function hasOnlySystemHashMaterialization(sessions, sessionId) {
|
|
5442
|
+
const pendingCauses = causes.get(sessions)?.get(sessionId);
|
|
5443
|
+
return sessions.has(sessionId) && pendingCauses?.size === 1 && pendingCauses.has("system_hash");
|
|
5444
|
+
}
|
|
5445
|
+
|
|
5446
|
+
// ../plugin/src/hooks/magic-context/system-prompt-delivery.ts
|
|
5447
|
+
var pending2 = new BoundedSessionMap(1000);
|
|
5448
|
+
var retiredRequests = new WeakSet;
|
|
5449
|
+
var heldRequests = new WeakSet;
|
|
5450
|
+
var refreshOwners = new BoundedSessionMap(1000);
|
|
5451
|
+
function recordSystemRefreshOwnership(sessionId, hash, ownsHistoryRefresh, history, materialization) {
|
|
5452
|
+
const previous = refreshOwners.get(sessionId);
|
|
5453
|
+
const inherited = previous?.ownsHistoryRefresh === true && previous.history === history && history?.has(sessionId) === true && materialization !== undefined && hasOnlySystemHashMaterialization(materialization, sessionId);
|
|
5454
|
+
refreshOwners.set(sessionId, {
|
|
5455
|
+
hash,
|
|
5456
|
+
ownsHistoryRefresh: ownsHistoryRefresh || inherited,
|
|
5457
|
+
history
|
|
5458
|
+
});
|
|
5459
|
+
}
|
|
5460
|
+
function preparation(sessionId, request) {
|
|
5461
|
+
if (retiredRequests.has(request))
|
|
5462
|
+
return;
|
|
5463
|
+
const previous = pending2.get(sessionId);
|
|
5464
|
+
if (previous?.request === request)
|
|
5465
|
+
return previous;
|
|
5466
|
+
const next = { request, held: false };
|
|
5467
|
+
pending2.set(sessionId, next);
|
|
5468
|
+
return next;
|
|
5469
|
+
}
|
|
5470
|
+
function recordSystemPromptForRequest(sessionId, request, hash, db, ownsHistoryRefresh, history, materialization) {
|
|
5471
|
+
if (!request || !hash)
|
|
5472
|
+
return;
|
|
5473
|
+
if (ownsHistoryRefresh !== undefined)
|
|
5474
|
+
recordSystemRefreshOwnership(sessionId, hash, ownsHistoryRefresh, history, materialization);
|
|
5475
|
+
const previous = pending2.get(sessionId);
|
|
5476
|
+
if (previous?.request === request && previous.held && previous.hash && previous.hash !== hash) {
|
|
5477
|
+
retirePendingSystemPromptDelivery(sessionId);
|
|
5478
|
+
return;
|
|
5479
|
+
}
|
|
5480
|
+
const saved = preparation(sessionId, request);
|
|
5481
|
+
if (!saved)
|
|
5482
|
+
return;
|
|
5483
|
+
const owner = refreshOwners.get(sessionId);
|
|
5484
|
+
Object.assign(saved, {
|
|
5485
|
+
hash,
|
|
5486
|
+
db,
|
|
5487
|
+
ownsHistoryRefresh: owner?.hash === hash && owner.ownsHistoryRefresh
|
|
5488
|
+
});
|
|
5489
|
+
}
|
|
5490
|
+
function recordHeldHeadForRequest(sessionId, request, deferRefresh) {
|
|
5491
|
+
const saved = request && preparation(sessionId, request);
|
|
5492
|
+
if (saved) {
|
|
5493
|
+
heldRequests.add(saved.request);
|
|
5494
|
+
Object.assign(saved, { held: true, deferRefresh });
|
|
5495
|
+
}
|
|
5496
|
+
}
|
|
5497
|
+
function bindSystemPromptResponse(sessionId, request, response) {
|
|
5498
|
+
const saved = pending2.get(sessionId);
|
|
5499
|
+
if (!saved || saved.request !== request || request?.kind !== "v2" || !response.responseId || response.responseId === request.previousResponseId || response.modelKey !== request.modelKey || !Number.isFinite(response.createdAt) || response.createdAt <= request.startedAt)
|
|
5500
|
+
return;
|
|
5501
|
+
if (saved.response && saved.response.id !== response.responseId)
|
|
5502
|
+
return;
|
|
5503
|
+
saved.response = { id: response.responseId, createdAt: response.createdAt };
|
|
5504
|
+
}
|
|
5505
|
+
function acknowledgeSystemPromptDelivery(args) {
|
|
5506
|
+
const saved = pending2.get(args.sessionId);
|
|
5507
|
+
if (!saved || saved.request !== args.request || !args.responseId)
|
|
5508
|
+
return;
|
|
5509
|
+
const request = saved.request;
|
|
5510
|
+
if (request.modelKey !== args.modelKey)
|
|
5511
|
+
return;
|
|
5512
|
+
if (request.kind === "v1") {
|
|
5513
|
+
if (args.v2 || request.responseId !== args.responseId)
|
|
5514
|
+
return;
|
|
5515
|
+
} else if (!args.v2 || request.previousResponseId === args.responseId || args.createdAt === undefined || !Number.isFinite(args.createdAt) || args.createdAt <= request.startedAt || saved.response?.id !== args.responseId || saved.response.createdAt !== args.createdAt)
|
|
5516
|
+
return;
|
|
5517
|
+
if (providerResponseFailed(args)) {
|
|
5518
|
+
retirePendingSystemPromptDelivery(args.sessionId);
|
|
5519
|
+
return;
|
|
5520
|
+
}
|
|
5521
|
+
if (!isSuccessfulProviderCompletion(args))
|
|
5522
|
+
return;
|
|
5523
|
+
retirePendingSystemPromptDelivery(args.sessionId);
|
|
5524
|
+
if (saved.held && saved.hash && saved.db) {
|
|
5525
|
+
try {
|
|
5526
|
+
updateSessionMeta(saved.db, args.sessionId, { cachedM0SystemHash: saved.hash });
|
|
5527
|
+
saved.deferRefresh?.(saved.ownsHistoryRefresh === true);
|
|
5528
|
+
refreshOwners.delete(args.sessionId);
|
|
5529
|
+
} catch (error) {
|
|
5530
|
+
sessionLog2(args.sessionId, "system delivery acknowledgement failed (keeping pending work):", error);
|
|
5531
|
+
}
|
|
5532
|
+
}
|
|
5533
|
+
}
|
|
5534
|
+
function deferDeliveredSystemRefresh(deps, sessionId, ownsHistoryRefresh) {
|
|
5535
|
+
if (!hasOnlySystemHashMaterialization(deps.pendingMaterializationSessions, sessionId))
|
|
5536
|
+
return;
|
|
5537
|
+
clearPendingMaterialization(deps.pendingMaterializationSessions, sessionId);
|
|
5538
|
+
(deps.deferredMaterializationSessions ??= new Set).add(sessionId);
|
|
5539
|
+
if (ownsHistoryRefresh && deps.historyRefreshSessions.delete(sessionId)) {
|
|
5540
|
+
(deps.deferredHistoryRefreshSessions ??= new Set).add(sessionId);
|
|
5541
|
+
}
|
|
5542
|
+
}
|
|
5543
|
+
function clearSystemPromptDelivery(sessionId) {
|
|
5544
|
+
retirePendingSystemPromptDelivery(sessionId);
|
|
5545
|
+
refreshOwners.delete(sessionId);
|
|
5546
|
+
}
|
|
5547
|
+
function retirePendingSystemPromptDelivery(sessionId) {
|
|
5548
|
+
const saved = pending2.get(sessionId);
|
|
5549
|
+
if (saved)
|
|
5550
|
+
retiredRequests.add(saved.request);
|
|
5551
|
+
pending2.delete(sessionId);
|
|
5552
|
+
}
|
|
5553
|
+
|
|
5554
|
+
// ../plugin/src/hooks/magic-context/lkg-measured-request.ts
|
|
5555
|
+
var requests = new BoundedSessionMap(1000);
|
|
5556
|
+
var claimedRequests = new WeakSet;
|
|
5557
|
+
var captures = new BoundedSessionMap(1000);
|
|
5558
|
+
function clearCapturedLkgMeasurement(sessionId) {
|
|
5559
|
+
captures.delete(sessionId);
|
|
5560
|
+
}
|
|
5561
|
+
|
|
5562
|
+
// ../plugin/src/hooks/magic-context/lkg-persist.ts
|
|
5563
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
5564
|
+
function parseStringArray(value) {
|
|
5565
|
+
if (typeof value !== "string")
|
|
5566
|
+
return null;
|
|
5567
|
+
let parsed;
|
|
5568
|
+
try {
|
|
5569
|
+
parsed = JSON.parse(value);
|
|
5570
|
+
} catch {
|
|
5571
|
+
return null;
|
|
5572
|
+
}
|
|
5573
|
+
if (!Array.isArray(parsed))
|
|
5574
|
+
return null;
|
|
5575
|
+
const result = [];
|
|
5576
|
+
for (const entry of parsed) {
|
|
5577
|
+
if (typeof entry !== "string" || entry.length === 0)
|
|
5578
|
+
return null;
|
|
5579
|
+
result.push(entry);
|
|
5580
|
+
}
|
|
5581
|
+
return result;
|
|
5582
|
+
}
|
|
5583
|
+
function parseNullableString(value) {
|
|
5584
|
+
if (value === null || value === undefined)
|
|
5585
|
+
return null;
|
|
5586
|
+
return typeof value === "string" ? value : undefined;
|
|
5587
|
+
}
|
|
5588
|
+
function parseNullableInteger(value) {
|
|
5589
|
+
if (value === null || value === undefined)
|
|
5590
|
+
return;
|
|
5591
|
+
return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
|
|
5592
|
+
}
|
|
5593
|
+
function parsePersistedLkgSlot(row) {
|
|
5594
|
+
if (!row || typeof row !== "object")
|
|
5595
|
+
return;
|
|
5596
|
+
const record = row;
|
|
5597
|
+
const jsonPrefix = record.json_prefix;
|
|
5598
|
+
const lastInputMessageId = record.last_input_message_id;
|
|
5599
|
+
const capturedAt = record.captured_at;
|
|
5600
|
+
let inputIdsRaw = record.input_id_seq;
|
|
5601
|
+
let piOutputEntryIds;
|
|
5602
|
+
if (typeof inputIdsRaw === "string") {
|
|
5603
|
+
try {
|
|
5604
|
+
const metadata = JSON.parse(inputIdsRaw);
|
|
5605
|
+
if (metadata && !Array.isArray(metadata) && metadata.version === 1 && Array.isArray(metadata.piOutputEntryIds)) {
|
|
5606
|
+
if (!metadata.piOutputEntryIds.every((id) => id === null || typeof id === "string" && id.length > 0))
|
|
5607
|
+
return;
|
|
5608
|
+
piOutputEntryIds = metadata.piOutputEntryIds;
|
|
5609
|
+
inputIdsRaw = JSON.stringify(metadata.inputIds);
|
|
5610
|
+
}
|
|
5611
|
+
} catch {
|
|
5612
|
+
return;
|
|
5613
|
+
}
|
|
5614
|
+
}
|
|
5615
|
+
const inputIdSeq = parseStringArray(inputIdsRaw);
|
|
5616
|
+
const inputContentDigests = parseStringArray(record.input_content_digests);
|
|
5617
|
+
const modelKey = parseNullableString(record.model_key);
|
|
5618
|
+
const providerKey = parseNullableString(record.provider_key);
|
|
5619
|
+
if (typeof jsonPrefix !== "string" || typeof lastInputMessageId !== "string" || lastInputMessageId.length === 0 || typeof capturedAt !== "number" || !Number.isFinite(capturedAt) || inputIdSeq === null || inputContentDigests === null || inputContentDigests.length !== inputIdSeq.length || modelKey === undefined || providerKey === undefined) {
|
|
5620
|
+
return;
|
|
5621
|
+
}
|
|
5622
|
+
if (piOutputEntryIds) {
|
|
5623
|
+
try {
|
|
5624
|
+
const output = JSON.parse(jsonPrefix);
|
|
5625
|
+
const inputs = new Set(inputIdSeq);
|
|
5626
|
+
if (!Array.isArray(output) || output.length !== piOutputEntryIds.length || piOutputEntryIds.some((id) => id !== null && !inputs.has(id)))
|
|
5627
|
+
return;
|
|
5628
|
+
} catch {
|
|
5629
|
+
return;
|
|
5630
|
+
}
|
|
5631
|
+
}
|
|
5632
|
+
let inputContentSignatures;
|
|
5633
|
+
if (record.input_content_signatures !== null && record.input_content_signatures !== undefined) {
|
|
5634
|
+
const parsed = parseStringArray(record.input_content_signatures);
|
|
5635
|
+
if (parsed === null || parsed.length !== inputIdSeq.length)
|
|
5636
|
+
return;
|
|
5637
|
+
inputContentSignatures = parsed;
|
|
5638
|
+
}
|
|
5639
|
+
const slot = {
|
|
5640
|
+
jsonPrefix,
|
|
5641
|
+
inputIdSeq,
|
|
5642
|
+
inputContentDigests,
|
|
5643
|
+
lastInputMessageId,
|
|
5644
|
+
modelKey,
|
|
5645
|
+
providerKey,
|
|
5646
|
+
capturedAt
|
|
5647
|
+
};
|
|
5648
|
+
if (inputContentSignatures)
|
|
5649
|
+
slot.inputContentSignatures = inputContentSignatures;
|
|
5650
|
+
if (piOutputEntryIds)
|
|
5651
|
+
slot.piOutputEntryIds = piOutputEntryIds;
|
|
5652
|
+
const rowVersion = parseNullableInteger(record.row_version);
|
|
5653
|
+
if (rowVersion !== undefined)
|
|
5654
|
+
slot.rowVersion = rowVersion;
|
|
5655
|
+
const captureSequence = parseNullableInteger(record.capture_sequence);
|
|
5656
|
+
if (captureSequence !== undefined)
|
|
5657
|
+
slot.captureSequence = captureSequence;
|
|
5658
|
+
return slot;
|
|
5659
|
+
}
|
|
5660
|
+
var persistedFingerprints = new WeakMap;
|
|
5661
|
+
var PERSISTED_FINGERPRINT_MAX_SESSIONS = 1000;
|
|
5662
|
+
function rememberFingerprint(db, sessionId, fingerprint) {
|
|
5663
|
+
let saved = persistedFingerprints.get(db);
|
|
5664
|
+
if (!saved) {
|
|
5665
|
+
saved = new Map;
|
|
5666
|
+
persistedFingerprints.set(db, saved);
|
|
5667
|
+
}
|
|
5668
|
+
saved.delete(sessionId);
|
|
5669
|
+
if (saved.size >= PERSISTED_FINGERPRINT_MAX_SESSIONS) {
|
|
5670
|
+
const oldest = saved.keys().next().value;
|
|
5671
|
+
if (oldest !== undefined)
|
|
5672
|
+
saved.delete(oldest);
|
|
5673
|
+
}
|
|
5674
|
+
saved.set(sessionId, fingerprint);
|
|
5675
|
+
}
|
|
5676
|
+
function slotFingerprint(slot) {
|
|
5677
|
+
return createHash3("sha256").update(JSON.stringify([
|
|
5678
|
+
slot.jsonPrefix,
|
|
5679
|
+
slot.inputIdSeq,
|
|
5680
|
+
slot.inputContentDigests,
|
|
5681
|
+
slot.inputContentSignatures,
|
|
5682
|
+
slot.piOutputEntryIds,
|
|
5683
|
+
slot.lastInputMessageId,
|
|
5684
|
+
slot.modelKey,
|
|
5685
|
+
slot.providerKey,
|
|
5686
|
+
slot.rowVersion,
|
|
5687
|
+
slot.captureSequence
|
|
5688
|
+
])).digest("hex");
|
|
5689
|
+
}
|
|
5690
|
+
function persistLkgSlot(db, sessionId, slot, publishMetadata) {
|
|
5691
|
+
const fingerprint = slotFingerprint(slot);
|
|
5692
|
+
if (!publishMetadata && persistedFingerprints.get(db)?.get(sessionId) === fingerprint) {
|
|
5693
|
+
const durable = loadPersistedLkgSlot(db, sessionId);
|
|
5694
|
+
if (durable && slotFingerprint(durable) === fingerprint)
|
|
5695
|
+
return true;
|
|
5696
|
+
}
|
|
5697
|
+
const layout = layoutLkgPrefix(slot.jsonPrefix);
|
|
7869
5698
|
try {
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
|
|
5699
|
+
db.transaction(() => {
|
|
5700
|
+
const storedHashes = new Map;
|
|
5701
|
+
for (const row of db.prepare("SELECT chunk, hash FROM lkg_slot_chunks WHERE session_id = ?").all(sessionId)) {
|
|
5702
|
+
storedHashes.set(row.chunk, row.hash);
|
|
5703
|
+
}
|
|
5704
|
+
const upsertChunk = db.prepare(`INSERT INTO lkg_slot_chunks (session_id, chunk, hash, body) VALUES (?, ?, ?, ?)
|
|
5705
|
+
ON CONFLICT(session_id, chunk) DO UPDATE SET hash = excluded.hash, body = excluded.body`);
|
|
5706
|
+
for (let index = 0;index < layout.chunks.length; index += 1) {
|
|
5707
|
+
if (storedHashes.get(index) === layout.chunkHashes[index])
|
|
5708
|
+
continue;
|
|
5709
|
+
upsertChunk.run(sessionId, index, layout.chunkHashes[index], layout.chunks[index]);
|
|
5710
|
+
}
|
|
5711
|
+
db.prepare("DELETE FROM lkg_slot_chunks WHERE session_id = ? AND chunk >= ?").run(sessionId, layout.chunks.length);
|
|
5712
|
+
db.prepare(`INSERT INTO lkg_slots (
|
|
5713
|
+
session_id, json_prefix_chars, json_prefix_chunks, json_prefix_hash,
|
|
5714
|
+
input_id_seq, input_content_digests, input_content_signatures,
|
|
5715
|
+
last_input_message_id, model_key, provider_key,
|
|
5716
|
+
captured_at, row_version, capture_sequence
|
|
5717
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5718
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
5719
|
+
json_prefix_chars = excluded.json_prefix_chars,
|
|
5720
|
+
json_prefix_chunks = excluded.json_prefix_chunks,
|
|
5721
|
+
json_prefix_hash = excluded.json_prefix_hash,
|
|
5722
|
+
input_id_seq = excluded.input_id_seq,
|
|
5723
|
+
input_content_digests = excluded.input_content_digests,
|
|
5724
|
+
input_content_signatures = excluded.input_content_signatures,
|
|
5725
|
+
last_input_message_id = excluded.last_input_message_id,
|
|
5726
|
+
model_key = excluded.model_key,
|
|
5727
|
+
provider_key = excluded.provider_key,
|
|
5728
|
+
captured_at = excluded.captured_at,
|
|
5729
|
+
row_version = excluded.row_version,
|
|
5730
|
+
capture_sequence = excluded.capture_sequence`).run(sessionId, layout.chars, layout.chunks.length, layout.hash, JSON.stringify(slot.piOutputEntryIds ? {
|
|
5731
|
+
version: 1,
|
|
5732
|
+
inputIds: slot.inputIdSeq,
|
|
5733
|
+
piOutputEntryIds: slot.piOutputEntryIds
|
|
5734
|
+
} : slot.inputIdSeq), JSON.stringify(slot.inputContentDigests), slot.inputContentSignatures ? JSON.stringify(slot.inputContentSignatures) : null, slot.lastInputMessageId, slot.modelKey, slot.providerKey, slot.capturedAt, slot.rowVersion ?? null, slot.captureSequence ?? null);
|
|
5735
|
+
publishMetadata?.();
|
|
5736
|
+
}).immediate();
|
|
5737
|
+
rememberFingerprint(db, sessionId, fingerprint);
|
|
5738
|
+
return true;
|
|
5739
|
+
} catch (error) {
|
|
5740
|
+
if (!publishMetadata)
|
|
5741
|
+
sessionLog2(sessionId, "LKG snapshot persistence failed (in-memory slot retained):", error);
|
|
5742
|
+
return false;
|
|
7879
5743
|
}
|
|
7880
5744
|
}
|
|
7881
|
-
function
|
|
5745
|
+
function saveLkgSlotToDb(db, sessionId, slot, publishMetadata, fence = {}) {
|
|
5746
|
+
return commitLkgWithRecoveryFence({
|
|
5747
|
+
sessionId,
|
|
5748
|
+
slot,
|
|
5749
|
+
...fence,
|
|
5750
|
+
load: () => loadPersistedLkgSlot(db, sessionId, true),
|
|
5751
|
+
commit: () => persistLkgSlot(db, sessionId, slot, publishMetadata)
|
|
5752
|
+
});
|
|
5753
|
+
}
|
|
5754
|
+
function clearPersistedLkgSlot(db, sessionId) {
|
|
7882
5755
|
try {
|
|
7883
|
-
|
|
7884
|
-
} catch {
|
|
7885
|
-
|
|
5756
|
+
clearPersistedLkgSlotStrict(db, sessionId);
|
|
5757
|
+
} catch (error) {
|
|
5758
|
+
sessionLog2(sessionId, "LKG snapshot durable clear failed:", error);
|
|
7886
5759
|
}
|
|
7887
5760
|
}
|
|
7888
|
-
function
|
|
7889
|
-
|
|
5761
|
+
function clearPersistedLkgSlotStrict(db, sessionId) {
|
|
5762
|
+
clearLkgRecoveryFence(sessionId, () => db.transaction(() => {
|
|
5763
|
+
db.prepare("DELETE FROM lkg_slot_chunks WHERE session_id = ?").run(sessionId);
|
|
5764
|
+
db.prepare("DELETE FROM lkg_slots WHERE session_id = ?").run(sessionId);
|
|
5765
|
+
}).immediate());
|
|
5766
|
+
persistedFingerprints.get(db)?.delete(sessionId);
|
|
7890
5767
|
}
|
|
7891
|
-
function
|
|
7892
|
-
|
|
7893
|
-
|
|
7894
|
-
|
|
7895
|
-
|
|
5768
|
+
function loadPersistedLkgSlot(db, sessionId, forPublication = false) {
|
|
5769
|
+
const rustHost = getHarness2() === "opencode" || getHarness2() === "opencode2";
|
|
5770
|
+
if (rustHost && !forPublication && isRustMarkerAdmissionFenced(db, sessionId))
|
|
5771
|
+
return;
|
|
5772
|
+
let row;
|
|
5773
|
+
let chunkRows;
|
|
5774
|
+
try {
|
|
5775
|
+
({ row, chunkRows } = db.transaction(() => {
|
|
5776
|
+
const slotRow = db.prepare("SELECT * FROM lkg_slots WHERE session_id = ?").get(sessionId);
|
|
5777
|
+
if (!slotRow)
|
|
5778
|
+
return { row: undefined, chunkRows: [] };
|
|
5779
|
+
const slices = db.prepare("SELECT chunk, hash, body FROM lkg_slot_chunks WHERE session_id = ? ORDER BY chunk").all(sessionId);
|
|
5780
|
+
return { row: slotRow, chunkRows: slices };
|
|
5781
|
+
}).deferred());
|
|
5782
|
+
} catch (error) {
|
|
5783
|
+
sessionLog2(sessionId, "LKG snapshot durable load failed:", error);
|
|
5784
|
+
return;
|
|
7896
5785
|
}
|
|
7897
|
-
|
|
5786
|
+
if (!row)
|
|
5787
|
+
return;
|
|
5788
|
+
const prefix = assembleLkgPrefix({
|
|
5789
|
+
chars: row.json_prefix_chars,
|
|
5790
|
+
chunks: row.json_prefix_chunks,
|
|
5791
|
+
hash: row.json_prefix_hash
|
|
5792
|
+
}, chunkRows);
|
|
5793
|
+
const slot = prefix ? parsePersistedLkgSlot({ ...row, json_prefix: prefix.jsonPrefix }) : undefined;
|
|
5794
|
+
if (!prefix || !slot) {
|
|
5795
|
+
if (!prefix)
|
|
5796
|
+
sessionLog2(sessionId, "LKG snapshot slices failed verification; slot cleared");
|
|
5797
|
+
clearPersistedLkgSlot(db, sessionId);
|
|
5798
|
+
return;
|
|
5799
|
+
}
|
|
5800
|
+
return slot;
|
|
7898
5801
|
}
|
|
7899
|
-
function
|
|
7900
|
-
const
|
|
7901
|
-
|
|
7902
|
-
|
|
7903
|
-
|
|
5802
|
+
function pruneStaleLkgSlotsBatch(db, now) {
|
|
5803
|
+
const previousTimeout = db.prepare("PRAGMA busy_timeout").get();
|
|
5804
|
+
const cutoff = now - 7 * 24 * 60 * 60 * 1000;
|
|
5805
|
+
const stale = `captured_at < ? AND NOT EXISTS (
|
|
5806
|
+
SELECT 1 FROM session_projects sp
|
|
5807
|
+
WHERE sp.session_id = lkg_slots.session_id AND sp.updated_at >= ?
|
|
5808
|
+
)`;
|
|
5809
|
+
const slot = db.prepare(`SELECT session_id FROM lkg_slots WHERE ${stale} LIMIT 1`).get(cutoff, cutoff);
|
|
5810
|
+
const chunks = db.prepare(`SELECT rowid FROM lkg_slot_chunks c WHERE
|
|
5811
|
+
session_id = ? OR NOT EXISTS (SELECT 1 FROM lkg_slots s WHERE s.session_id = c.session_id)
|
|
5812
|
+
LIMIT 25`).all(slot?.session_id ?? "");
|
|
5813
|
+
if (!slot && chunks.length === 0)
|
|
5814
|
+
return { slots: 0, chunks: 0 };
|
|
5815
|
+
try {
|
|
5816
|
+
db.exec("PRAGMA busy_timeout = 0");
|
|
5817
|
+
let transactionStartedAt = 0;
|
|
5818
|
+
const remove = () => db.transaction(() => {
|
|
5819
|
+
transactionStartedAt = performance.now();
|
|
5820
|
+
const removed = slot ? db.prepare(`DELETE FROM lkg_slots WHERE session_id = ? AND ${stale}`).run(slot.session_id, cutoff, cutoff).changes : 0;
|
|
5821
|
+
const removeChunk = db.prepare(`DELETE FROM lkg_slot_chunks WHERE rowid = ? AND NOT EXISTS (
|
|
5822
|
+
SELECT 1 FROM lkg_slots s WHERE s.session_id = lkg_slot_chunks.session_id
|
|
5823
|
+
)`);
|
|
5824
|
+
let removedChunks = 0;
|
|
5825
|
+
for (const { rowid } of chunks)
|
|
5826
|
+
removedChunks += removeChunk.run(rowid).changes;
|
|
5827
|
+
return { slots: removed, chunks: removedChunks };
|
|
5828
|
+
}).immediate();
|
|
5829
|
+
const changes = slot ? clearLkgRecoveryFence(slot.session_id, remove, (result) => !!result?.slots) ?? {
|
|
5830
|
+
slots: 0,
|
|
5831
|
+
chunks: 0
|
|
5832
|
+
} : remove();
|
|
5833
|
+
logSlowWriteTransaction("lkg_stale_gc", transactionStartedAt);
|
|
5834
|
+
if (changes.slots && slot) {
|
|
5835
|
+
persistedFingerprints.get(db)?.delete(slot.session_id);
|
|
5836
|
+
}
|
|
5837
|
+
return changes;
|
|
5838
|
+
} finally {
|
|
5839
|
+
db.exec(`PRAGMA busy_timeout = ${Number(previousTimeout.timeout) || 0}`);
|
|
7904
5840
|
}
|
|
7905
|
-
return { directoryMtimeMs: readDirectoryMtimeMs(projectDirectory), files };
|
|
7906
5841
|
}
|
|
7907
|
-
function
|
|
7908
|
-
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
|
|
5842
|
+
async function drainStaleLkgSlots(db, now = Date.now(), budgetMs = 2000) {
|
|
5843
|
+
let removed = 0;
|
|
5844
|
+
await drainBackgroundBatches(() => {
|
|
5845
|
+
const batch = pruneStaleLkgSlotsBatch(db, now);
|
|
5846
|
+
removed += batch.slots;
|
|
5847
|
+
return batch.slots + batch.chunks > 0;
|
|
5848
|
+
}, { budgetMs });
|
|
5849
|
+
return removed;
|
|
5850
|
+
}
|
|
5851
|
+
function createDbLkgPersistence(db) {
|
|
5852
|
+
return {
|
|
5853
|
+
load: (sessionId) => loadPersistedLkgSlot(db, sessionId),
|
|
5854
|
+
clear: (sessionId) => clearPersistedLkgSlot(db, sessionId)
|
|
5855
|
+
};
|
|
5856
|
+
}
|
|
5857
|
+
|
|
5858
|
+
// ../plugin/src/hooks/magic-context/openai-compat-adjacency.ts
|
|
5859
|
+
function assertOpenAiCompatAdjacency(messages) {
|
|
5860
|
+
const violations = [];
|
|
5861
|
+
for (let i = 0;i < messages.length; i++) {
|
|
5862
|
+
const msg = messages[i];
|
|
5863
|
+
if (msg.role !== "assistant" || !msg.tool_calls || msg.tool_calls.length === 0) {
|
|
7914
5864
|
continue;
|
|
7915
5865
|
}
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
5866
|
+
const expectedIds = msg.tool_calls.map((tc) => tc.id);
|
|
5867
|
+
const expectedSet = new Set(expectedIds);
|
|
5868
|
+
const collected = new Map;
|
|
5869
|
+
let j = i + 1;
|
|
5870
|
+
while (j < messages.length && messages[j].role === "tool") {
|
|
5871
|
+
const toolMsg = messages[j];
|
|
5872
|
+
const id = toolMsg.tool_call_id;
|
|
5873
|
+
if (!id) {
|
|
5874
|
+
violations.push({
|
|
5875
|
+
index: i,
|
|
5876
|
+
kind: "unmatched_tool_call_id",
|
|
5877
|
+
detail: `tool message at index ${j} missing tool_call_id`
|
|
5878
|
+
});
|
|
5879
|
+
} else if (!expectedSet.has(id)) {
|
|
5880
|
+
violations.push({
|
|
5881
|
+
index: i,
|
|
5882
|
+
kind: "unmatched_tool_call_id",
|
|
5883
|
+
toolCallId: id,
|
|
5884
|
+
assistantToolCallIds: expectedIds,
|
|
5885
|
+
detail: `tool message at index ${j} references unexpected id ${id}`
|
|
5886
|
+
});
|
|
5887
|
+
} else {
|
|
5888
|
+
collected.set(id, j);
|
|
5889
|
+
}
|
|
5890
|
+
j++;
|
|
5891
|
+
}
|
|
5892
|
+
const followingRoles = messages.slice(i + 1, Math.min(messages.length, i + 4)).map((m) => m.role);
|
|
5893
|
+
const missing = expectedIds.filter((id) => !collected.has(id));
|
|
5894
|
+
if (missing.length > 0) {
|
|
5895
|
+
violations.push({
|
|
5896
|
+
index: i,
|
|
5897
|
+
kind: "missing_tool_messages",
|
|
5898
|
+
assistantToolCallIds: expectedIds,
|
|
5899
|
+
followingRoles,
|
|
5900
|
+
detail: missing.length === expectedIds.length ? `assistant at index ${i} has tool_calls but next messages are not contiguous tool role (following: ${followingRoles.join(", ") || "none"})` : `assistant at index ${i} missing tool results for: ${missing.join(", ")}`
|
|
5901
|
+
});
|
|
5902
|
+
if (j < messages.length && messages[j].role !== "tool") {
|
|
5903
|
+
const last = violations[violations.length - 1];
|
|
5904
|
+
last.detail += `; blocked by ${messages.slice(i + 1, j + 1).map((m, off) => `${m.role}[${i + 1 + off}]`).join(", ")}`;
|
|
5905
|
+
}
|
|
7922
5906
|
}
|
|
7923
|
-
|
|
5907
|
+
}
|
|
5908
|
+
for (let i = 0;i < messages.length; i++) {
|
|
5909
|
+
if (messages[i].role !== "tool")
|
|
5910
|
+
continue;
|
|
5911
|
+
const id = messages[i].tool_call_id ?? "";
|
|
5912
|
+
if (!id)
|
|
7924
5913
|
continue;
|
|
5914
|
+
let found = false;
|
|
5915
|
+
for (let k = i - 1;k >= 0; k--) {
|
|
5916
|
+
const prev = messages[k];
|
|
5917
|
+
if (prev.role === "assistant" && prev.tool_calls?.some((tc) => tc.id === id)) {
|
|
5918
|
+
const between = messages.slice(k + 1, i);
|
|
5919
|
+
if (between.every((m) => m.role === "tool")) {
|
|
5920
|
+
found = true;
|
|
5921
|
+
}
|
|
5922
|
+
break;
|
|
5923
|
+
}
|
|
5924
|
+
if (prev.role === "assistant" || prev.role === "user")
|
|
5925
|
+
break;
|
|
5926
|
+
}
|
|
5927
|
+
if (!found) {
|
|
5928
|
+
violations.push({
|
|
5929
|
+
index: i,
|
|
5930
|
+
kind: "orphan_tool_message",
|
|
5931
|
+
toolCallId: id,
|
|
5932
|
+
detail: `tool message at index ${i} is not immediately after its assistant tool_calls`
|
|
5933
|
+
});
|
|
7925
5934
|
}
|
|
7926
|
-
const canonicalContent = canonicalizeDocContent(readFileSync7(filePath, "utf8"));
|
|
7927
|
-
hashPieces.push(`file:${filename}
|
|
7928
|
-
${canonicalContent}`);
|
|
7929
|
-
renderedSections.push(`<file name="${escapeXmlAttr(filename)}">
|
|
7930
|
-
${escapeXmlContent(canonicalContent)}
|
|
7931
|
-
</file>`);
|
|
7932
5935
|
}
|
|
7933
|
-
return {
|
|
5936
|
+
return { ok: violations.length === 0, violations };
|
|
7934
5937
|
}
|
|
7935
|
-
function buildRenderedBlock(renderedSections) {
|
|
7936
|
-
if (renderedSections.length === 0) {
|
|
7937
|
-
return "";
|
|
7938
|
-
}
|
|
7939
|
-
return `<project-docs>
|
|
7940
|
-
${renderedSections.join(`
|
|
7941
5938
|
|
|
7942
|
-
|
|
7943
|
-
|
|
5939
|
+
// ../plugin/src/hooks/magic-context/lkg-replay.ts
|
|
5940
|
+
function canonicalLkgModelKeys(modelKey, providerKey) {
|
|
5941
|
+
const canonicalModelKey = modelKey ? piModelRefToCanonical(modelKey) : null;
|
|
5942
|
+
const slash = canonicalModelKey?.indexOf("/") ?? -1;
|
|
5943
|
+
return {
|
|
5944
|
+
modelKey: canonicalModelKey,
|
|
5945
|
+
providerKey: slash > 0 && canonicalModelKey ? canonicalModelKey.slice(0, slash) : providerKey
|
|
5946
|
+
};
|
|
7944
5947
|
}
|
|
7945
|
-
function
|
|
7946
|
-
|
|
7947
|
-
|
|
5948
|
+
function recordValue(info, key) {
|
|
5949
|
+
return info && typeof info === "object" ? info[key] : undefined;
|
|
5950
|
+
}
|
|
5951
|
+
function messageInfo(message) {
|
|
5952
|
+
if (message.info && typeof message.info === "object")
|
|
5953
|
+
return message.info;
|
|
5954
|
+
return message;
|
|
5955
|
+
}
|
|
5956
|
+
function messageParts(message) {
|
|
5957
|
+
return Array.isArray(message.parts) ? message.parts : [];
|
|
5958
|
+
}
|
|
5959
|
+
function messageRole(message) {
|
|
5960
|
+
const infoRole = recordValue(messageInfo(message), "role");
|
|
5961
|
+
if (typeof infoRole === "string")
|
|
5962
|
+
return infoRole;
|
|
5963
|
+
const role = recordValue(message, "role");
|
|
5964
|
+
return typeof role === "string" ? role : undefined;
|
|
5965
|
+
}
|
|
5966
|
+
function messageId(message) {
|
|
5967
|
+
const id = recordValue(messageInfo(message), "id") ?? recordValue(message, "id");
|
|
5968
|
+
return typeof id === "string" && id.length > 0 ? id : null;
|
|
5969
|
+
}
|
|
5970
|
+
function entryIdsAreValid(slot, entryIds) {
|
|
5971
|
+
if (slot.inputIdSeq.length === 0 || entryIds.length < slot.inputIdSeq.length)
|
|
5972
|
+
return false;
|
|
5973
|
+
if (slot.inputIdSeq[slot.inputIdSeq.length - 1] !== slot.lastInputMessageId)
|
|
5974
|
+
return false;
|
|
5975
|
+
const seen = new Set;
|
|
5976
|
+
for (const id of entryIds) {
|
|
5977
|
+
if (!id || seen.has(id))
|
|
5978
|
+
return false;
|
|
5979
|
+
seen.add(id);
|
|
7948
5980
|
}
|
|
7949
|
-
|
|
5981
|
+
if (entryIds.indexOf(slot.lastInputMessageId) !== slot.inputIdSeq.length - 1)
|
|
5982
|
+
return false;
|
|
5983
|
+
for (let index = 0;index < slot.inputIdSeq.length; index += 1) {
|
|
5984
|
+
if (entryIds[index] !== slot.inputIdSeq[index])
|
|
5985
|
+
return false;
|
|
5986
|
+
}
|
|
5987
|
+
return true;
|
|
7950
5988
|
}
|
|
7951
|
-
function
|
|
7952
|
-
|
|
7953
|
-
|
|
7954
|
-
|
|
7955
|
-
const
|
|
7956
|
-
|
|
7957
|
-
|
|
7958
|
-
|
|
7959
|
-
|
|
7960
|
-
|
|
7961
|
-
|
|
5989
|
+
function entryContentIsValid(slot, entry) {
|
|
5990
|
+
return entry.entryContentDigests.length >= slot.inputContentDigests.length && slot.inputContentDigests.every((digest, index) => isLegacyLkgDigest(digest) ? entry.entryLegacyContentDigests?.[index] === digest : entry.entryContentDigests[index] === digest);
|
|
5991
|
+
}
|
|
5992
|
+
function partCallIds(message) {
|
|
5993
|
+
const ids = [];
|
|
5994
|
+
for (const rawPart of messageParts(message)) {
|
|
5995
|
+
if (!rawPart || typeof rawPart !== "object")
|
|
5996
|
+
continue;
|
|
5997
|
+
const part = rawPart;
|
|
5998
|
+
if (part.type !== "tool" && part.type !== "tool_use")
|
|
5999
|
+
continue;
|
|
6000
|
+
const callId = part.callID ?? part.callId ?? part.id;
|
|
6001
|
+
if (typeof callId === "string" && callId.length > 0)
|
|
6002
|
+
ids.push(callId);
|
|
7962
6003
|
}
|
|
7963
|
-
|
|
7964
|
-
const canonicalHash = hashCanonicalPieces(hashPieces);
|
|
7965
|
-
const renderedBlock = buildRenderedBlock(renderedSections);
|
|
7966
|
-
docsCache.set(canonicalDirectory, {
|
|
7967
|
-
directoryMtimeMs: current.directoryMtimeMs,
|
|
7968
|
-
files: current.files,
|
|
7969
|
-
cachedHash: canonicalHash,
|
|
7970
|
-
cachedRendered: renderedBlock
|
|
7971
|
-
});
|
|
7972
|
-
return { renderedBlock, canonicalHash };
|
|
6004
|
+
return ids;
|
|
7973
6005
|
}
|
|
7974
|
-
|
|
7975
|
-
|
|
7976
|
-
|
|
7977
|
-
|
|
7978
|
-
|
|
7979
|
-
|
|
7980
|
-
|
|
7981
|
-
|
|
7982
|
-
|
|
7983
|
-
|
|
7984
|
-
|
|
7985
|
-
|
|
7986
|
-
|
|
7987
|
-
|
|
7988
|
-
|
|
7989
|
-
|
|
7990
|
-
|
|
7991
|
-
|
|
7992
|
-
|
|
7993
|
-
return
|
|
6006
|
+
function partResultIds(message) {
|
|
6007
|
+
const ids = [];
|
|
6008
|
+
for (const rawPart of messageParts(message)) {
|
|
6009
|
+
if (!rawPart || typeof rawPart !== "object")
|
|
6010
|
+
continue;
|
|
6011
|
+
const part = rawPart;
|
|
6012
|
+
if (part.type !== "tool_result" && part.type !== "tool-result")
|
|
6013
|
+
continue;
|
|
6014
|
+
const callId = part.tool_call_id ?? part.tool_use_id ?? part.callID ?? part.callId;
|
|
6015
|
+
if (typeof callId === "string" && callId.length > 0)
|
|
6016
|
+
ids.push(callId);
|
|
6017
|
+
}
|
|
6018
|
+
return ids;
|
|
6019
|
+
}
|
|
6020
|
+
function partIsReasoning(part) {
|
|
6021
|
+
return Boolean(part && typeof part === "object" && part.type === "reasoning");
|
|
6022
|
+
}
|
|
6023
|
+
function partIsAnthropicThinking(part) {
|
|
6024
|
+
if (!part || typeof part !== "object")
|
|
6025
|
+
return false;
|
|
6026
|
+
const type = part.type;
|
|
6027
|
+
return type === "thinking" || type === "reasoning" || type === "redacted_thinking";
|
|
6028
|
+
}
|
|
6029
|
+
function partEndsAnthropicAssistantRun(part) {
|
|
6030
|
+
if (!part || typeof part !== "object")
|
|
6031
|
+
return false;
|
|
6032
|
+
const value = part;
|
|
6033
|
+
if (value.type !== "tool" || value.providerExecuted === true || !value.state || typeof value.state !== "object") {
|
|
6034
|
+
return false;
|
|
7994
6035
|
}
|
|
7995
|
-
|
|
7996
|
-
|
|
6036
|
+
const status = value.state.status;
|
|
6037
|
+
return status === "completed" || status === "error";
|
|
6038
|
+
}
|
|
6039
|
+
function partIsOpenCodeStepMetadata(part) {
|
|
6040
|
+
if (!part || typeof part !== "object")
|
|
6041
|
+
return false;
|
|
6042
|
+
const type = part.type;
|
|
6043
|
+
return type === "step-start" || type === "step-finish";
|
|
6044
|
+
}
|
|
6045
|
+
function validateAnthropicReasoningRuns(messages) {
|
|
6046
|
+
let index = 0;
|
|
6047
|
+
while (index < messages.length) {
|
|
6048
|
+
if (messageRole(messages[index]) !== "assistant") {
|
|
6049
|
+
index += 1;
|
|
6050
|
+
continue;
|
|
6051
|
+
}
|
|
6052
|
+
let firstMessageInRun = null;
|
|
6053
|
+
let sawOtherContent = false;
|
|
6054
|
+
while (index < messages.length && messageRole(messages[index]) === "assistant") {
|
|
6055
|
+
for (const part of messageParts(messages[index])) {
|
|
6056
|
+
if (partEndsAnthropicAssistantRun(part)) {
|
|
6057
|
+
firstMessageInRun = null;
|
|
6058
|
+
sawOtherContent = false;
|
|
6059
|
+
} else if (!partIsOpenCodeStepMetadata(part)) {
|
|
6060
|
+
if (firstMessageInRun === null)
|
|
6061
|
+
firstMessageInRun = index;
|
|
6062
|
+
if (partIsAnthropicThinking(part)) {
|
|
6063
|
+
if (sawOtherContent || index !== firstMessageInRun)
|
|
6064
|
+
return false;
|
|
6065
|
+
} else {
|
|
6066
|
+
sawOtherContent = true;
|
|
6067
|
+
}
|
|
6068
|
+
}
|
|
6069
|
+
}
|
|
6070
|
+
index += 1;
|
|
6071
|
+
}
|
|
7997
6072
|
}
|
|
7998
|
-
|
|
7999
|
-
|
|
6073
|
+
return true;
|
|
6074
|
+
}
|
|
6075
|
+
function validateLkgSeamBoundary(prefix, tail) {
|
|
6076
|
+
const last = prefix[prefix.length - 1];
|
|
6077
|
+
const first = tail[0];
|
|
6078
|
+
if (!last || !first)
|
|
6079
|
+
return true;
|
|
6080
|
+
const lastCalls = partCallIds(last);
|
|
6081
|
+
if (lastCalls.length === 0)
|
|
6082
|
+
return true;
|
|
6083
|
+
const firstCalls = new Set([...partCallIds(first), ...partResultIds(first)]);
|
|
6084
|
+
if (messageRole(first) === "tool" || lastCalls.some((callId) => firstCalls.has(callId)))
|
|
6085
|
+
return false;
|
|
6086
|
+
return !messageParts(last).some((part) => {
|
|
6087
|
+
if (!part || typeof part !== "object")
|
|
6088
|
+
return false;
|
|
6089
|
+
const value = part;
|
|
6090
|
+
if (value.type !== "tool")
|
|
6091
|
+
return false;
|
|
6092
|
+
const state = value.state;
|
|
6093
|
+
return !state || typeof state !== "object" || state.status !== "completed";
|
|
6094
|
+
});
|
|
6095
|
+
}
|
|
6096
|
+
function validateLkgSeam(prefix, tail, providerKey) {
|
|
6097
|
+
const all = [...prefix, ...tail];
|
|
6098
|
+
const ids = new Set;
|
|
6099
|
+
const calls = new Set;
|
|
6100
|
+
const results = new Set;
|
|
6101
|
+
for (const message of all) {
|
|
6102
|
+
const id = messageId(message);
|
|
6103
|
+
if (id !== null) {
|
|
6104
|
+
if (ids.has(id))
|
|
6105
|
+
return false;
|
|
6106
|
+
ids.add(id);
|
|
6107
|
+
}
|
|
6108
|
+
for (const callId of partCallIds(message)) {
|
|
6109
|
+
if (calls.has(callId))
|
|
6110
|
+
return false;
|
|
6111
|
+
calls.add(callId);
|
|
6112
|
+
}
|
|
6113
|
+
for (const callId of partResultIds(message)) {
|
|
6114
|
+
if (results.has(callId))
|
|
6115
|
+
return false;
|
|
6116
|
+
results.add(callId);
|
|
6117
|
+
}
|
|
6118
|
+
if (messageRole(message) !== "assistant" && messageParts(message).some(partIsReasoning))
|
|
6119
|
+
return false;
|
|
6120
|
+
if (providerKey !== "anthropic" && messageParts(message).some((part) => {
|
|
6121
|
+
if (!part || typeof part !== "object")
|
|
6122
|
+
return false;
|
|
6123
|
+
const value = part;
|
|
6124
|
+
return (value.type === "text" || value.type === "reasoning") && value.text === "";
|
|
6125
|
+
}))
|
|
6126
|
+
return false;
|
|
8000
6127
|
}
|
|
8001
|
-
|
|
8002
|
-
|
|
8003
|
-
|
|
8004
|
-
|
|
8005
|
-
|
|
8006
|
-
|
|
8007
|
-
|
|
6128
|
+
if (!validateLkgSeamBoundary(prefix, tail))
|
|
6129
|
+
return false;
|
|
6130
|
+
const wireCandidates = all.map((message) => message);
|
|
6131
|
+
if (wireCandidates.every((message) => typeof message.role === "string")) {
|
|
6132
|
+
const adjacency = assertOpenAiCompatAdjacency(wireCandidates);
|
|
6133
|
+
if (!adjacency.ok)
|
|
6134
|
+
return false;
|
|
6135
|
+
const wireCallIds = new Set;
|
|
6136
|
+
for (const wireMessage of wireCandidates) {
|
|
6137
|
+
for (const call of wireMessage.tool_calls ?? []) {
|
|
6138
|
+
if (wireCallIds.has(call.id))
|
|
6139
|
+
return false;
|
|
6140
|
+
wireCallIds.add(call.id);
|
|
6141
|
+
}
|
|
8008
6142
|
}
|
|
8009
|
-
this.store.set(sessionId, value);
|
|
8010
6143
|
}
|
|
8011
|
-
|
|
8012
|
-
|
|
6144
|
+
return true;
|
|
6145
|
+
}
|
|
6146
|
+
function replayLkg(args) {
|
|
6147
|
+
const slot = getSlot(args.sessionId);
|
|
6148
|
+
if (!slot)
|
|
6149
|
+
return { ok: false, reason: "lkg_invalidated_reshape" };
|
|
6150
|
+
const requestedModelKeys = canonicalLkgModelKeys(args.modelKey, args.providerKey);
|
|
6151
|
+
const capturedModelKeys = canonicalLkgModelKeys(slot.modelKey, slot.providerKey);
|
|
6152
|
+
if (capturedModelKeys.modelKey !== requestedModelKeys.modelKey || capturedModelKeys.providerKey !== requestedModelKeys.providerKey) {
|
|
6153
|
+
dropSlot(args.sessionId, "lkg_model_mismatch");
|
|
6154
|
+
return { ok: false, reason: "lkg_model_mismatch" };
|
|
6155
|
+
}
|
|
6156
|
+
const entry = args.entry ?? noteEntry(args.sessionId, args.messages);
|
|
6157
|
+
if (!entry || entry.anchorIndex !== slot.inputIdSeq.length - 1 || !entryIdsAreValid(slot, entry.entryInputIds)) {
|
|
6158
|
+
dropSlot(args.sessionId, "lkg_invalidated_reshape");
|
|
6159
|
+
return { ok: false, reason: "lkg_invalidated_reshape" };
|
|
6160
|
+
}
|
|
6161
|
+
if (!entryContentIsValid(slot, entry)) {
|
|
6162
|
+
dropSlot(args.sessionId, "lkg_content_mismatch");
|
|
6163
|
+
return { ok: false, reason: "lkg_content_mismatch" };
|
|
6164
|
+
}
|
|
6165
|
+
let prefix;
|
|
6166
|
+
try {
|
|
6167
|
+
const parsed = JSON.parse(slot.jsonPrefix);
|
|
6168
|
+
if (!Array.isArray(parsed))
|
|
6169
|
+
throw new Error("prefix is not an array");
|
|
6170
|
+
prefix = parsed;
|
|
6171
|
+
} catch {
|
|
6172
|
+
dropSlot(args.sessionId, "lkg_seam_invalid");
|
|
6173
|
+
return { ok: false, reason: "lkg_seam_invalid" };
|
|
8013
6174
|
}
|
|
8014
|
-
|
|
8015
|
-
|
|
6175
|
+
const replayed = [...prefix, ...entry.pristineTail];
|
|
6176
|
+
args.prepareReplay?.(replayed);
|
|
6177
|
+
if (!args.skipSeamValidation) {
|
|
6178
|
+
if (!validateLkgSeamBoundary(prefix, entry.pristineTail)) {
|
|
6179
|
+
dropSlot(args.sessionId, "lkg_unsafe_seam");
|
|
6180
|
+
return { ok: false, reason: "lkg_unsafe_seam" };
|
|
6181
|
+
}
|
|
6182
|
+
if (!validateLkgSeam(prefix, entry.pristineTail, requestedModelKeys.providerKey)) {
|
|
6183
|
+
dropSlot(args.sessionId, "lkg_seam_invalid");
|
|
6184
|
+
return { ok: false, reason: "lkg_seam_invalid" };
|
|
6185
|
+
}
|
|
8016
6186
|
}
|
|
8017
|
-
|
|
8018
|
-
|
|
6187
|
+
if (requestedModelKeys.providerKey === "anthropic" && !validateAnthropicReasoningRuns(replayed)) {
|
|
6188
|
+
dropSlot(args.sessionId, "lkg_anthropic_reasoning_run_invalid");
|
|
6189
|
+
return { ok: false, reason: "lkg_anthropic_reasoning_run_invalid" };
|
|
8019
6190
|
}
|
|
6191
|
+
return { ok: true, messages: replayed };
|
|
8020
6192
|
}
|
|
8021
6193
|
|
|
8022
|
-
// ../plugin/src/
|
|
8023
|
-
|
|
8024
|
-
|
|
8025
|
-
|
|
8026
|
-
|
|
8027
|
-
return ["error", "failed", "abort", "aborted", "interrupted", "cancelled", "canceled"].includes(finish);
|
|
8028
|
-
}
|
|
8029
|
-
function isSuccessfulProviderCompletion(input) {
|
|
8030
|
-
if (providerResponseFailed(input))
|
|
8031
|
-
return false;
|
|
8032
|
-
return typeof input.completedAt === "number" && Number.isFinite(input.completedAt) && input.completedAt > 0 || typeof input.finish === "string" && input.finish.trim().length > 0;
|
|
6194
|
+
// ../plugin/src/hooks/magic-context/lkg-recovery-prefix.ts
|
|
6195
|
+
var sessions = new BoundedSessionMap(1000);
|
|
6196
|
+
function clearLkgRecoverySession(sessionId) {
|
|
6197
|
+
sessions.delete(sessionId);
|
|
6198
|
+
clearLkgFenceProcessState(sessionId);
|
|
8033
6199
|
}
|
|
8034
|
-
|
|
8035
|
-
|
|
8036
|
-
|
|
8037
|
-
var claimedRequests = new WeakSet;
|
|
8038
|
-
var captures = new BoundedSessionMap(1000);
|
|
8039
|
-
function clearCapturedLkgMeasurement(sessionId) {
|
|
8040
|
-
captures.delete(sessionId);
|
|
6200
|
+
function noteLkgCapturedPrefix(sessionId) {
|
|
6201
|
+
if (!sessions.has(sessionId))
|
|
6202
|
+
sessions.set(sessionId, {});
|
|
8041
6203
|
}
|
|
8042
6204
|
|
|
8043
6205
|
// ../plugin/src/hooks/magic-context/lkg-slot.ts
|
|
@@ -8177,7 +6339,7 @@ var DIGEST_CHUNK_BYTES = 64 * 1024;
|
|
|
8177
6339
|
var digestChunk;
|
|
8178
6340
|
function lkgContentDigestFromFields(fields) {
|
|
8179
6341
|
lkgDigestsComputed += 1;
|
|
8180
|
-
const hash =
|
|
6342
|
+
const hash = createHash4("sha256");
|
|
8181
6343
|
digestChunk ??= Buffer.allocUnsafe(DIGEST_CHUNK_BYTES);
|
|
8182
6344
|
const chunk = digestChunk;
|
|
8183
6345
|
let offset = 0;
|
|
@@ -8240,7 +6402,7 @@ function legacyLkgDigestFromFields(fields) {
|
|
|
8240
6402
|
const value = typeof field === "symbol" ? field.description ?? "" : String(field);
|
|
8241
6403
|
key += `${typeof field}:${value.length}:${value}\x00`;
|
|
8242
6404
|
}
|
|
8243
|
-
return
|
|
6405
|
+
return createHash4("sha256").update(key).digest("base64url");
|
|
8244
6406
|
}
|
|
8245
6407
|
function legacyLkgContentDigest(message) {
|
|
8246
6408
|
const fields = flattenContentFields(withoutEmptyUserDiffSummary(message));
|
|
@@ -8355,6 +6517,7 @@ function captureSlot(sessionId, slot) {
|
|
|
8355
6517
|
lkgHeapHolder.entries.set(sessionId, entry);
|
|
8356
6518
|
totalBytes += bytes;
|
|
8357
6519
|
hydrationAttemptBySession.delete(sessionId);
|
|
6520
|
+
noteLkgCapturedPrefix(sessionId);
|
|
8358
6521
|
return true;
|
|
8359
6522
|
}
|
|
8360
6523
|
function installHydratedSlot(sessionId, slot) {
|
|
@@ -8442,6 +6605,7 @@ function getSlot(sessionId) {
|
|
|
8442
6605
|
return copySlotForRead(entry.slot);
|
|
8443
6606
|
}
|
|
8444
6607
|
function forgetInMemorySlot(sessionId) {
|
|
6608
|
+
clearLkgRecoverySession(sessionId);
|
|
8445
6609
|
const entry = lkgHeapHolder.entries.get(sessionId);
|
|
8446
6610
|
if (entry) {
|
|
8447
6611
|
lkgHeapHolder.entries.delete(sessionId);
|
|
@@ -9726,7 +7890,7 @@ function formatNoteNudge(args) {
|
|
|
9726
7890
|
}
|
|
9727
7891
|
|
|
9728
7892
|
// ../plugin/src/shared/prompt-surface-runtime.ts
|
|
9729
|
-
import { existsSync as existsSync5, readFileSync as
|
|
7893
|
+
import { existsSync as existsSync5, readFileSync as readFileSync7, statSync as statSync5 } from "node:fs";
|
|
9730
7894
|
import { dirname as dirname4, isAbsolute as isAbsolute3, resolve as resolve3 } from "node:path";
|
|
9731
7895
|
|
|
9732
7896
|
// ../plugin/src/tools/light-descriptions.ts
|
|
@@ -9794,7 +7958,7 @@ function createPromptSurfaceRuntime(options) {
|
|
|
9794
7958
|
warnOnce(`guidance-not-file:${path}`, `prompt_surface.guidance_override_path (${path}) is not a file; using built-in guidance.`);
|
|
9795
7959
|
return;
|
|
9796
7960
|
}
|
|
9797
|
-
content =
|
|
7961
|
+
content = readFileSync7(path, "utf8");
|
|
9798
7962
|
} catch (error) {
|
|
9799
7963
|
const reason = error instanceof Error ? error.message : String(error);
|
|
9800
7964
|
warnOnce(`guidance-unreadable:${path}:${reason}`, `prompt_surface.guidance_override_path (${path}) could not be read (${reason}); using built-in guidance.`);
|
|
@@ -9869,7 +8033,7 @@ function createPromptSurfaceGuidanceEpochCache(runtime) {
|
|
|
9869
8033
|
}
|
|
9870
8034
|
|
|
9871
8035
|
// src/read-session-pi.ts
|
|
9872
|
-
import { createHash as
|
|
8036
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
9873
8037
|
var SYNTH_USER_ID_PREFIX = "synth-user-";
|
|
9874
8038
|
function resolvePiStableId(msg, index, entryIds, entryIdByRef) {
|
|
9875
8039
|
if (!msg || typeof msg !== "object")
|
|
@@ -9908,7 +8072,7 @@ function piContentFallbackIds(messages, resolveReal) {
|
|
|
9908
8072
|
return;
|
|
9909
8073
|
const m = message;
|
|
9910
8074
|
const role = typeof m.role === "string" ? m.role : "unknown";
|
|
9911
|
-
const digest =
|
|
8075
|
+
const digest = createHash5("sha256").update(stableStringify([
|
|
9912
8076
|
typeof m.responseId === "string" ? m.responseId : null,
|
|
9913
8077
|
typeof m.timestamp === "number" || typeof m.timestamp === "string" ? m.timestamp : null,
|
|
9914
8078
|
role,
|
|
@@ -10702,7 +8866,7 @@ function takeCurateSafetyRefusalCount(sessionId) {
|
|
|
10702
8866
|
}
|
|
10703
8867
|
|
|
10704
8868
|
// ../plugin/src/features/magic-context/smart-notes/wake-plane.ts
|
|
10705
|
-
import { join as
|
|
8869
|
+
import { join as join4 } from "node:path";
|
|
10706
8870
|
var WAKE_PLANE_CAPABILITY = "wake.create";
|
|
10707
8871
|
var WAKE_PLANE_STATUS_TTL_MS = 5 * 60 * 1000;
|
|
10708
8872
|
var WAKE_PLANE_HANDSHAKE_TIMEOUT_MS = 2000;
|
|
@@ -10711,7 +8875,7 @@ var inFlightProbe = null;
|
|
|
10711
8875
|
var catalogProbe = probeWakePlaneCatalog;
|
|
10712
8876
|
var now = () => Date.now();
|
|
10713
8877
|
function connectionFile() {
|
|
10714
|
-
return
|
|
8878
|
+
return join4(getDataDir(), "cortexkit", "run", "subc-connection.json");
|
|
10715
8879
|
}
|
|
10716
8880
|
async function probeWakePlaneCatalog() {
|
|
10717
8881
|
const file = connectionFile();
|
|
@@ -10762,7 +8926,7 @@ async function wakePlaneStatus() {
|
|
|
10762
8926
|
import { statSync as statSync6 } from "node:fs";
|
|
10763
8927
|
|
|
10764
8928
|
// ../plugin/src/plugin/embedding-bootstrap-helpers.ts
|
|
10765
|
-
import { createHash as
|
|
8929
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
10766
8930
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
10767
8931
|
"embedding.api_key",
|
|
10768
8932
|
"embedding.endpoint",
|
|
@@ -10810,7 +8974,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
10810
8974
|
];
|
|
10811
8975
|
var loggedFailureSignatures = new Map;
|
|
10812
8976
|
function sha256Prefix(value, length = 16) {
|
|
10813
|
-
return
|
|
8977
|
+
return createHash6("sha256").update(value).digest("hex").slice(0, length);
|
|
10814
8978
|
}
|
|
10815
8979
|
function warningLooksEmbeddingRelated(message) {
|
|
10816
8980
|
const lower = message.toLowerCase();
|
|
@@ -11174,6 +9338,7 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
|
|
|
11174
9338
|
const agentMigrated = migrateLegacyAgentEnabledInMemory(configToMigrate, preMigrationWarnings);
|
|
11175
9339
|
const migratedExperimental = migrateLegacyExperimental(agentMigrated, preMigrationWarnings);
|
|
11176
9340
|
warnDeprecatedMuralModel(migratedExperimental, preMigrationWarnings);
|
|
9341
|
+
warnDeprecatedWindowOverlayPath(migratedExperimental, preMigrationWarnings);
|
|
11177
9342
|
const migrated = migrateDreamerV2(migratedExperimental, preMigrationWarnings);
|
|
11178
9343
|
const parsed = MagicContextConfigSchema.safeParse(migrated);
|
|
11179
9344
|
if (parsed.success) {
|
|
@@ -11416,7 +9581,6 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
|
|
|
11416
9581
|
parsed.config.profile = profileResolution.activeProfile;
|
|
11417
9582
|
if (applyRuntimeGlobals) {
|
|
11418
9583
|
setOutputReserveConfig(parsed.config.output_reserve);
|
|
11419
|
-
setWindowOverlayPath(parsed.config.models?.window_overlay_path);
|
|
11420
9584
|
}
|
|
11421
9585
|
warnings.push(...parsed.warnings.map((warning) => `[merged config] ${warning}`));
|
|
11422
9586
|
const substitutionFailures = loadedFiles.flatMap(bindSubstitutionFailures);
|
|
@@ -11542,8 +9706,8 @@ async function ensureProjectRegisteredFromPiDirectory(directory, db) {
|
|
|
11542
9706
|
}
|
|
11543
9707
|
|
|
11544
9708
|
// src/pi-harness-kind.ts
|
|
11545
|
-
import { existsSync as existsSync7, readFileSync as
|
|
11546
|
-
import { dirname as dirname5, join as
|
|
9709
|
+
import { existsSync as existsSync7, readFileSync as readFileSync8, realpathSync as realpathSync2 } from "node:fs";
|
|
9710
|
+
import { dirname as dirname5, join as join5, parse as parse3, resolve as resolve4 } from "node:path";
|
|
11547
9711
|
import { pathToFileURL } from "node:url";
|
|
11548
9712
|
var OMP_UTILS_MODULE = "@oh-my-pi/pi-utils";
|
|
11549
9713
|
var OMP_HOST_PACKAGE = "@oh-my-pi/pi-coding-agent";
|
|
@@ -11575,7 +9739,7 @@ function hostEntries() {
|
|
|
11575
9739
|
}
|
|
11576
9740
|
function readPackageJson(path) {
|
|
11577
9741
|
try {
|
|
11578
|
-
return JSON.parse(
|
|
9742
|
+
return JSON.parse(readFileSync8(path, "utf8"));
|
|
11579
9743
|
} catch {
|
|
11580
9744
|
return;
|
|
11581
9745
|
}
|
|
@@ -11584,7 +9748,7 @@ function nearestPackageName(entryPath) {
|
|
|
11584
9748
|
let directory = dirname5(entryPath);
|
|
11585
9749
|
const root = parse3(directory).root;
|
|
11586
9750
|
while (true) {
|
|
11587
|
-
const packagePath =
|
|
9751
|
+
const packagePath = join5(directory, "package.json");
|
|
11588
9752
|
if (existsSync7(packagePath)) {
|
|
11589
9753
|
const name = readPackageJson(packagePath)?.name;
|
|
11590
9754
|
return typeof name === "string" ? name : undefined;
|
|
@@ -11611,8 +9775,8 @@ function dependencyPackageRoot(entryPath, moduleName) {
|
|
|
11611
9775
|
let directory = dirname5(entryPath);
|
|
11612
9776
|
const root = parse3(directory).root;
|
|
11613
9777
|
while (true) {
|
|
11614
|
-
const packageRoot =
|
|
11615
|
-
if (existsSync7(
|
|
9778
|
+
const packageRoot = join5(directory, "node_modules", ...moduleParts);
|
|
9779
|
+
if (existsSync7(join5(packageRoot, "package.json")))
|
|
11616
9780
|
return packageRoot;
|
|
11617
9781
|
if (directory === root)
|
|
11618
9782
|
return;
|
|
@@ -11635,7 +9799,7 @@ function hostModuleImportUrl(entryPath) {
|
|
|
11635
9799
|
const packageRoot = dependencyPackageRoot(entryPath, OMP_UTILS_MODULE);
|
|
11636
9800
|
if (!packageRoot)
|
|
11637
9801
|
return;
|
|
11638
|
-
const packageJson = readPackageJson(
|
|
9802
|
+
const packageJson = readPackageJson(join5(packageRoot, "package.json"));
|
|
11639
9803
|
const target = importTarget(packageJson?.exports) ?? (typeof packageJson?.module === "string" ? packageJson.module : typeof packageJson?.main === "string" ? packageJson.main : undefined);
|
|
11640
9804
|
if (!target?.startsWith("./"))
|
|
11641
9805
|
return;
|
|
@@ -11895,7 +10059,7 @@ function compareMemorySelectionPriority(left, right) {
|
|
|
11895
10059
|
}
|
|
11896
10060
|
|
|
11897
10061
|
// ../plugin/src/features/magic-context/mural/render-trigger.ts
|
|
11898
|
-
import { createHash as
|
|
10062
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
11899
10063
|
|
|
11900
10064
|
// ../plugin/src/features/magic-context/mural/mural-selection.ts
|
|
11901
10065
|
var DEFAULT_MURAL_MEMORY_BUDGET = 8000;
|
|
@@ -12584,7 +10748,7 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
|
|
|
12584
10748
|
return { ...cached.result };
|
|
12585
10749
|
}
|
|
12586
10750
|
const plan = planMuralRender(entries);
|
|
12587
|
-
const textHash =
|
|
10751
|
+
const textHash = createHash7("sha256").update(plan.layout.text).digest("hex");
|
|
12588
10752
|
if (existing && existing.contentHash === textHash && existing.width === plan.width && existing.height === plan.height) {
|
|
12589
10753
|
return rememberRender(db, projectIdentity, key, existing.image, {
|
|
12590
10754
|
hasMural: true,
|
|
@@ -12641,14 +10805,14 @@ function resolveMuralWire(db, projectIdentity, modelKey, enabled, budgetTokens =
|
|
|
12641
10805
|
}
|
|
12642
10806
|
|
|
12643
10807
|
// ../plugin/src/features/magic-context/compaction-marker.ts
|
|
12644
|
-
import { createHash as
|
|
10808
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
12645
10809
|
import { existsSync as existsSync8 } from "node:fs";
|
|
12646
10810
|
var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
12647
10811
|
var ID_PREFIX_HEX_LENGTH = 12;
|
|
12648
10812
|
var ID_SUFFIX_LENGTH = 14;
|
|
12649
10813
|
var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
|
|
12650
10814
|
function deterministicBase62(seed, length) {
|
|
12651
|
-
let value = BigInt(`0x${
|
|
10815
|
+
let value = BigInt(`0x${createHash8("sha256").update(seed).digest("hex")}`);
|
|
12652
10816
|
const chars = Array(length);
|
|
12653
10817
|
for (let index = length - 1;index >= 0; index -= 1) {
|
|
12654
10818
|
chars[index] = BASE62_CHARS[Number(value % 62n)];
|
|
@@ -14084,8 +12248,8 @@ function resolveCtxExpandMode(args, domain) {
|
|
|
14084
12248
|
}
|
|
14085
12249
|
|
|
14086
12250
|
// ../plugin/src/tools/ctx-expand/render.ts
|
|
14087
|
-
import { createHash as
|
|
14088
|
-
function
|
|
12251
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
12252
|
+
function isRecord3(value) {
|
|
14089
12253
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
14090
12254
|
}
|
|
14091
12255
|
function roleLabel(role) {
|
|
@@ -14097,7 +12261,7 @@ function roleLabel(role) {
|
|
|
14097
12261
|
}
|
|
14098
12262
|
function verboseRoleLabel(msg) {
|
|
14099
12263
|
if (msg.role === "user" && msg.parts.length > 0 && msg.parts.every((part) => {
|
|
14100
|
-
if (!
|
|
12264
|
+
if (!isRecord3(part))
|
|
14101
12265
|
return false;
|
|
14102
12266
|
if (part.type === "tool_result")
|
|
14103
12267
|
return true;
|
|
@@ -14125,15 +12289,15 @@ function keyArg(input) {
|
|
|
14125
12289
|
function asToolPart(part) {
|
|
14126
12290
|
const type = typeof part.type === "string" ? part.type : "";
|
|
14127
12291
|
if (type === "tool") {
|
|
14128
|
-
const state =
|
|
12292
|
+
const state = isRecord3(part.state) ? part.state : null;
|
|
14129
12293
|
const output = state && typeof state.output === "string" ? state.output : state && state.output != null ? JSON.stringify(state.output) : null;
|
|
14130
|
-
const metadata = state &&
|
|
12294
|
+
const metadata = state && isRecord3(state.metadata) ? state.metadata : null;
|
|
14131
12295
|
const title = state && typeof state.title === "string" && state.title || metadata && typeof metadata.title === "string" && metadata.title || null;
|
|
14132
12296
|
return {
|
|
14133
12297
|
name: typeof part.tool === "string" ? part.tool : "tool",
|
|
14134
12298
|
callId: typeof part.callID === "string" ? part.callID : "",
|
|
14135
12299
|
title,
|
|
14136
|
-
input: state &&
|
|
12300
|
+
input: state && isRecord3(state.input) ? state.input : null,
|
|
14137
12301
|
output
|
|
14138
12302
|
};
|
|
14139
12303
|
}
|
|
@@ -14142,7 +12306,7 @@ function asToolPart(part) {
|
|
|
14142
12306
|
name: typeof part.name === "string" ? part.name : "tool",
|
|
14143
12307
|
callId: typeof part.id === "string" ? part.id : "",
|
|
14144
12308
|
title: null,
|
|
14145
|
-
input:
|
|
12309
|
+
input: isRecord3(part.input) ? part.input : null,
|
|
14146
12310
|
output: null
|
|
14147
12311
|
};
|
|
14148
12312
|
}
|
|
@@ -14171,7 +12335,7 @@ function reasoningOf(part) {
|
|
|
14171
12335
|
return null;
|
|
14172
12336
|
}
|
|
14173
12337
|
function renderPartPreview(part, expandTools) {
|
|
14174
|
-
if (!
|
|
12338
|
+
if (!isRecord3(part))
|
|
14175
12339
|
return null;
|
|
14176
12340
|
const expansion = expandToolPart(part, expandTools, true);
|
|
14177
12341
|
if (expansion !== null)
|
|
@@ -14198,7 +12362,7 @@ function renderPartPreview(part, expandTools) {
|
|
|
14198
12362
|
return ` • [${type}]`;
|
|
14199
12363
|
}
|
|
14200
12364
|
function renderPartFull(part) {
|
|
14201
|
-
if (!
|
|
12365
|
+
if (!isRecord3(part))
|
|
14202
12366
|
return null;
|
|
14203
12367
|
const text = textOf(part);
|
|
14204
12368
|
if (text !== null) {
|
|
@@ -14285,11 +12449,11 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
14285
12449
|
const message = readRawSessionMessageById2(sessionId, owner);
|
|
14286
12450
|
if (!message)
|
|
14287
12451
|
return `Tag ${number}'s original tool owner is no longer in stored history.`;
|
|
14288
|
-
const parts = message?.parts.filter((part) =>
|
|
14289
|
-
if (!parts.some((part) =>
|
|
12452
|
+
const parts = message?.parts.filter((part) => isRecord3(part) && asToolPart(part)?.callId === tag.messageId) ?? [];
|
|
12453
|
+
if (!parts.some((part) => isRecord3(part) && asToolPart(part)?.output !== null)) {
|
|
14290
12454
|
visitRawSessionMessages2(sessionId, message.ordinal + 1, Number.MAX_SAFE_INTEGER, (candidate) => {
|
|
14291
|
-
const matching = candidate.parts.filter((part) =>
|
|
14292
|
-
if (matching.some((part) =>
|
|
12455
|
+
const matching = candidate.parts.filter((part) => isRecord3(part) && asToolPart(part)?.callId === tag.messageId);
|
|
12456
|
+
if (matching.some((part) => isRecord3(part) && part.type === "tool_use"))
|
|
14293
12457
|
return false;
|
|
14294
12458
|
parts.push(...matching);
|
|
14295
12459
|
return matching.length === 0;
|
|
@@ -14306,9 +12470,9 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
|
|
|
14306
12470
|
if (!message)
|
|
14307
12471
|
return `Tag ${number}'s original text is no longer in stored history.`;
|
|
14308
12472
|
const index = scoped ? Number(scoped[2]) : 0;
|
|
14309
|
-
const piText = message.parts.filter((part) =>
|
|
12473
|
+
const piText = message.parts.filter((part) => isRecord3(part) && part.type === "text");
|
|
14310
12474
|
const part = message.parts[index];
|
|
14311
|
-
const matching = derived ? piText.filter((part) =>
|
|
12475
|
+
const matching = derived ? piText.filter((part) => isRecord3(part) && typeof part.text === "string" && createHash9("sha256").update(part.text).digest("hex") === derived[3]) : [];
|
|
14312
12476
|
const selected = derived ? matching[Number(derived[4])] : textIndexDomain === "text" ? piText[index] : part;
|
|
14313
12477
|
return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
|
|
14314
12478
|
}
|
|
@@ -15390,9 +13554,9 @@ import { existsSync as existsSync9 } from "node:fs";
|
|
|
15390
13554
|
import { isAbsolute as isAbsolute5 } from "node:path";
|
|
15391
13555
|
|
|
15392
13556
|
// ../retina-local-fs/src/path-fence.ts
|
|
15393
|
-
import { lstat,
|
|
13557
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
15394
13558
|
import { homedir as homedir3 } from "node:os";
|
|
15395
|
-
import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as
|
|
13559
|
+
import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute4, join as join6, relative, resolve as resolve5, sep } from "node:path";
|
|
15396
13560
|
|
|
15397
13561
|
// ../retina-local-fs/src/errors.ts
|
|
15398
13562
|
class ProviderError extends Error {
|
|
@@ -15407,7 +13571,7 @@ class ProviderError extends Error {
|
|
|
15407
13571
|
// ../retina-local-fs/src/path-fence.ts
|
|
15408
13572
|
async function resolveAndFenceProviderPath(configuredPath, options) {
|
|
15409
13573
|
const { home, dataDirectory, aliases } = await resolveFenceRoots(options);
|
|
15410
|
-
const expanded = configuredPath.startsWith("~/") ?
|
|
13574
|
+
const expanded = configuredPath.startsWith("~/") ? join6(home, configuredPath.slice(2)) : configuredPath === "~" ? home : configuredPath;
|
|
15411
13575
|
const absolute = isAbsolute4(expanded) ? resolve5(expanded) : resolve5(options.cwd ?? process.cwd(), expanded);
|
|
15412
13576
|
const canonical = await canonicalPath(absolute, options.allowMissing);
|
|
15413
13577
|
if (fenceCandidates(canonical, aliases).some((candidate) => isFencedPath(candidate, home, dataDirectory))) {
|
|
@@ -15424,13 +13588,13 @@ async function resolveFenceRoots(options) {
|
|
|
15424
13588
|
} catch (error) {
|
|
15425
13589
|
throw fsError(configuredHomePath, error);
|
|
15426
13590
|
}
|
|
15427
|
-
const configuredDataDirectory = resolve5(options.dataDirectory ?? process.env.XDG_DATA_HOME ??
|
|
13591
|
+
const configuredDataDirectory = resolve5(options.dataDirectory ?? process.env.XDG_DATA_HOME ?? join6(home, ".local", "share"));
|
|
15428
13592
|
const dataDirectory = await canonicalPath(configuredDataDirectory, true);
|
|
15429
13593
|
const aliases = [];
|
|
15430
|
-
const logicalCortexkit =
|
|
13594
|
+
const logicalCortexkit = join6(dataDirectory, "cortexkit");
|
|
15431
13595
|
for (const logical of [
|
|
15432
13596
|
logicalCortexkit,
|
|
15433
|
-
...FENCED_CORTEXKIT_ROOTS.map((root) =>
|
|
13597
|
+
...FENCED_CORTEXKIT_ROOTS.map((root) => join6(logicalCortexkit, root))
|
|
15434
13598
|
]) {
|
|
15435
13599
|
const canonical = await canonicalPath(logical, true);
|
|
15436
13600
|
if (canonical !== logical)
|
|
@@ -15444,7 +13608,7 @@ function fenceCandidates(canonical, aliases) {
|
|
|
15444
13608
|
const relativeToAlias = relative(alias.canonical, canonical);
|
|
15445
13609
|
const inside = relativeToAlias === "" || relativeToAlias !== ".." && !relativeToAlias.startsWith(`..${sep}`) && !isAbsolute4(relativeToAlias);
|
|
15446
13610
|
if (inside)
|
|
15447
|
-
candidates.push(
|
|
13611
|
+
candidates.push(join6(alias.logical, relativeToAlias));
|
|
15448
13612
|
}
|
|
15449
13613
|
return candidates;
|
|
15450
13614
|
}
|
|
@@ -15458,18 +13622,16 @@ async function canonicalPath(path, allowMissing) {
|
|
|
15458
13622
|
const suffix = [];
|
|
15459
13623
|
let candidate = path;
|
|
15460
13624
|
while (true) {
|
|
13625
|
+
let symbolicLink = false;
|
|
15461
13626
|
try {
|
|
15462
|
-
|
|
15463
|
-
if (metadata.isSymbolicLink()) {
|
|
15464
|
-
const target = await readlink(candidate);
|
|
15465
|
-
const resolvedTarget = resolve5(dirname6(candidate), target);
|
|
15466
|
-
return canonicalPath(join7(resolvedTarget, ...suffix), true);
|
|
15467
|
-
}
|
|
13627
|
+
symbolicLink = (await lstat(candidate)).isSymbolicLink();
|
|
15468
13628
|
} catch (candidateError) {
|
|
15469
13629
|
if (!isMissingError(candidateError)) {
|
|
15470
13630
|
throw fsError(path, candidateError);
|
|
15471
13631
|
}
|
|
15472
13632
|
}
|
|
13633
|
+
if (symbolicLink)
|
|
13634
|
+
throw fsError(path, error);
|
|
15473
13635
|
const parent = dirname6(candidate);
|
|
15474
13636
|
if (parent === candidate) {
|
|
15475
13637
|
throw fsError(path, error);
|
|
@@ -15477,7 +13639,7 @@ async function canonicalPath(path, allowMissing) {
|
|
|
15477
13639
|
suffix.unshift(basename3(candidate));
|
|
15478
13640
|
candidate = parent;
|
|
15479
13641
|
try {
|
|
15480
|
-
return
|
|
13642
|
+
return join6(await realpath(candidate), ...suffix);
|
|
15481
13643
|
} catch (parentError) {
|
|
15482
13644
|
if (!isMissingError(parentError)) {
|
|
15483
13645
|
throw fsError(path, parentError);
|
|
@@ -15486,8 +13648,8 @@ async function canonicalPath(path, allowMissing) {
|
|
|
15486
13648
|
}
|
|
15487
13649
|
}
|
|
15488
13650
|
}
|
|
15489
|
-
function isFencedPath(canonicalPath, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ??
|
|
15490
|
-
const cortexkitRoot =
|
|
13651
|
+
function isFencedPath(canonicalPath, homeDirectory, dataDirectory = process.env.XDG_DATA_HOME ?? join6(resolve5(homeDirectory), ".local", "share")) {
|
|
13652
|
+
const cortexkitRoot = join6(resolve5(dataDirectory), "cortexkit");
|
|
15491
13653
|
const relativeToCortexkit = relative(cortexkitRoot, canonicalPath);
|
|
15492
13654
|
const insideCortexkit = relativeToCortexkit !== "" && relativeToCortexkit !== ".." && !relativeToCortexkit.startsWith(`..${sep}`) && !isAbsolute4(relativeToCortexkit);
|
|
15493
13655
|
const parts = insideCortexkit ? relativeToCortexkit.split(sep) : [];
|
|
@@ -16243,9 +14405,15 @@ Stamp: file reads, search results and tool outputs the work ahead no longer need
|
|
|
16243
14405
|
Keep: user messages (never stamp one for its directive), your own conversation text, unresolved errors, raw evidence you haven't extracted yet, and outputs whose exact wording may still matter.
|
|
16244
14406
|
|
|
16245
14407
|
Look at each tag before stamping it; never blanket-stamp a range like "1-50". Many small targeted stamps beat one sweep. \`drop\` accepts "3-5", "1,2,9", "1-5,8,12-15".`;
|
|
16246
|
-
|
|
16247
|
-
|
|
16248
|
-
|
|
14408
|
+
function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
|
|
14409
|
+
const parts = [];
|
|
14410
|
+
if (stampedCount > 0) {
|
|
14411
|
+
parts.push(`${stampedCount} tag${stampedCount === 1 ? "" : "s"} stamped.`);
|
|
14412
|
+
}
|
|
14413
|
+
if (selfStampCount > 0) {
|
|
14414
|
+
parts.push(selfStampCount === 1 ? "1 was a ctx_reduce call; leave those alone, they are cleaned up automatically." : `${selfStampCount} were ctx_reduce calls; leave those alone, they are cleaned up automatically.`);
|
|
14415
|
+
}
|
|
14416
|
+
return parts.join(" ");
|
|
16249
14417
|
}
|
|
16250
14418
|
|
|
16251
14419
|
// src/tools/ctx-reduce.ts
|
|
@@ -16293,17 +14461,8 @@ function createCtxReduceTool(deps) {
|
|
|
16293
14461
|
return err4(`Error: Unknown tag(s) ${formatIds(unknownIds)}. Check available tags in conversation.`);
|
|
16294
14462
|
}
|
|
16295
14463
|
const ctxReduceSelfStampIds = new Set(allTags.filter((tag) => tag.toolName?.toLowerCase() === "ctx_reduce").map((tag) => tag.tagNumber));
|
|
16296
|
-
const
|
|
14464
|
+
const ctxReduceSelfStampCount = new Set(dropIds.filter((id) => ctxReduceSelfStampIds.has(id))).size;
|
|
16297
14465
|
dropIds = dropIds.filter((id) => !ctxReduceSelfStampIds.has(id));
|
|
16298
|
-
const activeTags = allTags.filter((tag) => tag.status === "active");
|
|
16299
|
-
const effectiveFloor = readEpochFloorSnapshot(deps.db, sessionId) ?? deps.resolveFloor?.(ctx) ?? deps.floor ?? deps.protectedTokens ?? 16000;
|
|
16300
|
-
const windowResult = getProtectionWindowForSession(deps.db, sessionId, effectiveFloor);
|
|
16301
|
-
const hasToolTags = allTags.some((t) => t.type === "tool");
|
|
16302
|
-
const windowSet = hasToolTags ? windowResult.tagNumberSet.tagNumbers : typeof deps.protectedTags === "number" && deps.protectedTags > 0 ? new Set(activeTags.map((tag) => tag.tagNumber).sort((left, right) => right - left).slice(0, deps.protectedTags)) : new Set;
|
|
16303
|
-
const protectedSet = new Set([
|
|
16304
|
-
...windowSet,
|
|
16305
|
-
...protectedToolTagNumbers(activeTags, deps.resolveProtectedTools?.(ctx) ?? deps.protectedTools)
|
|
16306
|
-
]);
|
|
16307
14466
|
const tagStatusMap = new Map(allTags.map((tag) => [tag.tagNumber, tag.status]));
|
|
16308
14467
|
const inertWhitespaceTagNumbers = new Set(getInertWhitespaceAssistantTagsByNumbers2(deps.db, sessionId, dropIds).map((tag) => tag.tagNumber));
|
|
16309
14468
|
const inertDropIds = [
|
|
@@ -16321,26 +14480,15 @@ function createCtxReduceTool(deps) {
|
|
|
16321
14480
|
if (conflicts.length > 0) {
|
|
16322
14481
|
return err4(`Error: Conflicting operations — ${conflicts.join("; ")}.`);
|
|
16323
14482
|
}
|
|
16324
|
-
const
|
|
16325
|
-
...new Set(dropIds.filter((id) => tagStatusMap.get(id) === "dropped"))
|
|
16326
|
-
];
|
|
16327
|
-
const alreadyQueued = [
|
|
16328
|
-
...new Set(dropIds.filter((id) => tagStatusMap.get(id) !== "dropped" && pendingMap.get(id) === "drop"))
|
|
16329
|
-
];
|
|
16330
|
-
const skippedNote = [
|
|
16331
|
-
alreadyDropped.length ? `Already dropped: ${formatIds(alreadyDropped)}.` : "",
|
|
16332
|
-
alreadyQueued.length ? `Already queued: ${formatIds(alreadyQueued)}.` : ""
|
|
16333
|
-
].filter(Boolean).join(" ");
|
|
14483
|
+
const stampedCount = new Set(dropIds.filter((id) => !inertWhitespaceTagNumbers.has(id))).size;
|
|
16334
14484
|
dropIds = dropIds.filter((id) => !inertWhitespaceTagNumbers.has(id) && tagStatusMap.get(id) !== "dropped" && pendingMap.get(id) !== "drop");
|
|
16335
14485
|
if (dropIds.length === 0) {
|
|
16336
|
-
const
|
|
16337
|
-
|
|
16338
|
-
inertNote
|
|
16339
|
-
|
|
16340
|
-
|
|
16341
|
-
|
|
16342
|
-
noActionNotes.push("No new action is needed.");
|
|
16343
|
-
return ok4(noActionNotes.join(" "));
|
|
14486
|
+
const reply = formatCtxReduceReply(stampedCount, ctxReduceSelfStampCount);
|
|
14487
|
+
if (reply)
|
|
14488
|
+
return ok4(`${reply}${inertNote ? ` ${inertNote}` : ""}`);
|
|
14489
|
+
if (inertNote)
|
|
14490
|
+
return ok4(inertNote);
|
|
14491
|
+
return ok4("No new action is needed.");
|
|
16344
14492
|
}
|
|
16345
14493
|
try {
|
|
16346
14494
|
deps.db.transaction(() => {
|
|
@@ -16356,17 +14504,8 @@ function createCtxReduceTool(deps) {
|
|
|
16356
14504
|
updateSessionMeta(deps.db, sessionId, {
|
|
16357
14505
|
lastNudgeTokens: currentInputTokens
|
|
16358
14506
|
});
|
|
16359
|
-
const
|
|
16360
|
-
|
|
16361
|
-
...new Set(dropIds.filter((id) => protectedSet.has(id)))
|
|
16362
|
-
];
|
|
16363
|
-
const parts = [];
|
|
16364
|
-
if (immediateDropIds.length > 0)
|
|
16365
|
-
parts.push(`drop ${formatIds(immediateDropIds)}`);
|
|
16366
|
-
if (deferredDropIds.length > 0)
|
|
16367
|
-
parts.push(`deferred drop ${formatIds(deferredDropIds)}`);
|
|
16368
|
-
const held = deferredDropIds.length === 1 ? `Held: §${deferredDropIds[0]} is inside the protected working set; it applies once newer work displaces it.` : deferredDropIds.length > 1 ? `Held: ${deferredDropIds.map((id) => `§${id}`).join(", ")} are inside the protected working set; they apply once newer work displaces them.` : "";
|
|
16369
|
-
return ok4(`Queued: ${parts.join(", ")}.${held ? ` ${held}` : ""}${skippedNote ? ` ${skippedNote}` : ""}${inertNote ? ` ${inertNote}` : ""}${ctxReduceSelfStampNote ? ` ${ctxReduceSelfStampNote}` : ""}`);
|
|
14507
|
+
const reply = formatCtxReduceReply(stampedCount, ctxReduceSelfStampCount);
|
|
14508
|
+
return ok4(`${reply}${inertNote ? ` ${inertNote}` : ""}`);
|
|
16370
14509
|
}
|
|
16371
14510
|
};
|
|
16372
14511
|
}
|
|
@@ -17183,4 +15322,4 @@ function registerMagicContextTools(pi, opts) {
|
|
|
17183
15322
|
}
|
|
17184
15323
|
}
|
|
17185
15324
|
|
|
17186
|
-
export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve,
|
|
15325
|
+
export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, embedPauseBySession, embedRunStateBySession, autoEmbedAttemptedBySession, autoEmbedIdentityBySession, invalidateAutoEmbedSession, getEmbedDrainUiStatus, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, 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, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, countHistorianRuns, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
|