typeclaw 0.45.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 +2 -2
- package/src/agent/index.ts +31 -3
- package/src/agent/loop-guard.ts +208 -10
- package/src/agent/plugin-tools.ts +59 -5
- package/src/agent/provider-error.ts +10 -3
- package/src/agent/retry-same-ref.ts +66 -0
- package/src/agent/subagents.ts +28 -2
- package/src/agent/tools/channel-reply.ts +15 -1
- package/src/agent/tools/channel-send.ts +17 -1
- package/src/agent/turn-runner.ts +23 -9
- package/src/bundled-plugins/reviewer/skills/code-review.ts +5 -0
- package/src/channels/adapters/discord-bot.ts +25 -4
- 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/router.ts +320 -6
- package/src/run/llm-fetch-observer.ts +147 -9
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typeclaw",
|
|
3
|
-
"version": "0.45.
|
|
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"
|
|
@@ -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",
|
package/src/agent/index.ts
CHANGED
|
@@ -252,6 +252,15 @@ export async function createSession(options: CreateSessionOptions = {}): Promise
|
|
|
252
252
|
return session
|
|
253
253
|
}
|
|
254
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
|
+
|
|
255
264
|
export async function createSessionWithDispose(options: CreateSessionOptions = {}): Promise<CreateSessionResult> {
|
|
256
265
|
const resolved = resolveProfile(getConfig().models, options.profile)
|
|
257
266
|
// Unknown profiles silently fall back to `default`. The fallback is by design
|
|
@@ -301,6 +310,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
301
310
|
// plugin-tools.ts for why aborting (not throwing) is what stops the loop.
|
|
302
311
|
const abortHolder: { abort?: (reason?: string) => void; reason?: string } = {}
|
|
303
312
|
const getAbort: () => ((reason?: string) => void) | undefined = () => abortHolder.abort
|
|
313
|
+
let loopGuardTurnId = 0
|
|
314
|
+
const getLoopGuardTurn = () => loopGuardTurnId
|
|
304
315
|
|
|
305
316
|
// Subagent built-in tool refs resolve to `ToolDefinition`s (see
|
|
306
317
|
// plugin-tools.ts). Their NAMES narrow the session via `tools:`; their wrapped
|
|
@@ -312,8 +323,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
312
323
|
const subagentBuiltinNames = resolvedSubagentBuiltins.map((t) => t.name)
|
|
313
324
|
const subagentTypeclawToolDefinitions = resolvedSubagentBuiltins.filter((t) => !isPiCodingBuiltinName(t.name))
|
|
314
325
|
const pluginCustomTools = options.pluginSubagent
|
|
315
|
-
? wrapSubagentCustomTools(options.pluginSubagent, options.plugins, getOrigin, getAbort)
|
|
316
|
-
: wrapRegistryTools(options.plugins, getOrigin, getAbort)
|
|
326
|
+
? wrapSubagentCustomTools(options.pluginSubagent, options.plugins, getOrigin, getAbort, getLoopGuardTurn)
|
|
327
|
+
: wrapRegistryTools(options.plugins, getOrigin, getAbort, getLoopGuardTurn)
|
|
317
328
|
|
|
318
329
|
// Per-run budget state for the tool-result byte ceiling. Allocated once per
|
|
319
330
|
// session creation and threaded into every wrapped tool so they share the
|
|
@@ -442,10 +453,17 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
442
453
|
hooks: options.plugins?.hooks ?? createHookBus(),
|
|
443
454
|
getOrigin,
|
|
444
455
|
getAbort,
|
|
456
|
+
getLoopGuardTurn,
|
|
445
457
|
...(options.permissions ? { permissions: options.permissions } : {}),
|
|
446
458
|
...(options.bashPolicy !== undefined ? { bashPolicy: options.bashPolicy } : {}),
|
|
447
459
|
})
|
|
448
|
-
const wrappedCustomSystemTools = wrapSystemTools(
|
|
460
|
+
const wrappedCustomSystemTools = wrapSystemTools(
|
|
461
|
+
customSystemTools,
|
|
462
|
+
options.plugins,
|
|
463
|
+
getOrigin,
|
|
464
|
+
getAbort,
|
|
465
|
+
getLoopGuardTurn,
|
|
466
|
+
)
|
|
449
467
|
const customToolsPreBudget = [...wrappedCustomSystemTools, ...pluginCustomTools, ...builtinPiToolOverrides]
|
|
450
468
|
const customTools =
|
|
451
469
|
sessionBudget && sessionBudgetState
|
|
@@ -491,6 +509,9 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
491
509
|
;(session as { setAutoRetryEnabled?: (enabled: boolean) => void }).setAutoRetryEnabled?.(false)
|
|
492
510
|
const getAbortReason = () => abortHolder.reason
|
|
493
511
|
const sessionWithAbortReason = Object.assign(session, { getAbortReason })
|
|
512
|
+
const unsubLoopGuardTurn = attachLoopGuardTurnTracking(session.agent, () => {
|
|
513
|
+
loopGuardTurnId += 1
|
|
514
|
+
})
|
|
494
515
|
|
|
495
516
|
// Layer the replay sanitizer over pi's convertToLlm so a transcript with an
|
|
496
517
|
// orphaned toolResult (e.g. a torn-down restart turn) can't wedge the session
|
|
@@ -524,6 +545,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
524
545
|
const unsubToolNudge = attachToolNotFoundNudge(session, intendedActiveToolNames)
|
|
525
546
|
|
|
526
547
|
const dispose = async () => {
|
|
548
|
+
unsubLoopGuardTurn()
|
|
527
549
|
unsubRestart?.()
|
|
528
550
|
unsubToolNudge()
|
|
529
551
|
if (materializedSkills) await materializedSkills.dispose()
|
|
@@ -863,6 +885,7 @@ function wrapRegistryTools(
|
|
|
863
885
|
plugins: PluginSessionWiring | undefined,
|
|
864
886
|
getOrigin: () => SessionOrigin | undefined,
|
|
865
887
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
888
|
+
getLoopGuardTurn: () => number | undefined,
|
|
866
889
|
): ToolDefinition[] {
|
|
867
890
|
if (!plugins) return []
|
|
868
891
|
return plugins.registry.tools.map((t: PluginRegisteredTool) =>
|
|
@@ -875,6 +898,7 @@ function wrapRegistryTools(
|
|
|
875
898
|
hooks: plugins.hooks,
|
|
876
899
|
getOrigin,
|
|
877
900
|
getAbort,
|
|
901
|
+
getLoopGuardTurn,
|
|
878
902
|
}),
|
|
879
903
|
)
|
|
880
904
|
}
|
|
@@ -884,6 +908,7 @@ function wrapSystemTools(
|
|
|
884
908
|
plugins: PluginSessionWiring | undefined,
|
|
885
909
|
getOrigin: () => SessionOrigin | undefined,
|
|
886
910
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
911
|
+
getLoopGuardTurn: () => number | undefined,
|
|
887
912
|
): ToolDefinition[] {
|
|
888
913
|
if (!hasToolHooks(plugins)) return tools
|
|
889
914
|
return tools.map((tool) =>
|
|
@@ -893,6 +918,7 @@ function wrapSystemTools(
|
|
|
893
918
|
hooks: plugins.hooks,
|
|
894
919
|
getOrigin,
|
|
895
920
|
getAbort,
|
|
921
|
+
getLoopGuardTurn,
|
|
896
922
|
}),
|
|
897
923
|
)
|
|
898
924
|
}
|
|
@@ -907,6 +933,7 @@ function wrapSubagentCustomTools(
|
|
|
907
933
|
plugins: PluginSessionWiring | undefined,
|
|
908
934
|
getOrigin: () => SessionOrigin | undefined,
|
|
909
935
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
936
|
+
getLoopGuardTurn: () => number | undefined,
|
|
910
937
|
): ToolDefinition[] {
|
|
911
938
|
if (!selection.customTools || !plugins) return []
|
|
912
939
|
const logger = makePluginLogger(selection.pluginName)
|
|
@@ -920,6 +947,7 @@ function wrapSubagentCustomTools(
|
|
|
920
947
|
hooks: plugins.hooks,
|
|
921
948
|
getOrigin,
|
|
922
949
|
getAbort,
|
|
950
|
+
getLoopGuardTurn,
|
|
923
951
|
}),
|
|
924
952
|
)
|
|
925
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 {
|
|
@@ -200,6 +200,7 @@ export type WrapToolOptions = {
|
|
|
200
200
|
// time) because tools are wrapped BEFORE `createAgentSession` returns the
|
|
201
201
|
// session whose `agent.abort` this points at. See `fireLoopAbort`.
|
|
202
202
|
getAbort?: () => ((reason?: string) => void) | undefined
|
|
203
|
+
getLoopGuardTurn?: () => number | undefined
|
|
203
204
|
}
|
|
204
205
|
|
|
205
206
|
export type WrapSystemToolOptions = {
|
|
@@ -208,6 +209,7 @@ export type WrapSystemToolOptions = {
|
|
|
208
209
|
hooks: HookBus
|
|
209
210
|
getOrigin?: () => SessionOrigin | undefined
|
|
210
211
|
getAbort?: () => ((reason?: string) => void) | undefined
|
|
212
|
+
getLoopGuardTurn?: () => number | undefined
|
|
211
213
|
// When present, the bash builtin is rewritten through the per-tool bwrap
|
|
212
214
|
// sandbox with role-derived path masks. Absent (or no masks for the role)
|
|
213
215
|
// runs bash unchanged — preserving today's behavior for trusted+ and for
|
|
@@ -269,7 +271,13 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
|
|
|
269
271
|
return errorResult(`blocked: ${blockResult.reason}`)
|
|
270
272
|
}
|
|
271
273
|
|
|
272
|
-
const loopGate = gateLoopGuard(
|
|
274
|
+
const loopGate = gateLoopGuard(
|
|
275
|
+
opts.sessionId,
|
|
276
|
+
opts.toolName,
|
|
277
|
+
before.args,
|
|
278
|
+
opts.getLoopGuardTurn?.(),
|
|
279
|
+
opts.agentDir,
|
|
280
|
+
)
|
|
273
281
|
if (loopGate.blockNow) {
|
|
274
282
|
fireLoopAbort(opts.getAbort, 'loop_guard:block')
|
|
275
283
|
return errorResult(loopGate.message)
|
|
@@ -332,7 +340,7 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
|
|
|
332
340
|
if (blockResult !== undefined) {
|
|
333
341
|
throw new Error(`blocked: ${blockResult.reason}`)
|
|
334
342
|
}
|
|
335
|
-
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
|
|
343
|
+
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
|
|
336
344
|
if (loopGate.blockNow) {
|
|
337
345
|
fireLoopAbort(opts.getAbort, 'loop_guard:block')
|
|
338
346
|
throw new Error(loopGate.message)
|
|
@@ -406,7 +414,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
406
414
|
// loop-detection state, or pi's execute.
|
|
407
415
|
const bashEnvOverlay = readBashEnvOverlay(mutableArgs)
|
|
408
416
|
delete mutableArgs[TYPECLAW_INTERNAL_BASH_ENV]
|
|
409
|
-
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
|
|
417
|
+
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
|
|
410
418
|
if (loopGate.blockNow) {
|
|
411
419
|
fireLoopAbort(opts.getAbort, 'loop_guard:block')
|
|
412
420
|
throw new Error(loopGate.message)
|
|
@@ -818,6 +826,44 @@ function subagentPollStatus(toolName: string, result: ToolResult): 'running' | '
|
|
|
818
826
|
return details.status === 'running' ? 'running' : 'terminal'
|
|
819
827
|
}
|
|
820
828
|
|
|
829
|
+
function observedReadResult(
|
|
830
|
+
toolName: string,
|
|
831
|
+
result: ToolResult,
|
|
832
|
+
): { nonEmpty: boolean; outputLines?: number; textual: boolean } | undefined {
|
|
833
|
+
if (toolName !== 'read') return undefined
|
|
834
|
+
const details = result.details as { truncation?: { outputLines?: unknown } } | undefined
|
|
835
|
+
const outputLines = details?.truncation?.outputLines
|
|
836
|
+
const hasImage = result.content.some((part) => part.type === 'image')
|
|
837
|
+
const hasText = result.content.some(
|
|
838
|
+
(part) => part.type === 'text' && typeof part.text === 'string' && part.text.trim().length > 0,
|
|
839
|
+
)
|
|
840
|
+
const imageFallback =
|
|
841
|
+
!hasImage &&
|
|
842
|
+
result.content.some(
|
|
843
|
+
(part) => part.type === 'text' && typeof part.text === 'string' && /^Read image file \[[^\]]+\]/.test(part.text),
|
|
844
|
+
)
|
|
845
|
+
const observedOutputLines =
|
|
846
|
+
typeof outputLines === 'number' && Number.isFinite(outputLines)
|
|
847
|
+
? outputLines
|
|
848
|
+
: !hasImage && !imageFallback
|
|
849
|
+
? countReadOutputLines(result.content)
|
|
850
|
+
: undefined
|
|
851
|
+
return {
|
|
852
|
+
nonEmpty: hasImage || hasText,
|
|
853
|
+
textual: !hasImage && !imageFallback,
|
|
854
|
+
...(observedOutputLines !== undefined ? { outputLines: observedOutputLines } : {}),
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function countReadOutputLines(content: ContentPart[]): number | undefined {
|
|
859
|
+
const textParts = content.filter(
|
|
860
|
+
(part): part is Extract<ContentPart, { type: 'text' }> => part.type === 'text' && typeof part.text === 'string',
|
|
861
|
+
)
|
|
862
|
+
if (textParts.length !== 1) return undefined
|
|
863
|
+
const fileText = textParts[0]!.text.replace(/\n\n\[\d+ more lines in file\. Use offset=\d+ to continue\.\]$/, '')
|
|
864
|
+
return fileText.length === 0 ? 0 : fileText.split('\n').length
|
|
865
|
+
}
|
|
866
|
+
|
|
821
867
|
type LoopGuardGate = {
|
|
822
868
|
// True when the guard wants to block AND the block is enforced now (every tool
|
|
823
869
|
// except a deferable `subagent_output` poll). The caller aborts + errors.
|
|
@@ -835,13 +881,21 @@ type LoopGuardGate = {
|
|
|
835
881
|
// semantics. `check` runs here (recording the observation); the returned
|
|
836
882
|
// `resolve` is called after execute with the tool's result, feeding the poll's
|
|
837
883
|
// running/terminal status back to the guard so future blocks stop deferring.
|
|
838
|
-
function gateLoopGuard(
|
|
839
|
-
|
|
884
|
+
function gateLoopGuard(
|
|
885
|
+
sessionId: string,
|
|
886
|
+
toolName: string,
|
|
887
|
+
args: unknown,
|
|
888
|
+
turnId?: number,
|
|
889
|
+
cwd?: string,
|
|
890
|
+
): LoopGuardGate {
|
|
891
|
+
const decision = sharedLoopGuard.check(sessionId, toolName, args, { turnId, cwd })
|
|
840
892
|
const defer = shouldDeferLoopBlock(toolName, decision)
|
|
841
893
|
return {
|
|
842
894
|
blockNow: decision.kind === 'block' && !defer,
|
|
843
895
|
message: decision.kind === 'ok' ? '' : decision.message,
|
|
844
896
|
resolve(result) {
|
|
897
|
+
const readResult = observedReadResult(toolName, result)
|
|
898
|
+
if (readResult !== undefined) sharedLoopGuard.noteReadResult(decision.receipt, readResult)
|
|
845
899
|
const pollStatus = subagentPollStatus(toolName, result)
|
|
846
900
|
if (pollStatus !== undefined) {
|
|
847
901
|
sharedLoopGuard.noteResult(decision.receipt, pollStatus)
|
|
@@ -42,17 +42,17 @@ const OBSERVER_TIMEOUT = /\(typeclaw observer timeout\)/i
|
|
|
42
42
|
// `wss://…/codex/responses` non-101 upgrade). Provider protocol tokens — English
|
|
43
43
|
// by design (the system-token exception to the multi-language rule).
|
|
44
44
|
const TRANSPORT_FAILURE =
|
|
45
|
-
/provider[_ -]?transport[_ -]?failure|(?:websocket|ws) connection
|
|
45
|
+
/provider[_ -]?transport[_ -]?failure|(?:websocket|ws)(?: connection)?(?:(?: was| is)? closed|.*failed)|expected 101|session expired/i
|
|
46
46
|
|
|
47
47
|
// Auth failure: the provider rejected our credentials (bad/expired/missing API
|
|
48
|
-
// key, 401, failed authentication). Account-wide — a different ref shares the
|
|
48
|
+
// key or token, 401/403, failed authentication). Account-wide — a different ref shares the
|
|
49
49
|
// same credential problem — so this is BOTH a redacted safe-message class (a
|
|
50
50
|
// 401 body can carry a Bearer token) AND a NON_FAILOVER_FAULT reason. Shared as
|
|
51
51
|
// one constant so the two uses can never drift: previously the safe-message copy
|
|
52
52
|
// matched `api key ... expired` but the failover copy didn't, letting
|
|
53
53
|
// `session expired: api key expired` wrongly fail over past the auth guard.
|
|
54
54
|
const AUTH_FAULT =
|
|
55
|
-
/\b(401|unauthori[sz]ed|invalid[_ -]?api[_ -]?key|api key.*(?:invalid|expired|missing)|authentication failed|invalid bearer)\b/i
|
|
55
|
+
/\b(401|403|unauthori[sz]ed|forbidden|access denied|invalid[_ -]?api[_ -]?key|api key.*(?:invalid|expired|missing)|(?:access|session)[_ -]?token(?:(?:[_ -]+)(?:has|is))?[_ -]+expired|authentication(?: failed|[_ -]?error)|invalid bearer)\b/i
|
|
56
56
|
|
|
57
57
|
// Each entry pairs a narrow matcher against the raw provider text with the
|
|
58
58
|
// canonical, leak-free sentence shown in channels. Matchers are intentionally
|
|
@@ -120,6 +120,11 @@ const NON_FAILOVER_FAULT = new RegExp(
|
|
|
120
120
|
'i',
|
|
121
121
|
)
|
|
122
122
|
|
|
123
|
+
// Context-window exhaustion belongs to the SDK compaction/error path, never
|
|
124
|
+
// transport recovery. Keep this to provider protocol forms rather than matching
|
|
125
|
+
// natural-language user text.
|
|
126
|
+
const CONTEXT_OVERFLOW = /\bcontext[_ -]?length[_ -]?exceeded\b/i
|
|
127
|
+
|
|
123
128
|
export function isThrottleOrOverload(raw: string): boolean {
|
|
124
129
|
if (NON_FAILOVER_FAULT.test(raw)) return false
|
|
125
130
|
return THROTTLE_OR_OVERLOAD.test(raw)
|
|
@@ -133,6 +138,7 @@ export function isThrottleOrOverload(raw: string): boolean {
|
|
|
133
138
|
// Account-wide faults (billing/quota/auth) are excluded up front — a different
|
|
134
139
|
// ref shares the same account problem, so switching can't help.
|
|
135
140
|
export function isFailoverWorthy(raw: string): boolean {
|
|
141
|
+
if (CONTEXT_OVERFLOW.test(raw)) return false
|
|
136
142
|
if (NON_FAILOVER_FAULT.test(raw)) return false
|
|
137
143
|
return isThrottleOrOverload(raw) || OBSERVER_TIMEOUT.test(raw) || TRANSPORT_FAILURE.test(raw)
|
|
138
144
|
}
|
|
@@ -157,6 +163,7 @@ const NETWORK_OR_5XX =
|
|
|
157
163
|
// does NOT match context-overflow: that stays on the SDK compaction path and must
|
|
158
164
|
// never be treated as a retryable provider failure.
|
|
159
165
|
export function isRetryableSameRef(raw: string): boolean {
|
|
166
|
+
if (CONTEXT_OVERFLOW.test(raw)) return false
|
|
160
167
|
if (NON_FAILOVER_FAULT.test(raw)) return false
|
|
161
168
|
if (isThrottleOrOverload(raw)) return false
|
|
162
169
|
return TRANSPORT_FAILURE.test(raw) || OBSERVER_TIMEOUT.test(raw) || NETWORK_OR_5XX.test(raw)
|