zelio-cli 0.1.0-beta.4 → 0.1.0-beta.6

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.
Files changed (40) hide show
  1. package/dist/cli.js +5 -1
  2. package/dist/cli.js.map +1 -1
  3. package/dist/db/db.js +31 -0
  4. package/dist/db/db.js.map +1 -1
  5. package/dist/orchestrator/area-notes.js +87 -0
  6. package/dist/orchestrator/area-notes.js.map +1 -0
  7. package/dist/orchestrator/codex-session.js +10 -9
  8. package/dist/orchestrator/codex-session.js.map +1 -1
  9. package/dist/orchestrator/new-task-prompt.js +3 -3
  10. package/dist/orchestrator/research.js +27 -12
  11. package/dist/orchestrator/research.js.map +1 -1
  12. package/dist/orchestrator/retrieval.js +333 -0
  13. package/dist/orchestrator/retrieval.js.map +1 -0
  14. package/dist/orchestrator/runtime.js +11 -9
  15. package/dist/orchestrator/runtime.js.map +1 -1
  16. package/dist/repo/code-map.js +152 -0
  17. package/dist/repo/code-map.js.map +1 -0
  18. package/dist/run/codex-planner-config.js +26 -0
  19. package/dist/run/codex-planner-config.js.map +1 -0
  20. package/dist/run/codex-runtime.js +9 -0
  21. package/dist/run/codex-runtime.js.map +1 -1
  22. package/dist/run/harnesses.js +5 -0
  23. package/dist/run/harnesses.js.map +1 -1
  24. package/dist/run/settings.js +1 -1
  25. package/dist/run/settings.js.map +1 -1
  26. package/dist/server/app.js +303 -65
  27. package/dist/server/app.js.map +1 -1
  28. package/dist/server/provider-auth.js +206 -0
  29. package/dist/server/provider-auth.js.map +1 -0
  30. package/dist/server/terminal.js +2 -2
  31. package/dist/server/terminal.js.map +1 -1
  32. package/dist/setup/onboarding.js +7 -12
  33. package/dist/setup/onboarding.js.map +1 -1
  34. package/dist/web/assets/index-cF8zhiLs.css +1 -0
  35. package/dist/web/assets/index-xdwxQJd_.js +255 -0
  36. package/dist/web/index.html +2 -2
  37. package/dist/web/sw.js +1 -1
  38. package/package.json +1 -1
  39. package/dist/web/assets/index-CCQMrUIF.js +0 -255
  40. package/dist/web/assets/index-lzGSgTRQ.css +0 -1
@@ -10,9 +10,13 @@ import { checkSkillName, checkSkillText, fetchSkillText, githubSkillLink } from
10
10
  import { AttachmentError, absoluteAttachments, attachmentPaths, deleteAttachments, imageMime, readAttachmentImages, saveAttachment, sniffImage, } from "../attachments.js";
11
11
  import { MAX_IMAGE_BYTES, MAX_MESSAGE_CHARS, PLAN_TURN_DEADLINE_MS } from "../limits.js";
12
12
  import { newTaskTurns, summariseTurns } from "../metrics.js";
13
+ import { ProviderKeyError, ProviderSignIns, SignInBusyError, isKeyId, isSignInId, saveProviderKey, } from "./provider-auth.js";
13
14
  import { TransitionError, canTransition, checkSpec, describeRefusal, reviewEvidence, } from "../db/lifecycle.js";
14
15
  import { MAX_CARDS, OrchestratorError, EMPTY_TURN_STATS, INTAKE_THINKING_CAP, assignIds, cardVerify, fallbackHandoff, keepListedModels, normaliseCard, normaliseQuestions, runOrchestrator, summarizeConversation, } from "../orchestrator/runtime.js";
15
- import { linkedBoardQuestion, runResearch, taskResearchQuestions, } from "../orchestrator/research.js";
16
+ import { linkedBoardQuestion, runResearch } from "../orchestrator/research.js";
17
+ import { SEARCH_QUESTIONS, searchRepo } from "../orchestrator/retrieval.js";
18
+ import { areaQuestion, areasOf, noteFindings, staleArea, } from "../orchestrator/area-notes.js";
19
+ import { buildCodeMap } from "../repo/code-map.js";
16
20
  import { describeRepo } from "../repo/linked-boards.js";
17
21
  import { ProjectRepoError, validateRepoFolder } from "../repo/project-repos.js";
18
22
  import { pickRepoFolder } from "./repo-picker.js";
@@ -33,7 +37,7 @@ import { consultWatchdog } from "../run/watchdog.js";
33
37
  import { consultReviewer } from "../run/auto-review.js";
34
38
  import { buildCheckFixPrompt, buildCommentPrompt, buildConflictPrompt, buildReviewPrompt, COMMENT_AGENT_PROMPT, CONFLICT_AGENT_PROMPT, REVIEW_AGENT_PROMPT, VERIFIED_CODING_AGENT_PROMPT, } from "../run/prompt.js";
35
39
  import { listCodexModels } from "../run/codex-client.js";
36
- import { listHarnessModels } from "../run/harnesses.js";
40
+ import { HARNESSES, checkHarnessAuth, checkPiModelAuth, detectHarnesses, installHarness, listHarnessModels, } from "../run/harnesses.js";
37
41
  import { profileFor } from "../run/profiles.js";
38
42
  import { readSkills, skillBriefs, skillStoreOf } from "../run/skills.js";
39
43
  import { asMaxAgents, asPlannerThinking } from "../run/settings.js";
@@ -83,6 +87,13 @@ function turnRefusal(c, cause) {
83
87
  }
84
88
  throw cause;
85
89
  }
90
+ /** A harness id the dialog sent that the server does not know; null when it is fine or absent. */
91
+ function unknownHarness(value) {
92
+ if (typeof value !== "string")
93
+ return null;
94
+ const id = value.trim();
95
+ return id && !HARNESSES.some((harness) => harness.id === id) ? id : null;
96
+ }
86
97
  /**
87
98
  * The bottom panel's shells are local only: a pseudoterminal is a shell on the
88
99
  * Mac, so the tunnel allowlist does not carry these routes, and the routes
@@ -129,6 +140,10 @@ class UnknownConversationError extends Error {
129
140
  const EMPTY_ANSWERS = { decided: [], block: "" };
130
141
  /** Repos one intake may send a scout into; more than this is a project, not a card set. */
131
142
  const MAX_REPO_SCOUTS = 2;
143
+ /** How often an idle board checks whether HEAD moved and the code map needs the new files. */
144
+ const CODE_MAP_POLL_MS = 30_000;
145
+ /** How long a folder whose note could not be written waits before another try. */
146
+ const NOTE_RETRY_MS = 60 * 60_000;
132
147
  /** Answers as they arrive from the panel: anything unreadable is simply not an answer. */
133
148
  function asAnswers(value) {
134
149
  if (!Array.isArray(value))
@@ -201,7 +216,7 @@ function applyDecided(cards, decided) {
201
216
  }
202
217
  return out;
203
218
  }
204
- export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl, plan, summarize, harness, setup, listModels, skills: skillStore, plannerThinking, plannerToolBudget, summaryTimeoutMs, runtime, runTimeoutMs, retro, lead, leadEnabled, watchdog, watchdogEnabled, watchdogTickMs, watchdogBackstopMs, autoReview, autoReviewEnabled, redCheckEnabled, testsFirstEnabled, research, researchEnabled, maxRunning, prepare, prepareTicket, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, mergePollMs, index: indexOverride, indexOnStart, onRunsChange, voice: voiceOverride, build: buildOption, phone, terminals: terminalOverride, onLiveChange, repoRegistryFile, repoPicker = { available: process.platform === "darwin", pick: pickRepoFolder }, }) {
219
+ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl, providerAuth, plan, summarize, harness, setup, listModels, skills: skillStore, plannerThinking, plannerToolBudget, summaryTimeoutMs, runtime, runTimeoutMs, retro, lead, leadEnabled, watchdog, watchdogEnabled, watchdogTickMs, watchdogBackstopMs, autoReview, autoReviewEnabled, redCheckEnabled, testsFirstEnabled, research, search, areaNote, areaNotesEnabled, researchEnabled, maxRunning, prepare, prepareTicket, agentPath, ghCommand, factsPollMs, retryPolicy, tokenPublishMs, mergePollMs, index: indexOverride, indexOnStart, onRunsChange, voice: voiceOverride, build: buildOption, phone, terminals: terminalOverride, onLiveChange, repoRegistryFile, repoPicker = { available: process.platform === "darwin", pick: pickRepoFolder }, }) {
205
220
  const app = new Hono();
206
221
  const auth = createAuth({ token, port });
207
222
  const idempotency = createIdempotency(db);
@@ -211,10 +226,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
211
226
  const skills = skillStore ?? skillStoreOf(db);
212
227
  const setupStore = setup ?? memorySetupStore({ harness: "pi", modelChosen: true });
213
228
  const effectiveHarness = () => harness?.trim() || process.env.ZELIO_HARNESS?.trim() || setupStore.read().harness || "pi";
214
- const effectivePlannerModel = () => {
229
+ // A saved model belongs to the harness it was saved under, so a model picked
230
+ // on another harness never falls back to the saved one.
231
+ const plannerModelFor = (command) => {
215
232
  const saved = setupStore.read();
216
- return effectiveHarness() === saved.harness ? saved.plannerModel : "";
233
+ return command === saved.harness ? saved.plannerModel : "";
217
234
  };
235
+ const effectivePlannerModel = () => plannerModelFor(effectiveHarness());
218
236
  const effectiveDeveloperModel = () => {
219
237
  const saved = setupStore.read();
220
238
  return effectiveHarness() === saved.harness ? saved.developerModel : "";
@@ -286,26 +304,111 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
286
304
  // `researchEnabled`; otherwise an intake never has research to start.
287
305
  const researchRunner = research ??
288
306
  (researchEnabled
289
- ? (questions, onFinding) => runResearch(questions, {
307
+ ? (questions, onFinding, choice) => runResearch(questions, {
290
308
  runtime: agentRuntime,
291
309
  cwd: root,
292
310
  cwdFor: (name) => linkedBoards().find((board) => board.name === name)?.root,
293
- command: effectiveHarness(),
294
- model: effectiveDeveloperModel() || undefined,
311
+ command: choice?.command || effectiveHarness(),
312
+ model: choice ? choice.model || undefined : effectiveDeveloperModel() || undefined,
295
313
  onFinding,
296
314
  })
297
315
  : undefined);
316
+ /**
317
+ * The code map, kept against `git HEAD` the way the repo index is. Built when
318
+ * the board starts and refreshed between turns, so a new task's search reads
319
+ * a warm map; a turn that finds HEAD moved waits only for the files that did.
320
+ */
321
+ let codeMap = null;
322
+ let mapping = null;
323
+ const ensureCodeMap = () => {
324
+ mapping ??= (async () => {
325
+ try {
326
+ if (!codeMap || codeMap.head !== (await readHead(root))) {
327
+ codeMap = await buildCodeMap(root, codeMap);
328
+ }
329
+ return codeMap;
330
+ }
331
+ finally {
332
+ mapping = null;
333
+ }
334
+ })();
335
+ return mapping;
336
+ };
337
+ const searcher = search ??
338
+ (researchEnabled
339
+ ? async (description) => searchRepo(description, { root, map: await ensureCodeMap() })
340
+ : undefined);
341
+ const noteWriter = areaNote ??
342
+ (areaNotesEnabled && researchRunner
343
+ ? async (area) => {
344
+ const [finding] = await researchRunner([areaQuestion(area)], () => { });
345
+ const note = finding?.error === null ? finding.answer.trim() : "";
346
+ return note || null;
347
+ }
348
+ : undefined);
349
+ // A folder whose scout failed waits this long before it is tried again.
350
+ const noteFailedAt = new Map();
351
+ let noting = false;
352
+ /** At most one note at a time, and never while a person is waiting on a plan. */
353
+ const refreshAreaNote = async (map) => {
354
+ if (!noteWriter || noting || planning)
355
+ return;
356
+ const now = Date.now();
357
+ const areas = areasOf(map).filter((area) => now - (noteFailedAt.get(area.path) ?? 0) >= NOTE_RETRY_MS);
358
+ const area = staleArea(areas, db.listAreaNotes(), now);
359
+ if (!area)
360
+ return;
361
+ noting = true;
362
+ try {
363
+ const note = await noteWriter(area);
364
+ if (note) {
365
+ db.saveAreaNote({
366
+ path: area.path,
367
+ hash: area.hash,
368
+ head: map.head,
369
+ note,
370
+ written_at: new Date().toISOString(),
371
+ });
372
+ }
373
+ else {
374
+ noteFailedAt.set(area.path, Date.now());
375
+ }
376
+ }
377
+ catch {
378
+ noteFailedAt.set(area.path, Date.now());
379
+ }
380
+ finally {
381
+ noting = false;
382
+ }
383
+ };
384
+ if (researchEnabled && !search && indexOnStart) {
385
+ void ensureCodeMap().catch(() => undefined);
386
+ // One git call while idle, a rebuild only when an agent's commit moved HEAD,
387
+ // and at most one folder note per tick.
388
+ setInterval(() => {
389
+ if (planning)
390
+ return;
391
+ void ensureCodeMap()
392
+ .then(refreshAreaNote)
393
+ .catch(() => undefined);
394
+ }, CODE_MAP_POLL_MS).unref();
395
+ }
396
+ /** The reading, plus the notes for the folders its search placed the change in. */
397
+ const withNotes = (findings) => findings && [
398
+ ...findings,
399
+ ...noteFindings(findings.find((finding) => finding.question === SEARCH_QUESTIONS.where), db.listAreaNotes()),
400
+ ];
298
401
  // Readings started by an intake, keyed by the conversation they belong to. The
299
402
  // answer turn takes its own; a reading nobody asks for is dropped after a while.
300
403
  const pendingResearch = new Map();
301
- const startResearch = (conversationId, questions) => {
302
- if (!researchRunner || questions.length === 0)
303
- return undefined;
404
+ /** One row per reading, like a planner turn, and a TTL so an unanswered one is dropped. */
405
+ const startReading = (conversationId, total, read, choice) => {
304
406
  const startedAt = Date.now();
305
407
  const reading = {
306
408
  promise: Promise.resolve([]),
307
409
  done: 0,
308
- total: questions.length,
410
+ total,
411
+ choice,
309
412
  };
310
413
  // One row per reading, like a planner turn. It never throws.
311
414
  const record = (ok, error) => {
@@ -326,7 +429,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
326
429
  capped: null,
327
430
  prompt_chars: 0,
328
431
  output_chars: 0,
329
- questions: questions.length,
432
+ questions: total,
330
433
  cards: 0,
331
434
  started_at: new Date(startedAt).toISOString(),
332
435
  });
@@ -335,7 +438,9 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
335
438
  // The log is diagnostics only.
336
439
  }
337
440
  };
338
- reading.promise = runReading(reading, questions).then((findings) => {
441
+ reading.promise = Promise.resolve()
442
+ .then(() => read(reading))
443
+ .then((findings) => {
339
444
  record(true, null);
340
445
  return findings;
341
446
  }, (cause) => {
@@ -353,23 +458,39 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
353
458
  });
354
459
  return reading;
355
460
  };
461
+ const startResearch = (conversationId, questions, choice) => researchRunner && questions.length > 0
462
+ ? startReading(conversationId, questions.length, (reading) => runReading(reading, questions), choice)
463
+ : undefined;
464
+ /**
465
+ * A new task's reading of this repo: one code search, counted as the three
466
+ * findings it returns. `choice` rides along for the linked-repo scouts an
467
+ * intake may add to the same reading.
468
+ */
469
+ const startSearch = (conversationId, description, choice) => searcher
470
+ ? startReading(conversationId, Object.keys(SEARCH_QUESTIONS).length, async (reading) => {
471
+ const findings = await searcher(description);
472
+ reading.done += findings.length;
473
+ reading.listener?.(reading.done, reading.total);
474
+ return findings;
475
+ }, choice)
476
+ : undefined;
356
477
  /** One batch of scouts on a reading; `done` counts across every batch it has. */
357
478
  function runReading(reading, questions) {
358
479
  return Promise.resolve().then(() => researchRunner(questions, () => {
359
480
  reading.done += 1;
360
481
  reading.listener?.(reading.done, reading.total);
361
- }));
482
+ }, reading.choice));
362
483
  }
363
484
  /**
364
485
  * Adds scouts to a reading already under way, for the linked boards the
365
486
  * intake named. The answer turn waits for both batches as one reading.
366
487
  */
367
- const extendResearch = (conversationId, questions) => {
488
+ const extendResearch = (conversationId, questions, choice) => {
368
489
  if (!researchRunner || questions.length === 0)
369
490
  return;
370
491
  const reading = pendingResearch.get(conversationId);
371
492
  if (!reading) {
372
- startResearch(conversationId, questions);
493
+ startResearch(conversationId, questions, choice);
373
494
  return;
374
495
  }
375
496
  reading.total += questions.length;
@@ -895,36 +1016,47 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
895
1016
  skills: skillBriefs(readSkills(skills)),
896
1017
  };
897
1018
  };
1019
+ /**
1020
+ * The harness and model one planner turn runs on: the dialog's pick for the
1021
+ * turn, else the board's harness and its saved model.
1022
+ */
1023
+ const plannerChoice = (turnHarness, turnModel) => {
1024
+ const command = turnHarness || effectiveHarness();
1025
+ return { command, model: turnModel || plannerModelFor(command) };
1026
+ };
898
1027
  const runPlan = plan ??
899
- (async (messages, brief, draft, board, onStatus, handoff, mode, onStats, attachments = [], images = [], thinking, findings, timeoutMs, linked, turnModel) => runOrchestrator({
900
- repoRoot: root,
901
- messages,
902
- brief,
903
- plan: draft,
904
- board,
905
- handoff,
906
- // The door changes the directive. Dropping it here silently gave every
907
- // real turn the chat prompt while tests saw the new-task one.
908
- mode,
909
- attachments,
910
- images,
911
- command: effectiveHarness(),
912
- // The dialog's choice for this turn, else the saved planner model.
913
- planner: createPlanner(effectiveHarness(), turnModel || effectivePlannerModel()),
914
- model: turnModel || effectivePlannerModel() || undefined,
915
- thinking: thinking ?? plannerThinkingForTurn(),
916
- budget: plannerToolBudget,
917
- // The planner and the run it writes for must agree on what "done" means;
918
- // otherwise every ticket it drafts asks for a check the run will skip.
919
- workflow: db.getStageWorkflow("in_progress"),
920
- onStatus,
921
- onStats,
922
- research: findings,
923
- timeoutMs,
924
- linkedBoards: linked,
925
- // The intake drafts no run, so it does not wait on a model list.
926
- developer: mode === "intake" ? null : await developerBrief(),
927
- }));
1028
+ (async (messages, brief, draft, board, onStatus, handoff, mode, onStats, attachments = [], images = [], thinking, findings, timeoutMs, linked, turnModel, turnHarness) => {
1029
+ const choice = plannerChoice(turnHarness, turnModel);
1030
+ return runOrchestrator({
1031
+ repoRoot: root,
1032
+ messages,
1033
+ brief,
1034
+ plan: draft,
1035
+ board,
1036
+ handoff,
1037
+ // The door changes the directive. Dropping it here silently gave every
1038
+ // real turn the chat prompt while tests saw the new-task one.
1039
+ mode,
1040
+ attachments,
1041
+ images,
1042
+ command: choice.command,
1043
+ // The dialog's choices for this turn, else the saved planner model for that harness.
1044
+ planner: createPlanner(choice.command, choice.model),
1045
+ model: choice.model || undefined,
1046
+ thinking: thinking ?? plannerThinkingForTurn(),
1047
+ budget: plannerToolBudget,
1048
+ // The planner and the run it writes for must agree on what "done" means;
1049
+ // otherwise every ticket it drafts asks for a check the run will skip.
1050
+ workflow: db.getStageWorkflow("in_progress"),
1051
+ onStatus,
1052
+ onStats,
1053
+ research: findings,
1054
+ timeoutMs,
1055
+ linkedBoards: linked,
1056
+ // The intake drafts no run, so it does not wait on a model list.
1057
+ developer: mode === "intake" ? null : await developerBrief(),
1058
+ });
1059
+ });
928
1060
  // A test that injected the planner explicitly asked for no subprocess. Only
929
1061
  // an explicitly named harness (or a summary injection) opts back in.
930
1062
  const harnessNamed = harness !== undefined || process.env.ZELIO_HARNESS !== undefined;
@@ -1053,6 +1185,47 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
1053
1185
  effectiveDeveloperModel: effectiveDeveloperModel(),
1054
1186
  });
1055
1187
  app.get("/api/setup", (c) => c.json({ setup: setupResponse() }));
1188
+ const providerSignIns = new ProviderSignIns(providerAuth?.signIn);
1189
+ const keyDeps = providerAuth?.keys ?? {};
1190
+ app.get("/api/providers", async (c) => {
1191
+ const detected = await detectHarnesses();
1192
+ const installed = Object.fromEntries(detected.map((item) => [item.id, item.installed]));
1193
+ const [claude, openai, piOpenAISubscription, piOpenAIKey, deepseek, googleSubscription, googleApiKey,] = await Promise.all([
1194
+ checkHarnessAuth("claude"),
1195
+ checkHarnessAuth("codex"),
1196
+ checkPiModelAuth("openai-codex/gpt-5"),
1197
+ checkPiModelAuth("openai/gpt-5"),
1198
+ checkPiModelAuth("deepseek/deepseek-chat"),
1199
+ checkPiModelAuth("google-gemini-cli/gemini-2.5-pro"),
1200
+ checkPiModelAuth("google/gemini-2.5-pro"),
1201
+ ]);
1202
+ return c.json({
1203
+ providers: {
1204
+ installed,
1205
+ signIns: providerSignIns.snapshot(),
1206
+ claude,
1207
+ openai,
1208
+ piOpenAISubscription,
1209
+ piOpenAIKey,
1210
+ deepseek,
1211
+ googleSubscription,
1212
+ googleApiKey,
1213
+ },
1214
+ });
1215
+ });
1216
+ app.post("/api/providers/pi/install", async (c) => {
1217
+ if (c.get("principal").kind !== "local") {
1218
+ return c.json({ error: "Pi can only be installed from the local board" }, 403);
1219
+ }
1220
+ try {
1221
+ await installHarness("pi");
1222
+ return c.json({ installed: true });
1223
+ }
1224
+ catch (cause) {
1225
+ const message = cause instanceof Error ? cause.message : "Pi installation failed";
1226
+ return c.json({ error: message }, 500);
1227
+ }
1228
+ });
1056
1229
  app.put("/api/setup", async (c) => {
1057
1230
  const body = await c.req
1058
1231
  .json()
@@ -1301,6 +1474,52 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
1301
1474
  return c.json({ comment }, 201);
1302
1475
  });
1303
1476
  app.use("/api/*", auth, idempotency);
1477
+ /**
1478
+ * Sign-in and key saves change this machine's credentials, so both are local
1479
+ * only. They sit below the auth registration on purpose: Hono runs handlers in
1480
+ * registration order, so a route above it would never see the principal.
1481
+ */
1482
+ app.post("/api/providers/:provider/sign-in", async (c) => {
1483
+ if (c.get("principal").kind !== "local") {
1484
+ return c.json({ error: "Sign-in is available from the local board only" }, 403);
1485
+ }
1486
+ const provider = c.req.param("provider");
1487
+ if (!isSignInId(provider))
1488
+ return c.json({ error: "This provider has no sign-in" }, 404);
1489
+ try {
1490
+ return c.json({ signIn: await providerSignIns.start(provider) });
1491
+ }
1492
+ catch (cause) {
1493
+ if (cause instanceof SignInBusyError) {
1494
+ return c.json({ error: cause.message, code: "busy" }, 409);
1495
+ }
1496
+ throw cause;
1497
+ }
1498
+ });
1499
+ app.post("/api/providers/:provider/key", async (c) => {
1500
+ if (c.get("principal").kind !== "local") {
1501
+ return c.json({ error: "API keys are saved from the local board only" }, 403);
1502
+ }
1503
+ const provider = c.req.param("provider");
1504
+ if (!isKeyId(provider))
1505
+ return c.json({ error: "This provider does not take a key" }, 404);
1506
+ const body = await c.req.json().catch(() => ({}));
1507
+ const key = typeof body.key === "string" ? body.key.trim() : "";
1508
+ if (!key)
1509
+ return c.json({ error: "Enter an API key" }, 400);
1510
+ if (key.length > 500 || /\s/.test(key)) {
1511
+ return c.json({ error: "That does not look like an API key. Paste the whole key." }, 400);
1512
+ }
1513
+ try {
1514
+ await saveProviderKey(provider, key, keyDeps);
1515
+ return c.json({ saved: true });
1516
+ }
1517
+ catch (cause) {
1518
+ if (cause instanceof ProviderKeyError)
1519
+ return c.json({ error: cause.message }, cause.status);
1520
+ return c.json({ error: "Could not save the key" }, 500);
1521
+ }
1522
+ });
1304
1523
  /**
1305
1524
  * Who the caller is and what it may do. The phone uses this to hide controls
1306
1525
  * the tunnel allowlist would refuse anyway; the server stays the authority.
@@ -2209,8 +2428,14 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2209
2428
  else {
2210
2429
  conversation = db.appendMessage("user", said, "message", conversation.id);
2211
2430
  }
2212
- // Start scouts before the index and intake, using only the original description.
2213
- const intakeReading = mode === "intake" ? startResearch(conversation.id, taskResearchQuestions(text)) : undefined;
2431
+ // The reading starts with the request, from the original description only:
2432
+ // a code search here, and scouts for any linked repo the intake names.
2433
+ const intakeReading = mode === "intake"
2434
+ ? startSearch(conversation.id, text, plannerChoice(options.harness, options.model))
2435
+ : undefined;
2436
+ // With no linked repo there is nothing for the intake to decide that the
2437
+ // draft cannot: the search has already read, so the first pass is the draft.
2438
+ const merged = mode === "intake" && candidates.length === 0;
2214
2439
  // Waiting here is usually free: the index is built at startup and the
2215
2440
  // head check is one git call. When it is not free — a first run, or a
2216
2441
  // checkout that just changed — the build is minutes of silence with no
@@ -2231,7 +2456,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2231
2456
  }, attachments, images, passThinking, findings,
2232
2457
  // What is left of the request, not a fresh clock per pass: the intake,
2233
2458
  // the scouts and the draft share one deadline, and the planner is told it.
2234
- Math.max(MIN_PASS_MS, PLAN_TURN_DEADLINE_MS - (Date.now() - startedAt)), repoBriefs, options.model);
2459
+ Math.max(MIN_PASS_MS, PLAN_TURN_DEADLINE_MS - (Date.now() - startedAt)), repoBriefs, options.model, options.harness);
2235
2460
  };
2236
2461
  // Saves what the planner decided. Research is a planner input, not part of
2237
2462
  // the plan the dialog reads, so it is not stored.
@@ -2267,17 +2492,20 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2267
2492
  }, conversation.id);
2268
2493
  return { saved, questions: next.questions.length, cards: cards.length };
2269
2494
  };
2270
- // An answer turn in the wizard reads what its intake started, first.
2271
- let findings;
2272
- if (mode === "new-task") {
2273
- const reading = pendingResearch.get(target.id);
2274
- if (reading) {
2275
- pendingResearch.delete(target.id);
2276
- findings = forDraft(await awaitReading(reading));
2277
- }
2278
- }
2279
- const drafted = await planOnce(mode, findings);
2280
- if (mode === "intake") {
2495
+ // A draft reads what the request started: the merged first pass its own
2496
+ // search, an answer turn what its intake began. The reading stays until it
2497
+ // expires, so a second round of answers or a comment on the draft reads it too.
2498
+ const pass = merged ? "new-task" : mode;
2499
+ if (merged)
2500
+ door = "new-task";
2501
+ const reading = merged
2502
+ ? intakeReading
2503
+ : mode === "new-task"
2504
+ ? pendingResearch.get(target.id)
2505
+ : undefined;
2506
+ const findings = reading ? withNotes(forDraft(await awaitReading(reading))) : undefined;
2507
+ const drafted = await planOnce(pass, findings);
2508
+ if (pass === "intake") {
2281
2509
  // The intake names the repos the work may touch. A scout starts reading
2282
2510
  // each one now, so the draft has its findings without asking the person.
2283
2511
  const onBoard = new Set(candidates.map((repo) => repo.name));
@@ -2286,14 +2514,14 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2286
2514
  const named = [...new Set(drafted.boards ?? [])]
2287
2515
  .filter((name) => onBoard.has(name))
2288
2516
  .slice(0, MAX_REPO_SCOUTS);
2289
- extendResearch(conversation.id, named.map((name) => linkedBoardQuestion(name, text)));
2517
+ extendResearch(conversation.id, named.map((name) => linkedBoardQuestion(name, text)), plannerChoice(options.harness, options.model));
2290
2518
  }
2291
2519
  let outcome;
2292
- if (mode !== "intake") {
2520
+ if (pass !== "intake") {
2293
2521
  outcome = store(drafted);
2294
2522
  }
2295
2523
  else {
2296
- // Scouts have been running since the request arrived.
2524
+ // The reading has been running since the request arrived.
2297
2525
  if (normaliseQuestions(drafted.questions).length > 0) {
2298
2526
  outcome = store({ ...drafted, cards: [] });
2299
2527
  }
@@ -2301,8 +2529,10 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2301
2529
  // Nothing to ask and nothing drafted: the intake's row is recorded, then
2302
2530
  // the draft waits for the reading in this same request.
2303
2531
  measure({ ok: true });
2304
- pendingResearch.delete(conversation.id);
2305
- const readFirst = intakeReading ? forDraft(await awaitReading(intakeReading)) : undefined;
2532
+ // The map, not `intakeReading`: linked-repo scouts may have started a
2533
+ // reading of their own when this board searches nothing.
2534
+ const started = pendingResearch.get(conversation.id);
2535
+ const readFirst = started ? withNotes(forDraft(await awaitReading(started))) : undefined;
2306
2536
  door = "new-task";
2307
2537
  rowStartedAt = Date.now();
2308
2538
  indexMs = 0;
@@ -2341,10 +2571,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2341
2571
  .catch(() => ({}));
2342
2572
  const text = typeof body.text === "string" ? body.text.trim() : "";
2343
2573
  const thinking = asThinking(body.thinking);
2574
+ const badHarness = unknownHarness(body.harness);
2344
2575
  if (!text)
2345
2576
  return c.json({ error: "text is required" }, 400);
2346
2577
  if (thinking === null)
2347
2578
  return c.json({ error: "unknown thinking level" }, 400);
2579
+ if (badHarness)
2580
+ return c.json({ error: `unknown harness: ${badHarness}` }, 400);
2348
2581
  if (text.length > MAX_MESSAGE_CHARS)
2349
2582
  return c.json({ error: "message too long" }, 400);
2350
2583
  const attachments = attachmentPaths(body.attachments);
@@ -2358,6 +2591,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2358
2591
  attachments,
2359
2592
  thinking: thinking ?? undefined,
2360
2593
  model: typeof body.model === "string" ? body.model.trim() || undefined : undefined,
2594
+ harness: typeof body.harness === "string" ? body.harness.trim() || undefined : undefined,
2361
2595
  }),
2362
2596
  });
2363
2597
  }
@@ -2396,10 +2630,13 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2396
2630
  .catch(() => ({}));
2397
2631
  const text = typeof body.text === "string" ? body.text.trim() : "";
2398
2632
  const thinking = asThinking(body.thinking);
2633
+ const badHarness = unknownHarness(body.harness);
2399
2634
  if (!text)
2400
2635
  return c.json({ error: "a description is required" }, 400);
2401
2636
  if (thinking === null)
2402
2637
  return c.json({ error: "unknown thinking level" }, 400);
2638
+ if (badHarness)
2639
+ return c.json({ error: `unknown harness: ${badHarness}` }, 400);
2403
2640
  if (text.length > MAX_MESSAGE_CHARS) {
2404
2641
  return c.json({ error: "that description is too long" }, 400);
2405
2642
  }
@@ -2419,6 +2656,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2419
2656
  attachments,
2420
2657
  thinking: thinking ?? undefined,
2421
2658
  model: typeof body.model === "string" ? body.model.trim() || undefined : undefined,
2659
+ harness: typeof body.harness === "string" ? body.harness.trim() || undefined : undefined,
2422
2660
  }),
2423
2661
  });
2424
2662
  }