@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,150 @@
1
+ import { Config } from "../config/config"
2
+ import z from "zod"
3
+ import { Provider } from "../provider/provider"
4
+ import { generateObject, type ModelMessage } from "ai"
5
+ import PROMPT_GENERATE from "./generate.txt"
6
+ import { SystemPrompt } from "../session/system"
7
+ import { Instance } from "../project/instance"
8
+ import { mergeDeep } from "remeda"
9
+
10
+ export namespace Agent {
11
+ export const Info = z
12
+ .object({
13
+ name: z.string(),
14
+ description: z.string().optional(),
15
+ mode: z.enum(["subagent", "primary", "all"]),
16
+ builtIn: z.boolean(),
17
+ topP: z.number().optional(),
18
+ temperature: z.number().optional(),
19
+ color: z.string().optional(),
20
+ model: z
21
+ .object({
22
+ modelID: z.string(),
23
+ providerID: z.string(),
24
+ })
25
+ .optional(),
26
+ prompt: z.string().optional(),
27
+ tools: z.record(z.string(), z.boolean()),
28
+ options: z.record(z.string(), z.any()),
29
+ })
30
+ .meta({
31
+ ref: "Agent",
32
+ })
33
+ export type Info = z.infer<typeof Info>
34
+
35
+ const state = Instance.state(async () => {
36
+ const cfg = await Config.get()
37
+ const defaultTools = cfg.tools ?? {}
38
+
39
+ const result: Record<string, Info> = {
40
+ general: {
41
+ name: "general",
42
+ description:
43
+ "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
44
+ tools: {
45
+ todoread: false,
46
+ todowrite: false,
47
+ ...defaultTools,
48
+ },
49
+ options: {},
50
+ mode: "subagent",
51
+ builtIn: true,
52
+ },
53
+ build: {
54
+ name: "build",
55
+ tools: { ...defaultTools },
56
+ options: {},
57
+ mode: "primary",
58
+ builtIn: true,
59
+ },
60
+ plan: {
61
+ name: "plan",
62
+ options: {},
63
+ tools: {
64
+ ...defaultTools,
65
+ },
66
+ mode: "primary",
67
+ builtIn: true,
68
+ },
69
+ }
70
+ for (const [key, value] of Object.entries(cfg.agent ?? {})) {
71
+ if (value.disable) {
72
+ delete result[key]
73
+ continue
74
+ }
75
+ let item = result[key]
76
+ if (!item)
77
+ item = result[key] = {
78
+ name: key,
79
+ mode: "all",
80
+ options: {},
81
+ tools: {},
82
+ builtIn: false,
83
+ }
84
+ const { name, model, prompt, tools, description, temperature, top_p, mode, color, ...extra } = value
85
+ item.options = {
86
+ ...item.options,
87
+ ...extra,
88
+ }
89
+ if (model) item.model = Provider.parseModel(model)
90
+ if (prompt) item.prompt = prompt
91
+ if (tools)
92
+ item.tools = {
93
+ ...item.tools,
94
+ ...tools,
95
+ }
96
+ item.tools = {
97
+ ...defaultTools,
98
+ ...item.tools,
99
+ }
100
+ if (description) item.description = description
101
+ if (temperature != undefined) item.temperature = temperature
102
+ if (top_p != undefined) item.topP = top_p
103
+ if (mode) item.mode = mode
104
+ if (color) item.color = color
105
+ // just here for consistency & to prevent it from being added as an option
106
+ if (name) item.name = name
107
+ }
108
+ return result
109
+ })
110
+
111
+ export async function get(agent: string) {
112
+ return state().then((x) => x[agent])
113
+ }
114
+
115
+ export async function list() {
116
+ return state().then((x) => Object.values(x))
117
+ }
118
+
119
+ export async function generate(input: { description: string }) {
120
+ const defaultModel = await Provider.defaultModel()
121
+ const model = await Provider.getModel(defaultModel.providerID, defaultModel.modelID)
122
+ const system = SystemPrompt.header(defaultModel.providerID)
123
+ system.push(PROMPT_GENERATE)
124
+ const existing = await list()
125
+ const result = await generateObject({
126
+ temperature: 0.3,
127
+ prompt: [
128
+ ...system.map(
129
+ (item): ModelMessage => ({
130
+ role: "system",
131
+ content: item,
132
+ }),
133
+ ),
134
+ {
135
+ role: "user",
136
+ content: `Create an agent configuration based on this request: \"${input.description}\".\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existing.map((i) => i.name).join(", ")}\n Return ONLY the JSON object, no other text, do not wrap in backticks`,
137
+ },
138
+ ],
139
+ model: model.language,
140
+ schema: z.object({
141
+ identifier: z.string(),
142
+ whenToUse: z.string(),
143
+ systemPrompt: z.string(),
144
+ }),
145
+ })
146
+ return result.object
147
+ }
148
+ }
149
+
150
+ // Permission system removed - no longer needed
@@ -0,0 +1,75 @@
1
+ You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.
2
+
3
+ **Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.
4
+
5
+ When a user describes what they want an agent to do, you will:
6
+
7
+ 1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.
8
+
9
+ 2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.
10
+
11
+ 3. **Architect Comprehensive Instructions**: Develop a system prompt that:
12
+
13
+ - Establishes clear behavioral boundaries and operational parameters
14
+ - Provides specific methodologies and best practices for task execution
15
+ - Anticipates edge cases and provides guidance for handling them
16
+ - Incorporates any specific requirements or preferences mentioned by the user
17
+ - Defines output format expectations when relevant
18
+ - Aligns with project-specific coding standards and patterns from CLAUDE.md
19
+
20
+ 4. **Optimize for Performance**: Include:
21
+
22
+ - Decision-making frameworks appropriate to the domain
23
+ - Quality control mechanisms and self-verification steps
24
+ - Efficient workflow patterns
25
+ - Clear escalation or fallback strategies
26
+
27
+ 5. **Create Identifier**: Design a concise, descriptive identifier that:
28
+ - Uses lowercase letters, numbers, and hyphens only
29
+ - Is typically 2-4 words joined by hyphens
30
+ - Clearly indicates the agent's primary function
31
+ - Is memorable and easy to type
32
+ - Avoids generic terms like "helper" or "assistant"
33
+
34
+ 6 **Example agent descriptions**:
35
+
36
+ - in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
37
+ - examples should be of the form:
38
+ - <example>
39
+ Context: The user is creating a code-review agent that should be called after a logical chunk of code is written.
40
+ user: "Please write a function that checks if a number is prime"
41
+ assistant: "Here is the relevant function: "
42
+ <function call omitted for brevity only for this example>
43
+ <commentary>
44
+ Since the user is greeting, use the Task tool to launch the greeting-responder agent to respond with a friendly joke.
45
+ </commentary>
46
+ assistant: "Now let me use the code-reviewer agent to review the code"
47
+ </example>
48
+ - <example>
49
+ Context: User is creating an agent to respond to the word "hello" with a friendly jok.
50
+ user: "Hello"
51
+ assistant: "I'm going to use the Task tool to launch the greeting-responder agent to respond with a friendly joke"
52
+ <commentary>
53
+ Since the user is greeting, use the greeting-responder agent to respond with a friendly joke.
54
+ </commentary>
55
+ </example>
56
+ - If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
57
+ - NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.
58
+
59
+ Your output must be a valid JSON object with exactly these fields:
60
+ {
61
+ "identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'code-reviewer', 'api-docs-writer', 'test-generator')",
62
+ "whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.",
63
+ "systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
64
+ }
65
+
66
+ Key principles for your system prompts:
67
+
68
+ - Be specific rather than generic - avoid vague instructions
69
+ - Include concrete examples when they would clarify behavior
70
+ - Balance comprehensiveness with clarity - every instruction should add value
71
+ - Ensure the agent has enough context to handle variations of the core task
72
+ - Make the agent proactive in seeking clarification when needed
73
+ - Build in quality assurance and self-correction mechanisms
74
+
75
+ Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
@@ -0,0 +1,64 @@
1
+ import path from "path"
2
+ import { Global } from "../global"
3
+ import fs from "fs/promises"
4
+ import z from "zod"
5
+
6
+ export namespace Auth {
7
+ export const Oauth = z
8
+ .object({
9
+ type: z.literal("oauth"),
10
+ refresh: z.string(),
11
+ access: z.string(),
12
+ expires: z.number(),
13
+ enterpriseUrl: z.string().optional(),
14
+ })
15
+ .meta({ ref: "OAuth" })
16
+
17
+ export const Api = z
18
+ .object({
19
+ type: z.literal("api"),
20
+ key: z.string(),
21
+ })
22
+ .meta({ ref: "ApiAuth" })
23
+
24
+ export const WellKnown = z
25
+ .object({
26
+ type: z.literal("wellknown"),
27
+ key: z.string(),
28
+ token: z.string(),
29
+ })
30
+ .meta({ ref: "WellKnownAuth" })
31
+
32
+ export const Info = z.discriminatedUnion("type", [Oauth, Api, WellKnown]).meta({ ref: "Auth" })
33
+ export type Info = z.infer<typeof Info>
34
+
35
+ const filepath = path.join(Global.Path.data, "auth.json")
36
+
37
+ export async function get(providerID: string) {
38
+ const file = Bun.file(filepath)
39
+ return file
40
+ .json()
41
+ .catch(() => ({}))
42
+ .then((x) => x[providerID] as Info | undefined)
43
+ }
44
+
45
+ export async function all(): Promise<Record<string, Info>> {
46
+ const file = Bun.file(filepath)
47
+ return file.json().catch(() => ({}))
48
+ }
49
+
50
+ export async function set(key: string, info: Info) {
51
+ const file = Bun.file(filepath)
52
+ const data = await all()
53
+ await Bun.write(file, JSON.stringify({ ...data, [key]: info }, null, 2))
54
+ await fs.chmod(file.name!, 0o600)
55
+ }
56
+
57
+ export async function remove(key: string) {
58
+ const file = Bun.file(filepath)
59
+ const data = await all()
60
+ delete data[key]
61
+ await Bun.write(file, JSON.stringify(data, null, 2))
62
+ await fs.chmod(file.name!, 0o600)
63
+ }
64
+ }
@@ -0,0 +1,96 @@
1
+ import z from "zod"
2
+ import { Global } from "../global"
3
+ import { Log } from "../util/log"
4
+ import path from "path"
5
+ import { NamedError } from "../util/error"
6
+ import { readableStreamToText } from "bun"
7
+
8
+ export namespace BunProc {
9
+ const log = Log.create({ service: "bun" })
10
+
11
+ export async function run(cmd: string[], options?: Bun.SpawnOptions.OptionsObject<any, any, any>) {
12
+ log.info("running", {
13
+ cmd: [which(), ...cmd],
14
+ ...options,
15
+ })
16
+ const result = Bun.spawn([which(), ...cmd], {
17
+ ...options,
18
+ stdout: "pipe",
19
+ stderr: "pipe",
20
+ env: {
21
+ ...process.env,
22
+ ...options?.env,
23
+ BUN_BE_BUN: "1",
24
+ },
25
+ })
26
+ const code = await result.exited
27
+ const stdout = result.stdout
28
+ ? typeof result.stdout === "number"
29
+ ? result.stdout
30
+ : await readableStreamToText(result.stdout)
31
+ : undefined
32
+ const stderr = result.stderr
33
+ ? typeof result.stderr === "number"
34
+ ? result.stderr
35
+ : await readableStreamToText(result.stderr)
36
+ : undefined
37
+ log.info("done", {
38
+ code,
39
+ stdout,
40
+ stderr,
41
+ })
42
+ if (code !== 0) {
43
+ throw new Error(`Command failed with exit code ${result.exitCode}`)
44
+ }
45
+ return result
46
+ }
47
+
48
+ export function which() {
49
+ return process.execPath
50
+ }
51
+
52
+ export const InstallFailedError = NamedError.create(
53
+ "BunInstallFailedError",
54
+ z.object({
55
+ pkg: z.string(),
56
+ version: z.string(),
57
+ }),
58
+ )
59
+
60
+ export async function install(pkg: string, version = "latest") {
61
+ const mod = path.join(Global.Path.cache, "node_modules", pkg)
62
+ const pkgjson = Bun.file(path.join(Global.Path.cache, "package.json"))
63
+ const parsed = await pkgjson.json().catch(async () => {
64
+ const result = { dependencies: {} }
65
+ await Bun.write(pkgjson.name!, JSON.stringify(result, null, 2))
66
+ return result
67
+ })
68
+ if (parsed.dependencies[pkg] === version) return mod
69
+
70
+ // Build command arguments
71
+ const args = ["add", "--force", "--exact", "--cwd", Global.Path.cache, pkg + "@" + version]
72
+
73
+ // Let Bun handle registry resolution:
74
+ // - If .npmrc files exist, Bun will use them automatically
75
+ // - If no .npmrc files exist, Bun will default to https://registry.npmjs.org
76
+ // - No need to pass --registry flag
77
+ log.info("installing package using Bun's default registry resolution", {
78
+ pkg,
79
+ version,
80
+ })
81
+
82
+ await BunProc.run(args, {
83
+ cwd: Global.Path.cache,
84
+ }).catch((e) => {
85
+ throw new InstallFailedError(
86
+ { pkg, version },
87
+ {
88
+ cause: e,
89
+ },
90
+ )
91
+ })
92
+ parsed.dependencies[pkg] = version
93
+ await Bun.write(pkgjson.name!, JSON.stringify(parsed, null, 2))
94
+ return mod
95
+ }
96
+ }
@@ -0,0 +1,10 @@
1
+ import { EventEmitter } from "events"
2
+
3
+ export const GlobalBus = new EventEmitter<{
4
+ event: [
5
+ {
6
+ directory: string
7
+ payload: any
8
+ },
9
+ ]
10
+ }>()
@@ -0,0 +1,119 @@
1
+ import z from "zod"
2
+ import type { ZodType } from "zod"
3
+ import { Log } from "../util/log"
4
+ import { Instance } from "../project/instance"
5
+ import { GlobalBus } from "./global"
6
+
7
+ export namespace Bus {
8
+ const log = Log.create({ service: "bus" })
9
+ type Subscription = (event: any) => void
10
+
11
+ const state = Instance.state(() => {
12
+ const subscriptions = new Map<any, Subscription[]>()
13
+
14
+ return {
15
+ subscriptions,
16
+ }
17
+ })
18
+
19
+ export type EventDefinition = ReturnType<typeof event>
20
+
21
+ const registry = new Map<string, EventDefinition>()
22
+
23
+ export function event<Type extends string, Properties extends ZodType>(type: Type, properties: Properties) {
24
+ const result = {
25
+ type,
26
+ properties,
27
+ }
28
+ registry.set(type, result)
29
+ return result
30
+ }
31
+
32
+ export function payloads() {
33
+ return z
34
+ .discriminatedUnion(
35
+ "type",
36
+ registry
37
+ .entries()
38
+ .map(([type, def]) => {
39
+ return z
40
+ .object({
41
+ type: z.literal(type),
42
+ properties: def.properties,
43
+ })
44
+ .meta({
45
+ ref: "Event" + "." + def.type,
46
+ })
47
+ })
48
+ .toArray() as any,
49
+ )
50
+ .meta({
51
+ ref: "Event",
52
+ })
53
+ }
54
+
55
+ export async function publish<Definition extends EventDefinition>(
56
+ def: Definition,
57
+ properties: z.output<Definition["properties"]>,
58
+ ) {
59
+ const payload = {
60
+ type: def.type,
61
+ properties,
62
+ }
63
+ log.info("publishing", {
64
+ type: def.type,
65
+ })
66
+ const pending = []
67
+ for (const key of [def.type, "*"]) {
68
+ const match = state().subscriptions.get(key)
69
+ for (const sub of match ?? []) {
70
+ pending.push(sub(payload))
71
+ }
72
+ }
73
+ GlobalBus.emit("event", {
74
+ directory: Instance.directory,
75
+ payload,
76
+ })
77
+ return Promise.all(pending)
78
+ }
79
+
80
+ export function subscribe<Definition extends EventDefinition>(
81
+ def: Definition,
82
+ callback: (event: { type: Definition["type"]; properties: z.infer<Definition["properties"]> }) => void,
83
+ ) {
84
+ return raw(def.type, callback)
85
+ }
86
+
87
+ export function once<Definition extends EventDefinition>(
88
+ def: Definition,
89
+ callback: (event: {
90
+ type: Definition["type"]
91
+ properties: z.infer<Definition["properties"]>
92
+ }) => "done" | undefined,
93
+ ) {
94
+ const unsub = subscribe(def, (event) => {
95
+ if (callback(event)) unsub()
96
+ })
97
+ }
98
+
99
+ export function subscribeAll(callback: (event: any) => void) {
100
+ return raw("*", callback)
101
+ }
102
+
103
+ function raw(type: string, callback: (event: any) => void) {
104
+ log.info("subscribing", { type })
105
+ const subscriptions = state().subscriptions
106
+ let match = subscriptions.get(type) ?? []
107
+ match.push(callback)
108
+ subscriptions.set(type, match)
109
+
110
+ return () => {
111
+ log.info("unsubscribing", { type })
112
+ const match = subscriptions.get(type)
113
+ if (!match) return
114
+ const index = match.indexOf(callback)
115
+ if (index === -1) return
116
+ match.splice(index, 1)
117
+ }
118
+ }
119
+ }
@@ -0,0 +1,41 @@
1
+ // Permalink: https://github.com/sst/opencode/blob/main/packages/opencode/src/cli/bootstrap.ts
2
+ // Permalink: https://github.com/sst/opencode/blob/main/packages/opencode/src/project/instance.ts
3
+ // Permalink: https://github.com/sst/opencode/blob/main/packages/opencode/src/project/bootstrap.ts
4
+
5
+ import { createOpencode } from '@opencode-ai/sdk'
6
+
7
+ class Instance {
8
+ static directory = process.cwd()
9
+ static worktree = process.cwd()
10
+
11
+ static provide(options) {
12
+ this.directory = options.directory
13
+ this.worktree = options.directory
14
+ return options.fn()
15
+ }
16
+
17
+ static dispose() {
18
+ // Cleanup
19
+ }
20
+ }
21
+
22
+ class InstanceBootstrap {
23
+ static async init() {
24
+ // Minimal bootstrap
25
+ }
26
+ }
27
+
28
+ export async function bootstrap(directory, cb) {
29
+ return Instance.provide({
30
+ directory,
31
+ init: InstanceBootstrap,
32
+ fn: async () => {
33
+ try {
34
+ const result = await cb()
35
+ return result
36
+ } finally {
37
+ await Instance.dispose()
38
+ }
39
+ },
40
+ })
41
+ }
@@ -0,0 +1,17 @@
1
+ import { InstanceBootstrap } from "../project/bootstrap"
2
+ import { Instance } from "../project/instance"
3
+
4
+ export async function bootstrap<T>(directory: string, cb: () => Promise<T>) {
5
+ return Instance.provide({
6
+ directory,
7
+ init: InstanceBootstrap,
8
+ fn: async () => {
9
+ try {
10
+ const result = await cb()
11
+ return result
12
+ } finally {
13
+ await Instance.dispose()
14
+ }
15
+ },
16
+ })
17
+ }