typeclaw 0.41.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/README.md +3 -2
- package/auth.schema.json +57 -0
- package/package.json +4 -4
- package/secrets.schema.json +57 -0
- package/src/agent/adaptive-thinking-compat.ts +79 -0
- package/src/agent/index.ts +89 -107
- 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/session-origin.ts +1 -0
- 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/channel-history-render.ts +21 -0
- package/src/agent/tools/channel-history.ts +2 -17
- package/src/agent/tools/channel-read.ts +206 -0
- package/src/agent/tools/stream-snapshot.ts +8 -3
- package/src/bundled-plugins/agent-browser/index.ts +18 -8
- package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +26 -2
- package/src/bundled-plugins/github-cli-auth/index.ts +25 -6
- 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/bundled-plugins/memory/vector/hybrid.ts +73 -6
- package/src/bundled-plugins/memory/vector/passages.ts +2 -24
- package/src/bundled-plugins/memory/vector/truncation.ts +28 -0
- package/src/bundled-plugins/tool-result-cap/README.md +10 -1
- package/src/bundled-plugins/tool-result-cap/cap-result.ts +8 -0
- 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/adapters/discord-bot.ts +112 -0
- package/src/channels/adapters/instagram-channel-resolver.ts +113 -0
- package/src/channels/adapters/instagram-classify.ts +69 -0
- package/src/channels/adapters/instagram-format.ts +8 -0
- package/src/channels/adapters/instagram.ts +346 -0
- package/src/channels/adapters/slack-bot.ts +147 -0
- package/src/channels/manager.ts +96 -44
- package/src/channels/router.ts +75 -2
- package/src/channels/schema.ts +5 -0
- package/src/channels/types.ts +46 -0
- package/src/cli/channel.ts +121 -9
- package/src/cli/hostd.ts +4 -3
- package/src/cli/init.ts +1 -0
- 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 +37 -14
- 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/channels-mutation.ts +2 -1
- 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/doctor/channel-checks.ts +28 -0
- package/src/hostd/daemon.ts +11 -7
- package/src/hostd/protocol.ts +2 -0
- package/src/init/index.ts +51 -2
- package/src/init/instagram-auth.ts +289 -0
- package/src/init/run-owner-claim.ts +1 -0
- package/src/inspect/logs-item.ts +2 -2
- package/src/mcp/client.ts +1 -1
- package/src/permissions/match-rule.ts +1 -1
- package/src/permissions/resolve.ts +1 -0
- package/src/role-claim/match-rule.ts +2 -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 +103 -0
- package/src/secrets/kakao-store.ts +4 -13
- package/src/secrets/line-store.ts +4 -13
- package/src/secrets/schema.ts +18 -0
- 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 +30 -0
- 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 +175 -1
|
@@ -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
|
@@ -153,6 +153,7 @@ const PLATFORM_INFO: Record<AdapterId, PlatformInfo> = {
|
|
|
153
153
|
supportsAttachments: true,
|
|
154
154
|
},
|
|
155
155
|
github: { displayName: 'GitHub', mentionMode: 'at-username', supportsReactions: true, supportsAttachments: false },
|
|
156
|
+
instagram: { displayName: 'Instagram', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
|
|
156
157
|
'telegram-bot': {
|
|
157
158
|
displayName: 'Telegram',
|
|
158
159
|
mentionMode: 'at-username',
|
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
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ChannelHistoryMessage } from '@/channels/types'
|
|
2
|
+
|
|
3
|
+
// Render history as one line per message, chronological order. `BOT` marker
|
|
4
|
+
// distinguishes the agent's own past replies from user messages so the model
|
|
5
|
+
// does not treat them as user input. Author name is shown alongside the id so
|
|
6
|
+
// the agent can refer to people by name. Shared by channel_history (origin-
|
|
7
|
+
// bound) and channel_read (arbitrary-chat) so both render identically.
|
|
8
|
+
export function renderHistoryMessages(messages: readonly ChannelHistoryMessage[]): string {
|
|
9
|
+
if (messages.length === 0) return '(no messages)'
|
|
10
|
+
const lines: string[] = []
|
|
11
|
+
for (const m of messages) {
|
|
12
|
+
lines.push(renderHistoryMessage(m))
|
|
13
|
+
}
|
|
14
|
+
return lines.join('\n')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function renderHistoryMessage(m: ChannelHistoryMessage): string {
|
|
18
|
+
const iso = m.ts > 0 ? new Date(m.ts).toISOString() : 'unknown-time'
|
|
19
|
+
const who = m.isBot ? `BOT (${m.authorName})` : `${m.authorName} (<@${m.authorId}>)`
|
|
20
|
+
return `[${iso}] ${who}: ${m.text}`
|
|
21
|
+
}
|
|
@@ -3,8 +3,8 @@ import { defineTool } from '@mariozechner/pi-coding-agent'
|
|
|
3
3
|
|
|
4
4
|
import type { ChannelRouter } from '@/channels/router'
|
|
5
5
|
import type { AdapterId } from '@/channels/schema'
|
|
6
|
-
import type { ChannelHistoryMessage } from '@/channels/types'
|
|
7
6
|
|
|
7
|
+
import { renderHistoryMessages } from './channel-history-render'
|
|
8
8
|
import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
|
|
9
9
|
|
|
10
10
|
export type ChannelHistoryOrigin = {
|
|
@@ -96,7 +96,7 @@ export function createChannelHistoryTool({
|
|
|
96
96
|
|
|
97
97
|
router.registerHistoryAttachments(origin, result.messages)
|
|
98
98
|
|
|
99
|
-
const rendered =
|
|
99
|
+
const rendered = renderHistoryMessages(result.messages)
|
|
100
100
|
const cursorLine =
|
|
101
101
|
result.nextCursor !== undefined
|
|
102
102
|
? `\n\n(more older messages available — call channel_history again with cursor: ${JSON.stringify(result.nextCursor)})`
|
|
@@ -113,18 +113,3 @@ export function createChannelHistoryTool({
|
|
|
113
113
|
},
|
|
114
114
|
})
|
|
115
115
|
}
|
|
116
|
-
|
|
117
|
-
// Render history as one line per message, chronological order. `BOT` marker
|
|
118
|
-
// distinguishes the agent's own past replies from user messages so the
|
|
119
|
-
// model doesn't treat them as user input. Author name is shown alongside
|
|
120
|
-
// the id so the agent can refer to people by name in its reply.
|
|
121
|
-
function renderMessages(messages: readonly ChannelHistoryMessage[]): string {
|
|
122
|
-
if (messages.length === 0) return '(no messages)'
|
|
123
|
-
const lines: string[] = []
|
|
124
|
-
for (const m of messages) {
|
|
125
|
-
const iso = m.ts > 0 ? new Date(m.ts).toISOString() : 'unknown-time'
|
|
126
|
-
const who = m.isBot ? `BOT (${m.authorName})` : `${m.authorName} (<@${m.authorId}>)`
|
|
127
|
-
lines.push(`[${iso}] ${who}: ${m.text}`)
|
|
128
|
-
}
|
|
129
|
-
return lines.join('\n')
|
|
130
|
-
}
|