@mnemonik/shared 7.51.0 → 7.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/claudeProxySettings.d.ts +45 -0
- package/dist/claudeProxySettings.d.ts.map +1 -0
- package/dist/claudeProxySettings.js +375 -0
- package/dist/claudeProxySettings.js.map +1 -0
- package/dist/contextBudget.d.ts +8 -3
- package/dist/contextBudget.d.ts.map +1 -1
- package/dist/contextBudget.js +19 -94
- package/dist/contextBudget.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/settingsIo.d.ts +22 -0
- package/dist/settingsIo.d.ts.map +1 -0
- package/dist/settingsIo.js +352 -0
- package/dist/settingsIo.js.map +1 -0
- package/package.json +1 -1
- package/src/claudeProxySettings.ts +505 -0
- package/src/contextBudget.ts +24 -103
- package/src/index.ts +2 -0
- package/src/settingsIo.ts +382 -0
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
import { dirname, join, resolve } from 'node:path';
|
|
2
|
+
import { chmod, mkdir } from 'node:fs/promises';
|
|
3
|
+
import {
|
|
4
|
+
atomicWriteText,
|
|
5
|
+
canonicalizeConfigTargets,
|
|
6
|
+
installerConfigLockPath,
|
|
7
|
+
readTextIfExists,
|
|
8
|
+
withFileLocks,
|
|
9
|
+
} from './settingsIo.js';
|
|
10
|
+
|
|
11
|
+
const PROXY_TOKEN_PATTERN = /^pxt_[a-f0-9]{32}$/;
|
|
12
|
+
|
|
13
|
+
export type ClaudeBaseUrlState = { kind: 'absent' } | { kind: 'value'; value: string };
|
|
14
|
+
|
|
15
|
+
export type ClaudeProxyStatus = 'on' | 'off' | 'custom' | 'not-paired' | 'invalid';
|
|
16
|
+
|
|
17
|
+
export interface ClaudeProxySettingsOptions {
|
|
18
|
+
homeDir?: string;
|
|
19
|
+
settingsPath?: string;
|
|
20
|
+
configPath?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type ClaudeProxyPairingConfig = Record<string, unknown> & {
|
|
24
|
+
server: string;
|
|
25
|
+
proxyToken: string;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export interface ClaudeProxyMutationResult {
|
|
29
|
+
changed: boolean;
|
|
30
|
+
handoffCleanupUnconfirmed: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ClaudeProxyOffResult extends ClaudeProxyMutationResult {
|
|
34
|
+
outcome: 'disabled' | 'already-off';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ClaudeProxyOnResult extends ClaudeProxyMutationResult {
|
|
38
|
+
outcome: 'enabled' | 'already-on';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface ClaudeProxyPaths {
|
|
42
|
+
settingsPath: string;
|
|
43
|
+
configPath: string;
|
|
44
|
+
lockPath: string;
|
|
45
|
+
configLockPath: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface ClaudeProxyBasePaths {
|
|
49
|
+
homeDir: string;
|
|
50
|
+
configPath: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface ParsedSettings {
|
|
54
|
+
raw: string | null;
|
|
55
|
+
value: Record<string, unknown>;
|
|
56
|
+
baseUrl: ClaudeBaseUrlState;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface PairedProxyConfig {
|
|
60
|
+
raw: string;
|
|
61
|
+
value: Record<string, unknown>;
|
|
62
|
+
server: string;
|
|
63
|
+
proxyToken: string;
|
|
64
|
+
previousProxyToken: string | null;
|
|
65
|
+
proxyUrl: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class ClaudeProxyConflictError extends Error {
|
|
69
|
+
constructor() {
|
|
70
|
+
super('Claude Code already has a base URL that does not match this paired device.');
|
|
71
|
+
this.name = 'ClaudeProxyConflictError';
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export class ClaudeProxySettingsError extends Error {
|
|
76
|
+
constructor() {
|
|
77
|
+
super('Claude settings are invalid or unreadable.');
|
|
78
|
+
this.name = 'ClaudeProxySettingsError';
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export class ClaudeProxyNotPairedError extends Error {
|
|
83
|
+
constructor() {
|
|
84
|
+
super('This device is not paired with Mnemonik. Run pairing first.');
|
|
85
|
+
this.name = 'ClaudeProxyNotPairedError';
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function resolveHomeDirectory(
|
|
90
|
+
env: Partial<Record<'HOME' | 'USERPROFILE', string | undefined>> = process.env
|
|
91
|
+
): string {
|
|
92
|
+
const home = env.HOME?.trim() || env.USERPROFILE?.trim();
|
|
93
|
+
if (!home) throw new ClaudeProxyNotPairedError();
|
|
94
|
+
return resolve(home);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function resolveBasePaths(options: ClaudeProxySettingsOptions): ClaudeProxyBasePaths {
|
|
98
|
+
const homeDir = resolve(options.homeDir ?? resolveHomeDirectory());
|
|
99
|
+
const configPath = resolve(options.configPath ?? join(homeDir, '.mnemonik', 'config.json'));
|
|
100
|
+
return { homeDir, configPath };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function resolvePaths(
|
|
104
|
+
options: ClaudeProxySettingsOptions,
|
|
105
|
+
basePaths = resolveBasePaths(options)
|
|
106
|
+
): Promise<ClaudeProxyPaths> {
|
|
107
|
+
const requestedSettingsPath = resolve(
|
|
108
|
+
options.settingsPath ?? join(basePaths.homeDir, '.claude', 'settings.json')
|
|
109
|
+
);
|
|
110
|
+
const [settingsPath, configPath] = await canonicalizeConfigTargets([
|
|
111
|
+
requestedSettingsPath,
|
|
112
|
+
basePaths.configPath,
|
|
113
|
+
]);
|
|
114
|
+
if (!settingsPath || !configPath) throw new ClaudeProxySettingsError();
|
|
115
|
+
const runtimeParent = join(basePaths.homeDir, '.mnemonik', 'hooks');
|
|
116
|
+
return {
|
|
117
|
+
settingsPath,
|
|
118
|
+
configPath,
|
|
119
|
+
lockPath: installerConfigLockPath(settingsPath, runtimeParent),
|
|
120
|
+
configLockPath: installerConfigLockPath(configPath, runtimeParent),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
125
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function parseSettingsRaw(raw: string | null): ParsedSettings {
|
|
129
|
+
if (raw === null) return { raw: null, value: {}, baseUrl: { kind: 'absent' } };
|
|
130
|
+
|
|
131
|
+
let parsed: unknown;
|
|
132
|
+
try {
|
|
133
|
+
parsed = JSON.parse(raw);
|
|
134
|
+
} catch {
|
|
135
|
+
throw new ClaudeProxySettingsError();
|
|
136
|
+
}
|
|
137
|
+
if (!isRecord(parsed)) throw new ClaudeProxySettingsError();
|
|
138
|
+
if (parsed.env === undefined) return { raw, value: parsed, baseUrl: { kind: 'absent' } };
|
|
139
|
+
if (!isRecord(parsed.env)) throw new ClaudeProxySettingsError();
|
|
140
|
+
const baseUrl = parsed.env.ANTHROPIC_BASE_URL;
|
|
141
|
+
if (baseUrl === undefined) return { raw, value: parsed, baseUrl: { kind: 'absent' } };
|
|
142
|
+
if (typeof baseUrl !== 'string' || baseUrl.length === 0) {
|
|
143
|
+
throw new ClaudeProxySettingsError();
|
|
144
|
+
}
|
|
145
|
+
return { raw, value: parsed, baseUrl: { kind: 'value', value: baseUrl } };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function readSettings(settingsPath: string): Promise<ParsedSettings> {
|
|
149
|
+
try {
|
|
150
|
+
return parseSettingsRaw(await readTextIfExists(settingsPath));
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (error instanceof ClaudeProxySettingsError) throw error;
|
|
153
|
+
throw new ClaudeProxySettingsError();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function buildClaudeProxyUrl(server: string, proxyToken: string): string {
|
|
158
|
+
const trimmedServer = server.trim();
|
|
159
|
+
if (!trimmedServer || !PROXY_TOKEN_PATTERN.test(proxyToken)) {
|
|
160
|
+
throw new ClaudeProxyNotPairedError();
|
|
161
|
+
}
|
|
162
|
+
const proxyUrl = `${trimmedServer.replace(/\/$/, '')}/proxy/${proxyToken}`;
|
|
163
|
+
try {
|
|
164
|
+
const parsed = new URL(proxyUrl);
|
|
165
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
166
|
+
throw new ClaudeProxyNotPairedError();
|
|
167
|
+
}
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (error instanceof ClaudeProxyNotPairedError) throw error;
|
|
170
|
+
throw new ClaudeProxyNotPairedError();
|
|
171
|
+
}
|
|
172
|
+
return proxyUrl;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function parsePairedProxyConfig(raw: string | null): PairedProxyConfig | null {
|
|
176
|
+
if (raw === null) return null;
|
|
177
|
+
let parsed: unknown;
|
|
178
|
+
try {
|
|
179
|
+
parsed = JSON.parse(raw);
|
|
180
|
+
} catch {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
if (!isRecord(parsed) || typeof parsed.server !== 'string') return null;
|
|
184
|
+
if (typeof parsed.proxyToken !== 'string') return null;
|
|
185
|
+
const previousProxyToken = parsed.previousProxyToken;
|
|
186
|
+
if (
|
|
187
|
+
previousProxyToken !== undefined &&
|
|
188
|
+
(typeof previousProxyToken !== 'string' || !PROXY_TOKEN_PATTERN.test(previousProxyToken))
|
|
189
|
+
) {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
const normalizedPreviousToken =
|
|
194
|
+
previousProxyToken && previousProxyToken !== parsed.proxyToken ? previousProxyToken : null;
|
|
195
|
+
return {
|
|
196
|
+
raw,
|
|
197
|
+
value: parsed,
|
|
198
|
+
server: parsed.server,
|
|
199
|
+
proxyToken: parsed.proxyToken,
|
|
200
|
+
previousProxyToken: normalizedPreviousToken,
|
|
201
|
+
proxyUrl: buildClaudeProxyUrl(parsed.server, parsed.proxyToken),
|
|
202
|
+
};
|
|
203
|
+
} catch {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function readPairedProxyConfig(configPath: string): Promise<PairedProxyConfig | null> {
|
|
209
|
+
try {
|
|
210
|
+
return parsePairedProxyConfig(await readTextIfExists(configPath));
|
|
211
|
+
} catch {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function managedProxyTokenForUrl(baseUrl: string, config: PairedProxyConfig): string | null {
|
|
217
|
+
if (matchesProxyUrlForToken(baseUrl, config.server, config.proxyToken)) {
|
|
218
|
+
return config.proxyToken;
|
|
219
|
+
}
|
|
220
|
+
if (
|
|
221
|
+
config.previousProxyToken &&
|
|
222
|
+
matchesProxyUrlForToken(baseUrl, config.server, config.previousProxyToken)
|
|
223
|
+
) {
|
|
224
|
+
return config.previousProxyToken;
|
|
225
|
+
}
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function matchesProxyUrlForToken(baseUrl: string, server: string, proxyToken: string): boolean {
|
|
230
|
+
return (
|
|
231
|
+
baseUrl === buildClaudeProxyUrl(server, proxyToken) ||
|
|
232
|
+
baseUrl === `${server}/proxy/${proxyToken}`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function matchesManagedProxyUrl(baseUrl: string, config: PairedProxyConfig): boolean {
|
|
237
|
+
return managedProxyTokenForUrl(baseUrl, config) !== null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function serializeConfig(config: Record<string, unknown>): string {
|
|
241
|
+
return `${JSON.stringify(config, null, 2)}\n`;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function clearPreviousProxyToken(
|
|
245
|
+
paths: ClaudeProxyPaths,
|
|
246
|
+
config: PairedProxyConfig,
|
|
247
|
+
expectedProxyToken: string
|
|
248
|
+
): Promise<void> {
|
|
249
|
+
if (config.proxyToken !== expectedProxyToken || config.previousProxyToken === null) return;
|
|
250
|
+
const nextConfig = { ...config.value };
|
|
251
|
+
delete nextConfig.previousProxyToken;
|
|
252
|
+
await atomicWriteText(paths.configPath, serializeConfig(nextConfig), config.raw, { mode: 0o600 });
|
|
253
|
+
await chmod(paths.configPath, 0o600);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function tryClearPreviousProxyToken(
|
|
257
|
+
paths: ClaudeProxyPaths,
|
|
258
|
+
config: PairedProxyConfig,
|
|
259
|
+
expectedProxyToken: string
|
|
260
|
+
): Promise<boolean> {
|
|
261
|
+
try {
|
|
262
|
+
await clearPreviousProxyToken(paths, config, expectedProxyToken);
|
|
263
|
+
return false;
|
|
264
|
+
} catch {
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function withProxyLocks<T>(paths: ClaudeProxyPaths, action: () => Promise<T>): Promise<T> {
|
|
270
|
+
return withFileLocks([paths.lockPath, paths.configLockPath], action);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function setBaseUrl(
|
|
274
|
+
settings: Record<string, unknown>,
|
|
275
|
+
next: ClaudeBaseUrlState
|
|
276
|
+
): Record<string, unknown> {
|
|
277
|
+
const updated = { ...settings };
|
|
278
|
+
if (next.kind === 'value') {
|
|
279
|
+
const env = isRecord(settings.env) ? { ...settings.env } : {};
|
|
280
|
+
env.ANTHROPIC_BASE_URL = next.value;
|
|
281
|
+
updated.env = env;
|
|
282
|
+
return updated;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (!isRecord(settings.env)) return updated;
|
|
286
|
+
const env = { ...settings.env };
|
|
287
|
+
delete env.ANTHROPIC_BASE_URL;
|
|
288
|
+
if (Object.keys(env).length === 0) delete updated.env;
|
|
289
|
+
else updated.env = env;
|
|
290
|
+
return updated;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function serializeSettings(settings: Record<string, unknown>): string {
|
|
294
|
+
return `${JSON.stringify(settings, null, 2)}\n`;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function writeBaseUrl(
|
|
298
|
+
settingsPath: string,
|
|
299
|
+
settings: ParsedSettings,
|
|
300
|
+
next: ClaudeBaseUrlState
|
|
301
|
+
): Promise<void> {
|
|
302
|
+
await atomicWriteText(
|
|
303
|
+
settingsPath,
|
|
304
|
+
serializeSettings(setBaseUrl(settings.value, next)),
|
|
305
|
+
settings.raw
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async function pairedConfigOrThrow(configPath: string): Promise<PairedProxyConfig> {
|
|
310
|
+
const config = await readPairedProxyConfig(configPath);
|
|
311
|
+
if (!config) throw new ClaudeProxyNotPairedError();
|
|
312
|
+
return config;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export async function stageClaudeProxyPairingConfig(
|
|
316
|
+
nextConfig: ClaudeProxyPairingConfig,
|
|
317
|
+
options: ClaudeProxySettingsOptions = {}
|
|
318
|
+
): Promise<void> {
|
|
319
|
+
const nextProxyUrl = buildClaudeProxyUrl(nextConfig.server, nextConfig.proxyToken);
|
|
320
|
+
const basePaths = resolveBasePaths(options);
|
|
321
|
+
await mkdir(dirname(basePaths.configPath), { recursive: true, mode: 0o700 });
|
|
322
|
+
await chmod(dirname(basePaths.configPath), 0o700);
|
|
323
|
+
const paths = await resolvePaths(options, basePaths);
|
|
324
|
+
await withProxyLocks(paths, async () => {
|
|
325
|
+
const currentRaw = await readTextIfExists(paths.configPath);
|
|
326
|
+
const currentConfig = parsePairedProxyConfig(currentRaw);
|
|
327
|
+
const settings = await readSettings(paths.settingsPath);
|
|
328
|
+
let previousProxyToken: string | null = null;
|
|
329
|
+
|
|
330
|
+
if (settings.baseUrl.kind === 'value') {
|
|
331
|
+
if (!currentConfig) throw new ClaudeProxyConflictError();
|
|
332
|
+
previousProxyToken = managedProxyTokenForUrl(settings.baseUrl.value, currentConfig);
|
|
333
|
+
if (!previousProxyToken) throw new ClaudeProxyConflictError();
|
|
334
|
+
if (settings.baseUrl.value === nextProxyUrl) {
|
|
335
|
+
previousProxyToken = null;
|
|
336
|
+
} else if (
|
|
337
|
+
!matchesProxyUrlForToken(settings.baseUrl.value, nextConfig.server, previousProxyToken)
|
|
338
|
+
) {
|
|
339
|
+
throw new ClaudeProxyConflictError();
|
|
340
|
+
} else if (previousProxyToken === nextConfig.proxyToken) {
|
|
341
|
+
previousProxyToken = null;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const serializedConfig = { ...nextConfig };
|
|
346
|
+
delete serializedConfig.previousProxyToken;
|
|
347
|
+
if (previousProxyToken) serializedConfig.previousProxyToken = previousProxyToken;
|
|
348
|
+
await atomicWriteText(paths.configPath, serializeConfig(serializedConfig), currentRaw, {
|
|
349
|
+
mode: 0o600,
|
|
350
|
+
});
|
|
351
|
+
await chmod(paths.configPath, 0o600);
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export async function assertClaudeProxyCanBeConfigured(
|
|
356
|
+
options: ClaudeProxySettingsOptions = {}
|
|
357
|
+
): Promise<void> {
|
|
358
|
+
const paths = await resolvePaths(options);
|
|
359
|
+
return withProxyLocks(paths, async () => {
|
|
360
|
+
const config = await readPairedProxyConfig(paths.configPath);
|
|
361
|
+
const settings = await readSettings(paths.settingsPath);
|
|
362
|
+
if (
|
|
363
|
+
settings.baseUrl.kind === 'value' &&
|
|
364
|
+
(!config || !matchesManagedProxyUrl(settings.baseUrl.value, config))
|
|
365
|
+
) {
|
|
366
|
+
throw new ClaudeProxyConflictError();
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export async function configureClaudeProxy(
|
|
372
|
+
server: string,
|
|
373
|
+
proxyToken: string,
|
|
374
|
+
options: ClaudeProxySettingsOptions = {}
|
|
375
|
+
): Promise<ClaudeProxyMutationResult> {
|
|
376
|
+
const proxyUrl = buildClaudeProxyUrl(server, proxyToken);
|
|
377
|
+
const paths = await resolvePaths(options);
|
|
378
|
+
return withProxyLocks(paths, async () => {
|
|
379
|
+
const config = await pairedConfigOrThrow(paths.configPath);
|
|
380
|
+
if (config.proxyToken !== proxyToken || config.proxyUrl !== proxyUrl) {
|
|
381
|
+
throw new ClaudeProxyConflictError();
|
|
382
|
+
}
|
|
383
|
+
const settings = await readSettings(paths.settingsPath);
|
|
384
|
+
let changed = false;
|
|
385
|
+
if (settings.baseUrl.kind === 'value') {
|
|
386
|
+
if (!matchesManagedProxyUrl(settings.baseUrl.value, config)) {
|
|
387
|
+
throw new ClaudeProxyConflictError();
|
|
388
|
+
}
|
|
389
|
+
if (settings.baseUrl.value !== proxyUrl) {
|
|
390
|
+
await writeBaseUrl(paths.settingsPath, settings, { kind: 'value', value: proxyUrl });
|
|
391
|
+
changed = true;
|
|
392
|
+
}
|
|
393
|
+
} else {
|
|
394
|
+
await writeBaseUrl(paths.settingsPath, settings, { kind: 'value', value: proxyUrl });
|
|
395
|
+
changed = true;
|
|
396
|
+
}
|
|
397
|
+
const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(paths, config, proxyToken);
|
|
398
|
+
return { changed, handoffCleanupUnconfirmed };
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export async function turnClaudeProxyOff(
|
|
403
|
+
options: ClaudeProxySettingsOptions = {}
|
|
404
|
+
): Promise<ClaudeProxyOffResult> {
|
|
405
|
+
const basePaths = resolveBasePaths(options);
|
|
406
|
+
await pairedConfigOrThrow(basePaths.configPath);
|
|
407
|
+
const paths = await resolvePaths(options, basePaths);
|
|
408
|
+
return withProxyLocks(paths, async () => {
|
|
409
|
+
const config = await pairedConfigOrThrow(paths.configPath);
|
|
410
|
+
const settings = await readSettings(paths.settingsPath);
|
|
411
|
+
if (settings.baseUrl.kind === 'absent') {
|
|
412
|
+
const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
|
|
413
|
+
paths,
|
|
414
|
+
config,
|
|
415
|
+
config.proxyToken
|
|
416
|
+
);
|
|
417
|
+
return { changed: false, outcome: 'already-off', handoffCleanupUnconfirmed };
|
|
418
|
+
}
|
|
419
|
+
if (!matchesManagedProxyUrl(settings.baseUrl.value, config)) {
|
|
420
|
+
throw new ClaudeProxyConflictError();
|
|
421
|
+
}
|
|
422
|
+
await writeBaseUrl(paths.settingsPath, settings, { kind: 'absent' });
|
|
423
|
+
const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
|
|
424
|
+
paths,
|
|
425
|
+
config,
|
|
426
|
+
config.proxyToken
|
|
427
|
+
);
|
|
428
|
+
return { changed: true, outcome: 'disabled', handoffCleanupUnconfirmed };
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export async function turnClaudeProxyOn(
|
|
433
|
+
options: ClaudeProxySettingsOptions = {}
|
|
434
|
+
): Promise<ClaudeProxyOnResult> {
|
|
435
|
+
const basePaths = resolveBasePaths(options);
|
|
436
|
+
await pairedConfigOrThrow(basePaths.configPath);
|
|
437
|
+
const paths = await resolvePaths(options, basePaths);
|
|
438
|
+
return withProxyLocks(paths, async () => {
|
|
439
|
+
const config = await pairedConfigOrThrow(paths.configPath);
|
|
440
|
+
const settings = await readSettings(paths.settingsPath);
|
|
441
|
+
if (settings.baseUrl.kind === 'value') {
|
|
442
|
+
if (settings.baseUrl.value === config.proxyUrl) {
|
|
443
|
+
const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
|
|
444
|
+
paths,
|
|
445
|
+
config,
|
|
446
|
+
config.proxyToken
|
|
447
|
+
);
|
|
448
|
+
return { changed: false, outcome: 'already-on', handoffCleanupUnconfirmed };
|
|
449
|
+
}
|
|
450
|
+
if (!matchesManagedProxyUrl(settings.baseUrl.value, config)) {
|
|
451
|
+
throw new ClaudeProxyConflictError();
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
await writeBaseUrl(paths.settingsPath, settings, {
|
|
455
|
+
kind: 'value',
|
|
456
|
+
value: config.proxyUrl,
|
|
457
|
+
});
|
|
458
|
+
const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
|
|
459
|
+
paths,
|
|
460
|
+
config,
|
|
461
|
+
config.proxyToken
|
|
462
|
+
);
|
|
463
|
+
return { changed: true, outcome: 'enabled', handoffCleanupUnconfirmed };
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export async function getClaudeProxyStatus(
|
|
468
|
+
options: ClaudeProxySettingsOptions = {}
|
|
469
|
+
): Promise<ClaudeProxyStatus> {
|
|
470
|
+
try {
|
|
471
|
+
const basePaths = resolveBasePaths(options);
|
|
472
|
+
if (!(await readPairedProxyConfig(basePaths.configPath))) return 'not-paired';
|
|
473
|
+
const paths = await resolvePaths(options, basePaths);
|
|
474
|
+
return await withProxyLocks(paths, async () => {
|
|
475
|
+
const config = await readPairedProxyConfig(paths.configPath);
|
|
476
|
+
if (!config) return 'not-paired';
|
|
477
|
+
const settings = await readSettings(paths.settingsPath);
|
|
478
|
+
if (settings.baseUrl.kind === 'absent') return 'off';
|
|
479
|
+
return matchesManagedProxyUrl(settings.baseUrl.value, config) ? 'on' : 'custom';
|
|
480
|
+
});
|
|
481
|
+
} catch {
|
|
482
|
+
return 'invalid';
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export function formatClaudeProxyStatus(status: ClaudeProxyStatus): string {
|
|
487
|
+
switch (status) {
|
|
488
|
+
case 'on':
|
|
489
|
+
return 'Mnemonik proxy is on and correctly configured.';
|
|
490
|
+
case 'off':
|
|
491
|
+
return 'Mnemonik proxy is off.';
|
|
492
|
+
case 'custom':
|
|
493
|
+
return 'Claude Code has a base URL that does not match this paired device.';
|
|
494
|
+
case 'not-paired':
|
|
495
|
+
return 'This device is not paired with Mnemonik.';
|
|
496
|
+
case 'invalid':
|
|
497
|
+
return 'Claude settings are invalid or unreadable.';
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export function formatClaudeProxyCleanupWarning(result: ClaudeProxyMutationResult): string | null {
|
|
502
|
+
return result.handoffCleanupUnconfirmed
|
|
503
|
+
? 'Mnemonik could not confirm cleanup of the saved token handoff. The next proxy-changing command will check and retry it.'
|
|
504
|
+
: null;
|
|
505
|
+
}
|
package/src/contextBudget.ts
CHANGED
|
@@ -7,12 +7,14 @@ export type ContextBudgetUnits = 'characters' | 'utf8-bytes';
|
|
|
7
7
|
export interface ContextBudgetItem {
|
|
8
8
|
/** Exact text emitted when the item fits in full. */
|
|
9
9
|
text: string;
|
|
10
|
-
/** Stable envelope name used
|
|
10
|
+
/** Stable envelope name used for diagnostics only. Never emitted as a retrieval stub. */
|
|
11
11
|
name: string;
|
|
12
12
|
/** Memory identity when this item is one pointer-terminated memory precis. */
|
|
13
13
|
memoryId?: string;
|
|
14
14
|
/** Memory identities when one rendered envelope represents several memories. */
|
|
15
15
|
memoryIds?: readonly string[];
|
|
16
|
+
/** Exact server-side call that can retrieve this emission after it is shed. */
|
|
17
|
+
retrievalRoute?: string;
|
|
16
18
|
}
|
|
17
19
|
|
|
18
20
|
export type ContextBudgetPiece = string | ContextBudgetItem;
|
|
@@ -20,12 +22,13 @@ export type ContextBudgetPiece = string | ContextBudgetItem;
|
|
|
20
22
|
export interface BudgetedContextFit {
|
|
21
23
|
value: string;
|
|
22
24
|
fullyDeliveredItems: number;
|
|
25
|
+
/** Retained for caller compatibility. Atomic shedding never sets it. */
|
|
23
26
|
partialItemIndex: number | null;
|
|
27
|
+
/** Retained for caller compatibility. Atomic shedding always returns zero. */
|
|
24
28
|
partialUnitsDelivered: number;
|
|
25
29
|
}
|
|
26
30
|
|
|
27
31
|
const JOINER = '\n\n';
|
|
28
|
-
const CONTINUATION_PREFIX = '… continues: ';
|
|
29
32
|
const NOT_REACHED_PREFIX = '… not reached: ';
|
|
30
33
|
|
|
31
34
|
function itemMemoryIds(item: ContextBudgetItem): readonly string[] {
|
|
@@ -33,19 +36,17 @@ function itemMemoryIds(item: ContextBudgetItem): readonly string[] {
|
|
|
33
36
|
return item.memoryId ? [item.memoryId] : [];
|
|
34
37
|
}
|
|
35
38
|
|
|
36
|
-
function
|
|
39
|
+
function retrievalRoutes(item: ContextBudgetItem): readonly string[] {
|
|
37
40
|
const memoryIds = itemMemoryIds(item);
|
|
38
|
-
if (memoryIds.length > 0) return memoryIds.map((id) => `memory_get ${id}`)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
function continuationPointer(item: ContextBudgetItem): string {
|
|
43
|
-
return `${CONTINUATION_PREFIX}${identity(item)}`;
|
|
41
|
+
if (memoryIds.length > 0) return memoryIds.map((id) => `memory_get ${id}`);
|
|
42
|
+
const route = item.retrievalRoute?.replace(/\s+/g, ' ').trim();
|
|
43
|
+
return route ? [route] : [];
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
function notReachedPointer(items: readonly ContextBudgetItem[]): string | null {
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
const routes = [...new Set(items.flatMap(retrievalRoutes))];
|
|
48
|
+
if (routes.length === 0) return null;
|
|
49
|
+
return `${NOT_REACHED_PREFIX}${routes.join(', ')}`;
|
|
49
50
|
}
|
|
50
51
|
|
|
51
52
|
function joinSections(sections: readonly (string | null)[]): string {
|
|
@@ -59,73 +60,11 @@ export function measureContext(text: string, units: ContextBudgetUnits = 'charac
|
|
|
59
60
|
return units === 'utf8-bytes' ? Buffer.byteLength(text, 'utf8') : text.length;
|
|
60
61
|
}
|
|
61
62
|
|
|
62
|
-
interface NaturalUnits {
|
|
63
|
-
prefix: string;
|
|
64
|
-
units: string[];
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function withoutTerminalMemoryPointer(item: ContextBudgetItem): string {
|
|
68
|
-
if (!item.memoryId) return item.text;
|
|
69
|
-
const terminalPointer = new RegExp(`\\s*${AMBIENT_ITEM_POINTER_SOURCE}\\s*$`);
|
|
70
|
-
return item.text.replace(terminalPointer, '').trimEnd();
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Prefer bullet lines whenever the item contains them. Text ahead of the first
|
|
75
|
-
* bullet is framing and travels with the first admitted fact. Otherwise each
|
|
76
|
-
* sentence (including a final sentence ending at end-of-item) is one unit.
|
|
77
|
-
*/
|
|
78
|
-
function naturalUnits(item: ContextBudgetItem): NaturalUnits {
|
|
79
|
-
const text = withoutTerminalMemoryPointer(item);
|
|
80
|
-
const bulletStarts: number[] = [];
|
|
81
|
-
const bulletPattern = /(^|\n)(?=[ \t]*(?:•|[-*])[ \t]+)/g;
|
|
82
|
-
let bulletMatch: RegExpExecArray | null;
|
|
83
|
-
while ((bulletMatch = bulletPattern.exec(text)) !== null) {
|
|
84
|
-
bulletStarts.push(bulletMatch.index + (bulletMatch[1] ?? '').length);
|
|
85
|
-
if (bulletPattern.lastIndex === bulletMatch.index) bulletPattern.lastIndex += 1;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// The validated-use clause is a factual unit of its own. Keeping its start
|
|
89
|
-
// beside bullet starts means a partial-memory fit emits the whole clause or
|
|
90
|
-
// none of it; the context boundary can never cut inside the count or date.
|
|
91
|
-
const trackStarts: number[] = [];
|
|
92
|
-
const trackPattern = /(^|\n)(?=\(acted on and validated \d+ times; last \d{4}-\d{2}-\d{2}\))/g;
|
|
93
|
-
let trackMatch: RegExpExecArray | null;
|
|
94
|
-
while ((trackMatch = trackPattern.exec(text)) !== null) {
|
|
95
|
-
trackStarts.push(trackMatch.index + (trackMatch[1] ?? '').length);
|
|
96
|
-
if (trackPattern.lastIndex === trackMatch.index) trackPattern.lastIndex += 1;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const explicitStarts = [...new Set([...bulletStarts, ...trackStarts])].sort((a, b) => a - b);
|
|
100
|
-
if (explicitStarts.length > 0) {
|
|
101
|
-
return {
|
|
102
|
-
prefix: text.slice(0, explicitStarts[0]),
|
|
103
|
-
units: explicitStarts.map((start, index) => text.slice(start, explicitStarts[index + 1])),
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const units: string[] = [];
|
|
108
|
-
const sentenceEnd = /[.!?](?:["')\]]*)?(?=\s|$)/g;
|
|
109
|
-
let cursor = 0;
|
|
110
|
-
let sentenceMatch: RegExpExecArray | null;
|
|
111
|
-
while ((sentenceMatch = sentenceEnd.exec(text)) !== null) {
|
|
112
|
-
const end = sentenceMatch.index + sentenceMatch[0].length;
|
|
113
|
-
units.push(text.slice(cursor, end));
|
|
114
|
-
cursor = end;
|
|
115
|
-
}
|
|
116
|
-
if (cursor < text.length) units.push(text.slice(cursor));
|
|
117
|
-
return { prefix: '', units: units.filter((unit) => unit.trim().length > 0) };
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function partialText(item: ContextBudgetItem, plan: NaturalUnits, count: number): string {
|
|
121
|
-
const content = `${plan.prefix}${plan.units.slice(0, count).join('')}`.trimEnd();
|
|
122
|
-
return `${content}\n${continuationPointer(item)}`;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
63
|
/**
|
|
126
64
|
* Compose ordered items within a fixed budget. Full items are emitted exactly;
|
|
127
|
-
* the first item that does not fit
|
|
128
|
-
*
|
|
65
|
+
* the first item that does not fit and every later item are shed. Shed items
|
|
66
|
+
* share one trailing marker containing only their explicit retrieval routes.
|
|
67
|
+
* Items without a route leave no agent-visible stub.
|
|
129
68
|
*/
|
|
130
69
|
export function fitContextItems(
|
|
131
70
|
items: readonly ContextBudgetItem[],
|
|
@@ -163,35 +102,17 @@ export function fitContextItems(
|
|
|
163
102
|
continue;
|
|
164
103
|
}
|
|
165
104
|
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
...suffix.map((entry) => entry.text),
|
|
173
|
-
notReachedPointer(later),
|
|
174
|
-
]);
|
|
175
|
-
if (measureContext(candidate, units) > opts.budget) break;
|
|
176
|
-
partialUnitsDelivered = count;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
// A one-fact excerpt reads as though it were the whole memory. Require two
|
|
180
|
-
// complete units before admitting a partial item; otherwise name it only.
|
|
181
|
-
const meaningfulMinimum = Math.min(2, plan.units.length);
|
|
182
|
-
const partialAccepted = partialUnitsDelivered >= meaningfulMinimum && partialUnitsDelivered > 0;
|
|
183
|
-
const partial = partialAccepted ? partialText(item, plan, partialUnitsDelivered) : null;
|
|
184
|
-
const unreached = partialAccepted ? later : items.slice(index);
|
|
105
|
+
const withoutPointer = joinSections([...accepted, ...suffix.map((entry) => entry.text)]);
|
|
106
|
+
const withPointer = joinSections([
|
|
107
|
+
...accepted,
|
|
108
|
+
...suffix.map((entry) => entry.text),
|
|
109
|
+
notReachedPointer(items.slice(index)),
|
|
110
|
+
]);
|
|
185
111
|
return {
|
|
186
|
-
value:
|
|
187
|
-
...accepted,
|
|
188
|
-
partial,
|
|
189
|
-
...suffix.map((entry) => entry.text),
|
|
190
|
-
notReachedPointer(unreached),
|
|
191
|
-
]),
|
|
112
|
+
value: measureContext(withPointer, units) <= opts.budget ? withPointer : withoutPointer,
|
|
192
113
|
fullyDeliveredItems: index,
|
|
193
|
-
partialItemIndex:
|
|
194
|
-
partialUnitsDelivered:
|
|
114
|
+
partialItemIndex: null,
|
|
115
|
+
partialUnitsDelivered: 0,
|
|
195
116
|
};
|
|
196
117
|
}
|
|
197
118
|
|