@cat-factory/executor-harness 1.60.0 → 1.64.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/README.md +10 -1
- package/dist/agent-runner.js +81 -8
- package/dist/agent.js +9 -3
- package/dist/claude-stream.js +18 -0
- package/dist/coding-agent.js +32 -4
- package/dist/embed.js +2 -1
- package/dist/git.js +0 -319
- package/dist/host-markdown.js +142 -0
- package/dist/pi-workspace.js +35 -2
- package/dist/pi.js +15 -184
- package/dist/pr-description.js +157 -0
- package/dist/progress-guard.js +211 -0
- package/dist/subagents.js +1 -50
- package/dist/vcs-api.js +402 -0
- package/package.json +4 -3
- package/src/agent-runner.ts +88 -8
- package/src/agent.ts +8 -3
- package/src/claude-stream.ts +19 -0
- package/src/coding-agent.ts +45 -3
- package/src/embed.ts +5 -3
- package/src/git.ts +1 -385
- package/src/host-markdown.ts +155 -0
- package/src/pi-workspace.ts +40 -4
- package/src/pi.ts +26 -252
- package/src/pr-description.ts +171 -0
- package/src/progress-guard.ts +285 -0
- package/src/subagents.ts +7 -16
- package/src/vcs-api.ts +512 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { readFile, rm } from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { inertInline, inertMarkdown, walkFences } from './host-markdown.js'
|
|
4
|
+
import { redactSecrets } from './redact.js'
|
|
5
|
+
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
// The agent-authored pull-request description side channel. A coding agent whose
|
|
8
|
+
// dispatch opens a PR is asked (via the backend-composed system prompt) to end its
|
|
9
|
+
// run by writing a reviewer briefing — the problem, the decisions made, what to
|
|
10
|
+
// look out for — to a sentinel file at the root of the checkout the PR belongs to.
|
|
11
|
+
// The harness reads it after the agent settles, removes it (so it never lands in a
|
|
12
|
+
// commit), and uses it as the PR body in place of the generic dispatch-time text
|
|
13
|
+
// the job body carries. Absent or unusable ⇒ the dispatch-time fallback, unchanged.
|
|
14
|
+
//
|
|
15
|
+
// The briefing is MODEL-AUTHORED text landing verbatim on a host-parsed surface, so
|
|
16
|
+
// it crosses `host-markdown.ts` (auto-link triggers defused, open code fences closed)
|
|
17
|
+
// on the way out — see that module for why a PR body is not an inert string sink.
|
|
18
|
+
//
|
|
19
|
+
// The filename is kept in sync with `PR_DESCRIPTION_FILE` in `@cat-factory/agents`
|
|
20
|
+
// (the executor-harness has no dependency on that package), exactly like the
|
|
21
|
+
// effort-report and follow-ups sentinels.
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
/** The sentinel file the agent writes its PR description to (relative to the checkout root). */
|
|
25
|
+
export const PR_DESCRIPTION_FILE = '.cat-pr-description.md'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Ceiling on the agent-authored body.
|
|
29
|
+
*
|
|
30
|
+
* The engine appends its verification report to the SAME body later, and that section carries
|
|
31
|
+
* its own 50,000-character ceiling (`MAX_SECTION_CHARS` in kernel's `hostMarkdown`). GitHub
|
|
32
|
+
* rejects a body over 65,536 with a 422, and the report publisher swallows its own failures —
|
|
33
|
+
* so a briefing budget that does not leave the report room would surface as a report that
|
|
34
|
+
* silently never publishes. 15,000 + 50,000 stays under the limit with room to join them.
|
|
35
|
+
*/
|
|
36
|
+
const MAX_PR_BODY_CHARS = 15_000
|
|
37
|
+
|
|
38
|
+
/** Ceiling on an agent-supplied title (GitHub truncates around 256; a title should be short). */
|
|
39
|
+
const MAX_PR_TITLE_CHARS = 160
|
|
40
|
+
|
|
41
|
+
/** Opens the engine-managed region of a PR body (kept in sync with `kernel/domain/pr-report.ts`). */
|
|
42
|
+
export const PR_REPORT_MARKER_START = '<!-- cat-factory:verification-report:start -->'
|
|
43
|
+
/** Closes the engine-managed region of a PR body. */
|
|
44
|
+
export const PR_REPORT_MARKER_END = '<!-- cat-factory:verification-report:end -->'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A marker inside the agent-authored briefing would make the engine's splice treat part of the
|
|
48
|
+
* briefing as its own managed region and rewrite it, so any occurrence is stripped up front.
|
|
49
|
+
* Deliberately laxer than the exact constants above (whitespace-tolerant), so a near-miss the
|
|
50
|
+
* splice itself would not match cannot survive here either.
|
|
51
|
+
*/
|
|
52
|
+
const MANAGED_SECTION_MARKER = /<!--\s*cat-factory:verification-report:(?:start|end)\s*-->/g
|
|
53
|
+
|
|
54
|
+
/** An agent-authored PR description: an optional title plus the briefing body. */
|
|
55
|
+
export interface AgentPrDescription {
|
|
56
|
+
title?: string
|
|
57
|
+
body?: string
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Read + parse + REMOVE the agent's PR-description sentinel from `dir`. Lenient: returns
|
|
62
|
+
* undefined when the file is absent (the agent wrote none) or carries nothing usable. Never
|
|
63
|
+
* throws — a bad description must never fail an otherwise-good run; the caller falls back to
|
|
64
|
+
* the dispatch-time text.
|
|
65
|
+
*
|
|
66
|
+
* A SINGLE `# <title>` heading on the first line sets the PR title; everything after it is the
|
|
67
|
+
* body (see {@link splitTitle} for why a LONE heading is required). The whole text is
|
|
68
|
+
* secret-scrubbed, an over-budget body is truncated WITH a visible note (a silent cut would
|
|
69
|
+
* read as the complete briefing), and both halves are made inert for the host.
|
|
70
|
+
*
|
|
71
|
+
* On scrubbing: `redactSecrets`'s credential-assignment rule is deliberately eager, so a
|
|
72
|
+
* briefing sentence like "the token: handling changed" loses its next word. That is the right
|
|
73
|
+
* trade for a surface this public — the rule is shared with every other redaction path, and
|
|
74
|
+
* narrowing it so prose reads better would weaken all of them.
|
|
75
|
+
*/
|
|
76
|
+
export async function readPrDescription(dir: string): Promise<AgentPrDescription | undefined> {
|
|
77
|
+
const path = join(dir, PR_DESCRIPTION_FILE)
|
|
78
|
+
let raw: string
|
|
79
|
+
try {
|
|
80
|
+
raw = await readFile(path, 'utf8')
|
|
81
|
+
} catch {
|
|
82
|
+
return undefined // no description written — the fallback body applies
|
|
83
|
+
}
|
|
84
|
+
// Remove it so it never lands in a commit (defence in depth; the checkout also excludes it).
|
|
85
|
+
await rm(path, { force: true }).catch(() => {})
|
|
86
|
+
const text = redactSecrets(raw).replace(MANAGED_SECTION_MARKER, '').trim()
|
|
87
|
+
if (!text) return undefined
|
|
88
|
+
|
|
89
|
+
const split = splitTitle(text)
|
|
90
|
+
// Cap BEFORE the escapes on both halves, so a numeric entity can never be sliced in half.
|
|
91
|
+
const title = split.title ? inertInline(capTitle(split.title)) : undefined
|
|
92
|
+
const body = split.body ? inertMarkdown(capBody(split.body)) : undefined
|
|
93
|
+
if (!title && !body) return undefined
|
|
94
|
+
return { ...(title ? { title } : {}), ...(body ? { body } : {}) }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Split a leading `# <title>` heading off the briefing.
|
|
99
|
+
*
|
|
100
|
+
* The heading becomes the title ONLY when it is the single level-1 heading in the whole file,
|
|
101
|
+
* which is exactly what the prompt asks for ("a single `# <title>` heading line"). An agent
|
|
102
|
+
* that instead uses `#` for its section headings — `# Problem`, `# Decisions`, entirely
|
|
103
|
+
* idiomatic for the briefing the prompt describes — would otherwise have its first section
|
|
104
|
+
* silently become the pull request's title, replacing `<block> (<pipeline>)` with the word
|
|
105
|
+
* "Problem". Headings inside fenced code are not headings and are skipped, or a briefing
|
|
106
|
+
* quoting a shell snippet (`# rebuild the image`) would lose its title to the snippet.
|
|
107
|
+
*/
|
|
108
|
+
function splitTitle(text: string): { title?: string; body: string } {
|
|
109
|
+
const lines = text.split('\n')
|
|
110
|
+
const headings: number[] = []
|
|
111
|
+
let index = 0
|
|
112
|
+
walkFences(lines, (line, insideFence) => {
|
|
113
|
+
if (!insideFence && /^#\s+\S/.test(line)) headings.push(index)
|
|
114
|
+
index += 1
|
|
115
|
+
})
|
|
116
|
+
if (headings.length !== 1 || headings[0] !== 0) return { body: text }
|
|
117
|
+
const title = lines[0]!.replace(/^#\s+/, '').trim()
|
|
118
|
+
if (!title) return { body: text }
|
|
119
|
+
return { title, body: lines.slice(1).join('\n').trim() }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Cut an over-long title at a word boundary when one is near, marking the cut. */
|
|
123
|
+
function capTitle(value: string): string {
|
|
124
|
+
const collapsed = value.trim()
|
|
125
|
+
if (collapsed.length <= MAX_PR_TITLE_CHARS) return collapsed
|
|
126
|
+
const head = collapsed.slice(0, MAX_PR_TITLE_CHARS - 1)
|
|
127
|
+
const space = head.lastIndexOf(' ')
|
|
128
|
+
const kept = space > MAX_PR_TITLE_CHARS * 0.6 ? head.slice(0, space) : head
|
|
129
|
+
return `${kept.trimEnd()}…`
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Cut an over-budget body, marking the cut so it is never read as the whole briefing. */
|
|
133
|
+
function capBody(value: string): string {
|
|
134
|
+
if (value.length <= MAX_PR_BODY_CHARS) return value
|
|
135
|
+
return (
|
|
136
|
+
value.slice(0, MAX_PR_BODY_CHARS).trimEnd() +
|
|
137
|
+
'\n\n_Truncated by the platform: the description exceeded the size budget._'
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Fold an agent-authored description over the dispatch-time fallback the job body carries.
|
|
143
|
+
* Field-wise: the agent's title/body each win when present, so a body-only briefing keeps the
|
|
144
|
+
* backend-composed title and vice versa.
|
|
145
|
+
*/
|
|
146
|
+
export function applyPrDescription(
|
|
147
|
+
fallback: { title: string; body: string },
|
|
148
|
+
agent: AgentPrDescription | undefined,
|
|
149
|
+
): { title: string; body: string } {
|
|
150
|
+
if (!agent) return fallback
|
|
151
|
+
return { title: agent.title ?? fallback.title, body: agent.body ?? fallback.body }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The body to PATCH onto an ALREADY-OPEN pull request when a resumed run produced a fresh
|
|
156
|
+
* briefing: the new description followed by whatever the engine's managed verification-report
|
|
157
|
+
* region currently holds.
|
|
158
|
+
*
|
|
159
|
+
* Carrying the region across is what makes the refresh safe. The engine re-publishes the report
|
|
160
|
+
* on every step settlement, so dropping it here would usually self-heal — but "usually" is not
|
|
161
|
+
* a property to rest the one artefact a reviewer reads on, and a run that settles no further
|
|
162
|
+
* step (the work is already merged, the run failed after its push) would never restore it.
|
|
163
|
+
*/
|
|
164
|
+
export function preserveManagedSection(currentBody: string | undefined, nextBody: string): string {
|
|
165
|
+
const existing = currentBody ?? ''
|
|
166
|
+
const start = existing.indexOf(PR_REPORT_MARKER_START)
|
|
167
|
+
const end = existing.indexOf(PR_REPORT_MARKER_END)
|
|
168
|
+
if (start === -1 || end <= start) return nextBody
|
|
169
|
+
const region = existing.slice(start, end + PR_REPORT_MARKER_END.length)
|
|
170
|
+
return `${nextBody.trim()}\n\n${region}\n`
|
|
171
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { SUBAGENT_TOOL_NAMES } from './claude-stream.js'
|
|
2
|
+
|
|
3
|
+
// The harness's no-progress guard: the live anti-rabbithole bound every agent run is held to,
|
|
4
|
+
// plus the tool-name vocabulary it classifies calls with and the limits it reads from the
|
|
5
|
+
// environment. Extracted from `pi.ts` when the guard stopped being Pi's: it now also drives the
|
|
6
|
+
// claude-code subscription runner (`agent-runner.ts` feeds it via `observeSignal`), so the two
|
|
7
|
+
// harnesses share ONE definition of "this run has stopped making progress" — and the tool-name
|
|
8
|
+
// sets below deliberately cover both CLIs' vocabularies.
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Tool-call signal read off a streamed Pi event, or undefined if not a tool call. Exported for
|
|
12
|
+
* `runPi`'s span emitter, which reads the same event for its per-tool trace spans.
|
|
13
|
+
*/
|
|
14
|
+
export function toolCallSignal(
|
|
15
|
+
event: Record<string, unknown>,
|
|
16
|
+
): { name: string; isError: boolean } | undefined {
|
|
17
|
+
// `tool_execution_end` is the canonical per-call stream event (statsFromEvents
|
|
18
|
+
// counts the same one), so the guard reads it and nothing else — no double count.
|
|
19
|
+
if (event.type !== 'tool_execution_end') return undefined
|
|
20
|
+
const name = typeof event.toolName === 'string' ? event.toolName : ''
|
|
21
|
+
return { name, isError: event.isError === true }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Tunable bounds for the {@link ProgressGuard}. */
|
|
25
|
+
export interface ProgressGuardLimits {
|
|
26
|
+
/**
|
|
27
|
+
* Abort once the agent has made this many NON-exploration tool calls without ever
|
|
28
|
+
* using a file-editing tool (see `FILE_EDIT_TOOLS`). The signature of the credential
|
|
29
|
+
* rabbit-hole that motivated this: probing the environment (`bash`/exec) endlessly
|
|
30
|
+
* without implementing anything. Read-only exploration (`read`/`grep`/… — see
|
|
31
|
+
* `EXPLORATION_TOOLS`) and planning (`todo`) do NOT count, so a large task that
|
|
32
|
+
* legitimately reads/searches many files before its first edit is not killed for it.
|
|
33
|
+
* Disabled when `expectsEdits` is false (e.g. the assess-only merger / Blueprinter,
|
|
34
|
+
* which legitimately edit nothing). Note this bound only guards the run UNTIL its
|
|
35
|
+
* first edit: once the agent has edited a file at all, it has demonstrably started
|
|
36
|
+
* the work, so only `maxConsecutiveErrors` guards a later stall.
|
|
37
|
+
*/
|
|
38
|
+
maxToolCallsWithoutEdit: number
|
|
39
|
+
/**
|
|
40
|
+
* Abort after this many consecutive failing tool calls — the agent is stuck
|
|
41
|
+
* retrying an operation that keeps failing rather than making progress.
|
|
42
|
+
*/
|
|
43
|
+
maxConsecutiveErrors: number
|
|
44
|
+
/**
|
|
45
|
+
* Abort after this many consecutive web-search/web-fetch calls with no other tool
|
|
46
|
+
* call in between. Web tools are read-only exploration (they don't count toward the
|
|
47
|
+
* no-edit bound), so without this a model could rabbit-hole on searches indefinitely
|
|
48
|
+
* without ever tripping a guard. Any non-web tool call resets the streak. Optional:
|
|
49
|
+
* defaults to {@link DEFAULT_PROGRESS_GUARD_LIMITS} when a caller builds limits
|
|
50
|
+
* without it.
|
|
51
|
+
*/
|
|
52
|
+
maxConsecutiveWebCalls?: number
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// `satisfies` (not a type annotation) so each property keeps its concrete `number`
|
|
56
|
+
// type — `maxConsecutiveWebCalls` is optional on the interface (callers may omit it),
|
|
57
|
+
// but the defaults always define it, so consumers reading it off here get a `number`.
|
|
58
|
+
export const DEFAULT_PROGRESS_GUARD_LIMITS = {
|
|
59
|
+
// Counts only non-exploration, non-planning calls (see EXPLORATION_TOOLS), so the
|
|
60
|
+
// ceiling can be generous without risking a false kill on a read-heavy large task.
|
|
61
|
+
maxToolCallsWithoutEdit: 40,
|
|
62
|
+
maxConsecutiveErrors: 12,
|
|
63
|
+
// A genuine research burst is a handful of searches; an uninterrupted run of this
|
|
64
|
+
// many web calls (with no read/edit/bash between) is a search loop, not progress.
|
|
65
|
+
maxConsecutiveWebCalls: 25,
|
|
66
|
+
} satisfies ProgressGuardLimits
|
|
67
|
+
|
|
68
|
+
// Tool names that mutate files, so a call to one clears the no-edit suspicion. Kept
|
|
69
|
+
// broad on purpose: different models/extensions name the same capability differently
|
|
70
|
+
// (`edit`/`write`, but also `apply_patch`/`patch`/`str_replace`/`multiedit`/`create`),
|
|
71
|
+
// and a false "no edits" reading would kill a run that IS making changes. Matched
|
|
72
|
+
// case-insensitively. NOTE: a file written purely via `bash` (e.g. a heredoc) is not
|
|
73
|
+
// recognised here — broaden or move to a working-tree signal if that becomes common.
|
|
74
|
+
const FILE_EDIT_TOOLS = new Set([
|
|
75
|
+
'edit',
|
|
76
|
+
'write',
|
|
77
|
+
'apply_patch',
|
|
78
|
+
'patch',
|
|
79
|
+
'str_replace',
|
|
80
|
+
'multiedit',
|
|
81
|
+
'create',
|
|
82
|
+
// Claude Code tool names (the guard now runs on the claude-code stream too): Edit/Write/
|
|
83
|
+
// MultiEdit already match above; NotebookEdit is its own tool.
|
|
84
|
+
'notebookedit',
|
|
85
|
+
])
|
|
86
|
+
|
|
87
|
+
// Planning/bookkeeping tools that are neither file edits nor the environment-probing
|
|
88
|
+
// the no-edit bound targets — the todo list the agent maintains as it works. These do
|
|
89
|
+
// NOT count toward `maxToolCallsWithoutEdit`: a run that diligently updates a long
|
|
90
|
+
// todo list before its first edit (common on a large task) would otherwise be killed
|
|
91
|
+
// for "no edits" purely from planning calls. They still reset the consecutive-error
|
|
92
|
+
// streak (a successful call means the agent isn't wedged). Matched case-insensitively.
|
|
93
|
+
// `todo` is Pi's tool; `TodoWrite` and the incremental `TaskCreate`/`TaskUpdate` pair are
|
|
94
|
+
// Claude Code's plan vocabularies — all pure bookkeeping, exempt from the no-edit bound.
|
|
95
|
+
const PLANNING_TOOLS = new Set(['todo', 'todowrite', 'taskcreate', 'taskupdate'])
|
|
96
|
+
|
|
97
|
+
// A subagent dispatch (Claude Code's `Agent`/`Task`) is exempt from the no-edit bound because
|
|
98
|
+
// the parent stream CANNOT see the edits it makes: only the dispatch and its terminal
|
|
99
|
+
// tool_result appear there, while every Edit/Write the subagent performs happens on a transcript
|
|
100
|
+
// the guard never reads (`subagents.ts` watches those separately, for usage/progress only). So a
|
|
101
|
+
// coder that fans its implementation out across subagents looks, to this guard, like a run making
|
|
102
|
+
// dozens of action calls and zero edits — and would be killed for making excellent progress.
|
|
103
|
+
// Counting them as edits instead would be worse (a read-only research subagent would then clear
|
|
104
|
+
// the suspicion the bound exists to hold), so they are neutral: they neither count toward the
|
|
105
|
+
// bound nor satisfy it. Sourced from the same set the slice tracker matches on, lower-cased for
|
|
106
|
+
// this module's case-insensitive comparison.
|
|
107
|
+
const SUBAGENT_DISPATCH_TOOLS = new Set([...SUBAGENT_TOOL_NAMES].map((name) => name.toLowerCase()))
|
|
108
|
+
|
|
109
|
+
// Read-only exploration tools: reading/searching the repo is legitimate work-up to an
|
|
110
|
+
// edit, NOT the environment-probing the no-edit bound targets, so they don't count
|
|
111
|
+
// toward `maxToolCallsWithoutEdit` (a large task may read/search dozens of files
|
|
112
|
+
// before its first edit). The bound thus counts only "action" calls — chiefly `bash`
|
|
113
|
+
// (the credential rabbit-hole's vector) — that have yet to produce an edit. Kept broad
|
|
114
|
+
// since models/extensions name the same capability differently. Matched case-insensitively.
|
|
115
|
+
const EXPLORATION_TOOLS = new Set([
|
|
116
|
+
'read',
|
|
117
|
+
'grep',
|
|
118
|
+
'search',
|
|
119
|
+
'glob',
|
|
120
|
+
'ls',
|
|
121
|
+
'list',
|
|
122
|
+
'find',
|
|
123
|
+
'tree',
|
|
124
|
+
'cat',
|
|
125
|
+
'view',
|
|
126
|
+
'head',
|
|
127
|
+
'tail',
|
|
128
|
+
'stat',
|
|
129
|
+
// rpiv-web-tools (Pi) + Claude Code's WebSearch/WebFetch: querying/reading the web is
|
|
130
|
+
// read-only research up to an edit, not the environment-probing the no-edit bound targets.
|
|
131
|
+
'web_search',
|
|
132
|
+
'web_fetch',
|
|
133
|
+
'websearch',
|
|
134
|
+
'webfetch',
|
|
135
|
+
])
|
|
136
|
+
|
|
137
|
+
// The web-tool calls, tracked separately so an unbounded run of them (with no other tool
|
|
138
|
+
// call between) can be caught as a search loop — see `maxConsecutiveWebCalls`. Covers both
|
|
139
|
+
// Pi's `web_search`/`web_fetch` and Claude Code's `WebSearch`/`WebFetch`.
|
|
140
|
+
const WEB_TOOLS = new Set(['web_search', 'web_fetch', 'websearch', 'webfetch'])
|
|
141
|
+
|
|
142
|
+
/** Read {@link ProgressGuardLimits} from the environment, falling back to the defaults. */
|
|
143
|
+
export function progressGuardLimitsFromEnv(
|
|
144
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
145
|
+
): ProgressGuardLimits {
|
|
146
|
+
const num = (raw: string | undefined, fallback: number): number => {
|
|
147
|
+
const n = Number(raw)
|
|
148
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
maxToolCallsWithoutEdit: num(
|
|
152
|
+
env.JOB_MAX_TOOLCALLS_WITHOUT_EDIT,
|
|
153
|
+
DEFAULT_PROGRESS_GUARD_LIMITS.maxToolCallsWithoutEdit,
|
|
154
|
+
),
|
|
155
|
+
maxConsecutiveErrors: num(
|
|
156
|
+
env.JOB_MAX_CONSECUTIVE_TOOL_ERRORS,
|
|
157
|
+
DEFAULT_PROGRESS_GUARD_LIMITS.maxConsecutiveErrors,
|
|
158
|
+
),
|
|
159
|
+
maxConsecutiveWebCalls: num(
|
|
160
|
+
env.JOB_MAX_CONSECUTIVE_WEB_CALLS,
|
|
161
|
+
DEFAULT_PROGRESS_GUARD_LIMITS.maxConsecutiveWebCalls,
|
|
162
|
+
),
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Apply per-knob overrides onto a base set of guard limits, ENFORCING loosen-only: an
|
|
168
|
+
* override can only RAISE a knob (more headroom), never lower it below the base. A
|
|
169
|
+
* larger value is more lenient for every knob (more no-edit tool calls / errors / web
|
|
170
|
+
* calls tolerated), so each result is `max(base, override)`. This is a hard guarantee,
|
|
171
|
+
* not a convention — a tuning entry (built-in or a custom kind's, which reaches this via
|
|
172
|
+
* an untrusted job body) that supplies a value TIGHTER than the base is clamped back up
|
|
173
|
+
* to the base rather than aborting a legitimately-progressing run. An absent/undefined
|
|
174
|
+
* knob keeps the base value untouched.
|
|
175
|
+
*/
|
|
176
|
+
export function mergeGuardLimits(
|
|
177
|
+
base: ProgressGuardLimits,
|
|
178
|
+
overrides: Partial<ProgressGuardLimits> | undefined,
|
|
179
|
+
): ProgressGuardLimits {
|
|
180
|
+
if (!overrides) return base
|
|
181
|
+
const loosen = (b: number, o: number | undefined): number =>
|
|
182
|
+
typeof o === 'number' ? Math.max(b, o) : b
|
|
183
|
+
return {
|
|
184
|
+
maxToolCallsWithoutEdit: loosen(
|
|
185
|
+
base.maxToolCallsWithoutEdit,
|
|
186
|
+
overrides.maxToolCallsWithoutEdit,
|
|
187
|
+
),
|
|
188
|
+
maxConsecutiveErrors: loosen(base.maxConsecutiveErrors, overrides.maxConsecutiveErrors),
|
|
189
|
+
// `maxConsecutiveWebCalls` is optional on the interface (callers may omit it), so
|
|
190
|
+
// fall back to the default before loosening — keeps `loosen`'s base a concrete number.
|
|
191
|
+
maxConsecutiveWebCalls: loosen(
|
|
192
|
+
base.maxConsecutiveWebCalls ?? DEFAULT_PROGRESS_GUARD_LIMITS.maxConsecutiveWebCalls,
|
|
193
|
+
overrides.maxConsecutiveWebCalls,
|
|
194
|
+
),
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Live anti-rabbithole guard: fed each streamed Pi event, it returns a diagnostic
|
|
200
|
+
* reason the moment a run has plainly stopped making progress, so the harness can
|
|
201
|
+
* kill Pi early instead of letting it burn the whole budget (and then surface a
|
|
202
|
+
* useful failure instead of a generic "no file changes"). Pure and incremental so
|
|
203
|
+
* it can be unit-tested over a fixed event sequence.
|
|
204
|
+
*/
|
|
205
|
+
export class ProgressGuard {
|
|
206
|
+
private toolCalls = 0
|
|
207
|
+
private edits = 0
|
|
208
|
+
private consecutiveErrors = 0
|
|
209
|
+
private consecutiveWebCalls = 0
|
|
210
|
+
|
|
211
|
+
constructor(
|
|
212
|
+
private readonly limits: ProgressGuardLimits,
|
|
213
|
+
/** When false (assess-only runs like the merger), the no-edit bound is skipped. */
|
|
214
|
+
private readonly expectsEdits: boolean = true,
|
|
215
|
+
) {}
|
|
216
|
+
|
|
217
|
+
/** Feed one parsed Pi event; returns a diagnostic reason when the run should abort, else null. */
|
|
218
|
+
observe(event: Record<string, unknown>): string | null {
|
|
219
|
+
const tool = toolCallSignal(event)
|
|
220
|
+
if (!tool) return null
|
|
221
|
+
return this.observeSignal(tool)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Feed one already-parsed tool-call signal (name + error flag), returning a diagnostic reason
|
|
226
|
+
* when the run should abort, else null. Split out of {@link observe} so a caller whose stream
|
|
227
|
+
* is NOT Pi's `tool_execution_end` envelope — the claude-code runner, which correlates a
|
|
228
|
+
* `tool_use` block's name with its `tool_result`'s `is_error` — can drive the SAME guard logic
|
|
229
|
+
* without synthesising a fake Pi event.
|
|
230
|
+
*/
|
|
231
|
+
observeSignal(tool: { name: string; isError: boolean }): string | null {
|
|
232
|
+
const name = tool.name.toLowerCase()
|
|
233
|
+
// The error streak tracks ANY tool call (a planning call still proves the agent
|
|
234
|
+
// isn't wedged in a failing-op loop), so it's updated before the planning skip.
|
|
235
|
+
this.consecutiveErrors = tool.isError ? this.consecutiveErrors + 1 : 0
|
|
236
|
+
if (this.consecutiveErrors >= this.limits.maxConsecutiveErrors) {
|
|
237
|
+
return (
|
|
238
|
+
`no progress: ${this.consecutiveErrors} consecutive failing tool calls — the agent is stuck ` +
|
|
239
|
+
`retrying a failing operation rather than making progress. Aborting.`
|
|
240
|
+
)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Web search/fetch loop: web tools are read-only (they don't count toward the
|
|
244
|
+
// no-edit bound), so guard them separately — an uninterrupted streak of them is a
|
|
245
|
+
// research rabbit-hole. Any non-web tool call resets the streak.
|
|
246
|
+
if (WEB_TOOLS.has(name)) {
|
|
247
|
+
this.consecutiveWebCalls++
|
|
248
|
+
const webCap =
|
|
249
|
+
this.limits.maxConsecutiveWebCalls ?? DEFAULT_PROGRESS_GUARD_LIMITS.maxConsecutiveWebCalls
|
|
250
|
+
if (this.consecutiveWebCalls >= webCap) {
|
|
251
|
+
return (
|
|
252
|
+
`no progress: ${this.consecutiveWebCalls} consecutive web search/fetch calls without ` +
|
|
253
|
+
`any other action — the agent is stuck researching instead of doing the work. Aborting.`
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
} else {
|
|
257
|
+
this.consecutiveWebCalls = 0
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Planning, read-only exploration and subagent-dispatch calls don't count toward the
|
|
261
|
+
// no-edit bound (see PLANNING_TOOLS / EXPLORATION_TOOLS / SUBAGENT_DISPATCH_TOOLS) —
|
|
262
|
+
// only "action" calls without an edit do.
|
|
263
|
+
if (
|
|
264
|
+
PLANNING_TOOLS.has(name) ||
|
|
265
|
+
EXPLORATION_TOOLS.has(name) ||
|
|
266
|
+
SUBAGENT_DISPATCH_TOOLS.has(name)
|
|
267
|
+
) {
|
|
268
|
+
return null
|
|
269
|
+
}
|
|
270
|
+
this.toolCalls++
|
|
271
|
+
if (FILE_EDIT_TOOLS.has(name)) this.edits++
|
|
272
|
+
|
|
273
|
+
if (
|
|
274
|
+
this.expectsEdits &&
|
|
275
|
+
this.edits === 0 &&
|
|
276
|
+
this.toolCalls >= this.limits.maxToolCallsWithoutEdit
|
|
277
|
+
) {
|
|
278
|
+
return (
|
|
279
|
+
`no progress: ${this.toolCalls} tool calls and not one file edit — the agent is exploring or ` +
|
|
280
|
+
`probing the environment without implementing anything. Aborting before it burns the whole run.`
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
return null
|
|
284
|
+
}
|
|
285
|
+
}
|
package/src/subagents.ts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { readdir, stat } from 'node:fs/promises'
|
|
2
2
|
import { createReadStream, type Dirent } from 'node:fs'
|
|
3
3
|
import { basename, join } from 'node:path'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
claudeAssistantContent,
|
|
6
|
+
claudeCallUsage,
|
|
7
|
+
isObject,
|
|
8
|
+
redactBody,
|
|
9
|
+
SUBAGENT_TOOL_NAMES,
|
|
10
|
+
} from './claude-stream.js'
|
|
5
11
|
import type { Logger } from './logger.js'
|
|
6
12
|
import { publishCallMetric, type HarnessCallMetric, type TodoProgress } from './pi.js'
|
|
7
13
|
|
|
@@ -42,21 +48,6 @@ import { publishCallMetric, type HarnessCallMetric, type TodoProgress } from './
|
|
|
42
48
|
// Slice / progress tracking off the PARENT stream (D2.1)
|
|
43
49
|
// ---------------------------------------------------------------------------
|
|
44
50
|
|
|
45
|
-
/**
|
|
46
|
-
* The tool names the Claude Code CLI dispatches a parallel subagent under. `Agent` is what the
|
|
47
|
-
* shipped schema declares (`AgentInput` in `sdk-tools.d.ts`, carrying `description` / `prompt` /
|
|
48
|
-
* `subagent_type`); `Task` is the older name for the same dispatch. Both are matched because the
|
|
49
|
-
* harness runs against whatever CLI the image happens to bundle, and matching only the old name
|
|
50
|
-
* is what left a CLI 2.1.x pr-review reporting no slices at all.
|
|
51
|
-
*
|
|
52
|
-
* Note the asymmetry: keeping the legacy `Task` here is the one place a CLI rename could produce a
|
|
53
|
-
* FALSE signal rather than merely no signal — if a future build were to name a plain task-list
|
|
54
|
-
* tool `Task`, its writes would be counted as in-flight slices. We accept that because no shipped
|
|
55
|
-
* build does (the incremental plan tool is `TaskCreate`/`TaskUpdate`, tracked separately in
|
|
56
|
-
* `progress.ts`), and dropping legacy coverage is the more likely regression.
|
|
57
|
-
*/
|
|
58
|
-
const SUBAGENT_TOOL_NAMES = new Set(['Agent', 'Task'])
|
|
59
|
-
|
|
60
51
|
interface TrackedSlice {
|
|
61
52
|
/** The dispatch's tool_use id, used to pair the terminal tool_result. */
|
|
62
53
|
toolUseId: string
|