zelio-cli 0.0.0-stage → 0.1.0-beta.10
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.md +71 -2
- package/dist/attachments.js +121 -0
- package/dist/attachments.js.map +1 -0
- package/dist/cli-main.js +521 -0
- package/dist/cli-main.js.map +1 -0
- package/dist/cli.js +22 -0
- package/dist/cli.js.map +1 -0
- package/dist/cloud/account.js +109 -0
- package/dist/cloud/account.js.map +1 -0
- package/dist/cloud/board.js +311 -0
- package/dist/cloud/board.js.map +1 -0
- package/dist/cloud/command.js +265 -0
- package/dist/cloud/command.js.map +1 -0
- package/dist/cloud/config.js +132 -0
- package/dist/cloud/config.js.map +1 -0
- package/dist/cloud/credentials.js +134 -0
- package/dist/cloud/credentials.js.map +1 -0
- package/dist/cloud/login.js +166 -0
- package/dist/cloud/login.js.map +1 -0
- package/dist/cloud/pair.js +110 -0
- package/dist/cloud/pair.js.map +1 -0
- package/dist/cloud/pkce.js +16 -0
- package/dist/cloud/pkce.js.map +1 -0
- package/dist/cloud/push-nudge.js +65 -0
- package/dist/cloud/push-nudge.js.map +1 -0
- package/dist/cloud/relay.js +134 -0
- package/dist/cloud/relay.js.map +1 -0
- package/dist/cloud/token.js +66 -0
- package/dist/cloud/token.js.map +1 -0
- package/dist/cloud/tunnel.js +474 -0
- package/dist/cloud/tunnel.js.map +1 -0
- package/dist/db/db.js +1838 -0
- package/dist/db/db.js.map +1 -0
- package/dist/db/lifecycle.js +146 -0
- package/dist/db/lifecycle.js.map +1 -0
- package/dist/limits.js +35 -0
- package/dist/limits.js.map +1 -0
- package/dist/metrics.js +30 -0
- package/dist/metrics.js.map +1 -0
- package/dist/orchestrator/area-notes.js +87 -0
- package/dist/orchestrator/area-notes.js.map +1 -0
- package/dist/orchestrator/claude-session.js +208 -0
- package/dist/orchestrator/claude-session.js.map +1 -0
- package/dist/orchestrator/codex-session.js +327 -0
- package/dist/orchestrator/codex-session.js.map +1 -0
- package/dist/orchestrator/contract.js +189 -0
- package/dist/orchestrator/contract.js.map +1 -0
- package/dist/orchestrator/explore.js +176 -0
- package/dist/orchestrator/explore.js.map +1 -0
- package/dist/orchestrator/new-task-prompt.js +51 -0
- package/dist/orchestrator/new-task-prompt.js.map +1 -0
- package/dist/orchestrator/pi-session.js +234 -0
- package/dist/orchestrator/pi-session.js.map +1 -0
- package/dist/orchestrator/prompt.js +110 -0
- package/dist/orchestrator/prompt.js.map +1 -0
- package/dist/orchestrator/research.js +193 -0
- package/dist/orchestrator/research.js.map +1 -0
- package/dist/orchestrator/retrieval.js +333 -0
- package/dist/orchestrator/retrieval.js.map +1 -0
- package/dist/orchestrator/runtime.js +1217 -0
- package/dist/orchestrator/runtime.js.map +1 -0
- package/dist/orchestrator/session.js +2 -0
- package/dist/orchestrator/session.js.map +1 -0
- package/dist/orchestrator/types.js +2 -0
- package/dist/orchestrator/types.js.map +1 -0
- package/dist/orchestrator/web.js +276 -0
- package/dist/orchestrator/web.js.map +1 -0
- package/dist/repo/code-map.js +152 -0
- package/dist/repo/code-map.js.map +1 -0
- package/dist/repo/index.js +188 -0
- package/dist/repo/index.js.map +1 -0
- package/dist/repo/instructions.js +58 -0
- package/dist/repo/instructions.js.map +1 -0
- package/dist/repo/linked-boards.js +149 -0
- package/dist/repo/linked-boards.js.map +1 -0
- package/dist/repo/project-repos.js +78 -0
- package/dist/repo/project-repos.js.map +1 -0
- package/dist/run/actions.js +257 -0
- package/dist/run/actions.js.map +1 -0
- package/dist/run/auto-review.js +116 -0
- package/dist/run/auto-review.js.map +1 -0
- package/dist/run/bash-guard.js +183 -0
- package/dist/run/bash-guard.js.map +1 -0
- package/dist/run/claude-runtime.js +284 -0
- package/dist/run/claude-runtime.js.map +1 -0
- package/dist/run/claude-stream.js +306 -0
- package/dist/run/claude-stream.js.map +1 -0
- package/dist/run/codex-client.js +213 -0
- package/dist/run/codex-client.js.map +1 -0
- package/dist/run/codex-planner-config.js +26 -0
- package/dist/run/codex-planner-config.js.map +1 -0
- package/dist/run/codex-runtime.js +469 -0
- package/dist/run/codex-runtime.js.map +1 -0
- package/dist/run/consult.js +109 -0
- package/dist/run/consult.js.map +1 -0
- package/dist/run/context.js +87 -0
- package/dist/run/context.js.map +1 -0
- package/dist/run/developer-sandbox.js +67 -0
- package/dist/run/developer-sandbox.js.map +1 -0
- package/dist/run/diff.js +238 -0
- package/dist/run/diff.js.map +1 -0
- package/dist/run/evidence.js +48 -0
- package/dist/run/evidence.js.map +1 -0
- package/dist/run/finish.js +430 -0
- package/dist/run/finish.js.map +1 -0
- package/dist/run/handoff.js +51 -0
- package/dist/run/handoff.js.map +1 -0
- package/dist/run/harness-runtime.js +31 -0
- package/dist/run/harness-runtime.js.map +1 -0
- package/dist/run/harnesses.js +293 -0
- package/dist/run/harnesses.js.map +1 -0
- package/dist/run/issue.js +79 -0
- package/dist/run/issue.js.map +1 -0
- package/dist/run/keep-awake.js +58 -0
- package/dist/run/keep-awake.js.map +1 -0
- package/dist/run/lead.js +183 -0
- package/dist/run/lead.js.map +1 -0
- package/dist/run/manager.js +2737 -0
- package/dist/run/manager.js.map +1 -0
- package/dist/run/mentions.js +35 -0
- package/dist/run/mentions.js.map +1 -0
- package/dist/run/merge-watch.js +425 -0
- package/dist/run/merge-watch.js.map +1 -0
- package/dist/run/models.js +88 -0
- package/dist/run/models.js.map +1 -0
- package/dist/run/phases.js +23 -0
- package/dist/run/phases.js.map +1 -0
- package/dist/run/pi-packages.js +72 -0
- package/dist/run/pi-packages.js.map +1 -0
- package/dist/run/pi-rpc.js +464 -0
- package/dist/run/pi-rpc.js.map +1 -0
- package/dist/run/piped-check.js +56 -0
- package/dist/run/piped-check.js.map +1 -0
- package/dist/run/pr-checks.js +67 -0
- package/dist/run/pr-checks.js.map +1 -0
- package/dist/run/pr-merge.js +121 -0
- package/dist/run/pr-merge.js.map +1 -0
- package/dist/run/profiles.js +43 -0
- package/dist/run/profiles.js.map +1 -0
- package/dist/run/prompt.js +405 -0
- package/dist/run/prompt.js.map +1 -0
- package/dist/run/pull-request.js +23 -0
- package/dist/run/pull-request.js.map +1 -0
- package/dist/run/red-check.js +130 -0
- package/dist/run/red-check.js.map +1 -0
- package/dist/run/result-tool.js +93 -0
- package/dist/run/result-tool.js.map +1 -0
- package/dist/run/result.js +113 -0
- package/dist/run/result.js.map +1 -0
- package/dist/run/retro.js +346 -0
- package/dist/run/retro.js.map +1 -0
- package/dist/run/settings.js +28 -0
- package/dist/run/settings.js.map +1 -0
- package/dist/run/skills.js +146 -0
- package/dist/run/skills.js.map +1 -0
- package/dist/run/tests-first.js +146 -0
- package/dist/run/tests-first.js.map +1 -0
- package/dist/run/thinking.js +41 -0
- package/dist/run/thinking.js.map +1 -0
- package/dist/run/types.js +2 -0
- package/dist/run/types.js.map +1 -0
- package/dist/run/watchdog.js +266 -0
- package/dist/run/watchdog.js.map +1 -0
- package/dist/run/workflow.js +277 -0
- package/dist/run/workflow.js.map +1 -0
- package/dist/run/worktree.js +354 -0
- package/dist/run/worktree.js.map +1 -0
- package/dist/server/app.js +3286 -0
- package/dist/server/app.js.map +1 -0
- package/dist/server/auth.js +93 -0
- package/dist/server/auth.js.map +1 -0
- package/dist/server/demo.js +96 -0
- package/dist/server/demo.js.map +1 -0
- package/dist/server/idempotency.js +104 -0
- package/dist/server/idempotency.js.map +1 -0
- package/dist/server/port.js +36 -0
- package/dist/server/port.js.map +1 -0
- package/dist/server/principal.js +93 -0
- package/dist/server/principal.js.map +1 -0
- package/dist/server/provider-auth.js +206 -0
- package/dist/server/provider-auth.js.map +1 -0
- package/dist/server/repo-picker.js +18 -0
- package/dist/server/repo-picker.js.map +1 -0
- package/dist/server/terminal.js +285 -0
- package/dist/server/terminal.js.map +1 -0
- package/dist/setup/components.js +98 -0
- package/dist/setup/components.js.map +1 -0
- package/dist/setup/config.js +71 -0
- package/dist/setup/config.js.map +1 -0
- package/dist/setup/ink-ui.js +189 -0
- package/dist/setup/ink-ui.js.map +1 -0
- package/dist/setup/onboarding.js +157 -0
- package/dist/setup/onboarding.js.map +1 -0
- package/dist/setup/run.js +69 -0
- package/dist/setup/run.js.map +1 -0
- package/dist/skills.js +151 -0
- package/dist/skills.js.map +1 -0
- package/dist/ticket-cli.js +157 -0
- package/dist/ticket-cli.js.map +1 -0
- package/dist/version.js +13 -0
- package/dist/version.js.map +1 -0
- package/dist/voice/index.js +69 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/voice/moonshine.js +247 -0
- package/dist/voice/moonshine.js.map +1 -0
- package/dist/voice/wav.js +54 -0
- package/dist/voice/wav.js.map +1 -0
- package/dist/voice/whisper.js +491 -0
- package/dist/voice/whisper.js.map +1 -0
- package/dist/web/assets/index-TN5sUF2z.css +1 -0
- package/dist/web/assets/index-vB3Cucuc.js +258 -0
- package/dist/web/icons/apple-touch-icon.png +0 -0
- package/dist/web/icons/icon-192.png +0 -0
- package/dist/web/icons/icon-512.png +0 -0
- package/dist/web/icons/maskable-512.png +0 -0
- package/dist/web/index.html +21 -0
- package/dist/web/manifest.webmanifest +30 -0
- package/dist/web/sw.js +185 -0
- package/media/board.png +0 -0
- package/media/mobile.png +0 -0
- package/media/new-task.png +0 -0
- package/media/review.png +0 -0
- package/package.json +105 -4
|
@@ -0,0 +1,1217 @@
|
|
|
1
|
+
import { absoluteAttachments } from "../attachments.js";
|
|
2
|
+
import { normaliseVerify } from "../db/db.js";
|
|
3
|
+
import { actionDetail, finishAction, startAction } from "../run/actions.js";
|
|
4
|
+
import { resolveThinkingLevel, parseThinkingLevel } from "../run/thinking.js";
|
|
5
|
+
import { renderWorkflowBrief } from "../run/workflow.js";
|
|
6
|
+
import { normaliseCardSkills } from "../run/skills.js";
|
|
7
|
+
import { NEW_TASK_INTAKE_PROMPT, NEW_TASK_PROMPT } from "./new-task-prompt.js";
|
|
8
|
+
import { MAX_CARD_CHECKS, MAX_CARD_CONTEXT, MAX_CONTEXT_CHARS, acceptanceChecks, } from "./contract.js";
|
|
9
|
+
import { ORCHESTRATOR_PROMPT, SUMMARY_PROMPT } from "./prompt.js";
|
|
10
|
+
import { PiPlannerSession } from "./pi-session.js";
|
|
11
|
+
import { MAX_RESEARCH, normaliseResearch as normaliseResearchQuestions } from "./research.js";
|
|
12
|
+
/** Research questions are parsed by the module that runs them. */
|
|
13
|
+
export { MAX_RESEARCH, normaliseResearchQuestions };
|
|
14
|
+
export { toolLabel } from "./pi-session.js";
|
|
15
|
+
/**
|
|
16
|
+
* Runs the orchestrator as a subprocess and returns its plan.
|
|
17
|
+
*
|
|
18
|
+
* Everything here is deliberately boring: one turn, one JSON block, a hard
|
|
19
|
+
* timeout, and a read-only toolset. The agent that plans must never be able to
|
|
20
|
+
* write to the repo — the whole design rests on planning and doing being
|
|
21
|
+
* different agents.
|
|
22
|
+
*/
|
|
23
|
+
export class OrchestratorError extends Error {
|
|
24
|
+
kind;
|
|
25
|
+
/**
|
|
26
|
+
* What the model wrote, when the failure is in that text. The planner runs on
|
|
27
|
+
* an ephemeral session, so this is the only copy: without it an unreadable
|
|
28
|
+
* block can be described but never looked at.
|
|
29
|
+
*/
|
|
30
|
+
output;
|
|
31
|
+
constructor(kind, message, output) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "OrchestratorError";
|
|
34
|
+
this.kind = kind;
|
|
35
|
+
this.output = output ?? null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Nothing ran: a turn served by an injected planner in a test. */
|
|
39
|
+
export const EMPTY_TURN_STATS = {
|
|
40
|
+
firstEventMs: null,
|
|
41
|
+
harnessMs: 0,
|
|
42
|
+
toolCalls: 0,
|
|
43
|
+
toolErrors: 0,
|
|
44
|
+
promptChars: 0,
|
|
45
|
+
outputChars: 0,
|
|
46
|
+
toolBudget: 0,
|
|
47
|
+
capped: null,
|
|
48
|
+
};
|
|
49
|
+
/** A planning pass the caller did not give a clock to. The board always does. */
|
|
50
|
+
export const PLANNER_TIMEOUT_MS = 240_000;
|
|
51
|
+
/** A summary is allowed to take a while, but never as long as a planning turn. */
|
|
52
|
+
export const SUMMARY_TIMEOUT_MS = 30_000;
|
|
53
|
+
export const MAX_CARDS = 7;
|
|
54
|
+
/**
|
|
55
|
+
* How many tool calls a panel turn gets.
|
|
56
|
+
*
|
|
57
|
+
* Ten, because the measured number was 17 and 32 at 2-3s per round, and nothing
|
|
58
|
+
* in the turn told the planner it was spending anything. Six or seven reads plus
|
|
59
|
+
* a couple of searches is what a card actually cites; the rest was the planner
|
|
60
|
+
* looking around. Short enough that the turn has a ceiling instead of a timeout.
|
|
61
|
+
*/
|
|
62
|
+
export const DEFAULT_TOOL_BUDGET = 10;
|
|
63
|
+
/**
|
|
64
|
+
* The intake pass reads nothing: the description and the repo index decide
|
|
65
|
+
* whether to ask. The scouts that read the repo started with the request.
|
|
66
|
+
*/
|
|
67
|
+
export const DEFAULT_INTAKE_TOOL_BUDGET = 0;
|
|
68
|
+
/**
|
|
69
|
+
* The draft pass with no research: the wizard reads the repo itself, so it
|
|
70
|
+
* needs the room to trace a change end to end. Twelve, down from thirty, because
|
|
71
|
+
* the scouts now do the wide reading and the draft confirms what it cites.
|
|
72
|
+
*/
|
|
73
|
+
export const DEFAULT_NEW_TASK_TOOL_BUDGET = 12;
|
|
74
|
+
/**
|
|
75
|
+
* The draft pass when every scout answered: the findings are the wide reading,
|
|
76
|
+
* so the draft only confirms what it cites and traces what they left open. Two
|
|
77
|
+
* was too few to do either — a draft that found a second cause had to write the
|
|
78
|
+
* card from a guess — and the whole turn uses well under half its deadline.
|
|
79
|
+
*/
|
|
80
|
+
export const DRAFT_WITH_RESEARCH_TOOL_BUDGET = 6;
|
|
81
|
+
/**
|
|
82
|
+
* Whether the scouts did the reading the short draft budget assumes. One failed
|
|
83
|
+
* or timed-out scout leaves a hole the draft has to read for itself, so it gets
|
|
84
|
+
* the full budget, the same as a draft with no scouts at all.
|
|
85
|
+
*/
|
|
86
|
+
export function researchComplete(findings) {
|
|
87
|
+
return (findings.length > 0 &&
|
|
88
|
+
findings.every((finding) => finding.error === null && finding.answer.trim().length > 0));
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The intake pass is a short decision, not the expensive reading. Its thinking
|
|
92
|
+
* is capped here so five calls do not each spend a long reasoning round.
|
|
93
|
+
*/
|
|
94
|
+
export const INTAKE_THINKING_CAP = "medium";
|
|
95
|
+
/** Extra tool calls a stopped turn may make before the process is killed. */
|
|
96
|
+
const BUDGET_OVERTUN = 3;
|
|
97
|
+
/**
|
|
98
|
+
* A configured budget wins; a bad value is a startup error rather than a silent
|
|
99
|
+
* fallback, because a typo would otherwise leave the planner unbounded. Zero is
|
|
100
|
+
* not a typo: it turns the budget off.
|
|
101
|
+
*/
|
|
102
|
+
export function resolveToolBudget(value, source, fallback) {
|
|
103
|
+
if (!value?.trim())
|
|
104
|
+
return fallback;
|
|
105
|
+
const budget = Number(value.trim());
|
|
106
|
+
if (!Number.isInteger(budget) || budget < 0) {
|
|
107
|
+
throw new Error(`${source} must be a whole number of tool calls (0 turns it off), got "${value}"`);
|
|
108
|
+
}
|
|
109
|
+
return budget;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The door decides the ceiling.
|
|
113
|
+
*
|
|
114
|
+
* An explicit budget (a CLI flag, or a test) wins for every door. Otherwise each
|
|
115
|
+
* door reads its own env var and falls back to its own default, so raising the
|
|
116
|
+
* wizard's room does not also raise the chat's. The draft door's default depends
|
|
117
|
+
* on whether scouts ran first.
|
|
118
|
+
*/
|
|
119
|
+
export function resolvePlannerBudget(mode, configured, hasResearch = false) {
|
|
120
|
+
if (mode === "intake")
|
|
121
|
+
return DEFAULT_INTAKE_TOOL_BUDGET;
|
|
122
|
+
if (configured !== undefined)
|
|
123
|
+
return configured;
|
|
124
|
+
if (mode === "new-task") {
|
|
125
|
+
return resolveToolBudget(process.env.ZELIO_NEW_TASK_BUDGET, "ZELIO_NEW_TASK_BUDGET", hasResearch ? DRAFT_WITH_RESEARCH_TOOL_BUDGET : DEFAULT_NEW_TASK_TOOL_BUDGET);
|
|
126
|
+
}
|
|
127
|
+
return resolveToolBudget(process.env.ZELIO_PLANNER_BUDGET, "ZELIO_PLANNER_BUDGET", DEFAULT_TOOL_BUDGET);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* The budget, said in the prompt as well as enforced in the loop.
|
|
131
|
+
*
|
|
132
|
+
* A limit the model cannot see is a trap: it spends its last round opening a
|
|
133
|
+
* file it does not need and then has no turn left to write the card. The number
|
|
134
|
+
* up front is what makes it spend the first rounds on evidence instead.
|
|
135
|
+
*/
|
|
136
|
+
export function renderBudget(budget) {
|
|
137
|
+
if (budget <= 0)
|
|
138
|
+
return "";
|
|
139
|
+
return `<budget tool-calls="${budget}">
|
|
140
|
+
You have ${budget} tool calls this turn. Spend them on what a card will have to cite — the file it names, the route, the table — not on a tour: the index above already carries the file list, the scripts and the README.
|
|
141
|
+
|
|
142
|
+
A ceiling is not a target. A change confined to one file and its test needs two or three reads; a store, a route and a screen needs the path traced end to end. Stop when the next file would not change a field of the card.
|
|
143
|
+
|
|
144
|
+
At ${budget} the turn stops. Write the block from what you have read, and put every file you did not open in \`assumed\` as "field: what you assumed". Arriving at the budget with honest flags is this door working; arriving with no card is it failing.
|
|
145
|
+
</budget>`;
|
|
146
|
+
}
|
|
147
|
+
/** Sent mid-turn, so the model reads it as the next thing the person said. */
|
|
148
|
+
export const BUDGET_STEER = `You have used all of this turn's tool calls. Do not call another tool. Write the json block now, from what you have already read, and put every file you did not open in \`assumed\` as "field: what you assumed". If likely_files is a guess, say so there.`;
|
|
149
|
+
/**
|
|
150
|
+
* How much of a pass is left when the planner is told to write the block.
|
|
151
|
+
* A tail, not a share of the time: a turn that finishes on its own is never
|
|
152
|
+
* nudged, and only one about to be cut off is asked to wrap up.
|
|
153
|
+
*/
|
|
154
|
+
export const CLOCK_STEER_TAIL_MS = 35_000;
|
|
155
|
+
/**
|
|
156
|
+
* How much of a pass is left when a turn that still has no block is stopped
|
|
157
|
+
* and asked, without tools, to write it from what it read. The pass's deadline
|
|
158
|
+
* is the person's wait, so the wrap-up has to fit inside it, not after it.
|
|
159
|
+
*/
|
|
160
|
+
export const CLOCK_STOP_TAIL_MS = 20_000;
|
|
161
|
+
/** When into a pass a turn with no block is stopped. A short pass keeps its last quarter. */
|
|
162
|
+
export function clockStopDelay(timeoutMs) {
|
|
163
|
+
return Math.max(timeoutMs - CLOCK_STOP_TAIL_MS, timeoutMs * 0.75);
|
|
164
|
+
}
|
|
165
|
+
/** When into a pass the warning goes out. A short pass is warned at its midpoint, not at once. */
|
|
166
|
+
export function clockSteerDelay(timeoutMs) {
|
|
167
|
+
return Math.max(timeoutMs - CLOCK_STEER_TAIL_MS, timeoutMs * 0.5);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The wall clock, said in the prompt as the tool budget is.
|
|
171
|
+
*
|
|
172
|
+
* The limit is not lowered by saying it. A turn that cannot see its clock reads
|
|
173
|
+
* a fourth file, thinks a fifth time, and is cut off with the card unwritten;
|
|
174
|
+
* one that can see it spends the first minutes on evidence and keeps the last
|
|
175
|
+
* for the block. A screenshot makes both passes slower, so this is the turn
|
|
176
|
+
* that most needs to know.
|
|
177
|
+
*/
|
|
178
|
+
export function renderClock(timeoutMs) {
|
|
179
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
|
|
180
|
+
return "";
|
|
181
|
+
const seconds = Math.max(1, Math.round(timeoutMs / 1000));
|
|
182
|
+
const tail = Math.round((timeoutMs - clockSteerDelay(timeoutMs)) / 1000);
|
|
183
|
+
return `<clock seconds="${seconds}">
|
|
184
|
+
You are planning this ticket against a wall clock of ${seconds} seconds, so balance quality and speed. Read what the card has to cite and think as much as it needs, no more: do not rush a card that needs evidence, and do not tour the repo for one that does not. A screenshot makes each model call slower.
|
|
185
|
+
|
|
186
|
+
If the turn is still going with about ${tail} seconds left you will be asked to write the block. Do it then, from what you have read, and put every file you did not open in \`assumed\`. If there is still no block near the end, the turn is stopped and you write it without tools; a card with honest flags beats no card.
|
|
187
|
+
</clock>`;
|
|
188
|
+
}
|
|
189
|
+
/** Sent mid-turn when the clock is mostly spent, so the model reads it as the person speaking. */
|
|
190
|
+
export const CLOCK_STEER = `Most of this turn's time is spent. Do not start another read or another round of thinking. Write the json block now, from what you have already read, and put every file you did not open in \`assumed\` as "field: what you assumed".`;
|
|
191
|
+
/**
|
|
192
|
+
* The second prompt when a stopped turn still has no block. The process keeps
|
|
193
|
+
* the whole conversation — every tool result it already paid for — so this is
|
|
194
|
+
* one model call, not a second tour of the repo.
|
|
195
|
+
*/
|
|
196
|
+
export const BUDGET_WRAPUP = `The turn hit its tool budget and was stopped before it wrote the block. Write the json block now, from the conversation above. Do not call a tool. Every field you did not verify goes in \`assumed\`.`;
|
|
197
|
+
/** The same second prompt when it was the clock, not the budget, that stopped the turn. */
|
|
198
|
+
export const CLOCK_WRAPUP = `The turn ran out of time and was stopped before it wrote the block. Write the json block now, from the conversation above, briefly. Do not call a tool and do not think at length. Every field you did not verify goes in \`assumed\`.`;
|
|
199
|
+
export function buildPrompt(messages, brief = "", plan = null, board = [], handoff = null, mode, budget = 0, workflow = null, attachments = [], research = [], clockMs = 0, linkedBoards = [], developer = null) {
|
|
200
|
+
// Notes are records for the panel (a handoff divider), not things either
|
|
201
|
+
// person said. They are stored in the transcript but not replayed as speech.
|
|
202
|
+
const conversation = messages.filter((message) => message.kind !== "note");
|
|
203
|
+
const last = conversation.at(-1);
|
|
204
|
+
const opening = last?.content ?? "";
|
|
205
|
+
const transcript = conversation.length <= 1
|
|
206
|
+
? opening
|
|
207
|
+
: `Conversation so far:\n\n${conversation
|
|
208
|
+
.map((message) => `${message.role === "user" ? "Person" : "You"}: ${message.content}`)
|
|
209
|
+
.join("\n\n")}\n\nRespond to the last message. Keep every earlier constraint.`;
|
|
210
|
+
const parts = [];
|
|
211
|
+
const carried = renderHandoff(typeof handoff === "string" ? { summary: handoff, conversationId: "earlier" } : handoff);
|
|
212
|
+
if (carried)
|
|
213
|
+
parts.push(carried);
|
|
214
|
+
parts.push(transcript);
|
|
215
|
+
const draft = plan ? renderDraft(plan) : "";
|
|
216
|
+
if (draft)
|
|
217
|
+
parts.push(draft);
|
|
218
|
+
const tickets = renderBoard(board);
|
|
219
|
+
if (tickets)
|
|
220
|
+
parts.push(tickets);
|
|
221
|
+
const findings = mode === "new-task" ? renderResearch(research) : "";
|
|
222
|
+
if (findings)
|
|
223
|
+
parts.push(findings);
|
|
224
|
+
const linked = renderLinkedBoards(mode, linkedBoards);
|
|
225
|
+
if (linked)
|
|
226
|
+
parts.push(linked);
|
|
227
|
+
const workflowBrief = workflow ? renderWorkflowBrief(workflow) : "";
|
|
228
|
+
if (workflowBrief)
|
|
229
|
+
parts.push(workflowBrief);
|
|
230
|
+
const run = renderDeveloperRun(mode, developer);
|
|
231
|
+
if (run)
|
|
232
|
+
parts.push(run);
|
|
233
|
+
const shots = renderScreenshots(attachments);
|
|
234
|
+
if (shots)
|
|
235
|
+
parts.push(shots);
|
|
236
|
+
if (brief.trim()) {
|
|
237
|
+
parts.push(`<repo-index>\n${brief}\n</repo-index>\n\nThe index above is the repo as of the last commit. Trust it for paths and manifests; read a file only when the detail matters to a card.`);
|
|
238
|
+
}
|
|
239
|
+
const directive = renderMode(mode);
|
|
240
|
+
if (directive)
|
|
241
|
+
parts.push(directive);
|
|
242
|
+
const limit = renderBudget(budget);
|
|
243
|
+
if (limit)
|
|
244
|
+
parts.push(limit);
|
|
245
|
+
// The intake is one tool-free call; there is nothing to pace.
|
|
246
|
+
const clock = mode === "intake" ? "" : renderClock(clockMs);
|
|
247
|
+
if (clock)
|
|
248
|
+
parts.push(clock);
|
|
249
|
+
return parts.join("\n\n");
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Why this turn exists. A typed line is not a conversation opener: there is no
|
|
253
|
+
* transcript behind it, no agreed shape, and one turn to get to cards the drafts
|
|
254
|
+
* dialog can act on. Saying so in the prompt is the difference between the
|
|
255
|
+
* planner asking three good questions and asking the person to explain
|
|
256
|
+
* themselves first.
|
|
257
|
+
*/
|
|
258
|
+
/**
|
|
259
|
+
* The reading, as the draft sees it: code search results for this repo and
|
|
260
|
+
* scout answers for linked ones. A quoted line is treated as read; a failed
|
|
261
|
+
* section is said so, and the draft reads for itself there.
|
|
262
|
+
*/
|
|
263
|
+
export function renderResearch(findings) {
|
|
264
|
+
if (findings.length === 0)
|
|
265
|
+
return "";
|
|
266
|
+
const sections = findings.map((finding) => {
|
|
267
|
+
const answer = finding.answer.trim();
|
|
268
|
+
const error = finding.error?.trim() ?? "";
|
|
269
|
+
let body;
|
|
270
|
+
if (answer && error)
|
|
271
|
+
body = `${answer}\n\n(Partial: ${error})`;
|
|
272
|
+
else if (answer)
|
|
273
|
+
body = answer;
|
|
274
|
+
else
|
|
275
|
+
body = `Failed: ${error || "no answer was returned"}`;
|
|
276
|
+
const where = finding.board ? `[${finding.board}] ` : "";
|
|
277
|
+
return `### ${where}${finding.question.trim()}\n${body}`;
|
|
278
|
+
});
|
|
279
|
+
return `<research>
|
|
280
|
+
Before this turn the repository was read for this task: a code search of this repo, and scouts for any linked repo. Below are the files that matched, the lines that matched in them with path:line, what imports them, and the tests that cover them. A quoted line is evidence for that line only. When a changed value or setting needs tracing, open the source at each handoff on the affected path from its source through storage or transport to each consumer and runtime effect, including in a linked repo; do not infer the path from citations or read unrelated files. Otherwise open a file only for surrounding code, a failed section, or a fact none covers.
|
|
281
|
+
|
|
282
|
+
The search ranks matches; it does not decide which of two paths wins. When the task reports behaviour that more than one place can set or read — the UI, an API route, a CLI command, a stored row, a config file — open each one that matched before you write the card, and never scope out one that could cause what the person reported.
|
|
283
|
+
|
|
284
|
+
${sections.join("\n\n")}
|
|
285
|
+
</research>`;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* The project repos on this board, as each pass needs them. The intake gets
|
|
289
|
+
* every repo with a line about it and names the ones the work may touch, so a
|
|
290
|
+
* scout reads them before the draft. The draft gets the same repos with their
|
|
291
|
+
* paths and writes the part that lives in one of them as its own card.
|
|
292
|
+
*/
|
|
293
|
+
/** A Pi board can list hundreds of models; the planner needs the choice, not the catalogue. */
|
|
294
|
+
export const MAX_BRIEFED_MODELS = 40;
|
|
295
|
+
/**
|
|
296
|
+
* The developer run a card starts, so the planner can size it. The intake is a
|
|
297
|
+
* short decision and drafts at most a small card, so it is told nothing and its
|
|
298
|
+
* cards run on the profile's defaults.
|
|
299
|
+
*/
|
|
300
|
+
export function renderDeveloperRun(mode, developer) {
|
|
301
|
+
if (!developer || mode === "intake")
|
|
302
|
+
return "";
|
|
303
|
+
const shown = developer.models.slice(0, MAX_BRIEFED_MODELS);
|
|
304
|
+
const more = developer.models.length - shown.length;
|
|
305
|
+
const models = shown.length > 0
|
|
306
|
+
? `Models this harness can run:\n${shown.map((model) => `- ${model}`).join("\n")}${more > 0 ? `\n(${more} more not listed)` : ""}`
|
|
307
|
+
: "This harness listed no models, so do not set `model` on any card.";
|
|
308
|
+
const skills = developer.skills ?? [];
|
|
309
|
+
const skillList = skills.length > 0
|
|
310
|
+
? `\nSkills the person enabled, as id — name: description:\n${skills
|
|
311
|
+
.map((skill) => `- ${skill.id} — ${skill.name}${skill.description ? `: ${skill.description}` : ""}`)
|
|
312
|
+
.join("\n")}`
|
|
313
|
+
: "";
|
|
314
|
+
return `<developer-run>
|
|
315
|
+
Each card you write is run by a developer agent on the \`${developer.harness}\` harness.
|
|
316
|
+
Default model: ${developer.model || "the harness default"}. Default thinking: ${developer.thinking}.
|
|
317
|
+
${models}${skillList}
|
|
318
|
+
</developer-run>`;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* A card's skills are ids the run will look up. One the planner invented, or
|
|
322
|
+
* one not enabled when it drafted, is dropped; the rest take the store's name,
|
|
323
|
+
* which is what the dialog shows.
|
|
324
|
+
*/
|
|
325
|
+
export function keepKnownSkills(plan, developer) {
|
|
326
|
+
if (plan.cards.every((card) => !card.skills))
|
|
327
|
+
return plan;
|
|
328
|
+
const known = new Map((developer?.skills ?? []).map((skill) => [skill.id, skill.name]));
|
|
329
|
+
return {
|
|
330
|
+
...plan,
|
|
331
|
+
cards: plan.cards.map((card) => {
|
|
332
|
+
if (!card.skills)
|
|
333
|
+
return card;
|
|
334
|
+
const { skills: chosen, ...rest } = card;
|
|
335
|
+
const skills = chosen
|
|
336
|
+
.filter((skill) => known.has(skill.id))
|
|
337
|
+
.map((skill) => ({ id: skill.id, name: known.get(skill.id) ?? skill.name }));
|
|
338
|
+
return skills.length > 0 ? { ...rest, skills } : rest;
|
|
339
|
+
}),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* A card's model is a harness id the board will pass to `--model`. One the
|
|
344
|
+
* harness did not list is the planner's invention, and a run on it fails at
|
|
345
|
+
* spawn, so it is dropped and the card runs on the profile's model instead.
|
|
346
|
+
*/
|
|
347
|
+
export function keepListedModels(plan, developer) {
|
|
348
|
+
const listed = new Set(developer?.models ?? []);
|
|
349
|
+
if (plan.cards.every((card) => !card.model || listed.has(card.model)))
|
|
350
|
+
return plan;
|
|
351
|
+
return {
|
|
352
|
+
...plan,
|
|
353
|
+
cards: plan.cards.map((card) => {
|
|
354
|
+
if (!card.model || listed.has(card.model))
|
|
355
|
+
return card;
|
|
356
|
+
const { model: _dropped, ...rest } = card;
|
|
357
|
+
return rest;
|
|
358
|
+
}),
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
export function renderLinkedBoards(mode, boards) {
|
|
362
|
+
if (boards.length === 0)
|
|
363
|
+
return "";
|
|
364
|
+
if (mode === "intake") {
|
|
365
|
+
const lines = boards.map((board) => `- ${board.name}${board.description ? ` — ${board.description}` : ""}`);
|
|
366
|
+
return `<project-repos>
|
|
367
|
+
This board also covers these repositories:
|
|
368
|
+
${lines.join("\n")}
|
|
369
|
+
|
|
370
|
+
If the work also needs a change in one of them, list its name in a top-level \`"boards"\` array in the json block so a scout reads it before the draft. Most work stays in the home repository: leave \`"boards"\` out then.
|
|
371
|
+
</project-repos>`;
|
|
372
|
+
}
|
|
373
|
+
if (mode !== "new-task")
|
|
374
|
+
return "";
|
|
375
|
+
const lines = boards.map((board) => `- ${board.name} — ${board.root}${board.description ? ` — ${board.description}` : ""}`);
|
|
376
|
+
return `<project-repos>
|
|
377
|
+
This board also covers these repositories. Each is a separate git repository with its own AGENTS.md:
|
|
378
|
+
${lines.join("\n")}
|
|
379
|
+
|
|
380
|
+
- Write the part that lives in one of them as its own card with \`"board": "<name>"\`. Its \`likely_files\`, \`context\` and \`verify\` are paths and commands relative to that repository's root, and follow its own AGENTS.md.
|
|
381
|
+
- A card without \`board\` runs in the home repository. One card never spans two repositories.
|
|
382
|
+
- Name the other card's change in \`context\` as a dependency. Each card stands alone: stub that change in this card's tests, and say in one card's acceptance who checks the whole flow end to end once both have landed.
|
|
383
|
+
- Findings labelled with a repository's name were read in that repository. For changed-value tracing, open files there by absolute path at each handoff on the affected path; otherwise open one only when a finding is missing a fact.
|
|
384
|
+
- If that repository turns out not to need a change, write no card for it and say so in \`reply\`.
|
|
385
|
+
</project-repos>`;
|
|
386
|
+
}
|
|
387
|
+
export function renderMode(mode) {
|
|
388
|
+
if (mode === "intake") {
|
|
389
|
+
return `<intake>
|
|
390
|
+
The person described the work in one box and has not left it. That description is the whole context.
|
|
391
|
+
|
|
392
|
+
- Ask only questions the person must answer (at most three), or return no questions.
|
|
393
|
+
- Write no cards and no research questions. The repository is already being read.
|
|
394
|
+
- The reply is one or two sentences about the decision you made.
|
|
395
|
+
</intake>`;
|
|
396
|
+
}
|
|
397
|
+
if (mode !== "new-task")
|
|
398
|
+
return "";
|
|
399
|
+
return `<new-task>
|
|
400
|
+
The person described the work in one box and has not left it. That description is the whole context: there is no earlier conversation, no goal, no scope and no acceptance criteria behind it.
|
|
401
|
+
|
|
402
|
+
- Do not send them away to write a better description. Use the research findings; trace changed values through the affected path by opening the source at each handoff, including linked repos. For other questions, read only missing facts, what surrounds a quoted line, or when findings are unavailable.
|
|
403
|
+
- Ask at most three questions, and only where the repo cannot answer. Everything else is a draft plus an \`assumed\` line.
|
|
404
|
+
- Draft in this same turn. The cards are shown to the person in the same dialog they typed into, with every field editable, and they confirm or discard them there. An unanswered question is what the person is about to decide, not a reason to withhold the card.
|
|
405
|
+
- A guess with a flag is better here than a question, because the person can edit a card and cannot edit a conversation.
|
|
406
|
+
- The reply is one or two sentences about the choice you made. Do not tell them where to go to find the card: it is already in front of them.
|
|
407
|
+
</new-task>`;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* The context the new chat starts with. The summary is inline because the
|
|
411
|
+
* planner's tools can read files but not the local database; the old id is a
|
|
412
|
+
* reference to the full record, never a substitute for the content.
|
|
413
|
+
*/
|
|
414
|
+
export function renderHandoff(handoff) {
|
|
415
|
+
const summary = handoff?.summary.trim();
|
|
416
|
+
if (!handoff || !summary)
|
|
417
|
+
return "";
|
|
418
|
+
const count = handoff.messageCount
|
|
419
|
+
? ` It compresses ${handoff.messageCount} earlier message${handoff.messageCount === 1 ? "" : "s"}.`
|
|
420
|
+
: "";
|
|
421
|
+
return `<handoff from-conversation="${handoff.conversationId}">
|
|
422
|
+
This chat continues from an earlier conversation. The summary below is what carries over.${count} The full transcript still exists in the local SQLite database under conversation id ${handoff.conversationId}. You cannot query SQLite with your tools, so the summary is the record you have; the id is only a reference for the person.
|
|
423
|
+
|
|
424
|
+
<summary>
|
|
425
|
+
${summary}
|
|
426
|
+
</summary>
|
|
427
|
+
</handoff>`;
|
|
428
|
+
}
|
|
429
|
+
/** The first message, the last four turns, the draft, the board, and the old id. */
|
|
430
|
+
const messageLine = (message) => `${message.role === "user" ? "Person" : "You"}: ${message.content}`;
|
|
431
|
+
export function fallbackHandoff(options) {
|
|
432
|
+
const messages = options.messages.filter((message) => message.kind !== "note");
|
|
433
|
+
// Group a turn as a person message plus whatever the planner said back, so
|
|
434
|
+
// "last 4 turns" means four exchanges rather than four rows.
|
|
435
|
+
const turns = [];
|
|
436
|
+
for (const message of messages) {
|
|
437
|
+
if (message.role === "user" || turns.length === 0)
|
|
438
|
+
turns.push([message]);
|
|
439
|
+
else
|
|
440
|
+
turns.at(-1).push(message);
|
|
441
|
+
}
|
|
442
|
+
const tail = turns.slice(-4).flat();
|
|
443
|
+
const first = messages[0];
|
|
444
|
+
const sections = [
|
|
445
|
+
`Fallback handoff from conversation ${options.conversationId}. The model summary could not be produced, so this is a deterministic record of the old chat.`,
|
|
446
|
+
];
|
|
447
|
+
if (options.priorSummary?.trim()) {
|
|
448
|
+
sections.push(`Context inherited from an earlier handoff:\n${options.priorSummary.trim()}`);
|
|
449
|
+
}
|
|
450
|
+
if (first && !tail.includes(first))
|
|
451
|
+
sections.push(`First message:\n${messageLine(first)}`);
|
|
452
|
+
if (tail.length > 0)
|
|
453
|
+
sections.push(`Last 4 turns:\n${tail.map(messageLine).join("\n")}`);
|
|
454
|
+
if (options.plan && options.plan.cards.length > 0) {
|
|
455
|
+
const cards = options.plan.cards
|
|
456
|
+
.map((card) => [
|
|
457
|
+
`- ${oneLine(card.title)}`,
|
|
458
|
+
` goal: ${oneLine(card.goal)}`,
|
|
459
|
+
` acceptance: ${oneLine(card.acceptance)}`,
|
|
460
|
+
` likely_files: ${card.likely_files.join(", ") || "none yet"}`,
|
|
461
|
+
` verify: ${(card.verify ?? []).map((check) => `${check.label} → ${check.command}`).join("; ") || "none yet"}`,
|
|
462
|
+
` context: ${(card.context ?? []).map(oneLine).join("; ") || "none"}`,
|
|
463
|
+
...(card.plan?.trim() ? [` plan: ${card.plan.trim()}`] : []),
|
|
464
|
+
].join("\n"))
|
|
465
|
+
.join("\n");
|
|
466
|
+
sections.push(`Draft plan on the table:\n${cards}`);
|
|
467
|
+
}
|
|
468
|
+
const board = (options.board ?? []).filter((ticket) => ticket.state !== "cancelled");
|
|
469
|
+
if (board.length > 0) {
|
|
470
|
+
sections.push(`Board tickets:\n${board
|
|
471
|
+
.map((ticket) => `- ${ticket.id} [${ticket.state}] ${oneLine(ticket.title)}`)
|
|
472
|
+
.join("\n")}`);
|
|
473
|
+
}
|
|
474
|
+
sections.push(`Full transcript conversation id: ${options.conversationId}`);
|
|
475
|
+
return sections.join("\n\n");
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* The board, as the planner needs it: what already exists, so it stops
|
|
479
|
+
* re-proposing work the person already accepted. Titles only — the cards it
|
|
480
|
+
* wrote are in the transcript, and the full tickets are the board's business,
|
|
481
|
+
* not the planner's.
|
|
482
|
+
*/
|
|
483
|
+
export function renderBoard(board) {
|
|
484
|
+
const open = board.filter((ticket) => ticket.state !== "cancelled");
|
|
485
|
+
if (open.length === 0)
|
|
486
|
+
return "";
|
|
487
|
+
const lines = open
|
|
488
|
+
.map((ticket) => `- ${ticket.id} [${ticket.state}] ${oneLine(ticket.title)}`)
|
|
489
|
+
.join("\n");
|
|
490
|
+
return `<board>\nTickets that already exist on this board:\n\n${lines}\n</board>\n\nThese are accepted work. Do not propose any of them again, and do not re-ask a question they already answer.`;
|
|
491
|
+
}
|
|
492
|
+
/** Long fields are clipped: a prompt that grows with every card is a slow turn. */
|
|
493
|
+
const FIELD_LIMIT = 400;
|
|
494
|
+
const oneLine = (value) => {
|
|
495
|
+
const text = value.replace(/\s+/g, " ").trim();
|
|
496
|
+
return text.length > FIELD_LIMIT ? `${text.slice(0, FIELD_LIMIT - 1)}…` : text;
|
|
497
|
+
};
|
|
498
|
+
/** A context fact may be long, but it must not end in the middle of a word. */
|
|
499
|
+
const clipContext = (value, limit) => {
|
|
500
|
+
const text = value.replace(/\s+/g, " ").trim();
|
|
501
|
+
if (text.length <= limit)
|
|
502
|
+
return text;
|
|
503
|
+
const cut = text.slice(0, limit - 1);
|
|
504
|
+
const lastSpace = cut.lastIndexOf(" ");
|
|
505
|
+
const head = lastSpace > limit * 0.6 ? cut.slice(0, lastSpace) : cut;
|
|
506
|
+
return `${head.trimEnd()}…`;
|
|
507
|
+
};
|
|
508
|
+
/**
|
|
509
|
+
* The cards already on the table, rendered so the next turn edits them instead
|
|
510
|
+
* of writing them again from scratch. The prose transcript is not enough: it
|
|
511
|
+
* carries what was said, not what was drafted.
|
|
512
|
+
*/
|
|
513
|
+
export function renderDraft(plan) {
|
|
514
|
+
if (plan.cards.length === 0 && plan.questions.length === 0)
|
|
515
|
+
return "";
|
|
516
|
+
const questions = plan.questions
|
|
517
|
+
.map((question) => [
|
|
518
|
+
`- id: ${question.id}`,
|
|
519
|
+
` question: ${oneLine(question.text)}`,
|
|
520
|
+
` evidence: ${question.derived ? (question.evidence ?? "from the repo") : "your guess"}`,
|
|
521
|
+
...question.options.map((option) => ` option ${option.id}${option.recommended ? " (recommended)" : ""}: ${oneLine(option.label)} — ${oneLine(option.cost)}`),
|
|
522
|
+
...(question.options.length === 0 ? [" options: none yet"] : []),
|
|
523
|
+
].join("\n"))
|
|
524
|
+
.join("\n");
|
|
525
|
+
// The contract says two cards whose likely files intersect are one card,
|
|
526
|
+
// but a model can write both before it reads that line. Name the exact
|
|
527
|
+
// overlap on every turn so the next edit has to resolve it.
|
|
528
|
+
const overlapNotes = new Map();
|
|
529
|
+
for (let first = 0; first < plan.cards.length; first += 1) {
|
|
530
|
+
for (let second = first + 1; second < plan.cards.length; second += 1) {
|
|
531
|
+
const left = plan.cards[first];
|
|
532
|
+
const right = plan.cards[second];
|
|
533
|
+
const shared = left.likely_files.filter((file) => right.likely_files.includes(file));
|
|
534
|
+
if (shared.length === 0)
|
|
535
|
+
continue;
|
|
536
|
+
const note = `SAME FILES as ${right.id}: ${shared.join(", ")}. They cannot run in parallel; make one card or sequence them.`;
|
|
537
|
+
overlapNotes.set(left.id, [...(overlapNotes.get(left.id) ?? []), note]);
|
|
538
|
+
const reverse = `SAME FILES as ${left.id}: ${shared.join(", ")}. They cannot run in parallel; make one card or sequence them.`;
|
|
539
|
+
overlapNotes.set(right.id, [...(overlapNotes.get(right.id) ?? []), reverse]);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const cards = plan.cards
|
|
543
|
+
.map((card) => [
|
|
544
|
+
`- id: ${card.id}`,
|
|
545
|
+
` title: ${oneLine(card.title)}`,
|
|
546
|
+
` goal: ${oneLine(card.goal)}`,
|
|
547
|
+
` out_of_scope: ${oneLine(card.out_of_scope)}`,
|
|
548
|
+
` acceptance: ${oneLine(card.acceptance)}`,
|
|
549
|
+
// The cap is a rule in the contract, and this is the loop that makes it
|
|
550
|
+
// hold: a card over the line is named on every turn until it is split,
|
|
551
|
+
// so the planner sees its own size where it edits the card.
|
|
552
|
+
...(acceptanceChecks(card.acceptance).length > MAX_CARD_CHECKS
|
|
553
|
+
? [
|
|
554
|
+
` TOO BIG: ${acceptanceChecks(card.acceptance).length} checks, at most ${MAX_CARD_CHECKS} per card. Split this into cards that each prove one behaviour.`,
|
|
555
|
+
]
|
|
556
|
+
: []),
|
|
557
|
+
...(overlapNotes.get(card.id)?.map((note) => ` FILES OVERLAP: ${note}`) ?? []),
|
|
558
|
+
` likely_files: ${card.likely_files.join(", ") || "none yet"}`,
|
|
559
|
+
` verify: ${(card.verify ?? []).map((check) => `${check.label} → ${check.command}`).join("; ") || "none yet"}`,
|
|
560
|
+
` context: ${(card.context ?? []).map(oneLine).join("; ") || "none"}`,
|
|
561
|
+
...(card.plan?.trim() ? [` plan: ${card.plan.trim()}`] : []),
|
|
562
|
+
` thinking: ${card.thinking ?? "default"}`,
|
|
563
|
+
` model: ${card.model ?? "default"}`,
|
|
564
|
+
` skills: ${(card.skills ?? []).map((skill) => skill.id).join(", ") || "none"}`,
|
|
565
|
+
` assumed: ${card.assumed.map(oneLine).join("; ") || "none"}`,
|
|
566
|
+
` decided: ${card.decided.map(oneLine).join("; ") || "none"}`,
|
|
567
|
+
].join("\n"))
|
|
568
|
+
.join("\n");
|
|
569
|
+
const parts = [];
|
|
570
|
+
if (questions) {
|
|
571
|
+
parts.push(`Questions you asked that the person has not answered yet:\n\n${questions}`);
|
|
572
|
+
}
|
|
573
|
+
if (cards) {
|
|
574
|
+
parts.push(`The cards on the table right now, from earlier turns:\n\n${cards}`);
|
|
575
|
+
}
|
|
576
|
+
return `<draft-plan>\n${parts.join("\n\n")}\n</draft-plan>\n\nYour json block replaces this draft: keep the id of every card you still want, leave out the ones you are removing, and change only what the last message asks for.`;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* The screenshots are part of the brief, not decoration. The images themselves
|
|
580
|
+
* ride with the prompt; these paths are how a later turn — or the coding agent
|
|
581
|
+
* that picks the ticket up — opens the same picture after this process is gone.
|
|
582
|
+
*/
|
|
583
|
+
export function renderScreenshots(paths) {
|
|
584
|
+
if (paths.length === 0)
|
|
585
|
+
return "";
|
|
586
|
+
const one = paths.length === 1;
|
|
587
|
+
return `<screenshots>
|
|
588
|
+
The person attached ${one ? "a screenshot" : `${paths.length} screenshots`} to this task. Look at ${one ? "it" : "them"} before drafting: ${one ? "it is" : "they are"} the reference for what the work should look like, and a card that contradicts the picture is wrong.
|
|
589
|
+
|
|
590
|
+
${paths.map((path) => `- ${path}`).join("\n")}
|
|
591
|
+
|
|
592
|
+
Do not copy these files into the repo or describe them as assets. They are a reference for the person's intent; the card is what the run will act on, and its \`likely_files\` are repo paths, not screenshot paths.
|
|
593
|
+
</screenshots>`;
|
|
594
|
+
}
|
|
595
|
+
const norm = (value) => value.toLowerCase().replace(/\s+/g, " ").trim();
|
|
596
|
+
/**
|
|
597
|
+
* Gives every card an id that survives turns. An id the model echoed wins; a
|
|
598
|
+
* card with no id but a title that already exists keeps that card's id, which
|
|
599
|
+
* is what happens when the model forgets to echo it; anything else is new.
|
|
600
|
+
* Ids of removed cards are never reused, so "drop card 1" stays dropped.
|
|
601
|
+
*/
|
|
602
|
+
export function assignIds(plan, previous) {
|
|
603
|
+
const previousCards = previous?.cards ?? [];
|
|
604
|
+
const known = new Set(previousCards.map((card) => card.id).filter(Boolean));
|
|
605
|
+
const byTitle = new Map();
|
|
606
|
+
for (const card of previousCards.toReversed()) {
|
|
607
|
+
if (card.id)
|
|
608
|
+
byTitle.set(norm(card.title), card.id);
|
|
609
|
+
}
|
|
610
|
+
let next = 1;
|
|
611
|
+
for (const card of previousCards) {
|
|
612
|
+
const number = Number(String(card.id ?? "").replace(/^c/, ""));
|
|
613
|
+
if (Number.isInteger(number))
|
|
614
|
+
next = Math.max(next, number + 1);
|
|
615
|
+
}
|
|
616
|
+
const used = new Set();
|
|
617
|
+
const mint = () => {
|
|
618
|
+
let id = `c${next++}`;
|
|
619
|
+
while (used.has(id) || known.has(id))
|
|
620
|
+
id = `c${next++}`;
|
|
621
|
+
return id;
|
|
622
|
+
};
|
|
623
|
+
const cards = plan.cards.map((card) => {
|
|
624
|
+
const wanted = [card.id, byTitle.get(norm(card.title))].find((id) => Boolean(id) && known.has(id) && !used.has(id));
|
|
625
|
+
const id = wanted ?? mint();
|
|
626
|
+
used.add(id);
|
|
627
|
+
return { ...card, id };
|
|
628
|
+
});
|
|
629
|
+
return { ...plan, cards };
|
|
630
|
+
}
|
|
631
|
+
function buildSummaryPrompt(options) {
|
|
632
|
+
const messages = options.messages.filter((message) => message.kind !== "note");
|
|
633
|
+
const sections = [
|
|
634
|
+
`<conversation-transcript>\n${messages
|
|
635
|
+
.map((message) => `${message.role === "user" ? "Person" : "You"}: ${message.content}`)
|
|
636
|
+
.join("\n\n")}\n</conversation-transcript>`,
|
|
637
|
+
];
|
|
638
|
+
if (options.priorSummary?.trim()) {
|
|
639
|
+
sections.push(`<inherited-summary>\n${options.priorSummary.trim()}\n</inherited-summary>`);
|
|
640
|
+
}
|
|
641
|
+
if (options.plan && options.plan.cards.length > 0) {
|
|
642
|
+
sections.push(`<draft-plan>\n${options.plan.cards
|
|
643
|
+
.map((card) => [
|
|
644
|
+
`- ${oneLine(card.title)}`,
|
|
645
|
+
` goal: ${oneLine(card.goal)}`,
|
|
646
|
+
` out_of_scope: ${oneLine(card.out_of_scope)}`,
|
|
647
|
+
` acceptance: ${oneLine(card.acceptance)}`,
|
|
648
|
+
` likely_files: ${card.likely_files.join(", ") || "none yet"}`,
|
|
649
|
+
` verify: ${(card.verify ?? []).map((check) => `${check.label} → ${check.command}`).join("; ") || "none yet"}`,
|
|
650
|
+
` context: ${(card.context ?? []).map(oneLine).join("; ") || "none"}`,
|
|
651
|
+
].join("\n"))
|
|
652
|
+
.join("\n")}\n</draft-plan>`);
|
|
653
|
+
}
|
|
654
|
+
const board = (options.board ?? []).filter((ticket) => ticket.state !== "cancelled");
|
|
655
|
+
if (board.length > 0) {
|
|
656
|
+
sections.push(`<board>\n${board
|
|
657
|
+
.map((ticket) => `- ${ticket.id} [${ticket.state}] ${oneLine(ticket.title)}`)
|
|
658
|
+
.join("\n")}\n</board>`);
|
|
659
|
+
}
|
|
660
|
+
return `${sections.join("\n\n")}\n\nWrite the handoff summary now.`;
|
|
661
|
+
}
|
|
662
|
+
/** One session, one prompt, and the text it produced. */
|
|
663
|
+
export async function runPlannerSession(session, options) {
|
|
664
|
+
const startedAt = Date.now();
|
|
665
|
+
let firstEventMs = null;
|
|
666
|
+
let toolCalls = 0;
|
|
667
|
+
let toolErrors = 0;
|
|
668
|
+
let text = "";
|
|
669
|
+
let actions = [];
|
|
670
|
+
let actionOutput = "";
|
|
671
|
+
let timedOut = false;
|
|
672
|
+
let exitCode = null;
|
|
673
|
+
let exitStderr = "";
|
|
674
|
+
/** Zero means the turn is not bounded. */
|
|
675
|
+
const budget = options.budget ?? 0;
|
|
676
|
+
let steered = false;
|
|
677
|
+
let stopped = false;
|
|
678
|
+
let wrapped = false;
|
|
679
|
+
let clockSteered = false;
|
|
680
|
+
let clockStopped = false;
|
|
681
|
+
const spoken = () => {
|
|
682
|
+
if (firstEventMs === null)
|
|
683
|
+
firstEventMs = Date.now() - startedAt;
|
|
684
|
+
};
|
|
685
|
+
const capped = () => clockStopped
|
|
686
|
+
? "clock"
|
|
687
|
+
: stopped
|
|
688
|
+
? "hard"
|
|
689
|
+
: steered
|
|
690
|
+
? "steer"
|
|
691
|
+
: clockSteered
|
|
692
|
+
? "clock-steer"
|
|
693
|
+
: null;
|
|
694
|
+
const stats = () => ({
|
|
695
|
+
firstEventMs,
|
|
696
|
+
harnessMs: Date.now() - startedAt,
|
|
697
|
+
toolCalls,
|
|
698
|
+
toolErrors,
|
|
699
|
+
promptChars: (options.systemPrompt?.length ?? 0) + (options.prompt?.length ?? 0),
|
|
700
|
+
outputChars: text.length,
|
|
701
|
+
toolBudget: budget,
|
|
702
|
+
capped: capped(),
|
|
703
|
+
});
|
|
704
|
+
const report = (label, tool) => {
|
|
705
|
+
options.onStatus?.({ label, tool, actions });
|
|
706
|
+
};
|
|
707
|
+
report("Thinking", null);
|
|
708
|
+
const timer = setTimeout(() => {
|
|
709
|
+
timedOut = true;
|
|
710
|
+
session.abort();
|
|
711
|
+
}, options.timeoutMs);
|
|
712
|
+
// The warning the prompt promised. It only asks the model to write the block;
|
|
713
|
+
// the abort above is still the ceiling, and neither moves the other.
|
|
714
|
+
const warning = options.mode === "intake"
|
|
715
|
+
? null
|
|
716
|
+
: setTimeout(() => {
|
|
717
|
+
if (hasPlanBlock(text))
|
|
718
|
+
return;
|
|
719
|
+
clockSteered = true;
|
|
720
|
+
session.steer(CLOCK_STEER);
|
|
721
|
+
report("Time is nearly spent — writing the card", null);
|
|
722
|
+
}, clockSteerDelay(options.timeoutMs));
|
|
723
|
+
// Near the end a turn that still has no block is stopped the way the budget
|
|
724
|
+
// stops one, and asked for the block without tools. The time it takes comes
|
|
725
|
+
// out of the deadline: the person is waiting on the deadline, not after it.
|
|
726
|
+
const stop = setTimeout(() => {
|
|
727
|
+
if (hasPlanBlock(text) || stopped || wrapped)
|
|
728
|
+
return;
|
|
729
|
+
clockStopped = true;
|
|
730
|
+
session.interrupt();
|
|
731
|
+
report("Time is up — writing the card from what was read", null);
|
|
732
|
+
}, clockStopDelay(options.timeoutMs));
|
|
733
|
+
try {
|
|
734
|
+
for await (const event of session.events) {
|
|
735
|
+
if (event.type === "text") {
|
|
736
|
+
spoken();
|
|
737
|
+
text += event.text;
|
|
738
|
+
}
|
|
739
|
+
else if (event.type === "tool_start") {
|
|
740
|
+
spoken();
|
|
741
|
+
toolCalls += 1;
|
|
742
|
+
actionOutput = "";
|
|
743
|
+
actions = startAction(actions, {
|
|
744
|
+
tool: event.tool,
|
|
745
|
+
label: event.label,
|
|
746
|
+
detail: actionDetail(event.tool, event.args),
|
|
747
|
+
});
|
|
748
|
+
report(event.label, event.tool);
|
|
749
|
+
if (options.mode === "intake") {
|
|
750
|
+
session.abort();
|
|
751
|
+
throw new OrchestratorError("output", "the intake attempted a tool call");
|
|
752
|
+
}
|
|
753
|
+
if (budget > 0 && !steered && toolCalls >= budget) {
|
|
754
|
+
steered = true;
|
|
755
|
+
session.steer(BUDGET_STEER);
|
|
756
|
+
report("Budget spent — writing the card", null);
|
|
757
|
+
}
|
|
758
|
+
else if (budget > 0 && !stopped && toolCalls > budget + BUDGET_OVERTUN) {
|
|
759
|
+
stopped = true;
|
|
760
|
+
session.interrupt();
|
|
761
|
+
report("Stopping the turn", null);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
else if (event.type === "tool_output") {
|
|
765
|
+
actionOutput = (actionOutput + event.text).slice(-4000);
|
|
766
|
+
}
|
|
767
|
+
else if (event.type === "tool_end") {
|
|
768
|
+
if (event.isError)
|
|
769
|
+
toolErrors += 1;
|
|
770
|
+
actions = finishAction(actions, {
|
|
771
|
+
isError: event.isError,
|
|
772
|
+
output: actionOutput,
|
|
773
|
+
});
|
|
774
|
+
actionOutput = "";
|
|
775
|
+
report("Thinking", null);
|
|
776
|
+
}
|
|
777
|
+
else if (event.type === "settled") {
|
|
778
|
+
if ((stopped || clockStopped) && !wrapped && !hasPlanBlock(text)) {
|
|
779
|
+
wrapped = true;
|
|
780
|
+
report("Writing the card", null);
|
|
781
|
+
session.prompt(clockStopped ? CLOCK_WRAPUP : BUDGET_WRAPUP);
|
|
782
|
+
}
|
|
783
|
+
else {
|
|
784
|
+
session.close();
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
else if (event.type === "exit") {
|
|
788
|
+
exitCode = event.code;
|
|
789
|
+
exitStderr = event.stderr;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
finally {
|
|
794
|
+
clearTimeout(timer);
|
|
795
|
+
clearTimeout(stop);
|
|
796
|
+
if (warning)
|
|
797
|
+
clearTimeout(warning);
|
|
798
|
+
options.onStats?.(stats());
|
|
799
|
+
}
|
|
800
|
+
// A card written before the deadline is the turn's answer even if the process
|
|
801
|
+
// was still going when the clock ran out: the timeout is only for no card.
|
|
802
|
+
if (timedOut && !hasPlanBlock(text)) {
|
|
803
|
+
throw new OrchestratorError("timeout", "the orchestrator timed out", text || undefined);
|
|
804
|
+
}
|
|
805
|
+
if (exitCode !== 0 && !text.trim()) {
|
|
806
|
+
const tail = exitStderr.trim().split("\n").slice(-3).join(" ");
|
|
807
|
+
const command = options.command ?? "pi";
|
|
808
|
+
throw new OrchestratorError("harness", command + " exited " + (exitCode ?? "without a code") + (tail ? ": " + tail : ""), text || undefined);
|
|
809
|
+
}
|
|
810
|
+
return text;
|
|
811
|
+
}
|
|
812
|
+
/** Keep the pi factory as the fallback for tests and custom pi-compatible commands. */
|
|
813
|
+
async function runHarness(options) {
|
|
814
|
+
const request = {
|
|
815
|
+
cwd: options.repoRoot,
|
|
816
|
+
systemPrompt: options.systemPrompt,
|
|
817
|
+
prompt: options.prompt,
|
|
818
|
+
id: options.id,
|
|
819
|
+
model: options.model,
|
|
820
|
+
thinking: options.thinking,
|
|
821
|
+
images: options.images,
|
|
822
|
+
timeoutMs: options.timeoutMs,
|
|
823
|
+
noTools: options.mode === "intake",
|
|
824
|
+
};
|
|
825
|
+
const session = options.planner
|
|
826
|
+
? options.planner(request)
|
|
827
|
+
: new PiPlannerSession({ ...request, command: options.command });
|
|
828
|
+
return runPlannerSession(session, {
|
|
829
|
+
id: options.id,
|
|
830
|
+
command: options.command,
|
|
831
|
+
systemPrompt: options.systemPrompt,
|
|
832
|
+
prompt: options.prompt,
|
|
833
|
+
budget: options.budget,
|
|
834
|
+
mode: options.mode,
|
|
835
|
+
timeoutMs: options.timeoutMs,
|
|
836
|
+
onStatus: options.onStatus,
|
|
837
|
+
onStats: options.onStats,
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
/** The dedicated compression pass, isolated from planning so it can fail safely. */
|
|
841
|
+
export async function summarizeConversation(options) {
|
|
842
|
+
const text = await runHarness({
|
|
843
|
+
repoRoot: options.repoRoot,
|
|
844
|
+
command: options.command ?? process.env.ZELIO_HARNESS ?? "pi",
|
|
845
|
+
planner: options.planner,
|
|
846
|
+
model: options.model,
|
|
847
|
+
timeoutMs: options.timeoutMs ?? SUMMARY_TIMEOUT_MS,
|
|
848
|
+
thinking: options.thinking ??
|
|
849
|
+
resolveThinkingLevel(process.env.ZELIO_PLANNER_THINKING, "ZELIO_PLANNER_THINKING", "high"),
|
|
850
|
+
systemPrompt: SUMMARY_PROMPT,
|
|
851
|
+
prompt: buildSummaryPrompt(options),
|
|
852
|
+
id: "summary-1",
|
|
853
|
+
onStatus: options.onStatus,
|
|
854
|
+
});
|
|
855
|
+
const summary = text.trim();
|
|
856
|
+
if (!summary)
|
|
857
|
+
throw new OrchestratorError("output", "the summariser returned nothing");
|
|
858
|
+
return summary;
|
|
859
|
+
}
|
|
860
|
+
/** Each door has its own doctrine; the chat's is the default. */
|
|
861
|
+
function promptFor(mode) {
|
|
862
|
+
if (mode === "intake")
|
|
863
|
+
return NEW_TASK_INTAKE_PROMPT;
|
|
864
|
+
if (mode === "new-task")
|
|
865
|
+
return NEW_TASK_PROMPT;
|
|
866
|
+
return ORCHESTRATOR_PROMPT;
|
|
867
|
+
}
|
|
868
|
+
export async function runOrchestrator(options) {
|
|
869
|
+
const research = options.research ?? [];
|
|
870
|
+
const budget = resolvePlannerBudget(options.mode, options.budget, researchComplete(research));
|
|
871
|
+
const timeoutMs = options.timeoutMs ?? PLANNER_TIMEOUT_MS;
|
|
872
|
+
const text = await runHarness({
|
|
873
|
+
repoRoot: options.repoRoot,
|
|
874
|
+
command: options.command ?? process.env.ZELIO_HARNESS ?? "pi",
|
|
875
|
+
planner: options.planner,
|
|
876
|
+
model: options.model,
|
|
877
|
+
timeoutMs,
|
|
878
|
+
thinking: options.thinking ??
|
|
879
|
+
resolveThinkingLevel(process.env.ZELIO_PLANNER_THINKING, "ZELIO_PLANNER_THINKING", "high"),
|
|
880
|
+
// The door decides who you are. A description in the dialog is a different
|
|
881
|
+
// job from a conversation in the panel, and a mode flag on one prompt could
|
|
882
|
+
// not grow one without dragging the other along.
|
|
883
|
+
systemPrompt: promptFor(options.mode),
|
|
884
|
+
prompt: buildPrompt(options.messages, options.brief ?? "", options.plan ?? null, options.board ?? [], options.handoff ?? null, options.mode, budget, options.workflow ?? null, absoluteAttachments(options.repoRoot, options.attachments ?? []), research, timeoutMs, options.linkedBoards ?? [], options.developer ?? null),
|
|
885
|
+
images: options.images,
|
|
886
|
+
budget,
|
|
887
|
+
mode: options.mode,
|
|
888
|
+
id: "plan-1",
|
|
889
|
+
onStatus: options.onStatus,
|
|
890
|
+
onStats: options.onStats,
|
|
891
|
+
});
|
|
892
|
+
const plan = parsePlan(text);
|
|
893
|
+
return keepKnownSkills(keepListedModels(validatePlan(assignIds(plan, options.plan ?? null)), options.developer), options.developer);
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* What the person is told when the model wrote the block and wrote it wrong.
|
|
897
|
+
* It is the turn's error, so it travels the way a timeout does: red line, the
|
|
898
|
+
* wording of the turn still in the box, one click to send it again.
|
|
899
|
+
*/
|
|
900
|
+
const UNREADABLE_PLAN = "the planner wrote a plan block that could not be read, so nothing was drafted";
|
|
901
|
+
/**
|
|
902
|
+
* The model is told to end with one fenced json block; everything before it is
|
|
903
|
+
* prose for the person. It does not always comply, and the two ways it misses
|
|
904
|
+
* are not the same miss.
|
|
905
|
+
*
|
|
906
|
+
* A greeting gets answered in words and the block is simply missing, so a turn
|
|
907
|
+
* with no block is read as a conversation turn with no cards — not as a
|
|
908
|
+
* failure. Refusing to show the agent's own answer was the bug: it reported a
|
|
909
|
+
* broken agent for what was a perfectly good reply.
|
|
910
|
+
*
|
|
911
|
+
* A block that is *there* and will not parse is the other case: the model meant
|
|
912
|
+
* to write the plan and wrote it wrong, and the turn has nothing to say to the
|
|
913
|
+
* person. Reading it back as prose put several thousand characters of
|
|
914
|
+
* narration and half-written JSON on screen as if the planner had said it —
|
|
915
|
+
* under "not enough to go on", which was true of the parser, not of the
|
|
916
|
+
* description. That is a failed turn, and it is reported as one.
|
|
917
|
+
*/
|
|
918
|
+
export function parsePlan(text) {
|
|
919
|
+
const blocks = fencedBlocks(text);
|
|
920
|
+
for (const candidate of candidates(text)) {
|
|
921
|
+
const plan = readPlanBody(candidate);
|
|
922
|
+
if (plan)
|
|
923
|
+
return plan;
|
|
924
|
+
}
|
|
925
|
+
if (blocks.length > 0)
|
|
926
|
+
throw new OrchestratorError("output", UNREADABLE_PLAN, text);
|
|
927
|
+
const reply = text.trim();
|
|
928
|
+
if (!reply)
|
|
929
|
+
throw new OrchestratorError("output", "the orchestrator returned nothing");
|
|
930
|
+
return { reply, questions: [], cards: [] };
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Whether the text already carries a block the parser will accept. Used to
|
|
934
|
+
* decide if a stopped turn still needs its wrap-up, so the test is "the parser
|
|
935
|
+
* would take this", never "it looks like the model tried".
|
|
936
|
+
*/
|
|
937
|
+
export function hasPlanBlock(text) {
|
|
938
|
+
return candidates(text).some((candidate) => readPlanBody(candidate) !== null);
|
|
939
|
+
}
|
|
940
|
+
/** Every place the plan could be, best guess first: the last fenced block wins. */
|
|
941
|
+
function candidates(text) {
|
|
942
|
+
const slice = braceSlice(text);
|
|
943
|
+
return [...fencedBlocks(text).toReversed(), ...(slice === null ? [] : [slice])];
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* The fenced blocks that could be the plan, in the order they were written. The
|
|
947
|
+
* last one wins: when the prompt shows an example, the real answer comes after
|
|
948
|
+
* it. Some models drop the fence or upper-case the language tag, so the body is
|
|
949
|
+
* tried on its merits rather than by its tag.
|
|
950
|
+
*
|
|
951
|
+
* A block closes only on a fence that ends its line. A card body that quotes a
|
|
952
|
+
* command as `"…\n```bash\npnpm test\n```"` carries backticks inside a JSON
|
|
953
|
+
* string, and closing on those cut the plan off mid-string: the turn failed as
|
|
954
|
+
* unreadable over a fence the model wrote correctly. Inside a string the next
|
|
955
|
+
* character is never a real newline, so the fence that ends the line is the
|
|
956
|
+
* block's own.
|
|
957
|
+
*/
|
|
958
|
+
function fencedBlocks(text) {
|
|
959
|
+
const blocks = [];
|
|
960
|
+
const fence = /```[ \t]*([A-Za-z0-9_-]*)[ \t]*\r?\n([\s\S]*?)(?:```(?=[ \t]*(?:\r?\n|$))|$)/g;
|
|
961
|
+
for (const match of text.matchAll(fence)) {
|
|
962
|
+
const body = (match[2] ?? "").trim();
|
|
963
|
+
if (body.startsWith("{"))
|
|
964
|
+
blocks.push(body);
|
|
965
|
+
}
|
|
966
|
+
return blocks;
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* The whole message as one block, for a model that forgot the fence. Tried
|
|
970
|
+
* last, and never counted as an attempted block: prose that happens to contain
|
|
971
|
+
* braces is not a plan, so it must not fail a chat turn.
|
|
972
|
+
*/
|
|
973
|
+
function braceSlice(text) {
|
|
974
|
+
const open = text.indexOf("{");
|
|
975
|
+
const close = text.lastIndexOf("}");
|
|
976
|
+
return open !== -1 && close > open ? text.slice(open, close + 1) : null;
|
|
977
|
+
}
|
|
978
|
+
/** One block, as a plan, or null when it is not one. */
|
|
979
|
+
function readPlanBody(candidate) {
|
|
980
|
+
const body = asObject(candidate) ?? asObject(stripTrailingCommas(candidate));
|
|
981
|
+
if (!body)
|
|
982
|
+
return null;
|
|
983
|
+
const research = normaliseResearchQuestions(body.research);
|
|
984
|
+
const boards = [
|
|
985
|
+
...new Set(asStrings(body.boards)
|
|
986
|
+
.map((name) => name.trim())
|
|
987
|
+
.filter(Boolean)),
|
|
988
|
+
];
|
|
989
|
+
return {
|
|
990
|
+
reply: typeof body.reply === "string" ? body.reply : "",
|
|
991
|
+
questions: normaliseQuestions(body.questions),
|
|
992
|
+
cards: Array.isArray(body.cards) ? body.cards.map(normaliseCard) : [],
|
|
993
|
+
// Absent when empty, so a plan with no research compares equal to one
|
|
994
|
+
// written before the field existed.
|
|
995
|
+
...(research.length > 0 ? { research } : {}),
|
|
996
|
+
...(boards.length > 0 ? { boards } : {}),
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
function asObject(candidate) {
|
|
1000
|
+
let parsed;
|
|
1001
|
+
try {
|
|
1002
|
+
parsed = JSON.parse(candidate);
|
|
1003
|
+
}
|
|
1004
|
+
catch {
|
|
1005
|
+
return null;
|
|
1006
|
+
}
|
|
1007
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
1008
|
+
return null;
|
|
1009
|
+
return parsed;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* The one repair worth making. Models write their block the way JavaScript
|
|
1013
|
+
* allows it, and a single comma before a closing brace costs the whole turn:
|
|
1014
|
+
* `JSON.parse` refuses the block, and a card the person could have edited is
|
|
1015
|
+
* thrown away over punctuation. Only a comma that sits outside a string and is
|
|
1016
|
+
* followed by `}` or `]` is dropped, so no value is ever rewritten.
|
|
1017
|
+
*/
|
|
1018
|
+
function stripTrailingCommas(text) {
|
|
1019
|
+
let out = "";
|
|
1020
|
+
let quoted = false;
|
|
1021
|
+
let escaped = false;
|
|
1022
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1023
|
+
const char = text[index];
|
|
1024
|
+
if (quoted) {
|
|
1025
|
+
out += char;
|
|
1026
|
+
if (escaped)
|
|
1027
|
+
escaped = false;
|
|
1028
|
+
else if (char === "\\")
|
|
1029
|
+
escaped = true;
|
|
1030
|
+
else if (char === '"')
|
|
1031
|
+
quoted = false;
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (char === '"') {
|
|
1035
|
+
quoted = true;
|
|
1036
|
+
out += char;
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
if (char === ",") {
|
|
1040
|
+
let next = index + 1;
|
|
1041
|
+
while (next < text.length && /\s/.test(text[next]))
|
|
1042
|
+
next += 1;
|
|
1043
|
+
if (text[next] === "}" || text[next] === "]")
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
out += char;
|
|
1047
|
+
}
|
|
1048
|
+
return out;
|
|
1049
|
+
}
|
|
1050
|
+
const asStrings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
1051
|
+
const asText = (value) => (typeof value === "string" ? value.trim() : "");
|
|
1052
|
+
/**
|
|
1053
|
+
* A question the planner asked and the person has not answered. Three is a
|
|
1054
|
+
* conversation; four is a form. The clamp lives here rather than in the prompt
|
|
1055
|
+
* because a prompt is a request and a parser is a guarantee.
|
|
1056
|
+
*/
|
|
1057
|
+
export const MAX_QUESTIONS = 3;
|
|
1058
|
+
const MAX_OPTIONS = 4;
|
|
1059
|
+
/** The setup route's own limit on a model id; a longer one is not a model. */
|
|
1060
|
+
const MAX_MODEL_CHARS = 200;
|
|
1061
|
+
/**
|
|
1062
|
+
* Options are the reason a question can be answered in one click, so the two
|
|
1063
|
+
* ways an option can be useless are removed: one with no label, and one with no
|
|
1064
|
+
* cost. A question that loses its choice is not a question any more.
|
|
1065
|
+
*/
|
|
1066
|
+
function normaliseOptions(value) {
|
|
1067
|
+
const kept = [];
|
|
1068
|
+
for (const raw of Array.isArray(value) ? value : []) {
|
|
1069
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
1070
|
+
continue;
|
|
1071
|
+
const body = raw;
|
|
1072
|
+
const label = asText(body.label);
|
|
1073
|
+
const cost = asText(body.cost);
|
|
1074
|
+
if (!label || !cost)
|
|
1075
|
+
continue;
|
|
1076
|
+
kept.push({ id: asText(body.id), label, cost, recommended: body.recommended === true });
|
|
1077
|
+
if (kept.length === MAX_OPTIONS)
|
|
1078
|
+
break;
|
|
1079
|
+
}
|
|
1080
|
+
// Two recommendations is the same as none: the point is a default, not a tie.
|
|
1081
|
+
let recommended = false;
|
|
1082
|
+
for (const option of kept) {
|
|
1083
|
+
option.recommended = option.recommended && !recommended;
|
|
1084
|
+
if (option.recommended)
|
|
1085
|
+
recommended = true;
|
|
1086
|
+
}
|
|
1087
|
+
return kept;
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Questions arrive from a model that drifts, and a bare string arrives from
|
|
1091
|
+
* every conversation stored before options existed. Both are read here, so the
|
|
1092
|
+
* parser is the only place that has to know about the old shape.
|
|
1093
|
+
*/
|
|
1094
|
+
export function normaliseQuestions(value) {
|
|
1095
|
+
if (!Array.isArray(value))
|
|
1096
|
+
return [];
|
|
1097
|
+
const kept = [];
|
|
1098
|
+
for (const raw of value) {
|
|
1099
|
+
if (kept.length === MAX_QUESTIONS)
|
|
1100
|
+
break;
|
|
1101
|
+
if (typeof raw === "string") {
|
|
1102
|
+
const text = raw.trim();
|
|
1103
|
+
if (text)
|
|
1104
|
+
kept.push({ id: "", text, options: [], derived: false });
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
1108
|
+
continue;
|
|
1109
|
+
const body = raw;
|
|
1110
|
+
const text = asText(body.text);
|
|
1111
|
+
if (!text)
|
|
1112
|
+
continue;
|
|
1113
|
+
// No options at all is the legacy shape and stays a question. Options that
|
|
1114
|
+
// were offered and did not survive are a question with nothing to click.
|
|
1115
|
+
const supplied = Array.isArray(body.options) && body.options.length > 0;
|
|
1116
|
+
const options = supplied ? normaliseOptions(body.options) : [];
|
|
1117
|
+
if (supplied && options.length < 2)
|
|
1118
|
+
continue;
|
|
1119
|
+
const evidence = asText(body.evidence);
|
|
1120
|
+
kept.push({
|
|
1121
|
+
id: asText(body.id),
|
|
1122
|
+
text,
|
|
1123
|
+
options,
|
|
1124
|
+
derived: body.derived === true,
|
|
1125
|
+
...(evidence ? { evidence } : {}),
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
// Ids are the server's, for the same reason card ids are: an answer posted
|
|
1129
|
+
// back has to name the thing this render showed.
|
|
1130
|
+
const questions = [];
|
|
1131
|
+
kept.forEach((question, index) => {
|
|
1132
|
+
const id = question.id || `q${index + 1}`;
|
|
1133
|
+
questions.push({
|
|
1134
|
+
id,
|
|
1135
|
+
text: question.text,
|
|
1136
|
+
derived: question.derived,
|
|
1137
|
+
...(question.evidence ? { evidence: question.evidence } : {}),
|
|
1138
|
+
options: question.options.map((option, optionIndex) => ({
|
|
1139
|
+
id: option.id || `${id}o${optionIndex + 1}`,
|
|
1140
|
+
label: option.label,
|
|
1141
|
+
cost: option.cost,
|
|
1142
|
+
recommended: option.recommended,
|
|
1143
|
+
})),
|
|
1144
|
+
});
|
|
1145
|
+
});
|
|
1146
|
+
return questions;
|
|
1147
|
+
}
|
|
1148
|
+
/**
|
|
1149
|
+
* A command that rewrites files instead of judging them: a formatter or a lint
|
|
1150
|
+
* fixer. It exits 0 on almost any tree, so as a card's check it reports "passed"
|
|
1151
|
+
* without proving anything, and a run that obeys the card runs it mid-turn.
|
|
1152
|
+
* Its `:check` forms (`pnpm fmt:check`, `oxfmt --check`) are checks and stay.
|
|
1153
|
+
*/
|
|
1154
|
+
export function rewritesFiles(command) {
|
|
1155
|
+
return (/\b(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?(?:fmt|format|lint:fix|fix)\b(?!:)/.test(command) ||
|
|
1156
|
+
/(?:^|\s)--(?:fix|write)\b/.test(command) ||
|
|
1157
|
+
/\b(?:oxfmt|biome\s+format)\b(?![^|;&]*--check)/.test(command) ||
|
|
1158
|
+
/\bprettier\b(?![^|;&]*--check)/.test(command));
|
|
1159
|
+
}
|
|
1160
|
+
/**
|
|
1161
|
+
* A card's verify list as the board will run it: no file rewriters, and none of
|
|
1162
|
+
* the In Progress workflow's own checks, which the board runs after every turn
|
|
1163
|
+
* anyway. A check listed twice is a check reported twice.
|
|
1164
|
+
*/
|
|
1165
|
+
export function cardVerify(verify, workflowCommands = []) {
|
|
1166
|
+
const workflow = new Set(workflowCommands.map((command) => command.trim()));
|
|
1167
|
+
return (verify ?? []).filter((check) => !rewritesFiles(check.command) && !workflow.has(check.command.trim()));
|
|
1168
|
+
}
|
|
1169
|
+
export function normaliseCard(card) {
|
|
1170
|
+
const thinking = parseThinkingLevel(typeof card.thinking === "string" ? card.thinking : null);
|
|
1171
|
+
const board = typeof card.board === "string" ? card.board.trim() : "";
|
|
1172
|
+
const model = typeof card.model === "string" ? card.model.trim().slice(0, MAX_MODEL_CHARS) : "";
|
|
1173
|
+
const skills = normaliseCardSkills(card.skills);
|
|
1174
|
+
return {
|
|
1175
|
+
// Empty here is normal: the server hands out ids, the model only echoes them.
|
|
1176
|
+
id: String(card.id ?? "").trim(),
|
|
1177
|
+
title: String(card.title ?? "").trim(),
|
|
1178
|
+
goal: String(card.goal ?? "").trim(),
|
|
1179
|
+
out_of_scope: String(card.out_of_scope ?? "").trim(),
|
|
1180
|
+
acceptance: String(card.acceptance ?? "").trim(),
|
|
1181
|
+
likely_files: asStrings(card.likely_files),
|
|
1182
|
+
verify: cardVerify(normaliseVerify(card.verify)),
|
|
1183
|
+
context: asStrings(card.context)
|
|
1184
|
+
.map((line) => clipContext(line, MAX_CONTEXT_CHARS))
|
|
1185
|
+
.filter(Boolean)
|
|
1186
|
+
.slice(0, MAX_CARD_CONTEXT),
|
|
1187
|
+
...(typeof card.plan === "string" && card.plan.trim()
|
|
1188
|
+
? { plan: card.plan.trim().slice(0, 12000) }
|
|
1189
|
+
: {}),
|
|
1190
|
+
rationale: String(card.rationale ?? "").trim(),
|
|
1191
|
+
assumed: asStrings(card.assumed),
|
|
1192
|
+
decided: asStrings(card.decided),
|
|
1193
|
+
...(thinking ? { thinking } : {}),
|
|
1194
|
+
...(model ? { model } : {}),
|
|
1195
|
+
...(typeof card.developer_harness === "string" && card.developer_harness.trim()
|
|
1196
|
+
? { developer_harness: card.developer_harness.trim() }
|
|
1197
|
+
: {}),
|
|
1198
|
+
...(skills.length > 0 ? { skills } : {}),
|
|
1199
|
+
// Kept as written; the server drops a card whose board the person did not include.
|
|
1200
|
+
...(board ? { board } : {}),
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
/** Rejects a plan the board could not act on, rather than storing a broken card. */
|
|
1204
|
+
export function validatePlan(plan) {
|
|
1205
|
+
if (plan.cards.length > MAX_CARDS) {
|
|
1206
|
+
throw new OrchestratorError("output", `the plan asked for ${plan.cards.length} cards; the cap is ${MAX_CARDS}`);
|
|
1207
|
+
}
|
|
1208
|
+
for (const card of plan.cards) {
|
|
1209
|
+
for (const field of ["title", "goal", "out_of_scope", "acceptance"]) {
|
|
1210
|
+
if (!card[field]) {
|
|
1211
|
+
throw new OrchestratorError("output", `a card is missing ${field}`);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
return plan;
|
|
1216
|
+
}
|
|
1217
|
+
//# sourceMappingURL=runtime.js.map
|