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,458 @@
1
+ import { BusEvent } from "@/bus/bus-event"
2
+ import { Bus } from "@/bus"
3
+ import { Decimal } from "decimal.js"
4
+ import z from "zod"
5
+ import { type LanguageModelUsage, type ProviderMetadata } from "ai"
6
+ import { Config } from "../config/config"
7
+ import { Flag } from "../flag/flag"
8
+ import { Identifier } from "../id/id"
9
+ import { Installation } from "../installation"
10
+
11
+ import { Storage } from "../storage/storage"
12
+ import { Log } from "../util/log"
13
+ import { MessageV2 } from "./message-v2"
14
+ import { Instance } from "../project/instance"
15
+ import { SessionPrompt } from "./prompt"
16
+ import { fn } from "@/util/fn"
17
+ import { Command } from "../command"
18
+ import { Snapshot } from "@/snapshot"
19
+
20
+ import type { Provider } from "@/provider/provider"
21
+
22
+ export namespace Session {
23
+ const log = Log.create({ service: "session" })
24
+
25
+ const parentTitlePrefix = "New session - "
26
+ const childTitlePrefix = "Child session - "
27
+
28
+ function createDefaultTitle(isChild = false) {
29
+ return (isChild ? childTitlePrefix : parentTitlePrefix) + new Date().toISOString()
30
+ }
31
+
32
+ export function isDefaultTitle(title: string) {
33
+ return new RegExp(
34
+ `^(${parentTitlePrefix}|${childTitlePrefix})\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$`,
35
+ ).test(title)
36
+ }
37
+
38
+ export const Info = z
39
+ .object({
40
+ id: Identifier.schema("session"),
41
+ projectID: z.string(),
42
+ directory: z.string(),
43
+ parentID: Identifier.schema("session").optional(),
44
+ summary: z
45
+ .object({
46
+ additions: z.number(),
47
+ deletions: z.number(),
48
+ files: z.number(),
49
+ diffs: Snapshot.FileDiff.array().optional(),
50
+ })
51
+ .optional(),
52
+ share: z
53
+ .object({
54
+ url: z.string(),
55
+ })
56
+ .optional(),
57
+ title: z.string(),
58
+ version: z.string(),
59
+ time: z.object({
60
+ created: z.number(),
61
+ updated: z.number(),
62
+ compacting: z.number().optional(),
63
+ archived: z.number().optional(),
64
+ }),
65
+ revert: z
66
+ .object({
67
+ messageID: z.string(),
68
+ partID: z.string().optional(),
69
+ snapshot: z.string().optional(),
70
+ diff: z.string().optional(),
71
+ })
72
+ .optional(),
73
+ })
74
+ .meta({
75
+ ref: "Session",
76
+ })
77
+ export type Info = z.output<typeof Info>
78
+
79
+ export const ShareInfo = z
80
+ .object({
81
+ secret: z.string(),
82
+ url: z.string(),
83
+ })
84
+ .meta({
85
+ ref: "SessionShare",
86
+ })
87
+ export type ShareInfo = z.output<typeof ShareInfo>
88
+
89
+ export const Event = {
90
+ Created: BusEvent.define(
91
+ "session.created",
92
+ z.object({
93
+ info: Info,
94
+ }),
95
+ ),
96
+ Updated: BusEvent.define(
97
+ "session.updated",
98
+ z.object({
99
+ info: Info,
100
+ }),
101
+ ),
102
+ Deleted: BusEvent.define(
103
+ "session.deleted",
104
+ z.object({
105
+ info: Info,
106
+ }),
107
+ ),
108
+ Diff: BusEvent.define(
109
+ "session.diff",
110
+ z.object({
111
+ sessionID: z.string(),
112
+ diff: Snapshot.FileDiff.array(),
113
+ }),
114
+ ),
115
+ Error: BusEvent.define(
116
+ "session.error",
117
+ z.object({
118
+ sessionID: z.string().optional(),
119
+ error: MessageV2.Assistant.shape.error,
120
+ }),
121
+ ),
122
+ }
123
+
124
+ export const create = fn(
125
+ z
126
+ .object({
127
+ parentID: Identifier.schema("session").optional(),
128
+ title: z.string().optional(),
129
+ })
130
+ .optional(),
131
+ async (input) => {
132
+ return createNext({
133
+ parentID: input?.parentID,
134
+ directory: Instance.directory,
135
+ title: input?.title,
136
+ })
137
+ },
138
+ )
139
+
140
+ export const fork = fn(
141
+ z.object({
142
+ sessionID: Identifier.schema("session"),
143
+ messageID: Identifier.schema("message").optional(),
144
+ }),
145
+ async (input) => {
146
+ const session = await createNext({
147
+ directory: Instance.directory,
148
+ })
149
+ const msgs = await messages({ sessionID: input.sessionID })
150
+ for (const msg of msgs) {
151
+ if (input.messageID && msg.info.id >= input.messageID) break
152
+ const cloned = await updateMessage({
153
+ ...msg.info,
154
+ sessionID: session.id,
155
+ id: Identifier.ascending("message"),
156
+ })
157
+
158
+ for (const part of msg.parts) {
159
+ await updatePart({
160
+ ...part,
161
+ id: Identifier.ascending("part"),
162
+ messageID: cloned.id,
163
+ sessionID: session.id,
164
+ })
165
+ }
166
+ }
167
+ return session
168
+ },
169
+ )
170
+
171
+ export const touch = fn(Identifier.schema("session"), async (sessionID) => {
172
+ await update(sessionID, (draft) => {
173
+ draft.time.updated = Date.now()
174
+ })
175
+ })
176
+
177
+ export async function createNext(input: { id?: string; title?: string; parentID?: string; directory: string }) {
178
+ const result: Info = {
179
+ id: Identifier.descending("session", input.id),
180
+ version: Installation.VERSION,
181
+ projectID: Instance.project.id,
182
+ directory: input.directory,
183
+ parentID: input.parentID,
184
+ title: input.title ?? createDefaultTitle(!!input.parentID),
185
+ time: {
186
+ created: Date.now(),
187
+ updated: Date.now(),
188
+ },
189
+ }
190
+ log.info("created", result)
191
+ await Storage.write(["session", Instance.project.id, result.id], result)
192
+ Bus.publish(Event.Created, {
193
+ info: result,
194
+ })
195
+ const cfg = await Config.get()
196
+ if (!result.parentID && (Flag.BINCODE_AUTO_SHARE || cfg.share === "auto"))
197
+ share(result.id)
198
+ .then((share) => {
199
+ update(result.id, (draft) => {
200
+ draft.share = share
201
+ })
202
+ })
203
+ .catch(() => {
204
+ // Silently ignore sharing errors during session creation
205
+ })
206
+ Bus.publish(Event.Updated, {
207
+ info: result,
208
+ })
209
+ return result
210
+ }
211
+
212
+ export const get = fn(Identifier.schema("session"), async (id) => {
213
+ const read = await Storage.read<Info>(["session", Instance.project.id, id])
214
+ return read as Info
215
+ })
216
+
217
+ export const getShare = fn(Identifier.schema("session"), async (id) => {
218
+ return Storage.read<ShareInfo>(["share", id])
219
+ })
220
+
221
+ export const share = fn(Identifier.schema("session"), async (id) => {
222
+ const cfg = await Config.get()
223
+ if (cfg.share === "disabled") {
224
+ throw new Error("Sharing is disabled in configuration")
225
+ }
226
+ const { ShareNext } = await import("@/share/share-next")
227
+ const share = await ShareNext.create(id)
228
+ await update(id, (draft) => {
229
+ draft.share = {
230
+ url: share.url,
231
+ }
232
+ })
233
+ return share
234
+ })
235
+
236
+ export const unshare = fn(Identifier.schema("session"), async (id) => {
237
+ // Use ShareNext to remove the share (same as share function uses ShareNext to create)
238
+ const { ShareNext } = await import("@/share/share-next")
239
+ await ShareNext.remove(id)
240
+ await update(id, (draft) => {
241
+ draft.share = undefined
242
+ })
243
+ })
244
+
245
+ export async function update(id: string, editor: (session: Info) => void) {
246
+ const project = Instance.project
247
+ const result = await Storage.update<Info>(["session", project.id, id], (draft) => {
248
+ editor(draft)
249
+ draft.time.updated = Date.now()
250
+ })
251
+ Bus.publish(Event.Updated, {
252
+ info: result,
253
+ })
254
+ return result
255
+ }
256
+
257
+ export const diff = fn(Identifier.schema("session"), async (sessionID) => {
258
+ const diffs = await Storage.read<Snapshot.FileDiff[]>(["session_diff", sessionID])
259
+ return diffs ?? []
260
+ })
261
+
262
+ export const messages = fn(
263
+ z.object({
264
+ sessionID: Identifier.schema("session"),
265
+ limit: z.number().optional(),
266
+ }),
267
+ async (input) => {
268
+ const result = [] as MessageV2.WithParts[]
269
+ for await (const msg of MessageV2.stream(input.sessionID)) {
270
+ if (input.limit && result.length >= input.limit) break
271
+ result.push(msg)
272
+ }
273
+ result.reverse()
274
+ return result
275
+ },
276
+ )
277
+
278
+ export async function* list() {
279
+ const project = Instance.project
280
+ for (const item of await Storage.list(["session", project.id])) {
281
+ yield Storage.read<Info>(item)
282
+ }
283
+ }
284
+
285
+ export const children = fn(Identifier.schema("session"), async (parentID) => {
286
+ const project = Instance.project
287
+ const result = [] as Session.Info[]
288
+ for (const item of await Storage.list(["session", project.id])) {
289
+ const session = await Storage.read<Info>(item)
290
+ if (session.parentID !== parentID) continue
291
+ result.push(session)
292
+ }
293
+ return result
294
+ })
295
+
296
+ export const remove = fn(Identifier.schema("session"), async (sessionID) => {
297
+ const project = Instance.project
298
+ try {
299
+ const session = await get(sessionID)
300
+ for (const child of await children(sessionID)) {
301
+ await remove(child.id)
302
+ }
303
+ await unshare(sessionID).catch(() => {})
304
+ for (const msg of await Storage.list(["message", sessionID])) {
305
+ for (const part of await Storage.list(["part", msg.at(-1)!])) {
306
+ await Storage.remove(part)
307
+ }
308
+ await Storage.remove(msg)
309
+ }
310
+ await Storage.remove(["session", project.id, sessionID])
311
+ Bus.publish(Event.Deleted, {
312
+ info: session,
313
+ })
314
+ } catch (e) {
315
+ log.error(e)
316
+ }
317
+ })
318
+
319
+ export const updateMessage = fn(MessageV2.Info, async (msg) => {
320
+ await Storage.write(["message", msg.sessionID, msg.id], msg)
321
+ Bus.publish(MessageV2.Event.Updated, {
322
+ info: msg,
323
+ })
324
+ return msg
325
+ })
326
+
327
+ export const removeMessage = fn(
328
+ z.object({
329
+ sessionID: Identifier.schema("session"),
330
+ messageID: Identifier.schema("message"),
331
+ }),
332
+ async (input) => {
333
+ await Storage.remove(["message", input.sessionID, input.messageID])
334
+ Bus.publish(MessageV2.Event.Removed, {
335
+ sessionID: input.sessionID,
336
+ messageID: input.messageID,
337
+ })
338
+ return input.messageID
339
+ },
340
+ )
341
+
342
+ export const removePart = fn(
343
+ z.object({
344
+ sessionID: Identifier.schema("session"),
345
+ messageID: Identifier.schema("message"),
346
+ partID: Identifier.schema("part"),
347
+ }),
348
+ async (input) => {
349
+ await Storage.remove(["part", input.messageID, input.partID])
350
+ Bus.publish(MessageV2.Event.PartRemoved, {
351
+ sessionID: input.sessionID,
352
+ messageID: input.messageID,
353
+ partID: input.partID,
354
+ })
355
+ return input.partID
356
+ },
357
+ )
358
+
359
+ const UpdatePartInput = z.union([
360
+ MessageV2.Part,
361
+ z.object({
362
+ part: MessageV2.TextPart,
363
+ delta: z.string(),
364
+ }),
365
+ z.object({
366
+ part: MessageV2.ReasoningPart,
367
+ delta: z.string(),
368
+ }),
369
+ ])
370
+
371
+ export const updatePart = fn(UpdatePartInput, async (input) => {
372
+ const part = "delta" in input ? input.part : input
373
+ const delta = "delta" in input ? input.delta : undefined
374
+ await Storage.write(["part", part.messageID, part.id], part)
375
+ Bus.publish(MessageV2.Event.PartUpdated, {
376
+ part,
377
+ delta,
378
+ })
379
+ return part
380
+ })
381
+
382
+ export const getUsage = fn(
383
+ z.object({
384
+ model: z.custom<Provider.Model>(),
385
+ usage: z.custom<LanguageModelUsage>(),
386
+ metadata: z.custom<ProviderMetadata>().optional(),
387
+ }),
388
+ (input) => {
389
+ const cachedInputTokens = input.usage.cachedInputTokens ?? 0
390
+ const excludesCachedTokens = !!(input.metadata?.["anthropic"] || input.metadata?.["bedrock"])
391
+ const adjustedInputTokens = excludesCachedTokens
392
+ ? (input.usage.inputTokens ?? 0)
393
+ : (input.usage.inputTokens ?? 0) - cachedInputTokens
394
+ const safe = (value: number) => {
395
+ if (!Number.isFinite(value)) return 0
396
+ return value
397
+ }
398
+
399
+ const tokens = {
400
+ input: safe(adjustedInputTokens),
401
+ output: safe(input.usage.outputTokens ?? 0),
402
+ reasoning: safe(input.usage?.reasoningTokens ?? 0),
403
+ cache: {
404
+ write: safe(
405
+ (input.metadata?.["anthropic"]?.["cacheCreationInputTokens"] ??
406
+ // @ts-expect-error
407
+ input.metadata?.["bedrock"]?.["usage"]?.["cacheWriteInputTokens"] ??
408
+ 0) as number,
409
+ ),
410
+ read: safe(cachedInputTokens),
411
+ },
412
+ }
413
+
414
+ const costInfo =
415
+ input.model.cost?.experimentalOver200K && tokens.input + tokens.cache.read > 200_000
416
+ ? input.model.cost.experimentalOver200K
417
+ : input.model.cost
418
+ return {
419
+ cost: safe(
420
+ new Decimal(0)
421
+ .add(new Decimal(tokens.input).mul(costInfo?.input ?? 0).div(1_000_000))
422
+ .add(new Decimal(tokens.output).mul(costInfo?.output ?? 0).div(1_000_000))
423
+ .add(new Decimal(tokens.cache.read).mul(costInfo?.cache?.read ?? 0).div(1_000_000))
424
+ .add(new Decimal(tokens.cache.write).mul(costInfo?.cache?.write ?? 0).div(1_000_000))
425
+ // TODO: update models.dev to have better pricing model, for now:
426
+ // charge reasoning tokens at the same rate as output tokens
427
+ .add(new Decimal(tokens.reasoning).mul(costInfo?.output ?? 0).div(1_000_000))
428
+ .toNumber(),
429
+ ),
430
+ tokens,
431
+ }
432
+ },
433
+ )
434
+
435
+ export class BusyError extends Error {
436
+ constructor(public readonly sessionID: string) {
437
+ super(`Session ${sessionID} is busy`)
438
+ }
439
+ }
440
+
441
+ export const initialize = fn(
442
+ z.object({
443
+ sessionID: Identifier.schema("session"),
444
+ modelID: z.string(),
445
+ providerID: z.string(),
446
+ messageID: Identifier.schema("message"),
447
+ }),
448
+ async (input) => {
449
+ await SessionPrompt.command({
450
+ sessionID: input.sessionID,
451
+ messageID: input.messageID,
452
+ model: input.providerID + "/" + input.modelID,
453
+ command: Command.Default.INIT,
454
+ arguments: "",
455
+ })
456
+ },
457
+ )
458
+ }
@@ -0,0 +1,201 @@
1
+ import { Provider } from "@/provider/provider"
2
+ import { Log } from "@/util/log"
3
+ import { streamText, wrapLanguageModel, type ModelMessage, type StreamTextResult, type Tool, type ToolSet } from "ai"
4
+ import { clone, mergeDeep, pipe } from "remeda"
5
+ import { ProviderTransform } from "@/provider/transform"
6
+ import { Config } from "@/config/config"
7
+ import { Instance } from "@/project/instance"
8
+ import type { Agent } from "@/agent/agent"
9
+ import type { MessageV2 } from "./message-v2"
10
+ import { Plugin } from "@/plugin"
11
+ import { SystemPrompt } from "./system"
12
+ import { ToolRegistry } from "@/tool/registry"
13
+ import { Flag } from "@/flag/flag"
14
+
15
+ export namespace LLM {
16
+ const log = Log.create({ service: "llm" })
17
+
18
+ export const OUTPUT_TOKEN_MAX = Flag.BINCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX || 32_000
19
+
20
+ export type StreamInput = {
21
+ user: MessageV2.User
22
+ sessionID: string
23
+ model: Provider.Model
24
+ agent: Agent.Info
25
+ system: string[]
26
+ abort: AbortSignal
27
+ messages: ModelMessage[]
28
+ small?: boolean
29
+ tools: Record<string, Tool>
30
+ retries?: number
31
+ }
32
+
33
+ export type StreamOutput = StreamTextResult<ToolSet, unknown>
34
+
35
+ export async function stream(input: StreamInput) {
36
+ const l = log
37
+ .clone()
38
+ .tag("providerID", input.model.providerID)
39
+ .tag("modelID", input.model.id)
40
+ .tag("sessionID", input.sessionID)
41
+ .tag("small", (input.small ?? false).toString())
42
+ .tag("agent", input.agent.name)
43
+ l.info("stream", {
44
+ modelID: input.model.id,
45
+ providerID: input.model.providerID,
46
+ })
47
+ const [language, cfg] = await Promise.all([Provider.getLanguage(input.model), Config.get()])
48
+
49
+ const system = SystemPrompt.header(input.model.providerID)
50
+ system.push(
51
+ [
52
+ // use agent prompt otherwise provider prompt
53
+ ...(input.agent.prompt ? [input.agent.prompt] : SystemPrompt.provider(input.model)),
54
+ // any custom prompt passed into this call
55
+ ...input.system,
56
+ // any custom prompt from last user message
57
+ ...(input.user.system ? [input.user.system] : []),
58
+ ]
59
+ .filter((x) => x)
60
+ .join("\n"),
61
+ )
62
+
63
+ const header = system[0]
64
+ const original = clone(system)
65
+ await Plugin.trigger("experimental.chat.system.transform", {}, { system })
66
+ if (system.length === 0) {
67
+ system.push(...original)
68
+ }
69
+ // rejoin to maintain 2-part structure for caching if header unchanged
70
+ if (system.length > 2 && system[0] === header) {
71
+ const rest = system.slice(1)
72
+ system.length = 0
73
+ system.push(header, rest.join("\n"))
74
+ }
75
+
76
+ const provider = await Provider.getProvider(input.model.providerID)
77
+
78
+ const params = await Plugin.trigger(
79
+ "chat.params",
80
+ {
81
+ sessionID: input.sessionID,
82
+ agent: input.agent,
83
+ model: input.model,
84
+ provider: Provider.getProvider(input.model.providerID),
85
+ message: input.user,
86
+ },
87
+ {
88
+ temperature: input.model.capabilities.temperature
89
+ ? (input.agent.temperature ?? ProviderTransform.temperature(input.model))
90
+ : undefined,
91
+ topP: input.agent.topP ?? ProviderTransform.topP(input.model),
92
+ topK: ProviderTransform.topK(input.model),
93
+ options: pipe(
94
+ {},
95
+ mergeDeep(ProviderTransform.options(input.model, input.sessionID, provider.options)),
96
+ input.small ? mergeDeep(ProviderTransform.smallOptions(input.model)) : mergeDeep({}),
97
+ mergeDeep(input.model.options),
98
+ mergeDeep(input.agent.options),
99
+ ),
100
+ },
101
+ )
102
+
103
+ l.info("params", {
104
+ params,
105
+ })
106
+
107
+ const maxOutputTokens = ProviderTransform.maxOutputTokens(
108
+ input.model.api.npm,
109
+ params.options,
110
+ input.model.limit.output,
111
+ OUTPUT_TOKEN_MAX,
112
+ )
113
+
114
+ const tools = await resolveTools(input)
115
+
116
+ return streamText({
117
+ onError(error) {
118
+ l.error("stream error", {
119
+ error,
120
+ })
121
+ },
122
+ async experimental_repairToolCall(failed) {
123
+ const lower = failed.toolCall.toolName.toLowerCase()
124
+ if (lower !== failed.toolCall.toolName && tools[lower]) {
125
+ l.info("repairing tool call", {
126
+ tool: failed.toolCall.toolName,
127
+ repaired: lower,
128
+ })
129
+ return {
130
+ ...failed.toolCall,
131
+ toolName: lower,
132
+ }
133
+ }
134
+ return {
135
+ ...failed.toolCall,
136
+ input: JSON.stringify({
137
+ tool: failed.toolCall.toolName,
138
+ error: failed.error.message,
139
+ }),
140
+ toolName: "invalid",
141
+ }
142
+ },
143
+ temperature: params.temperature,
144
+ topP: params.topP,
145
+ topK: params.topK,
146
+ providerOptions: ProviderTransform.providerOptions(input.model, params.options),
147
+ activeTools: Object.keys(tools).filter((x) => x !== "invalid"),
148
+ tools,
149
+ maxOutputTokens,
150
+ abortSignal: input.abort,
151
+ headers: {
152
+ ...(input.model.providerID.startsWith("bincode")
153
+ ? {
154
+ "x-bincode-project": Instance.project.id,
155
+ "x-bincode-session": input.sessionID,
156
+ "x-bincode-request": input.user.id,
157
+ "x-bincode-client": Flag.BINCODE_CLIENT,
158
+ }
159
+ : undefined),
160
+ ...input.model.headers,
161
+ },
162
+ maxRetries: input.retries ?? 0,
163
+ messages: [
164
+ ...system.map(
165
+ (x): ModelMessage => ({
166
+ role: "system",
167
+ content: x,
168
+ }),
169
+ ),
170
+ ...input.messages,
171
+ ],
172
+ model: wrapLanguageModel({
173
+ model: language,
174
+ middleware: [
175
+ {
176
+ async transformParams(args) {
177
+ if (args.type === "stream") {
178
+ // @ts-expect-error
179
+ args.params.prompt = ProviderTransform.message(args.params.prompt, input.model)
180
+ }
181
+ return args.params
182
+ },
183
+ },
184
+ ],
185
+ }),
186
+ experimental_telemetry: { isEnabled: cfg.experimental?.openTelemetry },
187
+ })
188
+ }
189
+
190
+ async function resolveTools(input: Pick<StreamInput, "tools" | "agent" | "user">) {
191
+ const enabled = pipe(
192
+ input.agent.tools,
193
+ mergeDeep(await ToolRegistry.enabled(input.agent)),
194
+ mergeDeep(input.user.tools ?? {}),
195
+ )
196
+ for (const [key, value] of Object.entries(enabled)) {
197
+ if (value === false) delete input.tools[key]
198
+ }
199
+ return input.tools
200
+ }
201
+ }