typeclaw 0.48.2 → 0.48.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/scripts/dump-system-prompt.ts +146 -11
- package/src/agent/index.ts +35 -9
- package/src/agent/plugin-tools.ts +21 -0
- package/src/agent/todo/continuation-policy.ts +11 -1
- package/src/agent/todo/continuation-state.ts +3 -1
- package/src/agent/todo/continuation-wiring.ts +2 -0
- package/src/agent/tool-file-safety.ts +19 -3
- package/src/agent/tools/channel-reply.ts +18 -1
- package/src/agent/tools/runtime-notice.ts +29 -0
- package/src/bundled-plugins/github-cli-auth/git-command.ts +497 -652
- package/src/bundled-plugins/memory/load-memory.ts +23 -27
- package/src/bundled-plugins/security/index.ts +1 -0
- package/src/bundled-plugins/security/policies/private-surface-read.ts +152 -40
- package/src/channels/adapters/discord-bot-reactions.ts +1 -0
- package/src/channels/adapters/discord-bot.ts +11 -2
- package/src/channels/adapters/discord-reactions.ts +1 -0
- package/src/channels/adapters/discord.ts +1 -0
- package/src/channels/adapters/slack-bot.ts +11 -2
- package/src/channels/adapters/slack.ts +1 -0
- package/src/channels/completion-claim.ts +307 -0
- package/src/channels/router.ts +307 -102
- package/src/channels/types.ts +4 -1
- package/src/cli/hostd.ts +1 -1
- package/src/config/providers.ts +16 -10
- package/src/hostd/kakao-renewal-manager.ts +23 -11
- package/src/init/models-dev.ts +25 -8
- package/src/mcp/client.ts +65 -7
- package/src/mcp/tools.ts +71 -4
- package/src/permissions/index.ts +1 -0
- package/src/permissions/permissions.ts +23 -0
- package/src/plugin/index.ts +1 -0
- package/src/plugin/manager.ts +19 -1
- package/src/plugin/types.ts +9 -0
- package/src/sandbox/canonical-secrets.ts +24 -4
- package/src/sandbox/hidden-paths.ts +8 -3
- package/src/sandbox/index.ts +2 -0
- package/src/secrets/kakao-renewal.ts +123 -20
- package/src/skills/typeclaw-permissions/SKILL.md +13 -1
- package/src/skills/typeclaw-plugins/SKILL.md +91 -11
package/src/channels/types.ts
CHANGED
|
@@ -273,8 +273,11 @@ export type SendErrorCode =
|
|
|
273
273
|
// Optional throughout: an adapter whose SDK does not hand back an id (legacy
|
|
274
274
|
// slack/discord user-account adapters) omits both, and callers must treat a
|
|
275
275
|
// missing id as "not available", never as an error.
|
|
276
|
+
// `reactionRef` is the outbound message's adapter-owned TARGET ref — the entity
|
|
277
|
+
// a later ReactionRequest reacts to. It is explicitly NOT the per-reaction
|
|
278
|
+
// removal-instance ref returned by `ReactionResult.reactionRef` after an add.
|
|
276
279
|
export type SendResult =
|
|
277
|
-
| { ok: true; messageId?: string; messageIds?: readonly string[] }
|
|
280
|
+
| { ok: true; messageId?: string; messageIds?: readonly string[]; reactionRef?: ReactionRef }
|
|
278
281
|
| { ok: false; error: string; code?: SendErrorCode }
|
|
279
282
|
|
|
280
283
|
export type OutboundCallback = (msg: OutboundMessage) => Promise<SendResult>
|
package/src/cli/hostd.ts
CHANGED
|
@@ -254,7 +254,7 @@ function formatLog(event: DaemonLogEvent | SupervisorLogEvent): string {
|
|
|
254
254
|
case 'kakao-renewal-tick-skipped':
|
|
255
255
|
return `[hostd] kakao renewal skipped for ${event.containerName}: ${event.reason}${event.ageMs !== undefined ? ` (age=${Math.round(event.ageMs / 1000 / 60 / 60)}h)` : ''}`
|
|
256
256
|
case 'kakao-renewal-tick-ok':
|
|
257
|
-
return `[hostd] kakao renewal OK for ${event.containerName} account=${event.accountId} (was last updated ${event.previousUpdatedAt})`
|
|
257
|
+
return `[hostd] kakao renewal OK for ${event.containerName} account=${event.accountId}${event.method ? ` method=${event.method}` : ''} (was last updated ${event.previousUpdatedAt})`
|
|
258
258
|
case 'kakao-renewal-tick-reauth-required':
|
|
259
259
|
return `[hostd] kakao renewal REAUTH REQUIRED for ${event.containerName} account=${event.accountId} reason=${event.reason} — ${event.message}`
|
|
260
260
|
case 'kakao-renewal-tick-transient-failure':
|
package/src/config/providers.ts
CHANGED
|
@@ -781,14 +781,20 @@ export const KNOWN_PROVIDERS = {
|
|
|
781
781
|
// the console, the OpenAI-SDK example, and the agent docs all use bare `/v1`.
|
|
782
782
|
//
|
|
783
783
|
// Model lineup spans two families on the same Console API + key:
|
|
784
|
-
// * Closed chat models
|
|
785
|
-
//
|
|
786
|
-
//
|
|
787
|
-
//
|
|
788
|
-
// 2026-
|
|
789
|
-
// (31B,
|
|
790
|
-
//
|
|
791
|
-
//
|
|
784
|
+
// * Closed chat models, per the live model pages under
|
|
785
|
+
// console.upstage.ai/docs/models — solar-pro-4, solar-pro-3,
|
|
786
|
+
// solar-pro-2, solar-mini (the slugs are hyphenated; the unhyphenated
|
|
787
|
+
// form 404s): solar-pro4 (524288 context / 131072 output, released
|
|
788
|
+
// 2026-08-06, current flagship), solar-pro3 (102B MoE / 12B active,
|
|
789
|
+
// 128000), solar-pro2 (31B, 65536), solar-mini (10.7B, 32768,
|
|
790
|
+
// cheap/fast). The contextWindow values below are those exact
|
|
791
|
+
// documented figures. Upstage publishes NO maximum output length for
|
|
792
|
+
// pro3/pro2/mini, so their maxTokens are deliberate conservative
|
|
793
|
+
// choices of ours rather than sourced numbers — do not "correct" them
|
|
794
|
+
// against a third-party catalog that states one. The older agent API
|
|
795
|
+
// reference (console.upstage.ai/api/docs/for-agents) is stale
|
|
796
|
+
// (self-dated 2026-03-07) and omits pro4 — its absence there is not
|
|
797
|
+
// evidence the model is unavailable.
|
|
792
798
|
// * The open-weight Solar Open family: solar-open2 (Solar Open 2), a 102B
|
|
793
799
|
// MoE / 12B active model with a 128K context. It launched on the Console
|
|
794
800
|
// API for the Solar Agent Partner program (Stage 1, from 2026-07-17) —
|
|
@@ -965,7 +971,7 @@ export const KNOWN_PROVIDERS = {
|
|
|
965
971
|
},
|
|
966
972
|
input: ['text'],
|
|
967
973
|
cost: { input: 0.15, output: 0.6, cacheRead: 0.015, cacheWrite: 0 },
|
|
968
|
-
contextWindow:
|
|
974
|
+
contextWindow: 65536,
|
|
969
975
|
maxTokens: 16000,
|
|
970
976
|
compat: {
|
|
971
977
|
supportsStore: false,
|
|
@@ -985,7 +991,7 @@ export const KNOWN_PROVIDERS = {
|
|
|
985
991
|
reasoning: false,
|
|
986
992
|
input: ['text'],
|
|
987
993
|
cost: { input: 0.15, output: 0.15, cacheRead: 0, cacheWrite: 0 },
|
|
988
|
-
contextWindow:
|
|
994
|
+
contextWindow: 32768,
|
|
989
995
|
maxTokens: 8000,
|
|
990
996
|
compat: {
|
|
991
997
|
supportsStore: false,
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
renewCurrentAccount,
|
|
3
|
+
type AttemptLoginFn,
|
|
4
|
+
type RefreshOAuthTokenFn,
|
|
5
|
+
type RenewalMethod,
|
|
6
|
+
} from '@/secrets/kakao-renewal'
|
|
2
7
|
import { createKeyStore, type KeyStore } from '@/secrets/keys'
|
|
3
8
|
|
|
4
9
|
import { keysDir } from './paths'
|
|
@@ -19,7 +24,13 @@ export type KakaoRenewalStartInput = {
|
|
|
19
24
|
export type KakaoRenewalLogEvent =
|
|
20
25
|
| { kind: 'kakao-renewal-tick-start'; containerName: string }
|
|
21
26
|
| { kind: 'kakao-renewal-tick-skipped'; containerName: string; reason: string; ageMs?: number }
|
|
22
|
-
| {
|
|
27
|
+
| {
|
|
28
|
+
kind: 'kakao-renewal-tick-ok'
|
|
29
|
+
containerName: string
|
|
30
|
+
accountId: string
|
|
31
|
+
previousUpdatedAt: string
|
|
32
|
+
method?: RenewalMethod
|
|
33
|
+
}
|
|
23
34
|
| {
|
|
24
35
|
kind: 'kakao-renewal-tick-reauth-required'
|
|
25
36
|
containerName: string
|
|
@@ -37,13 +48,12 @@ export type KakaoRenewalManagerOptions = {
|
|
|
37
48
|
tickIntervalMs?: number
|
|
38
49
|
keyStoreFactory?: () => KeyStore
|
|
39
50
|
attemptLogin?: AttemptLoginFn
|
|
51
|
+
refreshOAuthToken?: RefreshOAuthTokenFn
|
|
40
52
|
schedule?: (fn: () => void, intervalMs: number) => { stop: () => void }
|
|
41
|
-
// Invoked after a successful renewal so the host can
|
|
42
|
-
// and the in-memory
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
// wires this to the same restart path the `restart` RPC uses; tests can
|
|
46
|
-
// observe it via a fake.
|
|
53
|
+
// Invoked after a successful renewal so the host can hot-reload the adapter
|
|
54
|
+
// and the in-memory LOCO client picks up the fresh tokens. Production falls
|
|
55
|
+
// back to recreating the container only when the reload transport fails;
|
|
56
|
+
// tests can observe the callback via a fake.
|
|
47
57
|
onRenewalOk?: (input: { containerName: string; cwd: string; accountId: string }) => Promise<void>
|
|
48
58
|
// Optional predicate: only start the renewal cron for containers whose
|
|
49
59
|
// `typeclaw.json` actually has a `channels.kakaotalk` block. Without this,
|
|
@@ -74,8 +84,8 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
|
|
|
74
84
|
// one finishes. The Map's value is the most recent input.
|
|
75
85
|
const latestInput = new Map<string, KakaoRenewalStartInput>()
|
|
76
86
|
// Track in-flight tick promises per container so stop()/drain() can await
|
|
77
|
-
// them. Without this, daemon shutdown abandons an in-flight
|
|
78
|
-
//
|
|
87
|
+
// them. Without this, daemon shutdown abandons an in-flight renewal HTTPS
|
|
88
|
+
// request mid-write.
|
|
79
89
|
const inFlight = new Map<string, Promise<void>>()
|
|
80
90
|
// Pending immediate-tick request: set when start() is called while a tick
|
|
81
91
|
// is in flight, so we re-fire one tick after the in-flight settles.
|
|
@@ -89,6 +99,7 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
|
|
|
89
99
|
agentDir: input.cwd,
|
|
90
100
|
keyStore,
|
|
91
101
|
...(opts.attemptLogin ? { attemptLogin: opts.attemptLogin } : {}),
|
|
102
|
+
...(opts.refreshOAuthToken ? { refreshOAuthToken: opts.refreshOAuthToken } : {}),
|
|
92
103
|
})
|
|
93
104
|
if (result.kind === 'skipped') {
|
|
94
105
|
log({
|
|
@@ -103,9 +114,10 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
|
|
|
103
114
|
containerName: input.containerName,
|
|
104
115
|
accountId: result.account_id,
|
|
105
116
|
previousUpdatedAt: result.previousUpdatedAt,
|
|
117
|
+
method: result.method,
|
|
106
118
|
})
|
|
107
119
|
// A tick that started before stop()/drain() (deregister, shutdown) or
|
|
108
|
-
// before a re-register with a different cwd can finish the slow
|
|
120
|
+
// before a re-register with a different cwd can finish the slow renewal
|
|
109
121
|
// here. Restarting a container that is no longer the current
|
|
110
122
|
// registration would resurrect a just-deregistered agent or fight a
|
|
111
123
|
// shutdown, so skip onRenewalOk unless this container+cwd is still the
|
package/src/init/models-dev.ts
CHANGED
|
@@ -38,9 +38,12 @@ const PROVIDER_TO_MODELS_DEV: Record<KnownProviderId, string | null> = {
|
|
|
38
38
|
xai: 'xai',
|
|
39
39
|
minimax: 'minimax',
|
|
40
40
|
deepseek: 'deepseek',
|
|
41
|
-
//
|
|
42
|
-
//
|
|
43
|
-
//
|
|
41
|
+
// models.dev has listed Upstage since 2025-07-09 (solar-pro2 + solar-mini,
|
|
42
|
+
// then solar-pro3 on 2026-01-13 and solar-pro4 on 2026-08-06), so this
|
|
43
|
+
// mapping hits rather than misses — harmless either way, since `buildOption`
|
|
44
|
+
// lets upstream fill gaps but never override the curated Solar records, and
|
|
45
|
+
// those specify every field. solar-open2 is partner-program only and still
|
|
46
|
+
// absent upstream, so it surfaces curated.
|
|
44
47
|
upstage: 'upstage',
|
|
45
48
|
moonshot: 'moonshot',
|
|
46
49
|
// moonshot-coding (Kimi Code subscription) is a billing surface, not a
|
|
@@ -303,6 +306,19 @@ type BuildOptionOpts = {
|
|
|
303
306
|
upstream?: ModelsDevModel
|
|
304
307
|
}
|
|
305
308
|
|
|
309
|
+
// The curated record wins every field it specifies; upstream only fills gaps.
|
|
310
|
+
// A known ref always resolves to the curated record at runtime — `resolveModel`
|
|
311
|
+
// reads `KNOWN_PROVIDERS`, never models.dev, and `customModelMetaFromOption`
|
|
312
|
+
// declines to persist metadata for known refs — so letting upstream win here
|
|
313
|
+
// only desynchronized the picker from the model it was describing. It showed in
|
|
314
|
+
// what `formatModelLabel`/`formatModelHint` render (name, context, reasoning):
|
|
315
|
+
// models.dev names solar-pro3/pro2/mini with their bare ids, so the picker
|
|
316
|
+
// offered "solar-pro3" where the curated record says "Solar Pro 3". maxTokens
|
|
317
|
+
// and cost reach no surface today, so aligning them is consistency within the
|
|
318
|
+
// record, not a visible fix. `supportsVision` already resolved this way (see
|
|
319
|
+
// `resolveInput`, and the note on `ModelOption.supportsVision`); this extends
|
|
320
|
+
// the rule to the rest. Refs we do not curate still take everything from
|
|
321
|
+
// upstream, which is the whole point of merging it in.
|
|
306
322
|
function buildOption(ref: ModelRef | string, opts: BuildOptionOpts): ModelOption {
|
|
307
323
|
const providerId = providerForModelRef(ref)
|
|
308
324
|
const modelId = ref.slice(providerId.length + 1)
|
|
@@ -316,6 +332,7 @@ function buildOption(ref: ModelRef | string, opts: BuildOptionOpts): ModelOption
|
|
|
316
332
|
maxTokens?: number
|
|
317
333
|
reasoning?: boolean
|
|
318
334
|
input?: ReadonlyArray<string>
|
|
335
|
+
cost?: ModelOptionCost
|
|
319
336
|
}
|
|
320
337
|
>
|
|
321
338
|
)[modelId]
|
|
@@ -325,11 +342,11 @@ function buildOption(ref: ModelRef | string, opts: BuildOptionOpts): ModelOption
|
|
|
325
342
|
providerId,
|
|
326
343
|
providerName: provider.name,
|
|
327
344
|
modelId,
|
|
328
|
-
modelName:
|
|
329
|
-
reasoning:
|
|
330
|
-
contextWindow: opts.upstream?.limit?.context ??
|
|
331
|
-
maxTokens: opts.upstream?.limit?.output ??
|
|
332
|
-
cost: resolveCost(opts.upstream?.cost),
|
|
345
|
+
modelName: curatedModel?.name ?? opts.upstream?.name ?? modelId,
|
|
346
|
+
reasoning: curatedModel?.reasoning ?? opts.upstream?.reasoning ?? false,
|
|
347
|
+
contextWindow: curatedModel?.contextWindow ?? opts.upstream?.limit?.context ?? null,
|
|
348
|
+
maxTokens: curatedModel?.maxTokens ?? opts.upstream?.limit?.output ?? null,
|
|
349
|
+
cost: curatedModel?.cost ?? resolveCost(opts.upstream?.cost),
|
|
333
350
|
curated: opts.curated,
|
|
334
351
|
supportsVision: input.includes('image'),
|
|
335
352
|
}
|
package/src/mcp/client.ts
CHANGED
|
@@ -7,14 +7,24 @@ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
|
|
|
7
7
|
import { CallToolResultSchema, type CallToolResult, type ListToolsRequest } from '@modelcontextprotocol/sdk/types.js'
|
|
8
8
|
|
|
9
9
|
import type { McpServer } from '@/config/config'
|
|
10
|
+
import type { ToolFileOperands } from '@/plugin'
|
|
10
11
|
import { resolveSecret } from '@/secrets/resolve'
|
|
11
12
|
|
|
12
13
|
export type McpToolInfo = {
|
|
13
14
|
name: string
|
|
14
15
|
description: string
|
|
15
16
|
inputSchema: unknown
|
|
17
|
+
// Declared by MCP servers via the tool's `_meta['x-file-operands']`; consumed
|
|
18
|
+
// by the mcp_call dispatcher so the file-operand scanner honors tool-authored
|
|
19
|
+
// nonFile operand paths instead of rejecting free-text args that look path-shaped.
|
|
20
|
+
fileOperands?: ToolFileOperands
|
|
16
21
|
}
|
|
17
22
|
|
|
23
|
+
// The wire key an MCP server sets on a tool's `_meta` to declare its operands.
|
|
24
|
+
// `_meta` is an arbitrary record in the MCP spec and survives the server → wire
|
|
25
|
+
// → client round-trip through the official SDK unchanged.
|
|
26
|
+
export const MCP_FILE_OPERANDS_META_KEY = 'x-file-operands'
|
|
27
|
+
|
|
18
28
|
// The SDK defaults each request to 60s; typeclaw boot should fail fast enough
|
|
19
29
|
// that one dead MCP server does not make the agent feel hung at startup.
|
|
20
30
|
export const DEFAULT_MCP_REQUEST_TIMEOUT_MS = 30_000
|
|
@@ -23,17 +33,56 @@ export const DEFAULT_MCP_CONNECT_TIMEOUT_MS = 15_000
|
|
|
23
33
|
export type McpConnection = {
|
|
24
34
|
name: string
|
|
25
35
|
listTools(): Promise<McpToolInfo[]>
|
|
36
|
+
// Cache-only view of the last successful listTools(). Returns undefined until
|
|
37
|
+
// the catalog has been fetched once, and never performs I/O — the pre-execution
|
|
38
|
+
// file-operand preflight reads target metadata through this so resolving it can
|
|
39
|
+
// never spawn a stdio server or open an HTTP session before the security hooks run.
|
|
40
|
+
peekTools(): McpToolInfo[] | undefined
|
|
26
41
|
refresh(): Promise<McpToolInfo[]>
|
|
27
42
|
callTool(toolName: string, args?: Record<string, unknown>): Promise<CallToolResult>
|
|
28
43
|
close(): Promise<void>
|
|
29
44
|
}
|
|
30
45
|
|
|
46
|
+
const FILE_OPERAND_CATEGORIES = ['input', 'output', 'create', 'destructive', 'nonFile'] as const
|
|
47
|
+
|
|
48
|
+
// Wire metadata is server-controlled, so it is parsed rather than cast: a
|
|
49
|
+
// declaration like `{ nonFile: 'query' }` would otherwise reach the scanner as a
|
|
50
|
+
// string and have `.includes()` grant a substring-wide exemption. Any malformed
|
|
51
|
+
// recognized category discards the WHOLE declaration (fail closed) instead of
|
|
52
|
+
// honoring the well-formed remainder, so a partially-corrupt payload can never
|
|
53
|
+
// silently widen the scanned surface.
|
|
54
|
+
export function parseDeclaredFileOperands(meta: Record<string, unknown> | undefined): ToolFileOperands | undefined {
|
|
55
|
+
if (typeof meta !== 'object' || meta === null) return undefined
|
|
56
|
+
const declared = meta[MCP_FILE_OPERANDS_META_KEY]
|
|
57
|
+
if (typeof declared !== 'object' || declared === null || Array.isArray(declared)) return undefined
|
|
58
|
+
|
|
59
|
+
const parsed: Record<string, readonly string[]> = {}
|
|
60
|
+
const claimed = new Set<string>()
|
|
61
|
+
for (const category of FILE_OPERAND_CATEGORIES) {
|
|
62
|
+
const value = (declared as Record<string, unknown>)[category]
|
|
63
|
+
if (value === undefined) continue
|
|
64
|
+
if (!Array.isArray(value)) return undefined
|
|
65
|
+
if (!value.every((entry) => typeof entry === 'string' && entry.trim() !== '')) return undefined
|
|
66
|
+
// One operand path cannot be two things at once, and the combinations are
|
|
67
|
+
// not merely redundant but contradictory: `nonFile` claims a value is never
|
|
68
|
+
// dereferenced locally while `input` claims it is a real file to snapshot.
|
|
69
|
+
// Resolving such a conflict by precedence would make the effective policy
|
|
70
|
+
// depend on category order, so reject the declaration instead.
|
|
71
|
+
for (const operandPath of value as string[]) {
|
|
72
|
+
if (claimed.has(operandPath)) return undefined
|
|
73
|
+
claimed.add(operandPath)
|
|
74
|
+
}
|
|
75
|
+
parsed[category] = [...(value as string[])]
|
|
76
|
+
}
|
|
77
|
+
return Object.keys(parsed).length === 0 ? undefined : (parsed as ToolFileOperands)
|
|
78
|
+
}
|
|
79
|
+
|
|
31
80
|
export type McpSdkClient = {
|
|
32
81
|
listTools(
|
|
33
82
|
params?: ListToolsRequest['params'],
|
|
34
83
|
options?: RequestOptions,
|
|
35
84
|
): Promise<{
|
|
36
|
-
tools: { name: string; description?: string; inputSchema: unknown }[]
|
|
85
|
+
tools: { name: string; description?: string; inputSchema: unknown; _meta?: Record<string, unknown> }[]
|
|
37
86
|
nextCursor?: string
|
|
38
87
|
}>
|
|
39
88
|
callTool(
|
|
@@ -108,11 +157,15 @@ export function createMcpConnection(
|
|
|
108
157
|
signal: opts.signal,
|
|
109
158
|
})
|
|
110
159
|
tools.push(
|
|
111
|
-
...result.tools.map((tool) =>
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
160
|
+
...result.tools.map((tool) => {
|
|
161
|
+
const fileOperands = parseDeclaredFileOperands(tool._meta)
|
|
162
|
+
return {
|
|
163
|
+
name: tool.name,
|
|
164
|
+
description: tool.description ?? '',
|
|
165
|
+
inputSchema: tool.inputSchema,
|
|
166
|
+
...(fileOperands === undefined ? {} : { fileOperands }),
|
|
167
|
+
}
|
|
168
|
+
}),
|
|
116
169
|
)
|
|
117
170
|
cursor = result.nextCursor
|
|
118
171
|
} while (cursor !== undefined)
|
|
@@ -127,8 +180,13 @@ export function createMcpConnection(
|
|
|
127
180
|
if (cachedTools !== undefined) return cachedTools
|
|
128
181
|
return fetchTools()
|
|
129
182
|
},
|
|
183
|
+
peekTools(): McpToolInfo[] | undefined {
|
|
184
|
+
return cachedTools
|
|
185
|
+
},
|
|
186
|
+
// fetchTools never reads the cache, so the previous catalog is kept until a
|
|
187
|
+
// replacement is in hand: a failed or in-flight refresh must not blank out the
|
|
188
|
+
// metadata that peekTools() serves to the pre-execution operand preflight.
|
|
130
189
|
refresh(): Promise<McpToolInfo[]> {
|
|
131
|
-
cachedTools = undefined
|
|
132
190
|
return fetchTools()
|
|
133
191
|
},
|
|
134
192
|
callTool(toolName: string, args?: Record<string, unknown>): Promise<CallToolResult> {
|
package/src/mcp/tools.ts
CHANGED
|
@@ -2,8 +2,10 @@ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
|
|
|
2
2
|
import { z } from 'zod'
|
|
3
3
|
|
|
4
4
|
import { enforceAndPinToolFiles } from '@/agent/tool-file-safety'
|
|
5
|
+
import { checkPrivateSurfaceReadGuard } from '@/bundled-plugins/security/policies/private-surface-read'
|
|
5
6
|
import { defineTool } from '@/plugin/define'
|
|
6
|
-
import type { ContentPart, Tool, ToolResult } from '@/plugin/types'
|
|
7
|
+
import type { ContentPart, Tool, ToolFileOperands, ToolResult } from '@/plugin/types'
|
|
8
|
+
import type { HiddenPaths } from '@/sandbox'
|
|
7
9
|
|
|
8
10
|
import type { McpConnection, McpToolInfo } from './client'
|
|
9
11
|
import type { McpManager } from './manager'
|
|
@@ -17,8 +19,45 @@ export type McpCallArgs = { server: string; tool: string; args?: Record<string,
|
|
|
17
19
|
export type McpDispatcherTool = Tool<McpListToolsArgs> | Tool<McpDescribeArgs> | Tool<McpCallArgs>
|
|
18
20
|
export type McpDispatcherTools = [Tool<McpListToolsArgs>, Tool<McpDescribeArgs>, Tool<McpCallArgs>]
|
|
19
21
|
|
|
20
|
-
export function createMcpDispatcherTools(
|
|
21
|
-
|
|
22
|
+
export function createMcpDispatcherTools(
|
|
23
|
+
manager: McpManager,
|
|
24
|
+
opts: { resolveHidden: () => HiddenPaths },
|
|
25
|
+
): McpDispatcherTools {
|
|
26
|
+
return [createListToolsTool(manager), createDescribeTool(manager), createCallTool(manager, opts)]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// `wrapSystemTool` runs the security hooks — including the fail-closed
|
|
30
|
+
// private-surface-read scan — against the whole `{ server, tool, args }` envelope
|
|
31
|
+
// BEFORE the dispatcher body resolves the target, so without this preflight a
|
|
32
|
+
// target-declared free-text operand is scanned as an undeclared path and blocked
|
|
33
|
+
// for a restricted role.
|
|
34
|
+
//
|
|
35
|
+
// EVERY category is surfaced, not just `nonFile`. `nonFile` relaxes the scan, so
|
|
36
|
+
// alone it could only ever weaken the guard; the local categories are what let
|
|
37
|
+
// the guard scan a declared real-file operand that a prose-named key (`query`,
|
|
38
|
+
// `content`, ...) would otherwise exempt. Surfacing one without the other is the
|
|
39
|
+
// bypass. This is security metadata only: it is never forwarded to a pinning
|
|
40
|
+
// boundary, so pinning still happens exactly once, at the dispatcher's inner-args
|
|
41
|
+
// boundary below.
|
|
42
|
+
//
|
|
43
|
+
// The lookup is cache-only. Connecting here would spawn an MCP server before the
|
|
44
|
+
// security hooks have run; a cold catalog yields undefined, which keeps the
|
|
45
|
+
// existing fail-closed scan.
|
|
46
|
+
export function resolveMcpCallPreflightFileOperands(
|
|
47
|
+
manager: McpManager,
|
|
48
|
+
args: Record<string, unknown>,
|
|
49
|
+
): ToolFileOperands | undefined {
|
|
50
|
+
if (typeof args.server !== 'string' || typeof args.tool !== 'string') return undefined
|
|
51
|
+
const resolved = resolveToolArgs(args.server, args.tool)
|
|
52
|
+
const declared = manager.getConnection(resolved.server)?.peekTools()
|
|
53
|
+
const fileOperands = declared?.find((item) => item.name === resolved.tool)?.fileOperands
|
|
54
|
+
if (fileOperands === undefined) return undefined
|
|
55
|
+
const rebased: Record<string, readonly string[]> = {}
|
|
56
|
+
for (const [category, paths] of Object.entries(fileOperands)) {
|
|
57
|
+
if (paths === undefined || paths.length === 0) continue
|
|
58
|
+
rebased[category] = paths.map((operandPath) => `args.${operandPath}`)
|
|
59
|
+
}
|
|
60
|
+
return Object.keys(rebased).length === 0 ? undefined : (rebased as ToolFileOperands)
|
|
22
61
|
}
|
|
23
62
|
|
|
24
63
|
function createListToolsTool(manager: McpManager): Tool<McpListToolsArgs> {
|
|
@@ -80,7 +119,7 @@ function createDescribeTool(manager: McpManager): Tool<McpDescribeArgs> {
|
|
|
80
119
|
})
|
|
81
120
|
}
|
|
82
121
|
|
|
83
|
-
function createCallTool(manager: McpManager): Tool<McpCallArgs> {
|
|
122
|
+
function createCallTool(manager: McpManager, opts: { resolveHidden: () => HiddenPaths }): Tool<McpCallArgs> {
|
|
84
123
|
return defineTool<McpCallArgs>({
|
|
85
124
|
description: 'Call an MCP tool on a connected server. Use mcp_describe first to learn the input schema.',
|
|
86
125
|
parameters: z.object({
|
|
@@ -94,11 +133,28 @@ function createCallTool(manager: McpManager): Tool<McpCallArgs> {
|
|
|
94
133
|
if (connection === undefined) return textResult(unknownServerMessage(manager, resolved.server))
|
|
95
134
|
|
|
96
135
|
const toolArgs = args.args ?? {}
|
|
136
|
+
const targetFileOperands = await declaredFileOperands(connection, resolved.tool)
|
|
137
|
+
// Scoped to targets that actually declare operands. The cold-catalog gap
|
|
138
|
+
// this closes requires a declaration by definition: without one the outer
|
|
139
|
+
// envelope guard already scanned these values under the same role, and the
|
|
140
|
+
// generic fail-closed scan below stays the authority on undeclared ones —
|
|
141
|
+
// including its more precise "ambiguous local file operand" rejection.
|
|
142
|
+
if (targetFileOperands !== undefined) {
|
|
143
|
+
const blocked = checkPrivateSurfaceReadGuard({
|
|
144
|
+
tool: 'mcp_call',
|
|
145
|
+
args: toolArgs,
|
|
146
|
+
agentDir: ctx.agentDir,
|
|
147
|
+
hidden: opts.resolveHidden(),
|
|
148
|
+
fileOperands: targetFileOperands,
|
|
149
|
+
})
|
|
150
|
+
if (blocked !== undefined) throw new Error(`blocked: ${blocked.reason}`)
|
|
151
|
+
}
|
|
97
152
|
const pinned = await enforceAndPinToolFiles({
|
|
98
153
|
tool: 'mcp_call',
|
|
99
154
|
args: toolArgs,
|
|
100
155
|
agentDir: ctx.agentDir,
|
|
101
156
|
genericInputs: true,
|
|
157
|
+
...(targetFileOperands === undefined ? {} : { fileOperands: targetFileOperands }),
|
|
102
158
|
logger: ctx.logger,
|
|
103
159
|
signal: ctx.signal,
|
|
104
160
|
})
|
|
@@ -129,6 +185,17 @@ function unknownServerMessage(manager: McpManager, server: string): string {
|
|
|
129
185
|
return `Unknown MCP server ${JSON.stringify(server)}. Available servers: ${available || 'none'}.`
|
|
130
186
|
}
|
|
131
187
|
|
|
188
|
+
// Operand paths here are relative to the target's own schema, matching the inner
|
|
189
|
+
// `args.args` scan; a catalog failure degrades to the fail-closed generic scan
|
|
190
|
+
// rather than aborting, and safeCallTool surfaces the real transport error.
|
|
191
|
+
async function declaredFileOperands(connection: McpConnection, tool: string): Promise<ToolFileOperands | undefined> {
|
|
192
|
+
try {
|
|
193
|
+
return (await connection.listTools()).find((item) => item.name === tool)?.fileOperands
|
|
194
|
+
} catch {
|
|
195
|
+
return undefined
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
132
199
|
async function safeListTools(connection: McpConnection): Promise<McpToolInfo[]> {
|
|
133
200
|
try {
|
|
134
201
|
return await connection.listTools()
|
package/src/permissions/index.ts
CHANGED
|
@@ -99,6 +99,29 @@ export function findUnknownPermissions(
|
|
|
99
99
|
return out
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
+
// The mirror of findUnknownPermissions. `definePlugin({ permissions })`
|
|
103
|
+
// registers a string but grants nothing, so a plugin gating a surface on a
|
|
104
|
+
// fresh id without a matching `roles.<role>.permissions[]` entry is denied
|
|
105
|
+
// for EVERY caller including owner -- previously with no signal until the
|
|
106
|
+
// block fired at call time. Non-fatal: withholding a capability is a valid
|
|
107
|
+
// operator choice.
|
|
108
|
+
//
|
|
109
|
+
// Resolves the role table rather than reading raw config because
|
|
110
|
+
// expandOwnerWildcard auto-flows a plugin's `security.bypass.*` strings to
|
|
111
|
+
// owner; reading config would report every one of them as ungranted.
|
|
112
|
+
export function findUngrantedPluginPermissions(
|
|
113
|
+
roles: RolesConfig | undefined,
|
|
114
|
+
pluginPermissions: readonly string[],
|
|
115
|
+
ownerWildcardExclusions: readonly string[] = [],
|
|
116
|
+
): string[] {
|
|
117
|
+
if (pluginPermissions.length === 0) return []
|
|
118
|
+
const granted = new Set<string>()
|
|
119
|
+
for (const role of buildRoleTable(roles ?? {}, pluginPermissions, ownerWildcardExclusions)) {
|
|
120
|
+
for (const permission of role.permissions) granted.add(permission)
|
|
121
|
+
}
|
|
122
|
+
return pluginPermissions.filter((permission) => !granted.has(permission))
|
|
123
|
+
}
|
|
124
|
+
|
|
102
125
|
function closestPermission(target: string, known: ReadonlySet<string>): string {
|
|
103
126
|
let best: { name: string; distance: number } | null = null
|
|
104
127
|
for (const name of known) {
|
package/src/plugin/index.ts
CHANGED
package/src/plugin/manager.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { ResolveGithubTokenForRepo } from '@/channels/github-token-bridge'
|
|
|
4
4
|
import type { CronJob } from '@/cron'
|
|
5
5
|
import {
|
|
6
6
|
createPermissionService,
|
|
7
|
+
findUngrantedPluginPermissions,
|
|
7
8
|
findUnknownPermissions,
|
|
8
9
|
type PermissionService,
|
|
9
10
|
type RolesConfig,
|
|
@@ -154,9 +155,10 @@ export async function loadPlugins(opts: LoadPluginsOptions): Promise<LoadPlugins
|
|
|
154
155
|
// captured `permissions` by reference (their hooks read it at request time),
|
|
155
156
|
// so we mutate that same object in place rather than returning a new one.
|
|
156
157
|
const declaredPermissions = collectDeclaredPermissions(survivors)
|
|
158
|
+
const ownerWildcardExclusions = collectOwnerWildcardExclusions(survivors)
|
|
157
159
|
permissions.replacePluginPermissions?.({
|
|
158
160
|
pluginPermissions: declaredPermissions,
|
|
159
|
-
ownerWildcardExclusions
|
|
161
|
+
ownerWildcardExclusions,
|
|
160
162
|
})
|
|
161
163
|
|
|
162
164
|
// Non-fatal: surface user-declared `permissions[]` strings that aren't in
|
|
@@ -171,6 +173,22 @@ export async function loadPlugins(opts: LoadPluginsOptions): Promise<LoadPlugins
|
|
|
171
173
|
)
|
|
172
174
|
}
|
|
173
175
|
|
|
176
|
+
// The opposite direction, and the one that silently ships dead code: the
|
|
177
|
+
// plugin declared a permission but no role grants it, so every surface
|
|
178
|
+
// gated on it is denied for all callers. Without this the only symptom is
|
|
179
|
+
// a `missing permission` block at call time, long after the boot that
|
|
180
|
+
// could have explained it.
|
|
181
|
+
for (const permission of findUngrantedPluginPermissions(opts.roles, declaredPermissions, ownerWildcardExclusions)) {
|
|
182
|
+
const declaredBy = survivors
|
|
183
|
+
.filter((p) => p.resolved.defined.permissions?.includes(permission))
|
|
184
|
+
.map((p) => p.resolved.name)
|
|
185
|
+
.join(', ')
|
|
186
|
+
console.warn(
|
|
187
|
+
`[permissions] plugin "${declaredBy}" declares "${permission}" but no role grants it — ` +
|
|
188
|
+
`every surface gated on it will be denied. Add it to roles.<role>.permissions[] in typeclaw.json and restart.`,
|
|
189
|
+
)
|
|
190
|
+
}
|
|
191
|
+
|
|
174
192
|
return {
|
|
175
193
|
registry,
|
|
176
194
|
hooks,
|
package/src/plugin/types.ts
CHANGED
|
@@ -220,12 +220,21 @@ export type SessionPromptEvent = {
|
|
|
220
220
|
|
|
221
221
|
// Fired for plugin-defined tools and TypeClaw-exposed system tools, including
|
|
222
222
|
// built-in pi tools (read/bash/edit/write/grep/find/ls) when plugins are wired.
|
|
223
|
+
//
|
|
224
|
+
// Set exclusively by TypeClaw's tool wrappers before a tool.before hook runs.
|
|
225
|
+
// Tool names and arguments are model/plugin controlled, so guards must not use
|
|
226
|
+
// either as evidence that a call is first-party.
|
|
227
|
+
export type ToolProvenance = 'first-party' | 'plugin'
|
|
228
|
+
|
|
223
229
|
export type ToolBeforeEvent = {
|
|
224
230
|
tool: string
|
|
225
231
|
sessionId: string
|
|
226
232
|
callId: string
|
|
227
233
|
args: Record<string, unknown>
|
|
228
234
|
origin?: SessionOrigin
|
|
235
|
+
// Internal wrapper-authenticated provenance. Omitted only by direct callers;
|
|
236
|
+
// guards must treat an omitted value as untrusted.
|
|
237
|
+
toolProvenance?: ToolProvenance
|
|
229
238
|
// The tool author's operand declarations (never model-controlled — set on the
|
|
230
239
|
// static Tool definition at registration). Carried so a guard that runs before
|
|
231
240
|
// the file-operand scanner (private-surface-read) can honor the same
|
|
@@ -3,16 +3,36 @@ import {
|
|
|
3
3
|
LEGACY_AGENT_MESSENGER_CONFIG_RELATIVE_DIR,
|
|
4
4
|
} from '@/agent-messenger/config-dir'
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
// Runtime-owned credential stores: TypeClaw writes and reads these itself, and
|
|
7
|
+
// no shipped skill ever invokes a CLI that reads them. Masked at EVERY role.
|
|
8
|
+
export const RUNTIME_OWNED_SECRET_DIRS = [
|
|
9
9
|
// Retained permanently for interrupted migrations, operator backups under
|
|
10
|
-
// the old name, and older installs. This is not an active config location
|
|
10
|
+
// the old name, and older installs. This is not an active config location,
|
|
11
|
+
// so nothing an operator provisions today lands here.
|
|
11
12
|
LEGACY_AGENT_MESSENGER_CONFIG_RELATIVE_DIR,
|
|
12
13
|
'.typeclaw/home',
|
|
13
14
|
'.typeclaw/logs',
|
|
14
15
|
] as const
|
|
15
16
|
|
|
17
|
+
// SECURITY / classification: operator-provisioned CLI credential stores. TypeClaw
|
|
18
|
+
// writes these through its own init/auth flows and points the matching CLI at them
|
|
19
|
+
// (`dockerfile.ts` bakes `ENV AGENT_MESSENGER_CONFIG_DIR`), so the agent is MEANT
|
|
20
|
+
// to read them — the bundled `agent-*` and gws skills shell out to CLIs that
|
|
21
|
+
// resolve exactly these files. Masking them at every role does not withhold a
|
|
22
|
+
// secret, it breaks the skill and leaves the CLI reporting its own "not
|
|
23
|
+
// authenticated", which a model relays as a fact about the upstream service.
|
|
24
|
+
//
|
|
25
|
+
// So they take the ordinary private-surface role gate, which is what applied to
|
|
26
|
+
// them before they were named here (they live under `workspace/`). Add a path
|
|
27
|
+
// here only if a shipped skill needs to read it; anything that must stay hidden
|
|
28
|
+
// from every role belongs in `secrets.json`, not in a masked directory.
|
|
29
|
+
export const OPERATOR_CLI_CREDENTIAL_DIRS = ['workspace/.config/gws', AGENT_MESSENGER_CONFIG_RELATIVE_DIR] as const
|
|
30
|
+
|
|
31
|
+
// Union: every directory that is masked for SOME role. Consumers that need the
|
|
32
|
+
// full set regardless of gating (write-zone vetoes, hardlink-alias scanning)
|
|
33
|
+
// use this; consumers that must respect the gate read the two lists above.
|
|
34
|
+
export const CANONICAL_AGENT_SECRET_DIRS = [...OPERATOR_CLI_CREDENTIAL_DIRS, ...RUNTIME_OWNED_SECRET_DIRS] as const
|
|
35
|
+
|
|
16
36
|
export const CANONICAL_AGENT_SECRET_FILES = ['.env', 'secrets.json', 'auth.json'] as const
|
|
17
37
|
|
|
18
38
|
// Trusted runtime processes use this ephemeral container HOME. bwrap builds an
|
|
@@ -5,7 +5,12 @@ import type { SessionOrigin } from '@/agent/session-origin'
|
|
|
5
5
|
import { CORE_PERMISSIONS } from '@/permissions/builtins'
|
|
6
6
|
import type { PermissionService } from '@/permissions/permissions'
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
CANONICAL_AGENT_SECRET_DIRS,
|
|
10
|
+
CANONICAL_AGENT_SECRET_FILES,
|
|
11
|
+
OPERATOR_CLI_CREDENTIAL_DIRS,
|
|
12
|
+
RUNTIME_OWNED_SECRET_DIRS,
|
|
13
|
+
} from './canonical-secrets'
|
|
9
14
|
import { SandboxMaskTargetError } from './errors'
|
|
10
15
|
import { CANONICAL_AGENT_RUNTIME_PRIVATE_FILES } from './runtime-private'
|
|
11
16
|
|
|
@@ -36,8 +41,8 @@ export function resolveHiddenPaths(
|
|
|
36
41
|
): HiddenPaths {
|
|
37
42
|
const seesPrivate = canSeePrivateSurface(permissions, origin)
|
|
38
43
|
const dirs = [
|
|
39
|
-
...
|
|
40
|
-
...(seesPrivate ? [] : PRIVATE_DIRS.map((dir) => join(agentDir, dir))),
|
|
44
|
+
...RUNTIME_OWNED_SECRET_DIRS.map((dir) => join(agentDir, dir)),
|
|
45
|
+
...(seesPrivate ? [] : [...OPERATOR_CLI_CREDENTIAL_DIRS, ...PRIVATE_DIRS].map((dir) => join(agentDir, dir))),
|
|
41
46
|
]
|
|
42
47
|
const files = [...CANONICAL_AGENT_SECRET_FILES, ...CANONICAL_AGENT_RUNTIME_PRIVATE_FILES].map((f) =>
|
|
43
48
|
join(agentDir, f),
|
package/src/sandbox/index.ts
CHANGED
|
@@ -5,6 +5,8 @@ export {
|
|
|
5
5
|
CANONICAL_HOME_SECRET_DIRS,
|
|
6
6
|
CANONICAL_HOME_SECRET_FILES,
|
|
7
7
|
CONTAINER_RUNTIME_HOME,
|
|
8
|
+
OPERATOR_CLI_CREDENTIAL_DIRS,
|
|
9
|
+
RUNTIME_OWNED_SECRET_DIRS,
|
|
8
10
|
} from './canonical-secrets'
|
|
9
11
|
export { CANONICAL_AGENT_RUNTIME_PRIVATE_FILES } from './runtime-private'
|
|
10
12
|
export {
|