@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.
- package/LICENSE +202 -0
- package/README.md +431 -2
- package/docs/architecture.md +123 -0
- package/docs/configuration.md +123 -0
- package/docs/development.md +312 -0
- package/docs/integrations.md +84 -0
- package/docs/operations.md +136 -0
- package/docs/releases/v0.1.0-alpha.1.md +164 -0
- package/docs/security.md +120 -0
- package/examples/README.md +7 -0
- package/examples/approvals/README.md +27 -0
- package/examples/flowgraph/config.yaml +28 -0
- package/examples/flowgraph/opencode.jsonc +14 -0
- package/examples/headless/README.md +25 -0
- package/examples/headless/config.yaml +21 -0
- package/examples/native-agent/config.yaml +31 -0
- package/examples/native-agent/opencode.jsonc +10 -0
- package/examples/playground/README.md +61 -0
- package/examples/playground/config.yaml +40 -0
- package/examples/playground/opencode.jsonc +5 -0
- package/package.json +89 -4
- package/src/config/load.ts +122 -0
- package/src/config/repository.ts +72 -0
- package/src/config/schema.ts +215 -0
- package/src/core/approval.ts +190 -0
- package/src/core/comments.ts +175 -0
- package/src/core/index.ts +5 -0
- package/src/core/ports.ts +185 -0
- package/src/core/state.ts +186 -0
- package/src/core/types.ts +430 -0
- package/src/executors/flowgraph/client.ts +27 -0
- package/src/executors/flowgraph/executor.ts +593 -0
- package/src/executors/flowgraph/lazy.ts +77 -0
- package/src/executors/flowgraph/rpc.ts +145 -0
- package/src/executors/flowgraph/worker.ts +538 -0
- package/src/executors/native/bridge.ts +421 -0
- package/src/executors/native/executor.ts +295 -0
- package/src/executors/native/prompt.ts +57 -0
- package/src/executors/native/trust.ts +105 -0
- package/src/index.ts +116 -0
- package/src/rpc.ts +75 -0
- package/src/runtime/backends.ts +27 -0
- package/src/runtime/engine.ts +2345 -0
- package/src/runtime/server-backends.ts +136 -0
- package/src/runtime/service.ts +276 -0
- package/src/sources/github/client.ts +98 -0
- package/src/sources/github/source.ts +490 -0
- package/src/storage/capacity.ts +223 -0
- package/src/storage/jobs.ts +249 -0
- package/src/storage/locks.ts +342 -0
- package/src/tui.tsx +399 -0
- package/src/util/ids.ts +18 -0
- package/src/util/logger.ts +52 -0
- package/src/util/process.ts +119 -0
- package/src/util/redact.ts +28 -0
- package/src/version.ts +2 -0
- package/src/workspaces/native.ts +162 -0
- package/src/workspaces/publication.ts +477 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { BackendsProvider, BackendsResult, ReadyBackends } from "./backends.js"
|
|
2
|
+
import { loadConfig, type ConfigState } from "../config/load.js"
|
|
3
|
+
import type { Logger } from "../util/logger.js"
|
|
4
|
+
import type { CommandRunner } from "../util/process.js"
|
|
5
|
+
import type { OpenCodePluginContext, NativeBridge } from "../executors/native/bridge.js"
|
|
6
|
+
import { NativeExecutor } from "../executors/native/executor.js"
|
|
7
|
+
import { LazyFlowgraphExecutor } from "../executors/flowgraph/lazy.js"
|
|
8
|
+
import { trustedAgentsKey } from "../executors/native/trust.js"
|
|
9
|
+
import { WorkerFlowgraphClient } from "../executors/flowgraph/worker.js"
|
|
10
|
+
import { FlowgraphRpc } from "../executors/flowgraph/rpc.js"
|
|
11
|
+
import type { FlowgraphClient } from "../executors/flowgraph/client.js"
|
|
12
|
+
import type { KVPort } from "../storage/jobs.js"
|
|
13
|
+
import { GitHubClient } from "../sources/github/client.js"
|
|
14
|
+
import { GitHubSource } from "../sources/github/source.js"
|
|
15
|
+
import { GitHubPublisher } from "../workspaces/publication.js"
|
|
16
|
+
import { NativeWorkspaceProvider } from "../workspaces/native.js"
|
|
17
|
+
|
|
18
|
+
export interface ServerBackendsOptions {
|
|
19
|
+
readonly ctx: OpenCodePluginContext
|
|
20
|
+
readonly bridge: NativeBridge
|
|
21
|
+
readonly runner: CommandRunner
|
|
22
|
+
readonly logger: Logger
|
|
23
|
+
readonly projectID: string
|
|
24
|
+
readonly projectKey: string
|
|
25
|
+
readonly canonicalDirectory: string
|
|
26
|
+
readonly kv: KVPort
|
|
27
|
+
readonly schedulerGeneration?: () => string | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class ServerBackendsProvider implements BackendsProvider {
|
|
31
|
+
private cachedHash: string | undefined
|
|
32
|
+
private cached?: { state: ConfigState; backends?: ReadyBackends }
|
|
33
|
+
|
|
34
|
+
constructor(private readonly options: ServerBackendsOptions) {}
|
|
35
|
+
|
|
36
|
+
async get(): Promise<BackendsResult> {
|
|
37
|
+
const state = await loadConfig({
|
|
38
|
+
canonicalDirectory: this.options.canonicalDirectory,
|
|
39
|
+
runner: this.options.runner,
|
|
40
|
+
})
|
|
41
|
+
if (state.status !== "valid") {
|
|
42
|
+
this.cachedHash = undefined
|
|
43
|
+
this.cached = undefined
|
|
44
|
+
return { kind: "unavailable", configState: state }
|
|
45
|
+
}
|
|
46
|
+
if (this.cachedHash === state.contentHash && this.cached?.backends) {
|
|
47
|
+
return { kind: "ready", configState: state, backends: this.cached.backends }
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const backends = await this.build(state)
|
|
51
|
+
this.cachedHash = state.contentHash
|
|
52
|
+
this.cached = { state, backends }
|
|
53
|
+
return { kind: "ready", configState: state, backends }
|
|
54
|
+
} catch (error) {
|
|
55
|
+
this.cachedHash = undefined
|
|
56
|
+
this.cached = undefined
|
|
57
|
+
return {
|
|
58
|
+
kind: "unavailable",
|
|
59
|
+
configState: state,
|
|
60
|
+
error: error instanceof Error ? error.message : String(error),
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private async build(state: Extract<ConfigState, { status: "valid" }>): Promise<ReadyBackends> {
|
|
66
|
+
const config = state.config
|
|
67
|
+
const client = new GitHubClient({
|
|
68
|
+
runner: this.options.runner,
|
|
69
|
+
cwd: this.options.canonicalDirectory,
|
|
70
|
+
})
|
|
71
|
+
const source = new GitHubSource({
|
|
72
|
+
client,
|
|
73
|
+
repository: state.repository,
|
|
74
|
+
logger: this.options.logger,
|
|
75
|
+
})
|
|
76
|
+
const workspace = new NativeWorkspaceProvider({
|
|
77
|
+
worktree: this.options.ctx.worktree,
|
|
78
|
+
runner: this.options.runner,
|
|
79
|
+
logger: this.options.logger,
|
|
80
|
+
projectID: this.options.projectID,
|
|
81
|
+
canonicalDirectory: this.options.canonicalDirectory,
|
|
82
|
+
branchPrefix: config.publication.branch_prefix,
|
|
83
|
+
})
|
|
84
|
+
const publisher = new GitHubPublisher({
|
|
85
|
+
enabled: config.publication.enabled,
|
|
86
|
+
runner: this.options.runner,
|
|
87
|
+
client,
|
|
88
|
+
logger: this.options.logger,
|
|
89
|
+
repository: state.repository,
|
|
90
|
+
canonicalDirectory: this.options.canonicalDirectory,
|
|
91
|
+
...(config.publication.base_branch === undefined ? {} : { baseBranch: config.publication.base_branch }),
|
|
92
|
+
remote: config.publication.remote,
|
|
93
|
+
branchPrefix: config.publication.branch_prefix,
|
|
94
|
+
protectedPaths: config.publication.protected_paths,
|
|
95
|
+
generatedArtifacts: config.publication.generated_artifacts,
|
|
96
|
+
maxFileBytes: config.publication.max_file_bytes,
|
|
97
|
+
})
|
|
98
|
+
const localFlowgraph = this.options.ctx.rpc(FlowgraphRpc) as never
|
|
99
|
+
const trust = {
|
|
100
|
+
snapshot: async (directory: string) => {
|
|
101
|
+
const snapshot = await this.options.bridge.trustedContext(directory)
|
|
102
|
+
if (snapshot.agentDefinitions) {
|
|
103
|
+
await this.options.kv.set(trustedAgentsKey(this.options.projectKey), snapshot.agentDefinitions as never)
|
|
104
|
+
}
|
|
105
|
+
return snapshot
|
|
106
|
+
},
|
|
107
|
+
configSnapshot: (directory: string) => this.options.bridge.executionConfig(directory),
|
|
108
|
+
}
|
|
109
|
+
const workerFlowgraph = new WorkerFlowgraphClient({
|
|
110
|
+
kv: this.options.kv,
|
|
111
|
+
projectKey: this.options.projectKey,
|
|
112
|
+
canonicalDirectory: this.options.canonicalDirectory,
|
|
113
|
+
localClient: localFlowgraph,
|
|
114
|
+
logger: this.options.logger,
|
|
115
|
+
generation: this.options.schedulerGeneration ?? (() => undefined),
|
|
116
|
+
trust: () => trust.snapshot(this.options.canonicalDirectory),
|
|
117
|
+
}) as unknown as FlowgraphClient
|
|
118
|
+
const executors = {
|
|
119
|
+
agent: new NativeExecutor(this.options.bridge, this.options.logger, trust),
|
|
120
|
+
workflow: new LazyFlowgraphExecutor(
|
|
121
|
+
async () => workerFlowgraph,
|
|
122
|
+
this.options.bridge,
|
|
123
|
+
trust,
|
|
124
|
+
this.options.logger,
|
|
125
|
+
),
|
|
126
|
+
} as const
|
|
127
|
+
return {
|
|
128
|
+
config: state,
|
|
129
|
+
source,
|
|
130
|
+
executors,
|
|
131
|
+
workspace,
|
|
132
|
+
publisher,
|
|
133
|
+
defaultBranch: config.workspace.base_branch ?? config.publication.base_branch ?? "main",
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import type { TaskfeedSnapshot } from "../core/types.js"
|
|
3
|
+
import type { Logger } from "../util/logger.js"
|
|
4
|
+
import type { OpenCodePluginContext } from "../executors/native/bridge.js"
|
|
5
|
+
import { OpenCodeNativeBridge } from "../executors/native/bridge.js"
|
|
6
|
+
import { CapacityManager } from "../storage/capacity.js"
|
|
7
|
+
import { ProjectStore, projectKeyFor } from "../storage/jobs.js"
|
|
8
|
+
import { FileLease, FileMutex, projectLockPath } from "../storage/locks.js"
|
|
9
|
+
import { NodeCommandRunner } from "../util/process.js"
|
|
10
|
+
import { TaskfeedEngine } from "./engine.js"
|
|
11
|
+
import { ServerBackendsProvider } from "./server-backends.js"
|
|
12
|
+
import { PLUGIN_NAME, PLUGIN_VERSION } from "../version.js"
|
|
13
|
+
import { FlowgraphRpc } from "../executors/flowgraph/rpc.js"
|
|
14
|
+
import { FlowgraphWorker } from "../executors/flowgraph/worker.js"
|
|
15
|
+
import { applyTrustedAgents, trustedAgentsKey, type AgentEditorLike } from "../executors/native/trust.js"
|
|
16
|
+
|
|
17
|
+
export interface TaskfeedServiceOptions {
|
|
18
|
+
readonly ctx: OpenCodePluginContext
|
|
19
|
+
readonly logger: Logger
|
|
20
|
+
readonly onChange?: (snapshot: TaskfeedSnapshot) => void | Promise<void>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class TaskfeedService {
|
|
24
|
+
readonly engine: TaskfeedEngine
|
|
25
|
+
readonly bridge: OpenCodeNativeBridge
|
|
26
|
+
private readonly lease: FileLease
|
|
27
|
+
private readonly store: ProjectStore
|
|
28
|
+
private readonly logger: Logger
|
|
29
|
+
private readonly onChange?: (snapshot: TaskfeedSnapshot) => void | Promise<void>
|
|
30
|
+
private timer?: ReturnType<typeof setInterval>
|
|
31
|
+
private lastHeartbeat = 0
|
|
32
|
+
private lastAttempt = 0
|
|
33
|
+
private lastSnapshot = ""
|
|
34
|
+
private closed = false
|
|
35
|
+
private readonly canLead: boolean
|
|
36
|
+
private readonly worker?: FlowgraphWorker
|
|
37
|
+
private readonly disposeTrust?: () => Promise<void>
|
|
38
|
+
|
|
39
|
+
static async create(options: TaskfeedServiceOptions): Promise<TaskfeedService> {
|
|
40
|
+
const projectID = options.ctx.location.project.id
|
|
41
|
+
const canonical = options.ctx.location.project.canonical
|
|
42
|
+
const projectKey = projectKeyFor(projectID, canonical)
|
|
43
|
+
const runner = new NodeCommandRunner()
|
|
44
|
+
const lock = new FileMutex(await projectLockPath(projectKey, "state"), {
|
|
45
|
+
staleMs: 30_000,
|
|
46
|
+
waitMs: 10_000,
|
|
47
|
+
})
|
|
48
|
+
const kv = {
|
|
49
|
+
get: (key: string) => options.ctx.storage.get(key),
|
|
50
|
+
set: (key: string, value: never) => options.ctx.storage.set(key, value),
|
|
51
|
+
remove: (key: string) => options.ctx.storage.remove(key),
|
|
52
|
+
scan: (input: { prefix: string; after?: string; limit?: number }) => options.ctx.storage.scan(input),
|
|
53
|
+
}
|
|
54
|
+
const store = new ProjectStore({
|
|
55
|
+
kv,
|
|
56
|
+
projectKey,
|
|
57
|
+
lock,
|
|
58
|
+
})
|
|
59
|
+
const rawLimit = options.ctx.options.globalConcurrency
|
|
60
|
+
const limit =
|
|
61
|
+
typeof rawLimit === "number" && Number.isInteger(rawLimit) && rawLimit >= 1 && rawLimit <= 64 ? rawLimit : 1
|
|
62
|
+
const capacity = new CapacityManager(limit)
|
|
63
|
+
const lease = new FileLease(await projectLockPath(projectKey, "scheduler"), 30_000)
|
|
64
|
+
const leader = {
|
|
65
|
+
isLeader: () => lease.isLeader(),
|
|
66
|
+
heartbeat: () => lease.heartbeat(),
|
|
67
|
+
}
|
|
68
|
+
const bridge = new OpenCodeNativeBridge(options.ctx, options.logger)
|
|
69
|
+
const provider = new ServerBackendsProvider({
|
|
70
|
+
ctx: options.ctx,
|
|
71
|
+
bridge,
|
|
72
|
+
runner,
|
|
73
|
+
logger: options.logger,
|
|
74
|
+
projectID,
|
|
75
|
+
projectKey,
|
|
76
|
+
canonicalDirectory: canonical,
|
|
77
|
+
kv,
|
|
78
|
+
schedulerGeneration: () => lease.token,
|
|
79
|
+
})
|
|
80
|
+
const canLead = path.resolve(options.ctx.location.directory) === path.resolve(canonical)
|
|
81
|
+
const engine = new TaskfeedEngine({
|
|
82
|
+
projectID,
|
|
83
|
+
canonicalDirectory: canonical,
|
|
84
|
+
projectKey,
|
|
85
|
+
store,
|
|
86
|
+
capacity,
|
|
87
|
+
leader,
|
|
88
|
+
provider,
|
|
89
|
+
logger: options.logger,
|
|
90
|
+
canLead,
|
|
91
|
+
})
|
|
92
|
+
const worker = canLead
|
|
93
|
+
? undefined
|
|
94
|
+
: new FlowgraphWorker({
|
|
95
|
+
kv,
|
|
96
|
+
projectKey,
|
|
97
|
+
directory: options.ctx.location.directory,
|
|
98
|
+
client: options.ctx.rpc(FlowgraphRpc) as never,
|
|
99
|
+
trust: () => bridge.trustedContext(options.ctx.location.directory),
|
|
100
|
+
capacity,
|
|
101
|
+
logger: options.logger,
|
|
102
|
+
})
|
|
103
|
+
let disposeTrust: (() => Promise<void>) | undefined
|
|
104
|
+
if (!canLead) {
|
|
105
|
+
const definitions = await kv.get(trustedAgentsKey(projectKey)).catch(() => undefined)
|
|
106
|
+
if (definitions !== null && typeof definitions === "object" && !Array.isArray(definitions)) {
|
|
107
|
+
const registration = await options.ctx.agent.transform((editor) =>
|
|
108
|
+
applyTrustedAgents(editor as unknown as AgentEditorLike, definitions as Record<string, unknown>),
|
|
109
|
+
)
|
|
110
|
+
disposeTrust = () => registration.dispose()
|
|
111
|
+
} else {
|
|
112
|
+
options.logger.debug("Taskfeed worktree has no canonical agent snapshot yet; native execution is unaffected")
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return new TaskfeedService({
|
|
116
|
+
engine,
|
|
117
|
+
bridge,
|
|
118
|
+
lease,
|
|
119
|
+
store,
|
|
120
|
+
logger: options.logger,
|
|
121
|
+
canLead,
|
|
122
|
+
...(worker === undefined ? {} : { worker }),
|
|
123
|
+
...(disposeTrust === undefined ? {} : { disposeTrust }),
|
|
124
|
+
...(options.onChange === undefined ? {} : { onChange: options.onChange }),
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private constructor(input: {
|
|
129
|
+
engine: TaskfeedEngine
|
|
130
|
+
bridge: OpenCodeNativeBridge
|
|
131
|
+
lease: FileLease
|
|
132
|
+
store: ProjectStore
|
|
133
|
+
logger: Logger
|
|
134
|
+
canLead: boolean
|
|
135
|
+
worker?: FlowgraphWorker
|
|
136
|
+
disposeTrust?: () => Promise<void>
|
|
137
|
+
onChange?: (snapshot: TaskfeedSnapshot) => void | Promise<void>
|
|
138
|
+
}) {
|
|
139
|
+
this.engine = input.engine
|
|
140
|
+
this.bridge = input.bridge
|
|
141
|
+
this.lease = input.lease
|
|
142
|
+
this.store = input.store
|
|
143
|
+
this.logger = input.logger
|
|
144
|
+
this.canLead = input.canLead
|
|
145
|
+
this.worker = input.worker
|
|
146
|
+
this.disposeTrust = input.disposeTrust
|
|
147
|
+
this.onChange = input.onChange
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async start(): Promise<void> {
|
|
151
|
+
if (!this.canLead) {
|
|
152
|
+
await this.worker?.start()
|
|
153
|
+
this.logger.info("Taskfeed loaded as a worktree observer; scheduler ownership remains in the canonical checkout")
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
await this.attemptLeadership()
|
|
157
|
+
// Keep the first scheduling pass off the plugin setup path so location
|
|
158
|
+
// activation and RPC registration are never blocked by GitHub work.
|
|
159
|
+
setTimeout(() => void this.tick(), 2_000)
|
|
160
|
+
this.timer = setInterval(() => void this.tick(), 1_000)
|
|
161
|
+
this.timer.unref?.()
|
|
162
|
+
this.logger.info("Taskfeed scheduler started", {
|
|
163
|
+
plugin: PLUGIN_NAME,
|
|
164
|
+
version: PLUGIN_VERSION,
|
|
165
|
+
leader: await this.lease.isLeader(),
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async stop(): Promise<void> {
|
|
170
|
+
this.closed = true
|
|
171
|
+
if (this.timer) clearInterval(this.timer)
|
|
172
|
+
this.timer = undefined
|
|
173
|
+
await this.worker?.stop()
|
|
174
|
+
await this.disposeTrust?.()
|
|
175
|
+
const generation = this.lease.token
|
|
176
|
+
await this.lease.release()
|
|
177
|
+
if (generation) await this.store.clearSchedulerGeneration(generation).catch(() => undefined)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async snapshot(): Promise<TaskfeedSnapshot> {
|
|
181
|
+
return await this.engine.snapshot()
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async setEnabled(enabled: boolean): Promise<TaskfeedSnapshot> {
|
|
185
|
+
this.requireCanLead("change automation")
|
|
186
|
+
await this.engine.setEnabled(enabled)
|
|
187
|
+
await this.tick()
|
|
188
|
+
return await this.engine.snapshot()
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async setPaused(paused: boolean): Promise<TaskfeedSnapshot> {
|
|
192
|
+
this.requireCanLead("pause automation")
|
|
193
|
+
await this.engine.setPaused(paused)
|
|
194
|
+
return await this.engine.snapshot()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async refresh(): Promise<TaskfeedSnapshot> {
|
|
198
|
+
this.requireCanLead("refresh automation")
|
|
199
|
+
await this.engine.refresh()
|
|
200
|
+
return await this.engine.snapshot()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async requestControl(input: {
|
|
204
|
+
action: "dispatch" | "cancel" | "retry" | "cleanup_workspace" | "pause_workflow" | "resume_workflow"
|
|
205
|
+
jobID: string
|
|
206
|
+
}): Promise<TaskfeedSnapshot> {
|
|
207
|
+
this.requireCanLead(`request ${input.action}`)
|
|
208
|
+
await this.engine.requestControl({ ...input, requestedBy: "tui" })
|
|
209
|
+
await this.tick()
|
|
210
|
+
return await this.engine.snapshot()
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private requireCanLead(action: string): void {
|
|
214
|
+
if (!this.canLead) {
|
|
215
|
+
throw new Error(`Taskfeed cannot ${action} from a worktree observer; use the canonical checkout.`)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private async attemptLeadership(): Promise<void> {
|
|
220
|
+
if (!this.canLead || this.closed) return
|
|
221
|
+
if (await this.lease.isLeader()) {
|
|
222
|
+
if (this.lease.token) await this.store.setSchedulerGeneration(this.lease.token).catch(() => undefined)
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
const acquired = await this.lease.acquire()
|
|
226
|
+
if (acquired) {
|
|
227
|
+
if (this.lease.token) {
|
|
228
|
+
await this.store.setSchedulerGeneration(this.lease.token).catch((error) => {
|
|
229
|
+
this.logger.warn("could not publish the scheduler generation for Flowgraph workers", {
|
|
230
|
+
error: error instanceof Error ? error.message : String(error),
|
|
231
|
+
})
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
this.logger.info("Taskfeed acquired scheduler ownership")
|
|
235
|
+
this.lastHeartbeat = Date.now()
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private async tick(): Promise<void> {
|
|
240
|
+
if (this.closed || !this.canLead) return
|
|
241
|
+
const now = Date.now()
|
|
242
|
+
if (!(await this.lease.isLeader())) {
|
|
243
|
+
if (now - this.lastAttempt >= 5_000) {
|
|
244
|
+
this.lastAttempt = now
|
|
245
|
+
await this.attemptLeadership()
|
|
246
|
+
}
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
if (now - this.lastHeartbeat >= 5_000) {
|
|
250
|
+
this.lastHeartbeat = now
|
|
251
|
+
const generation = this.lease.token
|
|
252
|
+
if (!(await this.lease.heartbeat())) {
|
|
253
|
+
if (generation) await this.store.clearSchedulerGeneration(generation).catch(() => undefined)
|
|
254
|
+
this.logger.warn("Taskfeed scheduler ownership was lost")
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
await this.engine.tick()
|
|
259
|
+
await this.emitIfChanged()
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private async emitIfChanged(): Promise<void> {
|
|
263
|
+
if (!this.onChange) return
|
|
264
|
+
try {
|
|
265
|
+
const snapshot = await this.engine.snapshot()
|
|
266
|
+
const serialized = JSON.stringify(snapshot)
|
|
267
|
+
if (serialized === this.lastSnapshot) return
|
|
268
|
+
this.lastSnapshot = serialized
|
|
269
|
+
await this.onChange(snapshot)
|
|
270
|
+
} catch (error) {
|
|
271
|
+
this.logger.warn("could not emit Taskfeed snapshot", {
|
|
272
|
+
error: error instanceof Error ? error.message : String(error),
|
|
273
|
+
})
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { CommandRunner } from "../../util/process.js"
|
|
2
|
+
import { jsonCommand, runRequired } from "../../util/process.js"
|
|
3
|
+
import { redact } from "../../util/redact.js"
|
|
4
|
+
|
|
5
|
+
export class GitHubError extends Error {
|
|
6
|
+
readonly retryable: boolean
|
|
7
|
+
readonly code: "auth" | "rate_limit" | "not_found" | "forbidden" | "network" | "unknown"
|
|
8
|
+
|
|
9
|
+
constructor(
|
|
10
|
+
message: string,
|
|
11
|
+
code: GitHubError["code"],
|
|
12
|
+
retryable = false,
|
|
13
|
+
) {
|
|
14
|
+
super(redact(message))
|
|
15
|
+
this.name = "GitHubError"
|
|
16
|
+
this.code = code
|
|
17
|
+
this.retryable = retryable
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface GitHubClientOptions {
|
|
22
|
+
readonly runner: CommandRunner
|
|
23
|
+
readonly cwd: string
|
|
24
|
+
readonly timeoutMs?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RequestOptions {
|
|
28
|
+
readonly method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE"
|
|
29
|
+
readonly body?: unknown
|
|
30
|
+
readonly headers?: Record<string, string>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class GitHubClient {
|
|
34
|
+
constructor(private readonly options: GitHubClientOptions) {}
|
|
35
|
+
|
|
36
|
+
async gh<T = unknown>(args: readonly string[], input?: string): Promise<T> {
|
|
37
|
+
try {
|
|
38
|
+
const stdout = await runRequired(this.options.runner, "gh", [...args], {
|
|
39
|
+
cwd: this.options.cwd,
|
|
40
|
+
timeoutMs: this.options.timeoutMs ?? 30_000,
|
|
41
|
+
...(input === undefined ? {} : { stdin: input }),
|
|
42
|
+
})
|
|
43
|
+
if (stdout.trim() === "") return undefined as T
|
|
44
|
+
return jsonCommand<T>(stdout, "gh")
|
|
45
|
+
} catch (error) {
|
|
46
|
+
throw classify(error)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async api<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
|
|
51
|
+
const args = ["api", "--method", options.method ?? "GET", endpoint, "-H", "Accept: application/vnd.github+json"]
|
|
52
|
+
if (options.headers) for (const [key, value] of Object.entries(options.headers)) args.push("-H", `${key}: ${value}`)
|
|
53
|
+
if (options.body !== undefined) {
|
|
54
|
+
args.push("--input", "-")
|
|
55
|
+
return await this.gh<T>(args, JSON.stringify(options.body))
|
|
56
|
+
}
|
|
57
|
+
return await this.gh<T>(args)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async raw(args: readonly string[], timeoutMs = 120_000): Promise<string> {
|
|
61
|
+
try {
|
|
62
|
+
return await runRequired(this.options.runner, "gh", [...args], {
|
|
63
|
+
cwd: this.options.cwd,
|
|
64
|
+
timeoutMs,
|
|
65
|
+
})
|
|
66
|
+
} catch (error) {
|
|
67
|
+
throw classify(error)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function classify(error: unknown): GitHubError {
|
|
73
|
+
if (error instanceof GitHubError) return error
|
|
74
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
75
|
+
if (/auth|login|credential|token/iu.test(message) && !/rate limit/iu.test(message)) {
|
|
76
|
+
return new GitHubError(`GitHub authentication failed: ${message}`, "auth", false)
|
|
77
|
+
}
|
|
78
|
+
if (/rate limit|secondary rate|429|403/iu.test(message)) {
|
|
79
|
+
return new GitHubError(`GitHub request was rate limited: ${message}`, "rate_limit", true)
|
|
80
|
+
}
|
|
81
|
+
if (/not found|404/iu.test(message)) return new GitHubError(message, "not_found", false)
|
|
82
|
+
if (/forbidden|403/iu.test(message)) return new GitHubError(message, "forbidden", false)
|
|
83
|
+
if (/timed out|network|socket|ECONN|ENOTFOUND/iu.test(message)) {
|
|
84
|
+
return new GitHubError(message, "network", true)
|
|
85
|
+
}
|
|
86
|
+
return new GitHubError(message, "unknown", false)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function repositoryPath(repository: string): string {
|
|
90
|
+
const [owner, name] = repository.split("/")
|
|
91
|
+
if (!owner || !name) throw new Error("invalid GitHub repository")
|
|
92
|
+
return `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function issuePath(repository: string, issueNumber: number): string {
|
|
96
|
+
if (!Number.isSafeInteger(issueNumber) || issueNumber <= 0) throw new Error("invalid issue number")
|
|
97
|
+
return `${repositoryPath(repository)}/issues/${issueNumber}`
|
|
98
|
+
}
|