typeclaw 0.43.1 → 0.45.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/auth.schema.json +92 -0
- package/package.json +7 -6
- package/secrets.schema.json +92 -0
- package/src/agent/index.ts +25 -2
- package/src/agent/model-fallback.ts +59 -40
- package/src/agent/multimodal/look-at.ts +29 -10
- package/src/agent/plugin-tools.ts +9 -4
- package/src/agent/provider-error.ts +71 -18
- package/src/agent/retry-same-ref.ts +139 -0
- package/src/agent/session-origin.ts +1 -0
- package/src/agent/subagents.ts +6 -2
- package/src/agent/tools/channel-edit.ts +144 -0
- package/src/agent/tools/channel-fetch-attachment.ts +51 -8
- package/src/agent/tools/channel-reply.ts +41 -18
- package/src/agent/tools/channel-send.ts +82 -13
- package/src/agent/tools/curl-impersonate.ts +40 -1
- package/src/agent/tools/webfetch/fetch.ts +86 -3
- package/src/agent/tools/webfetch/tool.ts +26 -3
- package/src/agent/tools/webfetch/types.ts +8 -0
- package/src/agent/turn-runner.ts +65 -36
- package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +28 -11
- package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +101 -1
- package/src/bundled-plugins/github-cli-auth/review-recorder.ts +44 -3
- package/src/bundled-plugins/guard/policies/managed-config.ts +20 -4
- package/src/bundled-plugins/memory/README.md +9 -9
- package/src/bundled-plugins/memory/index.ts +40 -9
- package/src/bundled-plugins/reviewer/skills/code-review.ts +22 -2
- package/src/channels/adapters/discord-bot-edit.ts +49 -0
- package/src/channels/adapters/discord-bot.ts +5 -0
- package/src/channels/adapters/discord-edit.ts +51 -0
- package/src/channels/adapters/discord.ts +4 -0
- package/src/channels/adapters/github/inbound.ts +20 -14
- package/src/channels/adapters/github/review-thread-resolver.ts +38 -4
- package/src/channels/adapters/slack-bot-edit.ts +58 -0
- package/src/channels/adapters/slack-bot.ts +18 -6
- package/src/channels/adapters/slack-edit.ts +47 -0
- package/src/channels/adapters/slack.ts +5 -0
- package/src/channels/adapters/teams-classify.ts +144 -0
- package/src/channels/adapters/teams-edit.ts +61 -0
- package/src/channels/adapters/teams-id-token.ts +112 -0
- package/src/channels/adapters/teams-key.ts +32 -0
- package/src/channels/adapters/teams.ts +523 -0
- package/src/channels/adapters/telegram-bot-edit.ts +51 -0
- package/src/channels/adapters/telegram-bot.ts +5 -0
- package/src/channels/adapters/webex-bot.ts +5 -0
- package/src/channels/adapters/webex-edit.ts +47 -0
- package/src/channels/adapters/webex.ts +5 -0
- package/src/channels/continuation-willingness.ts +227 -35
- package/src/channels/github-review-turn-ledger.ts +43 -0
- package/src/channels/index.ts +1 -1
- package/src/channels/manager.ts +54 -1
- package/src/channels/router.ts +482 -53
- package/src/channels/schema.ts +33 -0
- package/src/channels/types.ts +36 -0
- package/src/cli/channel.ts +92 -4
- package/src/cli/hostd.ts +41 -0
- package/src/cli/init.ts +58 -1
- package/src/config/channels-mutation.ts +9 -1
- package/src/cron/index.ts +16 -4
- package/src/cron/reloadable.ts +25 -7
- package/src/cron/scheduler.ts +4 -0
- package/src/cron/schema.ts +143 -35
- package/src/doctor/channel-checks.ts +27 -0
- package/src/hostd/daemon.ts +23 -3
- package/src/hostd/protocol.ts +2 -0
- package/src/hostd/teams-renewal-manager.ts +212 -0
- package/src/init/checkpoint.ts +1 -1
- package/src/init/index.ts +68 -1
- package/src/init/run-owner-claim.ts +1 -0
- package/src/init/teams-auth.ts +111 -0
- package/src/inspect/label.ts +4 -0
- package/src/permissions/match-rule.ts +11 -1
- package/src/permissions/resolve.ts +1 -0
- package/src/role-claim/match-rule.ts +2 -1
- package/src/run/index.ts +35 -8
- package/src/run/llm-fetch-observer.ts +27 -5
- package/src/sandbox/build.ts +12 -0
- package/src/sandbox/policy.ts +13 -0
- package/src/sandbox/writable-zones.ts +46 -10
- package/src/secrets/schema.ts +32 -0
- package/src/secrets/teams-renewal.ts +229 -0
- package/src/secrets/teams-store.ts +108 -0
- package/src/server/command-runner.ts +2 -1
- package/src/server/index.ts +2 -1
- package/typeclaw.schema.json +163 -3
|
@@ -33,19 +33,36 @@ const GENERIC_SAFE_NOTICE = 'The upstream LLM provider failed. Operators can che
|
|
|
33
33
|
// and surface it. The literal is the system's own token — English by design.
|
|
34
34
|
const OBSERVER_TIMEOUT = /\(typeclaw observer timeout\)/i
|
|
35
35
|
|
|
36
|
+
// Transport-layer failure: the request died at the connection/session before a
|
|
37
|
+
// usable response — an expired live session, a WebSocket upgrade that never
|
|
38
|
+
// reached `101 Switching Protocols`, or a dropped transport. Unlike an
|
|
39
|
+
// account-wide auth/billing fault, this is transient AND ref-specific: a
|
|
40
|
+
// different ref opens its own session, so failing OVER can succeed. Observed from
|
|
41
|
+
// Codex/ChatGPT (`provider_transport_failure`, expired ChatGPT session, a
|
|
42
|
+
// `wss://…/codex/responses` non-101 upgrade). Provider protocol tokens — English
|
|
43
|
+
// by design (the system-token exception to the multi-language rule).
|
|
44
|
+
const TRANSPORT_FAILURE =
|
|
45
|
+
/provider[_ -]?transport[_ -]?failure|(?:websocket|ws) connection.*failed|expected 101|session expired/i
|
|
46
|
+
|
|
47
|
+
// Auth failure: the provider rejected our credentials (bad/expired/missing API
|
|
48
|
+
// key, 401, failed authentication). Account-wide — a different ref shares the
|
|
49
|
+
// same credential problem — so this is BOTH a redacted safe-message class (a
|
|
50
|
+
// 401 body can carry a Bearer token) AND a NON_FAILOVER_FAULT reason. Shared as
|
|
51
|
+
// one constant so the two uses can never drift: previously the safe-message copy
|
|
52
|
+
// matched `api key ... expired` but the failover copy didn't, letting
|
|
53
|
+
// `session expired: api key expired` wrongly fail over past the auth guard.
|
|
54
|
+
const AUTH_FAULT =
|
|
55
|
+
/\b(401|unauthori[sz]ed|invalid[_ -]?api[_ -]?key|api key.*(?:invalid|expired|missing)|authentication failed|invalid bearer)\b/i
|
|
56
|
+
|
|
36
57
|
// Each entry pairs a narrow matcher against the raw provider text with the
|
|
37
58
|
// canonical, leak-free sentence shown in channels. Matchers are intentionally
|
|
38
59
|
// specific: a miss falls through to GENERIC_SAFE_NOTICE rather than echoing raw
|
|
39
60
|
// text, so adding a new class is opt-in and never widens what we expose.
|
|
40
61
|
const SAFE_CLASSES: ReadonlyArray<{ match: RegExp; safe: string }> = [
|
|
41
62
|
{
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
|
|
45
|
-
// names the operator action (check the API key) without echoing the raw
|
|
46
|
-
// error, whose body can carry a Bearer token.
|
|
47
|
-
match:
|
|
48
|
-
/\b(401|unauthori[sz]ed|invalid[_ -]?api[_ -]?key|api key.*(?:invalid|expired|missing)|authentication failed|invalid bearer)\b/i,
|
|
63
|
+
// Matched first because a 401 body can also mention "account", which would
|
|
64
|
+
// otherwise fall into the billing class below.
|
|
65
|
+
match: AUTH_FAULT,
|
|
49
66
|
safe: 'The upstream LLM provider rejected the request as unauthorized. Operators should check the provider API key configuration and `typeclaw logs`.',
|
|
50
67
|
},
|
|
51
68
|
{
|
|
@@ -71,6 +88,10 @@ const SAFE_CLASSES: ReadonlyArray<{ match: RegExp; safe: string }> = [
|
|
|
71
88
|
match: OBSERVER_TIMEOUT,
|
|
72
89
|
safe: 'The upstream LLM provider stopped responding and the request timed out. Try again shortly.',
|
|
73
90
|
},
|
|
91
|
+
{
|
|
92
|
+
match: TRANSPORT_FAILURE,
|
|
93
|
+
safe: 'The connection to the upstream LLM provider dropped (session/transport failure). Try again shortly.',
|
|
94
|
+
},
|
|
74
95
|
]
|
|
75
96
|
|
|
76
97
|
function toSafeMessage(raw: string): string {
|
|
@@ -92,9 +113,12 @@ const THROTTLE_OR_OVERLOAD =
|
|
|
92
113
|
// help (same account) and would mask a config error the operator must fix. This
|
|
93
114
|
// is checked BEFORE the throttle match because providers often pair a `429`
|
|
94
115
|
// status with a quota/billing/auth reason (e.g. `429 insufficient quota`) — the
|
|
95
|
-
// status code alone must not force a pointless failover.
|
|
96
|
-
|
|
97
|
-
|
|
116
|
+
// status code alone must not force a pointless failover. The auth arm reuses the
|
|
117
|
+
// shared `AUTH_FAULT` source so it stays in lockstep with the safe-message class.
|
|
118
|
+
const NON_FAILOVER_FAULT = new RegExp(
|
|
119
|
+
`\\bcyber_policy\\b|insufficient.*(?:quota|credit|fund|balance)|\\bquota\\b|billing|payment|account is not active|${AUTH_FAULT.source}`,
|
|
120
|
+
'i',
|
|
121
|
+
)
|
|
98
122
|
|
|
99
123
|
export function isThrottleOrOverload(raw: string): boolean {
|
|
100
124
|
if (NON_FAILOVER_FAULT.test(raw)) return false
|
|
@@ -102,14 +126,40 @@ export function isThrottleOrOverload(raw: string): boolean {
|
|
|
102
126
|
}
|
|
103
127
|
|
|
104
128
|
// Failover predicate for turn-drivers' `shouldFailover`: rotate to the next model
|
|
105
|
-
// ref on a transient capacity signal (throttle/overload)
|
|
106
|
-
// timeout
|
|
107
|
-
//
|
|
108
|
-
// fail OVER before the caller surfaces a failure notice.
|
|
109
|
-
// (billing/quota/auth)
|
|
110
|
-
//
|
|
129
|
+
// ref on a transient capacity signal (throttle/overload), an observer stall
|
|
130
|
+
// timeout, or a transport/session failure. A stall or a dropped session is as
|
|
131
|
+
// transient as an overload and another ref (its own session/transport) may well
|
|
132
|
+
// succeed, so it must fail OVER before the caller surfaces a failure notice.
|
|
133
|
+
// Account-wide faults (billing/quota/auth) are excluded up front — a different
|
|
134
|
+
// ref shares the same account problem, so switching can't help.
|
|
111
135
|
export function isFailoverWorthy(raw: string): boolean {
|
|
112
|
-
|
|
136
|
+
if (NON_FAILOVER_FAULT.test(raw)) return false
|
|
137
|
+
return isThrottleOrOverload(raw) || OBSERVER_TIMEOUT.test(raw) || TRANSPORT_FAILURE.test(raw)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Transient network / upstream 5xx signals that a same-model replay may clear.
|
|
141
|
+
// Distinct from THROTTLE_OR_OVERLOAD (429/503/overload) on purpose: an overload
|
|
142
|
+
// means the model is out of capacity NOW, so the right move is to fail OVER to a
|
|
143
|
+
// different ref, not hammer the same one — whereas a socket hang-up or a 500 is a
|
|
144
|
+
// one-off blip a replay against the SAME ref often fixes. `\b` anchors the 5xx
|
|
145
|
+
// codes so they don't match digit runs in prose. Provider protocol tokens —
|
|
146
|
+
// English by design (the system-token exception to the multi-language rule).
|
|
147
|
+
const NETWORK_OR_5XX =
|
|
148
|
+
/econnreset|econnrefused|etimedout|enetunreach|socket hang up|network.?error|connection.?(?:error|refused|reset|lost)|fetch failed|other side closed|reset before headers|http2 request did not get a response|\b(?:500|502|504)\b/i
|
|
149
|
+
|
|
150
|
+
// Retry predicate for typeclaw-owned SAME-REF retry: replay the SAME model ref
|
|
151
|
+
// before advancing the chain. Deliberately NARROWER than `isFailoverWorthy` —
|
|
152
|
+
// only transient failures a same-model replay can plausibly clear: transport/
|
|
153
|
+
// session drops, observer stalls, and network/5xx blips. It intentionally EXCLUDES
|
|
154
|
+
// throttle/overload (429/503) — those mean "this ref is out of capacity now", so
|
|
155
|
+
// they should fail OVER to another ref rather than burn same-ref retries — and
|
|
156
|
+
// account-wide faults (auth/billing/quota/cyber_policy), which must surface. It
|
|
157
|
+
// does NOT match context-overflow: that stays on the SDK compaction path and must
|
|
158
|
+
// never be treated as a retryable provider failure.
|
|
159
|
+
export function isRetryableSameRef(raw: string): boolean {
|
|
160
|
+
if (NON_FAILOVER_FAULT.test(raw)) return false
|
|
161
|
+
if (isThrottleOrOverload(raw)) return false
|
|
162
|
+
return TRANSPORT_FAILURE.test(raw) || OBSERVER_TIMEOUT.test(raw) || NETWORK_OR_5XX.test(raw)
|
|
113
163
|
}
|
|
114
164
|
|
|
115
165
|
export function detectProviderError(message: unknown): DetectedProviderError | null {
|
|
@@ -134,7 +184,10 @@ export function detectProviderError(message: unknown): DetectedProviderError | n
|
|
|
134
184
|
export function detectHardProviderError(err: unknown): DetectedProviderError | null {
|
|
135
185
|
const message = err instanceof Error ? err.message : String(err)
|
|
136
186
|
const isProviderFailure =
|
|
137
|
-
isThrottleOrOverload(message) ||
|
|
187
|
+
isThrottleOrOverload(message) ||
|
|
188
|
+
NON_FAILOVER_FAULT.test(message) ||
|
|
189
|
+
OBSERVER_TIMEOUT.test(message) ||
|
|
190
|
+
TRANSPORT_FAILURE.test(message)
|
|
138
191
|
if (!isProviderFailure) return null
|
|
139
192
|
return { message, safeMessage: toSafeMessage(message) }
|
|
140
193
|
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { AgentSession } from './index'
|
|
2
|
+
import { isRetryableSameRef, subscribeProviderErrors } from './provider-error'
|
|
3
|
+
|
|
4
|
+
// Same-ref retry policy. Conservative on purpose: the pi-ai provider layer ALSO
|
|
5
|
+
// retries transport/5xx blips underneath us (WebSocket→SSE fallback + its own
|
|
6
|
+
// SSE retry loop), and each typeclaw attempt is bounded by the observer timeouts
|
|
7
|
+
// (TTFB 15s / idle 120s / overall 300s). Stacking a large per-ref retry count on
|
|
8
|
+
// top of that turns one outage into minutes of dead air, so we replay the same
|
|
9
|
+
// ref just ONCE by default and rely on cross-ref fallback for anything the single
|
|
10
|
+
// replay can't clear.
|
|
11
|
+
export const RETRIES_PER_REF = 1
|
|
12
|
+
const BASE_DELAY_MS = 1_000
|
|
13
|
+
const MAX_DELAY_MS = 5_000
|
|
14
|
+
|
|
15
|
+
// Full-jitter exponential backoff: random in [0, min(cap, base·2^attempt)].
|
|
16
|
+
// Jitter decorrelates concurrent turns (multiple channels/subagents recovering
|
|
17
|
+
// from the same upstream blip) so they don't retry in lockstep and re-collide.
|
|
18
|
+
export function retryBackoffMs(attempt: number, random: () => number = Math.random): number {
|
|
19
|
+
const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt)
|
|
20
|
+
return Math.floor(random() * ceiling)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
24
|
+
if (ms <= 0) return Promise.resolve()
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
const timer = setTimeout(resolve, ms)
|
|
27
|
+
signal?.addEventListener('abort', () => {
|
|
28
|
+
clearTimeout(timer)
|
|
29
|
+
resolve()
|
|
30
|
+
})
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// For callers that recreate the session themselves (cron) and only need the delay.
|
|
35
|
+
export function sleepBackoff(attempt: number, signal?: AbortSignal, random?: () => number): Promise<void> {
|
|
36
|
+
return sleep(retryBackoffMs(attempt, random), signal)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type ContinuableAgent = {
|
|
40
|
+
state?: { messages?: unknown }
|
|
41
|
+
continue?: () => Promise<void>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Replay the CURRENT turn on a persistent session WITHOUT re-appending the user
|
|
45
|
+
// message. Mirrors the SDK's own auto-retry shape, resuming via `agent.continue()`
|
|
46
|
+
// (which replays from the trailing user/tool-result message). Re-calling
|
|
47
|
+
// `session.prompt(text)` instead would duplicate the user message and corrupt
|
|
48
|
+
// history, so we never do that.
|
|
49
|
+
//
|
|
50
|
+
// Two resolved shapes are retryable, matching `continue()`'s contract that the
|
|
51
|
+
// last message be user/tool-result:
|
|
52
|
+
// - trailing ASSISTANT error leaf → pop it, then continue (soft error, or a
|
|
53
|
+
// hard throw AFTER a partial assistant message was written)
|
|
54
|
+
// - trailing USER message → the provider died BEFORE writing any assistant
|
|
55
|
+
// message (the reported incident: transport/session failure before stream
|
|
56
|
+
// start). Nothing to pop — continue() replays the user turn as-is.
|
|
57
|
+
// Any other trailing shape (tool-result mid-execution, custom, empty transcript,
|
|
58
|
+
// no `agent.continue`) fails CLOSED — the caller falls back / surfaces instead.
|
|
59
|
+
export async function retryTurnOnPersistentSession(
|
|
60
|
+
session: AgentSession,
|
|
61
|
+
opts: { attempt: number; signal?: AbortSignal; random?: () => number } = { attempt: 0 },
|
|
62
|
+
): Promise<boolean> {
|
|
63
|
+
const agent = (session as { agent?: ContinuableAgent }).agent
|
|
64
|
+
if (!agent || typeof agent.continue !== 'function') return false
|
|
65
|
+
const messages = agent.state?.messages
|
|
66
|
+
if (!Array.isArray(messages) || messages.length === 0) return false
|
|
67
|
+
const leafRole = (messages[messages.length - 1] as { role?: unknown }).role
|
|
68
|
+
if (leafRole !== 'assistant' && leafRole !== 'user') return false
|
|
69
|
+
|
|
70
|
+
await sleep(retryBackoffMs(opts.attempt, opts.random), opts.signal)
|
|
71
|
+
if (opts.signal?.aborted) return false
|
|
72
|
+
|
|
73
|
+
// Drop only a trailing assistant error leaf; a trailing user message is already
|
|
74
|
+
// the shape continue() wants, so leave it untouched (and never re-appended).
|
|
75
|
+
if (leafRole === 'assistant') {
|
|
76
|
+
;(agent.state as { messages: unknown }).messages = messages.slice(0, -1)
|
|
77
|
+
}
|
|
78
|
+
await agent.continue()
|
|
79
|
+
return true
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Same-ref retry for DIRECT `session.prompt()` call sites that bypass the model
|
|
83
|
+
// fallback helpers (non-stream TUI, slash commands, subagent drain/required-block
|
|
84
|
+
// nudges, multimodal look-at). These lost the SDK's built-in retry when it was
|
|
85
|
+
// disabled globally to kill the soft-error race; this restores equivalent
|
|
86
|
+
// same-model resilience WITHOUT cross-ref fallback (there's no chain here) and
|
|
87
|
+
// WITHOUT the race (typeclaw owns the soft-error signal). On a non-retryable
|
|
88
|
+
// failure it does exactly what a bare prompt() did: the throw propagates, or the
|
|
89
|
+
// soft error stays on the leaf for the caller to read.
|
|
90
|
+
export async function promptWithSameRefRetryOnly(
|
|
91
|
+
session: AgentSession,
|
|
92
|
+
text: string,
|
|
93
|
+
promptOpts?: Parameters<AgentSession['prompt']>[1],
|
|
94
|
+
): Promise<void> {
|
|
95
|
+
let softError: Error | undefined
|
|
96
|
+
// Feature-detect subscribe: some lightweight call sites / test fakes pass a
|
|
97
|
+
// session without an event stream. Without it we simply can't observe soft
|
|
98
|
+
// errors — the wrapper then only retries hard throws, still safe.
|
|
99
|
+
const canSubscribe = typeof (session as { subscribe?: unknown }).subscribe === 'function'
|
|
100
|
+
const unsub = canSubscribe
|
|
101
|
+
? subscribeProviderErrors(session, (err) => {
|
|
102
|
+
if (!softError) softError = new Error(err.message)
|
|
103
|
+
})
|
|
104
|
+
: () => {}
|
|
105
|
+
try {
|
|
106
|
+
// Carry the last attempt's failure so a retry that CAN'T run (unsafe
|
|
107
|
+
// transcript shape → retryTurnOnPersistentSession returns false) still
|
|
108
|
+
// surfaces the original failure instead of resolving as a phantom success.
|
|
109
|
+
let priorHardError: Error | undefined
|
|
110
|
+
for (let attempt = 0; ; attempt++) {
|
|
111
|
+
softError = undefined
|
|
112
|
+
let hardError: Error | undefined
|
|
113
|
+
try {
|
|
114
|
+
if (attempt === 0) {
|
|
115
|
+
await session.prompt(text, promptOpts)
|
|
116
|
+
} else if (!(await retryTurnOnPersistentSession(session, { attempt: attempt - 1 }))) {
|
|
117
|
+
// Continue-recipe not applicable: replay never happened, so the prior
|
|
118
|
+
// failure stands — re-throw a hard error, or return to leave a soft
|
|
119
|
+
// error on the leaf (bare-prompt() semantics).
|
|
120
|
+
if (priorHardError !== undefined) throw priorHardError
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
} catch (err) {
|
|
124
|
+
hardError = err instanceof Error ? err : new Error(String(err))
|
|
125
|
+
}
|
|
126
|
+
const error = hardError ?? softError
|
|
127
|
+
if (error === undefined) return
|
|
128
|
+
if (attempt >= RETRIES_PER_REF || !isRetryableSameRef(error.message)) {
|
|
129
|
+
// Out of budget or not retryable: preserve bare-prompt() semantics — a
|
|
130
|
+
// hard error throws; a soft error stays on the leaf for the caller.
|
|
131
|
+
if (hardError !== undefined) throw hardError
|
|
132
|
+
return
|
|
133
|
+
}
|
|
134
|
+
priorHardError = hardError
|
|
135
|
+
}
|
|
136
|
+
} finally {
|
|
137
|
+
unsub()
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -162,6 +162,7 @@ const PLATFORM_INFO: Record<AdapterId, PlatformInfo> = {
|
|
|
162
162
|
},
|
|
163
163
|
webex: { displayName: 'Webex', mentionMode: 'angle-id', supportsReactions: false, supportsAttachments: true },
|
|
164
164
|
'webex-bot': { displayName: 'Webex', mentionMode: 'angle-id', supportsReactions: false, supportsAttachments: false },
|
|
165
|
+
teams: { displayName: 'Teams', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
|
|
165
166
|
line: { displayName: 'LINE', mentionMode: 'alias', supportsReactions: false, supportsAttachments: false },
|
|
166
167
|
kakaotalk: { displayName: 'KakaoTalk', mentionMode: 'alias', supportsReactions: false, supportsAttachments: true },
|
|
167
168
|
}
|
package/src/agent/subagents.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { type AgentSession, createSession, type PluginSessionWiring } from './in
|
|
|
11
11
|
import { resolveFallbackChain } from './model-fallback'
|
|
12
12
|
import { applyModelRuntimeOverrides } from './model-overrides'
|
|
13
13
|
import { isFailoverWorthy, subscribeProviderErrors } from './provider-error'
|
|
14
|
+
import { promptWithSameRefRetryOnly } from './retry-same-ref'
|
|
14
15
|
import type { SubagentBashPolicy } from './reviewer-bash-policy'
|
|
15
16
|
import type { SessionOrigin } from './session-origin'
|
|
16
17
|
import {
|
|
@@ -375,7 +376,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
|
|
|
375
376
|
await runSubagentDrain(drainWatch, {
|
|
376
377
|
drain: backgroundDrain,
|
|
377
378
|
prompt: async (text) => {
|
|
378
|
-
await session
|
|
379
|
+
await promptWithSameRefRetryOnly(session, `${renderTurnTimeAnchor()}\n\n${text}`)
|
|
379
380
|
},
|
|
380
381
|
cancelled: () => aborted,
|
|
381
382
|
})
|
|
@@ -395,7 +396,10 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
|
|
|
395
396
|
console.warn(
|
|
396
397
|
`[subagent] ${name} required_block_retry attempt=${attempt}/${MAX_REQUIRED_BLOCK_RETRIES} tag=${requiredBlockTag}`,
|
|
397
398
|
)
|
|
398
|
-
await
|
|
399
|
+
await promptWithSameRefRetryOnly(
|
|
400
|
+
session,
|
|
401
|
+
`${renderTurnTimeAnchor()}\n\n${renderRequiredBlockRetryNudge(requiredBlockTag)}`,
|
|
402
|
+
)
|
|
399
403
|
}
|
|
400
404
|
if (!aborted && !capture.hasRequiredBlock()) {
|
|
401
405
|
console.warn(`[subagent] ${name} required_block_fallback tag=${requiredBlockTag}`)
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { Type } from '@mariozechner/pi-ai'
|
|
2
|
+
import { defineTool } from '@mariozechner/pi-coding-agent'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
containsKimiToolDelimiter,
|
|
6
|
+
isNoReplySignal,
|
|
7
|
+
isUpstreamEmptyResponseSentinel,
|
|
8
|
+
stripThinkBlocks,
|
|
9
|
+
type ChannelRouter,
|
|
10
|
+
} from '@/channels/router'
|
|
11
|
+
import { ADAPTER_IDS, type AdapterId } from '@/channels/schema'
|
|
12
|
+
import type { EditMessageResult } from '@/channels/types'
|
|
13
|
+
|
|
14
|
+
import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
|
|
15
|
+
import { renderOutboundEcho, TOOL_RESULT_PREFIX } from './channel-reply'
|
|
16
|
+
import { fenceToolResult } from './runtime-notice'
|
|
17
|
+
|
|
18
|
+
export type CreateChannelEditToolOptions = {
|
|
19
|
+
router: ChannelRouter
|
|
20
|
+
logger?: ChannelToolLogger
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function createChannelEditTool({ router, logger = consoleChannelLogger }: CreateChannelEditToolOptions) {
|
|
24
|
+
return defineTool({
|
|
25
|
+
name: 'channel_edit',
|
|
26
|
+
label: 'Channel Edit',
|
|
27
|
+
description:
|
|
28
|
+
'Edit the text of a message you already posted to an external messenger channel, replacing its body in place. ' +
|
|
29
|
+
'Pass the `message_id` a prior `channel_send` returned (Slack thread ts, Discord message id), plus the same ' +
|
|
30
|
+
'adapter/workspace/chat you sent it to, and the new `text`. Use this to fix a typo, correct a wrong answer, ' +
|
|
31
|
+
'or append a result to a status message you posted earlier — not to carry on a conversation (send a new ' +
|
|
32
|
+
'message for that). Editing is supported on "slack-bot", "slack", "discord-bot", "discord", "telegram-bot", ' +
|
|
33
|
+
'"webex", "webex-bot", and "teams" (chats/DMs only — Teams team-channel posts cannot be edited); an adapter ' +
|
|
34
|
+
'that does not implement editing at all returns ' +
|
|
35
|
+
'{ ok: false, error, code: "not-supported" }. You can only edit messages YOU authored; editing someone ' +
|
|
36
|
+
'else\'s returns code "permission-denied". On success returns { ok: true }; a missing/deleted target returns ' +
|
|
37
|
+
'code "not-found". Code "adapter-unavailable" is distinct from "not-supported": the adapter DOES support ' +
|
|
38
|
+
'editing but is not currently running (e.g. it failed to start on an expired token) — re-authenticating and ' +
|
|
39
|
+
'retrying may fix it, so do not treat it as permanently unsupported.',
|
|
40
|
+
parameters: Type.Object({
|
|
41
|
+
adapter: Type.Union(
|
|
42
|
+
ADAPTER_IDS.map((a) => Type.Literal(a)),
|
|
43
|
+
{
|
|
44
|
+
description:
|
|
45
|
+
'Adapter id. Editing is supported on "slack-bot", "slack", "discord-bot", "discord", "telegram-bot", ' +
|
|
46
|
+
'"webex", "webex-bot", and "teams" (Teams chats/DMs only — not team-channel posts).',
|
|
47
|
+
},
|
|
48
|
+
),
|
|
49
|
+
workspace: Type.String({
|
|
50
|
+
description:
|
|
51
|
+
'Discord guild id or Slack team id (e.g. "T0ACME"); use "@dm" for direct-message channels on either platform.',
|
|
52
|
+
minLength: 1,
|
|
53
|
+
}),
|
|
54
|
+
chat: Type.String({
|
|
55
|
+
description:
|
|
56
|
+
'Channel id the message lives in. Discord channel id (numeric snowflake) or Slack channel id (e.g. "C0CHANNEL", "D0DMID").',
|
|
57
|
+
minLength: 1,
|
|
58
|
+
}),
|
|
59
|
+
thread: Type.Optional(
|
|
60
|
+
Type.String({
|
|
61
|
+
description:
|
|
62
|
+
'Optional thread id the message lives in. Context only — the edit is addressed by `message_id`, so this is not required.',
|
|
63
|
+
minLength: 1,
|
|
64
|
+
}),
|
|
65
|
+
),
|
|
66
|
+
message_id: Type.String({
|
|
67
|
+
description:
|
|
68
|
+
'Platform-native id of the message to edit, as returned by a prior `channel_send` (Slack thread ts, Discord message id).',
|
|
69
|
+
minLength: 1,
|
|
70
|
+
}),
|
|
71
|
+
text: Type.String({
|
|
72
|
+
description: 'The new message body that fully replaces the current text.',
|
|
73
|
+
minLength: 1,
|
|
74
|
+
}),
|
|
75
|
+
}),
|
|
76
|
+
|
|
77
|
+
async execute(_toolCallId, params) {
|
|
78
|
+
const adapter = params.adapter as AdapterId
|
|
79
|
+
type DenyCode = NonNullable<(EditMessageResult & { ok: false })['code']>
|
|
80
|
+
const deny = (error: string, code?: DenyCode) => {
|
|
81
|
+
logger.warn(formatChannelToolFailure('channel_edit', error))
|
|
82
|
+
const details: { ok: false; error: string; code?: DenyCode } =
|
|
83
|
+
code !== undefined ? { ok: false, error, code } : { ok: false, error }
|
|
84
|
+
return {
|
|
85
|
+
content: [{ type: 'text' as const, text: `${TOOL_RESULT_PREFIX}channel_edit denied: ${error}` }],
|
|
86
|
+
details,
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const contentError = editTextGuardError(params.text)
|
|
91
|
+
if (contentError) return deny(contentError)
|
|
92
|
+
|
|
93
|
+
// Strip leaked `<think>` blocks before the edit reaches the router/adapter,
|
|
94
|
+
// exactly as the send path normalizes text. A replacement that is ONLY a
|
|
95
|
+
// think block leaves nothing to post, so deny rather than blank the message.
|
|
96
|
+
const text = stripThinkBlocks(params.text)
|
|
97
|
+
if (text === '') return deny('the replacement text is empty after removing reasoning blocks')
|
|
98
|
+
|
|
99
|
+
const result = await router.editMessage({
|
|
100
|
+
adapter,
|
|
101
|
+
workspace: params.workspace,
|
|
102
|
+
chat: params.chat,
|
|
103
|
+
...(params.thread !== undefined ? { thread: params.thread } : {}),
|
|
104
|
+
messageId: params.message_id,
|
|
105
|
+
text,
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
if (!result.ok) {
|
|
109
|
+
return deny(`${adapter}:${params.workspace}/${params.chat}: ${result.error}`, result.code)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const echo = renderOutboundEcho(text, undefined)
|
|
113
|
+
const receipt = `edited ${adapter}:${params.workspace}/${params.chat} message ${params.message_id}: ${echo}`
|
|
114
|
+
return {
|
|
115
|
+
content: [{ type: 'text' as const, text: fenceToolResult(receipt) }],
|
|
116
|
+
details: { ok: true },
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Same content guards channel_send runs, minus the send-only flood/dup/resolve
|
|
123
|
+
// logic: an edit is a mutation of an existing post, so the only shared risk is
|
|
124
|
+
// forwarding a control signal (NO_REPLY), the upstream empty-response sentinel
|
|
125
|
+
// (leaks thinking/signature), or raw provider tool-call delimiters as the new
|
|
126
|
+
// body. Blocked BEFORE the router call so the string never reaches the chat.
|
|
127
|
+
function editTextGuardError(text: string): string {
|
|
128
|
+
if (isNoReplySignal(text)) {
|
|
129
|
+
return '`NO_REPLY` is the silent-turn signal, not a message body. To edit a message, pass the replacement text.'
|
|
130
|
+
}
|
|
131
|
+
if (isUpstreamEmptyResponseSentinel(text)) {
|
|
132
|
+
return (
|
|
133
|
+
'refusing to forward an upstream `(Empty response: ...)` sentinel; ' +
|
|
134
|
+
"that string is a provider-SDK debug dump containing the model's thinking content and signature, not a message body."
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
if (containsKimiToolDelimiter(text)) {
|
|
138
|
+
return (
|
|
139
|
+
'refusing to forward raw provider tool-call control tokens; these are chat-template ' +
|
|
140
|
+
'delimiters that should have been parsed into a real tool call upstream.'
|
|
141
|
+
)
|
|
142
|
+
}
|
|
143
|
+
return ''
|
|
144
|
+
}
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { mkdir, writeFile } from 'node:fs/promises'
|
|
2
|
-
import { join } from 'node:path'
|
|
2
|
+
import { join, sep } from 'node:path'
|
|
3
3
|
|
|
4
4
|
import { Type } from '@mariozechner/pi-ai'
|
|
5
5
|
import { defineTool } from '@mariozechner/pi-coding-agent'
|
|
6
6
|
|
|
7
|
+
import type { SessionOrigin } from '@/agent/session-origin'
|
|
7
8
|
import type { ChannelRouter } from '@/channels/router'
|
|
8
9
|
import type { AdapterId } from '@/channels/schema'
|
|
10
|
+
import type { PermissionService } from '@/permissions'
|
|
11
|
+
import { resolveHiddenPaths } from '@/sandbox'
|
|
9
12
|
|
|
10
13
|
import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
|
|
11
14
|
|
|
@@ -16,28 +19,43 @@ export type ChannelFetchAttachmentOrigin = {
|
|
|
16
19
|
thread: string | null
|
|
17
20
|
}
|
|
18
21
|
|
|
22
|
+
type FetchAttachmentDetails = { ok: boolean; error?: string; path?: string; mimetype?: string; size?: number }
|
|
23
|
+
|
|
19
24
|
export type CreateChannelFetchAttachmentToolOptions = {
|
|
20
25
|
router: ChannelRouter
|
|
21
26
|
origin: ChannelFetchAttachmentOrigin
|
|
22
27
|
inboxDir?: string
|
|
28
|
+
// Resolved at execute time (role is a property of the live origin, not of
|
|
29
|
+
// construction), and wins over inboxDir/DEFAULT_INBOX_DIR. Lets the save
|
|
30
|
+
// location follow the caller's role so a role hidden from workspace/ never
|
|
31
|
+
// gets a file it can write but not read back (privateSurfaceRead would block
|
|
32
|
+
// its follow-up look_at/read). See buildChannelTools for the decision.
|
|
33
|
+
resolveBaseDir?: () => string
|
|
23
34
|
logger?: ChannelToolLogger
|
|
24
35
|
}
|
|
25
36
|
|
|
37
|
+
// workspace/ is private-surface: readable only by roles with fs.see.private.
|
|
26
38
|
export const DEFAULT_INBOX_DIR = '/agent/workspace/inbox'
|
|
39
|
+
// public/ is the guest-visible counterpart, so a redirected file stays readable
|
|
40
|
+
// back through look_at/read by the same role that fetched it.
|
|
41
|
+
export const PUBLIC_INBOX_DIR = '/agent/public/inbox'
|
|
27
42
|
|
|
28
43
|
export function createChannelFetchAttachmentTool({
|
|
29
44
|
router,
|
|
30
45
|
origin,
|
|
31
46
|
inboxDir,
|
|
47
|
+
resolveBaseDir,
|
|
32
48
|
logger = consoleChannelLogger,
|
|
33
49
|
}: CreateChannelFetchAttachmentToolOptions) {
|
|
34
|
-
const
|
|
50
|
+
const fallbackBaseDir = inboxDir ?? DEFAULT_INBOX_DIR
|
|
35
51
|
const adapter = origin.adapter
|
|
36
52
|
return defineTool({
|
|
37
53
|
name: 'channel_fetch_attachment',
|
|
38
54
|
label: 'Channel Fetch Attachment',
|
|
39
55
|
description:
|
|
40
|
-
'Download a file attached to a channel message and save it to disk.
|
|
56
|
+
'Download a file attached to a channel message and save it to disk. Use this only when you need the ' +
|
|
57
|
+
'file ON DISK (to edit it, re-upload it, or run a tool over it); to simply VIEW an image, use ' +
|
|
58
|
+
'`look_at_channel_attachment` instead — it returns a description without a disk write. Inbound channel ' +
|
|
41
59
|
'messages with attachments show `[<Platform> attachment #N: <kind> <metadata>]` in the text. Pass `N` as ' +
|
|
42
60
|
'`attachment_id`; do not invent ids that are not present in the message. The router resolves the private ' +
|
|
43
61
|
'platform ref itself. Attachments on the CURRENT inbound message resolve directly; for one from an EARLIER ' +
|
|
@@ -59,7 +77,6 @@ export function createChannelFetchAttachmentTool({
|
|
|
59
77
|
}),
|
|
60
78
|
|
|
61
79
|
async execute(_toolCallId, params) {
|
|
62
|
-
type Details = { ok: boolean; error?: string; path?: string; mimetype?: string; size?: number }
|
|
63
80
|
const found = router.lookupInboundAttachment({
|
|
64
81
|
adapter,
|
|
65
82
|
workspace: origin.workspace,
|
|
@@ -96,12 +113,13 @@ export function createChannelFetchAttachmentTool({
|
|
|
96
113
|
if (!result.ok) {
|
|
97
114
|
logger.warn(formatChannelToolFailure('channel_fetch_attachment', `${adapter}: ${result.error}`))
|
|
98
115
|
const text = `channel_fetch_attachment error: ${result.error}`
|
|
99
|
-
const details:
|
|
116
|
+
const details: FetchAttachmentDetails = { ok: false, error: result.error }
|
|
100
117
|
return { content: [{ type: 'text' as const, text }], details }
|
|
101
118
|
}
|
|
102
119
|
|
|
103
120
|
const safeFilename = sanitizeFilename(result.filename)
|
|
104
121
|
const refSlug = sanitizeRefSlug(ref)
|
|
122
|
+
const baseDir = resolveBaseDir?.() ?? fallbackBaseDir
|
|
105
123
|
const targetDir = join(baseDir, adapter, refSlug)
|
|
106
124
|
const targetPath = join(targetDir, safeFilename)
|
|
107
125
|
try {
|
|
@@ -111,13 +129,13 @@ export function createChannelFetchAttachmentTool({
|
|
|
111
129
|
const message = err instanceof Error ? err.message : String(err)
|
|
112
130
|
logger.warn(formatChannelToolFailure('channel_fetch_attachment', `${adapter}: write failed: ${message}`))
|
|
113
131
|
const text = `channel_fetch_attachment error: write failed: ${message}`
|
|
114
|
-
const details:
|
|
132
|
+
const details: FetchAttachmentDetails = { ok: false, error: `write failed: ${message}` }
|
|
115
133
|
return { content: [{ type: 'text' as const, text }], details }
|
|
116
134
|
}
|
|
117
135
|
|
|
118
136
|
const mimetypePart = result.mimetype !== undefined ? ` (${result.mimetype})` : ''
|
|
119
137
|
const text = `saved ${result.size} bytes to ${targetPath}${mimetypePart}`
|
|
120
|
-
const details:
|
|
138
|
+
const details: FetchAttachmentDetails = {
|
|
121
139
|
ok: true,
|
|
122
140
|
path: targetPath,
|
|
123
141
|
...(result.mimetype !== undefined ? { mimetype: result.mimetype } : {}),
|
|
@@ -128,8 +146,33 @@ export function createChannelFetchAttachmentTool({
|
|
|
128
146
|
})
|
|
129
147
|
}
|
|
130
148
|
|
|
149
|
+
// Picks the inbox root for the caller's live role. Reuses the guard's own
|
|
150
|
+
// deny-list resolution (resolveHiddenPaths) as the single source of truth, so
|
|
151
|
+
// the save location can never drift out of sync with what privateSurfaceRead
|
|
152
|
+
// will let the same role read back: if workspace/inbox lands under a hidden dir
|
|
153
|
+
// the file goes to the guest-visible public/ inbox instead.
|
|
154
|
+
//
|
|
155
|
+
// The hidden-check joins with the OS-native separator to stay byte-identical to
|
|
156
|
+
// resolveHiddenPaths' own dirs, but the RETURNED path is normalized to POSIX:
|
|
157
|
+
// this value names a location inside the Linux container (agentDir is /agent),
|
|
158
|
+
// so a win32 CI host must not leak backslashes into it.
|
|
159
|
+
export function resolveInboxBaseDir(
|
|
160
|
+
permissions: PermissionService,
|
|
161
|
+
origin: SessionOrigin | undefined,
|
|
162
|
+
agentDir: string,
|
|
163
|
+
): string {
|
|
164
|
+
const privateInbox = join(agentDir, 'workspace', 'inbox')
|
|
165
|
+
const { dirs } = resolveHiddenPaths(permissions, origin, agentDir)
|
|
166
|
+
const hidden = dirs.some((dir) => privateInbox === dir || privateInbox.startsWith(`${dir}${sep}`))
|
|
167
|
+
return toPosix(hidden ? join(agentDir, 'public', 'inbox') : privateInbox)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function toPosix(p: string): string {
|
|
171
|
+
return p.split(sep).join('/')
|
|
172
|
+
}
|
|
173
|
+
|
|
131
174
|
function errorResult(message: string) {
|
|
132
|
-
const details = { ok: false, error: message }
|
|
175
|
+
const details: FetchAttachmentDetails = { ok: false, error: message }
|
|
133
176
|
return { content: [{ type: 'text' as const, text: `channel_fetch_attachment error: ${message}` }], details }
|
|
134
177
|
}
|
|
135
178
|
|