-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimits.ts
More file actions
672 lines (598 loc) · 20 KB
/
Copy pathlimits.ts
File metadata and controls
672 lines (598 loc) · 20 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
import * as t from "@babel/types";
import { traverse } from "../babel.js";
import { print } from "../loader.js";
import type { Patch, PatchResult } from "../types.js";
import { getObjectKeyName, isMemberPropertyName } from "./ast-helpers.js";
const NEW_LINES_CAP = 5000;
const NEW_LINE_CHARS = 5000;
const NEW_BYTE_CEILING = 1048576;
const NEW_TOKEN_BUDGET = 50000;
// Persistence cap: controls when formatted results get disk-persisted.
// 120K chars ~ 30K tokens. The token budget (50K raw) remains the primary gate;
// this cap prevents large formatted output from staying inline forever.
const NEW_RESULT_SIZE_CAP = 120000;
// Per-tool maxResultSizeChars. Kept at 250K so the persistence cap (120K)
// is the effective governor: min(250K, 120K) = 120K.
const NEW_READ_MAX_RESULT_SIZE = 250000;
const READ_PROMPT_TRIGGERS = [
"Reads a file from the local filesystem",
"Read files from the local filesystem",
];
// Coupling: identifies the Read tool prompt via the same trigger phrase as
// read-with-bat.ts. This patch modifies variable declarations (numeric limits),
// while read-with-bat replaces the prompt body. Both can coexist safely.
// Store limit changes for reporting
let limitsChanged: NonNullable<PatchResult["limits"]> = {};
function isReadPromptTemplate(
quasis: Array<{ value: { raw: string } }>,
): boolean {
return quasis.some((q) =>
READ_PROMPT_TRIGGERS.some((trigger) => q.value.raw.includes(trigger)),
);
}
function isSameBinding(
path: any,
node: t.Node | null | undefined,
binding: any,
): boolean {
return (
!!binding &&
t.isIdentifier(node) &&
path.scope.getBinding(node.name) === binding
);
}
function isMathReference(node: t.Expression | t.Super): boolean {
if (t.isSuper(node)) return false;
if (t.isIdentifier(node)) return node.name === "Math";
if (!t.isMemberExpression(node)) return false;
return (
isMemberPropertyName(node, "Math") &&
t.isIdentifier(node.object) &&
node.object.name === "globalThis"
);
}
/** Resolve maxResultSizeChars value from NumericLiteral or BinaryExpression (1/0 = Infinity). */
function resolveMaxResultSizeValue(node: t.Node): number | null {
if (t.isNumericLiteral(node)) return node.value;
// 1 / 0 = Infinity
if (
t.isBinaryExpression(node, { operator: "/" }) &&
t.isNumericLiteral(node.left, { value: 1 }) &&
t.isNumericLiteral(node.right, { value: 0 })
) {
return Infinity;
}
return null;
}
function resolveResultSizeCapBinding(path: any): {
value: number;
binding: any;
} | null {
if (!t.isBlockStatement(path.node.body)) return null;
if (path.node.params.length < 3) return null;
const [_, maxCharsParam, ceilingParam] = path.node.params;
if (!t.isIdentifier(maxCharsParam)) return null;
if (!t.isAssignmentPattern(ceilingParam)) return null;
if (
!t.isIdentifier(ceilingParam.left) ||
!t.isIdentifier(ceilingParam.right)
) {
return null;
}
const maxCharsBinding = path.scope.getBinding(maxCharsParam.name);
const ceilingBinding = path.scope.getBinding(ceilingParam.left.name);
let foundClamp = false;
path.traverse({
CallExpression(innerPath: any) {
const callee = innerPath.node.callee;
if (!t.isMemberExpression(callee)) return;
if (!isMathReference(callee.object)) return;
if (!isMemberPropertyName(callee, "min")) return;
if (innerPath.node.arguments.length !== 2) return;
const [leftArg, rightArg] = innerPath.node.arguments;
if (!isSameBinding(innerPath, leftArg, maxCharsBinding)) return;
if (!isSameBinding(innerPath, rightArg, ceilingBinding)) return;
foundClamp = true;
innerPath.stop();
},
});
if (!foundClamp) return null;
const binding = path.scope.getBinding(ceilingParam.right.name);
if (!binding || !t.isVariableDeclarator(binding.path.node)) return null;
const init = binding.path.node.init;
if (!t.isNumericLiteral(init)) return null;
return { value: init.value, binding };
}
function collectCurrentLimits(ast: t.File): {
linesCap?: number;
lineChars?: number;
byteCeiling?: number;
tokenBudget?: number;
resultSizeCap?: number;
readMaxResultSize?: number;
hasTokenEnvRef?: boolean;
} {
const current: {
linesCap?: number;
lineChars?: number;
byteCeiling?: number;
tokenBudget?: number;
resultSizeCap?: number;
readMaxResultSize?: number;
hasTokenEnvRef?: boolean;
} = {};
// One full-tree traversal collects every verifier input at once. Each
// branch keeps its own first-match guard so the result matches what
// five separate traverses plus an env-ref check produced before.
traverse(ast, {
TemplateLiteral(path: any) {
if (current.linesCap !== undefined && current.lineChars !== undefined)
return;
const quasis = path.node.quasis;
const hasTrigger = isReadPromptTemplate(quasis);
if (!hasTrigger) return;
const exprs = path.node.expressions;
for (let i = 0; i < quasis.length; i++) {
if (i >= exprs.length) continue;
if (!t.isIdentifier(exprs[i])) continue;
const binding = path.scope.getBinding(exprs[i].name);
const init =
binding && t.isVariableDeclarator(binding.path.node)
? binding.path.node.init
: null;
if (!t.isNumericLiteral(init)) continue;
const text = quasis[i].value.raw;
if (text.includes("reads up to ")) current.linesCap = init.value;
if (text.includes("longer than ")) current.lineChars = init.value;
}
},
Function(path: any) {
// byteCeiling: file-size check function
if (
current.byteCeiling === undefined &&
t.isBlockStatement(path.node.body) &&
path.node.params.length >= 2
) {
const [fileParam, limitParam] = path.node.params;
if (
t.isIdentifier(fileParam) &&
t.isAssignmentPattern(limitParam) &&
t.isIdentifier(limitParam.left) &&
t.isIdentifier(limitParam.right)
) {
const fileParamName = fileParam.name;
const limitParamName = limitParam.left.name;
const byteCeilingVarName = limitParam.right.name;
const fileBinding = path.scope.getBinding(fileParamName);
const limitBinding = path.scope.getBinding(limitParamName);
let isFileSizeCheckFn = false;
path.traverse({
BinaryExpression(innerPath: any) {
const node = innerPath.node;
if (node.operator !== "<=") return;
if (!isSameBinding(innerPath, node.right, limitBinding)) return;
const left = node.left;
if (!t.isMemberExpression(left)) return;
if (!isMemberPropertyName(left, "size")) return;
const statCall = left.object;
if (!t.isCallExpression(statCall)) return;
if (!t.isMemberExpression(statCall.callee)) return;
if (!isMemberPropertyName(statCall.callee, "statSync")) return;
if (
statCall.arguments.length < 1 ||
!isSameBinding(innerPath, statCall.arguments[0], fileBinding)
)
return;
isFileSizeCheckFn = true;
innerPath.stop();
},
});
if (isFileSizeCheckFn) {
const binding = path.scope.getBinding(byteCeilingVarName);
const init =
binding && t.isVariableDeclarator(binding.path.node)
? binding.path.node.init
: null;
if (t.isNumericLiteral(init)) {
current.byteCeiling = init.value;
}
}
}
}
// tokenBudget: function whose body references the env var, with
// the budget default declared as the next sibling variable.
if (
current.tokenBudget === undefined &&
t.isBlockStatement(path.node.body)
) {
let hasEnv = false;
path.traverse({
MemberExpression(innerPath: any) {
const node = innerPath.node;
const prop = node.property;
const propName =
(t.isIdentifier(prop) && prop.name) ||
(t.isStringLiteral(prop) && prop.value) ||
null;
if (propName !== "CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS") return;
hasEnv = true;
innerPath.stop();
},
});
if (hasEnv) {
const nextSibling = path.getNextSibling?.();
if (nextSibling?.node && t.isVariableDeclaration(nextSibling.node)) {
for (const decl of nextSibling.node.declarations) {
if (
t.isNumericLiteral(decl.init) &&
(decl.init.value === 25000 ||
decl.init.value === NEW_TOKEN_BUDGET)
) {
current.tokenBudget = decl.init.value;
break;
}
}
}
}
}
// resultSizeCap
if (current.resultSizeCap === undefined) {
const resolved = resolveResultSizeCapBinding(path);
if (resolved) {
current.resultSizeCap = resolved.value;
}
}
},
ObjectExpression(path: any) {
// Read tool's maxResultSizeChars
if (current.readMaxResultSize !== undefined) return;
const nameProp = path.node.properties.find(
(p: any): p is t.ObjectProperty =>
t.isObjectProperty(p) && getObjectKeyName(p.key) === "name",
);
if (!nameProp) return;
let nameVal: string | null = null;
if (t.isStringLiteral(nameProp.value)) {
nameVal = nameProp.value.value;
} else if (t.isIdentifier(nameProp.value)) {
const binding = path.scope.getBinding(nameProp.value.name);
const init = binding?.path.node;
if (t.isVariableDeclarator(init) && t.isStringLiteral(init.init)) {
nameVal = init.init.value;
}
}
if (nameVal !== "Read") return;
// Discriminate against other tools: Read tool has searchHint with "read files"
const searchHintProp = path.node.properties.find(
(p: any): p is t.ObjectProperty =>
t.isObjectProperty(p) && getObjectKeyName(p.key) === "searchHint",
);
if (
searchHintProp &&
t.isStringLiteral(searchHintProp.value) &&
!searchHintProp.value.value.includes("read file")
) {
return;
}
const maxProp = path.node.properties.find(
(p: any): p is t.ObjectProperty =>
t.isObjectProperty(p) &&
getObjectKeyName(p.key) === "maxResultSizeChars",
);
if (!maxProp) return;
const resolved = resolveMaxResultSizeValue(maxProp.value);
if (resolved === null) return;
current.readMaxResultSize = resolved;
},
MemberExpression(path: any) {
// Token-budget env var: just confirm an occurrence exists somewhere
// in the bundle. The original verify did a dedicated full-tree
// traverse for this; folding it in here drops one full walk.
if (current.hasTokenEnvRef) return;
const prop = path.node.property;
const propName =
(t.isIdentifier(prop) && prop.name) ||
(t.isStringLiteral(prop) && prop.value) ||
null;
if (propName === "CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS") {
current.hasTokenEnvRef = true;
}
},
});
return current;
}
function runLimitsPatch(ast: t.File): void {
limitsChanged = {};
patchByteCeiling(ast);
patchTokenBudget(ast);
patchResultSizeCap(ast);
patchReadMaxResultSize(ast);
traverse(ast, {
TemplateLiteral(path: any) {
const quasis = path.node.quasis;
const hasTrigger = isReadPromptTemplate(quasis);
if (!hasTrigger) return;
const code = print(path.node);
if (code.includes("Reads a file from the local filesystem.")) {
const exprs = path.node.expressions;
for (let i = 0; i < quasis.length; i++) {
const q = quasis[i].value.raw;
if (q.includes("reads up to ")) {
if (i < exprs.length && t.isIdentifier(exprs[i])) {
const linesVarName = (exprs[i] as any).name;
updateVarValue(ast, linesVarName, NEW_LINES_CAP, "linesCap");
}
}
if (q.includes("longer than ")) {
if (i < exprs.length && t.isIdentifier(exprs[i])) {
const charsVarName = (exprs[i] as any).name;
updateVarValue(ast, charsVarName, NEW_LINE_CHARS, "lineChars");
}
}
}
}
},
});
function patchByteCeiling(ast: any) {
let patched = false;
traverse(ast, {
Function(path: any) {
if (patched) return;
if (!t.isBlockStatement(path.node.body)) return;
if (path.node.params.length < 2) return;
const [fileParam, limitParam] = path.node.params;
if (!t.isIdentifier(fileParam)) return;
if (!t.isAssignmentPattern(limitParam)) return;
if (!t.isIdentifier(limitParam.left)) return;
if (!t.isIdentifier(limitParam.right)) return;
const fileParamName = fileParam.name;
const limitParamName = limitParam.left.name;
const byteCeilingVarName = limitParam.right.name;
const fileBinding = path.scope.getBinding(fileParamName);
const limitBinding = path.scope.getBinding(limitParamName);
let isFileSizeCheckFn = false;
path.traverse({
BinaryExpression(innerPath: any) {
const node = innerPath.node;
if (node.operator !== "<=") return;
if (!isSameBinding(innerPath, node.right, limitBinding)) return;
const left = node.left;
if (!t.isMemberExpression(left)) return;
if (!isMemberPropertyName(left, "size")) return;
const statCall = left.object;
if (!t.isCallExpression(statCall)) return;
if (!t.isMemberExpression(statCall.callee)) return;
if (!isMemberPropertyName(statCall.callee, "statSync")) return;
if (
statCall.arguments.length < 1 ||
!isSameBinding(innerPath, statCall.arguments[0], fileBinding)
)
return;
isFileSizeCheckFn = true;
innerPath.stop();
},
});
if (!isFileSizeCheckFn) return;
const binding = path.scope.getBinding(byteCeilingVarName);
if (!binding || !t.isVariableDeclarator(binding.path.node)) return;
const init = binding.path.node.init;
if (!t.isNumericLiteral(init, { value: 262144 })) return;
binding.path.node.init = t.numericLiteral(NEW_BYTE_CEILING);
limitsChanged.byteCeiling = [
String(init.value),
String(NEW_BYTE_CEILING),
];
patched = true;
path.stop();
},
});
}
function patchTokenBudget(ast: any) {
let patched = false;
traverse(ast, {
Function(path: any) {
if (patched) return;
if (!t.isBlockStatement(path.node.body)) return;
let hasEnv = false;
path.traverse({
MemberExpression(innerPath: any) {
const node = innerPath.node;
const prop = node.property;
const propName =
(t.isIdentifier(prop) && prop.name) ||
(t.isStringLiteral(prop) && prop.value) ||
null;
if (propName !== "CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS") return;
hasEnv = true;
innerPath.stop();
},
});
if (!hasEnv) return;
// The token budget default is stored as a sibling variable after the function.
const nextSibling = path.getNextSibling?.();
if (!nextSibling?.node || !t.isVariableDeclaration(nextSibling.node))
return;
for (const decl of nextSibling.node.declarations) {
if (t.isNumericLiteral(decl.init, { value: 25000 })) {
const oldValue = decl.init.value;
decl.init = t.numericLiteral(NEW_TOKEN_BUDGET);
limitsChanged.tokenBudget = [
String(oldValue),
String(NEW_TOKEN_BUDGET),
];
patched = true;
path.stop();
return;
}
}
},
});
}
function patchResultSizeCap(ast: any) {
let patched = false;
traverse(ast, {
Function(path: any) {
if (patched) return;
const resolved = resolveResultSizeCapBinding(path);
if (!resolved) return;
const init = resolved.binding.path.node.init;
if (!t.isNumericLiteral(init, { value: 50000 })) return;
resolved.binding.path.node.init = t.numericLiteral(NEW_RESULT_SIZE_CAP);
limitsChanged.resultSizeCap = [
String(init.value),
String(NEW_RESULT_SIZE_CAP),
];
patched = true;
path.stop();
},
});
}
function patchReadMaxResultSize(ast: any) {
let patched = false;
traverse(ast, {
ObjectExpression(path: any) {
if (patched) return;
const nameProp = path.node.properties.find(
(p: any): p is t.ObjectProperty =>
t.isObjectProperty(p) && getObjectKeyName(p.key) === "name",
);
if (!nameProp) return;
let nameVal: string | null = null;
if (t.isStringLiteral(nameProp.value)) {
nameVal = nameProp.value.value;
} else if (t.isIdentifier(nameProp.value)) {
const binding = path.scope.getBinding(nameProp.value.name);
const init = binding?.path.node;
if (t.isVariableDeclarator(init) && t.isStringLiteral(init.init)) {
nameVal = init.init.value;
}
}
if (nameVal !== "Read") return;
// Discriminate against other tools: Read tool has searchHint with "read files"
const searchHintProp = path.node.properties.find(
(p: any): p is t.ObjectProperty =>
t.isObjectProperty(p) && getObjectKeyName(p.key) === "searchHint",
);
if (
searchHintProp &&
t.isStringLiteral(searchHintProp.value) &&
!searchHintProp.value.value.includes("read file")
) {
return;
}
const maxProp = path.node.properties.find(
(p: any): p is t.ObjectProperty =>
t.isObjectProperty(p) &&
getObjectKeyName(p.key) === "maxResultSizeChars",
);
if (!maxProp) return;
// Handle both NumericLiteral (1e5) and BinaryExpression (1 / 0 = Infinity)
const resolvedValue = resolveMaxResultSizeValue(maxProp.value);
if (resolvedValue === null) return;
// Skip if already >= our target (e.g. Infinity)
if (resolvedValue >= NEW_READ_MAX_RESULT_SIZE) {
limitsChanged.readMaxResultSize = [
String(resolvedValue),
String(resolvedValue),
];
patched = true;
path.stop();
return;
}
maxProp.value = t.numericLiteral(NEW_READ_MAX_RESULT_SIZE);
limitsChanged.readMaxResultSize = [
String(resolvedValue),
String(NEW_READ_MAX_RESULT_SIZE),
];
patched = true;
path.stop();
},
});
}
function updateVarValue(
ast: any,
varName: string,
newValue: number,
limitKey: keyof NonNullable<PatchResult["limits"]>,
) {
traverse(ast, {
VariableDeclarator(path: any) {
if (t.isIdentifier(path.node.id) && path.node.id.name === varName) {
const oldValue = t.isNumericLiteral(path.node.init)
? String(path.node.init.value)
: "unknown";
path.node.init = t.numericLiteral(newValue);
limitsChanged[limitKey] = [oldValue, String(newValue)];
path.stop();
}
},
});
}
}
export const limits: Patch = {
tag: "limits",
astPasses: (ast) => [
{
pass: "mutate",
visitor: {
Program: {
exit() {
runLimitsPatch(ast);
},
},
},
},
],
verify: (_code, ast) => {
if (!ast) return "Missing AST for limits verification";
const current = collectCurrentLimits(ast);
const requiredChecks: Array<
[keyof NonNullable<PatchResult["limits"]>, number, number | undefined]
> = [
["byteCeiling", NEW_BYTE_CEILING, current.byteCeiling],
["tokenBudget", NEW_TOKEN_BUDGET, current.tokenBudget],
["resultSizeCap", NEW_RESULT_SIZE_CAP, current.resultSizeCap],
];
for (const [key, expected, actual] of requiredChecks) {
if (actual === undefined) return `Could not resolve limit ${key}`;
if (actual !== expected) {
return `Limit ${key} has unexpected value: ${actual} (expected ${expected})`;
}
}
// readMaxResultSize accepts values >= target (Infinity is fine; means no per-tool cap)
if (current.readMaxResultSize === undefined) {
return "Could not resolve limit readMaxResultSize";
}
if (current.readMaxResultSize < NEW_READ_MAX_RESULT_SIZE) {
return `Limit readMaxResultSize has unexpected value: ${current.readMaxResultSize} (expected >= ${NEW_READ_MAX_RESULT_SIZE})`;
}
const optionalPromptChecks: Array<
[keyof NonNullable<PatchResult["limits"]>, number, number | undefined]
> = [
["linesCap", NEW_LINES_CAP, current.linesCap],
["lineChars", NEW_LINE_CHARS, current.lineChars],
];
for (const [key, expected, actual] of optionalPromptChecks) {
if (actual === undefined) continue;
if (actual !== expected) {
return `Limit ${key} has unexpected value: ${actual} (expected ${expected})`;
}
}
// Structural integrity: persistence cap must be less than maxResultSizeChars
// so it is the effective governor in the Math.min call
if (
current.resultSizeCap !== undefined &&
current.readMaxResultSize !== undefined &&
current.resultSizeCap >= current.readMaxResultSize
) {
return `resultSizeCap (${current.resultSizeCap}) must be less than readMaxResultSize (${current.readMaxResultSize}) for persistence to govern`;
}
if (!current.hasTokenEnvRef) {
return "CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS env var reference not found in token budget function";
}
return true;
},
};
export function getLimitsChanged(): PatchResult["limits"] {
return limitsChanged;
}