@kontourai/flow-agents 3.4.3 → 3.6.0
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/.github/workflows/ci.yml +4 -0
- package/CHANGELOG.md +15 -0
- package/build/src/builder-flow-run-adapter.d.ts +10 -1
- package/build/src/builder-flow-run-adapter.js +29 -1
- package/build/src/builder-flow-runtime.d.ts +18 -0
- package/build/src/builder-flow-runtime.js +205 -13
- package/build/src/builder-lifecycle-authority.d.ts +35 -0
- package/build/src/builder-lifecycle-authority.js +219 -0
- package/build/src/cli/assignment-provider.d.ts +13 -0
- package/build/src/cli/assignment-provider.js +120 -62
- package/build/src/cli/builder-run.js +46 -5
- package/build/src/cli/workflow-artifact-cleanup-audit.js +3 -0
- package/build/src/cli/workflow-sidecar.d.ts +3 -0
- package/build/src/cli/workflow-sidecar.js +140 -30
- package/build/src/cli/workflow.d.ts +2 -0
- package/build/src/cli/workflow.js +521 -0
- package/build/src/cli.js +2 -0
- package/build/src/index.d.ts +4 -0
- package/build/src/index.js +2 -0
- package/build/src/lib/flow-resolver.js +7 -2
- package/build/src/lib/package-version.d.ts +2 -0
- package/build/src/lib/package-version.js +13 -0
- package/build/src/lib/pinned-cli-command.d.ts +6 -0
- package/build/src/lib/pinned-cli-command.js +21 -0
- package/context/contracts/artifact-contract.md +1 -1
- package/context/contracts/assignment-provider-contract.md +5 -2
- package/context/scripts/hooks/config-protection.js +8 -1
- package/context/scripts/hooks/lib/config-protection-remedies.js +3 -0
- package/context/scripts/hooks/stop-goal-fit.js +1 -1
- package/docs/context-map.md +2 -0
- package/docs/public-workflow-cli.md +63 -0
- package/docs/spec/builder-flow-runtime.md +49 -5
- package/docs/workflow-usage-guide.md +5 -0
- package/evals/ci/run-baseline.sh +2 -0
- package/evals/integration/test_assignment_provider_local_file.sh +54 -0
- package/evals/integration/test_builder_entry_enforcement.sh +241 -24
- package/evals/integration/test_bundle_install.sh +97 -0
- package/evals/integration/test_current_json_per_actor.sh +1 -0
- package/evals/integration/test_dual_emit_flow_step.sh +2 -0
- package/evals/integration/test_flowdef_session_activation.sh +6 -3
- package/evals/integration/test_goal_fit_escape_hatch.sh +3 -3
- package/evals/integration/test_phase_map_and_gate_claim.sh +4 -0
- package/evals/integration/test_public_workflow_cli.sh +259 -0
- package/evals/integration/test_workflow_sidecar_writer.sh +1 -0
- package/package.json +2 -2
- package/schemas/builder-lifecycle-authorization.schema.json +57 -0
- package/schemas/lifecycle-authority-keys.schema.json +25 -0
- package/schemas/workflow-state.schema.json +1 -1
- package/scripts/hooks/config-protection.js +8 -1
- package/scripts/hooks/lib/config-protection-remedies.js +3 -0
- package/scripts/hooks/stop-goal-fit.js +1 -1
- package/src/builder-flow-run-adapter.ts +47 -0
- package/src/builder-flow-runtime.ts +216 -4
- package/src/builder-lifecycle-authority.ts +218 -0
- package/src/cli/assignment-provider.ts +84 -20
- package/src/cli/builder-flow-runtime.test.mjs +404 -1
- package/src/cli/builder-run.ts +56 -5
- package/src/cli/workflow-artifact-cleanup-audit.ts +3 -0
- package/src/cli/workflow-sidecar.ts +138 -31
- package/src/cli/workflow.ts +471 -0
- package/src/cli.ts +2 -0
- package/src/index.ts +14 -0
- package/src/lib/flow-resolver.ts +6 -2
- package/src/lib/package-version.ts +15 -0
- package/src/lib/pinned-cli-command.ts +23 -0
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
import { flowAgentsPackageVersion } from "./lib/package-version.js";
|
|
6
|
+
import { pinnedFlowAgentsCommand } from "./lib/pinned-cli-command.js";
|
|
4
7
|
import {
|
|
5
8
|
expectationsForGate,
|
|
9
|
+
lifecycleRequestMatches,
|
|
6
10
|
openGates,
|
|
7
11
|
readJson,
|
|
8
12
|
runDir,
|
|
@@ -12,11 +16,16 @@ import {
|
|
|
12
16
|
type FlowRunState,
|
|
13
17
|
type JsonObject,
|
|
14
18
|
} from "@kontourai/flow";
|
|
19
|
+
import { assertAuthorizationUnused, loadBuilderLifecycleAuthorization, readAuthorizationConsumption, recordAuthorizationConsumed } from "./builder-lifecycle-authority.js";
|
|
20
|
+
import { assignmentFilePath, performLocalReleaseUnderLock, readLocalAssignmentStatus, resolveCurrentAssignmentActor, withSubjectLock, type ActorStruct } from "./cli/assignment-provider.js";
|
|
15
21
|
import {
|
|
16
22
|
BUILDER_BUILD_FLOW_ID,
|
|
17
23
|
BuilderBuildRunInputError,
|
|
24
|
+
cancelBuilderBuildRun,
|
|
18
25
|
evaluateBuilderBuildRun,
|
|
19
26
|
loadBuilderBuildRun,
|
|
27
|
+
pauseBuilderBuildRun,
|
|
28
|
+
resumeBuilderBuildRun,
|
|
20
29
|
startBuilderBuildRun,
|
|
21
30
|
type BuilderBuildRunResult,
|
|
22
31
|
} from "./builder-flow-run-adapter.js";
|
|
@@ -27,6 +36,14 @@ export interface BuilderFlowSessionInput {
|
|
|
27
36
|
sessionDir: string;
|
|
28
37
|
}
|
|
29
38
|
|
|
39
|
+
export interface BuilderFlowAuthorizedLifecycleInput extends BuilderFlowSessionInput {
|
|
40
|
+
authorizationFile: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface BuilderFlowAgentLifecycleInput extends BuilderFlowSessionInput {
|
|
44
|
+
reason: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
30
47
|
export interface BuilderFlowSessionResult {
|
|
31
48
|
sessionDir: string;
|
|
32
49
|
projectRoot: string;
|
|
@@ -119,6 +136,195 @@ export async function recoverBuilderFlowSession(input: BuilderFlowSessionInput):
|
|
|
119
136
|
};
|
|
120
137
|
}
|
|
121
138
|
|
|
139
|
+
export async function pauseBuilderFlowSession(input: BuilderFlowAgentLifecycleInput): Promise<BuilderFlowSessionResult> {
|
|
140
|
+
return changeBuilderFlowSessionLifecycle(input, "pause");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function resumeBuilderFlowSession(input: BuilderFlowAgentLifecycleInput): Promise<BuilderFlowSessionResult> {
|
|
144
|
+
return changeBuilderFlowSessionLifecycle(input, "resume");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function cancelBuilderFlowSession(input: BuilderFlowAuthorizedLifecycleInput): Promise<BuilderFlowSessionResult & { assignmentReleased: boolean; idempotent: boolean }> {
|
|
148
|
+
const context = resolveSessionContext(input.sessionDir);
|
|
149
|
+
return await withSubjectLock(context.artifactRoot, context.slug, async () => {
|
|
150
|
+
const prepared = await prepareAuthorizedLifecycleChange(input, "cancel", context);
|
|
151
|
+
assertAuthorizationUnused(prepared.context.artifactRoot, prepared.authorization);
|
|
152
|
+
const changed = await cancelBuilderBuildRun({ cwd: prepared.context.projectRoot, runId: prepared.context.slug, request: prepared.authorization.request });
|
|
153
|
+
const released = performLocalReleaseUnderLock(prepared.context.artifactRoot, prepared.context.slug, prepared.authorization.assignment_actor, {
|
|
154
|
+
actorKey: prepared.authorization.assignment_actor_key,
|
|
155
|
+
reason: `canonical Flow run canceled by ${prepared.authorization.request.authority.request_ref}`,
|
|
156
|
+
tolerateNoActiveClaim: true,
|
|
157
|
+
});
|
|
158
|
+
const projection = projectFlowRun(prepared.context, changed, prepared.sidecarSnapshot.state);
|
|
159
|
+
writeProjection(prepared.context, projection, prepared.sidecarSnapshot.raw, "cancellation projection");
|
|
160
|
+
recordAuthorizationConsumed(prepared.context.artifactRoot, prepared.authorization);
|
|
161
|
+
return { sessionDir: prepared.context.sessionDir, projectRoot: prepared.context.projectRoot, run: changed, projection, attached: false, assignmentReleased: released !== null, idempotent: changed.idempotent };
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function releaseBuilderFlowAssignment(input: BuilderFlowAgentLifecycleInput): Promise<BuilderFlowSessionResult & { assignmentReleased: boolean }> {
|
|
166
|
+
const context = resolveSessionContext(input.sessionDir);
|
|
167
|
+
return await withSubjectLock(context.artifactRoot, context.slug, async () => {
|
|
168
|
+
const prepared = prepareAgentLifecycleChange(input, context);
|
|
169
|
+
const run = await loadBuilderBuildRun({ cwd: context.projectRoot, runId: context.slug });
|
|
170
|
+
const released = performLocalReleaseUnderLock(context.artifactRoot, context.slug, prepared.actor, { actorKey: prepared.actorKey, reason: input.reason });
|
|
171
|
+
return { sessionDir: context.sessionDir, projectRoot: context.projectRoot, run, projection: prepared.sidecarSnapshot.state, attached: false, assignmentReleased: released !== null };
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export async function archiveBuilderFlowSession(input: BuilderFlowAuthorizedLifecycleInput): Promise<BuilderFlowSessionResult & { archiveDir: string }> {
|
|
176
|
+
const context = resolveSessionContext(input.sessionDir);
|
|
177
|
+
return await withSubjectLock(context.artifactRoot, context.slug, async () => {
|
|
178
|
+
const prepared = await prepareAuthorizedLifecycleChange(input, "archive", context);
|
|
179
|
+
const priorConsumption = readAuthorizationConsumption(prepared.context.artifactRoot, prepared.authorization);
|
|
180
|
+
const recoveringPreparedArchive = priorConsumption !== null && prepared.sidecarSnapshot.state.status === "archived";
|
|
181
|
+
if (priorConsumption && !recoveringPreparedArchive) throw new Error("lifecycle authorization nonce has already been consumed");
|
|
182
|
+
const run = await loadBuilderBuildRun({ cwd: prepared.context.projectRoot, runId: prepared.context.slug });
|
|
183
|
+
if (run.state.status !== "completed" && run.state.status !== "canceled") {
|
|
184
|
+
throw new BuilderBuildRunInputError("flow_run.status", "must be completed or canceled before archival");
|
|
185
|
+
}
|
|
186
|
+
const archiveRoot = path.join(prepared.context.artifactRoot, "archive");
|
|
187
|
+
const archiveDir = path.join(archiveRoot, prepared.context.slug);
|
|
188
|
+
if (pathExistsNoFollow(archiveDir)) throw new BuilderBuildRunInputError("archive", "destination already exists");
|
|
189
|
+
fs.mkdirSync(archiveRoot, { recursive: true });
|
|
190
|
+
assertSafeDirectory(archiveRoot, prepared.context.artifactRoot, "archive root");
|
|
191
|
+
assertSafeDirectory(prepared.context.sessionDir, prepared.context.artifactRoot, "sessionDir");
|
|
192
|
+
if (!recoveringPreparedArchive && fs.readFileSync(prepared.context.stateFile, "utf8") !== prepared.sidecarSnapshot.raw) {
|
|
193
|
+
throw new BuilderBuildRunInputError("state.json", "changed during archive preparation");
|
|
194
|
+
}
|
|
195
|
+
const archivedState = recoveringPreparedArchive ? prepared.sidecarSnapshot.state : {
|
|
196
|
+
...prepared.sidecarSnapshot.state,
|
|
197
|
+
status: "archived",
|
|
198
|
+
phase: "done",
|
|
199
|
+
updated_at: new Date().toISOString(),
|
|
200
|
+
next_action: { status: "done", summary: "Builder session archived; canonical Flow artifacts remain retained." },
|
|
201
|
+
};
|
|
202
|
+
if (!recoveringPreparedArchive) {
|
|
203
|
+
writeExistingFileNoFollow(prepared.context.stateFile, `${JSON.stringify(archivedState, null, 2)}\n`);
|
|
204
|
+
clearCurrentPointers(prepared.context.artifactRoot, prepared.context.slug);
|
|
205
|
+
recordAuthorizationConsumed(prepared.context.artifactRoot, prepared.authorization);
|
|
206
|
+
}
|
|
207
|
+
fs.renameSync(prepared.context.sessionDir, archiveDir);
|
|
208
|
+
return {
|
|
209
|
+
sessionDir: archiveDir,
|
|
210
|
+
projectRoot: prepared.context.projectRoot,
|
|
211
|
+
run,
|
|
212
|
+
projection: archivedState,
|
|
213
|
+
attached: false,
|
|
214
|
+
archiveDir,
|
|
215
|
+
};
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function changeBuilderFlowSessionLifecycle(
|
|
220
|
+
input: BuilderFlowAgentLifecycleInput,
|
|
221
|
+
operation: "pause" | "resume",
|
|
222
|
+
): Promise<BuilderFlowSessionResult> {
|
|
223
|
+
const context = resolveSessionContext(input.sessionDir);
|
|
224
|
+
return await withSubjectLock(context.artifactRoot, context.slug, async () => {
|
|
225
|
+
const prepared = prepareAgentLifecycleChange(input, context);
|
|
226
|
+
const change = operation === "pause" ? pauseBuilderBuildRun : resumeBuilderBuildRun;
|
|
227
|
+
const at = new Date().toISOString();
|
|
228
|
+
const run = await change({
|
|
229
|
+
cwd: context.projectRoot,
|
|
230
|
+
runId: context.slug,
|
|
231
|
+
request: { reason: input.reason, authority: { kind: "operator_request", actor: prepared.actorKey, request_ref: `flow-agents://assignment/${context.slug}/${operation}/${at}`, requested_at: at } },
|
|
232
|
+
});
|
|
233
|
+
const projection = projectFlowRun(context, run, prepared.sidecarSnapshot.state);
|
|
234
|
+
writeProjection(context, projection, prepared.sidecarSnapshot.raw, `${operation} projection`);
|
|
235
|
+
return {
|
|
236
|
+
sessionDir: context.sessionDir,
|
|
237
|
+
projectRoot: context.projectRoot,
|
|
238
|
+
run,
|
|
239
|
+
projection,
|
|
240
|
+
attached: false,
|
|
241
|
+
};
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function prepareAuthorizedLifecycleChange(input: BuilderFlowAuthorizedLifecycleInput, operation: "cancel" | "archive", context: SessionContext): Promise<{
|
|
246
|
+
context: SessionContext;
|
|
247
|
+
sidecarSnapshot: SidecarSnapshot;
|
|
248
|
+
authorization: ReturnType<typeof loadBuilderLifecycleAuthorization>;
|
|
249
|
+
}> {
|
|
250
|
+
const sidecarSnapshot = readSidecarSnapshot(context);
|
|
251
|
+
const subject = workflowSubject(sidecarSnapshot.state);
|
|
252
|
+
const activeAssignment = readLocalAssignmentStatus(context.artifactRoot, context.slug).record;
|
|
253
|
+
const assignmentFile = assignmentFilePath(context.artifactRoot, context.slug);
|
|
254
|
+
const persistedAssignment = pathExistsNoFollow(assignmentFile)
|
|
255
|
+
? (assertSafeFile(assignmentFile, context.artifactRoot, "assignment record"), JSON.parse(fs.readFileSync(assignmentFile, "utf8")) as AnyRecord)
|
|
256
|
+
: null;
|
|
257
|
+
const canonicalRun = await loadBuilderBuildRun({ cwd: context.projectRoot, runId: context.slug });
|
|
258
|
+
const acceptsReleasedAssignment = (operation === "cancel" && canonicalRun.state.status === "canceled") || operation === "archive";
|
|
259
|
+
const assignment = activeAssignment ?? (acceptsReleasedAssignment && persistedAssignment?.status === "released" ? persistedAssignment : null);
|
|
260
|
+
if (!assignment || (assignment.status !== "claimed" && !acceptsReleasedAssignment) || !assignment.actor_key) {
|
|
261
|
+
throw new BuilderBuildRunInputError("assignment", "must be actively held by a canonical actor before a lifecycle change");
|
|
262
|
+
}
|
|
263
|
+
if (assignment.work_item_ref && assignment.work_item_ref !== subject) {
|
|
264
|
+
throw new BuilderBuildRunInputError("assignment.work_item_ref", "must match the selected Work Item");
|
|
265
|
+
}
|
|
266
|
+
const authorization = loadBuilderLifecycleAuthorization(input.authorizationFile, {
|
|
267
|
+
projectRoot: context.projectRoot,
|
|
268
|
+
operation,
|
|
269
|
+
runId: context.slug,
|
|
270
|
+
subject,
|
|
271
|
+
actorKey: assignment.actor_key,
|
|
272
|
+
...(operation === "cancel" && canonicalRun.state.status === "canceled" ? { allowExpired: true } : {}),
|
|
273
|
+
...(operation === "archive" && sidecarSnapshot.state.status === "archived" ? { allowExpired: true } : {}),
|
|
274
|
+
});
|
|
275
|
+
if (operation === "cancel" && canonicalRun.state.status === "canceled") {
|
|
276
|
+
const terminalEvent = canonicalRun.state.lifecycle?.at(-1);
|
|
277
|
+
if (!terminalEvent || terminalEvent.action !== "cancel" || !lifecycleRequestMatches(terminalEvent, authorization.request)) {
|
|
278
|
+
throw new BuilderBuildRunInputError("authorization.request", "does not match the canonical cancellation being recovered");
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (!sameActor(authorization.assignment_actor, assignment.actor)) {
|
|
282
|
+
throw new BuilderBuildRunInputError("authorization.assignment_actor", "must match the active assignment holder");
|
|
283
|
+
}
|
|
284
|
+
return { context, sidecarSnapshot, authorization };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function prepareAgentLifecycleChange(input: BuilderFlowAgentLifecycleInput, context: SessionContext): { sidecarSnapshot: SidecarSnapshot; actor: ActorStruct; actorKey: string } {
|
|
288
|
+
if (!input.reason.trim()) throw new BuilderBuildRunInputError("reason", "must be non-empty");
|
|
289
|
+
const resolved = resolveCurrentAssignmentActor();
|
|
290
|
+
const sidecarSnapshot = readSidecarSnapshot(context);
|
|
291
|
+
const subject = workflowSubject(sidecarSnapshot.state);
|
|
292
|
+
const assignment = readLocalAssignmentStatus(context.artifactRoot, context.slug).record;
|
|
293
|
+
if (!assignment || assignment.status !== "claimed" || assignment.actor_key !== resolved.actorKey || !sameActor(assignment.actor, resolved.actor)) {
|
|
294
|
+
throw new BuilderBuildRunInputError("assignment", "must be actively held by the current workflow actor");
|
|
295
|
+
}
|
|
296
|
+
if (assignment.work_item_ref && assignment.work_item_ref !== subject) throw new BuilderBuildRunInputError("assignment.work_item_ref", "must match the selected Work Item");
|
|
297
|
+
return { sidecarSnapshot, actor: resolved.actor, actorKey: resolved.actorKey };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function sameActor(left: ActorStruct, right: ActorStruct): boolean {
|
|
301
|
+
return isDeepStrictEqual({ ...left, human: left.human ?? null }, { ...right, human: right.human ?? null });
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function clearCurrentPointers(artifactRoot: string, slug: string): void {
|
|
305
|
+
const candidates = [path.join(artifactRoot, "current.json")];
|
|
306
|
+
const actorRoot = path.join(artifactRoot, "current");
|
|
307
|
+
if (pathExistsNoFollow(actorRoot)) {
|
|
308
|
+
assertSafeDirectory(actorRoot, artifactRoot, "current directory");
|
|
309
|
+
candidates.push(...fs.readdirSync(actorRoot).filter((name) => name.endsWith(".json")).map((name) => path.join(actorRoot, name)));
|
|
310
|
+
}
|
|
311
|
+
for (const file of candidates) {
|
|
312
|
+
if (!pathExistsNoFollow(file) || !fs.lstatSync(file).isFile()) continue;
|
|
313
|
+
const root = file === candidates[0] ? artifactRoot : actorRoot;
|
|
314
|
+
if (root === actorRoot) assertSafeDirectory(actorRoot, artifactRoot, "current directory");
|
|
315
|
+
assertSafeFile(file, root, "current pointer");
|
|
316
|
+
let pointer: AnyRecord;
|
|
317
|
+
try {
|
|
318
|
+
pointer = JSON.parse(fs.readFileSync(file, "utf8")) as AnyRecord;
|
|
319
|
+
} catch (error) {
|
|
320
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
321
|
+
// Archival retains malformed unrelated pointers for explicit repair.
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (pointer.active_slug === slug) fs.unlinkSync(file);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
122
328
|
export async function syncBuilderFlowSessionIfPresent(sessionDir: string): Promise<BuilderFlowSessionResult | null> {
|
|
123
329
|
let context: SessionContext;
|
|
124
330
|
try {
|
|
@@ -291,7 +497,9 @@ function projectFlowRun(context: SessionContext, run: BuilderBuildRunResult, sid
|
|
|
291
497
|
const definition = JSON.parse(fs.readFileSync(path.join(run.dir, "definition.json"), "utf8"));
|
|
292
498
|
const gates = openGates(definition, run.state) as Array<FlowGate & { id: string }>;
|
|
293
499
|
const complete = run.state.status === "completed";
|
|
294
|
-
const
|
|
500
|
+
const paused = run.state.status === "paused";
|
|
501
|
+
const canceled = run.state.status === "canceled";
|
|
502
|
+
const action = complete || paused || canceled ? { skills: [], operations: [] } : stepAction(run.state.current_step);
|
|
295
503
|
if (!action) {
|
|
296
504
|
throw new BuilderBuildRunInputError("kit.flow_step_actions", `does not declare Builder step ${run.state.current_step}`);
|
|
297
505
|
}
|
|
@@ -300,7 +508,7 @@ function projectFlowRun(context: SessionContext, run: BuilderBuildRunResult, sid
|
|
|
300
508
|
.map((expectation: FlowExpectation) => `${expectation.id} (${expectation.bundle_claim.claimType}/${expectation.bundle_claim.subjectType ?? "any"})`));
|
|
301
509
|
const skills = action?.skills ?? [];
|
|
302
510
|
const operations = action?.operations ?? [];
|
|
303
|
-
const syncCommand =
|
|
511
|
+
const syncCommand = pinnedFlowAgentsCommand(flowAgentsPackageVersion(), ["workflow", "status", "--session-dir", `.kontourai/flow-agents/${context.slug}`, "--json"]);
|
|
304
512
|
const routeBack = latestRouteBack(run.state);
|
|
305
513
|
const skillText = skills.length ? `Activate ${skills.map((skill) => `\`${skill}\``).join(" then ")}.` : "No Builder skill is required.";
|
|
306
514
|
const operationText = operations.length ? ` Perform ${operations.map((operation) => `\`${operation}\``).join(" then ")}.` : "";
|
|
@@ -312,6 +520,10 @@ function projectFlowRun(context: SessionContext, run: BuilderBuildRunResult, sid
|
|
|
312
520
|
: "";
|
|
313
521
|
const nextAction = complete
|
|
314
522
|
? { status: "done", summary: "Canonical Flow run is complete." }
|
|
523
|
+
: canceled
|
|
524
|
+
? { status: "done", summary: "Canonical Flow run was canceled by an authorized external request. Artifacts are retained until separately archived." }
|
|
525
|
+
: paused
|
|
526
|
+
? { status: "blocked", summary: "Canonical Flow run is paused. The current assignment actor may resume it with a reason." }
|
|
315
527
|
: {
|
|
316
528
|
status: "continue",
|
|
317
529
|
summary: `Flow step \`${run.state.current_step}\`: ${skillText}${operationText} ${gateText}${routeText} Then synchronize the recorded evidence.`,
|
|
@@ -322,8 +534,8 @@ function projectFlowRun(context: SessionContext, run: BuilderBuildRunResult, sid
|
|
|
322
534
|
const phase = phaseForStep(definition.phase_map, run.state.current_step) ?? sidecar.phase;
|
|
323
535
|
return {
|
|
324
536
|
...sidecar,
|
|
325
|
-
status: complete ? "delivered" : (run.state.transitions.length > 0 ? "in_progress" : sidecar.status),
|
|
326
|
-
phase: complete ? "done" : phase,
|
|
537
|
+
status: complete ? "delivered" : canceled ? "canceled" : paused ? "blocked" : (run.state.transitions.length > 0 ? "in_progress" : sidecar.status),
|
|
538
|
+
phase: complete || canceled ? "done" : phase,
|
|
327
539
|
updated_at: run.state.updated_at,
|
|
328
540
|
flow_run: {
|
|
329
541
|
run_id: run.runId,
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
4
|
+
import type { FlowLifecycleRequest } from "@kontourai/flow";
|
|
5
|
+
import type { ActorStruct } from "./cli/assignment-provider.js";
|
|
6
|
+
import { durableFlowAgentsRoot } from "./lib/local-artifact-root.js";
|
|
7
|
+
|
|
8
|
+
type JsonRecord = Record<string, unknown>;
|
|
9
|
+
export type AuthorizedBuilderLifecycleOperation = "cancel" | "archive";
|
|
10
|
+
|
|
11
|
+
export interface BuilderLifecycleAuthorization {
|
|
12
|
+
schema_version: "1.0";
|
|
13
|
+
operation: AuthorizedBuilderLifecycleOperation;
|
|
14
|
+
run_id: string;
|
|
15
|
+
subject: string;
|
|
16
|
+
assignment_actor_key: string;
|
|
17
|
+
assignment_actor: ActorStruct;
|
|
18
|
+
nonce: string;
|
|
19
|
+
expires_at: string;
|
|
20
|
+
request: FlowLifecycleRequest;
|
|
21
|
+
signature: { algorithm: "ed25519"; key_id: string; value: string };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function lifecycleAuthorityKeysPath(projectRoot: string): string {
|
|
25
|
+
return path.join(durableFlowAgentsRoot(projectRoot), "lifecycle-authority-keys.json");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function loadBuilderLifecycleAuthorization(
|
|
29
|
+
fileInput: string,
|
|
30
|
+
expected: { projectRoot: string; operation: AuthorizedBuilderLifecycleOperation; runId: string; subject: string; actorKey: string; now?: string; allowExpired?: boolean },
|
|
31
|
+
): BuilderLifecycleAuthorization {
|
|
32
|
+
const value = readRegularJson(fileInput, "lifecycle authorization");
|
|
33
|
+
assertExactKeys(value, ["schema_version", "operation", "run_id", "subject", "assignment_actor_key", "assignment_actor", "nonce", "expires_at", "request", "signature"], "authorization");
|
|
34
|
+
if (value.schema_version !== "1.0") throw new Error("lifecycle authorization schema_version must be 1.0");
|
|
35
|
+
assertEqual(value.operation, expected.operation, "operation");
|
|
36
|
+
assertEqual(value.run_id, expected.runId, "run_id");
|
|
37
|
+
assertEqual(value.subject, expected.subject, "subject");
|
|
38
|
+
assertEqual(value.assignment_actor_key, expected.actorKey, "assignment_actor_key");
|
|
39
|
+
const assignmentActor = validateActor(value.assignment_actor);
|
|
40
|
+
const request = validateRequest(value.request);
|
|
41
|
+
const nonce = boundedText(value.nonce, "nonce", 256);
|
|
42
|
+
const expiresAt = dateTime(value.expires_at, "expires_at");
|
|
43
|
+
const requestedAt = Date.parse(request.authority.requested_at);
|
|
44
|
+
const now = Date.parse(expected.now ?? new Date().toISOString());
|
|
45
|
+
if (expiresAt < requestedAt) throw new Error("lifecycle authorization expires_at must not precede request.authority.requested_at");
|
|
46
|
+
if (now > expiresAt && !expected.allowExpired) throw new Error("lifecycle authorization is expired");
|
|
47
|
+
if (requestedAt > now + 5 * 60_000) throw new Error("lifecycle authorization request time is in the future");
|
|
48
|
+
const signature = validateSignature(value.signature);
|
|
49
|
+
const authorization = {
|
|
50
|
+
schema_version: "1.0",
|
|
51
|
+
operation: expected.operation,
|
|
52
|
+
run_id: expected.runId,
|
|
53
|
+
subject: expected.subject,
|
|
54
|
+
assignment_actor_key: expected.actorKey,
|
|
55
|
+
assignment_actor: assignmentActor,
|
|
56
|
+
nonce,
|
|
57
|
+
expires_at: value.expires_at as string,
|
|
58
|
+
request,
|
|
59
|
+
signature,
|
|
60
|
+
} satisfies BuilderLifecycleAuthorization;
|
|
61
|
+
verifyAuthorizationSignature(authorization, lifecycleAuthorityKeysPath(expected.projectRoot));
|
|
62
|
+
return authorization;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function builderLifecycleAuthorizationPayload(value: Omit<BuilderLifecycleAuthorization, "signature">): string {
|
|
66
|
+
return JSON.stringify(value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function assertAuthorizationUnused(artifactRoot: string, authorization: BuilderLifecycleAuthorization): void {
|
|
70
|
+
if (!readAuthorizationConsumption(artifactRoot, authorization)) return;
|
|
71
|
+
throw new Error("lifecycle authorization nonce has already been consumed");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function readAuthorizationConsumption(artifactRoot: string, authorization: BuilderLifecycleAuthorization): JsonRecord | null {
|
|
75
|
+
const file = consumedAuthorizationPath(artifactRoot, authorization);
|
|
76
|
+
if (!pathExistsNoFollow(file)) return null;
|
|
77
|
+
const record = readRegularJson(file, "consumed lifecycle authorization record");
|
|
78
|
+
if (record.run_id !== authorization.run_id
|
|
79
|
+
|| record.operation !== authorization.operation
|
|
80
|
+
|| record.nonce !== authorization.nonce
|
|
81
|
+
|| record.key_id !== authorization.signature.key_id
|
|
82
|
+
|| record.authorization_sha256 !== authorizationDigest(authorization)) {
|
|
83
|
+
throw new Error("consumed lifecycle authorization record does not match its integrity key");
|
|
84
|
+
}
|
|
85
|
+
return record;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function recordAuthorizationConsumed(artifactRoot: string, authorization: BuilderLifecycleAuthorization, at = new Date().toISOString()): void {
|
|
89
|
+
const file = consumedAuthorizationPath(artifactRoot, authorization);
|
|
90
|
+
const directory = path.dirname(file);
|
|
91
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
92
|
+
const stat = fs.lstatSync(directory);
|
|
93
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || !pathIsWithin(fs.realpathSync(directory), fs.realpathSync(artifactRoot))) throw new Error("lifecycle authorization registry directory is unsafe");
|
|
94
|
+
const temporary = path.join(directory, `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
|
|
95
|
+
const descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
96
|
+
try {
|
|
97
|
+
fs.writeFileSync(descriptor, `${JSON.stringify({ run_id: authorization.run_id, operation: authorization.operation, nonce: authorization.nonce, key_id: authorization.signature.key_id, authorization_sha256: authorizationDigest(authorization), at })}\n`);
|
|
98
|
+
fs.fsyncSync(descriptor);
|
|
99
|
+
} finally {
|
|
100
|
+
fs.closeSync(descriptor);
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
fs.linkSync(temporary, file);
|
|
104
|
+
const directoryDescriptor = fs.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
105
|
+
try { fs.fsyncSync(directoryDescriptor); } finally { fs.closeSync(directoryDescriptor); }
|
|
106
|
+
} finally {
|
|
107
|
+
fs.rmSync(temporary, { force: true });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function consumedAuthorizationPath(artifactRoot: string, authorization: BuilderLifecycleAuthorization): string {
|
|
112
|
+
const integrityKey = createHash("sha256").update(authorization.run_id).update("\0").update(authorization.nonce).digest("hex");
|
|
113
|
+
return path.join(artifactRoot, "lifecycle-authority", "consumed", `${integrityKey}.json`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function authorizationDigest(authorization: BuilderLifecycleAuthorization): string {
|
|
117
|
+
return createHash("sha256").update(JSON.stringify(authorization)).digest("hex");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function verifyAuthorizationSignature(authorization: BuilderLifecycleAuthorization, keysFile: string): void {
|
|
121
|
+
const registry = readRegularJson(keysFile, "lifecycle authority key registry", true);
|
|
122
|
+
assertExactKeys(registry, ["schema_version", "keys"], "key registry");
|
|
123
|
+
if (registry.schema_version !== "1.0" || !Array.isArray(registry.keys)) throw new Error("lifecycle authority key registry must contain schema_version 1.0 and keys[]");
|
|
124
|
+
const key = registry.keys.find((candidate) => isRecord(candidate) && candidate.id === authorization.signature.key_id);
|
|
125
|
+
if (!isRecord(key) || key.algorithm !== "ed25519" || typeof key.public_key_pem !== "string" || key.public_key_pem.trim().length === 0) {
|
|
126
|
+
throw new Error(`lifecycle authorization key ${authorization.signature.key_id} is not trusted`);
|
|
127
|
+
}
|
|
128
|
+
const { signature: _signature, ...unsigned } = authorization;
|
|
129
|
+
let verified = false;
|
|
130
|
+
try {
|
|
131
|
+
verified = verify(null, Buffer.from(builderLifecycleAuthorizationPayload(unsigned)), createPublicKey(key.public_key_pem), Buffer.from(authorization.signature.value, "base64"));
|
|
132
|
+
} catch {
|
|
133
|
+
verified = false;
|
|
134
|
+
}
|
|
135
|
+
if (!verified) throw new Error("lifecycle authorization signature is invalid");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function readRegularJson(fileInput: string, label: string, requireProtected = false): JsonRecord {
|
|
139
|
+
const file = path.resolve(fileInput);
|
|
140
|
+
const descriptor = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
141
|
+
try {
|
|
142
|
+
const stat = fs.fstatSync(descriptor);
|
|
143
|
+
if (!stat.isFile()) throw new Error(`${label} must be a regular file`);
|
|
144
|
+
if (stat.size > 64 * 1024) throw new Error(`${label} exceeds 64 KiB`);
|
|
145
|
+
if (requireProtected && (stat.mode & 0o022) !== 0) throw new Error(`${label} must not be group- or world-writable`);
|
|
146
|
+
const value = JSON.parse(fs.readFileSync(descriptor, "utf8")) as unknown;
|
|
147
|
+
if (!isRecord(value)) throw new Error(`${label} must be a JSON object`);
|
|
148
|
+
return value;
|
|
149
|
+
} finally {
|
|
150
|
+
fs.closeSync(descriptor);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function validateActor(value: unknown): ActorStruct {
|
|
155
|
+
if (!isRecord(value)) throw new Error("lifecycle authorization assignment_actor must be an object");
|
|
156
|
+
assertExactKeys(value, ["runtime", "session_id", "host", "human"], "assignment_actor");
|
|
157
|
+
if (!Object.prototype.hasOwnProperty.call(value, "human")) throw new Error("lifecycle authorization assignment_actor.human is required");
|
|
158
|
+
for (const field of ["runtime", "session_id", "host"] as const) boundedText(value[field], `assignment_actor.${field}`, 256);
|
|
159
|
+
if (value.human !== undefined && value.human !== null) boundedText(value.human, "assignment_actor.human", 256);
|
|
160
|
+
return { runtime: value.runtime as string, session_id: value.session_id as string, host: value.host as string, human: value.human == null ? null : value.human as string };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function validateRequest(value: unknown): FlowLifecycleRequest {
|
|
164
|
+
if (!isRecord(value)) throw new Error("lifecycle authorization request must be an object");
|
|
165
|
+
assertExactKeys(value, ["reason", "authority"], "request");
|
|
166
|
+
const reason = boundedText(value.reason, "request.reason", 4096);
|
|
167
|
+
if (!isRecord(value.authority)) throw new Error("lifecycle authorization request.authority must be an object");
|
|
168
|
+
assertExactKeys(value.authority, ["kind", "actor", "request_ref", "requested_at"], "request.authority");
|
|
169
|
+
if (value.authority.kind !== "user_request" && value.authority.kind !== "operator_request") throw new Error("lifecycle authorization request.authority.kind must be user_request or operator_request");
|
|
170
|
+
const actor = boundedText(value.authority.actor, "request.authority.actor", 256);
|
|
171
|
+
const requestRef = boundedText(value.authority.request_ref, "request.authority.request_ref", 2048);
|
|
172
|
+
dateTime(value.authority.requested_at, "request.authority.requested_at");
|
|
173
|
+
return { reason, authority: { kind: value.authority.kind, actor, request_ref: requestRef, requested_at: value.authority.requested_at as string } };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function validateSignature(value: unknown): BuilderLifecycleAuthorization["signature"] {
|
|
177
|
+
if (!isRecord(value)) throw new Error("lifecycle authorization signature must be an object");
|
|
178
|
+
assertExactKeys(value, ["algorithm", "key_id", "value"], "signature");
|
|
179
|
+
if (value.algorithm !== "ed25519") throw new Error("lifecycle authorization signature.algorithm must be ed25519");
|
|
180
|
+
return { algorithm: "ed25519", key_id: boundedText(value.key_id, "signature.key_id", 256), value: boundedText(value.value, "signature.value", 1024) };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function assertEqual(actual: unknown, expected: string, field: string): void {
|
|
184
|
+
if (actual !== expected) throw new Error(`lifecycle authorization ${field} does not match the requested Builder operation`);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function assertExactKeys(value: JsonRecord, allowed: string[], field: string): void {
|
|
188
|
+
const unexpected = Object.keys(value).filter((key) => !allowed.includes(key));
|
|
189
|
+
if (unexpected.length) throw new Error(`lifecycle authorization ${field} contains unsupported field ${unexpected[0]}`);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function dateTime(value: unknown, field: string): number {
|
|
193
|
+
const text = boundedText(value, field, 128);
|
|
194
|
+
if (!Number.isFinite(Date.parse(text))) throw new Error(`lifecycle authorization ${field} must be a date-time`);
|
|
195
|
+
return Date.parse(text);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function boundedText(value: unknown, field: string, limit: number): string {
|
|
199
|
+
if (!nonEmpty(value) || [...value].length > limit) throw new Error(`lifecycle authorization ${field} must be a non-empty string of at most ${limit} characters`);
|
|
200
|
+
return value;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function nonEmpty(value: unknown): value is string {
|
|
204
|
+
return typeof value === "string" && value.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(value);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function isRecord(value: unknown): value is JsonRecord {
|
|
208
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function pathExistsNoFollow(candidate: string): boolean {
|
|
212
|
+
try { fs.lstatSync(candidate); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function pathIsWithin(candidate: string, root: string): boolean {
|
|
216
|
+
const relative = path.relative(root, candidate);
|
|
217
|
+
return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
|
|
218
|
+
}
|