-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.ts
More file actions
181 lines (167 loc) · 4.88 KB
/
context.ts
File metadata and controls
181 lines (167 loc) · 4.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import type { ISdk } from "iii-sdk";
import type { RetrievalIntent, Session } from "../types.js";
import { KV } from "../state/schema.js";
import type { StateKV } from "../state/kv.js";
import { logger } from "../logger.js";
import { retrieveRelevantBlocks } from "./retrieval-engine.js";
import { resolveSessionBranch } from "./session-branch.js";
import {
emptyContextForPressure,
getContextHotPathPressure,
} from "./hot-path-pressure.js";
type ContextResponse = {
context: string;
items: unknown[];
blocks: number;
tokens: number;
trace: unknown;
cache?: {
status: "hit" | "miss" | "coalesced";
ageMs?: number;
};
};
type ContextRequest = {
sessionId: string;
project?: string;
budget?: number;
query?: string;
intent?: RetrievalIntent;
files?: string[];
terms?: string[];
maxBlocks?: number;
};
const CODEX_PROJECT_SUFFIX = "/workspace/repos/codex";
const CODEX_CONTEXT_CACHE_TTL_MS = 2_000;
const codexContextCache = new Map<
string,
{ createdAt: number; value: ContextResponse }
>();
const codexContextInflight = new Map<string, Promise<ContextResponse>>();
function isCodexProject(project: string): boolean {
return project.endsWith(CODEX_PROJECT_SUFFIX);
}
function cacheableCodexContext(data: ContextRequest, project: string): boolean {
return (
isCodexProject(project) &&
data.intent !== "file_enrich" &&
!data.files?.length &&
!data.terms?.length
);
}
function contextCacheKey(
data: ContextRequest,
project: string,
branch: string | undefined,
budget: number,
): string {
return JSON.stringify({
project,
branch,
query: data.query || "",
intent: data.intent || "",
budget,
maxBlocks: data.maxBlocks || null,
});
}
function cloneContextResponse(
value: ContextResponse,
cache: ContextResponse["cache"],
): ContextResponse {
return {
...structuredClone(value),
cache,
};
}
export function registerContextFunction(
sdk: ISdk,
kv: StateKV,
tokenBudget: number,
): void {
sdk.registerFunction(
"mem::context",
async (data: ContextRequest) => {
const pressure = await getContextHotPathPressure(kv, {
ignoreDeferredQueue: data.intent === "manual_recall",
});
if (pressure) {
logger.warn("Context skipped under hot-path pressure", {
sessionId: data.sessionId,
intent: data.intent,
reason: pressure.reason,
});
return emptyContextForPressure(pressure);
}
const budget = data.budget || tokenBudget;
const session = await kv.get<Session>(KV.sessions, data.sessionId).catch(() => null);
const project = data.project || session?.project || "";
const branch = await resolveSessionBranch(kv, session);
const purpose = data.intent === "file_enrich" ? "enrich" : "context";
const cacheable = cacheableCodexContext(data, project);
const cacheKey = cacheable
? contextCacheKey(data, project, branch, budget)
: undefined;
if (cacheKey) {
const cached = codexContextCache.get(cacheKey);
if (cached && Date.now() - cached.createdAt <= CODEX_CONTEXT_CACHE_TTL_MS) {
return cloneContextResponse(cached.value, {
status: "hit",
ageMs: Date.now() - cached.createdAt,
});
}
const inflight = codexContextInflight.get(cacheKey);
if (inflight) {
const value = await inflight;
return cloneContextResponse(value, { status: "coalesced" });
}
}
const buildContext = async (): Promise<ContextResponse> => {
const result = await retrieveRelevantBlocks(kv, {
project,
sessionId: data.sessionId,
branch,
query: data.query,
intent: data.intent,
focusFiles: data.files || [],
focusConcepts: data.terms || [],
budget,
purpose,
maxBlocks: data.maxBlocks,
});
if (!result.context) {
logger.info("No context available", { project });
return {
context: "",
items: [],
blocks: 0,
tokens: 0,
trace: result.trace,
};
}
logger.info("Context generated", {
blocks: result.blocks.length,
tokens: result.tokens,
});
return {
context: result.context,
items: result.items,
blocks: result.blocks.length,
tokens: result.tokens,
trace: result.trace,
};
};
if (!cacheKey) return buildContext();
const pending = buildContext();
codexContextInflight.set(cacheKey, pending);
try {
const value = await pending;
codexContextCache.set(cacheKey, {
createdAt: Date.now(),
value,
});
return cloneContextResponse(value, { status: "miss" });
} finally {
codexContextInflight.delete(cacheKey);
}
},
);
}