@jmanuelcorral/bond-app 0.1.4 → 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.
@@ -0,0 +1,178 @@
1
+ import {
2
+ SETUP_AGENTS,
3
+ type AgentCredentialSummary,
4
+ type GitHubCredentialSummary,
5
+ type RunnerImageInfo,
6
+ type SetupState,
7
+ } from '../types.ts';
8
+
9
+ /**
10
+ * W-P1 (wizard): the aggregate the orchestrator serves at GET/PUT /api/v1/setup.
11
+ * Pure functions here so the calculation of `complete` is unit-testable without HTTP
12
+ * or docker; the orchestrator gathers the inputs and calls buildSetupState.
13
+ */
14
+
15
+ /**
16
+ * Parse the /opt/runner-agents manifest written by runner/setup.sh: comment lines
17
+ * start with '#'; one agent per line as `agent=<name> version=<v> config_sha256=<h|none>
18
+ * credentials=<yes|no>`. Returns the agent names in manifest order.
19
+ */
20
+ export function parseRunnerManifest(manifest: string): string[] {
21
+ const agents: string[] = [];
22
+ for (const line of manifest.split('\n')) {
23
+ const trimmed = line.trim();
24
+ if (!trimmed || trimmed.startsWith('#')) continue;
25
+ const match = trimmed.match(/^agent=([A-Za-z0-9_.-]+)(\s|$)/);
26
+ if (match) agents.push(match[1]);
27
+ }
28
+ return agents;
29
+ }
30
+
31
+ export interface SetupStateInputs {
32
+ setup_done: boolean;
33
+ agents_selected: string[];
34
+ /** Credential summaries (any agents); the aggregate keeps the SETUP_AGENTS ones. */
35
+ credentials: AgentCredentialSummary[];
36
+ github: GitHubCredentialSummary;
37
+ image: RunnerImageInfo;
38
+ /** W-P4: the suggestions model (supi) stored in the setup state; null = «sin sugerencias». */
39
+ suggestions_model?: string | null;
40
+ /** D-M1: the default working model for pi; null = provider baked default. */
41
+ default_model?: string | null;
42
+ /** P3: full model ids configured for pi (provider/id). */
43
+ models?: string[];
44
+ }
45
+
46
+ /**
47
+ * `complete` answers «can a run actually start here?»: a GitHub credential, at least one
48
+ * agent with a stored credential, and the runner image present. setup_done is an explicit
49
+ * flag only (the wizard's «Finalizar»), never part of the calculation.
50
+ */
51
+ export function buildSetupState(inputs: SetupStateInputs): SetupState {
52
+ const configuredByAgent = new Map(inputs.credentials.map((c) => [c.agent, c.configured]));
53
+ const agents = SETUP_AGENTS.map((agent) => ({
54
+ agent,
55
+ configured: configuredByAgent.get(agent) ?? false,
56
+ }));
57
+ const anyAgentConfigured = agents.some((a) => a.configured);
58
+ const githubConfigured = inputs.github.configured;
59
+
60
+ return {
61
+ complete: githubConfigured && anyAgentConfigured && inputs.image.present,
62
+ setup_done: inputs.setup_done,
63
+ agents_selected: inputs.agents_selected,
64
+ agents,
65
+ github: {
66
+ configured: githubConfigured,
67
+ ...(inputs.github.login !== undefined ? { login: inputs.github.login } : {}),
68
+ },
69
+ image: inputs.image,
70
+ suggestions_model: inputs.suggestions_model ?? null,
71
+ default_model: inputs.default_model ?? null,
72
+ models: inputs.models ?? [],
73
+ };
74
+ }
75
+
76
+ // --- W-P4: model list proxied from the provider -----------------------------------------
77
+
78
+ /** Timeout of the provider GET {base}/models proxy (plan W-P4: ~5 s). */
79
+ export const PROVIDER_MODELS_TIMEOUT_MS = 5000;
80
+
81
+ /** Upper bound of ids returned by the proxy; a provider listing thousands gets the first ones. */
82
+ export const PROVIDER_MODELS_MAX = 500;
83
+
84
+ /** The proxy failed (bad base_url, unreachable provider, bad response). The message never
85
+ * carries the API key; the base URL is not echoed either (it may embed credentials). */
86
+ export class ProviderModelsError extends Error {}
87
+
88
+ const PROVIDER_URL_RE = /^(https?:\/\/)([^\s/@]+)(\/[^\s]*)?$/i;
89
+
90
+ /**
91
+ * Same normalization the builder dialog uses (app/mods/bond-settings/pi-models.js):
92
+ * http(s) with host; no path (or "/") gets "/v1" — where Ollama, LM Studio, vLLM and
93
+ * friends serve —; a path is kept as entered, minus a trailing slash. Returns null if
94
+ * the text is not an http(s) URL.
95
+ */
96
+ export function normalizeProviderBase(raw: string): string | null {
97
+ const url = String(raw ?? '').trim();
98
+ const m = PROVIDER_URL_RE.exec(url);
99
+ if (!m || !m[2]) return null;
100
+ const [, scheme, host, path] = m;
101
+ if (!path || path === '/') return `${scheme}${host}/v1`;
102
+ return url.endsWith('/') ? url.slice(0, -1) : url;
103
+ }
104
+
105
+ /**
106
+ * Sanitize a provider's /models answer into a deduped list of non-empty ids. Accepts the
107
+ * OpenAI-compatible shapes seen in the wild: {data:[{id}]}, {models:[{id|name}]}, or a
108
+ * bare array of strings/objects. Non-strings without id/name are dropped.
109
+ */
110
+ export function sanitizeModelIds(doc: unknown): string[] {
111
+ const record = doc as Record<string, unknown> | null;
112
+ const arr = Array.isArray(doc)
113
+ ? doc
114
+ : Array.isArray(record?.data)
115
+ ? (record!.data as unknown[])
116
+ : Array.isArray(record?.models)
117
+ ? (record!.models as unknown[])
118
+ : [];
119
+ const out: string[] = [];
120
+ const seen = new Set<string>();
121
+ for (const item of arr) {
122
+ let id = '';
123
+ if (typeof item === 'string') id = item;
124
+ else if (item && typeof item === 'object') {
125
+ const rec = item as Record<string, unknown>;
126
+ id = typeof rec.id === 'string' ? rec.id : typeof rec.name === 'string' ? rec.name : '';
127
+ }
128
+ id = id.trim();
129
+ if (!id || seen.has(id)) continue;
130
+ seen.add(id);
131
+ out.push(id);
132
+ if (out.length >= PROVIDER_MODELS_MAX) break;
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /**
138
+ * W-P4: ask an OpenAI-compatible provider for its model ids (GET {base}/models). The
139
+ * optional API key travels only as this request's Bearer header; it is never logged and
140
+ * never appears in an error message (the proxy runs in the orchestrator, so the browser
141
+ * never sees the key either). Throws ProviderModelsError with a short, safe message.
142
+ */
143
+ export async function listProviderModels(opts: {
144
+ baseUrl: string;
145
+ apiKey?: string;
146
+ timeoutMs?: number;
147
+ }): Promise<string[]> {
148
+ const base = normalizeProviderBase(opts.baseUrl);
149
+ if (!base) throw new ProviderModelsError("'base_url' must be an http(s) URL");
150
+ const timeoutMs = opts.timeoutMs ?? PROVIDER_MODELS_TIMEOUT_MS;
151
+ const key = opts.apiKey?.trim() ?? '';
152
+ let res: Response;
153
+ try {
154
+ res = await fetch(`${base}/models`, {
155
+ signal: AbortSignal.timeout(timeoutMs),
156
+ headers: {
157
+ Accept: 'application/json',
158
+ ...(key ? { Authorization: `Bearer ${key}` } : {}),
159
+ },
160
+ });
161
+ } catch (err) {
162
+ const name = (err as Error)?.name ?? '';
163
+ if (name === 'TimeoutError' || name === 'AbortError') {
164
+ throw new ProviderModelsError('the provider timed out');
165
+ }
166
+ throw new ProviderModelsError('could not reach the provider');
167
+ }
168
+ if (!res.ok) throw new ProviderModelsError(`the provider answered HTTP ${res.status}`);
169
+ let doc: unknown;
170
+ try {
171
+ doc = await res.json();
172
+ } catch {
173
+ throw new ProviderModelsError('the provider answer was not JSON');
174
+ }
175
+ const models = sanitizeModelIds(doc);
176
+ if (models.length === 0) throw new ProviderModelsError('the provider returned no models');
177
+ return models;
178
+ }
@@ -49,6 +49,7 @@ export function initDatabase(dbPath: string): DatabaseSync {
49
49
  repos TEXT,
50
50
  repo_agents TEXT,
51
51
  team_engine TEXT DEFAULT 'hc',
52
+ bondify INTEGER NOT NULL DEFAULT 1,
52
53
  status TEXT NOT NULL DEFAULT 'ready',
53
54
  created_at TEXT NOT NULL,
54
55
  updated_at TEXT NOT NULL
@@ -103,6 +104,14 @@ export function initDatabase(dbPath: string): DatabaseSync {
103
104
  updated_at TEXT NOT NULL
104
105
  );
105
106
 
107
+ -- W-P1 (wizard): key/value store for the orchestrator's own setup state
108
+ -- (agents_selected, setup_done). Small strings only; never credentials.
109
+ CREATE TABLE IF NOT EXISTS app_settings (
110
+ key TEXT PRIMARY KEY,
111
+ value TEXT NOT NULL,
112
+ updated_at TEXT NOT NULL
113
+ );
114
+
106
115
  CREATE INDEX IF NOT EXISTS idx_runs_ticket_id ON runs(ticket_id);
107
116
  CREATE INDEX IF NOT EXISTS idx_runs_state ON runs(state);
108
117
  CREATE INDEX IF NOT EXISTS idx_events_run_id ON events(run_id);
@@ -166,6 +175,11 @@ export function initDatabase(dbPath: string): DatabaseSync {
166
175
  } else {
167
176
  db.exec("UPDATE tickets SET team_engine = 'herdr' WHERE team_engine IS NULL;");
168
177
  }
178
+ // P4 (D-U): bondify (auto-bondify non-bondified repos on run start; default true = 1).
179
+ if (!ticketCols.some((c) => c.name === 'bondify')) {
180
+ db.exec('ALTER TABLE tickets ADD COLUMN bondify INTEGER DEFAULT 1;');
181
+ db.exec('UPDATE tickets SET bondify = 1 WHERE bondify IS NULL;');
182
+ }
169
183
 
170
184
  return db;
171
185
  }
@@ -124,4 +124,112 @@ export class SettingsRepository {
124
124
  deleteGitHubCredential(): boolean {
125
125
  return this.db.prepare('DELETE FROM github_credential WHERE id = 1').run().changes > 0;
126
126
  }
127
+
128
+ // --- W-P1: setup state (wizard) -----------------------------------------------------
129
+ // A small key/value store of the orchestrator's own configuration state. Only the
130
+ // selection and the setup_done flag live here; credentials stay in their own tables.
131
+
132
+ getSetting(key: string): string | null {
133
+ const row = this.db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as
134
+ | { value?: string }
135
+ | undefined;
136
+ return row?.value !== undefined ? String(row.value) : null;
137
+ }
138
+
139
+ setSetting(key: string, value: string): void {
140
+ const now = new Date().toISOString();
141
+ this.db.prepare(`
142
+ INSERT INTO app_settings (key, value, updated_at) VALUES (?, ?, ?)
143
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
144
+ `).run(key, value, now);
145
+ }
146
+
147
+ /** The stored wizard state; unset means nothing selected and the wizard has not run. */
148
+ getSetupSelection(): {
149
+ setup_done: boolean;
150
+ agents_selected: string[];
151
+ suggestions_model: string | null;
152
+ default_model: string | null;
153
+ models: string[];
154
+ } {
155
+ const setupDone = this.getSetting('setup_done') === 'true';
156
+ let agentsSelected: string[] = [];
157
+ const raw = this.getSetting('agents_selected');
158
+ if (raw !== null) {
159
+ try {
160
+ const parsed = JSON.parse(raw);
161
+ if (Array.isArray(parsed)) agentsSelected = parsed.map((a) => String(a));
162
+ } catch {
163
+ // a corrupted value reads as "nothing selected"; PUT overwrites it.
164
+ }
165
+ }
166
+ // W-P4: the supi suggestions model; anything unreadable reads as «sin sugerencias».
167
+ let suggestionsModel: string | null = null;
168
+ const rawSug = this.getSetting('suggestions_model');
169
+ if (rawSug !== null) {
170
+ try {
171
+ const parsed = JSON.parse(rawSug);
172
+ if (typeof parsed === 'string' && parsed) suggestionsModel = parsed;
173
+ } catch {
174
+ // corrupt: same as unset; PUT overwrites it.
175
+ }
176
+ }
177
+ // D-M1: the default working model for pi.
178
+ let defaultModel: string | null = null;
179
+ const rawDef = this.getSetting('default_model');
180
+ if (rawDef !== null) {
181
+ try {
182
+ const parsed = JSON.parse(rawDef);
183
+ if (typeof parsed === 'string' && parsed) defaultModel = parsed;
184
+ } catch {
185
+ // corrupt: same as unset; PUT overwrites it.
186
+ }
187
+ }
188
+ // P3: full model ids configured for pi; corrupt or unset reads as [].
189
+ let models: string[] = [];
190
+ const rawModels = this.getSetting('pi_models');
191
+ if (rawModels !== null) {
192
+ try {
193
+ const parsed = JSON.parse(rawModels);
194
+ if (Array.isArray(parsed)) {
195
+ models = parsed.map((m) => String(m).trim()).filter(Boolean);
196
+ }
197
+ } catch {
198
+ // corrupt: fallback to []
199
+ }
200
+ }
201
+ return {
202
+ setup_done: setupDone,
203
+ agents_selected: agentsSelected,
204
+ suggestions_model: suggestionsModel,
205
+ default_model: defaultModel,
206
+ models,
207
+ };
208
+ }
209
+
210
+ /** Persists only the fields given (setup_done only via an explicit write, W-P1). */
211
+ saveSetupSelection(selection: {
212
+ agents_selected?: string[];
213
+ setup_done?: boolean;
214
+ suggestions_model?: string | null;
215
+ default_model?: string | null;
216
+ models?: string[];
217
+ }): void {
218
+ if (selection.agents_selected !== undefined) {
219
+ this.setSetting('agents_selected', JSON.stringify(selection.agents_selected));
220
+ }
221
+ if (selection.setup_done !== undefined) {
222
+ this.setSetting('setup_done', selection.setup_done ? 'true' : 'false');
223
+ }
224
+ if (selection.suggestions_model !== undefined) {
225
+ // stored as JSON so null and a string id are told apart; null = «sin sugerencias».
226
+ this.setSetting('suggestions_model', JSON.stringify(selection.suggestions_model));
227
+ }
228
+ if (selection.default_model !== undefined) {
229
+ this.setSetting('default_model', JSON.stringify(selection.default_model));
230
+ }
231
+ if (selection.models !== undefined) {
232
+ this.setSetting('pi_models', JSON.stringify(selection.models));
233
+ }
234
+ }
127
235
  }
@@ -34,6 +34,20 @@ export function repoKey(url: string): string {
34
34
  return url.trim().toLowerCase().replace(/\.git$/, '');
35
35
  }
36
36
 
37
+ /**
38
+ * Plan bond-app-nuevo-ticket (D1): with a linked GitHub issue, the issue names the ticket
39
+ * (`gh-<owner>-<repo>-<n>`) so the ticket, its id and the branch `feat/<id>` trace the issue.
40
+ * Anything that is not a plain GitHub issue URL yields null (uuid id as before).
41
+ */
42
+ export function issueTicketId(issueUrl?: string | null): string | null {
43
+ const url = String(issueUrl ?? '').trim();
44
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)(?:[#?].*)?$/.exec(url);
45
+ if (!m) return null;
46
+ const slug = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^[-.]+|[-.]+$/g, '');
47
+ const id = `gh-${slug(m[1])}-${slug(m[2])}-${m[3]}`.replace(/\.{2,}/g, '-');
48
+ return id.length <= 80 ? id : null;
49
+ }
50
+
37
51
  /**
38
52
  * P5: a ticket is exactly one of: a single repo (`repo_url`), a list of repos (`repos`; two
39
53
  * or more make the run create a hub) or an existing hub (`hub_url`, optional `hub_base`).
@@ -158,7 +172,13 @@ export class TicketRepository {
158
172
 
159
173
  const layout = normalizeLayout(input);
160
174
 
161
- const id = input.id || `ticket-${randomUUID().slice(0, 8)}`;
175
+ // D1: the linked issue decides the id unless one is given explicitly; the same issue
176
+ // cannot back two tickets.
177
+ const derivedId = input.id ? null : issueTicketId(input.issue_url);
178
+ if (derivedId && this.db.prepare('SELECT 1 FROM tickets WHERE id = ?').get(derivedId)) {
179
+ throw new Error(`There is already a ticket for this issue: ${derivedId}`);
180
+ }
181
+ const id = input.id || derivedId || `ticket-${randomUUID().slice(0, 8)}`;
162
182
  const now = new Date().toISOString();
163
183
  const baseBranch = layout.base_branch;
164
184
  const targetBranch = input.target_branch || `feat/${id}`;
@@ -192,6 +212,10 @@ export class TicketRepository {
192
212
  if (!validateVerifyCommands(verifyCommands)) {
193
213
  throw new Error("Field 'verify_commands' must be an array of at most 20 non-empty strings");
194
214
  }
215
+ if (input.bondify !== undefined && typeof input.bondify !== 'boolean') {
216
+ throw new Error("Field 'bondify' must be a boolean");
217
+ }
218
+ const bondify = input.bondify !== false;
195
219
  if (layoutBases(layout).includes(targetBranch)) {
196
220
  throw new Error('target_branch must differ from base_branch: a run only pushes its own branch (P4)');
197
221
  }
@@ -202,8 +226,8 @@ export class TicketRepository {
202
226
  INSERT INTO tickets (
203
227
  id, title, description, repo_url, base_branch, target_branch,
204
228
  budget_usd, timeout_minutes, agent, model, prompt, verify_commands,
205
- hub_url, hub_base, repos, repo_agents, issue_url, story, team_engine, status, created_at, updated_at
206
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
229
+ hub_url, hub_base, repos, repo_agents, issue_url, story, team_engine, bondify, status, created_at, updated_at
230
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
207
231
  `);
208
232
 
209
233
  const teamEngine = input.team_engine === 'herdr' ? 'herdr' : 'hc';
@@ -228,6 +252,7 @@ export class TicketRepository {
228
252
  input.issue_url ? String(input.issue_url).trim() : null,
229
253
  input.story || null,
230
254
  teamEngine,
255
+ bondify ? 1 : 0,
231
256
  status,
232
257
  now,
233
258
  now
@@ -324,6 +349,9 @@ export class TicketRepository {
324
349
  throw new Error("Field 'timeout_minutes' must be a positive finite number");
325
350
  }
326
351
  }
352
+ if (updates.bondify !== undefined && typeof updates.bondify !== 'boolean') {
353
+ throw new Error("Field 'bondify' must be a boolean");
354
+ }
327
355
 
328
356
  // Preserve status: status is managed via run lifecycle, not arbitrary ticket patch
329
357
  const merged = { ...existing, ...updates, status: existing.status, updated_at: new Date().toISOString() };
@@ -333,7 +361,7 @@ export class TicketRepository {
333
361
  title = ?, description = ?, repo_url = ?, base_branch = ?, target_branch = ?,
334
362
  budget_usd = ?, timeout_minutes = ?, agent = ?, model = ?, prompt = ?,
335
363
  verify_commands = ?, hub_url = ?, hub_base = ?, repos = ?, repo_agents = ?,
336
- issue_url = ?, story = ?, team_engine = ?, status = ?, updated_at = ?
364
+ issue_url = ?, story = ?, team_engine = ?, bondify = ?, status = ?, updated_at = ?
337
365
  WHERE id = ?
338
366
  `);
339
367
 
@@ -356,6 +384,7 @@ export class TicketRepository {
356
384
  merged.issue_url ? String(merged.issue_url).trim() : null,
357
385
  merged.story || null,
358
386
  merged.team_engine === 'herdr' ? 'herdr' : 'hc',
387
+ merged.bondify ? 1 : 0,
359
388
  merged.status,
360
389
  merged.updated_at,
361
390
  id
@@ -398,6 +427,7 @@ export class TicketRepository {
398
427
  prompt: row.prompt ? String(row.prompt) : undefined,
399
428
  verify_commands: parseVerifyCommands(row.verify_commands),
400
429
  team_engine: (row.team_engine === 'hc' ? 'hc' : 'herdr') as 'hc' | 'herdr',
430
+ bondify: row.bondify !== null && row.bondify !== undefined ? Number(row.bondify) !== 0 : true,
401
431
  status: row.status as RunState,
402
432
  created_at: String(row.created_at),
403
433
  updated_at: String(row.updated_at),
@@ -1,5 +1,7 @@
1
1
  import { execFile, spawn } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
+ import type { RunnerImageInfo } from '../types.ts';
4
+ import { parseRunnerManifest } from '../core/setup.ts';
3
5
 
4
6
  const execFileAsync = promisify(execFile);
5
7
 
@@ -389,4 +391,31 @@ export class DockerClient {
389
391
  throw err;
390
392
  }
391
393
  }
394
+
395
+ /**
396
+ * W-P1 (wizard): is the runner image there, and which agents does it bake? Presence is
397
+ * a plain `docker image inspect`; the agent list comes from the /opt/runner-agents
398
+ * manifest (image plan P1) read without booting the image's entrypoint: a throwaway
399
+ * `docker run --rm --network none --entrypoint cat` that no process of a run lives in.
400
+ * An older image without the manifest reports present with no agents. Never logs the
401
+ * manifest content; the manifest carries no secrets by design.
402
+ */
403
+ async inspectRunnerImage(image: string): Promise<RunnerImageInfo> {
404
+ try {
405
+ await execFileAsync('docker', ['image', 'inspect', image, '--format', '{{.Id}}'], { timeout: 20_000 });
406
+ } catch {
407
+ return { present: false };
408
+ }
409
+ try {
410
+ const { stdout } = await execFileAsync(
411
+ 'docker',
412
+ ['run', '--rm', '--network', 'none', '--entrypoint', 'cat', image, '/opt/runner-agents'],
413
+ { timeout: 30_000, maxBuffer: 256 * 1024 }
414
+ );
415
+ const agents = parseRunnerManifest(stdout);
416
+ return agents.length > 0 ? { present: true, agents } : { present: true };
417
+ } catch {
418
+ return { present: true };
419
+ }
420
+ }
392
421
  }
@@ -29,6 +29,20 @@ export interface PullRequest {
29
29
  created: boolean;
30
30
  }
31
31
 
32
+ /** Plan bond-app-nuevo-ticket (P1): una issue asignada al dueño del token, para el diálogo. */
33
+ export interface AssignedIssue {
34
+ url: string;
35
+ number: number;
36
+ owner: string;
37
+ repo: string;
38
+ title: string;
39
+ labels: string[];
40
+ ready: boolean;
41
+ updated_at: string;
42
+ /** Cuerpo de la issue (la US); recortado. El alta de ticket lo lleva como historia. */
43
+ body?: string;
44
+ }
45
+
32
46
  export class GitHubClient {
33
47
  private fetchImpl: FetchLike;
34
48
  private apiBase: string;
@@ -125,6 +139,111 @@ export class GitHubClient {
125
139
  return res.status === 200;
126
140
  }
127
141
 
142
+ /**
143
+ * Plan bond-app-nuevo-ticket (P1, D2): open issues assigned to the token's owner, across
144
+ * repos. Pull requests ride the /issues endpoints and are dropped here; `ready` is the
145
+ * label and sorts first, then most recently updated. 401/403 read as a credential problem.
146
+ */
147
+ async listAssigned(token: string): Promise<AssignedIssue[]> {
148
+ // REST root /issues: "issues assigned to the authenticated user" across repos
149
+ // (there is no /issues/assigned path on api.github.com; 404). PRs come mixed in
150
+ // and are filtered out below by the html_url shape.
151
+ const res = await this.call(token, 'GET', '/issues?state=open&per_page=100');
152
+ if (res.status !== 200) {
153
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
154
+ throw new GitHubApiError(`Failed to list assigned GitHub issues: ${msg}`, res.status);
155
+ }
156
+ const rows = Array.isArray(res.data) ? (res.data as Array<Record<string, unknown>>) : [];
157
+ const issues: AssignedIssue[] = [];
158
+ for (const row of rows) {
159
+ const url = String(row?.html_url ?? '');
160
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)$/.exec(url);
161
+ if (!m) continue; // pull requests and anything not a plain issue URL
162
+ const labels = Array.isArray(row?.labels)
163
+ ? (row.labels as Array<unknown>).map((l) => String((l as { name?: string })?.name ?? l ?? '')).filter(Boolean)
164
+ : [];
165
+ issues.push({
166
+ url,
167
+ number: parseInt(m[3], 10),
168
+ owner: m[1],
169
+ repo: m[2],
170
+ title: String(row?.title ?? ''),
171
+ labels,
172
+ ready: labels.some((l) => l.toLowerCase() === 'ready'),
173
+ updated_at: String(row?.updated_at ?? ''),
174
+ body: String(row?.body ?? '').slice(0, 8000),
175
+ });
176
+ }
177
+ issues.sort((a, b) => (Number(b.ready) - Number(a.ready)) || String(b.updated_at).localeCompare(String(a.updated_at)));
178
+ return issues;
179
+ }
180
+
181
+ /**
182
+ * Plan bond-app-nuevo-ticket (P2, búsqueda combinada): repos por nombre (los públicos y
183
+ * los privados accesibles con el token). La búsqueda es el buscador de GitHub sobre el
184
+ * nombre/descripción; orden tal cual los devuelve GitHub (best match).
185
+ */
186
+ async searchRepos(token: string, term: string): Promise<Array<{ full_name: string; url: string }>> {
187
+ const res = await this.call(token, 'GET', `/search/repositories?q=${encodeURIComponent(term)}&per_page=20`);
188
+ if (res.status !== 200) {
189
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
190
+ throw new GitHubApiError(`Failed to search GitHub repositories: ${msg}`, res.status);
191
+ }
192
+ const items = Array.isArray((res.data as { items?: unknown })?.items)
193
+ ? ((res.data as { items: Array<Record<string, unknown>> }).items)
194
+ : [];
195
+ const repos: Array<{ full_name: string; url: string }> = [];
196
+ for (const row of items) {
197
+ const full = String(row?.full_name ?? '');
198
+ if (!full || !String(row?.html_url ?? '').startsWith('https://github.com/')) continue;
199
+ repos.push({ full_name: full, url: String(row.html_url) });
200
+ }
201
+ return repos;
202
+ }
203
+
204
+ /**
205
+ * Open issues of one repo (the second step of the combined search): all open issues,
206
+ * not only assigned ones — `ready` first, the ones assigned to `myLogin` next.
207
+ */
208
+ async listRepoIssues(token: string, owner: string, repo: string, myLogin?: string | null) {
209
+ const res = await this.call(token, 'GET', `/repos/${owner}/${repo}/issues?state=open&per_page=100`);
210
+ if (res.status !== 200) {
211
+ const msg = (res.data as { message?: string } | null)?.message || `HTTP ${res.status}`;
212
+ throw new GitHubApiError(`Failed to list repo issues: ${msg}`, res.status);
213
+ }
214
+ const rows = Array.isArray(res.data) ? (res.data as Array<Record<string, unknown>>) : [];
215
+ const login = String(myLogin ?? '').toLowerCase();
216
+ const issues: Array<AssignedIssue & { assigned_to_me: boolean }> = [];
217
+ for (const row of rows) {
218
+ const url = String(row?.html_url ?? '');
219
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/issues\/([1-9][0-9]*)$/.exec(url);
220
+ if (!m) continue; // pull requests ride /repos/.../issues too
221
+ const labels = Array.isArray(row?.labels)
222
+ ? (row.labels as Array<unknown>).map((l) => String((l as { name?: string })?.name ?? l ?? '')).filter(Boolean)
223
+ : [];
224
+ const assignees = Array.isArray(row?.assignees)
225
+ ? (row.assignees as Array<Record<string, unknown>>).map((a) => String(a?.login ?? '').toLowerCase())
226
+ : [];
227
+ issues.push({
228
+ url,
229
+ number: parseInt(m[3], 10),
230
+ owner: m[1],
231
+ repo: m[2],
232
+ title: String(row?.title ?? ''),
233
+ labels,
234
+ ready: labels.some((l) => l.toLowerCase() === 'ready'),
235
+ updated_at: String(row?.updated_at ?? ''),
236
+ body: String(row?.body ?? '').slice(0, 8000),
237
+ assigned_to_me: Boolean(login) && assignees.includes(login),
238
+ });
239
+ }
240
+ issues.sort((a, b) =>
241
+ (Number(b.ready) - Number(a.ready))
242
+ || (Number(b.assigned_to_me) - Number(a.assigned_to_me))
243
+ || String(b.updated_at).localeCompare(String(a.updated_at)));
244
+ return issues;
245
+ }
246
+
128
247
  /**
129
248
  * P7: whether `branch` is merged into `base` in `owner/repo`.
130
249
  * Checks compare endpoint: status 'identical' or 'behind' (ahead_by === 0) means all commits in branch are in base.
@@ -190,6 +190,9 @@ export class HcClient {
190
190
  labels?: Record<string, string>;
191
191
  foreground?: { name?: string };
192
192
  };
193
+ const rawAgent = (res as any).agent || res.name || res.foreground?.name;
194
+ const isGeneric = rawAgent === 'agent' || (typeof rawAgent === 'string' && /^t\d+$/.test(rawAgent));
195
+ const agent = isGeneric ? undefined : rawAgent;
193
196
  return {
194
197
  address,
195
198
  name: res.name,
@@ -199,7 +202,7 @@ export class HcClient {
199
202
  exit_code: res.exit_code ?? null,
200
203
  turn: typeof res.turn === 'number' ? res.turn : 0,
201
204
  labels: res.labels ?? {},
202
- agent: res.name || res.foreground?.name,
205
+ agent,
203
206
  };
204
207
  }
205
208
 
@@ -273,7 +276,11 @@ export class HcClient {
273
276
  };
274
277
  }
275
278
  try {
276
- return await this.getTerminal(t.address);
279
+ const detail = await this.getTerminal(t.address);
280
+ return {
281
+ ...detail,
282
+ agent: detail.agent && detail.agent !== 'agent' ? detail.agent : (t.agent || t.name),
283
+ };
277
284
  } catch {
278
285
  return {
279
286
  address: t.address,