bazilion 0.0.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 (260) hide show
  1. package/.understand-anything/.understandignore +25 -0
  2. package/.understand-anything/fingerprints.json +14267 -0
  3. package/.understand-anything/knowledge-graph.json +18128 -0
  4. package/.understand-anything/meta.json +6 -0
  5. package/CLAUDE.md +164 -0
  6. package/LICENSE +21 -0
  7. package/README.md +195 -0
  8. package/apps/cli/package.json +21 -0
  9. package/apps/cli/src/auth-file.ts +18 -0
  10. package/apps/cli/src/client.ts +37 -0
  11. package/apps/cli/src/columnize.ts +32 -0
  12. package/apps/cli/src/commands/agent.ts +574 -0
  13. package/apps/cli/src/commands/auth.ts +110 -0
  14. package/apps/cli/src/commands/backup.ts +135 -0
  15. package/apps/cli/src/commands/completion.ts +155 -0
  16. package/apps/cli/src/commands/config.ts +95 -0
  17. package/apps/cli/src/commands/doctor.ts +131 -0
  18. package/apps/cli/src/commands/group.ts +132 -0
  19. package/apps/cli/src/commands/inbox.ts +82 -0
  20. package/apps/cli/src/commands/login.ts +73 -0
  21. package/apps/cli/src/commands/memory.ts +106 -0
  22. package/apps/cli/src/commands/profile.ts +259 -0
  23. package/apps/cli/src/commands/provider.ts +170 -0
  24. package/apps/cli/src/commands/send.ts +24 -0
  25. package/apps/cli/src/commands/serve.ts +89 -0
  26. package/apps/cli/src/commands/skill.ts +120 -0
  27. package/apps/cli/src/commands/token.ts +148 -0
  28. package/apps/cli/src/commands/trigger.ts +129 -0
  29. package/apps/cli/src/commands/uninstall.ts +156 -0
  30. package/apps/cli/src/index.ts +196 -0
  31. package/apps/cli/src/paths.ts +12 -0
  32. package/apps/cli/test/agent.test.ts +213 -0
  33. package/apps/cli/test/backup.test.ts +95 -0
  34. package/apps/cli/test/chat.test.ts +539 -0
  35. package/apps/cli/test/columnize.test.ts +29 -0
  36. package/apps/cli/test/completion.test.ts +45 -0
  37. package/apps/cli/test/config-page.test.ts +151 -0
  38. package/apps/cli/test/group.test.ts +74 -0
  39. package/apps/cli/test/helpers.ts +70 -0
  40. package/apps/cli/test/inbox-autodeliver.test.ts +143 -0
  41. package/apps/cli/test/inbox.test.ts +147 -0
  42. package/apps/cli/test/memory.test.ts +69 -0
  43. package/apps/cli/test/profile.test.ts +110 -0
  44. package/apps/cli/test/send.test.ts +30 -0
  45. package/apps/cli/test/server-fixture.ts +212 -0
  46. package/apps/cli/test/session-head.test.ts +45 -0
  47. package/apps/cli/test/skill.test.ts +128 -0
  48. package/apps/cli/test/token.test.ts +109 -0
  49. package/apps/cli/test/trigger.test.ts +245 -0
  50. package/apps/cli/tsconfig.json +4 -0
  51. package/apps/daemon/package.json +31 -0
  52. package/apps/daemon/src/app.ts +41 -0
  53. package/apps/daemon/src/core/agent/archive.ts +8 -0
  54. package/apps/daemon/src/core/agent/delete.ts +30 -0
  55. package/apps/daemon/src/core/agent/resolve.ts +31 -0
  56. package/apps/daemon/src/core/agent/spawn.ts +95 -0
  57. package/apps/daemon/src/core/agent/unarchive.ts +11 -0
  58. package/apps/daemon/src/core/availableModels.ts +58 -0
  59. package/apps/daemon/src/core/db/client.ts +113 -0
  60. package/apps/daemon/src/core/db/migrate.ts +41 -0
  61. package/apps/daemon/src/core/db/migrations/0001_init.sql +179 -0
  62. package/apps/daemon/src/core/group/delete.ts +21 -0
  63. package/apps/daemon/src/core/group/register.ts +68 -0
  64. package/apps/daemon/src/core/index.ts +71 -0
  65. package/apps/daemon/src/core/paths.ts +56 -0
  66. package/apps/daemon/src/core/profile/create.ts +78 -0
  67. package/apps/daemon/src/core/profile/delete.ts +26 -0
  68. package/apps/daemon/src/core/profile/identity.ts +70 -0
  69. package/apps/daemon/src/core/profile/load.ts +45 -0
  70. package/apps/daemon/src/core/profile/seed.ts +74 -0
  71. package/apps/daemon/src/core/profile/templates.ts +60 -0
  72. package/apps/daemon/src/core/profile/update.ts +57 -0
  73. package/apps/daemon/src/core/profile/validate.ts +9 -0
  74. package/apps/daemon/src/core/repos/agents.ts +202 -0
  75. package/apps/daemon/src/core/repos/config.ts +78 -0
  76. package/apps/daemon/src/core/repos/groups.ts +55 -0
  77. package/apps/daemon/src/core/repos/messages.ts +127 -0
  78. package/apps/daemon/src/core/repos/profiles.ts +83 -0
  79. package/apps/daemon/src/core/repos/providerModels.ts +58 -0
  80. package/apps/daemon/src/core/repos/providerState.ts +37 -0
  81. package/apps/daemon/src/core/repos/secrets.ts +145 -0
  82. package/apps/daemon/src/core/repos/skillMeta.ts +49 -0
  83. package/apps/daemon/src/core/repos/triggers.ts +101 -0
  84. package/apps/daemon/src/core/repos/webTokens.ts +87 -0
  85. package/apps/daemon/src/core/secrets.ts +65 -0
  86. package/apps/daemon/src/core/services.ts +264 -0
  87. package/apps/daemon/src/core/skills/discover.ts +28 -0
  88. package/apps/daemon/src/core/skills/import.ts +136 -0
  89. package/apps/daemon/src/core/skills/parse.ts +52 -0
  90. package/apps/daemon/src/core/skills/resolve.ts +50 -0
  91. package/apps/daemon/src/index.ts +45 -0
  92. package/apps/daemon/src/lib/agent-cancel.ts +48 -0
  93. package/apps/daemon/src/lib/agent-id.ts +13 -0
  94. package/apps/daemon/src/lib/agent-turn.ts +56 -0
  95. package/apps/daemon/src/lib/api-key.ts +56 -0
  96. package/apps/daemon/src/lib/auth.ts +41 -0
  97. package/apps/daemon/src/lib/cron.ts +93 -0
  98. package/apps/daemon/src/lib/ctx.ts +80 -0
  99. package/apps/daemon/src/lib/messaging-host.ts +34 -0
  100. package/apps/daemon/src/lib/middleware-auth.ts +52 -0
  101. package/apps/daemon/src/lib/scheduler.ts +294 -0
  102. package/apps/daemon/src/routes/agents.ts +772 -0
  103. package/apps/daemon/src/routes/auth-login.ts +193 -0
  104. package/apps/daemon/src/routes/config.ts +267 -0
  105. package/apps/daemon/src/routes/groups.ts +133 -0
  106. package/apps/daemon/src/routes/messages.ts +29 -0
  107. package/apps/daemon/src/routes/misc.ts +239 -0
  108. package/apps/daemon/src/routes/profiles.ts +197 -0
  109. package/apps/daemon/src/routes/skills.ts +123 -0
  110. package/apps/daemon/src/routes/triggers.ts +29 -0
  111. package/apps/daemon/src/runtime/auth/openai-codex.ts +121 -0
  112. package/apps/daemon/src/runtime/auto-reply/heartbeat.ts +31 -0
  113. package/apps/daemon/src/runtime/index.ts +77 -0
  114. package/apps/daemon/src/runtime/memory/files.ts +103 -0
  115. package/apps/daemon/src/runtime/memory/qmd.ts +152 -0
  116. package/apps/daemon/src/runtime/memory/types.ts +16 -0
  117. package/apps/daemon/src/runtime/pi/events.ts +173 -0
  118. package/apps/daemon/src/runtime/pi/session.ts +536 -0
  119. package/apps/daemon/src/runtime/pi/tools.ts +85 -0
  120. package/apps/daemon/src/runtime/providers/catalog.ts +145 -0
  121. package/apps/daemon/src/runtime/providers/pi-adapter.ts +272 -0
  122. package/apps/daemon/src/runtime/providers/registry.ts +374 -0
  123. package/apps/daemon/src/runtime/providers/retry.ts +176 -0
  124. package/apps/daemon/src/runtime/providers/types.ts +33 -0
  125. package/apps/daemon/src/runtime/session/prompt.ts +83 -0
  126. package/apps/daemon/src/runtime/tools/bootstrap.ts +22 -0
  127. package/apps/daemon/src/runtime/tools/home.ts +114 -0
  128. package/apps/daemon/src/runtime/tools/memory.ts +81 -0
  129. package/apps/daemon/src/runtime/tools/messaging.ts +127 -0
  130. package/apps/daemon/src/runtime/tools/registry.ts +29 -0
  131. package/apps/daemon/src/runtime/tools/types.ts +13 -0
  132. package/apps/daemon/src/runtime/tools/web-extract.ts +110 -0
  133. package/apps/daemon/src/runtime/tools/web-ssrf.ts +245 -0
  134. package/apps/daemon/src/runtime/tools/web.ts +273 -0
  135. package/apps/daemon/src/runtime/worker/entry.ts +221 -0
  136. package/apps/daemon/src/runtime/worker/ipc-protocol.ts +75 -0
  137. package/apps/daemon/src/runtime/worker/spawn.ts +249 -0
  138. package/apps/daemon/test/core/agents.test.ts +319 -0
  139. package/apps/daemon/test/core/available-models.test.ts +63 -0
  140. package/apps/daemon/test/core/config.test.ts +99 -0
  141. package/apps/daemon/test/core/groups.test.ts +63 -0
  142. package/apps/daemon/test/core/helpers.ts +50 -0
  143. package/apps/daemon/test/core/identity.test.ts +85 -0
  144. package/apps/daemon/test/core/migrations.test.ts +83 -0
  145. package/apps/daemon/test/core/profiles.test.ts +182 -0
  146. package/apps/daemon/test/core/provider-models.test.ts +57 -0
  147. package/apps/daemon/test/core/provider-state.test.ts +36 -0
  148. package/apps/daemon/test/core/skill-meta.test.ts +45 -0
  149. package/apps/daemon/test/core/skills.test.ts +271 -0
  150. package/apps/daemon/test/core/triggers.test.ts +182 -0
  151. package/apps/daemon/test/core/web-tokens.test.ts +79 -0
  152. package/apps/daemon/test/cron.test.ts +90 -0
  153. package/apps/daemon/test/runtime/heartbeat.test.ts +34 -0
  154. package/apps/daemon/test/runtime/memory-qmd.test.ts +97 -0
  155. package/apps/daemon/test/runtime/memory.test.ts +78 -0
  156. package/apps/daemon/test/runtime/messaging.test.ts +213 -0
  157. package/apps/daemon/test/runtime/mock-server.ts +65 -0
  158. package/apps/daemon/test/runtime/openai-codex-auth.test.ts +116 -0
  159. package/apps/daemon/test/runtime/providers.test.ts +306 -0
  160. package/apps/daemon/test/runtime/retry.test.ts +191 -0
  161. package/apps/daemon/test/runtime/session-head.test.ts +90 -0
  162. package/apps/daemon/test/runtime/tools-home.test.ts +102 -0
  163. package/apps/daemon/test/runtime/tools-web.test.ts +206 -0
  164. package/apps/daemon/tsconfig.json +4 -0
  165. package/apps/mobile/README.md +60 -0
  166. package/apps/mobile/app/_layout.tsx +58 -0
  167. package/apps/mobile/app/agents/[id]/chat.tsx +486 -0
  168. package/apps/mobile/app/agents/[id]/index.tsx +166 -0
  169. package/apps/mobile/app/agents/index.tsx +212 -0
  170. package/apps/mobile/app/index.tsx +21 -0
  171. package/apps/mobile/app/pair.tsx +226 -0
  172. package/apps/mobile/app/settings.tsx +419 -0
  173. package/apps/mobile/app.json +49 -0
  174. package/apps/mobile/assets/adaptive-icon.png +0 -0
  175. package/apps/mobile/assets/favicon.png +0 -0
  176. package/apps/mobile/assets/icon.png +0 -0
  177. package/apps/mobile/assets/splash-icon.png +0 -0
  178. package/apps/mobile/babel.config.js +6 -0
  179. package/apps/mobile/metro.config.js +28 -0
  180. package/apps/mobile/package.json +44 -0
  181. package/apps/mobile/src/auth.ts +66 -0
  182. package/apps/mobile/src/pair-url.ts +48 -0
  183. package/apps/mobile/src/theme-context.tsx +88 -0
  184. package/apps/mobile/src/theme.ts +135 -0
  185. package/apps/mobile/test/pair-url.test.ts +46 -0
  186. package/apps/mobile/tsconfig.json +23 -0
  187. package/apps/web/components.json +25 -0
  188. package/apps/web/package.json +39 -0
  189. package/apps/web/public/baziu.svg +8 -0
  190. package/apps/web/src/components/AgentTabs.tsx +45 -0
  191. package/apps/web/src/components/BaziuLogo.tsx +21 -0
  192. package/apps/web/src/components/ChatPane.tsx +1033 -0
  193. package/apps/web/src/components/ConfigTabs.tsx +29 -0
  194. package/apps/web/src/components/CopyButton.tsx +68 -0
  195. package/apps/web/src/components/CreateGroupDialog.tsx +127 -0
  196. package/apps/web/src/components/FieldRow.tsx +94 -0
  197. package/apps/web/src/components/Footer.tsx +10 -0
  198. package/apps/web/src/components/PawIcon.tsx +15 -0
  199. package/apps/web/src/components/Sidebar.tsx +287 -0
  200. package/apps/web/src/components/SpawnDialog.tsx +129 -0
  201. package/apps/web/src/components/ThemeToggle.tsx +75 -0
  202. package/apps/web/src/components/TopNav.tsx +34 -0
  203. package/apps/web/src/components/ui/button.tsx +67 -0
  204. package/apps/web/src/components/ui/card.tsx +103 -0
  205. package/apps/web/src/components/ui/checkbox.tsx +31 -0
  206. package/apps/web/src/components/ui/dialog.tsx +168 -0
  207. package/apps/web/src/components/ui/input.tsx +19 -0
  208. package/apps/web/src/components/ui/label.tsx +22 -0
  209. package/apps/web/src/components/ui/radio-group.tsx +44 -0
  210. package/apps/web/src/components/ui/select.tsx +192 -0
  211. package/apps/web/src/components/ui/separator.tsx +26 -0
  212. package/apps/web/src/components/ui/table.tsx +116 -0
  213. package/apps/web/src/components/ui/tabs.tsx +88 -0
  214. package/apps/web/src/components/ui/textarea.tsx +18 -0
  215. package/apps/web/src/lib/auth.ts +50 -0
  216. package/apps/web/src/lib/daemon-client.ts +34 -0
  217. package/apps/web/src/lib/md.ts +45 -0
  218. package/apps/web/src/lib/utils.ts +6 -0
  219. package/apps/web/src/lib/wire-constants.ts +27 -0
  220. package/apps/web/src/routeTree.gen.ts +408 -0
  221. package/apps/web/src/router.tsx +20 -0
  222. package/apps/web/src/routes/__root.tsx +123 -0
  223. package/apps/web/src/routes/agents/$id/inbox.tsx +207 -0
  224. package/apps/web/src/routes/agents/$id/index.tsx +527 -0
  225. package/apps/web/src/routes/agents/$id/triggers.tsx +239 -0
  226. package/apps/web/src/routes/agents/index.tsx +265 -0
  227. package/apps/web/src/routes/api/$.ts +88 -0
  228. package/apps/web/src/routes/config/index.tsx +315 -0
  229. package/apps/web/src/routes/config/services.tsx +49 -0
  230. package/apps/web/src/routes/config/tokens.tsx +192 -0
  231. package/apps/web/src/routes/groups/$id/index.tsx +153 -0
  232. package/apps/web/src/routes/groups/$id/memory.tsx +321 -0
  233. package/apps/web/src/routes/groups/index.tsx +191 -0
  234. package/apps/web/src/routes/index.tsx +133 -0
  235. package/apps/web/src/routes/login.tsx +63 -0
  236. package/apps/web/src/routes/profiles/$id.tsx +549 -0
  237. package/apps/web/src/routes/profiles/index.tsx +458 -0
  238. package/apps/web/src/routes/skills/index.tsx +297 -0
  239. package/apps/web/src/routes/welcome.tsx +61 -0
  240. package/apps/web/src/styles.css +449 -0
  241. package/apps/web/tsconfig.json +25 -0
  242. package/apps/web/vite.config.ts +25 -0
  243. package/biome.json +23 -0
  244. package/docs/agent-engine.md +219 -0
  245. package/docs/architecture.md +627 -0
  246. package/docs/backlog/README.md +42 -0
  247. package/docs/backlog/draft/BAZ-001-a2a-federation-spike.md +125 -0
  248. package/docs/openclaw-reference.md +210 -0
  249. package/package.json +38 -0
  250. package/packages/api-types/package.json +11 -0
  251. package/packages/api-types/src/entities.ts +146 -0
  252. package/packages/api-types/src/events.ts +55 -0
  253. package/packages/api-types/src/index.ts +488 -0
  254. package/packages/api-types/src/memory.ts +15 -0
  255. package/packages/client/package.json +13 -0
  256. package/packages/client/src/index.ts +117 -0
  257. package/pnpm-workspace.yaml +3 -0
  258. package/tsconfig.base.json +23 -0
  259. package/tsconfig.json +11 -0
  260. package/vitest.config.ts +22 -0
@@ -0,0 +1,114 @@
1
+ import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import type { ToolHandler } from './types.ts'
4
+
5
+ // Files the agent may read/write in its private home directory.
6
+ // BOOTSTRAP.md is readable but not writable — its lifecycle belongs to
7
+ // the `bootstrap_done` tool, not `home_write`.
8
+ const HOME_FILES_READABLE = [
9
+ 'IDENTITY.md',
10
+ 'SOUL.md',
11
+ 'BOOTSTRAP.md',
12
+ 'AGENTS.md',
13
+ 'TOOLS.md',
14
+ 'HEARTBEAT.md',
15
+ ] as const
16
+
17
+ const HOME_FILES_WRITABLE = [
18
+ 'IDENTITY.md',
19
+ 'SOUL.md',
20
+ 'AGENTS.md',
21
+ 'TOOLS.md',
22
+ 'HEARTBEAT.md',
23
+ ] as const
24
+
25
+ export function homeTools(agentDir: string): ToolHandler[] {
26
+ return [
27
+ {
28
+ def: {
29
+ name: 'home_read',
30
+ description:
31
+ 'Read one of your own home files — your identity, soul, or behaviour rules. These files are private to you and are also injected into your system prompt; read them when you need to quote exact wording or check current state.',
32
+ parameters: {
33
+ type: 'object',
34
+ properties: {
35
+ file: { type: 'string', enum: [...HOME_FILES_READABLE] },
36
+ },
37
+ required: ['file'],
38
+ },
39
+ },
40
+ async invoke(args) {
41
+ const file = String(args.file ?? '')
42
+ if (!HOME_FILES_READABLE.includes(file as (typeof HOME_FILES_READABLE)[number])) {
43
+ throw new Error(
44
+ `home_read: "file" must be one of ${HOME_FILES_READABLE.join(', ')}; got "${file}"`,
45
+ )
46
+ }
47
+ const path = join(agentDir, file)
48
+ try {
49
+ return readFileSync(path, 'utf8')
50
+ } catch (err) {
51
+ const msg = err instanceof Error ? err.message : String(err)
52
+ throw new Error(`home_read: could not read ${file}: ${msg}`)
53
+ }
54
+ },
55
+ },
56
+ {
57
+ def: {
58
+ name: 'home_write',
59
+ description:
60
+ "Overwrite one of your own home files. Use this to update your name, personality, or persistent self-definition. Do NOT use this for work output (use `write` / `edit` — those land in your group's shared directory) or for facts you want to remember (use `memory_write`). BOOTSTRAP.md is not writable here; call `bootstrap_done` to retire it.",
61
+ parameters: {
62
+ type: 'object',
63
+ properties: {
64
+ file: { type: 'string', enum: [...HOME_FILES_WRITABLE] },
65
+ content: { type: 'string', description: 'new full file content' },
66
+ },
67
+ required: ['file', 'content'],
68
+ },
69
+ },
70
+ async invoke(args) {
71
+ const file = String(args.file ?? '')
72
+ if (!HOME_FILES_WRITABLE.includes(file as (typeof HOME_FILES_WRITABLE)[number])) {
73
+ throw new Error(
74
+ `home_write: "file" must be one of ${HOME_FILES_WRITABLE.join(', ')}; got "${file}"`,
75
+ )
76
+ }
77
+ const content = typeof args.content === 'string' ? args.content : ''
78
+ const path = join(agentDir, file)
79
+ writeFileSync(path, content, 'utf8')
80
+ return `wrote ${file} (${Buffer.byteLength(content, 'utf8')} bytes)`
81
+ },
82
+ },
83
+ {
84
+ def: {
85
+ name: 'home_list',
86
+ description: 'List your home files with their sizes.',
87
+ parameters: { type: 'object', properties: {} },
88
+ },
89
+ async invoke() {
90
+ const entries: string[] = []
91
+ for (const file of HOME_FILES_READABLE) {
92
+ const path = join(agentDir, file)
93
+ try {
94
+ const s = statSync(path)
95
+ entries.push(`${file} (${s.size}b)`)
96
+ } catch {
97
+ // file not present — skip
98
+ }
99
+ }
100
+ if (entries.length === 0) {
101
+ const dirEntries = (() => {
102
+ try {
103
+ return readdirSync(agentDir)
104
+ } catch {
105
+ return []
106
+ }
107
+ })()
108
+ return `(no home files found; agent dir contains: ${dirEntries.join(', ') || 'nothing'})`
109
+ }
110
+ return entries.join('\n')
111
+ },
112
+ },
113
+ ]
114
+ }
@@ -0,0 +1,81 @@
1
+ import type { MemoryBackend } from '../memory/types.ts'
2
+ import type { ToolHandler } from './types.ts'
3
+
4
+ export function memoryTools(memory: MemoryBackend): ToolHandler[] {
5
+ return [
6
+ {
7
+ def: {
8
+ name: 'memory_write',
9
+ description:
10
+ 'Write or update a memory note in the GROUP-SHARED memory. All agents in this group can read what you write. Use it for project knowledge, codebase notes, decisions, and findings — anything other agents in the group should benefit from. For personal notes about yourself (preferences, persona), use `home_write` on IDENTITY.md instead. Key is a path-like string with a markdown extension, e.g. "auth-flow.md" or "people/alice.md".',
11
+ parameters: {
12
+ type: 'object',
13
+ properties: {
14
+ key: { type: 'string', description: 'memory key (relative path)' },
15
+ content: { type: 'string', description: 'note content (plain text or markdown)' },
16
+ },
17
+ required: ['key', 'content'],
18
+ },
19
+ },
20
+ async invoke(args) {
21
+ const key = String(args.key ?? '')
22
+ const content = String(args.content ?? '')
23
+ if (!key) throw new Error('memory_write: "key" is required')
24
+ const entry = await memory.write(key, content)
25
+ return `wrote ${entry.key} (${entry.content.length} bytes)`
26
+ },
27
+ },
28
+ {
29
+ def: {
30
+ name: 'memory_search',
31
+ description:
32
+ 'Search the group-shared memory by substring. Returns matching entry keys with short snippets around the match.',
33
+ parameters: {
34
+ type: 'object',
35
+ properties: {
36
+ query: { type: 'string' },
37
+ limit: { type: 'number', description: 'max results (default 10)' },
38
+ },
39
+ required: ['query'],
40
+ },
41
+ },
42
+ async invoke(args) {
43
+ const query = String(args.query ?? '')
44
+ if (!query) throw new Error('memory_search: "query" is required')
45
+ const limit = typeof args.limit === 'number' ? args.limit : 10
46
+ const hits = await memory.search(query, { limit })
47
+ if (hits.length === 0) return 'no matches'
48
+ return hits.map((h) => `${h.key}: ${h.snippet.replaceAll('\n', ' ')}`).join('\n')
49
+ },
50
+ },
51
+ {
52
+ def: {
53
+ name: 'memory_read',
54
+ description: 'Read a single entry from the group-shared memory by key.',
55
+ parameters: {
56
+ type: 'object',
57
+ properties: { key: { type: 'string' } },
58
+ required: ['key'],
59
+ },
60
+ },
61
+ async invoke(args) {
62
+ const key = String(args.key ?? '')
63
+ if (!key) throw new Error('memory_read: "key" is required')
64
+ const entry = await memory.read(key)
65
+ return entry.content
66
+ },
67
+ },
68
+ {
69
+ def: {
70
+ name: 'memory_list',
71
+ description: 'List every entry in the group-shared memory with its byte size.',
72
+ parameters: { type: 'object', properties: {} },
73
+ },
74
+ async invoke() {
75
+ const all = await memory.list()
76
+ if (all.length === 0) return '(empty)'
77
+ return all.map((e) => `${e.key} (${e.content.length}b)`).join('\n')
78
+ },
79
+ },
80
+ ]
81
+ }
@@ -0,0 +1,127 @@
1
+ import type { MessagingHost } from '../worker/ipc-protocol.ts'
2
+ import type { ToolHandler } from './types.ts'
3
+
4
+ interface MessagePayload {
5
+ text: string
6
+ [key: string]: unknown
7
+ }
8
+
9
+ function decodeText(payload: string): string {
10
+ try {
11
+ const parsed = JSON.parse(payload) as MessagePayload
12
+ if (parsed && typeof parsed.text === 'string') return parsed.text
13
+ } catch {
14
+ // not JSON; return raw payload
15
+ }
16
+ return payload
17
+ }
18
+
19
+ export function messagingTools(host: MessagingHost, fromAgentId: string): ToolHandler[] {
20
+ return [
21
+ {
22
+ def: {
23
+ name: 'send_message',
24
+ description: "Send a message to another agent. Use the recipient's agent id (UUID).",
25
+ parameters: {
26
+ type: 'object',
27
+ properties: {
28
+ to: { type: 'string', description: 'Recipient agent id' },
29
+ text: { type: 'string', description: 'Message text' },
30
+ reply_to: {
31
+ type: 'string',
32
+ description: 'Optional: id of the message you are replying to',
33
+ },
34
+ },
35
+ required: ['to', 'text'],
36
+ },
37
+ },
38
+ async invoke(args) {
39
+ const to = String(args.to ?? '')
40
+ const text = String(args.text ?? '')
41
+ if (!to) throw new Error('send_message: "to" is required')
42
+ if (!text) throw new Error('send_message: "text" is required')
43
+ if (!(await host.agentExists(to))) {
44
+ throw new Error(`send_message: agent not found: ${to}`)
45
+ }
46
+ const replyTo = typeof args.reply_to === 'string' ? args.reply_to : null
47
+ const { messageId } = await host.sendMessage({
48
+ from: fromAgentId,
49
+ to,
50
+ payload: JSON.stringify({ text }),
51
+ replyTo,
52
+ })
53
+ return `sent message ${messageId}`
54
+ },
55
+ },
56
+ {
57
+ def: {
58
+ name: 'read_inbox',
59
+ description: 'Read messages addressed to you. Marks unread messages as read by default.',
60
+ parameters: {
61
+ type: 'object',
62
+ properties: {
63
+ include_read: {
64
+ type: 'boolean',
65
+ description: 'Also include already-read messages (default false)',
66
+ },
67
+ },
68
+ },
69
+ },
70
+ async invoke(args) {
71
+ const includeRead = args.include_read === true
72
+ const messages = await host.listInbox(fromAgentId, { unreadOnly: !includeRead })
73
+ if (messages.length === 0) return '(no messages)'
74
+ const lines: string[] = []
75
+ for (const m of messages) {
76
+ lines.push(`from ${m.fromAgentId} [${m.id}]: ${decodeText(m.payload)}`)
77
+ if (!m.readAt) await host.markRead(m.id)
78
+ }
79
+ return lines.join('\n')
80
+ },
81
+ },
82
+ {
83
+ def: {
84
+ name: 'wait_for_reply',
85
+ description:
86
+ 'Block until a reply to a message you sent arrives, or until the timeout expires.',
87
+ parameters: {
88
+ type: 'object',
89
+ properties: {
90
+ message_id: {
91
+ type: 'string',
92
+ description: 'id of the message you sent',
93
+ },
94
+ timeout_ms: {
95
+ type: 'number',
96
+ description: 'max wait in milliseconds (default 30000)',
97
+ },
98
+ poll_ms: {
99
+ type: 'number',
100
+ description: 'poll interval in milliseconds (default 200)',
101
+ },
102
+ },
103
+ required: ['message_id'],
104
+ },
105
+ },
106
+ async invoke(args) {
107
+ const messageId = String(args.message_id ?? '')
108
+ if (!messageId) throw new Error('wait_for_reply: "message_id" is required')
109
+ const timeout = typeof args.timeout_ms === 'number' ? args.timeout_ms : 30000
110
+ const poll = typeof args.poll_ms === 'number' ? args.poll_ms : 200
111
+ const start = Date.now()
112
+ while (Date.now() - start < timeout) {
113
+ const replies = await host.findReplies(fromAgentId, messageId)
114
+ if (replies.length > 0) {
115
+ const r = replies[0]
116
+ if (r) {
117
+ if (!r.readAt) await host.markRead(r.id)
118
+ return `reply from ${r.fromAgentId} [${r.id}]: ${decodeText(r.payload)}`
119
+ }
120
+ }
121
+ await new Promise((r) => setTimeout(r, poll))
122
+ }
123
+ return `no reply within ${timeout}ms`
124
+ },
125
+ },
126
+ ]
127
+ }
@@ -0,0 +1,29 @@
1
+ import type { ToolHandler, ToolRegistry } from './types.ts'
2
+
3
+ export function createToolRegistry(handlers: ToolHandler[]): ToolRegistry {
4
+ const map = new Map<string, ToolHandler>()
5
+ for (const h of handlers) map.set(h.def.name, h)
6
+
7
+ return {
8
+ list() {
9
+ return [...map.values()].map((h) => h.def)
10
+ },
11
+ has(name) {
12
+ return map.has(name)
13
+ },
14
+ async invoke(name, jsonArgs) {
15
+ const handler = map.get(name)
16
+ if (!handler) throw new Error(`unknown tool: ${name}`)
17
+ let args: Record<string, unknown>
18
+ try {
19
+ args = jsonArgs ? JSON.parse(jsonArgs) : {}
20
+ } catch (err) {
21
+ throw new Error(`tool ${name}: invalid JSON arguments — ${(err as Error).message}`)
22
+ }
23
+ if (!args || typeof args !== 'object') {
24
+ throw new Error(`tool ${name}: arguments must be a JSON object`)
25
+ }
26
+ return handler.invoke(args)
27
+ },
28
+ }
29
+ }
@@ -0,0 +1,13 @@
1
+ import type { ToolDef } from '@bazilion/api-types'
2
+
3
+ export interface ToolHandler {
4
+ def: ToolDef
5
+ invoke(args: Record<string, unknown>): Promise<string>
6
+ }
7
+
8
+ export interface ToolRegistry {
9
+ list(): ToolDef[]
10
+ has(name: string): boolean
11
+ /** invoke a tool with JSON-serialized arguments; returns text result */
12
+ invoke(name: string, jsonArgs: string): Promise<string>
13
+ }
@@ -0,0 +1,110 @@
1
+ import { Readability } from '@mozilla/readability'
2
+ import { parseHTML } from 'linkedom'
3
+
4
+ export type ExtractMode = 'markdown' | 'text'
5
+
6
+ export interface ExtractResult {
7
+ text: string
8
+ title?: string
9
+ }
10
+
11
+ function decodeEntities(value: string): string {
12
+ return value
13
+ .replace(/&nbsp;/gi, ' ')
14
+ .replace(/&amp;/gi, '&')
15
+ .replace(/&quot;/gi, '"')
16
+ .replace(/&#39;/gi, "'")
17
+ .replace(/&lt;/gi, '<')
18
+ .replace(/&gt;/gi, '>')
19
+ .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)))
20
+ .replace(/&#(\d+);/gi, (_, dec) => String.fromCharCode(Number.parseInt(dec, 10)))
21
+ }
22
+
23
+ function stripTags(value: string): string {
24
+ return decodeEntities(value.replace(/<[^>]+>/g, ''))
25
+ }
26
+
27
+ function normalizeWhitespace(value: string): string {
28
+ return value
29
+ .replace(/\r/g, '')
30
+ .replace(/[ \t]+\n/g, '\n')
31
+ .replace(/\n{3,}/g, '\n\n')
32
+ .replace(/[ \t]{2,}/g, ' ')
33
+ .trim()
34
+ }
35
+
36
+ function htmlToMarkdown(html: string): { text: string; title?: string } {
37
+ const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)
38
+ const title = titleMatch ? normalizeWhitespace(stripTags(titleMatch[1] ?? '')) : undefined
39
+ let text = html
40
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
41
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
42
+ .replace(/<noscript[\s\S]*?<\/noscript>/gi, '')
43
+ .replace(/<nav[\s\S]*?<\/nav>/gi, '')
44
+ .replace(/<header[\s\S]*?<\/header>/gi, '')
45
+ .replace(/<footer[\s\S]*?<\/footer>/gi, '')
46
+ text = text.replace(/<a\s+[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, (_, href, body) => {
47
+ const label = normalizeWhitespace(stripTags(body))
48
+ return label ? `[${label}](${href})` : href
49
+ })
50
+ text = text.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi, (_, level, body) => {
51
+ const n = Math.max(1, Math.min(6, Number.parseInt(level, 10)))
52
+ return `\n${'#'.repeat(n)} ${normalizeWhitespace(stripTags(body))}\n`
53
+ })
54
+ text = text.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_, body) => {
55
+ const label = normalizeWhitespace(stripTags(body))
56
+ return label ? `\n- ${label}` : ''
57
+ })
58
+ text = text
59
+ .replace(/<(br|hr)\s*\/?>/gi, '\n')
60
+ .replace(/<\/(p|div|section|article|tr|ul|ol|table|blockquote)>/gi, '\n')
61
+ text = stripTags(text)
62
+ return { text: normalizeWhitespace(text), title }
63
+ }
64
+
65
+ function markdownToPlain(md: string): string {
66
+ let t = md
67
+ t = t.replace(/!\[[^\]]*]\([^)]+\)/g, '')
68
+ t = t.replace(/\[([^\]]+)]\([^)]+\)/g, '$1')
69
+ t = t.replace(/```[\s\S]*?```/g, (block) =>
70
+ block.replace(/```[^\n]*\n?/g, '').replace(/```/g, ''),
71
+ )
72
+ t = t.replace(/`([^`]+)`/g, '$1')
73
+ t = t.replace(/^#{1,6}\s+/gm, '')
74
+ t = t.replace(/^\s*[-*+]\s+/gm, '')
75
+ t = t.replace(/^\s*\d+\.\s+/gm, '')
76
+ return normalizeWhitespace(t)
77
+ }
78
+
79
+ /**
80
+ * Extract readable content from HTML using Readability, with a regex-based
81
+ * markdown fallback when Readability can't identify an article.
82
+ */
83
+ export function extractReadable(html: string, url: string, mode: ExtractMode): ExtractResult {
84
+ const fallback = (): ExtractResult => {
85
+ const r = htmlToMarkdown(html)
86
+ return mode === 'text' ? { text: markdownToPlain(r.text), title: r.title } : r
87
+ }
88
+ try {
89
+ const { document } = parseHTML(html)
90
+ try {
91
+ ;(document as unknown as { baseURI?: string }).baseURI = url
92
+ } catch {
93
+ // best-effort
94
+ }
95
+ type ReadabilityArg = ConstructorParameters<typeof Readability>[0]
96
+ const parsed = new Readability(document as unknown as ReadabilityArg, {
97
+ charThreshold: 0,
98
+ }).parse()
99
+ if (!parsed?.content) return fallback()
100
+ const title = parsed.title || undefined
101
+ if (mode === 'text') {
102
+ const text = normalizeWhitespace(parsed.textContent ?? '')
103
+ return text ? { text, title } : fallback()
104
+ }
105
+ const rendered = htmlToMarkdown(parsed.content)
106
+ return { text: rendered.text, title: title ?? rendered.title }
107
+ } catch {
108
+ return fallback()
109
+ }
110
+ }