typeclaw 0.50.0 → 0.52.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 (258) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +17 -0
  2. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  3. package/dist/types/agent/bash-sandbox.d.ts +98 -0
  4. package/dist/types/agent/compaction.d.ts +4 -4
  5. package/dist/types/agent/idle-compaction.d.ts +1 -0
  6. package/dist/types/agent/index.d.ts +10 -17
  7. package/dist/types/agent/multimodal/look-at.d.ts +1 -1
  8. package/dist/types/agent/output-allowance.d.ts +4 -0
  9. package/dist/types/agent/plugin-tools.d.ts +8 -75
  10. package/dist/types/agent/prompt-cache-key.d.ts +1 -0
  11. package/dist/types/agent/session-tail.d.ts +12 -0
  12. package/dist/types/agent/subagents.d.ts +5 -0
  13. package/dist/types/agent/system-prompt-composition.d.ts +18 -0
  14. package/dist/types/agent/system-prompt.d.ts +2 -0
  15. package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
  16. package/dist/types/agent/tools/channel-edit.d.ts +1 -1
  17. package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
  18. package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
  19. package/dist/types/agent/tools/channel-history.d.ts +1 -1
  20. package/dist/types/agent/tools/channel-react.d.ts +1 -1
  21. package/dist/types/agent/tools/channel-read.d.ts +10 -2
  22. package/dist/types/agent/tools/channel-reply.d.ts +1 -1
  23. package/dist/types/agent/tools/channel-send.d.ts +1 -1
  24. package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
  25. package/dist/types/agent/tools/ddg.d.ts +9 -0
  26. package/dist/types/agent/tools/grant-role.d.ts +1 -1
  27. package/dist/types/agent/tools/post-github-review.d.ts +1 -1
  28. package/dist/types/agent/tools/restart.d.ts +1 -1
  29. package/dist/types/agent/tools/skip-response.d.ts +1 -1
  30. package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
  31. package/dist/types/agent/tools/stream-snapshot.d.ts +2 -2
  32. package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
  33. package/dist/types/agent/tools/subagent-output.d.ts +1 -1
  34. package/dist/types/agent/tools/todo/index.d.ts +1 -1
  35. package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
  36. package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
  37. package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
  38. package/dist/types/agent/tools/websearch.d.ts +1 -1
  39. package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
  40. package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
  41. package/dist/types/channels/adapters/github/auth.d.ts +24 -0
  42. package/dist/types/channels/github-review-check.d.ts +1 -1
  43. package/dist/types/channels/github-token-bridge.d.ts +4 -0
  44. package/dist/types/channels/lost-background-context.d.ts +2 -0
  45. package/dist/types/channels/persistence.d.ts +1 -0
  46. package/dist/types/channels/router.d.ts +16 -50
  47. package/dist/types/channels/types.d.ts +1 -0
  48. package/dist/types/coding-agent/tool.d.ts +1 -1
  49. package/dist/types/config/config.d.ts +22 -0
  50. package/dist/types/config/providers.d.ts +50 -1
  51. package/dist/types/container/start.d.ts +1 -0
  52. package/dist/types/eval/cell.d.ts +26 -0
  53. package/dist/types/eval/config.d.ts +19 -0
  54. package/dist/types/eval/dispatch.d.ts +7 -0
  55. package/dist/types/eval/kernel.d.ts +28 -0
  56. package/dist/types/eval/process.d.ts +23 -0
  57. package/dist/types/eval/protocol.d.ts +34 -0
  58. package/dist/types/eval/sandbox.d.ts +12 -0
  59. package/dist/types/eval/tool.d.ts +17 -0
  60. package/dist/types/eval/wire.d.ts +33 -0
  61. package/dist/types/git/resolve-identity.d.ts +2 -0
  62. package/dist/types/init/dockerfile.d.ts +1 -0
  63. package/dist/types/init/gitignore.d.ts +1 -1
  64. package/dist/types/permissions/builtins.d.ts +1 -0
  65. package/dist/types/plugin/types.d.ts +3 -0
  66. package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
  67. package/dist/types/sandbox/coding-agent.d.ts +1 -1
  68. package/dist/types/sandbox/dependency-bins.d.ts +1 -0
  69. package/dist/types/sandbox/dev-source.d.ts +2 -2
  70. package/dist/types/sandbox/env-exposure.d.ts +2 -0
  71. package/dist/types/sandbox/hidden-paths.d.ts +1 -0
  72. package/dist/types/sandbox/index.d.ts +1 -1
  73. package/dist/types/sandbox/policy.d.ts +3 -0
  74. package/dist/types/typevault/cli-path.d.ts +2 -0
  75. package/dist/types/typevault/envelope-store.d.ts +11 -0
  76. package/dist/types/typevault/lifecycle.d.ts +13 -0
  77. package/dist/types/typevault/vault.d.ts +27 -0
  78. package/package.json +8 -7
  79. package/scripts/test.ts +252 -0
  80. package/src/agent/bash-sandbox-env.ts +136 -0
  81. package/src/agent/bash-sandbox-proc.ts +70 -0
  82. package/src/agent/bash-sandbox.ts +239 -0
  83. package/src/agent/compaction.ts +22 -10
  84. package/src/agent/idle-compaction.ts +7 -3
  85. package/src/agent/index.ts +185 -187
  86. package/src/agent/multimodal/look-at.ts +1 -1
  87. package/src/agent/output-allowance.ts +7 -0
  88. package/src/agent/plugin-tools.ts +64 -380
  89. package/src/agent/prompt-cache-key.ts +26 -3
  90. package/src/agent/session-origin.ts +41 -19
  91. package/src/agent/session-tail.ts +28 -0
  92. package/src/agent/subagent-completion-reminder.ts +2 -2
  93. package/src/agent/subagents.ts +21 -2
  94. package/src/agent/system-prompt-composition.ts +159 -0
  95. package/src/agent/system-prompt.ts +43 -5
  96. package/src/agent/todo/scope.ts +1 -1
  97. package/src/agent/tool-error-remediation.ts +18 -3
  98. package/src/agent/tools/channel-disengage.ts +1 -1
  99. package/src/agent/tools/channel-edit.ts +1 -1
  100. package/src/agent/tools/channel-fetch-attachment.ts +1 -1
  101. package/src/agent/tools/channel-handoff.ts +3 -2
  102. package/src/agent/tools/channel-history.ts +2 -1
  103. package/src/agent/tools/channel-react.ts +1 -1
  104. package/src/agent/tools/channel-read.ts +36 -3
  105. package/src/agent/tools/channel-reply.ts +1 -1
  106. package/src/agent/tools/channel-send.ts +4 -3
  107. package/src/agent/tools/channel-session-search.ts +13 -4
  108. package/src/agent/tools/ddg.ts +71 -11
  109. package/src/agent/tools/grant-role.ts +1 -1
  110. package/src/agent/tools/post-github-review.ts +1 -1
  111. package/src/agent/tools/restart.ts +1 -1
  112. package/src/agent/tools/skip-response.ts +1 -1
  113. package/src/agent/tools/spawn-subagent.ts +15 -1
  114. package/src/agent/tools/stream-snapshot.ts +1 -1
  115. package/src/agent/tools/subagent-cancel.ts +1 -1
  116. package/src/agent/tools/subagent-output.ts +1 -1
  117. package/src/agent/tools/todo/index.ts +1 -1
  118. package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
  119. package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
  120. package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
  121. package/src/agent/tools/webfetch/tool.ts +6 -5
  122. package/src/agent/tools/websearch.ts +1 -1
  123. package/src/agent/tools-without-local-file-operands.ts +4 -0
  124. package/src/browser/dockerfile.ts +1 -1
  125. package/src/browser/fill-secret.ts +364 -0
  126. package/src/browser/registry.ts +6 -6
  127. package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
  128. package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
  129. package/src/bundled-plugins/backup/index.ts +17 -2
  130. package/src/bundled-plugins/backup/runner.ts +37 -2
  131. package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
  132. package/src/bundled-plugins/browser-agent/index.ts +12 -5
  133. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  134. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  135. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  136. package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
  137. package/src/bundled-plugins/managed-browser/index.ts +130 -2
  138. package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
  139. package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
  140. package/src/bundled-plugins/memory/README.md +23 -2
  141. package/src/bundled-plugins/memory/append-fragment.ts +133 -0
  142. package/src/bundled-plugins/memory/append-tool.ts +80 -149
  143. package/src/bundled-plugins/memory/dreaming.ts +6 -1
  144. package/src/bundled-plugins/memory/index.ts +33 -6
  145. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  146. package/src/bundled-plugins/memory/memory-logger.ts +200 -6
  147. package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
  148. package/src/bundled-plugins/memory/remember-tool.ts +81 -0
  149. package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
  150. package/src/bundled-plugins/memory/search-tool.ts +58 -12
  151. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  152. package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
  153. package/src/bundled-plugins/memory/transcript-preload.ts +208 -0
  154. package/src/bundled-plugins/memory/transcript-view.ts +36 -0
  155. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  156. package/src/bundled-plugins/memory/watermark.ts +19 -10
  157. package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
  158. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
  159. package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
  160. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  161. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
  162. package/src/bundled-plugins/typevault/grants.ts +119 -0
  163. package/src/bundled-plugins/typevault/index.ts +152 -0
  164. package/src/bundled-plugins/typevault/request.ts +87 -0
  165. package/src/bundled-plugins/typevault/runtime.ts +45 -0
  166. package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
  167. package/src/channels/adapter-halt.ts +17 -0
  168. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  169. package/src/channels/adapters/discord-bot.ts +1 -0
  170. package/src/channels/adapters/discord-classify.ts +8 -3
  171. package/src/channels/adapters/discord.ts +29 -0
  172. package/src/channels/adapters/github/history.ts +23 -2
  173. package/src/channels/adapters/github/inbound.ts +60 -1
  174. package/src/channels/adapters/github/index.ts +27 -5
  175. package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
  176. package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
  177. package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
  178. package/src/channels/adapters/kakaotalk-classify.ts +7 -9
  179. package/src/channels/adapters/kakaotalk-list.ts +62 -0
  180. package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
  181. package/src/channels/adapters/kakaotalk-membership.ts +27 -10
  182. package/src/channels/adapters/kakaotalk-mention.ts +61 -0
  183. package/src/channels/adapters/kakaotalk.ts +159 -125
  184. package/src/channels/adapters/teams-classify.ts +18 -8
  185. package/src/channels/github-review-check.ts +5 -1
  186. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  187. package/src/channels/github-token-bridge.ts +13 -0
  188. package/src/channels/lost-background-context.ts +46 -0
  189. package/src/channels/manager.ts +52 -3
  190. package/src/channels/persistence.ts +5 -0
  191. package/src/channels/router.ts +208 -128
  192. package/src/channels/schema.ts +1 -1
  193. package/src/channels/subagent-completion-bridge.ts +3 -2
  194. package/src/channels/types.ts +3 -0
  195. package/src/cli/hostd.ts +3 -0
  196. package/src/coding-agent/tool.ts +1 -1
  197. package/src/config/config.ts +35 -1
  198. package/src/config/providers.ts +75 -4
  199. package/src/container/start.ts +52 -3
  200. package/src/doctor/channel-checks.ts +33 -0
  201. package/src/doctor/checks.ts +37 -18
  202. package/src/doctor/index.ts +48 -12
  203. package/src/doctor/operational-incidents.ts +16 -1
  204. package/src/doctor/plugin-bridge.ts +14 -1
  205. package/src/doctor/stage.ts +14 -0
  206. package/src/doctor/types.ts +6 -0
  207. package/src/eval/cell.ts +93 -0
  208. package/src/eval/config.ts +32 -0
  209. package/src/eval/dispatch.ts +67 -0
  210. package/src/eval/entry.ts +261 -0
  211. package/src/eval/kernel.ts +154 -0
  212. package/src/eval/process.ts +113 -0
  213. package/src/eval/protocol.ts +26 -0
  214. package/src/eval/redeclare.ts +174 -0
  215. package/src/eval/sandbox.ts +117 -0
  216. package/src/eval/tool.ts +99 -0
  217. package/src/eval/wire.ts +93 -0
  218. package/src/git/resolve-identity.ts +67 -2
  219. package/src/git/system-commit.ts +7 -0
  220. package/src/init/dockerfile.ts +5 -1
  221. package/src/init/gitignore.ts +3 -3
  222. package/src/init/index.ts +1 -0
  223. package/src/init/models-dev.ts +2 -0
  224. package/src/init/validate-api-key.ts +5 -0
  225. package/src/migrations/secrets-v1-to-v2.ts +2 -0
  226. package/src/operations/classify-tool-outcome.ts +1 -1
  227. package/src/permissions/builtins.ts +8 -0
  228. package/src/plugin/core-tool-names.ts +6 -1
  229. package/src/plugin/types.ts +6 -0
  230. package/src/run/bundled-plugins.ts +12 -0
  231. package/src/run/channel-session-factory.ts +3 -0
  232. package/src/run/index.ts +13 -2
  233. package/src/sandbox/build.ts +1 -0
  234. package/src/sandbox/canonical-secrets.ts +6 -0
  235. package/src/sandbox/dependency-bins.ts +13 -1
  236. package/src/sandbox/dev-source.ts +21 -12
  237. package/src/sandbox/env-exposure.ts +20 -0
  238. package/src/sandbox/hidden-paths.ts +1 -1
  239. package/src/sandbox/index.ts +1 -0
  240. package/src/sandbox/policy.ts +5 -0
  241. package/src/secrets/hydrate.ts +4 -1
  242. package/src/secrets/storage.ts +10 -1
  243. package/src/server/command-runner.ts +4 -0
  244. package/src/server/index.ts +54 -12
  245. package/src/skills/typeclaw-config/SKILL.md +36 -2
  246. package/src/skills/typeclaw-memory/SKILL.md +3 -1
  247. package/src/skills/typeclaw-permissions/SKILL.md +8 -8
  248. package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
  249. package/src/tunnels/active.ts +14 -0
  250. package/src/typevault/bash-cli.ts +18 -0
  251. package/src/typevault/cli-path.ts +11 -0
  252. package/src/typevault/envelope-helper.ts +17 -0
  253. package/src/typevault/envelope-store.ts +98 -0
  254. package/src/typevault/lifecycle.ts +132 -0
  255. package/src/typevault/prompt-tunnel.ts +33 -0
  256. package/src/typevault/redaction.ts +37 -0
  257. package/src/typevault/vault.ts +283 -0
  258. package/typeclaw.schema.json +92 -10
@@ -74,6 +74,7 @@ export type ServerLogger = {
74
74
  }
75
75
 
76
76
  export type ServerOptions = {
77
+ readonly getGithubSelf?: CreateSessionOptions['getGithubSelf']
77
78
  port: number
78
79
  reloadAll?: ReloadAllFn
79
80
  reloadRegistry?: ReloadRegistry
@@ -197,7 +198,7 @@ type QueuedPrompt = {
197
198
  }
198
199
 
199
200
  type SessionState = {
200
- session: AgentSession
201
+ session: AgentSession & { resetLoopGuard?: () => void }
201
202
  activeModelRef: ReturnType<typeof resolveFallbackChain>[number]
202
203
  // The session's creation-time thinking level, captured once. An escalated turn
203
204
  // moves `session.thinkingLevel` to `high`, so neither turn-driving path (drain
@@ -220,6 +221,7 @@ type SessionState = {
220
221
  // generation that ran session.start. A plugin reload mid-connection does
221
222
  // not re-target this session's lifecycle hooks.
222
223
  runtimeSnapshot: PluginRuntimeState | null
224
+ sessionStarted: boolean
223
225
  unsubTurnOutcome: Unsubscribe | null
224
226
  // Serializes outcome persistence and the idle continuation decision. The
225
227
  // tail always fulfills so one disk failure cannot poison every later turn;
@@ -285,6 +287,7 @@ function encodeBase64(bytes: Uint8Array): string {
285
287
  }
286
288
 
287
289
  export function createServer({
290
+ getGithubSelf,
288
291
  port,
289
292
  reloadAll,
290
293
  reloadRegistry,
@@ -313,6 +316,7 @@ export function createServer({
313
316
  runIdleContinuation: todoIdleContinuation = runIdleContinuation,
314
317
  }: ServerOptions) {
315
318
  const sessionStates = new WeakMap<Ws, SessionState>()
319
+ const initializingSessions = new WeakMap<Ws, Promise<void>>()
316
320
  const callIdToWs = new Map<string, AnyOwnerWs>()
317
321
 
318
322
  // The first TUI WS open per container lifetime checks for
@@ -513,8 +517,11 @@ export function createServer({
513
517
  if (rawWs.data.kind === 'tunnel-logs') return
514
518
  if (rawWs.data.kind === 'inspect') return
515
519
  const ws = rawWs as Ws
520
+ const initialized = Promise.withResolvers<void>()
521
+ initializingSessions.set(ws, initialized.promise)
516
522
  try {
517
523
  const handoff = await takeRestartHandoff()
524
+ if (ws.readyState !== WebSocket.OPEN) return
518
525
  const resumed = handoff !== null ? resumeFromHandoff(handoff, sessionFactory) : null
519
526
  const sessionManager = resumed ?? sessionFactory?.createPersisted()
520
527
  const sessionFileId = sessionManager?.getSessionId() ?? ws.data.sessionId
@@ -543,6 +550,7 @@ export function createServer({
543
550
  // either side at exactly its current tool surface.
544
551
  const subagentRegistry = runtimeSnapshot?.subagents
545
552
  const result = await createSession({
553
+ getGithubSelf,
546
554
  reloadRegistry,
547
555
  sessionManager,
548
556
  origin,
@@ -576,6 +584,7 @@ export function createServer({
576
584
  unsubClaim: null,
577
585
  activeClaimCode: null,
578
586
  runtimeSnapshot: runtimeSnapshot ?? null,
587
+ sessionStarted: false,
579
588
  unsubTurnOutcome: null,
580
589
  todoOutcomeWrite: Promise.resolve(true),
581
590
  todoContinuation: { recordTurnOutcome: todoOutcomeWriter, runIdleContinuation: todoIdleContinuation },
@@ -583,10 +592,14 @@ export function createServer({
583
592
  dispose,
584
593
  }
585
594
  sessionStates.set(ws, state)
595
+ // Close owns disposal, including a factory result that arrives after disconnect.
596
+ if (ws.readyState !== WebSocket.OPEN) return
586
597
 
587
598
  if (runtimeSnapshot !== undefined && agentDir !== undefined) {
599
+ state.sessionStarted = true
588
600
  await runtimeSnapshot.hooks.runSessionStart({ sessionId: sessionFileId, agentDir })
589
601
  }
602
+ if (ws.readyState !== WebSocket.OPEN) return
590
603
 
591
604
  if (agentDir !== undefined) {
592
605
  state.unsubTurnOutcome = subscribeTurnOutcome(state, agentDir, logger)
@@ -653,6 +666,7 @@ export function createServer({
653
666
  logger.error(`[server] ${sessionFileId}: clear abort suppression failed: ${describeErr(err)}`),
654
667
  )
655
668
  }
669
+ if (ws.readyState !== WebSocket.OPEN) return
656
670
  stream.publish({
657
671
  target: { kind: 'session', sessionId: sessionFileId },
658
672
  payload: { kind: 'prompt', text: ' ', delivery: 'queue' },
@@ -664,6 +678,9 @@ export function createServer({
664
678
  console.error(`session ${ws.data.sessionId}: open failed: ${message}`)
665
679
  send(ws, { type: 'error', message })
666
680
  ws.close()
681
+ } finally {
682
+ initialized.resolve()
683
+ initializingSessions.delete(ws)
667
684
  }
668
685
  },
669
686
  async message(rawWs, raw) {
@@ -822,6 +839,7 @@ export function createServer({
822
839
  return
823
840
  }
824
841
  send(ws, { type: 'prompt_started', messageId: `local-${crypto.randomUUID()}`, text: msg.text })
842
+ state.session.resetLoopGuard?.()
825
843
  const fallbackHooks = state.runtimeSnapshot?.hooks
826
844
  const retrievalContext: { results: string } = { results: '' }
827
845
  if (fallbackHooks !== undefined && agentDir !== undefined) {
@@ -903,26 +921,47 @@ export function createServer({
903
921
  return
904
922
  }
905
923
  const ws = rawWs as Ws
906
- const state = sessionStates.get(ws)
907
- state?.unsubBroadcast?.()
908
- state?.unsubPrompts?.()
909
- state?.unsubClaim?.()
910
- if (state?.activeClaimCode !== null && state?.activeClaimCode !== undefined && claimController) {
911
- claimController.cancelClaim(state.activeClaimCode)
912
- }
913
924
  commandRunner?.abortForOwner(ws)
914
925
  for (const [callId, owner] of callIdToWs) {
915
926
  if (owner === ws) callIdToWs.delete(callId)
916
927
  }
928
+ // Do not run session.end/dispose while session creation or session.start is pending.
929
+ await initializingSessions.get(ws)
930
+ const state = sessionStates.get(ws)
917
931
  try {
918
- if (state && state.runtimeSnapshot !== null) {
932
+ state?.unsubBroadcast?.()
933
+ state?.unsubPrompts?.()
934
+ state?.unsubClaim?.()
935
+ if (state?.activeClaimCode !== null && state?.activeClaimCode !== undefined && claimController) {
936
+ claimController.cancelClaim(state.activeClaimCode)
937
+ }
938
+ if (state?.sessionStarted && state.runtimeSnapshot !== null) {
919
939
  await state.runtimeSnapshot.hooks.runSessionEnd({ sessionId: state.sessionFileId, origin: state.origin })
920
940
  }
941
+ } catch (err) {
942
+ logger.error(
943
+ `[server] ${state?.sessionFileId ?? ws.data.sessionId}: close cleanup failed: ${describeErr(err)}`,
944
+ )
945
+ }
946
+ try {
947
+ try {
948
+ state?.unsubTurnOutcome?.()
949
+ } finally {
950
+ state?.session.dispose()
951
+ }
952
+ } catch (err) {
953
+ logger.error(
954
+ `[server] ${state?.sessionFileId ?? ws.data.sessionId}: session disposal failed: ${describeErr(err)}`,
955
+ )
956
+ }
957
+ try {
958
+ await state?.dispose()
959
+ } catch (err) {
960
+ logger.error(
961
+ `[server] ${state?.sessionFileId ?? ws.data.sessionId}: resource disposal failed: ${describeErr(err)}`,
962
+ )
921
963
  } finally {
922
964
  if (state) {
923
- state.unsubTurnOutcome?.()
924
- state.session.dispose()
925
- await state.dispose()
926
965
  liveSessionRegistry?.unregister(state.sessionFileId)
927
966
  }
928
967
  sessionStates.delete(ws)
@@ -1160,6 +1199,9 @@ async function drain(
1160
1199
  if (!item) break
1161
1200
  pushQueueState(ws, state)
1162
1201
  send(ws, { type: 'prompt_started', messageId: item.streamMessageId, text: item.text })
1202
+ // Only a prompt typed in the TUI is a new request; continuations,
1203
+ // subagent completions, and restart handoffs keep the loop guard's history.
1204
+ if (item.source === 'tui') state.session.resetLoopGuard?.()
1163
1205
 
1164
1206
  if (agentDir !== undefined) {
1165
1207
  // recordTurnStart is a read-modify-write of the same state file; let
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: typeclaw-config
3
- description: "Read or edit typeclaw.json — the host-stage runtime config: model, modelOverrides (per-channel models), port, mounts, plugins, alias, channels, portForward, docker.file (container package toggles + append), git.ignore.append, plus provider credentials (secrets.json/.env) and the allowed-models registry. Strict schema with a mix of live-reloadable and restart-required fields — load before touching the file or you risk corrupting it or promising a behavior the runtime won't deliver. Also the authority on what a field defaults to and whether a behavior is already on out of the box (port forwarding, container packages, model choice) — load before saying you don't know what X defaults to, or before proposing to add a field whose default the user is asking about; most fields already default to the expected behavior, so the answer is usually 'no edit needed'. Owns the GitHub channel config — which repos it watches (channels.github.repos), the code-review trigger (channels.github.review.on/approve), webhook auto-registration via a tunnel — load on 'github channel', 'github webhook', 'review these repos', 'watch repo X', 'set up code review', 'stop reviewing repo Y'; GitHub events are an inbound channel the agent engages directly, there is NO 'forward webhooks to a Slack channel' flow, do not invent destinations. Covers recommended host paths to mount for common use cases (references/recommended-mounts.md). For messenger-channel engagement BEHAVIOR (when the agent replies vs. observes, triggers, stickiness, alias matching, suppressors) load typeclaw-channels; for who is admitted to a channel load typeclaw-permissions."
3
+ description: "Read or edit typeclaw.json — the host-stage runtime config: model, modelOverrides (per-channel models), port, mounts, plugins, alias, channels, portForward, docker.file (container package toggles + append), git.ignore.append, eval (opt-in JavaScript eval tool), plus provider credentials (secrets.json/.env) and the allowed-models registry. Strict schema with a mix of live-reloadable and restart-required fields — load before touching the file or you risk corrupting it or promising a behavior the runtime won't deliver. Also the authority on what a field defaults to and whether a behavior is already on out of the box (port forwarding, container packages, model choice) — load before saying you don't know what X defaults to, or before proposing to add a field whose default the user is asking about; most fields already default to the expected behavior, so the answer is usually 'no edit needed'. Owns the GitHub channel config — which repos it watches (channels.github.repos), the code-review trigger (channels.github.review.on/approve), webhook auto-registration via a tunnel — load on 'github channel', 'github webhook', 'review these repos', 'watch repo X', 'set up code review', 'stop reviewing repo Y'; GitHub events are an inbound channel the agent engages directly, there is NO 'forward webhooks to a Slack channel' flow, do not invent destinations. Covers recommended host paths to mount for common use cases (references/recommended-mounts.md). For messenger-channel engagement BEHAVIOR (when the agent replies vs. observes, triggers, stickiness, alias matching, suppressors) load typeclaw-channels; for who is admitted to a channel load typeclaw-permissions."
4
4
  ---
5
5
 
6
6
  # typeclaw-config
@@ -60,11 +60,12 @@ You yourself cannot run `typeclaw restart` — that is a host-stage command and
60
60
  | `browser` | no | object | `{ engines, extensions }`. `engines` from `agent-browser` (default), `omowright`, `browser-use`; `extensions` from `browserskill` (default `[]`). Anything beyond the default starts a TypeClaw-managed shared Chrome; bash gets its token-gated CDP URL only with `browser.shared`. **Restart-required** (rebuilds the image). |
61
61
  | `docker` | no | object | Namespace for Docker-related blocks. Today the only child is `docker.file` — toggles (`tmux`, `gh`, `python`, `ffmpeg`, `cjkFonts`, `cloudflared`, `xvfb`, `claudeCode`, `codexCli`, `omoCli`) gate opinionated package installs; `append` adds custom Dockerfile lines just before `ENTRYPOINT`. `docker.file` defaults to `{ ffmpeg: false, gh: true, python: true, tmux: true, cjkFonts: 'auto', cloudflared: false, xvfb: true, claudeCode: false, codexCli: false, omoCli: false, append: [] }`. Omitted from scaffolded `typeclaw.json`. **Restart-required** (next `typeclaw start` rebuilds the image). See **Dockerfile** section below. |
62
62
  | `git` | no | object | Namespace for git-related blocks. Today the only child is `git.ignore` — extra patterns spliced into the autogenerated `.gitignore` before TypeClaw's protected rules. `git.ignore` defaults to `{ "append": [] }`. Omitted from scaffolded `typeclaw.json`. **Restart-required** (next `typeclaw start` refreshes `.gitignore`). See **Gitignore** section below. |
63
+ | `eval` | no | object | `{ enabled, origins? }`. Opt-in persistent JavaScript `eval` tool that batches tool calls in one step. Defaults to off. **Restart-required.** See **eval** below. |
63
64
  | `branding` | no | boolean | Whether the system prompt discloses that you run on TypeClaw. Defaults to `true`. Set `false` to strip every TypeClaw clue from the prompt: the base prompt opens generically (no "inside TypeClaw") and the `## Runtime` version block is omitted, on both the main and subagent prompt paths. Read fresh per session. Functional identifiers (`typeclaw.json`, the `typeclaw-render-pdf` / `typeclaw-troubleshooting` skill names) are unaffected. **Live-reloadable.** |
64
65
 
65
66
  > **Top-level keys not in this table are not "ignored unknowns" anymore** — they are reserved for **plugin config blocks**. The schema's `catchall(z.unknown())` preserves them, and the plugin loader hands each block to its owning plugin's `configSchema` for validation. The bundled memory plugin owns `memory` at the top level — see the `typeclaw-memory` skill for that block's semantics. Do not write a top-level key unless you know which plugin owns it.
66
67
 
67
- Within the well-known core fields (`$schema`, `port`, `models`, `modelOverrides`, `mounts`, `plugins`, `alias`, `channels`, `portForward`, `network`, `docker`, `git`), **fields the schema doesn't predeclare are silently dropped**. Legacy top-level `dockerfile` and `gitignore` keys are no longer migrated — use `docker.file` and `git.ignore` directly (the legacy keys are silently ignored). Do not invent runtime fields like `provider`, `apiKey`, `temperature`, `maxTokens`, `systemPrompt`, `tools`, `timeout`, etc. — those are not plugin blocks, they are imaginary. If the user asks for one, say it is not yet supported and (if it makes sense) suggest they file a request.
68
+ Within the well-known core fields (`$schema`, `port`, `models`, `modelOverrides`, `mounts`, `plugins`, `alias`, `channels`, `portForward`, `network`, `docker`, `git`, `eval`), **fields the schema doesn't predeclare are silently dropped**. Legacy top-level `dockerfile` and `gitignore` keys are no longer migrated — use `docker.file` and `git.ignore` directly (the legacy keys are silently ignored). Do not invent runtime fields like `provider`, `apiKey`, `temperature`, `maxTokens`, `systemPrompt`, `tools`, `timeout`, etc. — those are not plugin blocks, they are imaginary. If the user asks for one, say it is not yet supported and (if it makes sense) suggest they file a request.
68
69
 
69
70
  A scaffolded `typeclaw.json` looks like:
70
71
 
@@ -306,6 +307,39 @@ Off switch — the broker is constructed but never opens a WS, no LISTEN gets fo
306
307
  1. **Read `typeclaw.json`** and report the policy.
307
308
  2. **You cannot enumerate the live forwarded set from inside the container.** That state lives in the `_hostd` daemon on the host and isn't surfaced through any tool you have. Say so honestly: "Per `typeclaw.json` the policy is `<...>`; for the live list of forwards the user should check `~/.typeclaw/log/hostd.log` or run a host-stage tool that queries the daemon."
308
309
 
310
+ ## eval
311
+
312
+ `eval` turns on TypeClaw's own `eval` tool: the agent writes a JavaScript cell that runs in a persistent per-session Bun kernel and calls its normal tools from inside it (`await tool.read(...)`, `tool.grep`, `tool.bash`, `parallel(...)`, `text(...)`, `print(...)`). Several dependent or independent tool calls become one model step, and intermediate output stays out of the transcript. It is not a generic "code execution" feature to be wary of: the kernel runs in the same bwrap sandbox as model bash, with the same masks and environment, and every `tool.*` call goes through the same permission and security guards as a direct call. Its power equals the bash you already have.
313
+
314
+ ```json
315
+ "eval": { "enabled": true, "origins": ["subagent", "cron"] }
316
+ ```
317
+
318
+ - `enabled` (default `false`) switches the tool on.
319
+ - `origins` limits which session kinds get it: `tui`, `channel`, `cron`, `subagent`, `system`. Omit it to allow all of them; `[]` allows none.
320
+ - **Eligibility gate:** even when enabled, `eval` only appears in sessions that already have unrestricted bash. A session without bash, or with a bash command fence (for example the `reviewer` subagent), never gets it.
321
+ - **Restart-required.** The whole block is read at boot.
322
+
323
+ ### When the user asks "enable eval" / "turn on the eval tool" / "enable eval for all origins"
324
+
325
+ This is an ordinary operator config change, not a security request to push back on. Follow **Editing `typeclaw.json` safely**: set `eval.enabled` to `true`, and set `origins` to what they named (drop the key for "all origins"). Write, commit, and tell them: "Edited `eval` — restart-required. Run `typeclaw restart` (host stage)." If the installed TypeClaw predates `eval` (the field is missing from `typeclaw.schema.json`), say it needs a TypeClaw upgrade first instead of writing a field that would be dropped.
326
+
327
+ ## typevault (experimental)
328
+
329
+ ```json
330
+ "typevault": { "enabled": true, "promptPort": 8976 }
331
+ ```
332
+
333
+ `enabled` (default `false`) keeps the agent's `secrets.json` (provider keys, channel tokens, MCP logins) in the agent's own TypeVault vault instead of a plaintext file. **Restart-required**: the move happens in `typeclaw start`. Setting it back to `false` and restarting restores `secrets.json` from the vault; anything else stored in the vault stays there for the next time it is enabled. `.env` is never touched. While enabled, `secrets.json` only holds a marker; never edit it or `.typevault/` by hand.
334
+
335
+ ### When the user asks "turn on TypeVault" / "move my secrets into the vault"
336
+
337
+ Follow **Editing `typeclaw.json` safely**: set `typevault.enabled` to `true`, commit, and tell them: "Edited `typevault` — restart-required. Run `typeclaw restart` (host stage)." Mention that it is experimental. If the installed TypeClaw predates `typevault` (the field is missing from `typeclaw.schema.json`), say it needs an upgrade first.
338
+
339
+ ### The `vault_request` secret page
340
+
341
+ The one-time secret page is served on the container port in `typevault.promptPort` (default `8976`; **restart-required**), which must not match `channels.github.webhookPort` or any other listener. To move it, set the field, commit, and tell them to run `typeclaw restart`. With `typevault.enabled`, TypeClaw opens a free Cloudflare quick tunnel to it at boot and builds `cloudflared` into the image, so nothing needs configuring. An operator who wants a stable URL can add their own `manual` tunnel with `upstreamPort` set to that port, or a `cloudflare-named` one named `typevault` (its upstream is set in Cloudflare, so it has no `upstreamPort`); either replaces the implicit one. TypeClaw can't see or change a `cloudflare-named` tunnel's origin: whenever `typevault.promptPort` changes, the operator must also retarget the origin in Cloudflare, or the link opens but no page is served.
342
+
309
343
  ## Network and model HTTP internal destinations
310
344
 
311
345
  These are two independent gates:
@@ -15,7 +15,9 @@ Under budget you get shard bodies de-duplicated across turns; over budget you ge
15
15
 
16
16
  ## Writing
17
17
 
18
- You don't author shards directly. The dreaming subagent (runs on a cron schedule, default every 30 minutes) reads undreamed fragments from `memory/streams/<date>.jsonl` and rebalances the shards. Do not edit `memory/topics/`, `memory/skills/`, or the stream files yourself — the dreaming subagent and runtime own them. To capture something memorable, surface it in your reply and let the memory-logger append it to `memory/streams/`.
18
+ You don't author shards directly. The dreaming subagent (runs on a cron schedule, default every 30 minutes) reads undreamed fragments from `memory/streams/<date>.jsonl` and rebalances the shards. Do not edit `memory/topics/`, `memory/skills/`, or the stream files yourself — the dreaming subagent and runtime own them. Use `memory_remember({ topic, body, who?, verbatim? })` when asked to remember something, when correcting a fact, or when a durable decision or preference is established; skip routine chatter. Supply a short topic and self-contained body in the evidence language. `who` optionally names the attributed person; `verbatim: true` also saves the exact body as a linked reference.
19
+
20
+ `memory_remember` is available to every role alongside `memory_search`. The runtime stamps the session, transcript anchor, and channel provenance; the fragment and optional reference are indexed immediately. Deliberate fragments carry `kind: "explicit"` but still undergo normal dreaming consolidation. The tool never advances the memory-logger watermark, and memory-logger skips facts already saved by successful calls.
19
21
 
20
22
  `memory/skills/<name>/SKILL.md` is muscle memory the dreaming subagent distills from recurring procedures; the runtime auto-loads those as first-class skills on next boot. A durable task procedure you want to keep goes to its existing editable owner skill (or a support file that skill links) first — see `typeclaw-skills` for who owns which skill — not into `memory/skills/` or `AGENTS.md`.
21
23
 
@@ -25,12 +25,12 @@ You always have these four, even if `typeclaw.json` declares zero `roles`. User-
25
25
 
26
26
  Roles form a strict tower for **bypassable plugin guards**: each role bypasses guards at its tier and below. The canonical-secret invariant sits outside this tower.
27
27
 
28
- | Role | Built-in `match[]` | Tier bypass cap | Default `permissions[]` |
29
- | --------- | ----------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
30
- | `owner` | `["tui"]` (always prepended) | `high` | `channel.respond`, `session.control`, `session.admin`, `cron.schedule`, `cron.modify`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `subagent.spawn.operator`, `fs.see.private`, `browser.shared`, `fs.see.secrets`, `security.bypass.low`, `security.bypass.medium`, `security.bypass.high`, plus every plugin-contributed `security.bypass.<guard>` (wildcard expansion) |
31
- | `trusted` | none | `medium` | `channel.respond`, `session.control`, `session.admin`, `cron.schedule`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `subagent.spawn.operator`, `fs.see.private`, `browser.shared`, `fs.see.secrets`, `security.bypass.low`, `security.bypass.medium` |
32
- | `member` | none | `low` | `channel.respond`, `session.control`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `fs.see.private`, `browser.shared`, `security.bypass.low` |
33
- | `guest` | none (fallback when nothing else matches, or stamped role is bad) | (none) | none |
28
+ | Role | Built-in `match[]` | Tier bypass cap | Default `permissions[]` |
29
+ | --------- | ----------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
30
+ | `owner` | `["tui"]` (always prepended) | `high` | `channel.respond`, `session.control`, `session.admin`, `cron.schedule`, `cron.modify`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `subagent.spawn.operator`, `fs.see.private`, `browser.shared`, `fs.see.secrets`, `vault.use`, `security.bypass.low`, `security.bypass.medium`, `security.bypass.high`, plus every plugin-contributed `security.bypass.<guard>` (wildcard expansion) |
31
+ | `trusted` | none | `medium` | `channel.respond`, `session.control`, `session.admin`, `cron.schedule`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `subagent.spawn.operator`, `fs.see.private`, `browser.shared`, `fs.see.secrets`, `vault.use`, `security.bypass.low`, `security.bypass.medium` |
32
+ | `member` | none | `low` | `channel.respond`, `session.control`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `fs.see.private`, `browser.shared`, `vault.use`, `security.bypass.low` |
33
+ | `guest` | none (fallback when nothing else matches, or stamped role is bad) | (none) | none |
34
34
 
35
35
  A session that doesn't match anything resolves to `guest`. `guest` has no `channel.respond`, so the router silently drops inbound messages whose author resolves to `guest`. **This is the most common cause of "the agent stopped responding"**: the user added a channel but did not add a match rule, so every speaker in that channel is `guest` and every inbound is dropped before you ever see it. There is no message in your session log when this happens — only a host-side line `[channels] <key>: denied by permissions (channel.respond) author=<id>`.
36
36
 
@@ -58,7 +58,7 @@ For each user turn, the current speaker's effective role is delivered in the tur
58
58
 
59
59
  **The permission list (cron/subagent block) is exhaustive at session-creation time** for the resolved role. If a permission you expect isn't listed there, the role doesn't carry it — adding it requires editing `roles.<role>.permissions[]` and restarting.
60
60
 
61
- Memory recall is globally visible by default across all roles and origins. Provenance is additive searchable metadata, not an authorization boundary. The optional `workspace`, `chat`, and `thread` parameters on `memory_search` narrow results when a focused subset is needed; no memory-specific permission grant is required.
61
+ Memory recall is globally visible by default across all roles and origins. Provenance is additive searchable metadata, not an authorization boundary. The optional `workspace`, `chat`, and `thread` parameters on `memory_search` narrow results when a focused subset is needed; no memory-specific permission grant is required. `memory_remember` is likewise available to every role; it appends a runtime-stamped fragment to the daily stream for dreaming to consolidate.
62
62
 
63
63
  ## The match-rule DSL
64
64
 
@@ -92,7 +92,7 @@ Things the DSL rejects (the parser emits actionable errors at boot, but you shou
92
92
 
93
93
  Three sources contribute permission strings:
94
94
 
95
- 1. **Core** (always present): `channel.respond`, `session.control`, `session.admin`, `cron.schedule`, `cron.modify`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `subagent.spawn.operator`, `fs.see.private`, `fs.see.secrets`, `browser.shared`.
95
+ 1. **Core** (always present): `channel.respond`, `session.control`, `session.admin`, `cron.schedule`, `cron.modify`, `subagent.spawn`, `subagent.cancel`, `subagent.output`, `subagent.spawn.operator`, `fs.see.private`, `fs.see.secrets`, `browser.shared`, `vault.use` (with `typevault.enabled`, bash gets a TypeVault grant for the role's tier and the tiers below it).
96
96
  2. **Bundled security plugin** (always loaded): the eight per-guard strings (`security.bypass.secretExfilBash`, `security.bypass.gitExfil`, `security.bypass.gitRemoteTainted`, `security.bypass.secretExfilRead`, `security.bypass.ssrf`, `security.bypass.sessionSearchSecrets`, `security.bypass.systemPromptLeak`, `security.bypass.outboundSecret`) AND three severity-tier strings (`security.bypass.low`, `security.bypass.medium`, `security.bypass.high`).
97
97
  3. **User-declared plugins** (variable): each plugin can contribute its own strings via `definePlugin({ permissions: [...] })`.
98
98
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: typeclaw-troubleshooting
3
- description: Use this skill when you are stuck in a fix-it loop — you've made roughly three attempts at the same failure and you're still cycling shell commands (kill the process, re-run, `sleep`, `capture-pane`, inspect, retry) without converging. Triggers include a hung or runaway process that won't die, a `C-c` that didn't stop the program, `<defunct>`/zombie processes piling up in `ps`, an interactive program that blocks `bash` waiting for input, a script that "ran" but produced no output and no file, repeated "not found"/timeout/same-error-again loops, and any moment you catch yourself thinking "let me wait a bit more and check again" for the third time. Also read it before you start a minutes-long or input-waiting program in your own session (dev server, REPL, watcher, `docker compose up`, interactive installer) — foreground `bash` blocks until exit, and this skill has the detached tmux start/observe/drive/stop pattern. Read it before you spawn `operator` to take over the debugging — it covers the operator hand-off prompt, the tmux session pattern, killing stuck/zombie processes properly, and the edge-triggered capture-pane polling loop that the inline retry-and-sleep approach gets wrong. Also read it when `gh` works but `git push`/`git fetch` to GitHub fails with 403, "Permission denied", or "Authentication failed", or when `gh` and git seem to act as different GitHub accounts.
3
+ description: Use this skill when you are stuck in a fix-it loop — you've made roughly three attempts at the same failure and you're still cycling shell commands (kill the process, re-run, `sleep`, `capture-pane`, inspect, retry) without converging. Triggers include a hung or runaway process that won't die, a `C-c` that didn't stop the program, `<defunct>`/zombie processes piling up in `ps`, an interactive program that blocks `bash` waiting for input, a script that "ran" but produced no output and no file, repeated "not found"/timeout/same-error-again loops, and any moment you catch yourself thinking "let me wait a bit more and check again" for the third time. Also read it before you start a minutes-long or input-waiting program in your own session (dev server, REPL, watcher, `docker compose up`, interactive installer) — foreground `bash` blocks until exit, and this skill has the detached tmux start/observe/drive/stop pattern. Read it before you spawn `operator` to take over the debugging — it covers the operator hand-off prompt, the tmux session pattern, killing stuck/zombie processes properly, and the edge-triggered capture-pane polling loop that the inline retry-and-sleep approach gets wrong. Also read it when `gh` works but `git push`/`git fetch` to GitHub fails with 403, "Permission denied", or "Authentication failed", or when `gh` and git seem to act as different GitHub accounts. Also read it when `vault_request` fails with `internal daemon error`.
4
4
  ---
5
5
 
6
6
  # typeclaw-troubleshooting
@@ -126,3 +126,20 @@ TypeClaw has two GitHub credential sources, and you cannot see either one (`secr
126
126
  These can belong to different GitHub accounts. A green `gh auth status` or a working `gh api` call proves nothing about the account `git push` uses. When a brokered git command fails on auth, TypeClaw appends a note to the result naming the credential source it used and that account's login. Read it before retrying.
127
127
 
128
128
  Do not try to fix this from inside the session. Don't rewrite the remote URL, embed a token, run `gh auth login`, or edit git credential config: the broker owns these credentials, and you can't read or change them. Report the mismatch to the operator, naming both accounts and the target repo, and tell them how to recover: correct or remove the mismatched push credential (`channels.github` in `secrets.json`, or the declared `GH_TOKEN` in `.env`), then run `typeclaw restart`.
129
+
130
+ ## TypeVault: `vault_request` fails with `internal daemon error`
131
+
132
+ The daemon returns this text for every unexpected failure and writes the real exception to its log. `.typeclaw/typevault/` is masked from your tools, so you can't read that log and shouldn't spawn `operator` to look for it. Tell the operator to run this on the host, in the agent folder:
133
+
134
+ ```sh
135
+ tail -n 40 .typeclaw/typevault/config/typevault/checkouts/*/run/daemon.log
136
+ ```
137
+
138
+ If the log says `Failed to start server. Is port <port> in use?` (`EADDRINUSE`), another process in the container holds the secret-page port (`typevault.promptPort`, default `8976`). The daemon binds that port on the first request, so `typevault whoami` still succeeds and nothing fails at boot.
139
+
140
+ - **Check first:** `channels.github.webhookPort` may match it. `typeclaw doctor` warns about this as `channel.github.webhook-port`.
141
+ - **Otherwise:** a service the agent or operator started is listening on that port.
142
+ - **Fix:** set `typevault.promptPort` in `typeclaw.json` to a free port, and don't stop the other listener. See the `typeclaw-config` skill for the edit.
143
+ - **Then restart:** after a failed bind the daemon keeps returning this error until it restarts, even once the port is free. The field is restart-required too. Tell the operator to run `typeclaw restart`, then retry `vault_request`.
144
+
145
+ Never ask the user to paste the secret into chat while this is broken.
@@ -0,0 +1,14 @@
1
+ import type { TunnelManager } from './manager'
2
+
3
+ // The container's running tunnel manager, for in-process runtime code that
4
+ // needs a tunnel's current public URL at call time (quick-tunnel URLs rotate
5
+ // on every restart, so a boot-time snapshot would go stale).
6
+ let active: Pick<TunnelManager, 'urlFor'> | undefined
7
+
8
+ export function setActiveTunnelManager(manager: Pick<TunnelManager, 'urlFor'> | undefined): void {
9
+ active = manager
10
+ }
11
+
12
+ export function activeTunnelUrl(tunnelName: string): string | null {
13
+ return active?.urlFor(tunnelName) ?? null
14
+ }
@@ -0,0 +1,18 @@
1
+ import { typevaultCliPath } from './cli-path'
2
+
3
+ // The `typevault` command in model bash. Its grant and vault reach bash under
4
+ // TypeClaw's own names, so a project's own typevault CLI (`bun typevault` in a
5
+ // checkout) never finds a TYPEVAULT_* variable steering it to the agent's
6
+ // vault. Only this command maps them back.
7
+ const env = process.env
8
+ if (env.TYPECLAW_VAULT_DIR) {
9
+ env.TYPEVAULT_DIR = env.TYPECLAW_VAULT_DIR
10
+ env.TYPEVAULT_GLOBAL = '1'
11
+ }
12
+ if (env.TYPECLAW_VAULT_GRANT) env.TYPEVAULT_GRANT = env.TYPECLAW_VAULT_GRANT
13
+ // typevault strips its own TYPEVAULT_* variables from a `run` child; these
14
+ // would otherwise hand the child the session's whole grant.
15
+ delete env.TYPECLAW_VAULT_DIR
16
+ delete env.TYPECLAW_VAULT_GRANT
17
+
18
+ await import(typevaultCliPath())
@@ -0,0 +1,11 @@
1
+ import { dirname, join } from 'node:path'
2
+
3
+ // Resolved without importing the SDK, so the bash sandbox can wrap the CLI
4
+ // without loading typevault on every agent.
5
+ export function typevaultCliPath(): string {
6
+ return join(dirname(Bun.resolveSync('typevault', import.meta.dir)), 'cli', 'index.ts')
7
+ }
8
+
9
+ export function typevaultBashCliPath(): string {
10
+ return join(import.meta.dir, 'bash-cli.ts')
11
+ }
@@ -0,0 +1,17 @@
1
+ import { requireSecretsEntry, writeSecretsEntry } from './vault'
2
+
3
+ const [op, agentDir] = process.argv.slice(2)
4
+
5
+ try {
6
+ if (agentDir === undefined) throw new Error('usage: envelope-helper.ts <read|write> <agentDir>')
7
+ if (op === 'read') {
8
+ process.stdout.write(await requireSecretsEntry(agentDir))
9
+ } else if (op === 'write') {
10
+ await writeSecretsEntry(agentDir, await Bun.stdin.text())
11
+ } else {
12
+ throw new Error(`unknown operation: ${op}`)
13
+ }
14
+ } catch (error) {
15
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
16
+ process.exit(1)
17
+ }
@@ -0,0 +1,98 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import { typevaultDir } from './vault'
5
+
6
+ // secrets.json while the envelope lives in the vault. Its `version` is not 2,
7
+ // so a TypeClaw build without vault support refuses the file loudly instead of
8
+ // booting with an empty credential store.
9
+ export const TYPEVAULT_SECRETS_MARKER = {
10
+ $comment:
11
+ 'TypeClaw keeps this agent\'s secrets in its TypeVault vault (.typevault/). Set typevault.enabled to false in typeclaw.json and run "typeclaw restart" to restore this file.',
12
+ version: 'typevault',
13
+ } as const
14
+
15
+ export function typevaultMarkerText(): string {
16
+ return `${JSON.stringify(TYPEVAULT_SECRETS_MARKER, null, 2)}\n`
17
+ }
18
+
19
+ export function isTypevaultMarker(raw: string): boolean {
20
+ try {
21
+ const parsed: unknown = JSON.parse(raw)
22
+ return (
23
+ typeof parsed === 'object' &&
24
+ parsed !== null &&
25
+ (parsed as { version?: unknown }).version === TYPEVAULT_SECRETS_MARKER.version
26
+ )
27
+ } catch {
28
+ return false
29
+ }
30
+ }
31
+
32
+ export function isTypevaultMarkerFile(secretsPath: string): boolean {
33
+ return existsSync(secretsPath) && isTypevaultMarker(readFileSync(secretsPath, 'utf8'))
34
+ }
35
+
36
+ type CachedEnvelope = { text: string; stamp: string }
37
+
38
+ const cache = new Map<string, CachedEnvelope>()
39
+
40
+ // SecretsBackend's contract is synchronous, while typevault's SDK is async, so
41
+ // reads and writes cross into a short-lived helper process. Reads are cached
42
+ // per agent and refetched only when the vault's entries changed, which also
43
+ // picks up writes made by another process. Reads are lock-free, so a snapshot
44
+ // is cached only when no write landed while it was being fetched; otherwise an
45
+ // old envelope could be labelled with a newer write's stamp and later
46
+ // overwrite that write.
47
+ export function readEnvelopeTextSync(
48
+ agentDir: string,
49
+ fetch: (agentDir: string) => string = (dir) => runHelperSync(dir, 'read'),
50
+ ): string {
51
+ const before = entriesStamp(agentDir)
52
+ const cached = cache.get(agentDir)
53
+ if (cached !== undefined && cached.stamp === before) return cached.text
54
+ const text = fetch(agentDir)
55
+ if (entriesStamp(agentDir) === before) cache.set(agentDir, { text, stamp: before })
56
+ else cache.delete(agentDir)
57
+ return text
58
+ }
59
+
60
+ export function writeEnvelopeTextSync(agentDir: string, text: string): void {
61
+ cache.delete(agentDir)
62
+ runHelperSync(agentDir, 'write', text)
63
+ cache.set(agentDir, { text, stamp: entriesStamp(agentDir) })
64
+ }
65
+
66
+ // Every entry file's name, size and mtime, not just the directory's mtime, so
67
+ // a rewrite within one coarse directory timestamp still changes the stamp.
68
+ export function entriesStamp(agentDir: string): string {
69
+ const entries = join(typevaultDir(agentDir), 'entries')
70
+ if (!existsSync(entries)) return 'absent'
71
+ return readdirSync(entries)
72
+ .sort()
73
+ .map((name) => {
74
+ const stat = statSync(join(entries, name), { throwIfNoEntry: false })
75
+ return stat === undefined ? `${name}:gone` : `${name}:${stat.size}:${stat.mtimeMs}:${stat.ino}`
76
+ })
77
+ .join('|')
78
+ }
79
+
80
+ // A synchronous spawn cannot be interrupted from JavaScript, so a helper that
81
+ // never exits would block the caller's thread for good.
82
+ const HELPER_TIMEOUT_MS = 30_000
83
+
84
+ export function runHelperSync(agentDir: string, op: 'read' | 'write', input?: string): string {
85
+ const result = Bun.spawnSync([process.execPath, join(import.meta.dir, 'envelope-helper.ts'), op, agentDir], {
86
+ stdin: input === undefined ? 'ignore' : Buffer.from(input, 'utf8'),
87
+ stdout: 'pipe',
88
+ stderr: 'pipe',
89
+ timeout: HELPER_TIMEOUT_MS,
90
+ })
91
+ if (result.exitCode !== 0) {
92
+ const reason = result.exitedDueToTimeout
93
+ ? `timed out after ${HELPER_TIMEOUT_MS}ms`
94
+ : result.stderr.toString().trim() || `exit code ${result.exitCode}`
95
+ throw new Error(`TypeVault ${op} of the secrets envelope failed: ${reason}`)
96
+ }
97
+ return result.stdout.toString()
98
+ }
@@ -0,0 +1,132 @@
1
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ import lockfile from 'proper-lockfile'
5
+
6
+ import { parseSecretsFile } from '@/secrets/schema'
7
+ import { ASYNC_LOCK_OPTIONS } from '@/secrets/storage'
8
+
9
+ import { isTypevaultMarker, typevaultMarkerText } from './envelope-store'
10
+ import {
11
+ clearLegacyDaemonClaims,
12
+ provisionVault,
13
+ readSecretsEntry,
14
+ requireSecretsEntry,
15
+ vaultExists,
16
+ writeSecretsEntry,
17
+ } from './vault'
18
+
19
+ export type TypevaultReconcileResult =
20
+ | { action: 'unchanged' }
21
+ | { action: 'enabled' }
22
+ | { action: 'resumed' }
23
+ | { action: 'restored' }
24
+ | { action: 'skipped'; warning: string }
25
+
26
+ // Runs host-side in `typeclaw start` while the container is down, so it is
27
+ // the only writer. Whichever side was live before the toggle wins: enabling
28
+ // moves secrets.json into the vault (overwriting a dormant vault's stale copy),
29
+ // disabling writes the vault's copy back. A dormant vault is resumed, never
30
+ // re-initialized, so entries stored through the vault survive the round trip.
31
+ export async function reconcileTypevault(agentDir: string, enabled: boolean): Promise<TypevaultReconcileResult> {
32
+ const secretsPath = join(agentDir, 'secrets.json')
33
+ // The common case (never enabled) must not even take the lock: start runs
34
+ // this on every launch, including agent folders it cannot write to.
35
+ if (!enabled && !isMarkerFile(secretsPath)) return { action: 'unchanged' }
36
+ const release = await lockfile.lock(secretsPath, ASYNC_LOCK_OPTIONS)
37
+ try {
38
+ clearLegacyDaemonClaims(agentDir)
39
+ return enabled ? await enable(agentDir, secretsPath) : await disable(agentDir, secretsPath)
40
+ } finally {
41
+ await release()
42
+ }
43
+ }
44
+
45
+ async function enable(agentDir: string, secretsPath: string): Promise<TypevaultReconcileResult> {
46
+ const raw = existsSync(secretsPath) ? readFileSync(secretsPath, 'utf8') : ''
47
+ const markerPresent = isTypevaultMarker(raw)
48
+ const resuming = vaultExists(agentDir)
49
+
50
+ // Already enabled: the vault holds the only copy, so it is checked, never
51
+ // provisioned. Provisioning could replace keys the ciphertext still needs.
52
+ if (markerPresent) {
53
+ try {
54
+ await requireSecretsEntry(agentDir)
55
+ return { action: 'unchanged' }
56
+ } catch (error) {
57
+ return skipped(
58
+ `secrets.json points at the TypeVault vault, but its secrets cannot be read: ${describe(error)}. ` +
59
+ 'Nothing was changed. Restore .typevault/ and .typeclaw/typevault/ from a backup of this agent folder.',
60
+ )
61
+ }
62
+ }
63
+
64
+ try {
65
+ await provisionVault(agentDir)
66
+ await readSecretsEntry(agentDir)
67
+ } catch (error) {
68
+ return skipped(
69
+ `${resuming ? "The agent's TypeVault vault (.typevault/) could not be opened" : 'Could not create the TypeVault vault'}: ${describe(error)}. ` +
70
+ 'Keeping secrets.json as the credential store. If the vault came from another copy of this agent without its key, move .typevault/ aside and restart.',
71
+ )
72
+ }
73
+
74
+ const invalid = invalidEnvelope(raw)
75
+ if (invalid !== null) {
76
+ return skipped(
77
+ `secrets.json is not a valid TypeClaw secrets file (${invalid}); fix it, then restart to move it into TypeVault.`,
78
+ )
79
+ }
80
+ await writeSecretsEntry(agentDir, raw)
81
+ if ((await requireSecretsEntry(agentDir)) !== raw) {
82
+ return skipped(
83
+ 'The secrets copied into TypeVault did not read back identically; keeping secrets.json as the credential store.',
84
+ )
85
+ }
86
+ writeAtomic(secretsPath, typevaultMarkerText())
87
+ return { action: resuming ? 'resumed' : 'enabled' }
88
+ }
89
+
90
+ async function disable(agentDir: string, secretsPath: string): Promise<TypevaultReconcileResult> {
91
+ if (!isMarkerFile(secretsPath)) return { action: 'unchanged' }
92
+ let text: string
93
+ try {
94
+ text = await requireSecretsEntry(agentDir)
95
+ } catch (error) {
96
+ return skipped(
97
+ `Could not read the secrets back out of TypeVault to restore secrets.json: ${describe(error)}. The agent keeps using the vault until this is fixed.`,
98
+ )
99
+ }
100
+ writeAtomic(secretsPath, text)
101
+ return { action: 'restored' }
102
+ }
103
+
104
+ function isMarkerFile(secretsPath: string): boolean {
105
+ return existsSync(secretsPath) && isTypevaultMarker(readFileSync(secretsPath, 'utf8'))
106
+ }
107
+
108
+ function invalidEnvelope(raw: string): string | null {
109
+ if (!raw.trim()) return null
110
+ let parsed: unknown
111
+ try {
112
+ parsed = JSON.parse(raw)
113
+ } catch (error) {
114
+ return `not valid JSON: ${describe(error)}`
115
+ }
116
+ const result = parseSecretsFile(parsed)
117
+ return result.ok ? null : result.reason
118
+ }
119
+
120
+ function writeAtomic(path: string, text: string): void {
121
+ const tmp = `${path}.${process.pid}.${Date.now()}.typevault.tmp`
122
+ writeFileSync(tmp, text, { encoding: 'utf8', mode: 0o600 })
123
+ renameSync(tmp, path)
124
+ }
125
+
126
+ function skipped(warning: string): TypevaultReconcileResult {
127
+ return { action: 'skipped', warning }
128
+ }
129
+
130
+ function describe(error: unknown): string {
131
+ return error instanceof Error ? error.message : String(error)
132
+ }