@namzu/sdk 73.0.0 → 74.0.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/CHANGELOG.md +38 -0
- package/README.md +34 -34
- package/dist/authorization/protected-paths.d.ts +7 -0
- package/dist/authorization/protected-paths.d.ts.map +1 -1
- package/dist/authorization/protected-paths.js +7 -0
- package/dist/authorization/protected-paths.js.map +1 -1
- package/dist/authorization/readonly-commands.d.ts +23 -0
- package/dist/authorization/readonly-commands.d.ts.map +1 -1
- package/dist/authorization/readonly-commands.js +89 -3
- package/dist/authorization/readonly-commands.js.map +1 -1
- package/dist/authorization/shell-paths.d.ts +8 -0
- package/dist/authorization/shell-paths.d.ts.map +1 -1
- package/dist/authorization/shell-paths.js +125 -2
- package/dist/authorization/shell-paths.js.map +1 -1
- package/dist/bridge/acp/permission.d.ts +6 -0
- package/dist/bridge/acp/permission.d.ts.map +1 -1
- package/dist/bridge/acp/permission.js.map +1 -1
- package/dist/bridge/acp/server.d.ts.map +1 -1
- package/dist/bridge/acp/server.js +21 -3
- package/dist/bridge/acp/server.js.map +1 -1
- package/dist/compaction/context-window.d.ts.map +1 -1
- package/dist/compaction/context-window.js +11 -0
- package/dist/compaction/context-window.js.map +1 -1
- package/dist/compaction/manual.d.ts.map +1 -1
- package/dist/compaction/manual.js +15 -8
- package/dist/compaction/manual.js.map +1 -1
- package/dist/compaction/plan.d.ts +2 -1
- package/dist/compaction/plan.d.ts.map +1 -1
- package/dist/compaction/plan.js +6 -5
- package/dist/compaction/plan.js.map +1 -1
- package/dist/compaction/retained-images.d.ts +16 -0
- package/dist/compaction/retained-images.d.ts.map +1 -0
- package/dist/compaction/retained-images.js +113 -0
- package/dist/compaction/retained-images.js.map +1 -0
- package/dist/compaction/token-estimate.d.ts +8 -3
- package/dist/compaction/token-estimate.d.ts.map +1 -1
- package/dist/compaction/token-estimate.js +76 -8
- package/dist/compaction/token-estimate.js.map +1 -1
- package/dist/compaction/tool-result-editing.d.ts.map +1 -1
- package/dist/compaction/tool-result-editing.js +15 -8
- package/dist/compaction/tool-result-editing.js.map +1 -1
- package/dist/constants/acp/index.d.ts +2 -0
- package/dist/constants/acp/index.d.ts.map +1 -1
- package/dist/constants/acp/index.js +2 -0
- package/dist/constants/acp/index.js.map +1 -1
- package/dist/pricing/catalogue.generated.d.ts.map +1 -1
- package/dist/pricing/catalogue.generated.js +178 -1
- package/dist/pricing/catalogue.generated.js.map +1 -1
- package/dist/provider/attribution.js +1 -1
- package/dist/provider/attribution.js.map +1 -1
- package/dist/public-runtime.d.ts +4 -2
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +7 -1
- package/dist/public-runtime.js.map +1 -1
- package/dist/rag/embedding.d.ts +5 -1
- package/dist/rag/embedding.d.ts.map +1 -1
- package/dist/rag/embedding.js +22 -7
- package/dist/rag/embedding.js.map +1 -1
- package/dist/runtime/query/abandon-turn.d.ts.map +1 -1
- package/dist/runtime/query/abandon-turn.js +9 -0
- package/dist/runtime/query/abandon-turn.js.map +1 -1
- package/dist/runtime/query/compact-session.d.ts +10 -3
- package/dist/runtime/query/compact-session.d.ts.map +1 -1
- package/dist/runtime/query/compact-session.js +24 -14
- package/dist/runtime/query/compact-session.js.map +1 -1
- package/dist/runtime/query/index.d.ts.map +1 -1
- package/dist/runtime/query/index.js +1 -0
- package/dist/runtime/query/index.js.map +1 -1
- package/dist/runtime/query/iteration/index.d.ts.map +1 -1
- package/dist/runtime/query/iteration/index.js +14 -0
- package/dist/runtime/query/iteration/index.js.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/compaction.js +60 -5
- package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
- package/dist/runtime/query/iteration/phases/context.d.ts +2 -0
- package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
- package/dist/runtime/query/iteration/phases/context.js +1 -0
- package/dist/runtime/query/iteration/phases/context.js.map +1 -1
- package/dist/runtime/query/iteration/request-prefix.d.ts +21 -0
- package/dist/runtime/query/iteration/request-prefix.d.ts.map +1 -0
- package/dist/runtime/query/iteration/request-prefix.js +111 -0
- package/dist/runtime/query/iteration/request-prefix.js.map +1 -0
- package/dist/runtime/query/review-policy.d.ts +11 -3
- package/dist/runtime/query/review-policy.d.ts.map +1 -1
- package/dist/runtime/query/review-policy.js +54 -3
- package/dist/runtime/query/review-policy.js.map +1 -1
- package/dist/sandbox/exec-stdin.d.ts +21 -0
- package/dist/sandbox/exec-stdin.d.ts.map +1 -0
- package/dist/sandbox/exec-stdin.js +40 -0
- package/dist/sandbox/exec-stdin.js.map +1 -0
- package/dist/sandbox/file-walk.d.ts +12 -7
- package/dist/sandbox/file-walk.d.ts.map +1 -1
- package/dist/sandbox/file-walk.js +13 -4
- package/dist/sandbox/file-walk.js.map +1 -1
- package/dist/sandbox/ignore-matcher.d.ts +1 -0
- package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
- package/dist/sandbox/ignore-matcher.js.map +1 -1
- package/dist/sandbox/ignore-source.js +1 -1
- package/dist/sandbox/index.d.ts +3 -2
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +2 -1
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/provider/local.d.ts.map +1 -1
- package/dist/sandbox/provider/local.js +2 -0
- package/dist/sandbox/provider/local.js.map +1 -1
- package/dist/session/paths.d.ts +6 -0
- package/dist/session/paths.d.ts.map +1 -1
- package/dist/session/paths.js +7 -0
- package/dist/session/paths.js.map +1 -1
- package/dist/session-query/index.d.ts +1 -0
- package/dist/session-query/index.d.ts.map +1 -1
- package/dist/session-query/index.js +26 -15
- package/dist/session-query/index.js.map +1 -1
- package/dist/store/evidence/disk.js +3 -1
- package/dist/store/evidence/disk.js.map +1 -1
- package/dist/store/evidence/index-page.d.ts +1 -0
- package/dist/store/evidence/index-page.d.ts.map +1 -1
- package/dist/store/evidence/index-page.js +8 -0
- package/dist/store/evidence/index-page.js.map +1 -1
- package/dist/store/memory/operation-lock.d.ts.map +1 -1
- package/dist/store/memory/operation-lock.js +15 -1
- package/dist/store/memory/operation-lock.js.map +1 -1
- package/dist/store/session-log/core.d.ts.map +1 -1
- package/dist/store/session-log/core.js +23 -0
- package/dist/store/session-log/core.js.map +1 -1
- package/dist/tools/builtins/computer-use-image.d.ts +9 -0
- package/dist/tools/builtins/computer-use-image.d.ts.map +1 -1
- package/dist/tools/builtins/computer-use-image.js +21 -0
- package/dist/tools/builtins/computer-use-image.js.map +1 -1
- package/dist/tools/builtins/computer-use.d.ts +1 -9
- package/dist/tools/builtins/computer-use.d.ts.map +1 -1
- package/dist/tools/builtins/computer-use.js +2 -22
- package/dist/tools/builtins/computer-use.js.map +1 -1
- package/dist/toolsets/manager.d.ts +7 -3
- package/dist/toolsets/manager.d.ts.map +1 -1
- package/dist/toolsets/manager.js +7 -3
- package/dist/toolsets/manager.js.map +1 -1
- package/dist/types/common/index.d.ts +20 -0
- package/dist/types/common/index.d.ts.map +1 -1
- package/dist/types/common/index.js +4 -1
- package/dist/types/common/index.js.map +1 -1
- package/dist/types/hitl/index.d.ts +11 -0
- package/dist/types/hitl/index.d.ts.map +1 -1
- package/dist/types/hitl/index.js.map +1 -1
- package/dist/types/rag/embedding.d.ts +4 -0
- package/dist/types/rag/embedding.d.ts.map +1 -1
- package/dist/types/sandbox/index.d.ts +19 -0
- package/dist/types/sandbox/index.d.ts.map +1 -1
- package/dist/types/sandbox/index.js.map +1 -1
- package/dist/types/session/events.d.ts +48 -0
- package/dist/types/session/events.d.ts.map +1 -1
- package/dist/types/session/events.js.map +1 -1
- package/dist/types/session/records.d.ts +2 -0
- package/dist/types/session/records.d.ts.map +1 -1
- package/dist/types/session/records.js +9 -0
- package/dist/types/session/records.js.map +1 -1
- package/dist/utils/cost.d.ts +15 -0
- package/dist/utils/cost.d.ts.map +1 -1
- package/dist/utils/cost.js +24 -1
- package/dist/utils/cost.js.map +1 -1
- package/package.json +2 -2
- package/src/authorization/protected-paths.ts +7 -0
- package/src/authorization/readonly-commands.ts +85 -3
- package/src/authorization/shell-paths.ts +141 -3
- package/src/bridge/acp/permission.ts +6 -0
- package/src/bridge/acp/server.ts +20 -1
- package/src/compaction/context-window.ts +11 -0
- package/src/compaction/manual.ts +23 -8
- package/src/compaction/plan.ts +11 -5
- package/src/compaction/retained-images.ts +130 -0
- package/src/compaction/token-estimate.ts +86 -8
- package/src/compaction/tool-result-editing.ts +20 -8
- package/src/constants/acp/index.ts +2 -0
- package/src/pricing/catalogue.generated.ts +178 -1
- package/src/pricing/rates.source.json +155 -2
- package/src/provider/attribution.ts +1 -1
- package/src/public-runtime.ts +21 -0
- package/src/rag/embedding.ts +23 -7
- package/src/runtime/query/abandon-turn.ts +9 -0
- package/src/runtime/query/compact-session.ts +50 -15
- package/src/runtime/query/index.ts +1 -0
- package/src/runtime/query/iteration/index.ts +14 -0
- package/src/runtime/query/iteration/phases/compaction.ts +77 -5
- package/src/runtime/query/iteration/phases/context.ts +3 -0
- package/src/runtime/query/iteration/request-prefix.ts +161 -0
- package/src/runtime/query/review-policy.ts +79 -11
- package/src/sandbox/exec-stdin.ts +54 -0
- package/src/sandbox/file-walk.ts +25 -18
- package/src/sandbox/ignore-matcher.ts +1 -0
- package/src/sandbox/ignore-source.ts +1 -1
- package/src/sandbox/index.ts +8 -2
- package/src/sandbox/provider/local.ts +2 -0
- package/src/session/paths.ts +9 -0
- package/src/session-query/index.ts +23 -14
- package/src/store/evidence/disk.ts +3 -1
- package/src/store/evidence/index-page.ts +11 -0
- package/src/store/memory/operation-lock.ts +19 -1
- package/src/store/session-log/core.ts +26 -0
- package/src/tools/builtins/computer-use-image.ts +20 -0
- package/src/tools/builtins/computer-use.ts +1 -20
- package/src/toolsets/manager.ts +7 -3
- package/src/types/common/index.ts +26 -1
- package/src/types/hitl/index.ts +11 -0
- package/src/types/rag/embedding.ts +7 -0
- package/src/types/sandbox/index.ts +19 -0
- package/src/types/session/events.ts +49 -0
- package/src/types/session/records.ts +14 -0
- package/src/utils/cost.ts +44 -1
|
@@ -117,6 +117,14 @@ export interface ShellPathUse {
|
|
|
117
117
|
* literal relative directory is followed; anything else is `unknown`.
|
|
118
118
|
*/
|
|
119
119
|
readonly directory?: ShellDirectory
|
|
120
|
+
/**
|
|
121
|
+
* True for a path the reading derived rather than read: the file a copy or
|
|
122
|
+
* move into a directory would create there, which the line names only by its
|
|
123
|
+
* directory. The caller checks it the same way as any other write, but
|
|
124
|
+
* without treating its absence as proof that nothing was written at that
|
|
125
|
+
* name, because the reading never looked at the disk.
|
|
126
|
+
*/
|
|
127
|
+
readonly candidate?: true
|
|
120
128
|
}
|
|
121
129
|
|
|
122
130
|
/** Where a `cd` earlier in the line left the shell, relative to where the line began. */
|
|
@@ -208,11 +216,25 @@ function isLongOption(name: string, full: string, minimum: number): boolean {
|
|
|
208
216
|
* prefixes below are the shortest that no other option of `cp`, `mv` or
|
|
209
217
|
* `install` shares: `--t` for `--target-directory`, `--su` for `--suffix`,
|
|
210
218
|
* `--l` for `--link`, `--sy` for `--symbolic-link`. `--reflink` is a copy.
|
|
219
|
+
*
|
|
220
|
+
* `targetDirectory` is the value of `-t`/`--target-directory` when the line
|
|
221
|
+
* gave one: that word is a directory by definition, which the destination
|
|
222
|
+
* operand alone does not say. `--parents` keeps each source's own path under
|
|
223
|
+
* that directory, and `-T`/`--no-target-directory` says the destination is the
|
|
224
|
+
* file itself, so neither derives a name inside a directory.
|
|
211
225
|
*/
|
|
212
|
-
function readCopyArguments(args: Args): {
|
|
226
|
+
function readCopyArguments(args: Args): {
|
|
227
|
+
operands: CopyOperand[]
|
|
228
|
+
links: boolean
|
|
229
|
+
targetDirectory?: ShellWord
|
|
230
|
+
parents: boolean
|
|
231
|
+
noTargetDirectory: boolean
|
|
232
|
+
} {
|
|
213
233
|
const out: CopyOperand[] = []
|
|
214
234
|
let links = false
|
|
215
235
|
let target: ShellWord | undefined
|
|
236
|
+
let parents = false
|
|
237
|
+
let noTargetDirectory = false
|
|
216
238
|
let afterDashes = false
|
|
217
239
|
for (let i = 0; i < args.length; i += 1) {
|
|
218
240
|
const arg = args[i] as ShellWord
|
|
@@ -237,11 +259,14 @@ function readCopyArguments(args: Args): { operands: CopyOperand[]; links: boolea
|
|
|
237
259
|
} else if (isLongOption(name, '--suffix', 4) && eq < 0) i += 1
|
|
238
260
|
else if (isLongOption(name, '--link', 3) || isLongOption(name, '--symbolic-link', 4))
|
|
239
261
|
links = true
|
|
262
|
+
else if (isLongOption(name, '--parents', 4) && eq < 0) parents = true
|
|
263
|
+
else if (isLongOption(name, '--no-target-directory', 6) && eq < 0) noTargetDirectory = true
|
|
240
264
|
continue
|
|
241
265
|
}
|
|
242
266
|
for (let j = 1; j < text.length; j += 1) {
|
|
243
267
|
const letter = text[j] as string
|
|
244
268
|
if (letter === 'l' || letter === 's') links = true
|
|
269
|
+
if (letter === 'T') noTargetDirectory = true
|
|
245
270
|
if (letter !== 't' && letter !== 'S') continue
|
|
246
271
|
const rest = text.slice(j + 1)
|
|
247
272
|
if (letter === 't') {
|
|
@@ -256,11 +281,104 @@ function readCopyArguments(args: Args): { operands: CopyOperand[]; links: boolea
|
|
|
256
281
|
}
|
|
257
282
|
if (target !== undefined) {
|
|
258
283
|
out.push({ word: target, destination: true })
|
|
259
|
-
return { operands: out, links }
|
|
284
|
+
return { operands: out, links, targetDirectory: target, parents, noTargetDirectory }
|
|
260
285
|
}
|
|
261
286
|
const last = out[out.length - 1]
|
|
262
287
|
if (last !== undefined) out[out.length - 1] = { word: last.word, destination: true }
|
|
263
|
-
return { operands: out, links }
|
|
288
|
+
return { operands: out, links, parents, noTargetDirectory }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Whether a word's spelling alone says it is a directory, with no look at the
|
|
293
|
+
* disk: a trailing slash, or a final `.`/`..` segment.
|
|
294
|
+
*
|
|
295
|
+
* Only `/` separates, because only POSIX shell text reaches this: the reader
|
|
296
|
+
* reads `bash` or `sh`, where a backslash is an ordinary character of a name,
|
|
297
|
+
* so `dir\` is a file called `dir\` and not a directory. The `cmd` dialect
|
|
298
|
+
* names no operands here.
|
|
299
|
+
*/
|
|
300
|
+
function spelledAsDirectory(value: string): boolean {
|
|
301
|
+
if (value.endsWith('/')) return true
|
|
302
|
+
return /(?:^|\/)\.\.?$/.test(value)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** `value` without its trailing slashes: a word ending in `/` names the directory before it. */
|
|
306
|
+
function withoutTrailingSlashes(value: string): string {
|
|
307
|
+
let end = value.length
|
|
308
|
+
while (end > 0 && value[end - 1] === '/') end -= 1
|
|
309
|
+
return value.slice(0, end)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The files a copy or move into a directory would create there: the target
|
|
314
|
+
* directory joined to each source's base name.
|
|
315
|
+
*
|
|
316
|
+
* Whether the destination is a directory cannot be read from one source and a
|
|
317
|
+
* destination alone — `cp a b` may put a file at `b` or copy `a` into a
|
|
318
|
+
* directory `b` — so only the spellings that say it on their own are followed:
|
|
319
|
+
* the value of `-t`/`--target-directory`, which is a directory by definition, a
|
|
320
|
+
* destination with `--parents`, which GNU also requires to be a directory, a
|
|
321
|
+
* destination written with a trailing slash or a final `.`/`..`, and a bare
|
|
322
|
+
* destination operand with more than one source, which GNU accepts only as a
|
|
323
|
+
* directory. Each file is
|
|
324
|
+
* derived, not read: the caller gets it as a candidate and checks the name
|
|
325
|
+
* without treating its absence as proof. A source whose name is decided at run
|
|
326
|
+
* time names no file, so it contributes none.
|
|
327
|
+
*
|
|
328
|
+
* `cp -T`/`--no-target-directory` says the destination is the file itself, so
|
|
329
|
+
* nothing is derived. `--parents` keeps the source's own path under the
|
|
330
|
+
* directory (`cp --parents a/b c/` writes `c/a/b`), so a `..` segment, whose
|
|
331
|
+
* landing place the word alone does not say, derives nothing.
|
|
332
|
+
*
|
|
333
|
+
* The names are POSIX: only `/` separates, and a backslash is an ordinary
|
|
334
|
+
* character of one, so a trailing backslash neither says "directory" nor is
|
|
335
|
+
* dropped from a name.
|
|
336
|
+
*/
|
|
337
|
+
function copyDestinationFiles(
|
|
338
|
+
operands: readonly CopyOperand[],
|
|
339
|
+
targetDirectory: ShellWord | undefined,
|
|
340
|
+
parents: boolean,
|
|
341
|
+
noTargetDirectory: boolean,
|
|
342
|
+
): ShellWord[] {
|
|
343
|
+
const destination = operands.find((operand) => operand.destination)?.word
|
|
344
|
+
const directory = targetDirectory ?? destination
|
|
345
|
+
if (directory === undefined || noTargetDirectory) return []
|
|
346
|
+
// GNU refuses to copy several sources anywhere but a directory, so a bare
|
|
347
|
+
// destination operand beside more than one source names one too.
|
|
348
|
+
const sources = operands.reduce((n, operand) => (operand.destination ? n : n + 1), 0)
|
|
349
|
+
const saysDirectory =
|
|
350
|
+
parents || targetDirectory !== undefined || sources > 1 || spelledAsDirectory(directory.value)
|
|
351
|
+
if (!saysDirectory) return []
|
|
352
|
+
// A trailing `/` or `/.` is how a word says "directory" and nothing else;
|
|
353
|
+
// `..` is a segment of its own and stays.
|
|
354
|
+
const trimmed = withoutTrailingSlashes(directory.value)
|
|
355
|
+
const base = trimmed.endsWith('/.') ? trimmed.slice(0, -2) : trimmed
|
|
356
|
+
const out: ShellWord[] = []
|
|
357
|
+
for (const operand of operands) {
|
|
358
|
+
if (operand.destination) continue
|
|
359
|
+
const source = operand.word
|
|
360
|
+
if (source.value === '' || expandsAtRuntime(source)) continue
|
|
361
|
+
const name = parents
|
|
362
|
+
? parentedName(source.value)
|
|
363
|
+
: basename(withoutTrailingSlashes(source.value))
|
|
364
|
+
if (name === undefined || name === '' || name === '.' || name === '..') continue
|
|
365
|
+
out.push(derived(directory, `${base}/${name}`))
|
|
366
|
+
}
|
|
367
|
+
return out
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* The name `cp --parents` gives a source under the destination directory: the
|
|
372
|
+
* source's own path with trailing slashes removed and a leading `/` or `./`
|
|
373
|
+
* dropped, so `cp --parents a/b dest/` writes `dest/a/b`. A `..` segment is
|
|
374
|
+
* not followed, because where it lands cannot be read from the word alone.
|
|
375
|
+
*/
|
|
376
|
+
function parentedName(value: string): string | undefined {
|
|
377
|
+
let name = withoutTrailingSlashes(value)
|
|
378
|
+
while (name.startsWith('/')) name = name.slice(1)
|
|
379
|
+
while (name.startsWith('./')) name = name.slice(2)
|
|
380
|
+
if (name === '' || name.split('/').includes('..')) return undefined
|
|
381
|
+
return name
|
|
264
382
|
}
|
|
265
383
|
|
|
266
384
|
/**
|
|
@@ -1505,6 +1623,26 @@ export function shellPathAccess(reading: ShellReading): ShellPathAccess {
|
|
|
1505
1623
|
...(directory !== undefined ? { directory } : {}),
|
|
1506
1624
|
})
|
|
1507
1625
|
}
|
|
1626
|
+
// A copy into a directory writes a file inside it that the line names
|
|
1627
|
+
// only by its directory: report that file beside the directory, as a
|
|
1628
|
+
// candidate, so a protected name that matches it still asks instead of
|
|
1629
|
+
// being bypassed by naming the directory.
|
|
1630
|
+
for (const file of copyDestinationFiles(
|
|
1631
|
+
copy.operands,
|
|
1632
|
+
copy.targetDirectory,
|
|
1633
|
+
copy.parents,
|
|
1634
|
+
copy.noTargetDirectory,
|
|
1635
|
+
)) {
|
|
1636
|
+
if (file.value === '' || isHarmlessTarget(file.value)) continue
|
|
1637
|
+
uses.push({
|
|
1638
|
+
path: file.value,
|
|
1639
|
+
access: 'write',
|
|
1640
|
+
via: program,
|
|
1641
|
+
unresolved: expandsAtRuntime(file),
|
|
1642
|
+
candidate: true,
|
|
1643
|
+
...(directory !== undefined ? { directory } : {}),
|
|
1644
|
+
})
|
|
1645
|
+
}
|
|
1508
1646
|
}
|
|
1509
1647
|
if (program === 'touch') {
|
|
1510
1648
|
for (const arg of touchReferences(args)) {
|
|
@@ -20,6 +20,12 @@ export interface AcpPermissionRequest {
|
|
|
20
20
|
* name with the question; the answer goes back to that teammate's call only.
|
|
21
21
|
*/
|
|
22
22
|
readonly teammate?: { readonly name: string; readonly team: string }
|
|
23
|
+
/**
|
|
24
|
+
* Aborts when the question stops being open on the agent's side: the person wrote a message
|
|
25
|
+
* instead of answering, or the turn was stopped. The client is told to take the question off
|
|
26
|
+
* screen (`$/cancel_request`) and any answer that still arrives is ignored.
|
|
27
|
+
*/
|
|
28
|
+
readonly signal?: AbortSignal
|
|
23
29
|
readonly toolCalls: readonly (ToolCallSummary & {
|
|
24
30
|
/** Rides to the client untouched; see {@link AcpFileChangePreview}. */
|
|
25
31
|
readonly preview?: AcpFileChangePreview
|
package/src/bridge/acp/server.ts
CHANGED
|
@@ -379,6 +379,13 @@ export class ACPServer {
|
|
|
379
379
|
method: string,
|
|
380
380
|
params: Record<string, unknown>,
|
|
381
381
|
signal?: AbortSignal,
|
|
382
|
+
/**
|
|
383
|
+
* The turn's own signal, when the request is a question to the person. A request taken back
|
|
384
|
+
* while the turn goes on is told to the client (`$/cancel_request`) so its card comes down;
|
|
385
|
+
* one that ends because the turn stopped is not, since the stop settles the client's cards
|
|
386
|
+
* itself and says which actions never ran.
|
|
387
|
+
*/
|
|
388
|
+
turn?: AbortSignal,
|
|
382
389
|
): Promise<T> {
|
|
383
390
|
this.requestSeq += 1
|
|
384
391
|
const id = `agent_${this.requestSeq}`
|
|
@@ -390,6 +397,14 @@ export class ACPServer {
|
|
|
390
397
|
return true
|
|
391
398
|
}
|
|
392
399
|
const onAbort = (): void => {
|
|
400
|
+
// The client is told the question is closed, so a card it shows comes down. The
|
|
401
|
+
// protocol's own cancellation notice; a client that does not know it ignores it.
|
|
402
|
+
if (this.pending.get(id) === entry && !this.stopped && turn?.aborted === false)
|
|
403
|
+
void this.send({
|
|
404
|
+
jsonrpc: '2.0',
|
|
405
|
+
method: ACP_CLIENT_NOTIFICATIONS.CANCEL_REQUEST,
|
|
406
|
+
params: { requestId: id },
|
|
407
|
+
}).catch(() => {})
|
|
393
408
|
const reason =
|
|
394
409
|
signal?.reason instanceof Error
|
|
395
410
|
? signal.reason
|
|
@@ -850,6 +865,9 @@ export class ACPServer {
|
|
|
850
865
|
signal: AbortSignal,
|
|
851
866
|
): Promise<AcpPermissionOutcome> {
|
|
852
867
|
signal.throwIfAborted()
|
|
868
|
+
// Closed by the turn stopping or by the question itself being withdrawn.
|
|
869
|
+
const asking = request.signal ? AbortSignal.any([signal, request.signal]) : signal
|
|
870
|
+
asking.throwIfAborted()
|
|
853
871
|
// The latch, read from the SESSION. Checked here rather than in the
|
|
854
872
|
// gateway so no gateway can forget it.
|
|
855
873
|
// A call marked `alwaysAsk` exists to put a question to a person, so the
|
|
@@ -866,9 +884,10 @@ export class ACPServer {
|
|
|
866
884
|
toolCalls: request.toolCalls,
|
|
867
885
|
...(request.teammate ? { teammate: request.teammate } : {}),
|
|
868
886
|
},
|
|
887
|
+
asking,
|
|
869
888
|
signal,
|
|
870
889
|
)
|
|
871
|
-
|
|
890
|
+
asking.throwIfAborted()
|
|
872
891
|
|
|
873
892
|
switch (answer?.outcome) {
|
|
874
893
|
case 'approve':
|
|
@@ -174,6 +174,17 @@ const WINDOWS: ReadonlyArray<readonly [prefix: string, tokens: number]> = [
|
|
|
174
174
|
['claude-3-opus', 200_000],
|
|
175
175
|
['claude-', 200_000],
|
|
176
176
|
['gpt-5', 400_000],
|
|
177
|
+
// The gpt-6 API models state a 1,050,000-token window (922,000 input, 128,000
|
|
178
|
+
// output) on each model's page, e.g.
|
|
179
|
+
// https://developers.openai.com/api/docs/models/gpt-6-sol; every id the API
|
|
180
|
+
// lists is named here rather than matched by a bare `gpt-6`.
|
|
181
|
+
['gpt-6-astra', 1_050_000],
|
|
182
|
+
['gpt-6-luna', 1_050_000],
|
|
183
|
+
['gpt-6-sol', 1_050_000],
|
|
184
|
+
['gpt-6.1-sol', 1_050_000],
|
|
185
|
+
['gpt-6.1-terra', 1_050_000],
|
|
186
|
+
['gpt-6.2-astra', 1_050_000],
|
|
187
|
+
['gpt-6.2-sol', 1_050_000],
|
|
177
188
|
['gpt-4.1', 1_047_576],
|
|
178
189
|
['gpt-4o', 128_000],
|
|
179
190
|
['gpt-4-turbo', 128_000],
|
package/src/compaction/manual.ts
CHANGED
|
@@ -39,9 +39,10 @@ import {
|
|
|
39
39
|
recordRestorable,
|
|
40
40
|
renderRestoredContext,
|
|
41
41
|
} from './restore.js'
|
|
42
|
+
import { fitRetainedImages } from './retained-images.js'
|
|
42
43
|
import { findRetainedIndices } from './retention.js'
|
|
43
44
|
import { buildCompactionMessage, collectRevealedTools, isCompactionMessage } from './summary.js'
|
|
44
|
-
import {
|
|
45
|
+
import { estimateMessagesTokensForModel } from './token-estimate.js'
|
|
45
46
|
import { type CompactionVerificationOptions, buildVerifiedSummary } from './verifier.js'
|
|
46
47
|
|
|
47
48
|
/**
|
|
@@ -170,7 +171,7 @@ async function beforePass(
|
|
|
170
171
|
reason: 'manual',
|
|
171
172
|
trigger: hooks.trigger === 'idle' ? 'auto' : 'manual',
|
|
172
173
|
instructions: hooks.trigger === 'idle' ? null : input.instructions?.trim() || null,
|
|
173
|
-
tokensBefore:
|
|
174
|
+
tokensBefore: estimateMessagesTokensForModel(input.messages, input.model),
|
|
174
175
|
contextWindowTokens: windowTokens,
|
|
175
176
|
},
|
|
176
177
|
)
|
|
@@ -202,8 +203,8 @@ async function afterPass(
|
|
|
202
203
|
compaction: {
|
|
203
204
|
reason: 'manual',
|
|
204
205
|
trigger: hooks.trigger === 'idle' ? 'auto' : 'manual',
|
|
205
|
-
tokensBefore:
|
|
206
|
-
tokensAfter:
|
|
206
|
+
tokensBefore: estimateMessagesTokensForModel(input.messages, input.model),
|
|
207
|
+
tokensAfter: estimateMessagesTokensForModel(result.messages, input.model),
|
|
207
208
|
contextWindowTokens: windowTokens,
|
|
208
209
|
...postCompactSummary(messageText(result.summary.content)),
|
|
209
210
|
},
|
|
@@ -386,6 +387,7 @@ export async function compactNow(input: CompactNowInput): Promise<CompactionResu
|
|
|
386
387
|
config: input.config,
|
|
387
388
|
contextWindowTokens: window.tokens,
|
|
388
389
|
estimatedTokens: window.tokens,
|
|
390
|
+
...(input.model ? { model: input.model } : {}),
|
|
389
391
|
force: true,
|
|
390
392
|
allowNoSystemFloor: true,
|
|
391
393
|
skipToolResultClear: true,
|
|
@@ -433,7 +435,7 @@ export async function compactNow(input: CompactNowInput): Promise<CompactionResu
|
|
|
433
435
|
hookInstructions,
|
|
434
436
|
awaitPending: true,
|
|
435
437
|
// The swap must leave the history smaller than it is.
|
|
436
|
-
limitTokens:
|
|
438
|
+
limitTokens: estimateMessagesTokensForModel(input.messages, input.model),
|
|
437
439
|
// Only a window the host stated: the one resolved here may not know the
|
|
438
440
|
// provider's own figure the summary was sized for, and a guess must not
|
|
439
441
|
// refuse a summary that is still good.
|
|
@@ -441,8 +443,11 @@ export async function compactNow(input: CompactNowInput): Promise<CompactionResu
|
|
|
441
443
|
? { windowTokens: input.contextWindowTokens }
|
|
442
444
|
: {}),
|
|
443
445
|
tokensAfterSwap: (keepStart, summary) =>
|
|
444
|
-
|
|
445
|
-
|
|
446
|
+
estimateMessagesTokensForModel(
|
|
447
|
+
input.messages.slice(0, plan.systemMessages.length),
|
|
448
|
+
input.model,
|
|
449
|
+
) +
|
|
450
|
+
estimateMessagesTokensForModel(input.messages.slice(keepStart), input.model) +
|
|
446
451
|
Math.ceil(summary.length / CHARS_PER_TOKEN),
|
|
447
452
|
},
|
|
448
453
|
)
|
|
@@ -512,7 +517,17 @@ export async function compactNow(input: CompactNowInput): Promise<CompactionResu
|
|
|
512
517
|
input.askWhenUnclear,
|
|
513
518
|
)
|
|
514
519
|
const published = await publishManualCompaction(input, {
|
|
515
|
-
messages
|
|
520
|
+
messages: fitRetainedImages(
|
|
521
|
+
messages,
|
|
522
|
+
Math.floor(window.tokens * input.config.resetThreshold),
|
|
523
|
+
input.model,
|
|
524
|
+
input.config.keepRecentTokens === undefined
|
|
525
|
+
? undefined
|
|
526
|
+
: {
|
|
527
|
+
start: preservedSystem.length + 1 + retainedOlder.length,
|
|
528
|
+
tokens: input.config.keepRecentTokens,
|
|
529
|
+
},
|
|
530
|
+
),
|
|
516
531
|
shed: input.messages.length - messages.length,
|
|
517
532
|
summary,
|
|
518
533
|
usage,
|
package/src/compaction/plan.ts
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
planNothingToShed,
|
|
11
11
|
planWorkingSet,
|
|
12
12
|
} from './salience/working-set.js'
|
|
13
|
-
import {
|
|
13
|
+
import { estimateMessageTokensForModel, estimateMessagesTokensForModel } from './token-estimate.js'
|
|
14
14
|
import { clearStaleToolResults } from './tool-result-editing.js'
|
|
15
15
|
|
|
16
16
|
/**
|
|
@@ -67,6 +67,7 @@ export type CompactionPlan =
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
export interface CompactionPlanInput {
|
|
70
|
+
readonly model?: string
|
|
70
71
|
readonly messages: readonly Message[]
|
|
71
72
|
readonly config: CompactionConfig
|
|
72
73
|
readonly contextWindowTokens: number
|
|
@@ -116,11 +117,15 @@ export interface CompactionPlanInput {
|
|
|
116
117
|
* one boundary calculation is the failure this extraction exists to end, so
|
|
117
118
|
* the phase's copy is gone and its tests point here.
|
|
118
119
|
*/
|
|
119
|
-
export function naiveKeepStartByTokens(
|
|
120
|
+
export function naiveKeepStartByTokens(
|
|
121
|
+
messages: readonly Message[],
|
|
122
|
+
budgetTokens: number,
|
|
123
|
+
model?: string,
|
|
124
|
+
): number {
|
|
120
125
|
let tokens = 0
|
|
121
126
|
let start = messages.length
|
|
122
127
|
for (let index = messages.length - 1; index >= 0; index--) {
|
|
123
|
-
const cost =
|
|
128
|
+
const cost = estimateMessageTokensForModel(messages[index] as Message, model)
|
|
124
129
|
// Checked BEFORE adding, so the boundary never includes a message
|
|
125
130
|
// that pushes the tail over. Adding first and trimming after would
|
|
126
131
|
// admit one oversized message on every turn.
|
|
@@ -236,7 +241,8 @@ export function planCompaction(input: CompactionPlanInput): CompactionPlan {
|
|
|
236
241
|
|
|
237
242
|
if (edit.clearedCount > 0) {
|
|
238
243
|
const reclaimedTokens =
|
|
239
|
-
|
|
244
|
+
estimateMessagesTokensForModel(input.messages, input.model) -
|
|
245
|
+
estimateMessagesTokensForModel(edit.messages, input.model)
|
|
240
246
|
// NOT on a forced pass. A forced pass runs because the provider
|
|
241
247
|
// REJECTED the prompt as too long, which is a measurement — and
|
|
242
248
|
// answering it with the same estimate the provider just refuted
|
|
@@ -302,7 +308,7 @@ export function planCompaction(input: CompactionPlanInput): CompactionPlan {
|
|
|
302
308
|
const naiveKeepStart =
|
|
303
309
|
config.keepRecentTokens === undefined
|
|
304
310
|
? messages.length - config.keepRecentMessages
|
|
305
|
-
: naiveKeepStartByTokens(messages, config.keepRecentTokens)
|
|
311
|
+
: naiveKeepStartByTokens(messages, config.keepRecentTokens, input.model)
|
|
306
312
|
let keepStart = -1
|
|
307
313
|
for (let candidate = naiveKeepStart; candidate > systemMessages.length; candidate--) {
|
|
308
314
|
if (findSafeTrimIndex(messages as Message[], candidate) === candidate) {
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { Message, MessageAttachment, ToolResultBlock } from '../types/message/index.js'
|
|
2
|
+
import { findRetainedIndices } from './retention.js'
|
|
3
|
+
import {
|
|
4
|
+
estimateMessagesTokensForModel,
|
|
5
|
+
estimateRichContentTokens,
|
|
6
|
+
estimateTextTokens,
|
|
7
|
+
} from './token-estimate.js'
|
|
8
|
+
|
|
9
|
+
const MAX_RETAINED_IMAGES = 16
|
|
10
|
+
const MAX_RETAINED_IMAGE_BYTES = 8 * 1024 * 1024
|
|
11
|
+
|
|
12
|
+
type RichBlock = MessageAttachment | Exclude<ToolResultBlock, { type: 'text' }>
|
|
13
|
+
|
|
14
|
+
function isImage(block: RichBlock): boolean {
|
|
15
|
+
return block.type === 'stored' ? block.kind === 'image' : block.type !== 'document'
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function label(text: string): string {
|
|
19
|
+
return text.replace(/\s+/g, ' ').trim().slice(0, 100)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function compactedImageMarker(block: RichBlock, source: string): string {
|
|
23
|
+
const name = 'name' in block && block.name ? ` "${label(block.name)}"` : ''
|
|
24
|
+
return `[image omitted by compaction: ${label(source)}${name} (${label(block.mediaType)})]`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Fit images around the retained text and the summary. Keep a small recent
|
|
29
|
+
* set, including when a single tool call returned a batch of images.
|
|
30
|
+
* Replacements leave the producing call, caption and result ID in place.
|
|
31
|
+
*/
|
|
32
|
+
export function fitRetainedImages(
|
|
33
|
+
messages: Message[],
|
|
34
|
+
tokenLimit: number,
|
|
35
|
+
model?: string,
|
|
36
|
+
tail?: { readonly start: number; readonly tokens: number },
|
|
37
|
+
): Message[] {
|
|
38
|
+
const items: {
|
|
39
|
+
index: number
|
|
40
|
+
itemIndex: number
|
|
41
|
+
block: RichBlock
|
|
42
|
+
tokens: number
|
|
43
|
+
marker: string
|
|
44
|
+
tool: boolean
|
|
45
|
+
}[] = []
|
|
46
|
+
const tools = new Map<string, string>()
|
|
47
|
+
let newestUser = -1
|
|
48
|
+
for (const [index, message] of messages.entries()) {
|
|
49
|
+
if (message.role === 'user') newestUser = index
|
|
50
|
+
if (message.role === 'assistant') {
|
|
51
|
+
for (const call of message.toolCalls ?? []) tools.set(call.id, call.function.name)
|
|
52
|
+
}
|
|
53
|
+
const tool = message.role === 'tool'
|
|
54
|
+
const blocks =
|
|
55
|
+
message.role === 'user' ? message.attachments : tool ? message.content : undefined
|
|
56
|
+
if (!Array.isArray(blocks)) continue
|
|
57
|
+
for (const [itemIndex, block] of (
|
|
58
|
+
blocks as readonly (RichBlock | { type: 'text' })[]
|
|
59
|
+
).entries()) {
|
|
60
|
+
if (block.type === 'text' || !isImage(block)) continue
|
|
61
|
+
if ('modelOmission' in block && block.modelOmission) continue
|
|
62
|
+
const source = tool ? (tools.get(message.toolCallId) ?? 'tool result') : 'user attachment'
|
|
63
|
+
items.push({
|
|
64
|
+
index,
|
|
65
|
+
itemIndex,
|
|
66
|
+
block,
|
|
67
|
+
tokens: estimateRichContentTokens(block, model, tool),
|
|
68
|
+
marker: compactedImageMarker(block, source),
|
|
69
|
+
tool,
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (items.length === 0) return messages
|
|
74
|
+
|
|
75
|
+
let promptTokens = estimateMessagesTokensForModel(messages, model)
|
|
76
|
+
let tailTokens = tail ? estimateMessagesTokensForModel(messages.slice(tail.start), model) : 0
|
|
77
|
+
let count = items.length
|
|
78
|
+
let bytes = items.reduce((sum, { block }) => sum + ('data' in block ? block.data.length : 0), 0)
|
|
79
|
+
const retained = findRetainedIndices(messages)
|
|
80
|
+
const omitted = new Map<number, Map<number, string>>()
|
|
81
|
+
// Old tool observations go first. Within the latest user turn, keep the
|
|
82
|
+
// newest observations regardless of which role supplied them.
|
|
83
|
+
const priority = (item: (typeof items)[number]) =>
|
|
84
|
+
item.index >= newestUser ? 2 : item.tool ? 0 : 1
|
|
85
|
+
for (const item of [...items].sort((a, b) => priority(a) - priority(b))) {
|
|
86
|
+
if (retained.has(item.index)) continue
|
|
87
|
+
const overTail = tail && tailTokens > tail.tokens
|
|
88
|
+
const overPrompt =
|
|
89
|
+
promptTokens > tokenLimit || count > MAX_RETAINED_IMAGES || bytes > MAX_RETAINED_IMAGE_BYTES
|
|
90
|
+
if (!overPrompt && !overTail) break
|
|
91
|
+
if (overTail && !overPrompt && item.index < tail.start) continue
|
|
92
|
+
let blocks = omitted.get(item.index)
|
|
93
|
+
if (!blocks) {
|
|
94
|
+
blocks = new Map()
|
|
95
|
+
omitted.set(item.index, blocks)
|
|
96
|
+
}
|
|
97
|
+
blocks.set(item.itemIndex, item.marker)
|
|
98
|
+
const saved = item.tokens - estimateTextTokens(`\n${item.marker}`)
|
|
99
|
+
promptTokens -= saved
|
|
100
|
+
if (tail && item.index >= tail.start) tailTokens -= saved
|
|
101
|
+
if ('data' in item.block) bytes -= item.block.data.length
|
|
102
|
+
count--
|
|
103
|
+
}
|
|
104
|
+
if (omitted.size === 0) return messages
|
|
105
|
+
|
|
106
|
+
return messages.map((message, index) => {
|
|
107
|
+
const blocks = omitted.get(index)
|
|
108
|
+
if (!blocks) return message
|
|
109
|
+
if (message.role === 'tool' && typeof message.content !== 'string') {
|
|
110
|
+
return {
|
|
111
|
+
...message,
|
|
112
|
+
content: message.content.map((block, itemIndex): ToolResultBlock => {
|
|
113
|
+
const marker = blocks.get(itemIndex)
|
|
114
|
+
return marker ? { type: 'text', text: marker } : block
|
|
115
|
+
}),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (message.role === 'user') {
|
|
119
|
+
const { attachments, ...rest } = message
|
|
120
|
+
const kept = attachments?.filter((_, itemIndex) => !blocks.has(itemIndex)) ?? []
|
|
121
|
+
const markers = attachments?.flatMap((_, itemIndex) => blocks.get(itemIndex) ?? []) ?? []
|
|
122
|
+
return {
|
|
123
|
+
...rest,
|
|
124
|
+
content: [message.content, ...markers].filter(Boolean).join('\n'),
|
|
125
|
+
...(kept.length > 0 ? { attachments: kept } : {}),
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return message
|
|
129
|
+
})
|
|
130
|
+
}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer'
|
|
1
2
|
import { CHARS_PER_TOKEN } from '../constants/limits.js'
|
|
3
|
+
import {
|
|
4
|
+
pngSize,
|
|
5
|
+
screenshotLimitsForModel,
|
|
6
|
+
screenshotTargetSize,
|
|
7
|
+
} from '../tools/builtins/computer-use-image.js'
|
|
2
8
|
import type { Message, MessageAttachment, ToolResultBlock } from '../types/message/index.js'
|
|
3
9
|
|
|
4
10
|
// Heuristic allowances, not provider billing formulas or upper bounds. Encoded
|
|
@@ -8,10 +14,68 @@ const IMAGE_TOKENS = 1_024
|
|
|
8
14
|
const DOCUMENT_TOKENS = 4_096
|
|
9
15
|
const OMITTED_IMAGE_TOKENS = 64
|
|
10
16
|
|
|
11
|
-
function
|
|
12
|
-
|
|
17
|
+
export function estimateRichContentTokens(
|
|
18
|
+
block: Exclude<ToolResultBlock, { type: 'text' }> | MessageAttachment,
|
|
19
|
+
model = '',
|
|
20
|
+
toolResult = false,
|
|
21
|
+
): number {
|
|
22
|
+
const id = model.toLowerCase().split('/').at(-1) ?? ''
|
|
23
|
+
const limits = screenshotLimitsForModel(model)
|
|
24
|
+
const gemini = /^gemini-[34](?:[.-]|$)/.test(id)
|
|
25
|
+
const modernPatches = /^(?:gpt-6-astra|gpt-5\.[456])(?:[.-]|$)/.test(id)
|
|
26
|
+
const widePatches = /^gpt-5\.2(?:-|$)/.test(id)
|
|
27
|
+
let tileCost = 0
|
|
28
|
+
if (/^gpt-5(?:\.1)?(?:-20|$)/.test(id)) tileCost = 140
|
|
29
|
+
if (/^gpt-4o-mini(?:-|$)/.test(id)) tileCost = 5667
|
|
30
|
+
if (/^gpt-4(?:o|\.1)(?:-20|$)/.test(id)) tileCost = 170
|
|
31
|
+
|
|
32
|
+
let visualLimit = IMAGE_TOKENS
|
|
33
|
+
if (id.startsWith('claude-')) visualLimit = limits.maxTiles
|
|
34
|
+
if (gemini) visualLimit = 1120
|
|
35
|
+
if (modernPatches) visualLimit = 3000
|
|
36
|
+
if (widePatches) visualLimit = 7373
|
|
37
|
+
if (tileCost) visualLimit = Math.ceil(4.5 * tileCost)
|
|
38
|
+
if (block.type === 'stored') return block.kind === 'image' ? visualLimit : DOCUMENT_TOKENS
|
|
13
39
|
if (block.type === 'document') return DOCUMENT_TOKENS
|
|
14
|
-
|
|
40
|
+
if (block.modelOmission) return OMITTED_IMAGE_TOKENS
|
|
41
|
+
// Read just the PNG header. Other raster formats use the model allowance.
|
|
42
|
+
if (
|
|
43
|
+
gemini ||
|
|
44
|
+
block.mediaType !== 'image/png' ||
|
|
45
|
+
block.data.length < 32 ||
|
|
46
|
+
!block.data.startsWith('iVBORw0KGgo')
|
|
47
|
+
)
|
|
48
|
+
return visualLimit
|
|
49
|
+
const header = Buffer.from(block.data.slice(0, 32), 'base64')
|
|
50
|
+
if (header.length < 24 || header.toString('ascii', 12, 16) !== 'IHDR') return visualLimit
|
|
51
|
+
const { width, height } = pngSize(header)
|
|
52
|
+
if (!width || !height) return visualLimit
|
|
53
|
+
if (modernPatches || widePatches) {
|
|
54
|
+
let edge = 2048
|
|
55
|
+
let patchLimit = widePatches ? 6144 : 2500
|
|
56
|
+
// Tool observations use high detail. Recent families can use original
|
|
57
|
+
// resolution by default for pasted images.
|
|
58
|
+
if (!toolResult && /^gpt-5\.5(?:-|$)/.test(id)) {
|
|
59
|
+
edge = 6000
|
|
60
|
+
patchLimit = 10_000
|
|
61
|
+
}
|
|
62
|
+
if (!toolResult && /^(?:gpt-6-astra|gpt-5\.6)(?:-|$)/.test(id)) {
|
|
63
|
+
edge = 65_535
|
|
64
|
+
patchLimit = 30_000
|
|
65
|
+
}
|
|
66
|
+
const scale = Math.min(1, edge / Math.max(width, height))
|
|
67
|
+
const patches = Math.ceil((width * scale) / 32) * Math.ceil((height * scale) / 32)
|
|
68
|
+
return Math.ceil(1.2 * Math.min(patchLimit, patches))
|
|
69
|
+
}
|
|
70
|
+
if (tileCost) {
|
|
71
|
+
const scale = Math.min(1, 2048 / Math.max(width, height), 768 / Math.min(width, height))
|
|
72
|
+
return (
|
|
73
|
+
Math.floor(tileCost / 2) +
|
|
74
|
+
tileCost * Math.ceil((width * scale) / 512) * Math.ceil((height * scale) / 512)
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
const sized = screenshotTargetSize(width, height, limits)
|
|
78
|
+
return Math.ceil(sized.width / 28) * Math.ceil(sized.height / 28)
|
|
15
79
|
}
|
|
16
80
|
|
|
17
81
|
/**
|
|
@@ -19,11 +83,15 @@ function richTokens(block: Exclude<ToolResultBlock, { type: 'text' }> | MessageA
|
|
|
19
83
|
*
|
|
20
84
|
* Text and tool inputs use the existing characters-per-token approximation.
|
|
21
85
|
* Images and documents have an explicit allowance independent of compression
|
|
22
|
-
* and
|
|
23
|
-
*
|
|
86
|
+
* and fall back to an allowance for legacy stored images and formats without
|
|
87
|
+
* cheaply available dimensions. Exact costs depend on the serving model. In
|
|
24
88
|
* particular, serialized base64 is never treated as model-visible prose.
|
|
25
89
|
*/
|
|
26
90
|
export function estimateMessageTokens(message: Message): number {
|
|
91
|
+
return estimateMessageTokensForModel(message)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function estimateMessageTokensForModel(message: Message, model?: string): number {
|
|
27
95
|
let chars = 0
|
|
28
96
|
let rich = 0
|
|
29
97
|
if (typeof message.content === 'string') chars += message.content.length
|
|
@@ -31,7 +99,7 @@ export function estimateMessageTokens(message: Message): number {
|
|
|
31
99
|
for (const block of message.content) {
|
|
32
100
|
if (block.type === 'text') chars += block.text.length
|
|
33
101
|
else {
|
|
34
|
-
rich +=
|
|
102
|
+
rich += estimateRichContentTokens(block, model, message.role === 'tool')
|
|
35
103
|
if (block.type === 'document') chars += block.name?.length ?? 0
|
|
36
104
|
}
|
|
37
105
|
}
|
|
@@ -43,7 +111,7 @@ export function estimateMessageTokens(message: Message): number {
|
|
|
43
111
|
}
|
|
44
112
|
if (message.role === 'user') {
|
|
45
113
|
for (const attachment of message.attachments ?? []) {
|
|
46
|
-
rich +=
|
|
114
|
+
rich += estimateRichContentTokens(attachment, model)
|
|
47
115
|
if (attachment.type === 'document' || attachment.type === 'stored') {
|
|
48
116
|
chars += attachment.name?.length ?? 0
|
|
49
117
|
}
|
|
@@ -58,5 +126,15 @@ export function estimateTextTokens(text: string): number {
|
|
|
58
126
|
}
|
|
59
127
|
|
|
60
128
|
export function estimateMessagesTokens(messages: readonly Message[]): number {
|
|
61
|
-
return messages
|
|
129
|
+
return estimateMessagesTokensForModel(messages)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function estimateMessagesTokensForModel(
|
|
133
|
+
messages: readonly Message[],
|
|
134
|
+
model?: string,
|
|
135
|
+
): number {
|
|
136
|
+
return messages.reduce(
|
|
137
|
+
(total, message) => total + estimateMessageTokensForModel(message, model),
|
|
138
|
+
0,
|
|
139
|
+
)
|
|
62
140
|
}
|