typeclaw 0.44.0 → 0.45.1
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/package.json +7 -6
- package/src/agent/index.ts +42 -3
- package/src/agent/loop-guard.ts +208 -10
- package/src/agent/model-fallback.ts +59 -40
- package/src/agent/multimodal/look-at.ts +2 -1
- package/src/agent/plugin-tools.ts +59 -5
- package/src/agent/provider-error.ts +78 -18
- package/src/agent/retry-same-ref.ts +205 -0
- package/src/agent/subagents.ts +34 -4
- package/src/agent/tools/channel-edit.ts +144 -0
- package/src/agent/tools/channel-fetch-attachment.ts +6 -5
- package/src/agent/tools/channel-reply.ts +15 -1
- package/src/agent/tools/channel-send.ts +17 -1
- package/src/agent/tools/curl-impersonate.ts +40 -1
- package/src/agent/tools/webfetch/fetch.ts +86 -3
- package/src/agent/tools/webfetch/tool.ts +26 -3
- package/src/agent/tools/webfetch/types.ts +8 -0
- package/src/agent/turn-runner.ts +79 -36
- package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
- package/src/bundled-plugins/reviewer/skills/code-review.ts +27 -2
- package/src/channels/adapters/discord-bot-edit.ts +49 -0
- package/src/channels/adapters/discord-bot.ts +30 -4
- package/src/channels/adapters/discord-edit.ts +51 -0
- package/src/channels/adapters/discord.ts +4 -0
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +10 -1
- package/src/channels/adapters/kakaotalk-typing.ts +125 -0
- package/src/channels/adapters/kakaotalk.ts +19 -0
- package/src/channels/adapters/slack-bot-edit.ts +58 -0
- package/src/channels/adapters/slack-bot.ts +18 -6
- package/src/channels/adapters/slack-edit.ts +47 -0
- package/src/channels/adapters/slack.ts +5 -0
- package/src/channels/adapters/teams-edit.ts +61 -0
- package/src/channels/adapters/teams.ts +4 -0
- package/src/channels/adapters/telegram-bot-edit.ts +51 -0
- package/src/channels/adapters/telegram-bot.ts +5 -0
- package/src/channels/adapters/webex-bot.ts +5 -0
- package/src/channels/adapters/webex-edit.ts +47 -0
- package/src/channels/adapters/webex.ts +5 -0
- package/src/channels/continuation-willingness.ts +227 -35
- package/src/channels/router.ts +500 -20
- package/src/channels/schema.ts +24 -0
- package/src/channels/types.ts +36 -0
- package/src/run/llm-fetch-observer.ts +147 -9
- package/src/server/command-runner.ts +2 -1
- package/src/server/index.ts +2 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typeclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.1",
|
|
4
4
|
"homepage": "https://github.com/typeclaw/typeclaw#readme",
|
|
5
5
|
"bugs": {
|
|
6
6
|
"url": "https://github.com/typeclaw/typeclaw/issues"
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"access": "public"
|
|
32
32
|
},
|
|
33
33
|
"scripts": {
|
|
34
|
-
"typecheck": "
|
|
34
|
+
"typecheck": "tsc --noEmit",
|
|
35
35
|
"lint": "oxlint",
|
|
36
36
|
"format": "oxfmt --write .",
|
|
37
37
|
"format:check": "oxfmt --check .",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"@mariozechner/pi-tui": "^0.73.1",
|
|
51
51
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
52
52
|
"@mozilla/readability": "^0.6.0",
|
|
53
|
-
"agent-messenger": "^2.
|
|
53
|
+
"agent-messenger": "^2.31.0",
|
|
54
54
|
"cheerio": "^1.2.0",
|
|
55
55
|
"citty": "^0.2.2",
|
|
56
56
|
"cron-parser": "^5.5.0",
|
|
@@ -69,12 +69,13 @@
|
|
|
69
69
|
"@types/qrcode": "^1.5.6",
|
|
70
70
|
"@types/sinonjs__fake-timers": "^15.0.1",
|
|
71
71
|
"@types/turndown": "^5.0.6",
|
|
72
|
-
"@typescript/
|
|
72
|
+
"@typescript/typescript6": "^6.0.2",
|
|
73
73
|
"oxfmt": "^0.45.0",
|
|
74
|
-
"oxlint": "^1.60.0"
|
|
74
|
+
"oxlint": "^1.60.0",
|
|
75
|
+
"typescript": "^7.0.2"
|
|
75
76
|
},
|
|
76
77
|
"peerDependencies": {
|
|
77
|
-
"typescript": "^5"
|
|
78
|
+
"typescript": "^5 || ^6 || ^7"
|
|
78
79
|
},
|
|
79
80
|
"engines": {
|
|
80
81
|
"bun": ">=1.1.0"
|
package/src/agent/index.ts
CHANGED
|
@@ -72,6 +72,7 @@ import {
|
|
|
72
72
|
import { attachToolNotFoundNudge } from './tool-not-found-nudge'
|
|
73
73
|
import { createBudgetState, type ToolResultBudget, wrapToolDefinitionWithBudget } from './tool-result-budget'
|
|
74
74
|
import { createChannelDisengageTool } from './tools/channel-disengage'
|
|
75
|
+
import { createChannelEditTool } from './tools/channel-edit'
|
|
75
76
|
import { createChannelFetchAttachmentTool, resolveInboxBaseDir } from './tools/channel-fetch-attachment'
|
|
76
77
|
import { createChannelHistoryTool } from './tools/channel-history'
|
|
77
78
|
import { createChannelReactTool } from './tools/channel-react'
|
|
@@ -251,6 +252,15 @@ export async function createSession(options: CreateSessionOptions = {}): Promise
|
|
|
251
252
|
return session
|
|
252
253
|
}
|
|
253
254
|
|
|
255
|
+
export function attachLoopGuardTurnTracking(
|
|
256
|
+
agent: { subscribe: (listener: (event: unknown) => void) => () => void },
|
|
257
|
+
onTurnStart: () => void,
|
|
258
|
+
): () => void {
|
|
259
|
+
return agent.subscribe((event: unknown) => {
|
|
260
|
+
if ((event as { type?: string }).type === 'turn_start') onTurnStart()
|
|
261
|
+
})
|
|
262
|
+
}
|
|
263
|
+
|
|
254
264
|
export async function createSessionWithDispose(options: CreateSessionOptions = {}): Promise<CreateSessionResult> {
|
|
255
265
|
const resolved = resolveProfile(getConfig().models, options.profile)
|
|
256
266
|
// Unknown profiles silently fall back to `default`. The fallback is by design
|
|
@@ -300,6 +310,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
300
310
|
// plugin-tools.ts for why aborting (not throwing) is what stops the loop.
|
|
301
311
|
const abortHolder: { abort?: (reason?: string) => void; reason?: string } = {}
|
|
302
312
|
const getAbort: () => ((reason?: string) => void) | undefined = () => abortHolder.abort
|
|
313
|
+
let loopGuardTurnId = 0
|
|
314
|
+
const getLoopGuardTurn = () => loopGuardTurnId
|
|
303
315
|
|
|
304
316
|
// Subagent built-in tool refs resolve to `ToolDefinition`s (see
|
|
305
317
|
// plugin-tools.ts). Their NAMES narrow the session via `tools:`; their wrapped
|
|
@@ -311,8 +323,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
311
323
|
const subagentBuiltinNames = resolvedSubagentBuiltins.map((t) => t.name)
|
|
312
324
|
const subagentTypeclawToolDefinitions = resolvedSubagentBuiltins.filter((t) => !isPiCodingBuiltinName(t.name))
|
|
313
325
|
const pluginCustomTools = options.pluginSubagent
|
|
314
|
-
? wrapSubagentCustomTools(options.pluginSubagent, options.plugins, getOrigin, getAbort)
|
|
315
|
-
: wrapRegistryTools(options.plugins, getOrigin, getAbort)
|
|
326
|
+
? wrapSubagentCustomTools(options.pluginSubagent, options.plugins, getOrigin, getAbort, getLoopGuardTurn)
|
|
327
|
+
: wrapRegistryTools(options.plugins, getOrigin, getAbort, getLoopGuardTurn)
|
|
316
328
|
|
|
317
329
|
// Per-run budget state for the tool-result byte ceiling. Allocated once per
|
|
318
330
|
// session creation and threaded into every wrapped tool so they share the
|
|
@@ -441,10 +453,17 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
441
453
|
hooks: options.plugins?.hooks ?? createHookBus(),
|
|
442
454
|
getOrigin,
|
|
443
455
|
getAbort,
|
|
456
|
+
getLoopGuardTurn,
|
|
444
457
|
...(options.permissions ? { permissions: options.permissions } : {}),
|
|
445
458
|
...(options.bashPolicy !== undefined ? { bashPolicy: options.bashPolicy } : {}),
|
|
446
459
|
})
|
|
447
|
-
const wrappedCustomSystemTools = wrapSystemTools(
|
|
460
|
+
const wrappedCustomSystemTools = wrapSystemTools(
|
|
461
|
+
customSystemTools,
|
|
462
|
+
options.plugins,
|
|
463
|
+
getOrigin,
|
|
464
|
+
getAbort,
|
|
465
|
+
getLoopGuardTurn,
|
|
466
|
+
)
|
|
448
467
|
const customToolsPreBudget = [...wrappedCustomSystemTools, ...pluginCustomTools, ...builtinPiToolOverrides]
|
|
449
468
|
const customTools =
|
|
450
469
|
sessionBudget && sessionBudgetState
|
|
@@ -480,8 +499,19 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
480
499
|
customTools,
|
|
481
500
|
...(thinkingLevel ? { thinkingLevel } : {}),
|
|
482
501
|
})
|
|
502
|
+
// typeclaw owns retry/fallback in its turn drivers, so the SDK's own
|
|
503
|
+
// same-model auto-retry must be OFF. Leaving it on races typeclaw's
|
|
504
|
+
// soft-error capture: the SDK can silently recover a `stopReason:'error'` turn
|
|
505
|
+
// while typeclaw has already latched the failure, reporting a recovered turn as
|
|
506
|
+
// failed (and burning an unnecessary failover). Disabling it makes a soft error
|
|
507
|
+
// a deterministic, typeclaw-owned signal. Compaction/context-overflow recovery
|
|
508
|
+
// is independent (gated on compaction settings), so this does not disable those.
|
|
509
|
+
;(session as { setAutoRetryEnabled?: (enabled: boolean) => void }).setAutoRetryEnabled?.(false)
|
|
483
510
|
const getAbortReason = () => abortHolder.reason
|
|
484
511
|
const sessionWithAbortReason = Object.assign(session, { getAbortReason })
|
|
512
|
+
const unsubLoopGuardTurn = attachLoopGuardTurnTracking(session.agent, () => {
|
|
513
|
+
loopGuardTurnId += 1
|
|
514
|
+
})
|
|
485
515
|
|
|
486
516
|
// Layer the replay sanitizer over pi's convertToLlm so a transcript with an
|
|
487
517
|
// orphaned toolResult (e.g. a torn-down restart turn) can't wedge the session
|
|
@@ -515,6 +545,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
515
545
|
const unsubToolNudge = attachToolNotFoundNudge(session, intendedActiveToolNames)
|
|
516
546
|
|
|
517
547
|
const dispose = async () => {
|
|
548
|
+
unsubLoopGuardTurn()
|
|
518
549
|
unsubRestart?.()
|
|
519
550
|
unsubToolNudge()
|
|
520
551
|
if (materializedSkills) await materializedSkills.dispose()
|
|
@@ -704,6 +735,7 @@ export function buildChannelTools(
|
|
|
704
735
|
...(sessionId !== undefined ? { sessionId } : {}),
|
|
705
736
|
}),
|
|
706
737
|
)
|
|
738
|
+
tools.push(createChannelEditTool({ router: channelRouter }))
|
|
707
739
|
// Read the live turn origin, falling back to the static snapshot when no
|
|
708
740
|
// getter is wired (composition tests). `reactionRef` is per-turn, so the
|
|
709
741
|
// getter is what makes reactions work outside tests.
|
|
@@ -735,6 +767,7 @@ export function buildChannelTools(
|
|
|
735
767
|
} else {
|
|
736
768
|
tools.push(createChannelSendTool({ router: channelRouter }))
|
|
737
769
|
tools.push(createChannelReadTool({ router: channelRouter }))
|
|
770
|
+
tools.push(createChannelEditTool({ router: channelRouter }))
|
|
738
771
|
}
|
|
739
772
|
return tools
|
|
740
773
|
}
|
|
@@ -852,6 +885,7 @@ function wrapRegistryTools(
|
|
|
852
885
|
plugins: PluginSessionWiring | undefined,
|
|
853
886
|
getOrigin: () => SessionOrigin | undefined,
|
|
854
887
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
888
|
+
getLoopGuardTurn: () => number | undefined,
|
|
855
889
|
): ToolDefinition[] {
|
|
856
890
|
if (!plugins) return []
|
|
857
891
|
return plugins.registry.tools.map((t: PluginRegisteredTool) =>
|
|
@@ -864,6 +898,7 @@ function wrapRegistryTools(
|
|
|
864
898
|
hooks: plugins.hooks,
|
|
865
899
|
getOrigin,
|
|
866
900
|
getAbort,
|
|
901
|
+
getLoopGuardTurn,
|
|
867
902
|
}),
|
|
868
903
|
)
|
|
869
904
|
}
|
|
@@ -873,6 +908,7 @@ function wrapSystemTools(
|
|
|
873
908
|
plugins: PluginSessionWiring | undefined,
|
|
874
909
|
getOrigin: () => SessionOrigin | undefined,
|
|
875
910
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
911
|
+
getLoopGuardTurn: () => number | undefined,
|
|
876
912
|
): ToolDefinition[] {
|
|
877
913
|
if (!hasToolHooks(plugins)) return tools
|
|
878
914
|
return tools.map((tool) =>
|
|
@@ -882,6 +918,7 @@ function wrapSystemTools(
|
|
|
882
918
|
hooks: plugins.hooks,
|
|
883
919
|
getOrigin,
|
|
884
920
|
getAbort,
|
|
921
|
+
getLoopGuardTurn,
|
|
885
922
|
}),
|
|
886
923
|
)
|
|
887
924
|
}
|
|
@@ -896,6 +933,7 @@ function wrapSubagentCustomTools(
|
|
|
896
933
|
plugins: PluginSessionWiring | undefined,
|
|
897
934
|
getOrigin: () => SessionOrigin | undefined,
|
|
898
935
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
936
|
+
getLoopGuardTurn: () => number | undefined,
|
|
899
937
|
): ToolDefinition[] {
|
|
900
938
|
if (!selection.customTools || !plugins) return []
|
|
901
939
|
const logger = makePluginLogger(selection.pluginName)
|
|
@@ -909,6 +947,7 @@ function wrapSubagentCustomTools(
|
|
|
909
947
|
hooks: plugins.hooks,
|
|
910
948
|
getOrigin,
|
|
911
949
|
getAbort,
|
|
950
|
+
getLoopGuardTurn,
|
|
912
951
|
}),
|
|
913
952
|
)
|
|
914
953
|
}
|
package/src/agent/loop-guard.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { posix } from 'node:path'
|
|
2
|
+
|
|
1
3
|
// Detects when the model is stuck looping on tool calls. Two independent
|
|
2
4
|
// detectors run per call; the more severe decision wins.
|
|
3
5
|
//
|
|
@@ -10,8 +12,9 @@
|
|
|
10
12
|
// re-reading one file with drifting offsets. Over a sliding window of the
|
|
11
13
|
// last WINDOW_SIZE calls, if one signature recurs WINDOW_SOFT_WARN times it
|
|
12
14
|
// warns and WINDOW_HARD_BLOCK times it blocks. Path-bearing tools coarsen
|
|
13
|
-
// their signature to the path alone
|
|
14
|
-
//
|
|
15
|
+
// their signature to the path alone. Read calls additionally recognize one
|
|
16
|
+
// assistant tool batch and successfully-observed forward pagination so
|
|
17
|
+
// productive inspection does not look like a reactive cycle.
|
|
15
18
|
//
|
|
16
19
|
// Both warn/block decisions carry the byte-identical or coarsened nudge text.
|
|
17
20
|
// The wrapping in plugin-tools.ts maps a block to `errorResult` for plugin tools
|
|
@@ -71,12 +74,20 @@ export type LoopGuardReceipt = {
|
|
|
71
74
|
tool: string
|
|
72
75
|
signature: string
|
|
73
76
|
windowSignature: string
|
|
77
|
+
recorded: boolean
|
|
78
|
+
readPage?: ReadPage
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type LoopGuardCheckContext = {
|
|
82
|
+
turnId?: number
|
|
83
|
+
cwd?: string
|
|
74
84
|
}
|
|
75
85
|
|
|
76
86
|
// Post-execution classification of a `subagent_output` poll, fed back via
|
|
77
87
|
// `noteResult`. 'running' is a still-pending wait; 'terminal' is completed/failed
|
|
78
88
|
// — a repeated terminal poll is a real loop.
|
|
79
89
|
export type LoopObservedResult = 'running' | 'terminal'
|
|
90
|
+
export type ReadObservedResult = { nonEmpty: boolean; outputLines?: number; textual?: boolean }
|
|
80
91
|
|
|
81
92
|
export type LoopGuardDecision =
|
|
82
93
|
| { kind: 'ok'; receipt: LoopGuardReceipt }
|
|
@@ -91,7 +102,7 @@ type Verdict =
|
|
|
91
102
|
| { kind: 'block'; count: number; reason: LoopReason; message: string }
|
|
92
103
|
|
|
93
104
|
export type LoopGuard = {
|
|
94
|
-
check: (sessionId: string, tool: string, args: unknown) => LoopGuardDecision
|
|
105
|
+
check: (sessionId: string, tool: string, args: unknown, context?: LoopGuardCheckContext) => LoopGuardDecision
|
|
95
106
|
reset: (sessionId: string) => void
|
|
96
107
|
forget: (sessionId: string) => void
|
|
97
108
|
// Clears only the residue a single tool left behind in a session: its entries
|
|
@@ -104,9 +115,10 @@ export type LoopGuard = {
|
|
|
104
115
|
forgetTool: (sessionId: string, tool: string) => void
|
|
105
116
|
// Undoes the one observation a prior `check` recorded, identified by its
|
|
106
117
|
// receipt. Pops that signature from the windowed history and, when the
|
|
107
|
-
// current consecutive streak is the call this receipt named
|
|
108
|
-
//
|
|
109
|
-
//
|
|
118
|
+
// current consecutive streak is the call this receipt named, rewinds the
|
|
119
|
+
// streak by one. Suppressed same-batch read receipts are explicit no-ops so
|
|
120
|
+
// parallel sibling completion cannot retract the recorded observation. Used
|
|
121
|
+
// post-execution for a
|
|
110
122
|
// `subagent_output` poll that returned `status: 'running'` — a still-pending
|
|
111
123
|
// wait, not a loop — so it never accumulates toward either detector.
|
|
112
124
|
retract: (receipt: LoopGuardReceipt) => void
|
|
@@ -117,6 +129,7 @@ export type LoopGuard = {
|
|
|
117
129
|
// mark for that signature (a task can only move running→terminal, but a
|
|
118
130
|
// signature can be reused across episodes).
|
|
119
131
|
noteResult: (receipt: LoopGuardReceipt, result: LoopObservedResult) => void
|
|
132
|
+
noteReadResult: (receipt: LoopGuardReceipt, result: ReadObservedResult) => void
|
|
120
133
|
}
|
|
121
134
|
|
|
122
135
|
type SessionState = {
|
|
@@ -134,8 +147,19 @@ type SessionState = {
|
|
|
134
147
|
// A block on such a signature is enforced pre-execute (not deferred), so a
|
|
135
148
|
// completed task is not re-polled forever just to re-learn it is done.
|
|
136
149
|
termKnown: Set<string>
|
|
150
|
+
// A model turn may emit several tool calls in one assistant message. Those
|
|
151
|
+
// calls cannot react to one another's results, so same-path reads in that
|
|
152
|
+
// batch count as one loop observation rather than a reactive cycle.
|
|
153
|
+
readTurnId: number | undefined
|
|
154
|
+
readPathsThisTurn: Set<string>
|
|
155
|
+
// Observed contiguous line progress per recently-read canonical path.
|
|
156
|
+
// Suppressed siblings may wait here for earlier siblings to complete, but
|
|
157
|
+
// only exact adjacency advances the frontier.
|
|
158
|
+
readFrontiers: Map<string, ReadProgress>
|
|
137
159
|
}
|
|
138
160
|
|
|
161
|
+
type ReadProgress = { frontier?: number; pending: Map<number, number> }
|
|
162
|
+
|
|
139
163
|
export type CreateLoopGuardOptions = {
|
|
140
164
|
softWarn?: number
|
|
141
165
|
hardBlock?: number
|
|
@@ -228,10 +252,8 @@ export function createLoopGuard(options: CreateLoopGuardOptions = {}): LoopGuard
|
|
|
228
252
|
}
|
|
229
253
|
|
|
230
254
|
return {
|
|
231
|
-
check(sessionId, tool, args) {
|
|
255
|
+
check(sessionId, tool, args, context) {
|
|
232
256
|
const signature = makeCallSignature(tool, args)
|
|
233
|
-
const windowSig = makeWindowSignature(tool, args)
|
|
234
|
-
const receipt: LoopGuardReceipt = { sessionId, tool, signature, windowSignature: windowSig }
|
|
235
257
|
const existing = sessions.get(sessionId)
|
|
236
258
|
|
|
237
259
|
const state: SessionState = existing ?? {
|
|
@@ -241,6 +263,36 @@ export function createLoopGuard(options: CreateLoopGuardOptions = {}): LoopGuard
|
|
|
241
263
|
window: [],
|
|
242
264
|
windowWarned: new Set(),
|
|
243
265
|
termKnown: new Set(),
|
|
266
|
+
readTurnId: undefined,
|
|
267
|
+
readPathsThisTurn: new Set(),
|
|
268
|
+
readFrontiers: new Map(),
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const readTarget = parseReadTarget(tool, args, context?.cwd)
|
|
272
|
+
const readPage = parseReadPage(tool, args, context?.cwd)
|
|
273
|
+
if (readTarget !== undefined && context?.turnId !== undefined) {
|
|
274
|
+
if (readPathSeenThisTurn(state, readTarget.path, context.turnId, windowSize)) {
|
|
275
|
+
const receipt: LoopGuardReceipt = {
|
|
276
|
+
sessionId,
|
|
277
|
+
tool,
|
|
278
|
+
signature,
|
|
279
|
+
windowSignature: readPathSignature(readTarget.path),
|
|
280
|
+
recorded: false,
|
|
281
|
+
...(readPage !== undefined ? { readPage } : {}),
|
|
282
|
+
}
|
|
283
|
+
touch(sessionId, state)
|
|
284
|
+
return { kind: 'ok', receipt }
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const windowSig = makeWindowSignature(tool, args, state, context?.cwd)
|
|
289
|
+
const receipt: LoopGuardReceipt = {
|
|
290
|
+
sessionId,
|
|
291
|
+
tool,
|
|
292
|
+
signature,
|
|
293
|
+
windowSignature: windowSig,
|
|
294
|
+
recorded: true,
|
|
295
|
+
...(readPage !== undefined ? { readPage } : {}),
|
|
244
296
|
}
|
|
245
297
|
|
|
246
298
|
if (state.signature !== signature) {
|
|
@@ -296,8 +348,14 @@ export function createLoopGuard(options: CreateLoopGuardOptions = {}): LoopGuard
|
|
|
296
348
|
for (const sig of state.termKnown) {
|
|
297
349
|
if (signatureBelongsToTool(sig, tool)) state.termKnown.delete(sig)
|
|
298
350
|
}
|
|
351
|
+
if (tool === 'read') {
|
|
352
|
+
state.readTurnId = undefined
|
|
353
|
+
state.readPathsThisTurn.clear()
|
|
354
|
+
state.readFrontiers.clear()
|
|
355
|
+
}
|
|
299
356
|
},
|
|
300
357
|
retract(receipt) {
|
|
358
|
+
if (!receipt.recorded) return
|
|
301
359
|
const state = sessions.get(receipt.sessionId)
|
|
302
360
|
if (state === undefined) return
|
|
303
361
|
|
|
@@ -322,11 +380,21 @@ export function createLoopGuard(options: CreateLoopGuardOptions = {}): LoopGuard
|
|
|
322
380
|
}
|
|
323
381
|
},
|
|
324
382
|
noteResult(receipt, result) {
|
|
383
|
+
if (!receipt.recorded) return
|
|
325
384
|
const state = sessions.get(receipt.sessionId)
|
|
326
385
|
if (state === undefined) return
|
|
327
386
|
if (result === 'terminal') state.termKnown.add(receipt.signature)
|
|
328
387
|
else state.termKnown.delete(receipt.signature)
|
|
329
388
|
},
|
|
389
|
+
noteReadResult(receipt, result) {
|
|
390
|
+
const page = receipt.readPage
|
|
391
|
+
if (page === undefined || !result.nonEmpty || result.textual === false) return
|
|
392
|
+
const state = sessions.get(receipt.sessionId)
|
|
393
|
+
if (state === undefined) return
|
|
394
|
+
const span = result.outputLines
|
|
395
|
+
if (span === undefined || !Number.isFinite(span) || span <= 0) return
|
|
396
|
+
updateReadFrontier(state, page.path, page.offset, page.offset + span, receipt.recorded, windowSize)
|
|
397
|
+
},
|
|
330
398
|
}
|
|
331
399
|
}
|
|
332
400
|
|
|
@@ -385,7 +453,16 @@ function makeCallSignature(tool: string, args: unknown): string {
|
|
|
385
453
|
// target path alone so re-reading one target with drifting non-path args
|
|
386
454
|
// collapses to a single signature. All other tools fall back to the exact
|
|
387
455
|
// signature.
|
|
388
|
-
function makeWindowSignature(tool: string, args: unknown): string {
|
|
456
|
+
function makeWindowSignature(tool: string, args: unknown, state: SessionState, cwd: string | undefined): string {
|
|
457
|
+
const readPage = parseReadPage(tool, args, cwd)
|
|
458
|
+
if (readPage !== undefined) {
|
|
459
|
+
const coarse = readPathSignature(readPage.path)
|
|
460
|
+
const previousFrontier = state.readFrontiers.get(readPage.path)?.frontier
|
|
461
|
+
return previousFrontier !== undefined && readPage.offset === previousFrontier
|
|
462
|
+
? `${coarse}#frontier:${readPage.offset}`
|
|
463
|
+
: coarse
|
|
464
|
+
}
|
|
465
|
+
|
|
389
466
|
const isRequiredPath = REQUIRED_PATH_TOOLS.has(tool)
|
|
390
467
|
const isDefaultPath = DEFAULT_PATH_TOOLS.has(tool)
|
|
391
468
|
if ((isRequiredPath || isDefaultPath) && args !== null && typeof args === 'object') {
|
|
@@ -401,6 +478,127 @@ function makeWindowSignature(tool: string, args: unknown): string {
|
|
|
401
478
|
return makeCallSignature(tool, args)
|
|
402
479
|
}
|
|
403
480
|
|
|
481
|
+
type ReadTarget = { path: string }
|
|
482
|
+
type ReadPage = ReadTarget & { offset: number; limit?: number }
|
|
483
|
+
|
|
484
|
+
function parseReadTarget(tool: string, args: unknown, cwd?: string): ReadTarget | undefined {
|
|
485
|
+
if (tool !== 'read' || args === null || typeof args !== 'object') return undefined
|
|
486
|
+
const record = args as Record<string, unknown>
|
|
487
|
+
const path = PATH_ARG_KEYS.map((key) => record[key]).find(
|
|
488
|
+
(value): value is string => typeof value === 'string' && value.length > 0,
|
|
489
|
+
)
|
|
490
|
+
return path === undefined ? undefined : { path: canonicalizeReadPath(path, cwd) }
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function parseReadPage(tool: string, args: unknown, cwd?: string): ReadPage | undefined {
|
|
494
|
+
const target = parseReadTarget(tool, args, cwd)
|
|
495
|
+
if (target === undefined || args === null || typeof args !== 'object') return undefined
|
|
496
|
+
const record = args as Record<string, unknown>
|
|
497
|
+
const { offset, limit } = record
|
|
498
|
+
if (
|
|
499
|
+
(offset !== undefined && (typeof offset !== 'number' || !Number.isFinite(offset) || offset < 1)) ||
|
|
500
|
+
(limit !== undefined && (typeof limit !== 'number' || !Number.isFinite(limit) || limit <= 0))
|
|
501
|
+
) {
|
|
502
|
+
return undefined
|
|
503
|
+
}
|
|
504
|
+
return {
|
|
505
|
+
path: target.path,
|
|
506
|
+
offset: typeof offset === 'number' ? offset : 1,
|
|
507
|
+
...(typeof limit === 'number' ? { limit } : {}),
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function readPathSignature(path: string): string {
|
|
512
|
+
return `read#path:${path}`
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function readPathSeenThisTurn(state: SessionState, path: string, turnId: number, maxReadPaths: number): boolean {
|
|
516
|
+
if (state.readTurnId !== turnId) {
|
|
517
|
+
state.readTurnId = turnId
|
|
518
|
+
state.readPathsThisTurn.clear()
|
|
519
|
+
}
|
|
520
|
+
const seen = state.readPathsThisTurn.has(path)
|
|
521
|
+
if (seen) state.readPathsThisTurn.delete(path)
|
|
522
|
+
state.readPathsThisTurn.add(path)
|
|
523
|
+
while (state.readPathsThisTurn.size > maxReadPaths) {
|
|
524
|
+
const oldest = state.readPathsThisTurn.values().next().value
|
|
525
|
+
if (oldest === undefined) break
|
|
526
|
+
state.readPathsThisTurn.delete(oldest)
|
|
527
|
+
}
|
|
528
|
+
return seen
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function updateReadFrontier(
|
|
532
|
+
state: SessionState,
|
|
533
|
+
path: string,
|
|
534
|
+
observedStart: number,
|
|
535
|
+
observedEnd: number,
|
|
536
|
+
recorded: boolean,
|
|
537
|
+
maxReadFrontiers: number,
|
|
538
|
+
): void {
|
|
539
|
+
let progress = state.readFrontiers.get(path)
|
|
540
|
+
if (progress === undefined) {
|
|
541
|
+
progress = { pending: new Map() }
|
|
542
|
+
}
|
|
543
|
+
state.readFrontiers.delete(path)
|
|
544
|
+
state.readFrontiers.set(path, progress)
|
|
545
|
+
|
|
546
|
+
if (progress.frontier === undefined) {
|
|
547
|
+
if (recorded) {
|
|
548
|
+
progress.frontier = observedEnd
|
|
549
|
+
drainContiguousReadIntervals(progress)
|
|
550
|
+
} else {
|
|
551
|
+
rememberReadInterval(progress, observedStart, observedEnd, maxReadFrontiers)
|
|
552
|
+
}
|
|
553
|
+
} else if (observedStart === progress.frontier) {
|
|
554
|
+
progress.frontier = observedEnd
|
|
555
|
+
drainContiguousReadIntervals(progress)
|
|
556
|
+
} else if (!recorded && observedStart > progress.frontier) {
|
|
557
|
+
rememberReadInterval(progress, observedStart, observedEnd, maxReadFrontiers)
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
while (state.readFrontiers.size > maxReadFrontiers) {
|
|
561
|
+
const oldest = state.readFrontiers.keys().next().value
|
|
562
|
+
if (oldest === undefined) break
|
|
563
|
+
state.readFrontiers.delete(oldest)
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function rememberReadInterval(progress: ReadProgress, start: number, end: number, maxIntervals: number): void {
|
|
568
|
+
const previousEnd = progress.pending.get(start)
|
|
569
|
+
progress.pending.delete(start)
|
|
570
|
+
progress.pending.set(start, previousEnd === undefined ? end : Math.max(previousEnd, end))
|
|
571
|
+
while (progress.pending.size > maxIntervals) {
|
|
572
|
+
const oldest = progress.pending.keys().next().value
|
|
573
|
+
if (oldest === undefined) break
|
|
574
|
+
progress.pending.delete(oldest)
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function drainContiguousReadIntervals(progress: ReadProgress): void {
|
|
579
|
+
let frontier = progress.frontier
|
|
580
|
+
if (frontier === undefined) return
|
|
581
|
+
for (const start of progress.pending.keys()) {
|
|
582
|
+
if (start < frontier) progress.pending.delete(start)
|
|
583
|
+
}
|
|
584
|
+
let nextEnd = progress.pending.get(frontier)
|
|
585
|
+
while (nextEnd !== undefined) {
|
|
586
|
+
progress.pending.delete(frontier)
|
|
587
|
+
frontier = nextEnd
|
|
588
|
+
progress.frontier = frontier
|
|
589
|
+
nextEnd = progress.pending.get(frontier)
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function canonicalizeReadPath(path: string, cwd?: string): string {
|
|
594
|
+
const normalizedPath = path.replaceAll('\\', '/')
|
|
595
|
+
if (normalizedPath.startsWith('/') || /^[A-Za-z]:\//.test(normalizedPath)) {
|
|
596
|
+
return posix.normalize(normalizedPath)
|
|
597
|
+
}
|
|
598
|
+
if (cwd === undefined) return posix.normalize(normalizedPath)
|
|
599
|
+
return posix.normalize(`${cwd.replaceAll('\\', '/')}/${normalizedPath}`)
|
|
600
|
+
}
|
|
601
|
+
|
|
404
602
|
// Order-independent JSON serialization so semantically-identical objects
|
|
405
603
|
// produce identical signatures regardless of key insertion order.
|
|
406
604
|
function stableStringify(value: unknown): string {
|
|
@@ -3,7 +3,8 @@ import type { Models } from '@/config/config'
|
|
|
3
3
|
import type { KnownModelRef, ModelRef } from '@/config/providers'
|
|
4
4
|
|
|
5
5
|
import type { AgentSession } from './index'
|
|
6
|
-
import { subscribeProviderErrors } from './provider-error'
|
|
6
|
+
import { isRetryableSameRef, subscribeProviderErrors } from './provider-error'
|
|
7
|
+
import { RETRIES_PER_REF, sleepBackoff } from './retry-same-ref'
|
|
7
8
|
import { renderTurnTimeAnchor } from './system-prompt'
|
|
8
9
|
|
|
9
10
|
// Result of a single fallback-aware prompt run.
|
|
@@ -87,53 +88,71 @@ export async function promptWithFallback<TRef extends FallbackModelRef>(opts: {
|
|
|
87
88
|
for (let i = 0; i < opts.refs.length; i++) {
|
|
88
89
|
const ref = opts.refs[i]!
|
|
89
90
|
const isLast = i === opts.refs.length - 1
|
|
91
|
+
// Try this ref, replaying the SAME ref on a transient failure before we give
|
|
92
|
+
// up on it. Cron sessions are cheap and fresh-per-attempt, so a same-ref
|
|
93
|
+
// retry just recreates the session — no state surgery needed.
|
|
94
|
+
const outcome = await attemptRefWithRetry(ref, opts)
|
|
95
|
+
if (outcome.kind === 'success') {
|
|
96
|
+
attempts.push({ ref, outcome: 'success' })
|
|
97
|
+
return { success: true, refUsed: ref, attempts, session: outcome.session, dispose: outcome.dispose }
|
|
98
|
+
}
|
|
99
|
+
attempts.push({ ref, outcome: outcome.kind, errorMessage: outcome.error.message })
|
|
100
|
+
lastError = outcome.error
|
|
101
|
+
const stop = isLast || !failoverGate(outcome.error)
|
|
102
|
+
if (!stop) opts.onAttemptFailed?.({ ref, outcome: outcome.kind, errorMessage: outcome.error.message })
|
|
103
|
+
// The failed ref's session is spent either way — dispose it. On stop we still
|
|
104
|
+
// hand the caller the (now-disposed) session for its final surface, with a
|
|
105
|
+
// no-op dispose so a double-dispose can't happen.
|
|
106
|
+
await outcome.dispose()
|
|
107
|
+
if (stop) {
|
|
108
|
+
return { success: false, refUsed: ref, attempts, session: outcome.session, dispose: async () => {}, lastError }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
throw new Error('promptWithFallback: unreachable — loop terminated without returning')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
type RefAttemptOutcome =
|
|
115
|
+
| { kind: 'success'; session: AgentSession; dispose: () => Promise<void> }
|
|
116
|
+
| { kind: 'hard' | 'soft'; error: Error; session: AgentSession; dispose: () => Promise<void> }
|
|
117
|
+
|
|
118
|
+
// One ref, with same-ref retry. Each attempt gets a fresh session (cron's
|
|
119
|
+
// pattern); a retryable failure disposes it and recreates the same ref up to
|
|
120
|
+
// RETRIES_PER_REF times before returning failure to the chain. The returned
|
|
121
|
+
// session/dispose is always from the LAST attempt so the caller can surface or
|
|
122
|
+
// keep it exactly as before.
|
|
123
|
+
async function attemptRefWithRetry<TRef extends FallbackModelRef>(
|
|
124
|
+
ref: TRef,
|
|
125
|
+
opts: {
|
|
126
|
+
text: string
|
|
127
|
+
createSessionForRef: (ref: TRef) => Promise<{ session: AgentSession; dispose: () => Promise<void> }>
|
|
128
|
+
},
|
|
129
|
+
): Promise<RefAttemptOutcome> {
|
|
130
|
+
for (let attempt = 0; ; attempt++) {
|
|
90
131
|
const { session, dispose } = await opts.createSessionForRef(ref)
|
|
91
|
-
// Capture the first soft error per attempt. The
|
|
92
|
-
//
|
|
93
|
-
//
|
|
94
|
-
// `softError` is populated if a soft error occurred.
|
|
132
|
+
// Capture the first soft error per attempt. The listener fires synchronously
|
|
133
|
+
// off `message_end`, which lands BEFORE `session.prompt()` resolves, so by
|
|
134
|
+
// the time `await` returns `softError` is populated if one occurred.
|
|
95
135
|
let softError: Error | undefined
|
|
96
136
|
const unsub = subscribeProviderErrors(session, (err) => {
|
|
97
137
|
if (!softError) softError = new Error(err.message)
|
|
98
138
|
})
|
|
139
|
+
let outcome: RefAttemptOutcome
|
|
99
140
|
try {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
attempts.push(attempt)
|
|
106
|
-
lastError = error
|
|
107
|
-
const stop = isLast || !failoverGate(error)
|
|
108
|
-
if (!stop) opts.onAttemptFailed?.(attempt)
|
|
109
|
-
unsub()
|
|
110
|
-
await dispose()
|
|
111
|
-
if (stop) {
|
|
112
|
-
return { success: false, refUsed: ref, attempts, session, dispose: async () => {}, lastError }
|
|
113
|
-
}
|
|
114
|
-
continue
|
|
115
|
-
}
|
|
116
|
-
if (softError !== undefined) {
|
|
117
|
-
const attempt: FallbackAttempt<TRef> = { ref, outcome: 'soft', errorMessage: softError.message }
|
|
118
|
-
attempts.push(attempt)
|
|
119
|
-
lastError = softError
|
|
120
|
-
const stop = isLast || !failoverGate(softError)
|
|
121
|
-
if (!stop) opts.onAttemptFailed?.(attempt)
|
|
122
|
-
unsub()
|
|
123
|
-
await dispose()
|
|
124
|
-
if (stop) {
|
|
125
|
-
return { success: false, refUsed: ref, attempts, session, dispose: async () => {}, lastError }
|
|
126
|
-
}
|
|
127
|
-
continue
|
|
128
|
-
}
|
|
129
|
-
attempts.push({ ref, outcome: 'success' })
|
|
130
|
-
unsub()
|
|
131
|
-
return { success: true, refUsed: ref, attempts, session, dispose }
|
|
141
|
+
await session.prompt(`${renderTurnTimeAnchor()}\n\n${opts.text}`)
|
|
142
|
+
outcome =
|
|
143
|
+
softError === undefined
|
|
144
|
+
? { kind: 'success', session, dispose }
|
|
145
|
+
: { kind: 'soft', error: softError, session, dispose }
|
|
132
146
|
} catch (err) {
|
|
147
|
+
outcome = { kind: 'hard', error: err instanceof Error ? err : new Error(String(err)), session, dispose }
|
|
148
|
+
} finally {
|
|
133
149
|
unsub()
|
|
134
|
-
await dispose()
|
|
135
|
-
throw err
|
|
136
150
|
}
|
|
151
|
+
if (outcome.kind === 'success') return outcome
|
|
152
|
+
const canRetry = attempt < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message)
|
|
153
|
+
if (!canRetry) return outcome
|
|
154
|
+
// Retryable and budget remains: drop this session and replay the same ref.
|
|
155
|
+
await dispose()
|
|
156
|
+
await sleepBackoff(attempt)
|
|
137
157
|
}
|
|
138
|
-
throw new Error('promptWithFallback: unreachable — loop terminated without returning')
|
|
139
158
|
}
|
|
@@ -12,6 +12,7 @@ import { providerForModelRef } from '@/config/providers'
|
|
|
12
12
|
import { LLM_FETCH_OBSERVER_TIMEOUTS, type LlmFetchObservedRequestInit } from '@/run/llm-fetch-observer'
|
|
13
13
|
import { SecretsBackend } from '@/secrets'
|
|
14
14
|
|
|
15
|
+
import { promptWithSameRefRetryOnly } from '../retry-same-ref'
|
|
15
16
|
import { buildMultimodalLookerSystemPrompt, resolveImage, type ImageInput } from './looker'
|
|
16
17
|
|
|
17
18
|
type ImageParam = { url: string } | { path: string } | { data: string; mimeType: string }
|
|
@@ -188,7 +189,7 @@ async function runLookAtImages(imageContents: ImageContent[], prompt: string | u
|
|
|
188
189
|
})
|
|
189
190
|
|
|
190
191
|
try {
|
|
191
|
-
await session
|
|
192
|
+
await promptWithSameRefRetryOnly(session, userText, { images: imageContents })
|
|
192
193
|
const text = extractLastAssistantText(session.messages)
|
|
193
194
|
if (text === null) {
|
|
194
195
|
return errorResult('multimodal-looker returned no text response', {
|