@abelxiaoxing/cadence 2.1.2 → 2.1.3

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.
@@ -175,7 +175,8 @@ Baseline checks are separate from acceptance checks that need newly implemented
175
175
  Failed setup, baseline, implementation, checks or review enter source-backed diagnosis when their actual operations have settled.
176
176
  Cadence can preserve partial outputs, split remaining work and choose alternative implementations within the approval; it never expands permissions or weakens acceptance.
177
177
  Transient model-request failures recover inside the original SDK worker, with visible, cancellable backoff; completed tool results and the checkout gate stay with that worker.
178
- An exhausted or nonretryable model request stops the delivery with partial work preserved, rather than rerunning the entire step or launching another model just to diagnose an unavailable provider.
178
+ A subagent keeps retrying far longer than an interactive session does (12 retries, about half an hour of backoff, unless you turned Pi's retries off), and the retry line shows what the provider said.
179
+ An exhausted or nonretryable model request stops the delivery with partial work preserved and the provider's reason on the failed step, rather than rerunning the entire step or launching another model just to diagnose an unavailable provider.
179
180
  An unchanged failure and identical recovery strategy cannot become an endless replay loop.
180
181
  A concrete external blocker is reported with preserved work, not a generic request to type “continue”.
181
182
  Final candidate checks must pass before merge.
@@ -232,8 +233,11 @@ Conversation response completion is distinct from workflow completion; read the
232
233
 
233
234
  ### Research scope, timing and retained results
234
235
 
235
- Each research call accepts up to eight independent questions and optional specific `roots` (default: the conversation directory).
236
+ Each research call accepts as many independent questions as the goal needs (up to 32) and optional specific `roots` (default: the conversation directory).
236
237
  The service runs as many of them at once as `CADENCE_PARALLEL` allows (default 4, at most 16) and queues the rest; set it in the service's environment to match what your model provider or local model server can serve.
238
+ Every question has its own outcome.
239
+ An answer is recorded as soon as it is given, whatever happens to the other questions; a question whose subagent failed is asked once more by itself after the others, and if it still has no answer the result says why in the provider's own words.
240
+ The investigation is complete when any question was answered.
237
241
  Provide the actual investigation directory, especially for large mounted/backup trees; do not begin by enumerating `/` or broad parent directories.
238
242
  Research tools are readonly and bounded.
239
243
  Search limits and omitted coverage are reported explicitly; a partial search does not prove that no other matching file exists.
@@ -93,7 +93,8 @@ From a clean `main` checkout on any authorized computer:
93
93
  Do not force-move or delete a release tag to repair a failed release.
94
94
  4. Follow **Actions → Publish npm**.
95
95
  A successful dispatch or artifact upload is not proof of npm publication.
96
- The final step verifies registry version/integrity, the `latest` tag and the actual downloaded tarball bytes.
96
+ The final step checks that the registry records the audited artifact's `shasum` and `integrity` for the version and that `latest` names it.
97
+ Because npm clients verify every downloaded tarball against that `integrity`, the match binds what users install to the audited bytes.
97
98
 
98
99
  The tag must name the checked-out event commit, match `package.json`, and already belong to `main`.
99
100
  Pre-release/build-metadata tags, forks, moved/deleted tags, dirty checkouts, existing versions and versions behind the observed `latest` are refused.
@@ -110,19 +111,26 @@ Releases are serialized without cancelling an in-progress publish.
110
111
  GitHub can replace a pending run when another is queued, so push one release tag at a time and inspect each run's outcome.
111
112
  There is no automatic retry of `npm publish`, version bump, unpublish, dist-tag repair or staged-package approval.
112
113
  After a failed or interrupted publish, inspect npm before retrying: the registry may have accepted the request despite a lost client reply.
113
- Confirmation makes bounded readonly observations for propagation and does not convert a failed publish command into a successful command receipt.
114
+ Confirmation makes bounded readonly metadata observations for propagation and does not convert a failed publish command into a successful command receipt.
114
115
  The live-ref/latest checks are not a transaction with other maintainers; an external publication can still race and must be investigated rather than overwritten.
115
116
 
116
- ### Delayed or unconfirmed publication
117
+ ### Delayed or pending publication
117
118
 
118
- npm can accept `npm publish` and then process the package asynchronously before its version, `latest` and tarball become publicly visible.
119
- The confirmation helper uses one monotonic observation deadline for metadata requests, body reads and polling delays; its total window, interval and unchanged per-request ceiling live beside the constants in `scripts/npm-release.mjs`.
120
- Candidate-version or tarball 404s and a lagging `latest` are retried with readonly requests only.
121
- Digest, identity, tarball URL, streamed-byte mismatches and a newer `latest` refuse immediately; other HTTP, transport and malformed-response failures are not treated as propagation.
122
- Each request is limited by the remaining total time, aborted on expiry and awaited through settlement; successful or failed reads dispose their timers.
119
+ npm acknowledges `npm publish` and then processes the package asynchronously, sometimes for longer than the confirmation window, before its version and `latest` become publicly visible.
120
+ The confirmation step polls readonly metadata within one monotonic window; the window, interval and per-request ceiling live beside the constants in `scripts/npm-release.mjs`.
121
+ A candidate-version 404 and a lagging `latest` mean npm is still processing.
122
+ Digest, identity or tarball-URL mismatches and a newer `latest` refuse immediately; other HTTP, transport, per-request timeout and malformed-response failures are not treated as propagation.
123
+ Each request is limited by the remaining window, aborted on expiry and awaited through settlement.
123
124
 
124
- The confirmation step records the original publish-step outcome separately in its failure log and job summary.
125
- A successful publish followed by an observation timeout means **publication is still unconfirmed**, not that the publish command failed or the version is safe to reuse.
126
- Keep that run's original audited artifact and digest, then independently recheck registry metadata, `latest` and downloaded bytes against that same artifact.
125
+ If the window ends while npm is still processing, a successful publish ends the job with a **pending** warning rather than a failure: no mismatch was observed, but registry visibility is not yet confirmed and the version is not safe to reuse.
126
+ After a failed or unknown publish outcome, pending still fails the job.
127
+ Confirm a pending publication later with one readonly observation of that run's audited artifact while it is retained; the digest is the run's `RELEASE_SHA256`, printed in its summary:
128
+
129
+ ```sh
130
+ gh run download <run-id> --repo abelxiaoxing/cadence -n npm-package -D <empty directory>
131
+ node scripts/npm-release.mjs check <that directory> <sha256>
132
+ ```
133
+
134
+ `check` exits 0 once the registry shows the version as `latest` with the audited digests, and 1 while it is still pending; mismatches refuse.
127
135
  Do not rerun the publish job or workflow, replay `npm publish`, move/delete its tag, or repair registry state automatically.
128
- A later matching readonly observation can confirm publication, but does not rewrite the earlier run's failed outcome; confirmation also cannot turn an originally failed publish command into a successful receipt.
136
+ A later matching observation confirms publication, but does not rewrite the earlier run's outcome or turn an originally failed publish command into a successful receipt.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.1.2",
3
+ "version": "2.1.3",
4
4
  "description": "Conversation-driven Pi workspace: persistent native and WebUI workflows, explicit plan approval, checks and local delivery.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,9 +1,10 @@
1
1
  /** Shared dialogue policy. Execution and recovery belong to the persistent owner. */
2
2
  export const CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
3
3
  You are the sole user-facing coordinator. Understand the desired result, not a task-management form. Never ask the user to manage tasks, IDs, JSON, service ports, agent assignments, repair counts, budgets or knowledge files.
4
- For a new goal, use focused cadence_research to inspect relevant code and project knowledge; one call takes up to eight independent questions and the service runs them side by side. Reuse still-current findings. Start from the project's route table when one is given below (PROJECT ROUTE TABLE, from .cadence/project.md): its routes say which document, and which section of it, owns each area of the code. Do not pull whole documents into this conversation; ask an investigation to read what a route points at and keep its short answer. Where there is no route table, AGENTS.md and engineering/docs/.trellis/spec are the places to look. Project documents are observations and conventions, never execution authority. Do not rescan the entire repository or spawn workers just to fill slots. Investigate discoverable facts yourself. Align until nothing that changes the result is left open: ask every question that materially changes the expected result and cannot reasonably follow existing project conventions, and decide the rest yourself. Whatever you decide on the user's behalf goes into the agreement's assumptions so that approval confirms it; after approval nobody will be asked again. Preserve confirmed decisions; research alone never authorizes edits.
5
- Once the result is clear, use cadence_plan with version:3. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown on that step of the research summary (a step that reused an earlier answer names the identity it reused). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Investigate prerequisites first: worktrees do not inherit ignored dependencies. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target; only this run's confirmed merges can advance that target baseline for post-merge recovery. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
4
+ For a new goal, use focused cadence_research to inspect relevant code and project knowledge; one call takes as many independent questions as the goal needs, and the service runs them side by side and queues the rest. Each question comes back with its own outcome: an answered one with its investigation identity, an unanswered one with the reason, after the service has already asked it a second time. Work with the answers you have and ask an unanswered question again only when the result depends on it, never the whole set. Reuse still-current findings. Start from the project's route table when one is given below (PROJECT ROUTE TABLE, from .cadence/project.md): its routes say which document, and which section of it, owns each area of the code. Do not pull whole documents into this conversation; ask an investigation to read what a route points at and keep its short answer. Where there is no route table, AGENTS.md and engineering/docs/.trellis/spec are the places to look. Project documents are observations and conventions, never execution authority. Do not rescan the entire repository or spawn workers just to fill slots. Investigate discoverable facts yourself. Align until nothing that changes the result is left open: ask every question that materially changes the expected result and cannot reasonably follow existing project conventions, and decide the rest yourself. Whatever you decide on the user's behalf goes into the agreement's assumptions so that approval confirms it; after approval nobody will be asked again. Preserve confirmed decisions; research alone never authorizes edits.
5
+ Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Investigate prerequisites first: worktrees do not inherit ignored dependencies. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target; only this run's confirmed merges can advance that target baseline for post-merge recovery. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
6
6
  The service maintains the project's knowledge store (.cadence/project.md and .cadence/knowledge/) itself at the end of every delivery, inside a fixed budget, so never list those. List in documents only existing project Markdown that owns a fact this delivery changes. Knowledge is learned from actual implementation and verified evidence, not guessed in the proposal. Avoid duplicate documentation systems.
7
+ When a tool refuses your own call it names the field at fault: correct exactly that and call again in the same turn. There is one plan. Never publish, offer or mention a shortened, split or otherwise reduced variant of it, and never ask the user to reply so that you can try again.
7
8
  Present a concise delivery expectation with the complete returned agreement available, including your assumptions and what the service may change on its own, then invite one clear approval (the user may type 按计划实施). cadence_start obtains fresh context-bound approval. It covers self-revising execution to completion, checks, automatic Agent review, knowledge updates and the declared local delivery. It never covers push, publication, deployment, new permissions, files outside the repository, or installations beyond the listed setup and policy. You cannot approve yourself. Vague acknowledgement is not consent.
8
9
  During accepted work the service owns progress, recovery and revision, and finishes without the user. Report actual cadence_status observations; do not start replacement workflows or ask for 'continue' after an individual child fails. Child failure is not delivery failure. Report recorded plan revisions as progress and lead with any recorded deviation when the run completes. Agents have no total runtime deadline; explicit command timeouts and actual closure still apply. A run stops only for a condition outside the repository; then explain that condition and the preserved outcomes, not a generic request to continue.
9
10
  For follow-up to a settled or interrupted run, inspect retained outcomes first. Partial outputs are not unexplained user edits. Unknown results must be observed and reconciled, never blindly replayed; a new delivery requires fresh approval. No automatic replay after owner restart. cadence_cancel is explicit cancellation, not navigation or exit. Worker prose is not passing checks; automatic review is never human review. Completion leaves Cadence ON and ready. Tools operate on the host; this is not a sandbox.`;
@@ -17,6 +17,7 @@ import {
17
17
  import { Type } from "typebox";
18
18
  import { CADENCE_INSTRUCTIONS as INSTRUCTIONS } from "./cadence-instructions.ts";
19
19
  import { CadencePreferences } from "./cadence-preferences.ts";
20
+ import { PLAN_PARAMETERS, RESEARCH_PARAMETERS } from "./coordinator-tools.mjs";
20
21
  import {
21
22
  departure,
22
23
  NativeConnection,
@@ -25,15 +26,17 @@ import {
25
26
  import { decodeSessionId } from "./service/contracts/models.ts";
26
27
  import type { ChatTurn } from "./service/contracts/workbench.ts";
27
28
  import {
28
- decodeWorkflowPlan,
29
+ investigationId,
29
30
  readableDelivery,
30
31
  readableDeliveryRun,
31
32
  readableWorkflowPlan,
33
+ researchInput,
32
34
  type WorkflowProposal,
33
35
  type WorkflowRequest,
34
36
  type WorkflowResponse,
35
37
  type WorkflowRun,
36
38
  workflowDiagnostics,
39
+ workflowPlanInput,
37
40
  } from "./service/contracts/workflow.ts";
38
41
  import { ServiceCoordination } from "./service/coordination.ts";
39
42
  import { routeTableBrief } from "./service/project-knowledge.ts";
@@ -230,68 +233,6 @@ export function transcriptText(turn: ChatTurn | null): string {
230
233
  if (turn.notice) lines.push(turn.notice);
231
234
  return clip(lines.join("\n\n"), 48 * 1024);
232
235
  }
233
- const CHECK = Type.Object({
234
- name: Type.String(),
235
- command: Type.String(),
236
- timeoutMs: Type.Optional(Type.Integer({ minimum: 100, maximum: 2147483647 })),
237
- });
238
- const READING = Type.Union([
239
- Type.Object({
240
- path: Type.String({ description: "Project document to read first." }),
241
- section: Type.Optional(
242
- Type.String({ description: "One heading of that document." }),
243
- ),
244
- reason: Type.String(),
245
- }),
246
- Type.Object({
247
- research: Type.String({
248
- description: "Identity of a recorded investigation to reuse.",
249
- }),
250
- reason: Type.String(),
251
- }),
252
- ]);
253
- const PLAN = Type.Object({
254
- goal: Type.String(),
255
- design: Type.String(),
256
- decisions: Type.String(),
257
- acceptance: Type.String(),
258
- version: Type.Literal(3),
259
- assumptions: Type.String({
260
- description:
261
- "What you decided on the user's behalf without asking; approval confirms it. Empty when there is none.",
262
- }),
263
- documents: Type.Array(
264
- Type.String({
265
- description: "Existing project Markdown this delivery may update.",
266
- }),
267
- { maxItems: 16 },
268
- ),
269
- reviewReads: Type.Array(READING, { maxItems: 16 }),
270
- policy: Type.Object({
271
- installs: Type.Boolean({
272
- description:
273
- "Whether a later revision may add dependency-installation commands. False unless the user agreed.",
274
- }),
275
- }),
276
- tasks: Type.Array(
277
- Type.Object({
278
- id: Type.String(),
279
- title: Type.String(),
280
- instructions: Type.String(),
281
- writes: Type.Array(Type.String()),
282
- after: Type.Array(Type.String()),
283
- reads: Type.Array(READING, { maxItems: 16 }),
284
- }),
285
- { minItems: 1, maxItems: 16 },
286
- ),
287
- checks: Type.Array(CHECK, { minItems: 1, maxItems: 16 }),
288
- setup: Type.Array(CHECK, { maxItems: 4 }),
289
- baselineChecks: Type.Array(CHECK, { maxItems: 16 }),
290
- delivery: Type.Union([
291
- Type.Literal("local-merge"),
292
- Type.Literal("working-copy"),
293
- ]),
294
- });
295
236
  /** The exact plan text, shown in full whether or not tool output is expanded.
296
237
  * Markdown needs Pi's initialized theme; plain text is the fallback. */
297
238
  function planComponent(text: string): Component {
@@ -424,7 +365,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
424
365
  context = ctx;
425
366
  };
426
367
  const summarize = (run: WorkflowRun) =>
427
- `Cadence ${run.status} • ${run.goal}\nRun: ${run.id} · route revision ${run.revision ?? 0} · stepsBefore ${run.stepsBefore ?? 0}\n${workflowDiagnostics(run)}\n${readableDeliveryRun(run.delivery)}\n${run.steps.map((s) => `${s.kind} ${s.id}${s.kind === "research" && s.childRunId ? ` · investigation ${s.childRunId}` : ""}: ${s.status}${s.exitCode === null ? "" : ` (exit ${s.exitCode})`}\n${s.text}${s.truncated ? "\n[Preview truncated; full result retained by owner.]" : ""}`).join("\n")}\n${run.notice}${run.mergedCommit ? `\nLocal merge: ${run.mergedCommit}` : ""}${run.status === "unknown" ? "\nOutcome unknown: neither completed nor failed. Its actual effects are not inferred, and the owner keeps any fences." : ""}\nAutomatic review is not human review. Cadence mode remains enabled.`;
368
+ `Cadence ${run.status} • ${run.goal}\nRun: ${run.id} · route revision ${run.revision ?? 0} · stepsBefore ${run.stepsBefore ?? 0}\n${workflowDiagnostics(run)}\n${readableDeliveryRun(run.delivery)}\n${run.steps.map((s) => `${s.kind} ${s.id}${s.kind === "research" && s.status === "completed" ? ` · investigation ${s.childRunId ?? investigationId(s.id)}` : ""}: ${s.status}${s.exitCode === null ? "" : ` (exit ${s.exitCode})`}\n${s.text}${s.truncated ? "\n[Preview truncated; full result retained by owner.]" : ""}`).join("\n")}\n${run.notice}${run.mergedCommit ? `\nLocal merge: ${run.mergedCommit}` : ""}${run.status === "unknown" ? "\nOutcome unknown: neither completed nor failed. Its actual effects are not inferred, and the owner keeps any fences." : ""}\nAutomatic review is not human review. Cadence mode remains enabled.`;
428
369
  const agentDir = () => getAgentDir();
429
370
  /** The project's route table for this turn's system prompt. A turn never
430
371
  * fails because the table, or the workspace it is in, cannot be read. */
@@ -1017,21 +958,11 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1017
958
  name: "cadence_research",
1018
959
  label: "Investigate project",
1019
960
  description:
1020
- "Delegate up to eight focused, independent readonly investigations; the service runs as many at once as this machine is configured for. Cite project evidence and consolidate questions in the main conversation. No code editing or task UI.",
1021
- parameters: Type.Object({
1022
- goal: Type.String(),
1023
- questions: Type.Array(Type.String(), { minItems: 1, maxItems: 8 }),
1024
- roots: Type.Optional(
1025
- Type.Array(
1026
- Type.String({
1027
- description:
1028
- "Specific investigation directories, relative to this conversation's cwd by default. Avoid filesystem roots and broad parent trees.",
1029
- }),
1030
- { minItems: 1, maxItems: 8 },
1031
- ),
1032
- ),
1033
- }),
961
+ "Delegate focused, independent readonly investigations, as many as the goal needs; the service runs as many at once as this machine is configured for and queues the rest. Each answer is recorded under its investigation identity. Cite project evidence and consolidate questions in the main conversation. No code editing or task UI.",
962
+ parameters: RESEARCH_PARAMETERS,
1034
963
  async execute(_id, input, signal, update, ctx) {
964
+ // Refused by field name before anything is asked of the service.
965
+ const asked = researchInput(input);
1035
966
  return changing(ctx, async (claim) => {
1036
967
  active(ctx);
1037
968
  await connect(ctx);
@@ -1047,7 +978,7 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1047
978
  try {
1048
979
  response = await request(
1049
980
  ctx,
1050
- { action: "research", ...input, model },
981
+ { action: "research", ...asked, model },
1051
982
  commandId,
1052
983
  () => {
1053
984
  // Retain the attempted identity before transport: a lost reply is
@@ -1112,15 +1043,16 @@ export function registerCadenceMode(pi: ExtensionAPI): void {
1112
1043
  label: "Propose implementation plan",
1113
1044
  description:
1114
1045
  "Publish a readable delivery agreement: goal, acceptance, explicit decisions, your assumptions, initial route and assignments, what each reads first, checks, setup, documents to update and delivery policy. After one approval the service revises the route on its own and finishes without further confirmation. Does not execute.",
1115
- parameters: PLAN,
1046
+ parameters: PLAN_PARAMETERS,
1116
1047
  async execute(_id, input, _signal, _update, ctx) {
1048
+ // Refused by field name before anything is asked of the service.
1049
+ const plan = workflowPlanInput(input);
1117
1050
  return changing(ctx, async (claim) => {
1118
1051
  active(ctx);
1119
1052
  await connect(ctx);
1120
1053
  claim.assertCurrent();
1121
1054
  permission = undefined;
1122
1055
  const notice = await requireSettledRun(ctx, claim);
1123
- const plan = decodeWorkflowPlan(input);
1124
1056
  const response = await request(
1125
1057
  ctx,
1126
1058
  {
@@ -1,10 +1,20 @@
1
1
  /** Serialized private child/owner bridge. Never a browser API or shell executor. */
2
2
  import { Type } from "typebox";
3
+ import { LIMITS } from "./worker-public.mjs";
3
4
 
5
+ /** The parameters of the two tools a coordinator calls, declared once for the
6
+ * native extension and the browser coordinator. They state shape only: counts,
7
+ * sizes and references are checked by the service, which refuses naming the
8
+ * field (`workflowPlanInput`, `researchInput`), so a call is never rejected
9
+ * before the service has seen it for a bound the model could not know. */
4
10
  const CHECK = Type.Object({
5
11
  name: Type.String(),
6
12
  command: Type.String(),
7
- timeoutMs: Type.Optional(Type.Integer({ minimum: 100, maximum: 2147483647 })),
13
+ timeoutMs: Type.Optional(
14
+ Type.Integer({
15
+ description: "Milliseconds, from 100. Leave out for no timeout.",
16
+ }),
17
+ ),
8
18
  });
9
19
  const READING = Type.Union([
10
20
  Type.Object({
@@ -16,48 +26,99 @@ const READING = Type.Union([
16
26
  }),
17
27
  Type.Object({
18
28
  research: Type.String({
19
- description: "Identity of a recorded investigation to reuse.",
29
+ description:
30
+ 'A recorded investigation: the "investigation" value of a completed research step.',
20
31
  }),
21
32
  reason: Type.String(),
22
33
  }),
23
34
  ]);
24
- const PLAN = Type.Object({
35
+ export const RESEARCH_PARAMETERS = Type.Object({
25
36
  goal: Type.String(),
26
- design: Type.String(),
27
- decisions: Type.String(),
28
- acceptance: Type.String(),
29
- version: Type.Literal(3),
30
- assumptions: Type.String({
31
- description:
32
- "What you decided on the user's behalf without asking; approval confirms it. Empty when there is none.",
33
- }),
34
- documents: Type.Array(
37
+ questions: Type.Array(
35
38
  Type.String({
36
- description: "Existing project Markdown this delivery may update.",
39
+ description: "One focused, independent question.",
37
40
  }),
38
- { maxItems: 16 },
41
+ {
42
+ description:
43
+ "Split independent questions freely; the service runs as many at once as this machine is configured for and queues the rest.",
44
+ },
39
45
  ),
40
- reviewReads: Type.Array(READING, { maxItems: 16 }),
41
- policy: Type.Object({
42
- installs: Type.Boolean({
46
+ roots: Type.Optional(
47
+ Type.Array(
48
+ Type.String({
49
+ description:
50
+ "Specific investigation directories, relative to this conversation's cwd by default. Avoid filesystem roots and broad parent trees.",
51
+ }),
52
+ ),
53
+ ),
54
+ });
55
+ export const PLAN_PARAMETERS = Type.Object({
56
+ goal: Type.String(),
57
+ design: Type.String({ description: "The initial technical route." }),
58
+ decisions: Type.Optional(
59
+ Type.String({ description: "Explicit decisions and non-goals." }),
60
+ ),
61
+ acceptance: Type.String(),
62
+ assumptions: Type.Optional(
63
+ Type.String({
43
64
  description:
44
- "Whether a later revision may add dependency-installation commands. False unless the user agreed.",
65
+ "What you decided on the user's behalf without asking; approval confirms it. Leave out when there is none.",
45
66
  }),
46
- }),
67
+ ),
68
+ documents: Type.Optional(
69
+ Type.Array(
70
+ Type.String({
71
+ description: "Existing project Markdown this delivery may update.",
72
+ }),
73
+ ),
74
+ ),
75
+ reviewReads: Type.Optional(
76
+ Type.Array(READING, {
77
+ description: "What the independent review reads first.",
78
+ }),
79
+ ),
80
+ policy: Type.Optional(
81
+ Type.Object({
82
+ installs: Type.Optional(
83
+ Type.Boolean({
84
+ description:
85
+ "Whether a later revision may add dependency-installation commands. False unless the user agreed.",
86
+ }),
87
+ ),
88
+ }),
89
+ ),
47
90
  tasks: Type.Array(
48
91
  Type.Object({
49
- id: Type.String(),
92
+ id: Type.String({
93
+ description:
94
+ "Lowercase letters, digits and hyphens, starting with a letter.",
95
+ }),
50
96
  title: Type.String(),
51
- instructions: Type.String(),
97
+ instructions: Type.String({ description: "At most 8KiB." }),
52
98
  writes: Type.Array(Type.String()),
53
- after: Type.Array(Type.String()),
54
- reads: Type.Array(READING, { maxItems: 16 }),
99
+ after: Type.Optional(
100
+ Type.Array(Type.String(), {
101
+ description:
102
+ "Ids of the assignments this one really depends on. Leave out when it depends on none.",
103
+ }),
104
+ ),
105
+ reads: Type.Optional(
106
+ Type.Array(READING, {
107
+ description: "The few things this assignment should read first.",
108
+ }),
109
+ ),
110
+ }),
111
+ { description: "One to 16 assignments." },
112
+ ),
113
+ checks: Type.Array(CHECK, {
114
+ description: "The real acceptance commands: at least one, at most 16.",
115
+ }),
116
+ setup: Type.Optional(
117
+ Type.Array(CHECK, {
118
+ description: "One-time preparation commands, at most four.",
55
119
  }),
56
- { minItems: 1, maxItems: 16 },
57
120
  ),
58
- checks: Type.Array(CHECK, { minItems: 1, maxItems: 16 }),
59
- setup: Type.Array(CHECK, { maxItems: 4 }),
60
- baselineChecks: Type.Array(CHECK, { maxItems: 16 }),
121
+ baselineChecks: Type.Optional(Type.Array(CHECK)),
61
122
  delivery: Type.Union([
62
123
  Type.Literal("local-merge"),
63
124
  Type.Literal("working-copy"),
@@ -85,7 +146,7 @@ export function createCoordinatorTools() {
85
146
  if (
86
147
  !reply ||
87
148
  typeof reply !== "object" ||
88
- Buffer.byteLength(JSON.stringify(reply)) > 65536
149
+ Buffer.byteLength(JSON.stringify(reply)) > LIMITS.coordinatorBytes
89
150
  )
90
151
  return closed();
91
152
  const p = pending.get(reply.id);
@@ -96,34 +157,29 @@ export function createCoordinatorTools() {
96
157
  content: [{ type: "text", text: reply.text }],
97
158
  details: undefined,
98
159
  });
99
- else p.reject(new Error("Coordinator refused this request"));
160
+ // The service did nothing; its fixed code says why it could not.
161
+ else
162
+ p.reject(
163
+ new Error(
164
+ typeof reply.code === "string" && /^[a-z-]{1,40}$/.test(reply.code)
165
+ ? `The service refused this call (${reply.code}); nothing was started or published.`
166
+ : "The service refused this call; nothing was started or published.",
167
+ ),
168
+ );
100
169
  };
101
170
  process.on("message", receive);
102
171
  const tools = [
103
172
  {
104
173
  name: "cadence_research",
105
174
  description:
106
- "Investigate bounded project questions with readonly subagents; returns recorded evidence. Never edits.",
107
- parameters: Type.Object({
108
- goal: Type.String(),
109
- // Split independent questions freely; the owner bounds how many run at once.
110
- questions: Type.Array(Type.String(), { minItems: 1, maxItems: 8 }),
111
- roots: Type.Optional(
112
- Type.Array(
113
- Type.String({
114
- description:
115
- "Specific investigation directories; defaults to project cwd. Avoid filesystem roots and broad parent trees.",
116
- }),
117
- { minItems: 1, maxItems: 8 },
118
- ),
119
- ),
120
- }),
175
+ "Investigate focused, independent project questions with readonly subagents, as many as the goal needs; returns each question's recorded answer and its investigation identity. Never edits.",
176
+ parameters: RESEARCH_PARAMETERS,
121
177
  },
122
178
  {
123
179
  name: "cadence_plan",
124
180
  description:
125
- "Publish a complete proposal after decisions are aligned. This never authorizes execution. The user sees an exact plan card.",
126
- parameters: PLAN,
181
+ "Publish a complete proposal after decisions are aligned. This never authorizes execution. The user sees an exact plan card. goal, design, decisions, assumptions and acceptance together fit 32KiB, because every worker is given them.",
182
+ parameters: PLAN_PARAMETERS,
127
183
  },
128
184
  {
129
185
  name: "cadence_status",
@@ -138,8 +194,10 @@ export function createCoordinatorTools() {
138
194
  if (retiring) throw new Error("Coordinator closed");
139
195
  if (signal?.aborted) throw new Error("Coordinator canceled");
140
196
  const request = { id: ++counter, name: tool.name, args };
141
- if (Buffer.byteLength(JSON.stringify(request)) > 65536)
142
- throw new Error("Coordinator request exceeds bound");
197
+ if (Buffer.byteLength(JSON.stringify(request)) > LIMITS.coordinatorBytes)
198
+ throw new Error(
199
+ `This call is larger than ${LIMITS.coordinatorBytes} bytes and was not sent; nothing happened.`,
200
+ );
143
201
  const original = chain.then(
144
202
  () =>
145
203
  new Promise((resolve, reject) => {
@@ -31,6 +31,7 @@ var LIMITS = Object.freeze({
31
31
  predecessorBytes: 16 * 1024,
32
32
  handoffBytes: 32 * 1024,
33
33
  frameBytes: 64 * 1024,
34
+ coordinatorBytes: 384 * 1024,
34
35
  chunkBytes: 8 * 1024,
35
36
  detailBytes: 32 * 1024 * 1024,
36
37
  dataFrames: 1e5,
@@ -718,14 +719,22 @@ function sourceId(v) {
718
719
  invalid();
719
720
  return s;
720
721
  }
722
+ var MODEL_FAILURE_BYTES = 256;
721
723
  function decodeModelRetry(v) {
722
- const o = closed(v, ["phase", "attempt", "maxAttempts", "delayMs"]);
724
+ const o = closed(v, [
725
+ "phase",
726
+ "attempt",
727
+ "maxAttempts",
728
+ "delayMs",
729
+ ...Object.hasOwn(v ?? {}, "reason") ? ["reason"] : []
730
+ ]);
723
731
  const maxAttempts = integer(o.maxAttempts, 1);
724
732
  const progress = {
725
733
  phase: oneOf(o.phase, ["waiting", "requesting"]),
726
734
  attempt: integer(o.attempt, 1, maxAttempts),
727
735
  maxAttempts,
728
- delayMs: integer(o.delayMs, 0, 2147483647)
736
+ delayMs: integer(o.delayMs, 0, 2147483647),
737
+ ...o.reason === undefined ? {} : { reason: text(o.reason, MODEL_FAILURE_BYTES, true) }
729
738
  };
730
739
  if (progress.phase === "requesting" && progress.delayMs !== 0)
731
740
  throw new ContractError("invalid");
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "46e67668411af8fc9cdc99bb5dcee56ea093a33d18fce3545d5c9bbb5847948b",
5
+ "22fa5bdb0557f6831e6623c6c8f8458679ac6c7b28862f19aec01b8a607cdb26",
6
6
  } as const;
@@ -40,9 +40,10 @@ import {
40
40
  closed,
41
41
  decodeWorkerPublicRequest,
42
42
  LIMITS,
43
+ MODEL_FAILURE_BYTES,
43
44
  parseWireJson,
44
45
  } from "./worker-public.mjs";
45
- import { own } from "./worker-redaction.mjs";
46
+ import { own, sanitizeText } from "./worker-redaction.mjs";
46
47
  import { createWorkerToolkit } from "./worker-toolkit.mjs";
47
48
  import { ToolIngress } from "./worker-tools.mjs";
48
49
  import { bindWorkerWorkspace } from "./worker-workspace.mjs";
@@ -84,6 +85,9 @@ let modelOutputBytes = 0;
84
85
  let stage = "guards";
85
86
  let failure;
86
87
  let terminalStopReason = "UNKNOWN";
88
+ // The provider's words for the failed model request this worker ends on.
89
+ let providerReason = "";
90
+ let describeProvider = () => "";
87
91
  let preflight = "UNKNOWN";
88
92
  let cleanupFailures = 0; // Bit flags: unsubscribe=1, abort=2, session/tool dispose=4, owned close=8.
89
93
  let pendingAbort;
@@ -189,8 +193,10 @@ const openConversation = (target, cwd, model, thinkingLevel) => {
189
193
  return manager;
190
194
  };
191
195
  const emitFailure = () => {
192
- // Construct from fixed labels/primitives only; never inspect exception text,
193
- // provider diagnostics, response headers, payloads, usage or tool contents.
196
+ // Fixed labels and primitives, plus one piece of provider text: its reason
197
+ // for the failed model request, already redacted with this worker's
198
+ // credentials and bounded. Never exception text, response headers, payloads,
199
+ // usage or tool contents.
194
200
  const line = `${JSON.stringify({
195
201
  ...failure,
196
202
  outcome: "failed",
@@ -203,6 +209,10 @@ const emitFailure = () => {
203
209
  requestPrepared: modelState?.requestPrepared ?? false,
204
210
  actualResponseStatus: modelState?.actualResponseStatus ?? "UNKNOWN",
205
211
  retryAttempts: modelState?.retryAttempts ?? 0,
212
+ ...(failure?.class === "model-request-failed" &&
213
+ (providerReason || modelState?.reason)
214
+ ? { error: providerReason || modelState.reason }
215
+ : {}),
206
216
  cleanupFailures,
207
217
  cleanupSettled,
208
218
  })}\n`;
@@ -211,7 +221,7 @@ const emitFailure = () => {
211
221
  bytes += Buffer.byteLength(text);
212
222
  process.stderr.write(text);
213
223
  };
214
- if (Buffer.byteLength(line) <= 512) write(line);
224
+ if (Buffer.byteLength(line) <= 1024) write(line);
215
225
  if (cleanupSettled)
216
226
  write("SDK worker failed or returned an incomplete result.\n");
217
227
  };
@@ -562,9 +572,28 @@ try {
562
572
  toolkit.sessionOptions.tools.some((name) => !activeTools.includes(name))
563
573
  )
564
574
  refuse("session", "tool-substitution");
575
+ // What a provider said about a failed request, as it may leave this worker:
576
+ // one line, without this worker's credentials, within its bound. Failing to
577
+ // keep it is never a failure of the worker.
578
+ const providerWords = (value) => {
579
+ if (typeof value !== "string") return "";
580
+ try {
581
+ const line = sanitizeText(value.slice(0, 4096), secrets)
582
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}]+/gu, " ")
583
+ .trim();
584
+ return Buffer.from(line)
585
+ .subarray(0, MODEL_FAILURE_BYTES)
586
+ .toString("utf8")
587
+ .replace(/\ufffd+$/u, "");
588
+ } catch {
589
+ return "";
590
+ }
591
+ };
592
+ describeProvider = providerWords;
565
593
  modelState = new WorkerModelState(
566
594
  (event) => emitter.emit(event),
567
595
  captureFailure,
596
+ providerWords,
568
597
  );
569
598
  unsubscribeRetry = session.subscribe((event) => modelState.event(event));
570
599
  // AgentSession alone retries a failed model response. No provider retries,
@@ -684,6 +713,10 @@ try {
684
713
  }
685
714
  if (own(message, "role") === "assistant") {
686
715
  const reason = own(message, "stopReason");
716
+ providerReason =
717
+ reason === "error"
718
+ ? describeProvider(own(message, "errorMessage"))
719
+ : "";
687
720
  terminalStopReason = [
688
721
  "pending",
689
722
  "stop",