perf(core): cut repeated work in Code Mode runs (#66250)

This commit is contained in:
Aiden Cline 2026-11-25 01:02:26 -06:00 • committed by GitHub
parent fb5ba10f4f
commit df2f7837e1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 138 additions and 30 deletions

View file

@ -423,6 +423,22 @@ const rank = (
.map(({ entry }) => entry)
}
// Each tool by its path and by the expression that calls it, for exact-match lookups. Both are unique per tool.
const exactEntries = new WeakMap<
ReadonlyArray<SearchEntry>,
{ readonly paths: Map<string, SearchEntry>; readonly expressions: Map<string, SearchEntry> }
>()
const exactLookup = (searchIndex: ReadonlyArray<SearchEntry>) => {
const known = exactEntries.get(searchIndex)
if (known !== undefined) return known
const made = {
paths: new Map(searchIndex.map((entry) => [entry.description.path, entry])),
expressions: new Map(searchIndex.map((entry) => [toolExpression(entry.description.path), entry])),
}
exactEntries.set(searchIndex, made)
return made
}
const makeSearchTool = (searchIndex: ReadonlyArray<SearchEntry>): Tool => ({
_tag: "CodeModeTool",
description: "Search available tools",
@ -438,18 +454,18 @@ const makeSearchTool = (searchIndex: ReadonlyArray<SearchEntry>): Tool => ({
if (ns === "tools") ns = undefined
else if (ns.startsWith("tools.")) ns = ns.slice("tools.".length)
}
const scoped =
ns === undefined
? searchIndex
: searchIndex.filter((entry) => entry.description.path === ns || entry.description.path.startsWith(`${ns}.`))
const inScope = (entry: SearchEntry) =>
ns === undefined || entry.description.path === ns || entry.description.path.startsWith(`${ns}.`)
const scoped = ns === undefined ? searchIndex : searchIndex.filter(inScope)
const trimmed = query.trim()
const pathQuery = trimmed.startsWith("tools.") ? trimmed.slice("tools.".length) : trimmed
const lookup = exactLookup(searchIndex)
const exact =
pathQuery === ""
? undefined
: scoped.find(
(entry) => entry.description.path === pathQuery || toolExpression(entry.description.path) === trimmed,
)
: [lookup.paths.get(pathQuery), lookup.expressions.get(trimmed)]
.filter((entry): entry is SearchEntry => entry !== undefined && inScope(entry))
.toSorted((left, right) => left.position - right.position)[0]
const ranked = exact !== undefined ? [exact] : rank(scoped, pathQuery, searchIndex)
const items = ranked.slice(offset, offset + (request.limit ?? defaultSearchLimit)).map(({ description }) => ({
...description,
@ -784,15 +800,18 @@ export const globals = <R>(
}
// `search("notes")` is shorthand for `search({ query: "notes" })`.
const searchCall = (args: ReadonlyArray<unknown>, call: Host.Call) =>
executeTool(
let searchTool: Tool | undefined
const searchCall = (args: ReadonlyArray<unknown>, call: Host.Call) => {
const tool = (searchTool ??= makeSearchTool(prepared.searchIndex))
return executeTool(
"search",
makeSearchTool(prepared.searchIndex),
makeSearchTool(prepared.searchIndex).execute as ExecuteFn<unknown, unknown, R>,
tool,
tool.execute as ExecuteFn<unknown, unknown, R>,
typeof args[0] === "string" ? [{ query: args[0] }, ...args.slice(1)] : args,
call,
false,
)
}
const search = Host.fn(searchCall, { type: "sync-thenable" })
// Models often write `tools.search(...)` for the bare `search(...)`; it is honored unless a tool owns that path.
const searchAlias = Host.fn(searchCall, { type: "async" })

View file

@ -1117,6 +1117,37 @@ describe("CodeMode public contract", () => {
if (!invalid.ok) expect(invalid.error.kind).toBe("InvalidToolInput")
})
test("an exact match is the first tool in scope that the query names by path or by call expression", async () => {
const simple = (description: string) =>
Tool.make({
description,
input: Schema.Struct({ id: Schema.String }),
output: Schema.String,
execute: () => Effect.succeed("ok"),
})
const runtime = CodeMode.make({
tools: {
"a-b": simple("Dashed"),
'tools["a-b"]': simple("Bracketed"),
github: { list_issues: simple("List issues") },
linear: { list_issues: simple("List Linear issues") },
},
})
const search = async (input: unknown) => {
const result = await Effect.runPromise(runtime.execute(`return search(${JSON.stringify(input)})`))
if (!result.ok) throw new Error(result.error.message)
return (result.value as { items: Array<{ path: string; description: string }> }).items
}
expect(await search('tools["a-b"]')).toMatchObject([{ path: 'tools["a-b"]', description: "Dashed" }])
expect(await search({ query: "linear.list_issues", namespace: "linear" })).toMatchObject([
{ path: "tools.linear.list_issues" },
])
expect((await search({ query: "linear.list_issues", namespace: "github" })).map((item) => item.path)).toEqual([
"tools.github.list_issues",
])
})
test("matches input parameter names and partial-word substrings", async () => {
const upload = Tool.make({
description: "Send a document to the workspace",

View file

@ -410,12 +410,13 @@ const glob = (host: Host, given: string, cwd: string, dot: boolean) =>
() => Effect.succeed([]),
),
)
const matches = Glob.matcher(pattern, { dot })
return entries
.map((entry) => ({
path: path.isAbsolute(pattern) ? path.join(base, entry.path) : path.join(path.relative(cwd, base), entry.path),
type: entry.type,
}))
.filter((entry) => Glob.match(pattern, entry.path, { dot }))
.filter((entry) => matches(entry.path))
})
type Entry = { readonly path: string; readonly type: Environment.FileType }
@ -526,11 +527,12 @@ export const extension = Extension.make({
write: Extension.async(writeTo),
Glob: Extension.constructible((pattern: string) => {
if (typeof pattern !== "string") throw new TypeError("Bun.Glob expects a pattern string.")
const matches = Glob.matcher(pattern)
return {
scan: (options?: string | ScanOptions) => scan(pattern, options),
scanSync: (options?: string | ScanOptions) => scan(pattern, options),
// As in Bun, `match` takes a dot file that a scan without `dot` leaves out.
match: (name: string) => Glob.match(pattern, name),
match: (name: string) => matches(name),
}
}),
},

View file

@ -73,12 +73,19 @@ export const make = Effect.fnUntraced(function* (
),
),
}).pipe(Effect.provideService(Job.BlockingParent, id), Effect.interruptible, Effect.exit)
yield* Deferred.done(result, exit)
// With one text part, bounding the result gives the same text as bounding the body, so the full output
// is saved once and the step's own truncation keeps the bounded result.
const single =
Exit.isSuccess(exit) &&
exit.value.metadata?.truncated === undefined &&
exit.value.content.filter((part) => part.type === "text").length === 1
const bounded = single ? Exit.succeed(yield* output.truncate(exit.value)) : exit
yield* Deferred.done(result, bounded)
if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause)
const text = Exit.isFailure(exit)
? Cause.pretty(exit.cause)
: exit.value.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
const body = yield* truncate(text)
const text = Exit.isFailure(bounded)
? Cause.pretty(bounded.cause)
: bounded.value.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
const body = single ? text : yield* truncate(text)
if (Exit.isFailure(exit) || exit.value.metadata?.error === true) return yield* Effect.fail(new Error(body))
return body
}),

View file

@ -167,7 +167,8 @@ export const create = (
Effect.gen(function* () {
const callIndex = yield* Ref.make(0)
const files = yield* Ref.make<Array<CollectedFiles>>([])
const calls = yield* Ref.make<Array<ExecuteCall>>([])
// Changed only under the lock; each publish and the result take a copy.
const calls: Array<ExecuteCall> = []
const lock = Semaphore.makeUnsafe(1)
// Each update replaces the last, so send at most one per 100 ms; a trailing one carries the latest rows.
// A success drops a pending one when the scope closes, since the result carries the final rows.
@ -179,14 +180,14 @@ export const create = (
yield* Ref.set(publishedAt, yield* Clock.currentTimeMillis)
const changed = diffs.files()
yield* context.progress({
toolCalls: yield* Ref.get(calls),
toolCalls: calls.slice(),
...(changed.length > 0 ? { files: changed } : {}),
})
})
const record = (update: (items: Array<ExecuteCall>) => Array<ExecuteCall>) =>
const record = (update: (items: Array<ExecuteCall>) => void) =>
lock.withPermit(
Effect.gen(function* () {
yield* Ref.update(calls, update)
update(calls)
if (yield* Ref.get(trailing)) return
const wait = (yield* Ref.get(publishedAt)) + 100 - (yield* Clock.currentTimeMillis)
if (wait <= 0) return yield* publish
@ -196,7 +197,7 @@ export const create = (
)
// The files the program changes, shown under the call as it runs and when it ends in the foreground. A failed
// or stopped one keeps them too, since they really changed.
const diffs = CodeModeDiffs.make(record((items) => items))
const diffs = CodeModeDiffs.make(record(() => {}))
const result = yield* runtime(inventory)
.execute(code, undefined, {
extensions: runExtensions(services !== undefined),
@ -240,7 +241,7 @@ export const create = (
Effect.provide(yield* executionServices(context, permission, services, api)),
Effect.provideService(CodeModeDiffs.Service, diffs),
)
const toolCalls = yield* Ref.get(calls)
const toolCalls = calls.slice()
const collected = (yield* Ref.get(files))
.toSorted((left, right) => left.index - right.index)
.flatMap((item) => item.files)
@ -276,20 +277,18 @@ export const create = (
}
// Rows appear in start order; the same call object arrives at both hooks, so a call finds its row again.
function progressHooks(record: (update: (items: Array<ExecuteCall>) => Array<ExecuteCall>) => Effect.Effect<unknown>) {
function progressHooks(record: (update: (items: Array<ExecuteCall>) => void) => Effect.Effect<unknown>) {
const rows = new WeakMap<object, number>()
const start = (call: object, entry: ExecuteCall) =>
record((items) => {
rows.set(call, items.length)
return [...items, entry]
items.push(entry)
})
const settle = (call: object, result: CodeMode.CallResult) => {
const index = rows.get(call)
if (index === undefined) return Effect.void
return record((items) => {
const next = [...items]
next[index] = { ...items[index], status: result.status === "success" ? "completed" : "error" }
return next
items[index] = { ...items[index], status: result.status === "success" ? "completed" : "error" }
})
}
return {

View file

@ -148,4 +148,37 @@ describe("execute timeout and background", () => {
expect(h.notices[0]?.text).toContain("done")
}),
)
it.live("a foreground script's output is bounded once, for both its result and its job", () =>
Effect.gen(function* () {
const jobs = yield* Job.Service
const truncated: Array<Tool.NormalizedResult> = []
let finished: Job.Info | undefined
const run = yield* CodeModeJob.make(
{
...jobs,
block: (input) =>
jobs.block(input).pipe(Effect.tap((blocked) => Effect.sync(() => void (finished = blocked?.info)))),
},
() => Effect.die("no notice expected"),
yield* Scope.make(),
).pipe(
Effect.provideService(ToolOutput.Service, {
truncate: (result: Tool.NormalizedResult) =>
Effect.sync(() => {
truncated.push(result)
return {
...result,
content: [{ type: "text" as const, text: "bounded" }],
metadata: { ...result.metadata, truncated: true },
}
}),
} as unknown as ToolOutput.Interface),
)
if (!run) throw new Error("no job runner")
const result = yield* run(context("ses_bounded"), script(0))
expect(truncated).toHaveLength(1)
expect(result).toMatchObject({ content: [{ type: "text", text: "bounded" }], metadata: { truncated: true } })
expect(finished?.output).toBe("bounded")
}),
)
})

View file

@ -1,5 +1,5 @@
import { glob, type GlobOptionsWithFileTypesFalse } from "glob"
import { minimatch } from "minimatch"
import { Minimatch, minimatch } from "minimatch"
export namespace Glob {
export interface Options {
@ -29,4 +29,10 @@ export namespace Glob {
export function match(pattern: string, filepath: string, options: { dot?: boolean } = {}): boolean {
return minimatch(filepath, pattern, { dot: options.dot ?? true })
}
/** `match` for one pattern, compiled on first use and reused for every later path. */
export function matcher(pattern: string, options: { dot?: boolean } = {}): (filepath: string) => boolean {
let compiled: Minimatch | undefined
return (filepath) => (compiled ??= new Minimatch(pattern, { dot: options.dot ?? true })).match(filepath)
}
}

View file

@ -0,0 +1,11 @@
import { expect, test } from "bun:test"
import { Glob } from "../src/glob.js"
test("a compiled matcher agrees with match", () => {
const paths = ["a.ts", "src/b.ts", ".hidden/c.ts", "src/.d.ts", "e.js", "#notes", "src/nested/f.tsx"]
for (const pattern of ["**/*.ts", "*.{ts,js}", "src/**", ".*/*", "#notes", "**/*.ts?(x)", "!(*.ts)"])
for (const dot of [undefined, true, false]) {
const matches = Glob.matcher(pattern, { dot })
expect(paths.map(matches)).toEqual(paths.map((path) => Glob.match(pattern, path, { dot })))
}
})