@abelxiaoxing/cadence 2.0.19 → 2.0.21
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/README.de.md +24 -8
- package/README.es.md +24 -8
- package/README.fr.md +24 -8
- package/README.ja.md +27 -12
- package/README.ko.md +25 -12
- package/README.md +30 -13
- package/README.pt-BR.md +24 -8
- package/README.ru.md +24 -8
- package/README.zh-CN.md +33 -15
- package/docs/conversation-mode.md +104 -0
- package/docs/service-management.md +6 -4
- package/package.json +8 -3
- package/src/cadence-instructions.ts +7 -0
- package/src/cadence-mode.ts +794 -0
- package/src/cadence-preferences.ts +43 -0
- package/src/coordinator-tools.mjs +109 -0
- package/src/index.ts +2 -0
- package/src/native-build.ts +1 -1
- package/src/sdk-worker.mjs +28 -8
- package/src/service/contracts/workbench.ts +276 -3
- package/src/service/contracts/workflow.ts +465 -0
- package/src/service/coordination.ts +2 -0
- package/src/service-cli.mjs +3 -1
- package/src/service-host.mjs +2397 -224
- package/src/startup-card.ts +1 -1
- package/src/task-shell.ts +5 -4
- package/web/dist/assets/cadence.css +1 -1
- package/web/dist/assets/cadence.js +19 -12
- package/web/dist/manifest.json +7 -7
package/src/service-host.mjs
CHANGED
|
@@ -3911,7 +3911,348 @@ function decodeModelCatalog(value) {
|
|
|
3911
3911
|
withheld
|
|
3912
3912
|
};
|
|
3913
3913
|
}
|
|
3914
|
+
// src/service/contracts/workflow.ts
|
|
3915
|
+
var WORKFLOW_LIMITS = {
|
|
3916
|
+
tasks: 16,
|
|
3917
|
+
parallel: 2,
|
|
3918
|
+
checks: 16,
|
|
3919
|
+
repairs: 2,
|
|
3920
|
+
bytes: 256 * 1024,
|
|
3921
|
+
runs: 200,
|
|
3922
|
+
durationMs: 90 * 60 * 1000
|
|
3923
|
+
};
|
|
3924
|
+
function workflowPath(v) {
|
|
3925
|
+
const p = text(v, 1024, true);
|
|
3926
|
+
if (p.startsWith("/") || p.includes("\\") || [...p].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127 || c === ":") || p.split("/").some((s) => !s || s === "." || s === ".." || s.toLowerCase() === ".git") || /(^|\/)\.env(?:\.|$)/iu.test(p))
|
|
3927
|
+
throw new Error("Invalid workflow file path");
|
|
3928
|
+
return p;
|
|
3929
|
+
}
|
|
3930
|
+
var taskId = (v) => {
|
|
3931
|
+
const s = text(v, 64, true);
|
|
3932
|
+
if (!/^[a-z][a-z0-9-]*$/u.test(s))
|
|
3933
|
+
throw new Error("Invalid task id");
|
|
3934
|
+
return s;
|
|
3935
|
+
};
|
|
3936
|
+
function decodeWorkflowCheck(v) {
|
|
3937
|
+
const o = closed(v, ["name", "command", "timeoutMs"]);
|
|
3938
|
+
return {
|
|
3939
|
+
name: text(o.name, 128, true),
|
|
3940
|
+
command: text(o.command, 4096, true),
|
|
3941
|
+
timeoutMs: integer(o.timeoutMs, 100, 1200000)
|
|
3942
|
+
};
|
|
3943
|
+
}
|
|
3944
|
+
function workflowOrder(tasks) {
|
|
3945
|
+
const done = new Set, ordered = [];
|
|
3946
|
+
if (new Set(tasks.map((t) => t.id)).size !== tasks.length)
|
|
3947
|
+
throw new Error("Duplicate task id");
|
|
3948
|
+
while (ordered.length < tasks.length) {
|
|
3949
|
+
const next = tasks.find((t) => !done.has(t.id) && t.after.every((id) => done.has(id)));
|
|
3950
|
+
if (!next)
|
|
3951
|
+
throw new Error("Missing dependency or cyclic plan");
|
|
3952
|
+
ordered.push(next);
|
|
3953
|
+
done.add(next.id);
|
|
3954
|
+
}
|
|
3955
|
+
return ordered;
|
|
3956
|
+
}
|
|
3957
|
+
function workflowAncestors(tasks, id) {
|
|
3958
|
+
const needed = new Set;
|
|
3959
|
+
const visit = (key) => {
|
|
3960
|
+
for (const dep of tasks.find((t) => t.id === key)?.after ?? []) {
|
|
3961
|
+
if (!needed.has(dep)) {
|
|
3962
|
+
needed.add(dep);
|
|
3963
|
+
visit(dep);
|
|
3964
|
+
}
|
|
3965
|
+
}
|
|
3966
|
+
};
|
|
3967
|
+
workflowOrder(tasks);
|
|
3968
|
+
visit(id);
|
|
3969
|
+
return workflowOrder(tasks).filter((t) => needed.has(t.id));
|
|
3970
|
+
}
|
|
3971
|
+
function decodeWorkflowPlan(v) {
|
|
3972
|
+
canonicalJson(v, WORKFLOW_LIMITS.bytes);
|
|
3973
|
+
const o = closed(v, [
|
|
3974
|
+
"goal",
|
|
3975
|
+
"design",
|
|
3976
|
+
"decisions",
|
|
3977
|
+
"acceptance",
|
|
3978
|
+
"projectContext",
|
|
3979
|
+
"tasks",
|
|
3980
|
+
"checks",
|
|
3981
|
+
"setup",
|
|
3982
|
+
"baselineChecks",
|
|
3983
|
+
"repairAttempts",
|
|
3984
|
+
"delivery"
|
|
3985
|
+
]);
|
|
3986
|
+
const tasks = list(o.tasks, WORKFLOW_LIMITS.tasks, (value) => {
|
|
3987
|
+
const t = closed(value, ["id", "title", "instructions", "writes", "after"]);
|
|
3988
|
+
return {
|
|
3989
|
+
id: taskId(t.id),
|
|
3990
|
+
title: text(t.title, 256, true),
|
|
3991
|
+
instructions: text(t.instructions, 8192, true),
|
|
3992
|
+
writes: list(t.writes, 128, workflowPath),
|
|
3993
|
+
after: list(t.after, WORKFLOW_LIMITS.tasks, taskId)
|
|
3994
|
+
};
|
|
3995
|
+
});
|
|
3996
|
+
if (!tasks.length || tasks.some((t) => !t.writes.length || new Set(t.writes).size !== t.writes.length || new Set(t.after).size !== t.after.length))
|
|
3997
|
+
throw new Error("Empty or duplicate task scope");
|
|
3998
|
+
workflowOrder(tasks);
|
|
3999
|
+
for (const a of tasks)
|
|
4000
|
+
for (const b of tasks) {
|
|
4001
|
+
if (a.id >= b.id || workflowAncestors(tasks, a.id).some((t) => t.id === b.id) || workflowAncestors(tasks, b.id).some((t) => t.id === a.id))
|
|
4002
|
+
continue;
|
|
4003
|
+
if (a.writes.some((p) => b.writes.some((q) => p === q || p.startsWith(`${q}/`) || q.startsWith(`${p}/`))))
|
|
4004
|
+
throw new Error("Independent tasks share write paths; assign an owner and dependency");
|
|
4005
|
+
}
|
|
4006
|
+
const checks = list(o.checks, WORKFLOW_LIMITS.checks, decodeWorkflowCheck);
|
|
4007
|
+
if (!checks.length)
|
|
4008
|
+
throw new Error("At least one real verification command is required");
|
|
4009
|
+
const result = {
|
|
4010
|
+
goal: text(o.goal, 8192, true),
|
|
4011
|
+
design: text(o.design, 32768, true),
|
|
4012
|
+
decisions: text(o.decisions, 16384),
|
|
4013
|
+
acceptance: text(o.acceptance, 16384, true),
|
|
4014
|
+
projectContext: text(o.projectContext, 16384),
|
|
4015
|
+
tasks,
|
|
4016
|
+
checks,
|
|
4017
|
+
setup: list(o.setup, 4, decodeWorkflowCheck),
|
|
4018
|
+
baselineChecks: list(o.baselineChecks, WORKFLOW_LIMITS.checks, decodeWorkflowCheck),
|
|
4019
|
+
repairAttempts: integer(o.repairAttempts, 0, WORKFLOW_LIMITS.repairs),
|
|
4020
|
+
delivery: oneOf(o.delivery, ["local-merge", "working-copy"])
|
|
4021
|
+
};
|
|
4022
|
+
workflowContext(result);
|
|
4023
|
+
text(result.tasks.flatMap((t) => t.writes).join(", "), 16384);
|
|
4024
|
+
for (const value of [
|
|
4025
|
+
result.goal,
|
|
4026
|
+
result.design,
|
|
4027
|
+
result.decisions,
|
|
4028
|
+
result.acceptance,
|
|
4029
|
+
result.projectContext,
|
|
4030
|
+
...result.tasks.flatMap((t) => [t.title, t.instructions]),
|
|
4031
|
+
...[...result.checks, ...result.setup, ...result.baselineChecks].flatMap((c) => [c.name, c.command])
|
|
4032
|
+
])
|
|
4033
|
+
if ([...value].some((c) => c.charCodeAt(0) < 32 && c !== `
|
|
4034
|
+
` && c !== "\t" || c.charCodeAt(0) === 127 || /[\u202a-\u202e\u2066-\u2069]/u.test(c)))
|
|
4035
|
+
throw new Error("Plan contains invisible terminal controls");
|
|
4036
|
+
return result;
|
|
4037
|
+
}
|
|
4038
|
+
function workflowContext(p) {
|
|
4039
|
+
return text(`# ${p.goal}
|
|
4040
|
+
|
|
4041
|
+
${p.design}
|
|
4042
|
+
|
|
4043
|
+
Decisions: ${p.decisions}
|
|
4044
|
+
|
|
4045
|
+
Acceptance: ${p.acceptance}`, 32768, true);
|
|
4046
|
+
}
|
|
4047
|
+
function decodeWorkflowProposal(v) {
|
|
4048
|
+
const modern = v !== null && typeof v === "object" && Object.hasOwn(v, "display");
|
|
4049
|
+
const o = closed(v, [
|
|
4050
|
+
"id",
|
|
4051
|
+
"epoch",
|
|
4052
|
+
"digest",
|
|
4053
|
+
"observation",
|
|
4054
|
+
"model",
|
|
4055
|
+
"plan",
|
|
4056
|
+
"cwd",
|
|
4057
|
+
...modern ? ["display"] : []
|
|
4058
|
+
]);
|
|
4059
|
+
return {
|
|
4060
|
+
id: decodeId(o.id),
|
|
4061
|
+
epoch: decodeId(o.epoch),
|
|
4062
|
+
digest: decodeHash(o.digest),
|
|
4063
|
+
observation: decodeHash(o.observation),
|
|
4064
|
+
model: decodeChoiceVersion(o.model),
|
|
4065
|
+
plan: decodeWorkflowPlan(o.plan),
|
|
4066
|
+
cwd: text(o.cwd, 4096, true),
|
|
4067
|
+
...modern ? {
|
|
4068
|
+
display: (() => {
|
|
4069
|
+
const d = closed(o.display, ["model", "branch", "baseCommit"]);
|
|
4070
|
+
return {
|
|
4071
|
+
model: text(d.model, 1024, true),
|
|
4072
|
+
branch: text(d.branch, 1024),
|
|
4073
|
+
baseCommit: text(d.baseCommit, 64)
|
|
4074
|
+
};
|
|
4075
|
+
})()
|
|
4076
|
+
} : {}
|
|
4077
|
+
};
|
|
4078
|
+
}
|
|
4079
|
+
function decodeWorkflowRequest(v) {
|
|
4080
|
+
const action = Object.getOwnPropertyDescriptor(v ?? {}, "action")?.value;
|
|
4081
|
+
if (action === "research") {
|
|
4082
|
+
const o2 = closed(v, ["action", "goal", "questions", "model"]);
|
|
4083
|
+
const questions = list(o2.questions, WORKFLOW_LIMITS.parallel, (q) => text(q, 8192, true));
|
|
4084
|
+
if (!questions.length)
|
|
4085
|
+
throw new Error("Research needs a question");
|
|
4086
|
+
return {
|
|
4087
|
+
action,
|
|
4088
|
+
goal: text(o2.goal, 8192, true),
|
|
4089
|
+
questions,
|
|
4090
|
+
model: decodeChoiceVersion(o2.model)
|
|
4091
|
+
};
|
|
4092
|
+
}
|
|
4093
|
+
if (action === "propose") {
|
|
4094
|
+
const o2 = closed(v, ["action", "plan", "model"]);
|
|
4095
|
+
return {
|
|
4096
|
+
action,
|
|
4097
|
+
plan: decodeWorkflowPlan(o2.plan),
|
|
4098
|
+
model: decodeChoiceVersion(o2.model)
|
|
4099
|
+
};
|
|
4100
|
+
}
|
|
4101
|
+
if (action === "prepare" || action === "execute") {
|
|
4102
|
+
const o2 = closed(v, action === "execute" ? ["action", "proposalId", "digest", "grant"] : ["action", "proposalId", "digest"]);
|
|
4103
|
+
const base = {
|
|
4104
|
+
proposalId: decodeId(o2.proposalId),
|
|
4105
|
+
digest: decodeHash(o2.digest)
|
|
4106
|
+
};
|
|
4107
|
+
return action === "prepare" ? { action, ...base } : { action, ...base, grant: decodeId(o2.grant) };
|
|
4108
|
+
}
|
|
4109
|
+
const o = closed(v, ["action", "runId"]);
|
|
4110
|
+
return { action: oneOf(o.action, ["cancel"]), runId: decodeId(o.runId) };
|
|
4111
|
+
}
|
|
4112
|
+
function decodeWorkflowRun(v) {
|
|
4113
|
+
const o = closed(v, [
|
|
4114
|
+
"id",
|
|
4115
|
+
"epoch",
|
|
4116
|
+
"goal",
|
|
4117
|
+
"status",
|
|
4118
|
+
"phase",
|
|
4119
|
+
"steps",
|
|
4120
|
+
"notice",
|
|
4121
|
+
"mergedCommit",
|
|
4122
|
+
"humanReviewed"
|
|
4123
|
+
]);
|
|
4124
|
+
const status = (x) => oneOf(x, [
|
|
4125
|
+
"running",
|
|
4126
|
+
"completed",
|
|
4127
|
+
"failed",
|
|
4128
|
+
"canceled",
|
|
4129
|
+
"timeout",
|
|
4130
|
+
"unknown"
|
|
4131
|
+
]);
|
|
4132
|
+
if (o.humanReviewed !== false)
|
|
4133
|
+
throw new Error("Automatic execution is not human review");
|
|
4134
|
+
return {
|
|
4135
|
+
id: decodeId(o.id),
|
|
4136
|
+
epoch: decodeId(o.epoch),
|
|
4137
|
+
goal: text(o.goal, 8192),
|
|
4138
|
+
status: o.status === "queued" ? "queued" : status(o.status),
|
|
4139
|
+
phase: oneOf(o.phase, [
|
|
4140
|
+
"research",
|
|
4141
|
+
"implementing",
|
|
4142
|
+
"verifying",
|
|
4143
|
+
"reviewing",
|
|
4144
|
+
"integrating",
|
|
4145
|
+
"finished"
|
|
4146
|
+
]),
|
|
4147
|
+
notice: text(o.notice, 2048),
|
|
4148
|
+
mergedCommit: nullable(o.mergedCommit, (s) => text(s, 64, true)),
|
|
4149
|
+
humanReviewed: false,
|
|
4150
|
+
steps: list(o.steps, 256, (v2) => {
|
|
4151
|
+
const linked = v2 !== null && typeof v2 === "object" && Object.hasOwn(v2, "childRunId");
|
|
4152
|
+
const s = closed(v2, [
|
|
4153
|
+
"id",
|
|
4154
|
+
"kind",
|
|
4155
|
+
"status",
|
|
4156
|
+
"text",
|
|
4157
|
+
"exitCode",
|
|
4158
|
+
"truncated",
|
|
4159
|
+
...linked ? ["childRunId"] : []
|
|
4160
|
+
]);
|
|
4161
|
+
return {
|
|
4162
|
+
id: text(s.id, 160, true),
|
|
4163
|
+
...linked ? { childRunId: decodeId(s.childRunId) } : {},
|
|
4164
|
+
kind: oneOf(s.kind, [
|
|
4165
|
+
"research",
|
|
4166
|
+
"implementation",
|
|
4167
|
+
"review",
|
|
4168
|
+
"check",
|
|
4169
|
+
"git"
|
|
4170
|
+
]),
|
|
4171
|
+
status: status(s.status),
|
|
4172
|
+
text: text(s.text, 65536),
|
|
4173
|
+
exitCode: nullable(s.exitCode, (n) => integer(n, -2147483648, 2147483647)),
|
|
4174
|
+
truncated: bool(s.truncated)
|
|
4175
|
+
};
|
|
4176
|
+
})
|
|
4177
|
+
};
|
|
4178
|
+
}
|
|
4179
|
+
function decodeWorkflowResponse(v) {
|
|
4180
|
+
const type = Object.getOwnPropertyDescriptor(v ?? {}, "type")?.value;
|
|
4181
|
+
if (type === "run") {
|
|
4182
|
+
const o2 = closed(v, ["type", "run"]);
|
|
4183
|
+
return { type, run: decodeWorkflowRun(o2.run) };
|
|
4184
|
+
}
|
|
4185
|
+
if (type === "proposal") {
|
|
4186
|
+
const o2 = closed(v, ["type", "proposal"]);
|
|
4187
|
+
return { type, proposal: decodeWorkflowProposal(o2.proposal) };
|
|
4188
|
+
}
|
|
4189
|
+
const o = closed(v, ["type", "proposal", "grant", "expiresAt"]);
|
|
4190
|
+
return {
|
|
4191
|
+
type: oneOf(o.type, ["grant"]),
|
|
4192
|
+
proposal: decodeWorkflowProposal(o.proposal),
|
|
4193
|
+
grant: decodeId(o.grant),
|
|
4194
|
+
expiresAt: integer(o.expiresAt, 0)
|
|
4195
|
+
};
|
|
4196
|
+
}
|
|
4197
|
+
function readableWorkflowPlan(p) {
|
|
4198
|
+
return `# ${p.goal}
|
|
4199
|
+
|
|
4200
|
+
## Design
|
|
4201
|
+
${p.design}
|
|
4202
|
+
|
|
4203
|
+
## Decisions
|
|
4204
|
+
${p.decisions}
|
|
4205
|
+
|
|
4206
|
+
## Acceptance
|
|
4207
|
+
${p.acceptance}
|
|
4208
|
+
|
|
4209
|
+
## Tasks
|
|
4210
|
+
${workflowOrder(p.tasks).map((t) => `### ${t.id}: ${t.title}
|
|
4211
|
+
Depends on: ${t.after.join(", ") || "none"}
|
|
4212
|
+
Writes: ${t.writes.join(", ")}
|
|
4213
|
+
${t.instructions}`).join(`
|
|
4214
|
+
|
|
4215
|
+
`)}
|
|
4216
|
+
|
|
4217
|
+
## Setup (explicitly authorized commands)
|
|
4218
|
+
${p.setup.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join(`
|
|
4219
|
+
`) || "None; no dependency installation or copying."}
|
|
4220
|
+
|
|
4221
|
+
## Baseline verification
|
|
4222
|
+
${p.baselineChecks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join(`
|
|
4223
|
+
`) || "No separate baseline checks declared."}
|
|
4224
|
+
|
|
4225
|
+
## Verification
|
|
4226
|
+
${p.checks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join(`
|
|
4227
|
+
`)}
|
|
4228
|
+
|
|
4229
|
+
## Automation boundary
|
|
4230
|
+
At most ${p.repairAttempts} repair rounds. ${p.delivery === "local-merge" ? "Authorize isolated task worktrees, local task commits and fast-forward integration into the current branch." : "Direct working-copy edits; failures leave actual edits for inspection. No Git commit or merge."} No push, publication, deployment, unplanned installation or recursive delegation. Generated project context and workflow Markdown are included. Worktrees/tools are not a sandbox.
|
|
4231
|
+
|
|
4232
|
+
## Project context
|
|
4233
|
+
${p.projectContext}
|
|
4234
|
+
`;
|
|
4235
|
+
}
|
|
4236
|
+
|
|
3914
4237
|
// src/service/contracts/workbench.ts
|
|
4238
|
+
function decodeCadenceConversation(v) {
|
|
4239
|
+
const o = closed(v, [
|
|
4240
|
+
"id",
|
|
4241
|
+
"revision",
|
|
4242
|
+
"enabled",
|
|
4243
|
+
"head",
|
|
4244
|
+
"proposal",
|
|
4245
|
+
"runs"
|
|
4246
|
+
]);
|
|
4247
|
+
return {
|
|
4248
|
+
id: decodeId(o.id),
|
|
4249
|
+
revision: integer(o.revision, 0),
|
|
4250
|
+
enabled: bool(o.enabled),
|
|
4251
|
+
head: nullable(o.head, decodeId),
|
|
4252
|
+
proposal: nullable(o.proposal, decodeWorkflowProposal),
|
|
4253
|
+
runs: list(o.runs, 200, decodeId)
|
|
4254
|
+
};
|
|
4255
|
+
}
|
|
3915
4256
|
var statuses = [
|
|
3916
4257
|
"queued",
|
|
3917
4258
|
"running",
|
|
@@ -3924,6 +4265,22 @@ var statuses = [
|
|
|
3924
4265
|
function decodeWorkbenchRead(v) {
|
|
3925
4266
|
const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
|
|
3926
4267
|
switch (kind) {
|
|
4268
|
+
case "cadence-conversation": {
|
|
4269
|
+
const o = closed(v, ["kind", "id"]);
|
|
4270
|
+
return { kind, id: decodeId(o.id) };
|
|
4271
|
+
}
|
|
4272
|
+
case "workflow-active":
|
|
4273
|
+
closed(v, ["kind"]);
|
|
4274
|
+
return { kind };
|
|
4275
|
+
case "workflow-transcript":
|
|
4276
|
+
case "workflow-detail": {
|
|
4277
|
+
const o = closed(v, ["kind", "id", "stepId"]);
|
|
4278
|
+
return { kind, id: decodeId(o.id), stepId: text(o.stepId, 160, true) };
|
|
4279
|
+
}
|
|
4280
|
+
case "workflow": {
|
|
4281
|
+
const o = closed(v, ["kind", "id"]);
|
|
4282
|
+
return { kind, id: decodeId(o.id) };
|
|
4283
|
+
}
|
|
3927
4284
|
case "conversations":
|
|
3928
4285
|
case "projects":
|
|
3929
4286
|
closed(v, ["kind"]);
|
|
@@ -3947,6 +4304,77 @@ function decodeWorkbenchRead(v) {
|
|
|
3947
4304
|
}
|
|
3948
4305
|
function decodeWorkbenchCommand(v) {
|
|
3949
4306
|
const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
|
|
4307
|
+
if (kind === "restore-model" || kind === "workflow-cancel") {
|
|
4308
|
+
const o2 = closed(v, kind === "restore-model" ? ["kind", "commandId", "epoch"] : ["kind", "commandId", "epoch", "runId"]);
|
|
4309
|
+
const base = { commandId: decodeId(o2.commandId), epoch: decodeId(o2.epoch) };
|
|
4310
|
+
return kind === "restore-model" ? { kind, ...base } : { kind, ...base, runId: decodeId(o2.runId) };
|
|
4311
|
+
}
|
|
4312
|
+
if (kind === "cadence-exit") {
|
|
4313
|
+
const o2 = closed(v, [
|
|
4314
|
+
"kind",
|
|
4315
|
+
"commandId",
|
|
4316
|
+
"conversationId",
|
|
4317
|
+
"head",
|
|
4318
|
+
"revision"
|
|
4319
|
+
]);
|
|
4320
|
+
return {
|
|
4321
|
+
kind,
|
|
4322
|
+
commandId: decodeId(o2.commandId),
|
|
4323
|
+
conversationId: decodeId(o2.conversationId),
|
|
4324
|
+
head: nullable(o2.head, decodeId),
|
|
4325
|
+
revision: integer(o2.revision, 0)
|
|
4326
|
+
};
|
|
4327
|
+
}
|
|
4328
|
+
if (kind === "cadence-send") {
|
|
4329
|
+
const o2 = closed(v, [
|
|
4330
|
+
"kind",
|
|
4331
|
+
"commandId",
|
|
4332
|
+
"conversationId",
|
|
4333
|
+
"head",
|
|
4334
|
+
"text",
|
|
4335
|
+
"model",
|
|
4336
|
+
"revision",
|
|
4337
|
+
"intent"
|
|
4338
|
+
]);
|
|
4339
|
+
return {
|
|
4340
|
+
kind,
|
|
4341
|
+
commandId: decodeId(o2.commandId),
|
|
4342
|
+
conversationId: decodeId(o2.conversationId),
|
|
4343
|
+
head: nullable(o2.head, decodeId),
|
|
4344
|
+
text: text(o2.text, 16384, true),
|
|
4345
|
+
model: decodeChoiceVersion(o2.model),
|
|
4346
|
+
revision: integer(o2.revision, 0),
|
|
4347
|
+
intent: oneOf(o2.intent, ["message", "enter", "exit"])
|
|
4348
|
+
};
|
|
4349
|
+
}
|
|
4350
|
+
if (kind === "cadence-prepare" || kind === "cadence-approve") {
|
|
4351
|
+
const keys2 = [
|
|
4352
|
+
"kind",
|
|
4353
|
+
"commandId",
|
|
4354
|
+
"conversationId",
|
|
4355
|
+
"revision",
|
|
4356
|
+
"proposalId",
|
|
4357
|
+
"digest"
|
|
4358
|
+
];
|
|
4359
|
+
const o2 = closed(v, kind === "cadence-approve" ? [...keys2, "grant"] : keys2);
|
|
4360
|
+
const base = {
|
|
4361
|
+
commandId: decodeId(o2.commandId),
|
|
4362
|
+
conversationId: decodeId(o2.conversationId),
|
|
4363
|
+
revision: integer(o2.revision, 0),
|
|
4364
|
+
proposalId: decodeId(o2.proposalId),
|
|
4365
|
+
digest: decodeHash(o2.digest)
|
|
4366
|
+
};
|
|
4367
|
+
return kind === "cadence-prepare" ? { kind, ...base } : { kind, ...base, grant: decodeId(o2.grant) };
|
|
4368
|
+
}
|
|
4369
|
+
if (kind === "workflow") {
|
|
4370
|
+
const o2 = closed(v, ["kind", "commandId", "epoch", "request"]);
|
|
4371
|
+
return {
|
|
4372
|
+
kind,
|
|
4373
|
+
commandId: decodeId(o2.commandId),
|
|
4374
|
+
epoch: decodeId(o2.epoch),
|
|
4375
|
+
request: decodeWorkflowRequest(o2.request)
|
|
4376
|
+
};
|
|
4377
|
+
}
|
|
3950
4378
|
if (kind === "link-task") {
|
|
3951
4379
|
const o2 = closed(v, [
|
|
3952
4380
|
"kind",
|
|
@@ -4006,12 +4434,20 @@ function decodeWorkbenchCommand(v) {
|
|
|
4006
4434
|
};
|
|
4007
4435
|
}
|
|
4008
4436
|
function decodeChatTurn(v) {
|
|
4009
|
-
const
|
|
4437
|
+
const keys2 = ["id", "epoch", "status", "items", "notice"];
|
|
4438
|
+
const current = v !== null && typeof v === "object" && Object.hasOwn(v, "omitted");
|
|
4439
|
+
const o = closed(v, current ? [...keys2, "omitted"] : keys2);
|
|
4440
|
+
const omitted = current ? closed(o.omitted, ["thinking", "media", "other"]) : null;
|
|
4010
4441
|
return {
|
|
4011
4442
|
id: decodeId(o.id),
|
|
4012
4443
|
epoch: decodeId(o.epoch),
|
|
4013
4444
|
status: oneOf(o.status, statuses),
|
|
4014
4445
|
notice: text(o.notice, 1024),
|
|
4446
|
+
omitted: {
|
|
4447
|
+
thinking: omitted ? bool(omitted.thinking) : false,
|
|
4448
|
+
media: omitted ? bool(omitted.media) : false,
|
|
4449
|
+
other: omitted ? bool(omitted.other) : false
|
|
4450
|
+
},
|
|
4015
4451
|
items: list(o.items, 256, (v2) => {
|
|
4016
4452
|
const i = closed(v2, ["id", "role", "text", "name", "args", "error"]);
|
|
4017
4453
|
return {
|
|
@@ -4026,18 +4462,71 @@ function decodeChatTurn(v) {
|
|
|
4026
4462
|
};
|
|
4027
4463
|
}
|
|
4028
4464
|
function decodeChatSummary(v) {
|
|
4029
|
-
const
|
|
4465
|
+
const modern = v !== null && typeof v === "object" && Object.hasOwn(v, "cadence");
|
|
4466
|
+
const o = closed(v, [
|
|
4467
|
+
"id",
|
|
4468
|
+
"title",
|
|
4469
|
+
"head",
|
|
4470
|
+
"status",
|
|
4471
|
+
"updatedAt",
|
|
4472
|
+
...modern ? ["cadence"] : []
|
|
4473
|
+
]);
|
|
4030
4474
|
return {
|
|
4031
4475
|
id: decodeId(o.id),
|
|
4032
4476
|
title: text(o.title, 512, true),
|
|
4033
4477
|
head: decodeId(o.head),
|
|
4034
4478
|
status: oneOf(o.status, statuses),
|
|
4035
|
-
updatedAt: integer(o.updatedAt, 0)
|
|
4479
|
+
updatedAt: integer(o.updatedAt, 0),
|
|
4480
|
+
...modern ? { cadence: bool(o.cadence) } : {}
|
|
4036
4481
|
};
|
|
4037
4482
|
}
|
|
4038
4483
|
function decodeWorkbenchResult(v) {
|
|
4039
4484
|
canonicalJson(v, 512 * 1024);
|
|
4485
|
+
const k = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
|
|
4486
|
+
if (k === "workflow-transcript") {
|
|
4487
|
+
const o2 = closed(v, ["kind", "runId", "stepId", "turn"]);
|
|
4488
|
+
return {
|
|
4489
|
+
kind: k,
|
|
4490
|
+
runId: decodeId(o2.runId),
|
|
4491
|
+
stepId: text(o2.stepId, 160, true),
|
|
4492
|
+
turn: nullable(o2.turn, decodeChatTurn)
|
|
4493
|
+
};
|
|
4494
|
+
}
|
|
4495
|
+
if (k === "cadence-conversation") {
|
|
4496
|
+
const o2 = closed(v, ["kind", "state"]);
|
|
4497
|
+
return { kind: k, state: decodeCadenceConversation(o2.state) };
|
|
4498
|
+
}
|
|
4499
|
+
if (k === "workflow-active") {
|
|
4500
|
+
const o2 = closed(v, ["kind", "runs"]);
|
|
4501
|
+
return { kind: k, runs: list(o2.runs, 4, decodeWorkflowRun) };
|
|
4502
|
+
}
|
|
4503
|
+
if (k === "cadence-grant") {
|
|
4504
|
+
const o2 = closed(v, [
|
|
4505
|
+
"kind",
|
|
4506
|
+
"commandId",
|
|
4507
|
+
"grant",
|
|
4508
|
+
"expiresAt",
|
|
4509
|
+
"revision",
|
|
4510
|
+
"proposal"
|
|
4511
|
+
]);
|
|
4512
|
+
return {
|
|
4513
|
+
kind: k,
|
|
4514
|
+
commandId: decodeId(o2.commandId),
|
|
4515
|
+
grant: decodeId(o2.grant),
|
|
4516
|
+
expiresAt: integer(o2.expiresAt, 0),
|
|
4517
|
+
revision: integer(o2.revision, 0),
|
|
4518
|
+
proposal: decodeWorkflowProposal(o2.proposal)
|
|
4519
|
+
};
|
|
4520
|
+
}
|
|
4040
4521
|
const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
|
|
4522
|
+
if (kind === "workflow") {
|
|
4523
|
+
const o2 = closed(v, ["kind", "commandId", "response"]);
|
|
4524
|
+
return {
|
|
4525
|
+
kind,
|
|
4526
|
+
commandId: nullable(o2.commandId, decodeId),
|
|
4527
|
+
response: decodeWorkflowResponse(o2.response)
|
|
4528
|
+
};
|
|
4529
|
+
}
|
|
4041
4530
|
if (kind === "task-origin") {
|
|
4042
4531
|
const o2 = closed(v, ["kind", "taskId", "conversationId"]);
|
|
4043
4532
|
return {
|
|
@@ -5555,7 +6044,9 @@ class ServiceCoordination {
|
|
|
5555
6044
|
"access.json",
|
|
5556
6045
|
"host-config.json",
|
|
5557
6046
|
"history-v2",
|
|
5558
|
-
"conversations-v1"
|
|
6047
|
+
"conversations-v1",
|
|
6048
|
+
"conversation-workflows-v1",
|
|
6049
|
+
"workflows-v1"
|
|
5559
6050
|
]);
|
|
5560
6051
|
this.files.directory(join6(directory, "history-v2"), false, walks);
|
|
5561
6052
|
}
|
|
@@ -7656,9 +8147,9 @@ class TaskPublicationLineage {
|
|
|
7656
8147
|
};
|
|
7657
8148
|
endpoint = null;
|
|
7658
8149
|
graphIdentity = null;
|
|
7659
|
-
apply(row, seq,
|
|
8150
|
+
apply(row, seq, taskId2, savedGraphIdentity) {
|
|
7660
8151
|
const v = row.value;
|
|
7661
|
-
if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id ===
|
|
8152
|
+
if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id === taskId2) {
|
|
7662
8153
|
const i2 = v.intent.identity;
|
|
7663
8154
|
requireFact(i2.expected.task);
|
|
7664
8155
|
if (i2.action.kind === "save-plan") {
|
|
@@ -7681,7 +8172,7 @@ class TaskPublicationLineage {
|
|
|
7681
8172
|
for (const e of v.events) {
|
|
7682
8173
|
if (e.kind !== "owner" || e.value.kind !== "fact" || e.value.fact.kind !== "publication-intent" && e.value.fact.kind !== "publication-settled")
|
|
7683
8174
|
continue;
|
|
7684
|
-
requireFact(v.link.taskId ===
|
|
8175
|
+
requireFact(v.link.taskId === taskId2 && v.link.epoch === i.expected.epoch && v.link.runId === this.operation.runId);
|
|
7685
8176
|
this.state = publicationTransition(this.state, i.expected.task, e.value.fact, seq);
|
|
7686
8177
|
if (this.state.status === "published" && this.state.intent)
|
|
7687
8178
|
this.endpoint = {
|
|
@@ -8909,6 +9400,12 @@ import {
|
|
|
8909
9400
|
createServer
|
|
8910
9401
|
} from "node:http";
|
|
8911
9402
|
import { WebSocketServer } from "ws";
|
|
9403
|
+
|
|
9404
|
+
// src/service/workbench-send-refusal.ts
|
|
9405
|
+
class UnacceptedConversationCommand extends ContractError {
|
|
9406
|
+
}
|
|
9407
|
+
|
|
9408
|
+
// src/service/http.ts
|
|
8912
9409
|
function refusal(code2 = "invalid", uncertain = false) {
|
|
8913
9410
|
return {
|
|
8914
9411
|
kind: "error",
|
|
@@ -9324,7 +9821,7 @@ Content-Length: 0\r
|
|
|
9324
9821
|
else {
|
|
9325
9822
|
const code2 = e instanceof ContractError ? e.code : "unavailable";
|
|
9326
9823
|
res.setHeader("Connection", "close");
|
|
9327
|
-
send(res, errorStatus(code2), refusal(code2, dispatched));
|
|
9824
|
+
send(res, errorStatus(code2), refusal(code2, dispatched && !(e instanceof UnacceptedConversationCommand)));
|
|
9328
9825
|
}
|
|
9329
9826
|
} finally {
|
|
9330
9827
|
clearTimeout(timer);
|
|
@@ -9389,13 +9886,17 @@ Content-Length: 0\r
|
|
|
9389
9886
|
kind: "ok",
|
|
9390
9887
|
value: a.workbench.read(decodeWorkbenchRead(input))
|
|
9391
9888
|
};
|
|
9392
|
-
case "workbenchCommand":
|
|
9889
|
+
case "workbenchCommand": {
|
|
9393
9890
|
if (!a.workbench)
|
|
9394
9891
|
unavailable();
|
|
9892
|
+
const command = decodeWorkbenchCommand(input);
|
|
9893
|
+
if (command.kind === "workflow" && caller.authority !== "local")
|
|
9894
|
+
throw new ContractError("forbidden");
|
|
9395
9895
|
return {
|
|
9396
9896
|
kind: "ok",
|
|
9397
|
-
value: await a.workbench.command(
|
|
9897
|
+
value: await a.workbench.command(command, caller)
|
|
9398
9898
|
};
|
|
9899
|
+
}
|
|
9399
9900
|
case "current":
|
|
9400
9901
|
if (!a.current)
|
|
9401
9902
|
unavailable();
|
|
@@ -9778,6 +10279,81 @@ import { dirname as dirname10, isAbsolute as isAbsolute6, join as join12, relati
|
|
|
9778
10279
|
// src/worker-redaction.mjs
|
|
9779
10280
|
var marker = "[redacted]";
|
|
9780
10281
|
var sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|password|passwd|secret|token|api[-_]?key|access[-_]?token|refresh[-_]?token|credentials|headers|env)$/i;
|
|
10282
|
+
function own(value, name) {
|
|
10283
|
+
if (!value || typeof value !== "object")
|
|
10284
|
+
throw new ContractError;
|
|
10285
|
+
const d = Object.getOwnPropertyDescriptor(value, name);
|
|
10286
|
+
if (!d)
|
|
10287
|
+
return;
|
|
10288
|
+
if (!("value" in d))
|
|
10289
|
+
throw new ContractError;
|
|
10290
|
+
return d.value;
|
|
10291
|
+
}
|
|
10292
|
+
function ownArray(value, maximum = LIMITS.dataFrames) {
|
|
10293
|
+
if (!Array.isArray(value))
|
|
10294
|
+
throw new ContractError;
|
|
10295
|
+
const length = own(value, "length");
|
|
10296
|
+
if (!Number.isSafeInteger(length) || length > maximum)
|
|
10297
|
+
throw new ContractError("oversize");
|
|
10298
|
+
return Array.from({ length }, (_, index) => own(value, String(index)));
|
|
10299
|
+
}
|
|
10300
|
+
function sourceBytes(value) {
|
|
10301
|
+
let bytes = 0;
|
|
10302
|
+
for (let i = 0;i < value.length; i++) {
|
|
10303
|
+
const code2 = value.charCodeAt(i);
|
|
10304
|
+
if (code2 < 128)
|
|
10305
|
+
bytes++;
|
|
10306
|
+
else if (code2 < 2048)
|
|
10307
|
+
bytes += 2;
|
|
10308
|
+
else if (code2 >= 55296 && code2 <= 56319 && value.charCodeAt(i + 1) >= 56320 && value.charCodeAt(i + 1) <= 57343) {
|
|
10309
|
+
bytes += 4;
|
|
10310
|
+
i++;
|
|
10311
|
+
} else if (code2 >= 55296 && code2 <= 57343)
|
|
10312
|
+
throw new ContractError;
|
|
10313
|
+
else
|
|
10314
|
+
bytes += 3;
|
|
10315
|
+
}
|
|
10316
|
+
return bytes;
|
|
10317
|
+
}
|
|
10318
|
+
function measureData(value, maximum = LIMITS.workerQueueBytes) {
|
|
10319
|
+
let bytes = 0;
|
|
10320
|
+
let nodes = 0;
|
|
10321
|
+
const seen = new Set;
|
|
10322
|
+
function visit(v, depth) {
|
|
10323
|
+
if (++nodes > LIMITS.dataFrames || depth > 64)
|
|
10324
|
+
throw new ContractError("oversize");
|
|
10325
|
+
if (typeof v === "string")
|
|
10326
|
+
bytes += sourceBytes(v) * 6 + 2;
|
|
10327
|
+
else if (v === null || typeof v === "boolean")
|
|
10328
|
+
bytes += 5;
|
|
10329
|
+
else if (typeof v === "number" && Number.isFinite(v))
|
|
10330
|
+
bytes += 32;
|
|
10331
|
+
else if (v && typeof v === "object") {
|
|
10332
|
+
if (seen.has(v) || ![Object.prototype, Array.prototype, null].includes(Object.getPrototypeOf(v)))
|
|
10333
|
+
throw new ContractError;
|
|
10334
|
+
seen.add(v);
|
|
10335
|
+
bytes += 2;
|
|
10336
|
+
const names2 = Reflect.ownKeys(v);
|
|
10337
|
+
if (names2.length > LIMITS.dataFrames)
|
|
10338
|
+
throw new ContractError("oversize");
|
|
10339
|
+
for (const key of names2) {
|
|
10340
|
+
if (Array.isArray(v) && key === "length")
|
|
10341
|
+
continue;
|
|
10342
|
+
if (typeof key !== "string")
|
|
10343
|
+
throw new ContractError;
|
|
10344
|
+
bytes += sourceBytes(key) * 6 + 4;
|
|
10345
|
+
visit(own(v, key), depth + 1);
|
|
10346
|
+
}
|
|
10347
|
+
seen.delete(v);
|
|
10348
|
+
} else
|
|
10349
|
+
throw new ContractError;
|
|
10350
|
+
if (bytes > maximum)
|
|
10351
|
+
throw new ContractError("oversize");
|
|
10352
|
+
}
|
|
10353
|
+
visit(value, 0);
|
|
10354
|
+
return bytes;
|
|
10355
|
+
}
|
|
10356
|
+
|
|
9781
10357
|
class TextSanitizer {
|
|
9782
10358
|
constructor(secrets = []) {
|
|
9783
10359
|
if (secrets.some((s) => typeof s !== "string") || secrets.reduce((n, s) => n + utf8Bytes(s), 0) > LIMITS.workerRequestBytes * 2)
|
|
@@ -9923,6 +10499,27 @@ function sanitizeText(value, secrets = []) {
|
|
|
9923
10499
|
const sanitizer = new TextSanitizer(secrets);
|
|
9924
10500
|
return sanitizer.write(value, true);
|
|
9925
10501
|
}
|
|
10502
|
+
function sanitizeData(value, secrets = []) {
|
|
10503
|
+
measureData(value);
|
|
10504
|
+
function visit(v) {
|
|
10505
|
+
if (typeof v === "string")
|
|
10506
|
+
return sanitizeText(v, secrets);
|
|
10507
|
+
if (v === null || typeof v !== "object")
|
|
10508
|
+
return v;
|
|
10509
|
+
if (Array.isArray(v))
|
|
10510
|
+
return ownArray(v).map(visit);
|
|
10511
|
+
const result = Object.create(null);
|
|
10512
|
+
for (const key of Object.keys(v).sort()) {
|
|
10513
|
+
const safeKey = sanitizeText(key, secrets);
|
|
10514
|
+
if (Object.hasOwn(result, safeKey))
|
|
10515
|
+
throw new ContractError;
|
|
10516
|
+
result[safeKey] = sensitive.test(key) ? marker : visit(own(v, key));
|
|
10517
|
+
}
|
|
10518
|
+
return result;
|
|
10519
|
+
}
|
|
10520
|
+
return canonicalJson(visit(value), LIMITS.workerQueueBytes);
|
|
10521
|
+
}
|
|
10522
|
+
|
|
9926
10523
|
class DetailSanitizer {
|
|
9927
10524
|
constructor(encoding, secrets = [], partial = false) {
|
|
9928
10525
|
this.encoding = encoding;
|
|
@@ -10285,7 +10882,7 @@ async function createGateway(value, hostUrl, source) {
|
|
|
10285
10882
|
const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
|
|
10286
10883
|
const web = loadWebAssets(source?.webDirectory);
|
|
10287
10884
|
const build2 = {
|
|
10288
|
-
contractHash: "
|
|
10885
|
+
contractHash: "d19e63723270a27a4c00776d8301849e08480e054bc832ca455f889d061c65c9",
|
|
10289
10886
|
assets: {
|
|
10290
10887
|
sourceHash: web.manifest.sourceHash,
|
|
10291
10888
|
contractHash: web.manifest.contractHash,
|
|
@@ -10854,8 +11451,8 @@ Content-Length: 0\r
|
|
|
10854
11451
|
}
|
|
10855
11452
|
|
|
10856
11453
|
// src/service/host.ts
|
|
10857
|
-
import { lstatSync as
|
|
10858
|
-
import { join as
|
|
11454
|
+
import { lstatSync as lstatSync16, opendirSync as opendirSync11 } from "node:fs";
|
|
11455
|
+
import { join as join28 } from "node:path";
|
|
10859
11456
|
|
|
10860
11457
|
// src/agent-registry.ts
|
|
10861
11458
|
import { createHash as createHash10 } from "node:crypto";
|
|
@@ -10882,6 +11479,43 @@ function loadAgentDefinitions() {
|
|
|
10882
11479
|
});
|
|
10883
11480
|
}
|
|
10884
11481
|
|
|
11482
|
+
// src/cadence-preferences.ts
|
|
11483
|
+
import { join as join13 } from "node:path";
|
|
11484
|
+
class CadencePreferences {
|
|
11485
|
+
path;
|
|
11486
|
+
files;
|
|
11487
|
+
constructor(agentDir) {
|
|
11488
|
+
this.path = join13(agentDir, "cadence", "settings.json");
|
|
11489
|
+
this.files = new PrivateFiles(agentDir, false);
|
|
11490
|
+
}
|
|
11491
|
+
read() {
|
|
11492
|
+
const saved = this.files.read(this.path);
|
|
11493
|
+
if (!saved)
|
|
11494
|
+
return null;
|
|
11495
|
+
const o = closed(parseWireJson(saved.bytes.toString("utf8")), [
|
|
11496
|
+
"schema",
|
|
11497
|
+
"model"
|
|
11498
|
+
]);
|
|
11499
|
+
if (o.schema !== "cadence-preferences/1")
|
|
11500
|
+
throw new Error("Unsupported Cadence preferences");
|
|
11501
|
+
return decodeModelSelector(o.model);
|
|
11502
|
+
}
|
|
11503
|
+
save(model) {
|
|
11504
|
+
const selected2 = decodeModelSelector(model);
|
|
11505
|
+
const previous = this.files.read(this.path);
|
|
11506
|
+
if (previous && canonicalJson(this.read()) === canonicalJson(selected2))
|
|
11507
|
+
return;
|
|
11508
|
+
const bytes = canonicalJson({
|
|
11509
|
+
schema: "cadence-preferences/1",
|
|
11510
|
+
model: selected2
|
|
11511
|
+
});
|
|
11512
|
+
if (previous)
|
|
11513
|
+
this.files.replace(this.path, previous, bytes);
|
|
11514
|
+
else
|
|
11515
|
+
this.files.create(this.path, bytes);
|
|
11516
|
+
}
|
|
11517
|
+
}
|
|
11518
|
+
|
|
10885
11519
|
// src/history/live.ts
|
|
10886
11520
|
function scopedSnapshot(source, scope) {
|
|
10887
11521
|
if (scope.kind === "task" || source.scope.kind === "child")
|
|
@@ -11132,11 +11766,11 @@ class HistoryLive {
|
|
|
11132
11766
|
// src/history/navigation.ts
|
|
11133
11767
|
import { createHash as createHash11 } from "node:crypto";
|
|
11134
11768
|
import { lstatSync as lstatSync10 } from "node:fs";
|
|
11135
|
-
import { dirname as dirname11, join as
|
|
11769
|
+
import { dirname as dirname11, join as join15 } from "node:path";
|
|
11136
11770
|
|
|
11137
11771
|
// src/history/index-tree.ts
|
|
11138
11772
|
import { lstatSync as lstatSync9 } from "node:fs";
|
|
11139
|
-
import { join as
|
|
11773
|
+
import { join as join14 } from "node:path";
|
|
11140
11774
|
var MAX_NODE = 16 * 1024;
|
|
11141
11775
|
var ACTIVE_KEY = "active";
|
|
11142
11776
|
function chainHash(seq, previous, previousHash) {
|
|
@@ -11179,7 +11813,7 @@ class IndexTree {
|
|
|
11179
11813
|
this.files = files;
|
|
11180
11814
|
}
|
|
11181
11815
|
path(id) {
|
|
11182
|
-
return
|
|
11816
|
+
return join14(this.files.directory, "indexes", "nodes", id.slice(0, 2), `${id}.json`);
|
|
11183
11817
|
}
|
|
11184
11818
|
load(id, budget, unit) {
|
|
11185
11819
|
decodeHash(id);
|
|
@@ -11512,7 +12146,7 @@ class HistoryNavigation {
|
|
|
11512
12146
|
}
|
|
11513
12147
|
}
|
|
11514
12148
|
indexPath(group, id) {
|
|
11515
|
-
return
|
|
12149
|
+
return join15(this.files.directory, "indexes", group, `${id}.json`);
|
|
11516
12150
|
}
|
|
11517
12151
|
hintKey(group, id) {
|
|
11518
12152
|
return `${this.files.directory}/${this.files.format.storeId}/${group}/${id}`;
|
|
@@ -11679,17 +12313,17 @@ class HistoryNavigation {
|
|
|
11679
12313
|
continue;
|
|
11680
12314
|
this.write(lease, "run-locators", runId, { pointers: [...pointers, p] }, charge, true);
|
|
11681
12315
|
}
|
|
11682
|
-
for (const
|
|
11683
|
-
const head = prepared?.heads.get(`roster:${
|
|
11684
|
-
const old = head ? undefined : this.files.files.read(this.indexPath("rosters",
|
|
12316
|
+
for (const taskId2 of rosters) {
|
|
12317
|
+
const head = prepared?.heads.get(`roster:${taskId2}`);
|
|
12318
|
+
const old = head ? undefined : this.files.files.read(this.indexPath("rosters", taskId2));
|
|
11685
12319
|
const previous = head ? head.previous : old ? decodeSequence(closed(parseWireJson(old.bytes.toString("utf8")), ["seq"]).seq) : null;
|
|
11686
|
-
this.write(lease, "roster-links", `${
|
|
12320
|
+
this.write(lease, "roster-links", `${taskId2}/${p.seq}`, {
|
|
11687
12321
|
pointer: p,
|
|
11688
12322
|
previous,
|
|
11689
12323
|
...head ? { hash: head.hash, previousHash: head.previousHash } : {}
|
|
11690
12324
|
}, charge);
|
|
11691
12325
|
if (!head)
|
|
11692
|
-
this.write(lease, "rosters",
|
|
12326
|
+
this.write(lease, "rosters", taskId2, { seq: p.seq }, charge, true);
|
|
11693
12327
|
}
|
|
11694
12328
|
this.write(lease, "heads", "latest", p, charge, true);
|
|
11695
12329
|
}
|
|
@@ -12098,16 +12732,16 @@ class HistoryNavigation {
|
|
|
12098
12732
|
previous: previous !== null && previousHash !== null ? { seq: previous, hash: previousHash } : null
|
|
12099
12733
|
};
|
|
12100
12734
|
}
|
|
12101
|
-
taskSuffix(
|
|
12102
|
-
decodeId(
|
|
12735
|
+
taskSuffix(taskId2, snapshot, budget, accept) {
|
|
12736
|
+
decodeId(taskId2);
|
|
12103
12737
|
try {
|
|
12104
|
-
let head = this.anchoredHead(
|
|
12738
|
+
let head = this.anchoredHead(taskId2, snapshot, budget) ?? null;
|
|
12105
12739
|
const newer = [];
|
|
12106
12740
|
while (head) {
|
|
12107
12741
|
const base = accept(head);
|
|
12108
12742
|
if (base !== undefined)
|
|
12109
12743
|
return { base, batches: newer.reverse() };
|
|
12110
|
-
const link = this.link("entity-links",
|
|
12744
|
+
const link = this.link("entity-links", taskId2, head, budget);
|
|
12111
12745
|
newer.push(this.batch(link.pointer, budget));
|
|
12112
12746
|
head = link.previous;
|
|
12113
12747
|
}
|
|
@@ -12307,16 +12941,16 @@ var STATES = 8;
|
|
|
12307
12941
|
|
|
12308
12942
|
class TaskFoldMemory {
|
|
12309
12943
|
tasks = new Map;
|
|
12310
|
-
has(
|
|
12311
|
-
return this.tasks.has(
|
|
12944
|
+
has(taskId2) {
|
|
12945
|
+
return this.tasks.has(taskId2);
|
|
12312
12946
|
}
|
|
12313
|
-
remember(
|
|
12314
|
-
let states = this.tasks.get(
|
|
12947
|
+
remember(taskId2, anchor, state) {
|
|
12948
|
+
let states = this.tasks.get(taskId2);
|
|
12315
12949
|
if (!states) {
|
|
12316
12950
|
if (this.tasks.size >= TASKS)
|
|
12317
12951
|
this.tasks.delete(this.tasks.keys().next().value ?? "");
|
|
12318
12952
|
states = new Map;
|
|
12319
|
-
this.tasks.set(
|
|
12953
|
+
this.tasks.set(taskId2, states);
|
|
12320
12954
|
}
|
|
12321
12955
|
states.delete(anchor.seq);
|
|
12322
12956
|
states.set(anchor.seq, {
|
|
@@ -12326,8 +12960,8 @@ class TaskFoldMemory {
|
|
|
12326
12960
|
if (states.size > STATES)
|
|
12327
12961
|
states.delete(states.keys().next().value ?? "");
|
|
12328
12962
|
}
|
|
12329
|
-
recall(
|
|
12330
|
-
const entry = this.tasks.get(
|
|
12963
|
+
recall(taskId2, anchor) {
|
|
12964
|
+
const entry = this.tasks.get(taskId2)?.get(anchor.seq);
|
|
12331
12965
|
return entry?.hash === anchor.hash ? structuredClone(entry.state) : undefined;
|
|
12332
12966
|
}
|
|
12333
12967
|
}
|
|
@@ -12341,10 +12975,10 @@ function taskFoldMemory(files) {
|
|
|
12341
12975
|
}
|
|
12342
12976
|
return memory;
|
|
12343
12977
|
}
|
|
12344
|
-
function resumeTaskFold(files, navigation,
|
|
12978
|
+
function resumeTaskFold(files, navigation, taskId2, snapshot, budget, resume) {
|
|
12345
12979
|
const memory = taskFoldMemory(files);
|
|
12346
|
-
const suffix = memory.has(
|
|
12347
|
-
const state = memory.recall(
|
|
12980
|
+
const suffix = memory.has(taskId2) ? navigation.taskSuffix(taskId2, snapshot, budget, (head) => {
|
|
12981
|
+
const state = memory.recall(taskId2, head);
|
|
12348
12982
|
if (!state)
|
|
12349
12983
|
return;
|
|
12350
12984
|
try {
|
|
@@ -12356,7 +12990,7 @@ function resumeTaskFold(files, navigation, taskId, snapshot, budget, resume) {
|
|
|
12356
12990
|
}) : undefined;
|
|
12357
12991
|
return suffix ?? {
|
|
12358
12992
|
base: undefined,
|
|
12359
|
-
batches: navigation.entityBatches(
|
|
12993
|
+
batches: navigation.entityBatches(taskId2, snapshot, budget) ?? navigation.scanSnapshot(snapshot, budget)
|
|
12360
12994
|
};
|
|
12361
12995
|
}
|
|
12362
12996
|
|
|
@@ -12368,10 +13002,10 @@ class CheckFold {
|
|
|
12368
13002
|
this.starts = new Map(state?.starts);
|
|
12369
13003
|
this.settled = new Map(state?.settled);
|
|
12370
13004
|
}
|
|
12371
|
-
apply(batch,
|
|
13005
|
+
apply(batch, taskId2) {
|
|
12372
13006
|
for (const row of batch.rows) {
|
|
12373
13007
|
const v = row.value;
|
|
12374
|
-
if (v.kind !== "owner" || v.link.taskId !==
|
|
13008
|
+
if (v.kind !== "owner" || v.link.taskId !== taskId2)
|
|
12375
13009
|
continue;
|
|
12376
13010
|
for (const e of v.events) {
|
|
12377
13011
|
if (e.kind !== "owner" || e.value.kind !== "fact")
|
|
@@ -12412,7 +13046,7 @@ class CheckFold {
|
|
|
12412
13046
|
settled: [...this.settled]
|
|
12413
13047
|
};
|
|
12414
13048
|
}
|
|
12415
|
-
evaluate(
|
|
13049
|
+
evaluate(taskId2, configured, current) {
|
|
12416
13050
|
const results = new Map;
|
|
12417
13051
|
const incomplete = new Map;
|
|
12418
13052
|
for (const [key, s] of this.settled) {
|
|
@@ -12430,7 +13064,7 @@ class CheckFold {
|
|
|
12430
13064
|
throw new ContractError("receipt-inconclusive");
|
|
12431
13065
|
return {
|
|
12432
13066
|
checks: decodeCheckObligations({
|
|
12433
|
-
taskId,
|
|
13067
|
+
taskId: taskId2,
|
|
12434
13068
|
revision: configured.revision,
|
|
12435
13069
|
definitions: configured.selections.map((selection) => results.get(canonicalJson(selection)) ?? {
|
|
12436
13070
|
selection,
|
|
@@ -12443,18 +13077,18 @@ class CheckFold {
|
|
|
12443
13077
|
};
|
|
12444
13078
|
}
|
|
12445
13079
|
}
|
|
12446
|
-
function checkFold(files,
|
|
13080
|
+
function checkFold(files, taskId2, snapshot, budget, navigation = new HistoryNavigation(files)) {
|
|
12447
13081
|
navigation.snapshot(snapshot, budget);
|
|
12448
|
-
const { base, batches } = resumeTaskFold(files, navigation,
|
|
13082
|
+
const { base, batches } = resumeTaskFold(files, navigation, taskId2, snapshot, budget, (state) => state.checks);
|
|
12449
13083
|
const fold = new CheckFold(base);
|
|
12450
13084
|
for (const b of batches)
|
|
12451
|
-
fold.apply(b,
|
|
13085
|
+
fold.apply(b, taskId2);
|
|
12452
13086
|
return fold;
|
|
12453
13087
|
}
|
|
12454
|
-
function currentChecks(files,
|
|
13088
|
+
function currentChecks(files, taskId2, configured, current, snapshotSeq) {
|
|
12455
13089
|
const budget = HistoryReadBudget.authority(), navigation = new HistoryNavigation(files);
|
|
12456
13090
|
const snapshot = snapshotSeq ?? navigation.latest(budget);
|
|
12457
|
-
return checkFold(files,
|
|
13091
|
+
return checkFold(files, taskId2, snapshot, budget, navigation).evaluate(taskId2, configured, current);
|
|
12458
13092
|
}
|
|
12459
13093
|
|
|
12460
13094
|
// src/history/entity-state.ts
|
|
@@ -16247,16 +16881,16 @@ class HistoryProjection {
|
|
|
16247
16881
|
};
|
|
16248
16882
|
}
|
|
16249
16883
|
};
|
|
16250
|
-
checkObligations = async (
|
|
16884
|
+
checkObligations = async (taskId2) => this.environment.checkObligations?.(taskId2) ?? currentChecks(this.reader.files, taskId2, this.environment.checks(taskId2), this.environment.context(taskId2)).checks;
|
|
16251
16885
|
snapshot = async (input) => {
|
|
16252
16886
|
const scope = decodeScope(input), budget = new HistoryReadBudget, seq2 = this.navigation.latest(budget), epoch = this.readEpoch();
|
|
16253
16887
|
this.navigation.snapshot(seq2, budget);
|
|
16254
|
-
let
|
|
16888
|
+
let taskId2 = scope.kind === "task" ? scope.id : null;
|
|
16255
16889
|
const active = this.navigation.active(seq2, budget), groups = [], seen = new Set;
|
|
16256
16890
|
const selected2 = (id) => {
|
|
16257
16891
|
const group = this.runState(id, seq2, budget).projections(epoch).filter((r) => fits2(r, scope));
|
|
16258
16892
|
if (group.length) {
|
|
16259
|
-
|
|
16893
|
+
taskId2 = group[0].taskId;
|
|
16260
16894
|
seen.add(id);
|
|
16261
16895
|
}
|
|
16262
16896
|
return group;
|
|
@@ -16267,7 +16901,7 @@ class HistoryProjection {
|
|
|
16267
16901
|
if (group.length)
|
|
16268
16902
|
groups.push(group);
|
|
16269
16903
|
}
|
|
16270
|
-
if (!
|
|
16904
|
+
if (!taskId2) {
|
|
16271
16905
|
for (const b of this.navigation.reverseBatches(scope.id, seq2, budget)) {
|
|
16272
16906
|
for (const row of b.rows)
|
|
16273
16907
|
if (row.value.kind === "owner") {
|
|
@@ -16280,11 +16914,11 @@ class HistoryProjection {
|
|
|
16280
16914
|
}
|
|
16281
16915
|
}
|
|
16282
16916
|
}
|
|
16283
|
-
if (
|
|
16917
|
+
if (taskId2)
|
|
16284
16918
|
break;
|
|
16285
16919
|
}
|
|
16286
16920
|
}
|
|
16287
|
-
if (!
|
|
16921
|
+
if (!taskId2)
|
|
16288
16922
|
fail();
|
|
16289
16923
|
const runs = groups.flat();
|
|
16290
16924
|
const base = {
|
|
@@ -16322,8 +16956,8 @@ class HistoryProjection {
|
|
|
16322
16956
|
runs.push(...group);
|
|
16323
16957
|
}
|
|
16324
16958
|
}
|
|
16325
|
-
const context = decodeControlContext(this.environment.context(
|
|
16326
|
-
if (controlWorkspace(context) !== this.reader.files.format.workspaceId || controlTask(context) !==
|
|
16959
|
+
const context = decodeControlContext(this.environment.context(taskId2));
|
|
16960
|
+
if (controlWorkspace(context) !== this.reader.files.format.workspaceId || controlTask(context) !== taskId2)
|
|
16327
16961
|
fail();
|
|
16328
16962
|
const snapshot = decodeSnapshot({ ...base, context, runs });
|
|
16329
16963
|
for (const observer of this.snapshotObservers) {
|
|
@@ -16342,7 +16976,7 @@ class HistoryProjection {
|
|
|
16342
16976
|
// src/history/reader.ts
|
|
16343
16977
|
import { createHash as createHash18 } from "node:crypto";
|
|
16344
16978
|
import { existsSync as existsSync2 } from "node:fs";
|
|
16345
|
-
import { join as
|
|
16979
|
+
import { join as join16 } from "node:path";
|
|
16346
16980
|
|
|
16347
16981
|
// src/history/saved-graph-state.ts
|
|
16348
16982
|
var freshSavedGraph = () => ({
|
|
@@ -16565,10 +17199,10 @@ class PlanFold {
|
|
|
16565
17199
|
constructor(lineage) {
|
|
16566
17200
|
this.lineage = lineage;
|
|
16567
17201
|
}
|
|
16568
|
-
apply(batch,
|
|
17202
|
+
apply(batch, taskId2) {
|
|
16569
17203
|
batch.rows.forEach((row, index) => {
|
|
16570
17204
|
const value = row.value;
|
|
16571
|
-
if (value.kind === "admission" && value.intent.identity.kind === "action" && value.intent.identity.action.kind === "save-plan" && value.intent.identity.action.taskId ===
|
|
17205
|
+
if (value.kind === "admission" && value.intent.identity.kind === "action" && value.intent.identity.action.kind === "save-plan" && value.intent.identity.action.taskId === taskId2) {
|
|
16572
17206
|
if (value.intent.runId !== null)
|
|
16573
17207
|
throw new ContractError("corrupt-selected");
|
|
16574
17208
|
this.operation = new OperationState(value.intent.operationId);
|
|
@@ -16578,7 +17212,7 @@ class PlanFold {
|
|
|
16578
17212
|
this.operation?.apply(row, batch.pointer.seq);
|
|
16579
17213
|
if (!this.lineage)
|
|
16580
17214
|
return;
|
|
16581
|
-
this.lineage.apply(row, batch.pointer.seq,
|
|
17215
|
+
this.lineage.apply(row, batch.pointer.seq, taskId2, this.graphIdentity);
|
|
16582
17216
|
if (value.kind === "admission" && this.lineage.operationId === value.intent.operationId)
|
|
16583
17217
|
this.lineageAt = { pointer: batch.pointer, row: index };
|
|
16584
17218
|
});
|
|
@@ -16616,7 +17250,7 @@ class PlanFold {
|
|
|
16616
17250
|
return fold;
|
|
16617
17251
|
}
|
|
16618
17252
|
}
|
|
16619
|
-
function planFold(files,
|
|
17253
|
+
function planFold(files, taskId2, snapshot, budget, navigation, withLineage) {
|
|
16620
17254
|
navigation.snapshot(snapshot, budget);
|
|
16621
17255
|
const read2 = (at) => {
|
|
16622
17256
|
if (BigInt(at.pointer.seq) > BigInt(snapshot))
|
|
@@ -16626,20 +17260,20 @@ function planFold(files, taskId, snapshot, budget, navigation, withLineage) {
|
|
|
16626
17260
|
throw new ContractError("invalid");
|
|
16627
17261
|
return row;
|
|
16628
17262
|
};
|
|
16629
|
-
const { base, batches } = resumeTaskFold(files, navigation,
|
|
17263
|
+
const { base, batches } = resumeTaskFold(files, navigation, taskId2, snapshot, budget, (state) => PlanFold.resumed(state.plan, withLineage, read2));
|
|
16630
17264
|
const fold = base ?? new PlanFold(withLineage ? new TaskPublicationLineage : null);
|
|
16631
17265
|
for (const batch of batches)
|
|
16632
|
-
fold.apply(batch,
|
|
17266
|
+
fold.apply(batch, taskId2);
|
|
16633
17267
|
return fold;
|
|
16634
17268
|
}
|
|
16635
|
-
function latestTaskRun(files,
|
|
17269
|
+
function latestTaskRun(files, taskId2, snapshot, budget, navigation = new HistoryNavigation(files)) {
|
|
16636
17270
|
navigation.snapshot(snapshot, budget);
|
|
16637
|
-
const { base, batches } = resumeTaskFold(files, navigation,
|
|
17271
|
+
const { base, batches } = resumeTaskFold(files, navigation, taskId2, snapshot, budget, (state) => state.run);
|
|
16638
17272
|
let latest = base ?? null;
|
|
16639
17273
|
for (const batch of batches)
|
|
16640
17274
|
for (const row of batch.rows) {
|
|
16641
17275
|
const v = row.value;
|
|
16642
|
-
if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id ===
|
|
17276
|
+
if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id === taskId2 && (v.intent.identity.action.kind === "start" || v.intent.identity.action.kind === "generate-plan"))
|
|
16643
17277
|
latest = v.intent.runId;
|
|
16644
17278
|
}
|
|
16645
17279
|
return latest;
|
|
@@ -16672,11 +17306,11 @@ class HistoryReader {
|
|
|
16672
17306
|
throw new ContractError("corrupt-selected");
|
|
16673
17307
|
return this.files.readAdmission(runId, state.admission, budget);
|
|
16674
17308
|
}
|
|
16675
|
-
publishedPlan(
|
|
16676
|
-
decodeId(
|
|
17309
|
+
publishedPlan(taskId2, snapshotSeq, current2) {
|
|
17310
|
+
decodeId(taskId2);
|
|
16677
17311
|
decodeSequence(snapshotSeq);
|
|
16678
17312
|
const budget = HistoryReadBudget.authority();
|
|
16679
|
-
const fold = planFold(this.files,
|
|
17313
|
+
const fold = planFold(this.files, taskId2, snapshotSeq, budget, this.navigation, !!current2);
|
|
16680
17314
|
const { operation, lineage } = fold;
|
|
16681
17315
|
if (!operation)
|
|
16682
17316
|
return null;
|
|
@@ -16690,7 +17324,7 @@ class HistoryReader {
|
|
|
16690
17324
|
const ref = graph.plan;
|
|
16691
17325
|
const { detail, bytes: text2 } = this.planText({
|
|
16692
17326
|
storeId: this.storeId,
|
|
16693
|
-
scope: { kind: "task", id:
|
|
17327
|
+
scope: { kind: "task", id: taskId2 },
|
|
16694
17328
|
snapshotSeq,
|
|
16695
17329
|
query: null,
|
|
16696
17330
|
recordId: ref.recordId,
|
|
@@ -16698,7 +17332,7 @@ class HistoryReader {
|
|
|
16698
17332
|
field: "plan",
|
|
16699
17333
|
offset: 0
|
|
16700
17334
|
}, budget);
|
|
16701
|
-
if (canonicalJson(detail.content) !== canonicalJson(ref) || detail.origin.kind !== "owner" || detail.origin.id !== operation.operationId || detail.owner.taskId !==
|
|
17335
|
+
if (canonicalJson(detail.content) !== canonicalJson(ref) || detail.origin.kind !== "owner" || detail.origin.id !== operation.operationId || detail.owner.taskId !== taskId2 || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId2 || detail.owner.entity.version !== graph.planRevision || ref.bytes > 32768)
|
|
16702
17336
|
throw new ContractError("corrupt-selected");
|
|
16703
17337
|
if (text2.toString("utf8") !== plan)
|
|
16704
17338
|
throw new ContractError("corrupt-selected");
|
|
@@ -16722,11 +17356,11 @@ class HistoryReader {
|
|
|
16722
17356
|
committedSeq: receipt.receipt.committedSeq
|
|
16723
17357
|
};
|
|
16724
17358
|
}
|
|
16725
|
-
reviewRun(
|
|
16726
|
-
decodeId(
|
|
17359
|
+
reviewRun(taskId2, runId, snapshotSeq, budget = HistoryReadBudget.authority()) {
|
|
17360
|
+
decodeId(taskId2);
|
|
16727
17361
|
decodeId(runId);
|
|
16728
17362
|
decodeSequence(snapshotSeq);
|
|
16729
|
-
const latest = latestTaskRun(this.files,
|
|
17363
|
+
const latest = latestTaskRun(this.files, taskId2, snapshotSeq, budget, this.navigation);
|
|
16730
17364
|
if (latest !== runId)
|
|
16731
17365
|
throw new ContractError("stale");
|
|
16732
17366
|
const state = new RunState(runId);
|
|
@@ -16734,14 +17368,14 @@ class HistoryReader {
|
|
|
16734
17368
|
for (const batch of runBatches)
|
|
16735
17369
|
for (const row of batch.rows)
|
|
16736
17370
|
state.apply(row, batch.pointer.seq);
|
|
16737
|
-
if (!state.admission || state.admission.context.task?.id !==
|
|
17371
|
+
if (!state.admission || state.admission.context.task?.id !== taskId2 || !state.drained || state.publication !== "published")
|
|
16738
17372
|
throw new ContractError("conflict");
|
|
16739
17373
|
this.files.readAdmission(runId, state.admission, budget);
|
|
16740
17374
|
return state;
|
|
16741
17375
|
}
|
|
16742
|
-
reviewSelection(
|
|
17376
|
+
reviewSelection(taskId2, runId, snapshotSeq) {
|
|
16743
17377
|
const budget = HistoryReadBudget.authority();
|
|
16744
|
-
const run = this.reviewRun(
|
|
17378
|
+
const run = this.reviewRun(taskId2, runId, snapshotSeq, budget);
|
|
16745
17379
|
if (!run.admission)
|
|
16746
17380
|
throw new ContractError("corrupt-selected");
|
|
16747
17381
|
const { graph } = this.files.readAdmission(runId, run.admission, budget);
|
|
@@ -16750,7 +17384,7 @@ class HistoryReader {
|
|
|
16750
17384
|
const ref = graph.plan;
|
|
16751
17385
|
const { detail, bytes } = this.planText({
|
|
16752
17386
|
storeId: this.storeId,
|
|
16753
|
-
scope: { kind: "task", id:
|
|
17387
|
+
scope: { kind: "task", id: taskId2 },
|
|
16754
17388
|
snapshotSeq,
|
|
16755
17389
|
query: null,
|
|
16756
17390
|
recordId: ref.recordId,
|
|
@@ -16758,7 +17392,7 @@ class HistoryReader {
|
|
|
16758
17392
|
field: "plan",
|
|
16759
17393
|
offset: 0
|
|
16760
17394
|
}, budget);
|
|
16761
|
-
if (ref.bytes > 32768 || canonicalJson(detail.content) !== canonicalJson(ref) || detail.owner.taskId !==
|
|
17395
|
+
if (ref.bytes > 32768 || canonicalJson(detail.content) !== canonicalJson(ref) || detail.owner.taskId !== taskId2 || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId2 || detail.owner.entity.version !== graph.planRevision)
|
|
16762
17396
|
throw new ContractError("corrupt-selected");
|
|
16763
17397
|
return { run, graph, readablePlan: bytes.toString("utf8") };
|
|
16764
17398
|
}
|
|
@@ -17110,7 +17744,7 @@ class HistoryReader {
|
|
|
17110
17744
|
}
|
|
17111
17745
|
async readDetail(value) {
|
|
17112
17746
|
const cursor = decodeCursor(value);
|
|
17113
|
-
if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync2(
|
|
17747
|
+
if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync2(join16(this.files.directory, "indexes", "heads", "latest.json")))
|
|
17114
17748
|
return readRetainedDetail(this, cursor);
|
|
17115
17749
|
if (this.files.format.schema !== FORMAT)
|
|
17116
17750
|
return this.detail(cursor);
|
|
@@ -17312,7 +17946,7 @@ class HistoryReader {
|
|
|
17312
17946
|
|
|
17313
17947
|
// src/history/writer.ts
|
|
17314
17948
|
import { createHash as createHash20, randomUUID as randomUUID12 } from "node:crypto";
|
|
17315
|
-
import { join as
|
|
17949
|
+
import { join as join18 } from "node:path";
|
|
17316
17950
|
|
|
17317
17951
|
// src/history/plans.ts
|
|
17318
17952
|
import { createHash as createHash19, randomUUID as randomUUID11 } from "node:crypto";
|
|
@@ -17391,7 +18025,7 @@ import {
|
|
|
17391
18025
|
openSync as openSync6,
|
|
17392
18026
|
realpathSync as realpathSync4
|
|
17393
18027
|
} from "node:fs";
|
|
17394
|
-
import { dirname as dirname12, isAbsolute as isAbsolute7, join as
|
|
18028
|
+
import { dirname as dirname12, isAbsolute as isAbsolute7, join as join17, relative as relative6, sep as sep5 } from "node:path";
|
|
17395
18029
|
function summary(text2, maximum, runId) {
|
|
17396
18030
|
const label = `[Cadence summary${runId ? `; run ${runId}` : ""}; retained history is separate]
|
|
17397
18031
|
`;
|
|
@@ -17573,10 +18207,10 @@ ${result}`;
|
|
|
17573
18207
|
throw new ContractError("capacity");
|
|
17574
18208
|
return record2;
|
|
17575
18209
|
}
|
|
17576
|
-
function syncTaskPublication(store,
|
|
18210
|
+
function syncTaskPublication(store, taskId2) {
|
|
17577
18211
|
if (process.platform === "win32")
|
|
17578
18212
|
return;
|
|
17579
|
-
for (let path =
|
|
18213
|
+
for (let path = join17(store.tasks, taskId2);; path = dirname12(path)) {
|
|
17580
18214
|
if (!safeDirectory(path))
|
|
17581
18215
|
throw new ContractError("conflict");
|
|
17582
18216
|
const fd = openSync6(path, constants6.O_RDONLY | constants6.O_DIRECTORY);
|
|
@@ -17875,11 +18509,11 @@ class HistoryWriter {
|
|
|
17875
18509
|
this.reviews.set(operationId, { taskId: identity.action.taskId });
|
|
17876
18510
|
return this.ownerPort();
|
|
17877
18511
|
}
|
|
17878
|
-
controlRevision(
|
|
17879
|
-
return this.revisions.get(
|
|
18512
|
+
controlRevision(taskId2) {
|
|
18513
|
+
return this.revisions.get(taskId2 ?? "workspace") ?? 1;
|
|
17880
18514
|
}
|
|
17881
|
-
currentContext(
|
|
17882
|
-
const v = this.contexts.get(
|
|
18515
|
+
currentContext(taskId2) {
|
|
18516
|
+
const v = this.contexts.get(taskId2 ?? "workspace");
|
|
17883
18517
|
return v ? decodeContext(v) : null;
|
|
17884
18518
|
}
|
|
17885
18519
|
fence() {
|
|
@@ -17909,13 +18543,13 @@ class HistoryWriter {
|
|
|
17909
18543
|
const last = operation.publication;
|
|
17910
18544
|
if (last?.kind === "publication-settled" && (last.status === "uncertain" || last.status === "conflict"))
|
|
17911
18545
|
return;
|
|
17912
|
-
const
|
|
17913
|
-
if (!
|
|
18546
|
+
const taskId2 = intent.createdTaskId ?? intent.identity.expected.task?.id;
|
|
18547
|
+
if (!taskId2)
|
|
17914
18548
|
throw new ContractError("conflict");
|
|
17915
18549
|
return this.ownerValue({
|
|
17916
18550
|
link: {
|
|
17917
18551
|
epoch: intent.identity.expected.epoch,
|
|
17918
|
-
taskId,
|
|
18552
|
+
taskId: taskId2,
|
|
17919
18553
|
runId: intent.runId,
|
|
17920
18554
|
operationId
|
|
17921
18555
|
},
|
|
@@ -18329,7 +18963,7 @@ class HistoryWriter {
|
|
|
18329
18963
|
try {
|
|
18330
18964
|
const budget = HistoryReadBudget.authority();
|
|
18331
18965
|
const intent = this.files.readCommand(commandId, budget);
|
|
18332
|
-
const directoryExists = this.files.files.directory(
|
|
18966
|
+
const directoryExists = this.files.files.directory(join18(this.files.directory, "commands", commandId));
|
|
18333
18967
|
const wanted = intent ? decodeAdmissionIntent(json(intent, RECORD_BYTES)) : null;
|
|
18334
18968
|
let found = null;
|
|
18335
18969
|
let run = null;
|
|
@@ -18475,8 +19109,8 @@ class HistoryWriter {
|
|
|
18475
19109
|
this.assertOrdinary();
|
|
18476
19110
|
const bytes = encoded(intent);
|
|
18477
19111
|
this.charge(Buffer.byteLength(bytes), intent.runId, true);
|
|
18478
|
-
this.files.files.create(
|
|
18479
|
-
this.files.syncParents(
|
|
19112
|
+
this.files.files.create(join18(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
|
|
19113
|
+
this.files.syncParents(join18(this.files.directory, "commands", intent.commandId, "intent.json"));
|
|
18480
19114
|
await this.options.observeWrite?.("intent");
|
|
18481
19115
|
const policy = this.resourcePolicy(intent.identity.kind === "action" ? intent.identity.expected.configRev : 1);
|
|
18482
19116
|
return { kind: "admission", intent, record: record2, policy };
|
|
@@ -18604,15 +19238,15 @@ class HistoryWriter {
|
|
|
18604
19238
|
for (const { value: v } of rows)
|
|
18605
19239
|
if (v.kind === "owner" && v.events.some((e) => e.kind === "owner" && e.value.kind === "fact" && e.value.fact.kind === "publication-settled"))
|
|
18606
19240
|
tasks.add(v.link.taskId);
|
|
18607
|
-
for (const
|
|
18608
|
-
const head = prepared.heads.get(
|
|
19241
|
+
for (const taskId2 of tasks) {
|
|
19242
|
+
const head = prepared.heads.get(taskId2);
|
|
18609
19243
|
if (!head || head.seq !== this.state.committedSeq)
|
|
18610
19244
|
continue;
|
|
18611
19245
|
try {
|
|
18612
|
-
const checks = checkFold(this.files,
|
|
18613
|
-
const run = latestTaskRun(this.files,
|
|
18614
|
-
const plan = planFold(this.files,
|
|
18615
|
-
taskFoldMemory(this.files).remember(
|
|
19246
|
+
const checks = checkFold(this.files, taskId2, head.seq, HistoryReadBudget.authority()).state();
|
|
19247
|
+
const run = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
|
|
19248
|
+
const plan = planFold(this.files, taskId2, head.seq, HistoryReadBudget.authority(), new HistoryNavigation(this.files), true).state();
|
|
19249
|
+
taskFoldMemory(this.files).remember(taskId2, head, {
|
|
18616
19250
|
checks,
|
|
18617
19251
|
run,
|
|
18618
19252
|
plan
|
|
@@ -18657,8 +19291,8 @@ class HistoryWriter {
|
|
|
18657
19291
|
throw new ContractError("stale");
|
|
18658
19292
|
if (intent.identity.kind !== "action" || intent.identity.expected.epoch !== this.lease.registration.epoch)
|
|
18659
19293
|
throw new ContractError("stale");
|
|
18660
|
-
const identity = intent.identity,
|
|
18661
|
-
if (!
|
|
19294
|
+
const identity = intent.identity, taskId2 = intent.createdTaskId ?? identity.expected.task?.id;
|
|
19295
|
+
if (!taskId2)
|
|
18662
19296
|
throw new ContractError("conflict");
|
|
18663
19297
|
const current2 = this.contexts.get(identity.expected.task?.id ?? "workspace");
|
|
18664
19298
|
if (!current2 || current2.epoch !== identity.expected.epoch || current2.controlRev !== identity.expected.controlRev + 1)
|
|
@@ -18668,7 +19302,7 @@ class HistoryWriter {
|
|
|
18668
19302
|
if (!latest || canonicalJson(latest) !== canonicalJson(current2))
|
|
18669
19303
|
throw new ContractError("stale");
|
|
18670
19304
|
if (identity.action.kind === "review") {
|
|
18671
|
-
const review = this.options.reviewContext?.(
|
|
19305
|
+
const review = this.options.reviewContext?.(taskId2, this.reviews.get(request3.operationId)?.published);
|
|
18672
19306
|
if (!review || review.observation.identity !== identity.action.changesIdentity || review.checks.revision !== identity.action.checksRevision)
|
|
18673
19307
|
throw new ContractError("stale");
|
|
18674
19308
|
}
|
|
@@ -18680,7 +19314,7 @@ class HistoryWriter {
|
|
|
18680
19314
|
expected = run ? run.publicationExpected() : operation.state.publicationExpected();
|
|
18681
19315
|
link = {
|
|
18682
19316
|
epoch: identity.expected.epoch,
|
|
18683
|
-
taskId,
|
|
19317
|
+
taskId: taskId2,
|
|
18684
19318
|
runId: intent.runId,
|
|
18685
19319
|
operationId: intent.operationId
|
|
18686
19320
|
};
|
|
@@ -19120,13 +19754,13 @@ class HistoryWriter {
|
|
|
19120
19754
|
}
|
|
19121
19755
|
return { kind: "capture", link: input.link, source: input.source, events };
|
|
19122
19756
|
}
|
|
19123
|
-
assertContent(content,
|
|
19757
|
+
assertContent(content, taskId2, runId, entity, operationId) {
|
|
19124
19758
|
const reader = HistoryReader.open(this.lease.coordination);
|
|
19125
19759
|
if (!reader)
|
|
19126
19760
|
throw new ContractError("corrupt-selected");
|
|
19127
19761
|
const detail = reader.selected({
|
|
19128
19762
|
storeId: reader.storeId,
|
|
19129
|
-
scope: { kind: "task", id:
|
|
19763
|
+
scope: { kind: "task", id: taskId2 },
|
|
19130
19764
|
snapshotSeq: this.state.committedSeq,
|
|
19131
19765
|
recordId: content.recordId,
|
|
19132
19766
|
recordVersion: content.version,
|
|
@@ -19134,7 +19768,7 @@ class HistoryWriter {
|
|
|
19134
19768
|
offset: 0,
|
|
19135
19769
|
query: null
|
|
19136
19770
|
});
|
|
19137
|
-
if (canonicalJson(detail.content) !== canonicalJson(content) || detail.owner.taskId !==
|
|
19771
|
+
if (canonicalJson(detail.content) !== canonicalJson(content) || detail.owner.taskId !== taskId2 || detail.owner.runId !== runId || detail.owner.entity.id !== entity.id || detail.owner.entity.kind !== entity.kind || operationId !== undefined && (detail.origin.kind !== "owner" || detail.origin.id !== operationId) || "version" in entity && detail.owner.entity.version !== entity.version)
|
|
19138
19772
|
throw new ContractError("corrupt-selected");
|
|
19139
19773
|
for (const _ of reader.parts(detail, this.state.committedSeq)) {}
|
|
19140
19774
|
}
|
|
@@ -19510,6 +20144,7 @@ class OwnerModelChoice {
|
|
|
19510
20144
|
this.catalogId = randomUUID13();
|
|
19511
20145
|
this.options.owner.configurationInstalled();
|
|
19512
20146
|
}
|
|
20147
|
+
this.options.remember?.(request3.choice);
|
|
19513
20148
|
return this.snapshot();
|
|
19514
20149
|
} finally {
|
|
19515
20150
|
this.installing = false;
|
|
@@ -19519,7 +20154,7 @@ class OwnerModelChoice {
|
|
|
19519
20154
|
|
|
19520
20155
|
// src/service/model-config.ts
|
|
19521
20156
|
import { lstatSync as lstatSync11, realpathSync as realpathSync5 } from "node:fs";
|
|
19522
|
-
import { dirname as dirname13, isAbsolute as isAbsolute8, join as
|
|
20157
|
+
import { dirname as dirname13, isAbsolute as isAbsolute8, join as join19, resolve as resolve7 } from "node:path";
|
|
19523
20158
|
var CONFIG_BYTES2 = 1024 * 1024;
|
|
19524
20159
|
var ENTRY_LIMIT = 256;
|
|
19525
20160
|
function refuse2() {
|
|
@@ -19586,13 +20221,13 @@ function captureEnvironment(value) {
|
|
|
19586
20221
|
function piSource(agentDir, home, cwd, env) {
|
|
19587
20222
|
if (!isAbsolute8(home) || !isAbsolute8(cwd))
|
|
19588
20223
|
refuse2();
|
|
19589
|
-
let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ??
|
|
20224
|
+
let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ?? join19(home, ".pi", "agent");
|
|
19590
20225
|
if (!selected2 || selected2.includes("\x00"))
|
|
19591
20226
|
refuse2();
|
|
19592
20227
|
if (selected2 === "~" || selected2.startsWith("~/"))
|
|
19593
20228
|
selected2 = home + selected2.slice(1);
|
|
19594
20229
|
selected2 = resolve7(cwd, selected2);
|
|
19595
|
-
const directory =
|
|
20230
|
+
const directory = join19(realpathSync5(dirname13(selected2)), selected2.slice(dirname13(selected2).length + 1));
|
|
19596
20231
|
if (!lstatSync11(directory).isDirectory() || lstatSync11(directory).isSymbolicLink())
|
|
19597
20232
|
refuse2();
|
|
19598
20233
|
const files = new PrivateFiles(directory, false);
|
|
@@ -19601,8 +20236,8 @@ function piSource(agentDir, home, cwd, env) {
|
|
|
19601
20236
|
return {
|
|
19602
20237
|
directory,
|
|
19603
20238
|
files,
|
|
19604
|
-
authPath:
|
|
19605
|
-
modelsPath:
|
|
20239
|
+
authPath: join19(directory, "auth.json"),
|
|
20240
|
+
modelsPath: join19(directory, "models.json")
|
|
19606
20241
|
};
|
|
19607
20242
|
}
|
|
19608
20243
|
function templateNames(value) {
|
|
@@ -21036,7 +21671,7 @@ import { realpathSync as realpathSync6 } from "node:fs";
|
|
|
21036
21671
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
21037
21672
|
import { createHash as createHash21 } from "node:crypto";
|
|
21038
21673
|
import { lstatSync as lstatSync12, readdirSync as readdirSync3, readlinkSync } from "node:fs";
|
|
21039
|
-
import { join as
|
|
21674
|
+
import { join as join20, relative as relative7 } from "node:path";
|
|
21040
21675
|
var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
|
|
21041
21676
|
var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
|
|
21042
21677
|
function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
|
|
@@ -21079,7 +21714,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
|
|
|
21079
21714
|
return;
|
|
21080
21715
|
}
|
|
21081
21716
|
try {
|
|
21082
|
-
const path =
|
|
21717
|
+
const path = join20(root, name);
|
|
21083
21718
|
const st = lstatSync12(path);
|
|
21084
21719
|
add(name, `${st.mode}:${st.size}`);
|
|
21085
21720
|
if (st.isSymbolicLink()) {
|
|
@@ -21220,7 +21855,7 @@ ${data2.toString("utf8")}`);
|
|
|
21220
21855
|
return;
|
|
21221
21856
|
}
|
|
21222
21857
|
for (const name of names2) {
|
|
21223
|
-
const path =
|
|
21858
|
+
const path = join20(dir, name);
|
|
21224
21859
|
const rel = relative7(root, path).split("\\").join("/");
|
|
21225
21860
|
if (rel === ".git" || admin(rel))
|
|
21226
21861
|
continue;
|
|
@@ -21783,7 +22418,7 @@ class ActionAdmission {
|
|
|
21783
22418
|
|
|
21784
22419
|
// src/service/graph.ts
|
|
21785
22420
|
import { createHash as createHash22 } from "node:crypto";
|
|
21786
|
-
import { join as
|
|
22421
|
+
import { join as join21 } from "node:path";
|
|
21787
22422
|
var hash3 = (text2) => createHash22("sha256").update(text2).digest("hex");
|
|
21788
22423
|
|
|
21789
22424
|
class GraphContext {
|
|
@@ -21793,7 +22428,7 @@ class GraphContext {
|
|
|
21793
22428
|
identity;
|
|
21794
22429
|
constructor(root) {
|
|
21795
22430
|
this.root = root;
|
|
21796
|
-
const bytes = readBounded(
|
|
22431
|
+
const bytes = readBounded(join21(root, "AGENTS.md"), 32768);
|
|
21797
22432
|
this.hints = bytes ? new TextDecoder("utf-8", { fatal: true }).decode(bytes) : "";
|
|
21798
22433
|
this.identity = hash3(canonicalJson({
|
|
21799
22434
|
hints: bytes === undefined ? null : hash3(bytes),
|
|
@@ -21930,7 +22565,7 @@ import { randomUUID as randomUUID17 } from "node:crypto";
|
|
|
21930
22565
|
|
|
21931
22566
|
// src/subagent-process.ts
|
|
21932
22567
|
import { spawn as spawn2 } from "node:child_process";
|
|
21933
|
-
import { join as
|
|
22568
|
+
import { join as join22 } from "node:path";
|
|
21934
22569
|
import { StringDecoder } from "node:string_decoder";
|
|
21935
22570
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
21936
22571
|
|
|
@@ -21944,7 +22579,7 @@ function argumentsData(value, secrets) {
|
|
|
21944
22579
|
throw new Error("Unsupported context arguments");
|
|
21945
22580
|
return parseWireJson(source, 64 * 1024);
|
|
21946
22581
|
}
|
|
21947
|
-
function
|
|
22582
|
+
function own2(value, key2) {
|
|
21948
22583
|
const d = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, key2) : undefined;
|
|
21949
22584
|
if (!d || !("value" in d))
|
|
21950
22585
|
throw new Error("Invalid usage");
|
|
@@ -21953,7 +22588,7 @@ function own(value, key2) {
|
|
|
21953
22588
|
function counts(value, keys3) {
|
|
21954
22589
|
const out = Object.create(null);
|
|
21955
22590
|
for (const key2 of keys3) {
|
|
21956
|
-
const n =
|
|
22591
|
+
const n = own2(value, key2);
|
|
21957
22592
|
if (typeof n !== "number" || !Number.isFinite(n) || n < 0)
|
|
21958
22593
|
throw new Error("Invalid usage");
|
|
21959
22594
|
out[key2] = n;
|
|
@@ -21996,7 +22631,7 @@ function conversationMessages(messages, secrets = []) {
|
|
|
21996
22631
|
"cacheWrite",
|
|
21997
22632
|
"totalTokens"
|
|
21998
22633
|
]);
|
|
21999
|
-
usage.cost = counts(
|
|
22634
|
+
usage.cost = counts(own2(message.usage, "cost"), [
|
|
22000
22635
|
"input",
|
|
22001
22636
|
"output",
|
|
22002
22637
|
"cacheRead",
|
|
@@ -22603,7 +23238,7 @@ class WorkerRecording {
|
|
|
22603
23238
|
// src/subagent-process.ts
|
|
22604
23239
|
function terminateWindowsTree(pid, fallback) {
|
|
22605
23240
|
const root = process.env.SystemRoot;
|
|
22606
|
-
const taskkill = spawn2(root ?
|
|
23241
|
+
const taskkill = spawn2(root ? join22(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
|
|
22607
23242
|
taskkill.once("error", fallback);
|
|
22608
23243
|
taskkill.once("close", (code2) => {
|
|
22609
23244
|
if (code2 !== 0)
|
|
@@ -22648,7 +23283,8 @@ function runProcess(spec) {
|
|
|
22648
23283
|
spec.input === undefined ? "ignore" : "pipe",
|
|
22649
23284
|
"pipe",
|
|
22650
23285
|
"pipe",
|
|
22651
|
-
...spec.onContext ? ["pipe"] : []
|
|
23286
|
+
...spec.onContext || spec.onCoordinator ? [spec.onContext ? "pipe" : "ignore"] : [],
|
|
23287
|
+
...spec.onCoordinator ? ["ipc"] : []
|
|
22652
23288
|
]
|
|
22653
23289
|
});
|
|
22654
23290
|
const contextStream = spec.onContext ? child.stdio[3] : null;
|
|
@@ -22728,6 +23364,8 @@ function runProcess(spec) {
|
|
|
22728
23364
|
child.stderr.destroy();
|
|
22729
23365
|
child.stdin?.destroy();
|
|
22730
23366
|
contextStream?.destroy();
|
|
23367
|
+
if (child.connected)
|
|
23368
|
+
child.disconnect();
|
|
22731
23369
|
}
|
|
22732
23370
|
};
|
|
22733
23371
|
const signalChild = (signal) => {
|
|
@@ -22753,6 +23391,40 @@ function runProcess(spec) {
|
|
|
22753
23391
|
killTimer = setTimeout(() => signalChild("SIGKILL"), 1000);
|
|
22754
23392
|
unknownTimer = setTimeout(() => finish(false, null, null), 3000);
|
|
22755
23393
|
};
|
|
23394
|
+
let bridgeCalls = 0;
|
|
23395
|
+
let bridgeBusy = false;
|
|
23396
|
+
if (spec.onCoordinator)
|
|
23397
|
+
child.on("message", (message) => {
|
|
23398
|
+
if (settled || stopping)
|
|
23399
|
+
return;
|
|
23400
|
+
(async () => {
|
|
23401
|
+
let id;
|
|
23402
|
+
try {
|
|
23403
|
+
const body = JSON.stringify(message);
|
|
23404
|
+
if (++bridgeCalls > 16 || bridgeBusy || Buffer.byteLength(body) > 65536 || sanitizeText(body, spec.secrets ?? []) !== body)
|
|
23405
|
+
throw new Error("Invalid coordinator frame");
|
|
23406
|
+
const row = closed(message, ["id", "name", "args"]);
|
|
23407
|
+
if (!Number.isSafeInteger(row.id) || row.id < 1 || typeof row.name !== "string")
|
|
23408
|
+
throw new Error("Invalid coordinator frame");
|
|
23409
|
+
id = row.id;
|
|
23410
|
+
bridgeBusy = true;
|
|
23411
|
+
const value = await spec.onCoordinator?.(row.name, row.args, ingressStop.signal);
|
|
23412
|
+
const text2 = sanitizeText(JSON.stringify(value), spec.secrets ?? []);
|
|
23413
|
+
const reply = { id, ok: true, text: text2 };
|
|
23414
|
+
if (Buffer.byteLength(JSON.stringify(reply)) > 65536)
|
|
23415
|
+
throw new Error("Coordinator result exceeds bound");
|
|
23416
|
+
if (!settled && !stopping && child.connected)
|
|
23417
|
+
child.send(reply, () => {});
|
|
23418
|
+
} catch {
|
|
23419
|
+
if (id !== undefined && child.connected && !settled && !stopping)
|
|
23420
|
+
child.send({ id, ok: false }, () => {});
|
|
23421
|
+
else
|
|
23422
|
+
stop("failed");
|
|
23423
|
+
} finally {
|
|
23424
|
+
bridgeBusy = false;
|
|
23425
|
+
}
|
|
23426
|
+
})();
|
|
23427
|
+
});
|
|
22756
23428
|
const abort = () => stop("canceled");
|
|
22757
23429
|
const timeout = setTimeout(() => stop("timeout"), spec.timeoutMs);
|
|
22758
23430
|
spec.signal.addEventListener("abort", abort, { once: true });
|
|
@@ -23076,6 +23748,7 @@ function launchConversation(prepared, conversation, signal, options) {
|
|
|
23076
23748
|
return launchEncoded(encoded2, signal, options.timeoutMs, {
|
|
23077
23749
|
maySignal: options.maySignal,
|
|
23078
23750
|
onNative: options.onNative,
|
|
23751
|
+
onCoordinator: options.onCoordinator,
|
|
23079
23752
|
onFrame: (frame) => options.onFrame(frame, secrets),
|
|
23080
23753
|
onContext: (source) => {
|
|
23081
23754
|
const value = closed(parseWireJson(source, CONTEXT_BYTES), [
|
|
@@ -23092,7 +23765,28 @@ function launchConversation(prepared, conversation, signal, options) {
|
|
|
23092
23765
|
});
|
|
23093
23766
|
});
|
|
23094
23767
|
}
|
|
23095
|
-
function
|
|
23768
|
+
function launchWorkflowWorker(prepared, cwd, signal, options) {
|
|
23769
|
+
let encoded2;
|
|
23770
|
+
return prepared.consume((material) => {
|
|
23771
|
+
encoded2 = encodeEnvelope({
|
|
23772
|
+
...material,
|
|
23773
|
+
cwd,
|
|
23774
|
+
model: { ...material.model }
|
|
23775
|
+
});
|
|
23776
|
+
return encoded2.input;
|
|
23777
|
+
}, (input) => {
|
|
23778
|
+
if (!encoded2 || encoded2.input !== input)
|
|
23779
|
+
throw new Error("Invalid workflow launch");
|
|
23780
|
+
const secrets = [...encoded2.secrets, ...options.ownerSecrets];
|
|
23781
|
+
return launchEncoded(encoded2, signal, options.timeoutMs, {
|
|
23782
|
+
secrets,
|
|
23783
|
+
maySignal: options.maySignal,
|
|
23784
|
+
onNative: (native, capture) => options.onNative(native, capture?.selected?.messageId),
|
|
23785
|
+
onFrame: (frame) => options.onFrame(frame, secrets)
|
|
23786
|
+
});
|
|
23787
|
+
});
|
|
23788
|
+
}
|
|
23789
|
+
function runCheck(check, cwd, signal, service) {
|
|
23096
23790
|
return runProcess({
|
|
23097
23791
|
command: process.platform === "win32" ? (service?.environment ?? process.env).COMSPEC ?? "cmd.exe" : "/bin/sh",
|
|
23098
23792
|
args: process.platform === "win32" ? ["/d", "/s", "/c", `"${check.command}"`] : ["-c", check.command],
|
|
@@ -23457,8 +24151,8 @@ class TaskScheduler {
|
|
|
23457
24151
|
stage: e.reason || e.settling || this.closed ? "draining" : e.allocated ? "active" : "accepted-unallocated"
|
|
23458
24152
|
}));
|
|
23459
24153
|
}
|
|
23460
|
-
activeTask(
|
|
23461
|
-
return [...this.episodes.values()].find((e) => e.link.taskId ===
|
|
24154
|
+
activeTask(taskId2) {
|
|
24155
|
+
return [...this.episodes.values()].find((e) => e.link.taskId === taskId2)?.target.runId ?? null;
|
|
23462
24156
|
}
|
|
23463
24157
|
async settled(runId) {
|
|
23464
24158
|
await this.episodes.get(runId)?.done;
|
|
@@ -24248,8 +24942,8 @@ class TaskActions {
|
|
|
24248
24942
|
lookupForAdmission: (id) => options.host.writer.lookupForAdmission(id),
|
|
24249
24943
|
commit: (intent) => this.commit(intent)
|
|
24250
24944
|
}, this, { now: () => Date.now(), uuid: () => randomUUID18() });
|
|
24251
|
-
options.host.writer.bindReviewContext((
|
|
24252
|
-
const current2 = this.reviewing.get(
|
|
24945
|
+
options.host.writer.bindReviewContext((taskId2, published) => {
|
|
24946
|
+
const current2 = this.reviewing.get(taskId2);
|
|
24253
24947
|
if (!current2)
|
|
24254
24948
|
throw new ContractError("unavailable");
|
|
24255
24949
|
return current2(published);
|
|
@@ -24376,11 +25070,11 @@ class TaskActions {
|
|
|
24376
25070
|
if (canonicalJson(choice.selection) !== canonicalJson(version.model) || choice.configRev !== version.configRev || choice.checkEnvGeneration !== version.checkEnvGeneration)
|
|
24377
25071
|
throw new ContractError("stale");
|
|
24378
25072
|
}
|
|
24379
|
-
savedGraph(
|
|
24380
|
-
const h = this.options.host, saved = h.coordination.store.loadSnapshot(
|
|
25073
|
+
savedGraph(taskId2, snapshot = this.options.host.writer.committedSeq) {
|
|
25074
|
+
const h = this.options.host, saved = h.coordination.store.loadSnapshot(taskId2);
|
|
24381
25075
|
if (!saved)
|
|
24382
25076
|
throw new ContractError("stale");
|
|
24383
|
-
return h.reader.publishedPlan(
|
|
25077
|
+
return h.reader.publishedPlan(taskId2, snapshot, {
|
|
24384
25078
|
identity: saved.identity,
|
|
24385
25079
|
revision: saved.record.revision,
|
|
24386
25080
|
plan: saved.record.plan
|
|
@@ -24420,8 +25114,8 @@ class TaskActions {
|
|
|
24420
25114
|
this.drafts.set(record2.id, { identity: identity2, graph });
|
|
24421
25115
|
return graph;
|
|
24422
25116
|
}
|
|
24423
|
-
checks(
|
|
24424
|
-
if (!this.options.host.coordination.store.loadSnapshot(
|
|
25117
|
+
checks(taskId2) {
|
|
25118
|
+
if (!this.options.host.coordination.store.loadSnapshot(taskId2))
|
|
24425
25119
|
throw new ContractError("stale");
|
|
24426
25120
|
const selections = this.configuredChecks();
|
|
24427
25121
|
const identity2 = canonicalJson(selections);
|
|
@@ -24456,12 +25150,12 @@ class TaskActions {
|
|
|
24456
25150
|
...h.models.redactionLiterals(selection)
|
|
24457
25151
|
];
|
|
24458
25152
|
}
|
|
24459
|
-
observeCurrent(
|
|
25153
|
+
observeCurrent(taskId2, snapshot, legacyStart = false) {
|
|
24460
25154
|
this.alive();
|
|
24461
25155
|
const h = this.options.host, choice = this.choiceSnapshot();
|
|
24462
25156
|
const access = this.currentAccess();
|
|
24463
25157
|
const committedSeq = snapshot ?? h.writer.committedSeq;
|
|
24464
|
-
const selected2 =
|
|
25158
|
+
const selected2 = taskId2 ? h.coordination.store.loadSnapshot(taskId2) : null;
|
|
24465
25159
|
if (selected2 && realpathSync6(selected2.record.cwd) !== this.cwd)
|
|
24466
25160
|
throw new ContractError("unsupported-context");
|
|
24467
25161
|
const secrets = this.viewSecrets();
|
|
@@ -24474,7 +25168,7 @@ class TaskActions {
|
|
|
24474
25168
|
const plan = selected2 ? sanitizeText(selected2.record.plan, secrets) : null;
|
|
24475
25169
|
const editable = selected2 ? plan === selected2.record.plan : true;
|
|
24476
25170
|
let descriptor = null;
|
|
24477
|
-
let unavailable2 =
|
|
25171
|
+
let unavailable2 = taskId2 && !selected2 ? publicError("unavailable") : null;
|
|
24478
25172
|
let saved = { status: "none" };
|
|
24479
25173
|
if (selected2) {
|
|
24480
25174
|
try {
|
|
@@ -24511,7 +25205,7 @@ class TaskActions {
|
|
|
24511
25205
|
version: {
|
|
24512
25206
|
...access,
|
|
24513
25207
|
configRev: choice.configRev,
|
|
24514
|
-
controlRev: h.writer.controlRevision(
|
|
25208
|
+
controlRev: h.writer.controlRevision(taskId2),
|
|
24515
25209
|
workspaceId: h.reader.files.format.workspaceId,
|
|
24516
25210
|
cwdId: this.cwdId,
|
|
24517
25211
|
model: choice.selection,
|
|
@@ -24533,11 +25227,11 @@ class TaskActions {
|
|
|
24533
25227
|
} : {
|
|
24534
25228
|
status: "unavailable",
|
|
24535
25229
|
workspaceId: h.reader.files.format.workspaceId,
|
|
24536
|
-
taskId,
|
|
25230
|
+
taskId: taskId2,
|
|
24537
25231
|
error: unavailable2 ?? publicError("unavailable")
|
|
24538
25232
|
};
|
|
24539
25233
|
const view = decodeCurrentView({
|
|
24540
|
-
request: { storeId: h.reader.storeId, taskId },
|
|
25234
|
+
request: { storeId: h.reader.storeId, taskId: taskId2 },
|
|
24541
25235
|
workspaceId: h.reader.files.format.workspaceId,
|
|
24542
25236
|
epoch: access.epoch,
|
|
24543
25237
|
committedSeq,
|
|
@@ -24568,8 +25262,8 @@ class TaskActions {
|
|
|
24568
25262
|
throw new ContractError("stale");
|
|
24569
25263
|
if (choice.selection)
|
|
24570
25264
|
h.models.assertCurrent(choice.selection);
|
|
24571
|
-
const latest =
|
|
24572
|
-
if (latest?.identity !== selected2?.identity || canonicalJson(choice) !== canonicalJson(this.choiceSnapshot()) || canonicalJson(access) !== canonicalJson(this.currentAccess()) || context.status === "available" && (h.writer.controlRevision(
|
|
25265
|
+
const latest = taskId2 ? h.coordination.store.loadSnapshot(taskId2) : null;
|
|
25266
|
+
if (latest?.identity !== selected2?.identity || canonicalJson(choice) !== canonicalJson(this.choiceSnapshot()) || canonicalJson(access) !== canonicalJson(this.currentAccess()) || context.status === "available" && (h.writer.controlRevision(taskId2) !== context.version.controlRev || this.generation !== context.version.checkoutGeneration))
|
|
24573
25267
|
throw new ContractError("stale");
|
|
24574
25268
|
};
|
|
24575
25269
|
assertCurrent();
|
|
@@ -24655,8 +25349,8 @@ class TaskActions {
|
|
|
24655
25349
|
}
|
|
24656
25350
|
return decodeActiveRuns({ ...base, status: "complete", runs });
|
|
24657
25351
|
}
|
|
24658
|
-
context(
|
|
24659
|
-
return this.current({ storeId: this.options.host.reader.storeId, taskId }).context;
|
|
25352
|
+
context(taskId2) {
|
|
25353
|
+
return this.current({ storeId: this.options.host.reader.storeId, taskId: taskId2 }).context;
|
|
24660
25354
|
}
|
|
24661
25355
|
workspace() {
|
|
24662
25356
|
const { view, secrets } = this.observeCurrent(null);
|
|
@@ -24667,11 +25361,11 @@ class TaskActions {
|
|
|
24667
25361
|
activeRuns: this.activeRuns()
|
|
24668
25362
|
};
|
|
24669
25363
|
}
|
|
24670
|
-
checkObligations(
|
|
24671
|
-
const { view, assertCurrent } = this.observeCurrent(
|
|
25364
|
+
checkObligations(taskId2) {
|
|
25365
|
+
const { view, assertCurrent } = this.observeCurrent(taskId2);
|
|
24672
25366
|
if (!view.task)
|
|
24673
25367
|
throw new ContractError("unavailable");
|
|
24674
|
-
const checks = this.obligationsFor(
|
|
25368
|
+
const checks = this.obligationsFor(taskId2, view.task.kind, view.context, view.committedSeq).checks;
|
|
24675
25369
|
assertCurrent();
|
|
24676
25370
|
return checks;
|
|
24677
25371
|
}
|
|
@@ -24680,41 +25374,41 @@ class TaskActions {
|
|
|
24680
25374
|
throw new ContractError("stale");
|
|
24681
25375
|
return this.obligationsFor(version.task.id, version.task.kind, { status: "available", version }, snapshot, reads);
|
|
24682
25376
|
}
|
|
24683
|
-
obligationsFor(
|
|
24684
|
-
const configured = this.checks(
|
|
25377
|
+
obligationsFor(taskId2, kind, context, snapshot, reads) {
|
|
25378
|
+
const configured = this.checks(taskId2);
|
|
24685
25379
|
const selections = kind === "code" ? configured : { revision: configured.revision, selections: [] };
|
|
24686
|
-
const fold = () => currentChecks(this.options.host.reader.files,
|
|
24687
|
-
const state = reads ? reads(`checks:${canonicalJson({ taskId, selections, context, snapshot })}`, fold) : fold();
|
|
24688
|
-
if (canonicalJson(configured) !== canonicalJson(this.checks(
|
|
25380
|
+
const fold = () => currentChecks(this.options.host.reader.files, taskId2, selections, context, snapshot);
|
|
25381
|
+
const state = reads ? reads(`checks:${canonicalJson({ taskId: taskId2, selections, context, snapshot })}`, fold) : fold();
|
|
25382
|
+
if (canonicalJson(configured) !== canonicalJson(this.checks(taskId2)))
|
|
24689
25383
|
throw new ContractError("stale");
|
|
24690
25384
|
if (context.status !== "available")
|
|
24691
25385
|
return {
|
|
24692
25386
|
...state,
|
|
24693
25387
|
checks: {
|
|
24694
25388
|
...state.checks,
|
|
24695
|
-
revision: this.reviewVersions.get(
|
|
25389
|
+
revision: this.reviewVersions.get(taskId2)?.revision ?? configured.revision
|
|
24696
25390
|
}
|
|
24697
25391
|
};
|
|
24698
25392
|
const signature = canonicalJson({ configured, ...state });
|
|
24699
|
-
let prior = this.reviewVersions.get(
|
|
25393
|
+
let prior = this.reviewVersions.get(taskId2);
|
|
24700
25394
|
if (!prior || prior.signature !== signature) {
|
|
24701
25395
|
if (this.reviewVersions.size >= 16 && !prior)
|
|
24702
25396
|
this.reviewVersions.delete(this.reviewVersions.keys().next().value ?? "");
|
|
24703
25397
|
if (!Number.isSafeInteger(this.reviewRevision + 1))
|
|
24704
25398
|
throw new ContractError("capacity");
|
|
24705
25399
|
prior = { signature, revision: ++this.reviewRevision };
|
|
24706
|
-
this.reviewVersions.set(
|
|
25400
|
+
this.reviewVersions.set(taskId2, prior);
|
|
24707
25401
|
}
|
|
24708
25402
|
return { ...state, checks: { ...state.checks, revision: prior.revision } };
|
|
24709
25403
|
}
|
|
24710
25404
|
async observe(action) {
|
|
24711
25405
|
const h = this.options.host;
|
|
24712
|
-
const
|
|
24713
|
-
if (this.metadata.size >= 16 || this.metadata.has(
|
|
25406
|
+
const taskId2 = action.kind === "create" ? null : action.taskId;
|
|
25407
|
+
if (this.metadata.size >= 16 || this.metadata.has(taskId2 ?? "workspace"))
|
|
24714
25408
|
throw new ContractError("conflict");
|
|
24715
25409
|
const pending = this.committed;
|
|
24716
25410
|
const ownAcceptance = pending?.intent.identity.kind === "action" && canonicalJson(pending.intent.identity.action) === canonicalJson(action);
|
|
24717
|
-
const current2 = this.observeCurrent(
|
|
25411
|
+
const current2 = this.observeCurrent(taskId2, ownAcceptance ? pending.previousSeq : undefined, action.kind === "start");
|
|
24718
25412
|
const { selected: selected2, graph, changes } = current2;
|
|
24719
25413
|
if (current2.view.context.status !== "available")
|
|
24720
25414
|
throw new ContractError(current2.view.context.error.code);
|
|
@@ -24751,7 +25445,7 @@ class TaskActions {
|
|
|
24751
25445
|
for (const assignment of graph.assignments)
|
|
24752
25446
|
this.sources.request(selected2.record, graph, randomUUID18(), randomUUID18(), assignment, { graphRevision: graph.revision, inputs: [] });
|
|
24753
25447
|
}
|
|
24754
|
-
const checks =
|
|
25448
|
+
const checks = taskId2 ? this.checks(taskId2).selections : this.configuredChecks();
|
|
24755
25449
|
if (sanitizeText(canonicalJson(checks), current2.secrets) !== canonicalJson(checks))
|
|
24756
25450
|
throw new ContractError("unsupported-context");
|
|
24757
25451
|
const review = action.kind === "review" ? this.reviewObservation(action.runId, version) : null;
|
|
@@ -24762,14 +25456,14 @@ class TaskActions {
|
|
|
24762
25456
|
cwdLabel: diagnosticText(sanitizeText(this.cwd, current2.secrets), 4096),
|
|
24763
25457
|
readablePlan: action.kind === "save-plan" ? action.plan : review?.readablePlan ?? selected2?.record.plan ?? "",
|
|
24764
25458
|
graph: action.kind === "save-plan" ? action.graph : action.kind === "generate-plan" ? null : review ? review.graph : graph,
|
|
24765
|
-
activeRunId:
|
|
25459
|
+
activeRunId: taskId2 ? this.scheduler.activeTask(taskId2) : null,
|
|
24766
25460
|
issues: review?.issues ?? (changes.complete ? [] : ["incomplete-observation"]),
|
|
24767
25461
|
configuredChecks: checks,
|
|
24768
25462
|
...action.kind === "check" ? { checkEnvironmentPolicy: "service-launch-ordinary/1" } : {},
|
|
24769
|
-
checksRevision: review?.checks.revision ?? (
|
|
25463
|
+
checksRevision: review?.checks.revision ?? (taskId2 && this.options.choice ? this.obligations(version, current2.view.committedSeq).checks.revision : taskId2 ? this.checks(taskId2).revision : 0),
|
|
24770
25464
|
reviewRunId: action.kind === "review" ? action.runId : null
|
|
24771
25465
|
});
|
|
24772
|
-
const latestChecks =
|
|
25466
|
+
const latestChecks = taskId2 ? this.checks(taskId2).selections : this.configuredChecks();
|
|
24773
25467
|
if (canonicalJson(checks) !== canonicalJson(latestChecks))
|
|
24774
25468
|
throw new ContractError("stale");
|
|
24775
25469
|
current2.assertCurrent();
|
|
@@ -24927,9 +25621,9 @@ class TaskActions {
|
|
|
24927
25621
|
reviewObservation(runId, version, snapshot = this.options.host.writer.committedSeq, reads) {
|
|
24928
25622
|
if (!version.task)
|
|
24929
25623
|
throw new ContractError("stale");
|
|
24930
|
-
const h = this.options.host,
|
|
24931
|
-
const select = () => h.reader.reviewSelection(
|
|
24932
|
-
const selection = reads ? reads(`selection:${
|
|
25624
|
+
const h = this.options.host, taskId2 = version.task.id;
|
|
25625
|
+
const select = () => h.reader.reviewSelection(taskId2, runId, snapshot);
|
|
25626
|
+
const selection = reads ? reads(`selection:${taskId2}:${runId}:${snapshot}`, select) : select();
|
|
24933
25627
|
const { run } = selection;
|
|
24934
25628
|
const state = this.obligations(version, snapshot, reads);
|
|
24935
25629
|
const current2 = {
|
|
@@ -25125,8 +25819,8 @@ class TaskActions {
|
|
|
25125
25819
|
lease.reservation.release();
|
|
25126
25820
|
}
|
|
25127
25821
|
}
|
|
25128
|
-
async settled(
|
|
25129
|
-
await this.metadata.get(
|
|
25822
|
+
async settled(taskId2) {
|
|
25823
|
+
await this.metadata.get(taskId2 ?? "workspace");
|
|
25130
25824
|
}
|
|
25131
25825
|
requestCancel(command) {
|
|
25132
25826
|
this.scheduler.cancel(command.runId);
|
|
@@ -25148,16 +25842,343 @@ class TaskActions {
|
|
|
25148
25842
|
}
|
|
25149
25843
|
|
|
25150
25844
|
// src/service/workbench.ts
|
|
25151
|
-
import { opendirSync as
|
|
25152
|
-
import { join as
|
|
25845
|
+
import { opendirSync as opendirSync10 } from "node:fs";
|
|
25846
|
+
import { join as join27 } from "node:path";
|
|
25153
25847
|
|
|
25154
|
-
// src/service/
|
|
25848
|
+
// src/service/conversation-workflow.ts
|
|
25155
25849
|
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
25156
|
-
import {
|
|
25157
|
-
import { dirname as dirname14, join as
|
|
25850
|
+
import { opendirSync as opendirSync7 } from "node:fs";
|
|
25851
|
+
import { dirname as dirname14, join as join23 } from "node:path";
|
|
25852
|
+
|
|
25853
|
+
// src/cadence-instructions.ts
|
|
25854
|
+
var CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits.
|
|
25855
|
+
You are the sole user-facing coordinator. Continue normal conversation, not a task-manager UI. Do not ask the user to manage tasks, IDs, JSON, service ports, Save/Start/check menus or agent assignments.
|
|
25856
|
+
For each new goal: inspect relevant project evidence through cadence_research (up to two independent readonly subagents); read existing AGENTS/docs/.cadence/project.md before proposing conventions. Reuse still-current findings; do not rescan the entire repository or spawn agents merely to fill slots. Aggregate questions yourself. Investigate discoverable facts and ask focused, frequent questions only for unresolved product/technical decisions. Preserve confirmed decisions across turns. Diagnosis/research alone never imply implementation.
|
|
25857
|
+
Once material decisions and acceptance criteria are aligned, use cadence_plan with a readable design, explicit non-goals/decisions, exact file scopes, a finite dependency DAG, real verification commands, worktree prerequisites and a bounded repair budget. Independent writes may run concurrently; shared files need a single owner or dependency. Investigate local tool/dependency prerequisites BEFORE finalizing: isolated worktrees do not inherit ignored node_modules. Setup commands require inclusion in the final approval; never silently install/download/copy dependencies or credentials. local-merge needs an existing Git branch and commit identity; working-copy is explicit direct editing without Git mutation and is serialized.
|
|
25858
|
+
Present the returned complete plan and invite a single clear execution approval (the user can type 按计划实施). cadence_start binds the exact displayed plan and obtains fresh user consent; never interpret a vague acknowledgement as approval. No further confirmations are needed for the approved bounded pipeline. No push, publication, deployment, recursive delegation or scope expansion. If a material decision changes, revise the plan and seek fresh approval.
|
|
25859
|
+
During accepted work answer questions, report actual retained progress, and let the service execute. cadence_cancel is explicit cancellation, not navigation/exit. Never claim a worker's prose is a passing check or automatic review is human review. Failed/unknown/blocked outcomes are not success. A completed goal leaves Cadence ON and ready for the next goal; do not require /cadence again. Unrelated discussion is still ordinary conversation within this mode, not implicit permission to start another implementation. Tools operate on the host; this is not a sandbox.`;
|
|
25860
|
+
|
|
25861
|
+
// src/service/conversation-workflow.ts
|
|
25862
|
+
var BYTES = 384 * 1024;
|
|
25863
|
+
|
|
25864
|
+
class ConversationWorkflow {
|
|
25865
|
+
o;
|
|
25866
|
+
root;
|
|
25867
|
+
activeTurn = null;
|
|
25868
|
+
grants = new Map;
|
|
25869
|
+
constructor(o) {
|
|
25870
|
+
this.o = o;
|
|
25871
|
+
this.root = join23(o.coordination.directory, "conversation-workflows-v1");
|
|
25872
|
+
}
|
|
25873
|
+
path(id) {
|
|
25874
|
+
return join23(this.root, decodeId(id), "state.json");
|
|
25875
|
+
}
|
|
25876
|
+
read(id) {
|
|
25877
|
+
this.o.owner.lease.assert();
|
|
25878
|
+
const file = this.o.coordination.files.read(this.path(id), BYTES);
|
|
25879
|
+
if (!file) {
|
|
25880
|
+
if (this.o.conversations.controlBound(id) || this.o.coordination.files.directory(dirname14(this.path(id))))
|
|
25881
|
+
throw new ContractError("corrupt-selected");
|
|
25882
|
+
return {
|
|
25883
|
+
state: {
|
|
25884
|
+
id,
|
|
25885
|
+
revision: 0,
|
|
25886
|
+
enabled: false,
|
|
25887
|
+
head: null,
|
|
25888
|
+
proposal: null,
|
|
25889
|
+
runs: []
|
|
25890
|
+
}
|
|
25891
|
+
};
|
|
25892
|
+
}
|
|
25893
|
+
const record2 = closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
|
|
25894
|
+
"schema",
|
|
25895
|
+
"state"
|
|
25896
|
+
]);
|
|
25897
|
+
if (record2.schema !== "cadence-conversation-workflow/1")
|
|
25898
|
+
throw new ContractError("corrupt-selected");
|
|
25899
|
+
const state = decodeCadenceConversation(record2.state);
|
|
25900
|
+
if (!this.o.conversations.controlBound(id) || state.id !== id || state.head && !this.o.conversations.hasTurn(id, state.head))
|
|
25901
|
+
throw new ContractError("corrupt-selected");
|
|
25902
|
+
return { state, file };
|
|
25903
|
+
}
|
|
25904
|
+
save(state, file) {
|
|
25905
|
+
this.o.owner.lease.assert();
|
|
25906
|
+
if (!Number.isSafeInteger(state.revision))
|
|
25907
|
+
throw new ContractError("capacity");
|
|
25908
|
+
const body = canonicalJson({
|
|
25909
|
+
schema: "cadence-conversation-workflow/1",
|
|
25910
|
+
state: decodeCadenceConversation(state)
|
|
25911
|
+
}, BYTES);
|
|
25912
|
+
try {
|
|
25913
|
+
if (file)
|
|
25914
|
+
this.o.coordination.files.replace(this.path(state.id), file, body, BYTES);
|
|
25915
|
+
else
|
|
25916
|
+
this.o.coordination.files.create(this.path(state.id), body, BYTES);
|
|
25917
|
+
} catch (e) {
|
|
25918
|
+
this.o.owner.quarantine();
|
|
25919
|
+
throw e;
|
|
25920
|
+
}
|
|
25921
|
+
}
|
|
25922
|
+
assertRecords() {
|
|
25923
|
+
if (!this.o.coordination.files.directory(this.root))
|
|
25924
|
+
return;
|
|
25925
|
+
const dir = opendirSync7(this.root);
|
|
25926
|
+
let count2 = 0;
|
|
25927
|
+
try {
|
|
25928
|
+
for (let e = dir.readSync();e; e = dir.readSync()) {
|
|
25929
|
+
if (!e.isDirectory() || ++count2 > 200)
|
|
25930
|
+
throw new ContractError("capacity");
|
|
25931
|
+
this.read(decodeId(e.name));
|
|
25932
|
+
}
|
|
25933
|
+
} finally {
|
|
25934
|
+
dir.closeSync();
|
|
25935
|
+
}
|
|
25936
|
+
}
|
|
25937
|
+
state(id) {
|
|
25938
|
+
return this.read(id).state;
|
|
25939
|
+
}
|
|
25940
|
+
run(id) {
|
|
25941
|
+
const view = this.o.workflows.view(id);
|
|
25942
|
+
if (view.kind !== "workflow" || view.response.type !== "run")
|
|
25943
|
+
throw new ContractError("unavailable");
|
|
25944
|
+
return view.response.run;
|
|
25945
|
+
}
|
|
25946
|
+
preview(run, bytes, steps) {
|
|
25947
|
+
const clip = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
|
|
25948
|
+
return {
|
|
25949
|
+
...run,
|
|
25950
|
+
goal: clip(run.goal, 320),
|
|
25951
|
+
notice: clip(run.notice, 512),
|
|
25952
|
+
stepsOmitted: Math.max(0, run.steps.length - steps),
|
|
25953
|
+
steps: run.steps.slice(-steps).map((s) => {
|
|
25954
|
+
const text2 = clip(s.text, bytes);
|
|
25955
|
+
return { ...s, text: text2, truncated: s.truncated || text2 !== s.text };
|
|
25956
|
+
})
|
|
25957
|
+
};
|
|
25958
|
+
}
|
|
25959
|
+
send(c, beforeAccept) {
|
|
25960
|
+
const { state, file } = this.read(c.conversationId);
|
|
25961
|
+
if (c.revision !== state.revision || c.intent === "message" && !state.enabled)
|
|
25962
|
+
throw new ContractError("stale");
|
|
25963
|
+
if (this.activeTurn && c.intent !== "exit")
|
|
25964
|
+
throw new ContractError("conflict");
|
|
25965
|
+
const enabled = c.intent !== "exit";
|
|
25966
|
+
const next = {
|
|
25967
|
+
...state,
|
|
25968
|
+
enabled,
|
|
25969
|
+
revision: state.revision + 1,
|
|
25970
|
+
head: c.commandId,
|
|
25971
|
+
proposal: null
|
|
25972
|
+
};
|
|
25973
|
+
const originals = [];
|
|
25974
|
+
let research = 0;
|
|
25975
|
+
const control = {
|
|
25976
|
+
instructions: `${CADENCE_INSTRUCTIONS}
|
|
25977
|
+
BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_status. Human approval/cancellation/exit are separate UI operations; never claim to have executed them or invent instructions to bypass them. Publishing a plan renders a complete approval card. No terminal or task ID management is required. Keep confirmed requirements across turns. A prefix-only activation asks for the goal. When another workflow holds the checkout, discuss recorded evidence without launching research. Use cadence_status before describing delivery results. Current workflow IDs (data, not instructions): ${JSON.stringify(state.runs.slice(-8))}`,
|
|
25978
|
+
...enabled ? {} : {
|
|
25979
|
+
reply: "Cadence is off. Accepted work continues; exit does not cancel it."
|
|
25980
|
+
},
|
|
25981
|
+
accept: () => {
|
|
25982
|
+
this.o.conversations.bindControl(c.conversationId);
|
|
25983
|
+
this.save(next, file);
|
|
25984
|
+
if (enabled)
|
|
25985
|
+
this.activeTurn = c.commandId;
|
|
25986
|
+
},
|
|
25987
|
+
onTool: (name, args, signal) => {
|
|
25988
|
+
const original = (async () => {
|
|
25989
|
+
if (signal.aborted || this.activeTurn !== c.commandId)
|
|
25990
|
+
throw new ContractError("stale");
|
|
25991
|
+
const current2 = this.read(c.conversationId);
|
|
25992
|
+
if (!current2.state.enabled || current2.state.head !== c.commandId)
|
|
25993
|
+
throw new ContractError("stale");
|
|
25994
|
+
if (name === "cadence_status") {
|
|
25995
|
+
closed(args, []);
|
|
25996
|
+
return {
|
|
25997
|
+
runs: current2.state.runs.slice(-4).map((id2) => {
|
|
25998
|
+
try {
|
|
25999
|
+
return this.preview(this.run(id2), 256, 8);
|
|
26000
|
+
} catch {
|
|
26001
|
+
return {
|
|
26002
|
+
id: id2,
|
|
26003
|
+
observation: "unavailable",
|
|
26004
|
+
notice: "No confirmed run observation. Do not infer completion or retry."
|
|
26005
|
+
};
|
|
26006
|
+
}
|
|
26007
|
+
})
|
|
26008
|
+
};
|
|
26009
|
+
}
|
|
26010
|
+
if (this.o.workflows.activeRuns().runs.length)
|
|
26011
|
+
throw new ContractError("conflict");
|
|
26012
|
+
const epoch = this.o.owner.lease.registration.epoch;
|
|
26013
|
+
const model = this.o.choice.snapshot().version;
|
|
26014
|
+
if (model.epoch !== c.model.epoch || model.configRev !== c.model.configRev || model.catalogId !== c.model.catalogId)
|
|
26015
|
+
throw new ContractError("stale");
|
|
26016
|
+
if (name === "cadence_plan") {
|
|
26017
|
+
const plan = decodeWorkflowPlan(args);
|
|
26018
|
+
const p = this.o.workflows.command(randomUUID19(), epoch, {
|
|
26019
|
+
action: "propose",
|
|
26020
|
+
plan,
|
|
26021
|
+
model
|
|
26022
|
+
});
|
|
26023
|
+
if (p.kind !== "workflow" || p.response.type !== "proposal")
|
|
26024
|
+
throw new ContractError("unavailable");
|
|
26025
|
+
this.save({
|
|
26026
|
+
...current2.state,
|
|
26027
|
+
revision: current2.state.revision + 1,
|
|
26028
|
+
proposal: p.response.proposal
|
|
26029
|
+
}, current2.file);
|
|
26030
|
+
return {
|
|
26031
|
+
proposalId: p.response.proposal.id,
|
|
26032
|
+
digest: p.response.proposal.digest,
|
|
26033
|
+
notice: "Complete plan displayed for human approval. No execution has been authorized."
|
|
26034
|
+
};
|
|
26035
|
+
}
|
|
26036
|
+
if (name !== "cadence_research" || ++research > 2 || current2.state.runs.length >= 200)
|
|
26037
|
+
throw new ContractError("capacity");
|
|
26038
|
+
const a = closed(args, ["goal", "questions"]);
|
|
26039
|
+
const goal = text(a.goal, 8192, true), questions = list(a.questions, 2, (q) => text(q, 8192, true));
|
|
26040
|
+
if (!questions.length)
|
|
26041
|
+
throw new ContractError("invalid");
|
|
26042
|
+
const id = randomUUID19();
|
|
26043
|
+
this.save({
|
|
26044
|
+
...current2.state,
|
|
26045
|
+
revision: current2.state.revision + 1,
|
|
26046
|
+
runs: [...current2.state.runs, id]
|
|
26047
|
+
}, current2.file);
|
|
26048
|
+
this.o.workflows.command(id, epoch, {
|
|
26049
|
+
action: "research",
|
|
26050
|
+
goal,
|
|
26051
|
+
questions,
|
|
26052
|
+
model
|
|
26053
|
+
});
|
|
26054
|
+
const cancel = () => {
|
|
26055
|
+
try {
|
|
26056
|
+
this.o.workflows.command(randomUUID19(), epoch, {
|
|
26057
|
+
action: "cancel",
|
|
26058
|
+
runId: id
|
|
26059
|
+
});
|
|
26060
|
+
} catch {}
|
|
26061
|
+
};
|
|
26062
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
26063
|
+
if (signal.aborted)
|
|
26064
|
+
cancel();
|
|
26065
|
+
try {
|
|
26066
|
+
await this.o.workflows.join(id);
|
|
26067
|
+
} finally {
|
|
26068
|
+
signal.removeEventListener("abort", cancel);
|
|
26069
|
+
}
|
|
26070
|
+
return this.preview(this.run(id), 4096, 2);
|
|
26071
|
+
})();
|
|
26072
|
+
originals.push(original);
|
|
26073
|
+
return original;
|
|
26074
|
+
},
|
|
26075
|
+
settle: async () => {
|
|
26076
|
+
try {
|
|
26077
|
+
await Promise.allSettled(originals);
|
|
26078
|
+
} finally {
|
|
26079
|
+
if (this.activeTurn === c.commandId)
|
|
26080
|
+
this.activeTurn = null;
|
|
26081
|
+
}
|
|
26082
|
+
}
|
|
26083
|
+
};
|
|
26084
|
+
const userText = enabled ? sanitizeText(c.text, this.o.secrets()) : "exit cadence";
|
|
26085
|
+
return this.o.conversations.send({
|
|
26086
|
+
kind: "send",
|
|
26087
|
+
commandId: c.commandId,
|
|
26088
|
+
conversationId: c.conversationId,
|
|
26089
|
+
head: c.head,
|
|
26090
|
+
text: userText,
|
|
26091
|
+
model: c.model
|
|
26092
|
+
}, control, beforeAccept);
|
|
26093
|
+
}
|
|
26094
|
+
approval(c, caller) {
|
|
26095
|
+
if (!caller)
|
|
26096
|
+
throw new ContractError("forbidden");
|
|
26097
|
+
const { state, file } = this.read(c.conversationId);
|
|
26098
|
+
const view = this.o.conversations.view(c.conversationId, null);
|
|
26099
|
+
if (!state.enabled || c.revision !== state.revision || !state.proposal || state.proposal.id !== c.proposalId || state.proposal.digest !== c.digest || view.kind !== "conversation" || view.summary?.head !== state.head || view.summary.status !== "completed" || this.activeTurn)
|
|
26100
|
+
throw new ContractError("stale");
|
|
26101
|
+
const epoch = this.o.owner.lease.registration.epoch;
|
|
26102
|
+
if (c.kind === "cadence-prepare") {
|
|
26103
|
+
for (const [id, g2] of this.grants)
|
|
26104
|
+
if (g2.expiresAt < Date.now())
|
|
26105
|
+
this.grants.delete(id);
|
|
26106
|
+
if (this.grants.size >= 16)
|
|
26107
|
+
throw new ContractError("capacity");
|
|
26108
|
+
const prepared = this.o.workflows.command(c.commandId, epoch, {
|
|
26109
|
+
action: "prepare",
|
|
26110
|
+
proposalId: c.proposalId,
|
|
26111
|
+
digest: c.digest
|
|
26112
|
+
});
|
|
26113
|
+
if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
|
|
26114
|
+
throw new ContractError("unavailable");
|
|
26115
|
+
const g = prepared.response, grant2 = randomUUID19();
|
|
26116
|
+
this.grants.set(grant2, {
|
|
26117
|
+
caller: canonicalJson(caller),
|
|
26118
|
+
revision: c.revision,
|
|
26119
|
+
conversationId: c.conversationId,
|
|
26120
|
+
proposalId: c.proposalId,
|
|
26121
|
+
digest: c.digest,
|
|
26122
|
+
expiresAt: g.expiresAt,
|
|
26123
|
+
nativeGrant: g.grant
|
|
26124
|
+
});
|
|
26125
|
+
return {
|
|
26126
|
+
kind: "cadence-grant",
|
|
26127
|
+
commandId: c.commandId,
|
|
26128
|
+
grant: grant2,
|
|
26129
|
+
expiresAt: g.expiresAt,
|
|
26130
|
+
revision: c.revision,
|
|
26131
|
+
proposal: g.proposal
|
|
26132
|
+
};
|
|
26133
|
+
}
|
|
26134
|
+
const grant = this.grants.get(c.grant);
|
|
26135
|
+
this.grants.delete(c.grant);
|
|
26136
|
+
if (!grant || grant.caller !== canonicalJson(caller) || grant.expiresAt < Date.now() || grant.revision !== c.revision || grant.conversationId !== c.conversationId || grant.proposalId !== c.proposalId || grant.digest !== c.digest)
|
|
26137
|
+
throw new ContractError("expired-grant");
|
|
26138
|
+
if (state.runs.length >= 200)
|
|
26139
|
+
throw new ContractError("capacity");
|
|
26140
|
+
try {
|
|
26141
|
+
this.o.coordination.files.create(join23(this.root, state.id, "approvals", `${c.commandId}.json`), canonicalJson({
|
|
26142
|
+
commandId: c.commandId,
|
|
26143
|
+
conversationId: state.id,
|
|
26144
|
+
revision: c.revision,
|
|
26145
|
+
proposalId: c.proposalId,
|
|
26146
|
+
digest: c.digest,
|
|
26147
|
+
caller,
|
|
26148
|
+
epoch,
|
|
26149
|
+
at: Date.now()
|
|
26150
|
+
}, 16384), 16384);
|
|
26151
|
+
} catch (e) {
|
|
26152
|
+
this.o.owner.quarantine();
|
|
26153
|
+
throw e;
|
|
26154
|
+
}
|
|
26155
|
+
this.save({
|
|
26156
|
+
...state,
|
|
26157
|
+
revision: state.revision + 1,
|
|
26158
|
+
proposal: null,
|
|
26159
|
+
runs: [...state.runs, c.commandId]
|
|
26160
|
+
}, file);
|
|
26161
|
+
return this.o.workflows.command(c.commandId, epoch, {
|
|
26162
|
+
action: "execute",
|
|
26163
|
+
proposalId: c.proposalId,
|
|
26164
|
+
digest: c.digest,
|
|
26165
|
+
grant: grant.nativeGrant
|
|
26166
|
+
});
|
|
26167
|
+
}
|
|
26168
|
+
}
|
|
26169
|
+
|
|
26170
|
+
// src/service/conversations.ts
|
|
26171
|
+
import { randomUUID as randomUUID20 } from "node:crypto";
|
|
26172
|
+
import { lstatSync as lstatSync13, opendirSync as opendirSync8, realpathSync as realpathSync7, statfsSync as statfsSync2 } from "node:fs";
|
|
26173
|
+
import { dirname as dirname15, join as join24 } from "node:path";
|
|
25158
26174
|
var TURN_BYTES = 384 * 1024;
|
|
25159
26175
|
var META_BYTES = 64 * 1024;
|
|
25160
26176
|
var SESSION_LIMIT = 200;
|
|
26177
|
+
var OMITTED_FLAG = {
|
|
26178
|
+
"hidden-thinking": "thinking",
|
|
26179
|
+
binary: "media",
|
|
26180
|
+
unsupported: "other"
|
|
26181
|
+
};
|
|
25161
26182
|
|
|
25162
26183
|
class ConversationCapture {
|
|
25163
26184
|
turn;
|
|
@@ -25251,8 +26272,8 @@ class ConversationCapture {
|
|
|
25251
26272
|
item.error = e.isError;
|
|
25252
26273
|
} else if (e.kind === "worker-failure")
|
|
25253
26274
|
this.turn.notice = `worker-failure: ${e.code}`;
|
|
25254
|
-
else if (e.kind === "omitted-block")
|
|
25255
|
-
this.turn.
|
|
26275
|
+
else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff")
|
|
26276
|
+
this.turn.omitted[OMITTED_FLAG[e.block.reason]] = true;
|
|
25256
26277
|
if ([...this.details.values()].reduce((size, detail) => size + Buffer.byteLength(detail.text) + detail.sanitizer.retainedBytes, 0) > TURN_BYTES)
|
|
25257
26278
|
throw new ContractError("capacity");
|
|
25258
26279
|
canonicalJson(this.turn, TURN_BYTES);
|
|
@@ -25273,7 +26294,7 @@ class Conversations {
|
|
|
25273
26294
|
active = new Map;
|
|
25274
26295
|
constructor(o) {
|
|
25275
26296
|
this.o = o;
|
|
25276
|
-
this.root =
|
|
26297
|
+
this.root = join24(o.coordination.directory, "conversations-v1");
|
|
25277
26298
|
this.cwd = realpathSync7(o.cwd);
|
|
25278
26299
|
}
|
|
25279
26300
|
currentDirectory() {
|
|
@@ -25284,13 +26305,13 @@ class Conversations {
|
|
|
25284
26305
|
return this.o.coordination.files;
|
|
25285
26306
|
}
|
|
25286
26307
|
path(id, name) {
|
|
25287
|
-
return
|
|
26308
|
+
return join24(this.root, "turns", decodeId(id), name);
|
|
25288
26309
|
}
|
|
25289
26310
|
identityPath(id) {
|
|
25290
|
-
return
|
|
26311
|
+
return join24(this.root, "identities", `${decodeId(id)}.json`);
|
|
25291
26312
|
}
|
|
25292
26313
|
metadataPath(id) {
|
|
25293
|
-
return
|
|
26314
|
+
return join24(this.root, "sessions", `${decodeId(id)}.json`);
|
|
25294
26315
|
}
|
|
25295
26316
|
read(path, max) {
|
|
25296
26317
|
const value = this.files.read(path, max);
|
|
@@ -25339,6 +26360,23 @@ class Conversations {
|
|
|
25339
26360
|
notice: "Original work is not observed. No automatic replay."
|
|
25340
26361
|
} : turn;
|
|
25341
26362
|
}
|
|
26363
|
+
controlBound(id) {
|
|
26364
|
+
const path = join24(this.root, "control-links", `${decodeId(id)}.json`);
|
|
26365
|
+
const value = this.read(path, META_BYTES);
|
|
26366
|
+
if (value === undefined)
|
|
26367
|
+
return false;
|
|
26368
|
+
const record2 = closed(value, ["schema", "conversationId"]);
|
|
26369
|
+
if (record2.schema !== "cadence-conversation-control/1" || record2.conversationId !== id)
|
|
26370
|
+
throw new ContractError("corrupt-selected");
|
|
26371
|
+
return true;
|
|
26372
|
+
}
|
|
26373
|
+
bindControl(id) {
|
|
26374
|
+
if (!this.controlBound(id))
|
|
26375
|
+
this.write(join24(this.root, "control-links", `${decodeId(id)}.json`), { schema: "cadence-conversation-control/1", conversationId: id }, META_BYTES);
|
|
26376
|
+
}
|
|
26377
|
+
hasTurn(id, turnId) {
|
|
26378
|
+
return this.metadata(id)?.turns.includes(turnId) ?? false;
|
|
26379
|
+
}
|
|
25342
26380
|
summary(meta) {
|
|
25343
26381
|
const head = meta.turns.at(-1), turn = this.turn(head);
|
|
25344
26382
|
const accepted2 = closed(this.read(this.path(head, "accepted.json"), META_BYTES), ["command", "at"]);
|
|
@@ -25364,13 +26402,13 @@ class Conversations {
|
|
|
25364
26402
|
}
|
|
25365
26403
|
list() {
|
|
25366
26404
|
this.o.owner.lease.assert();
|
|
25367
|
-
const dir =
|
|
26405
|
+
const dir = join24(this.root, "sessions");
|
|
25368
26406
|
if (!this.files.directory(dir))
|
|
25369
26407
|
return {
|
|
25370
26408
|
kind: "conversations",
|
|
25371
26409
|
entries: [...this.active.values()].map((live) => this.liveSummary(live))
|
|
25372
26410
|
};
|
|
25373
|
-
const entries = [], opened =
|
|
26411
|
+
const entries = [], opened = opendirSync8(dir);
|
|
25374
26412
|
try {
|
|
25375
26413
|
for (let e = opened.readSync();e; e = opened.readSync()) {
|
|
25376
26414
|
if (!e.isFile() || !e.name.endsWith(".json") || entries.length >= SESSION_LIMIT)
|
|
@@ -25441,12 +26479,12 @@ class Conversations {
|
|
|
25441
26479
|
const visit = (directory, depth) => {
|
|
25442
26480
|
if (depth > 4 || !this.files.directory(directory))
|
|
25443
26481
|
return;
|
|
25444
|
-
const dir =
|
|
26482
|
+
const dir = opendirSync8(directory);
|
|
25445
26483
|
try {
|
|
25446
26484
|
for (let entry = dir.readSync();entry; entry = dir.readSync()) {
|
|
25447
26485
|
if (++count2 > 1e4)
|
|
25448
26486
|
throw new ContractError("capacity");
|
|
25449
|
-
const path =
|
|
26487
|
+
const path = join24(directory, entry.name);
|
|
25450
26488
|
if (entry.isDirectory())
|
|
25451
26489
|
visit(path, depth + 1);
|
|
25452
26490
|
else if (entry.isFile())
|
|
@@ -25462,11 +26500,16 @@ class Conversations {
|
|
|
25462
26500
|
};
|
|
25463
26501
|
visit(this.root, 0);
|
|
25464
26502
|
}
|
|
25465
|
-
|
|
26503
|
+
attempted(conversationId, commandId) {
|
|
26504
|
+
this.o.owner.lease.assert();
|
|
26505
|
+
const meta = this.metadata(conversationId);
|
|
26506
|
+
return this.active.has(commandId) || this.files.directory(dirname15(this.path(commandId, "accepted.json"))) || !!meta?.turns.includes(commandId) || !meta && !!this.files.read(this.identityPath(conversationId), META_BYTES);
|
|
26507
|
+
}
|
|
26508
|
+
send(input, control, beforeAccept) {
|
|
25466
26509
|
this.o.owner.lease.assert();
|
|
25467
26510
|
const command = {
|
|
25468
26511
|
...input,
|
|
25469
|
-
text: sanitizeText(input.text, this.o.secrets())
|
|
26512
|
+
text: control?.reply ? "exit cadence" : sanitizeText(input.text, this.o.secrets())
|
|
25470
26513
|
};
|
|
25471
26514
|
const prior = this.read(this.path(input.commandId, "accepted.json"), META_BYTES);
|
|
25472
26515
|
if (prior !== undefined) {
|
|
@@ -25475,14 +26518,15 @@ class Conversations {
|
|
|
25475
26518
|
throw new ContractError("conflict");
|
|
25476
26519
|
return { kind: "accepted", commandId: input.commandId };
|
|
25477
26520
|
}
|
|
25478
|
-
if (this.files.directory(
|
|
26521
|
+
if (this.files.directory(dirname15(this.path(input.commandId, "accepted.json"))))
|
|
25479
26522
|
throw new ContractError("corrupt-selected");
|
|
25480
26523
|
if (this.o.owner.state !== "idle")
|
|
25481
26524
|
throw new ContractError("quarantine");
|
|
25482
26525
|
const choice = this.o.choice.snapshot();
|
|
25483
|
-
if (!choice.selected || canonicalJson(choice.version) !== canonicalJson(input.model))
|
|
26526
|
+
if (!choice.selected && !control?.reply || canonicalJson(choice.version) !== canonicalJson(input.model))
|
|
25484
26527
|
throw new ContractError("stale");
|
|
25485
|
-
|
|
26528
|
+
if (choice.selected && !control?.reply)
|
|
26529
|
+
this.o.models.assertCurrent(choice.selected);
|
|
25486
26530
|
if (!this.currentDirectory())
|
|
25487
26531
|
throw new ContractError("stale");
|
|
25488
26532
|
const beforeMeta = this.files.read(this.metadataPath(input.conversationId), META_BYTES);
|
|
@@ -25492,7 +26536,7 @@ class Conversations {
|
|
|
25492
26536
|
throw new ContractError("corrupt-selected");
|
|
25493
26537
|
if ((meta?.turns.at(-1) ?? null) !== input.head)
|
|
25494
26538
|
throw new ContractError("stale");
|
|
25495
|
-
if (meta && this.turn(input.head).status !== "completed")
|
|
26539
|
+
if (meta && this.turn(input.head).status !== "completed" && (!control || ["queued", "running", "unknown"].includes(this.turn(input.head).status)))
|
|
25496
26540
|
throw new ContractError("conflict");
|
|
25497
26541
|
if (this.active.size >= 8 || (meta?.turns.length ?? 0) >= 1000 || !meta && this.list().entries.length >= SESSION_LIMIT)
|
|
25498
26542
|
throw new ContractError("capacity");
|
|
@@ -25509,6 +26553,7 @@ class Conversations {
|
|
|
25509
26553
|
epoch: input.model.epoch,
|
|
25510
26554
|
status: "queued",
|
|
25511
26555
|
notice: "",
|
|
26556
|
+
omitted: { thinking: false, media: false, other: false },
|
|
25512
26557
|
items: [
|
|
25513
26558
|
{
|
|
25514
26559
|
id: "user",
|
|
@@ -25535,7 +26580,7 @@ class Conversations {
|
|
|
25535
26580
|
const ready2 = new Promise((resolve8) => {
|
|
25536
26581
|
begin = resolve8;
|
|
25537
26582
|
});
|
|
25538
|
-
const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort));
|
|
26583
|
+
const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort, control));
|
|
25539
26584
|
const live = {
|
|
25540
26585
|
turn,
|
|
25541
26586
|
abort,
|
|
@@ -25546,9 +26591,11 @@ class Conversations {
|
|
|
25546
26591
|
turnFile: null,
|
|
25547
26592
|
metaFile: null
|
|
25548
26593
|
};
|
|
26594
|
+
beforeAccept?.();
|
|
25549
26595
|
this.active.set(turn.id, live);
|
|
25550
26596
|
this.o.owner.trackConversation(original, () => abort.abort());
|
|
25551
26597
|
try {
|
|
26598
|
+
control?.accept();
|
|
25552
26599
|
if (!meta)
|
|
25553
26600
|
this.write(this.identityPath(next.id), { schema: "cadence-conversation/1", id: next.id, cwd: this.cwd }, META_BYTES);
|
|
25554
26601
|
this.write(this.path(turn.id, "accepted.json"), { command, at: live.acceptedAt }, META_BYTES);
|
|
@@ -25563,29 +26610,29 @@ class Conversations {
|
|
|
25563
26610
|
begin();
|
|
25564
26611
|
return { kind: "accepted", commandId: turn.id };
|
|
25565
26612
|
}
|
|
25566
|
-
origin(
|
|
26613
|
+
origin(taskId2) {
|
|
25567
26614
|
this.o.owner.lease.assert();
|
|
25568
|
-
const value = this.read(
|
|
26615
|
+
const value = this.read(join24(this.root, "task-links", `${decodeId(taskId2)}.json`), META_BYTES);
|
|
25569
26616
|
if (value === undefined)
|
|
25570
|
-
return { kind: "task-origin", taskId, conversationId: null };
|
|
26617
|
+
return { kind: "task-origin", taskId: taskId2, conversationId: null };
|
|
25571
26618
|
const row = closed(value, ["conversationId"]);
|
|
25572
26619
|
return {
|
|
25573
26620
|
kind: "task-origin",
|
|
25574
|
-
taskId,
|
|
26621
|
+
taskId: taskId2,
|
|
25575
26622
|
conversationId: decodeId(row.conversationId)
|
|
25576
26623
|
};
|
|
25577
26624
|
}
|
|
25578
|
-
link(
|
|
26625
|
+
link(taskId2, conversationId, epoch) {
|
|
25579
26626
|
this.o.owner.lease.assert();
|
|
25580
26627
|
if (epoch !== this.o.owner.lease.registration.epoch || this.o.owner.state !== "idle")
|
|
25581
26628
|
throw new ContractError("stale");
|
|
25582
|
-
if (!this.metadata(conversationId) || !this.o.coordination.store.load(
|
|
26629
|
+
if (!this.metadata(conversationId) || !this.o.coordination.store.load(taskId2))
|
|
25583
26630
|
throw new ContractError("unavailable");
|
|
25584
|
-
const existing = this.origin(
|
|
26631
|
+
const existing = this.origin(taskId2).conversationId;
|
|
25585
26632
|
if (existing !== null && existing !== conversationId)
|
|
25586
26633
|
throw new ContractError("conflict");
|
|
25587
26634
|
if (existing === null)
|
|
25588
|
-
this.write(
|
|
26635
|
+
this.write(join24(this.root, "task-links", `${decodeId(taskId2)}.json`), { conversationId }, META_BYTES);
|
|
25589
26636
|
}
|
|
25590
26637
|
interrupt(id, turnId, epoch) {
|
|
25591
26638
|
this.o.owner.lease.assert();
|
|
@@ -25603,7 +26650,7 @@ class Conversations {
|
|
|
25603
26650
|
throw new ContractError("stale");
|
|
25604
26651
|
this.active.get(turnId)?.abort.abort();
|
|
25605
26652
|
}
|
|
25606
|
-
async run(command, turn, previous, previousFile, meta, abort) {
|
|
26653
|
+
async run(command, turn, previous, previousFile, meta, abort, control) {
|
|
25607
26654
|
let barrier;
|
|
25608
26655
|
let authSettled;
|
|
25609
26656
|
let uncertain = false;
|
|
@@ -25639,9 +26686,16 @@ class Conversations {
|
|
|
25639
26686
|
try {
|
|
25640
26687
|
if (!current2())
|
|
25641
26688
|
throw new ContractError("stale");
|
|
25642
|
-
|
|
25643
|
-
|
|
25644
|
-
|
|
26689
|
+
if (control?.reply) {
|
|
26690
|
+
turn.status = "completed";
|
|
26691
|
+
turn.notice = control.reply;
|
|
26692
|
+
return { status: "settled" };
|
|
26693
|
+
}
|
|
26694
|
+
if (!control) {
|
|
26695
|
+
barrier = await this.o.actions.scheduler.conversationBarrier(turn.id, abort.signal);
|
|
26696
|
+
barrier.assertHeld();
|
|
26697
|
+
this.o.actions.conversationBoundary(barrier);
|
|
26698
|
+
}
|
|
25645
26699
|
if (!current2())
|
|
25646
26700
|
throw new ContractError("stale");
|
|
25647
26701
|
const choice = this.o.choice.snapshot(), selected2 = choice.selected;
|
|
@@ -25650,24 +26704,24 @@ class Conversations {
|
|
|
25650
26704
|
const request3 = decodeWorkerPublicRequest({
|
|
25651
26705
|
protocol: 2,
|
|
25652
26706
|
taskId: meta.id,
|
|
25653
|
-
taskKind: "code",
|
|
26707
|
+
taskKind: control ? "research" : "code",
|
|
25654
26708
|
runId: turn.id,
|
|
25655
|
-
childRunId:
|
|
26709
|
+
childRunId: randomUUID20(),
|
|
25656
26710
|
assignmentId: "conversation",
|
|
25657
|
-
purpose: "edit",
|
|
26711
|
+
purpose: control ? "research" : "edit",
|
|
25658
26712
|
model: selected2,
|
|
25659
26713
|
role: {
|
|
25660
|
-
role: "implementation-worker",
|
|
25661
|
-
sha256: hash2("Ordinary conversation.")
|
|
26714
|
+
role: control ? "design-explorer" : "implementation-worker",
|
|
26715
|
+
sha256: hash2(control?.instructions ?? "Ordinary conversation.")
|
|
25662
26716
|
},
|
|
25663
26717
|
context: "",
|
|
25664
|
-
instructions: "Ordinary conversation.",
|
|
26718
|
+
instructions: control?.instructions ?? "Ordinary conversation.",
|
|
25665
26719
|
prompt: command.text,
|
|
25666
26720
|
handoff: { graphRevision: 1, inputs: [] }
|
|
25667
26721
|
});
|
|
25668
26722
|
const auth = this.o.models.prepareTracked({
|
|
25669
26723
|
request: request3,
|
|
25670
|
-
operationId:
|
|
26724
|
+
operationId: randomUUID20(),
|
|
25671
26725
|
epoch: turn.epoch,
|
|
25672
26726
|
timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
|
|
25673
26727
|
signal: abort.signal,
|
|
@@ -25692,10 +26746,12 @@ class Conversations {
|
|
|
25692
26746
|
]);
|
|
25693
26747
|
const running = Promise.resolve().then(() => launchConversation(prepared.prepared, {
|
|
25694
26748
|
previous,
|
|
25695
|
-
agentDir: this.o.agentDir
|
|
26749
|
+
agentDir: this.o.agentDir,
|
|
26750
|
+
...control ? { coordinator: true } : {}
|
|
25696
26751
|
}, abort.signal, {
|
|
25697
26752
|
timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
|
|
25698
26753
|
ownerSecrets: this.o.secrets,
|
|
26754
|
+
onCoordinator: control?.onTool,
|
|
25699
26755
|
onContext: (messages) => {
|
|
25700
26756
|
checkpoint = messages;
|
|
25701
26757
|
},
|
|
@@ -25734,6 +26790,7 @@ class Conversations {
|
|
|
25734
26790
|
turn.status = uncertain ? "unknown" : abort.signal.aborted ? "canceled" : "failed";
|
|
25735
26791
|
turn.notice ||= error2 instanceof ContractError ? error2.code : "Conversation failed.";
|
|
25736
26792
|
} finally {
|
|
26793
|
+
await control?.settle();
|
|
25737
26794
|
await authSettled;
|
|
25738
26795
|
uncertain ||= this.o.owner.state === "quarantined";
|
|
25739
26796
|
if (uncertain)
|
|
@@ -25745,7 +26802,7 @@ class Conversations {
|
|
|
25745
26802
|
if (turn.status !== "completed")
|
|
25746
26803
|
turn.notice = [
|
|
25747
26804
|
turn.notice,
|
|
25748
|
-
"Start a new conversation; incomplete context is not replayed."
|
|
26805
|
+
control ? "Incomplete work is not replayed. A new explicit message may continue from the last complete checkpoint." : "Start a new conversation; incomplete context is not replayed."
|
|
25749
26806
|
].filter(Boolean).join(`
|
|
25750
26807
|
`);
|
|
25751
26808
|
save();
|
|
@@ -25762,29 +26819,1085 @@ class Conversations {
|
|
|
25762
26819
|
}
|
|
25763
26820
|
}
|
|
25764
26821
|
|
|
26822
|
+
// src/service/workflows.ts
|
|
26823
|
+
import { randomUUID as randomUUID21 } from "node:crypto";
|
|
26824
|
+
import {
|
|
26825
|
+
lstatSync as lstatSync15,
|
|
26826
|
+
opendirSync as opendirSync9,
|
|
26827
|
+
realpathSync as realpathSync8,
|
|
26828
|
+
statfsSync as statfsSync3,
|
|
26829
|
+
writeFileSync as writeFileSync3
|
|
26830
|
+
} from "node:fs";
|
|
26831
|
+
import { dirname as dirname17, join as join26 } from "node:path";
|
|
26832
|
+
|
|
26833
|
+
// src/service/workflow-git.ts
|
|
26834
|
+
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
26835
|
+
import { lstatSync as lstatSync14, readFileSync as readFileSync2 } from "node:fs";
|
|
26836
|
+
import { dirname as dirname16, join as join25, relative as relative8, resolve as resolve8 } from "node:path";
|
|
26837
|
+
function gitRead(cwd, args) {
|
|
26838
|
+
const r = spawnSync3("git", gitArguments(args), {
|
|
26839
|
+
cwd,
|
|
26840
|
+
env: gitEnvironment(),
|
|
26841
|
+
encoding: "utf8",
|
|
26842
|
+
timeout: 1e4,
|
|
26843
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
26844
|
+
windowsHide: true
|
|
26845
|
+
});
|
|
26846
|
+
if (r.error || r.status !== 0)
|
|
26847
|
+
throw new ContractError("unavailable");
|
|
26848
|
+
return r.stdout;
|
|
26849
|
+
}
|
|
26850
|
+
function safeWorkflowFile(cwd, name) {
|
|
26851
|
+
workflowPath(name);
|
|
26852
|
+
const p = resolve8(cwd, name);
|
|
26853
|
+
if (relative8(cwd, p).startsWith(".."))
|
|
26854
|
+
throw new ContractError("forbidden");
|
|
26855
|
+
safeDirectory(dirname16(p));
|
|
26856
|
+
try {
|
|
26857
|
+
const st = lstatSync14(p);
|
|
26858
|
+
if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
|
|
26859
|
+
throw new ContractError("forbidden");
|
|
26860
|
+
} catch (e) {
|
|
26861
|
+
if (!(e instanceof Error && ("code" in e) && e.code === "ENOENT"))
|
|
26862
|
+
throw e;
|
|
26863
|
+
}
|
|
26864
|
+
return p;
|
|
26865
|
+
}
|
|
26866
|
+
function workflowChanged(cwd) {
|
|
26867
|
+
return [
|
|
26868
|
+
...new Set([
|
|
26869
|
+
...gitRead(cwd, [
|
|
26870
|
+
"diff",
|
|
26871
|
+
"--name-only",
|
|
26872
|
+
"-z",
|
|
26873
|
+
"--no-renames",
|
|
26874
|
+
"--no-ext-diff",
|
|
26875
|
+
"--no-textconv",
|
|
26876
|
+
"HEAD",
|
|
26877
|
+
"--"
|
|
26878
|
+
]).split("\x00").filter(Boolean),
|
|
26879
|
+
...gitRead(cwd, [
|
|
26880
|
+
"diff",
|
|
26881
|
+
"--cached",
|
|
26882
|
+
"--name-only",
|
|
26883
|
+
"-z",
|
|
26884
|
+
"--no-renames",
|
|
26885
|
+
"--no-ext-diff",
|
|
26886
|
+
"--no-textconv",
|
|
26887
|
+
"HEAD",
|
|
26888
|
+
"--"
|
|
26889
|
+
]).split("\x00").filter(Boolean),
|
|
26890
|
+
...gitRead(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]).split("\x00").filter(Boolean)
|
|
26891
|
+
])
|
|
26892
|
+
];
|
|
26893
|
+
}
|
|
26894
|
+
function assertWorkflowScope(cwd, allowed) {
|
|
26895
|
+
const changes = workflowChanged(cwd);
|
|
26896
|
+
for (const name of changes) {
|
|
26897
|
+
if (!allowed.includes(name))
|
|
26898
|
+
throw new ContractError("forbidden");
|
|
26899
|
+
safeWorkflowFile(cwd, name);
|
|
26900
|
+
}
|
|
26901
|
+
return changes;
|
|
26902
|
+
}
|
|
26903
|
+
function assertWorkflowCommit(cwd, before, commit, allowed) {
|
|
26904
|
+
if (gitRead(cwd, ["show", "-s", "--format=%P", commit]).trim() !== before)
|
|
26905
|
+
throw new ContractError("stale");
|
|
26906
|
+
const names2 = gitRead(cwd, [
|
|
26907
|
+
"diff",
|
|
26908
|
+
"--name-only",
|
|
26909
|
+
"-z",
|
|
26910
|
+
"--no-renames",
|
|
26911
|
+
"--no-ext-diff",
|
|
26912
|
+
"--no-textconv",
|
|
26913
|
+
before,
|
|
26914
|
+
commit,
|
|
26915
|
+
"--"
|
|
26916
|
+
]).split("\x00").filter(Boolean);
|
|
26917
|
+
for (const name of names2) {
|
|
26918
|
+
if (!allowed.includes(name))
|
|
26919
|
+
throw new ContractError("forbidden");
|
|
26920
|
+
safeWorkflowFile(cwd, name);
|
|
26921
|
+
}
|
|
26922
|
+
}
|
|
26923
|
+
function workflowObservation(cwd, plan) {
|
|
26924
|
+
const paths = [
|
|
26925
|
+
...new Set([
|
|
26926
|
+
".cadence/project.md",
|
|
26927
|
+
"AGENTS.md",
|
|
26928
|
+
...plan?.tasks.flatMap((t) => t.writes) ?? []
|
|
26929
|
+
])
|
|
26930
|
+
];
|
|
26931
|
+
const contents = paths.map((p) => {
|
|
26932
|
+
const file = safeWorkflowFile(cwd, p);
|
|
26933
|
+
const bytes = readBounded(file, 1024 * 1024);
|
|
26934
|
+
return [p, bytes ? hash2(bytes) : null];
|
|
26935
|
+
});
|
|
26936
|
+
if (plan?.delivery === "working-copy") {
|
|
26937
|
+
return { identity: hash2(JSON.stringify(contents)), head: "", branch: "" };
|
|
26938
|
+
}
|
|
26939
|
+
const head = gitRead(cwd, ["rev-parse", "--verify", "HEAD"]).trim();
|
|
26940
|
+
const branch = gitRead(cwd, ["symbolic-ref", "HEAD"]).trim();
|
|
26941
|
+
if (!/^refs\/heads\//u.test(branch) || !/^[a-f0-9]{40,64}$/u.test(head))
|
|
26942
|
+
throw new ContractError("invalid");
|
|
26943
|
+
if (plan) {
|
|
26944
|
+
const dirty = workflowChanged(cwd);
|
|
26945
|
+
if (dirty.some((p) => paths.some((q) => p === q || p.startsWith(`${q}/`) || q.startsWith(`${p}/`))))
|
|
26946
|
+
throw new ContractError("conflict");
|
|
26947
|
+
gitRead(cwd, ["var", "GIT_AUTHOR_IDENT"]);
|
|
26948
|
+
gitRead(cwd, ["var", "GIT_COMMITTER_IDENT"]);
|
|
26949
|
+
}
|
|
26950
|
+
return {
|
|
26951
|
+
head,
|
|
26952
|
+
branch,
|
|
26953
|
+
identity: hash2(JSON.stringify({
|
|
26954
|
+
head,
|
|
26955
|
+
branch,
|
|
26956
|
+
contents,
|
|
26957
|
+
status: gitRead(cwd, ["status", "--porcelain=v1", "-uall"]),
|
|
26958
|
+
index: gitRead(cwd, [
|
|
26959
|
+
"diff",
|
|
26960
|
+
"--cached",
|
|
26961
|
+
"--binary",
|
|
26962
|
+
"--no-ext-diff",
|
|
26963
|
+
"--no-textconv"
|
|
26964
|
+
]),
|
|
26965
|
+
worktree: gitRead(cwd, [
|
|
26966
|
+
"diff",
|
|
26967
|
+
"--binary",
|
|
26968
|
+
"--no-ext-diff",
|
|
26969
|
+
"--no-textconv"
|
|
26970
|
+
])
|
|
26971
|
+
}))
|
|
26972
|
+
};
|
|
26973
|
+
}
|
|
26974
|
+
function projectMarkdown(cwd, context) {
|
|
26975
|
+
const file = safeWorkflowFile(cwd, ".cadence/project.md");
|
|
26976
|
+
const previous = readBounded(file, 128 * 1024)?.toString("utf8") ?? `# Cadence project context
|
|
26977
|
+
`;
|
|
26978
|
+
const start = "<!-- CADENCE:PROJECT:START -->", end = "<!-- CADENCE:PROJECT:END -->";
|
|
26979
|
+
if (previous.split(start).length !== previous.split(end).length || previous.split(start).length > 2)
|
|
26980
|
+
throw new ContractError("conflict");
|
|
26981
|
+
const block = `${start}
|
|
26982
|
+
${context}
|
|
26983
|
+
${end}`;
|
|
26984
|
+
if (!previous.includes(start))
|
|
26985
|
+
return `${previous.trimEnd()}
|
|
26986
|
+
|
|
26987
|
+
${block}
|
|
26988
|
+
`;
|
|
26989
|
+
if (previous.indexOf(end) < previous.indexOf(start))
|
|
26990
|
+
throw new ContractError("conflict");
|
|
26991
|
+
return previous.slice(0, previous.indexOf(start)) + block + previous.slice(previous.indexOf(end) + end.length);
|
|
26992
|
+
}
|
|
26993
|
+
function assertWorktree(root, cwd) {
|
|
26994
|
+
if (!safeDirectory(cwd) || resolve8(gitRead(cwd, ["rev-parse", "--show-toplevel"]).trim()) !== resolve8(cwd))
|
|
26995
|
+
throw new ContractError("stale");
|
|
26996
|
+
const common = (p) => resolve8(p, gitRead(p, ["rev-parse", "--git-common-dir"]).trim());
|
|
26997
|
+
if (common(root) !== common(cwd))
|
|
26998
|
+
throw new ContractError("stale");
|
|
26999
|
+
const marker2 = join25(cwd, ".git");
|
|
27000
|
+
if (!lstatSync14(marker2).isFile() || !readFileSync2(marker2, "utf8").startsWith("gitdir: "))
|
|
27001
|
+
throw new ContractError("stale");
|
|
27002
|
+
}
|
|
27003
|
+
|
|
27004
|
+
// src/service/workflows.ts
|
|
27005
|
+
var RECORD_BYTES2 = 384 * 1024;
|
|
27006
|
+
|
|
27007
|
+
class WorkflowFailure extends Error {
|
|
27008
|
+
outcome;
|
|
27009
|
+
constructor(outcome, message) {
|
|
27010
|
+
super(message);
|
|
27011
|
+
this.outcome = outcome;
|
|
27012
|
+
}
|
|
27013
|
+
}
|
|
27014
|
+
|
|
27015
|
+
class Workflows {
|
|
27016
|
+
o;
|
|
27017
|
+
root;
|
|
27018
|
+
cwd;
|
|
27019
|
+
active = new Map;
|
|
27020
|
+
grants = new Map;
|
|
27021
|
+
constructor(o) {
|
|
27022
|
+
this.o = o;
|
|
27023
|
+
this.root = join26(o.coordination.directory, "workflows-v1");
|
|
27024
|
+
this.cwd = realpathSync8(o.coordination.store.root);
|
|
27025
|
+
const runs = join26(this.root, "runs");
|
|
27026
|
+
if (this.files.directory(runs)) {
|
|
27027
|
+
const dir = opendirSync9(runs);
|
|
27028
|
+
try {
|
|
27029
|
+
let count2 = 0;
|
|
27030
|
+
for (let e = dir.readSync();e; e = dir.readSync()) {
|
|
27031
|
+
if (++count2 > WORKFLOW_LIMITS.runs || !e.isDirectory())
|
|
27032
|
+
throw new ContractError("capacity");
|
|
27033
|
+
const id = decodeId(e.name);
|
|
27034
|
+
const state = this.files.read(this.path(id, "state.json"), RECORD_BYTES2);
|
|
27035
|
+
if (!state)
|
|
27036
|
+
throw new ContractError("quarantine");
|
|
27037
|
+
const run = decodeWorkflowRun(parseWireJson(state.bytes.toString("utf8"), RECORD_BYTES2));
|
|
27038
|
+
if (["queued", "running", "unknown"].includes(run.status))
|
|
27039
|
+
throw new ContractError("quarantine");
|
|
27040
|
+
}
|
|
27041
|
+
} finally {
|
|
27042
|
+
dir.closeSync();
|
|
27043
|
+
}
|
|
27044
|
+
}
|
|
27045
|
+
}
|
|
27046
|
+
get files() {
|
|
27047
|
+
return this.o.coordination.files;
|
|
27048
|
+
}
|
|
27049
|
+
path(id, name) {
|
|
27050
|
+
return join26(this.root, "runs", decodeId(id), name);
|
|
27051
|
+
}
|
|
27052
|
+
write(path, value, expected, max = RECORD_BYTES2) {
|
|
27053
|
+
this.o.owner.lease.assert();
|
|
27054
|
+
const body = canonicalJson(value, max);
|
|
27055
|
+
try {
|
|
27056
|
+
return expected ? this.files.replace(path, expected, body, max) : this.files.create(path, body, max);
|
|
27057
|
+
} catch (e) {
|
|
27058
|
+
this.o.owner.quarantine();
|
|
27059
|
+
throw e;
|
|
27060
|
+
}
|
|
27061
|
+
}
|
|
27062
|
+
current() {
|
|
27063
|
+
this.o.owner.lease.assert();
|
|
27064
|
+
if (this.o.owner.state !== "idle" || resolveWorkspace(this.o.cwd).root !== this.cwd)
|
|
27065
|
+
throw new ContractError("quarantine");
|
|
27066
|
+
}
|
|
27067
|
+
model(version, admitted = false) {
|
|
27068
|
+
const state = this.o.choice.snapshot();
|
|
27069
|
+
if (!state.selected || (admitted ? state.version.epoch !== version.epoch || state.version.configRev !== version.configRev || state.version.catalogId !== version.catalogId : canonicalJson(state.version) !== canonicalJson(version)))
|
|
27070
|
+
throw new ContractError("stale");
|
|
27071
|
+
this.o.models.assertCurrent(state.selected);
|
|
27072
|
+
return state.selected;
|
|
27073
|
+
}
|
|
27074
|
+
observation(plan, source = workflowObservation(this.cwd, plan)) {
|
|
27075
|
+
return hash2(canonicalJson({
|
|
27076
|
+
source,
|
|
27077
|
+
working: plan.delivery === "working-copy" ? captureChanges(this.cwd).fingerprint : null
|
|
27078
|
+
}));
|
|
27079
|
+
}
|
|
27080
|
+
proposal(id) {
|
|
27081
|
+
const file = this.files.read(join26(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
|
|
27082
|
+
if (!file)
|
|
27083
|
+
throw new ContractError("unavailable");
|
|
27084
|
+
return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
|
|
27085
|
+
}
|
|
27086
|
+
assertProposal(p, digest, admitted = false) {
|
|
27087
|
+
this.current();
|
|
27088
|
+
this.model(p.model, admitted);
|
|
27089
|
+
if (p.epoch !== this.o.owner.lease.registration.epoch || p.digest !== digest || p.cwd !== this.cwd || this.observation(p.plan) !== p.observation)
|
|
27090
|
+
throw new ContractError("stale");
|
|
27091
|
+
}
|
|
27092
|
+
activeRuns() {
|
|
27093
|
+
this.o.owner.lease.assert();
|
|
27094
|
+
return {
|
|
27095
|
+
kind: "workflow-active",
|
|
27096
|
+
runs: [...this.active.values()].map(({ run }) => ({
|
|
27097
|
+
...structuredClone(run),
|
|
27098
|
+
goal: run.goal.slice(0, 320),
|
|
27099
|
+
steps: []
|
|
27100
|
+
}))
|
|
27101
|
+
};
|
|
27102
|
+
}
|
|
27103
|
+
async join(id) {
|
|
27104
|
+
await this.active.get(id)?.original;
|
|
27105
|
+
}
|
|
27106
|
+
view(id) {
|
|
27107
|
+
this.o.owner.lease.assert();
|
|
27108
|
+
const live = this.active.get(id);
|
|
27109
|
+
const file = live ? undefined : this.files.read(this.path(id, "state.json"), RECORD_BYTES2);
|
|
27110
|
+
if (!live && !file)
|
|
27111
|
+
throw new ContractError("unavailable");
|
|
27112
|
+
const run = decodeWorkflowRun(live ? live.run : parseWireJson(file ? file.bytes.toString("utf8") : "null", RECORD_BYTES2));
|
|
27113
|
+
if (!live && ["running", "queued"].includes(run.status))
|
|
27114
|
+
run.status = "unknown";
|
|
27115
|
+
return {
|
|
27116
|
+
kind: "workflow",
|
|
27117
|
+
commandId: null,
|
|
27118
|
+
response: { type: "run", run }
|
|
27119
|
+
};
|
|
27120
|
+
}
|
|
27121
|
+
transcript(id, stepId) {
|
|
27122
|
+
const view = this.view(id);
|
|
27123
|
+
if (view.kind !== "workflow" || view.response.type !== "run")
|
|
27124
|
+
throw new ContractError("unavailable");
|
|
27125
|
+
const run = view.response.run, step = run.steps.find((s) => s.id === stepId);
|
|
27126
|
+
if (!step?.childRunId)
|
|
27127
|
+
throw new ContractError("unavailable");
|
|
27128
|
+
const file = this.files.read(this.path(id, `transcripts/${step.childRunId}.json`), RECORD_BYTES2);
|
|
27129
|
+
const turn = file ? decodeChatTurn(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2)) : null;
|
|
27130
|
+
if (turn && (turn.id !== step.childRunId || turn.epoch !== run.epoch))
|
|
27131
|
+
throw new ContractError("corrupt-selected");
|
|
27132
|
+
if (turn && turn.status === "running" && step.status !== "running") {
|
|
27133
|
+
turn.status = "unknown";
|
|
27134
|
+
turn.notice = "Retained transcript is incomplete; original activity is not inferred.";
|
|
27135
|
+
}
|
|
27136
|
+
return { kind: "workflow-transcript", runId: id, stepId, turn };
|
|
27137
|
+
}
|
|
27138
|
+
detail(id, stepId) {
|
|
27139
|
+
const view = this.view(id);
|
|
27140
|
+
if (view.kind !== "workflow" || view.response.type !== "run" || !view.response.run.steps.some((s) => s.id === stepId))
|
|
27141
|
+
throw new ContractError("invalid");
|
|
27142
|
+
const file = this.files.read(this.path(id, `results/${hash2(stepId)}.json`), RECORD_BYTES2);
|
|
27143
|
+
if (!file)
|
|
27144
|
+
throw new ContractError("unavailable");
|
|
27145
|
+
return {
|
|
27146
|
+
kind: "file",
|
|
27147
|
+
path: `workflow/${id}/${stepId}`,
|
|
27148
|
+
text: sanitizeData(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2), this.o.secrets()),
|
|
27149
|
+
limited: false
|
|
27150
|
+
};
|
|
27151
|
+
}
|
|
27152
|
+
command(commandId, epoch, r) {
|
|
27153
|
+
this.current();
|
|
27154
|
+
if (epoch !== this.o.owner.lease.registration.epoch)
|
|
27155
|
+
throw new ContractError("stale");
|
|
27156
|
+
if (r.action === "cancel") {
|
|
27157
|
+
const live2 = this.active.get(r.runId);
|
|
27158
|
+
if (live2)
|
|
27159
|
+
live2.abort.abort();
|
|
27160
|
+
const view = this.view(r.runId);
|
|
27161
|
+
return { ...view, commandId };
|
|
27162
|
+
}
|
|
27163
|
+
const encoded2 = canonicalJson(r, RECORD_BYTES2);
|
|
27164
|
+
if (sanitizeText(encoded2, this.o.secrets()) !== encoded2)
|
|
27165
|
+
throw new ContractError("forbidden");
|
|
27166
|
+
if (r.action === "propose") {
|
|
27167
|
+
this.model(r.model);
|
|
27168
|
+
this.capacity();
|
|
27169
|
+
const plan = decodeWorkflowPlan(r.plan);
|
|
27170
|
+
if (sanitizeText(canonicalJson(plan), this.o.secrets()) !== canonicalJson(plan))
|
|
27171
|
+
throw new ContractError("forbidden");
|
|
27172
|
+
const source = workflowObservation(this.cwd, plan);
|
|
27173
|
+
const selected2 = this.model(r.model);
|
|
27174
|
+
const p = {
|
|
27175
|
+
id: commandId,
|
|
27176
|
+
epoch,
|
|
27177
|
+
model: r.model,
|
|
27178
|
+
plan,
|
|
27179
|
+
cwd: this.cwd,
|
|
27180
|
+
observation: this.observation(plan, source),
|
|
27181
|
+
display: {
|
|
27182
|
+
model: `${selected2.provider}/${selected2.model} · ${selected2.thinking}`,
|
|
27183
|
+
branch: source.branch,
|
|
27184
|
+
baseCommit: source.head
|
|
27185
|
+
},
|
|
27186
|
+
digest: hash2(canonicalJson(plan))
|
|
27187
|
+
};
|
|
27188
|
+
if (sanitizeText(canonicalJson(p), this.o.secrets()) !== canonicalJson(p))
|
|
27189
|
+
throw new ContractError("forbidden");
|
|
27190
|
+
const target2 = join26(this.root, "proposals", `${commandId}.json`);
|
|
27191
|
+
const previous = this.files.read(target2, RECORD_BYTES2);
|
|
27192
|
+
if (previous) {
|
|
27193
|
+
if (previous.bytes.toString("utf8") !== canonicalJson(p))
|
|
27194
|
+
throw new ContractError("conflict");
|
|
27195
|
+
} else
|
|
27196
|
+
this.write(target2, p);
|
|
27197
|
+
return {
|
|
27198
|
+
kind: "workflow",
|
|
27199
|
+
commandId,
|
|
27200
|
+
response: { type: "proposal", proposal: p }
|
|
27201
|
+
};
|
|
27202
|
+
}
|
|
27203
|
+
if (r.action === "prepare") {
|
|
27204
|
+
const p = this.proposal(r.proposalId);
|
|
27205
|
+
this.assertProposal(p, r.digest);
|
|
27206
|
+
for (const [key2, v] of this.grants)
|
|
27207
|
+
if (v.expiresAt < Date.now())
|
|
27208
|
+
this.grants.delete(key2);
|
|
27209
|
+
if (this.grants.size >= 16)
|
|
27210
|
+
throw new ContractError("capacity");
|
|
27211
|
+
const grant = randomUUID21(), expiresAt = Date.now() + 120000;
|
|
27212
|
+
this.grants.set(grant, { proposalId: p.id, digest: p.digest, expiresAt });
|
|
27213
|
+
return {
|
|
27214
|
+
kind: "workflow",
|
|
27215
|
+
commandId,
|
|
27216
|
+
response: { type: "grant", proposal: p, grant, expiresAt }
|
|
27217
|
+
};
|
|
27218
|
+
}
|
|
27219
|
+
const acceptedPath = this.path(commandId, "accepted.json");
|
|
27220
|
+
const prior = this.files.read(acceptedPath, RECORD_BYTES2);
|
|
27221
|
+
if (prior) {
|
|
27222
|
+
if (prior.bytes.toString("utf8") !== canonicalJson({ epoch, request: r }))
|
|
27223
|
+
throw new ContractError("conflict");
|
|
27224
|
+
return { ...this.view(commandId), commandId };
|
|
27225
|
+
}
|
|
27226
|
+
if (this.files.directory(dirname17(acceptedPath)))
|
|
27227
|
+
throw new ContractError("quarantine");
|
|
27228
|
+
let proposal;
|
|
27229
|
+
if (r.action === "execute") {
|
|
27230
|
+
proposal = this.proposal(r.proposalId);
|
|
27231
|
+
this.assertProposal(proposal, r.digest);
|
|
27232
|
+
const grant = this.grants.get(r.grant);
|
|
27233
|
+
this.grants.delete(r.grant);
|
|
27234
|
+
if (!grant || grant.expiresAt < Date.now() || grant.proposalId !== proposal.id || grant.digest !== proposal.digest)
|
|
27235
|
+
throw new ContractError("expired-grant");
|
|
27236
|
+
} else
|
|
27237
|
+
this.model(r.model);
|
|
27238
|
+
this.capacity();
|
|
27239
|
+
if (this.active.size >= 4)
|
|
27240
|
+
throw new ContractError("capacity");
|
|
27241
|
+
const run = {
|
|
27242
|
+
id: commandId,
|
|
27243
|
+
epoch,
|
|
27244
|
+
goal: proposal?.plan.goal ?? (r.action === "research" ? r.goal : ""),
|
|
27245
|
+
status: "queued",
|
|
27246
|
+
phase: r.action === "research" ? "research" : "implementing",
|
|
27247
|
+
steps: [],
|
|
27248
|
+
notice: "",
|
|
27249
|
+
mergedCommit: null,
|
|
27250
|
+
humanReviewed: false
|
|
27251
|
+
};
|
|
27252
|
+
const abort = new AbortController;
|
|
27253
|
+
let begin;
|
|
27254
|
+
const ready2 = new Promise((resolve9) => {
|
|
27255
|
+
begin = resolve9;
|
|
27256
|
+
});
|
|
27257
|
+
const live = {
|
|
27258
|
+
run,
|
|
27259
|
+
abort,
|
|
27260
|
+
original: ready2.then(() => this.execute(live, r, proposal)),
|
|
27261
|
+
plan: proposal?.plan
|
|
27262
|
+
};
|
|
27263
|
+
this.active.set(commandId, live);
|
|
27264
|
+
this.o.owner.trackConversation(live.original, () => abort.abort());
|
|
27265
|
+
try {
|
|
27266
|
+
this.write(acceptedPath, { epoch, request: r });
|
|
27267
|
+
live.file = this.write(this.path(commandId, "state.json"), run);
|
|
27268
|
+
} catch (e) {
|
|
27269
|
+
abort.abort();
|
|
27270
|
+
begin();
|
|
27271
|
+
throw e;
|
|
27272
|
+
}
|
|
27273
|
+
begin();
|
|
27274
|
+
return {
|
|
27275
|
+
kind: "workflow",
|
|
27276
|
+
commandId,
|
|
27277
|
+
response: { type: "run", run: structuredClone(run) }
|
|
27278
|
+
};
|
|
27279
|
+
}
|
|
27280
|
+
capacity() {
|
|
27281
|
+
let bytes = 0, count2 = 0;
|
|
27282
|
+
const visit = (path, depth) => {
|
|
27283
|
+
if (depth > 5 || !this.files.directory(path))
|
|
27284
|
+
return;
|
|
27285
|
+
const dir = opendirSync9(path);
|
|
27286
|
+
try {
|
|
27287
|
+
for (let e = dir.readSync();e; e = dir.readSync()) {
|
|
27288
|
+
if (++count2 > 1e4)
|
|
27289
|
+
throw new ContractError("capacity");
|
|
27290
|
+
const p = join26(path, e.name);
|
|
27291
|
+
if (e.isDirectory())
|
|
27292
|
+
visit(p, depth + 1);
|
|
27293
|
+
else if (e.isFile())
|
|
27294
|
+
bytes += lstatSync15(p).size;
|
|
27295
|
+
else
|
|
27296
|
+
throw new ContractError("forbidden");
|
|
27297
|
+
if (bytes > 512 * 1024 * 1024)
|
|
27298
|
+
throw new ContractError("capacity");
|
|
27299
|
+
}
|
|
27300
|
+
} finally {
|
|
27301
|
+
dir.closeSync();
|
|
27302
|
+
}
|
|
27303
|
+
};
|
|
27304
|
+
visit(join26(this.root, "runs"), 0);
|
|
27305
|
+
visit(join26(this.root, "proposals"), 0);
|
|
27306
|
+
const runDirectory = join26(this.root, "runs");
|
|
27307
|
+
if (this.files.directory(runDirectory)) {
|
|
27308
|
+
const dir = opendirSync9(runDirectory);
|
|
27309
|
+
try {
|
|
27310
|
+
let runs = 0;
|
|
27311
|
+
while (dir.readSync())
|
|
27312
|
+
if (++runs >= WORKFLOW_LIMITS.runs)
|
|
27313
|
+
throw new ContractError("capacity");
|
|
27314
|
+
} finally {
|
|
27315
|
+
dir.closeSync();
|
|
27316
|
+
}
|
|
27317
|
+
}
|
|
27318
|
+
const space = statfsSync3(this.o.coordination.directory);
|
|
27319
|
+
if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
|
|
27320
|
+
throw new ContractError("capacity");
|
|
27321
|
+
}
|
|
27322
|
+
save(live) {
|
|
27323
|
+
if (!live.file)
|
|
27324
|
+
throw new ContractError("corrupt-selected");
|
|
27325
|
+
live.file = this.write(this.path(live.run.id, "state.json"), live.run, live.file);
|
|
27326
|
+
}
|
|
27327
|
+
assertRunning(live) {
|
|
27328
|
+
this.current();
|
|
27329
|
+
const space = statfsSync3(this.o.coordination.directory);
|
|
27330
|
+
if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
|
|
27331
|
+
throw new ContractError("capacity");
|
|
27332
|
+
if (live.abort.signal.aborted)
|
|
27333
|
+
throw new ContractError("stale");
|
|
27334
|
+
}
|
|
27335
|
+
step(live, id, kind, childRunId) {
|
|
27336
|
+
if (live.run.steps.length >= 256)
|
|
27337
|
+
throw new ContractError("capacity");
|
|
27338
|
+
const s = {
|
|
27339
|
+
id: `${id.slice(0, 80)}-${randomUUID21()}`,
|
|
27340
|
+
...childRunId ? { childRunId } : {},
|
|
27341
|
+
kind,
|
|
27342
|
+
status: "running",
|
|
27343
|
+
text: "",
|
|
27344
|
+
exitCode: null,
|
|
27345
|
+
truncated: false
|
|
27346
|
+
};
|
|
27347
|
+
live.run.steps.push(s);
|
|
27348
|
+
this.save(live);
|
|
27349
|
+
return s;
|
|
27350
|
+
}
|
|
27351
|
+
sanitizeResult(result) {
|
|
27352
|
+
const secrets = this.o.secrets();
|
|
27353
|
+
return {
|
|
27354
|
+
...result,
|
|
27355
|
+
text: sanitizeText(result.text, secrets),
|
|
27356
|
+
output: sanitizeText(result.output, secrets)
|
|
27357
|
+
};
|
|
27358
|
+
}
|
|
27359
|
+
finishStep(live, s, original) {
|
|
27360
|
+
const result = this.sanitizeResult(original);
|
|
27361
|
+
this.write(this.path(live.run.id, `results/${hash2(s.id)}.json`), {
|
|
27362
|
+
stepId: s.id,
|
|
27363
|
+
result
|
|
27364
|
+
});
|
|
27365
|
+
s.status = result.outcome;
|
|
27366
|
+
s.text = diagnosticText(result.text || result.output, s.kind === "research" ? 16384 : 1024, this.o.secrets());
|
|
27367
|
+
s.exitCode = result.exitCode;
|
|
27368
|
+
s.truncated = result.truncated || Buffer.byteLength(result.text || result.output) > Buffer.byteLength(s.text);
|
|
27369
|
+
if (!result.closed)
|
|
27370
|
+
this.o.owner.quarantine();
|
|
27371
|
+
this.save(live);
|
|
27372
|
+
}
|
|
27373
|
+
async worker(live, cwd, id, prompt, readonly, version) {
|
|
27374
|
+
this.assertRunning(live);
|
|
27375
|
+
const model = this.model(version, true);
|
|
27376
|
+
const role2 = loadAgentDefinitions().find((r) => r.role === (readonly ? "design-explorer" : "implementation-worker"));
|
|
27377
|
+
if (!role2)
|
|
27378
|
+
throw new ContractError("unavailable");
|
|
27379
|
+
const childRunId = randomUUID21(), op = randomUUID21();
|
|
27380
|
+
const request3 = decodeWorkerPublicRequest({
|
|
27381
|
+
protocol: 2,
|
|
27382
|
+
taskId: live.run.id,
|
|
27383
|
+
taskKind: readonly ? "research" : "code",
|
|
27384
|
+
runId: live.run.id,
|
|
27385
|
+
childRunId,
|
|
27386
|
+
assignmentId: id,
|
|
27387
|
+
purpose: readonly ? "research" : "edit",
|
|
27388
|
+
model,
|
|
27389
|
+
role: { role: role2.role, sha256: role2.sha256 },
|
|
27390
|
+
context: live.plan ? workflowContext(live.plan) : "Read applicable AGENTS.md and existing project documentation, including .cadence/project.md. Cite evidence and separate observations from assumptions.",
|
|
27391
|
+
instructions: `${role2.content}
|
|
27392
|
+
Read applicable AGENTS.md, existing project conventions and relevant tests before work. Do not delegate, retry, mutate Git, install dependencies, publish or deploy. Report actual work and uncertainty. Do not weaken tests to manufacture success. Worker completion is not verification.`,
|
|
27393
|
+
prompt: text(prompt, 32768, true),
|
|
27394
|
+
handoff: { graphRevision: 1, inputs: [] }
|
|
27395
|
+
});
|
|
27396
|
+
const step = this.step(live, id, readonly ? live.run.phase === "research" ? "research" : "review" : "implementation", childRunId);
|
|
27397
|
+
const current2 = () => {
|
|
27398
|
+
try {
|
|
27399
|
+
this.assertRunning(live);
|
|
27400
|
+
if (cwd !== this.cwd)
|
|
27401
|
+
assertWorktree(this.cwd, cwd);
|
|
27402
|
+
return true;
|
|
27403
|
+
} catch {
|
|
27404
|
+
return false;
|
|
27405
|
+
}
|
|
27406
|
+
};
|
|
27407
|
+
let native;
|
|
27408
|
+
let selectedMessageId;
|
|
27409
|
+
const auth = this.o.models.prepareTracked({
|
|
27410
|
+
request: request3,
|
|
27411
|
+
operationId: op,
|
|
27412
|
+
epoch: live.run.epoch,
|
|
27413
|
+
timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
|
|
27414
|
+
signal: live.abort.signal,
|
|
27415
|
+
current: current2,
|
|
27416
|
+
journal: {
|
|
27417
|
+
preparation: (v) => {
|
|
27418
|
+
this.write(this.path(live.run.id, `auth/${op}-intent.json`), v);
|
|
27419
|
+
},
|
|
27420
|
+
settlement: (v) => {
|
|
27421
|
+
this.write(this.path(live.run.id, `auth/${op}-settled.json`), v);
|
|
27422
|
+
}
|
|
27423
|
+
}
|
|
27424
|
+
});
|
|
27425
|
+
try {
|
|
27426
|
+
const result = await auth.result;
|
|
27427
|
+
if (result.status !== "prepared" || !current2())
|
|
27428
|
+
throw new ContractError("auth-unavailable");
|
|
27429
|
+
this.write(this.path(live.run.id, `launches/${childRunId}.json`), {
|
|
27430
|
+
cwd,
|
|
27431
|
+
request: request3
|
|
27432
|
+
});
|
|
27433
|
+
const transcript = {
|
|
27434
|
+
id: childRunId,
|
|
27435
|
+
epoch: live.run.epoch,
|
|
27436
|
+
status: "running",
|
|
27437
|
+
items: [],
|
|
27438
|
+
notice: "",
|
|
27439
|
+
omitted: { thinking: false, media: false, other: false }
|
|
27440
|
+
};
|
|
27441
|
+
let transcriptFile;
|
|
27442
|
+
let credentials = [];
|
|
27443
|
+
const saveTranscript = () => {
|
|
27444
|
+
transcriptFile = this.write(this.path(live.run.id, `transcripts/${childRunId}.json`), transcript, transcriptFile);
|
|
27445
|
+
};
|
|
27446
|
+
const capture = new ConversationCapture(transcript, saveTranscript, () => [...this.o.secrets(), ...credentials]);
|
|
27447
|
+
const running = Promise.resolve().then(() => launchWorkflowWorker(result.prepared, cwd, live.abort.signal, {
|
|
27448
|
+
timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
|
|
27449
|
+
ownerSecrets: this.o.secrets(),
|
|
27450
|
+
maySignal: () => {
|
|
27451
|
+
try {
|
|
27452
|
+
this.o.owner.lease.assert();
|
|
27453
|
+
return true;
|
|
27454
|
+
} catch {
|
|
27455
|
+
return false;
|
|
27456
|
+
}
|
|
27457
|
+
},
|
|
27458
|
+
onNative: (v, messageId) => {
|
|
27459
|
+
native = v;
|
|
27460
|
+
selectedMessageId = messageId;
|
|
27461
|
+
},
|
|
27462
|
+
onFrame: (frame, secrets) => {
|
|
27463
|
+
credentials = secrets;
|
|
27464
|
+
capture.accept(frame);
|
|
27465
|
+
}
|
|
27466
|
+
}));
|
|
27467
|
+
this.o.owner.trackConversationProcess(running.then(() => {
|
|
27468
|
+
if (!native)
|
|
27469
|
+
throw new ContractError("quarantine");
|
|
27470
|
+
return native;
|
|
27471
|
+
}), () => live.abort.abort());
|
|
27472
|
+
const completed = this.sanitizeResult(await running);
|
|
27473
|
+
if (completed.outcome === "completed") {
|
|
27474
|
+
const selected2 = transcript.items.find((item) => item.id === selectedMessageId && item.role === "assistant");
|
|
27475
|
+
if (!selected2)
|
|
27476
|
+
throw new ContractError("corrupt-selected");
|
|
27477
|
+
const text2 = sanitizeText(selected2.text, [
|
|
27478
|
+
...this.o.secrets(),
|
|
27479
|
+
...credentials
|
|
27480
|
+
]);
|
|
27481
|
+
completed.text = diagnosticText(text2, 16384);
|
|
27482
|
+
completed.truncated ||= Buffer.byteLength(text2) > 16384;
|
|
27483
|
+
}
|
|
27484
|
+
transcript.status = completed.outcome;
|
|
27485
|
+
saveTranscript();
|
|
27486
|
+
this.finishStep(live, step, completed);
|
|
27487
|
+
return completed;
|
|
27488
|
+
} finally {
|
|
27489
|
+
await auth.settled;
|
|
27490
|
+
if (step.status === "running") {
|
|
27491
|
+
step.status = this.o.owner.state === "quarantined" ? "unknown" : live.abort.signal.aborted ? "canceled" : "failed";
|
|
27492
|
+
step.text = "Worker did not produce a completed native/recorded result.";
|
|
27493
|
+
this.save(live);
|
|
27494
|
+
}
|
|
27495
|
+
}
|
|
27496
|
+
}
|
|
27497
|
+
async process(live, cwd, args, title) {
|
|
27498
|
+
this.assertRunning(live);
|
|
27499
|
+
if (cwd !== this.cwd && !Array.isArray(args))
|
|
27500
|
+
assertWorktree(this.cwd, cwd);
|
|
27501
|
+
const id = randomUUID21();
|
|
27502
|
+
this.write(this.path(live.run.id, `operations/${id}-intent.json`), {
|
|
27503
|
+
cwd,
|
|
27504
|
+
args
|
|
27505
|
+
});
|
|
27506
|
+
let native;
|
|
27507
|
+
const shell = !Array.isArray(args);
|
|
27508
|
+
const step = shell ? this.step(live, title, "check") : undefined;
|
|
27509
|
+
const environment2 = {
|
|
27510
|
+
...this.o.checkEnvironment ?? {},
|
|
27511
|
+
CADENCE_SUBAGENT_CHILD: "1"
|
|
27512
|
+
};
|
|
27513
|
+
const running = Promise.resolve().then(() => runProcess({
|
|
27514
|
+
command: shell ? process.platform === "win32" ? environment2.COMSPEC ?? "cmd.exe" : "/bin/sh" : "git",
|
|
27515
|
+
args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${args.command}"`] : ["-c", args.command] : gitArguments([
|
|
27516
|
+
"-c",
|
|
27517
|
+
`core.hooksPath=${join26(this.root, "empty-hooks")}`,
|
|
27518
|
+
"-c",
|
|
27519
|
+
"commit.gpgsign=false",
|
|
27520
|
+
"-c",
|
|
27521
|
+
"gc.auto=0",
|
|
27522
|
+
"-c",
|
|
27523
|
+
"maintenance.auto=false",
|
|
27524
|
+
...args
|
|
27525
|
+
]),
|
|
27526
|
+
windowsVerbatimArguments: shell && process.platform === "win32" ? true : undefined,
|
|
27527
|
+
cwd,
|
|
27528
|
+
env: shell ? environment2 : gitEnvironment(),
|
|
27529
|
+
signal: live.abort.signal,
|
|
27530
|
+
timeoutMs: shell ? args.timeoutMs : 30000,
|
|
27531
|
+
secrets: [...this.o.secrets()],
|
|
27532
|
+
maySignal: () => {
|
|
27533
|
+
try {
|
|
27534
|
+
this.o.owner.lease.assert();
|
|
27535
|
+
return true;
|
|
27536
|
+
} catch {
|
|
27537
|
+
return false;
|
|
27538
|
+
}
|
|
27539
|
+
},
|
|
27540
|
+
onCheckNative: (v) => {
|
|
27541
|
+
native = v;
|
|
27542
|
+
}
|
|
27543
|
+
}));
|
|
27544
|
+
this.o.owner.trackCheck(running.then(() => {
|
|
27545
|
+
if (!native)
|
|
27546
|
+
throw new ContractError("quarantine");
|
|
27547
|
+
return native;
|
|
27548
|
+
}), () => live.abort.abort());
|
|
27549
|
+
const result = this.sanitizeResult(await running);
|
|
27550
|
+
this.write(this.path(live.run.id, `operations/${id}-settled.json`), {
|
|
27551
|
+
result,
|
|
27552
|
+
native
|
|
27553
|
+
});
|
|
27554
|
+
if (!result.closed)
|
|
27555
|
+
this.o.owner.quarantine();
|
|
27556
|
+
if (step)
|
|
27557
|
+
this.finishStep(live, step, result);
|
|
27558
|
+
return result;
|
|
27559
|
+
}
|
|
27560
|
+
success(result) {
|
|
27561
|
+
if (result.outcome !== "completed" || !result.closed || result.exitCode !== 0)
|
|
27562
|
+
throw new WorkflowFailure(result.outcome, `Operation ${result.outcome}: ${diagnosticText(result.text || result.output, 512, this.o.secrets())}`);
|
|
27563
|
+
}
|
|
27564
|
+
async git(live, cwd, args) {
|
|
27565
|
+
this.success(await this.process(live, cwd, args, "git"));
|
|
27566
|
+
}
|
|
27567
|
+
async setup(live, cwd, plan) {
|
|
27568
|
+
for (const c of plan.setup)
|
|
27569
|
+
this.success(await this.process(live, cwd, c, `setup: ${c.name}`));
|
|
27570
|
+
}
|
|
27571
|
+
async checks(live, cwd, plan, baseline = false) {
|
|
27572
|
+
live.run.phase = "verifying";
|
|
27573
|
+
this.save(live);
|
|
27574
|
+
let passed = true;
|
|
27575
|
+
for (const c of baseline ? plan.baselineChecks : plan.checks) {
|
|
27576
|
+
const r = await this.process(live, cwd, c, c.name);
|
|
27577
|
+
if (!r.closed || r.outcome === "canceled" || r.outcome === "timeout")
|
|
27578
|
+
this.success(r);
|
|
27579
|
+
passed &&= r.outcome === "completed" && r.exitCode === 0;
|
|
27580
|
+
}
|
|
27581
|
+
return passed;
|
|
27582
|
+
}
|
|
27583
|
+
unchangedHead(cwd, before) {
|
|
27584
|
+
if (gitRead(cwd, ["rev-parse", "HEAD"]).trim() !== before)
|
|
27585
|
+
throw new ContractError("stale");
|
|
27586
|
+
}
|
|
27587
|
+
async commit(live, cwd, allowed, message, before) {
|
|
27588
|
+
this.unchangedHead(cwd, before);
|
|
27589
|
+
const changes = assertWorkflowScope(cwd, allowed);
|
|
27590
|
+
if (!changes.length)
|
|
27591
|
+
return null;
|
|
27592
|
+
await this.git(live, cwd, ["add", "--", ...changes]);
|
|
27593
|
+
assertWorkflowScope(cwd, allowed);
|
|
27594
|
+
this.unchangedHead(cwd, before);
|
|
27595
|
+
if (!gitRead(cwd, [
|
|
27596
|
+
"diff",
|
|
27597
|
+
"--cached",
|
|
27598
|
+
"--name-only",
|
|
27599
|
+
"-z",
|
|
27600
|
+
"--no-ext-diff",
|
|
27601
|
+
"--no-textconv",
|
|
27602
|
+
"HEAD",
|
|
27603
|
+
"--"
|
|
27604
|
+
]))
|
|
27605
|
+
return null;
|
|
27606
|
+
await this.git(live, cwd, ["commit", "--no-verify", "-m", message]);
|
|
27607
|
+
const commit = gitRead(cwd, ["rev-parse", "HEAD"]).trim();
|
|
27608
|
+
assertWorkflowCommit(cwd, before, commit, allowed);
|
|
27609
|
+
return commit;
|
|
27610
|
+
}
|
|
27611
|
+
async review(live, cwd, p) {
|
|
27612
|
+
live.run.phase = "reviewing";
|
|
27613
|
+
this.save(live);
|
|
27614
|
+
const r = await this.worker(live, cwd, `review-${randomUUID21()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
|
|
27615
|
+
Files: ${p.plan.tasks.flatMap((t) => t.writes).join(", ")}`, true, p.model);
|
|
27616
|
+
this.success(r);
|
|
27617
|
+
try {
|
|
27618
|
+
const raw = r.text.trim().replace(/^```(?:json)?\s*/u, "").replace(/\s*```$/u, "");
|
|
27619
|
+
const verdict = JSON.parse(raw);
|
|
27620
|
+
return verdict.approved === true && Array.isArray(verdict.blockingIssues) && verdict.blockingIssues.length === 0;
|
|
27621
|
+
} catch {
|
|
27622
|
+
return false;
|
|
27623
|
+
}
|
|
27624
|
+
}
|
|
27625
|
+
async verifyAndRepair(live, cwd, p, git) {
|
|
27626
|
+
const allowed = p.plan.tasks.flatMap((t) => t.writes);
|
|
27627
|
+
for (let attempt = 0;attempt <= p.plan.repairAttempts; attempt++) {
|
|
27628
|
+
const beforeChecks = git ? gitRead(cwd, ["rev-parse", "HEAD"]).trim() : "";
|
|
27629
|
+
const reviewed = await this.review(live, cwd, p);
|
|
27630
|
+
const checked2 = await this.checks(live, cwd, p.plan);
|
|
27631
|
+
if (git) {
|
|
27632
|
+
this.unchangedHead(cwd, beforeChecks);
|
|
27633
|
+
assertWorkflowScope(cwd, allowed);
|
|
27634
|
+
}
|
|
27635
|
+
if (reviewed && checked2)
|
|
27636
|
+
return;
|
|
27637
|
+
if (attempt === p.plan.repairAttempts)
|
|
27638
|
+
throw new Error("Verification/review failed; repair budget exhausted. Artifacts preserved; nothing merged.");
|
|
27639
|
+
const failures = live.run.steps.filter((s) => s.kind === "check" || s.kind === "review").slice(-8);
|
|
27640
|
+
const beforeRepair = git ? gitRead(cwd, ["rev-parse", "HEAD"]).trim() : "";
|
|
27641
|
+
const repair = await this.worker(live, cwd, `repair-${attempt + 1}`, `Repair only within approved paths and acceptance. Do not remove or weaken tests, install dependencies, change scope or Git. If a product decision is missing, stop and report it.
|
|
27642
|
+
Allowed files: ${allowed.join(", ")}
|
|
27643
|
+
Observed failures/review: ${canonicalJson(failures, 65536)}`, false, p.model);
|
|
27644
|
+
this.success(repair);
|
|
27645
|
+
if (git)
|
|
27646
|
+
await this.commit(live, cwd, allowed, `Cadence: bounded repair ${attempt + 1}`, beforeRepair);
|
|
27647
|
+
}
|
|
27648
|
+
}
|
|
27649
|
+
publish(live, cwd, plan) {
|
|
27650
|
+
const base = `.cadence/assistant/workflows/${live.run.id}`;
|
|
27651
|
+
const documents = new Map([
|
|
27652
|
+
[`${base}/plan.md`, readableWorkflowPlan(plan)],
|
|
27653
|
+
[
|
|
27654
|
+
`${base}/result.md`,
|
|
27655
|
+
`# Verified candidate
|
|
27656
|
+
|
|
27657
|
+
${live.run.steps.map((s) => `- ${s.kind} ${s.id}: ${s.status}${s.exitCode === null ? "" : ` (exit ${s.exitCode})`}`).join(`
|
|
27658
|
+
`)}
|
|
27659
|
+
|
|
27660
|
+
Automatic review, not human review. Final integration/native outcomes are retained by the owner.
|
|
27661
|
+
`
|
|
27662
|
+
]
|
|
27663
|
+
]);
|
|
27664
|
+
if (plan.projectContext)
|
|
27665
|
+
documents.set(".cadence/project.md", projectMarkdown(cwd, plan.projectContext));
|
|
27666
|
+
for (const [name, body] of documents) {
|
|
27667
|
+
const file = safeWorkflowFile(cwd, name);
|
|
27668
|
+
if (!safeDirectory(dirname17(file), true))
|
|
27669
|
+
throw new ContractError("forbidden");
|
|
27670
|
+
writeFileSync3(file, body, {
|
|
27671
|
+
flag: name === ".cadence/project.md" ? "w" : "wx"
|
|
27672
|
+
});
|
|
27673
|
+
}
|
|
27674
|
+
return [...documents.keys()];
|
|
27675
|
+
}
|
|
27676
|
+
async implement(live, p) {
|
|
27677
|
+
const plan = p.plan;
|
|
27678
|
+
if (plan.delivery === "working-copy") {
|
|
27679
|
+
await this.setup(live, this.cwd, plan);
|
|
27680
|
+
if (!await this.checks(live, this.cwd, plan, true))
|
|
27681
|
+
throw new Error("Baseline checks failed; no implementation started.");
|
|
27682
|
+
for (const task of workflowOrder(plan.tasks)) {
|
|
27683
|
+
live.run.phase = "implementing";
|
|
27684
|
+
this.save(live);
|
|
27685
|
+
this.success(await this.worker(live, this.cwd, task.id, `${task.instructions}
|
|
27686
|
+
Write only these exact files: ${task.writes.join(", ")}`, false, p.model));
|
|
27687
|
+
}
|
|
27688
|
+
await this.verifyAndRepair(live, this.cwd, p, false);
|
|
27689
|
+
this.publish(live, this.cwd, plan);
|
|
27690
|
+
if (!await this.checks(live, this.cwd, plan))
|
|
27691
|
+
throw new Error("Post-publication checks failed; direct working-copy edits preserved.");
|
|
27692
|
+
return;
|
|
27693
|
+
}
|
|
27694
|
+
const initial4 = workflowObservation(this.cwd, plan);
|
|
27695
|
+
const home = join26(this.root, "worktrees", live.run.id);
|
|
27696
|
+
this.files.directory(home, true);
|
|
27697
|
+
const taskHome = join26(home, "tasks");
|
|
27698
|
+
this.files.directory(taskHome, true);
|
|
27699
|
+
const integration = join26(home, "integration");
|
|
27700
|
+
await this.git(live, this.cwd, [
|
|
27701
|
+
"worktree",
|
|
27702
|
+
"add",
|
|
27703
|
+
"--detach",
|
|
27704
|
+
integration,
|
|
27705
|
+
initial4.head
|
|
27706
|
+
]);
|
|
27707
|
+
assertWorktree(this.cwd, integration);
|
|
27708
|
+
await this.setup(live, integration, plan);
|
|
27709
|
+
assertWorkflowScope(integration, []);
|
|
27710
|
+
if (!await this.checks(live, integration, plan, true))
|
|
27711
|
+
throw new Error("Candidate baseline checks failed. Configure worktree prerequisites in the plan; no implicit dependency installation or copying.");
|
|
27712
|
+
this.unchangedHead(integration, initial4.head);
|
|
27713
|
+
const commits = new Map, pending = new Set(plan.tasks.map((t) => t.id));
|
|
27714
|
+
while (pending.size) {
|
|
27715
|
+
this.assertRunning(live);
|
|
27716
|
+
const batch = workflowOrder(plan.tasks).filter((t) => pending.has(t.id) && t.after.every((d) => commits.has(d))).slice(0, WORKFLOW_LIMITS.parallel);
|
|
27717
|
+
if (!batch.length)
|
|
27718
|
+
throw new ContractError("invalid");
|
|
27719
|
+
live.run.phase = "implementing";
|
|
27720
|
+
this.save(live);
|
|
27721
|
+
const outcomes2 = await Promise.allSettled(batch.map(async (task) => {
|
|
27722
|
+
const cwd = join26(taskHome, task.id);
|
|
27723
|
+
await this.git(live, this.cwd, [
|
|
27724
|
+
"worktree",
|
|
27725
|
+
"add",
|
|
27726
|
+
"--detach",
|
|
27727
|
+
cwd,
|
|
27728
|
+
initial4.head
|
|
27729
|
+
]);
|
|
27730
|
+
for (const dep of workflowAncestors(plan.tasks, task.id)) {
|
|
27731
|
+
const commit2 = commits.get(dep.id);
|
|
27732
|
+
if (commit2)
|
|
27733
|
+
await this.git(live, cwd, ["cherry-pick", "--no-edit", commit2]);
|
|
27734
|
+
}
|
|
27735
|
+
const beforeWorker = gitRead(cwd, ["rev-parse", "HEAD"]).trim();
|
|
27736
|
+
await this.setup(live, cwd, plan);
|
|
27737
|
+
this.unchangedHead(cwd, beforeWorker);
|
|
27738
|
+
assertWorkflowScope(cwd, []);
|
|
27739
|
+
this.success(await this.worker(live, cwd, task.id, `${task.instructions}
|
|
27740
|
+
Write only these exact files: ${task.writes.join(", ")}. Dependencies are already applied to this worktree.`, false, p.model));
|
|
27741
|
+
const commit = await this.commit(live, cwd, task.writes, `Cadence: ${task.title}`, beforeWorker);
|
|
27742
|
+
commits.set(task.id, commit);
|
|
27743
|
+
pending.delete(task.id);
|
|
27744
|
+
}));
|
|
27745
|
+
const failed = outcomes2.find((r) => r.status === "rejected");
|
|
27746
|
+
if (failed?.status === "rejected")
|
|
27747
|
+
throw failed.reason;
|
|
27748
|
+
}
|
|
27749
|
+
for (const task of workflowOrder(plan.tasks)) {
|
|
27750
|
+
const commit = commits.get(task.id);
|
|
27751
|
+
if (commit)
|
|
27752
|
+
await this.git(live, integration, ["cherry-pick", "--no-edit", commit]);
|
|
27753
|
+
}
|
|
27754
|
+
await this.verifyAndRepair(live, integration, p, true);
|
|
27755
|
+
const documentNames = [
|
|
27756
|
+
`.cadence/assistant/workflows/${live.run.id}/plan.md`,
|
|
27757
|
+
`.cadence/assistant/workflows/${live.run.id}/result.md`,
|
|
27758
|
+
...plan.projectContext ? [".cadence/project.md"] : []
|
|
27759
|
+
];
|
|
27760
|
+
const documentBefore = new Map(documentNames.map((p2) => [
|
|
27761
|
+
p2,
|
|
27762
|
+
readBounded(safeWorkflowFile(this.cwd, p2), 128 * 1024)
|
|
27763
|
+
]));
|
|
27764
|
+
const beforePublication = gitRead(integration, [
|
|
27765
|
+
"rev-parse",
|
|
27766
|
+
"HEAD"
|
|
27767
|
+
]).trim();
|
|
27768
|
+
const documents = this.publish(live, integration, plan);
|
|
27769
|
+
await this.commit(live, integration, documents, "Cadence: project context and delivery notes", beforePublication);
|
|
27770
|
+
const head = gitRead(integration, ["rev-parse", "HEAD"]).trim();
|
|
27771
|
+
if (!await this.checks(live, integration, plan))
|
|
27772
|
+
throw new Error("Final candidate checks failed; nothing merged.");
|
|
27773
|
+
this.unchangedHead(integration, head);
|
|
27774
|
+
assertWorkflowScope(integration, []);
|
|
27775
|
+
this.assertProposal(p, p.digest, true);
|
|
27776
|
+
live.run.phase = "integrating";
|
|
27777
|
+
this.save(live);
|
|
27778
|
+
await this.git(live, this.cwd, ["merge", "--ff-only", "--no-edit", head]);
|
|
27779
|
+
live.run.mergedCommit = head;
|
|
27780
|
+
this.save(live);
|
|
27781
|
+
for (const name of documents) {
|
|
27782
|
+
if (gitRead(this.cwd, ["ls-files", "--", name]).trim())
|
|
27783
|
+
continue;
|
|
27784
|
+
const file = safeWorkflowFile(this.cwd, name), before = documentBefore.get(name), now = readBounded(file, 128 * 1024);
|
|
27785
|
+
if ((before ? hash2(before) : null) !== (now ? hash2(now) : null))
|
|
27786
|
+
throw new ContractError("conflict");
|
|
27787
|
+
const content = name === ".cadence/project.md" ? projectMarkdown(this.cwd, plan.projectContext) : readBounded(safeWorkflowFile(integration, name), 128 * 1024);
|
|
27788
|
+
if (content === undefined || !safeDirectory(dirname17(file), true))
|
|
27789
|
+
throw new ContractError("unavailable");
|
|
27790
|
+
writeFileSync3(file, content, { flag: before ? "w" : "wx" });
|
|
27791
|
+
}
|
|
27792
|
+
if (!await this.checks(live, this.cwd, plan))
|
|
27793
|
+
throw new Error("Local merge completed, but post-merge checks failed. No reset or rollback was attempted.");
|
|
27794
|
+
this.unchangedHead(this.cwd, head);
|
|
27795
|
+
}
|
|
27796
|
+
async execute(live, request3, proposal) {
|
|
27797
|
+
let barrier;
|
|
27798
|
+
let budgetExpired = false;
|
|
27799
|
+
const timer = setTimeout(() => {
|
|
27800
|
+
budgetExpired = true;
|
|
27801
|
+
live.abort.abort();
|
|
27802
|
+
}, WORKFLOW_LIMITS.durationMs);
|
|
27803
|
+
try {
|
|
27804
|
+
this.assertRunning(live);
|
|
27805
|
+
barrier = await this.o.actions.scheduler.conversationBarrier(live.run.id, live.abort.signal);
|
|
27806
|
+
barrier.assertHeld();
|
|
27807
|
+
this.o.actions.conversationBoundary(barrier);
|
|
27808
|
+
if (proposal)
|
|
27809
|
+
this.assertProposal(proposal, proposal.digest, true);
|
|
27810
|
+
live.run.status = "running";
|
|
27811
|
+
this.save(live);
|
|
27812
|
+
if (request3.action === "research") {
|
|
27813
|
+
const answers = await Promise.allSettled(request3.questions.map((q, i) => this.worker(live, this.cwd, `research-${i + 1}`, `Goal: ${request3.goal}
|
|
27814
|
+
Investigation: ${q}
|
|
27815
|
+
Read only. Cite paths and distinguish evidence, assumptions, user decisions and environment prerequisites.`, true, request3.model)));
|
|
27816
|
+
for (const a of answers) {
|
|
27817
|
+
if (a.status === "rejected")
|
|
27818
|
+
throw a.reason;
|
|
27819
|
+
this.success(a.value);
|
|
27820
|
+
}
|
|
27821
|
+
} else if (proposal)
|
|
27822
|
+
await this.implement(live, proposal);
|
|
27823
|
+
else
|
|
27824
|
+
throw new ContractError("invalid");
|
|
27825
|
+
live.run.status = "completed";
|
|
27826
|
+
} catch (error2) {
|
|
27827
|
+
live.run.status = this.o.owner.state === "quarantined" ? "unknown" : budgetExpired ? "timeout" : live.abort.signal.aborted ? "canceled" : error2 instanceof WorkflowFailure && error2.outcome !== "completed" ? error2.outcome : "failed";
|
|
27828
|
+
live.run.notice = diagnosticText(error2 instanceof ContractError ? error2.code : error2 instanceof Error ? error2.message : "Workflow failed", 2048, this.o.secrets());
|
|
27829
|
+
} finally {
|
|
27830
|
+
clearTimeout(timer);
|
|
27831
|
+
live.run.phase = "finished";
|
|
27832
|
+
try {
|
|
27833
|
+
if (barrier && this.o.owner.state === "idle")
|
|
27834
|
+
this.o.actions.conversationBoundary(barrier);
|
|
27835
|
+
this.save(live);
|
|
27836
|
+
} catch {
|
|
27837
|
+
this.o.owner.quarantine();
|
|
27838
|
+
}
|
|
27839
|
+
if (this.o.owner.state === "idle")
|
|
27840
|
+
barrier?.release();
|
|
27841
|
+
this.active.delete(live.run.id);
|
|
27842
|
+
}
|
|
27843
|
+
return {
|
|
27844
|
+
status: this.o.owner.state === "quarantined" ? "uncertain" : "settled"
|
|
27845
|
+
};
|
|
27846
|
+
}
|
|
27847
|
+
}
|
|
27848
|
+
|
|
25765
27849
|
// src/service/workbench.ts
|
|
25766
27850
|
class Workbench {
|
|
25767
27851
|
o;
|
|
25768
27852
|
conversations;
|
|
25769
27853
|
files;
|
|
27854
|
+
workflows;
|
|
27855
|
+
cadence;
|
|
25770
27856
|
projectRoot;
|
|
25771
27857
|
opening = new Map;
|
|
25772
27858
|
constructor(o) {
|
|
25773
27859
|
this.o = o;
|
|
25774
27860
|
this.conversations = new Conversations(o);
|
|
27861
|
+
this.workflows = new Workflows(o);
|
|
27862
|
+
this.cadence = new ConversationWorkflow({
|
|
27863
|
+
...o,
|
|
27864
|
+
conversations: this.conversations,
|
|
27865
|
+
workflows: this.workflows
|
|
27866
|
+
});
|
|
27867
|
+
this.cadence.assertRecords();
|
|
27868
|
+
for (const entry of this.conversations.list().entries)
|
|
27869
|
+
this.cadence.state(entry.id);
|
|
25775
27870
|
if (this.conversations.list().entries.some((entry) => entry.status === "unknown"))
|
|
25776
27871
|
throw new ContractError("quarantine");
|
|
25777
27872
|
this.files = new WorkbenchFiles(o.cwd, [o.coordination.files.namespace, o.agentDir], o.secrets);
|
|
25778
|
-
this.projectRoot =
|
|
27873
|
+
this.projectRoot = join27(o.coordination.files.namespace, "workbench-projects-v1");
|
|
25779
27874
|
}
|
|
25780
27875
|
read(value) {
|
|
25781
27876
|
const request3 = decodeWorkbenchRead(value);
|
|
25782
27877
|
this.o.owner.lease.assert();
|
|
25783
27878
|
switch (request3.kind) {
|
|
27879
|
+
case "cadence-conversation":
|
|
27880
|
+
return { kind: request3.kind, state: this.cadence.state(request3.id) };
|
|
27881
|
+
case "workflow-active":
|
|
27882
|
+
return this.workflows.activeRuns();
|
|
27883
|
+
case "workflow-transcript":
|
|
27884
|
+
return this.workflows.transcript(request3.id, request3.stepId);
|
|
27885
|
+
case "workflow-detail":
|
|
27886
|
+
return this.workflows.detail(request3.id, request3.stepId);
|
|
27887
|
+
case "workflow":
|
|
27888
|
+
return this.workflows.view(request3.id);
|
|
25784
27889
|
case "task-origin":
|
|
25785
27890
|
return this.conversations.origin(request3.taskId);
|
|
25786
|
-
case "conversations":
|
|
25787
|
-
|
|
27891
|
+
case "conversations": {
|
|
27892
|
+
const value2 = this.conversations.list();
|
|
27893
|
+
return {
|
|
27894
|
+
...value2,
|
|
27895
|
+
entries: value2.entries.map((entry) => ({
|
|
27896
|
+
...entry,
|
|
27897
|
+
cadence: this.cadence.state(entry.id).enabled
|
|
27898
|
+
}))
|
|
27899
|
+
};
|
|
27900
|
+
}
|
|
25788
27901
|
case "conversation":
|
|
25789
27902
|
return this.conversations.view(request3.id, request3.before);
|
|
25790
27903
|
case "files":
|
|
@@ -25797,6 +27910,34 @@ class Workbench {
|
|
|
25797
27910
|
return this.projects();
|
|
25798
27911
|
}
|
|
25799
27912
|
}
|
|
27913
|
+
send(request3) {
|
|
27914
|
+
let mayHaveEffects = true;
|
|
27915
|
+
try {
|
|
27916
|
+
const state = this.cadence.state(request3.conversationId);
|
|
27917
|
+
mayHaveEffects = this.o.owner.state !== "idle" || state.head === request3.commandId || this.conversations.attempted(request3.conversationId, request3.commandId);
|
|
27918
|
+
const accepting = () => {
|
|
27919
|
+
mayHaveEffects = true;
|
|
27920
|
+
};
|
|
27921
|
+
if (request3.kind === "send") {
|
|
27922
|
+
if (state.enabled)
|
|
27923
|
+
throw new ContractError("conflict");
|
|
27924
|
+
return this.conversations.send(request3, undefined, accepting);
|
|
27925
|
+
}
|
|
27926
|
+
if (request3.kind === "cadence-exit")
|
|
27927
|
+
return this.cadence.send({
|
|
27928
|
+
...request3,
|
|
27929
|
+
kind: "cadence-send",
|
|
27930
|
+
text: "exit cadence",
|
|
27931
|
+
model: this.o.choice.snapshot().version,
|
|
27932
|
+
intent: "exit"
|
|
27933
|
+
}, accepting);
|
|
27934
|
+
return this.cadence.send(request3, accepting);
|
|
27935
|
+
} catch (error2) {
|
|
27936
|
+
if (!mayHaveEffects && error2 instanceof ContractError)
|
|
27937
|
+
throw new UnacceptedConversationCommand(error2.code);
|
|
27938
|
+
throw error2;
|
|
27939
|
+
}
|
|
27940
|
+
}
|
|
25800
27941
|
projects() {
|
|
25801
27942
|
const secrets = this.o.secrets();
|
|
25802
27943
|
if (sanitizeText(this.o.cwd, secrets) !== this.o.cwd)
|
|
@@ -25804,12 +27945,12 @@ class Workbench {
|
|
|
25804
27945
|
const entries = [{ path: this.o.cwd, current: true }], files = this.o.coordination.files;
|
|
25805
27946
|
if (!files.directory(this.projectRoot))
|
|
25806
27947
|
return { kind: "projects", entries };
|
|
25807
|
-
const directory =
|
|
27948
|
+
const directory = opendirSync10(this.projectRoot);
|
|
25808
27949
|
try {
|
|
25809
27950
|
for (let e = directory.readSync();e; e = directory.readSync()) {
|
|
25810
27951
|
if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries.length > 128)
|
|
25811
27952
|
throw new ContractError("corrupt-selected");
|
|
25812
|
-
const saved = files.read(
|
|
27953
|
+
const saved = files.read(join27(this.projectRoot, e.name));
|
|
25813
27954
|
if (!saved)
|
|
25814
27955
|
throw new ContractError("corrupt-selected");
|
|
25815
27956
|
const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
|
|
@@ -25825,10 +27966,34 @@ class Workbench {
|
|
|
25825
27966
|
}
|
|
25826
27967
|
return { kind: "projects", entries };
|
|
25827
27968
|
}
|
|
25828
|
-
command(value) {
|
|
27969
|
+
command(value, caller) {
|
|
25829
27970
|
const request3 = decodeWorkbenchCommand(value);
|
|
25830
|
-
if (request3.kind === "
|
|
25831
|
-
|
|
27971
|
+
if (request3.kind === "restore-model") {
|
|
27972
|
+
if (request3.epoch !== this.o.owner.lease.registration.epoch)
|
|
27973
|
+
throw new ContractError("stale");
|
|
27974
|
+
const before = this.o.choice.snapshot();
|
|
27975
|
+
if (!before.selected) {
|
|
27976
|
+
const choice = new CadencePreferences(this.o.agentDir).read();
|
|
27977
|
+
if (!choice)
|
|
27978
|
+
throw new ContractError("unavailable");
|
|
27979
|
+
this.o.choice.choose({ expected: before.version, choice });
|
|
27980
|
+
}
|
|
27981
|
+
return { kind: "accepted", commandId: request3.commandId };
|
|
27982
|
+
}
|
|
27983
|
+
if (request3.kind === "send" || request3.kind === "cadence-send" || request3.kind === "cadence-exit")
|
|
27984
|
+
return this.send(request3);
|
|
27985
|
+
if (request3.kind === "cadence-prepare" || request3.kind === "cadence-approve")
|
|
27986
|
+
return this.cadence.approval(request3, caller);
|
|
27987
|
+
if (request3.kind === "workflow-cancel") {
|
|
27988
|
+
if (!caller)
|
|
27989
|
+
throw new ContractError("forbidden");
|
|
27990
|
+
return this.workflows.command(request3.commandId, request3.epoch, {
|
|
27991
|
+
action: "cancel",
|
|
27992
|
+
runId: request3.runId
|
|
27993
|
+
});
|
|
27994
|
+
}
|
|
27995
|
+
if (request3.kind === "workflow")
|
|
27996
|
+
return this.workflows.command(request3.commandId, request3.epoch, request3.request);
|
|
25832
27997
|
if (request3.kind === "link-task") {
|
|
25833
27998
|
this.conversations.link(request3.taskId, request3.conversationId, request3.epoch);
|
|
25834
27999
|
return { kind: "accepted", commandId: request3.commandId };
|
|
@@ -25853,7 +28018,7 @@ class Workbench {
|
|
|
25853
28018
|
if (this.opening.size >= 64)
|
|
25854
28019
|
throw new ContractError("capacity");
|
|
25855
28020
|
const path = this.files.directory(request3.path);
|
|
25856
|
-
const marker2 =
|
|
28021
|
+
const marker2 = join27(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
|
|
25857
28022
|
const files = this.o.coordination.files;
|
|
25858
28023
|
if (files.read(marker2))
|
|
25859
28024
|
throw new ContractError("receipt-inconclusive");
|
|
@@ -25871,7 +28036,7 @@ class Workbench {
|
|
|
25871
28036
|
}
|
|
25872
28037
|
const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
|
|
25873
28038
|
for (const root of [this.o.cwd, opened.path]) {
|
|
25874
|
-
const entry =
|
|
28039
|
+
const entry = join27(this.projectRoot, `${hash2(root)}.json`);
|
|
25875
28040
|
const saved = files.read(entry);
|
|
25876
28041
|
if (!saved)
|
|
25877
28042
|
files.create(entry, canonicalJson({ path: root }));
|
|
@@ -25902,7 +28067,7 @@ function legacy(store, budget, reader) {
|
|
|
25902
28067
|
throw new ContractError("capacity");
|
|
25903
28068
|
}
|
|
25904
28069
|
}
|
|
25905
|
-
const dir =
|
|
28070
|
+
const dir = opendirSync11(store.tasks), records = [];
|
|
25906
28071
|
let entries = 0;
|
|
25907
28072
|
try {
|
|
25908
28073
|
for (let entry = dir.readSync();entry; entry = dir.readSync()) {
|
|
@@ -25911,8 +28076,8 @@ function legacy(store, budget, reader) {
|
|
|
25911
28076
|
decodeId(entry.name);
|
|
25912
28077
|
if (created.has(entry.name))
|
|
25913
28078
|
continue;
|
|
25914
|
-
const path =
|
|
25915
|
-
const size =
|
|
28079
|
+
const path = join28(store.tasks, entry.name, "task.json");
|
|
28080
|
+
const size = lstatSync16(path).size;
|
|
25916
28081
|
if (size > 128 * 1024)
|
|
25917
28082
|
throw new ContractError("corrupt-selected");
|
|
25918
28083
|
budget.reserve(size);
|
|
@@ -25934,7 +28099,7 @@ function refuseAt(stage, step) {
|
|
|
25934
28099
|
}
|
|
25935
28100
|
}
|
|
25936
28101
|
async function createServiceHost(value, sourceBuild) {
|
|
25937
|
-
const embedded = "
|
|
28102
|
+
const embedded = "d19e63723270a27a4c00776d8301849e08480e054bc832ca455f889d061c65c9";
|
|
25938
28103
|
if (embedded && sourceBuild)
|
|
25939
28104
|
throw new ContractError("unsupported-context");
|
|
25940
28105
|
const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
|
|
@@ -26046,7 +28211,14 @@ async function createServiceHost(value, sourceBuild) {
|
|
|
26046
28211
|
cwd: input.config.cwd,
|
|
26047
28212
|
environment: launch
|
|
26048
28213
|
});
|
|
26049
|
-
const
|
|
28214
|
+
const preferences = new CadencePreferences(input.config.agentDir);
|
|
28215
|
+
const choice = new OwnerModelChoice({
|
|
28216
|
+
owner,
|
|
28217
|
+
writer,
|
|
28218
|
+
models,
|
|
28219
|
+
access,
|
|
28220
|
+
remember: (value2) => preferences.save(value2)
|
|
28221
|
+
});
|
|
26050
28222
|
const { PI_OFFLINE: _offline, ...ordinary } = launch;
|
|
26051
28223
|
const checkEnvironment = Object.freeze(ordinary);
|
|
26052
28224
|
const actions = sourceBuild?.deferActions ? null : new TaskActions({
|
|
@@ -26077,6 +28249,7 @@ async function createServiceHost(value, sourceBuild) {
|
|
|
26077
28249
|
cwd: input.config.cwd,
|
|
26078
28250
|
agentDir: input.config.agentDir,
|
|
26079
28251
|
projectsEnabled: !input.config.http.proxy,
|
|
28252
|
+
checkEnvironment,
|
|
26080
28253
|
hostUrl: new URL(sourceBuild ? "../service-host.mjs" : "./service-host.mjs", import.meta.url),
|
|
26081
28254
|
secrets: () => [
|
|
26082
28255
|
...access.redactionLiterals(),
|
|
@@ -26086,10 +28259,10 @@ async function createServiceHost(value, sourceBuild) {
|
|
|
26086
28259
|
],
|
|
26087
28260
|
timeoutMs: sourceBuild?.workerTimeoutMs
|
|
26088
28261
|
}) : null;
|
|
26089
|
-
const unavailable2 = (
|
|
28262
|
+
const unavailable2 = (taskId2) => ({
|
|
26090
28263
|
status: "unavailable",
|
|
26091
28264
|
workspaceId: reader.files.format.workspaceId,
|
|
26092
|
-
taskId,
|
|
28265
|
+
taskId: taskId2,
|
|
26093
28266
|
error: publicError(owner?.state === "idle" ? "unavailable" : "quarantine")
|
|
26094
28267
|
});
|
|
26095
28268
|
const projection = new HistoryProjection(reader, {
|