@abelxiaoxing/cadence 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,6 +64,12 @@ Browsing, reconnecting and choosing a model alone never start the execution serv
64
64
 
65
65
  ## Messages while a reply is running
66
66
 
67
+ An ordinary browser turn starts independently of turns in other Pi sessions, even in the same directory.
68
+ **Starting** means the service has accepted the turn and is preparing it, not that it is queued or the model has replied.
69
+ You can stop it without stopping the other sessions.
70
+ Only one browser run at a time is allowed in a session.
71
+ If the owner refuses a new Send at capacity, no turn is created; your draft stays editable and nothing sends it later.
72
+
67
73
  The service accepts a further message for a reply that is still running, in one of two ways.
68
74
  A **steer** reaches the model at its next opportunity, after the tool calls in progress and before its next request, and continues the conversation as its own turn from there.
69
75
  A **queued** message waits and is sent once the reply has ended normally.
@@ -130,8 +136,8 @@ With no choice and no saved preference, Send opens the model list and continues
130
136
  Closing the picker or stopping/replacing that service ends the unsent continuation; your draft stays, and choosing a model never restarts a stopped service.
131
137
  Exiting Cadence changes mode, not your pending model choice.
132
138
  If no usable preference exists, choose once; an unreadable preference file falls back to the current Pi model, and choosing a model rewrites it.
133
- An accepted message or workflow keeps its original directory and exact model, including while queued.
134
- Different subdirectories of one repository can have independent conversations while sharing one checkout owner and execution gate.
139
+ An accepted message or workflow keeps its original directory and exact model.
140
+ Conversations in different subdirectories of one checkout share the same owner, not one working directory.
135
141
  Tools and check commands use the conversation directory; a plan's declared write paths stay relative to the displayed checkout root, including in isolated Git worktrees.
136
142
  Changing the current conversation's model makes its older unaccepted plan require fresh validation and approval in the browser, not another chat message; changing another conversation's model does not.
137
143
  An unavailable remembered model is not silently substituted.
@@ -162,7 +168,7 @@ The plan chooses one delivery policy:
162
168
  Local task commits and the merge are included in the plan approval.
163
169
  Git hooks and commit signing are disabled for these internal commits; verification is explicitly declared instead.
164
170
  No remote push occurs.
165
- - **Working copy:** explicit direct host-tool editing, serialized, including for non-Git directories.
171
+ - **Working copy:** explicit direct host-tool editing, serialized among workflows, including for non-Git directories.
166
172
  No commit or merge.
167
173
  Failed or canceled work leaves actual edits in place; this is not transactional application or a sandbox.
168
174
 
@@ -177,9 +183,10 @@ Only owned worktrees at the delivered commit, after successful post-merge checks
177
183
  Ignored setup/build output such as `node_modules` also retains the worktree; failures, cancellation and unknown outcomes never trigger cleanup.
178
184
  Separate WebUI or terminal conversations may run independent local-merge workflows concurrently, within the owner's four-active-run limit including investigations.
179
185
  A single conversation still permits only one approved implementation at a time; open another conversation for an independent goal.
180
- Target preflight and candidate creation are exclusive.
181
- Implementation, checks and automatic review then run in isolated candidates without holding the target checkout gate; working-copy edits and ordinary host-tool conversations remain exclusive.
182
- Final delivery is exclusive and serialized from candidate refresh through shared project-knowledge maintenance, post-merge checks and cleanup.
186
+ Local-merge workflows take exclusive checkout access for target preflight and candidate creation, release it during isolated implementation, checks and automatic review, then take it again from candidate refresh through shared project-knowledge maintenance, post-merge checks and cleanup.
187
+ Ordinary browser conversations do not wait for this access.
188
+ Like separate Pi terminals, they can edit the same files as each other or as a workflow.
189
+ Coordinate overlapping edits yourself: delivery rechecks the target branch, HEAD and declared paths, but these checks are not a file transaction and do not merge concurrent edits or prevent overwrites.
183
190
  There is no fixed delivery-duration or repair-round quota.
184
191
  Agents have no fixed total runtime deadline.
185
192
  Setup/check commands default to no timeout; an explicitly approved per-command timeout still applies, including in older plans.
@@ -207,7 +214,7 @@ Failed candidate/worktree setup, baseline, implementation, checks or review ente
207
214
  A failed target preflight ends without dispatching an editor into the original checkout.
208
215
  Incomplete assignment reports show `partial` or `blocked`, not a process crash; their outputs remain available, but dependencies and final delivery still require completion and real verification.
209
216
  Cadence can preserve partial outputs, split remaining work and choose alternative implementations within the approval; it never expands permissions or weakens acceptance.
210
- 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.
217
+ Transient model-request failures recover inside the original SDK worker, with visible, cancellable backoff; completed tool results stay with that worker, and a workflow stage that holds checkout access keeps it.
211
218
  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.
212
219
  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.
213
220
  An unchanged failure and identical recovery strategy cannot become an endless replay loop.
@@ -302,7 +309,7 @@ A revision may also change the assignments that have not started yet (drop, rewr
302
309
 
303
310
  The unified WebUI sidebar automatically lists active work in this account and state home, including projects you have never selected.
304
311
  An interactive terminal must load the Cadence extension: a real model/tool round appears even without `/cadence`, but an idle terminal or idle owner does not.
305
- Terminal rounds are observe-only; owner turns and workflows retain their actual queue, execution, recovery and settlement phases and existing authorized controls.
312
+ Terminal rounds are observe-only; owner turns and workflows show their actual phases (including ordinary turn startup and workflow queueing) and existing authorized controls.
306
313
  Separate terminal instances and owner work keep their own rows; work already shown under **Running work** is not repeated.
307
314
 
308
315
  Click an activity to remember its directory and read the shared Pi session at the observed branch.
@@ -45,6 +45,12 @@ cadence.example.net {
45
45
  ```
46
46
 
47
47
  Audit any additional proxy-generated forwarding headers against the exact backend policy before use.
48
+ Forward `/app`, `/assets/start.js`, `/ui/` and the API to the same Cadence instance, without shared caching or rewriting asset failures to the app HTML.
49
+ For a stale page, compare the authenticated `/app` response's `X-Cadence-Web-Build` with the `/ui/<build>/assets/cadence.js` URL in that response and the browser's loaded module.
50
+ An old entry served by a still-running process is not fixed by clearing browser data.
51
+ Do not share cookies, access codes or full authenticated network traces.
52
+ Recovery runs in the delivered page: if the proxy itself serves a 502 instead of the initial HTML, no Cadence script can retry from that document.
53
+ Never enable proxy retries for all methods to compensate; a lost command response is not permission to repeat the command.
48
54
  HTTP and WebSocket upgrade must use the same authenticated route; no public backend bypass or insecure credential-bearing HTTP.
49
55
  This example does not install Caddy, provision DNS/certificates, change a firewall or deploy a service.
50
56
 
@@ -48,7 +48,11 @@ The JSON result reports the canonical checkout, saved default cwd and endpoint;
48
48
  Keep that link private.
49
49
  Open Pi in the same project and use `/cadence` for the native client; explicit `cadence stop --workspace <path>` stops only that project.
50
50
  Opening another project never changes the cwd or cancels work in the former one.
51
- Different folders of one checkout share its owner and execution gate, but conversations keep independent directories and model choices; an admitted run keeps its original snapshot.
51
+ Different folders of one checkout share the project owner and its on-disk lease, not a queue for ordinary Sends.
52
+ Each admitted run keeps its conversation's working directory and model.
53
+ The owner allows one active browser run per Pi session and refuses new runs at capacity.
54
+ Different Pi sessions can use host tools concurrently, even while a workflow holds an exclusive checkout permit.
55
+ If two sessions, or a session and a workflow, edit the same file, either can overwrite the other's changes; see [Execution and delivery](conversation-mode.md#execution-and-delivery).
52
56
  The owner launches from the checkout root.
53
57
  A removed saved default subdirectory does not prevent other conversation directories from starting; no old conversation is redirected or rewritten.
54
58
  The default workbench routes all associated projects through one origin, including a configured HTTPS proxy.
@@ -139,11 +143,17 @@ A machine without a supported user service manager and `CADENCE_AUTOSTART=0` kee
139
143
 
140
144
  On Linux the workbench has a **Cadence service** dialog: the server button on the entry page, or **More → Cadence service** in a project.
141
145
  It shows the running version and its systemd unit, shows its installation method, asks that package manager for the latest version only when you press **Check for updates**, and offers **Restart service** and **Upgrade to VERSION**.
142
- The confirmation names the running workflows and conversations the restart stops; they stop through the orderly Stop, never by a signal.
143
- If work starts or ends before you confirm, the request is refused as stale and the dialog reads the service again.
146
+ **Upgrade to VERSION** is the final confirmation.
147
+ If workflows or conversations are running, the dialog lists each one by project and ID, and the button says **Stop work and upgrade to VERSION**.
148
+ Restart keeps its separate confirmation.
149
+ Both use orderly Stop.
150
+ If the listed work changes before you confirm, the request is refused as stale and the dialog reads the service again.
151
+ The job checks the same list again when it requests Stop, including after downloading an upgrade.
144
152
 
145
153
  The request runs outside the service, in a transient unit `cadence.maintenance.service` (`cadence-NAME.maintenance.service` for a named service), so closing or reloading the page does not interrupt it and one job runs at a time.
146
- It runs the same `cadence server restart` or `cadence server upgrade`, then records its outcome; the page waits for that record and offers to reload.
154
+ It runs the same `cadence server restart` or `cadence server upgrade`, then records its outcome.
155
+ After a successful upgrade, the requesting page reloads automatically when the target version is serving.
156
+ A restart still offers a reload; a failed, rolled-back or unconfirmed upgrade leaves the result on screen.
147
157
  If it reports nothing, see `journalctl --user -u cadence.maintenance.service` (without `--user` for a system service) and `cadence server status`.
148
158
 
149
159
  An upgrade fetches the exact release and previous version while the service still runs, so an unreachable registry changes nothing.
@@ -388,7 +398,7 @@ The next start (`cadence start`, `cadence project open`, the workbench, the back
388
398
  Cadence recovered project /home/me/app automatically: the machine restarted while Cadence was running; released its locks, continued its history after the last complete entry.
389
399
  ```
390
400
 
391
- The WebUI shows the same recovery once at the top of the page.
401
+ The WebUI recovers silently; `cadence doctor` reports the recorded recovery.
392
402
  Nothing is asked of you unless Cadence cannot prove the old process is gone.
393
403
 
394
404
  What a start does, in order:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abelxiaoxing/cadence",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
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",
@@ -2,7 +2,7 @@
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
4
  Start with existing evidence. Use cadence_knowledge to read a named project document or heading directly (the route table, AGENTS.md and the project index identify sources). Reuse recorded investigation answers from this conversation by passing their investigation ID to cadence_knowledge, which rechecks their cited files; older conclusions are leads until checked against current sources. For a directly verifiable fact, use cadence_knowledge with path and match to read the actual source line and nearby context. Read the returned results before broadening an investigation. Surface material user choices as soon as the tradeoffs are understood. Exact implementation values, selectors and file inventories ordinarily belong to implementation workers and need not delay the design or plan. Zero research runs is appropriate when evidence suffices. Use cadence_research only for unresolved questions whose answers could change the design or acceptance. Ask focused independent questions together and reuse answered results by investigation ID.
5
- For material choices about experience, scope or expensive tradeoffs, call cadence_design with one batch of real alternatives in the user's language before publishing a plan. Describe each option's cost, the recommendation and reason, and what acceptance it affects. Give stable lowercase IDs; use when for predictable dependencies on earlier options. Keep routine implementation decisions yourself. Do not invent a questionnaire for a settled task. The user can edit any question, enter other ideas, fill remaining recommendations and submit once. A submitted design or "按你推荐的来" calls for the final implementation card in the same conversation; it never authorizes execution. Respect the submitted decisions, including custom answers, throughout the plan and review.
5
+ For material choices about experience, scope or expensive tradeoffs, call cadence_design with one batch of real alternatives in the user's language before publishing a plan. Describe each option's cost, the recommendation and reason, and what acceptance it affects. Give stable lowercase IDs; omit when (or use null) unless the question depends on an earlier option. Publish the choices through the tool, not a Markdown questionnaire asking for a typed reply. If publication is refused for invalid input, correct the named field and repeat the complete batch yourself. Keep routine implementation decisions yourself. Do not invent a questionnaire for a settled task. The user can edit any question, enter other ideas, fill remaining recommendations and submit once. A submitted design or "按你推荐的来" calls for the final implementation card in the same conversation; it never authorizes execution. Respect the submitted decisions, including custom answers, throughout the plan and review.
6
6
  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. Focus on the project, its implementation and its real checks. The owner supplies private, workspace-specific TMPDIR/TEMP/TMP to every delivery command and worker, including recovery. Do not add temporary-directory setup, environment discovery, path handoff or marker checks to the plan; name the project's check command directly. This standard runtime policy is displayed with the plan and covered by its one approval. For local preparation, use cadence_knowledge with checkout: [the needed dependency directory names] to observe the original checkout, Git placement and local entries directly. Use the original entry by path if the user authorizes sharing installed dependencies; the link target and its contents are unnecessary. cadence_plan checks the actual write targets and Git commit identity. Leave those checks to the owner. Do not send researchers to enumerate Git internals, ignored dependencies or private workflow records for these facts. Worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. 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. Separate conversations may implement local-merge workflows concurrently, one per conversation; final delivery is serialized. A verified non-overlapping sibling delivery may advance a pending candidate's integration frontier and be merged into its isolated worktree, followed by fresh checks and automatic review. Only this run's confirmed merges can advance its target baseline for post-merge recovery. Conflicts, overlapping writes, changed instructions or external branch changes retain the candidate and require a fresh plan. 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.
7
7
  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.
8
8
  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.
@@ -101,11 +101,14 @@ export const DESIGN_PARAMETERS = Type.Object({
101
101
  description: "Acceptance item this decision affects",
102
102
  }),
103
103
  when: Type.Optional(
104
- Type.Object(
105
- { question: Type.String(), option: Type.String() },
104
+ Type.Union(
105
+ [
106
+ Type.Null(),
107
+ Type.Object({ question: Type.String(), option: Type.String() }),
108
+ ],
106
109
  {
107
110
  description:
108
- "Only relevant for this earlier question and selected option.",
111
+ "Omit or use null for an independent question. For a conditional question give an earlier question ID and one of its option IDs.",
109
112
  },
110
113
  ),
111
114
  ),
@@ -2,5 +2,5 @@
2
2
  export const nativeBuild = {
3
3
  kind: "native",
4
4
  contractHash:
5
- "1b833e54ac91fb9d8e570f43da35e3e2faf6c9e214bd9d1bd7cce19c2fe7f243",
5
+ "190a21e723f753a233225a9f4bcf12a99d71b294a58728961846cd110cd60a17",
6
6
  } as const;
@@ -9,6 +9,7 @@ import {
9
9
  list,
10
10
  text,
11
11
  } from "./core.ts";
12
+ import { entries, fields, issue, words } from "./workflow.ts";
12
13
 
13
14
  export interface DesignQuestion {
14
15
  id: string;
@@ -30,63 +31,91 @@ export interface DesignDraft {
30
31
  submitted: boolean;
31
32
  }
32
33
  const label = (v: unknown) => text(v, 1024, true);
33
- const key = (v: unknown) => {
34
- const s = text(v, 48, true);
34
+ const key = (v: unknown, path = "id") => {
35
+ const s = words(path, v, 48, true);
35
36
  if (!/^[a-z][a-z0-9-]*$/u.test(s))
36
- throw new Error("id: use lowercase letters, digits and hyphens");
37
+ return issue(
38
+ path,
39
+ "start with a lowercase letter; use lowercase letters, digits and hyphens",
40
+ );
37
41
  return s;
38
42
  };
39
- export function designQuestions(input: unknown): DesignQuestion[] {
40
- const { questions } = closed(input, ["questions"]);
43
+ function designQuestions(
44
+ input: unknown,
45
+ source: "tool" | "record",
46
+ ): DesignQuestion[] {
47
+ const { questions } = fields("design", input, ["questions"]);
41
48
  const seen = new Map<string, Set<string>>();
42
- const rows = list(questions, 12, (raw) => {
43
- const q = closed(raw, [
44
- "id",
45
- "question",
46
- "options",
47
- "recommended",
48
- "reason",
49
- "acceptance",
50
- ...(Object.hasOwn(raw ?? {}, "when") ? ["when"] : []),
51
- ]);
52
- const id = key(q.id);
53
- const options = list(q.options, 6, (raw) => {
54
- const o = closed(raw, ["id", "label", "cost"]);
55
- return { id: key(o.id), label: label(o.label), cost: label(o.cost) };
49
+ const rows = entries("questions", questions, 12, (raw, path) => {
50
+ const q = fields(
51
+ path,
52
+ raw,
53
+ ["id", "question", "options", "recommended", "reason", "acceptance"],
54
+ ["when"],
55
+ );
56
+ const id = key(q.id, `${path}.id`);
57
+ if (seen.has(id)) return issue(`${path}.id`, "use a distinct question ID");
58
+ const ids = new Set<string>();
59
+ const options = entries(`${path}.options`, q.options, 6, (raw, path) => {
60
+ const o = fields(path, raw, ["id", "label", "cost"]);
61
+ const id = key(o.id, `${path}.id`);
62
+ if (ids.has(id)) return issue(`${path}.id`, "use a distinct option ID");
63
+ ids.add(id);
64
+ return {
65
+ id,
66
+ label: words(`${path}.label`, o.label, 1024, true),
67
+ cost: words(`${path}.cost`, o.cost, 1024, true),
68
+ };
56
69
  });
57
- const ids = new Set(options.map((o) => o.id));
58
- const recommended = key(q.recommended);
59
- if (
60
- seen.has(id) ||
61
- ids.size !== options.length ||
62
- ids.size < 2 ||
63
- !ids.has(recommended)
64
- )
65
- throw new Error(
66
- "questions: use distinct question and option IDs and identify one recommended option",
67
- );
68
- const dep =
69
- q.when === undefined ? null : closed(q.when, ["question", "option"]);
70
- const when = dep && {
71
- question: key(dep.question),
72
- option: key(dep.option),
73
- };
74
- if (when && !seen.get(when.question)?.has(when.option))
75
- throw new Error("when: name an option of an earlier question");
70
+ if (options.length < 2)
71
+ return issue(`${path}.options`, "supply at least two alternatives");
72
+ const recommended = key(q.recommended, `${path}.recommended`);
73
+ if (!ids.has(recommended))
74
+ return issue(`${path}.recommended`, "name an option ID of this question");
75
+ // Some providers populate optional objects even for independent questions.
76
+ // Only an unambiguous no-dependency value may disappear at tool ingress.
77
+ let when: DesignQuestion["when"];
78
+ if (q.when !== undefined && !(source === "tool" && q.when === null)) {
79
+ const dep = fields(`${path}.when`, q.when, ["question", "option"]);
80
+ if (!(source === "tool" && dep.question === "" && dep.option === "")) {
81
+ const question = key(dep.question, `${path}.when.question`);
82
+ if (!seen.has(question))
83
+ return issue(
84
+ `${path}.when.question`,
85
+ "name an earlier question, or omit when for an independent question",
86
+ );
87
+ const option = key(dep.option, `${path}.when.option`);
88
+ if (!seen.get(question)?.has(option))
89
+ return issue(
90
+ `${path}.when.option`,
91
+ "name an option ID of the earlier question",
92
+ );
93
+ when = { question, option };
94
+ }
95
+ }
76
96
  seen.set(id, ids);
77
97
  return {
78
98
  id,
79
- question: label(q.question),
99
+ question: words(`${path}.question`, q.question, 1024, true),
80
100
  options,
81
101
  recommended,
82
- reason: label(q.reason),
83
- acceptance: label(q.acceptance),
102
+ reason: words(`${path}.reason`, q.reason, 1024, true),
103
+ acceptance: words(`${path}.acceptance`, q.acceptance, 1024, true),
84
104
  ...(when ? { when } : {}),
85
105
  };
86
106
  });
87
107
  if (!rows.length)
88
108
  throw new Error("questions: supply a material product decision");
89
- canonicalJson(rows, 24 * 1024);
109
+ try {
110
+ canonicalJson(rows, 24 * 1024);
111
+ } catch (error) {
112
+ if (!(error instanceof ContractError) || error.code !== "oversize")
113
+ throw error;
114
+ return issue(
115
+ "questions",
116
+ "the complete batch must fit in 24 KiB of encoded JSON",
117
+ );
118
+ }
90
119
  return rows;
91
120
  }
92
121
  export function designAnswers(v: unknown): DesignAnswer[] {
@@ -134,7 +163,7 @@ export function selectDesign(
134
163
  }
135
164
  export function decodeDesign(v: unknown): DesignDraft {
136
165
  const o = closed(v, ["id", "revision", "questions", "answers", "submitted"]);
137
- const questions = designQuestions({ questions: o.questions });
166
+ const questions = designQuestions({ questions: o.questions }, "record");
138
167
  const submitted = bool(o.submitted);
139
168
  const answers = designAnswers(o.answers);
140
169
  if (
@@ -155,7 +184,7 @@ export function newDesign(
155
184
  input: unknown,
156
185
  previous?: DesignDraft,
157
186
  ): DesignDraft {
158
- const questions = designQuestions(input);
187
+ const questions = designQuestions(input, "tool");
159
188
  const retained =
160
189
  previous?.answers.filter((a) => {
161
190
  const before = previous.questions.find((q) => q.id === a.question);
@@ -48,6 +48,18 @@ import {
48
48
  type WorkflowRun,
49
49
  } from "./workflow.ts";
50
50
 
51
+ /** Response header on an authenticated workbench project observation. Separate
52
+ * from the closed JSON body (owner status/epoch). An associated project may
53
+ * request a session when running; association alone is not an attachment. */
54
+ export const PROJECT_ASSOCIATION_HEADER = "x-cadence-project-association";
55
+ export function decodeProjectAssociation(value: unknown) {
56
+ // Older gateways do not report this fact. Missing evidence is neither a
57
+ // successful attachment nor proof that an owner is independent.
58
+ return value === null || value === undefined
59
+ ? "unknown"
60
+ : oneOf(value, ["associated", "unassociated"]);
61
+ }
62
+
51
63
  export interface CadenceConversation {
52
64
  design?: DesignDraft;
53
65
  id: string;
@@ -366,14 +378,21 @@ export type WorkbenchCommand =
366
378
  archived: boolean;
367
379
  }
368
380
  | { kind: "open-project"; commandId: string; path: string; epoch: string };
369
- export type ChatStatus =
370
- | "queued"
371
- | "running"
372
- | "completed"
373
- | "failed"
374
- | "canceled"
375
- | "timeout"
376
- | "unknown";
381
+ /** A workflow transcript retains its own lifecycle; only an ordinary Send
382
+ * starts in preparation rather than queued. */
383
+ const workflowTurnStatuses = [
384
+ "queued",
385
+ "running",
386
+ "completed",
387
+ "failed",
388
+ "canceled",
389
+ "timeout",
390
+ "unknown",
391
+ ] as const;
392
+ export const CHAT_STATUSES = ["starting", ...workflowTurnStatuses] as const;
393
+ export type ChatStatus = (typeof CHAT_STATUSES)[number];
394
+ export const isLiveChatStatus = (status: ChatStatus) =>
395
+ status === "starting" || status === "queued" || status === "running";
377
396
  export interface ChatImage {
378
397
  live?: true;
379
398
  /** Pi entry ID, or the admitted command ID until Pi flushes its user entry. */
@@ -418,7 +437,7 @@ export interface ChatTurn {
418
437
  retry?: ModelRetry;
419
438
  id: string;
420
439
  epoch: string;
421
- status: ChatStatus;
440
+ status: (typeof workflowTurnStatuses)[number];
422
441
  items: ChatItem[];
423
442
  notice: string;
424
443
  /** Immutable full-transcript pages; items above are only the latest preview. */
@@ -752,15 +771,6 @@ export interface WorkbenchPort {
752
771
  },
753
772
  ): WorkbenchResult | Promise<WorkbenchResult>;
754
773
  }
755
- const statuses = [
756
- "queued",
757
- "running",
758
- "completed",
759
- "failed",
760
- "canceled",
761
- "timeout",
762
- "unknown",
763
- ] as const;
764
774
  export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
765
775
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
766
776
  switch (kind) {
@@ -1257,7 +1267,7 @@ export function decodeChatTurn(v: unknown): ChatTurn {
1257
1267
  ...(o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) }),
1258
1268
  id: decodeId(o.id),
1259
1269
  epoch: decodeId(o.epoch),
1260
- status: oneOf(o.status, statuses),
1270
+ status: oneOf(o.status, workflowTurnStatuses),
1261
1271
  notice: text(o.notice, 1024),
1262
1272
  ...(transcript
1263
1273
  ? { transcript: { pages: integer(transcript.pages, 0) } }
@@ -1441,7 +1451,7 @@ function decodeChatTurnHeader(v: unknown): ChatTurnHeader {
1441
1451
  ? {}
1442
1452
  : { parent: nullable(o.parent, decodeEntryId) }),
1443
1453
  at: integer(o.at, 0),
1444
- status: oneOf(o.status, statuses),
1454
+ status: oneOf(o.status, CHAT_STATUSES),
1445
1455
  notice: text(o.notice, 1024),
1446
1456
  omitted: {
1447
1457
  thinking: bool(omitted.thinking),
@@ -1473,7 +1483,7 @@ export function decodeChatSummary(v: unknown): ChatSummary {
1473
1483
  id: decodeSessionId(o.id),
1474
1484
  title: text(o.title, 512, true),
1475
1485
  leaf: nullable(o.leaf, decodeEntryId),
1476
- status: oneOf(o.status, statuses),
1486
+ status: oneOf(o.status, CHAT_STATUSES),
1477
1487
  updatedAt: integer(o.updatedAt, 0),
1478
1488
  origin: oneOf(o.origin, ["terminal", "webui"]),
1479
1489
  ...(has("cadence") ? { cadence: bool(o.cadence) } : {}),
@@ -1493,7 +1503,7 @@ function decodeChatAttempt(v: unknown): ChatAttempt {
1493
1503
  return {
1494
1504
  commandId: decodeId(o.commandId),
1495
1505
  text: text(o.text, 16 * 1024),
1496
- status: oneOf(o.status, statuses),
1506
+ status: oneOf(o.status, CHAT_STATUSES),
1497
1507
  notice: text(o.notice, 1024),
1498
1508
  };
1499
1509
  }
@@ -324,7 +324,7 @@ export type WorkflowResponse =
324
324
  /** A plan or an investigation request that its author can correct: the message
325
325
  * names the field, what it holds and what is accepted there. */
326
326
  export class WorkflowInputError extends Error {}
327
- function issue(path: string, problem: string): never {
327
+ export function issue(path: string, problem: string): never {
328
328
  throw new WorkflowInputError(`${path}: ${problem}`);
329
329
  }
330
330
  const quoted = (value: string) => JSON.stringify(clipUnits(value, 80));
@@ -346,7 +346,7 @@ function at<T>(path: string, read: () => T): T {
346
346
  );
347
347
  }
348
348
  }
349
- function words(
349
+ export function words(
350
350
  path: string,
351
351
  v: unknown,
352
352
  maximum: number,
@@ -360,7 +360,7 @@ function words(
360
360
  return issue(path, `is ${bytes} bytes; at most ${maximum}`);
361
361
  return at(path, () => text(v, maximum, nonempty));
362
362
  }
363
- function entries<T>(
363
+ export function entries<T>(
364
364
  path: string,
365
365
  v: unknown,
366
366
  maximum: number,
@@ -375,7 +375,7 @@ function entries<T>(
375
375
  );
376
376
  }
377
377
  /** A closed object: every required field present, nothing unknown. */
378
- function fields(
378
+ export function fields(
379
379
  path: string,
380
380
  v: unknown,
381
381
  required: readonly string[],