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
@@ -0,0 +1,174 @@
1
+ // Kernel-child helper, so it must stay dependency-free (see entry.ts).
2
+ //
3
+ // Models habitually reuse names like `const [a, b] = ...` across cells, and a
4
+ // REPL keeps top-level lexical bindings, so a later cell fails with "Can't
5
+ // create duplicate variable". A var cannot shadow an existing const either, so
6
+ // every cell's top-level const/let becomes var before it runs. Nested scopes
7
+ // keep their block semantics.
8
+ //
9
+ // The scan also reports top-level binding names: a top-level declaration of a
10
+ // helper like `tool` shadows it for the rest of the session, so the kernel
11
+ // refuses those cells. Initializers are skipped and collection resumes at each
12
+ // declarator comma; destructuring keys or defaults may be over-reported, which
13
+ // is acceptable for a refusal that only asks the model to rename.
14
+ const REGEX_PRECEDERS = new Set('(,=:[!&|?{};+-*%<>~^'.split(''))
15
+ const REGEX_KEYWORDS = new Set(['return', 'typeof', 'await', 'yield', 'case', 'in', 'of', 'void', 'delete', 'new'])
16
+ const CONTROL_HEADERS = new Set(['if', 'while', 'for', 'with'])
17
+
18
+ export function topLevelDeclarationsToVar(code: string): string {
19
+ return rewriteCell(code).code
20
+ }
21
+
22
+ export function rewriteCell(code: string): { code: string; declared: string[] } {
23
+ const declared: string[] = []
24
+ // A top-level declaration runs until `;` or a line end not following a comma;
25
+ // binding names are read until each declarator's `=`.
26
+ let inDeclaration = false
27
+ let collecting = false
28
+ let out = ''
29
+ let depth = 0
30
+ // Brace depths at which an open `${` returns to its enclosing template.
31
+ const templates: number[] = []
32
+ // Whether each open `(` is a control header: `/` after `if (x)` starts a
33
+ // regex, while `/` after a call like `f(x)` is division.
34
+ const parens: boolean[] = []
35
+ let previous = ''
36
+ let word = ''
37
+ let i = 0
38
+ const isIdent = (c: string | undefined) => c !== undefined && /[\p{L}\p{N}_$]/u.test(c)
39
+
40
+ const readTemplate = () => {
41
+ while (i < code.length) {
42
+ const c = code[i]
43
+ if (c === '\\') {
44
+ out += code.slice(i, i + 2)
45
+ i += 2
46
+ continue
47
+ }
48
+ if (c === '`') {
49
+ out += c
50
+ i += 1
51
+ return
52
+ }
53
+ if (c === '$' && code[i + 1] === '{') {
54
+ out += '${'
55
+ i += 2
56
+ templates.push(depth)
57
+ depth += 1
58
+ return
59
+ }
60
+ out += c
61
+ i += 1
62
+ }
63
+ }
64
+
65
+ while (i < code.length) {
66
+ const c = code[i] as string
67
+ const next = code[i + 1]
68
+ if (c === '/' && next === '/') {
69
+ const end = code.indexOf('\n', i)
70
+ const stop = end === -1 ? code.length : end
71
+ out += code.slice(i, stop)
72
+ i = stop
73
+ continue
74
+ }
75
+ if (c === '/' && next === '*') {
76
+ const end = code.indexOf('*/', i + 2)
77
+ const stop = end === -1 ? code.length : end + 2
78
+ out += code.slice(i, stop)
79
+ i = stop
80
+ continue
81
+ }
82
+ if (c === '"' || c === "'") {
83
+ let j = i + 1
84
+ while (j < code.length && code[j] !== c && code[j] !== '\n') j += code[j] === '\\' ? 2 : 1
85
+ out += code.slice(i, j + 1)
86
+ i = j + 1
87
+ previous = c
88
+ word = ''
89
+ continue
90
+ }
91
+ if (c === '`') {
92
+ out += c
93
+ i += 1
94
+ readTemplate()
95
+ previous = '`'
96
+ word = ''
97
+ continue
98
+ }
99
+ if (c === '/' && (previous === '' || REGEX_PRECEDERS.has(previous) || REGEX_KEYWORDS.has(word))) {
100
+ let j = i + 1
101
+ let inClass = false
102
+ while (j < code.length && code[j] !== '\n') {
103
+ if (code[j] === '\\') j += 1
104
+ else if (code[j] === '[') inClass = true
105
+ else if (code[j] === ']') inClass = false
106
+ else if (code[j] === '/' && !inClass) break
107
+ j += 1
108
+ }
109
+ j += 1
110
+ while (isIdent(code[j])) j += 1
111
+ out += code.slice(i, j)
112
+ i = j
113
+ previous = '/'
114
+ word = ''
115
+ continue
116
+ }
117
+ if (isIdent(c)) {
118
+ let j = i
119
+ while (isIdent(code[j])) j += 1
120
+ const token = code.slice(i, j)
121
+ const declaration =
122
+ depth === 0 &&
123
+ (token === 'const' || token === 'let' || token === 'var') &&
124
+ code[i - 1] !== '.' &&
125
+ /^\s*[[{\p{L}_$]/u.test(code.slice(j))
126
+ if (declaration) {
127
+ out += 'var'
128
+ inDeclaration = true
129
+ collecting = true
130
+ } else {
131
+ if (collecting) declared.push(token)
132
+ out += token
133
+ }
134
+ i = j
135
+ previous = token.at(-1) as string
136
+ word = token
137
+ continue
138
+ }
139
+ if (c === '(') parens.push(CONTROL_HEADERS.has(word))
140
+ if (c === '(' || c === '[' || c === '{') depth += 1
141
+ if (c === ')' && parens.pop() === true) {
142
+ depth -= 1
143
+ out += c
144
+ i += 1
145
+ previous = ';'
146
+ word = ''
147
+ continue
148
+ }
149
+ if (c === ')' || c === ']' || c === '}') {
150
+ depth -= 1
151
+ if (c === '}' && templates.at(-1) === depth) {
152
+ templates.pop()
153
+ out += c
154
+ i += 1
155
+ readTemplate()
156
+ previous = '`'
157
+ word = ''
158
+ continue
159
+ }
160
+ }
161
+ if (inDeclaration && depth === 0) {
162
+ if (c === '=') collecting = false
163
+ else if (c === ',') collecting = true
164
+ else if (c === ';' || (c === '\n' && previous !== ',')) inDeclaration = collecting = false
165
+ }
166
+ out += c
167
+ i += 1
168
+ if (!/\s/.test(c)) {
169
+ previous = c
170
+ word = ''
171
+ }
172
+ }
173
+ return { code: out, declared }
174
+ }
@@ -0,0 +1,117 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { stat } from 'node:fs/promises'
3
+ import { dirname } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ import { prepareBashSandbox } from '@/agent/bash-sandbox'
7
+ import type { SessionOrigin } from '@/agent/session-origin'
8
+ import type { GetGithubSelf } from '@/channels/github-token-bridge'
9
+ import type { PermissionService } from '@/permissions/permissions'
10
+ import { shellQuote } from '@/sandbox/quote'
11
+
12
+ import { EvalKernel } from './kernel'
13
+
14
+ // Retained bindings survive while the principal and audience are unchanged.
15
+ // A channel origin also carries conversational state (participant counters,
16
+ // timestamps, the reaction target, the review round, display names) that
17
+ // changes on every inbound message without changing authority, so it must not
18
+ // reset the kernel.
19
+ export function authorityOrigin(origin: SessionOrigin | undefined): unknown {
20
+ if (origin === undefined) return undefined
21
+ switch (origin.kind) {
22
+ case 'channel': {
23
+ const {
24
+ participants: _participants,
25
+ membership: _membership,
26
+ reactionRef: _reactionRef,
27
+ githubReviewRound: _githubReviewRound,
28
+ workspaceName: _workspaceName,
29
+ chatName: _chatName,
30
+ parentChatName: _parentChatName,
31
+ ...authority
32
+ } = origin
33
+ return authority
34
+ }
35
+ case 'subagent':
36
+ return { ...origin, spawnedByOrigin: authorityOrigin(origin.spawnedByOrigin) }
37
+ default:
38
+ return origin
39
+ }
40
+ }
41
+
42
+ export function createSandboxedEvalKernel(options: {
43
+ readonly getGithubSelf?: GetGithubSelf
44
+ readonly agentDir: string
45
+ readonly sessionId: string
46
+ readonly permissions: PermissionService
47
+ readonly getOrigin: () => SessionOrigin | undefined
48
+ }): EvalKernel {
49
+ return new EvalKernel(async () => {
50
+ const origin = options.getOrigin()
51
+ const entry = fileURLToPath(new URL('./entry.ts', import.meta.url))
52
+ const prepared = await prepareBashSandbox({
53
+ getGithubSelf: options.getGithubSelf,
54
+ command: `exec ${shellQuote(process.execPath)} --no-install ${shellQuote(entry)}`,
55
+ agentDir: options.agentDir,
56
+ sessionId: options.sessionId,
57
+ permissions: options.permissions,
58
+ origin,
59
+ // The bridge uses stdio, never a reachable loopback server. Network work
60
+ // goes through tool.bash/web_fetch with their normal guards.
61
+ network: 'none',
62
+ })
63
+ try {
64
+ await prepared.verify()
65
+ const policy = prepared.policy
66
+ const paths = new Set([
67
+ ...prepared.withheld.paths.dirs,
68
+ ...prepared.withheld.paths.files,
69
+ ...(policy.protected?.dirs ?? []),
70
+ ...(policy.protected?.files ?? []),
71
+ ...(policy.writable?.dirs ?? []),
72
+ ...(policy.writable?.files ?? []),
73
+ ...(policy.mounts ?? []).flatMap((mount) => ('source' in mount ? [mount.source] : [])),
74
+ ])
75
+ // File bind mounts pin identities, not names. An atomic replacement can
76
+ // leave a persistent process with a detached mask or protection. Include
77
+ // ancestors too: moving a directory can retain its children's inodes.
78
+ for (const path of paths) {
79
+ let parent = dirname(path)
80
+ while (!paths.has(parent)) {
81
+ paths.add(parent)
82
+ const next = dirname(parent)
83
+ if (next === parent) break
84
+ parent = next
85
+ }
86
+ }
87
+ const identities = await Promise.all(
88
+ [...paths].sort().map(async (path) => {
89
+ const identity = await stat(path, { bigint: true })
90
+ return [path, String(identity.dev), String(identity.ino)]
91
+ }),
92
+ )
93
+ return {
94
+ command: prepared.commandString,
95
+ cwd: options.agentDir,
96
+ env: prepared.spawnEnv,
97
+ // Includes the live principal, even when two principals have the same
98
+ // role. Never share retained values across a channel author change.
99
+ fingerprint: createHash('sha256')
100
+ .update(
101
+ JSON.stringify({
102
+ origin: authorityOrigin(origin),
103
+ role: options.permissions.describe(origin),
104
+ command: prepared.commandString,
105
+ env: prepared.spawnEnv,
106
+ identities,
107
+ }),
108
+ )
109
+ .digest('hex'),
110
+ cleanup: prepared.cleanup,
111
+ }
112
+ } catch (error) {
113
+ await prepared.cleanup()
114
+ throw error
115
+ }
116
+ })
117
+ }
@@ -0,0 +1,99 @@
1
+ import { defineTool, type ToolDefinition } from '@earendil-works/pi-coding-agent'
2
+ import { Type } from 'typebox'
3
+ import type { z } from 'zod'
4
+
5
+ import type { WrapSystemToolOptions } from '@/agent/plugin-tools'
6
+ import { wrapSystemTool } from '@/agent/plugin-tools'
7
+ import { wrapToolDefinitionWithBudget, type BudgetState, type ToolResultBudget } from '@/agent/tool-result-budget'
8
+ import { noopPermissionService } from '@/permissions/permissions'
9
+
10
+ import { evalEnabledForSession, type evalConfigSchema } from './config'
11
+ import { createEvalDispatch } from './dispatch'
12
+ import { EVAL_LIMITS, EvalError } from './protocol'
13
+ import { createSandboxedEvalKernel } from './sandbox'
14
+
15
+ export const EVAL_PROMPT_HINT =
16
+ 'Use eval to keep large tool output out of your context: fetch, filter or compute in the cell, and print only the answer; unprinted data never reaches you. ' +
17
+ 'It also runs steps where the next call depends on the last result in one call: ' +
18
+ "const root = 'src'; const hits = await tool.grep({ pattern: 'openDoor', path: root }); " +
19
+ "const files = [...new Set(text(hits).split('\\n').filter((l) => l.includes(':')).map((l) => root + '/' + l.split(':')[0]))].slice(0, 5); " +
20
+ 'const bodies = await parallel(files.map((f) => () => tool.read({ path: f }))); ' +
21
+ 'for (const [i, b] of bodies.entries()) print(files[i], text(b, 1500)). ' +
22
+ 'Independent reads alone do not need eval; call those tools directly. ' +
23
+ "text(result, maxChars) extracts a tool result's text; never print whole result objects. " +
24
+ 'JavaScript bindings persist in this session until idle expiry, authority changes, or kernel failure. ' +
25
+ 'Only printed/displayed output is returned. Await all work; no background cells, install helpers, or Python cells.'
26
+
27
+ export function registerEvalTool(options: {
28
+ readonly settings: z.infer<typeof evalConfigSchema>
29
+ readonly tools: ToolDefinition[]
30
+ readonly activeNames: string[]
31
+ readonly getActiveNames: () => readonly string[]
32
+ readonly wrappers: WrapSystemToolOptions
33
+ readonly budget?: ToolResultBudget
34
+ readonly budgetState?: BudgetState
35
+ }): { dispose(): Promise<void> } | undefined {
36
+ const eligible = () =>
37
+ evalEnabledForSession({
38
+ settings: options.settings,
39
+ origin: options.wrappers.getOrigin?.(),
40
+ tools: options.getActiveNames(),
41
+ bashPolicy: options.wrappers.bashPolicy,
42
+ })
43
+ if (!eligible()) return undefined
44
+ const kernel = createSandboxedEvalKernel({
45
+ getGithubSelf: options.wrappers.getGithubSelf,
46
+ agentDir: options.wrappers.agentDir,
47
+ sessionId: options.wrappers.sessionId,
48
+ permissions: options.wrappers.permissions ?? noopPermissionService,
49
+ getOrigin: () => options.wrappers.getOrigin?.(),
50
+ })
51
+ const tool = wrapSystemTool(
52
+ defineTool({
53
+ name: 'eval',
54
+ label: 'eval',
55
+ description:
56
+ 'Run a foreground JavaScript cell in a persistent, bash-sandboxed Bun kernel. ' +
57
+ 'Use await tool.read/grep/find/ls/bash/write/edit/web_search/web_fetch with their normal arguments, ' +
58
+ "parallel(thunks) (up to 8 workers), print/display(value), and text(result, maxChars = 2000) to extract a result's text. " +
59
+ 'Tool calls return the normal content/details object; print selected text, not whole results. ' +
60
+ 'A failed tool call rejects; wrap risky calls in try/catch so one failure does not discard a batch. ' +
61
+ 'tool.grep patterns are ripgrep regex: escape ( ) [ ] and . as \\\\(, lookaround is unsupported, and literal:true matches plain text. ' +
62
+ 'Only active tools are callable; recursion, orchestration, posting, role changes and MCP dispatch are refused. ' +
63
+ '30s default, 60s hard maximum; timeout kills the kernel. Output is capped at 64 KiB / 1000 lines. ' +
64
+ 'No background cells, package installation helpers or Python. Use await import(...) for modules.',
65
+ parameters: Type.Object({
66
+ code: Type.String({ maxLength: EVAL_LIMITS.codeBytes }),
67
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: EVAL_LIMITS.maxTimeoutMs })),
68
+ }),
69
+ async execute(_id, args, signal, _onUpdate, context) {
70
+ if (!eligible()) {
71
+ await kernel.dispose()
72
+ throw new EvalError('refused', 'eval requires active, unrestricted bash in an enabled origin')
73
+ }
74
+ const result = await kernel.run(args.code, {
75
+ signal,
76
+ timeoutMs: args.timeoutMs,
77
+ dispatch: createEvalDispatch({
78
+ tools: options.tools,
79
+ getActiveNames: options.getActiveNames,
80
+ context,
81
+ }),
82
+ })
83
+ if (result.isError) throw new EvalError('closed', result.text)
84
+ return {
85
+ content: [{ type: 'text', text: result.text || '(no output)' }],
86
+ details: { truncated: result.truncated, restarted: result.restarted },
87
+ }
88
+ },
89
+ }),
90
+ options.wrappers,
91
+ )
92
+ options.tools.push(
93
+ options.budget && options.budgetState
94
+ ? wrapToolDefinitionWithBudget(tool, options.budget, options.budgetState)
95
+ : tool,
96
+ )
97
+ options.activeNames.push('eval')
98
+ return { dispose: () => kernel.dispose() }
99
+ }
@@ -0,0 +1,93 @@
1
+ import type { HostFrame, KernelFrame } from './protocol'
2
+
3
+ export const EVAL_LIMITS = {
4
+ codeBytes: 64 * 1024,
5
+ frameBytes: 1024 * 1024,
6
+ outputBytes: 64 * 1024,
7
+ outputLines: 1000,
8
+ outputWarnBytes: 16 * 1024,
9
+ timeoutMs: 30_000,
10
+ maxTimeoutMs: 60_000,
11
+ idleMs: 5 * 60_000,
12
+ calls: 128,
13
+ concurrency: 8,
14
+ } as const
15
+
16
+ export const FRAME_PREFIX = '@typeclaw-eval '
17
+ export class EvalError extends Error {
18
+ override readonly name = 'EvalError'
19
+ constructor(
20
+ readonly kind: 'protocol' | 'closed' | 'timeout' | 'busy' | 'refused' | 'cell',
21
+ message: string,
22
+ ) {
23
+ super(message)
24
+ }
25
+ }
26
+
27
+ export function assertNever(value: never): never {
28
+ throw new EvalError('protocol', `unexpected eval frame: ${String(value)}`)
29
+ }
30
+
31
+ export function encodeFrame(frame: HostFrame | KernelFrame): string {
32
+ const line = FRAME_PREFIX + JSON.stringify(frame) + '\n'
33
+ if (Buffer.byteLength(line) > EVAL_LIMITS.frameBytes) {
34
+ throw new EvalError('protocol', 'eval bridge frame exceeds its byte limit')
35
+ }
36
+ return line
37
+ }
38
+
39
+ // Both complete lines and an unterminated flood are bounded before JSON.parse.
40
+ export class FrameLines {
41
+ private pending = Buffer.alloc(0)
42
+
43
+ push(chunk: Uint8Array): string[] {
44
+ const bytes = Buffer.concat([this.pending, chunk])
45
+ const lines: string[] = []
46
+ let start = 0
47
+ let end = bytes.indexOf(10)
48
+ while (end !== -1) {
49
+ if (end - start > EVAL_LIMITS.frameBytes) throw new EvalError('protocol', 'eval bridge line is too large')
50
+ lines.push(bytes.subarray(start, end).toString('utf8'))
51
+ start = end + 1
52
+ end = bytes.indexOf(10, start)
53
+ }
54
+ if (bytes.length - start > EVAL_LIMITS.frameBytes) {
55
+ throw new EvalError('protocol', 'eval bridge unterminated line is too large')
56
+ }
57
+ this.pending = Buffer.from(bytes.subarray(start))
58
+ return lines
59
+ }
60
+ }
61
+
62
+ const FILTER_ADVICE = 'filter in the cell and print only what you need'
63
+
64
+ export class CellOutput {
65
+ private text = ''
66
+ private bytes = 0
67
+ private lines = 0
68
+ truncated = false
69
+
70
+ append(text: string): void {
71
+ if (this.truncated) return
72
+ for (const character of text) {
73
+ const size = Buffer.byteLength(character)
74
+ if (this.bytes + size > EVAL_LIMITS.outputBytes || this.lines >= EVAL_LIMITS.outputLines) {
75
+ this.truncated = true
76
+ return
77
+ }
78
+ this.text += character
79
+ this.bytes += size
80
+ if (character === '\n') this.lines += 1
81
+ }
82
+ }
83
+
84
+ render(): string {
85
+ // Everything printed lands in the model's context; past the warning size
86
+ // the cell is no longer saving tokens over a direct tool call.
87
+ if (this.truncated) return `${this.text}\n[eval output truncated: limit reached; ${FILTER_ADVICE}]\n`
88
+ if (this.bytes > EVAL_LIMITS.outputWarnBytes) {
89
+ return `${this.text}\n[eval printed ${Math.round(this.bytes / 1024)} KB; ${FILTER_ADVICE}]\n`
90
+ }
91
+ return this.text
92
+ }
93
+ }
@@ -1,3 +1,5 @@
1
+ import { basename } from 'node:path'
2
+
1
3
  import { resolveAgentGit } from './resolve-agent-git'
2
4
  import { runGit } from './run'
3
5
 
@@ -9,6 +11,11 @@ const GIT_CONFIG_ENV = {
9
11
  GIT_TERMINAL_PROMPT: '0',
10
12
  } as const
11
13
 
14
+ // Records the identity ensureGitIdentity synthesized, so only that exact
15
+ // identity is treated as a fallback; a configured one that happens to match the
16
+ // folder name is not.
17
+ const FALLBACK_MARKER_KEY = 'typeclaw.fallbackidentity'
18
+
12
19
  const GIT_REPOSITORY_ENV_NAMES = new Set([
13
20
  'GIT_COMMON_DIR',
14
21
  'GIT_DIR',
@@ -27,11 +34,69 @@ export async function resolveGitIdentity(cwd: string): Promise<GitIdentity | nul
27
34
  return name !== null && email !== null ? { name, email } : null
28
35
  }
29
36
 
30
- async function readRepositoryIdentity(cwd: string, gitArgs: readonly string[]): Promise<Map<string, string[]>> {
37
+ // Commits by the runtime (backup, dreaming, system files) need an identity, and
38
+ // repository-local config is lost on clone or by hand edits. Fill only the
39
+ // missing keys from the agent folder name; an identity the user set is kept.
40
+ export async function ensureGitIdentity(cwd: string): Promise<GitIdentity | null> {
41
+ const repo = resolveAgentGit(cwd)
42
+ if (repo === null) return null
43
+
44
+ const values = await readRepositoryIdentity(cwd, repo.gitArgs)
45
+ const fallback = fallbackGitIdentity(cwd)
46
+ const name = values.get('user.name')?.at(-1)?.trim() || null
47
+ const email = values.get('user.email')?.at(-1)?.trim() || null
48
+ if (name !== null && email !== null) return { name, email }
49
+
50
+ const identity = { name: name ?? fallback.name, email: email ?? fallback.email }
51
+ if (name === null && !(await writeLocalConfig(cwd, repo.gitArgs, 'user.name', identity.name))) return null
52
+ if (email === null && !(await writeLocalConfig(cwd, repo.gitArgs, 'user.email', identity.email))) return null
53
+ await writeLocalConfig(cwd, repo.gitArgs, FALLBACK_MARKER_KEY, formatIdentity(identity))
54
+ return identity
55
+ }
56
+
57
+ // GIT_* env overrides repo config, so forwarding the fallback would freeze it
58
+ // over an identity hatching or the user sets while the container runs.
59
+ export async function isFallbackGitIdentity(cwd: string, identity: GitIdentity): Promise<boolean> {
60
+ const repo = resolveAgentGit(cwd)
61
+ if (repo === null) return false
62
+ const marker = (await readRepositoryIdentity(cwd, repo.gitArgs)).get(FALLBACK_MARKER_KEY)?.at(-1)
63
+ return marker === formatIdentity(identity)
64
+ }
65
+
66
+ function formatIdentity(identity: GitIdentity): string {
67
+ return `${identity.name} <${identity.email}>`
68
+ }
69
+
70
+ function fallbackGitIdentity(cwd: string): GitIdentity {
71
+ const folder = basename(cwd).trim()
72
+ const slug = folder
73
+ .toLowerCase()
74
+ .replace(/[^a-z0-9._-]+/g, '-')
75
+ .replace(/^[-.]+|[-.]+$/g, '')
76
+ return { name: folder || 'agent', email: `${slug || 'agent'}@typeclaw.local` }
77
+ }
78
+
79
+ async function writeLocalConfig(cwd: string, gitArgs: readonly string[], key: string, value: string): Promise<boolean> {
31
80
  try {
32
- const result = await runGit(Bun, cwd, [...gitArgs, 'config', '--null', '--get-regexp', '^user\\.(name|email)$'], {
81
+ const result = await runGit(Bun, cwd, [...gitArgs, 'config', '--local', key, value], {
33
82
  env: { ...withoutGitOverrides(process.env), ...GIT_CONFIG_ENV },
34
83
  })
84
+ return result.exitCode === 0
85
+ } catch {
86
+ return false
87
+ }
88
+ }
89
+
90
+ async function readRepositoryIdentity(cwd: string, gitArgs: readonly string[]): Promise<Map<string, string[]>> {
91
+ try {
92
+ const result = await runGit(
93
+ Bun,
94
+ cwd,
95
+ [...gitArgs, 'config', '--null', '--get-regexp', '^(user\\.(name|email)|typeclaw\\.fallbackidentity)$'],
96
+ {
97
+ env: { ...withoutGitOverrides(process.env), ...GIT_CONFIG_ENV },
98
+ },
99
+ )
35
100
  if (result.exitCode !== 0) return new Map()
36
101
  return parseNullConfigEntries(result.stdout)
37
102
  } catch {
@@ -54,6 +54,10 @@ export async function commitSystemFile(cwd: string, file: string | readonly stri
54
54
  await commit.exited
55
55
  }
56
56
 
57
+ // A git child that never exits would otherwise block the caller's thread for
58
+ // good, since a synchronous spawn cannot be interrupted from JavaScript.
59
+ const SPAWN_SYNC_TIMEOUT_MS = 30_000
60
+
57
61
  // Synchronous variant for callers that already hold a synchronous codepath
58
62
  // — specifically `persistMigratedConfig` in src/config/config.ts. The
59
63
  // migration write is itself synchronous (writeFileSync) and the call sites
@@ -83,6 +87,7 @@ export function commitSystemFileSync(cwd: string, file: string | readonly string
83
87
  cwd,
84
88
  stdout: 'pipe',
85
89
  stderr: 'pipe',
90
+ timeout: SPAWN_SYNC_TIMEOUT_MS,
86
91
  })
87
92
  if (status.exitCode !== 0) return
88
93
  if (new TextDecoder().decode(status.stdout).trim().length === 0) return
@@ -92,6 +97,7 @@ export function commitSystemFileSync(cwd: string, file: string | readonly string
92
97
  cwd,
93
98
  stdout: 'pipe',
94
99
  stderr: 'pipe',
100
+ timeout: SPAWN_SYNC_TIMEOUT_MS,
95
101
  })
96
102
  if (add.exitCode !== 0) return
97
103
 
@@ -100,6 +106,7 @@ export function commitSystemFileSync(cwd: string, file: string | readonly string
100
106
  cwd,
101
107
  stdout: 'pipe',
102
108
  stderr: 'pipe',
109
+ timeout: SPAWN_SYNC_TIMEOUT_MS,
103
110
  })
104
111
  }
105
112
 
@@ -28,6 +28,10 @@ export type BuildDockerfileOptions = {
28
28
  // hosts without buildx. `start` sets this to false when buildx is absent so
29
29
  // the legacy `docker build` can still build the agent image.
30
30
  buildKit?: boolean
31
+ // `typeclaw.json#typevault.enabled`: an enabled vault serves its one-time
32
+ // secret pages through a cloudflare-quick tunnel, so it needs cloudflared
33
+ // even when `docker.file.cloudflared` is off.
34
+ typevault?: boolean
31
35
  }
32
36
 
33
37
  // Apt packages that EVERY image must have — git for the agent runtime,
@@ -781,7 +785,7 @@ export function buildDockerfile(
781
785
  const cjkFonts = resolveCjkFonts(config.cjkFonts, options.cjkFontsAuto ?? false)
782
786
  const toggleAptArgs = collectToggleAptArgs(config, cjkFonts)
783
787
  const ghKeyringLayer = renderGhKeyringLayer(config.gh, buildKit)
784
- const cloudflaredLayer = renderCloudflaredLayer(config.cloudflared)
788
+ const cloudflaredLayer = renderCloudflaredLayer(config.cloudflared || options.typevault === true)
785
789
  const customLines = renderCustomDockerfileLines(config.append)
786
790
  const baseImageVersion = options.baseImageVersion ?? null
787
791
 
@@ -24,7 +24,7 @@ export const TRULY_IGNORED_PATTERNS = [
24
24
  // The reconciler MUST fail-closed and never untrack these, even if a custom
25
25
  // git.ignore.append pattern (e.g. `**`) matches them — doing so would drop
26
26
  // runtime-owned state out of git.
27
- export const SYSTEM_MANAGED_ROOTS = ['sessions/', 'memory/', 'channels/', 'todo/', 'cron/'] as const
27
+ export const SYSTEM_MANAGED_ROOTS = ['sessions/', 'memory/', 'channels/', 'todo/', 'cron/', '.typevault/'] as const
28
28
 
29
29
  export function buildGitignore(config: GitignoreConfig = { append: [] }): string {
30
30
  const customEntries = renderCustomGitignoreEntries(config.append)
@@ -51,8 +51,8 @@ ${TRULY_IGNORED_PATTERNS.join('\n')}
51
51
 
52
52
  # System-managed: gitignored by default so the agent never stages them by hand,
53
53
  # but TypeClaw force-commits them on its own schedule (sessions/ + todo/ via
54
- # auto-backup, memory/ via the dreaming subagent). Treat them as runtime-owned,
55
- # not agent-owned.
54
+ # auto-backup, memory/ via the dreaming subagent, .typevault/ ciphertext via
55
+ # auto-backup). Treat them as runtime-owned, not agent-owned.
56
56
  ${SYSTEM_MANAGED_ROOTS.join('\n')}
57
57
  `
58
58
  }
package/src/init/index.ts CHANGED
@@ -819,6 +819,7 @@ export async function writeDockerAssets(root: string): Promise<DockerAssetsResul
819
819
  // `null` selects the inline `oven/bun:1-slim` path in buildDockerfile.
820
820
  baseImageVersion: devMode ? null : resolveBaseImageVersion(root),
821
821
  cjkFontsAuto: hostLocaleIsCjk(),
822
+ typevault: typeclawConfig.typevault.enabled,
822
823
  }),
823
824
  { flag: 'wx' },
824
825
  ).catch(ignoreExists)
@@ -56,6 +56,8 @@ const PROVIDER_TO_MODELS_DEV: Record<KnownProviderId, string | null> = {
56
56
  // are retired for new users or don't serve chat. Surface the curated
57
57
  // Mercury 3 record alone.
58
58
  inception: null,
59
+ // models.dev has no EXAONE catalog. Surface the curated K-EXAONE 2.5 record.
60
+ exaone: null,
59
61
  }
60
62
 
61
63
  function upstreamProviderFor(