zelio-cli 0.1.0-beta.5 → 0.1.0-beta.7

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 (47) hide show
  1. package/dist/cli.js +5 -1
  2. package/dist/cli.js.map +1 -1
  3. package/dist/db/db.js +74 -4
  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/contract.js +4 -3
  10. package/dist/orchestrator/contract.js.map +1 -1
  11. package/dist/orchestrator/new-task-prompt.js +4 -4
  12. package/dist/orchestrator/prompt.js +4 -4
  13. package/dist/orchestrator/research.js +27 -12
  14. package/dist/orchestrator/research.js.map +1 -1
  15. package/dist/orchestrator/retrieval.js +333 -0
  16. package/dist/orchestrator/retrieval.js.map +1 -0
  17. package/dist/orchestrator/runtime.js +12 -10
  18. package/dist/orchestrator/runtime.js.map +1 -1
  19. package/dist/repo/code-map.js +152 -0
  20. package/dist/repo/code-map.js.map +1 -0
  21. package/dist/run/codex-planner-config.js +26 -0
  22. package/dist/run/codex-planner-config.js.map +1 -0
  23. package/dist/run/codex-runtime.js +9 -0
  24. package/dist/run/codex-runtime.js.map +1 -1
  25. package/dist/run/harnesses.js +5 -0
  26. package/dist/run/harnesses.js.map +1 -1
  27. package/dist/run/manager.js +27 -7
  28. package/dist/run/manager.js.map +1 -1
  29. package/dist/run/prompt.js +3 -3
  30. package/dist/run/prompt.js.map +1 -1
  31. package/dist/run/settings.js +4 -3
  32. package/dist/run/settings.js.map +1 -1
  33. package/dist/server/app.js +328 -51
  34. package/dist/server/app.js.map +1 -1
  35. package/dist/server/provider-auth.js +206 -0
  36. package/dist/server/provider-auth.js.map +1 -0
  37. package/dist/server/terminal.js +2 -2
  38. package/dist/server/terminal.js.map +1 -1
  39. package/dist/setup/onboarding.js +7 -12
  40. package/dist/setup/onboarding.js.map +1 -1
  41. package/dist/web/assets/index-C65GAaps.js +255 -0
  42. package/dist/web/assets/index-cF8zhiLs.css +1 -0
  43. package/dist/web/index.html +2 -2
  44. package/dist/web/sw.js +1 -1
  45. package/package.json +1 -1
  46. package/dist/web/assets/index-Bua_eeem.js +0 -255
  47. package/dist/web/assets/index-Iz1ACqw-.css +0 -1
@@ -1,6 +1,8 @@
1
1
  import { Hono } from "hono";
2
2
  import { streamSSE } from "hono/streaming";
3
3
  import { randomBytes } from "node:crypto";
4
+ import { execFile } from "node:child_process";
5
+ import { promisify } from "node:util";
4
6
  import { existsSync } from "node:fs";
5
7
  import { readFile } from "node:fs/promises";
6
8
  import { basename, join } from "node:path";
@@ -10,9 +12,13 @@ import { checkSkillName, checkSkillText, fetchSkillText, githubSkillLink } from
10
12
  import { AttachmentError, absoluteAttachments, attachmentPaths, deleteAttachments, imageMime, readAttachmentImages, saveAttachment, sniffImage, } from "../attachments.js";
11
13
  import { MAX_IMAGE_BYTES, MAX_MESSAGE_CHARS, PLAN_TURN_DEADLINE_MS } from "../limits.js";
12
14
  import { newTaskTurns, summariseTurns } from "../metrics.js";
15
+ import { ProviderKeyError, ProviderSignIns, SignInBusyError, isKeyId, isSignInId, saveProviderKey, } from "./provider-auth.js";
13
16
  import { TransitionError, canTransition, checkSpec, describeRefusal, reviewEvidence, } from "../db/lifecycle.js";
14
17
  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";
18
+ import { linkedBoardQuestion, runResearch } from "../orchestrator/research.js";
19
+ import { SEARCH_QUESTIONS, searchRepo } from "../orchestrator/retrieval.js";
20
+ import { areaQuestion, areasOf, noteFindings, staleArea, } from "../orchestrator/area-notes.js";
21
+ import { buildCodeMap } from "../repo/code-map.js";
16
22
  import { describeRepo } from "../repo/linked-boards.js";
17
23
  import { ProjectRepoError, validateRepoFolder } from "../repo/project-repos.js";
18
24
  import { pickRepoFolder } from "./repo-picker.js";
@@ -33,7 +39,7 @@ import { consultWatchdog } from "../run/watchdog.js";
33
39
  import { consultReviewer } from "../run/auto-review.js";
34
40
  import { buildCheckFixPrompt, buildCommentPrompt, buildConflictPrompt, buildReviewPrompt, COMMENT_AGENT_PROMPT, CONFLICT_AGENT_PROMPT, REVIEW_AGENT_PROMPT, VERIFIED_CODING_AGENT_PROMPT, } from "../run/prompt.js";
35
41
  import { listCodexModels } from "../run/codex-client.js";
36
- import { HARNESSES, listHarnessModels } from "../run/harnesses.js";
42
+ import { HARNESSES, checkHarnessAuth, checkPiModelAuth, detectHarnesses, installHarness, listHarnessModels, } from "../run/harnesses.js";
37
43
  import { profileFor } from "../run/profiles.js";
38
44
  import { readSkills, skillBriefs, skillStoreOf } from "../run/skills.js";
39
45
  import { asMaxAgents, asPlannerThinking } from "../run/settings.js";
@@ -136,6 +142,10 @@ class UnknownConversationError extends Error {
136
142
  const EMPTY_ANSWERS = { decided: [], block: "" };
137
143
  /** Repos one intake may send a scout into; more than this is a project, not a card set. */
138
144
  const MAX_REPO_SCOUTS = 2;
145
+ /** How often an idle board checks whether HEAD moved and the code map needs the new files. */
146
+ const CODE_MAP_POLL_MS = 30_000;
147
+ /** How long a folder whose note could not be written waits before another try. */
148
+ const NOTE_RETRY_MS = 60 * 60_000;
139
149
  /** Answers as they arrive from the panel: anything unreadable is simply not an answer. */
140
150
  function asAnswers(value) {
141
151
  if (!Array.isArray(value))
@@ -208,7 +218,7 @@ function applyDecided(cards, decided) {
208
218
  }
209
219
  return out;
210
220
  }
211
- 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 }, }) {
221
+ 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 }, }) {
212
222
  const app = new Hono();
213
223
  const auth = createAuth({ token, port });
214
224
  const idempotency = createIdempotency(db);
@@ -239,6 +249,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
239
249
  const plannerThinkingForTurn = () => plannerThinking ?? db.getBoardSettings().plannerThinking;
240
250
  const testsFirstForcedOff = () => testsFirstEnabled === false || process.env.ZELIO_TESTS_FIRST === "off";
241
251
  const testsFirstForRun = () => !testsFirstForcedOff() && db.getBoardSettings().testsFirstEnabled;
252
+ const plannerChoiceForRun = () => db.getBoardSettings().plannerChoiceEnabled;
242
253
  const prepareOverride = prepare ?? prepareTicket;
243
254
  // One planning run at a time. Two in flight would cost twice and race on
244
255
  // creating the same cards.
@@ -296,26 +307,111 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
296
307
  // `researchEnabled`; otherwise an intake never has research to start.
297
308
  const researchRunner = research ??
298
309
  (researchEnabled
299
- ? (questions, onFinding) => runResearch(questions, {
310
+ ? (questions, onFinding, choice) => runResearch(questions, {
300
311
  runtime: agentRuntime,
301
312
  cwd: root,
302
313
  cwdFor: (name) => linkedBoards().find((board) => board.name === name)?.root,
303
- command: effectiveHarness(),
304
- model: effectiveDeveloperModel() || undefined,
314
+ command: choice?.command || effectiveHarness(),
315
+ model: choice ? choice.model || undefined : effectiveDeveloperModel() || undefined,
305
316
  onFinding,
306
317
  })
307
318
  : undefined);
319
+ /**
320
+ * The code map, kept against `git HEAD` the way the repo index is. Built when
321
+ * the board starts and refreshed between turns, so a new task's search reads
322
+ * a warm map; a turn that finds HEAD moved waits only for the files that did.
323
+ */
324
+ let codeMap = null;
325
+ let mapping = null;
326
+ const ensureCodeMap = () => {
327
+ mapping ??= (async () => {
328
+ try {
329
+ if (!codeMap || codeMap.head !== (await readHead(root))) {
330
+ codeMap = await buildCodeMap(root, codeMap);
331
+ }
332
+ return codeMap;
333
+ }
334
+ finally {
335
+ mapping = null;
336
+ }
337
+ })();
338
+ return mapping;
339
+ };
340
+ const searcher = search ??
341
+ (researchEnabled
342
+ ? async (description) => searchRepo(description, { root, map: await ensureCodeMap() })
343
+ : undefined);
344
+ const noteWriter = areaNote ??
345
+ (areaNotesEnabled && researchRunner
346
+ ? async (area) => {
347
+ const [finding] = await researchRunner([areaQuestion(area)], () => { });
348
+ const note = finding?.error === null ? finding.answer.trim() : "";
349
+ return note || null;
350
+ }
351
+ : undefined);
352
+ // A folder whose scout failed waits this long before it is tried again.
353
+ const noteFailedAt = new Map();
354
+ let noting = false;
355
+ /** At most one note at a time, and never while a person is waiting on a plan. */
356
+ const refreshAreaNote = async (map) => {
357
+ if (!noteWriter || noting || planning)
358
+ return;
359
+ const now = Date.now();
360
+ const areas = areasOf(map).filter((area) => now - (noteFailedAt.get(area.path) ?? 0) >= NOTE_RETRY_MS);
361
+ const area = staleArea(areas, db.listAreaNotes(), now);
362
+ if (!area)
363
+ return;
364
+ noting = true;
365
+ try {
366
+ const note = await noteWriter(area);
367
+ if (note) {
368
+ db.saveAreaNote({
369
+ path: area.path,
370
+ hash: area.hash,
371
+ head: map.head,
372
+ note,
373
+ written_at: new Date().toISOString(),
374
+ });
375
+ }
376
+ else {
377
+ noteFailedAt.set(area.path, Date.now());
378
+ }
379
+ }
380
+ catch {
381
+ noteFailedAt.set(area.path, Date.now());
382
+ }
383
+ finally {
384
+ noting = false;
385
+ }
386
+ };
387
+ if (researchEnabled && !search && indexOnStart) {
388
+ void ensureCodeMap().catch(() => undefined);
389
+ // One git call while idle, a rebuild only when an agent's commit moved HEAD,
390
+ // and at most one folder note per tick.
391
+ setInterval(() => {
392
+ if (planning)
393
+ return;
394
+ void ensureCodeMap()
395
+ .then(refreshAreaNote)
396
+ .catch(() => undefined);
397
+ }, CODE_MAP_POLL_MS).unref();
398
+ }
399
+ /** The reading, plus the notes for the folders its search placed the change in. */
400
+ const withNotes = (findings) => findings && [
401
+ ...findings,
402
+ ...noteFindings(findings.find((finding) => finding.question === SEARCH_QUESTIONS.where), db.listAreaNotes()),
403
+ ];
308
404
  // Readings started by an intake, keyed by the conversation they belong to. The
309
405
  // answer turn takes its own; a reading nobody asks for is dropped after a while.
310
406
  const pendingResearch = new Map();
311
- const startResearch = (conversationId, questions) => {
312
- if (!researchRunner || questions.length === 0)
313
- return undefined;
407
+ /** One row per reading, like a planner turn, and a TTL so an unanswered one is dropped. */
408
+ const startReading = (conversationId, total, read, choice) => {
314
409
  const startedAt = Date.now();
315
410
  const reading = {
316
411
  promise: Promise.resolve([]),
317
412
  done: 0,
318
- total: questions.length,
413
+ total,
414
+ choice,
319
415
  };
320
416
  // One row per reading, like a planner turn. It never throws.
321
417
  const record = (ok, error) => {
@@ -336,7 +432,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
336
432
  capped: null,
337
433
  prompt_chars: 0,
338
434
  output_chars: 0,
339
- questions: questions.length,
435
+ questions: total,
340
436
  cards: 0,
341
437
  started_at: new Date(startedAt).toISOString(),
342
438
  });
@@ -345,7 +441,9 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
345
441
  // The log is diagnostics only.
346
442
  }
347
443
  };
348
- reading.promise = runReading(reading, questions).then((findings) => {
444
+ reading.promise = Promise.resolve()
445
+ .then(() => read(reading))
446
+ .then((findings) => {
349
447
  record(true, null);
350
448
  return findings;
351
449
  }, (cause) => {
@@ -363,23 +461,39 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
363
461
  });
364
462
  return reading;
365
463
  };
464
+ const startResearch = (conversationId, questions, choice) => researchRunner && questions.length > 0
465
+ ? startReading(conversationId, questions.length, (reading) => runReading(reading, questions), choice)
466
+ : undefined;
467
+ /**
468
+ * A new task's reading of this repo: one code search, counted as the three
469
+ * findings it returns. `choice` rides along for the linked-repo scouts an
470
+ * intake may add to the same reading.
471
+ */
472
+ const startSearch = (conversationId, description, choice) => searcher
473
+ ? startReading(conversationId, Object.keys(SEARCH_QUESTIONS).length, async (reading) => {
474
+ const findings = await searcher(description);
475
+ reading.done += findings.length;
476
+ reading.listener?.(reading.done, reading.total);
477
+ return findings;
478
+ }, choice)
479
+ : undefined;
366
480
  /** One batch of scouts on a reading; `done` counts across every batch it has. */
367
481
  function runReading(reading, questions) {
368
482
  return Promise.resolve().then(() => researchRunner(questions, () => {
369
483
  reading.done += 1;
370
484
  reading.listener?.(reading.done, reading.total);
371
- }));
485
+ }, reading.choice));
372
486
  }
373
487
  /**
374
488
  * Adds scouts to a reading already under way, for the linked boards the
375
489
  * intake named. The answer turn waits for both batches as one reading.
376
490
  */
377
- const extendResearch = (conversationId, questions) => {
491
+ const extendResearch = (conversationId, questions, choice) => {
378
492
  if (!researchRunner || questions.length === 0)
379
493
  return;
380
494
  const reading = pendingResearch.get(conversationId);
381
495
  if (!reading) {
382
- startResearch(conversationId, questions);
496
+ startResearch(conversationId, questions, choice);
383
497
  return;
384
498
  }
385
499
  reading.total += questions.length;
@@ -481,7 +595,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
481
595
  ...(watchdogTickMs ? { tickMs: watchdogTickMs } : {}),
482
596
  ...(watchdogBackstopMs ? { backstopMs: watchdogBackstopMs } : {}),
483
597
  }
484
- : undefined);
598
+ : undefined, plannerChoiceForRun);
485
599
  /**
486
600
  * The ticket's checkout, with its branch recorded on the row the first time.
487
601
  * Every path that starts work goes through here: a branch that exists on disk
@@ -630,6 +744,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
630
744
  verify: normaliseVerify(card.verify),
631
745
  state: "todo",
632
746
  quick: true,
747
+ planner_harness: source.planner_harness,
633
748
  repo: source.repo,
634
749
  });
635
750
  }
@@ -894,13 +1009,17 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
894
1009
  listedModels.set(command, { at: Date.now(), models });
895
1010
  return models;
896
1011
  };
897
- const developerBrief = async () => {
1012
+ const developerBrief = async (plannerHarness) => {
898
1013
  const profile = db.getProfile("developer") ?? profileFor("developer");
899
- const command = profile.harness.trim() || effectiveHarness();
1014
+ const command = plannerChoiceForRun() && plannerHarness
1015
+ ? plannerHarness
1016
+ : profile.harness.trim() || effectiveHarness();
1017
+ const profileHarness = profile.harness.trim() || effectiveHarness();
900
1018
  return {
901
1019
  harness: command,
902
1020
  models: await harnessModels(command),
903
- model: profile.model.trim() || (command === effectiveHarness() ? effectiveDeveloperModel() : ""),
1021
+ model: (command === profileHarness ? profile.model.trim() : "") ||
1022
+ (command === effectiveHarness() ? effectiveDeveloperModel() : ""),
904
1023
  thinking: profile.thinking,
905
1024
  skills: skillBriefs(readSkills(skills)),
906
1025
  };
@@ -911,7 +1030,10 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
911
1030
  */
912
1031
  const plannerChoice = (turnHarness, turnModel) => {
913
1032
  const command = turnHarness || effectiveHarness();
914
- return { command, model: turnModel || plannerModelFor(command) };
1033
+ return {
1034
+ command,
1035
+ model: turnModel === undefined ? plannerModelFor(command) : turnModel.trim(),
1036
+ };
915
1037
  };
916
1038
  const runPlan = plan ??
917
1039
  (async (messages, brief, draft, board, onStatus, handoff, mode, onStats, attachments = [], images = [], thinking, findings, timeoutMs, linked, turnModel, turnHarness) => {
@@ -943,7 +1065,9 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
943
1065
  timeoutMs,
944
1066
  linkedBoards: linked,
945
1067
  // The intake drafts no run, so it does not wait on a model list.
946
- developer: mode === "intake" ? null : await developerBrief(),
1068
+ developer: mode === "intake"
1069
+ ? null
1070
+ : await developerBrief(plannerChoice(turnHarness, turnModel).command),
947
1071
  });
948
1072
  });
949
1073
  // A test that injected the planner explicitly asked for no subprocess. Only
@@ -1074,6 +1198,47 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
1074
1198
  effectiveDeveloperModel: effectiveDeveloperModel(),
1075
1199
  });
1076
1200
  app.get("/api/setup", (c) => c.json({ setup: setupResponse() }));
1201
+ const providerSignIns = new ProviderSignIns(providerAuth?.signIn);
1202
+ const keyDeps = providerAuth?.keys ?? {};
1203
+ app.get("/api/providers", async (c) => {
1204
+ const detected = await detectHarnesses();
1205
+ const installed = Object.fromEntries(detected.map((item) => [item.id, item.installed]));
1206
+ const [claude, openai, piOpenAISubscription, piOpenAIKey, deepseek, googleSubscription, googleApiKey,] = await Promise.all([
1207
+ checkHarnessAuth("claude"),
1208
+ checkHarnessAuth("codex"),
1209
+ checkPiModelAuth("openai-codex/gpt-5"),
1210
+ checkPiModelAuth("openai/gpt-5"),
1211
+ checkPiModelAuth("deepseek/deepseek-chat"),
1212
+ checkPiModelAuth("google-gemini-cli/gemini-2.5-pro"),
1213
+ checkPiModelAuth("google/gemini-2.5-pro"),
1214
+ ]);
1215
+ return c.json({
1216
+ providers: {
1217
+ installed,
1218
+ signIns: providerSignIns.snapshot(),
1219
+ claude,
1220
+ openai,
1221
+ piOpenAISubscription,
1222
+ piOpenAIKey,
1223
+ deepseek,
1224
+ googleSubscription,
1225
+ googleApiKey,
1226
+ },
1227
+ });
1228
+ });
1229
+ app.post("/api/providers/pi/install", async (c) => {
1230
+ if (c.get("principal").kind !== "local") {
1231
+ return c.json({ error: "Pi can only be installed from the local board" }, 403);
1232
+ }
1233
+ try {
1234
+ await installHarness("pi");
1235
+ return c.json({ installed: true });
1236
+ }
1237
+ catch (cause) {
1238
+ const message = cause instanceof Error ? cause.message : "Pi installation failed";
1239
+ return c.json({ error: message }, 500);
1240
+ }
1241
+ });
1077
1242
  app.put("/api/setup", async (c) => {
1078
1243
  const body = await c.req
1079
1244
  .json()
@@ -1124,6 +1289,24 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
1124
1289
  return c.json({ error: "testsFirstEnabled must be a boolean" }, 400);
1125
1290
  patch.testsFirstEnabled = body.testsFirstEnabled;
1126
1291
  }
1292
+ if (body.plannerChoiceEnabled !== undefined) {
1293
+ if (typeof body.plannerChoiceEnabled !== "boolean")
1294
+ return c.json({ error: "plannerChoiceEnabled must be a boolean" }, 400);
1295
+ patch.plannerChoiceEnabled = body.plannerChoiceEnabled;
1296
+ }
1297
+ if (body.plannerHarness !== undefined) {
1298
+ if (typeof body.plannerHarness !== "string")
1299
+ return c.json({ error: "plannerHarness must be a string" }, 400);
1300
+ const invalidHarness = unknownHarness(body.plannerHarness);
1301
+ if (invalidHarness)
1302
+ return c.json({ error: `unknown harness: ${invalidHarness}` }, 400);
1303
+ patch.plannerHarness = body.plannerHarness.trim();
1304
+ }
1305
+ if (body.plannerModel !== undefined) {
1306
+ if (typeof body.plannerModel !== "string" || body.plannerModel.trim().length > 200)
1307
+ return c.json({ error: "plannerModel must be a string up to 200 characters" }, 400);
1308
+ patch.plannerModel = body.plannerModel.trim();
1309
+ }
1127
1310
  if (Object.keys(patch).length === 0)
1128
1311
  return c.json({ error: "nothing to save" }, 400);
1129
1312
  db.setBoardSettings(patch);
@@ -1322,6 +1505,52 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
1322
1505
  return c.json({ comment }, 201);
1323
1506
  });
1324
1507
  app.use("/api/*", auth, idempotency);
1508
+ /**
1509
+ * Sign-in and key saves change this machine's credentials, so both are local
1510
+ * only. They sit below the auth registration on purpose: Hono runs handlers in
1511
+ * registration order, so a route above it would never see the principal.
1512
+ */
1513
+ app.post("/api/providers/:provider/sign-in", async (c) => {
1514
+ if (c.get("principal").kind !== "local") {
1515
+ return c.json({ error: "Sign-in is available from the local board only" }, 403);
1516
+ }
1517
+ const provider = c.req.param("provider");
1518
+ if (!isSignInId(provider))
1519
+ return c.json({ error: "This provider has no sign-in" }, 404);
1520
+ try {
1521
+ return c.json({ signIn: await providerSignIns.start(provider) });
1522
+ }
1523
+ catch (cause) {
1524
+ if (cause instanceof SignInBusyError) {
1525
+ return c.json({ error: cause.message, code: "busy" }, 409);
1526
+ }
1527
+ throw cause;
1528
+ }
1529
+ });
1530
+ app.post("/api/providers/:provider/key", async (c) => {
1531
+ if (c.get("principal").kind !== "local") {
1532
+ return c.json({ error: "API keys are saved from the local board only" }, 403);
1533
+ }
1534
+ const provider = c.req.param("provider");
1535
+ if (!isKeyId(provider))
1536
+ return c.json({ error: "This provider does not take a key" }, 404);
1537
+ const body = await c.req.json().catch(() => ({}));
1538
+ const key = typeof body.key === "string" ? body.key.trim() : "";
1539
+ if (!key)
1540
+ return c.json({ error: "Enter an API key" }, 400);
1541
+ if (key.length > 500 || /\s/.test(key)) {
1542
+ return c.json({ error: "That does not look like an API key. Paste the whole key." }, 400);
1543
+ }
1544
+ try {
1545
+ await saveProviderKey(provider, key, keyDeps);
1546
+ return c.json({ saved: true });
1547
+ }
1548
+ catch (cause) {
1549
+ if (cause instanceof ProviderKeyError)
1550
+ return c.json({ error: cause.message }, cause.status);
1551
+ return c.json({ error: "Could not save the key" }, 500);
1552
+ }
1553
+ });
1325
1554
  /**
1326
1555
  * Who the caller is and what it may do. The phone uses this to hide controls
1327
1556
  * the tunnel allowlist would refuse anyway; the server stays the authority.
@@ -1649,11 +1878,22 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
1649
1878
  return c.json({ ticket: removed });
1650
1879
  });
1651
1880
  /** The home repo and the repos attached to this board. */
1652
- app.get("/api/repos", (c) => c.json({
1653
- home: { name: basename(root), root },
1654
- repos: db.listRepos(),
1655
- folderPicker: repoPicker.available && c.get("principal").kind === "local",
1656
- }));
1881
+ const execFileAsync = promisify(execFile);
1882
+ app.get("/api/repos", async (c) => {
1883
+ let home = null;
1884
+ try {
1885
+ await execFileAsync("git", ["-C", root, "rev-parse", "--show-toplevel"], { timeout: 3000 });
1886
+ home = { name: basename(root), root };
1887
+ }
1888
+ catch {
1889
+ // An ordinary folder is not the board's home repository.
1890
+ }
1891
+ return c.json({
1892
+ home,
1893
+ repos: db.listRepos(),
1894
+ folderPicker: repoPicker.available && c.get("principal").kind === "local",
1895
+ });
1896
+ });
1657
1897
  app.post("/api/repos/pick-folder", async (c) => {
1658
1898
  if (c.get("principal").kind !== "local") {
1659
1899
  return c.json({ error: "choosing a repository is available from the local board only" }, 403);
@@ -1950,6 +2190,21 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
1950
2190
  quick: body.quick === true,
1951
2191
  thinking: asThinking(body.thinking) ?? null,
1952
2192
  model: typeof body.model === "string" ? body.model.trim().slice(0, 200) || null : null,
2193
+ planner_harness: (() => {
2194
+ const source = typeof draft.conversationId === "string"
2195
+ ? db.getConversation(draft.conversationId)
2196
+ : null;
2197
+ if (source?.kind === "task")
2198
+ return source.plannerHarness ?? null;
2199
+ if (body.quick === true) {
2200
+ const requested = typeof draft.plannerHarness === "string" ? draft.plannerHarness : "";
2201
+ if (requested && !unknownHarness(requested))
2202
+ return requested.trim();
2203
+ const saved = db.getBoardSettings().plannerHarness ?? "";
2204
+ return saved && !unknownHarness(saved) ? saved : null;
2205
+ }
2206
+ return null;
2207
+ })(),
1953
2208
  skills: body.skills,
1954
2209
  });
1955
2210
  return c.json({ ticket }, 201);
@@ -2230,8 +2485,18 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2230
2485
  else {
2231
2486
  conversation = db.appendMessage("user", said, "message", conversation.id);
2232
2487
  }
2233
- // Start scouts before the index and intake, using only the original description.
2234
- const intakeReading = mode === "intake" ? startResearch(conversation.id, taskResearchQuestions(text)) : undefined;
2488
+ const requestedHarness = options.harness || target.plannerHarness || undefined;
2489
+ const turnChoice = plannerChoice(requestedHarness, options.model !== undefined
2490
+ ? options.model
2491
+ : requestedHarness === target.plannerHarness
2492
+ ? (target.plannerModel ?? undefined)
2493
+ : undefined);
2494
+ // The reading starts with the request, from the original description only:
2495
+ // a code search here, and scouts for any linked repo the intake names.
2496
+ const intakeReading = mode === "intake" ? startSearch(conversation.id, text, turnChoice) : undefined;
2497
+ // With no linked repo there is nothing for the intake to decide that the
2498
+ // draft cannot: the search has already read, so the first pass is the draft.
2499
+ const merged = mode === "intake" && candidates.length === 0;
2235
2500
  // Waiting here is usually free: the index is built at startup and the
2236
2501
  // head check is one git call. When it is not free — a first run, or a
2237
2502
  // checkout that just changed — the build is minutes of silence with no
@@ -2241,18 +2506,24 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2241
2506
  indexMs = Date.now() - indexStarted;
2242
2507
  const brief = index ? renderBrief(index) : "";
2243
2508
  // One planner run. Its stats are its own, so the row it writes is too.
2244
- const planOnce = (passMode, findings) => {
2509
+ const planOnce = async (passMode, findings) => {
2245
2510
  stats = EMPTY_TURN_STATS;
2246
2511
  // The intake decides, it does not read at length: its level is capped in
2247
2512
  // this one place so the injected test planner and the real one agree.
2248
2513
  const level = options.thinking ?? plannerThinkingForTurn();
2249
2514
  const passThinking = passMode === "intake" ? capThinking(level, INTAKE_THINKING_CAP) : level;
2250
- return runPlan(conversation.messages, brief, draft, board, publish, handoff, passMode, (measured) => {
2515
+ const planned = await runPlan(conversation.messages, brief, draft, board, publish, handoff, passMode, (measured) => {
2251
2516
  stats = measured;
2252
2517
  }, attachments, images, passThinking, findings,
2253
2518
  // What is left of the request, not a fresh clock per pass: the intake,
2254
2519
  // the scouts and the draft share one deadline, and the planner is told it.
2255
- Math.max(MIN_PASS_MS, PLAN_TURN_DEADLINE_MS - (Date.now() - startedAt)), repoBriefs, options.model, options.harness);
2520
+ Math.max(MIN_PASS_MS, PLAN_TURN_DEADLINE_MS - (Date.now() - startedAt)), repoBriefs, turnChoice.model, turnChoice.command);
2521
+ conversation = db.setConversationPlannerChoice(conversation.id, turnChoice.command, turnChoice.model || null);
2522
+ // The real orchestrator already filters card models against this pass's
2523
+ // developer brief. Do not make intake or injected planners discover a
2524
+ // model list just to repeat that check; ticket runs and plan edits each
2525
+ // validate against their authoritative harness before use.
2526
+ return planned;
2256
2527
  };
2257
2528
  // Saves what the planner decided. Research is a planner input, not part of
2258
2529
  // the plan the dialog reads, so it is not stored.
@@ -2288,17 +2559,20 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2288
2559
  }, conversation.id);
2289
2560
  return { saved, questions: next.questions.length, cards: cards.length };
2290
2561
  };
2291
- // An answer turn in the wizard reads what its intake started, first.
2292
- let findings;
2293
- if (mode === "new-task") {
2294
- const reading = pendingResearch.get(target.id);
2295
- if (reading) {
2296
- pendingResearch.delete(target.id);
2297
- findings = forDraft(await awaitReading(reading));
2298
- }
2299
- }
2300
- const drafted = await planOnce(mode, findings);
2301
- if (mode === "intake") {
2562
+ // A draft reads what the request started: the merged first pass its own
2563
+ // search, an answer turn what its intake began. The reading stays until it
2564
+ // expires, so a second round of answers or a comment on the draft reads it too.
2565
+ const pass = merged ? "new-task" : mode;
2566
+ if (merged)
2567
+ door = "new-task";
2568
+ const reading = merged
2569
+ ? intakeReading
2570
+ : mode === "new-task"
2571
+ ? pendingResearch.get(target.id)
2572
+ : undefined;
2573
+ const findings = reading ? withNotes(forDraft(await awaitReading(reading))) : undefined;
2574
+ const drafted = await planOnce(pass, findings);
2575
+ if (pass === "intake") {
2302
2576
  // The intake names the repos the work may touch. A scout starts reading
2303
2577
  // each one now, so the draft has its findings without asking the person.
2304
2578
  const onBoard = new Set(candidates.map((repo) => repo.name));
@@ -2307,14 +2581,14 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2307
2581
  const named = [...new Set(drafted.boards ?? [])]
2308
2582
  .filter((name) => onBoard.has(name))
2309
2583
  .slice(0, MAX_REPO_SCOUTS);
2310
- extendResearch(conversation.id, named.map((name) => linkedBoardQuestion(name, text)));
2584
+ extendResearch(conversation.id, named.map((name) => linkedBoardQuestion(name, text)), turnChoice);
2311
2585
  }
2312
2586
  let outcome;
2313
- if (mode !== "intake") {
2587
+ if (pass !== "intake") {
2314
2588
  outcome = store(drafted);
2315
2589
  }
2316
2590
  else {
2317
- // Scouts have been running since the request arrived.
2591
+ // The reading has been running since the request arrived.
2318
2592
  if (normaliseQuestions(drafted.questions).length > 0) {
2319
2593
  outcome = store({ ...drafted, cards: [] });
2320
2594
  }
@@ -2322,8 +2596,10 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2322
2596
  // Nothing to ask and nothing drafted: the intake's row is recorded, then
2323
2597
  // the draft waits for the reading in this same request.
2324
2598
  measure({ ok: true });
2325
- pendingResearch.delete(conversation.id);
2326
- const readFirst = intakeReading ? forDraft(await awaitReading(intakeReading)) : undefined;
2599
+ // The map, not `intakeReading`: linked-repo scouts may have started a
2600
+ // reading of their own when this board searches nothing.
2601
+ const started = pendingResearch.get(conversation.id);
2602
+ const readFirst = started ? withNotes(forDraft(await awaitReading(started))) : undefined;
2327
2603
  door = "new-task";
2328
2604
  rowStartedAt = Date.now();
2329
2605
  indexMs = 0;
@@ -2381,7 +2657,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2381
2657
  conversationId: asConversationId(body.conversationId),
2382
2658
  attachments,
2383
2659
  thinking: thinking ?? undefined,
2384
- model: typeof body.model === "string" ? body.model.trim() || undefined : undefined,
2660
+ model: typeof body.model === "string" ? body.model.trim() : undefined,
2385
2661
  harness: typeof body.harness === "string" ? body.harness.trim() || undefined : undefined,
2386
2662
  }),
2387
2663
  });
@@ -2446,7 +2722,7 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2446
2722
  conversationId: session.id,
2447
2723
  attachments,
2448
2724
  thinking: thinking ?? undefined,
2449
- model: typeof body.model === "string" ? body.model.trim() || undefined : undefined,
2725
+ model: typeof body.model === "string" ? body.model.trim() : undefined,
2450
2726
  harness: typeof body.harness === "string" ? body.harness.trim() || undefined : undefined,
2451
2727
  }),
2452
2728
  });
@@ -2486,9 +2762,10 @@ export function createApp({ db, token, port, webRoot, repoRoot, accountAvatarUrl
2486
2762
  }
2487
2763
  // A model the developer harness does not list is cleared, as a planner turn
2488
2764
  // clears it, so the card shows the default instead of a model it cannot run.
2489
- const plan = keepListedModels({ ...conversation.plan, cards }, await developerBrief());
2765
+ const plannerHarness = conversation.plannerHarness ?? undefined;
2766
+ const filteredPlan = keepListedModels({ ...conversation.plan, cards }, await developerBrief(plannerHarness));
2490
2767
  return c.json({
2491
- conversation: db.setPlan(plan, conversation.id),
2768
+ conversation: db.setPlan(filteredPlan, conversation.id),
2492
2769
  });
2493
2770
  });
2494
2771
  /** "New chat": a new row, so the old transcript can still be read later. */