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.
Files changed (40) hide show
  1. package/package.json +2 -2
  2. package/scripts/dump-system-prompt.ts +146 -11
  3. package/src/agent/index.ts +35 -9
  4. package/src/agent/plugin-tools.ts +21 -0
  5. package/src/agent/todo/continuation-policy.ts +11 -1
  6. package/src/agent/todo/continuation-state.ts +3 -1
  7. package/src/agent/todo/continuation-wiring.ts +2 -0
  8. package/src/agent/tool-file-safety.ts +19 -3
  9. package/src/agent/tools/channel-reply.ts +18 -1
  10. package/src/agent/tools/runtime-notice.ts +29 -0
  11. package/src/bundled-plugins/github-cli-auth/git-command.ts +497 -652
  12. package/src/bundled-plugins/memory/load-memory.ts +23 -27
  13. package/src/bundled-plugins/security/index.ts +1 -0
  14. package/src/bundled-plugins/security/policies/private-surface-read.ts +152 -40
  15. package/src/channels/adapters/discord-bot-reactions.ts +1 -0
  16. package/src/channels/adapters/discord-bot.ts +11 -2
  17. package/src/channels/adapters/discord-reactions.ts +1 -0
  18. package/src/channels/adapters/discord.ts +1 -0
  19. package/src/channels/adapters/slack-bot.ts +11 -2
  20. package/src/channels/adapters/slack.ts +1 -0
  21. package/src/channels/completion-claim.ts +307 -0
  22. package/src/channels/router.ts +307 -102
  23. package/src/channels/types.ts +4 -1
  24. package/src/cli/hostd.ts +1 -1
  25. package/src/config/providers.ts +16 -10
  26. package/src/hostd/kakao-renewal-manager.ts +23 -11
  27. package/src/init/models-dev.ts +25 -8
  28. package/src/mcp/client.ts +65 -7
  29. package/src/mcp/tools.ts +71 -4
  30. package/src/permissions/index.ts +1 -0
  31. package/src/permissions/permissions.ts +23 -0
  32. package/src/plugin/index.ts +1 -0
  33. package/src/plugin/manager.ts +19 -1
  34. package/src/plugin/types.ts +9 -0
  35. package/src/sandbox/canonical-secrets.ts +24 -4
  36. package/src/sandbox/hidden-paths.ts +8 -3
  37. package/src/sandbox/index.ts +2 -0
  38. package/src/secrets/kakao-renewal.ts +123 -20
  39. package/src/skills/typeclaw-permissions/SKILL.md +13 -1
  40. package/src/skills/typeclaw-plugins/SKILL.md +91 -11
@@ -1,6 +1,11 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { attemptLogin as upstreamAttemptLogin, type KakaoDeviceType } from 'agent-messenger/kakaotalk'
3
+ import {
4
+ attemptLogin as upstreamAttemptLogin,
5
+ KakaoOAuthRefreshError,
6
+ type KakaoDeviceType,
7
+ refreshKakaoOAuthToken as upstreamRefreshKakaoOAuthToken,
8
+ } from 'agent-messenger/kakaotalk'
4
9
 
5
10
  import { decrypt, EncryptionError } from './encryption'
6
11
  import { SecretsKakaoCredentialStore } from './kakao-store'
@@ -15,26 +20,44 @@ export const RENEWAL_THRESHOLD_MS = 5 * 24 * 60 * 60 * 1000
15
20
  // for cron skips (host asleep, daemon respawning, etc.) and to absorb any
16
21
  // downward drift in KakaoTalk's actual TTL.
17
22
 
23
+ type ReauthDecision = {
24
+ kind: 'reauth_required'
25
+ reason: 'no_password' | 'no_email' | 'key_missing' | 'decrypt_failed'
26
+ message: string
27
+ }
28
+
29
+ type PasswordRenewalDecision =
30
+ | ReauthDecision
31
+ | { kind: 'should_renew'; method: 'password'; account: AccountSnapshot & { email: string }; password: string }
32
+
18
33
  export type RenewalDecision =
19
34
  | { kind: 'skip'; reason: 'no_account' | 'fresh_enough'; ageMs?: number }
20
- | { kind: 'reauth_required'; reason: 'no_password' | 'no_email' | 'key_missing' | 'decrypt_failed'; message: string }
21
- | { kind: 'should_renew'; account: AccountSnapshot; password: string }
35
+ | ReauthDecision
36
+ | { kind: 'should_renew'; method: 'oauth_refresh'; account: AccountSnapshot }
37
+ | PasswordRenewalDecision
22
38
 
23
39
  export type AccountSnapshot = {
24
40
  account_id: string
25
- email: string
41
+ oauth_token: string
42
+ user_id: string
43
+ refresh_token?: string
26
44
  device_uuid: string
27
45
  device_type: KakaoDeviceType
46
+ auth_method?: 'login' | 'extract'
28
47
  created_at: string
29
48
  updated_at: string
49
+ email?: string
30
50
  }
31
51
 
52
+ export type RenewalMethod = 'oauth_refresh' | 'password'
53
+
32
54
  export type RenewalAttempt =
33
- | { kind: 'ok'; account_id: string; previousUpdatedAt: string; nextUpdatedAt: string }
55
+ | { kind: 'ok'; account_id: string; previousUpdatedAt: string; nextUpdatedAt: string; method: RenewalMethod }
34
56
  | { kind: 'reauth_required'; account_id: string; reason: string; message: string }
35
57
  | { kind: 'transient_failure'; account_id: string; reason: string }
36
58
 
37
59
  export type AttemptLoginFn = typeof upstreamAttemptLogin
60
+ export type RefreshOAuthTokenFn = typeof upstreamRefreshKakaoOAuthToken
38
61
 
39
62
  export type RenewalContext = {
40
63
  containerName: string
@@ -42,6 +65,7 @@ export type RenewalContext = {
42
65
  keyStore: KeyStore
43
66
  now?: () => number
44
67
  attemptLogin?: AttemptLoginFn
68
+ refreshOAuthToken?: RefreshOAuthTokenFn
45
69
  }
46
70
 
47
71
  export async function decideRenewal(block: KakaoChannelBlock, ctx: RenewalContext): Promise<RenewalDecision> {
@@ -56,42 +80,64 @@ export async function decideRenewal(block: KakaoChannelBlock, ctx: RenewalContex
56
80
  return { kind: 'skip', reason: 'fresh_enough', ageMs }
57
81
  }
58
82
 
83
+ const snapshot = snapshotAccount(account)
84
+ if (account.refresh_token !== undefined) {
85
+ return { kind: 'should_renew', method: 'oauth_refresh', account: snapshot }
86
+ }
87
+
88
+ return decidePasswordRenewal(snapshot, account.encryptedPassword, ctx)
89
+ }
90
+
91
+ function snapshotAccount(account: KakaoChannelBlock['accounts'][string]): AccountSnapshot {
92
+ return {
93
+ account_id: account.account_id,
94
+ oauth_token: account.oauth_token,
95
+ user_id: account.user_id,
96
+ ...(account.refresh_token !== undefined ? { refresh_token: account.refresh_token } : {}),
97
+ device_uuid: account.device_uuid,
98
+ device_type: account.device_type,
99
+ ...(account.auth_method !== undefined ? { auth_method: account.auth_method } : {}),
100
+ created_at: account.created_at,
101
+ updated_at: account.updated_at,
102
+ ...(account.email !== undefined ? { email: account.email } : {}),
103
+ }
104
+ }
105
+
106
+ async function decidePasswordRenewal(
107
+ account: AccountSnapshot,
108
+ encryptedPassword: KakaoChannelBlock['accounts'][string]['encryptedPassword'],
109
+ ctx: RenewalContext,
110
+ ): Promise<PasswordRenewalDecision> {
59
111
  if (!account.email) {
60
112
  return {
61
113
  kind: 'reauth_required',
62
114
  reason: 'no_email',
63
- message: `KakaoTalk account ${accountId} has no stored email — run \`typeclaw channel reauth kakaotalk\`.`,
115
+ message: `KakaoTalk account ${account.account_id} has no stored email — run \`typeclaw channel reauth kakaotalk\`.`,
64
116
  }
65
117
  }
66
- if (!account.encryptedPassword) {
118
+ if (!encryptedPassword) {
67
119
  return {
68
120
  kind: 'reauth_required',
69
121
  reason: 'no_password',
70
- message: `KakaoTalk account ${accountId} has no stored password — run \`typeclaw channel reauth kakaotalk\`.`,
122
+ message: `KakaoTalk account ${account.account_id} has no stored password — run \`typeclaw channel reauth kakaotalk\`.`,
71
123
  }
72
124
  }
73
125
 
74
126
  let plaintextPassword: string
75
127
  try {
76
128
  const key = await ctx.keyStore.read(ctx.containerName)
77
- plaintextPassword = decrypt(account.encryptedPassword, key, {
129
+ plaintextPassword = decrypt(encryptedPassword, key, {
78
130
  containerName: ctx.containerName,
79
131
  accountId: account.account_id,
80
132
  })
81
133
  } catch (err) {
82
- return classifyDecryptFailure(err, accountId)
134
+ return classifyDecryptFailure(err, account.account_id)
83
135
  }
84
136
 
85
137
  return {
86
138
  kind: 'should_renew',
87
- account: {
88
- account_id: account.account_id,
89
- email: account.email,
90
- device_uuid: account.device_uuid,
91
- device_type: account.device_type,
92
- created_at: account.created_at,
93
- updated_at: account.updated_at,
94
- },
139
+ method: 'password',
140
+ account: { ...account, email: account.email },
95
141
  password: plaintextPassword,
96
142
  }
97
143
  }
@@ -103,7 +149,7 @@ export async function renewCurrentAccount(
103
149
  const backend = new SecretsBackend(secretsPath)
104
150
  const block = backend.readChannelsSync()?.kakaotalk
105
151
  const parsed = parseBlockOrEmpty(block)
106
- const decision = await decideRenewal(parsed, ctx)
152
+ let decision = await decideRenewal(parsed, ctx)
107
153
 
108
154
  if (decision.kind === 'skip') {
109
155
  return {
@@ -121,6 +167,62 @@ export async function renewCurrentAccount(
121
167
  }
122
168
  }
123
169
 
170
+ if (decision.method === 'oauth_refresh') {
171
+ const refreshOAuthToken = ctx.refreshOAuthToken ?? upstreamRefreshKakaoOAuthToken
172
+ try {
173
+ const refreshed = await refreshOAuthToken({
174
+ accessToken: decision.account.oauth_token,
175
+ refreshToken: decision.account.refresh_token ?? '',
176
+ deviceUuid: decision.account.device_uuid,
177
+ })
178
+ const store = new SecretsKakaoCredentialStore({ mode: 'host', secretsPath })
179
+ const nowIso = new Date().toISOString()
180
+ await store.setAccount({
181
+ account_id: decision.account.account_id,
182
+ oauth_token: refreshed.accessToken,
183
+ user_id: decision.account.user_id,
184
+ refresh_token: refreshed.refreshToken,
185
+ device_uuid: decision.account.device_uuid,
186
+ device_type: decision.account.device_type,
187
+ ...(decision.account.auth_method !== undefined ? { auth_method: decision.account.auth_method } : {}),
188
+ created_at: decision.account.created_at,
189
+ updated_at: nowIso,
190
+ })
191
+ return {
192
+ kind: 'ok',
193
+ account_id: decision.account.account_id,
194
+ previousUpdatedAt: decision.account.updated_at,
195
+ nextUpdatedAt: nowIso,
196
+ method: 'oauth_refresh',
197
+ }
198
+ } catch (err) {
199
+ // Only a rejected or incomplete refresh credential justifies the heavier
200
+ // password login. Transport/server failures keep the refresh token in
201
+ // place and retry next tick rather than risk a passcode or captcha prompt.
202
+ if (
203
+ !(err instanceof KakaoOAuthRefreshError) ||
204
+ (err.code !== 'refresh_rejected' && err.code !== 'refresh_credentials_missing')
205
+ ) {
206
+ return {
207
+ kind: 'transient_failure',
208
+ account_id: decision.account.account_id,
209
+ reason: err instanceof Error ? err.message : String(err),
210
+ }
211
+ }
212
+
213
+ const account = parsed.accounts[decision.account.account_id]
214
+ decision = await decidePasswordRenewal(decision.account, account?.encryptedPassword, ctx)
215
+ if (decision.kind === 'reauth_required') {
216
+ return {
217
+ kind: 'reauth_required',
218
+ account_id: parsed.currentAccount ?? '',
219
+ reason: decision.reason,
220
+ message: decision.message,
221
+ }
222
+ }
223
+ }
224
+ }
225
+
124
226
  const attemptLogin = ctx.attemptLogin ?? upstreamAttemptLogin
125
227
  const result = await attemptLogin(
126
228
  decision.account.email,
@@ -166,6 +268,7 @@ export async function renewCurrentAccount(
166
268
  account_id: decision.account.account_id,
167
269
  previousUpdatedAt: decision.account.updated_at,
168
270
  nextUpdatedAt: nowIso,
271
+ method: 'password',
169
272
  }
170
273
  }
171
274
 
@@ -174,7 +277,7 @@ function parseBlockOrEmpty(value: unknown): KakaoChannelBlock {
174
277
  return value as KakaoChannelBlock
175
278
  }
176
279
 
177
- function classifyDecryptFailure(err: unknown, accountId: string): RenewalDecision {
280
+ function classifyDecryptFailure(err: unknown, accountId: string): ReauthDecision {
178
281
  if (err instanceof KeyStoreError) {
179
282
  if (err.code === 'missing') {
180
283
  return {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: typeclaw-permissions
3
- description: Use this skill whenever the user asks who you talk to, why you went silent in a channel, why a tool call was blocked with `blocked:` / "denied by permissions", how to grant access, what a role can or can't do, or whenever you are about to edit the `roles` block in `typeclaw.json`. Triggers include "who can talk to you", "why aren't you replying in #channel", "add me to the agent", "let X talk to you", "grant trusted to Y", "your role", "what permissions do you have", "blocked", "denied by permissions", "owner", "trusted", "member", "guest", "match rule", "channel.respond", "security.bypass", "scheduledByRole", "spawnedByRole", or any mention of `roles` / `roles[*].match` / `roles[*].permissions` in `typeclaw.json`. Read it before editing `roles` — the file has a strict match-rule DSL, restart semantics, and silent failure modes (a missing role match makes you silently drop every inbound), and the agent's own runtime behavior depends on its role and resolved permissions.
3
+ description: Use this skill whenever the user asks who you talk to, why you went silent in a channel, why a tool call was blocked with `blocked:` / "denied by permissions", how to grant access, what a role can or can't do, or whenever you are about to edit the `roles` block in `typeclaw.json`. Triggers include "who can talk to you", "why aren't you replying in #channel", "add me to the agent", "let X talk to you", "grant trusted to Y", "your role", "what permissions do you have", "blocked", "denied by permissions", "owner", "trusted", "member", "guest", "match rule", "channel.respond", "security.bypass", "scheduledByRole", "spawnedByRole", "missing permission", "plugin permission", "always denied", or any mention of `roles` / `roles[*].match` / `roles[*].permissions` in `typeclaw.json`. Read it before editing `roles` — the file has a strict match-rule DSL, restart semantics, and silent failure modes (a missing role match makes you silently drop every inbound), and the agent's own runtime behavior depends on its role and resolved permissions.
4
4
  ---
5
5
 
6
6
  # typeclaw-permissions
@@ -134,6 +134,18 @@ Note on the two-step `gitRemoteTainted` defense: trusted bypasses `gitExfil` via
134
134
 
135
135
  User-declared `permissions[]` strings that don't appear in any of the three sources are **logged as warnings at boot** (`[permissions] role "X" declares unknown permission "Y" — did you mean 'Z'?`) but the role still resolves with the unknown string in its list. This is intentional — the runtime is forward-compatible with strings from plugins that aren't loaded yet — but it also means typos silently fail to bypass guards. If you wrote `security.bypass.secretExfilBach` instead of `Bash`, no guard will be skipped and you will only notice when you read the boot logs.
136
136
 
137
+ ### The mirror failure: a plugin permission no role grants
138
+
139
+ The typo case above is a role naming a permission that doesn't exist. The opposite also happens: a plugin declares a permission via `definePlugin({ permissions: [...] })` (see `typeclaw-plugins`), but no role's `permissions[]` in `typeclaw.json` ever lists it. Declaring a permission only registers the string into the known-permission universe — it does not grant it. The only strings that auto-flow to a role are `security.bypass.*` ones, and only to `owner`, via the wildcard sentinel. Every other plugin-declared string starts out held by **nobody** — not owner, not trusted, not member, not guest.
140
+
141
+ **Symptom**: a plugin tool or command fails every call, for every user including owner, with a message naming the id — `missing permission: <id>`, or a `blocked:` reason citing it. Unlike a security-guard block, there's no acknowledgement and no role that already has it to fall back to; the string simply isn't granted anywhere.
142
+
143
+ **Boot signal**: `[permissions] plugin "<name>" declares "<id>" but no role grants it — every surface gated on it will be denied. Add it to roles.<role>.permissions[] in typeclaw.json and restart.`
144
+
145
+ **Fix**: add the exact string to `roles.<role>.permissions[]` and restart — same restart-required rule as every other `permissions[]` edit in this file. If `<role>` is a built-in (`owner`/`trusted`/`member`), remember an explicit `permissions[]` replaces that role's default list wholesale (see the table above); re-list the role's full default set alongside the new string, or the role silently loses `channel.respond` and everything else.
146
+
147
+ See `typeclaw-plugins` for the authoring side of this — declaring and gating on a permission is a two-part recipe, and shipping the declaration without the grant leaves a surface that looks wired but is dead.
148
+
137
149
  ## When a tool is blocked
138
150
 
139
151
  The security plugin's `tool.before` hook produces block messages. For most guards the message is:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: typeclaw-plugins
3
- description: TypeClaw plugin authoring and operation guide. Use when writing, editing, configuring, debugging, or installing a TypeClaw plugin — including any work with definePlugin, defineTool, defineSubagent, plugin hooks (session.start/end/idle/prompt, tool.before/after), plugin cron jobs, plugin commands (host/container/either CLI subcommands callable as `typeclaw <name>`), plugin skills, the typeclaw/plugin import path, or per-plugin config blocks in typeclaw.json. Also use when you need to bridge a cron `exec` job to LLM-driven work — the canonical pattern is a `surface: 'container'` plugin command whose `run` calls `ctx.prompt(...)`, invoked as `typeclaw <command>` from cron's `command` array. Triggers on mentions of 'TypeClaw plugin', 'definePlugin', 'plugin hook', 'plugin cron', 'plugin command', 'PluginCommand', 'ContainerCommand', 'HostCommand', 'EitherCommand', 'ctx.prompt', 'ctx.subagent', 'ctx.exec', 'plugins[]', 'typeclaw-plugin-', or any file under src/plugin/ or plugins/.
3
+ description: TypeClaw plugin authoring and operation guide. Use when writing, editing, configuring, debugging, or installing a TypeClaw plugin — including any work with definePlugin, defineTool, defineSubagent, plugin hooks (session.start/end/idle/prompt, tool.before/after), plugin cron jobs, plugin commands (host/container/either CLI subcommands callable as `typeclaw <name>`), plugin skills, the typeclaw/plugin import path, or per-plugin config blocks in typeclaw.json. Also use when you need to bridge a cron `exec` job to LLM-driven work — the canonical pattern is a `surface: 'container'` plugin command whose `run` calls `ctx.prompt(...)`, invoked as `typeclaw <command>` from cron's `command` array. Triggers on mentions of 'TypeClaw plugin', 'definePlugin', 'plugin hook', 'plugin cron', 'plugin command', 'PluginCommand', 'ContainerCommand', 'HostCommand', 'EitherCommand', 'ctx.prompt', 'ctx.subagent', 'ctx.exec', 'plugins[]', 'typeclaw-plugin-', 'plugin permission', 'definePlugin permissions', 'missing permission', 'permission-gated tool', or any file under src/plugin/ or plugins/.
4
4
  ---
5
5
 
6
6
  # TypeClaw Plugins
@@ -203,6 +203,7 @@ tools: {
203
203
  - Args are **validated once** before `tool.before` hooks see them — no double-parse. Hooks receive `event.args` as a **mutable bag** (`Record<string, unknown>`); mutations propagate to later hooks and to `execute`.
204
204
  - `ToolContext` is **stripped down** to `{ signal, sessionId, agentDir, logger }`. It does NOT expose the engine's `ExtensionContext`. If your tool wants `read`/`bash`/etc., it cannot call them — declare a subagent with `tools: [readTool, ...]` instead.
205
205
  - `ToolResult.content` uses TypeClaw's `ContentPart` union: `{ type: 'text'; text }` or `{ type: 'image'; mimeType; data }`.
206
+ - Tools have **no `permissions` field**. To gate one per role, declare the string on the plugin and block from a `tool.before` hook — and grant it in `typeclaw.json`, or the tool is dead for every caller. See "`permissions: [...]` — declaring and gating" in §5.7.
206
207
 
207
208
  #### Declare every filesystem operand
208
209
 
@@ -330,7 +331,7 @@ type CronHandlerContext = {
330
331
  readonly agentDir: string // /agent in container
331
332
  readonly logger: PluginLogger
332
333
  readonly signal: AbortSignal // reserved for future cancellation; currently inert
333
- readonly permissions: PermissionService
334
+ readonly permissions: PermissionService // live service — has() gating, see "permissions: [...] — declaring and gating" in §5.7 below
334
335
  readonly origin: SessionOrigin // { kind: 'cron', jobKind: 'handler', ... }
335
336
  readonly prompt: (text: string) => Promise<string> // full agent session, slim system prompt mode
336
337
  readonly subagent: (name, payload?) => Promise<void>
@@ -481,7 +482,7 @@ type ContainerCommandContext = {
481
482
  readonly version: string | undefined
482
483
  readonly agentDir: string // /agent inside the container
483
484
  readonly logger: PluginLogger
484
- readonly permissions: PermissionService
485
+ readonly permissions: PermissionService // live service — has() gating, see "permissions: [...] — declaring and gating" below
485
486
  readonly origin: SessionOrigin // caller's origin — cron job, TUI op, etc.
486
487
  readonly signal: AbortSignal // aborts on ws close or host Ctrl-C
487
488
  readonly stdin: ReadableStream<Uint8Array>
@@ -579,20 +580,98 @@ args: z.object({
579
580
  - `.describe(...)` populates `--help` output. Use it.
580
581
  - Omit `args` entirely if the command takes no flags.
581
582
 
582
- #### `permissions: [...]` on the command
583
+ #### `permissions: [...]` — declaring and gating
584
+
585
+ **Declaring a permission grants it to nobody.** `definePlugin({ permissions: [...] })` only registers the string into the known-permission universe — used for the boot-time typo warning and, for `security.bypass.*` strings only, owner-wildcard expansion. Every other permission string starts out held by no role: not owner, not trusted, not member, not guest. A plugin that gates a command or tool on a permission and never adds that string to any `roles.<role>.permissions[]` in `typeclaw.json` has shipped a permanently blocked surface — declaring is half the work, granting is the other half. Never ship one without the other.
586
+
587
+ **`definePlugin({ permissions })` is the only declaration that does anything.** `ContainerCommand.permissions` exists in the type but no production path reads it — it is not rendered in `--help` (`renderCommandHelp` prints description, plugin, surface, options), not collected into the known-permission universe (`collectDeclaredPermissions` reads only the plugin-level list), and never checked for you. Declare at the plugin level. Setting it on a command instead is worse than useless: the string stays outside the known universe, so granting it in a role also trips the `unknown permission` typo warning at boot.
588
+
589
+ **Gating a command** — declare the string on the plugin, then check it inside `run`:
583
590
 
584
591
  ```ts
592
+ const WRITE_PERMISSION = 'standup.write.entry'
593
+
594
+ export default definePlugin({
595
+ permissions: [WRITE_PERMISSION],
596
+ commands: {
597
+ standup: {
598
+ surface: 'container',
599
+ description: 'Append a standup entry.',
600
+ async run(ctx, args) {
601
+ if (!ctx.permissions.has(ctx.origin, WRITE_PERMISSION)) {
602
+ const writer = ctx.stderr.getWriter()
603
+ await writer.write(new TextEncoder().encode(`missing permission: ${WRITE_PERMISSION}\n`))
604
+ writer.releaseLock()
605
+ return 1
606
+ }
607
+ // ...
608
+ return 0
609
+ },
610
+ },
611
+ },
612
+ plugin: async () => ({}),
613
+ })
614
+ ```
615
+
616
+ ```jsonc
617
+ // typeclaw.json — the grant this declaration needs, or the command always fails
585
618
  {
586
- surface: 'container',
587
- permissions: ['standup-log.write.standup'],
588
- async run(ctx, args) {
589
- ctx.permissions.assert(ctx.origin, 'standup-log.write.standup')
590
- // ...
619
+ "roles": {
620
+ "trusted": {
621
+ "permissions": ["standup.write.entry" /* ...trusted's full default list too, see below */],
622
+ },
591
623
  },
592
624
  }
593
625
  ```
594
626
 
595
- Declared permissions are surfaced in `--help` and (for container commands) checked against the caller's origin. Same `<plugin>.<verb>.<noun>` shape as the rest of the permission system; see `typeclaw-permissions`.
627
+ `PermissionService` exposes `has(origin, permission)` — a boolean. **There is no `assert`.** Nothing authorizes on your behalf: `has` resolves the caller's origin to a role and returns false unless that role's permission list contains the exact string, and it is on you to fail the call. Same `<plugin>.<verb>.<noun>` shape as the rest of the permission system; see `typeclaw-permissions`.
628
+
629
+ **Permission ids cannot contain hyphens.** `roles[].permissions[]` validates against `^[a-z][a-z0-9]*(\.[a-z][a-zA-Z0-9]*)+$` — dot-separated segments, each starting lowercase, alphanumeric after (camelCase is fine, `-` is not). Nothing validates the `definePlugin({ permissions })` side, so a hyphenated id like `standup-log.write.entry` declares happily and then **cannot be granted at all**: the config edit fails schema validation. A hyphenated plugin name needs a hyphen-free permission namespace — plugin `standup-log` uses `standup.write.entry`.
630
+
631
+ **Gating a tool** — tools have no `permissions` field of their own; gate them from a `tool.before` hook with `pluginContext.permissions.has(event.origin, ...)`:
632
+
633
+ ```ts
634
+ const PUBLISH_PERMISSION = 'standup.publish.remote'
635
+
636
+ export default definePlugin({
637
+ permissions: [PUBLISH_PERMISSION],
638
+ plugin: async (pluginContext) => ({
639
+ tools: {
640
+ standup_publish: defineTool({
641
+ /* ... */
642
+ }),
643
+ },
644
+ hooks: {
645
+ 'tool.before': (event) => {
646
+ if (event.tool !== 'standup_publish') return
647
+ if (pluginContext.permissions.has(event.origin, PUBLISH_PERMISSION)) return
648
+ return { block: true, reason: `missing permission: ${PUBLISH_PERMISSION}` }
649
+ },
650
+ },
651
+ }),
652
+ })
653
+ ```
654
+
655
+ ```jsonc
656
+ // typeclaw.json — same recipe: declaring PUBLISH_PERMISSION above grants nothing on its own
657
+ {
658
+ "roles": {
659
+ "trusted": {
660
+ "permissions": ["standup.publish.remote" /* ...trusted's full default list too, see below */],
661
+ },
662
+ },
663
+ }
664
+ ```
665
+
666
+ Omit that second half and the failure is silent and total: the plugin compiles, boots, and registers the tool, but every call — including from `owner` — is blocked forever, because nothing ever granted the string. The tool looks wired and is dead.
667
+
668
+ **Built-in roles: an explicit `permissions[]` REPLACES the default, it does not add to it.** Add your string to `roles.owner.permissions[]` and you must re-list `owner`'s entire default permission set alongside it, including the `security.bypass.*` strings the wildcard sentinel would otherwise expand for you (the sentinel is an internal runtime value — you cannot write it, and the schema rejects it). Don't copy the default lists from memory; read `typeclaw-permissions` for the current per-role defaults.
669
+
670
+ **Restart required.** `roles.<role>.permissions[]` is a `restart-required` field — `typeclaw reload` will not pick up a new grant. `roles.<role>.match[]` is live-reloadable; permissions are not. Run `typeclaw restart`.
671
+
672
+ **The boot-time signal for a forgotten grant**: `[permissions] plugin "<name>" declares "<id>" but no role grants it — every surface gated on it will be denied. Add it to roles.<role>.permissions[] in typeclaw.json and restart.` If you see this at boot, or a tool/command you just wired is blocked for every caller including yourself, this is why.
673
+
674
+ **When NOT to declare a permission.** If your plugin is the only caller of the surface it gates — no operator will ever want to withhold or grant this capability per role — the check is just an `if (false)` with extra steps. Declare a permission only when you actually want an operator able to grant or withhold it per role.
596
675
 
597
676
  #### `isolated: true` (container surface only)
598
677
 
@@ -631,6 +710,7 @@ type PluginContext<TConfig = never> = {
631
710
  readonly agentDir: string // absolute, agent folder root
632
711
  readonly config: TConfig // inferred from configSchema
633
712
  readonly logger: PluginLogger // prefixed: [plugin:<name>]
713
+ readonly permissions: PermissionService // live service — has() gating, see "permissions: [...] — declaring and gating" in §5.7 above
634
714
  spawnSubagent: (name: string, payload?: unknown) => Promise<void>
635
715
  }
636
716
  ```
@@ -872,7 +952,7 @@ export default definePlugin({
872
952
  commands: {
873
953
  /* name: { surface, run, args?, ... } */
874
954
  }, // optional, declared BY-VALUE (not inside factory)
875
- permissions: ['my-plugin.write.x'], // optional
955
+ permissions: ['myplugin.write.x'], // optional; declares only — grant it in roles.<role>.permissions[] in typeclaw.json or nobody has it
876
956
  plugin: async (ctx) => ({
877
957
  // required
878
958
  tools,