bincode-cli 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/AGENTS.md +27 -0
  2. package/README.md +15 -0
  3. package/bin/bincode +98 -0
  4. package/bunfig.toml +4 -0
  5. package/package.json +124 -0
  6. package/parsers-config.ts +239 -0
  7. package/script/build.ts +167 -0
  8. package/script/postinstall.mjs +206 -0
  9. package/script/publish.ts +99 -0
  10. package/script/schema.ts +47 -0
  11. package/src/acp/README.md +164 -0
  12. package/src/acp/agent.ts +1051 -0
  13. package/src/acp/session.ts +101 -0
  14. package/src/acp/types.ts +22 -0
  15. package/src/agent/agent.ts +398 -0
  16. package/src/agent/generate.txt +75 -0
  17. package/src/agent/prompt/compaction.txt +12 -0
  18. package/src/agent/prompt/explore.txt +18 -0
  19. package/src/agent/prompt/summary.txt +10 -0
  20. package/src/agent/prompt/title.txt +36 -0
  21. package/src/auth/bineric-login.ts +506 -0
  22. package/src/auth/index.ts +70 -0
  23. package/src/bun/index.ts +114 -0
  24. package/src/bus/bus-event.ts +43 -0
  25. package/src/bus/global.ts +10 -0
  26. package/src/bus/index.ts +105 -0
  27. package/src/cli/auth-check.ts +61 -0
  28. package/src/cli/bootstrap.ts +21 -0
  29. package/src/cli/cmd/acp.ts +88 -0
  30. package/src/cli/cmd/agent.ts +256 -0
  31. package/src/cli/cmd/auth.ts +436 -0
  32. package/src/cli/cmd/cmd.ts +7 -0
  33. package/src/cli/cmd/debug/config.ts +15 -0
  34. package/src/cli/cmd/debug/file.ts +91 -0
  35. package/src/cli/cmd/debug/index.ts +43 -0
  36. package/src/cli/cmd/debug/lsp.ts +48 -0
  37. package/src/cli/cmd/debug/ripgrep.ts +83 -0
  38. package/src/cli/cmd/debug/scrap.ts +15 -0
  39. package/src/cli/cmd/debug/skill.ts +15 -0
  40. package/src/cli/cmd/debug/snapshot.ts +48 -0
  41. package/src/cli/cmd/export.ts +88 -0
  42. package/src/cli/cmd/generate.ts +38 -0
  43. package/src/cli/cmd/github.ts +1399 -0
  44. package/src/cli/cmd/import.ts +98 -0
  45. package/src/cli/cmd/login.ts +112 -0
  46. package/src/cli/cmd/logout.ts +38 -0
  47. package/src/cli/cmd/mcp.ts +654 -0
  48. package/src/cli/cmd/models.ts +77 -0
  49. package/src/cli/cmd/pr.ts +112 -0
  50. package/src/cli/cmd/run.ts +368 -0
  51. package/src/cli/cmd/serve.ts +31 -0
  52. package/src/cli/cmd/session.ts +106 -0
  53. package/src/cli/cmd/stats.ts +298 -0
  54. package/src/cli/cmd/tui/app.tsx +669 -0
  55. package/src/cli/cmd/tui/attach.ts +30 -0
  56. package/src/cli/cmd/tui/component/border.tsx +21 -0
  57. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  58. package/src/cli/cmd/tui/component/dialog-command.tsx +123 -0
  59. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  60. package/src/cli/cmd/tui/component/dialog-model.tsx +223 -0
  61. package/src/cli/cmd/tui/component/dialog-provider.tsx +224 -0
  62. package/src/cli/cmd/tui/component/dialog-session-list.tsx +102 -0
  63. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  64. package/src/cli/cmd/tui/component/dialog-status.tsx +162 -0
  65. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  66. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  67. package/src/cli/cmd/tui/component/logo.tsx +32 -0
  68. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +560 -0
  69. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  70. package/src/cli/cmd/tui/component/prompt/index.tsx +1052 -0
  71. package/src/cli/cmd/tui/context/args.tsx +14 -0
  72. package/src/cli/cmd/tui/context/directory.ts +13 -0
  73. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  74. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  75. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  76. package/src/cli/cmd/tui/context/kv.tsx +49 -0
  77. package/src/cli/cmd/tui/context/local.tsx +339 -0
  78. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  79. package/src/cli/cmd/tui/context/route.tsx +46 -0
  80. package/src/cli/cmd/tui/context/sdk.tsx +74 -0
  81. package/src/cli/cmd/tui/context/sync.tsx +372 -0
  82. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  83. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  84. package/src/cli/cmd/tui/context/theme/bincode.json +245 -0
  85. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  86. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  87. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  88. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  89. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  90. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  91. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  92. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  93. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  94. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  95. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  96. package/src/cli/cmd/tui/context/theme/lucent-orng.json +227 -0
  97. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  98. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  99. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  100. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  101. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  102. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  103. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  104. package/src/cli/cmd/tui/context/theme/orng.json +245 -0
  105. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  106. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  107. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  108. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  109. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  110. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  111. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  112. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  113. package/src/cli/cmd/tui/context/theme.tsx +1109 -0
  114. package/src/cli/cmd/tui/event.ts +40 -0
  115. package/src/cli/cmd/tui/routes/home.tsx +105 -0
  116. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  117. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  118. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  119. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  120. package/src/cli/cmd/tui/routes/session/footer.tsx +88 -0
  121. package/src/cli/cmd/tui/routes/session/header.tsx +141 -0
  122. package/src/cli/cmd/tui/routes/session/index.tsx +1888 -0
  123. package/src/cli/cmd/tui/routes/session/sidebar.tsx +321 -0
  124. package/src/cli/cmd/tui/spawn.ts +60 -0
  125. package/src/cli/cmd/tui/thread.ts +120 -0
  126. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  127. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  128. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  129. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  130. package/src/cli/cmd/tui/ui/dialog-select.tsx +330 -0
  131. package/src/cli/cmd/tui/ui/dialog.tsx +170 -0
  132. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  133. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  134. package/src/cli/cmd/tui/util/clipboard.ts +127 -0
  135. package/src/cli/cmd/tui/util/editor.ts +32 -0
  136. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  137. package/src/cli/cmd/tui/worker.ts +63 -0
  138. package/src/cli/cmd/uninstall.ts +344 -0
  139. package/src/cli/cmd/upgrade.ts +67 -0
  140. package/src/cli/cmd/web.ts +84 -0
  141. package/src/cli/error.ts +55 -0
  142. package/src/cli/ui.ts +84 -0
  143. package/src/cli/upgrade.ts +25 -0
  144. package/src/command/index.ts +80 -0
  145. package/src/command/template/initialize.txt +10 -0
  146. package/src/command/template/review.txt +97 -0
  147. package/src/config/config.ts +995 -0
  148. package/src/config/markdown.ts +41 -0
  149. package/src/env/index.ts +26 -0
  150. package/src/file/ignore.ts +83 -0
  151. package/src/file/index.ts +328 -0
  152. package/src/file/ripgrep.ts +393 -0
  153. package/src/file/time.ts +64 -0
  154. package/src/file/watcher.ts +103 -0
  155. package/src/flag/flag.ts +46 -0
  156. package/src/format/formatter.ts +315 -0
  157. package/src/format/index.ts +137 -0
  158. package/src/global/index.ts +52 -0
  159. package/src/id/id.ts +73 -0
  160. package/src/ide/index.ts +76 -0
  161. package/src/index.ts +217 -0
  162. package/src/installation/index.ts +196 -0
  163. package/src/lsp/client.ts +229 -0
  164. package/src/lsp/index.ts +485 -0
  165. package/src/lsp/language.ts +116 -0
  166. package/src/lsp/server.ts +1895 -0
  167. package/src/mcp/auth.ts +135 -0
  168. package/src/mcp/index.ts +654 -0
  169. package/src/mcp/oauth-callback.ts +200 -0
  170. package/src/mcp/oauth-provider.ts +154 -0
  171. package/src/patch/index.ts +622 -0
  172. package/src/permission/index.ts +199 -0
  173. package/src/plugin/index.ts +101 -0
  174. package/src/project/bootstrap.ts +31 -0
  175. package/src/project/instance.ts +78 -0
  176. package/src/project/project.ts +221 -0
  177. package/src/project/state.ts +65 -0
  178. package/src/project/vcs.ts +76 -0
  179. package/src/provider/auth.ts +143 -0
  180. package/src/provider/models-macro.ts +11 -0
  181. package/src/provider/models.ts +106 -0
  182. package/src/provider/provider.ts +1071 -0
  183. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  184. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  185. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +101 -0
  186. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  187. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  188. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  189. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  190. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  191. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
  192. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  193. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  194. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  195. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  196. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  197. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  198. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  199. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  200. package/src/provider/transform.ts +455 -0
  201. package/src/pty/index.ts +231 -0
  202. package/src/server/error.ts +36 -0
  203. package/src/server/project.ts +79 -0
  204. package/src/server/server.ts +2642 -0
  205. package/src/server/tui.ts +71 -0
  206. package/src/session/compaction.ts +223 -0
  207. package/src/session/index.ts +458 -0
  208. package/src/session/llm.ts +201 -0
  209. package/src/session/message-v2.ts +659 -0
  210. package/src/session/message.ts +189 -0
  211. package/src/session/processor.ts +409 -0
  212. package/src/session/prompt/anthropic-20250930.txt +166 -0
  213. package/src/session/prompt/anthropic.txt +104 -0
  214. package/src/session/prompt/anthropic_spoof.txt +1 -0
  215. package/src/session/prompt/beast.txt +147 -0
  216. package/src/session/prompt/build-switch.txt +5 -0
  217. package/src/session/prompt/codex.txt +318 -0
  218. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  219. package/src/session/prompt/gemini.txt +155 -0
  220. package/src/session/prompt/max-steps.txt +16 -0
  221. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  222. package/src/session/prompt/plan.txt +26 -0
  223. package/src/session/prompt/polaris.txt +106 -0
  224. package/src/session/prompt/qwen.txt +109 -0
  225. package/src/session/prompt.ts +1446 -0
  226. package/src/session/retry.ts +86 -0
  227. package/src/session/revert.ts +108 -0
  228. package/src/session/status.ts +76 -0
  229. package/src/session/summary.ts +194 -0
  230. package/src/session/system.ts +120 -0
  231. package/src/session/todo.ts +37 -0
  232. package/src/share/share-next.ts +194 -0
  233. package/src/share/share.ts +87 -0
  234. package/src/shell/shell.ts +67 -0
  235. package/src/skill/index.ts +1 -0
  236. package/src/skill/skill.ts +83 -0
  237. package/src/snapshot/index.ts +197 -0
  238. package/src/storage/storage.ts +226 -0
  239. package/src/tool/bash.ts +306 -0
  240. package/src/tool/bash.txt +158 -0
  241. package/src/tool/batch.ts +175 -0
  242. package/src/tool/batch.txt +24 -0
  243. package/src/tool/codesearch.ts +138 -0
  244. package/src/tool/codesearch.txt +12 -0
  245. package/src/tool/edit.ts +675 -0
  246. package/src/tool/edit.txt +10 -0
  247. package/src/tool/glob.ts +65 -0
  248. package/src/tool/glob.txt +6 -0
  249. package/src/tool/grep.ts +121 -0
  250. package/src/tool/grep.txt +8 -0
  251. package/src/tool/invalid.ts +17 -0
  252. package/src/tool/ls.ts +110 -0
  253. package/src/tool/ls.txt +1 -0
  254. package/src/tool/lsp-diagnostics.ts +26 -0
  255. package/src/tool/lsp-diagnostics.txt +1 -0
  256. package/src/tool/lsp-hover.ts +31 -0
  257. package/src/tool/lsp-hover.txt +1 -0
  258. package/src/tool/lsp.ts +87 -0
  259. package/src/tool/lsp.txt +19 -0
  260. package/src/tool/multiedit.ts +46 -0
  261. package/src/tool/multiedit.txt +41 -0
  262. package/src/tool/patch.ts +233 -0
  263. package/src/tool/patch.txt +1 -0
  264. package/src/tool/read.ts +219 -0
  265. package/src/tool/read.txt +12 -0
  266. package/src/tool/registry.ts +162 -0
  267. package/src/tool/skill.ts +100 -0
  268. package/src/tool/task.ts +136 -0
  269. package/src/tool/task.txt +60 -0
  270. package/src/tool/todo.ts +39 -0
  271. package/src/tool/todoread.txt +14 -0
  272. package/src/tool/todowrite.txt +167 -0
  273. package/src/tool/tool.ts +71 -0
  274. package/src/tool/webfetch.ts +187 -0
  275. package/src/tool/webfetch.txt +13 -0
  276. package/src/tool/websearch.ts +150 -0
  277. package/src/tool/websearch.txt +11 -0
  278. package/src/tool/write.ts +110 -0
  279. package/src/tool/write.txt +8 -0
  280. package/src/util/archive.ts +16 -0
  281. package/src/util/color.ts +19 -0
  282. package/src/util/context.ts +25 -0
  283. package/src/util/defer.ts +12 -0
  284. package/src/util/eventloop.ts +20 -0
  285. package/src/util/filesystem.ts +83 -0
  286. package/src/util/fn.ts +11 -0
  287. package/src/util/iife.ts +3 -0
  288. package/src/util/keybind.ts +102 -0
  289. package/src/util/lazy.ts +11 -0
  290. package/src/util/locale.ts +81 -0
  291. package/src/util/lock.ts +98 -0
  292. package/src/util/log.ts +180 -0
  293. package/src/util/queue.ts +32 -0
  294. package/src/util/rpc.ts +42 -0
  295. package/src/util/scrap.ts +10 -0
  296. package/src/util/signal.ts +12 -0
  297. package/src/util/timeout.ts +14 -0
  298. package/src/util/token.ts +7 -0
  299. package/src/util/wildcard.ts +54 -0
  300. package/tsconfig.json +16 -0
@@ -0,0 +1,659 @@
1
+ import { BusEvent } from "@/bus/bus-event"
2
+ import { Bus } from "@/bus"
3
+ import z from "zod"
4
+ import { NamedError } from "@bincode-ai/util/error"
5
+ import { Message } from "./message"
6
+ import { APICallError, convertToModelMessages, LoadAPIKeyError, type ModelMessage, type UIMessage } from "ai"
7
+ import { Identifier } from "../id/id"
8
+ import { LSP } from "../lsp"
9
+ import { Snapshot } from "@/snapshot"
10
+ import { fn } from "@/util/fn"
11
+ import { Storage } from "@/storage/storage"
12
+ import { ProviderTransform } from "@/provider/transform"
13
+ import { STATUS_CODES } from "http"
14
+ import { iife } from "@/util/iife"
15
+
16
+ export namespace MessageV2 {
17
+ export const OutputLengthError = NamedError.create("MessageOutputLengthError", z.object({}))
18
+ export const AbortedError = NamedError.create("MessageAbortedError", z.object({ message: z.string() }))
19
+ export const AuthError = NamedError.create(
20
+ "ProviderAuthError",
21
+ z.object({
22
+ providerID: z.string(),
23
+ message: z.string(),
24
+ }),
25
+ )
26
+ export const APIError = NamedError.create(
27
+ "APIError",
28
+ z.object({
29
+ message: z.string(),
30
+ statusCode: z.number().optional(),
31
+ isRetryable: z.boolean(),
32
+ responseHeaders: z.record(z.string(), z.string()).optional(),
33
+ responseBody: z.string().optional(),
34
+ }),
35
+ )
36
+ export type APIError = z.infer<typeof APIError.Schema>
37
+
38
+ const PartBase = z.object({
39
+ id: z.string(),
40
+ sessionID: z.string(),
41
+ messageID: z.string(),
42
+ })
43
+
44
+ export const SnapshotPart = PartBase.extend({
45
+ type: z.literal("snapshot"),
46
+ snapshot: z.string(),
47
+ }).meta({
48
+ ref: "SnapshotPart",
49
+ })
50
+ export type SnapshotPart = z.infer<typeof SnapshotPart>
51
+
52
+ export const PatchPart = PartBase.extend({
53
+ type: z.literal("patch"),
54
+ hash: z.string(),
55
+ files: z.string().array(),
56
+ }).meta({
57
+ ref: "PatchPart",
58
+ })
59
+ export type PatchPart = z.infer<typeof PatchPart>
60
+
61
+ export const TextPart = PartBase.extend({
62
+ type: z.literal("text"),
63
+ text: z.string(),
64
+ synthetic: z.boolean().optional(),
65
+ ignored: z.boolean().optional(),
66
+ time: z
67
+ .object({
68
+ start: z.number(),
69
+ end: z.number().optional(),
70
+ })
71
+ .optional(),
72
+ metadata: z.record(z.string(), z.any()).optional(),
73
+ }).meta({
74
+ ref: "TextPart",
75
+ })
76
+ export type TextPart = z.infer<typeof TextPart>
77
+
78
+ export const ReasoningPart = PartBase.extend({
79
+ type: z.literal("reasoning"),
80
+ text: z.string(),
81
+ metadata: z.record(z.string(), z.any()).optional(),
82
+ time: z.object({
83
+ start: z.number(),
84
+ end: z.number().optional(),
85
+ }),
86
+ }).meta({
87
+ ref: "ReasoningPart",
88
+ })
89
+ export type ReasoningPart = z.infer<typeof ReasoningPart>
90
+
91
+ const FilePartSourceBase = z.object({
92
+ text: z
93
+ .object({
94
+ value: z.string(),
95
+ start: z.number().int(),
96
+ end: z.number().int(),
97
+ })
98
+ .meta({
99
+ ref: "FilePartSourceText",
100
+ }),
101
+ })
102
+
103
+ export const FileSource = FilePartSourceBase.extend({
104
+ type: z.literal("file"),
105
+ path: z.string(),
106
+ }).meta({
107
+ ref: "FileSource",
108
+ })
109
+
110
+ export const SymbolSource = FilePartSourceBase.extend({
111
+ type: z.literal("symbol"),
112
+ path: z.string(),
113
+ range: LSP.Range,
114
+ name: z.string(),
115
+ kind: z.number().int(),
116
+ }).meta({
117
+ ref: "SymbolSource",
118
+ })
119
+
120
+ export const FilePartSource = z.discriminatedUnion("type", [FileSource, SymbolSource]).meta({
121
+ ref: "FilePartSource",
122
+ })
123
+
124
+ export const FilePart = PartBase.extend({
125
+ type: z.literal("file"),
126
+ mime: z.string(),
127
+ filename: z.string().optional(),
128
+ url: z.string(),
129
+ source: FilePartSource.optional(),
130
+ }).meta({
131
+ ref: "FilePart",
132
+ })
133
+ export type FilePart = z.infer<typeof FilePart>
134
+
135
+ export const AgentPart = PartBase.extend({
136
+ type: z.literal("agent"),
137
+ name: z.string(),
138
+ source: z
139
+ .object({
140
+ value: z.string(),
141
+ start: z.number().int(),
142
+ end: z.number().int(),
143
+ })
144
+ .optional(),
145
+ }).meta({
146
+ ref: "AgentPart",
147
+ })
148
+ export type AgentPart = z.infer<typeof AgentPart>
149
+
150
+ export const CompactionPart = PartBase.extend({
151
+ type: z.literal("compaction"),
152
+ auto: z.boolean(),
153
+ }).meta({
154
+ ref: "CompactionPart",
155
+ })
156
+ export type CompactionPart = z.infer<typeof CompactionPart>
157
+
158
+ export const SubtaskPart = PartBase.extend({
159
+ type: z.literal("subtask"),
160
+ prompt: z.string(),
161
+ description: z.string(),
162
+ agent: z.string(),
163
+ command: z.string().optional(),
164
+ })
165
+ export type SubtaskPart = z.infer<typeof SubtaskPart>
166
+
167
+ export const RetryPart = PartBase.extend({
168
+ type: z.literal("retry"),
169
+ attempt: z.number(),
170
+ error: APIError.Schema,
171
+ time: z.object({
172
+ created: z.number(),
173
+ }),
174
+ }).meta({
175
+ ref: "RetryPart",
176
+ })
177
+ export type RetryPart = z.infer<typeof RetryPart>
178
+
179
+ export const StepStartPart = PartBase.extend({
180
+ type: z.literal("step-start"),
181
+ snapshot: z.string().optional(),
182
+ }).meta({
183
+ ref: "StepStartPart",
184
+ })
185
+ export type StepStartPart = z.infer<typeof StepStartPart>
186
+
187
+ export const StepFinishPart = PartBase.extend({
188
+ type: z.literal("step-finish"),
189
+ reason: z.string(),
190
+ snapshot: z.string().optional(),
191
+ cost: z.number(),
192
+ tokens: z.object({
193
+ input: z.number(),
194
+ output: z.number(),
195
+ reasoning: z.number(),
196
+ cache: z.object({
197
+ read: z.number(),
198
+ write: z.number(),
199
+ }),
200
+ }),
201
+ }).meta({
202
+ ref: "StepFinishPart",
203
+ })
204
+ export type StepFinishPart = z.infer<typeof StepFinishPart>
205
+
206
+ export const ToolStatePending = z
207
+ .object({
208
+ status: z.literal("pending"),
209
+ input: z.record(z.string(), z.any()),
210
+ raw: z.string(),
211
+ })
212
+ .meta({
213
+ ref: "ToolStatePending",
214
+ })
215
+
216
+ export type ToolStatePending = z.infer<typeof ToolStatePending>
217
+
218
+ export const ToolStateRunning = z
219
+ .object({
220
+ status: z.literal("running"),
221
+ input: z.record(z.string(), z.any()),
222
+ title: z.string().optional(),
223
+ metadata: z.record(z.string(), z.any()).optional(),
224
+ time: z.object({
225
+ start: z.number(),
226
+ }),
227
+ })
228
+ .meta({
229
+ ref: "ToolStateRunning",
230
+ })
231
+ export type ToolStateRunning = z.infer<typeof ToolStateRunning>
232
+
233
+ export const ToolStateCompleted = z
234
+ .object({
235
+ status: z.literal("completed"),
236
+ input: z.record(z.string(), z.any()),
237
+ output: z.string(),
238
+ title: z.string(),
239
+ metadata: z.record(z.string(), z.any()),
240
+ time: z.object({
241
+ start: z.number(),
242
+ end: z.number(),
243
+ compacted: z.number().optional(),
244
+ }),
245
+ attachments: FilePart.array().optional(),
246
+ })
247
+ .meta({
248
+ ref: "ToolStateCompleted",
249
+ })
250
+ export type ToolStateCompleted = z.infer<typeof ToolStateCompleted>
251
+
252
+ export const ToolStateError = z
253
+ .object({
254
+ status: z.literal("error"),
255
+ input: z.record(z.string(), z.any()),
256
+ error: z.string(),
257
+ metadata: z.record(z.string(), z.any()).optional(),
258
+ time: z.object({
259
+ start: z.number(),
260
+ end: z.number(),
261
+ }),
262
+ })
263
+ .meta({
264
+ ref: "ToolStateError",
265
+ })
266
+ export type ToolStateError = z.infer<typeof ToolStateError>
267
+
268
+ export const ToolState = z
269
+ .discriminatedUnion("status", [ToolStatePending, ToolStateRunning, ToolStateCompleted, ToolStateError])
270
+ .meta({
271
+ ref: "ToolState",
272
+ })
273
+
274
+ export const ToolPart = PartBase.extend({
275
+ type: z.literal("tool"),
276
+ callID: z.string(),
277
+ tool: z.string(),
278
+ state: ToolState,
279
+ metadata: z.record(z.string(), z.any()).optional(),
280
+ }).meta({
281
+ ref: "ToolPart",
282
+ })
283
+ export type ToolPart = z.infer<typeof ToolPart>
284
+
285
+ const Base = z.object({
286
+ id: z.string(),
287
+ sessionID: z.string(),
288
+ })
289
+
290
+ export const User = Base.extend({
291
+ role: z.literal("user"),
292
+ time: z.object({
293
+ created: z.number(),
294
+ }),
295
+ summary: z
296
+ .object({
297
+ title: z.string().optional(),
298
+ body: z.string().optional(),
299
+ diffs: Snapshot.FileDiff.array(),
300
+ })
301
+ .optional(),
302
+ agent: z.string(),
303
+ model: z.object({
304
+ providerID: z.string(),
305
+ modelID: z.string(),
306
+ }),
307
+ system: z.string().optional(),
308
+ tools: z.record(z.string(), z.boolean()).optional(),
309
+ }).meta({
310
+ ref: "UserMessage",
311
+ })
312
+ export type User = z.infer<typeof User>
313
+
314
+ export const Part = z
315
+ .discriminatedUnion("type", [
316
+ TextPart,
317
+ SubtaskPart,
318
+ ReasoningPart,
319
+ FilePart,
320
+ ToolPart,
321
+ StepStartPart,
322
+ StepFinishPart,
323
+ SnapshotPart,
324
+ PatchPart,
325
+ AgentPart,
326
+ RetryPart,
327
+ CompactionPart,
328
+ ])
329
+ .meta({
330
+ ref: "Part",
331
+ })
332
+ export type Part = z.infer<typeof Part>
333
+
334
+ export const Assistant = Base.extend({
335
+ role: z.literal("assistant"),
336
+ time: z.object({
337
+ created: z.number(),
338
+ completed: z.number().optional(),
339
+ }),
340
+ error: z
341
+ .discriminatedUnion("name", [
342
+ AuthError.Schema,
343
+ NamedError.Unknown.Schema,
344
+ OutputLengthError.Schema,
345
+ AbortedError.Schema,
346
+ APIError.Schema,
347
+ ])
348
+ .optional(),
349
+ parentID: z.string(),
350
+ modelID: z.string(),
351
+ providerID: z.string(),
352
+ /**
353
+ * @deprecated
354
+ */
355
+ mode: z.string(),
356
+ agent: z.string(),
357
+ path: z.object({
358
+ cwd: z.string(),
359
+ root: z.string(),
360
+ }),
361
+ summary: z.boolean().optional(),
362
+ cost: z.number(),
363
+ tokens: z.object({
364
+ input: z.number(),
365
+ output: z.number(),
366
+ reasoning: z.number(),
367
+ cache: z.object({
368
+ read: z.number(),
369
+ write: z.number(),
370
+ }),
371
+ }),
372
+ finish: z.string().optional(),
373
+ }).meta({
374
+ ref: "AssistantMessage",
375
+ })
376
+ export type Assistant = z.infer<typeof Assistant>
377
+
378
+ export const Info = z.discriminatedUnion("role", [User, Assistant]).meta({
379
+ ref: "Message",
380
+ })
381
+ export type Info = z.infer<typeof Info>
382
+
383
+ export const Event = {
384
+ Updated: BusEvent.define(
385
+ "message.updated",
386
+ z.object({
387
+ info: Info,
388
+ }),
389
+ ),
390
+ Removed: BusEvent.define(
391
+ "message.removed",
392
+ z.object({
393
+ sessionID: z.string(),
394
+ messageID: z.string(),
395
+ }),
396
+ ),
397
+ PartUpdated: BusEvent.define(
398
+ "message.part.updated",
399
+ z.object({
400
+ part: Part,
401
+ delta: z.string().optional(),
402
+ }),
403
+ ),
404
+ PartRemoved: BusEvent.define(
405
+ "message.part.removed",
406
+ z.object({
407
+ sessionID: z.string(),
408
+ messageID: z.string(),
409
+ partID: z.string(),
410
+ }),
411
+ ),
412
+ }
413
+
414
+ export const WithParts = z.object({
415
+ info: Info,
416
+ parts: z.array(Part),
417
+ })
418
+ export type WithParts = z.infer<typeof WithParts>
419
+
420
+ export function toModelMessage(input: WithParts[]): ModelMessage[] {
421
+ const result: UIMessage[] = []
422
+
423
+ for (const msg of input) {
424
+ if (msg.parts.length === 0) continue
425
+
426
+ if (msg.info.role === "user") {
427
+ const userMessage: UIMessage = {
428
+ id: msg.info.id,
429
+ role: "user",
430
+ parts: [],
431
+ }
432
+ result.push(userMessage)
433
+ for (const part of msg.parts) {
434
+ if (part.type === "text" && !part.ignored)
435
+ userMessage.parts.push({
436
+ type: "text",
437
+ text: part.text,
438
+ })
439
+ // text/plain and directory files are converted into text parts, ignore them
440
+ if (part.type === "file" && part.mime !== "text/plain" && part.mime !== "application/x-directory")
441
+ userMessage.parts.push({
442
+ type: "file",
443
+ url: part.url,
444
+ mediaType: part.mime,
445
+ filename: part.filename,
446
+ })
447
+
448
+ if (part.type === "compaction") {
449
+ userMessage.parts.push({
450
+ type: "text",
451
+ text: "What did we do so far?",
452
+ })
453
+ }
454
+ if (part.type === "subtask") {
455
+ userMessage.parts.push({
456
+ type: "text",
457
+ text: "The following tool was executed by the user",
458
+ })
459
+ }
460
+ }
461
+ }
462
+
463
+ if (msg.info.role === "assistant") {
464
+ if (
465
+ msg.info.error &&
466
+ !(
467
+ MessageV2.AbortedError.isInstance(msg.info.error) &&
468
+ msg.parts.some((part) => part.type !== "step-start" && part.type !== "reasoning")
469
+ )
470
+ ) {
471
+ continue
472
+ }
473
+ const assistantMessage: UIMessage = {
474
+ id: msg.info.id,
475
+ role: "assistant",
476
+ parts: [],
477
+ }
478
+ result.push(assistantMessage)
479
+ for (const part of msg.parts) {
480
+ if (part.type === "text")
481
+ assistantMessage.parts.push({
482
+ type: "text",
483
+ text: part.text,
484
+ providerMetadata: part.metadata,
485
+ })
486
+ if (part.type === "step-start")
487
+ assistantMessage.parts.push({
488
+ type: "step-start",
489
+ })
490
+ if (part.type === "tool") {
491
+ if (part.state.status === "completed") {
492
+ if (part.state.attachments?.length) {
493
+ result.push({
494
+ id: Identifier.ascending("message"),
495
+ role: "user",
496
+ parts: [
497
+ {
498
+ type: "text",
499
+ text: `Tool ${part.tool} returned an attachment:`,
500
+ },
501
+ ...part.state.attachments.map((attachment) => ({
502
+ type: "file" as const,
503
+ url: attachment.url,
504
+ mediaType: attachment.mime,
505
+ filename: attachment.filename,
506
+ })),
507
+ ],
508
+ })
509
+ }
510
+ assistantMessage.parts.push({
511
+ type: ("tool-" + part.tool) as `tool-${string}`,
512
+ state: "output-available",
513
+ toolCallId: part.callID,
514
+ input: part.state.input,
515
+ output: part.state.time.compacted ? "[Old tool result content cleared]" : part.state.output,
516
+ callProviderMetadata: part.metadata,
517
+ })
518
+ }
519
+ if (part.state.status === "error")
520
+ assistantMessage.parts.push({
521
+ type: ("tool-" + part.tool) as `tool-${string}`,
522
+ state: "output-error",
523
+ toolCallId: part.callID,
524
+ input: part.state.input,
525
+ errorText: part.state.error,
526
+ callProviderMetadata: part.metadata,
527
+ })
528
+ }
529
+ if (part.type === "reasoning") {
530
+ assistantMessage.parts.push({
531
+ type: "reasoning",
532
+ text: part.text,
533
+ providerMetadata: part.metadata,
534
+ })
535
+ }
536
+ }
537
+ }
538
+ }
539
+
540
+ return convertToModelMessages(result.filter((msg) => msg.parts.length > 0))
541
+ }
542
+
543
+ export const stream = fn(Identifier.schema("session"), async function* (sessionID) {
544
+ const list = await Array.fromAsync(await Storage.list(["message", sessionID]))
545
+ for (let i = list.length - 1; i >= 0; i--) {
546
+ yield await get({
547
+ sessionID,
548
+ messageID: list[i][2],
549
+ })
550
+ }
551
+ })
552
+
553
+ export const parts = fn(Identifier.schema("message"), async (messageID) => {
554
+ const result = [] as MessageV2.Part[]
555
+ for (const item of await Storage.list(["part", messageID])) {
556
+ const read = await Storage.read<MessageV2.Part>(item)
557
+ result.push(read)
558
+ }
559
+ result.sort((a, b) => (a.id > b.id ? 1 : -1))
560
+ return result
561
+ })
562
+
563
+ export const get = fn(
564
+ z.object({
565
+ sessionID: Identifier.schema("session"),
566
+ messageID: Identifier.schema("message"),
567
+ }),
568
+ async (input) => {
569
+ return {
570
+ info: await Storage.read<MessageV2.Info>(["message", input.sessionID, input.messageID]),
571
+ parts: await parts(input.messageID),
572
+ }
573
+ },
574
+ )
575
+
576
+ export async function filterCompacted(stream: AsyncIterable<MessageV2.WithParts>) {
577
+ const result = [] as MessageV2.WithParts[]
578
+ const completed = new Set<string>()
579
+ for await (const msg of stream) {
580
+ result.push(msg)
581
+ if (
582
+ msg.info.role === "user" &&
583
+ completed.has(msg.info.id) &&
584
+ msg.parts.some((part) => part.type === "compaction")
585
+ )
586
+ break
587
+ if (msg.info.role === "assistant" && msg.info.summary && msg.info.finish) completed.add(msg.info.parentID)
588
+ }
589
+ result.reverse()
590
+ return result
591
+ }
592
+
593
+ export function fromError(e: unknown, ctx: { providerID: string }) {
594
+ switch (true) {
595
+ case e instanceof DOMException && e.name === "AbortError":
596
+ return new MessageV2.AbortedError(
597
+ { message: e.message },
598
+ {
599
+ cause: e,
600
+ },
601
+ ).toObject()
602
+ case MessageV2.OutputLengthError.isInstance(e):
603
+ return e
604
+ case LoadAPIKeyError.isInstance(e):
605
+ return new MessageV2.AuthError(
606
+ {
607
+ providerID: ctx.providerID,
608
+ message: e.message,
609
+ },
610
+ { cause: e },
611
+ ).toObject()
612
+ case APICallError.isInstance(e):
613
+ const message = iife(() => {
614
+ let msg = e.message
615
+ if (msg === "") {
616
+ if (e.responseBody) return e.responseBody
617
+ if (e.statusCode) {
618
+ const err = STATUS_CODES[e.statusCode]
619
+ if (err) return err
620
+ }
621
+ return "Unknown error"
622
+ }
623
+ const transformed = ProviderTransform.error(ctx.providerID, e)
624
+ if (transformed !== msg) {
625
+ return transformed
626
+ }
627
+ if (!e.responseBody || (e.statusCode && msg !== STATUS_CODES[e.statusCode])) {
628
+ return msg
629
+ }
630
+
631
+ try {
632
+ const body = JSON.parse(e.responseBody)
633
+ // try to extract common error message fields
634
+ const errMsg = body.message || body.error || body.error?.message
635
+ if (errMsg && typeof errMsg === "string") {
636
+ return `${msg}: ${errMsg}`
637
+ }
638
+ } catch {}
639
+
640
+ return `${msg}: ${e.responseBody}`
641
+ }).trim()
642
+
643
+ return new MessageV2.APIError(
644
+ {
645
+ message,
646
+ statusCode: e.statusCode,
647
+ isRetryable: e.isRetryable,
648
+ responseHeaders: e.responseHeaders,
649
+ responseBody: e.responseBody,
650
+ },
651
+ { cause: e },
652
+ ).toObject()
653
+ case e instanceof Error:
654
+ return new NamedError.Unknown({ message: e.toString() }, { cause: e }).toObject()
655
+ default:
656
+ return new NamedError.Unknown({ message: JSON.stringify(e) }, { cause: e })
657
+ }
658
+ }
659
+ }