@jmanuelcorral/bond-app 0.1.5 → 0.1.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 (70) hide show
  1. package/README.md +211 -17
  2. package/app/brand/TOKENS.md +5 -5
  3. package/app/layouts/bond.json +10 -14
  4. package/app/mods/bond-agents/api.js +35 -0
  5. package/app/mods/bond-agents/branch.svg +1 -0
  6. package/app/mods/bond-agents/brand.js +53 -2
  7. package/app/mods/bond-agents/config.js +4 -0
  8. package/app/mods/bond-agents/eye-off.svg +1 -0
  9. package/app/mods/bond-agents/eye.svg +1 -0
  10. package/app/mods/bond-agents/main.js +308 -327
  11. package/app/mods/bond-agents/model.js +354 -5
  12. package/app/mods/bond-board/api.js +35 -0
  13. package/app/mods/bond-board/branch.svg +1 -0
  14. package/app/mods/bond-board/brand.js +53 -2
  15. package/app/mods/bond-board/config.js +4 -0
  16. package/app/mods/bond-board/main.js +686 -444
  17. package/app/mods/bond-board/model.js +99 -25
  18. package/app/mods/bond-pane/close.svg +1 -0
  19. package/app/mods/bond-pane/hide.svg +1 -0
  20. package/app/mods/bond-pane/main.js +103 -0
  21. package/app/mods/bond-pane/mod.json +1 -0
  22. package/app/mods/bond-pane/model.js +18 -0
  23. package/app/mods/bond-pane/split-down.svg +1 -0
  24. package/app/mods/bond-pane/split-right.svg +1 -0
  25. package/app/mods/bond-pane/unzoom.svg +1 -0
  26. package/app/mods/bond-pane/zoom.svg +1 -0
  27. package/app/mods/bond-settings/api.js +35 -0
  28. package/app/mods/bond-settings/brand.js +53 -2
  29. package/app/mods/bond-settings/config.js +4 -0
  30. package/app/mods/bond-settings/main.js +1159 -278
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-status/api.js +35 -0
  33. package/app/mods/bond-status/brand.js +53 -2
  34. package/app/mods/bond-status/config.js +4 -0
  35. package/app/mods/bond-status/main.js +37 -15
  36. package/app/mods/bond-status/model.js +19 -1
  37. package/app/mods/bond-tabs/brand.js +53 -2
  38. package/app/mods/bond-tabs/main.js +45 -3
  39. package/app/mods/bond-titlebar/brand.js +53 -2
  40. package/app/mods/bond-titlebar/main.js +85 -29
  41. package/app/mods/bond-titlebar/version.js +3 -0
  42. package/app/themes/bond-dark.json +5 -5
  43. package/app/themes/bond-light.json +5 -5
  44. package/package.json +1 -1
  45. package/runner/Dockerfile +16 -2
  46. package/runner/SPIKE-BOND.md +6 -2
  47. package/runner/entrypoint.sh +16 -0
  48. package/runner/setup.sh +439 -8
  49. package/runner/versions.env +32 -1
  50. package/scripts/app-install.ts +60 -1
  51. package/src/cli.ts +53 -3
  52. package/src/core/agy-login.ts +682 -0
  53. package/src/core/delivery.ts +3 -1
  54. package/src/core/orchestrator.ts +736 -78
  55. package/src/core/repo-host.ts +60 -0
  56. package/src/core/setup.ts +62 -1
  57. package/src/core/watchdog.ts +6 -6
  58. package/src/db/database.ts +41 -1
  59. package/src/db/settings-repo.ts +332 -7
  60. package/src/db/ticket-repo.ts +46 -20
  61. package/src/index.ts +4 -4
  62. package/src/runner/azure-devops-client.ts +163 -0
  63. package/src/runner/docker-client.ts +59 -9
  64. package/src/runner/github-client.ts +30 -3
  65. package/src/runner/hc-client.ts +33 -5
  66. package/src/runner/image-builder.ts +123 -5
  67. package/src/runner/jira-client.ts +368 -0
  68. package/src/runner/tool-catalog.ts +84 -0
  69. package/src/server/app.ts +377 -5
  70. package/src/types.ts +129 -2
@@ -0,0 +1,60 @@
1
+ import { validateGitHubUrl } from '../types.ts';
2
+
3
+ /**
4
+ * Plan bond-app-azure-jira P1: where a ticket's repo lives. GitHub (as always) or Azure
5
+ * Repos (Azure DevOps). Hubs and repo lists stay GitHub only; a single-repo ticket may be
6
+ * either.
7
+ */
8
+ export type RepoHost = 'github' | 'azure';
9
+
10
+ export interface AzureRepoRef {
11
+ /** https://dev.azure.com/<org> (the API and git root). */
12
+ orgUrl: string;
13
+ org: string;
14
+ project: string;
15
+ repo: string;
16
+ }
17
+
18
+ const NAME = '[A-Za-z0-9][A-Za-z0-9_.-]{0,99}';
19
+ // Projects and repos may carry spaces (URL-encoded as %20) and a few other characters.
20
+ const SEG = "[A-Za-z0-9_.~%'()+-]{1,200}";
21
+ const DEV_AZURE = new RegExp(`^https://(?:${NAME}@)?dev\\.azure\\.com/(${NAME})/(${SEG})/_git/(${SEG}?)/?$`);
22
+ const VISUALSTUDIO = new RegExp(`^https://(?:${NAME}@)?(${NAME})\\.visualstudio\\.com/(?:DefaultCollection/)?(${SEG})/_git/(${SEG}?)/?$`);
23
+
24
+ /**
25
+ * An Azure Repos clone URL, in either the dev.azure.com form or the older
26
+ * <org>.visualstudio.com one, with or without the `<user>@` git adds. Null otherwise.
27
+ */
28
+ export function parseAzureRepoUrl(url: string): AzureRepoRef | null {
29
+ const u = String(url ?? '').trim();
30
+ const m = DEV_AZURE.exec(u) ?? VISUALSTUDIO.exec(u);
31
+ if (!m) return null;
32
+ const [, org, project, repoRaw] = m;
33
+ const repo = repoRaw.replace(/\.git$/, '');
34
+ if (!repo || project.includes('..') || repo.includes('..')) return null;
35
+ return { orgUrl: `https://dev.azure.com/${org}`, org, project, repo };
36
+ }
37
+
38
+ /** The canonical clone URL of an Azure repo (dev.azure.com, no user part). */
39
+ export function azureRepoUrl(ref: AzureRepoRef): string {
40
+ return `${ref.orgUrl}/${ref.project}/_git/${ref.repo}`;
41
+ }
42
+
43
+ export function repoHostOf(url: string): RepoHost | null {
44
+ if (validateGitHubUrl(url)) return 'github';
45
+ if (parseAzureRepoUrl(url)) return 'azure';
46
+ return null;
47
+ }
48
+
49
+ /** A repo a single-repo ticket can work on: GitHub or Azure Repos. */
50
+ export function validateRepoUrl(url: string): boolean {
51
+ return repoHostOf(url) !== null;
52
+ }
53
+
54
+ /** «owner/repo» or «org/project/repo», for messages and the delete preview. */
55
+ export function repoLabel(url: string): string {
56
+ const az = parseAzureRepoUrl(url);
57
+ if (az) return `${az.org}/${decodeURIComponent(az.project)}/${decodeURIComponent(az.repo)}`;
58
+ const gh = /github\.com\/([^/]+)\/([^/]+?)(?:\.git)?$/.exec(url);
59
+ return gh ? `${gh[1]}/${gh[2]}` : url;
60
+ }
package/src/core/setup.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  type RunnerImageInfo,
6
6
  type SetupState,
7
7
  } from '../types.ts';
8
+ import { TOOL_CATALOG } from '../runner/tool-catalog.ts';
8
9
 
9
10
  /**
10
11
  * W-P1 (wizard): the aggregate the orchestrator serves at GET/PUT /api/v1/setup.
@@ -28,6 +29,51 @@ export function parseRunnerManifest(manifest: string): string[] {
28
29
  return agents;
29
30
  }
30
31
 
32
+ /**
33
+ * Plan bond-app-ajustes-imagen P2: the developer tool groups (`group=<id> installed=yes`)
34
+ * and extra apt packages (`apt_extra=a,b`) a manifest records. An image built before the
35
+ * catalog has neither: no tools.
36
+ */
37
+ export function parseRunnerManifestTools(manifest: string): { tools: string[]; apt_extra: string[] } {
38
+ const tools: string[] = [];
39
+ let aptExtra: string[] = [];
40
+ for (const line of manifest.split('\n')) {
41
+ const trimmed = line.trim();
42
+ const group = trimmed.match(/^group=([A-Za-z0-9_.-]+)(\s|$)/);
43
+ if (group) tools.push(group[1]);
44
+ const apt = trimmed.match(/^apt_extra=(\S+)$/);
45
+ if (apt) aptExtra = apt[1].split(',').filter(Boolean);
46
+ }
47
+ return { tools, apt_extra: aptExtra };
48
+ }
49
+
50
+ /** What the image lacks against the selection (agents and tool groups) and what it has extra. */
51
+ export function imageDrift(
52
+ image: RunnerImageInfo,
53
+ selection: { agents_selected: string[]; tools_selected: string[]; apt_extra: string[] },
54
+ recipe?: string
55
+ ): { stale: boolean; missing_agents: string[]; missing_tools: string[]; extra_tools: string[]; apt_changed: boolean; recipe_changed: boolean } {
56
+ if (!image.present) return { stale: false, missing_agents: [], missing_tools: [], extra_tools: [], apt_changed: false, recipe_changed: false };
57
+ const agents = image.agents ?? [];
58
+ const tools = image.tools ?? [];
59
+ const missing_agents = agents.length ? selection.agents_selected.filter((a) => !agents.includes(a)) : [];
60
+ const missing_tools = selection.tools_selected.filter((t) => !tools.includes(t));
61
+ const extra_tools = tools.filter((t) => !selection.tools_selected.includes(t));
62
+ const have = [...(image.apt_extra ?? [])].sort().join(',');
63
+ const want = [...selection.apt_extra].sort().join(',');
64
+ const apt_changed = have !== want;
65
+ // Only when the current recipe is known: an image without the label is older than it.
66
+ const recipe_changed = Boolean(recipe) && image.recipe !== recipe;
67
+ return {
68
+ stale: missing_agents.length > 0 || missing_tools.length > 0 || extra_tools.length > 0 || apt_changed || recipe_changed,
69
+ missing_agents,
70
+ missing_tools,
71
+ extra_tools,
72
+ apt_changed,
73
+ recipe_changed,
74
+ };
75
+ }
76
+
31
77
  export interface SetupStateInputs {
32
78
  setup_done: boolean;
33
79
  agents_selected: string[];
@@ -41,6 +87,11 @@ export interface SetupStateInputs {
41
87
  default_model?: string | null;
42
88
  /** P3: full model ids configured for pi (provider/id). */
43
89
  models?: string[];
90
+ /** Plan bond-app-ajustes-imagen P2: chosen tool groups and extra apt packages. */
91
+ tools_selected?: string[];
92
+ apt_extra?: string[];
93
+ /** Fingerprint of the current runner recipe (runnerRecipeHash); compared with the image's. */
94
+ recipe?: string;
44
95
  }
45
96
 
46
97
  /**
@@ -66,7 +117,17 @@ export function buildSetupState(inputs: SetupStateInputs): SetupState {
66
117
  configured: githubConfigured,
67
118
  ...(inputs.github.login !== undefined ? { login: inputs.github.login } : {}),
68
119
  },
69
- image: inputs.image,
120
+ image: {
121
+ ...inputs.image,
122
+ ...imageDrift(inputs.image, {
123
+ agents_selected: inputs.agents_selected,
124
+ tools_selected: inputs.tools_selected ?? [],
125
+ apt_extra: inputs.apt_extra ?? [],
126
+ }, inputs.recipe),
127
+ },
128
+ tools_selected: inputs.tools_selected ?? [],
129
+ apt_extra: inputs.apt_extra ?? [],
130
+ catalog: TOOL_CATALOG.map((g) => ({ ...g })),
70
131
  suggestions_model: inputs.suggestions_model ?? null,
71
132
  default_model: inputs.default_model ?? null,
72
133
  models: inputs.models ?? [],
@@ -71,14 +71,13 @@ export class Watchdog {
71
71
  return true;
72
72
  }
73
73
 
74
- // 2. Queued timeout check (M-D, P3 criterion 4): timeout measured strictly from created_at
75
- if (run.state === 'queued') {
74
+ // 2. Queued timeout check (M-D, P3 criterion 4): timeout measured strictly from created_at.
75
+ // timeout_minutes <= 0 means no timeout at all: a queued run is never terminated by
76
+ // the watchdog; it stays queued until budget or an explicit action ends it.
77
+ if (run.state === 'queued' && ticket.timeout_minutes > 0) {
76
78
  const queuedAt = new Date(run.created_at).getTime();
77
79
  const queuedElapsedMs = Date.now() - queuedAt;
78
- const maxQueuedMs =
79
- ticket.timeout_minutes > 0
80
- ? Math.min(ticket.timeout_minutes * 60 * 1000, 120_000)
81
- : 120_000;
80
+ const maxQueuedMs = Math.min(ticket.timeout_minutes * 60 * 1000, 120_000);
82
81
  if (queuedElapsedMs > maxQueuedMs) {
83
82
  await this.terminateViaOrchestrator(run.id, 'timeout');
84
83
  return true;
@@ -87,6 +86,7 @@ export class Watchdog {
87
86
 
88
87
  // 3. Execution timeout check (Criterion 4, P7)
89
88
  // Wall-clock timeout counts only time in running/verifying/analyzing (pause it in waiting, blocked and finished).
89
+ // timeout_minutes <= 0 disables it entirely.
90
90
  if (
91
91
  run.started_at &&
92
92
  ticket.timeout_minutes > 0 &&
@@ -37,7 +37,7 @@ export function initDatabase(dbPath: string): DatabaseSync {
37
37
  base_branch TEXT NOT NULL DEFAULT 'main',
38
38
  target_branch TEXT NOT NULL,
39
39
  budget_usd REAL NOT NULL DEFAULT 1.0,
40
- timeout_minutes INTEGER NOT NULL DEFAULT 20,
40
+ timeout_minutes INTEGER NOT NULL DEFAULT 0,
41
41
  agent TEXT NOT NULL DEFAULT 'pi',
42
42
  model TEXT,
43
43
  prompt TEXT,
@@ -50,6 +50,7 @@ export function initDatabase(dbPath: string): DatabaseSync {
50
50
  repo_agents TEXT,
51
51
  team_engine TEXT DEFAULT 'hc',
52
52
  bondify INTEGER NOT NULL DEFAULT 1,
53
+ docker INTEGER NOT NULL DEFAULT 0,
53
54
  status TEXT NOT NULL DEFAULT 'ready',
54
55
  created_at TEXT NOT NULL,
55
56
  updated_at TEXT NOT NULL
@@ -104,6 +105,28 @@ export function initDatabase(dbPath: string): DatabaseSync {
104
105
  updated_at TEXT NOT NULL
105
106
  );
106
107
 
108
+ -- Plan bond-app-azure-jira P1: the Azure DevOps PAT for Azure Repos (clone, push, PR).
109
+ -- One row; never returned by the API. agents_enabled: it also reaches the run's agents.
110
+ CREATE TABLE IF NOT EXISTS azure_devops_credential (
111
+ id INTEGER PRIMARY KEY CHECK (id = 1),
112
+ org_url TEXT NOT NULL,
113
+ pat TEXT NOT NULL,
114
+ account TEXT,
115
+ agents_enabled INTEGER NOT NULL DEFAULT 1,
116
+ updated_at TEXT NOT NULL
117
+ );
118
+
119
+ -- Plan bond-app-azure-jira (P2): Jira Cloud credential (email + API token)
120
+ CREATE TABLE IF NOT EXISTS jira_credential (
121
+ id INTEGER PRIMARY KEY CHECK (id = 1),
122
+ site TEXT NOT NULL,
123
+ email TEXT NOT NULL,
124
+ token TEXT NOT NULL,
125
+ agents_enabled INTEGER NOT NULL DEFAULT 1,
126
+ account_name TEXT,
127
+ updated_at TEXT NOT NULL
128
+ );
129
+
107
130
  -- W-P1 (wizard): key/value store for the orchestrator's own setup state
108
131
  -- (agents_selected, setup_done). Small strings only; never credentials.
109
132
  CREATE TABLE IF NOT EXISTS app_settings (
@@ -180,6 +203,23 @@ export function initDatabase(dbPath: string): DatabaseSync {
180
203
  db.exec('ALTER TABLE tickets ADD COLUMN bondify INTEGER DEFAULT 1;');
181
204
  db.exec('UPDATE tickets SET bondify = 1 WHERE bondify IS NULL;');
182
205
  }
206
+ // Plan bond-app-ajustes-imagen P4: «Docker en el run» (privileged container + dockerd); off.
207
+ if (!ticketCols.some((c) => c.name === 'docker')) {
208
+ db.exec('ALTER TABLE tickets ADD COLUMN docker INTEGER NOT NULL DEFAULT 0;');
209
+ }
210
+
211
+ // Plan bond-app-azure-jira P2: Jira Cloud credential table for pre-existing databases
212
+ db.exec(`
213
+ CREATE TABLE IF NOT EXISTS jira_credential (
214
+ id INTEGER PRIMARY KEY CHECK (id = 1),
215
+ site TEXT NOT NULL,
216
+ email TEXT NOT NULL,
217
+ token TEXT NOT NULL,
218
+ agents_enabled INTEGER NOT NULL DEFAULT 1,
219
+ account_name TEXT,
220
+ updated_at TEXT NOT NULL
221
+ );
222
+ `);
183
223
 
184
224
  return db;
185
225
  }
@@ -1,19 +1,128 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
2
4
  import {
3
5
  SUPPORTED_AGENTS,
4
6
  isValidAgent,
5
7
  validateGitHubLogin,
6
8
  validateGitHubToken,
9
+ validateJiraSite,
10
+ normalizeJiraSite,
11
+ validateJiraEmail,
12
+ validateJiraToken,
7
13
  type AgentCredential,
8
14
  type AgentCredentialSummary,
9
15
  type GitHubCredentialSummary,
16
+ type AzureDevOpsCredentialSummary,
17
+ type JiraCredential,
18
+ type JiraCredentialSummary,
10
19
  } from '../types.ts';
20
+ import { APT_PACKAGE_RE, DEFAULT_TOOLS, TOOL_IDS } from '../runner/tool-catalog.ts';
21
+
22
+ /** A `claude setup-token` token lasts one year from when it was made (stored). */
23
+ function withExpiry(summary: AgentCredentialSummary): AgentCredentialSummary {
24
+ if (summary.agent !== 'claude' || summary.provider !== 'setup-token' || !summary.updated_at) return summary;
25
+ const ends = new Date(summary.updated_at);
26
+ if (Number.isNaN(ends.getTime())) return summary;
27
+ ends.setFullYear(ends.getFullYear() + 1);
28
+ return { ...summary, expires_at: ends.toISOString() };
29
+ }
30
+
31
+ /**
32
+ * The account a login credential belongs to, for Ajustes (never the token): codex's ChatGPT
33
+ * email (from the id_token's claims) and copilot's GitHub login. Null when unreadable.
34
+ */
35
+ export function credentialAccount(agent: string, config: string | null | undefined): string | undefined {
36
+ if (!config) return undefined;
37
+ try {
38
+ if (agent === 'codex') {
39
+ const doc = JSON.parse(config) as { tokens?: { id_token?: string } };
40
+ const payload = doc.tokens?.id_token?.split('.')[1];
41
+ if (!payload) return undefined;
42
+ const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as Record<string, unknown>;
43
+ const profile = claims['https://api.openai.com/profile'] as { email?: unknown } | undefined;
44
+ const email = typeof claims.email === 'string' ? claims.email : profile?.email;
45
+ return typeof email === 'string' ? email : undefined;
46
+ }
47
+ if (agent === 'copilot') {
48
+ // copilot's config.json starts with // comment lines: not strict JSON.
49
+ const doc = JSON.parse(config.replace(/^\s*\/\/.*$/gm, '')) as { lastLoggedInUser?: { login?: unknown } };
50
+ const login = doc.lastLoggedInUser?.login;
51
+ return typeof login === 'string' ? login : undefined;
52
+ }
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * pi's models.json with every provider keyed: Ajustes never shows the saved key, so a provider
61
+ * saved without one keeps the key it already had (same provider name), and one that never had
62
+ * any gets "none" (pi refuses a provider without apiKey even when the server does not check).
63
+ * Anything that is not a pi models document is returned untouched.
64
+ */
65
+ export function keepPiKeys(previous: string | null | undefined, next: string): string {
66
+ let doc: { providers?: Record<string, Record<string, unknown>> };
67
+ try {
68
+ doc = JSON.parse(next);
69
+ } catch {
70
+ return next;
71
+ }
72
+ if (!doc?.providers || typeof doc.providers !== 'object') return next;
73
+ let old: Record<string, Record<string, unknown>> = {};
74
+ try {
75
+ old = (JSON.parse(previous ?? '{}') as { providers?: Record<string, Record<string, unknown>> }).providers ?? {};
76
+ } catch {}
77
+ let changed = false;
78
+ for (const [name, entry] of Object.entries(doc.providers)) {
79
+ if (!entry || typeof entry !== 'object' || (typeof entry.apiKey === 'string' && entry.apiKey.trim())) continue;
80
+ const kept = old[name]?.apiKey;
81
+ entry.apiKey = typeof kept === 'string' && kept.trim() ? kept : 'none';
82
+ changed = true;
83
+ }
84
+ return changed ? JSON.stringify(doc, null, 2) : next;
85
+ }
11
86
 
12
87
  export class SettingsRepository {
13
88
  private db: DatabaseSync;
89
+ private dataDir?: string;
14
90
 
15
- constructor(db: DatabaseSync) {
91
+ constructor(db: DatabaseSync, dataDir?: string) {
16
92
  this.db = db;
93
+ this.dataDir = dataDir;
94
+ }
95
+
96
+ setDataDir(dataDir: string): void {
97
+ this.dataDir = dataDir;
98
+ }
99
+
100
+ private getAgySummary(): AgentCredentialSummary | null {
101
+ if (!this.dataDir || this.dataDir === ':memory:') return null;
102
+ const tokenPath = path.join(this.dataDir, 'antigravity-oauth-token');
103
+ try {
104
+ if (!fs.existsSync(tokenPath)) {
105
+ return {
106
+ agent: 'agy',
107
+ configured: false,
108
+ };
109
+ }
110
+ const stat = fs.statSync(tokenPath);
111
+ const content = fs.readFileSync(tokenPath, 'utf8');
112
+ const parsed = JSON.parse(content);
113
+ const email = typeof parsed?.id_token_email === 'string' ? parsed.id_token_email : undefined;
114
+ return {
115
+ agent: 'agy',
116
+ configured: true,
117
+ email,
118
+ updated_at: stat.mtime.toISOString(),
119
+ };
120
+ } catch {
121
+ return {
122
+ agent: 'agy',
123
+ configured: false,
124
+ };
125
+ }
17
126
  }
18
127
 
19
128
  setCredential(agent: string, configJson: string, provider?: string): AgentCredential {
@@ -32,6 +141,16 @@ export class SettingsRepository {
32
141
  `);
33
142
 
34
143
  stmt.run(agent, provider || null, configJson, now);
144
+
145
+ if (agent === 'agy' && this.dataDir && this.dataDir !== ':memory:') {
146
+ const tokenPath = path.join(this.dataDir, 'antigravity-oauth-token');
147
+ try {
148
+ fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
149
+ fs.writeFileSync(tokenPath, configJson, { mode: 0o600 });
150
+ fs.chmodSync(tokenPath, 0o600);
151
+ } catch {}
152
+ }
153
+
35
154
  return {
36
155
  agent,
37
156
  provider,
@@ -41,6 +160,20 @@ export class SettingsRepository {
41
160
  }
42
161
 
43
162
  getCredential(agent: string): AgentCredential | null {
163
+ if (agent === 'agy' && this.dataDir && this.dataDir !== ':memory:') {
164
+ const tokenPath = path.join(this.dataDir, 'antigravity-oauth-token');
165
+ try {
166
+ if (fs.existsSync(tokenPath)) {
167
+ const content = fs.readFileSync(tokenPath, 'utf8');
168
+ const stat = fs.statSync(tokenPath);
169
+ return {
170
+ agent: 'agy',
171
+ config_json: content,
172
+ updated_at: stat.mtime.toISOString(),
173
+ };
174
+ }
175
+ } catch {}
176
+ }
44
177
  const stmt = this.db.prepare('SELECT * FROM agent_credentials WHERE agent = ?');
45
178
  const row = stmt.get(agent) as unknown as Record<string, unknown> | undefined;
46
179
  if (!row) return null;
@@ -53,38 +186,63 @@ export class SettingsRepository {
53
186
  }
54
187
 
55
188
  getSummary(agent: string): AgentCredentialSummary {
189
+ if (agent === 'agy' && this.dataDir && this.dataDir !== ':memory:') {
190
+ const agySummary = this.getAgySummary();
191
+ if (agySummary) return agySummary;
192
+ }
56
193
  const cred = this.getCredential(agent);
57
- return {
194
+ const account = credentialAccount(agent, cred?.config_json);
195
+ return withExpiry({
58
196
  agent,
59
197
  provider: cred?.provider,
60
198
  configured: Boolean(cred),
61
199
  updated_at: cred?.updated_at,
62
- };
200
+ ...(account ? { email: account } : {}),
201
+ });
63
202
  }
64
203
 
65
204
  listSummaries(): AgentCredentialSummary[] {
66
- const stmt = this.db.prepare('SELECT agent, provider, updated_at FROM agent_credentials');
205
+ const agySummary = this.dataDir && this.dataDir !== ':memory:' ? this.getAgySummary() : null;
206
+ const stmt = this.db.prepare('SELECT agent, provider, config_json, updated_at FROM agent_credentials');
67
207
  const rows = stmt.all() as unknown as Array<Record<string, unknown>>;
68
- const configuredMap = new Map<string, { provider?: string; updated_at: string }>();
208
+ const configuredMap = new Map<string, { provider?: string; updated_at: string; email?: string }>();
69
209
 
70
210
  for (const row of rows) {
71
211
  configuredMap.set(String(row.agent), {
72
212
  provider: row.provider ? String(row.provider) : undefined,
73
213
  updated_at: String(row.updated_at),
214
+ email: credentialAccount(String(row.agent), row.config_json ? String(row.config_json) : null),
74
215
  });
75
216
  }
76
217
 
77
218
  return SUPPORTED_AGENTS.map((agent) => {
219
+ if (agent === 'agy' && agySummary) {
220
+ return agySummary;
221
+ }
78
222
  const info = configuredMap.get(agent);
79
- return {
223
+ return withExpiry({
80
224
  agent,
81
225
  provider: info?.provider,
82
226
  configured: Boolean(info),
83
227
  updated_at: info?.updated_at,
84
- };
228
+ ...(info?.email ? { email: info.email } : {}),
229
+ });
85
230
  });
86
231
  }
87
232
 
233
+ deleteCredential(agent: string): boolean {
234
+ if (agent === 'agy' && this.dataDir && this.dataDir !== ':memory:') {
235
+ const tokenPath = path.join(this.dataDir, 'antigravity-oauth-token');
236
+ try {
237
+ if (fs.existsSync(tokenPath)) {
238
+ fs.unlinkSync(tokenPath);
239
+ }
240
+ } catch {}
241
+ }
242
+ const res = this.db.prepare('DELETE FROM agent_credentials WHERE agent = ?').run(agent);
243
+ return res.changes > 0;
244
+ }
245
+
88
246
  /** D20: store (or replace) the GitHub credential taken from the user's gh session. */
89
247
  setGitHubCredential(token: string, login?: string | null): GitHubCredentialSummary {
90
248
  if (!validateGitHubToken(token)) {
@@ -125,6 +283,139 @@ export class SettingsRepository {
125
283
  return this.db.prepare('DELETE FROM github_credential WHERE id = 1').run().changes > 0;
126
284
  }
127
285
 
286
+ // --- Alta de ticket: repos favoritos (★) -------------------------------------------------
287
+
288
+ /** The favorite repos, in the order they were added (clone URLs, GitHub or Azure). */
289
+ getFavoriteRepos(): string[] {
290
+ try {
291
+ const parsed = JSON.parse(this.getSetting('favorite_repos') ?? '[]');
292
+ return Array.isArray(parsed) ? parsed.map((u) => String(u)).filter(Boolean) : [];
293
+ } catch {
294
+ return [];
295
+ }
296
+ }
297
+
298
+ setFavoriteRepos(urls: string[]): string[] {
299
+ const clean = [...new Set(urls.map((u) => String(u).trim()).filter(Boolean))].slice(0, 50);
300
+ this.setSetting('favorite_repos', JSON.stringify(clean));
301
+ return clean;
302
+ }
303
+
304
+ // --- Plan bond-app-azure-jira P1: Azure DevOps (Azure Repos) ---------------------------
305
+
306
+ setAzureDevOpsCredential(orgUrl: string, pat: string, account: string | null, agentsEnabled: boolean): AzureDevOpsCredentialSummary {
307
+ if (!/^https:\/\/dev\.azure\.com\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(orgUrl)) throw new Error('Invalid Azure DevOps organization URL');
308
+ if (!/^[A-Za-z0-9]{20,200}$/.test(pat)) throw new Error('Invalid Azure DevOps PAT format');
309
+ const now = new Date().toISOString();
310
+ this.db.prepare(`
311
+ INSERT INTO azure_devops_credential (id, org_url, pat, account, agents_enabled, updated_at) VALUES (1, ?, ?, ?, ?, ?)
312
+ ON CONFLICT(id) DO UPDATE SET org_url = excluded.org_url, pat = excluded.pat, account = excluded.account,
313
+ agents_enabled = excluded.agents_enabled, updated_at = excluded.updated_at
314
+ `).run(orgUrl, pat, account, agentsEnabled ? 1 : 0, now);
315
+ return this.getAzureDevOpsSummary();
316
+ }
317
+
318
+ /** Only the «available to the agents» switch, keeping the PAT. */
319
+ setAzureDevOpsAgentsEnabled(enabled: boolean): AzureDevOpsCredentialSummary {
320
+ this.db.prepare('UPDATE azure_devops_credential SET agents_enabled = ? WHERE id = 1').run(enabled ? 1 : 0);
321
+ return this.getAzureDevOpsSummary();
322
+ }
323
+
324
+ /** For the orchestrator only: clone/push (stdin), PR calls (header), agent env (0600 file). */
325
+ getAzureDevOpsCredential(): { org_url: string; pat: string; agents_enabled: boolean } | null {
326
+ const row = this.db.prepare('SELECT org_url, pat, agents_enabled FROM azure_devops_credential WHERE id = 1').get() as
327
+ | { org_url?: string; pat?: string; agents_enabled?: number }
328
+ | undefined;
329
+ if (!row?.pat || !row.org_url) return null;
330
+ return { org_url: String(row.org_url), pat: String(row.pat), agents_enabled: Number(row.agents_enabled ?? 1) !== 0 };
331
+ }
332
+
333
+ getAzureDevOpsSummary(): AzureDevOpsCredentialSummary {
334
+ const row = this.db.prepare('SELECT org_url, account, agents_enabled, updated_at FROM azure_devops_credential WHERE id = 1').get() as
335
+ | { org_url?: string; account?: string | null; agents_enabled?: number; updated_at?: string }
336
+ | undefined;
337
+ if (!row) return { configured: false };
338
+ return {
339
+ configured: true,
340
+ org_url: String(row.org_url),
341
+ ...(row.account ? { account: String(row.account) } : {}),
342
+ agents_enabled: Number(row.agents_enabled ?? 1) !== 0,
343
+ updated_at: row.updated_at ? String(row.updated_at) : undefined,
344
+ };
345
+ }
346
+
347
+ deleteAzureDevOpsCredential(): boolean {
348
+ return this.db.prepare('DELETE FROM azure_devops_credential WHERE id = 1').run().changes > 0;
349
+ }
350
+
351
+ // --- Plan bond-app-azure-jira P2: Jira Cloud credentials ---------------------------
352
+
353
+ setJiraCredential(
354
+ site: string,
355
+ email: string,
356
+ token: string,
357
+ agentsEnabled = true,
358
+ accountName?: string | null
359
+ ): JiraCredentialSummary {
360
+ if (!validateJiraSite(site)) {
361
+ throw new Error("Invalid Jira site URL (must be https://<name>.atlassian.net)");
362
+ }
363
+ if (!validateJiraEmail(email)) {
364
+ throw new Error("Invalid Jira email address");
365
+ }
366
+ if (!validateJiraToken(token)) {
367
+ throw new Error("Invalid Jira API token");
368
+ }
369
+ const normalizedSite = normalizeJiraSite(site);
370
+ const now = new Date().toISOString();
371
+ this.db.prepare(`
372
+ INSERT INTO jira_credential (id, site, email, token, agents_enabled, account_name, updated_at)
373
+ VALUES (1, ?, ?, ?, ?, ?, ?)
374
+ ON CONFLICT(id) DO UPDATE SET
375
+ site = excluded.site,
376
+ email = excluded.email,
377
+ token = excluded.token,
378
+ agents_enabled = excluded.agents_enabled,
379
+ account_name = excluded.account_name,
380
+ updated_at = excluded.updated_at
381
+ `).run(normalizedSite, email.trim(), token.trim(), agentsEnabled ? 1 : 0, accountName ?? null, now);
382
+ return this.getJiraSummary();
383
+ }
384
+
385
+ getJiraCredential(): JiraCredential | null {
386
+ const row = this.db.prepare('SELECT site, email, token, agents_enabled, account_name, updated_at FROM jira_credential WHERE id = 1').get() as
387
+ | { site: string; email: string; token: string; agents_enabled: number; account_name?: string | null; updated_at: string }
388
+ | undefined;
389
+ if (!row) return null;
390
+ return {
391
+ site: String(row.site),
392
+ email: String(row.email),
393
+ token: String(row.token),
394
+ agents_enabled: Boolean(row.agents_enabled),
395
+ account_name: row.account_name ? String(row.account_name) : null,
396
+ updated_at: String(row.updated_at),
397
+ };
398
+ }
399
+
400
+ getJiraSummary(): JiraCredentialSummary {
401
+ const row = this.db.prepare('SELECT site, email, agents_enabled, account_name, updated_at FROM jira_credential WHERE id = 1').get() as
402
+ | { site: string; email: string; agents_enabled: number; account_name?: string | null; updated_at: string }
403
+ | undefined;
404
+ if (!row) return { configured: false };
405
+ return {
406
+ configured: true,
407
+ site: String(row.site),
408
+ email: String(row.email),
409
+ agents_enabled: Boolean(row.agents_enabled),
410
+ account_name: row.account_name ? String(row.account_name) : null,
411
+ updated_at: String(row.updated_at),
412
+ };
413
+ }
414
+
415
+ deleteJiraCredential(): boolean {
416
+ return this.db.prepare('DELETE FROM jira_credential WHERE id = 1').run().changes > 0;
417
+ }
418
+
128
419
  // --- W-P1: setup state (wizard) -----------------------------------------------------
129
420
  // A small key/value store of the orchestrator's own configuration state. Only the
130
421
  // selection and the setup_done flag live here; credentials stay in their own tables.
@@ -151,6 +442,8 @@ export class SettingsRepository {
151
442
  suggestions_model: string | null;
152
443
  default_model: string | null;
153
444
  models: string[];
445
+ tools_selected: string[];
446
+ apt_extra: string[];
154
447
  } {
155
448
  const setupDone = this.getSetting('setup_done') === 'true';
156
449
  let agentsSelected: string[] = [];
@@ -198,12 +491,36 @@ export class SettingsRepository {
198
491
  // corrupt: fallback to []
199
492
  }
200
493
  }
494
+ // Plan bond-app-ajustes-imagen P2: never chosen → the catalog's defaults; a stored list
495
+ // (even empty: «sin herramientas») is kept as is. Unknown ids from an older catalog drop.
496
+ let toolsSelected: string[] = [...DEFAULT_TOOLS];
497
+ const rawTools = this.getSetting('tools_selected');
498
+ if (rawTools !== null) {
499
+ try {
500
+ const parsed = JSON.parse(rawTools);
501
+ if (Array.isArray(parsed)) toolsSelected = TOOL_IDS.filter((id) => parsed.includes(id));
502
+ } catch {
503
+ // corrupt: the defaults; PUT overwrites it.
504
+ }
505
+ }
506
+ let aptExtra: string[] = [];
507
+ const rawApt = this.getSetting('apt_extra');
508
+ if (rawApt !== null) {
509
+ try {
510
+ const parsed = JSON.parse(rawApt);
511
+ if (Array.isArray(parsed)) aptExtra = parsed.map((p) => String(p)).filter((p) => APT_PACKAGE_RE.test(p));
512
+ } catch {
513
+ // corrupt: none.
514
+ }
515
+ }
201
516
  return {
202
517
  setup_done: setupDone,
203
518
  agents_selected: agentsSelected,
204
519
  suggestions_model: suggestionsModel,
205
520
  default_model: defaultModel,
206
521
  models,
522
+ tools_selected: toolsSelected,
523
+ apt_extra: aptExtra,
207
524
  };
208
525
  }
209
526
 
@@ -214,6 +531,8 @@ export class SettingsRepository {
214
531
  suggestions_model?: string | null;
215
532
  default_model?: string | null;
216
533
  models?: string[];
534
+ tools_selected?: string[];
535
+ apt_extra?: string[];
217
536
  }): void {
218
537
  if (selection.agents_selected !== undefined) {
219
538
  this.setSetting('agents_selected', JSON.stringify(selection.agents_selected));
@@ -231,5 +550,11 @@ export class SettingsRepository {
231
550
  if (selection.models !== undefined) {
232
551
  this.setSetting('pi_models', JSON.stringify(selection.models));
233
552
  }
553
+ if (selection.tools_selected !== undefined) {
554
+ this.setSetting('tools_selected', JSON.stringify(selection.tools_selected));
555
+ }
556
+ if (selection.apt_extra !== undefined) {
557
+ this.setSetting('apt_extra', JSON.stringify(selection.apt_extra));
558
+ }
234
559
  }
235
560
  }