typeclaw 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) 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 +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -1,5 +1,11 @@
1
- import { lstat, mkdir, readdir, readFile, realpath, writeFile } from 'node:fs/promises'
1
+ import { execFile } from 'node:child_process'
2
+ import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises'
2
3
  import path, { isAbsolute, join, resolve } from 'node:path'
4
+ import { promisify } from 'node:util'
5
+
6
+ import { CANONICAL_AGENT_SECRET_DIRS, CANONICAL_AGENT_SECRET_FILES } from './canonical-secrets'
7
+
8
+ const execFileAsync = promisify(execFile)
3
9
 
4
10
  export type WritableZones = {
5
11
  dirs: string[]
@@ -37,7 +43,7 @@ const WRITABLE_DIRS = ['workspace', 'public', 'mounts', '.git'] as const
37
43
 
38
44
  // SECURITY: configured writable paths (`sandbox.writablePaths`) may NOT resolve
39
45
  // onto these. `.git` carries the hook/config escalation surface; `.env` and
40
- // `secrets.json` are the credential files; `sessions`/`memory` are the agent's
46
+ // `secrets.json`/`auth.json` are credential files; `sessions`/`memory` are the agent's
41
47
  // private surface (masked from low-trust roles by hidden-paths); `.typeclaw`
42
48
  // holds system-managed home persistence; `node_modules` is executable
43
49
  // dependency code. Granting blanket RW to any of these via config would defeat
@@ -46,17 +52,14 @@ const WRITABLE_DIRS = ['workspace', 'public', 'mounts', '.git'] as const
46
52
  // whole tree erases the read-only confinement wholesale.
47
53
  const FORBIDDEN_WRITABLE_ROOTS = [
48
54
  '.git',
49
- '.env',
50
- 'secrets.json',
55
+ ...CANONICAL_AGENT_SECRET_FILES,
51
56
  'sessions',
52
57
  'memory',
53
58
  '.typeclaw',
59
+ ...CANONICAL_AGENT_SECRET_DIRS,
54
60
  'node_modules',
55
61
  ] as const
56
62
 
57
- const PROTECTED_GIT_DIRS = ['.git/hooks'] as const
58
- const PROTECTED_GIT_FILES = ['.git/config'] as const
59
-
60
63
  // Bash may EDIT these when present; creating a MISSING root file goes through
61
64
  // write/edit (bwrap cannot RW-bind a non-existent source without pre-creating it).
62
65
  //
@@ -69,8 +72,8 @@ const PROTECTED_GIT_FILES = ['.git/config'] as const
69
72
  // this list forces every mutation of a guarded file through the one guarded path
70
73
  // (the write/edit tool), so a managed file has exactly one mutation boundary.
71
74
  // `package.json` stays writable: it is NOT a semantically-guarded managed file
72
- // (only cron.json/typeclaw.json are), and `bun add`/manual dep edits legitimately
73
- // touch it from bash.
75
+ // (only cron.json/typeclaw.json are), and ordinary trusted/manual edits remain
76
+ // supported.
74
77
  const WRITABLE_ROOT_FILES = ['AGENTS.md', 'IDENTITY.md', 'SOUL.md', 'USER.md', 'package.json'] as const
75
78
 
76
79
  // SECURITY: the symlink rejection is load-bearing. An RW bind follows symlinks,
@@ -153,115 +156,6 @@ function dedupe(values: string[]): string[] {
153
156
  return [...new Set(values)]
154
157
  }
155
158
 
156
- export type PackageInstallZones = {
157
- root: string
158
- protected: ProtectedZones
159
- // Guarded managed files that are ABSENT at jail-build time. The RW package-
160
- // install root would otherwise let a `bun install` postinstall lifecycle
161
- // script CREATE them (a guard bypass — see the SECURITY note on
162
- // MANAGED_ROOT_FILES). Rendered as `--ro-bind /dev/null <path>` so the path is
163
- // occupied by an empty read-only object that blocks creation, without
164
- // manufacturing a real (invalid) file on the host FS the way the secret-mask
165
- // placeholder pattern would. Present managed files go in `protected.files`.
166
- blockedCreation: string[]
167
- }
168
-
169
- // SECURITY: the semantically-guarded managed files. They are gated by the
170
- // managedConfig / cronPromotion guards (write/edit tools only), so bash must
171
- // never be able to write OR create them. The normal jail already excludes them
172
- // from WRITABLE_ROOT_FILES; the package-install RW root needs the extra step of
173
- // blocking their CREATION when absent (see PackageInstallZones.blockedCreation).
174
- const MANAGED_ROOT_FILES = ['cron.json', 'typeclaw.json'] as const
175
-
176
- // SECURITY: the package-install RW root is governed by an ALLOWLIST, not a
177
- // denylist. `bun add` writes exactly these and nothing else: `node_modules/`
178
- // (deps), `package.json` + `bun.lock` (manifest + lockfile, plus the temp
179
- // lockfile created in the root DIR). The scratch zones (`workspace`, `public`,
180
- // `mounts`) stay writable to match the normal jail. EVERY other existing root
181
- // entry is RO-bound, so a denylist of "executable/runtime-sensitive" paths is
182
- // not needed — it would be unbounded (any file the unsandboxed runtime reads or
183
- // execs, including `src/`/`scripts/` in dev-mode agents where typeclaw is a
184
- // file:/link: dep, the agent's own lifecycle scripts, and prompt-source files)
185
- // and fails OPEN for any root entry not yet listed. An allowlist fails CLOSED.
186
- const PACKAGE_INSTALL_WRITABLE_DIRS = ['node_modules', 'workspace', 'public', 'mounts'] as const
187
- const PACKAGE_INSTALL_WRITABLE_FILES = ['package.json', 'bun.lock'] as const
188
-
189
- // Resolves the jail layout for a recognized standalone dependency install
190
- // (`bun add` / `bun install`). The RW root lets bun create node_modules/ and its
191
- // temp lockfile (`bun.lock.NNN.tmp`, renamed) — a file-level bind of `bun.lock`
192
- // alone cannot, since the temp file needs DIRECTORY write. Pre-creates an empty
193
- // node_modules/ so the dir exists before the RW root bind. Then RO-binds every
194
- // EXISTING root entry not in the writable allowlist (readdir enumeration, so a
195
- // new file like `src/` or a planted `cron.json` is covered without a hardcoded
196
- // list), plus `node_modules/typeclaw` (the live/symlinked runtime, nested under
197
- // the writable node_modules) and the whole `.git` (a `bun add` never needs git,
198
- // so RO-binding it wholesale is simpler and safer than the hooks/config carve-out
199
- // — it closes the hook / core.hooksPath escalation by construction).
200
- //
201
- // SECURITY: rejects a symlink at agentDir, at any install-touched path
202
- // (node_modules, package.json, bun.lock), and at every RO-bind source — an RW
203
- // root or an RO bind that follows a symlink would write/read outside the jail.
204
- // The secret/private masks render AFTER this protected set (subtractMasked in
205
- // applyBashSandbox drops any protected entry a mask already hides), so .env /
206
- // secrets.json / memory / sessions stay hidden, not merely RO.
207
- export async function resolvePackageInstallZones(agentDir: string): Promise<PackageInstallZones> {
208
- await assertNotSymlink(agentDir)
209
- await mkdir(join(agentDir, 'node_modules'), { recursive: true })
210
- for (const rel of ['node_modules', ...PACKAGE_INSTALL_WRITABLE_FILES] as const) {
211
- const target = join(agentDir, rel)
212
- if (await exists(target)) await assertNotSymlink(target)
213
- }
214
-
215
- const writable = new Set<string>([...PACKAGE_INSTALL_WRITABLE_DIRS, ...PACKAGE_INSTALL_WRITABLE_FILES])
216
- const dirs: string[] = []
217
- const files: string[] = []
218
- for (const entry of await readdir(agentDir, { withFileTypes: true })) {
219
- if (writable.has(entry.name)) continue
220
- // A symlinked root entry is skipped, not RO-bound: an RO bind follows it to
221
- // an outside target. Skipping leaves it under the RW root — but it is the
222
- // agent's OWN symlink under its OWN root, contained by the agent-folder bind
223
- // and the always-on kernel invariants, the same residual the default jail
224
- // accepts for symlinks pointing outside /agent.
225
- if (entry.isSymbolicLink()) continue
226
- const target = join(agentDir, entry.name)
227
- if (entry.isDirectory()) dirs.push(target)
228
- else if (entry.isFile()) files.push(target)
229
- }
230
-
231
- // node_modules itself is writable (deps land there), but the runtime under it
232
- // must not be — RO-bind it nested, last-op-wins over the writable node_modules.
233
- const runtime = join(agentDir, 'node_modules', 'typeclaw')
234
- if (await isRealEntry(runtime, 'dir')) dirs.push(runtime)
235
-
236
- // Guarded managed files: a PRESENT real one is already RO-bound by the readdir
237
- // loop above (it is not in the writable set). The gap is a managed file ABSENT
238
- // at jail-build time — readdir never sees it, so nothing occupies its path and
239
- // a postinstall script could CREATE it under the RW root. Block that path with
240
- // `--ro-bind /dev/null`. A managed file that exists as a SYMLINK is also blocked
241
- // here rather than RO-bound (the readdir loop skipped it, and an RO bind would
242
- // follow it out of the jail) — occupying the path with /dev/null is safe.
243
- const blockedCreation: string[] = []
244
- for (const name of MANAGED_ROOT_FILES) {
245
- const target = join(agentDir, name)
246
- if (!(await isRealEntry(target, 'file'))) blockedCreation.push(target)
247
- }
248
-
249
- return {
250
- root: agentDir,
251
- protected: { dirs: dedupe(dirs), files: dedupe(files) },
252
- blockedCreation: dedupe(blockedCreation),
253
- }
254
- }
255
-
256
- async function exists(target: string): Promise<boolean> {
257
- try {
258
- await lstat(target)
259
- return true
260
- } catch {
261
- return false
262
- }
263
- }
264
-
265
159
  // Read-only re-protections rendered on top of the writable .git bind. Unlike
266
160
  // the writable resolvers, this MUST NOT drop absent entries: .git is writable,
267
161
  // so a path absent at jail-build time would otherwise be CREATED by sandboxed
@@ -276,20 +170,148 @@ async function exists(target: string): Promise<boolean> {
276
170
  // the .git/hooks RO-bind alone would not cover it, so that dir is protected too.
277
171
  export async function resolveProtectedZones(agentDir: string): Promise<ProtectedZones> {
278
172
  const dirs: string[] = []
279
- for (const rel of PROTECTED_GIT_DIRS) {
280
- dirs.push(await ensureProtectedDir(join(agentDir, rel)))
281
- }
173
+ const nodeModules = await resolveExistingProtectedDir(join(agentDir, 'node_modules'))
174
+ if (nodeModules !== undefined) dirs.push(nodeModules)
175
+ const layout = await resolveGitControlLayout(agentDir)
176
+ if (layout === undefined) return { dirs, files: [] }
177
+
178
+ dirs.push(await ensureProtectedDir(layout.defaultHooksDir))
282
179
  const files: string[] = []
283
- for (const rel of PROTECTED_GIT_FILES) {
284
- files.push(await ensureProtectedFile(join(agentDir, rel)))
285
- }
180
+ for (const configFile of layout.configFiles) files.push(await ensureProtectedFile(configFile))
181
+ if (layout.gitEntryFile !== undefined) files.push(layout.gitEntryFile)
286
182
 
287
- const hooksPathDir = await resolveEffectiveHooksPath(agentDir)
183
+ const hooksPathDir = await resolveEffectiveHooksPath(agentDir, layout)
288
184
  if (hooksPathDir !== undefined && !dirs.includes(hooksPathDir)) {
289
185
  dirs.push(await ensureProtectedDir(hooksPathDir))
290
186
  }
291
187
 
292
- return { dirs, files }
188
+ return { dirs: dedupe(dirs), files: dedupe(files) }
189
+ }
190
+
191
+ async function resolveExistingProtectedDir(target: string): Promise<string | undefined> {
192
+ const stats = await lstatOrUndefined(target)
193
+ if (stats === undefined) return undefined
194
+ if (stats.isSymbolicLink()) throw new Error(`sandbox: refusing to protect symlinked path ${target}`)
195
+ if (!stats.isDirectory()) throw new Error(`sandbox: protected directory is not a directory ${target}`)
196
+ return target
197
+ }
198
+
199
+ export async function isGitControlPath(agentDir: string, candidate: string): Promise<boolean> {
200
+ const absolute = resolve(agentDir, candidate)
201
+ const real = await realpathOrUndefined(absolute)
202
+ const candidates = real === undefined ? [absolute] : [absolute, real]
203
+ const lexicalGit = join(agentDir, '.git')
204
+ const lexicalGitstore = join(agentDir, '.gitstore')
205
+ if (candidates.some((path) => isLexicalGitControlPath(path, lexicalGit, lexicalGitstore))) {
206
+ return true
207
+ }
208
+
209
+ const layout = await resolveGitControlLayout(agentDir)
210
+ if (layout === undefined) return false
211
+ if (candidates.some((path) => layout.configFiles.includes(path))) return true
212
+ if (candidates.some((path) => path === layout.defaultHooksDir || isInside(layout.defaultHooksDir, path))) return true
213
+ const effectiveHooks = await resolveEffectiveHooksPath(agentDir, layout)
214
+ return (
215
+ effectiveHooks !== undefined && candidates.some((path) => path === effectiveHooks || isInside(effectiveHooks, path))
216
+ )
217
+ }
218
+
219
+ function isLexicalGitControlPath(candidate: string, dotGit: string, gitstore: string): boolean {
220
+ return (
221
+ candidate === dotGit ||
222
+ candidate === join(dotGit, 'config') ||
223
+ candidate === join(dotGit, 'hooks') ||
224
+ isInside(join(dotGit, 'hooks'), candidate) ||
225
+ candidate === join(gitstore, 'config') ||
226
+ candidate === join(gitstore, 'hooks') ||
227
+ isInside(join(gitstore, 'hooks'), candidate)
228
+ )
229
+ }
230
+
231
+ type GitControlLayout = {
232
+ gitEntryFile?: string
233
+ gitDir: string
234
+ defaultHooksDir: string
235
+ configFiles: string[]
236
+ }
237
+
238
+ async function resolveGitControlLayout(agentDir: string): Promise<GitControlLayout | undefined> {
239
+ const dotGit = join(agentDir, '.git')
240
+ const gitstore = join(agentDir, '.gitstore')
241
+ let gitDir: string
242
+ let gitEntryFile: string | undefined
243
+
244
+ const dotGitStats = await lstatOrUndefined(dotGit)
245
+ if (dotGitStats?.isDirectory()) {
246
+ gitDir = dotGit
247
+ } else if (dotGitStats?.isFile()) {
248
+ const pointer = await readFile(dotGit, 'utf8')
249
+ const match = /^gitdir:\s*(.+?)\s*$/im.exec(pointer)
250
+ if (match?.[1] === undefined) throw new Error(`sandbox: invalid worktree gitdir pointer ${dotGit}`)
251
+ gitDir = resolve(agentDir, match[1])
252
+ await assertRealDirectory(gitDir)
253
+ gitEntryFile = dotGit
254
+ } else {
255
+ const gitstoreStats = await lstatOrUndefined(gitstore)
256
+ if (!gitstoreStats?.isDirectory()) return undefined
257
+ gitDir = gitstore
258
+ }
259
+
260
+ const commonDir = await resolveCommonGitDir(gitDir)
261
+ const rootConfigFiles = [join(commonDir, 'config')]
262
+ const worktreeConfig = join(gitDir, 'config.worktree')
263
+ if (await isRealEntry(worktreeConfig, 'file')) rootConfigFiles.push(worktreeConfig)
264
+ const configFiles = await resolveLocalConfigFiles(agentDir, gitDir, rootConfigFiles)
265
+ return { gitEntryFile, gitDir, defaultHooksDir: join(commonDir, 'hooks'), configFiles }
266
+ }
267
+
268
+ async function resolveLocalConfigFiles(agentDir: string, gitDir: string, roots: readonly string[]): Promise<string[]> {
269
+ if (!(await isRealEntry(roots[0] as string, 'file'))) return roots.map((root) => resolve(root))
270
+ const result = await execLocalGitConfig(
271
+ agentDir,
272
+ gitDir,
273
+ roots[0] as string,
274
+ ['--includes', '--show-origin', '--null', '--name-only', '--list'],
275
+ 256 * 1024,
276
+ )
277
+ const fields = result.stdout.split('\0').filter((field) => field !== '')
278
+ const origins: string[] = []
279
+ for (let index = 0; index < fields.length; index += 2) {
280
+ const origin = fields[index]
281
+ if (origin === undefined || !origin.startsWith('file:')) continue
282
+ const configFile = resolve(origin.slice('file:'.length))
283
+ if (configFile === agentDir || isInside(agentDir, configFile)) origins.push(configFile)
284
+ }
285
+ return dedupe([...roots.map((root) => resolve(root)), ...origins])
286
+ }
287
+
288
+ async function resolveCommonGitDir(gitDir: string): Promise<string> {
289
+ try {
290
+ const relative = (await readFile(join(gitDir, 'commondir'), 'utf8')).trim()
291
+ if (relative.length === 0) return gitDir
292
+ const commonDir = resolve(gitDir, relative)
293
+ await assertRealDirectory(commonDir)
294
+ return commonDir
295
+ } catch (error) {
296
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return gitDir
297
+ throw error
298
+ }
299
+ }
300
+
301
+ async function assertRealDirectory(target: string): Promise<void> {
302
+ const stats = await lstat(target)
303
+ if (!stats.isDirectory() || stats.isSymbolicLink()) {
304
+ throw new Error(`sandbox: refusing non-directory git control root ${target}`)
305
+ }
306
+ }
307
+
308
+ async function lstatOrUndefined(target: string): Promise<Awaited<ReturnType<typeof lstat>> | undefined> {
309
+ try {
310
+ return await lstat(target)
311
+ } catch (error) {
312
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
313
+ throw error
314
+ }
293
315
  }
294
316
 
295
317
  // Fail closed: a symlink at a protected path would make the RO bind follow it
@@ -319,26 +341,68 @@ async function assertNotSymlink(target: string): Promise<void> {
319
341
  }
320
342
  }
321
343
 
322
- // Reads core.hooksPath straight from .git/config text (the file is about to be
323
- // RO-bound, so its content is the trusted baseline). Returns the resolved
324
- // absolute dir only when it lands inside agentDir — an outside path is not
325
- // writable by the jail and a relative path resolves against the repo root, per
326
- // gitconfig semantics.
327
- async function resolveEffectiveHooksPath(agentDir: string): Promise<string | undefined> {
328
- let text: string
344
+ // Ask Git to parse the effective value so quoting, escapes, comments, include,
345
+ // and includeIf semantics exactly match the process that may later run hooks.
346
+ // Global/system config and prompt-driven helpers are disabled so only the
347
+ // repository-owned config graph can influence the result.
348
+ async function resolveEffectiveHooksPath(agentDir: string, layout: GitControlLayout): Promise<string | undefined> {
349
+ let raw: string
329
350
  try {
330
- text = await readFile(join(agentDir, '.git', 'config'), 'utf8')
331
- } catch {
332
- return undefined
351
+ const result = await execLocalGitConfig(
352
+ agentDir,
353
+ layout.gitDir,
354
+ layout.configFiles[0] as string,
355
+ ['--includes', '--path', '--get', 'core.hooksPath'],
356
+ 64 * 1024,
357
+ )
358
+ raw = result.stdout.trim()
359
+ } catch (error) {
360
+ const code = (error as { code?: number | string }).code
361
+ if (code === 1) return undefined
362
+ throw error
333
363
  }
334
- const match = text.match(/^\s*hooksPath\s*=\s*(.+?)\s*$/m)
335
- if (match === null) return undefined
336
- const raw = match[1]?.trim()
337
- if (raw === undefined || raw.length === 0) return undefined
364
+ if (raw.length === 0) return undefined
338
365
  const resolved = isAbsolute(raw) ? resolve(raw) : resolve(agentDir, raw)
339
366
  return isInside(agentDir, resolved) ? resolved : undefined
340
367
  }
341
368
 
369
+ function gitConfigEnv(agentDir: string, gitDir: string): NodeJS.ProcessEnv {
370
+ return {
371
+ PATH: process.env.PATH ?? '/usr/bin:/bin',
372
+ HOME: agentDir,
373
+ GIT_DIR: gitDir,
374
+ GIT_WORK_TREE: agentDir,
375
+ GIT_CONFIG_GLOBAL: '/dev/null',
376
+ GIT_CONFIG_NOSYSTEM: '1',
377
+ GIT_TERMINAL_PROMPT: '0',
378
+ }
379
+ }
380
+
381
+ async function execLocalGitConfig(
382
+ agentDir: string,
383
+ gitDir: string,
384
+ rootConfig: string,
385
+ args: string[],
386
+ maxBuffer: number,
387
+ ): Promise<{ stdout: string; stderr: string }> {
388
+ const options = { env: gitConfigEnv(agentDir, gitDir), maxBuffer }
389
+ try {
390
+ return await execFileAsync(
391
+ 'git',
392
+ [`--git-dir=${gitDir}`, `--work-tree=${agentDir}`, 'config', '--local', ...args],
393
+ options,
394
+ )
395
+ } catch (error) {
396
+ const stderr = (error as { stderr?: string }).stderr ?? ''
397
+ if (!stderr.includes('--local can only be used inside a git repository')) throw error
398
+ return execFileAsync(
399
+ 'git',
400
+ [`--git-dir=${gitDir}`, `--work-tree=${agentDir}`, 'config', '--file', rootConfig, ...args],
401
+ options,
402
+ )
403
+ }
404
+ }
405
+
342
406
  // SECURITY: a writable RW bind renders AFTER the masks and last-op-wins, so an
343
407
  // RW bind on a masked path would re-expose the real (hidden) directory. Drop any
344
408
  // writable zone that is, or is nested under, a masked path so the confidentiality
@@ -21,3 +21,11 @@ export {
21
21
  exportClaudeCredentialsFileIfApplicable,
22
22
  resolveClaudeCredentialsPath,
23
23
  } from './export-claude-credentials-file'
24
+
25
+ export {
26
+ type ProviderRefreshEntry,
27
+ type ProviderRefreshOutcome,
28
+ type RefreshProviderOAuthResult,
29
+ refreshProviderOAuthCredentials,
30
+ refreshProviderOAuthForAgent,
31
+ } from './refresh-provider-oauth'
@@ -0,0 +1,128 @@
1
+ import { join } from 'node:path'
2
+
3
+ import type { AuthStorage } from '@mariozechner/pi-coding-agent'
4
+
5
+ import { createSecretsStoreForAgent } from './storage'
6
+
7
+ // Outcome for a single provider's proactive-refresh probe. `valid-or-refreshed`
8
+ // collapses "token was still good" and "token was expired and we refreshed it"
9
+ // on purpose — from the caller's view both mean "this provider can serve a turn
10
+ // now", and the SDK doesn't tell us which of the two happened. `refresh-failed`
11
+ // is the only actionable state: the token was expired and the refresh POST (or
12
+ // the lookup of the OAuth provider) did not yield a usable key.
13
+ export type ProviderRefreshOutcome = 'valid-or-refreshed' | 'refresh-failed'
14
+
15
+ export type ProviderRefreshEntry = {
16
+ providerId: string
17
+ outcome: ProviderRefreshOutcome
18
+ // Populated only for `refresh-failed`, drained from AuthStorage's internal
19
+ // error log so operators see WHY the refresh failed (network, 400 from the
20
+ // token endpoint, revoked refresh token, unknown OAuth provider).
21
+ error?: string
22
+ }
23
+
24
+ export type RefreshProviderOAuthResult = {
25
+ entries: ProviderRefreshEntry[]
26
+ }
27
+
28
+ export type RefreshProviderOAuthOptions = {
29
+ authStorage: AuthStorage
30
+ log?: (message: string) => void
31
+ }
32
+
33
+ // Proactively resolves every stored OAuth provider credential once, forcing the
34
+ // SDK's lazy refresh-and-persist path to run at boot instead of on the first
35
+ // user-facing turn.
36
+ //
37
+ // WHY THIS EXISTS. `AuthStorage.getApiKey()` is the SDK's only refresh trigger,
38
+ // and it is lazy: it fires on the first LLM call for a provider. A container
39
+ // that restarts with an already-expired access token therefore doesn't refresh
40
+ // until a real turn runs — and if that refresh then fails (a wedged network
41
+ // stack, a rotated refresh token), the failure surfaces as a generic
42
+ // provider-error notice posted into a live channel/PR thread. Channel-adapter
43
+ // OAuth already has host-side renewal crons (Kakao/Webex/Teams); provider OAuth
44
+ // had nothing. This closes that gap by paying the refresh cost at boot, where a
45
+ // failure is logged for the operator rather than shown to end users.
46
+ //
47
+ // Reuses the SDK path verbatim rather than re-implementing token refresh: a
48
+ // single `getApiKey()` call per provider runs the exact locked
49
+ // refresh-then-persist-to-secrets.json flow the runtime uses on every turn, so
50
+ // a boot-refreshed token is written back through the same atomic writer and no
51
+ // second refresh implementation can drift from it. `includeFallback: false`
52
+ // keeps an unrelated env var from masking an OAuth refresh failure as success.
53
+ //
54
+ // Never throws: a boot-time credential probe must not block the agent from
55
+ // starting. Each provider is isolated — one provider's failure doesn't stop the
56
+ // others from being probed — and every failure is returned for the caller to
57
+ // log.
58
+ export async function refreshProviderOAuthCredentials(
59
+ options: RefreshProviderOAuthOptions,
60
+ ): Promise<RefreshProviderOAuthResult> {
61
+ const { authStorage } = options
62
+ const entries: ProviderRefreshEntry[] = []
63
+
64
+ const oauthProviderIds = Object.entries(authStorage.getAll())
65
+ .filter(([, cred]) => cred.type === 'oauth')
66
+ .map(([providerId]) => providerId)
67
+
68
+ for (const providerId of oauthProviderIds) {
69
+ // getApiKey drives the locked refresh-and-persist internally. A non-empty
70
+ // return means the provider can serve a turn now (token was valid, or was
71
+ // expired and got refreshed + written back). `undefined` means the refresh
72
+ // truly failed — the SDK deliberately does NOT fall back to the stale token.
73
+ const apiKey = await resolveApiKeySafely(authStorage, providerId)
74
+ // Always drain so one provider's recorded error can't leak into the next
75
+ // provider's outcome. drainErrors clears the buffer as it reads.
76
+ const drained = authStorage.drainErrors()
77
+
78
+ if (apiKey !== undefined && apiKey !== '') {
79
+ entries.push({ providerId, outcome: 'valid-or-refreshed' })
80
+ continue
81
+ }
82
+
83
+ const error = drained.length > 0 ? drained.map((e) => e.message).join('; ') : 'refresh returned no API key'
84
+ options.log?.(`refreshProviderOAuth: ${providerId} refresh failed: ${error}`)
85
+ entries.push({ providerId, outcome: 'refresh-failed', error })
86
+ }
87
+
88
+ return { entries }
89
+ }
90
+
91
+ // getApiKey already swallows refresh errors into drainErrors and returns
92
+ // undefined, but guard the call itself so an unexpected throw (e.g. a corrupt
93
+ // credential shape the SDK doesn't expect) degrades to a failed entry instead
94
+ // of aborting the whole boot-time sweep.
95
+ async function resolveApiKeySafely(authStorage: AuthStorage, providerId: string): Promise<string | undefined> {
96
+ try {
97
+ return await authStorage.getApiKey(providerId, { includeFallback: false })
98
+ } catch {
99
+ return undefined
100
+ }
101
+ }
102
+
103
+ export type RefreshProviderOAuthForAgentOptions = {
104
+ agentDir: string
105
+ log?: (message: string) => void
106
+ }
107
+
108
+ // Boot-time convenience wrapper for src/run/index.ts, mirroring
109
+ // exportCodexAuthFileForAgent's contract: takes agentDir, never throws, returns
110
+ // a result the caller can log or ignore. Builds the same AuthStorage the run
111
+ // stage uses per provider (createSecretsStoreForAgent) so the refresh writes
112
+ // back through the bind-mounted secrets.json exactly as a live turn would.
113
+ export async function refreshProviderOAuthForAgent(
114
+ options: RefreshProviderOAuthForAgentOptions,
115
+ ): Promise<RefreshProviderOAuthResult> {
116
+ let authStorage: AuthStorage
117
+ try {
118
+ authStorage = createSecretsStoreForAgent(join(options.agentDir, 'secrets.json'))
119
+ } catch (err) {
120
+ const reason = err instanceof Error ? err.message : String(err)
121
+ options.log?.(`refreshProviderOAuth: ${reason}`)
122
+ return { entries: [] }
123
+ }
124
+ return refreshProviderOAuthCredentials({
125
+ authStorage,
126
+ ...(options.log !== undefined ? { log: options.log } : {}),
127
+ })
128
+ }
@@ -214,8 +214,14 @@ export function createCommandRunner(opts: CommandRunnerOptions): CommandRunner {
214
214
  return (command as EitherCommand<unknown>).run(ctx, argsParse.value)
215
215
  })()
216
216
 
217
+ // Logger lines are queued, not written inline, so they can still be in
218
+ // flight when `run` returns. `command_exit` is terminal for the call —
219
+ // `src/server/index.ts` drops the callId's websocket route as it sends it —
220
+ // so any frame emitted after exit is discarded. Drain the sink first on
221
+ // BOTH paths, or the last lines a command logs never reach the caller.
217
222
  const done = ctxPromise
218
- .then((code) => {
223
+ .then(async (code) => {
224
+ await drainWrites(stderrSink)
219
225
  if (typeof code !== 'number' || !Number.isFinite(code)) {
220
226
  opts.outbound.error(callId, `command "${name}" returned a non-numeric exit code`)
221
227
  opts.outbound.exit(callId, 1)
@@ -223,7 +229,8 @@ export function createCommandRunner(opts: CommandRunnerOptions): CommandRunner {
223
229
  }
224
230
  opts.outbound.exit(callId, code)
225
231
  })
226
- .catch((err: unknown) => {
232
+ .catch(async (err: unknown) => {
233
+ await drainWrites(stderrSink)
227
234
  const detail = err instanceof Error ? err.message : String(err)
228
235
  opts.outbound.error(callId, detail)
229
236
  opts.outbound.exit(callId, 1)
@@ -359,9 +366,46 @@ function makeWritable(onChunk: (chunk: Uint8Array) => void): WritableStream<Uint
359
366
  })
360
367
  }
361
368
 
369
+ // One sink backs every logger line for a command, and `getWriter()` throws
370
+ // while another writer holds the lock. Releasing in a `.then()` returns the
371
+ // lock a microtask too late: the next `logger.*` call runs synchronously from
372
+ // `ctx.run` and finds the stream still locked, so the line is lost and the
373
+ // throw escapes into the command. Chain each line onto the previous write so
374
+ // only one writer exists at a time, and release in `finally` so a rejected
375
+ // write can't strand the lock permanently.
376
+ //
377
+ // Keyed per stream rather than held for the run because the same sink is also
378
+ // handed to plugins as `ctx.stderr`; the lock has to be dropped between lines
379
+ // or a plugin writing to it directly would be locked out.
380
+ //
381
+ // Scope of the `.catch()` on the stored tail: it keeps ONE failed write from
382
+ // rejecting the promise every later line chains onto, and it keeps the lock
383
+ // released. It does NOT restore delivery — per the Streams standard a sink
384
+ // that throws leaves the stream errored, and every subsequent `write()`
385
+ // rejects with that same error. Recovering delivery would mean replacing the
386
+ // sink, which is out of scope here.
387
+ const writeTails = new WeakMap<WritableStream<Uint8Array>, Promise<void>>()
388
+
362
389
  function writeLine(stream: WritableStream<Uint8Array>, line: string): void {
363
- const writer = stream.getWriter()
364
- void writer.write(new TextEncoder().encode(`${line}\n`)).then(() => writer.releaseLock())
390
+ const bytes = new TextEncoder().encode(`${line}\n`)
391
+ const tail = (writeTails.get(stream) ?? Promise.resolve()).then(async () => {
392
+ const writer = stream.getWriter()
393
+ try {
394
+ await writer.write(bytes)
395
+ } finally {
396
+ writer.releaseLock()
397
+ }
398
+ })
399
+ writeTails.set(
400
+ stream,
401
+ tail.catch(() => {}),
402
+ )
403
+ }
404
+
405
+ // Settles once every line queued on `stream` so far has been handed to the
406
+ // sink. The stored tail already absorbs rejections, so this never throws.
407
+ function drainWrites(stream: WritableStream<Uint8Array>): Promise<void> {
408
+ return writeTails.get(stream) ?? Promise.resolve()
365
409
  }
366
410
 
367
411
  export type CreateSessionForCommand = (options: CreateSessionOptions) => Promise<CreateSessionResult>
@@ -38,6 +38,7 @@ import type { ChannelRouter } from '@/channels/router'
38
38
  import { getConfig, resolveModel } from '@/config'
39
39
  import { aggregateCronList, type CronJob, type CronListEntry, loadCron } from '@/cron'
40
40
  import type { McpManager } from '@/mcp'
41
+ import type { PermissionService } from '@/permissions'
41
42
  import type { HookBus } from '@/plugin'
42
43
  import type { BrokerWsData, ContainerBroker } from '@/portbroker'
43
44
  import type { ReloadAllResult, ReloadRegistry } from '@/reload'
@@ -83,6 +84,7 @@ export type ServerOptions = {
83
84
  mcpManager?: McpManager
84
85
  agentDir?: string
85
86
  pluginRuntime?: PluginRuntime
87
+ permissions?: PermissionService
86
88
  // Durable cron fire-progress lookup so `cron list` marks count-exhausted jobs
87
89
  // as retired instead of showing a stale future fire time. Omit in tests/dev.
88
90
  getFiredCount?: (job: CronJob) => number
@@ -280,6 +282,7 @@ export function createServer({
280
282
  mcpManager,
281
283
  agentDir,
282
284
  pluginRuntime,
285
+ permissions,
283
286
  getFiredCount,
284
287
  containerName,
285
288
  runtimeVersion,
@@ -531,6 +534,7 @@ export function createServer({
531
534
  ...(channelRouter ? { channelRouter } : {}),
532
535
  ...(mcpManager ? { mcpManager } : {}),
533
536
  ...(pluginsWiring ? { plugins: pluginsWiring } : {}),
537
+ ...(permissions !== undefined ? { permissions } : {}),
534
538
  ...(containerName !== undefined ? { containerName } : {}),
535
539
  ...(runtimeVersion !== undefined ? { runtimeVersion } : {}),
536
540
  ...(liveSubagentRegistry !== undefined ? { liveSubagentRegistry } : {}),