@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
package/src/tui.tsx ADDED
@@ -0,0 +1,399 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"
3
+ import { Plugin, usePlugin } from "@opencode/plugin/tui"
4
+ import type { RpcClient } from "@opencode/client/promise"
5
+ import { TaskfeedRpc, type TaskfeedRpcDefinition } from "./rpc.js"
6
+ import type { JobView, TaskfeedSnapshot } from "./core/types.js"
7
+ import { PLUGIN_VERSION } from "./version.js"
8
+
9
+ const PAGE = "taskfeed"
10
+ type TaskfeedClient = RpcClient<TaskfeedRpcDefinition>
11
+
12
+ const SECTIONS: Array<{ key: JobView["status"]; label: string }> = [
13
+ { key: "queued", label: "QUEUED" },
14
+ { key: "running", label: "RUNNING" },
15
+ { key: "awaiting_approval", label: "AWAITING REVIEW" },
16
+ { key: "blocked", label: "BLOCKED" },
17
+ { key: "completed", label: "COMPLETED" },
18
+ { key: "failed", label: "FAILED" },
19
+ { key: "cancelled", label: "CANCELLED" },
20
+ ]
21
+
22
+ function sectionFor(status: JobView["status"]): string {
23
+ if (status === "starting" || status === "paused") return "RUNNING"
24
+ if (status === "discovered") return "QUEUED"
25
+ return SECTIONS.find((item) => item.key === status)?.label ?? String(status).toUpperCase()
26
+ }
27
+
28
+ function shortObjective(title: string): string {
29
+ const value = title.replace(/\s+/gu, " ").trim()
30
+ return value.length > 64 ? `${value.slice(0, 61)}…` : value
31
+ }
32
+
33
+ function stateColor(theme: ReturnType<typeof usePlugin>["theme"], job: JobView) {
34
+ if (job.status === "completed") return theme.text.feedback.success.base
35
+ if (job.status === "failed" || job.status === "cancelled") return theme.text.feedback.error.base
36
+ if (job.status === "blocked") return theme.text.feedback.warning.base
37
+ if (job.status === "awaiting_approval") return theme.text.feedback.info.base
38
+ return theme.text.base
39
+ }
40
+
41
+ function gateCommand(job: JobView): string | undefined {
42
+ if (!job.gate || job.gate.status !== "open") return undefined
43
+ if (!job.gate.pullRequestURL) return "Remote review artifact unavailable"
44
+ if (job.gate.kind === "native_review") return `/taskfeed approve ${job.gate.id} ${job.gate.revision}`
45
+ if (job.gate.outcomes?.includes("approved")) return `/taskfeed approve ${job.gate.id} ${job.gate.revision}`
46
+ return `/taskfeed outcome ${job.gate.id} ${job.gate.revision} <declared-outcome>`
47
+ }
48
+
49
+ function TaskfeedPage() {
50
+ const context = usePlugin()
51
+ const location = () => context.location ?? context.data.location.default()
52
+ const rpc = (): TaskfeedClient => context.client.rpc(TaskfeedRpc)
53
+ const [snapshot, setSnapshot] = createSignal<TaskfeedSnapshot | undefined>(undefined)
54
+ const [selectedID, setSelectedID] = createSignal<string | undefined>(undefined)
55
+ const [error, setError] = createSignal<string | undefined>(undefined)
56
+ const [loading, setLoading] = createSignal(true)
57
+ let unsubscribe: (() => void) | undefined
58
+ let timer: ReturnType<typeof setInterval> | undefined
59
+
60
+ const jobs = createMemo(() => snapshot()?.jobs ?? [])
61
+ const selected = createMemo(() => {
62
+ const current = selectedID()
63
+ return jobs().find((job) => job.jobID === current) ?? jobs()[0]
64
+ })
65
+
66
+ const reload = async () => {
67
+ try {
68
+ const next = await rpc().getSnapshot({}, { location: { directory: location().directory } })
69
+ setSnapshot(next)
70
+ setError(undefined)
71
+ if (!next.jobs.some((job) => job.jobID === selectedID())) {
72
+ setSelectedID(next.jobs[0]?.jobID)
73
+ }
74
+ } catch (cause) {
75
+ setError(cause instanceof Error ? cause.message : String(cause))
76
+ } finally {
77
+ setLoading(false)
78
+ }
79
+ }
80
+
81
+ const toast = (message: string, variant: "info" | "success" | "warning" | "error" = "info") =>
82
+ context.ui.toast.show({ message, variant })
83
+
84
+ const action = async (
85
+ label: string,
86
+ fn: () => Promise<TaskfeedSnapshot>,
87
+ confirm?: { title: string; message: string },
88
+ ) => {
89
+ try {
90
+ if (confirm && !(await context.ui.dialog.confirm({ ...confirm, label: { confirm: label, cancel: "Cancel" } }))) {
91
+ return
92
+ }
93
+ const next = await fn()
94
+ setSnapshot(next)
95
+ toast(label)
96
+ } catch (cause) {
97
+ toast(cause instanceof Error ? cause.message : String(cause), "error")
98
+ }
99
+ }
100
+
101
+ const choose = (delta: number) => {
102
+ const list = jobs()
103
+ if (list.length === 0) return
104
+ const index = Math.max(0, list.findIndex((job) => job.jobID === selected()?.jobID))
105
+ setSelectedID(list[(index + delta + list.length) % list.length]?.jobID)
106
+ }
107
+
108
+ const toggleAutomation = () => {
109
+ const current = snapshot()
110
+ if (!current) return
111
+ void action(current.scheduler.enabled ? "Disable automation" : "Enable automation", () =>
112
+ rpc().setAutomation({ enabled: !current.scheduler.enabled }, { location: { directory: location().directory } }),
113
+ )
114
+ }
115
+
116
+ const togglePaused = () => {
117
+ const current = snapshot()
118
+ if (!current) return
119
+ void action(current.scheduler.paused ? "Resume scheduling" : "Pause scheduling", () =>
120
+ rpc().setPaused({ paused: !current.scheduler.paused }, { location: { directory: location().directory } }),
121
+ )
122
+ }
123
+
124
+ const dispatch = () => {
125
+ const job = selected()
126
+ if (!job) return
127
+ void action("Dispatch job", () =>
128
+ rpc().dispatch({ jobID: job.jobID }, { location: { directory: location().directory } }),
129
+ )
130
+ }
131
+
132
+ const cancel = () => {
133
+ const job = selected()
134
+ if (!job) return
135
+ void action(
136
+ "Cancel job",
137
+ () => rpc().cancel({ jobID: job.jobID }, { location: { directory: location().directory } }),
138
+ { title: "Cancel execution", message: `Cancel #${job.task.issueNumber}? The workspace is retained.` },
139
+ )
140
+ }
141
+
142
+ const retry = () => {
143
+ const job = selected()
144
+ if (!job) return
145
+ void action("Retry job", () =>
146
+ rpc().retry({ jobID: job.jobID }, { location: { directory: location().directory } }),
147
+ )
148
+ }
149
+
150
+ const cleanup = () => {
151
+ const job = selected()
152
+ if (!job) return
153
+ void action(
154
+ "Clean up workspace",
155
+ () => rpc().cleanupWorkspace({ jobID: job.jobID }, { location: { directory: location().directory } }),
156
+ {
157
+ title: "Remove worktree",
158
+ message: `Remove the clean worktree for #${job.task.issueNumber}? The branch and commits are kept.`,
159
+ },
160
+ )
161
+ }
162
+
163
+ const toggleWorkflow = () => {
164
+ const job = selected()
165
+ if (!job) return
166
+ if (job.status === "paused") {
167
+ void action("Resume workflow", () =>
168
+ rpc().resumeWorkflow({ jobID: job.jobID }, { location: { directory: location().directory } }),
169
+ )
170
+ } else {
171
+ void action("Pause workflow", () =>
172
+ rpc().pauseWorkflow({ jobID: job.jobID }, { location: { directory: location().directory } }),
173
+ )
174
+ }
175
+ }
176
+
177
+ const openSession = () => {
178
+ const job = selected()
179
+ if (!job?.sessionID) {
180
+ toast("No native session is associated with this job", "warning")
181
+ return
182
+ }
183
+ if (context.ui.tabs.enabled()) context.ui.tabs.focus(job.sessionID)
184
+ context.ui.router.navigate({ type: "session", sessionID: job.sessionID })
185
+ }
186
+
187
+ context.keymap.layer(() => ({
188
+ mode: "global",
189
+ priority: 20,
190
+ commands: [
191
+ { id: "taskfeed.select.next", title: "Next Taskfeed job", bind: "down", run: () => choose(1) },
192
+ { id: "taskfeed.select.previous", title: "Previous Taskfeed job", bind: "up", run: () => choose(-1) },
193
+ { id: "taskfeed.open", title: "Open Taskfeed session", bind: "return", run: openSession },
194
+ { id: "taskfeed.automation", title: "Toggle Taskfeed automation", bind: "a", run: toggleAutomation },
195
+ { id: "taskfeed.pause", title: "Pause Taskfeed scheduling", bind: "p", run: togglePaused },
196
+ { id: "taskfeed.dispatch", title: "Dispatch Taskfeed job", bind: "d", run: dispatch },
197
+ { id: "taskfeed.cancel", title: "Cancel Taskfeed job", bind: "x", run: cancel },
198
+ { id: "taskfeed.retry", title: "Retry Taskfeed job", bind: "t", run: retry },
199
+ { id: "taskfeed.cleanup", title: "Clean Taskfeed worktree", bind: "c", run: cleanup },
200
+ { id: "taskfeed.workflow", title: "Pause or resume Taskfeed workflow", bind: "w", run: toggleWorkflow },
201
+ { id: "taskfeed.refresh", title: "Refresh Taskfeed", bind: "r", run: () => void reload() },
202
+ ],
203
+ }))
204
+
205
+ onMount(() => {
206
+ void reload()
207
+ unsubscribe = rpc().events.on("changed", (event) => {
208
+ if (event.location.directory !== location().directory) return
209
+ void reload()
210
+ })
211
+ timer = setInterval(() => void reload(), 3_000)
212
+ })
213
+ onCleanup(() => {
214
+ unsubscribe?.()
215
+ if (timer) clearInterval(timer)
216
+ })
217
+
218
+ const current = () => snapshot()
219
+ const job = () => selected()
220
+
221
+ return (
222
+ <box flexDirection="column" padding={1}>
223
+ <text fg={context.theme.text.base}>
224
+ TASKFEED — Current project
225
+ <span style={{ fg: context.theme.text.faint }}> · {PLUGIN_VERSION}</span>
226
+ </text>
227
+ <Show when={current()} fallback={<text fg={context.theme.text.muted}>{loading() ? "Loading Taskfeed…" : error()}</text>}>
228
+ {(state) => (
229
+ <box flexDirection="column">
230
+ <text fg={context.theme.text.muted}>
231
+ Watching: GitHub
232
+ {state().config.repository ? ` · ${state().config.repository}` : " · not configured"}
233
+ </text>
234
+ <text fg={context.theme.text.muted}>
235
+ Automation: {state().scheduler.enabled ? "Enabled" : "Disabled"} · Scheduler:{" "}
236
+ {state().scheduler.leader ? "Owner" : "Standby"}
237
+ {state().scheduler.paused ? " · Paused" : ""}
238
+ </text>
239
+ <text fg={context.theme.text.muted}>
240
+ Capacity: project {state().scheduler.running}/{state().scheduler.concurrency} · global{" "}
241
+ {state().scheduler.globalUsed}/{state().scheduler.globalLimit}
242
+ {state().scheduler.globalAmbiguous > 0 ? ` · ambiguous ${state().scheduler.globalAmbiguous}` : ""}
243
+ </text>
244
+ <text fg={context.theme.text.muted}>
245
+ Execution: {state().config.execution ? `${state().config.execution?.type} ${state().config.execution?.name}` : "not configured"} ·
246
+ config {state().config.status}
247
+ </text>
248
+ <Show when={state().config.error}>
249
+ <text fg={context.theme.text.feedback.error.base}>{state().config.error}</text>
250
+ </Show>
251
+ <Show when={state().scheduler.lastError}>
252
+ <text fg={context.theme.text.feedback.warning.base}>{state().scheduler.lastError}</text>
253
+ </Show>
254
+ <Show when={error()}>
255
+ <text fg={context.theme.text.feedback.error.base}>{error()}</text>
256
+ </Show>
257
+ <text> </text>
258
+ <Show
259
+ when={jobs().length > 0}
260
+ fallback={
261
+ <text fg={context.theme.text.muted}>
262
+ {state().config.status === "missing"
263
+ ? "Add .taskfeed/config.yaml to start watching GitHub."
264
+ : "No Taskfeed jobs yet. Label an issue agent-ready from an authorized account."}
265
+ </text>
266
+ }
267
+ >
268
+ {SECTIONS.map((section) => {
269
+ const items = jobs().filter((item) => sectionFor(item.status) === section.label)
270
+ return (
271
+ <Show when={items.length > 0}>
272
+ <text fg={context.theme.text.faint}>
273
+ {section.label} · {items.length}
274
+ </text>
275
+ {items.map((item) => {
276
+ const active = item.jobID === job()?.jobID
277
+ return (
278
+ <text fg={active ? context.theme.text.feedback.success.base : stateColor(context.theme, item)}>
279
+ {active ? "›" : " "} #{item.task.issueNumber} {shortObjective(item.task.title)} · {item.status}
280
+ {item.execution.type === "workflow" ? ` · ${item.execution.name}` : ""}
281
+ {item.pendingDecision ? " · decision waiting for capacity" : ""}
282
+ </text>
283
+ )
284
+ })}
285
+ </Show>
286
+ )
287
+ })}
288
+ </Show>
289
+ <Show when={job()}>
290
+ {(item) => (
291
+ <box flexDirection="column">
292
+ <text> </text>
293
+ <text fg={context.theme.text.base}>
294
+ #{item().task.issueNumber} {item().task.title}
295
+ </text>
296
+ <text fg={context.theme.text.muted}>
297
+ {item().status} · revision {item().revision} · attempt {item().attempts} · feedback{" "}
298
+ {item().feedbackIterations}
299
+ </text>
300
+ <Show when={item().branch}>
301
+ <text fg={context.theme.text.muted}>Branch: {item().branch}</text>
302
+ </Show>
303
+ <Show when={item().commitSHA}>
304
+ <text fg={context.theme.text.muted}>Commit: {item().commitSHA}</text>
305
+ </Show>
306
+ <Show when={item().pullRequestURL}>
307
+ <text fg={context.theme.text.muted}>Draft PR: {item().pullRequestURL}</text>
308
+ </Show>
309
+ <Show when={item().publication?.status === "local_only" || item().publication?.status === "disabled"}>
310
+ <text fg={context.theme.text.feedback.warning.base}>
311
+ Local-only: external review artifact unavailable
312
+ </text>
313
+ </Show>
314
+ <Show when={item().blocker}>
315
+ <text fg={context.theme.text.feedback.warning.base}>
316
+ Blocker {item().blocker?.code}: {item().blocker?.message}
317
+ </text>
318
+ <Show when={item().blocker?.action}>
319
+ <text fg={context.theme.text.faint}>{item().blocker?.action}</text>
320
+ </Show>
321
+ </Show>
322
+ <Show when={gateCommand(item())}>
323
+ <text fg={context.theme.text.feedback.info.base}>{gateCommand(item())}</text>
324
+ </Show>
325
+ <Show when={item().lastError}>
326
+ <text fg={context.theme.text.feedback.error.base}>{item().lastError}</text>
327
+ </Show>
328
+ </box>
329
+ )}
330
+ </Show>
331
+ <text> </text>
332
+ <text fg={context.theme.text.faint}>
333
+ up/down select · enter open session · a automation · p scheduler pause · r refresh · d dispatch · x cancel · t retry · c cleanup · w workflow pause/resume
334
+ </text>
335
+ </box>
336
+ )}
337
+ </Show>
338
+ </box>
339
+ )
340
+ }
341
+
342
+ export default Plugin.define({
343
+ id: "taskfeed.tui",
344
+ setup(context) {
345
+ const location = () => context.location ?? context.data.location.default()
346
+ const rpc = () => context.client.rpc(TaskfeedRpc)
347
+ const toast = (message: string, variant: "info" | "success" | "warning" | "error" = "info") =>
348
+ context.ui.toast.show({ message, variant })
349
+
350
+ const runCommand = async (input?: string) => {
351
+ const command = input?.trim().toLowerCase()
352
+ try {
353
+ if (command === "on" || command === "off") {
354
+ await rpc().setAutomation({ enabled: command === "on" }, { location: { directory: location().directory } })
355
+ toast(`Taskfeed automation ${command === "on" ? "enabled" : "disabled"}`, "success")
356
+ return
357
+ }
358
+ if (command === "pause" || command === "resume") {
359
+ await rpc().setPaused({ paused: command === "pause" }, { location: { directory: location().directory } })
360
+ toast(`Taskfeed scheduling ${command === "pause" ? "paused" : "resumed"}`, "success")
361
+ return
362
+ }
363
+ if (command === "refresh") {
364
+ await rpc().refresh({}, { location: { directory: location().directory } })
365
+ toast("Taskfeed refresh requested", "success")
366
+ return
367
+ }
368
+ } catch (cause) {
369
+ toast(cause instanceof Error ? cause.message : String(cause), "error")
370
+ return
371
+ }
372
+ context.ui.router.navigate({ type: "plugin", name: PAGE })
373
+ }
374
+
375
+ const unregister = context.ui.router.register({
376
+ name: PAGE,
377
+ render: () => <TaskfeedPage />,
378
+ })
379
+ context.keymap.layer(() => ({
380
+ mode: "global",
381
+ priority: 10,
382
+ commands: [
383
+ {
384
+ id: "taskfeed.open",
385
+ title: "Taskfeed",
386
+ description: "Open the Taskfeed automation panel",
387
+ group: "Taskfeed",
388
+ palette: true,
389
+ slash: { name: "taskfeed", arguments: true },
390
+ run: (input) => void runCommand(input),
391
+ },
392
+ ],
393
+ bindings: ["taskfeed.open"],
394
+ }))
395
+ return () => {
396
+ unregister()
397
+ }
398
+ },
399
+ })
@@ -0,0 +1,18 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+
3
+ export function uuid(): string {
4
+ return randomUUID()
5
+ }
6
+
7
+ export function stableHash(value: string, length = 16): string {
8
+ return createHash("sha256").update(value).digest("hex").slice(0, length)
9
+ }
10
+
11
+ export function slug(value: string, max = 40): string {
12
+ const result = value
13
+ .toLowerCase()
14
+ .replace(/[^a-z0-9]+/gu, "-")
15
+ .replace(/^-+|-+$/gu, "")
16
+ .slice(0, max)
17
+ return result || "task"
18
+ }
@@ -0,0 +1,52 @@
1
+ import { redactRecord } from "./redact.js"
2
+
3
+ export type LogLevel = "debug" | "info" | "warn" | "error"
4
+
5
+ export interface Logger {
6
+ debug(message: string, fields?: Record<string, unknown>): void
7
+ info(message: string, fields?: Record<string, unknown>): void
8
+ warn(message: string, fields?: Record<string, unknown>): void
9
+ error(message: string, fields?: Record<string, unknown>): void
10
+ }
11
+
12
+ export class ConsoleLogger implements Logger {
13
+ constructor(private readonly prefix = "taskfeed") {}
14
+
15
+ private write(level: LogLevel, message: string, fields: Record<string, unknown> = {}): void {
16
+ const safe = redactRecord(fields)
17
+ const suffix = typeof safe !== "object" || safe === null || Object.keys(safe).length === 0 ? "" : ` ${JSON.stringify(safe)}`
18
+ const line = `${this.prefix}: ${level}: ${message}${suffix}`
19
+ if (level === "error") console.error(line)
20
+ else if (level === "warn") console.warn(line)
21
+ else console.log(line)
22
+ }
23
+
24
+ debug(message: string, fields?: Record<string, unknown>): void {
25
+ this.write("debug", message, fields)
26
+ }
27
+ info(message: string, fields?: Record<string, unknown>): void {
28
+ this.write("info", message, fields)
29
+ }
30
+ warn(message: string, fields?: Record<string, unknown>): void {
31
+ this.write("warn", message, fields)
32
+ }
33
+ error(message: string, fields?: Record<string, unknown>): void {
34
+ this.write("error", message, fields)
35
+ }
36
+ }
37
+
38
+ export class MemoryLogger implements Logger {
39
+ readonly entries: Array<{ level: LogLevel; message: string; fields?: Record<string, unknown> }> = []
40
+ debug(message: string, fields?: Record<string, unknown>): void {
41
+ this.entries.push({ level: "debug", message, fields })
42
+ }
43
+ info(message: string, fields?: Record<string, unknown>): void {
44
+ this.entries.push({ level: "info", message, fields })
45
+ }
46
+ warn(message: string, fields?: Record<string, unknown>): void {
47
+ this.entries.push({ level: "warn", message, fields })
48
+ }
49
+ error(message: string, fields?: Record<string, unknown>): void {
50
+ this.entries.push({ level: "error", message, fields })
51
+ }
52
+ }
@@ -0,0 +1,119 @@
1
+ import { spawn } from "node:child_process"
2
+
3
+ export interface CommandResult {
4
+ readonly command: string
5
+ readonly args: readonly string[]
6
+ readonly exitCode: number
7
+ readonly stdout: string
8
+ readonly stderr: string
9
+ readonly truncated?: boolean
10
+ }
11
+
12
+ export interface CommandOptions {
13
+ readonly cwd?: string
14
+ readonly env?: NodeJS.ProcessEnv
15
+ readonly timeoutMs?: number
16
+ readonly maxBytes?: number
17
+ readonly stdin?: string
18
+ }
19
+
20
+ export interface CommandRunner {
21
+ run(command: string, args: readonly string[], options?: CommandOptions): Promise<CommandResult>
22
+ }
23
+
24
+ export class CommandFailure extends Error {
25
+ constructor(readonly result: CommandResult) {
26
+ super(
27
+ `${result.command} exited with ${result.exitCode}: ${(result.stderr || result.stdout).trim().slice(0, 1_000)}`,
28
+ )
29
+ this.name = "CommandFailure"
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Spawns without a shell. Arguments are always passed as an array so untrusted
35
+ * issue text can never become shell syntax.
36
+ */
37
+ export class NodeCommandRunner implements CommandRunner {
38
+ async run(command: string, args: readonly string[], options: CommandOptions = {}): Promise<CommandResult> {
39
+ const timeoutMs = options.timeoutMs ?? 30_000
40
+ const maxBytes = options.maxBytes ?? 8 * 1024 * 1024
41
+ return await new Promise((resolve, reject) => {
42
+ const child = spawn(command, [...args], {
43
+ cwd: options.cwd,
44
+ env: options.env === undefined ? process.env : { ...process.env, ...options.env },
45
+ shell: false,
46
+ stdio: [options.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
47
+ })
48
+ if (options.stdin !== undefined) {
49
+ child.stdin?.end(options.stdin)
50
+ }
51
+ const stdout: Buffer[] = []
52
+ const stderr: Buffer[] = []
53
+ let total = 0
54
+ let settled = false
55
+ const finish = (result: CommandResult) => {
56
+ if (settled) return
57
+ settled = true
58
+ clearTimeout(timer)
59
+ resolve(result)
60
+ }
61
+ const fail = (error: Error) => {
62
+ if (settled) return
63
+ settled = true
64
+ clearTimeout(timer)
65
+ reject(error)
66
+ }
67
+ const timer = setTimeout(() => {
68
+ child.kill("SIGKILL")
69
+ fail(
70
+ new CommandFailure({
71
+ command,
72
+ args,
73
+ exitCode: 124,
74
+ stdout: Buffer.concat(stdout).toString("utf8"),
75
+ stderr: `command timed out after ${timeoutMs}ms`,
76
+ }),
77
+ )
78
+ }, timeoutMs)
79
+ timer.unref?.()
80
+ const collect = (target: Buffer[], chunk: Buffer) => {
81
+ total += chunk.byteLength
82
+ if (total <= maxBytes) target.push(chunk)
83
+ }
84
+ child.stdout?.on("data", (chunk: Buffer) => collect(stdout, chunk))
85
+ child.stderr?.on("data", (chunk: Buffer) => collect(stderr, chunk))
86
+ child.on("error", fail)
87
+ child.on("close", (code) => {
88
+ const result: CommandResult = {
89
+ command,
90
+ args,
91
+ exitCode: code ?? 1,
92
+ stdout: Buffer.concat(stdout).toString("utf8"),
93
+ stderr: total > maxBytes ? `${Buffer.concat(stderr).toString("utf8")}\n[output truncated]` : Buffer.concat(stderr).toString("utf8"),
94
+ truncated: total > maxBytes,
95
+ }
96
+ finish(result)
97
+ })
98
+ })
99
+ }
100
+ }
101
+
102
+ export async function runRequired(
103
+ runner: CommandRunner,
104
+ command: string,
105
+ args: readonly string[],
106
+ options?: CommandOptions,
107
+ ): Promise<string> {
108
+ const result = await runner.run(command, args, options)
109
+ if (result.exitCode !== 0) throw new CommandFailure(result)
110
+ return result.stdout
111
+ }
112
+
113
+ export function jsonCommand<T>(stdout: string, label: string): T {
114
+ try {
115
+ return JSON.parse(stdout) as T
116
+ } catch {
117
+ throw new Error(`${label} returned invalid JSON`)
118
+ }
119
+ }
@@ -0,0 +1,28 @@
1
+ const SECRET_PATTERNS: ReadonlyArray<[RegExp, string]> = [
2
+ [/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/gu, "[redacted-github-token]"],
3
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}\b/gu, "[redacted-github-token]"],
4
+ [/\bsk-[A-Za-z0-9_-]{16,}\b/gu, "[redacted-api-key]"],
5
+ [/\bAKIA[0-9A-Z]{16}\b/gu, "[redacted-aws-key]"],
6
+ [/(authorization\s*:\s*bearer\s+)[^\s]+/giu, "$1[redacted]"],
7
+ [/\b(password|token|secret|api[_-]?key)\s*[=:]\s*["']?[^"'\s]+/giu, "$1=[redacted]"],
8
+ ]
9
+
10
+ export function redact(value: string): string {
11
+ let result = value
12
+ for (const [pattern, replacement] of SECRET_PATTERNS) result = result.replace(pattern, replacement)
13
+ return result
14
+ }
15
+
16
+ export function redactRecord(value: unknown): unknown {
17
+ if (typeof value === "string") return redact(value)
18
+ if (Array.isArray(value)) return value.map(redactRecord)
19
+ if (value !== null && typeof value === "object") {
20
+ return Object.fromEntries(
21
+ Object.entries(value as Record<string, unknown>).map(([key, item]) => [
22
+ key,
23
+ /token|secret|password|authorization|credential/i.test(key) ? "[redacted]" : redactRecord(item),
24
+ ]),
25
+ )
26
+ }
27
+ return value
28
+ }
package/src/version.ts ADDED
@@ -0,0 +1,2 @@
1
+ export const PLUGIN_NAME = "@alvarolorentedev/opencode-taskfeed"
2
+ export const PLUGIN_VERSION = "0.1.0-alpha.1"