@mjasnikovs/pi-nop 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +116 -2
- package/package.json +87 -5
- package/src/config/box.ts +29 -0
- package/src/config/command.ts +138 -0
- package/src/config/config.ts +238 -0
- package/src/config/sections.ts +58 -0
- package/src/index.ts +17 -0
- package/src/plan/ask.ts +226 -0
- package/src/plan/goal.ts +43 -0
- package/src/plan/panel.ts +567 -0
- package/src/plan/plan.ts +581 -0
- package/src/plan/steps.ts +192 -0
- package/src/plan/track.ts +131 -0
- package/src/search/brave.ts +56 -0
- package/src/search/ddg.ts +67 -0
- package/src/search/engines.ts +63 -0
- package/src/search/exa.ts +74 -0
- package/src/search/search.ts +58 -0
- package/src/subagent/answer.ts +151 -0
- package/src/subagent/budget.ts +19 -0
- package/src/subagent/describe.ts +8 -0
- package/src/subagent/docs/docs.ts +123 -0
- package/src/subagent/docs/files.ts +90 -0
- package/src/subagent/docs/header.ts +60 -0
- package/src/subagent/docs/locate.ts +262 -0
- package/src/subagent/docs/manifest.ts +43 -0
- package/src/subagent/docs/npm.ts +287 -0
- package/src/subagent/fetch/digest.ts +379 -0
- package/src/subagent/fetch/errors.ts +10 -0
- package/src/subagent/fetch/fetch.ts +176 -0
- package/src/subagent/fetch/pdf.ts +120 -0
- package/src/subagent/guards/churn.ts +37 -0
- package/src/subagent/guards/circle.ts +49 -0
- package/src/subagent/guards/ground.ts +75 -0
- package/src/subagent/guards/guard.ts +24 -0
- package/src/subagent/guards/guards.ts +107 -0
- package/src/subagent/guards/key.ts +13 -0
- package/src/subagent/guards/leak.ts +42 -0
- package/src/subagent/guards/lines.ts +24 -0
- package/src/subagent/guards/loop.ts +77 -0
- package/src/subagent/guards/repeat.ts +70 -0
- package/src/subagent/guards/stale.ts +38 -0
- package/src/subagent/guards/toolCall.ts +46 -0
- package/src/subagent/guards/visited.ts +89 -0
- package/src/subagent/platform.ts +81 -0
- package/src/subagent/progress.ts +34 -0
- package/src/subagent/slots.ts +42 -0
- package/src/subagent/subagent.ts +537 -0
- package/src/subagent/subagentTui.ts +292 -0
- package/src/tui/hidden.ts +16 -0
- package/src/tui/spinner.ts +64 -0
- package/src/types/turndown-plugin-gfm.d.ts +5 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type {AgentToolResult} from '@earendil-works/pi-agent-core'
|
|
2
|
+
import {estimateTokens} from '@earendil-works/pi-coding-agent'
|
|
3
|
+
|
|
4
|
+
import type {Guard, Trip} from './guard'
|
|
5
|
+
import {noop} from './guard'
|
|
6
|
+
|
|
7
|
+
// MAGIC NUMBER: pi-task's factor. A local server drops the oldest context without a word, so
|
|
8
|
+
// results past twice the window mean the model is re-reading what it already lost.
|
|
9
|
+
const factor = 2
|
|
10
|
+
|
|
11
|
+
const churnHint =
|
|
12
|
+
'[SYSTEM NOTE: Your previous attempt pulled in more file content than its context window '
|
|
13
|
+
+ 'holds twice over, so the earliest material was dropped and it began re-reading it. It '
|
|
14
|
+
+ 'was stopped and its conversation discarded. Redo the work from here, reading only what '
|
|
15
|
+
+ 'the answer needs.]'
|
|
16
|
+
|
|
17
|
+
const createChurn = (trip: Trip, contextWindow: number): Guard => {
|
|
18
|
+
let tokens = 0
|
|
19
|
+
|
|
20
|
+
return {
|
|
21
|
+
onEvent: event => {
|
|
22
|
+
if (event.type !== 'tool_execution_end') return
|
|
23
|
+
tokens += estimateTokens({
|
|
24
|
+
role: 'toolResult',
|
|
25
|
+
toolCallId: event.toolCallId,
|
|
26
|
+
toolName: event.toolName,
|
|
27
|
+
content: (event.result as AgentToolResult).content,
|
|
28
|
+
isError: event.isError,
|
|
29
|
+
timestamp: Date.now()
|
|
30
|
+
})
|
|
31
|
+
if (tokens > contextWindow * factor) trip({id: 'churn', hint: churnHint})
|
|
32
|
+
},
|
|
33
|
+
dispose: noop
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export {createChurn}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type {Guard, Trip} from './guard'
|
|
2
|
+
import {noop} from './guard'
|
|
3
|
+
import {createLineReader} from './lines'
|
|
4
|
+
import type {Visited} from './visited'
|
|
5
|
+
|
|
6
|
+
// MAGIC NUMBER: measured in PLANNING_MODE section 15. Healthy thinking said a second line 5 times.
|
|
7
|
+
const times = 8
|
|
8
|
+
// Thinking that drafts code says a fence or a brace this often. A loop says whole sentences.
|
|
9
|
+
const sentence = /^[A-Za-z].*[.!?]$/
|
|
10
|
+
|
|
11
|
+
const circleHint = (visited: Visited): string =>
|
|
12
|
+
'[SYSTEM NOTE: Your previous attempt said the same lines over and over in its thinking and '
|
|
13
|
+
+ 'was stopped as a loop. Its conversation is discarded. Redo the work from here. Do not go '
|
|
14
|
+
+ `over a point twice: decide with what you know and answer.${visited.list()}]`
|
|
15
|
+
|
|
16
|
+
// A loop where one line changes each round never repeats a block, so the repeat guard is blind.
|
|
17
|
+
const createCircle = (trip: Trip, visited: Visited): Guard => {
|
|
18
|
+
const reader = createLineReader()
|
|
19
|
+
let said = new Map<string, number>()
|
|
20
|
+
let often = 0
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
onEvent: event => {
|
|
24
|
+
if (event.type !== 'message_update') return
|
|
25
|
+
const update = event.assistantMessageEvent
|
|
26
|
+
|
|
27
|
+
if (update.type === 'thinking_start') {
|
|
28
|
+
said = new Map()
|
|
29
|
+
often = 0
|
|
30
|
+
reader.reset()
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (update.type !== 'thinking_delta') return
|
|
35
|
+
|
|
36
|
+
for (const line of reader.take(update.delta)) {
|
|
37
|
+
if (!sentence.test(line)) continue
|
|
38
|
+
const count = (said.get(line) ?? 0) + 1
|
|
39
|
+
said.set(line, count)
|
|
40
|
+
if (count !== times) continue
|
|
41
|
+
often += 1
|
|
42
|
+
if (often === 2) trip({id: 'circle', hint: circleHint(visited)})
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
dispose: noop
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export {createCircle}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type {Guard, Trip} from './guard'
|
|
2
|
+
import {noop} from './guard'
|
|
3
|
+
import {callKey} from './key'
|
|
4
|
+
import type {Visited} from './visited'
|
|
5
|
+
|
|
6
|
+
// MAGIC NUMBER: pi-task's limit. Eight dead calls in a row is past any honest run of misses.
|
|
7
|
+
const limit = 8
|
|
8
|
+
|
|
9
|
+
const groundHint = (visited: Visited): string =>
|
|
10
|
+
`[SYSTEM NOTE: Your previous attempt made ${limit} tool calls in a row that brought nothing `
|
|
11
|
+
+ 'new: repeats of earlier calls or errors. It was stopped and its conversation discarded. '
|
|
12
|
+
+ 'Redo the work from here. Read each region of a file at most once, and fix a failing call '
|
|
13
|
+
+ `instead of retrying it.${visited.list()}]`
|
|
14
|
+
|
|
15
|
+
// A tool that answers a reworded call from memory says so itself, since its call key is new.
|
|
16
|
+
const ownRepeat = (result: unknown): boolean =>
|
|
17
|
+
(result as {details?: {repeat?: unknown}} | undefined)?.details?.repeat === true
|
|
18
|
+
|
|
19
|
+
// A call is dead when it repeats an earlier call of the attempt or comes back as an error.
|
|
20
|
+
const createGround = (
|
|
21
|
+
trip: Trip,
|
|
22
|
+
visited: Visited,
|
|
23
|
+
waits: ReadonlySet<string> = new Set()
|
|
24
|
+
): Guard => {
|
|
25
|
+
const seen = new Set<string>()
|
|
26
|
+
const repeats = new Set<string>()
|
|
27
|
+
const asked = new Map<string, string>()
|
|
28
|
+
let streak = 0
|
|
29
|
+
let waiting = 0
|
|
30
|
+
let held = 0
|
|
31
|
+
let answered = false
|
|
32
|
+
|
|
33
|
+
// A refused question is asked again on purpose, so only one that went through is seen.
|
|
34
|
+
const settle = (toolCallId: string, isError: boolean): void => {
|
|
35
|
+
const key = asked.get(toolCallId)
|
|
36
|
+
asked.delete(toolCallId)
|
|
37
|
+
waiting -= 1
|
|
38
|
+
if (!isError && key !== undefined) seen.add(key)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Judged once no waiting call is in flight, so a dead call cannot stop a question on screen.
|
|
42
|
+
const judge = (dead: boolean): void => {
|
|
43
|
+
if (dead) held += 1
|
|
44
|
+
else answered = true
|
|
45
|
+
if (waiting > 0) return
|
|
46
|
+
|
|
47
|
+
streak = answered ? 0 : streak + held
|
|
48
|
+
held = 0
|
|
49
|
+
answered = false
|
|
50
|
+
if (streak >= limit) trip({id: 'ground', hint: groundHint(visited)})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
onEvent: event => {
|
|
55
|
+
if (event.type === 'tool_execution_start') {
|
|
56
|
+
const key = callKey(event.toolName, event.args)
|
|
57
|
+
if (seen.has(key)) repeats.add(event.toolCallId)
|
|
58
|
+
|
|
59
|
+
if (!waits.has(event.toolName)) seen.add(key)
|
|
60
|
+
else {
|
|
61
|
+
asked.set(event.toolCallId, key)
|
|
62
|
+
waiting += 1
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (event.type !== 'tool_execution_end') return
|
|
67
|
+
const repeat = repeats.delete(event.toolCallId) || ownRepeat(event.result)
|
|
68
|
+
if (waits.has(event.toolName)) settle(event.toolCallId, event.isError)
|
|
69
|
+
judge(repeat || event.isError)
|
|
70
|
+
},
|
|
71
|
+
dispose: noop
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export {createGround}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type {AgentSessionEvent} from '@earendil-works/pi-coding-agent'
|
|
2
|
+
|
|
3
|
+
type GuardId = 'loop' | 'stale' | 'tool-call' | 'ground' | 'churn' | 'leak' | 'repeat' | 'circle'
|
|
4
|
+
|
|
5
|
+
type GuardHit = {id: GuardId; hint: string}
|
|
6
|
+
|
|
7
|
+
type Trip = (hit: GuardHit) => void
|
|
8
|
+
|
|
9
|
+
type Guard = {onEvent: (event: AgentSessionEvent) => void; dispose: () => void}
|
|
10
|
+
|
|
11
|
+
type Timer = ReturnType<typeof setTimeout>
|
|
12
|
+
|
|
13
|
+
type Clock = {schedule: (fn: () => void, ms: number) => Timer; cancel: (timer: Timer) => void}
|
|
14
|
+
|
|
15
|
+
const realClock: Clock = {
|
|
16
|
+
schedule: (fn, ms) => setTimeout(fn, ms),
|
|
17
|
+
cancel: timer => clearTimeout(timer)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const noop = (): void => undefined
|
|
21
|
+
const minutes = (ms: number): string => `${Math.round(ms / 60_000)} minutes`
|
|
22
|
+
|
|
23
|
+
export {minutes, noop, realClock}
|
|
24
|
+
export type {Clock, Guard, GuardHit, GuardId, Timer, Trip}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type {AgentSession, AgentSessionEvent} from '@earendil-works/pi-coding-agent'
|
|
2
|
+
|
|
3
|
+
import type {NopConfig} from '../../config/config'
|
|
4
|
+
import {read, restarts, staleMinutes, toolCallMinutes} from '../../config/config'
|
|
5
|
+
import {createChurn} from './churn'
|
|
6
|
+
import {createCircle} from './circle'
|
|
7
|
+
import type {Clock, Guard, GuardHit} from './guard'
|
|
8
|
+
import {realClock} from './guard'
|
|
9
|
+
import {createGround} from './ground'
|
|
10
|
+
import {createLeak} from './leak'
|
|
11
|
+
import {createLoop} from './loop'
|
|
12
|
+
import {createRepeat} from './repeat'
|
|
13
|
+
import {createStale} from './stale'
|
|
14
|
+
import {createToolCall} from './toolCall'
|
|
15
|
+
import {createVisited} from './visited'
|
|
16
|
+
|
|
17
|
+
type GuardSettings = {
|
|
18
|
+
staleMs: number | undefined
|
|
19
|
+
toolCallMs: number | undefined
|
|
20
|
+
restarts: number
|
|
21
|
+
waits?: ReadonlySet<string>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
type GuardWatch = {hit: () => GuardHit | undefined; stop: () => void}
|
|
25
|
+
|
|
26
|
+
const minutesToMs = (value: number | 'off'): number | undefined =>
|
|
27
|
+
value === 'off' ? undefined : value * 60_000
|
|
28
|
+
|
|
29
|
+
const guardSettings = (nop: NopConfig): GuardSettings => ({
|
|
30
|
+
staleMs: minutesToMs(read(nop, staleMinutes)),
|
|
31
|
+
toolCallMs: minutesToMs(read(nop, toolCallMinutes)),
|
|
32
|
+
restarts: read(nop, restarts)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// A server that sends no tool call id leaves pi with ''. Pairing each end with the oldest open
|
|
36
|
+
// start of its tool keeps one entry per call. Two calls of one tool can still swap.
|
|
37
|
+
const nameBlankIds = (): ((event: AgentSessionEvent) => AgentSessionEvent) => {
|
|
38
|
+
const open: {toolCallId: string; toolName: string}[] = []
|
|
39
|
+
let count = 0
|
|
40
|
+
|
|
41
|
+
return event => {
|
|
42
|
+
if (event.type === 'tool_execution_start' && event.toolCallId === '') {
|
|
43
|
+
count += 1
|
|
44
|
+
const toolCallId = `blank-${count}`
|
|
45
|
+
open.push({toolCallId, toolName: event.toolName})
|
|
46
|
+
return {...event, toolCallId}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (event.type !== 'tool_execution_end' || event.toolCallId !== '') return event
|
|
50
|
+
|
|
51
|
+
const at = open.findIndex(call => call.toolName === event.toolName)
|
|
52
|
+
const [started] = at === -1 ? [] : open.splice(at, 1)
|
|
53
|
+
return {...event, toolCallId: started?.toolCallId ?? ''}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// One subscription for the attempt. The first hit wins and aborts the run if it is still going.
|
|
58
|
+
const watchGuards = (
|
|
59
|
+
session: AgentSession,
|
|
60
|
+
settings: GuardSettings,
|
|
61
|
+
contextWindow: number,
|
|
62
|
+
clock: Clock = realClock
|
|
63
|
+
): GuardWatch => {
|
|
64
|
+
let hit: GuardHit | undefined
|
|
65
|
+
let closing = false
|
|
66
|
+
let ended = false
|
|
67
|
+
|
|
68
|
+
// A trip during the closing agent_end has nothing left to abort. One after it is stale.
|
|
69
|
+
const trip = (next: GuardHit): void => {
|
|
70
|
+
if (hit !== undefined || ended) return
|
|
71
|
+
hit = next
|
|
72
|
+
if (!closing) void session.abort()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const visited = createVisited()
|
|
76
|
+
const guards: Guard[] = [
|
|
77
|
+
visited,
|
|
78
|
+
createLoop(trip, visited),
|
|
79
|
+
createGround(trip, visited, settings.waits),
|
|
80
|
+
createLeak(trip),
|
|
81
|
+
createRepeat(trip, visited),
|
|
82
|
+
createCircle(trip, visited)
|
|
83
|
+
]
|
|
84
|
+
if (settings.staleMs !== undefined) guards.push(createStale(trip, settings.staleMs, clock))
|
|
85
|
+
if (settings.toolCallMs !== undefined)
|
|
86
|
+
guards.push(createToolCall(trip, settings.toolCallMs, clock, settings.waits))
|
|
87
|
+
if (contextWindow > 0) guards.push(createChurn(trip, contextWindow))
|
|
88
|
+
|
|
89
|
+
const named = nameBlankIds()
|
|
90
|
+
const unsubscribe = session.subscribe(raw => {
|
|
91
|
+
const event = named(raw)
|
|
92
|
+
closing = event.type === 'agent_end' && !event.willRetry
|
|
93
|
+
for (const guard of guards) guard.onEvent(event)
|
|
94
|
+
if (closing) ended = true
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
hit: () => hit,
|
|
99
|
+
stop: () => {
|
|
100
|
+
unsubscribe()
|
|
101
|
+
for (const guard of guards) guard.dispose()
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export {guardSettings, watchGuards}
|
|
107
|
+
export type {GuardSettings, GuardWatch}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const canonical = (value: unknown): unknown => {
|
|
2
|
+
if (Array.isArray(value)) return value.map(canonical)
|
|
3
|
+
if (value === null || typeof value !== 'object') return value
|
|
4
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
5
|
+
entries.sort(([a], [b]) => a.localeCompare(b))
|
|
6
|
+
return Object.fromEntries(entries.map(([name, inner]) => [name, canonical(inner)]))
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// A model sends the same args in a different key order from one call to the next.
|
|
10
|
+
const callKey = (name: string, args: unknown): string =>
|
|
11
|
+
`${name} ${JSON.stringify(canonical(args))}`
|
|
12
|
+
|
|
13
|
+
export {callKey}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type {AssistantMessage} from '@earendil-works/pi-ai'
|
|
2
|
+
import {contentText} from '@earendil-works/pi-ai'
|
|
3
|
+
|
|
4
|
+
import type {Guard, Trip} from './guard'
|
|
5
|
+
import {noop} from './guard'
|
|
6
|
+
|
|
7
|
+
const leakHint = (marker: string): string =>
|
|
8
|
+
`[SYSTEM NOTE: Your previous attempt wrote a tool call as plain text (${marker}) instead of `
|
|
9
|
+
+ 'calling the tool, so it never ran. Call tools through the tool API. Never type '
|
|
10
|
+
+ '<tool_call>, <function=…> or <parameter=…> markup into your answer.]'
|
|
11
|
+
|
|
12
|
+
// A leaked call starts its own line outside a code fence. Markup quoted mid-line or fenced, as
|
|
13
|
+
// evidence, is not a leak.
|
|
14
|
+
const fence = /```[\s\S]*?```/g
|
|
15
|
+
const toolCallTag = /^\s*(<tool_call\b[^>]*>)/im
|
|
16
|
+
const functionTag = /^\s*(<function=[\w.-]+\s*>)/im
|
|
17
|
+
const parameterTag = /^\s*<parameter=[\w.-]+\s*>/im
|
|
18
|
+
|
|
19
|
+
const leakedMarker = (answer: string): string | undefined => {
|
|
20
|
+
const text = answer.replace(fence, '')
|
|
21
|
+
const tag = toolCallTag.exec(text)?.[1]
|
|
22
|
+
if (tag !== undefined) return tag
|
|
23
|
+
return parameterTag.test(text) ? functionTag.exec(text)?.[1] : undefined
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// A cut-off or failed run is reported as that, not as a leak.
|
|
27
|
+
const checked = new Set<AssistantMessage['stopReason']>(['stop', 'toolUse'])
|
|
28
|
+
|
|
29
|
+
// Checked once the run ended on its own: a leak is text the model wrote instead of a tool call.
|
|
30
|
+
const createLeak = (trip: Trip): Guard => ({
|
|
31
|
+
onEvent: event => {
|
|
32
|
+
if (event.type !== 'agent_end') return
|
|
33
|
+
const last = event.messages.findLast(message => message.role === 'assistant')
|
|
34
|
+
|
|
35
|
+
if (last === undefined || !checked.has(last.stopReason)) return
|
|
36
|
+
const marker = leakedMarker(contentText(last.content))
|
|
37
|
+
if (marker !== undefined) trip({id: 'leak', hint: leakHint(marker)})
|
|
38
|
+
},
|
|
39
|
+
dispose: noop
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
export {createLeak, leakedMarker}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
type LineReader = {
|
|
2
|
+
/** The trimmed, non-blank lines the delta finished. A line with no line break yet waits. */
|
|
3
|
+
take: (delta: string) => string[]
|
|
4
|
+
reset: () => void
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const createLineReader = (): LineReader => {
|
|
8
|
+
let open = ''
|
|
9
|
+
|
|
10
|
+
return {
|
|
11
|
+
take: delta => {
|
|
12
|
+
const rows = delta.split('\n')
|
|
13
|
+
rows[0] = open + (rows[0] ?? '')
|
|
14
|
+
open = rows.pop() ?? ''
|
|
15
|
+
return rows.map(row => row.trim()).filter(row => row !== '')
|
|
16
|
+
},
|
|
17
|
+
reset: () => {
|
|
18
|
+
open = ''
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export {createLineReader}
|
|
24
|
+
export type {LineReader}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type {Guard, Trip} from './guard'
|
|
2
|
+
import {noop} from './guard'
|
|
3
|
+
import {callKey} from './key'
|
|
4
|
+
import type {ReadCall, Visited} from './visited'
|
|
5
|
+
import {readCall, readEnd} from './visited'
|
|
6
|
+
|
|
7
|
+
// MAGIC NUMBER: pi-task's tested pair. Fewer flags a model that re-checks one file; more lets
|
|
8
|
+
// a loop run for minutes before the kill.
|
|
9
|
+
const windowSize = 20
|
|
10
|
+
const threshold = 5
|
|
11
|
+
|
|
12
|
+
type Entry = {id: string; key: string; read: ReadCall | undefined}
|
|
13
|
+
|
|
14
|
+
const repeatHint = (name: string, args: unknown, count: number, visited: Visited): string =>
|
|
15
|
+
`[SYSTEM NOTE: Your previous attempt called ${name}(${JSON.stringify(args)}) ${count} times `
|
|
16
|
+
+ `in its last ${windowSize} tool calls and was stopped as a loop. Its conversation is `
|
|
17
|
+
+ 'discarded. Redo the work from here without repeating that call. Take a different angle.'
|
|
18
|
+
+ `${visited.list()}]`
|
|
19
|
+
|
|
20
|
+
const revisitHint = (path: string, visited: Visited): string =>
|
|
21
|
+
`[SYSTEM NOTE: Your previous attempt re-read ${path} ${threshold} times without reaching `
|
|
22
|
+
+ 'new lines and was stopped as a loop. Its conversation is discarded. Redo the work from '
|
|
23
|
+
+ 'here, reading each region of a file at most once. When a file is too large to read whole, '
|
|
24
|
+
+ `page forward through it instead of re-opening the start.${visited.list()}]`
|
|
25
|
+
|
|
26
|
+
// A read that goes past the highest line already read on that path is progress. Any other is
|
|
27
|
+
// a revisit.
|
|
28
|
+
const revisits = (window: Entry[], path: string): number => {
|
|
29
|
+
let top = Number.NEGATIVE_INFINITY
|
|
30
|
+
let count = 0
|
|
31
|
+
|
|
32
|
+
for (const {read} of window) {
|
|
33
|
+
if (read?.path !== path) continue
|
|
34
|
+
if (read.to > top) top = read.to
|
|
35
|
+
else count += 1
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return count
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const createLoop = (trip: Trip, visited: Visited): Guard => {
|
|
42
|
+
const window: Entry[] = []
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
onEvent: event => {
|
|
46
|
+
if (event.type === 'tool_execution_end') {
|
|
47
|
+
const entry = window.find(other => other.id === event.toolCallId)
|
|
48
|
+
if (entry?.read !== undefined)
|
|
49
|
+
entry.read = readEnd(entry.read, event.result, event.isError)
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (event.type !== 'tool_execution_start') return
|
|
54
|
+
const {toolCallId, toolName, args} = event
|
|
55
|
+
const entry = {
|
|
56
|
+
id: toolCallId,
|
|
57
|
+
key: callKey(toolName, args),
|
|
58
|
+
read: readCall(toolName, args)
|
|
59
|
+
}
|
|
60
|
+
window.push(entry)
|
|
61
|
+
if (window.length > windowSize) window.shift()
|
|
62
|
+
|
|
63
|
+
const count = window.filter(other => other.key === entry.key).length
|
|
64
|
+
|
|
65
|
+
if (count >= threshold) {
|
|
66
|
+
trip({id: 'loop', hint: repeatHint(toolName, args, count, visited)})
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (entry.read !== undefined && revisits(window, entry.read.path) >= threshold)
|
|
71
|
+
trip({id: 'loop', hint: revisitHint(entry.read.path, visited)})
|
|
72
|
+
},
|
|
73
|
+
dispose: noop
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export {createLoop}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type {Guard, Trip} from './guard'
|
|
2
|
+
import {noop} from './guard'
|
|
3
|
+
import {createLineReader} from './lines'
|
|
4
|
+
import type {Visited} from './visited'
|
|
5
|
+
|
|
6
|
+
// MAGIC NUMBER: measured in PLANNING_MODE section 11. Fewer copies hit more quoted files.
|
|
7
|
+
const copies = 8
|
|
8
|
+
|
|
9
|
+
const repeatHint = (size: number, visited: Visited): string =>
|
|
10
|
+
`[SYSTEM NOTE: Your previous attempt wrote the same ${size} lines ${copies} times in a row `
|
|
11
|
+
+ 'and was stopped as a loop. Its conversation is discarded. Redo the work from here. Do not '
|
|
12
|
+
+ `go over a point twice: decide with what you know and answer.${visited.list()}]`
|
|
13
|
+
|
|
14
|
+
const tailOfOneLine = (lines: string[]): number => {
|
|
15
|
+
const last = lines.length - 1
|
|
16
|
+
let run = 1
|
|
17
|
+
while (run <= last && lines[last - run] === lines[last]) run += 1
|
|
18
|
+
return run
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const repeatedBlock = (lines: string[]): number | undefined => {
|
|
22
|
+
const last = lines.length - 1
|
|
23
|
+
const tail = tailOfOneLine(lines)
|
|
24
|
+
|
|
25
|
+
// One line many times over is healthy output too: closing braces, an empty grid.
|
|
26
|
+
for (let size = tail + 1; size * copies <= lines.length; size += 1) {
|
|
27
|
+
// Without this each size walks a long tail of equal lines before it fails.
|
|
28
|
+
if (lines[last - tail] !== lines[last - tail - size]) continue
|
|
29
|
+
const span = size * (copies - 1)
|
|
30
|
+
let same = 0
|
|
31
|
+
while (same < span && lines[last - same] === lines[last - same - size]) same += 1
|
|
32
|
+
if (same === span) return size
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// A model looping inside one block makes no tool call, so no other guard sees it.
|
|
39
|
+
const createRepeat = (trip: Trip, visited: Visited): Guard => {
|
|
40
|
+
const reader = createLineReader()
|
|
41
|
+
let lines: string[] = []
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
onEvent: event => {
|
|
45
|
+
if (event.type !== 'message_update') return
|
|
46
|
+
const update = event.assistantMessageEvent
|
|
47
|
+
|
|
48
|
+
if (update.type === 'thinking_start' || update.type === 'text_start') {
|
|
49
|
+
lines = []
|
|
50
|
+
reader.reset()
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (update.type !== 'thinking_delta' && update.type !== 'text_delta') return
|
|
55
|
+
|
|
56
|
+
for (const line of reader.take(update.delta)) {
|
|
57
|
+
lines.push(line)
|
|
58
|
+
const size = repeatedBlock(lines)
|
|
59
|
+
|
|
60
|
+
if (size !== undefined) {
|
|
61
|
+
trip({id: 'repeat', hint: repeatHint(size, visited)})
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
dispose: noop
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export {createRepeat, repeatedBlock}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type {Clock, Guard, Timer, Trip} from './guard'
|
|
2
|
+
import {minutes} from './guard'
|
|
3
|
+
|
|
4
|
+
const staleHint = (ms: number): string =>
|
|
5
|
+
`[SYSTEM NOTE: Your previous attempt was stopped because the model sent nothing for `
|
|
6
|
+
+ `${minutes(ms)}. That is a hang, not a mistake you made. Its conversation is gone. `
|
|
7
|
+
+ 'Redo the work from here.]'
|
|
8
|
+
|
|
9
|
+
// The timer runs from the prompt. Every event resets it. It pauses while a tool call runs, which
|
|
10
|
+
// the tool-call guard watches, and during pi's retry sleep, which sends no event until it ends.
|
|
11
|
+
const createStale = (trip: Trip, ms: number, clock: Clock): Guard => {
|
|
12
|
+
let timer: Timer | undefined
|
|
13
|
+
let running = 0
|
|
14
|
+
let retrying = false
|
|
15
|
+
|
|
16
|
+
const cancel = (): void => {
|
|
17
|
+
if (timer !== undefined) clock.cancel(timer)
|
|
18
|
+
timer = undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const arm = (): void => {
|
|
22
|
+
cancel()
|
|
23
|
+
if (running > 0 || retrying) return
|
|
24
|
+
timer = clock.schedule(() => trip({id: 'stale', hint: staleHint(ms)}), ms)
|
|
25
|
+
}
|
|
26
|
+
arm()
|
|
27
|
+
return {
|
|
28
|
+
onEvent: event => {
|
|
29
|
+
if (event.type === 'tool_execution_start') running += 1
|
|
30
|
+
if (event.type === 'tool_execution_end') running = Math.max(0, running - 1)
|
|
31
|
+
retrying = event.type === 'auto_retry_start'
|
|
32
|
+
arm()
|
|
33
|
+
},
|
|
34
|
+
dispose: cancel
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export {createStale}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type {Clock, Guard, Timer, Trip} from './guard'
|
|
2
|
+
import {minutes} from './guard'
|
|
3
|
+
|
|
4
|
+
const toolCallHint = (name: string, args: unknown, ms: number): string =>
|
|
5
|
+
`[SYSTEM NOTE: Your previous attempt called ${name}(${JSON.stringify(args)}) and it had not `
|
|
6
|
+
+ `returned after ${minutes(ms)}, so the attempt was stopped and its conversation discarded. `
|
|
7
|
+
+ 'Do not repeat that call. Narrow it, or work from what you already have.]'
|
|
8
|
+
|
|
9
|
+
// A tool in waits is held open by the user, not by a stuck call, so it gets no timer.
|
|
10
|
+
const createToolCall = (
|
|
11
|
+
trip: Trip,
|
|
12
|
+
ms: number,
|
|
13
|
+
clock: Clock,
|
|
14
|
+
waits: ReadonlySet<string> = new Set()
|
|
15
|
+
): Guard => {
|
|
16
|
+
const timers = new Map<string, Timer>()
|
|
17
|
+
|
|
18
|
+
const clear = (id: string): void => {
|
|
19
|
+
const timer = timers.get(id)
|
|
20
|
+
if (timer !== undefined) clock.cancel(timer)
|
|
21
|
+
timers.delete(id)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
onEvent: event => {
|
|
26
|
+
if (event.type === 'tool_execution_start' && !waits.has(event.toolName)) {
|
|
27
|
+
const {toolCallId, toolName, args} = event
|
|
28
|
+
clear(toolCallId)
|
|
29
|
+
timers.set(
|
|
30
|
+
toolCallId,
|
|
31
|
+
clock.schedule(
|
|
32
|
+
() => trip({id: 'tool-call', hint: toolCallHint(toolName, args, ms)}),
|
|
33
|
+
ms
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (event.type === 'tool_execution_end') clear(event.toolCallId)
|
|
39
|
+
},
|
|
40
|
+
dispose: () => {
|
|
41
|
+
for (const id of [...timers.keys()]) clear(id)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export {createToolCall}
|