@jmanuelcorral/bond-app 0.1.3 → 0.1.5

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/README.md +41 -1
  2. package/app/mods/bond-agents/config.js +4 -0
  3. package/app/mods/bond-agents/main.js +10 -5
  4. package/app/mods/bond-agents/model.js +52 -4
  5. package/app/mods/bond-board/config.js +4 -0
  6. package/app/mods/bond-board/main.js +555 -84
  7. package/app/mods/bond-board/model.js +115 -2
  8. package/app/mods/bond-settings/config.js +4 -0
  9. package/app/mods/bond-settings/main.js +689 -12
  10. package/app/mods/bond-settings/pi-models.js +144 -0
  11. package/app/mods/bond-status/config.js +4 -0
  12. package/app/mods/bond-titlebar/main.js +63 -46
  13. package/package.json +1 -1
  14. package/runner/Dockerfile +42 -13
  15. package/runner/SPIKE-BOND.md +85 -0
  16. package/runner/build-config/.none +0 -0
  17. package/runner/build-creds/.none +0 -0
  18. package/runner/config.example/README.md +27 -0
  19. package/runner/config.example/pi/models.json +22 -0
  20. package/runner/credentials.example.env +27 -0
  21. package/runner/setup.sh +496 -0
  22. package/runner/versions.env +30 -0
  23. package/scripts/app-install.ts +38 -7
  24. package/src/config.ts +11 -0
  25. package/src/core/delivery.ts +61 -7
  26. package/src/core/hub-session.ts +154 -17
  27. package/src/core/hub.ts +55 -20
  28. package/src/core/orchestrator.ts +844 -200
  29. package/src/core/setup.ts +178 -0
  30. package/src/core/watchdog.ts +2 -2
  31. package/src/db/database.ts +14 -0
  32. package/src/db/run-repo.ts +8 -1
  33. package/src/db/settings-repo.ts +108 -0
  34. package/src/db/ticket-repo.ts +34 -4
  35. package/src/runner/docker-client.ts +42 -0
  36. package/src/runner/github-client.ts +126 -2
  37. package/src/runner/hc-client.ts +67 -9
  38. package/src/runner/image-builder.ts +146 -6
  39. package/src/server/app.ts +263 -36
  40. package/src/types.ts +40 -0
@@ -64,23 +64,77 @@ export function bundlePathFor(name: string): string {
64
64
  /** Where the runner leaves the bundle of the run's branch for the root push. */
65
65
  export const BUNDLE_PATH = '/tmp/bond-delivery.bundle';
66
66
 
67
+ /** Exit codes of COMMIT_SCRIPT the orchestrator maps to a run outcome. */
68
+ export const COMMIT_EXIT = { treeChanged: 9 } as const;
69
+
70
+ /**
71
+ * Límite y garantías de la guarda MEDIUM-2 (M-1, M-2, M-3):
72
+ * - M-1: Si la captura del árbol de trabajo falla antes de la verificación (con verify_commands no vacío),
73
+ * la entrega falla en cerrado y el run se bloquea (no se entrega sin verificar).
74
+ * - M-2: El commit se genera directamente desde el árbol verificado usando un índice temporal
75
+ * (GIT_INDEX_FILE) y `git commit-tree`, garantizando que el índice compartido (.git/index) con el
76
+ * agente vivo no puede interponerse ni alterar el commit.
77
+ * - M-3: Para cerrar el «flip-flop», el orquestador verifica el árbol de trabajo al inicio de la
78
+ * verificación, después de cada comando de verificación y antes del commit. Como límite documentado:
79
+ * si un proceso en el contenedor mutara un archivo y lo restaurara exactamente a su estado inicial
80
+ * en medio de la ejecución de un mismo comando (flip-flop intra-comando), el árbol final verificado
81
+ * coincide idénticamente con el commit, pero para hermetismo completo contra agentes hostiles se
82
+ * requeriría congelar los procesos del contenedor (cgroups freezer) o montar el árbol en solo lectura.
83
+ *
84
+ * Runs as `runner` in the clone before verification to capture the working tree sha (MEDIUM-2).
85
+ * Args: directory (default /workspace/repo).
86
+ */
87
+ export const TREE_SCRIPT = [
88
+ 'set -eu',
89
+ 'cd "${1:-/workspace/repo}"',
90
+ 'tmp_index=$(mktemp)',
91
+ 'rm -f "$tmp_index"',
92
+ 'trap \'rm -f "$tmp_index"\' EXIT',
93
+ 'if git rev-parse --verify --quiet HEAD >/dev/null 2>&1; then',
94
+ ' GIT_INDEX_FILE="$tmp_index" git read-tree HEAD',
95
+ 'fi',
96
+ 'GIT_INDEX_FILE="$tmp_index" git -c core.hooksPath=/dev/null add -A',
97
+ 'echo "tree=$(GIT_INDEX_FILE="$tmp_index" git write-tree)"',
98
+ ].join('\n');
99
+
67
100
  /**
68
101
  * Runs as `runner` in the clone. Args: target branch, commit message, author name, author
69
- * email. Commits whatever the agent left (hooks off), refuses if the clone is not on the
70
- * run's branch, bundles that branch and prints its head sha. Nothing it prints decides
71
- * what is pushed (review HIGH-1: the agent controls the clone and /tmp): root checks the
72
- * bundle against this sha and measures the branch against the real base from GitHub.
102
+ * email, clone directory (optional), bundle path (optional), expected tree sha (optional, MEDIUM-2).
103
+ * Commits whatever the agent left (hooks off), refuses if the clone is not on the
104
+ * run's branch or if the tree changed after verification, bundles that branch and prints its head sha.
105
+ * Nothing it prints decides what is pushed (review HIGH-1: the agent controls the clone and /tmp):
106
+ * root checks the bundle against this sha and measures the branch against the real base from GitHub.
107
+ *
108
+ * M-2: Uses an isolated temporary index (GIT_INDEX_FILE) seeded from HEAD and `git commit-tree`
109
+ * so the shared .git/index cannot interfere.
73
110
  */
74
111
  export const COMMIT_SCRIPT = [
75
112
  'set -eu',
76
113
  // P5: $5 is the clone (a hub repo's worktree) and $6 the bundle; the single repo's by default.
114
+ // MEDIUM-2: $7 is the expected tree sha from before verification.
77
115
  'cd "${5:-/workspace/repo}"',
78
116
  `bundle="\${6:-${BUNDLE_PATH}}"`,
79
117
  'cur=$(git symbolic-ref --quiet --short HEAD || true)',
80
118
  'if [ "$cur" != "$1" ]; then echo "the clone is on \'$cur\', not on the run branch \'$1\'" >&2; exit 3; fi',
81
- 'git -c core.hooksPath=/dev/null add -A',
82
- 'if ! git diff --cached --quiet; then',
83
- ' git -c core.hooksPath=/dev/null -c user.name="$3" -c user.email="$4" commit -q --no-verify -m "$2"',
119
+ 'tmp_index=$(mktemp)',
120
+ 'rm -f "$tmp_index"',
121
+ 'trap \'rm -f "$tmp_index"\' EXIT',
122
+ 'if git rev-parse --verify --quiet HEAD >/dev/null 2>&1; then',
123
+ ' GIT_INDEX_FILE="$tmp_index" git read-tree HEAD',
124
+ 'fi',
125
+ 'GIT_INDEX_FILE="$tmp_index" git -c core.hooksPath=/dev/null add -A',
126
+ 'cur_tree=$(GIT_INDEX_FILE="$tmp_index" git write-tree)',
127
+ 'if [ -n "${7:-}" ]; then',
128
+ ` if [ "$cur_tree" != "$7" ]; then echo "commit failed: working tree changed after verification ($cur_tree != $7)" >&2; exit ${COMMIT_EXIT.treeChanged}; fi`,
129
+ 'fi',
130
+ 'head_tree=$(git rev-parse --verify --quiet "HEAD^{tree}" 2>/dev/null || true)',
131
+ 'if [ "$cur_tree" != "$head_tree" ]; then',
132
+ ' if git rev-parse --verify --quiet HEAD >/dev/null 2>&1; then',
133
+ ' commit_sha=$(GIT_AUTHOR_NAME="$3" GIT_AUTHOR_EMAIL="$4" GIT_COMMITTER_NAME="$3" GIT_COMMITTER_EMAIL="$4" git commit-tree "$cur_tree" -p HEAD -m "$2")',
134
+ ' else',
135
+ ' commit_sha=$(GIT_AUTHOR_NAME="$3" GIT_AUTHOR_EMAIL="$4" GIT_COMMITTER_NAME="$3" GIT_COMMITTER_EMAIL="$4" git commit-tree "$cur_tree" -m "$2")',
136
+ ' fi',
137
+ ' git update-ref "refs/heads/$1" "$commit_sha"',
84
138
  'fi',
85
139
  'rm -f -- "$bundle"',
86
140
  'git bundle create -q "$bundle" "refs/heads/$1"',
@@ -7,6 +7,7 @@
7
7
  * origin refs) and a symlinked repo by pointing the container's .bond/hub.local.toml at
8
8
  * its clone; then `bond hub sync --yes` and `bond hub check --json` do the rest.
9
9
  */
10
+ import path from 'node:path';
10
11
  import type { DockerClient } from '../runner/docker-client.ts';
11
12
  import type { HcClient } from '../runner/hc-client.ts';
12
13
  import {
@@ -58,12 +59,16 @@ export interface MountResult {
58
59
  export class HubSession {
59
60
  private docker: DockerClient;
60
61
  private ctr: string;
62
+ private hcClient?: HcClient;
63
+ private hcMachine?: string;
61
64
  /** Called after each repo is mounted (the orchestrator refreshes the run; review H3). */
62
65
  onProgress: () => void = () => {};
63
66
 
64
- constructor(docker: DockerClient, containerName: string) {
67
+ constructor(docker: DockerClient, containerName: string, hcClient?: HcClient, hcMachine?: string) {
65
68
  this.docker = docker;
66
69
  this.ctr = containerName;
70
+ this.hcClient = hcClient;
71
+ this.hcMachine = hcMachine;
67
72
  }
68
73
 
69
74
  /** A command as `runner`, with its HOME (bond and git read their config from there). */
@@ -259,7 +264,7 @@ export class HubSession {
259
264
  * every agent a repo's bond.toml lists, but a run only starts the team's agents (checked
260
265
  * apart, in the image): those failures are warnings.
261
266
  */
262
- async check(teamAgent: (repo: string) => string = () => ''): Promise<{ failures: string[]; warnings: string[] }> {
267
+ async check(teamAgent: (repo: string) => string = () => 'pi'): Promise<{ failures: string[]; warnings: string[] }> {
263
268
  const res = await this.runner(['sh', '-c', `cd ${HUB_DIR} && bond hub check --json </dev/null`], 120_000);
264
269
  const failures: string[] = [];
265
270
  const warnings: string[] = [];
@@ -431,11 +436,54 @@ export class HubSession {
431
436
  return sha;
432
437
  }
433
438
 
439
+ /**
440
+ * P1 criterion 6 & A-1: Check whether a real `bond team` command is currently executing
441
+ * in the container by scanning `/proc/<pid>/cmdline` and checking argv elements, so
442
+ * fallback does not compete with the leader and restoreDefaultAgent does not race.
443
+ *
444
+ * Note (A-1): We scan argv elements (some argv[i] whose basename is 'bond' followed by
445
+ * argv[i+1] === 'team', or basename 'bond-team'), never matching on free substrings
446
+ * of the command line, because the leader process (exec pi "$(cat orchestrator-prompt.txt)")
447
+ * carries the prompt in its argv which literally contains "bond team '<branch>'".
448
+ *
449
+ * Fail-open design (M-2): If docker.exec fails or times out (e.g. docker daemon under load
450
+ * or container unreachable), this returns `false` rather than blocking launches, allowing
451
+ * recovery to proceed.
452
+ */
453
+ async isTeamCommandRunning(): Promise<boolean> {
454
+ try {
455
+ const res = await this.runner(['node', '-e', CHECK_TEAM_RUNNING_SCRIPT], 5_000);
456
+ return res.exitCode === 0 && Boolean(res.stdout.trim());
457
+ } catch {
458
+ // Fail-open (M-2): On docker execution error, assume not running to prevent hanging launches
459
+ return false;
460
+ }
461
+ }
462
+
434
463
  /**
435
464
  * Review L-2: whether the run's team is already open (every repo has its worktree on the
436
465
  * branch with an agent), e.g. after an orchestrator restart during the launch.
466
+ * P1 criterion 1: with hc engine, decides reuse directly from hcClient with zero dockerClient.exec
467
+ * calls, keeping the current docker exec behavior for herdr engine.
437
468
  */
438
- async teamOpen(branch: string, repoCount: number, engine = 'herdr'): Promise<boolean> {
469
+ async teamOpen(branch: string, repoCount: number, engine = 'herdr', hcClient?: HcClient, machine?: string): Promise<boolean> {
470
+ const client = hcClient || this.hcClient;
471
+ const targetMachine = machine || this.hcMachine;
472
+ if (engine === 'hc' && client && targetMachine) {
473
+ try {
474
+ const terminals = await client.getMachineTerminals(targetMachine);
475
+ const liveRepoTerminals = terminals.filter(
476
+ (t) => t.state === 'live' && t.labels?.['bond.branch'] === branch && t.name !== 'hub-leader' && !t.address?.endsWith('/t1')
477
+ );
478
+ if (repoCount > 0 && liveRepoTerminals.length >= repoCount) {
479
+ return true;
480
+ }
481
+ return false;
482
+ } catch {
483
+ // Fall back to docker exec if hcClient query fails
484
+ }
485
+ }
486
+
439
487
  const engineEnv = engine === 'hc' ? 'BOND_TEAM_ENGINE=hc ' : '';
440
488
  const res = await this.runner(['sh', '-c', `cd ${HUB_DIR} && ${engineEnv}bond team status --json </dev/null`], 60_000);
441
489
  if (res.exitCode !== 0) return false;
@@ -471,7 +519,7 @@ export class HubSession {
471
519
  machine: string,
472
520
  ticket: Ticket,
473
521
  repos: HubAnalysisRepo[],
474
- opts: { waitMs?: number; pollMs?: number; onTerminal?: (address: string) => void } = {}
522
+ opts: { waitMs?: number; pollMs?: number; onTerminal?: (address: string) => void; defaultModel?: string | null } = {}
475
523
  ): Promise<string> {
476
524
  const waitMs = opts.waitMs ?? 180_000;
477
525
  const pollMs = opts.pollMs ?? 1000;
@@ -547,9 +595,10 @@ export class HubSession {
547
595
 
548
596
  const agentCmd = ticket.agent === 'pi' || !ticket.agent ? 'pi' : ticket.agent;
549
597
  let modelArg = '';
550
- if (ticket.model) {
551
- if (!MODEL_RE.test(ticket.model)) throw new HubMountError(`Invalid model '${ticket.model}'`);
552
- modelArg = `--model ${shq(ticket.model)} `;
598
+ const effectiveModel = ticket.model || (agentCmd === 'pi' ? opts.defaultModel : null);
599
+ if (effectiveModel) {
600
+ if (!MODEL_RE.test(effectiveModel)) throw new HubMountError(`Invalid model '${effectiveModel}'`);
601
+ modelArg = `--model ${shq(effectiveModel)} `;
553
602
  }
554
603
  const runCmd = `cd ${HUB_DIR} && export BOND_TEAM_NO_TABLE=1 && exec ${agentCmd} ${modelArg}"$(cat ${promptPath})"`;
555
604
  const runRes = await this.runner(['herdr', 'pane', 'run', pane, runCmd], 15_000);
@@ -596,9 +645,30 @@ export class HubSession {
596
645
  await new Promise((r) => setTimeout(r, pollMs));
597
646
  }
598
647
  if (!opened) {
599
- if (!(await this.teamOpen(branch, repos.length))) {
600
- const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 HERDR_ENV=1 HERDR_PANE_ID=${shq(pane)} bond team ${shq(branch)} --repos ${repoList} --no-table --yes </dev/null`;
601
- await this.runner(['sh', '-c', fallbackCmd], 60_000);
648
+ // P1 criterion 6 (M-3 de P7): if leader is currently executing bond team, wait for it
649
+ if (await this.isTeamCommandRunning()) {
650
+ const teamEnd = Date.now() + Math.min(waitMs, 60_000);
651
+ while (Date.now() < teamEnd && (await this.isTeamCommandRunning())) {
652
+ if (await this.teamOpen(branch, repos.length)) {
653
+ opened = true;
654
+ break;
655
+ }
656
+ await new Promise((r) => setTimeout(r, pollMs));
657
+ }
658
+ }
659
+ if (!opened && !(await this.teamOpen(branch, repos.length))) {
660
+ if (!(await this.isTeamCommandRunning())) {
661
+ const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 HERDR_ENV=1 HERDR_PANE_ID=${shq(pane)} bond team ${shq(branch)} --repos ${repoList} --no-table --yes </dev/null`;
662
+ await this.runner(['sh', '-c', fallbackCmd], 60_000);
663
+ }
664
+ }
665
+ }
666
+
667
+ // P1 criterion 6: wait for any running bond team to complete before restoring default agents
668
+ if (await this.isTeamCommandRunning()) {
669
+ const restEnd = Date.now() + 30_000;
670
+ while (Date.now() < restEnd && (await this.isTeamCommandRunning())) {
671
+ await new Promise((r) => setTimeout(r, pollMs));
602
672
  }
603
673
  }
604
674
 
@@ -652,9 +722,10 @@ export class HubSession {
652
722
 
653
723
  const agentCmd = ticket.agent === 'pi' || !ticket.agent ? 'pi' : ticket.agent;
654
724
  let modelArg = '';
655
- if (ticket.model) {
656
- if (!MODEL_RE.test(ticket.model)) throw new HubMountError(`Invalid model '${ticket.model}'`);
657
- modelArg = `--model ${shq(ticket.model)} `;
725
+ const effectiveModel = ticket.model || (agentCmd === 'pi' ? opts.defaultModel : null);
726
+ if (effectiveModel) {
727
+ if (!MODEL_RE.test(effectiveModel)) throw new HubMountError(`Invalid model '${effectiveModel}'`);
728
+ modelArg = `--model ${shq(effectiveModel)} `;
658
729
  }
659
730
  const leaderShellCmd = `cd ${HUB_DIR} && export BOND_TEAM_ENGINE=hc BOND_TEAM_NO_TABLE=1 BOND_TEAM_LABELS='herdr.space=s1,herdr.tab=t1' && exec ${agentCmd} ${modelArg}"$(cat ${promptPath})"`;
660
731
  const terminal = await hc.startTerminal(
@@ -669,7 +740,7 @@ export class HubSession {
669
740
  const teamDeadline = Date.now() + waitMs;
670
741
  let opened = false;
671
742
  while (Date.now() < teamDeadline) {
672
- if (await this.teamOpen(branch, repos.length, 'hc')) {
743
+ if (await this.teamOpen(branch, repos.length, 'hc', hc, machine)) {
673
744
  opened = true;
674
745
  break;
675
746
  }
@@ -688,9 +759,30 @@ export class HubSession {
688
759
  await new Promise((r) => setTimeout(r, pollMs));
689
760
  }
690
761
  if (!opened) {
691
- if (!(await this.teamOpen(branch, repos.length, 'hc'))) {
692
- const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 BOND_TEAM_ENGINE=hc BOND_TEAM_LABELS='herdr.space=s1,herdr.tab=t1' bond team ${shq(branch)} --repos ${repoList} --engine hc --no-table --yes </dev/null`;
693
- await this.runner(['sh', '-c', fallbackCmd], 60_000);
762
+ // P1 criterion 6 (M-3 de P7): if leader is currently executing bond team, wait for it
763
+ if (await this.isTeamCommandRunning()) {
764
+ const teamEnd = Date.now() + Math.min(waitMs, 60_000);
765
+ while (Date.now() < teamEnd && (await this.isTeamCommandRunning())) {
766
+ if (await this.teamOpen(branch, repos.length, 'hc', hc, machine)) {
767
+ opened = true;
768
+ break;
769
+ }
770
+ await new Promise((r) => setTimeout(r, pollMs));
771
+ }
772
+ }
773
+ if (!opened && !(await this.teamOpen(branch, repos.length, 'hc', hc, machine))) {
774
+ if (!(await this.isTeamCommandRunning())) {
775
+ const fallbackCmd = `cd ${HUB_DIR} && BOND_TEAM_NO_TABLE=1 BOND_TEAM_ENGINE=hc BOND_TEAM_LABELS='herdr.space=s1,herdr.tab=t1' bond team ${shq(branch)} --repos ${repoList} --engine hc --no-table --yes </dev/null`;
776
+ await this.runner(['sh', '-c', fallbackCmd], 60_000);
777
+ }
778
+ }
779
+ }
780
+
781
+ // P1 criterion 6: wait for any running bond team to complete before restoring default agents
782
+ if (await this.isTeamCommandRunning()) {
783
+ const restEnd = Date.now() + 30_000;
784
+ while (Date.now() < restEnd && (await this.isTeamCommandRunning())) {
785
+ await new Promise((r) => setTimeout(r, pollMs));
694
786
  }
695
787
  }
696
788
 
@@ -728,4 +820,49 @@ export async function proposeUrls(
728
820
  return out;
729
821
  }
730
822
 
823
+ export const CHECK_TEAM_RUNNING_SCRIPT = `
824
+ const fs = require('fs');
825
+ const path = require('path');
826
+ try {
827
+ const pids = fs.readdirSync('/proc').filter((p) => /^\\d+$/.test(p));
828
+ for (const pid of pids) {
829
+ if (Number(pid) === process.pid) continue;
830
+ try {
831
+ const raw = fs.readFileSync('/proc/' + pid + '/cmdline');
832
+ if (!raw || raw.length === 0) continue;
833
+ const parts = raw.toString('utf8').split('\\0').filter(Boolean);
834
+ for (let i = 0; i < parts.length; i++) {
835
+ const base = path.basename(parts[i]).replace(/\\.[cm]?js$/, '');
836
+ if (base === 'bond-team') {
837
+ process.stdout.write('running\\n');
838
+ process.exit(0);
839
+ }
840
+ if (base === 'bond' && parts[i + 1] === 'team') {
841
+ process.stdout.write('running\\n');
842
+ process.exit(0);
843
+ }
844
+ }
845
+ } catch {}
846
+ }
847
+ } catch {}
848
+ process.exit(1);
849
+ `.trim().replace(/\n\s*/g, ' ');
850
+
851
+ /**
852
+ * P1 criterion 6 & A-1: Evaluates whether a process's argv elements represent
853
+ * a real `bond team` invocation, rather than substring matching the whole command line.
854
+ */
855
+ export function isBondTeamArgv(argv: string[]): boolean {
856
+ for (let i = 0; i < argv.length; i++) {
857
+ const base = path.basename(argv[i]).replace(/\.[cm]?js$/, '');
858
+ if (base === 'bond-team') {
859
+ return true;
860
+ }
861
+ if (base === 'bond' && argv[i + 1] === 'team') {
862
+ return true;
863
+ }
864
+ }
865
+ return false;
866
+ }
867
+
731
868
  export type { HubProbe };
package/src/core/hub.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * answer, and the text edits «Aprobar arreglos» makes. The orchestrator does the I/O.
5
5
  */
6
6
  import { validateBranchName, validateGitHubUrl, isValidAgent } from '../types.ts';
7
- export { NAME_RE as REPO_NAME_RE };
7
+ export { NAME_RE, NAME_RE as REPO_NAME_RE };
8
8
  import type { HubAnalysis, HubAnalysisRepo, HubGap, Ticket } from '../types.ts';
9
9
 
10
10
  /** Where the hub and the clones of its symlinked repos live in the container. */
@@ -79,7 +79,7 @@ export function parseHubToml(text: string): HubToml {
79
79
  const m = /^repos\.(?:"([^"]+)"|([A-Za-z0-9_.-]+))$/.exec(table[1].trim());
80
80
  if (m) {
81
81
  currentName = m[1] ?? m[2];
82
- if (!NAME_RE.test(currentName)) throw new HubTomlError(`hub.toml: invalid repo name '${currentName}'`);
82
+ if (!NAME_RE.test(currentName) || currentName === '_hub_') throw new HubTomlError(`hub.toml: invalid repo name '${currentName}'`);
83
83
  current = {};
84
84
  } else {
85
85
  current = null;
@@ -246,35 +246,70 @@ export interface AgentAnswer {
246
246
  summary: string;
247
247
  }
248
248
 
249
- /** The last JSON object line of the agent's output, validated; null if there is none. */
249
+ function validateParsedAnswer(parsed: unknown): AgentAnswer | null {
250
+ if (!parsed || typeof parsed !== 'object') return null;
251
+ const p = parsed as { ready?: unknown; missing?: unknown; summary?: unknown };
252
+ if (typeof p.ready !== 'boolean') return null;
253
+ const missing = Array.isArray(p.missing)
254
+ ? p.missing
255
+ .filter((m): m is Record<string, unknown> => Boolean(m) && typeof m === 'object')
256
+ .map((m) => ({
257
+ name: String(m.name ?? '').slice(0, 64),
258
+ url: typeof m.url === 'string' && m.url ? m.url.trim() : null,
259
+ why: String(m.why ?? '').slice(0, 300),
260
+ }))
261
+ .filter((m) => m.name || m.url)
262
+ .slice(0, 10)
263
+ : [];
264
+ return { ready: p.ready && missing.length === 0, missing, summary: String(p.summary ?? '').slice(0, 500) };
265
+ }
266
+
267
+ /** The last JSON object of the agent's output, validated (single-line or block); null if there is none. */
250
268
  export function parseAgentAnswer(output: string): AgentAnswer | null {
251
269
  const lines = output.split(/\r?\n/).map((l) => l.trim()).filter(Boolean).reverse();
252
270
  for (const line of lines) {
253
271
  const start = line.indexOf('{');
254
272
  const end = line.lastIndexOf('}');
255
273
  if (start < 0 || end <= start) continue;
256
- let parsed: unknown;
257
274
  try {
258
- parsed = JSON.parse(line.slice(start, end + 1));
275
+ const parsed = JSON.parse(line.slice(start, end + 1));
276
+ const res = validateParsedAnswer(parsed);
277
+ if (res) return res;
259
278
  } catch {
260
279
  continue;
261
280
  }
262
- if (!parsed || typeof parsed !== 'object') continue;
263
- const p = parsed as { ready?: unknown; missing?: unknown; summary?: unknown };
264
- if (typeof p.ready !== 'boolean') continue;
265
- const missing = Array.isArray(p.missing)
266
- ? p.missing
267
- .filter((m): m is Record<string, unknown> => Boolean(m) && typeof m === 'object')
268
- .map((m) => ({
269
- name: String(m.name ?? '').slice(0, 64),
270
- url: typeof m.url === 'string' && m.url ? m.url.trim() : null,
271
- why: String(m.why ?? '').slice(0, 300),
272
- }))
273
- .filter((m) => m.name || m.url)
274
- .slice(0, 10)
275
- : [];
276
- return { ready: p.ready && missing.length === 0, missing, summary: String(p.summary ?? '').slice(0, 500) };
277
281
  }
282
+
283
+ // Fallback: extract markdown code blocks ```json ... ``` or ``` ... ```
284
+ const blockRegex = /```(?:json)?\s*([\s\S]*?)\s*```/g;
285
+ let match: RegExpExecArray | null;
286
+ const blocks: string[] = [];
287
+ while ((match = blockRegex.exec(output)) !== null) {
288
+ blocks.push(match[1].trim());
289
+ }
290
+ for (const block of blocks.reverse()) {
291
+ try {
292
+ const parsed = JSON.parse(block);
293
+ const res = validateParsedAnswer(parsed);
294
+ if (res) return res;
295
+ } catch {
296
+ continue;
297
+ }
298
+ }
299
+
300
+ // Fallback: outermost balanced or slice JSON object
301
+ const firstBrace = output.indexOf('{');
302
+ const lastBrace = output.lastIndexOf('}');
303
+ if (firstBrace >= 0 && lastBrace > firstBrace) {
304
+ try {
305
+ const parsed = JSON.parse(output.slice(firstBrace, lastBrace + 1));
306
+ const res = validateParsedAnswer(parsed);
307
+ if (res) return res;
308
+ } catch {
309
+ // ignore
310
+ }
311
+ }
312
+
278
313
  return null;
279
314
  }
280
315