typeclaw 0.45.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +3 -2
- package/src/agent/git-nudge.ts +2 -1
- package/src/agent/index.ts +67 -25
- package/src/agent/live-subagents.ts +18 -0
- package/src/agent/loop-guard.ts +208 -10
- package/src/agent/multimodal/index.ts +1 -1
- package/src/agent/multimodal/look-at.ts +78 -44
- package/src/agent/multimodal/looker.ts +151 -39
- package/src/agent/network/response-body.ts +26 -0
- package/src/agent/network/safe-http.ts +198 -0
- package/src/agent/plugin-tools.ts +438 -162
- package/src/agent/provider-error.ts +62 -4
- package/src/agent/restart/index.ts +61 -40
- package/src/agent/restart-handoff/index.ts +73 -4
- package/src/agent/retry-same-ref.ts +66 -0
- package/src/agent/reviewer-bash-policy.ts +42 -1
- package/src/agent/session-origin.ts +2 -0
- package/src/agent/subagent-drain.ts +117 -7
- package/src/agent/subagents.ts +77 -18
- package/src/agent/throttle-circuit.ts +25 -5
- package/src/agent/tool-error-remediation.ts +72 -0
- package/src/agent/tool-file-safety.ts +1050 -0
- package/src/agent/tools/channel-fetch-attachment.ts +10 -3
- package/src/agent/tools/channel-reply.ts +15 -1
- package/src/agent/tools/channel-send.ts +17 -1
- package/src/agent/tools/ddg.ts +16 -2
- package/src/agent/tools/post-github-review.ts +199 -0
- package/src/agent/tools/spawn-subagent.ts +21 -18
- package/src/agent/tools/webfetch/fetch.ts +143 -183
- package/src/agent/tools/webfetch/tool.ts +2 -3
- package/src/agent/tools/websearch.ts +23 -2
- package/src/agent/tools-without-local-file-operands.ts +27 -0
- package/src/agent/turn-runner.ts +109 -15
- package/src/bundled-plugins/backup/index.ts +2 -1
- package/src/bundled-plugins/backup/runner.ts +2 -1
- package/src/bundled-plugins/doc-render/render.ts +93 -12
- package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
- package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
- package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
- package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
- package/src/bundled-plugins/memory/README.md +23 -11
- package/src/bundled-plugins/memory/append-tool.ts +15 -8
- package/src/bundled-plugins/memory/citations.ts +22 -9
- package/src/bundled-plugins/memory/dreaming.ts +13 -8
- package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
- package/src/bundled-plugins/memory/index.ts +0 -4
- package/src/bundled-plugins/memory/load-memory.ts +8 -3
- package/src/bundled-plugins/memory/provenance-index.ts +717 -0
- package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
- package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
- package/src/bundled-plugins/memory/search-tool.ts +163 -60
- package/src/bundled-plugins/memory/stream-events.ts +2 -0
- package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
- package/src/bundled-plugins/researcher/write-report.ts +6 -3
- package/src/bundled-plugins/reviewer/index.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
- package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
- package/src/bundled-plugins/scout/scout.ts +8 -0
- package/src/bundled-plugins/security/index.ts +4 -4
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
- package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
- package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
- package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
- package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
- package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
- package/src/channels/adapters/discord-bot.ts +91 -10
- package/src/channels/adapters/discord-channel-resolver.ts +91 -23
- package/src/channels/adapters/discord-id.ts +4 -0
- package/src/channels/adapters/discord-resolver-cache.ts +41 -0
- package/src/channels/adapters/discord.ts +57 -7
- package/src/channels/adapters/github/auth-app.ts +41 -12
- package/src/channels/adapters/github/index.ts +23 -11
- package/src/channels/adapters/github/review-submitter.ts +302 -0
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
- package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
- package/src/channels/adapters/kakaotalk-typing.ts +127 -0
- package/src/channels/adapters/kakaotalk.ts +19 -0
- package/src/channels/adapters/slack-attachment-download.ts +71 -0
- package/src/channels/adapters/slack-bot.ts +19 -8
- package/src/channels/adapters/slack-classify.ts +21 -2
- package/src/channels/adapters/slack.ts +59 -7
- package/src/channels/adapters/telegram-bot.ts +18 -5
- package/src/channels/adapters/webex-bot.ts +8 -3
- package/src/channels/adapters/webex.ts +8 -3
- package/src/channels/fetch-attachment.ts +43 -0
- package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
- package/src/channels/github-token-bridge.ts +10 -3
- package/src/channels/manager.ts +9 -0
- package/src/channels/router.ts +568 -12
- package/src/channels/types.ts +28 -1
- package/src/cli/channel.ts +1 -1
- package/src/cli/init.ts +1 -1
- package/src/cli/model.ts +57 -7
- package/src/compose/stop.ts +17 -5
- package/src/config/config.ts +6 -6
- package/src/config/models-mutation.ts +13 -1
- package/src/config/providers.ts +176 -0
- package/src/container/start.ts +49 -10
- package/src/doctor/checks.ts +3 -1
- package/src/doctor/commit.ts +2 -1
- package/src/doctor/file-ownership.ts +52 -0
- package/src/dreams/git.ts +2 -1
- package/src/git/hookless.ts +5 -0
- package/src/git/reconcile-ignored.ts +18 -5
- package/src/git/secret-history.ts +371 -0
- package/src/git/system-commit.ts +12 -6
- package/src/init/dockerfile.ts +86 -5
- package/src/init/index.ts +17 -5
- package/src/init/models-dev.ts +4 -0
- package/src/init/validate-api-key.ts +2 -0
- package/src/mcp/tools.ts +16 -3
- package/src/permissions/builtins.ts +3 -1
- package/src/plugin/context.ts +2 -0
- package/src/plugin/index.ts +1 -0
- package/src/plugin/manager.ts +4 -0
- package/src/plugin/types.ts +21 -0
- package/src/run/index.ts +40 -0
- package/src/run/llm-fetch-observer.ts +188 -13
- package/src/sandbox/build.ts +37 -15
- package/src/sandbox/canonical-secrets.ts +18 -0
- package/src/sandbox/env-exposure.ts +80 -0
- package/src/sandbox/errors.ts +13 -6
- package/src/sandbox/hidden-paths.ts +102 -44
- package/src/sandbox/index.ts +22 -4
- package/src/sandbox/package-install.ts +3 -27
- package/src/sandbox/policy.ts +11 -25
- package/src/sandbox/privileged-runtime.ts +255 -0
- package/src/sandbox/session-tmp.ts +8 -2
- package/src/sandbox/writable-zones.ts +204 -140
- package/src/secrets/index.ts +8 -0
- package/src/secrets/refresh-provider-oauth.ts +128 -0
- package/src/server/command-runner.ts +48 -4
- package/src/server/index.ts +4 -0
- package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
- package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
- package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
- package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
- package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
- package/src/skills/typeclaw-config/SKILL.md +5 -5
- package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
- package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
- package/src/skills/typeclaw-memory/SKILL.md +9 -3
- package/src/skills/typeclaw-permissions/SKILL.md +19 -15
- package/typeclaw.schema.json +20 -0
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
## Web & research — reads the web like a person
|
|
34
34
|
|
|
35
35
|
- 🔍 **Live web search & fetch** — pull a page as a readable article, a JSON query, a selected slice, a grep, or raw
|
|
36
|
-
-
|
|
36
|
+
- 🛡️ **Rebinding-safe page fetching** — validates every A/AAAA answer on the socket lookup and every redirect hop; private and mixed-address targets fail closed
|
|
37
37
|
- 🌐 **Interactive browser sessions** — drives a browser on live pages, with a dashboard you can step into for logins, 2FA, or CAPTCHA
|
|
38
38
|
|
|
39
39
|
## Security — defense-in-depth for risky actions
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "typeclaw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.46.0",
|
|
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",
|
|
@@ -58,6 +58,7 @@
|
|
|
58
58
|
"jsdom": "^29.0.2",
|
|
59
59
|
"proper-lockfile": "^4.1.2",
|
|
60
60
|
"qrcode": "^1.5.4",
|
|
61
|
+
"tough-cookie": "^6.0.2",
|
|
61
62
|
"turndown": "^7.2.4",
|
|
62
63
|
"zod": "^4.3.6"
|
|
63
64
|
},
|
package/src/agent/git-nudge.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hooklessGitArgs } from '@/git/hookless'
|
|
1
2
|
import { resolveAgentGit } from '@/git/resolve-agent-git'
|
|
2
3
|
|
|
3
4
|
const MAX_LISTED_PATHS = 10
|
|
@@ -71,7 +72,7 @@ const defaultDeps: GitNudgeDeps = {
|
|
|
71
72
|
if (!bun) return null
|
|
72
73
|
try {
|
|
73
74
|
const proc = bun.spawn({
|
|
74
|
-
cmd: ['git', ...gitArgs, 'status', '--porcelain=v1'],
|
|
75
|
+
cmd: ['git', ...hooklessGitArgs([...gitArgs, 'status', '--porcelain=v1'])],
|
|
75
76
|
cwd: agentDir,
|
|
76
77
|
stdout: 'pipe',
|
|
77
78
|
stderr: 'pipe',
|
package/src/agent/index.ts
CHANGED
|
@@ -24,7 +24,7 @@ import { defaultThinkingLevelForRef, isOpenAiFamilyRef, providerForModelRef, typ
|
|
|
24
24
|
import { renderMcpCatalog } from '@/mcp/catalog'
|
|
25
25
|
import type { McpManager } from '@/mcp/manager'
|
|
26
26
|
import { createMcpDispatcherTools, MCP_DISPATCHER_TOOL_NAMES } from '@/mcp/tools'
|
|
27
|
-
import type
|
|
27
|
+
import { noopPermissionService, type PermissionService, type RolesConfig } from '@/permissions'
|
|
28
28
|
import type {
|
|
29
29
|
BuiltinToolRef,
|
|
30
30
|
HookBus,
|
|
@@ -44,7 +44,7 @@ import { renderGitNudge } from './git-nudge'
|
|
|
44
44
|
import type { LiveSubagentRegistry } from './live-subagents'
|
|
45
45
|
import { sanitizeMessagesForLlmReplay } from './llm-replay-sanitizer'
|
|
46
46
|
import { applyModelRuntimeOverrides } from './model-overrides'
|
|
47
|
-
import { createChannelLookAtTool,
|
|
47
|
+
import { createChannelLookAtTool, createLookAtTool } from './multimodal'
|
|
48
48
|
import {
|
|
49
49
|
buildBuiltinPiToolOverrides,
|
|
50
50
|
isPiCodingBuiltinName,
|
|
@@ -80,6 +80,7 @@ import { createChannelReadTool } from './tools/channel-read'
|
|
|
80
80
|
import { createChannelReplyTool } from './tools/channel-reply'
|
|
81
81
|
import { createChannelSendTool } from './tools/channel-send'
|
|
82
82
|
import { createGrantRoleTool } from './tools/grant-role'
|
|
83
|
+
import { createPostGithubReviewTool } from './tools/post-github-review'
|
|
83
84
|
import { createRestartTool } from './tools/restart'
|
|
84
85
|
import { createSkipResponseTool } from './tools/skip-response'
|
|
85
86
|
import { createSpawnSubagentTool, renderPublicSubagentRoster } from './tools/spawn-subagent'
|
|
@@ -252,6 +253,15 @@ export async function createSession(options: CreateSessionOptions = {}): Promise
|
|
|
252
253
|
return session
|
|
253
254
|
}
|
|
254
255
|
|
|
256
|
+
export function attachLoopGuardTurnTracking(
|
|
257
|
+
agent: { subscribe: (listener: (event: unknown) => void) => () => void },
|
|
258
|
+
onTurnStart: () => void,
|
|
259
|
+
): () => void {
|
|
260
|
+
return agent.subscribe((event: unknown) => {
|
|
261
|
+
if ((event as { type?: string }).type === 'turn_start') onTurnStart()
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
|
|
255
265
|
export async function createSessionWithDispose(options: CreateSessionOptions = {}): Promise<CreateSessionResult> {
|
|
256
266
|
const resolved = resolveProfile(getConfig().models, options.profile)
|
|
257
267
|
// Unknown profiles silently fall back to `default`. The fallback is by design
|
|
@@ -301,6 +311,8 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
301
311
|
// plugin-tools.ts for why aborting (not throwing) is what stops the loop.
|
|
302
312
|
const abortHolder: { abort?: (reason?: string) => void; reason?: string } = {}
|
|
303
313
|
const getAbort: () => ((reason?: string) => void) | undefined = () => abortHolder.abort
|
|
314
|
+
let loopGuardTurnId = 0
|
|
315
|
+
const getLoopGuardTurn = () => loopGuardTurnId
|
|
304
316
|
|
|
305
317
|
// Subagent built-in tool refs resolve to `ToolDefinition`s (see
|
|
306
318
|
// plugin-tools.ts). Their NAMES narrow the session via `tools:`; their wrapped
|
|
@@ -312,8 +324,15 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
312
324
|
const subagentBuiltinNames = resolvedSubagentBuiltins.map((t) => t.name)
|
|
313
325
|
const subagentTypeclawToolDefinitions = resolvedSubagentBuiltins.filter((t) => !isPiCodingBuiltinName(t.name))
|
|
314
326
|
const pluginCustomTools = options.pluginSubagent
|
|
315
|
-
? wrapSubagentCustomTools(
|
|
316
|
-
|
|
327
|
+
? wrapSubagentCustomTools(
|
|
328
|
+
options.pluginSubagent,
|
|
329
|
+
options.plugins,
|
|
330
|
+
getOrigin,
|
|
331
|
+
getAbort,
|
|
332
|
+
getLoopGuardTurn,
|
|
333
|
+
options.permissions,
|
|
334
|
+
)
|
|
335
|
+
: wrapRegistryTools(options.plugins, getOrigin, getAbort, getLoopGuardTurn, options.permissions)
|
|
317
336
|
|
|
318
337
|
// Per-run budget state for the tool-result byte ceiling. Allocated once per
|
|
319
338
|
// session creation and threaded into every wrapped tool so they share the
|
|
@@ -387,7 +406,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
387
406
|
: [
|
|
388
407
|
webSearchTool,
|
|
389
408
|
webFetchTool,
|
|
390
|
-
|
|
409
|
+
createLookAtTool(options.permissions),
|
|
391
410
|
...(options.mcpManager ? buildMcpDispatcherToolDefinitions(options.mcpManager) : []),
|
|
392
411
|
...(options.reloadRegistry ? [createReloadTool({ registry: options.reloadRegistry })] : []),
|
|
393
412
|
...(options.stream ? [createStreamSnapshotTool({ stream: options.stream })] : []),
|
|
@@ -434,7 +453,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
434
453
|
// unwrapped copies are never the active implementation. Built unconditionally
|
|
435
454
|
// — the sandbox and bash policy are security behavior independent of whether
|
|
436
455
|
// any plugin registered a tool hook, so gating on hooks would leave an
|
|
437
|
-
//
|
|
456
|
+
// unwrapped bash path. `wrapBuiltinToolDefinition` no-ops the optional
|
|
438
457
|
// stages (plugin hooks, permissions, bashPolicy) when they are absent.
|
|
439
458
|
const builtinPiToolOverrides = buildBuiltinPiToolOverrides({
|
|
440
459
|
agentDir: options.plugins?.agentDir ?? process.cwd(),
|
|
@@ -442,10 +461,18 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
442
461
|
hooks: options.plugins?.hooks ?? createHookBus(),
|
|
443
462
|
getOrigin,
|
|
444
463
|
getAbort,
|
|
445
|
-
|
|
464
|
+
getLoopGuardTurn,
|
|
465
|
+
permissions: options.permissions ?? noopPermissionService,
|
|
446
466
|
...(options.bashPolicy !== undefined ? { bashPolicy: options.bashPolicy } : {}),
|
|
447
467
|
})
|
|
448
|
-
const wrappedCustomSystemTools = wrapSystemTools(customSystemTools,
|
|
468
|
+
const wrappedCustomSystemTools = wrapSystemTools(customSystemTools, {
|
|
469
|
+
agentDir: options.plugins?.agentDir ?? process.cwd(),
|
|
470
|
+
sessionId: options.plugins?.sessionId ?? sessionManager.getSessionId(),
|
|
471
|
+
hooks: options.plugins?.hooks ?? createHookBus(),
|
|
472
|
+
getOrigin,
|
|
473
|
+
getAbort,
|
|
474
|
+
getLoopGuardTurn,
|
|
475
|
+
})
|
|
449
476
|
const customToolsPreBudget = [...wrappedCustomSystemTools, ...pluginCustomTools, ...builtinPiToolOverrides]
|
|
450
477
|
const customTools =
|
|
451
478
|
sessionBudget && sessionBudgetState
|
|
@@ -491,6 +518,9 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
491
518
|
;(session as { setAutoRetryEnabled?: (enabled: boolean) => void }).setAutoRetryEnabled?.(false)
|
|
492
519
|
const getAbortReason = () => abortHolder.reason
|
|
493
520
|
const sessionWithAbortReason = Object.assign(session, { getAbortReason })
|
|
521
|
+
const unsubLoopGuardTurn = attachLoopGuardTurnTracking(session.agent, () => {
|
|
522
|
+
loopGuardTurnId += 1
|
|
523
|
+
})
|
|
494
524
|
|
|
495
525
|
// Layer the replay sanitizer over pi's convertToLlm so a transcript with an
|
|
496
526
|
// orphaned toolResult (e.g. a torn-down restart turn) can't wedge the session
|
|
@@ -524,6 +554,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
524
554
|
const unsubToolNudge = attachToolNotFoundNudge(session, intendedActiveToolNames)
|
|
525
555
|
|
|
526
556
|
const dispose = async () => {
|
|
557
|
+
unsubLoopGuardTurn()
|
|
527
558
|
unsubRestart?.()
|
|
528
559
|
unsubToolNudge()
|
|
529
560
|
if (materializedSkills) await materializedSkills.dispose()
|
|
@@ -704,6 +735,8 @@ export function buildChannelTools(
|
|
|
704
735
|
...(sessionId !== undefined ? { sessionId } : {}),
|
|
705
736
|
}),
|
|
706
737
|
)
|
|
738
|
+
if (origin.adapter === 'github' && sessionId !== undefined)
|
|
739
|
+
tools.push(createPostGithubReviewTool({ router: channelRouter, origin: channelOrigin, sessionId }))
|
|
707
740
|
tools.push(createChannelHistoryTool({ router: channelRouter, origin: channelOrigin }))
|
|
708
741
|
tools.push(createChannelReadTool({ router: channelRouter }))
|
|
709
742
|
tools.push(
|
|
@@ -732,12 +765,13 @@ export function buildChannelTools(
|
|
|
732
765
|
createChannelFetchAttachmentTool({
|
|
733
766
|
router: channelRouter,
|
|
734
767
|
origin: channelOrigin,
|
|
768
|
+
...(agentDir !== undefined ? { agentDir } : {}),
|
|
735
769
|
...(permissions !== undefined && agentDir !== undefined
|
|
736
770
|
? { resolveBaseDir: () => resolveInboxBaseDir(permissions, getOrigin?.() ?? origin, agentDir) }
|
|
737
771
|
: {}),
|
|
738
772
|
}),
|
|
739
773
|
)
|
|
740
|
-
tools.push(createChannelLookAtTool(channelRouter, channelOrigin))
|
|
774
|
+
tools.push(createChannelLookAtTool(channelRouter, channelOrigin, permissions))
|
|
741
775
|
tools.push(createChannelDisengageTool({ router: channelRouter, origin: channelOrigin }))
|
|
742
776
|
if (sessionId !== undefined) {
|
|
743
777
|
tools.push(createSkipResponseTool({ router: channelRouter, sessionId }))
|
|
@@ -863,6 +897,8 @@ function wrapRegistryTools(
|
|
|
863
897
|
plugins: PluginSessionWiring | undefined,
|
|
864
898
|
getOrigin: () => SessionOrigin | undefined,
|
|
865
899
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
900
|
+
getLoopGuardTurn: () => number | undefined,
|
|
901
|
+
permissions: PermissionService | undefined,
|
|
866
902
|
): ToolDefinition[] {
|
|
867
903
|
if (!plugins) return []
|
|
868
904
|
return plugins.registry.tools.map((t: PluginRegisteredTool) =>
|
|
@@ -875,38 +911,42 @@ function wrapRegistryTools(
|
|
|
875
911
|
hooks: plugins.hooks,
|
|
876
912
|
getOrigin,
|
|
877
913
|
getAbort,
|
|
914
|
+
getLoopGuardTurn,
|
|
915
|
+
...(permissions !== undefined ? { permissions } : {}),
|
|
878
916
|
}),
|
|
879
917
|
)
|
|
880
918
|
}
|
|
881
919
|
|
|
882
|
-
function wrapSystemTools(
|
|
920
|
+
export function wrapSystemTools(
|
|
883
921
|
tools: ToolDefinition[],
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
922
|
+
options: {
|
|
923
|
+
agentDir: string
|
|
924
|
+
sessionId: string
|
|
925
|
+
hooks: HookBus
|
|
926
|
+
getOrigin: () => SessionOrigin | undefined
|
|
927
|
+
getAbort: () => ((reason?: string) => void) | undefined
|
|
928
|
+
getLoopGuardTurn?: () => number | undefined
|
|
929
|
+
},
|
|
887
930
|
): ToolDefinition[] {
|
|
888
|
-
if (!hasToolHooks(plugins)) return tools
|
|
889
931
|
return tools.map((tool) =>
|
|
890
932
|
wrapSystemTool(tool, {
|
|
891
|
-
agentDir:
|
|
892
|
-
sessionId:
|
|
893
|
-
hooks:
|
|
894
|
-
getOrigin,
|
|
895
|
-
getAbort,
|
|
933
|
+
agentDir: options.agentDir,
|
|
934
|
+
sessionId: options.sessionId,
|
|
935
|
+
hooks: options.hooks,
|
|
936
|
+
getOrigin: options.getOrigin,
|
|
937
|
+
getAbort: options.getAbort,
|
|
938
|
+
getLoopGuardTurn: options.getLoopGuardTurn,
|
|
896
939
|
}),
|
|
897
940
|
)
|
|
898
941
|
}
|
|
899
942
|
|
|
900
|
-
function
|
|
901
|
-
if (!plugins) return false
|
|
902
|
-
return plugins.hooks.count('tool.before') > 0 || plugins.hooks.count('tool.after') > 0
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
function wrapSubagentCustomTools(
|
|
943
|
+
export function wrapSubagentCustomTools(
|
|
906
944
|
selection: PluginSubagentSelection,
|
|
907
945
|
plugins: PluginSessionWiring | undefined,
|
|
908
946
|
getOrigin: () => SessionOrigin | undefined,
|
|
909
947
|
getAbort: () => ((reason?: string) => void) | undefined,
|
|
948
|
+
getLoopGuardTurn: () => number | undefined,
|
|
949
|
+
permissions: PermissionService | undefined,
|
|
910
950
|
): ToolDefinition[] {
|
|
911
951
|
if (!selection.customTools || !plugins) return []
|
|
912
952
|
const logger = makePluginLogger(selection.pluginName)
|
|
@@ -920,6 +960,8 @@ function wrapSubagentCustomTools(
|
|
|
920
960
|
hooks: plugins.hooks,
|
|
921
961
|
getOrigin,
|
|
922
962
|
getAbort,
|
|
963
|
+
getLoopGuardTurn,
|
|
964
|
+
...(permissions !== undefined ? { permissions } : {}),
|
|
923
965
|
}),
|
|
924
966
|
)
|
|
925
967
|
}
|
|
@@ -143,6 +143,24 @@ export class LiveSubagentRegistry {
|
|
|
143
143
|
entry.status = completion.ok ? 'completed' : 'failed'
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
// First-writer-wins settlement, returning whether THIS caller won. A subagent
|
|
147
|
+
// has two racing settlement producers — its real completion (spawn_subagent's
|
|
148
|
+
// `completion.then`) and the parent drain's timeout ceiling — and both must
|
|
149
|
+
// not overwrite each other's terminal state, or the registry/broadcast would
|
|
150
|
+
// disagree with a reminder already delivered. There is no `await` between the
|
|
151
|
+
// status check and the mutation, so under JS run-to-completion this compare-
|
|
152
|
+
// and-set is atomic: a promise `.then` producer that races in on a later
|
|
153
|
+
// microtask sees `status !== 'running'` and loses. Production settlement paths
|
|
154
|
+
// MUST use this, not the unconditional `recordCompletion` (which stays for
|
|
155
|
+
// tests that seed terminal state directly).
|
|
156
|
+
recordCompletionIfRunning(taskId: string, completion: SubagentCompletion): boolean {
|
|
157
|
+
const entry = this.entries.get(taskId)
|
|
158
|
+
if (entry === undefined || entry.status !== 'running') return false
|
|
159
|
+
entry.completion = completion
|
|
160
|
+
entry.status = completion.ok ? 'completed' : 'failed'
|
|
161
|
+
return true
|
|
162
|
+
}
|
|
163
|
+
|
|
146
164
|
snapshot(taskId: string, now: number = Date.now()): StatusSnapshot | undefined {
|
|
147
165
|
const entry = this.entries.get(taskId)
|
|
148
166
|
if (entry === undefined) return undefined
|
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 {
|