@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,145 @@
|
|
|
1
|
+
import { Rpc } from "@opencode/plugin/rpc"
|
|
2
|
+
import { z } from "zod"
|
|
3
|
+
import { ReviewArtifactSchema } from "../../core/types.js"
|
|
4
|
+
|
|
5
|
+
const Empty = z.object({}).strict()
|
|
6
|
+
|
|
7
|
+
const Workflow = z
|
|
8
|
+
.object({
|
|
9
|
+
id: z.string(),
|
|
10
|
+
name: z.string().optional(),
|
|
11
|
+
description: z.string().optional(),
|
|
12
|
+
valid: z.boolean(),
|
|
13
|
+
hash: z.string().optional(),
|
|
14
|
+
errors: z.array(z.object({ path: z.string(), message: z.string() })).default([]),
|
|
15
|
+
warnings: z.array(z.string()).default([]),
|
|
16
|
+
})
|
|
17
|
+
.passthrough()
|
|
18
|
+
|
|
19
|
+
const RunSummary = z
|
|
20
|
+
.object({
|
|
21
|
+
runID: z.string(),
|
|
22
|
+
workflowID: z.string(),
|
|
23
|
+
status: z.string(),
|
|
24
|
+
revision: z.number(),
|
|
25
|
+
runSessionID: z.string().nullable().optional(),
|
|
26
|
+
currentNode: z.string().nullable().optional(),
|
|
27
|
+
blocker: z.any().nullable().optional(),
|
|
28
|
+
failure: z.any().nullable().optional(),
|
|
29
|
+
usage: z.any().optional(),
|
|
30
|
+
})
|
|
31
|
+
.passthrough()
|
|
32
|
+
|
|
33
|
+
const Step = z
|
|
34
|
+
.object({
|
|
35
|
+
stepID: z.string(),
|
|
36
|
+
sessionID: z.string(),
|
|
37
|
+
nodeID: z.string().optional(),
|
|
38
|
+
status: z.string().optional(),
|
|
39
|
+
outcome: z.string().optional(),
|
|
40
|
+
})
|
|
41
|
+
.passthrough()
|
|
42
|
+
|
|
43
|
+
const Blocker = z
|
|
44
|
+
.object({
|
|
45
|
+
type: z.string(),
|
|
46
|
+
message: z.string(),
|
|
47
|
+
nodeID: z.string().optional(),
|
|
48
|
+
outcomes: z.array(z.string()).optional(),
|
|
49
|
+
artifact: ReviewArtifactSchema.optional(),
|
|
50
|
+
})
|
|
51
|
+
.passthrough()
|
|
52
|
+
|
|
53
|
+
const RunDetail = z
|
|
54
|
+
.object({
|
|
55
|
+
run: RunSummary.extend({
|
|
56
|
+
steps: z.array(Step).default([]),
|
|
57
|
+
}).passthrough(),
|
|
58
|
+
currentStep: z.any().nullable().optional(),
|
|
59
|
+
currentSteps: z.array(Step).optional(),
|
|
60
|
+
blockers: z.array(Blocker).optional(),
|
|
61
|
+
pendingPermissions: z.array(z.any()).default([]),
|
|
62
|
+
resumable: z.boolean().optional(),
|
|
63
|
+
readOnly: z.literal(true).optional(),
|
|
64
|
+
})
|
|
65
|
+
.passthrough()
|
|
66
|
+
|
|
67
|
+
const Control = z
|
|
68
|
+
.object({
|
|
69
|
+
runID: z.string(),
|
|
70
|
+
requestID: z.string(),
|
|
71
|
+
expectedRevision: z.number(),
|
|
72
|
+
})
|
|
73
|
+
.strict()
|
|
74
|
+
|
|
75
|
+
export const FlowgraphRpc = Rpc.define({
|
|
76
|
+
id: "flowgraph",
|
|
77
|
+
methods: {
|
|
78
|
+
capabilities: {
|
|
79
|
+
input: Empty.optional(),
|
|
80
|
+
output: z
|
|
81
|
+
.object({
|
|
82
|
+
plugin: z.object({ name: z.string(), version: z.string() }).passthrough(),
|
|
83
|
+
rpc: z.object({ id: z.literal("flowgraph"), version: z.literal(1) }).passthrough(),
|
|
84
|
+
})
|
|
85
|
+
.passthrough(),
|
|
86
|
+
},
|
|
87
|
+
listWorkflows: {
|
|
88
|
+
input: Empty.optional(),
|
|
89
|
+
output: z.object({ workflows: z.array(Workflow), directory: z.string() }).passthrough(),
|
|
90
|
+
},
|
|
91
|
+
startRun: {
|
|
92
|
+
input: z.object({ workflowID: z.string(), objective: z.string(), requestID: z.string() }).strict(),
|
|
93
|
+
output: z.object({ runID: z.string(), status: z.string(), revision: z.number() }).passthrough(),
|
|
94
|
+
},
|
|
95
|
+
getRun: {
|
|
96
|
+
input: z.object({ runID: z.string() }).strict(),
|
|
97
|
+
output: RunDetail,
|
|
98
|
+
},
|
|
99
|
+
getRunStep: {
|
|
100
|
+
input: z.object({ runID: z.string(), stepID: z.string() }).strict(),
|
|
101
|
+
output: z
|
|
102
|
+
.object({
|
|
103
|
+
stepID: z.string(),
|
|
104
|
+
nodeID: z.string().optional(),
|
|
105
|
+
result: z
|
|
106
|
+
.object({
|
|
107
|
+
outcome: z.string().optional(),
|
|
108
|
+
summary: z.string().optional(),
|
|
109
|
+
feedback: z.string().optional(),
|
|
110
|
+
evidence: z.array(z.object({ kind: z.string(), value: z.string() })).optional(),
|
|
111
|
+
})
|
|
112
|
+
.passthrough()
|
|
113
|
+
.optional(),
|
|
114
|
+
})
|
|
115
|
+
.passthrough(),
|
|
116
|
+
},
|
|
117
|
+
respondRun: {
|
|
118
|
+
input: Control.extend({
|
|
119
|
+
nodeID: z.string().optional(),
|
|
120
|
+
outcome: z.string(),
|
|
121
|
+
summary: z.string().optional(),
|
|
122
|
+
feedback: z.string().optional(),
|
|
123
|
+
}).strict(),
|
|
124
|
+
output: z.object({ run: RunSummary }).passthrough(),
|
|
125
|
+
},
|
|
126
|
+
pauseRun: {
|
|
127
|
+
input: Control,
|
|
128
|
+
output: z.object({ run: RunSummary }).passthrough(),
|
|
129
|
+
},
|
|
130
|
+
resumeRun: {
|
|
131
|
+
input: Control.extend({ confirmRetry: z.boolean().optional() }).strict(),
|
|
132
|
+
output: z.object({ run: RunSummary }).passthrough(),
|
|
133
|
+
},
|
|
134
|
+
cancelRun: {
|
|
135
|
+
input: Control,
|
|
136
|
+
output: z.object({ run: RunSummary }).passthrough(),
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
events: {},
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
export type FlowgraphRpcDefinition = typeof FlowgraphRpc
|
|
143
|
+
export type FlowgraphRunDetail = z.infer<typeof RunDetail>
|
|
144
|
+
export type FlowgraphRun = z.infer<typeof RunSummary>
|
|
145
|
+
export type FlowgraphStep = z.infer<typeof Step>
|
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { z } from "zod"
|
|
3
|
+
import type { Logger } from "../../util/logger.js"
|
|
4
|
+
import type { KVPort } from "../../storage/jobs.js"
|
|
5
|
+
import { FileMutex, isLockOwnerCurrent, projectLockPath, taskfeedRoot } from "../../storage/locks.js"
|
|
6
|
+
import { stableHash, uuid } from "../../util/ids.js"
|
|
7
|
+
import type { TrustedContextSnapshot } from "../native/bridge.js"
|
|
8
|
+
import type { CapacityPort } from "../../core/ports.js"
|
|
9
|
+
import { JobSchema } from "../../core/types.js"
|
|
10
|
+
|
|
11
|
+
const TrustSnapshot = z
|
|
12
|
+
.object({
|
|
13
|
+
agents: z.record(z.string(), z.string()),
|
|
14
|
+
plugins: z.record(z.string(), z.string()),
|
|
15
|
+
configHash: z.string(),
|
|
16
|
+
})
|
|
17
|
+
.strict()
|
|
18
|
+
|
|
19
|
+
export const WorkerRequestSchema = z
|
|
20
|
+
.object({
|
|
21
|
+
version: z.literal(1),
|
|
22
|
+
id: z.string().min(1),
|
|
23
|
+
method: z.enum([
|
|
24
|
+
"capabilities",
|
|
25
|
+
"listWorkflows",
|
|
26
|
+
"startRun",
|
|
27
|
+
"getRun",
|
|
28
|
+
"getRunStep",
|
|
29
|
+
"respondRun",
|
|
30
|
+
"pauseRun",
|
|
31
|
+
"resumeRun",
|
|
32
|
+
"cancelRun",
|
|
33
|
+
]),
|
|
34
|
+
input: z.unknown().optional(),
|
|
35
|
+
directory: z.string().min(1),
|
|
36
|
+
createdAt: z.number().int().nonnegative(),
|
|
37
|
+
expiresAt: z.number().int().nonnegative(),
|
|
38
|
+
generation: z.string().min(1),
|
|
39
|
+
trust: TrustSnapshot.optional(),
|
|
40
|
+
})
|
|
41
|
+
.strict()
|
|
42
|
+
|
|
43
|
+
export type WorkerRequest = z.infer<typeof WorkerRequestSchema>
|
|
44
|
+
|
|
45
|
+
export const WorkerResponseSchema = z
|
|
46
|
+
.object({
|
|
47
|
+
version: z.literal(1),
|
|
48
|
+
id: z.string().min(1),
|
|
49
|
+
ok: z.boolean(),
|
|
50
|
+
output: z.unknown().optional(),
|
|
51
|
+
error: z.string().optional(),
|
|
52
|
+
errorCode: z
|
|
53
|
+
.enum(["expired", "cancelled", "obsolete_generation", "untrusted_context", "claim_lost", "job_mismatch", "capacity_missing", "failed"])
|
|
54
|
+
.optional(),
|
|
55
|
+
completedAt: z.number().int().nonnegative(),
|
|
56
|
+
})
|
|
57
|
+
.strict()
|
|
58
|
+
|
|
59
|
+
type WorkerResponse = z.infer<typeof WorkerResponseSchema>
|
|
60
|
+
type Method = WorkerRequest["method"]
|
|
61
|
+
|
|
62
|
+
const METHODS: readonly Method[] = [
|
|
63
|
+
"capabilities",
|
|
64
|
+
"listWorkflows",
|
|
65
|
+
"startRun",
|
|
66
|
+
"getRun",
|
|
67
|
+
"getRunStep",
|
|
68
|
+
"respondRun",
|
|
69
|
+
"pauseRun",
|
|
70
|
+
"resumeRun",
|
|
71
|
+
"cancelRun",
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
const SIDE_EFFECTS = new Set<Method>(["startRun", "respondRun", "pauseRun", "resumeRun", "cancelRun"])
|
|
75
|
+
|
|
76
|
+
function workerKey(projectKey: string, directory: string): string {
|
|
77
|
+
return stableHash(`${projectKey}\0${directory}`, 40)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function workerReadyKey(projectKey: string, directory: string): string {
|
|
81
|
+
return `flowgraph-worker/${projectKey}/ready/${workerKey(projectKey, directory)}`
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function workerRequestPrefix(projectKey: string, directory: string): string {
|
|
85
|
+
return `flowgraph-worker/${projectKey}/requests/${workerKey(projectKey, directory)}/`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function workerResponseKey(projectKey: string, directory: string, id: string): string {
|
|
89
|
+
return `flowgraph-worker/${projectKey}/responses/${workerKey(projectKey, directory)}/${id}`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function workerCancelKey(projectKey: string, directory: string, id: string): string {
|
|
93
|
+
return `flowgraph-worker/${projectKey}/cancelled/${workerKey(projectKey, directory)}/${id}`
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function workerSchedulerGenerationKey(projectKey: string): string {
|
|
97
|
+
return `${projectKey}/scheduler-generation`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function workerAdmissionKey(projectKey: string, directory: string, id: string): string {
|
|
101
|
+
return `flowgraph-worker/${projectKey}/admitted/${workerKey(projectKey, directory)}/${id}`
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function requestFingerprint(request: WorkerRequest): string {
|
|
105
|
+
return stableHash(JSON.stringify({ method: request.method, input: request.input, directory: request.directory }), 64)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function sameTrust(left: TrustedContextSnapshot, right: TrustedContextSnapshot): boolean {
|
|
109
|
+
return (
|
|
110
|
+
JSON.stringify(left.agents) === JSON.stringify(right.agents) &&
|
|
111
|
+
JSON.stringify(left.plugins) === JSON.stringify(right.plugins) &&
|
|
112
|
+
left.configHash === right.configHash
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A non-canonical Taskfeed instance proxies Flowgraph RPC for its own location.
|
|
118
|
+
* Server plugins cannot pass another location to ctx.rpc, so this storage-backed
|
|
119
|
+
* worker is the supported way to invoke the location-scoped Flowgraph plugin.
|
|
120
|
+
* Requests carry an expiry, scheduler generation and trusted-context snapshot.
|
|
121
|
+
* A local file lease claims one request per worker; a crash leaves the request
|
|
122
|
+
* in place and the next worker retries it. Flowgraph's deterministic requestID
|
|
123
|
+
* remains the final idempotency boundary for side effects.
|
|
124
|
+
*/
|
|
125
|
+
type LocalClient = Readonly<Record<string, ((input?: unknown) => Promise<unknown>) | undefined>>
|
|
126
|
+
|
|
127
|
+
export class FlowgraphWorker {
|
|
128
|
+
private readonly client: LocalClient
|
|
129
|
+
private timer?: ReturnType<typeof setInterval>
|
|
130
|
+
private running = false
|
|
131
|
+
private lastReadyAt = 0
|
|
132
|
+
private claimRoot?: string
|
|
133
|
+
|
|
134
|
+
constructor(
|
|
135
|
+
private readonly options: {
|
|
136
|
+
readonly kv: KVPort
|
|
137
|
+
readonly projectKey: string
|
|
138
|
+
readonly directory: string
|
|
139
|
+
readonly client: LocalClient
|
|
140
|
+
readonly logger: Logger
|
|
141
|
+
readonly trust?: () => Promise<TrustedContextSnapshot>
|
|
142
|
+
readonly capacity?: CapacityPort
|
|
143
|
+
readonly schedulerLease?: (generation: string) => Promise<boolean>
|
|
144
|
+
readonly claimRoot?: string
|
|
145
|
+
readonly now?: () => number
|
|
146
|
+
},
|
|
147
|
+
) {
|
|
148
|
+
this.client = options.client
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private now(): number {
|
|
152
|
+
return this.options.now?.() ?? Date.now()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async start(): Promise<void> {
|
|
156
|
+
this.claimRoot = this.options.claimRoot ?? (await taskfeedRoot())
|
|
157
|
+
await this.heartbeat()
|
|
158
|
+
this.timer = setInterval(() => void this.tick(), 250)
|
|
159
|
+
this.timer.unref?.()
|
|
160
|
+
await this.tick()
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async stop(): Promise<void> {
|
|
164
|
+
if (this.timer) clearInterval(this.timer)
|
|
165
|
+
this.timer = undefined
|
|
166
|
+
await this.options.kv.remove(workerReadyKey(this.options.projectKey, this.options.directory)).catch(() => undefined)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private async heartbeat(): Promise<void> {
|
|
170
|
+
if (Date.now() - this.lastReadyAt < 2_000) return
|
|
171
|
+
this.lastReadyAt = Date.now()
|
|
172
|
+
await this.options.kv
|
|
173
|
+
.set(workerReadyKey(this.options.projectKey, this.options.directory), {
|
|
174
|
+
directory: this.options.directory,
|
|
175
|
+
pid: process.pid,
|
|
176
|
+
at: this.lastReadyAt,
|
|
177
|
+
} as never)
|
|
178
|
+
.catch(() => undefined)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async tick(): Promise<void> {
|
|
182
|
+
if (this.running) return
|
|
183
|
+
this.running = true
|
|
184
|
+
try {
|
|
185
|
+
await this.heartbeat()
|
|
186
|
+
const prefix = workerRequestPrefix(this.options.projectKey, this.options.directory)
|
|
187
|
+
let after: string | undefined
|
|
188
|
+
for (;;) {
|
|
189
|
+
const page = await this.options.kv.scan({ prefix, ...(after === undefined ? {} : { after }), limit: 20 })
|
|
190
|
+
for (const entry of page.entries) {
|
|
191
|
+
await this.process(entry.key, entry.value)
|
|
192
|
+
}
|
|
193
|
+
if (page.next === undefined) break
|
|
194
|
+
after = page.next
|
|
195
|
+
}
|
|
196
|
+
} catch (error) {
|
|
197
|
+
this.options.logger.warn("Flowgraph location worker failed", {
|
|
198
|
+
error: error instanceof Error ? error.message : String(error),
|
|
199
|
+
})
|
|
200
|
+
} finally {
|
|
201
|
+
this.running = false
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private async process(key: string, value: unknown): Promise<void> {
|
|
206
|
+
const parsed = WorkerRequestSchema.safeParse(value)
|
|
207
|
+
if (!parsed.success) {
|
|
208
|
+
await this.options.kv.remove(key).catch(() => undefined)
|
|
209
|
+
return
|
|
210
|
+
}
|
|
211
|
+
const request = parsed.data
|
|
212
|
+
if (request.directory !== this.options.directory || !METHODS.includes(request.method)) {
|
|
213
|
+
await this.options.kv.remove(key).catch(() => undefined)
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
const responseKey = workerResponseKey(this.options.projectKey, this.options.directory, request.id)
|
|
217
|
+
if ((await this.options.kv.get(responseKey)) !== undefined) {
|
|
218
|
+
await this.options.kv.remove(key).catch(() => undefined)
|
|
219
|
+
return
|
|
220
|
+
}
|
|
221
|
+
const claim = await this.claim(request.id)
|
|
222
|
+
if (!claim) return
|
|
223
|
+
let heartbeat: ReturnType<typeof setInterval> | undefined
|
|
224
|
+
try {
|
|
225
|
+
const current = WorkerRequestSchema.safeParse(await this.options.kv.get(key))
|
|
226
|
+
if (!current.success) return
|
|
227
|
+
const claimed = current.data
|
|
228
|
+
const admissionKey = workerAdmissionKey(this.options.projectKey, this.options.directory, claimed.id)
|
|
229
|
+
const admissionValue = await this.options.kv.get(admissionKey)
|
|
230
|
+
const admitted = admissionValue !== undefined
|
|
231
|
+
if (admitted) {
|
|
232
|
+
const record = admissionValue as { fingerprint?: unknown }
|
|
233
|
+
if (record?.fingerprint !== requestFingerprint(claimed)) {
|
|
234
|
+
await this.respond(key, claimed, this.failure(claimed, "job_mismatch", "Flowgraph request ID was reused for a different operation"))
|
|
235
|
+
return
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (SIDE_EFFECTS.has(claimed.method) && claimed.method !== "cancelRun") {
|
|
239
|
+
if (!claimed.trust || !this.options.trust) {
|
|
240
|
+
await this.respond(key, claimed, this.failure(claimed, "untrusted_context", "Flowgraph side effects require a trusted context snapshot"))
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
const currentTrust = await this.options.trust()
|
|
244
|
+
if (!sameTrust(currentTrust, claimed.trust)) {
|
|
245
|
+
await this.respond(key, claimed, this.failure(claimed, "untrusted_context", "Worktree agent or plugin definitions no longer match the canonical snapshot"))
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const rejected = await this.preconditions(key, claimed, claim, admitted)
|
|
250
|
+
if (rejected) {
|
|
251
|
+
await this.respond(key, claimed, rejected)
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
if (!admitted && SIDE_EFFECTS.has(claimed.method)) {
|
|
255
|
+
await this.options.kv.set(admissionKey, {
|
|
256
|
+
id: claimed.id,
|
|
257
|
+
at: this.now(),
|
|
258
|
+
generation: claimed.generation,
|
|
259
|
+
fingerprint: requestFingerprint(claimed),
|
|
260
|
+
} as never)
|
|
261
|
+
}
|
|
262
|
+
heartbeat = setInterval(() => void claim.heartbeat(), 5_000)
|
|
263
|
+
heartbeat.unref?.()
|
|
264
|
+
const response = await this.execute(claimed)
|
|
265
|
+
await this.respond(key, claimed, response)
|
|
266
|
+
} finally {
|
|
267
|
+
if (heartbeat) clearInterval(heartbeat)
|
|
268
|
+
await claim.release().catch(() => undefined)
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private async preconditions(
|
|
273
|
+
key: string,
|
|
274
|
+
request: WorkerRequest,
|
|
275
|
+
claim: Awaited<ReturnType<FlowgraphWorker["claim"]>>,
|
|
276
|
+
admitted: boolean,
|
|
277
|
+
): Promise<WorkerResponse | undefined> {
|
|
278
|
+
const current = WorkerRequestSchema.safeParse(await this.options.kv.get(key))
|
|
279
|
+
if (!current.success || current.data.id !== request.id) {
|
|
280
|
+
return this.failure(request, "job_mismatch", "Flowgraph request disappeared or changed before admission")
|
|
281
|
+
}
|
|
282
|
+
const latest = current.data
|
|
283
|
+
if (!admitted) {
|
|
284
|
+
if (this.now() > latest.expiresAt) return this.failure(request, "expired", "Flowgraph worker request expired")
|
|
285
|
+
if ((await this.options.kv.get(workerCancelKey(this.options.projectKey, this.options.directory, request.id))) !== undefined) {
|
|
286
|
+
return this.failure(request, "cancelled", "Flowgraph worker request was cancelled")
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (!(await claim?.isHeld())) return this.failure(request, "claim_lost", "Flowgraph worker claim was lost before admission")
|
|
290
|
+
const generation = await this.options.kv.get(workerSchedulerGenerationKey(this.options.projectKey))
|
|
291
|
+
if (generation !== request.generation) {
|
|
292
|
+
return this.failure(request, "obsolete_generation", "Flowgraph request belongs to an obsolete scheduler generation")
|
|
293
|
+
}
|
|
294
|
+
const leaseValid = this.options.schedulerLease
|
|
295
|
+
? await this.options.schedulerLease(request.generation)
|
|
296
|
+
: await isLockOwnerCurrent(await projectLockPath(this.options.projectKey, "scheduler"), request.generation)
|
|
297
|
+
if (!leaseValid) {
|
|
298
|
+
return this.failure(request, "obsolete_generation", "The Taskfeed scheduler lease is no longer valid")
|
|
299
|
+
}
|
|
300
|
+
if (!SIDE_EFFECTS.has(request.method)) return undefined
|
|
301
|
+
const input = request.input !== null && typeof request.input === "object" ? (request.input as Record<string, unknown>) : {}
|
|
302
|
+
const requestID = typeof input.requestID === "string" ? input.requestID : ""
|
|
303
|
+
const match = /^tf:([^:]+):(\d+)(?::|$)/u.exec(requestID)
|
|
304
|
+
if (!match) return this.failure(request, "job_mismatch", "Flowgraph side effect has no Taskfeed job identity")
|
|
305
|
+
const jobID = match[1]!
|
|
306
|
+
const attempt = Number(match[2])
|
|
307
|
+
const stored = await this.options.kv.get(`${this.options.projectKey}/jobs/${jobID}`)
|
|
308
|
+
const job = JobSchema.safeParse(stored)
|
|
309
|
+
if (!job.success || job.data.workspace?.directory !== request.directory) {
|
|
310
|
+
return this.failure(request, "job_mismatch", "Flowgraph request does not match the admitted job and worktree")
|
|
311
|
+
}
|
|
312
|
+
if (attempt > 0 && job.data.attempts !== attempt) {
|
|
313
|
+
return this.failure(request, "job_mismatch", "Flowgraph request belongs to a different execution attempt")
|
|
314
|
+
}
|
|
315
|
+
if (request.method !== "startRun" && input.runID !== job.data.executionRef?.runID) {
|
|
316
|
+
return this.failure(request, "job_mismatch", "Flowgraph request does not match the recorded run")
|
|
317
|
+
}
|
|
318
|
+
if (request.method === "startRun" && !["starting", "running"].includes(job.data.status)) {
|
|
319
|
+
return this.failure(request, "job_mismatch", "Flowgraph start is not admissible for the current job state")
|
|
320
|
+
}
|
|
321
|
+
const capacity = job.data.capacity
|
|
322
|
+
if (!capacity) {
|
|
323
|
+
if (request.method === "cancelRun") return undefined
|
|
324
|
+
return this.failure(request, "capacity_missing", "Flowgraph side effect has no reserved execution capacity")
|
|
325
|
+
}
|
|
326
|
+
if (!this.options.capacity) {
|
|
327
|
+
return this.failure(request, "capacity_missing", "Flowgraph worker has no capacity verifier")
|
|
328
|
+
}
|
|
329
|
+
if (!(await this.options.capacity.heartbeat({
|
|
330
|
+
projectKey: this.options.projectKey,
|
|
331
|
+
jobID,
|
|
332
|
+
token: capacity.token,
|
|
333
|
+
generation: capacity.generation,
|
|
334
|
+
}))) {
|
|
335
|
+
return this.failure(request, "capacity_missing", "Flowgraph execution capacity reservation is no longer owned")
|
|
336
|
+
}
|
|
337
|
+
return undefined
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private async claim(id: string) {
|
|
341
|
+
if (!this.claimRoot) return undefined
|
|
342
|
+
const mutex = new FileMutex(
|
|
343
|
+
path.join(this.claimRoot, "flowgraph-worker", workerKey(this.options.projectKey, this.options.directory), `${stableHash(id, 40)}.lock`),
|
|
344
|
+
{ staleMs: 30_000, waitMs: 0 },
|
|
345
|
+
)
|
|
346
|
+
return await mutex.tryAcquire()
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private failure(request: WorkerRequest, errorCode: NonNullable<WorkerResponse["errorCode"]>, error: string): WorkerResponse {
|
|
350
|
+
return { version: 1, id: request.id, ok: false, error, errorCode, completedAt: this.now() }
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private async respond(key: string, request: WorkerRequest, response: WorkerResponse): Promise<void> {
|
|
354
|
+
try {
|
|
355
|
+
await this.options.kv.set(
|
|
356
|
+
workerResponseKey(this.options.projectKey, this.options.directory, request.id),
|
|
357
|
+
response as never,
|
|
358
|
+
)
|
|
359
|
+
await this.options.kv.remove(key).catch(() => undefined)
|
|
360
|
+
} catch (error) {
|
|
361
|
+
this.options.logger.warn("Flowgraph worker could not publish its response; the request will be retried", {
|
|
362
|
+
requestID: request.id,
|
|
363
|
+
error: error instanceof Error ? error.message : String(error),
|
|
364
|
+
})
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private async execute(request: WorkerRequest): Promise<WorkerResponse> {
|
|
369
|
+
try {
|
|
370
|
+
const method = this.client[request.method]
|
|
371
|
+
if (typeof method !== "function") throw new Error(`Flowgraph RPC method unavailable: ${request.method}`)
|
|
372
|
+
const output = await method(request.input)
|
|
373
|
+
return {
|
|
374
|
+
version: 1,
|
|
375
|
+
id: request.id,
|
|
376
|
+
ok: true,
|
|
377
|
+
output,
|
|
378
|
+
completedAt: this.now(),
|
|
379
|
+
}
|
|
380
|
+
} catch (error) {
|
|
381
|
+
return {
|
|
382
|
+
version: 1,
|
|
383
|
+
id: request.id,
|
|
384
|
+
ok: false,
|
|
385
|
+
error: error instanceof Error ? error.message : String(error),
|
|
386
|
+
errorCode: "failed",
|
|
387
|
+
completedAt: this.now(),
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Routes canonical validation calls to the canonical Flowgraph instance and
|
|
395
|
+
* execution calls to a worker loaded at the requested worktree location.
|
|
396
|
+
*/
|
|
397
|
+
export class WorkerFlowgraphClient {
|
|
398
|
+
private readonly kv: KVPort
|
|
399
|
+
private readonly projectKey: string
|
|
400
|
+
private readonly canonicalDirectory: string
|
|
401
|
+
private readonly localClient: LocalClient
|
|
402
|
+
private readonly logger: Logger
|
|
403
|
+
private readonly timeoutMs: number
|
|
404
|
+
private readonly readyTimeoutMs: number
|
|
405
|
+
private readonly generation: () => string | undefined
|
|
406
|
+
private readonly trust?: () => Promise<TrustedContextSnapshot>
|
|
407
|
+
private readonly now: () => number
|
|
408
|
+
|
|
409
|
+
constructor(options: {
|
|
410
|
+
kv: KVPort
|
|
411
|
+
projectKey: string
|
|
412
|
+
canonicalDirectory: string
|
|
413
|
+
localClient: LocalClient
|
|
414
|
+
logger: Logger
|
|
415
|
+
generation: () => string | undefined
|
|
416
|
+
trust?: () => Promise<TrustedContextSnapshot>
|
|
417
|
+
timeoutMs?: number
|
|
418
|
+
readyTimeoutMs?: number
|
|
419
|
+
now?: () => number
|
|
420
|
+
}) {
|
|
421
|
+
this.kv = options.kv
|
|
422
|
+
this.projectKey = options.projectKey
|
|
423
|
+
this.canonicalDirectory = options.canonicalDirectory
|
|
424
|
+
this.localClient = options.localClient
|
|
425
|
+
this.logger = options.logger
|
|
426
|
+
this.timeoutMs = options.timeoutMs ?? 60_000
|
|
427
|
+
this.readyTimeoutMs = options.readyTimeoutMs ?? 20_000
|
|
428
|
+
this.generation = options.generation
|
|
429
|
+
this.trust = options.trust
|
|
430
|
+
this.now = options.now ?? Date.now
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private async call(method: Method, input: unknown, directory?: string): Promise<unknown> {
|
|
434
|
+
if (!directory || directory === this.canonicalDirectory) {
|
|
435
|
+
const local = this.localClient[method]
|
|
436
|
+
if (typeof local !== "function") throw new Error(`Flowgraph RPC method unavailable: ${method}`)
|
|
437
|
+
return await local(input)
|
|
438
|
+
}
|
|
439
|
+
const readyKey = workerReadyKey(this.projectKey, directory)
|
|
440
|
+
const deadline = this.now() + this.readyTimeoutMs
|
|
441
|
+
for (;;) {
|
|
442
|
+
const ready = await this.kv.get(readyKey)
|
|
443
|
+
if (ready !== undefined) {
|
|
444
|
+
const at =
|
|
445
|
+
ready !== null && typeof ready === "object" && "at" in ready && typeof ready.at === "number" ? ready.at : 0
|
|
446
|
+
if (this.now() - at < 30_000) break
|
|
447
|
+
}
|
|
448
|
+
if (this.now() >= deadline) {
|
|
449
|
+
throw new Error(
|
|
450
|
+
`No Taskfeed Flowgraph worker is active at ${directory}. Configure Taskfeed and Flowgraph globally or commit their plugin config so the worktree location can load them.`,
|
|
451
|
+
)
|
|
452
|
+
}
|
|
453
|
+
await new Promise((resolve) => setTimeout(resolve, 250))
|
|
454
|
+
}
|
|
455
|
+
const id = `fgrpc_${uuid()}`
|
|
456
|
+
const generation = this.generation()
|
|
457
|
+
if (!generation) throw new Error("Taskfeed scheduler generation is unavailable; refusing a Flowgraph side effect")
|
|
458
|
+
const snapshot = SIDE_EFFECTS.has(method) ? await this.trust?.() : undefined
|
|
459
|
+
const trust = snapshot ? { agents: snapshot.agents, plugins: snapshot.plugins, configHash: snapshot.configHash } : undefined
|
|
460
|
+
if (SIDE_EFFECTS.has(method) && !trust) {
|
|
461
|
+
throw new Error("Taskfeed cannot establish a canonical trusted context for the Flowgraph worker")
|
|
462
|
+
}
|
|
463
|
+
const request: WorkerRequest = {
|
|
464
|
+
version: 1,
|
|
465
|
+
id,
|
|
466
|
+
method,
|
|
467
|
+
...(input === undefined ? {} : { input }),
|
|
468
|
+
directory,
|
|
469
|
+
createdAt: this.now(),
|
|
470
|
+
expiresAt: this.now() + this.timeoutMs,
|
|
471
|
+
generation,
|
|
472
|
+
...(trust === undefined ? {} : { trust }),
|
|
473
|
+
}
|
|
474
|
+
const requestKey = `${workerRequestPrefix(this.projectKey, directory)}${id}`
|
|
475
|
+
await this.kv.set(requestKey, request as never)
|
|
476
|
+
const responseKey = workerResponseKey(this.projectKey, directory, id)
|
|
477
|
+
const responseDeadline = this.now() + this.timeoutMs
|
|
478
|
+
try {
|
|
479
|
+
for (;;) {
|
|
480
|
+
const value = await this.kv.get(responseKey)
|
|
481
|
+
if (value !== undefined) {
|
|
482
|
+
const response = WorkerResponseSchema.safeParse(value)
|
|
483
|
+
if (!response.success) throw new Error("Flowgraph worker returned an invalid response")
|
|
484
|
+
if (!response.data.ok) throw new Error(response.data.error ?? `Flowgraph ${method} failed`)
|
|
485
|
+
return response.data.output
|
|
486
|
+
}
|
|
487
|
+
if (this.now() >= responseDeadline) {
|
|
488
|
+
await this.cancel(directory, id)
|
|
489
|
+
throw new Error(`Flowgraph ${method} timed out in the worktree worker`)
|
|
490
|
+
}
|
|
491
|
+
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
492
|
+
}
|
|
493
|
+
} catch (error) {
|
|
494
|
+
throw error
|
|
495
|
+
} finally {
|
|
496
|
+
await this.kv.remove(responseKey).catch(() => undefined)
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private async cancel(directory: string, id: string): Promise<void> {
|
|
501
|
+
await this.kv
|
|
502
|
+
.set(workerCancelKey(this.projectKey, directory, id), {
|
|
503
|
+
id,
|
|
504
|
+
at: this.now(),
|
|
505
|
+
expiresAt: this.now() + this.timeoutMs,
|
|
506
|
+
} as never)
|
|
507
|
+
.catch(() => undefined)
|
|
508
|
+
await this.kv.remove(`${workerRequestPrefix(this.projectKey, directory)}${id}`).catch(() => undefined)
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async capabilities(input?: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
512
|
+
return await this.call("capabilities", input, options?.location?.directory)
|
|
513
|
+
}
|
|
514
|
+
async listWorkflows(input?: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
515
|
+
return await this.call("listWorkflows", input, options?.location?.directory)
|
|
516
|
+
}
|
|
517
|
+
async startRun(input: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
518
|
+
return await this.call("startRun", input, options?.location?.directory)
|
|
519
|
+
}
|
|
520
|
+
async getRun(input: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
521
|
+
return await this.call("getRun", input, options?.location?.directory)
|
|
522
|
+
}
|
|
523
|
+
async getRunStep(input: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
524
|
+
return await this.call("getRunStep", input, options?.location?.directory)
|
|
525
|
+
}
|
|
526
|
+
async respondRun(input: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
527
|
+
return await this.call("respondRun", input, options?.location?.directory)
|
|
528
|
+
}
|
|
529
|
+
async pauseRun(input: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
530
|
+
return await this.call("pauseRun", input, options?.location?.directory)
|
|
531
|
+
}
|
|
532
|
+
async resumeRun(input: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
533
|
+
return await this.call("resumeRun", input, options?.location?.directory)
|
|
534
|
+
}
|
|
535
|
+
async cancelRun(input: unknown, options?: { location?: { directory?: string } }): Promise<unknown> {
|
|
536
|
+
return await this.call("cancelRun", input, options?.location?.directory)
|
|
537
|
+
}
|
|
538
|
+
}
|