@link-assistant/agent 0.0.8

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 (133) hide show
  1. package/EXAMPLES.md +383 -0
  2. package/LICENSE +24 -0
  3. package/MODELS.md +95 -0
  4. package/README.md +388 -0
  5. package/TOOLS.md +134 -0
  6. package/package.json +89 -0
  7. package/src/agent/agent.ts +150 -0
  8. package/src/agent/generate.txt +75 -0
  9. package/src/auth/index.ts +64 -0
  10. package/src/bun/index.ts +96 -0
  11. package/src/bus/global.ts +10 -0
  12. package/src/bus/index.ts +119 -0
  13. package/src/cli/bootstrap.js +41 -0
  14. package/src/cli/bootstrap.ts +17 -0
  15. package/src/cli/cmd/agent.ts +165 -0
  16. package/src/cli/cmd/cmd.ts +5 -0
  17. package/src/cli/cmd/export.ts +88 -0
  18. package/src/cli/cmd/mcp.ts +80 -0
  19. package/src/cli/cmd/models.ts +58 -0
  20. package/src/cli/cmd/run.ts +359 -0
  21. package/src/cli/cmd/stats.ts +276 -0
  22. package/src/cli/error.ts +27 -0
  23. package/src/command/index.ts +73 -0
  24. package/src/command/template/initialize.txt +10 -0
  25. package/src/config/config.ts +705 -0
  26. package/src/config/markdown.ts +41 -0
  27. package/src/file/ripgrep.ts +391 -0
  28. package/src/file/time.ts +38 -0
  29. package/src/file/watcher.ts +75 -0
  30. package/src/file.ts +6 -0
  31. package/src/flag/flag.ts +19 -0
  32. package/src/format/formatter.ts +248 -0
  33. package/src/format/index.ts +137 -0
  34. package/src/global/index.ts +52 -0
  35. package/src/id/id.ts +72 -0
  36. package/src/index.js +371 -0
  37. package/src/mcp/index.ts +289 -0
  38. package/src/patch/index.ts +622 -0
  39. package/src/project/bootstrap.ts +22 -0
  40. package/src/project/instance.ts +67 -0
  41. package/src/project/project.ts +105 -0
  42. package/src/project/state.ts +65 -0
  43. package/src/provider/models-macro.ts +11 -0
  44. package/src/provider/models.ts +98 -0
  45. package/src/provider/opencode.js +47 -0
  46. package/src/provider/provider.ts +636 -0
  47. package/src/provider/transform.ts +241 -0
  48. package/src/server/project.ts +48 -0
  49. package/src/server/server.ts +249 -0
  50. package/src/session/agent.js +204 -0
  51. package/src/session/compaction.ts +249 -0
  52. package/src/session/index.ts +380 -0
  53. package/src/session/message-v2.ts +758 -0
  54. package/src/session/message.ts +189 -0
  55. package/src/session/processor.ts +356 -0
  56. package/src/session/prompt/anthropic-20250930.txt +166 -0
  57. package/src/session/prompt/anthropic.txt +105 -0
  58. package/src/session/prompt/anthropic_spoof.txt +1 -0
  59. package/src/session/prompt/beast.txt +147 -0
  60. package/src/session/prompt/build-switch.txt +5 -0
  61. package/src/session/prompt/codex.txt +318 -0
  62. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  63. package/src/session/prompt/gemini.txt +155 -0
  64. package/src/session/prompt/grok-code.txt +1 -0
  65. package/src/session/prompt/plan.txt +8 -0
  66. package/src/session/prompt/polaris.txt +107 -0
  67. package/src/session/prompt/qwen.txt +109 -0
  68. package/src/session/prompt/summarize-turn.txt +5 -0
  69. package/src/session/prompt/summarize.txt +10 -0
  70. package/src/session/prompt/title.txt +25 -0
  71. package/src/session/prompt.ts +1390 -0
  72. package/src/session/retry.ts +53 -0
  73. package/src/session/revert.ts +108 -0
  74. package/src/session/status.ts +75 -0
  75. package/src/session/summary.ts +179 -0
  76. package/src/session/system.ts +138 -0
  77. package/src/session/todo.ts +36 -0
  78. package/src/snapshot/index.ts +197 -0
  79. package/src/storage/storage.ts +226 -0
  80. package/src/tool/bash.ts +193 -0
  81. package/src/tool/bash.txt +121 -0
  82. package/src/tool/batch.ts +173 -0
  83. package/src/tool/batch.txt +28 -0
  84. package/src/tool/codesearch.ts +123 -0
  85. package/src/tool/codesearch.txt +12 -0
  86. package/src/tool/edit.ts +604 -0
  87. package/src/tool/edit.txt +10 -0
  88. package/src/tool/glob.ts +65 -0
  89. package/src/tool/glob.txt +6 -0
  90. package/src/tool/grep.ts +116 -0
  91. package/src/tool/grep.txt +8 -0
  92. package/src/tool/invalid.ts +17 -0
  93. package/src/tool/ls.ts +110 -0
  94. package/src/tool/ls.txt +1 -0
  95. package/src/tool/multiedit.ts +46 -0
  96. package/src/tool/multiedit.txt +41 -0
  97. package/src/tool/patch.ts +188 -0
  98. package/src/tool/patch.txt +1 -0
  99. package/src/tool/read.ts +201 -0
  100. package/src/tool/read.txt +12 -0
  101. package/src/tool/registry.ts +87 -0
  102. package/src/tool/task.ts +126 -0
  103. package/src/tool/task.txt +60 -0
  104. package/src/tool/todo.ts +39 -0
  105. package/src/tool/todoread.txt +14 -0
  106. package/src/tool/todowrite.txt +167 -0
  107. package/src/tool/tool.ts +66 -0
  108. package/src/tool/webfetch.ts +171 -0
  109. package/src/tool/webfetch.txt +14 -0
  110. package/src/tool/websearch.ts +133 -0
  111. package/src/tool/websearch.txt +11 -0
  112. package/src/tool/write.ts +33 -0
  113. package/src/tool/write.txt +8 -0
  114. package/src/util/binary.ts +41 -0
  115. package/src/util/context.ts +25 -0
  116. package/src/util/defer.ts +12 -0
  117. package/src/util/error.ts +54 -0
  118. package/src/util/eventloop.ts +20 -0
  119. package/src/util/filesystem.ts +69 -0
  120. package/src/util/fn.ts +11 -0
  121. package/src/util/iife.ts +3 -0
  122. package/src/util/keybind.ts +79 -0
  123. package/src/util/lazy.ts +11 -0
  124. package/src/util/locale.ts +39 -0
  125. package/src/util/lock.ts +98 -0
  126. package/src/util/log.ts +177 -0
  127. package/src/util/queue.ts +19 -0
  128. package/src/util/rpc.ts +42 -0
  129. package/src/util/scrap.ts +10 -0
  130. package/src/util/signal.ts +12 -0
  131. package/src/util/timeout.ts +14 -0
  132. package/src/util/token.ts +7 -0
  133. package/src/util/wildcard.ts +54 -0
@@ -0,0 +1,53 @@
1
+ import { iife } from "../util/iife"
2
+ import { MessageV2 } from "./message-v2"
3
+
4
+ export namespace SessionRetry {
5
+ export const RETRY_INITIAL_DELAY = 2000
6
+ export const RETRY_BACKOFF_FACTOR = 2
7
+ export const RETRY_MAX_DELAY_NO_HEADERS = 30_000 // 30 seconds
8
+
9
+ export async function sleep(ms: number, signal: AbortSignal): Promise<void> {
10
+ return new Promise((resolve, reject) => {
11
+ const timeout = setTimeout(resolve, ms)
12
+ signal.addEventListener(
13
+ "abort",
14
+ () => {
15
+ clearTimeout(timeout)
16
+ reject(new DOMException("Aborted", "AbortError"))
17
+ },
18
+ { once: true },
19
+ )
20
+ })
21
+ }
22
+
23
+ export function delay(error: MessageV2.APIError, attempt: number) {
24
+ const headers = error.data.responseHeaders
25
+ if (headers) {
26
+ const retryAfterMs = headers["retry-after-ms"]
27
+ if (retryAfterMs) {
28
+ const parsedMs = Number.parseFloat(retryAfterMs)
29
+ if (!Number.isNaN(parsedMs)) {
30
+ return parsedMs
31
+ }
32
+ }
33
+
34
+ const retryAfter = headers["retry-after"]
35
+ if (retryAfter) {
36
+ const parsedSeconds = Number.parseFloat(retryAfter)
37
+ if (!Number.isNaN(parsedSeconds)) {
38
+ // convert seconds to milliseconds
39
+ return Math.ceil(parsedSeconds * 1000)
40
+ }
41
+ // Try parsing as HTTP date format
42
+ const parsed = Date.parse(retryAfter) - Date.now()
43
+ if (!Number.isNaN(parsed) && parsed > 0) {
44
+ return Math.ceil(parsed)
45
+ }
46
+ }
47
+
48
+ return RETRY_INITIAL_DELAY * Math.pow(RETRY_BACKOFF_FACTOR, attempt - 1)
49
+ }
50
+
51
+ return Math.min(RETRY_INITIAL_DELAY * Math.pow(RETRY_BACKOFF_FACTOR, attempt - 1), RETRY_MAX_DELAY_NO_HEADERS)
52
+ }
53
+ }
@@ -0,0 +1,108 @@
1
+ import z from "zod"
2
+ import { Identifier } from "../id/id"
3
+ import { Snapshot } from "../snapshot"
4
+ import { MessageV2 } from "./message-v2"
5
+ import { Session } from "."
6
+ import { Log } from "../util/log"
7
+ import { splitWhen } from "remeda"
8
+ import { Storage } from "../storage/storage"
9
+ import { Bus } from "../bus"
10
+ import { SessionPrompt } from "./prompt"
11
+
12
+ export namespace SessionRevert {
13
+ const log = Log.create({ service: "session.revert" })
14
+
15
+ export const RevertInput = z.object({
16
+ sessionID: Identifier.schema("session"),
17
+ messageID: Identifier.schema("message"),
18
+ partID: Identifier.schema("part").optional(),
19
+ })
20
+ export type RevertInput = z.infer<typeof RevertInput>
21
+
22
+ export async function revert(input: RevertInput) {
23
+ SessionPrompt.assertNotBusy(input.sessionID)
24
+ const all = await Session.messages({ sessionID: input.sessionID })
25
+ let lastUser: MessageV2.User | undefined
26
+ const session = await Session.get(input.sessionID)
27
+
28
+ let revert: Session.Info["revert"]
29
+ const patches: Snapshot.Patch[] = []
30
+ for (const msg of all) {
31
+ if (msg.info.role === "user") lastUser = msg.info
32
+ const remaining = []
33
+ for (const part of msg.parts) {
34
+ if (revert) {
35
+ if (part.type === "patch") {
36
+ patches.push(part)
37
+ }
38
+ continue
39
+ }
40
+
41
+ if (!revert) {
42
+ if ((msg.info.id === input.messageID && !input.partID) || part.id === input.partID) {
43
+ // if no useful parts left in message, same as reverting whole message
44
+ const partID = remaining.some((item) => ["text", "tool"].includes(item.type)) ? input.partID : undefined
45
+ revert = {
46
+ messageID: !partID && lastUser ? lastUser.id : msg.info.id,
47
+ partID,
48
+ }
49
+ }
50
+ remaining.push(part)
51
+ }
52
+ }
53
+ }
54
+
55
+ if (revert) {
56
+ const session = await Session.get(input.sessionID)
57
+ revert.snapshot = session.revert?.snapshot ?? (await Snapshot.track())
58
+ await Snapshot.revert(patches)
59
+ if (revert.snapshot) revert.diff = await Snapshot.diff(revert.snapshot)
60
+ return Session.update(input.sessionID, (draft) => {
61
+ draft.revert = revert
62
+ })
63
+ }
64
+ return session
65
+ }
66
+
67
+ export async function unrevert(input: { sessionID: string }) {
68
+ log.info("unreverting", input)
69
+ SessionPrompt.assertNotBusy(input.sessionID)
70
+ const session = await Session.get(input.sessionID)
71
+ if (!session.revert) return session
72
+ if (session.revert.snapshot) await Snapshot.restore(session.revert.snapshot)
73
+ const next = await Session.update(input.sessionID, (draft) => {
74
+ draft.revert = undefined
75
+ })
76
+ return next
77
+ }
78
+
79
+ export async function cleanup(session: Session.Info) {
80
+ if (!session.revert) return
81
+ const sessionID = session.id
82
+ let msgs = await Session.messages({ sessionID })
83
+ const messageID = session.revert.messageID
84
+ const [preserve, remove] = splitWhen(msgs, (x) => x.info.id === messageID)
85
+ msgs = preserve
86
+ for (const msg of remove) {
87
+ await Storage.remove(["message", sessionID, msg.info.id])
88
+ await Bus.publish(MessageV2.Event.Removed, { sessionID: sessionID, messageID: msg.info.id })
89
+ }
90
+ const last = preserve.at(-1)
91
+ if (session.revert.partID && last) {
92
+ const partID = session.revert.partID
93
+ const [preserveParts, removeParts] = splitWhen(last.parts, (x) => x.id === partID)
94
+ last.parts = preserveParts
95
+ for (const part of removeParts) {
96
+ await Storage.remove(["part", last.info.id, part.id])
97
+ await Bus.publish(MessageV2.Event.PartRemoved, {
98
+ sessionID: sessionID,
99
+ messageID: last.info.id,
100
+ partID: part.id,
101
+ })
102
+ }
103
+ }
104
+ await Session.update(sessionID, (draft) => {
105
+ draft.revert = undefined
106
+ })
107
+ }
108
+ }
@@ -0,0 +1,75 @@
1
+ import { Bus } from "../bus"
2
+ import { Instance } from "../project/instance"
3
+ import z from "zod"
4
+
5
+ export namespace SessionStatus {
6
+ export const Info = z
7
+ .union([
8
+ z.object({
9
+ type: z.literal("idle"),
10
+ }),
11
+ z.object({
12
+ type: z.literal("retry"),
13
+ attempt: z.number(),
14
+ message: z.string(),
15
+ next: z.number(),
16
+ }),
17
+ z.object({
18
+ type: z.literal("busy"),
19
+ }),
20
+ ])
21
+ .meta({
22
+ ref: "SessionStatus",
23
+ })
24
+ export type Info = z.infer<typeof Info>
25
+
26
+ export const Event = {
27
+ Status: Bus.event(
28
+ "session.status",
29
+ z.object({
30
+ sessionID: z.string(),
31
+ status: Info,
32
+ }),
33
+ ),
34
+ // deprecated
35
+ Idle: Bus.event(
36
+ "session.idle",
37
+ z.object({
38
+ sessionID: z.string(),
39
+ }),
40
+ ),
41
+ }
42
+
43
+ const state = Instance.state(() => {
44
+ const data: Record<string, Info> = {}
45
+ return data
46
+ })
47
+
48
+ export function get(sessionID: string) {
49
+ return (
50
+ state()[sessionID] ?? {
51
+ type: "idle",
52
+ }
53
+ )
54
+ }
55
+
56
+ export function list() {
57
+ return Object.values(state())
58
+ }
59
+
60
+ export function set(sessionID: string, status: Info) {
61
+ Bus.publish(Event.Status, {
62
+ sessionID,
63
+ status,
64
+ })
65
+ if (status.type === "idle") {
66
+ // deprecated
67
+ Bus.publish(Event.Idle, {
68
+ sessionID,
69
+ })
70
+ delete state()[sessionID]
71
+ return
72
+ }
73
+ state()[sessionID] = status
74
+ }
75
+ }
@@ -0,0 +1,179 @@
1
+ import { Provider } from "../provider/provider"
2
+ import { fn } from "../util/fn"
3
+ import z from "zod"
4
+ import { Session } from "."
5
+ import { generateText, type ModelMessage } from "ai"
6
+ import { MessageV2 } from "./message-v2"
7
+ import { Identifier } from "../id/id"
8
+ import { Snapshot } from "../snapshot"
9
+ import { ProviderTransform } from "../provider/transform"
10
+ import { SystemPrompt } from "./system"
11
+ import { Log } from "../util/log"
12
+ import path from "path"
13
+ import { Instance } from "../project/instance"
14
+ import { Storage } from "../storage/storage"
15
+ import { Bus } from "../bus"
16
+
17
+ export namespace SessionSummary {
18
+ const log = Log.create({ service: "session.summary" })
19
+
20
+ export const summarize = fn(
21
+ z.object({
22
+ sessionID: z.string(),
23
+ messageID: z.string(),
24
+ }),
25
+ async (input) => {
26
+ const all = await Session.messages({ sessionID: input.sessionID })
27
+ await Promise.all([
28
+ summarizeSession({ sessionID: input.sessionID, messages: all }),
29
+ summarizeMessage({ messageID: input.messageID, messages: all }),
30
+ ])
31
+ },
32
+ )
33
+
34
+ async function summarizeSession(input: { sessionID: string; messages: MessageV2.WithParts[] }) {
35
+ const files = new Set(
36
+ input.messages
37
+ .flatMap((x) => x.parts)
38
+ .filter((x) => x.type === "patch")
39
+ .flatMap((x) => x.files)
40
+ .map((x) => path.relative(Instance.worktree, x)),
41
+ )
42
+ const diffs = await computeDiff({ messages: input.messages }).then((x) =>
43
+ x.filter((x) => {
44
+ return files.has(x.file)
45
+ }),
46
+ )
47
+ await Session.update(input.sessionID, (draft) => {
48
+ draft.summary = {
49
+ additions: diffs.reduce((sum, x) => sum + x.additions, 0),
50
+ deletions: diffs.reduce((sum, x) => sum + x.deletions, 0),
51
+ files: diffs.length,
52
+ }
53
+ })
54
+ await Storage.write(["session_diff", input.sessionID], diffs)
55
+ Bus.publish(Session.Event.Diff, {
56
+ sessionID: input.sessionID,
57
+ diff: diffs,
58
+ })
59
+ }
60
+
61
+ async function summarizeMessage(input: { messageID: string; messages: MessageV2.WithParts[] }) {
62
+ const messages = input.messages.filter(
63
+ (m) => m.info.id === input.messageID || (m.info.role === "assistant" && m.info.parentID === input.messageID),
64
+ )
65
+ const msgWithParts = messages.find((m) => m.info.id === input.messageID)!
66
+ const userMsg = msgWithParts.info as MessageV2.User
67
+ const diffs = await computeDiff({ messages })
68
+ userMsg.summary = {
69
+ ...userMsg.summary,
70
+ diffs,
71
+ }
72
+ await Session.updateMessage(userMsg)
73
+
74
+ const assistantMsg = messages.find((m) => m.info.role === "assistant")!.info as MessageV2.Assistant
75
+ const small = await Provider.getSmallModel(assistantMsg.providerID)
76
+ if (!small) return
77
+
78
+ const textPart = msgWithParts.parts.find((p) => p.type === "text" && !p.synthetic) as MessageV2.TextPart
79
+ if (textPart && !userMsg.summary?.title) {
80
+ const result = await generateText({
81
+ maxOutputTokens: small.info.reasoning ? 1500 : 20,
82
+ providerOptions: ProviderTransform.providerOptions(small.npm, small.providerID, {}),
83
+ messages: [
84
+ ...SystemPrompt.title(small.providerID).map(
85
+ (x): ModelMessage => ({
86
+ role: "system",
87
+ content: x,
88
+ }),
89
+ ),
90
+ {
91
+ role: "user" as const,
92
+ content: `
93
+ The following is the text to summarize:
94
+ <text>
95
+ ${textPart?.text ?? ""}
96
+ </text>
97
+ `,
98
+ },
99
+ ],
100
+ headers: small.info.headers,
101
+ model: small.language,
102
+ })
103
+ log.info("title", { title: result.text })
104
+ userMsg.summary.title = result.text
105
+ await Session.updateMessage(userMsg)
106
+ }
107
+
108
+ if (
109
+ messages.some(
110
+ (m) =>
111
+ m.info.role === "assistant" && m.parts.some((p) => p.type === "step-finish" && p.reason !== "tool-calls"),
112
+ )
113
+ ) {
114
+ let summary = messages
115
+ .findLast((m) => m.info.role === "assistant")
116
+ ?.parts.findLast((p) => p.type === "text")?.text
117
+ if (!summary || diffs.length > 0) {
118
+ const result = await generateText({
119
+ model: small.language,
120
+ maxOutputTokens: 100,
121
+ messages: [
122
+ {
123
+ role: "user",
124
+ content: `
125
+ Summarize the following conversation into 2 sentences MAX explaining what the assistant did and why. Do not explain the user's input. Do not speak in the third person about the assistant.
126
+ <conversation>
127
+ ${JSON.stringify(MessageV2.toModelMessage(messages))}
128
+ </conversation>
129
+ `,
130
+ },
131
+ ],
132
+ headers: small.info.headers,
133
+ }).catch(() => {})
134
+ if (result) summary = result.text
135
+ }
136
+ userMsg.summary.body = summary
137
+ log.info("body", { body: summary })
138
+ await Session.updateMessage(userMsg)
139
+ }
140
+ }
141
+
142
+ export const diff = fn(
143
+ z.object({
144
+ sessionID: Identifier.schema("session"),
145
+ messageID: Identifier.schema("message").optional(),
146
+ }),
147
+ async (input) => {
148
+ return Storage.read<Snapshot.FileDiff[]>(["session_diff", input.sessionID]).catch(() => [])
149
+ },
150
+ )
151
+
152
+ async function computeDiff(input: { messages: MessageV2.WithParts[] }) {
153
+ let from: string | undefined
154
+ let to: string | undefined
155
+
156
+ // scan assistant messages to find earliest from and latest to
157
+ // snapshot
158
+ for (const item of input.messages) {
159
+ if (!from) {
160
+ for (const part of item.parts) {
161
+ if (part.type === "step-start" && part.snapshot) {
162
+ from = part.snapshot
163
+ break
164
+ }
165
+ }
166
+ }
167
+
168
+ for (const part of item.parts) {
169
+ if (part.type === "step-finish" && part.snapshot) {
170
+ to = part.snapshot
171
+ break
172
+ }
173
+ }
174
+ }
175
+
176
+ if (from && to) return Snapshot.diffFull(from, to)
177
+ return []
178
+ }
179
+ }
@@ -0,0 +1,138 @@
1
+ import { Ripgrep } from "../file/ripgrep"
2
+ import { Global } from "../global"
3
+ import { Filesystem } from "../util/filesystem"
4
+ import { Config } from "../config/config"
5
+
6
+ import { Instance } from "../project/instance"
7
+ import path from "path"
8
+ import os from "os"
9
+
10
+ import PROMPT_ANTHROPIC from "./prompt/anthropic.txt"
11
+ import PROMPT_ANTHROPIC_WITHOUT_TODO from "./prompt/qwen.txt"
12
+ import PROMPT_POLARIS from "./prompt/polaris.txt"
13
+ import PROMPT_BEAST from "./prompt/beast.txt"
14
+ import PROMPT_GEMINI from "./prompt/gemini.txt"
15
+ import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
16
+ import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
17
+ import PROMPT_TITLE from "./prompt/title.txt"
18
+ import PROMPT_CODEX from "./prompt/codex.txt"
19
+ import PROMPT_GROK_CODE from "./prompt/grok-code.txt"
20
+
21
+ export namespace SystemPrompt {
22
+ export function header(providerID: string) {
23
+ if (providerID.includes("anthropic")) return [PROMPT_ANTHROPIC_SPOOF.trim()]
24
+ return []
25
+ }
26
+
27
+ export function provider(modelID: string) {
28
+ if (modelID.includes("gpt-5")) return [PROMPT_CODEX]
29
+ if (modelID.includes("gpt-") || modelID.includes("o1") || modelID.includes("o3")) return [PROMPT_BEAST]
30
+ if (modelID.includes("gemini-")) return [PROMPT_GEMINI]
31
+ if (modelID.includes("claude")) return [PROMPT_ANTHROPIC]
32
+ if (modelID.includes("polaris-alpha")) return [PROMPT_POLARIS]
33
+ if (modelID.includes("grok-code")) return [PROMPT_GROK_CODE]
34
+ return [PROMPT_ANTHROPIC_WITHOUT_TODO]
35
+ }
36
+
37
+ export async function environment() {
38
+ const project = Instance.project
39
+ return [
40
+ [
41
+ `Here is some useful information about the environment you are running in:`,
42
+ `<env>`,
43
+ ` Working directory: ${Instance.directory}`,
44
+ ` Is directory a git repo: ${project.vcs === "git" ? "yes" : "no"}`,
45
+ ` Platform: ${process.platform}`,
46
+ ` Today's date: ${new Date().toDateString()}`,
47
+ `</env>`,
48
+ `<files>`,
49
+ ` ${
50
+ project.vcs === "git"
51
+ ? await Ripgrep.tree({
52
+ cwd: Instance.directory,
53
+ limit: 200,
54
+ })
55
+ : ""
56
+ }`,
57
+ `</files>`,
58
+ ].join("\n"),
59
+ ]
60
+ }
61
+
62
+ const LOCAL_RULE_FILES = [
63
+ "AGENTS.md",
64
+ "CLAUDE.md",
65
+ "CONTEXT.md", // deprecated
66
+ ]
67
+ const GLOBAL_RULE_FILES = [
68
+ path.join(Global.Path.config, "AGENTS.md"),
69
+ path.join(os.homedir(), ".claude", "CLAUDE.md"),
70
+ ]
71
+
72
+ export async function custom() {
73
+ const config = await Config.get()
74
+ const paths = new Set<string>()
75
+
76
+ for (const localRuleFile of LOCAL_RULE_FILES) {
77
+ const matches = await Filesystem.findUp(localRuleFile, Instance.directory, Instance.worktree)
78
+ if (matches.length > 0) {
79
+ matches.forEach((path) => paths.add(path))
80
+ break
81
+ }
82
+ }
83
+
84
+ for (const globalRuleFile of GLOBAL_RULE_FILES) {
85
+ if (await Bun.file(globalRuleFile).exists()) {
86
+ paths.add(globalRuleFile)
87
+ break
88
+ }
89
+ }
90
+
91
+ if (config.instructions) {
92
+ for (let instruction of config.instructions) {
93
+ if (instruction.startsWith("~/")) {
94
+ instruction = path.join(os.homedir(), instruction.slice(2))
95
+ }
96
+ let matches: string[] = []
97
+ if (path.isAbsolute(instruction)) {
98
+ matches = await Array.fromAsync(
99
+ new Bun.Glob(path.basename(instruction)).scan({
100
+ cwd: path.dirname(instruction),
101
+ absolute: true,
102
+ onlyFiles: true,
103
+ }),
104
+ ).catch(() => [])
105
+ } else {
106
+ matches = await Filesystem.globUp(instruction, Instance.directory, Instance.worktree).catch(() => [])
107
+ }
108
+ matches.forEach((path) => paths.add(path))
109
+ }
110
+ }
111
+
112
+ const found = Array.from(paths).map((p) =>
113
+ Bun.file(p)
114
+ .text()
115
+ .catch(() => "")
116
+ .then((x) => "Instructions from: " + p + "\n" + x),
117
+ )
118
+ return Promise.all(found).then((result) => result.filter(Boolean))
119
+ }
120
+
121
+ export function summarize(providerID: string) {
122
+ switch (providerID) {
123
+ case "anthropic":
124
+ return [PROMPT_ANTHROPIC_SPOOF.trim(), PROMPT_SUMMARIZE]
125
+ default:
126
+ return [PROMPT_SUMMARIZE]
127
+ }
128
+ }
129
+
130
+ export function title(providerID: string) {
131
+ switch (providerID) {
132
+ case "anthropic":
133
+ return [PROMPT_ANTHROPIC_SPOOF.trim(), PROMPT_TITLE]
134
+ default:
135
+ return [PROMPT_TITLE]
136
+ }
137
+ }
138
+ }
@@ -0,0 +1,36 @@
1
+ import z from "zod"
2
+ import { Bus } from "../bus"
3
+ import { Storage } from "../storage/storage"
4
+
5
+ export namespace Todo {
6
+ export const Info = z
7
+ .object({
8
+ content: z.string().describe("Brief description of the task"),
9
+ status: z.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),
10
+ priority: z.string().describe("Priority level of the task: high, medium, low"),
11
+ id: z.string().describe("Unique identifier for the todo item"),
12
+ })
13
+ .meta({ ref: "Todo" })
14
+ export type Info = z.infer<typeof Info>
15
+
16
+ export const Event = {
17
+ Updated: Bus.event(
18
+ "todo.updated",
19
+ z.object({
20
+ sessionID: z.string(),
21
+ todos: z.array(Info),
22
+ }),
23
+ ),
24
+ }
25
+
26
+ export async function update(input: { sessionID: string; todos: Info[] }) {
27
+ await Storage.write(["todo", input.sessionID], input.todos)
28
+ Bus.publish(Event.Updated, input)
29
+ }
30
+
31
+ export async function get(sessionID: string) {
32
+ return Storage.read<Info[]>(["todo", sessionID])
33
+ .then((x) => x || [])
34
+ .catch(() => [])
35
+ }
36
+ }