typeclaw 0.42.0 → 0.42.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 +3 -3
- package/src/agent/adaptive-thinking-compat.ts +79 -0
- package/src/agent/index.ts +79 -101
- package/src/agent/plugin-tools.ts +77 -130
- package/src/agent/provider-error.ts +37 -0
- package/src/agent/reload-tool.ts +1 -1
- package/src/agent/subagents.ts +2 -2
- package/src/agent/system-prompt.ts +19 -5
- package/src/agent/tool-result-budget.ts +1 -1
- package/src/agent/tools/stream-snapshot.ts +8 -3
- package/src/bundled-plugins/agent-browser/index.ts +18 -8
- package/src/bundled-plugins/memory/README.md +4 -1
- package/src/bundled-plugins/memory/belief-sentence.ts +50 -0
- package/src/bundled-plugins/memory/dreaming.ts +13 -6
- package/src/bundled-plugins/memory/load-memory.ts +22 -2
- package/src/bundled-plugins/memory/memory-logger.ts +1 -1
- package/src/capabilities/control-plane.ts +24 -0
- package/src/capabilities/index.ts +2 -0
- package/src/capabilities/runtime.ts +30 -0
- package/src/channels/manager.ts +41 -47
- package/src/channels/router.ts +11 -2
- package/src/cli/channel.ts +49 -12
- package/src/cli/hostd.ts +4 -3
- package/src/cli/logs.ts +2 -2
- package/src/cli/restart.ts +5 -3
- package/src/cli/shell.ts +2 -2
- package/src/cli/start.ts +2 -2
- package/src/cli/status.ts +2 -2
- package/src/cli/stop.ts +2 -2
- package/src/compose/restart.ts +4 -3
- package/src/compose/start.ts +2 -2
- package/src/compose/stop.ts +2 -2
- package/src/config/config.ts +10 -1
- package/src/config/providers.ts +61 -9
- package/src/container/controller.ts +104 -0
- package/src/container/index.ts +9 -0
- package/src/init/index.ts +1 -1
- package/src/init/instagram-auth.ts +189 -34
- package/src/inspect/logs-item.ts +2 -2
- package/src/mcp/client.ts +1 -1
- package/src/run/index.ts +21 -9
- package/src/run/{codex-fetch-observer.ts → llm-fetch-observer.ts} +182 -82
- package/src/sandbox/availability.ts +2 -2
- package/src/sandbox/build.ts +1 -1
- package/src/sandbox/policy.ts +2 -2
- package/src/secrets/discord-store.ts +4 -13
- package/src/secrets/instagram-store.ts +4 -13
- package/src/secrets/kakao-store.ts +4 -13
- package/src/secrets/line-store.ts +4 -13
- package/src/secrets/secrets-provider.ts +86 -0
- package/src/secrets/slack-store.ts +4 -13
- package/src/secrets/webex-store.ts +4 -13
- package/src/server/index.ts +2 -2
- package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
- package/src/skills/typeclaw-config/SKILL.md +5 -3
- package/src/skills/typeclaw-plugins/SKILL.md +1 -1
- package/src/stream/broker.ts +4 -3
- package/src/stream/types.ts +1 -0
- package/typeclaw.schema.json +14 -0
|
@@ -1,20 +1,19 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
|
|
4
|
-
import type { AgentTool } from '@mariozechner/pi-agent-core'
|
|
5
4
|
import {
|
|
6
|
-
|
|
5
|
+
createBashToolDefinition as piCreateBashToolDefinition,
|
|
6
|
+
createEditToolDefinition as piCreateEditToolDefinition,
|
|
7
|
+
createFindToolDefinition as piCreateFindToolDefinition,
|
|
8
|
+
createGrepToolDefinition as piCreateGrepToolDefinition,
|
|
9
|
+
createLsToolDefinition as piCreateLsToolDefinition,
|
|
10
|
+
createReadToolDefinition as piCreateReadToolDefinition,
|
|
11
|
+
createWriteToolDefinition as piCreateWriteToolDefinition,
|
|
7
12
|
defineTool as piDefineTool,
|
|
8
|
-
editTool as piEditTool,
|
|
9
|
-
findTool as piFindTool,
|
|
10
|
-
grepTool as piGrepTool,
|
|
11
|
-
lsTool as piLsTool,
|
|
12
|
-
readTool as piReadTool,
|
|
13
|
-
writeTool as piWriteTool,
|
|
14
13
|
} from '@mariozechner/pi-coding-agent'
|
|
15
14
|
import type { BashSpawnContext, ToolDefinition } from '@mariozechner/pi-coding-agent'
|
|
16
|
-
import type { Static, TSchema } from '
|
|
17
|
-
import { Type } from '
|
|
15
|
+
import type { Static, TSchema } from 'typebox'
|
|
16
|
+
import { Type } from 'typebox'
|
|
18
17
|
import { z } from 'zod'
|
|
19
18
|
|
|
20
19
|
import {
|
|
@@ -102,8 +101,6 @@ function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
|
|
|
102
101
|
return { ...context, env: { ...context.env, ...overlay } }
|
|
103
102
|
}
|
|
104
103
|
|
|
105
|
-
const piBashTool = piCreateBashTool(process.cwd(), { spawnHook: bashSpawnHookWithOverlay })
|
|
106
|
-
|
|
107
104
|
const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
|
|
108
105
|
Type.Object(
|
|
109
106
|
{
|
|
@@ -115,31 +112,50 @@ const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
|
|
|
115
112
|
),
|
|
116
113
|
)
|
|
117
114
|
|
|
118
|
-
// pi-coding-agent 0.
|
|
119
|
-
// - `createAgentSession({ tools:
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
//
|
|
115
|
+
// pi-coding-agent 0.73 contract (load-bearing for hook coverage):
|
|
116
|
+
// - `createAgentSession({ tools: string[] })` is a name allowlist: only the
|
|
117
|
+
// listed names stay active, and that allowlist gates BOTH builtins and
|
|
118
|
+
// custom tools (see `allowedToolNames` in pi's `_refreshToolRegistry`).
|
|
119
|
+
// - `noTools: "builtin"` drops pi's read/bash/edit/write from the INITIAL
|
|
120
|
+
// active set; pi still registers its base builtins, so a same-named entry
|
|
121
|
+
// in `customTools` is what overrides the implementation (registry
|
|
122
|
+
// last-write-wins). Passing an explicit `tools:` allowlist plus shipping all
|
|
123
|
+
// seven wrapped builtins is what makes the wrapped versions the only
|
|
124
|
+
// callable ones.
|
|
123
125
|
//
|
|
124
|
-
// Consequence:
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
//
|
|
128
|
-
//
|
|
129
|
-
|
|
130
|
-
// name-filter path); the wrapped customTools just replace the implementation
|
|
131
|
-
// underneath so subagent and channel sessions share the same hook coverage.
|
|
132
|
-
type PiAgentToolName = 'read' | 'bash' | 'edit' | 'write' | 'grep' | 'find' | 'ls'
|
|
126
|
+
// Consequence: every builtin enters as a `ToolDefinition` (pi now exposes
|
|
127
|
+
// `create*ToolDefinition` factories), TypeClaw wraps each one with its hook +
|
|
128
|
+
// guard + sandbox pipeline, and the call site routes them through `customTools`
|
|
129
|
+
// while narrowing via `tools:` names. There is no longer an `AgentTool` vs
|
|
130
|
+
// `ToolDefinition` split.
|
|
131
|
+
type PiBuiltinToolName = 'read' | 'bash' | 'edit' | 'write' | 'grep' | 'find' | 'ls'
|
|
133
132
|
type TypeclawToolName = 'web_search' | 'web_fetch'
|
|
134
133
|
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
134
|
+
const PI_BUILTIN_TOOL_NAMES: readonly PiBuiltinToolName[] = ['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls']
|
|
135
|
+
|
|
136
|
+
// pi builtins resolve relative paths (and, for trusted/owner bash, the spawn
|
|
137
|
+
// cwd) against the cwd baked in at factory time, so the definitions are built
|
|
138
|
+
// per session from the session's agentDir rather than the module-load
|
|
139
|
+
// process.cwd() — otherwise a session whose agentDir differs from the import-
|
|
140
|
+
// time cwd would read/write in the wrong tree. bash keeps the spawnHook that
|
|
141
|
+
// threads the internal env overlay to the (non-sandboxed) spawn.
|
|
142
|
+
function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): ToolDefinition<any, any, any> {
|
|
143
|
+
switch (name) {
|
|
144
|
+
case 'read':
|
|
145
|
+
return piCreateReadToolDefinition(cwd)
|
|
146
|
+
case 'bash':
|
|
147
|
+
return piCreateBashToolDefinition(cwd, { spawnHook: bashSpawnHookWithOverlay })
|
|
148
|
+
case 'edit':
|
|
149
|
+
return piCreateEditToolDefinition(cwd)
|
|
150
|
+
case 'write':
|
|
151
|
+
return piCreateWriteToolDefinition(cwd)
|
|
152
|
+
case 'grep':
|
|
153
|
+
return piCreateGrepToolDefinition(cwd)
|
|
154
|
+
case 'find':
|
|
155
|
+
return piCreateFindToolDefinition(cwd)
|
|
156
|
+
case 'ls':
|
|
157
|
+
return piCreateLsToolDefinition(cwd)
|
|
158
|
+
}
|
|
143
159
|
}
|
|
144
160
|
|
|
145
161
|
const TYPECLAW_TOOL_DEFINITION_MAP: Record<TypeclawToolName, ToolDefinition<any, any, any>> = {
|
|
@@ -147,33 +163,25 @@ const TYPECLAW_TOOL_DEFINITION_MAP: Record<TypeclawToolName, ToolDefinition<any,
|
|
|
147
163
|
web_fetch: webFetchTool,
|
|
148
164
|
}
|
|
149
165
|
|
|
150
|
-
function
|
|
151
|
-
return
|
|
166
|
+
function isPiBuiltinToolName(name: string): name is PiBuiltinToolName {
|
|
167
|
+
return (PI_BUILTIN_TOOL_NAMES as readonly string[]).includes(name)
|
|
152
168
|
}
|
|
153
169
|
|
|
154
|
-
function
|
|
155
|
-
return name
|
|
170
|
+
export function isPiCodingBuiltinName(name: string): boolean {
|
|
171
|
+
return isPiBuiltinToolName(name)
|
|
156
172
|
}
|
|
157
173
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
toolDefinitions: ToolDefinition<any, any, any>[]
|
|
174
|
+
function isTypeclawToolName(name: string): name is TypeclawToolName {
|
|
175
|
+
return name in TYPECLAW_TOOL_DEFINITION_MAP
|
|
161
176
|
}
|
|
162
177
|
|
|
163
|
-
export function resolveBuiltinToolRefs(refs: BuiltinToolRef[]):
|
|
164
|
-
|
|
165
|
-
const toolDefinitions: ToolDefinition<any, any, any>[] = []
|
|
166
|
-
for (const ref of refs) {
|
|
178
|
+
export function resolveBuiltinToolRefs(refs: BuiltinToolRef[], cwd: string): ToolDefinition<any, any, any>[] {
|
|
179
|
+
return refs.map((ref) => {
|
|
167
180
|
const name = ref.__builtinTool
|
|
168
|
-
if (
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
} else {
|
|
173
|
-
throw new Error(`unknown built-in tool ref: ${name}`)
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
return { agentTools, toolDefinitions }
|
|
181
|
+
if (isPiBuiltinToolName(name)) return createPiBuiltinToolDefinition(name, cwd)
|
|
182
|
+
if (isTypeclawToolName(name)) return TYPECLAW_TOOL_DEFINITION_MAP[name]
|
|
183
|
+
throw new Error(`unknown built-in tool ref: ${name}`)
|
|
184
|
+
})
|
|
177
185
|
}
|
|
178
186
|
|
|
179
187
|
export type WrapToolOptions = {
|
|
@@ -363,81 +371,20 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
|
|
|
363
371
|
})
|
|
364
372
|
}
|
|
365
373
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
const mutableArgs = params as Record<string, unknown>
|
|
375
|
-
const liveOrigin = opts.getOrigin?.()
|
|
376
|
-
const blockResult = await opts.hooks.runToolBefore({
|
|
377
|
-
tool: tool.name,
|
|
378
|
-
sessionId: opts.sessionId,
|
|
379
|
-
callId: toolCallId,
|
|
380
|
-
args: mutableArgs,
|
|
381
|
-
...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
|
|
382
|
-
})
|
|
383
|
-
if (blockResult !== undefined) {
|
|
384
|
-
throw new Error(`blocked: ${blockResult.reason}`)
|
|
385
|
-
}
|
|
386
|
-
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
|
|
387
|
-
if (loopGate.blockNow) {
|
|
388
|
-
fireLoopAbort(opts.getAbort, 'loop_guard:block')
|
|
389
|
-
throw new Error(loopGate.message)
|
|
390
|
-
}
|
|
391
|
-
const guardResult = await runFinalWriteGuards({
|
|
392
|
-
tool: tool.name,
|
|
393
|
-
args: mutableArgs,
|
|
394
|
-
agentDir: opts.agentDir,
|
|
395
|
-
})
|
|
396
|
-
if (guardResult !== undefined) {
|
|
397
|
-
throw new Error(`blocked: ${guardResult.reason}`)
|
|
398
|
-
}
|
|
399
|
-
const readGuardResult = runFinalReadGuards({ tool: tool.name, args: mutableArgs })
|
|
400
|
-
if (readGuardResult !== undefined) {
|
|
401
|
-
throw new Error(`blocked: ${readGuardResult.reason}`)
|
|
402
|
-
}
|
|
403
|
-
stripGuardAcknowledgements(mutableArgs)
|
|
404
|
-
|
|
405
|
-
const result = await tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate)
|
|
406
|
-
const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
|
|
407
|
-
if ('deferredBlock' in resolved) {
|
|
408
|
-
fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
|
|
409
|
-
throw new Error(resolved.deferredBlock)
|
|
410
|
-
}
|
|
411
|
-
const hookResult = resolved.result
|
|
412
|
-
await opts.hooks.runToolAfter({
|
|
413
|
-
tool: tool.name,
|
|
414
|
-
sessionId: opts.sessionId,
|
|
415
|
-
callId: toolCallId,
|
|
416
|
-
result: hookResult,
|
|
417
|
-
})
|
|
418
|
-
return {
|
|
419
|
-
content: hookResult.content as ContentPart[],
|
|
420
|
-
details: hookResult.details as TDetails,
|
|
421
|
-
}
|
|
422
|
-
},
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
// Wraps a pi-coding-agent AgentTool into a ToolDefinition so it can ride in
|
|
427
|
-
// `customTools` and override pi's same-named builtin (see top-of-file contract
|
|
428
|
-
// block). The hook + guard pipeline matches `wrapSystemAgentTool`; only the
|
|
429
|
-
// input/output shape differs.
|
|
430
|
-
export function wrapAgentToolAsCustomToolDefinition<TParams extends TSchema, TDetails = unknown>(
|
|
431
|
-
tool: AgentTool<TParams, TDetails>,
|
|
374
|
+
// Wraps a pi builtin `ToolDefinition` (read/bash/edit/write/grep/find/ls) with
|
|
375
|
+
// TypeClaw's full pipeline — hooks, loop guard, write/read guards, per-subagent
|
|
376
|
+
// bash policy, bwrap sandbox, /tmp redirect, and the internal bash env overlay —
|
|
377
|
+
// then ships it through `customTools`. `noTools: "builtin"` at the call site
|
|
378
|
+
// disables pi's own unwrapped copies, so this wrapped definition is the ONLY
|
|
379
|
+
// registered implementation of each builtin name.
|
|
380
|
+
export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = unknown, TState = any>(
|
|
381
|
+
tool: ToolDefinition<TParams, TDetails, TState>,
|
|
432
382
|
opts: WrapSystemToolOptions,
|
|
433
|
-
): ToolDefinition<TParams, TDetails> {
|
|
383
|
+
): ToolDefinition<TParams, TDetails, TState> {
|
|
434
384
|
return piDefineTool({
|
|
435
|
-
|
|
436
|
-
label: tool.label,
|
|
437
|
-
description: tool.description,
|
|
385
|
+
...tool,
|
|
438
386
|
parameters: withGuardAcknowledgements(tool.name, tool.parameters),
|
|
439
|
-
|
|
440
|
-
async execute(toolCallId, params, signal, onUpdate) {
|
|
387
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
441
388
|
const mutableArgs = params as Record<string, unknown>
|
|
442
389
|
const liveOrigin = opts.getOrigin?.()
|
|
443
390
|
// Defense-in-depth: strip any pre-existing internal env-overlay key
|
|
@@ -499,7 +446,7 @@ export function wrapAgentToolAsCustomToolDefinition<TParams extends TSchema, TDe
|
|
|
499
446
|
let rawResult: ToolResult
|
|
500
447
|
try {
|
|
501
448
|
rawResult = await bashEnvStore.run(bashEnvOverlay, () =>
|
|
502
|
-
tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate),
|
|
449
|
+
tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx),
|
|
503
450
|
)
|
|
504
451
|
} catch (error) {
|
|
505
452
|
// A throwing tool (pi's bash rejects on non-zero exit) must still run
|
|
@@ -549,12 +496,12 @@ async function runToolAfterSafely(
|
|
|
549
496
|
}
|
|
550
497
|
}
|
|
551
498
|
|
|
552
|
-
export function
|
|
553
|
-
return
|
|
499
|
+
export function defaultBuiltinPiToolDefinitions(cwd: string): ToolDefinition<any, any, any>[] {
|
|
500
|
+
return PI_BUILTIN_TOOL_NAMES.map((name) => createPiBuiltinToolDefinition(name, cwd))
|
|
554
501
|
}
|
|
555
502
|
|
|
556
503
|
export function buildBuiltinPiToolOverrides(opts: WrapSystemToolOptions): ToolDefinition<any, any>[] {
|
|
557
|
-
return
|
|
504
|
+
return defaultBuiltinPiToolDefinitions(opts.agentDir).map((tool) => wrapBuiltinToolDefinition(tool, opts))
|
|
558
505
|
}
|
|
559
506
|
|
|
560
507
|
// Rewrites mutableArgs.command in place so the bash builtin runs inside bwrap
|
|
@@ -26,6 +26,13 @@ export type DetectedProviderError = {
|
|
|
26
26
|
|
|
27
27
|
const GENERIC_SAFE_NOTICE = 'The upstream LLM provider failed. Operators can check `typeclaw logs` for details.'
|
|
28
28
|
|
|
29
|
+
// The fetch observer (`llm-fetch-observer`) aborts a stalled provider stream
|
|
30
|
+
// with a message ending in this marker (TTFB / idle / overall deadline). Such a
|
|
31
|
+
// stall is a hard throw, not a `stopReason: 'error'` soft error, so it never
|
|
32
|
+
// reaches `detectProviderError`; the marker lets the hard-throw path recognize
|
|
33
|
+
// and surface it. The literal is the system's own token — English by design.
|
|
34
|
+
const OBSERVER_TIMEOUT = /\(typeclaw observer timeout\)/i
|
|
35
|
+
|
|
29
36
|
// Each entry pairs a narrow matcher against the raw provider text with the
|
|
30
37
|
// canonical, leak-free sentence shown in channels. Matchers are intentionally
|
|
31
38
|
// specific: a miss falls through to GENERIC_SAFE_NOTICE rather than echoing raw
|
|
@@ -60,6 +67,10 @@ const SAFE_CLASSES: ReadonlyArray<{ match: RegExp; safe: string }> = [
|
|
|
60
67
|
match: /\b(billing|quota|insufficient.*(credit|fund|balance)|payment|account is not active)\b/i,
|
|
61
68
|
safe: 'The upstream LLM provider rejected the request for a billing/quota reason. Operators can check `typeclaw logs` for details.',
|
|
62
69
|
},
|
|
70
|
+
{
|
|
71
|
+
match: OBSERVER_TIMEOUT,
|
|
72
|
+
safe: 'The upstream LLM provider stopped responding and the request timed out. Try again shortly.',
|
|
73
|
+
},
|
|
63
74
|
]
|
|
64
75
|
|
|
65
76
|
function toSafeMessage(raw: string): string {
|
|
@@ -90,6 +101,17 @@ export function isThrottleOrOverload(raw: string): boolean {
|
|
|
90
101
|
return THROTTLE_OR_OVERLOAD.test(raw)
|
|
91
102
|
}
|
|
92
103
|
|
|
104
|
+
// Failover predicate for turn-drivers' `shouldFailover`: rotate to the next model
|
|
105
|
+
// ref on a transient capacity signal (throttle/overload) OR an observer stall
|
|
106
|
+
// timeout. A stall — the provider accepted the stream but stopped sending bytes —
|
|
107
|
+
// is as transient as an overload and another ref may well succeed, so it must
|
|
108
|
+
// fail OVER before the caller surfaces a failure notice. Account-wide faults
|
|
109
|
+
// (billing/quota/auth) still return false via `isThrottleOrOverload` — a
|
|
110
|
+
// different ref shares the same account problem.
|
|
111
|
+
export function isFailoverWorthy(raw: string): boolean {
|
|
112
|
+
return isThrottleOrOverload(raw) || OBSERVER_TIMEOUT.test(raw)
|
|
113
|
+
}
|
|
114
|
+
|
|
93
115
|
export function detectProviderError(message: unknown): DetectedProviderError | null {
|
|
94
116
|
if (typeof message !== 'object' || message === null) return null
|
|
95
117
|
const m = message as { role?: unknown; stopReason?: unknown; errorMessage?: unknown }
|
|
@@ -102,6 +124,21 @@ export function detectProviderError(message: unknown): DetectedProviderError | n
|
|
|
102
124
|
return { message: text, safeMessage: toSafeMessage(text) }
|
|
103
125
|
}
|
|
104
126
|
|
|
127
|
+
// Classifies a HARD-thrown error (an exception out of `session.prompt()`, after
|
|
128
|
+
// model fallback is exhausted) into a user-facing notice — the throw counterpart
|
|
129
|
+
// to `detectProviderError`'s soft-error path. Returns `null` for errors that are
|
|
130
|
+
// NOT an operator-actionable provider failure (internal bugs, network blips),
|
|
131
|
+
// so the caller stays silent-with-log rather than spamming channels. The three
|
|
132
|
+
// recognized classes are: failover-worthy throttle/overload, account-wide faults
|
|
133
|
+
// (billing/quota/auth) that must surface, and observer stall timeouts.
|
|
134
|
+
export function detectHardProviderError(err: unknown): DetectedProviderError | null {
|
|
135
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
136
|
+
const isProviderFailure =
|
|
137
|
+
isThrottleOrOverload(message) || NON_FAILOVER_FAULT.test(message) || OBSERVER_TIMEOUT.test(message)
|
|
138
|
+
if (!isProviderFailure) return null
|
|
139
|
+
return { message, safeMessage: toSafeMessage(message) }
|
|
140
|
+
}
|
|
141
|
+
|
|
105
142
|
export type ProviderErrorListener = (error: DetectedProviderError) => void
|
|
106
143
|
export type Unsubscribe = () => void
|
|
107
144
|
|
package/src/agent/reload-tool.ts
CHANGED
package/src/agent/subagents.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { applyTurnThinkingLevel } from './attention-escalation'
|
|
|
10
10
|
import { type AgentSession, createSession, type PluginSessionWiring } from './index'
|
|
11
11
|
import { resolveFallbackChain } from './model-fallback'
|
|
12
12
|
import { applyModelRuntimeOverrides } from './model-overrides'
|
|
13
|
-
import {
|
|
13
|
+
import { isFailoverWorthy, subscribeProviderErrors } from './provider-error'
|
|
14
14
|
import type { SubagentBashPolicy } from './reviewer-bash-policy'
|
|
15
15
|
import type { SessionOrigin } from './session-origin'
|
|
16
16
|
import {
|
|
@@ -349,7 +349,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
|
|
|
349
349
|
text: turnText,
|
|
350
350
|
skipProviderErrorSubscription: true,
|
|
351
351
|
detectSoftErrorFromLeaf: true,
|
|
352
|
-
shouldFailover: (err) =>
|
|
352
|
+
shouldFailover: (err) => isFailoverWorthy(err.message),
|
|
353
353
|
setModelForRef: async (ref) => {
|
|
354
354
|
await session.setModel(applyModelRuntimeOverrides(resolveModel(ref), ref))
|
|
355
355
|
activeModelRef = ref
|
|
@@ -11,10 +11,15 @@ const PACKAGE_JSON_INSTALL_RULE =
|
|
|
11
11
|
// by the no-registry path (back-compat callers, the debug dumper); production
|
|
12
12
|
// full-mode sessions pass the real registry-rendered roster via
|
|
13
13
|
// `composeSystemPrompt`'s `subagentRoster` field.
|
|
14
|
-
export function buildDefaultSystemPrompt(subagentRoster: string): string {
|
|
15
|
-
|
|
14
|
+
export function buildDefaultSystemPrompt(subagentRoster: string, branding = true): string {
|
|
15
|
+
const opening = branding
|
|
16
|
+
? `You are a general-purpose AI agent running inside TypeClaw.
|
|
16
17
|
|
|
17
|
-
TypeClaw is domain-agnostic: \`IDENTITY.md\` defines your role, \`SOUL.md\` your voice, and \`AGENTS.md\` your operating manual. This prompt describes only the runtime
|
|
18
|
+
TypeClaw is domain-agnostic: \`IDENTITY.md\` defines your role, \`SOUL.md\` your voice, and \`AGENTS.md\` your operating manual. This prompt describes only the runtime.`
|
|
19
|
+
: `You are a general-purpose AI agent.
|
|
20
|
+
|
|
21
|
+
Your runtime is domain-agnostic: \`IDENTITY.md\` defines your role, \`SOUL.md\` your voice, and \`AGENTS.md\` your operating manual. This prompt describes only the runtime.`
|
|
22
|
+
return `${opening}
|
|
18
23
|
|
|
19
24
|
## Your agent folder
|
|
20
25
|
|
|
@@ -93,7 +98,7 @@ Use tmux only for work that belongs in your session. Delegate self-contained lon
|
|
|
93
98
|
|
|
94
99
|
## Version control
|
|
95
100
|
|
|
96
|
-
Your agent folder is a git repository, but **it is your own private backup repo — not a software project you develop.** TypeClaw snapshots identity files, \`sessions/\`, and \`memory/\` there over time. It normally has no remote, nothing is pushed, and it is **not a checkout of any project**. Commits here save your state, not a codebase contribution.
|
|
101
|
+
Your agent folder is a git repository, but **it is your own private backup repo — not a software project you develop.** ${branding ? 'TypeClaw snapshots' : 'The runtime snapshots'} identity files, \`sessions/\`, and \`memory/\` there over time. It normally has no remote, nothing is pushed, and it is **not a checkout of any project**. Commits here save your state, not a codebase contribution.
|
|
97
102
|
|
|
98
103
|
For project work (bug, feature, PR), clone the project repo into \`/tmp/<repo>\`, work there, and open the PR from that clone with \`gh\`. Never \`git init\`, add a remote, or push your agent folder as the project. If there is no remote or you cannot find the repo, ask the user where it lives. Your agent folder is where you live; the clone is where you work.
|
|
99
104
|
|
|
@@ -262,7 +267,9 @@ export function renderTurnRoleAnchor(role: string): string | undefined {
|
|
|
262
267
|
// The full DEFAULT_SYSTEM_PROMPT remains the right choice for TUI + channel
|
|
263
268
|
// sessions because there IS a human reading the output, the agent IS expected
|
|
264
269
|
// to maintain its agent folder over time, and conversational register matters.
|
|
265
|
-
export
|
|
270
|
+
export function buildSlimSystemPrompt(branding = true): string {
|
|
271
|
+
const opening = branding ? 'You are an AI agent running inside TypeClaw.' : 'You are an AI agent.'
|
|
272
|
+
return `${opening}
|
|
266
273
|
|
|
267
274
|
Never echo secrets from \`secrets.json\` or \`.env\`, or any credential you see in the environment. Never include them in tool calls, logs, or commit messages.
|
|
268
275
|
|
|
@@ -277,3 +284,10 @@ Your free-write zone is \`workspace/\`. Do not create files at the root of the a
|
|
|
277
284
|
The agent folder is a private backup repo with no remote, not a project checkout. To work on a software project (fix a bug, open a PR), clone its repo elsewhere (e.g. \`/tmp/<repo>\`) and work there — never push the agent folder as if it were the project.
|
|
278
285
|
|
|
279
286
|
See the session-origin block below for what kind of session this is and what's expected of you.`
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Back-compat constant: the slim prompt with branding on. Retained because
|
|
290
|
+
// tests assert `prompt.startsWith(SLIM_SYSTEM_PROMPT)` on the default path;
|
|
291
|
+
// production slim composition substitutes the branding flag via
|
|
292
|
+
// `buildSlimSystemPrompt`.
|
|
293
|
+
export const SLIM_SYSTEM_PROMPT = buildSlimSystemPrompt()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { AgentTool } from '@mariozechner/pi-agent-core'
|
|
2
2
|
import type { ToolDefinition } from '@mariozechner/pi-coding-agent'
|
|
3
|
-
import type { TSchema } from '
|
|
3
|
+
import type { TSchema } from 'typebox'
|
|
4
4
|
|
|
5
5
|
// Subagents that read large files (memory-logger and dreaming each read parent
|
|
6
6
|
// session transcripts that can run hundreds of KB) are vulnerable to a class
|
|
@@ -13,9 +13,13 @@ type TargetKind = (typeof TARGET_KINDS)[number]
|
|
|
13
13
|
|
|
14
14
|
export type CreateStreamSnapshotToolOptions = {
|
|
15
15
|
stream: Stream
|
|
16
|
+
// Clock source for the `since_ms_ago` cutoff. Defaults to the real clock;
|
|
17
|
+
// injectable so tests can pin `now` and assert the time filter without
|
|
18
|
+
// depending on wall-clock timing between publish and execute.
|
|
19
|
+
now?: () => number
|
|
16
20
|
}
|
|
17
21
|
|
|
18
|
-
export function createStreamSnapshotTool({ stream }: CreateStreamSnapshotToolOptions) {
|
|
22
|
+
export function createStreamSnapshotTool({ stream, now = Date.now }: CreateStreamSnapshotToolOptions) {
|
|
19
23
|
return defineTool({
|
|
20
24
|
name: 'stream_snapshot',
|
|
21
25
|
label: 'Stream Snapshot',
|
|
@@ -54,7 +58,7 @@ export function createStreamSnapshotTool({ stream }: CreateStreamSnapshotToolOpt
|
|
|
54
58
|
|
|
55
59
|
async execute(_toolCallId, params) {
|
|
56
60
|
const limit = clampLimit(params.limit)
|
|
57
|
-
const filter = buildFilter(params.target_kind, params.target_id, params.since_ms_ago, limit)
|
|
61
|
+
const filter = buildFilter(params.target_kind, params.target_id, params.since_ms_ago, limit, now)
|
|
58
62
|
const events = stream.scan(filter)
|
|
59
63
|
return formatResult(events, params)
|
|
60
64
|
},
|
|
@@ -71,10 +75,11 @@ function buildFilter(
|
|
|
71
75
|
id: string | undefined,
|
|
72
76
|
sinceMsAgo: number | undefined,
|
|
73
77
|
limit: number,
|
|
78
|
+
now: () => number,
|
|
74
79
|
): ScanFilter {
|
|
75
80
|
const filter: ScanFilter = { limit }
|
|
76
81
|
if (kind !== undefined) filter.target = buildTargetFilter(kind, id)
|
|
77
|
-
if (sinceMsAgo !== undefined) filter.sinceTs =
|
|
82
|
+
if (sinceMsAgo !== undefined) filter.sinceTs = now() - sinceMsAgo
|
|
78
83
|
return filter
|
|
79
84
|
}
|
|
80
85
|
|
|
@@ -9,8 +9,17 @@ type SafeResult = InstallShimResult | { kind: 'error'; binPath: string; error: u
|
|
|
9
9
|
|
|
10
10
|
// Documented in skills/agent-browser/SKILL.md so the agent can discover which
|
|
11
11
|
// host port the reserved dashboard forward actually bound. Moving or renaming
|
|
12
|
-
// this path requires updating the skill in lockstep.
|
|
13
|
-
|
|
12
|
+
// this path requires updating the skill in lockstep. The env override is an
|
|
13
|
+
// internal escape hatch for the parallel test harness (many worker processes on
|
|
14
|
+
// one host must not clobber a single shared /tmp path); production uses the
|
|
15
|
+
// documented default and the skill contract is unchanged.
|
|
16
|
+
const DEFAULT_PROXY_PORT_HINT_PATH = '/tmp/typeclaw-agent-browser-proxy-port'
|
|
17
|
+
const PROXY_PORT_HINT_PATH_ENV = 'TYPECLAW_AGENT_BROWSER_PROXY_PORT_HINT_PATH'
|
|
18
|
+
|
|
19
|
+
function proxyPortHintPath(): string {
|
|
20
|
+
return process.env[PROXY_PORT_HINT_PATH_ENV] || DEFAULT_PROXY_PORT_HINT_PATH
|
|
21
|
+
}
|
|
22
|
+
|
|
14
23
|
const DASHBOARD_TARGET_PORT = 4848
|
|
15
24
|
const DASHBOARD_HOST_CANDIDATES = [4848, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4857] as const
|
|
16
25
|
|
|
@@ -37,7 +46,7 @@ export function __resetForwardRequestForTesting(): void {
|
|
|
37
46
|
|
|
38
47
|
function requestDashboardForward(logger: { info: (msg: string) => void; warn: (msg: string) => void }): void {
|
|
39
48
|
if (!defaultBrokerEnabled()) {
|
|
40
|
-
recordProxyPort('TypeClaw dashboard forwarding unavailable: hostd broker is disabled.', logger)
|
|
49
|
+
void recordProxyPort('TypeClaw dashboard forwarding unavailable: hostd broker is disabled.', logger)
|
|
41
50
|
return
|
|
42
51
|
}
|
|
43
52
|
|
|
@@ -45,11 +54,11 @@ function requestDashboardForward(logger: { info: (msg: string) => void; warn: (m
|
|
|
45
54
|
unsubscribeForwardResult = subscribeForwardResult((event) => {
|
|
46
55
|
if (event.port !== DASHBOARD_TARGET_PORT) return
|
|
47
56
|
if (event.ok) {
|
|
48
|
-
recordProxyPort(String(event.hostPort), logger)
|
|
57
|
+
void recordProxyPort(String(event.hostPort), logger)
|
|
49
58
|
logger.info(`agent-browser dashboard forward reserved on host:${event.hostPort}`)
|
|
50
59
|
return
|
|
51
60
|
}
|
|
52
|
-
recordProxyPort(`TypeClaw dashboard forwarding unavailable: ${event.reason}`, logger)
|
|
61
|
+
void recordProxyPort(`TypeClaw dashboard forwarding unavailable: ${event.reason}`, logger)
|
|
53
62
|
logger.warn(`agent-browser dashboard forward failed: ${event.reason}`)
|
|
54
63
|
})
|
|
55
64
|
}
|
|
@@ -66,13 +75,14 @@ function defaultBrokerEnabled(): boolean {
|
|
|
66
75
|
return token !== undefined && token.length > 0
|
|
67
76
|
}
|
|
68
77
|
|
|
69
|
-
function recordProxyPort(contents: string, logger: { warn: (msg: string) => void }): void {
|
|
78
|
+
async function recordProxyPort(contents: string, logger: { warn: (msg: string) => void }): Promise<void> {
|
|
79
|
+
const path = proxyPortHintPath()
|
|
70
80
|
try {
|
|
71
|
-
Bun.write(
|
|
81
|
+
await Bun.write(path, contents)
|
|
72
82
|
} catch (error) {
|
|
73
83
|
// Hint is informational (lets a future `typeclaw status` or a human shell
|
|
74
84
|
// session report which port to open). Failure is non-fatal.
|
|
75
|
-
logger.warn(`failed to write ${
|
|
85
|
+
logger.warn(`failed to write ${path}: ${String(error)}`)
|
|
76
86
|
}
|
|
77
87
|
}
|
|
78
88
|
|
|
@@ -47,7 +47,9 @@ Memory is injected per turn into the user prompt; the system prompt never contai
|
|
|
47
47
|
|
|
48
48
|
**Cross-turn dedup (direct mode, non-channel).** Re-sending every shard body verbatim on every turn made a long conversation pay the same memory block dozens of times. The plugin keeps a per-session `slug → body-hash` record (`turn-dedup.ts`, `partitionDirectShards`) and, after a shard's full body has been injected once this session, replaces it on later turns with a one-line `slug:` reference plus a `memory_search({ topic: "<slug>" })` recovery hint. A shard whose body **changed** (a dreaming pass rewrote it) re-injects in full so the agent never reasons over a stale body. The "nothing the agent always had vanishes on an off-topic turn" guarantee is preserved by **availability, not literal presence**: every topic is still named (heading + slug) every turn, and the full body is one `memory_search` away. The per-session record is cleared on `session.end` (before the subagent-origin early-return, so subagent sessions don't leak it), so a resurrected session re-injects bodies in full rather than dangling a reference to text the rebuilt context no longer holds.
|
|
49
49
|
|
|
50
|
-
For **channel** origins, the per-turn render injects topic **headings only** — the excerpt body is stripped and the agent fetches it on demand via `memory_search`. A channel **direct-mode** turn is force-indexed to a headings/slugs section over **every** shard (not run through `hybridSearch`), so a full body can never reach a channel turn AND no heading is silently dropped by relevance-filtering or a stale vector index. Only channel turns that are genuinely **over budget** fall to `hybridSearch` top-K, where headings-only injection is the established channel policy regardless. This mirrors the direct-path policy that channel sessions never carry bodies: a topic heading is a self-contained belief sentence (the dreaming subagent writes exactly one), so the heading alone lets the model decide whether the topic is worth opening,
|
|
50
|
+
For **channel** origins, the per-turn render injects topic **headings only** — the excerpt body is stripped and the agent fetches it on demand via `memory_search`. A channel **direct-mode** turn is force-indexed to a headings/slugs section over **every** shard (not run through `hybridSearch`), so a full body can never reach a channel turn AND no heading is silently dropped by relevance-filtering or a stale vector index. Only channel turns that are genuinely **over budget** fall to `hybridSearch` top-K, where headings-only injection is the established channel policy regardless. This mirrors the direct-path policy that channel sessions never carry bodies: a topic heading is a self-contained belief sentence (the dreaming subagent writes exactly one — dreaming rule 6 requires the `heading` frontmatter to BE that belief sentence, not a noun-phrase title), so the heading alone lets the model decide whether the topic is worth opening — and, unlike a bare title, carries the fact itself so a casual turn that never calls `memory_search` still sees current truth instead of falling back to a stale model prior. The ~10-shard excerpt block — which dominated the per-turn injection and was usually abandoned unread — no longer rides in the (uncacheable) user turn on every message. Non-channel origins (TUI/direct) keep the full excerpt on first injection, where the extra retrieval round-trip isn't worth it.
|
|
51
|
+
|
|
52
|
+
**Legacy title-like headings.** A pre-contract shard whose `heading` is a noun-phrase title (detected as a clean kebab echo of its slug via `slugIsHeadingEcho`) would leave a channel turn with a fact-free label. `channelTopicEntry` (`load-memory.ts`) recovers the shard's first belief sentence from the body (`firstBeliefSentence`, `belief-sentence.ts`) and surfaces THAT instead — bounded to one sentence, never the full body, so the memory-bleed posture is unchanged. Both channel paths (direct-mode force-index and over-budget `hybridSearch` top-K) apply the fallback. Detection and extraction are script-agnostic (an all-CJK/Korean heading never reads as a slug echo, so a Korean belief-sentence heading is never mistaken for a title). This is the render-time bridge for shards written before the rule-6 heading contract; new/re-dreamed shards get belief-sentence headings natively.
|
|
51
53
|
|
|
52
54
|
Each stripped topic is injected with its `slug:` line so the agent can re-fetch the exact shard with `memory_search({ topic: "<slug>" })` — a direct slug lookup, not a second fuzzy search over the heading text the retrieval layer already matched. Undreamed `source: "stream"` items have no topic shard yet (no slug to look up), so they instead carry a `memory_search({ query: ... })` recovery hint; the channel directive names both paths so every stripped entry — topic or stream — has an explicit way back to its full text.
|
|
53
55
|
|
|
@@ -93,6 +95,7 @@ The subagent uses these signals to:
|
|
|
93
95
|
1. **Promote strong topics.** `days = 1` → tentative ("the user mentioned"). `days >= 3` → confident ("the user consistently"). `days >= 7` → declarative ("the user always"). Promotion is gated on distinct days, not raw citation count.
|
|
94
96
|
2. **Merge near-duplicates.** Topics that overlap get folded into one. The merged topic's citation set is the union.
|
|
95
97
|
3. **Demote decayed topics.** A weak/decayed topic stays as its own shard but the body should be trimmed to a single line. When index-mode injection is in effect, demoted shards' bodies don't enter the user turn at all — the index plus `memory_search` retrieval cover them on demand.
|
|
98
|
+
4. **Reinforce reaffirmed topics.** When a new fragment reaffirms, repeats, or user-corrects toward the current truth an existing shard already holds, the subagent adds that fragment id to the shard's `fragments:` list — a **distinct path from contradiction** (which supersedes) and from drop (which discards). Because the runtime recomputes `cites`/`days`/`lastReinforced` from the citation list, adding a citation IS the reinforcement mechanism; the subagent never edits the numbers. Reinforcement never moves an id into `superseded:` (that is contradiction-only). The dreaming prompt caps this at one pure-reinforcement citation per shard per day so a same-day burst can't inflate `days`, the promotion signal. This is what makes a fact the user repeatedly corrects get _stronger_ over time instead of being discarded as "already known" — and a correction that reveals a recurring wrong belief also sharpens the belief sentence with an explicit negative guard ("X is not Y anymore; X is Z"), which post-headings-fix is exactly what a channel turn sees first. The complementary capture half lives in the memory-logger prompt, which records a user correction as a distinct evidence-anchored fragment (semantically, in any language) even when memory may already know the affirmative fact.
|
|
96
99
|
|
|
97
100
|
There is no `## Historical observations` bucket. Demoted topics live as their own shards; injection-time filtering (the index/direct split) handles the prompt-budget pressure.
|
|
98
101
|
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { stripCitationLines } from './citations'
|
|
2
|
+
import { slugIsHeadingEcho } from './slug'
|
|
3
|
+
|
|
4
|
+
// Channel injection shows the agent only the heading, assuming the heading IS the
|
|
5
|
+
// shard's self-contained belief sentence. Legacy/dreaming shards put a noun-phrase
|
|
6
|
+
// TITLE there and the belief sentence in the body, so channel turns see a bare
|
|
7
|
+
// title carrying no fact. These helpers recover the belief sentence so a channel
|
|
8
|
+
// render can surface it — bounded to ONE sentence, never the full body, so the
|
|
9
|
+
// memory-bleed posture is unchanged. Script-agnostic by design (agents run in
|
|
10
|
+
// Korean/CJK/Arabic): no ASCII `\b`, no English stopword/verb heuristics.
|
|
11
|
+
|
|
12
|
+
const REFERENCES_HEADING = /^[\s-]*references\s*:\s*$/i
|
|
13
|
+
|
|
14
|
+
// Sentence terminators across the scripts agents run in: Latin `.!?`, CJK/fullwidth
|
|
15
|
+
// `。!?`, Arabic question mark `؟`, and Devanagari danda `।`. `\.` is only treated
|
|
16
|
+
// as a terminator when followed by whitespace or end-of-string, so a decimal like
|
|
17
|
+
// `3.5` or `v1.2` inside the belief does not cut the sentence short.
|
|
18
|
+
const SENTENCE_END = /[。!?؟।!?]|\.(?=\s|$)/u
|
|
19
|
+
|
|
20
|
+
// The first sentence of `line`: text up to and including the first terminator. A
|
|
21
|
+
// line with no terminator (a title/label) is itself one sentence and returned whole.
|
|
22
|
+
function firstSentenceOf(line: string): string {
|
|
23
|
+
const match = SENTENCE_END.exec(line)
|
|
24
|
+
if (match === null) return line
|
|
25
|
+
return line.slice(0, match.index + match[0].length).trim()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function firstBeliefSentence(body: string): string | undefined {
|
|
29
|
+
const prose = stripCitationLines(body)
|
|
30
|
+
for (const raw of prose.split('\n')) {
|
|
31
|
+
const line = raw.trim()
|
|
32
|
+
if (line === '') continue
|
|
33
|
+
if (REFERENCES_HEADING.test(line)) continue
|
|
34
|
+
const unwrapped = line.replace(/^#{1,6}\s+/, '').trim()
|
|
35
|
+
if (unwrapped !== '') return firstSentenceOf(unwrapped)
|
|
36
|
+
}
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// A heading is "title-like" (a noun-phrase label) rather than a self-contained
|
|
41
|
+
// belief sentence. The cheap, language-agnostic signal: a heading that is a clean
|
|
42
|
+
// kebab echo of its own slug ("T1 Competition Status 2026" -> `t1-competition-
|
|
43
|
+
// status-2026`) is a title, because a real belief sentence (with a predicate and
|
|
44
|
+
// scope) does not survive slugification as a clean echo — it is too long and
|
|
45
|
+
// carries punctuation/particles that `headingToSlug` collapses. `slugIsHeadingEcho`
|
|
46
|
+
// already returns false for all-CJK/emoji headings (normalization discarded
|
|
47
|
+
// content), so a Korean belief sentence is never misread as a title by this path.
|
|
48
|
+
export function isTitleLikeHeading(heading: string, slug: string): boolean {
|
|
49
|
+
return slugIsHeadingEcho(heading, slug)
|
|
50
|
+
}
|