typeclaw 0.45.1 → 0.46.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +161 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +207 -0
  11. package/src/agent/plugin-tools.ts +377 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1310 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +163 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +30 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/README.md +23 -10
  32. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  33. package/src/bundled-plugins/backup/index.ts +85 -44
  34. package/src/bundled-plugins/backup/runner.ts +85 -1
  35. package/src/bundled-plugins/doc-render/render.ts +93 -12
  36. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  37. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  38. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  39. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  40. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  41. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  42. package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
  43. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  44. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  45. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  46. package/src/bundled-plugins/memory/README.md +32 -11
  47. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  48. package/src/bundled-plugins/memory/citations.ts +22 -9
  49. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  50. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  51. package/src/bundled-plugins/memory/index.ts +0 -4
  52. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  53. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  54. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  55. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  56. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  57. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  58. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  59. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  60. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  61. package/src/bundled-plugins/researcher/write-report.ts +8 -5
  62. package/src/bundled-plugins/reviewer/index.ts +2 -2
  63. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  64. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  65. package/src/bundled-plugins/scout/scout.ts +8 -0
  66. package/src/bundled-plugins/security/index.ts +4 -4
  67. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  68. package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
  69. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  70. package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
  71. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  72. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  73. package/src/channels/adapters/discord-bot.ts +66 -6
  74. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  75. package/src/channels/adapters/discord-id.ts +4 -0
  76. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  77. package/src/channels/adapters/discord.ts +57 -7
  78. package/src/channels/adapters/github/auth-app.ts +41 -12
  79. package/src/channels/adapters/github/inbound.ts +11 -0
  80. package/src/channels/adapters/github/index.ts +71 -65
  81. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  82. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  83. package/src/channels/adapters/github/review-submitter.ts +302 -0
  84. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  85. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  86. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  87. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  88. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  89. package/src/channels/adapters/slack-bot.ts +26 -10
  90. package/src/channels/adapters/slack-classify.ts +21 -2
  91. package/src/channels/adapters/slack-format.ts +245 -0
  92. package/src/channels/adapters/slack.ts +59 -7
  93. package/src/channels/adapters/telegram-bot.ts +18 -5
  94. package/src/channels/adapters/webex-bot.ts +8 -3
  95. package/src/channels/adapters/webex.ts +8 -3
  96. package/src/channels/fetch-attachment.ts +43 -0
  97. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  98. package/src/channels/github-token-bridge.ts +12 -6
  99. package/src/channels/manager.ts +9 -0
  100. package/src/channels/router.ts +248 -6
  101. package/src/channels/types.ts +28 -1
  102. package/src/cli/channel.ts +1 -1
  103. package/src/cli/init.ts +1 -1
  104. package/src/cli/model.ts +57 -7
  105. package/src/compose/stop.ts +17 -5
  106. package/src/config/config.ts +6 -6
  107. package/src/config/models-mutation.ts +13 -1
  108. package/src/config/providers.ts +176 -0
  109. package/src/container/docker-app.ts +42 -13
  110. package/src/container/start.ts +62 -10
  111. package/src/cron/bridge.ts +9 -2
  112. package/src/doctor/checks.ts +8 -3
  113. package/src/doctor/commit.ts +2 -1
  114. package/src/doctor/file-ownership.ts +52 -0
  115. package/src/dreams/git.ts +2 -1
  116. package/src/git/bound-gc-config.ts +82 -0
  117. package/src/git/hookless.ts +5 -0
  118. package/src/git/reconcile-ignored.ts +18 -5
  119. package/src/git/system-commit.ts +12 -6
  120. package/src/hostd/spawn.ts +133 -47
  121. package/src/init/dockerfile.ts +99 -5
  122. package/src/init/index.ts +17 -5
  123. package/src/init/models-dev.ts +4 -0
  124. package/src/init/validate-api-key.ts +2 -0
  125. package/src/inspect/replay.ts +21 -9
  126. package/src/inspect/session-list.ts +71 -33
  127. package/src/mcp/tools.ts +17 -3
  128. package/src/network/internal-destinations.ts +267 -0
  129. package/src/permissions/builtins.ts +3 -1
  130. package/src/plugin/context.ts +2 -0
  131. package/src/plugin/index.ts +1 -0
  132. package/src/plugin/manager.ts +4 -0
  133. package/src/plugin/types.ts +22 -0
  134. package/src/run/index.ts +40 -0
  135. package/src/run/llm-fetch-observer.ts +41 -4
  136. package/src/sandbox/build.ts +37 -15
  137. package/src/sandbox/canonical-secrets.ts +18 -0
  138. package/src/sandbox/env-exposure.ts +83 -0
  139. package/src/sandbox/errors.ts +13 -6
  140. package/src/sandbox/hidden-paths.ts +102 -44
  141. package/src/sandbox/index.ts +22 -4
  142. package/src/sandbox/package-install.ts +3 -27
  143. package/src/sandbox/policy.ts +16 -28
  144. package/src/sandbox/privileged-runtime.ts +256 -0
  145. package/src/sandbox/session-tmp.ts +8 -2
  146. package/src/sandbox/writable-zones.ts +204 -140
  147. package/src/secrets/index.ts +8 -0
  148. package/src/secrets/refresh-provider-oauth.ts +128 -0
  149. package/src/server/command-runner.ts +48 -4
  150. package/src/server/index.ts +4 -0
  151. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  152. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  153. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  154. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  155. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  156. package/src/skills/typeclaw-config/SKILL.md +27 -11
  157. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  158. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  159. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  160. package/src/skills/typeclaw-permissions/SKILL.md +36 -19
  161. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  162. package/src/usage/scan.ts +11 -2
  163. package/typeclaw.schema.json +25 -0
@@ -39,36 +39,68 @@ export type ListSessionsOptions = {
39
39
  // character so empty-id filenames like `_.jsonl` don't slip through.
40
40
  const FILENAME_PATTERN = /^(?:.*_)?([^_/\\\s][^/\\\s]*)\.jsonl$/
41
41
 
42
- export async function listSessions(opts: ListSessionsOptions): Promise<SessionSummary[]> {
42
+ // Bounds concurrent per-file I/O. An agent folder can hold tens of thousands of
43
+ // session files, and an unbounded `Promise.all` over them opens one file
44
+ // descriptor per concurrent stat/stream — enough to blow past a 256 `ulimit -n`
45
+ // and crash the process with EMFILE. 32 keeps throughput high while staying well
46
+ // under any sane FD ceiling.
47
+ const SESSION_IO_CONCURRENCY = 32
48
+
49
+ // A dependency-free bounded worker pool: `concurrency` workers pull from a shared
50
+ // cursor until the list is drained, preserving input order in the result.
51
+ async function mapConcurrent<T, R>(
52
+ items: readonly T[],
53
+ concurrency: number,
54
+ fn: (item: T, index: number) => Promise<R>,
55
+ ): Promise<R[]> {
56
+ const results = new Array<R>(items.length)
57
+ let next = 0
58
+ const worker = async (): Promise<void> => {
59
+ while (true) {
60
+ const index = next++
61
+ if (index >= items.length) return
62
+ results[index] = await fn(items[index]!, index)
63
+ }
64
+ }
65
+ const workerCount = Math.min(concurrency, items.length)
66
+ await Promise.all(Array.from({ length: workerCount }, () => worker()))
67
+ return results
68
+ }
69
+
70
+ type StatEntry = { path: string; basename: string; sessionId: string; mtimeMs: number }
71
+
72
+ // Split from listSessions so resolveSession can match ids first and peek only the
73
+ // candidates, instead of reading every file body on disk. Reads no file content.
74
+ async function statSessionFiles(opts: ListSessionsOptions): Promise<StatEntry[]> {
43
75
  const entries = await readSessionFiles(opts.sessionsDir, opts.onWarn)
44
- const withStats = await Promise.all(
45
- entries.map(async (entry) => {
46
- const s = await safeStat(entry.path)
47
- if (s === null) return null
48
- const mtimeMs = s.mtimeMs
49
- if (opts.sinceMs !== undefined && mtimeMs < opts.sinceMs) return null
50
- return { ...entry, mtimeMs }
51
- }),
52
- )
53
- const valid = withStats.filter(
54
- (v): v is { path: string; basename: string; sessionId: string; mtimeMs: number } => v !== null,
55
- )
76
+ const withStats = await mapConcurrent(entries, SESSION_IO_CONCURRENCY, async (entry) => {
77
+ const s = await safeStat(entry.path)
78
+ if (s === null) return null
79
+ const mtimeMs = s.mtimeMs
80
+ if (opts.sinceMs !== undefined && mtimeMs < opts.sinceMs) return null
81
+ return { ...entry, mtimeMs }
82
+ })
83
+ const valid = withStats.filter((v): v is StatEntry => v !== null)
56
84
  valid.sort((a, b) => b.mtimeMs - a.mtimeMs)
57
- const limited = opts.limit !== undefined ? valid.slice(0, opts.limit) : valid
85
+ return valid
86
+ }
58
87
 
59
- return Promise.all(
60
- limited.map(async ({ path, basename, sessionId, mtimeMs }) => {
61
- const peek = await peekSession(path, opts.onWarn)
62
- return {
63
- sessionId,
64
- sessionFile: path,
65
- basename,
66
- mtimeMs,
67
- origin: peek.origin,
68
- firstPrompt: peek.firstPrompt,
69
- }
70
- }),
71
- )
88
+ async function summarizeEntry(entry: StatEntry, onWarn?: (msg: string) => void): Promise<SessionSummary> {
89
+ const peek = await peekSession(entry.path, onWarn)
90
+ return {
91
+ sessionId: entry.sessionId,
92
+ sessionFile: entry.path,
93
+ basename: entry.basename,
94
+ mtimeMs: entry.mtimeMs,
95
+ origin: peek.origin,
96
+ firstPrompt: peek.firstPrompt,
97
+ }
98
+ }
99
+
100
+ export async function listSessions(opts: ListSessionsOptions): Promise<SessionSummary[]> {
101
+ const valid = await statSessionFiles(opts)
102
+ const limited = opts.limit !== undefined ? valid.slice(0, opts.limit) : valid
103
+ return mapConcurrent(limited, SESSION_IO_CONCURRENCY, (entry) => summarizeEntry(entry, opts.onWarn))
72
104
  }
73
105
 
74
106
  // Overlay container-registry sessions onto the disk listing. A live session
@@ -105,17 +137,23 @@ export async function resolveSession(
105
137
  sessionIdOrPrefix: string,
106
138
  onWarn?: (msg: string) => void,
107
139
  ): Promise<ResolveResult> {
108
- const all = await listSessions({ sessionsDir, ...(onWarn !== undefined ? { onWarn } : {}) })
109
- const exact = all.find((s) => s.sessionId === sessionIdOrPrefix)
110
- if (exact !== undefined) return { ok: true, summary: exact }
140
+ // Match on stat-only metadata (filename-derived id + mtime) first, then peek
141
+ // ONLY the matched candidates. Peeking every session to find one by id/prefix
142
+ // opened a file descriptor per file — tens of thousands at once on a busy agent,
143
+ // which crashes with EMFILE. Id resolution never needs a file's body.
144
+ const entries = await statSessionFiles({ sessionsDir, ...(onWarn !== undefined ? { onWarn } : {}) })
145
+
146
+ const exact = entries.find((e) => e.sessionId === sessionIdOrPrefix)
147
+ if (exact !== undefined) return { ok: true, summary: await summarizeEntry(exact, onWarn) }
111
148
 
112
149
  if (sessionIdOrPrefix.length < MIN_PREFIX_LENGTH || !isSessionIdShape(sessionIdOrPrefix)) {
113
150
  return { ok: false, reason: 'not-found', matches: [] }
114
151
  }
115
- const prefixMatches = all.filter((s) => s.sessionId.startsWith(sessionIdOrPrefix))
152
+ const prefixMatches = entries.filter((e) => e.sessionId.startsWith(sessionIdOrPrefix))
116
153
  if (prefixMatches.length === 0) return { ok: false, reason: 'not-found', matches: [] }
117
- if (prefixMatches.length === 1) return { ok: true, summary: prefixMatches[0]! }
118
- return { ok: false, reason: 'ambiguous', matches: prefixMatches }
154
+ if (prefixMatches.length === 1) return { ok: true, summary: await summarizeEntry(prefixMatches[0]!, onWarn) }
155
+ const matches = await mapConcurrent(prefixMatches, SESSION_IO_CONCURRENCY, (e) => summarizeEntry(e, onWarn))
156
+ return { ok: false, reason: 'ambiguous', matches }
119
157
  }
120
158
 
121
159
  const SESSION_ID_SHAPE = /^[^_/\\\s][^/\\\s]*$/
package/src/mcp/tools.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
2
2
  import { z } from 'zod'
3
3
 
4
+ import { enforceAndPinToolFiles } from '@/agent/tool-file-safety'
4
5
  import { defineTool } from '@/plugin/define'
5
6
  import type { ContentPart, Tool, ToolResult } from '@/plugin/types'
6
7
 
@@ -87,13 +88,26 @@ function createCallTool(manager: McpManager): Tool<McpCallArgs> {
87
88
  tool: z.string().describe('The bare tool name or namespaced server__tool id.'),
88
89
  args: z.record(z.string(), z.unknown()).optional().describe('Arguments matching the tool input schema.'),
89
90
  }),
90
- async execute(args) {
91
+ async execute(args, ctx) {
91
92
  const resolved = resolveToolArgs(args.server, args.tool)
92
93
  const connection = await manager.ensureConnected(resolved.server)
93
94
  if (connection === undefined) return textResult(unknownServerMessage(manager, resolved.server))
94
95
 
95
- const result = await safeCallTool(connection, resolved.tool, args.args ?? {})
96
- return mapCallToolResult(resolved.server, resolved.tool, result)
96
+ const toolArgs = args.args ?? {}
97
+ const pinned = await enforceAndPinToolFiles({
98
+ tool: 'mcp_call',
99
+ args: toolArgs,
100
+ agentDir: ctx.agentDir,
101
+ genericInputs: true,
102
+ logger: ctx.logger,
103
+ signal: ctx.signal,
104
+ })
105
+ try {
106
+ const result = await safeCallTool(connection, resolved.tool, toolArgs)
107
+ return pinned.restoreResult(mapCallToolResult(resolved.server, resolved.tool, result))
108
+ } finally {
109
+ await pinned.cleanup()
110
+ }
97
111
  },
98
112
  })
99
113
  }
@@ -0,0 +1,267 @@
1
+ import { isIP } from 'node:net'
2
+
3
+ export const MODEL_HTTP_ALLOW_INTERNAL_HOSTS_ENV = 'TYPECLAW_MODEL_HTTP_ALLOW_INTERNAL_HOSTS'
4
+ export const MODEL_HTTP_ALLOW_INTERNAL_CIDRS_ENV = 'TYPECLAW_MODEL_HTTP_ALLOW_INTERNAL_CIDRS'
5
+ export const MAX_MODEL_HTTP_POLICY_ENTRIES = 64
6
+ const MAX_MODEL_HTTP_POLICY_VALUE_LENGTH = 8192
7
+
8
+ type ParsedAddress = { readonly family: 4 | 6; readonly value: bigint; readonly bits: 32 | 128 }
9
+ type ParsedCidr = ParsedAddress & { readonly prefix: number }
10
+
11
+ const RFC6052_PREFIX_LENGTHS = [32, 40, 48, 56, 64, 96] as const
12
+
13
+ export type InternalDestinationPolicy = {
14
+ readonly hostnames: readonly string[]
15
+ readonly cidrs: readonly ParsedCidr[]
16
+ }
17
+
18
+ export type InternalDestinationPolicyInput = {
19
+ allowInternalHosts?: readonly string[]
20
+ allowInternalCidrs?: readonly string[]
21
+ }
22
+
23
+ export function createInternalDestinationPolicy(input: InternalDestinationPolicyInput): InternalDestinationPolicy {
24
+ assertBounded(input.allowInternalHosts ?? [], MODEL_HTTP_ALLOW_INTERNAL_HOSTS_ENV)
25
+ assertBounded(input.allowInternalCidrs ?? [], MODEL_HTTP_ALLOW_INTERNAL_CIDRS_ENV)
26
+ const hostnames = (input.allowInternalHosts ?? []).map((value, index) => {
27
+ const normalized = normalizeExactHostname(value)
28
+ if (normalized === undefined) throw invalidEntry(MODEL_HTTP_ALLOW_INTERNAL_HOSTS_ENV, index, value)
29
+ return normalized
30
+ })
31
+ const cidrs = (input.allowInternalCidrs ?? []).map((value, index) => {
32
+ const parsed = parseCidr(value)
33
+ if (parsed === undefined) throw invalidEntry(MODEL_HTTP_ALLOW_INTERNAL_CIDRS_ENV, index, value)
34
+ return Object.freeze({ ...parsed, value: parsed.value & prefixMask(parsed.bits, parsed.prefix) })
35
+ })
36
+ return Object.freeze({ hostnames: Object.freeze([...new Set(hostnames)]), cidrs: Object.freeze(cidrs) })
37
+ }
38
+
39
+ export function buildInternalDestinationPolicyFromEnv(
40
+ env: Readonly<Record<string, string | undefined>>,
41
+ ): InternalDestinationPolicy {
42
+ return createInternalDestinationPolicy({
43
+ allowInternalHosts: parseEnvList(env[MODEL_HTTP_ALLOW_INTERNAL_HOSTS_ENV], MODEL_HTTP_ALLOW_INTERNAL_HOSTS_ENV),
44
+ allowInternalCidrs: parseEnvList(env[MODEL_HTTP_ALLOW_INTERNAL_CIDRS_ENV], MODEL_HTTP_ALLOW_INTERNAL_CIDRS_ENV),
45
+ })
46
+ }
47
+
48
+ const BOOT_INTERNAL_DESTINATION_POLICY = buildInternalDestinationPolicyFromEnv(process.env)
49
+
50
+ export function getBootInternalDestinationPolicy(): InternalDestinationPolicy {
51
+ return BOOT_INTERNAL_DESTINATION_POLICY
52
+ }
53
+
54
+ export function normalizeExactHostname(value: string): string | undefined {
55
+ const candidate = value.trim().replace(/\.$/, '')
56
+ if (candidate === '' || candidate.includes('[') || candidate.includes(']') || /[\s*:/\\@?#]/.test(candidate)) {
57
+ return undefined
58
+ }
59
+ let hostname: string
60
+ try {
61
+ hostname = new URL(`http://${candidate}/`).hostname.toLowerCase().replace(/\.$/, '')
62
+ } catch {
63
+ return undefined
64
+ }
65
+ if (hostname === '' || isIP(hostname) !== 0 || hostname.length > 253) return undefined
66
+ const labels = hostname.split('.')
67
+ if (
68
+ labels.some(
69
+ (label) =>
70
+ label.length === 0 ||
71
+ label.length > 63 ||
72
+ !/^[a-z0-9-]+$/.test(label) ||
73
+ label.startsWith('-') ||
74
+ label.endsWith('-'),
75
+ )
76
+ ) {
77
+ return undefined
78
+ }
79
+ return hostname
80
+ }
81
+
82
+ export function normalizeIpCidr(value: string): string | undefined {
83
+ if (value.includes('%')) return undefined
84
+ const parsed = parseCidr(value)
85
+ if (parsed === undefined) return undefined
86
+ const network = parsed.value & prefixMask(parsed.bits, parsed.prefix)
87
+ return `${formatAddress({ family: parsed.family, bits: parsed.bits, value: network })}/${parsed.prefix}`
88
+ }
89
+
90
+ export function hostnameMatchesPolicy(hostname: string, policy: InternalDestinationPolicy): boolean {
91
+ const normalized = normalizeExactHostname(hostname)
92
+ return normalized !== undefined && policy.hostnames.includes(normalized)
93
+ }
94
+
95
+ export function addressMatchesPolicy(address: string, policy: InternalDestinationPolicy): boolean {
96
+ const parsed = parseAddress(address)
97
+ if (parsed === undefined) return false
98
+ for (const cidr of policy.cidrs) {
99
+ if (matchesCidr(parsed, cidr)) return true
100
+ const embeddedIpv4 = ipv4FromEmbeddedIpv6(parsed)
101
+ if (embeddedIpv4 !== undefined && matchesCidr(embeddedIpv4, cidr)) return true
102
+ }
103
+ return false
104
+ }
105
+
106
+ export function extractEmbeddedIpv4Address(address: string): string | undefined {
107
+ const parsed = parseAddress(address)
108
+ if (parsed === undefined || parsed.family !== 6) return undefined
109
+ const ipv4 = ipv4FromEmbeddedIpv6(parsed)
110
+ return ipv4 === undefined ? undefined : formatAddress(ipv4)
111
+ }
112
+
113
+ export function extractRfc6052Ipv4Addresses(address: string): readonly string[] {
114
+ const parsed = parseAddress(address)
115
+ if (parsed === undefined || parsed.family !== 6 || extractAddressBits(parsed.value, 64, 8) !== 0n) return []
116
+ const candidates = RFC6052_PREFIX_LENGTHS.map((prefix) => {
117
+ if (prefix === 96) return extractAddressBits(parsed.value, 96, 32)
118
+ const leadingIpv4Bits = 64 - prefix
119
+ const trailingIpv4Bits = 32 - leadingIpv4Bits
120
+ return (
121
+ (extractAddressBits(parsed.value, prefix, leadingIpv4Bits) << BigInt(trailingIpv4Bits)) |
122
+ extractAddressBits(parsed.value, 72, trailingIpv4Bits)
123
+ )
124
+ })
125
+ return [...new Set(candidates.map((value) => formatAddress({ family: 4, bits: 32, value })))]
126
+ }
127
+
128
+ function parseEnvList(raw: string | undefined, name: string): string[] {
129
+ if (raw === undefined || raw === '') return []
130
+ if (raw.length > MAX_MODEL_HTTP_POLICY_VALUE_LENGTH) {
131
+ throw new Error(`${name} exceeds the ${MAX_MODEL_HTTP_POLICY_VALUE_LENGTH}-character limit`)
132
+ }
133
+ const entries = raw.split(',').map((entry) => entry.trim())
134
+ if (entries.some((entry) => entry === '')) throw new Error(`${name} contains an empty comma-separated entry`)
135
+ assertBounded(entries, name)
136
+ return entries
137
+ }
138
+
139
+ function assertBounded(entries: readonly string[], name: string): void {
140
+ if (entries.length > MAX_MODEL_HTTP_POLICY_ENTRIES) {
141
+ throw new Error(`${name} contains ${entries.length} entries; maximum is ${MAX_MODEL_HTTP_POLICY_ENTRIES}`)
142
+ }
143
+ }
144
+
145
+ function invalidEntry(name: string, index: number, value: string): Error {
146
+ const expected =
147
+ name === MODEL_HTTP_ALLOW_INTERNAL_HOSTS_ENV
148
+ ? 'an exact hostname without wildcards, a URL, or an IP literal'
149
+ : 'an IPv4 or IPv6 CIDR with an explicit prefix'
150
+ return new Error(`${name} entry ${index + 1} (${JSON.stringify(value)}) must be ${expected}`)
151
+ }
152
+
153
+ function parseCidr(value: string): ParsedCidr | undefined {
154
+ if (value.includes('%')) return undefined
155
+ const slash = value.indexOf('/')
156
+ if (slash <= 0 || slash !== value.lastIndexOf('/')) return undefined
157
+ const address = parseAddress(value.slice(0, slash))
158
+ const prefixText = value.slice(slash + 1)
159
+ if (address === undefined || !/^\d{1,3}$/.test(prefixText)) return undefined
160
+ const prefix = Number(prefixText)
161
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > address.bits) return undefined
162
+ return { ...address, prefix }
163
+ }
164
+
165
+ function parseAddress(rawAddress: string): ParsedAddress | undefined {
166
+ const address = rawAddress.toLowerCase().split('%')[0] ?? ''
167
+ const family = isIP(address)
168
+ if (family === 4) {
169
+ const octets = address.split('.').map(Number)
170
+ if (octets.length !== 4) return undefined
171
+ const value = octets.reduce((total, octet) => (total << 8n) | BigInt(octet), 0n)
172
+ return { family: 4, value, bits: 32 }
173
+ }
174
+ if (family !== 6) return undefined
175
+ const hextets = expandIpv6(address)
176
+ if (hextets === undefined) return undefined
177
+ const value = hextets.reduce((total, hextet) => (total << 16n) | BigInt(hextet), 0n)
178
+ return { family: 6, value, bits: 128 }
179
+ }
180
+
181
+ function expandIpv6(address: string): number[] | undefined {
182
+ let normalized = address
183
+ const dottedTail = normalized.match(/(?:^|:)(\d+\.\d+\.\d+\.\d+)$/)?.[1]
184
+ if (dottedTail !== undefined) {
185
+ const ipv4 = parseAddress(dottedTail)
186
+ if (ipv4 === undefined || ipv4.family !== 4) return undefined
187
+ const hi = Number((ipv4.value >> 16n) & 0xffffn).toString(16)
188
+ const lo = Number(ipv4.value & 0xffffn).toString(16)
189
+ normalized = `${normalized.slice(0, -dottedTail.length)}${hi}:${lo}`
190
+ }
191
+ const halves = normalized.split('::')
192
+ if (halves.length > 2) return undefined
193
+ const left = halves[0] === '' ? [] : halves[0]!.split(':')
194
+ const right = halves.length === 1 || halves[1] === '' ? [] : halves[1]!.split(':')
195
+ if ([...left, ...right].some((part) => !/^[0-9a-f]{1,4}$/.test(part))) return undefined
196
+ const missing = 8 - left.length - right.length
197
+ if ((halves.length === 1 && missing !== 0) || (halves.length === 2 && missing < 1)) return undefined
198
+ return [
199
+ ...left.map((part) => Number.parseInt(part, 16)),
200
+ ...Array(missing).fill(0),
201
+ ...right.map((part) => Number.parseInt(part, 16)),
202
+ ]
203
+ }
204
+
205
+ function prefixMask(bits: 32 | 128, prefix: number): bigint {
206
+ if (prefix === 0) return 0n
207
+ return ((1n << BigInt(prefix)) - 1n) << BigInt(bits - prefix)
208
+ }
209
+
210
+ function extractAddressBits(value: bigint, start: number, length: number): bigint {
211
+ if (length === 0) return 0n
212
+ return (value >> BigInt(128 - start - length)) & ((1n << BigInt(length)) - 1n)
213
+ }
214
+
215
+ function matchesCidr(address: ParsedAddress, cidr: ParsedCidr): boolean {
216
+ if (address.family !== cidr.family) return false
217
+ const mask = prefixMask(cidr.bits, cidr.prefix)
218
+ return (address.value & mask) === cidr.value
219
+ }
220
+
221
+ function ipv4FromEmbeddedIpv6(address: ParsedAddress): ParsedAddress | undefined {
222
+ if (address.family !== 6) return undefined
223
+ const high96 = address.value >> 32n
224
+ const isMapped = high96 === 0xffffn
225
+ const isTranslated = high96 === 0xffff0000n
226
+ const isCompatible = high96 === 0n && address.value > 1n
227
+ const nat64Prefix = 0x64ff9b0000000000000000n
228
+ const isWellKnownNat64 = high96 === nat64Prefix
229
+ if (isMapped || isTranslated || isCompatible || isWellKnownNat64) {
230
+ return { family: 4, bits: 32, value: address.value & 0xffffffffn }
231
+ }
232
+ const is6to4 = address.value >> 112n === 0x2002n
233
+ if (is6to4) return { family: 4, bits: 32, value: (address.value >> 80n) & 0xffffffffn }
234
+ return undefined
235
+ }
236
+
237
+ function formatAddress(address: ParsedAddress): string {
238
+ if (address.family === 4) {
239
+ return [24n, 16n, 8n, 0n].map((shift) => Number((address.value >> shift) & 0xffn)).join('.')
240
+ }
241
+ const hextets = Array.from({ length: 8 }, (_, index) => Number((address.value >> BigInt((7 - index) * 16)) & 0xffffn))
242
+ let bestStart = -1
243
+ let bestLength = 0
244
+ for (let start = 0; start < hextets.length; ) {
245
+ if (hextets[start] !== 0) {
246
+ start++
247
+ continue
248
+ }
249
+ let end = start
250
+ while (end < hextets.length && hextets[end] === 0) end++
251
+ if (end - start > bestLength && end - start >= 2) {
252
+ bestStart = start
253
+ bestLength = end - start
254
+ }
255
+ start = end
256
+ }
257
+ if (bestStart === -1) return hextets.map((part) => part.toString(16)).join(':')
258
+ const left = hextets
259
+ .slice(0, bestStart)
260
+ .map((part) => part.toString(16))
261
+ .join(':')
262
+ const right = hextets
263
+ .slice(bestStart + bestLength)
264
+ .map((part) => part.toString(16))
265
+ .join(':')
266
+ return `${left}::${right}`
267
+ }
@@ -32,7 +32,9 @@ export const CORE_PERMISSIONS = {
32
32
  // Phrased as capabilities to SEE, not to hide, so the role tower stays
33
33
  // monotonic (a higher tier sees a strict superset of a lower tier).
34
34
  // resolveHiddenPaths masks whatever the resolved role lacks: fsSeePrivate
35
- // gates workspace/+memory/+sessions/, fsSeeSecrets gates .env+secrets.json.
35
+ // gates workspace/+memory/+sessions/. fsSeeSecrets authorizes runtime-owned
36
+ // credential use, never raw LLM tool access to canonical credential stores;
37
+ // canonical files are unconditionally masked for every role.
36
38
  // The fail-safe floor is the undefined origin (see has() in
37
39
  // permissions.ts), not the guest role, which is now grantable.
38
40
  fsSeePrivate: 'fs.see.private',
@@ -14,6 +14,7 @@ export type CreatePluginContextOptions<TConfig> = {
14
14
  permissions: PermissionService
15
15
  resolveGithubTokenForRepo?: ResolveGithubTokenForRepo
16
16
  hasGithubAppTokenResolver?: () => boolean
17
+ getGithubAppSelfLogin?: () => string | null
17
18
  spawnSubagent: SpawnSubagentFn
18
19
  isBooted: () => boolean
19
20
  }
@@ -34,6 +35,7 @@ export function createPluginContext<TConfig>(opts: CreatePluginContextOptions<TC
34
35
  github: {
35
36
  resolveTokenForRepo: opts.resolveGithubTokenForRepo ?? githubTokenUnavailable,
36
37
  hasAppTokenResolver: opts.hasGithubAppTokenResolver ?? (() => false),
38
+ getAppSelfLogin: opts.getGithubAppSelfLogin ?? (() => null),
37
39
  },
38
40
  spawnSubagent: async (name: string, payload?: unknown, options?: SpawnSubagentOptions) => {
39
41
  if (!opts.isBooted()) {
@@ -60,6 +60,7 @@ export type {
60
60
  ToolBeforeEvent,
61
61
  ToolBeforeResult,
62
62
  ToolContext,
63
+ ToolFileOperands,
63
64
  ToolLogger,
64
65
  ToolResult,
65
66
  } from './types'
@@ -35,6 +35,7 @@ export type LoadPluginsOptions = {
35
35
  roles?: RolesConfig
36
36
  resolveGithubTokenForRepo?: ResolveGithubTokenForRepo
37
37
  hasGithubAppTokenResolver?: () => boolean
38
+ getGithubAppSelfLogin?: () => string | null
38
39
  // Bundled plugins resolved by the runtime (not from typeclaw.json). Loaded
39
40
  // before user-declared `entries` so a config block named after a bundled
40
41
  // plugin (e.g. "memory") is consumed by the bundled plugin, and so plugin-
@@ -126,6 +127,7 @@ export async function loadPlugins(opts: LoadPluginsOptions): Promise<LoadPlugins
126
127
  ctxDeps: {
127
128
  resolveGithubTokenForRepo: opts.resolveGithubTokenForRepo,
128
129
  hasGithubAppTokenResolver: opts.hasGithubAppTokenResolver,
130
+ getGithubAppSelfLogin: opts.getGithubAppSelfLogin,
129
131
  spawnSubagent: (name, payload, options) => spawnSubagentImpl(name, payload, options),
130
132
  isBooted: () => booted,
131
133
  },
@@ -224,6 +226,7 @@ type RegisterOnePluginArgs = {
224
226
  ctxDeps: {
225
227
  resolveGithubTokenForRepo?: ResolveGithubTokenForRepo
226
228
  hasGithubAppTokenResolver?: () => boolean
229
+ getGithubAppSelfLogin?: () => string | null
227
230
  spawnSubagent: SpawnSubagentFn
228
231
  isBooted: () => boolean
229
232
  }
@@ -255,6 +258,7 @@ async function registerOnePlugin(args: RegisterOnePluginArgs): Promise<void> {
255
258
  permissions: args.permissions,
256
259
  resolveGithubTokenForRepo: args.ctxDeps.resolveGithubTokenForRepo,
257
260
  hasGithubAppTokenResolver: args.ctxDeps.hasGithubAppTokenResolver,
261
+ getGithubAppSelfLogin: args.ctxDeps.getGithubAppSelfLogin,
258
262
  spawnSubagent: args.ctxDeps.spawnSubagent,
259
263
  isBooted: args.ctxDeps.isBooted,
260
264
  })
@@ -25,9 +25,24 @@ export type ToolContext = {
25
25
  logger: ToolLogger
26
26
  }
27
27
 
28
+ export type ToolFileOperands = {
29
+ input?: readonly string[]
30
+ output?: readonly string[]
31
+ create?: readonly string[]
32
+ destructive?: readonly string[]
33
+ // Operand paths whose string values are control tokens or remote identifiers,
34
+ // never a local file — the file-operand scanner skips them (like a first-party
35
+ // prose operand) instead of rejecting a value that collides with an existing
36
+ // agent-root entry. Scoped per operand path and survives
37
+ // the runtime `__plugin_*` tool-name prefix that a static in-scanner table
38
+ // cannot. Declare a real file input under `input` (it gets pinned), not here.
39
+ nonFile?: readonly string[]
40
+ }
41
+
28
42
  export type Tool<P = unknown> = {
29
43
  description: string
30
44
  parameters: z.ZodType<P>
45
+ fileOperands?: ToolFileOperands
31
46
  execute: (args: P, ctx: ToolContext) => Promise<ToolResult>
32
47
  }
33
48
 
@@ -211,6 +226,12 @@ export type ToolBeforeEvent = {
211
226
  callId: string
212
227
  args: Record<string, unknown>
213
228
  origin?: SessionOrigin
229
+ // The tool author's operand declarations (never model-controlled — set on the
230
+ // static Tool definition at registration). Carried so a guard that runs before
231
+ // the file-operand scanner (private-surface-read) can honor the same
232
+ // `nonFile` exemptions and not block a declared remote identifier that happens
233
+ // to collide with a hidden dir name. Present only for plugin tools.
234
+ fileOperands?: ToolFileOperands
214
235
  }
215
236
 
216
237
  export type ToolBeforeResult = void | undefined | { block: true; reason: string }
@@ -284,6 +305,7 @@ export type PluginContext<TConfig = never> = {
284
305
  export type PluginGithubServices = {
285
306
  resolveTokenForRepo: ResolveGithubTokenForRepo
286
307
  hasAppTokenResolver: () => boolean
308
+ getAppSelfLogin?: () => string | null
287
309
  }
288
310
 
289
311
  export type PluginExports = {
package/src/run/index.ts CHANGED
@@ -68,6 +68,7 @@ import {
68
68
  exportClaudeCredentialsFileForAgent,
69
69
  exportCodexAuthFileForAgent,
70
70
  hydrateChannelEnvFromSecrets,
71
+ refreshProviderOAuthForAgent,
71
72
  } from '@/secrets'
72
73
  import { createServer, type Server } from '@/server'
73
74
  import {
@@ -121,6 +122,10 @@ export type StartAgentOptions = {
121
122
  // over the real env + <cwd>/secrets.json. Injectable so tests can supply a
122
123
  // fake secrets provider without touching process.env.
123
124
  caps?: RuntimeCapabilities
125
+ // Boot-time proactive provider-OAuth refresh. Injectable so a test can supply
126
+ // a refresh that holds the real secrets lock on a gate, proving the boot
127
+ // barrier settles this before any session-producing consumer starts.
128
+ refreshProviderOAuth?: (options: { agentDir: string; log: (message: string) => void }) => Promise<unknown>
124
129
  }
125
130
 
126
131
  export type StartAgentResult = {
@@ -181,6 +186,7 @@ async function startAgentRuntime(
181
186
  createChannelManager: createChannelManagerFor = createChannelManager,
182
187
  createTunnelManager: createTunnelManagerFor = createTunnelManager,
183
188
  caps = createRuntimeCapabilities(process.env, join(cwd, 'secrets.json')),
189
+ refreshProviderOAuth = refreshProviderOAuthForAgent,
184
190
  }: StartAgentOptions,
185
191
  registerBootCleanup: (cleanup: () => void | Promise<void>) => void,
186
192
  ): Promise<StartAgentResult> {
@@ -287,6 +293,7 @@ async function startAgentRuntime(
287
293
  bundled: BUNDLED_PLUGINS,
288
294
  resolveGithubTokenForRepo: githubTokenBridge.resolveTokenForRepo,
289
295
  hasGithubAppTokenResolver: githubTokenBridge.hasAppTokenResolver,
296
+ getGithubAppSelfLogin: githubTokenBridge.getAppSelfLogin,
290
297
  ...(cwdConfig.roles !== undefined ? { roles: cwdConfig.roles } : {}),
291
298
  })
292
299
  const vectorStartupPromise = runVectorStartup(cwd)
@@ -374,6 +381,29 @@ async function startAgentRuntime(
374
381
  log: (message) => console.warn(message),
375
382
  })
376
383
 
384
+ // Proactively refresh any stored provider-OAuth token now. The SDK's own
385
+ // refresh is lazy (fires on the first LLM call), so a container that restarts
386
+ // with an already-expired access token otherwise discovers the staleness —
387
+ // and any refresh failure — mid-turn, surfacing a generic provider-error
388
+ // notice into a live thread. Doing it here moves that to a boot-time operator
389
+ // log. Channel-adapter OAuth already has host-side renewal crons; this is the
390
+ // provider-OAuth equivalent.
391
+ //
392
+ // MUST be awaited, and MUST run before the first session-producing consumer
393
+ // (subagentConsumer.start / cronConsumer.start / channelManager.start / the
394
+ // websocket server). The SDK refresh holds SecretsBackend's async file lock
395
+ // across its network request; getAuthFor()'s synchronous lock read gives up
396
+ // after ~200ms and process.exit(1)s on ELOCKED. Fire-and-forget here would let
397
+ // a slow refresh still own the lock when a consumer creates a session — worse
398
+ // than the lazy path. Awaiting behind this barrier guarantees no synchronous
399
+ // auth reader exists while the refresh owns the lock. Never throws (the
400
+ // wrapper swallows and logs), so a probe failure can't block boot; a refresh
401
+ // that hangs on a wedged network hangs the first turn today anyway.
402
+ await refreshProviderOAuth({
403
+ agentDir: cwd,
404
+ log: (message) => console.warn(message),
405
+ })
406
+
377
407
  const claimController = createClaimController({
378
408
  cwd,
379
409
  permissions: pluginsLoaded.permissions,
@@ -429,6 +459,11 @@ async function startAgentRuntime(
429
459
  child.status === 'running' && (newest === null || child.startedAt > newest) ? child.startedAt : newest,
430
460
  null,
431
461
  ),
462
+ listRunningBackgroundSubagentNames: (sessionId) =>
463
+ liveSubagentRegistry
464
+ .list({ parentSessionId: sessionId })
465
+ .filter((child) => child.status === 'running' && child.background === true)
466
+ .map((child) => child.subagentName),
432
467
  onReload: async () => {
433
468
  const { results } = await reloadRegistry.reloadAll()
434
469
  return formatChannelReloadSummary(results)
@@ -971,6 +1006,7 @@ async function startAgentRuntime(
971
1006
  ...mcpManagerOpt,
972
1007
  agentDir: cwd,
973
1008
  pluginRuntime,
1009
+ permissions: pluginsLoaded.permissions,
974
1010
  getFiredCount: (job) => cronCountStore?.get(job.id, job) ?? 0,
975
1011
  claimController,
976
1012
  commandRunnerFactory,
@@ -1038,6 +1074,10 @@ async function startAgentRuntime(
1038
1074
  forceExit.unref()
1039
1075
  void (async () => {
1040
1076
  if (containerName !== undefined) {
1077
+ // Persist the interrupted-subagent handoff BEFORE markRestartAbortForAllLive
1078
+ // aborts the sessions and stop() tears them down — both read the same live
1079
+ // set this write depends on.
1080
+ await channelManager.router.writeInterruptedSubagentHandoff().catch(() => undefined)
1041
1081
  await markRestartAbortPendingForOrigin(cwd, { kind: 'tui', sessionId: 'tui' }).catch(() => undefined)
1042
1082
  await channelManager.router.markRestartAbortForAllLive().catch(() => undefined)
1043
1083
  }