@alvarolorentedev/opencode-taskfeed 0.0.0-stage → 0.1.0-alpha.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 (58) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +431 -2
  3. package/docs/architecture.md +123 -0
  4. package/docs/configuration.md +123 -0
  5. package/docs/development.md +312 -0
  6. package/docs/integrations.md +84 -0
  7. package/docs/operations.md +136 -0
  8. package/docs/releases/v0.1.0-alpha.1.md +164 -0
  9. package/docs/security.md +120 -0
  10. package/examples/README.md +7 -0
  11. package/examples/approvals/README.md +27 -0
  12. package/examples/flowgraph/config.yaml +28 -0
  13. package/examples/flowgraph/opencode.jsonc +14 -0
  14. package/examples/headless/README.md +25 -0
  15. package/examples/headless/config.yaml +21 -0
  16. package/examples/native-agent/config.yaml +31 -0
  17. package/examples/native-agent/opencode.jsonc +10 -0
  18. package/examples/playground/README.md +61 -0
  19. package/examples/playground/config.yaml +40 -0
  20. package/examples/playground/opencode.jsonc +5 -0
  21. package/package.json +89 -4
  22. package/src/config/load.ts +122 -0
  23. package/src/config/repository.ts +72 -0
  24. package/src/config/schema.ts +215 -0
  25. package/src/core/approval.ts +190 -0
  26. package/src/core/comments.ts +175 -0
  27. package/src/core/index.ts +5 -0
  28. package/src/core/ports.ts +185 -0
  29. package/src/core/state.ts +186 -0
  30. package/src/core/types.ts +430 -0
  31. package/src/executors/flowgraph/client.ts +27 -0
  32. package/src/executors/flowgraph/executor.ts +593 -0
  33. package/src/executors/flowgraph/lazy.ts +77 -0
  34. package/src/executors/flowgraph/rpc.ts +145 -0
  35. package/src/executors/flowgraph/worker.ts +538 -0
  36. package/src/executors/native/bridge.ts +421 -0
  37. package/src/executors/native/executor.ts +295 -0
  38. package/src/executors/native/prompt.ts +57 -0
  39. package/src/executors/native/trust.ts +105 -0
  40. package/src/index.ts +116 -0
  41. package/src/rpc.ts +75 -0
  42. package/src/runtime/backends.ts +27 -0
  43. package/src/runtime/engine.ts +2345 -0
  44. package/src/runtime/server-backends.ts +136 -0
  45. package/src/runtime/service.ts +276 -0
  46. package/src/sources/github/client.ts +98 -0
  47. package/src/sources/github/source.ts +490 -0
  48. package/src/storage/capacity.ts +223 -0
  49. package/src/storage/jobs.ts +249 -0
  50. package/src/storage/locks.ts +342 -0
  51. package/src/tui.tsx +399 -0
  52. package/src/util/ids.ts +18 -0
  53. package/src/util/logger.ts +52 -0
  54. package/src/util/process.ts +119 -0
  55. package/src/util/redact.ts +28 -0
  56. package/src/version.ts +2 -0
  57. package/src/workspaces/native.ts +162 -0
  58. package/src/workspaces/publication.ts +477 -0
@@ -0,0 +1,421 @@
1
+ import { lstat, readdir, readFile } from "node:fs/promises"
2
+ import path from "node:path"
3
+ import type { Plugin as PluginType } from "@opencode/plugin"
4
+ import type { Agent } from "@opencode/schema/agent"
5
+ import type { Session } from "@opencode/schema/session"
6
+ import type { Logger } from "../../util/logger.js"
7
+ import { stableHash } from "../../util/ids.js"
8
+ import { hashExecutionConfig } from "./trust.js"
9
+
10
+ function errorText(error: unknown): string {
11
+ if (error instanceof Error) return error.message
12
+ if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
13
+ return error.message
14
+ }
15
+ return String(error)
16
+ }
17
+
18
+ const localSourceHashCache = new Map<string, { signature: string; hash: string }>()
19
+
20
+ async function hashLocalSource(root: string): Promise<string> {
21
+ const info = await lstat(root)
22
+ if (info.isFile()) {
23
+ return stableHash(JSON.stringify({ mode: info.mode & 0o777, content: await readFile(root, "base64") }), 64)
24
+ }
25
+ const files: Array<{ relative: string; mode: number; size: number; mtimeMs: number }> = []
26
+ const visited = new Set<string>()
27
+ let bytes = 0
28
+ const add = async (full: string, relative: string): Promise<void> => {
29
+ if (visited.has(relative)) return
30
+ visited.add(relative)
31
+ const stat = await lstat(full)
32
+ if (stat.isSymbolicLink()) throw new Error(`Trusted plugin source symlinks are not supported: ${relative}`)
33
+ if (stat.isDirectory()) {
34
+ for (const entry of await readdir(full, { withFileTypes: true })) {
35
+ if (["node_modules", ".git", ".taskfeed", "dist", "test", "tests", "docs", "examples", "spikes", "coverage"].includes(entry.name)) continue
36
+ await add(path.join(full, entry.name), relative ? `${relative}/${entry.name}` : entry.name)
37
+ }
38
+ return
39
+ }
40
+ if (!stat.isFile()) return
41
+ if (files.length >= 2_000) throw new Error(`trusted plugin source ${root} contains too many files to verify`)
42
+ bytes += stat.size
43
+ if (bytes > 16 * 1024 * 1024) throw new Error(`trusted plugin source ${root} is too large to verify`)
44
+ files.push({ relative, mode: stat.mode & 0o777, size: stat.size, mtimeMs: stat.mtimeMs })
45
+ }
46
+ await add(path.join(root, "package.json"), "package.json").catch((error: NodeJS.ErrnoException) => {
47
+ if (error.code !== "ENOENT") throw error
48
+ })
49
+ for (const name of ["index.ts", "index.js", "index.mjs", "index.cjs", "server.ts", "server.js", "rpc.ts", "rpc.js"]) {
50
+ await add(path.join(root, name), name).catch((error: NodeJS.ErrnoException) => {
51
+ if (error.code !== "ENOENT") throw error
52
+ })
53
+ }
54
+ await add(root, "")
55
+ const manifest = await readFile(path.join(root, "package.json"), "utf8").catch(() => undefined)
56
+ if (manifest) {
57
+ const targets: string[] = []
58
+ const collect = (value: unknown): void => {
59
+ if (typeof value === "string" && value.startsWith("./")) targets.push(value.slice(2))
60
+ else if (Array.isArray(value)) for (const item of value) collect(item)
61
+ else if (value !== null && typeof value === "object") for (const item of Object.values(value)) collect(item)
62
+ }
63
+ const exportsValue = (JSON.parse(manifest) as { exports?: unknown }).exports
64
+ if (exportsValue !== null && typeof exportsValue === "object" && !Array.isArray(exportsValue)) {
65
+ const record = exportsValue as Record<string, unknown>
66
+ collect(record["."])
67
+ collect(record["./server"])
68
+ collect(record["./rpc"])
69
+ } else {
70
+ collect(exportsValue)
71
+ }
72
+ for (const target of targets) {
73
+ await add(path.resolve(root, target), target).catch((error: NodeJS.ErrnoException) => {
74
+ if (error.code !== "ENOENT") throw error
75
+ })
76
+ }
77
+ }
78
+ files.sort((left, right) => left.relative.localeCompare(right.relative))
79
+ const signature = stableHash(JSON.stringify(files), 64)
80
+ const cached = localSourceHashCache.get(root)
81
+ if (cached?.signature === signature) return cached.hash
82
+ const content = await Promise.all(
83
+ files.map(async (file) => ({ relative: file.relative, mode: file.mode, content: await readFile(path.join(root, file.relative), "base64") })),
84
+ )
85
+ const hash = stableHash(JSON.stringify(content), 64)
86
+ localSourceHashCache.set(root, { signature, hash })
87
+ return hash
88
+ }
89
+
90
+ function normalizeAgent(agent: unknown): Record<string, unknown> {
91
+ const value = agent as Record<string, unknown>
92
+ const permissions = Array.isArray(value.permissions) ? value.permissions : undefined
93
+ if (!permissions) return value
94
+ const seen = new Set<string>()
95
+ return {
96
+ ...value,
97
+ permissions: permissions.filter((permission) => {
98
+ const key = stableJson(permission)
99
+ if (seen.has(key)) return false
100
+ seen.add(key)
101
+ return true
102
+ }),
103
+ }
104
+ }
105
+
106
+ function stableJson(value: unknown): string {
107
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`
108
+ if (value !== null && typeof value === "object") {
109
+ const record = value as Record<string, unknown>
110
+ return `{${Object.keys(record)
111
+ .sort()
112
+ .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)
113
+ .join(",")}}`
114
+ }
115
+ return JSON.stringify(value)
116
+ }
117
+
118
+ export type OpenCodePluginContext = Parameters<Parameters<typeof PluginType.define>[0]["setup"]>[0]
119
+
120
+ export interface NativeSession {
121
+ readonly id: string
122
+ readonly location: { readonly directory: string }
123
+ readonly time: { readonly idle?: number }
124
+ readonly outcome?: "succeeded" | "failed" | "interrupted"
125
+ readonly metadata?: Record<string, unknown>
126
+ readonly agent?: string
127
+ readonly cost?: number
128
+ readonly tokens?: { readonly input?: number; readonly output?: number }
129
+ }
130
+
131
+ export interface NativeMessage {
132
+ readonly id: string
133
+ readonly type: string
134
+ readonly time?: { readonly created?: number }
135
+ readonly metadata?: Record<string, unknown>
136
+ readonly content?: readonly NativeContent[]
137
+ readonly outcome?: "succeeded" | "failed" | "interrupted"
138
+ readonly error?: { readonly message?: string; readonly type?: string }
139
+ }
140
+
141
+ export interface NativeContent {
142
+ readonly type: string
143
+ readonly text?: string
144
+ readonly name?: string
145
+ readonly state?: {
146
+ readonly status?: string
147
+ readonly error?: { readonly message?: string }
148
+ }
149
+ }
150
+
151
+ export interface PendingPermission {
152
+ readonly id: string
153
+ readonly action: string
154
+ readonly resources: readonly string[]
155
+ readonly message?: string
156
+ }
157
+
158
+ export interface NativeAgentInfo {
159
+ readonly id: string
160
+ readonly name: string
161
+ readonly mode: string
162
+ readonly hidden: boolean
163
+ }
164
+
165
+ export interface TrustedContextSnapshot {
166
+ readonly agents: Readonly<Record<string, string>>
167
+ readonly plugins: Readonly<Record<string, string>>
168
+ readonly configHash: string
169
+ readonly agentDefinitions?: Readonly<Record<string, unknown>>
170
+ }
171
+
172
+ export interface NativeBridge {
173
+ validateAgent(name: string): Promise<NativeAgentInfo>
174
+ createSession(input: {
175
+ jobID: string
176
+ title: string
177
+ directory: string
178
+ agent: string
179
+ attempt: number
180
+ }): Promise<NativeSession>
181
+ ensureLocation(directory: string): Promise<void>
182
+ executionConfig(directory: string): Promise<string>
183
+ trustedContext(directory: string): Promise<TrustedContextSnapshot>
184
+ prompt(input: {
185
+ sessionID: string
186
+ text: string
187
+ jobID: string
188
+ attempt: number
189
+ kind: string
190
+ requestID: string
191
+ metadata?: Record<string, string>
192
+ }): Promise<{ messageID: string; recovered: boolean }>
193
+ getSession(sessionID: string): Promise<NativeSession | undefined>
194
+ messages(sessionID: string): Promise<readonly NativeMessage[]>
195
+ permissions(sessionID: string): Promise<readonly PendingPermission[]>
196
+ interrupt(sessionID: string): Promise<boolean>
197
+ findJobSessions(directory: string, jobID: string): Promise<readonly NativeSession[]>
198
+ recordIdle(sessionID: string, background: readonly string[]): void
199
+ idleBackground(sessionID: string): readonly string[] | undefined
200
+ }
201
+
202
+ export class OpenCodeNativeBridge implements NativeBridge {
203
+ private readonly idle = new Map<string, readonly string[]>()
204
+
205
+ constructor(
206
+ private readonly ctx: OpenCodePluginContext,
207
+ private readonly logger: Logger,
208
+ ) {}
209
+
210
+ async validateAgent(name: string): Promise<NativeAgentInfo> {
211
+ const result = await this.ctx.agent.get({ agentID: name as never })
212
+ const agent = result.data as unknown as Agent.Info
213
+ if (!agent) throw new Error(`Native agent "${name}" was not found`)
214
+ if (agent.hidden) throw new Error(`Native agent "${name}" is hidden and cannot be dispatched`)
215
+ if (agent.mode === "subagent") throw new Error(`Native agent "${name}" is a subagent; use a primary or all-mode agent`)
216
+ return { id: agent.id, name: agent.name, mode: agent.mode, hidden: agent.hidden }
217
+ }
218
+
219
+ async createSession(input: {
220
+ jobID: string
221
+ title: string
222
+ directory: string
223
+ agent: string
224
+ attempt: number
225
+ }): Promise<NativeSession> {
226
+ const session = await this.ctx.session.create({
227
+ title: input.title.slice(0, 200),
228
+ agent: input.agent as never,
229
+ location: { directory: input.directory },
230
+ metadata: {
231
+ taskfeed: {
232
+ jobID: input.jobID,
233
+ attempt: input.attempt,
234
+ managed: true,
235
+ },
236
+ },
237
+ permissions: [
238
+ { action: "external_directory", resource: "*", effect: "deny" },
239
+ { action: "edit", resource: ".taskfeed/**", effect: "deny" },
240
+ ],
241
+ })
242
+ return session as unknown as NativeSession
243
+ }
244
+
245
+ async ensureLocation(directory: string): Promise<void> {
246
+ // A location is activated through a location-scoped API call. Agent listing
247
+ // is read-only and boots the location graph (and its plugins) without
248
+ // creating a session or consuming a model call.
249
+ await this.ctx.agent.list({ location: { directory } })
250
+ }
251
+
252
+ async prompt(input: {
253
+ sessionID: string
254
+ text: string
255
+ jobID: string
256
+ attempt: number
257
+ kind: string
258
+ requestID: string
259
+ metadata?: Record<string, string>
260
+ }): Promise<{ messageID: string; recovered: boolean }> {
261
+ try {
262
+ const admitted = await this.ctx.session.prompt({
263
+ sessionID: input.sessionID as never,
264
+ id: input.requestID,
265
+ text: input.text,
266
+ metadata: {
267
+ taskfeed: {
268
+ jobID: input.jobID,
269
+ attempt: input.attempt,
270
+ kind: input.kind,
271
+ ...(input.metadata ?? {}),
272
+ },
273
+ },
274
+ })
275
+ return { messageID: admitted.id, recovered: false }
276
+ } catch (error) {
277
+ const message = errorText(error)
278
+ if (!/conflict|existing durable record|already exists/iu.test(message)) throw error
279
+ const existing = (await this.messages(input.sessionID)).find((item) => item.id === input.requestID)
280
+ const metadata = existing?.metadata?.taskfeed
281
+ if (
282
+ existing &&
283
+ metadata !== null &&
284
+ typeof metadata === "object" &&
285
+ (metadata as Record<string, unknown>).jobID === input.jobID &&
286
+ (metadata as Record<string, unknown>).attempt === input.attempt &&
287
+ (metadata as Record<string, unknown>).kind === input.kind
288
+ ) {
289
+ return { messageID: existing.id, recovered: true }
290
+ }
291
+ throw new Error(
292
+ `Prompt message ID ${input.requestID} is already used by a different durable record; refusing to replay.`,
293
+ )
294
+ }
295
+ }
296
+
297
+ async executionConfig(directory: string): Promise<string> {
298
+ return await hashExecutionConfig(directory)
299
+ }
300
+
301
+ async trustedContext(directory: string): Promise<TrustedContextSnapshot> {
302
+ const [agents, plugins, configHash] = await Promise.all([
303
+ this.ctx.agent.list({ location: { directory } }),
304
+ this.ctx.plugin.list({ location: { directory } }),
305
+ this.executionConfig(directory),
306
+ ])
307
+ const pluginEntries = await Promise.all(
308
+ plugins.data.map(async (plugin) => {
309
+ const source = plugin.source
310
+ const trustedSource =
311
+ source.type === "local"
312
+ ? { type: source.type, content: await hashLocalSource(source.path) }
313
+ : source
314
+ return [
315
+ plugin.id ??
316
+ `${source.type}:${
317
+ source.type === "local"
318
+ ? path.basename(source.path)
319
+ : source.type === "package"
320
+ ? source.target
321
+ : "plugin"
322
+ }`,
323
+ stableHash(stableJson({ source: trustedSource }), 64),
324
+ ] as const
325
+ }),
326
+ )
327
+ return {
328
+ agents: Object.fromEntries(
329
+ agents.data
330
+ .map((agent) => [agent.id, stableHash(stableJson(normalizeAgent(agent)), 64)] as const)
331
+ .sort(([left], [right]) => left.localeCompare(right)),
332
+ ),
333
+ plugins: Object.fromEntries(pluginEntries.sort(([left], [right]) => left.localeCompare(right))),
334
+ configHash,
335
+ agentDefinitions: Object.fromEntries(
336
+ agents.data.map((agent) => [agent.id, normalizeAgent(agent)]),
337
+ ),
338
+ }
339
+ }
340
+
341
+ async getSession(sessionID: string): Promise<NativeSession | undefined> {
342
+ try {
343
+ return (await this.ctx.session.get({ sessionID: sessionID as never })) as unknown as NativeSession
344
+ } catch (error) {
345
+ const message = error instanceof Error ? error.message : String(error)
346
+ if (/not found|NotFound/iu.test(message)) return undefined
347
+ throw error
348
+ }
349
+ }
350
+
351
+ async messages(sessionID: string): Promise<readonly NativeMessage[]> {
352
+ return (await this.ctx.session.context({ sessionID: sessionID as never })) as unknown as NativeMessage[]
353
+ }
354
+
355
+ async permissions(sessionID: string): Promise<readonly PendingPermission[]> {
356
+ try {
357
+ const result = await this.ctx.permission.list({ sessionID: sessionID as never })
358
+ return result.map((request) => ({
359
+ id: request.id,
360
+ action: request.action,
361
+ resources: request.resources,
362
+ ...(request.message === undefined ? {} : { message: request.message }),
363
+ }))
364
+ } catch (error) {
365
+ this.logger.warn("could not inspect native permissions", {
366
+ sessionID,
367
+ error: error instanceof Error ? error.message : String(error),
368
+ })
369
+ throw error
370
+ }
371
+ }
372
+
373
+ async interrupt(sessionID: string): Promise<boolean> {
374
+ const result = await this.ctx.session.interrupt({ sessionID: sessionID as never, resume: false })
375
+ return result.interrupted
376
+ }
377
+
378
+ async findJobSessions(directory: string, jobID: string): Promise<readonly NativeSession[]> {
379
+ const matches: NativeSession[] = []
380
+ let cursor: string | undefined
381
+ for (let page = 0; page < 20; page++) {
382
+ const result = (await this.ctx.session.list({
383
+ directory,
384
+ limit: 100,
385
+ ...(cursor === undefined ? {} : { cursor }),
386
+ } as never)) as unknown as {
387
+ data?: readonly NativeSession[]
388
+ cursor?: { next?: string | null }
389
+ }
390
+ for (const session of result.data ?? []) {
391
+ const taskfeed = session.metadata?.taskfeed
392
+ if (
393
+ taskfeed !== null &&
394
+ typeof taskfeed === "object" &&
395
+ (taskfeed as Record<string, unknown>).jobID === jobID
396
+ ) {
397
+ matches.push(session)
398
+ }
399
+ }
400
+ const next = result.cursor?.next
401
+ if (!next) break
402
+ cursor = next
403
+ }
404
+ return matches
405
+ }
406
+
407
+ recordIdle(sessionID: string, background: readonly string[]): void {
408
+ this.idle.set(sessionID, background)
409
+ }
410
+
411
+ idleBackground(sessionID: string): readonly string[] | undefined {
412
+ return this.idle.get(sessionID)
413
+ }
414
+ }
415
+
416
+ export function taskfeedMetadata(session: Session.Info): Record<string, unknown> | undefined {
417
+ const metadata = session.metadata
418
+ if (!metadata || typeof metadata !== "object") return undefined
419
+ const taskfeed = (metadata as Record<string, unknown>).taskfeed
420
+ return taskfeed && typeof taskfeed === "object" ? (taskfeed as Record<string, unknown>) : undefined
421
+ }