@pantheon.ai/agents 0.0.6 → 0.0.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 (2) hide show
  1. package/dist/index.js +2215 -2175
  2. package/package.json +4 -2
package/dist/index.js CHANGED
@@ -1,2128 +1,2260 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
+ import * as process$1 from "node:process";
3
4
  import { createCommand } from "commander";
4
- import expandTilde from "expand-tilde";
5
+ import * as fs from "node:fs";
5
6
  import path from "node:path";
6
- import * as process$1 from "node:process";
7
- import readline from "node:readline/promises";
8
7
  import { multistream, pino, transport } from "pino";
9
- import * as fs$1 from "node:fs";
10
8
  import { Kysely, MysqlDialect } from "kysely";
11
9
  import { createPool } from "mysql2";
12
10
  import z$1, { z } from "zod";
11
+ import readline from "node:readline/promises";
12
+ import expandTilde from "expand-tilde";
13
13
 
14
14
  //#region \0rolldown/runtime.js
15
15
  var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
16
16
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
17
17
 
18
18
  //#endregion
19
- //#region src/schemas/task-list.ts
20
- const taskItemSchema = z.discriminatedUnion("status", [
21
- z.object({
22
- status: z.literal("pending"),
23
- id: z.string(),
24
- task: z.string(),
25
- project_id: z.uuid(),
26
- base_branch_id: z.uuid(),
27
- queued_at: z.coerce.date()
28
- }),
29
- z.object({
30
- status: z.literal("running"),
31
- id: z.string(),
32
- task: z.string(),
33
- project_id: z.uuid(),
34
- base_branch_id: z.uuid(),
35
- branch_id: z.uuid(),
36
- queued_at: z.coerce.date(),
37
- started_at: z.coerce.date()
38
- }),
39
- z.object({
40
- status: z.literal("completed"),
41
- id: z.string(),
42
- task: z.string(),
43
- project_id: z.uuid(),
44
- base_branch_id: z.uuid(),
45
- branch_id: z.uuid(),
46
- queued_at: z.coerce.date(),
47
- started_at: z.coerce.date(),
48
- ended_at: z.coerce.date(),
49
- output: z.string()
50
- }),
51
- z.object({
52
- status: z.literal("failed"),
53
- id: z.string(),
54
- task: z.string(),
55
- project_id: z.uuid(),
56
- base_branch_id: z.uuid(),
57
- branch_id: z.uuid().nullable().optional(),
58
- queued_at: z.coerce.date(),
59
- started_at: z.coerce.date().nullable().optional(),
60
- ended_at: z.coerce.date().nullable().optional(),
61
- error: z.string()
62
- }),
63
- z.object({
64
- status: z.literal("cancelled"),
65
- id: z.string(),
66
- task: z.string(),
67
- project_id: z.uuid(),
68
- queued_at: z.coerce.date(),
69
- cancelled_at: z.coerce.date()
70
- })
71
- ]);
72
-
73
- //#endregion
74
- //#region src/utils/get-error-message.ts
75
- function getErrorMessage(error) {
76
- return String(error?.message ?? error);
77
- }
19
+ //#region ../../node_modules/dotenv/package.json
20
+ var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
21
+ module.exports = {
22
+ "name": "dotenv",
23
+ "version": "17.2.4",
24
+ "description": "Loads environment variables from .env file",
25
+ "main": "lib/main.js",
26
+ "types": "lib/main.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./lib/main.d.ts",
30
+ "require": "./lib/main.js",
31
+ "default": "./lib/main.js"
32
+ },
33
+ "./config": "./config.js",
34
+ "./config.js": "./config.js",
35
+ "./lib/env-options": "./lib/env-options.js",
36
+ "./lib/env-options.js": "./lib/env-options.js",
37
+ "./lib/cli-options": "./lib/cli-options.js",
38
+ "./lib/cli-options.js": "./lib/cli-options.js",
39
+ "./package.json": "./package.json"
40
+ },
41
+ "scripts": {
42
+ "dts-check": "tsc --project tests/types/tsconfig.json",
43
+ "lint": "standard",
44
+ "pretest": "npm run lint && npm run dts-check",
45
+ "test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
46
+ "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
47
+ "prerelease": "npm test",
48
+ "release": "standard-version"
49
+ },
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git://github.com/motdotla/dotenv.git"
53
+ },
54
+ "homepage": "https://github.com/motdotla/dotenv#readme",
55
+ "funding": "https://dotenvx.com",
56
+ "keywords": [
57
+ "dotenv",
58
+ "env",
59
+ ".env",
60
+ "environment",
61
+ "variables",
62
+ "config",
63
+ "settings"
64
+ ],
65
+ "readmeFilename": "README.md",
66
+ "license": "BSD-2-Clause",
67
+ "devDependencies": {
68
+ "@types/node": "^18.11.3",
69
+ "decache": "^4.6.2",
70
+ "sinon": "^14.0.1",
71
+ "standard": "^17.0.0",
72
+ "standard-version": "^9.5.0",
73
+ "tap": "^19.2.0",
74
+ "typescript": "^4.8.4"
75
+ },
76
+ "engines": { "node": ">=12" },
77
+ "browser": { "fs": false }
78
+ };
79
+ }));
78
80
 
79
81
  //#endregion
80
- //#region src/providers/task-list-provider.ts
81
- var TaskListProvider = class {
82
- logger;
83
- agentName;
84
- constructor(agentName, logger) {
85
- this.agentName = agentName;
86
- this.logger = logger;
82
+ //#region ../../node_modules/dotenv/lib/main.js
83
+ var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
84
+ const fs$1 = __require("fs");
85
+ const path$1 = __require("path");
86
+ const os = __require("os");
87
+ const crypto = __require("crypto");
88
+ const version = require_package().version;
89
+ const TIPS = [
90
+ "🔐 encrypt with Dotenvx: https://dotenvx.com",
91
+ "🔐 prevent committing .env to code: https://dotenvx.com/precommit",
92
+ "🔐 prevent building .env in docker: https://dotenvx.com/prebuild",
93
+ "📡 add observability to secrets: https://dotenvx.com/ops",
94
+ "👥 sync secrets across teammates & machines: https://dotenvx.com/ops",
95
+ "🗂️ backup and recover secrets: https://dotenvx.com/ops",
96
+ "✅ audit secrets and track compliance: https://dotenvx.com/ops",
97
+ "🔄 add secrets lifecycle management: https://dotenvx.com/ops",
98
+ "🔑 add access controls to secrets: https://dotenvx.com/ops",
99
+ "🛠️ run anywhere with `dotenvx run -- yourcommand`",
100
+ "⚙️ specify custom .env file path with { path: '/custom/path/.env' }",
101
+ "⚙️ enable debug logging with { debug: true }",
102
+ "⚙️ override existing env vars with { override: true }",
103
+ "⚙️ suppress all logs with { quiet: true }",
104
+ "⚙️ write to custom object with { processEnv: myObject }",
105
+ "⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"
106
+ ];
107
+ function _getRandomTip() {
108
+ return TIPS[Math.floor(Math.random() * TIPS.length)];
87
109
  }
88
- async createTask(params) {
89
- return await this.insertTask({
90
- status: "pending",
91
- ...params,
92
- queued_at: /* @__PURE__ */ new Date()
93
- });
110
+ function parseBoolean(value) {
111
+ if (typeof value === "string") return ![
112
+ "false",
113
+ "0",
114
+ "no",
115
+ "off",
116
+ ""
117
+ ].includes(value.toLowerCase());
118
+ return Boolean(value);
94
119
  }
95
- async startTask({ status, id, ...task }, startTask) {
96
- const now = /* @__PURE__ */ new Date();
97
- let updatePromise;
98
- try {
99
- this.logger.info(`Starting task ${id}`);
100
- const branchId = await startTask(task);
101
- this.logger.info(`Started task ${id} at branch ${branchId}`);
102
- updatePromise = this.updateTask({
103
- status: "running",
104
- id,
105
- ...task,
106
- branch_id: branchId,
107
- started_at: now
108
- });
109
- } catch (e) {
110
- this.logger.error("Failed to start task: %s", getErrorMessage(e));
111
- updatePromise = this.updateTask({
112
- status: "failed",
113
- id,
114
- ...task,
115
- started_at: now,
116
- ended_at: /* @__PURE__ */ new Date(),
117
- error: getErrorMessage(e)
118
- }).then(() => Promise.reject(e));
119
- }
120
- await updatePromise;
120
+ function supportsAnsi() {
121
+ return process.stdout.isTTY;
121
122
  }
122
- async failTask(task, error) {
123
- if (task.status !== "running") {
124
- this.logger.error(`Can't fail a task that is not running. [task = ${task.id}, status = ${task.status}]`);
125
- throw new Error("Can't fail a task that is not running");
126
- }
127
- await this.updateTask({
128
- ...task,
129
- status: "failed",
130
- ended_at: /* @__PURE__ */ new Date(),
131
- error
132
- });
123
+ function dim(text) {
124
+ return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text;
133
125
  }
134
- async completeTask(task, output) {
135
- if (task.status !== "running") {
136
- this.logger.error(`Can't complete a task that is not running. [task = ${task.id}, status = ${task.status}]`);
137
- throw new Error("Can't complete a task that is not running");
126
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
127
+ function parse(src) {
128
+ const obj = {};
129
+ let lines = src.toString();
130
+ lines = lines.replace(/\r\n?/gm, "\n");
131
+ let match;
132
+ while ((match = LINE.exec(lines)) != null) {
133
+ const key = match[1];
134
+ let value = match[2] || "";
135
+ value = value.trim();
136
+ const maybeQuote = value[0];
137
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
138
+ if (maybeQuote === "\"") {
139
+ value = value.replace(/\\n/g, "\n");
140
+ value = value.replace(/\\r/g, "\r");
141
+ }
142
+ obj[key] = value;
138
143
  }
139
- await this.updateTask({
140
- ...task,
141
- status: "completed",
142
- ended_at: /* @__PURE__ */ new Date(),
143
- output
144
- });
144
+ return obj;
145
145
  }
146
- async cancelTask(task) {
147
- if (task.status !== "pending") {
148
- this.logger.error(`Can't cancel a task that is not pending. [task = ${task.id}, status = ${task.status}]`);
149
- throw new Error("Can't cancel a task that is not pending");
146
+ function _parseVault(options) {
147
+ options = options || {};
148
+ const vaultPath = _vaultPath(options);
149
+ options.path = vaultPath;
150
+ const result = DotenvModule.configDotenv(options);
151
+ if (!result.parsed) {
152
+ const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
153
+ err.code = "MISSING_DATA";
154
+ throw err;
150
155
  }
151
- await this.updateTask({
152
- ...task,
153
- status: "cancelled",
154
- cancelled_at: /* @__PURE__ */ new Date()
155
- });
156
- }
157
- };
158
-
159
- //#endregion
160
- //#region src/providers/task-list-tidb-provider.ts
161
- var TaskListTidbProvider = class extends TaskListProvider {
162
- db;
163
- constructor(agentName, logger) {
164
- super(agentName, logger);
165
- this.db = new Kysely({ dialect: new MysqlDialect({ pool: createPool({
166
- uri: process.env.DATABASE_URL,
167
- supportBigNumbers: true,
168
- bigNumberStrings: true
169
- }) }) });
170
- }
171
- async close() {
172
- await this.db.destroy();
156
+ const keys = _dotenvKey(options).split(",");
157
+ const length = keys.length;
158
+ let decrypted;
159
+ for (let i = 0; i < length; i++) try {
160
+ const attrs = _instructions(result, keys[i].trim());
161
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
162
+ break;
163
+ } catch (error) {
164
+ if (i + 1 >= length) throw error;
165
+ }
166
+ return DotenvModule.parse(decrypted);
173
167
  }
174
- selectTask() {
175
- return this.db.selectFrom("task").selectAll().where("agent", "=", this.agentName);
168
+ function _warn(message) {
169
+ console.error(`[dotenv@${version}][WARN] ${message}`);
176
170
  }
177
- async getAgentConfig(projectId) {
178
- const config = await this.db.selectFrom("agent_project_config").selectAll().where("project_id", "=", projectId).where("agent", "=", this.agentName).executeTakeFirst();
179
- if (config == null) return null;
180
- return config;
171
+ function _debug(message) {
172
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
181
173
  }
182
- async getAgentConfigs() {
183
- return await this.db.selectFrom("agent_project_config").selectAll().where("agent", "=", this.agentName).execute();
174
+ function _log(message) {
175
+ console.log(`[dotenv@${version}] ${message}`);
184
176
  }
185
- async setAgentConfig({ skills, ...config }) {
186
- await this.db.insertInto("agent_project_config").values({
187
- agent: this.agentName,
188
- skills: JSON.stringify(skills),
189
- ...config
190
- }).execute();
177
+ function _dotenvKey(options) {
178
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
179
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
180
+ return "";
191
181
  }
192
- async getTask(taskId) {
193
- const taskItem = await this.selectTask().where("id", "=", taskId).executeTakeFirst();
194
- if (taskItem == null) return null;
195
- return taskItemSchema.parse(taskItem);
182
+ function _instructions(result, dotenvKey) {
183
+ let uri;
184
+ try {
185
+ uri = new URL(dotenvKey);
186
+ } catch (error) {
187
+ if (error.code === "ERR_INVALID_URL") {
188
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
189
+ err.code = "INVALID_DOTENV_KEY";
190
+ throw err;
191
+ }
192
+ throw error;
193
+ }
194
+ const key = uri.password;
195
+ if (!key) {
196
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
197
+ err.code = "INVALID_DOTENV_KEY";
198
+ throw err;
199
+ }
200
+ const environment = uri.searchParams.get("environment");
201
+ if (!environment) {
202
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
203
+ err.code = "INVALID_DOTENV_KEY";
204
+ throw err;
205
+ }
206
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
207
+ const ciphertext = result.parsed[environmentKey];
208
+ if (!ciphertext) {
209
+ const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
210
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
211
+ throw err;
212
+ }
213
+ return {
214
+ ciphertext,
215
+ key
216
+ };
196
217
  }
197
- async getTasks({ status, order_by, order_direction = "asc" } = {}) {
198
- let builder = this.selectTask();
199
- if (status && status.length > 0) builder = builder.where("status", "in", status);
200
- if (order_by) builder = builder.orderBy(order_by, order_direction);
201
- return (await builder.execute()).map((item) => taskItemSchema.parse(item));
218
+ function _vaultPath(options) {
219
+ let possibleVaultPath = null;
220
+ if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
221
+ for (const filepath of options.path) if (fs$1.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
222
+ } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
223
+ else possibleVaultPath = path$1.resolve(process.cwd(), ".env.vault");
224
+ if (fs$1.existsSync(possibleVaultPath)) return possibleVaultPath;
225
+ return null;
202
226
  }
203
- async listAgentNames() {
204
- return (await this.db.selectFrom("task").select("agent").distinct().execute()).map((item) => item.agent);
227
+ function _resolveHome(envPath) {
228
+ return envPath[0] === "~" ? path$1.join(os.homedir(), envPath.slice(1)) : envPath;
205
229
  }
206
- async updateTask(taskItem) {
207
- const { id, started_at, ended_at, queued_at, ...rest } = taskItem;
208
- await this.db.updateTable("task").set({
209
- started_at,
210
- ended_at,
211
- queued_at,
212
- ...rest
213
- }).where("id", "=", id).where("agent", "=", this.agentName).execute();
230
+ function _configVault(options) {
231
+ const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
232
+ const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
233
+ if (debug || !quiet) _log("Loading env from encrypted .env.vault");
234
+ const parsed = DotenvModule._parseVault(options);
235
+ let processEnv = process.env;
236
+ if (options && options.processEnv != null) processEnv = options.processEnv;
237
+ DotenvModule.populate(processEnv, parsed, options);
238
+ return { parsed };
214
239
  }
215
- async insertTask(taskItem) {
216
- const { started_at, ended_at, queued_at, ...rest } = taskItem;
217
- const { insertId } = await this.db.insertInto("task").values({
218
- agent: this.agentName,
219
- started_at,
220
- ended_at,
221
- queued_at,
222
- ...rest
223
- }).executeTakeFirstOrThrow();
224
- return {
225
- ...taskItem,
226
- id: String(insertId)
240
+ function configDotenv(options) {
241
+ const dotenvPath = path$1.resolve(process.cwd(), ".env");
242
+ let encoding = "utf8";
243
+ let processEnv = process.env;
244
+ if (options && options.processEnv != null) processEnv = options.processEnv;
245
+ let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
246
+ let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
247
+ if (options && options.encoding) encoding = options.encoding;
248
+ else if (debug) _debug("No encoding is specified. UTF-8 is used by default");
249
+ let optionPaths = [dotenvPath];
250
+ if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
251
+ else {
252
+ optionPaths = [];
253
+ for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
254
+ }
255
+ let lastError;
256
+ const parsedAll = {};
257
+ for (const path of optionPaths) try {
258
+ const parsed = DotenvModule.parse(fs$1.readFileSync(path, { encoding }));
259
+ DotenvModule.populate(parsedAll, parsed, options);
260
+ } catch (e) {
261
+ if (debug) _debug(`Failed to load ${path} ${e.message}`);
262
+ lastError = e;
263
+ }
264
+ const populated = DotenvModule.populate(processEnv, parsedAll, options);
265
+ debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
266
+ quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
267
+ if (debug || !quiet) {
268
+ const keysCount = Object.keys(populated).length;
269
+ const shortPaths = [];
270
+ for (const filePath of optionPaths) try {
271
+ const relative = path$1.relative(process.cwd(), filePath);
272
+ shortPaths.push(relative);
273
+ } catch (e) {
274
+ if (debug) _debug(`Failed to load ${filePath} ${e.message}`);
275
+ lastError = e;
276
+ }
277
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`);
278
+ }
279
+ if (lastError) return {
280
+ parsed: parsedAll,
281
+ error: lastError
227
282
  };
283
+ else return { parsed: parsedAll };
228
284
  }
229
- async deleteTask(taskId) {
230
- const result = await this.db.deleteFrom("task").where("id", "=", taskId).where("agent", "=", this.agentName).executeTakeFirst();
231
- return Number(result.numDeletedRows ?? 0) > 0;
285
+ function config(options) {
286
+ if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
287
+ const vaultPath = _vaultPath(options);
288
+ if (!vaultPath) {
289
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
290
+ return DotenvModule.configDotenv(options);
291
+ }
292
+ return DotenvModule._configVault(options);
232
293
  }
233
- };
234
-
235
- //#endregion
236
- //#region ../sdk/src/lib/stream-parser.ts
237
- var StreamResponseParser = class {
238
- options;
239
- constructor(options) {
240
- this.options = options;
294
+ function decrypt(encrypted, keyStr) {
295
+ const key = Buffer.from(keyStr.slice(-64), "hex");
296
+ let ciphertext = Buffer.from(encrypted, "base64");
297
+ const nonce = ciphertext.subarray(0, 12);
298
+ const authTag = ciphertext.subarray(-16);
299
+ ciphertext = ciphertext.subarray(12, -16);
300
+ try {
301
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
302
+ aesgcm.setAuthTag(authTag);
303
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
304
+ } catch (error) {
305
+ const isRange = error instanceof RangeError;
306
+ const invalidKeyLength = error.message === "Invalid key length";
307
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
308
+ if (isRange || invalidKeyLength) {
309
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
310
+ err.code = "INVALID_DOTENV_KEY";
311
+ throw err;
312
+ } else if (decryptionFailed) {
313
+ const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
314
+ err.code = "DECRYPTION_FAILED";
315
+ throw err;
316
+ } else throw error;
317
+ }
241
318
  }
242
- async handleResponse(response, context) {
243
- this.options.validateResponse?.(response);
244
- if (!response.body) throw new Error("Response body is missing");
245
- return this.options.pipe(response.body, Object.freeze({
246
- ...context,
247
- response
248
- }));
319
+ function populate(processEnv, parsed, options = {}) {
320
+ const debug = Boolean(options && options.debug);
321
+ const override = Boolean(options && options.override);
322
+ const populated = {};
323
+ if (typeof parsed !== "object") {
324
+ const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
325
+ err.code = "OBJECT_REQUIRED";
326
+ throw err;
327
+ }
328
+ for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
329
+ if (override === true) {
330
+ processEnv[key] = parsed[key];
331
+ populated[key] = parsed[key];
332
+ }
333
+ if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
334
+ else _debug(`"${key}" is already defined and was NOT overwritten`);
335
+ } else {
336
+ processEnv[key] = parsed[key];
337
+ populated[key] = parsed[key];
338
+ }
339
+ return populated;
249
340
  }
250
- };
251
-
252
- //#endregion
253
- //#region ../sdk/src/lib/validator.ts
254
- const VALIDATOR_SYMBOL = Symbol("validator");
255
- function isValidator(object) {
256
- return typeof object === "object" && object !== null && object[VALIDATOR_SYMBOL] === true && typeof object.parse === "function";
257
- }
341
+ const DotenvModule = {
342
+ configDotenv,
343
+ _configVault,
344
+ _parseVault,
345
+ config,
346
+ decrypt,
347
+ parse,
348
+ populate
349
+ };
350
+ module.exports.configDotenv = DotenvModule.configDotenv;
351
+ module.exports._configVault = DotenvModule._configVault;
352
+ module.exports._parseVault = DotenvModule._parseVault;
353
+ module.exports.config = DotenvModule.config;
354
+ module.exports.decrypt = DotenvModule.decrypt;
355
+ module.exports.parse = DotenvModule.parse;
356
+ module.exports.populate = DotenvModule.populate;
357
+ module.exports = DotenvModule;
358
+ }));
258
359
 
259
360
  //#endregion
260
- //#region ../../node_modules/url-template/lib/url-template.js
261
- function encodeReserved(str) {
262
- return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
263
- if (!/%[0-9A-Fa-f]/.test(part)) part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
264
- return part;
265
- }).join("");
266
- }
267
- function encodeUnreserved(str) {
268
- return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
269
- return "%" + c.charCodeAt(0).toString(16).toUpperCase();
270
- });
271
- }
272
- function encodeValue(operator, value, key) {
273
- value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
274
- if (key) return encodeUnreserved(key) + "=" + value;
275
- else return value;
276
- }
277
- function isDefined(value) {
278
- return value !== void 0 && value !== null;
279
- }
280
- function isKeyOperator(operator) {
281
- return operator === ";" || operator === "&" || operator === "?";
282
- }
283
- function getValues(context, operator, key, modifier) {
284
- var value = context[key], result = [];
285
- if (isDefined(value) && value !== "") if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
286
- value = value.toString();
287
- if (modifier && modifier !== "*") value = value.substring(0, parseInt(modifier, 10));
288
- result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
289
- } else if (modifier === "*") if (Array.isArray(value)) value.filter(isDefined).forEach(function(value) {
290
- result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
291
- });
292
- else Object.keys(value).forEach(function(k) {
293
- if (isDefined(value[k])) result.push(encodeValue(operator, value[k], k));
294
- });
295
- else {
296
- var tmp = [];
297
- if (Array.isArray(value)) value.filter(isDefined).forEach(function(value) {
298
- tmp.push(encodeValue(operator, value));
299
- });
300
- else Object.keys(value).forEach(function(k) {
301
- if (isDefined(value[k])) {
302
- tmp.push(encodeUnreserved(k));
303
- tmp.push(encodeValue(operator, value[k].toString()));
304
- }
305
- });
306
- if (isKeyOperator(operator)) result.push(encodeUnreserved(key) + "=" + tmp.join(","));
307
- else if (tmp.length !== 0) result.push(tmp.join(","));
308
- }
309
- else if (operator === ";") {
310
- if (isDefined(value)) result.push(encodeUnreserved(key));
311
- } else if (value === "" && (operator === "&" || operator === "?")) result.push(encodeUnreserved(key) + "=");
312
- else if (value === "") result.push("");
313
- return result;
314
- }
315
- function parseTemplate(template) {
316
- var operators = [
317
- "+",
318
- "#",
319
- ".",
320
- "/",
321
- ";",
322
- "?",
323
- "&"
324
- ];
325
- return { expand: function(context) {
326
- return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) {
327
- if (expression) {
328
- var operator = null, values = [];
329
- if (operators.indexOf(expression.charAt(0)) !== -1) {
330
- operator = expression.charAt(0);
331
- expression = expression.substr(1);
332
- }
333
- expression.split(/,/g).forEach(function(variable) {
334
- var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
335
- values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
336
- });
337
- if (operator && operator !== "+") {
338
- var separator = ",";
339
- if (operator === "?") separator = "&";
340
- else if (operator !== "#") separator = operator;
341
- return (values.length !== 0 ? operator : "") + values.join(separator);
342
- } else return values.join(",");
343
- } else return encodeReserved(literal);
344
- });
345
- } };
346
- }
361
+ //#region ../../node_modules/dotenv/lib/env-options.js
362
+ var require_env_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
363
+ const options = {};
364
+ if (process.env.DOTENV_CONFIG_ENCODING != null) options.encoding = process.env.DOTENV_CONFIG_ENCODING;
365
+ if (process.env.DOTENV_CONFIG_PATH != null) options.path = process.env.DOTENV_CONFIG_PATH;
366
+ if (process.env.DOTENV_CONFIG_QUIET != null) options.quiet = process.env.DOTENV_CONFIG_QUIET;
367
+ if (process.env.DOTENV_CONFIG_DEBUG != null) options.debug = process.env.DOTENV_CONFIG_DEBUG;
368
+ if (process.env.DOTENV_CONFIG_OVERRIDE != null) options.override = process.env.DOTENV_CONFIG_OVERRIDE;
369
+ if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
370
+ module.exports = options;
371
+ }));
347
372
 
348
373
  //#endregion
349
- //#region ../sdk/src/lib/api.ts
350
- function typeOf() {
351
- return null;
352
- }
353
- function createUrlTemplate(method) {
354
- return function(arr, ...params) {
355
- let url = arr[0];
356
- let expandedPaths = false;
357
- for (let i = 1; i < arr.length; i++) if (params[i - 1] === "path*") {
358
- url += "<path*>";
359
- expandedPaths = true;
360
- } else url += "{" + params[i - 1].replace(/\?$/, "") + "}" + arr[i];
361
- const [pathPart, searchPart] = url.split("?");
362
- const pathPartTemplate = expandedPaths ? { expand: (context) => {
363
- return parseTemplate(pathPart.replace(/<path\*>/, String(context["path*"]).replace(/^\//, ""))).expand(context);
364
- } } : parseTemplate(pathPart);
365
- const searchParamsBuilders = [];
366
- if (searchPart) searchPart.split("&").forEach((entry) => {
367
- const [key, value = ""] = entry.split("=").map(decodeURIComponent);
368
- if (/^\{[^}]+}$/.test(value)) {
369
- const templateValue = value.slice(1, -1);
370
- searchParamsBuilders.push((usp, context) => {
371
- if (templateValue in context) {
372
- const value = context[templateValue];
373
- if (value === void 0) return;
374
- if (Array.isArray(value)) value.forEach((v) => usp.append(key, String(v)));
375
- else usp.append(key, String(value));
376
- }
377
- });
378
- } else if (value !== "") {
379
- const template = parseTemplate(value);
380
- searchParamsBuilders.push((usp, context) => {
381
- usp.append(key, template.expand(context));
382
- });
383
- } else searchParamsBuilders.push((usp) => {
384
- usp.append(key, "");
385
- });
386
- });
387
- return {
388
- method,
389
- signature: `${method} ${url}`,
390
- templateUrl: url,
391
- template: { expand: (context) => {
392
- const pathPart = pathPartTemplate.expand(context);
393
- const usp = new URLSearchParams();
394
- searchParamsBuilders.forEach((template) => {
395
- template(usp, context);
396
- });
397
- if (Array.from(usp).length > 0) return pathPart + "?" + usp.toString();
398
- else return pathPart;
399
- } },
400
- __params__: typeOf()
401
- };
402
- };
403
- }
404
- const get = createUrlTemplate("get");
405
- const post = createUrlTemplate("post");
406
- const put = createUrlTemplate("put");
407
- const del = createUrlTemplate("delete");
408
- const patch = createUrlTemplate("patch");
409
- function defineApi(urlTemplate, _type, responseSchema) {
410
- const method = urlTemplate.method;
411
- return {
412
- method: urlTemplate.method,
413
- signature: urlTemplate.signature,
414
- url: ((params) => urlTemplate.template.expand(params ?? {})),
415
- requestInit: (body) => {
416
- if (method === "get" || method === "delete") return { method };
417
- if (body instanceof ReadableStream) return {
418
- method,
419
- body,
420
- duplex: "half"
421
- };
422
- else if (body instanceof FormData) return {
423
- method,
424
- body
425
- };
426
- else return {
427
- method,
428
- body: JSON.stringify(body),
429
- headers: { "Content-Type": "application/json" }
430
- };
431
- },
432
- handleResponse: async (response, context) => {
433
- if (responseSchema instanceof StreamResponseParser) return responseSchema.handleResponse(response, context);
434
- else if (responseSchema === "text") return await response.text();
435
- else if (responseSchema === "raw") return response;
436
- else if (isValidator(responseSchema)) return responseSchema.parse(response);
437
- else return responseSchema.parse(await response.json());
438
- }
374
+ //#region ../../node_modules/dotenv/lib/cli-options.js
375
+ var require_cli_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
376
+ const re = /^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;
377
+ module.exports = function optionMatcher(args) {
378
+ const options = args.reduce(function(acc, cur) {
379
+ const matches = cur.match(re);
380
+ if (matches) acc[matches[1]] = matches[2];
381
+ return acc;
382
+ }, {});
383
+ if (!("quiet" in options)) options.quiet = "true";
384
+ return options;
439
385
  };
440
- }
386
+ }));
441
387
 
442
388
  //#endregion
443
- //#region ../sdk/src/lib/zod.ts
444
- var ZodStream = class extends TransformStream {
445
- constructor({ schema, onParseFailed }) {
446
- super({ async transform(chunk, controller) {
447
- const result = await schema.safeParseAsync(chunk);
448
- if (result.success) controller.enqueue(result.data);
449
- else if (onParseFailed) onParseFailed(result.error, chunk, controller);
450
- else controller.error(result.error);
451
- } });
452
- }
453
- };
454
- const zodJsonDate = z.coerce.date();
389
+ //#region ../../node_modules/dotenv/config.js
390
+ (function() {
391
+ require_main().config(Object.assign({}, require_env_options(), require_cli_options()(process.argv)));
392
+ })();
455
393
 
456
394
  //#endregion
457
- //#region ../sdk/src/schemas/branch.ts
458
- const branchManifestArtifactSchema = z.object({
459
- type: z.string(),
460
- path: z.string(),
461
- description: z.string()
462
- });
463
- const branchManifestSchema = z.object({
464
- summary: z.string().optional(),
465
- export: z.object({
466
- include_patterns: z.string().array(),
467
- exclude_patterns: z.string().array()
468
- }).optional(),
469
- artifacts: branchManifestArtifactSchema.array().optional()
470
- });
471
- const snapSchema = z.object({
472
- snap_id: z.string(),
473
- snap_status: z.string(),
474
- snap_type: z.string(),
475
- started_at: zodJsonDate,
476
- finished_at: zodJsonDate,
477
- exit_code: z.number().nullable(),
478
- error: z.string().nullable(),
479
- step_index: z.number(),
480
- event_stream_id: z.string().nullable(),
481
- tool_use_id: z.string().nullable(),
482
- manifest_status: z.string().nullable(),
483
- manifest_task_id: z.string().nullable(),
484
- manifest_snap_id: z.string().nullable()
485
- });
486
- const snapDetailsSchema = snapSchema.extend({
487
- output: z.string().nullable(),
488
- command: z.string().array().nullable().optional()
489
- });
490
- const branchStatusSchema = z.enum([
491
- "created",
492
- "pending",
493
- "running",
494
- "ready_for_manifest",
495
- "manifesting",
496
- "succeed",
497
- "failed"
498
- ]);
499
- const branchSchema = z.object({
500
- id: z.string(),
501
- name: z.string(),
502
- display_name: z.string(),
503
- status: branchStatusSchema,
504
- status_text: z.string().nullable(),
505
- level: z.number(),
506
- project_id: z.string(),
507
- parent_id: z.string().nullable(),
508
- created_at: zodJsonDate,
509
- updated_at: zodJsonDate,
510
- latest_snap_id: z.string().nullable(),
511
- latest_snap: snapSchema.nullable(),
512
- manifest: branchManifestSchema.nullable()
513
- });
514
- const branchSnapsSchema = z.object({
515
- branch_id: z.string(),
516
- branch_name: z.string(),
517
- branch_status: branchStatusSchema,
518
- branch_status_text: z.string().nullable(),
519
- steps: z.array(snapDetailsSchema),
520
- steps_total: z.number()
521
- });
522
- const branchExecutionResultSchema = z.object({
523
- execution_id: z.string(),
524
- status: z.string(),
525
- status_text: z.string(),
526
- branch_id: z.string(),
527
- snap_id: z.string(),
528
- background_task_id: z.string().nullable(),
529
- started_at: zodJsonDate,
530
- last_polled_at: zodJsonDate,
531
- ended_at: zodJsonDate.nullable(),
532
- exit_code: z.number().nullable()
533
- });
395
+ //#region package.json
396
+ var version = "0.0.7";
534
397
 
535
398
  //#endregion
536
- //#region ../sdk/src/schemas/common.ts
537
- function paged(schema) {
538
- return z.object({
539
- items: z.array(schema),
540
- total: z.number(),
541
- page: z.number(),
542
- size: z.number(),
543
- pages: z.number()
544
- });
545
- }
399
+ //#region src/schemas/task-list.ts
400
+ const taskItemSchema = z.discriminatedUnion("status", [
401
+ z.object({
402
+ status: z.literal("pending"),
403
+ id: z.string(),
404
+ task: z.string(),
405
+ project_id: z.uuid(),
406
+ base_branch_id: z.uuid(),
407
+ queued_at: z.coerce.date()
408
+ }),
409
+ z.object({
410
+ status: z.literal("running"),
411
+ id: z.string(),
412
+ task: z.string(),
413
+ project_id: z.uuid(),
414
+ base_branch_id: z.uuid(),
415
+ branch_id: z.uuid(),
416
+ queued_at: z.coerce.date(),
417
+ started_at: z.coerce.date()
418
+ }),
419
+ z.object({
420
+ status: z.literal("completed"),
421
+ id: z.string(),
422
+ task: z.string(),
423
+ project_id: z.uuid(),
424
+ base_branch_id: z.uuid(),
425
+ branch_id: z.uuid(),
426
+ queued_at: z.coerce.date(),
427
+ started_at: z.coerce.date(),
428
+ ended_at: z.coerce.date(),
429
+ output: z.string()
430
+ }),
431
+ z.object({
432
+ status: z.literal("failed"),
433
+ id: z.string(),
434
+ task: z.string(),
435
+ project_id: z.uuid(),
436
+ base_branch_id: z.uuid(),
437
+ branch_id: z.uuid().nullable().optional(),
438
+ queued_at: z.coerce.date(),
439
+ started_at: z.coerce.date().nullable().optional(),
440
+ ended_at: z.coerce.date().nullable().optional(),
441
+ error: z.string()
442
+ }),
443
+ z.object({
444
+ status: z.literal("cancelled"),
445
+ id: z.string(),
446
+ task: z.string(),
447
+ project_id: z.uuid(),
448
+ queued_at: z.coerce.date(),
449
+ cancelled_at: z.coerce.date()
450
+ })
451
+ ]);
546
452
 
547
453
  //#endregion
548
- //#region ../sdk/src/schemas/exploration.ts
549
- const createExplorationResultSchema = z.object({
550
- id: z.string(),
551
- project_id: z.string(),
552
- parent_branch_id: z.string(),
553
- baseline_branch_id: z.string().nullable(),
554
- background_task_id: z.string().nullable(),
555
- status: z.string(),
556
- status_text: z.string().nullable(),
557
- started_at: zodJsonDate.nullable(),
558
- ended_at: zodJsonDate.nullable(),
559
- branches: z.object({
560
- branch_id: z.string(),
561
- branch_name: z.string(),
562
- branch_display_name: z.string(),
563
- latest_snap_id: z.string(),
564
- execution_results: branchExecutionResultSchema.array()
565
- }).array()
566
- });
567
- const explorationSchema = z.object({
568
- id: z.string(),
569
- project_id: z.string(),
570
- parent_branch_id: z.string(),
571
- tdd_baseline_branch_id: z.string().nullable(),
572
- background_task_id: z.string().nullable(),
573
- num_branches: z.number().int(),
574
- shared_prompt_sequence: z.string().array(),
575
- status_text: z.string(),
576
- call_agent: z.string().nullable(),
577
- started_at: zodJsonDate.nullable(),
578
- ended_at: zodJsonDate.nullable(),
579
- created_at: zodJsonDate,
580
- updated_at: zodJsonDate,
581
- agent: z.string(),
582
- status: z.string()
583
- });
584
- const explorationResultSchema = z.object({
585
- id: z.string(),
586
- project_id: z.string(),
587
- parent_branch_id: z.string(),
588
- baseline_branch_id: z.string().nullable(),
589
- background_task_id: z.string().nullable(),
590
- status: z.string(),
591
- status_text: z.string(),
592
- started_at: zodJsonDate,
593
- ended_at: zodJsonDate.nullable(),
594
- branches: z.object({
595
- branch_id: z.string(),
596
- branch_name: z.string(),
597
- branch_display_name: z.string(),
598
- latest_snap_id: z.string(),
599
- execution_results: z.object({
600
- execution_id: z.string(),
601
- status: z.string(),
602
- status_text: z.string(),
603
- branch_id: z.string(),
604
- snap_id: z.string(),
605
- background_task_id: z.string().nullable(),
606
- started_at: zodJsonDate,
607
- last_polled_at: zodJsonDate,
608
- ended_at: zodJsonDate.nullable(),
609
- exit_code: z.number().nullable()
610
- }).array()
611
- }).array()
612
- });
454
+ //#region src/utils/get-error-message.ts
455
+ function getErrorMessage(error) {
456
+ return String(error?.message ?? error);
457
+ }
613
458
 
614
459
  //#endregion
615
- //#region ../sdk/src/schemas/fs.ts
616
- const fsEntrySchema = z.object({
617
- name: z.string(),
618
- is_dir: z.boolean(),
619
- size: z.number(),
620
- mode: z.string(),
621
- mod_time: zodJsonDate
622
- });
623
- const FSResponseValidator = Object.freeze({
624
- [VALIDATOR_SYMBOL]: true,
625
- __phantom__: typeOf(),
626
- async parse(response) {
627
- if (response.headers.get("Content-Type") === "application/json+directory") {
628
- const data = await response.json();
629
- return fsEntrySchema.array().parse(data);
630
- } else {
631
- const blob = await response.blob();
632
- return new File([blob], response.url.split("/").pop(), { type: response.headers.get("content-type") ?? "application/octet-stream" });
460
+ //#region src/providers/task-list-provider.ts
461
+ var TaskListProvider = class {
462
+ logger;
463
+ agentName;
464
+ constructor(agentName, logger) {
465
+ this.agentName = agentName;
466
+ this.logger = logger;
467
+ }
468
+ async createTask(params) {
469
+ return await this.insertTask({
470
+ status: "pending",
471
+ ...params,
472
+ queued_at: /* @__PURE__ */ new Date()
473
+ });
474
+ }
475
+ async startTask({ status, id, ...task }, startTask) {
476
+ const now = /* @__PURE__ */ new Date();
477
+ let updatePromise;
478
+ try {
479
+ this.logger.info(`Starting task ${id}`);
480
+ const branchId = await startTask(task);
481
+ this.logger.info(`Started task ${id} at branch ${branchId}`);
482
+ updatePromise = this.updateTask({
483
+ status: "running",
484
+ id,
485
+ ...task,
486
+ branch_id: branchId,
487
+ started_at: now
488
+ });
489
+ } catch (e) {
490
+ this.logger.error("Failed to start task: %s", getErrorMessage(e));
491
+ updatePromise = this.updateTask({
492
+ status: "failed",
493
+ id,
494
+ ...task,
495
+ started_at: now,
496
+ ended_at: /* @__PURE__ */ new Date(),
497
+ error: getErrorMessage(e)
498
+ }).then(() => Promise.reject(e));
633
499
  }
500
+ await updatePromise;
501
+ }
502
+ async failTask(task, error) {
503
+ if (task.status !== "running") {
504
+ this.logger.error(`Can't fail a task that is not running. [task = ${task.id}, status = ${task.status}]`);
505
+ throw new Error("Can't fail a task that is not running");
506
+ }
507
+ await this.updateTask({
508
+ ...task,
509
+ status: "failed",
510
+ ended_at: /* @__PURE__ */ new Date(),
511
+ error
512
+ });
513
+ }
514
+ async completeTask(task, output) {
515
+ if (task.status !== "running") {
516
+ this.logger.error(`Can't complete a task that is not running. [task = ${task.id}, status = ${task.status}]`);
517
+ throw new Error("Can't complete a task that is not running");
518
+ }
519
+ await this.updateTask({
520
+ ...task,
521
+ status: "completed",
522
+ ended_at: /* @__PURE__ */ new Date(),
523
+ output
524
+ });
525
+ }
526
+ async cancelTask(task) {
527
+ if (task.status !== "pending") {
528
+ this.logger.error(`Can't cancel a task that is not pending. [task = ${task.id}, status = ${task.status}]`);
529
+ throw new Error("Can't cancel a task that is not pending");
530
+ }
531
+ await this.updateTask({
532
+ ...task,
533
+ status: "cancelled",
534
+ cancelled_at: /* @__PURE__ */ new Date()
535
+ });
634
536
  }
635
- });
636
-
637
- //#endregion
638
- //#region ../sdk/src/schemas/ai.ts
639
- const providerMetadataSchema = z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.any()));
640
- const messageMetadataSchema = z$1.object().loose();
641
- const toolsShapeMap = { fake: {
642
- input: z$1.object({ fakeIn: z$1.string() }).loose(),
643
- output: z$1.object({ fakeOut: z$1.string() }).loose()
644
- } };
645
- const dataTypes = {
646
- delta: z$1.object().loose(),
647
- "message-metadata": z$1.object().loose(),
648
- "ui-collapsed": z$1.object({
649
- toolParts: z$1.number(),
650
- reasoningParts: z$1.number(),
651
- collapsed: z$1.boolean(),
652
- parts: z$1.object().loose().array()
653
- }),
654
- "ui-running-tools": z$1.object({
655
- toolParts: z$1.object().loose().array(),
656
- textParts: z$1.object().loose().array(),
657
- reasoningParts: z$1.object().loose().array()
658
- })
659
537
  };
660
- const chunksShapeMap = {
661
- "text-start": {
662
- id: z$1.string(),
663
- providerMetadata: providerMetadataSchema.optional()
664
- },
665
- "text-delta": {
666
- delta: z$1.string(),
667
- id: z$1.string(),
668
- providerMetadata: providerMetadataSchema.optional()
669
- },
670
- "text-end": {
671
- id: z$1.string(),
672
- providerMetadata: providerMetadataSchema.optional()
673
- },
674
- "reasoning-start": {
675
- id: z$1.string(),
676
- providerMetadata: providerMetadataSchema.optional()
677
- },
678
- "reasoning-delta": {
679
- delta: z$1.string(),
680
- id: z$1.string(),
681
- providerMetadata: providerMetadataSchema.optional()
682
- },
683
- "reasoning-end": {
684
- id: z$1.string(),
685
- providerMetadata: providerMetadataSchema.optional()
686
- },
687
- error: { errorText: z$1.string() },
688
- "tool-input-available": {
689
- toolCallId: z$1.string(),
690
- toolName: z$1.string(),
691
- input: z$1.unknown(),
692
- providerExecuted: z$1.boolean().optional(),
693
- providerMetadata: providerMetadataSchema.optional(),
694
- dynamic: z$1.boolean().optional()
695
- },
696
- "tool-input-error": {
697
- toolCallId: z$1.string(),
698
- toolName: z$1.string(),
699
- input: z$1.unknown(),
700
- providerExecuted: z$1.boolean().optional(),
701
- providerMetadata: providerMetadataSchema.optional(),
702
- dynamic: z$1.boolean().optional(),
703
- errorText: z$1.string()
704
- },
705
- "tool-output-available": {
706
- toolCallId: z$1.string(),
707
- output: z$1.unknown(),
708
- providerExecuted: z$1.boolean().optional(),
709
- dynamic: z$1.boolean().optional(),
710
- preliminary: z$1.boolean().optional()
711
- },
712
- "tool-output-error": {
713
- toolCallId: z$1.string(),
714
- providerExecuted: z$1.boolean().optional(),
715
- dynamic: z$1.boolean().optional(),
716
- errorText: z$1.string()
717
- },
718
- "tool-input-start": {
719
- toolCallId: z$1.string(),
720
- toolName: z$1.string(),
721
- providerExecuted: z$1.boolean().optional(),
722
- dynamic: z$1.boolean().optional()
723
- },
724
- "tool-input-delta": {
725
- toolCallId: z$1.string(),
726
- inputTextDelta: z$1.string()
727
- },
728
- "source-url": {
729
- sourceId: z$1.string(),
730
- url: z$1.string(),
731
- title: z$1.string().optional(),
732
- providerMetadata: providerMetadataSchema.optional()
733
- },
734
- "source-document": {
735
- sourceId: z$1.string(),
736
- mediaType: z$1.string(),
737
- title: z$1.string(),
738
- filename: z$1.string().optional(),
739
- providerMetadata: providerMetadataSchema.optional()
740
- },
741
- file: {
742
- url: z$1.string(),
743
- mediaType: z$1.string()
744
- },
745
- "start-step": {},
746
- "finish-step": {},
747
- start: {
748
- messageId: z$1.string().optional(),
749
- messageMetadata: messageMetadataSchema.optional()
750
- },
751
- finish: { messageMetadata: messageMetadataSchema.optional() },
752
- abort: {},
753
- "message-metadata": { messageMetadata: messageMetadataSchema }
538
+
539
+ //#endregion
540
+ //#region src/providers/task-list-tidb-provider.ts
541
+ var TaskListTidbProvider = class extends TaskListProvider {
542
+ db;
543
+ constructor(agentName, logger) {
544
+ super(agentName, logger);
545
+ this.db = new Kysely({ dialect: new MysqlDialect({ pool: createPool({
546
+ uri: process.env.DATABASE_URL,
547
+ supportBigNumbers: true,
548
+ bigNumberStrings: true
549
+ }) }) });
550
+ }
551
+ async close() {
552
+ await this.db.destroy();
553
+ }
554
+ selectTask() {
555
+ return this.db.selectFrom("task").selectAll().where("agent", "=", this.agentName);
556
+ }
557
+ async getAgentConfig(projectId) {
558
+ const config = await this.db.selectFrom("agent_project_config").selectAll().where("project_id", "=", projectId).where("agent", "=", this.agentName).executeTakeFirst();
559
+ if (config == null) return null;
560
+ return config;
561
+ }
562
+ async getAgentConfigs() {
563
+ return await this.db.selectFrom("agent_project_config").selectAll().where("agent", "=", this.agentName).execute();
564
+ }
565
+ async setAgentConfig({ skills, ...config }) {
566
+ await this.db.insertInto("agent_project_config").values({
567
+ agent: this.agentName,
568
+ skills: JSON.stringify(skills),
569
+ ...config
570
+ }).execute();
571
+ }
572
+ async getTask(taskId) {
573
+ const taskItem = await this.selectTask().where("id", "=", taskId).executeTakeFirst();
574
+ if (taskItem == null) return null;
575
+ return taskItemSchema.parse(taskItem);
576
+ }
577
+ async getTasks({ status, order_by, order_direction = "asc" } = {}) {
578
+ let builder = this.selectTask();
579
+ if (status && status.length > 0) builder = builder.where("status", "in", status);
580
+ if (order_by) builder = builder.orderBy(order_by, order_direction);
581
+ return (await builder.execute()).map((item) => taskItemSchema.parse(item));
582
+ }
583
+ async listAgentNames() {
584
+ return (await this.db.selectFrom("task").select("agent").distinct().execute()).map((item) => item.agent);
585
+ }
586
+ async updateTask(taskItem) {
587
+ const { id, started_at, ended_at, queued_at, ...rest } = taskItem;
588
+ await this.db.updateTable("task").set({
589
+ started_at,
590
+ ended_at,
591
+ queued_at,
592
+ ...rest
593
+ }).where("id", "=", id).where("agent", "=", this.agentName).execute();
594
+ }
595
+ async insertTask(taskItem) {
596
+ const { started_at, ended_at, queued_at, ...rest } = taskItem;
597
+ const { insertId } = await this.db.insertInto("task").values({
598
+ agent: this.agentName,
599
+ started_at,
600
+ ended_at,
601
+ queued_at,
602
+ ...rest
603
+ }).executeTakeFirstOrThrow();
604
+ return {
605
+ ...taskItem,
606
+ id: String(insertId)
607
+ };
608
+ }
609
+ async deleteTask(taskId) {
610
+ const result = await this.db.deleteFrom("task").where("id", "=", taskId).where("agent", "=", this.agentName).executeTakeFirst();
611
+ return Number(result.numDeletedRows ?? 0) > 0;
612
+ }
754
613
  };
755
- const unknownDataChunkSchema = z$1.object({
756
- type: z$1.string().regex(/^data-/),
757
- id: z$1.string().optional(),
758
- data: z$1.unknown(),
759
- transient: z$1.boolean().optional()
760
- });
761
- const dataChunkSchema = Object.entries(dataTypes).map(([name, schema]) => z$1.object({
762
- type: z$1.literal(`data-${name}`),
763
- id: z$1.string().optional(),
764
- data: schema,
765
- transient: z$1.boolean().optional()
766
- }));
767
- const chunkSchema = Object.entries(chunksShapeMap).map(([type, schema]) => z$1.object({
768
- type: z$1.literal(type),
769
- ...schema
770
- }));
771
- const uiMessageChunkSchema = z$1.discriminatedUnion("type", [...chunkSchema, ...dataChunkSchema]);
772
- const partsShapeMap = {
773
- text: {
774
- text: z$1.string(),
775
- state: z$1.enum(["streaming", "done"]).optional(),
776
- providerMetadata: providerMetadataSchema.optional()
777
- },
778
- reasoning: {
779
- text: z$1.string(),
780
- state: z$1.enum(["streaming", "done"]).optional(),
781
- providerMetadata: providerMetadataSchema.optional()
782
- },
783
- "source-url": {
784
- sourceId: z$1.string(),
785
- url: z$1.string(),
786
- title: z$1.string().optional(),
787
- providerMetadata: providerMetadataSchema.optional()
788
- },
789
- "source-document": {
790
- sourceId: z$1.string(),
791
- mediaType: z$1.string(),
792
- title: z$1.string(),
793
- filename: z$1.string().optional(),
794
- providerMetadata: providerMetadataSchema.optional()
795
- },
796
- file: {
797
- url: z$1.string(),
798
- mediaType: z$1.string(),
799
- filename: z$1.string().optional(),
800
- providerMetadata: providerMetadataSchema.optional()
801
- },
802
- "step-start": {}
614
+
615
+ //#endregion
616
+ //#region ../sdk/src/lib/stream-parser.ts
617
+ var StreamResponseParser = class {
618
+ options;
619
+ constructor(options) {
620
+ this.options = options;
621
+ }
622
+ async handleResponse(response, context) {
623
+ this.options.validateResponse?.(response);
624
+ if (!response.body) throw new Error("Response body is missing");
625
+ return this.options.pipe(response.body, Object.freeze({
626
+ ...context,
627
+ response
628
+ }));
629
+ }
803
630
  };
804
- const dynamicToolSchema = z$1.discriminatedUnion("state", [
805
- z$1.object({
806
- type: z$1.literal("dynamic-tool"),
807
- toolName: z$1.string(),
808
- toolCallId: z$1.string(),
809
- state: z$1.literal("input-streaming"),
810
- input: z$1.unknown().optional(),
811
- output: z$1.never().optional(),
812
- errorText: z$1.never().optional()
813
- }),
814
- z$1.object({
815
- type: z$1.literal("dynamic-tool"),
816
- toolName: z$1.string(),
817
- toolCallId: z$1.string(),
818
- state: z$1.literal("input-available"),
819
- input: z$1.unknown(),
820
- output: z$1.never().optional(),
821
- errorText: z$1.never().optional(),
822
- callProviderMetadata: providerMetadataSchema.optional()
823
- }),
824
- z$1.object({
825
- type: z$1.literal("dynamic-tool"),
826
- toolName: z$1.string(),
827
- toolCallId: z$1.string(),
828
- state: z$1.literal("output-available"),
829
- input: z$1.unknown(),
830
- output: z$1.unknown(),
831
- errorText: z$1.never().optional(),
832
- callProviderMetadata: providerMetadataSchema.optional(),
833
- preliminary: z$1.boolean().optional()
834
- }),
835
- z$1.object({
836
- type: z$1.literal("dynamic-tool"),
837
- toolName: z$1.string(),
838
- toolCallId: z$1.string(),
839
- state: z$1.literal("output-error"),
840
- input: z$1.unknown(),
841
- output: z$1.never().optional(),
842
- errorText: z$1.string(),
843
- callProviderMetadata: providerMetadataSchema.optional()
844
- })
845
- ]);
846
- const dataPartSchema = Object.entries(dataTypes).map(([name, schema]) => z$1.object({
847
- type: z$1.literal(`data-${name}`),
848
- id: z$1.string().optional(),
849
- data: schema
850
- }));
851
- const notDefinedDataType = z$1.string().regex(/data-/).refine((type) => !Object.keys(dataTypes).includes(type.slice(5)));
852
- const unknownDataPartSchema = z$1.object({
853
- type: notDefinedDataType,
854
- id: z$1.string().optional(),
855
- data: z$1.unknown()
856
- });
857
- const notDefinedToolType = z$1.string().regex(/tool-/).refine((type) => !Object.keys(toolsShapeMap).includes(type.slice(5)));
858
- const unknownToolPartSchema = z$1.discriminatedUnion("state", [
859
- z$1.object({
860
- type: notDefinedToolType,
861
- toolCallId: z$1.string(),
862
- state: z$1.literal("input-streaming"),
863
- input: z$1.unknown().optional(),
864
- output: z$1.never().optional(),
865
- providerExecuted: z$1.boolean().optional(),
866
- errorText: z$1.never().optional()
867
- }),
868
- z$1.object({
869
- type: notDefinedToolType,
870
- toolCallId: z$1.string(),
871
- state: z$1.literal("input-available"),
872
- input: z$1.unknown(),
873
- output: z$1.never().optional(),
874
- providerExecuted: z$1.boolean().optional(),
875
- errorText: z$1.never().optional(),
876
- callProviderMetadata: providerMetadataSchema.optional()
877
- }),
878
- z$1.object({
879
- type: notDefinedToolType,
880
- toolCallId: z$1.string(),
881
- state: z$1.literal("output-available"),
882
- input: z$1.unknown(),
883
- output: z$1.unknown(),
884
- errorText: z$1.never().optional(),
885
- providerExecuted: z$1.boolean().optional(),
886
- callProviderMetadata: providerMetadataSchema.optional(),
887
- preliminary: z$1.boolean().optional()
888
- }),
889
- z$1.object({
890
- type: notDefinedToolType,
891
- toolCallId: z$1.string(),
892
- state: z$1.literal("output-error"),
893
- input: z$1.unknown().optional(),
894
- rawInput: z$1.unknown().optional(),
895
- output: z$1.never().optional(),
896
- errorText: z$1.string(),
897
- providerExecuted: z$1.boolean().optional(),
898
- callProviderMetadata: providerMetadataSchema.optional()
899
- })
900
- ]);
901
- const partSchema = Object.entries(partsShapeMap).map(([type, schema]) => z$1.object({
902
- type: z$1.literal(type),
903
- ...schema
904
- }));
905
- const toolsPartSchema = Object.entries(toolsShapeMap).map(([type, schema]) => z$1.discriminatedUnion("state", [
906
- z$1.object({
907
- type: z$1.literal(`tool-${type}`),
908
- toolCallId: z$1.string(),
909
- state: z$1.literal("input-streaming"),
910
- input: schema.input.partial().optional(),
911
- output: z$1.never().optional(),
912
- providerExecuted: z$1.boolean().optional(),
913
- errorText: z$1.never().optional()
914
- }),
915
- z$1.object({
916
- type: z$1.literal(`tool-${type}`),
917
- toolCallId: z$1.string(),
918
- state: z$1.literal("input-available"),
919
- input: schema.input,
920
- output: z$1.never().optional(),
921
- providerExecuted: z$1.boolean().optional(),
922
- errorText: z$1.never().optional(),
923
- callProviderMetadata: providerMetadataSchema.optional()
924
- }),
925
- z$1.object({
926
- type: z$1.literal(`tool-${type}`),
927
- toolCallId: z$1.string(),
928
- state: z$1.literal("output-available"),
929
- input: schema.input,
930
- output: schema.output,
931
- errorText: z$1.never().optional(),
932
- providerExecuted: z$1.boolean().optional(),
933
- callProviderMetadata: providerMetadataSchema.optional(),
934
- preliminary: z$1.boolean().optional()
935
- }),
936
- z$1.object({
937
- type: z$1.literal(`tool-${type}`),
938
- toolCallId: z$1.string(),
939
- state: z$1.literal("output-error"),
940
- input: schema.input.optional(),
941
- rawInput: z$1.unknown().optional(),
942
- output: z$1.never().optional(),
943
- errorText: z$1.string(),
944
- providerExecuted: z$1.boolean().optional(),
945
- callProviderMetadata: providerMetadataSchema.optional()
946
- })
947
- ]));
948
- const uiMessagePartSchema = z$1.discriminatedUnion("type", [
949
- ...partSchema,
950
- ...toolsPartSchema,
951
- ...dataPartSchema,
952
- dynamicToolSchema
953
- ]);
954
631
 
955
632
  //#endregion
956
- //#region ../sdk/src/schemas/project.ts
957
- const projectMetaGitHubSchema = z.object({
958
- repo_owner_login: z.string().optional(),
959
- repo_name: z.string().optional(),
960
- issue_type: z.string().optional(),
961
- issue_number: z.number().optional()
962
- }).optional();
963
- const projectMetaSchema = z.object({ github: projectMetaGitHubSchema }).optional().nullable();
964
- const projectSchema = z.object({
965
- id: z.string(),
966
- name: z.string(),
967
- display_name: z.string(),
968
- category: z.string(),
969
- description: z.string(),
970
- user_id: z.string().nullable(),
971
- owner_email: z.string().nullable().optional(),
972
- root_branch_id: z.string().nullable(),
973
- ongoing_stream_id: z.string().nullable(),
974
- status: z.enum([
975
- "CREATED",
976
- "PROVISIONING",
977
- "READY",
978
- "RUNNING",
979
- "PAUSED",
980
- "FAILED",
981
- "ARCHIVED"
982
- ]).nullable().optional(),
983
- error_message: z.string().nullable().optional(),
984
- meta: projectMetaSchema,
985
- github_source_owner_id: z.number().nullable().optional(),
986
- github_source_repo_id: z.number().nullable().optional(),
987
- github_source_number: z.number().nullable().optional(),
988
- created_at: zodJsonDate,
989
- updated_at: zodJsonDate,
990
- branches_total: z.number().int().nullable().optional(),
991
- background_tasks_total: z.number().int().nullable().optional()
992
- });
993
- const projectMessageSchema = z.object({
994
- id: z.string(),
995
- role: z.enum([
996
- "system",
997
- "user",
998
- "assistant"
999
- ]),
1000
- metadata: messageMetadataSchema.nullable().optional(),
1001
- parts: z.array(z.object().loose()),
1002
- ordinal: z.number(),
1003
- project_id: z.string(),
1004
- user_id: z.string().nullable(),
1005
- source_request_id: z.string().nullable().optional(),
1006
- event_stream_id: z.string().nullable(),
1007
- status: z.string().nullable(),
1008
- is_finished: z.boolean(),
1009
- created_at: zodJsonDate,
1010
- updated_at: zodJsonDate
1011
- });
1012
- const projectMessageStreamParser = new StreamResponseParser({ pipe: (input) => {
1013
- return input.pipeThrough(new TextDecoderStream()).pipeThrough(new BufferedLinesStream("\n\n")).pipeThrough(new SSEDataDecoderStream()).pipeThrough(new ZodStream({ schema: z.object().loose() }));
1014
- } });
1015
- const projectRawMessageStreamParser = new StreamResponseParser({ pipe: (input) => {
1016
- return input.pipeThrough(new TextDecoderStream()).pipeThrough(new BufferedLinesStream("\n\n")).pipeThrough(new SSEDataDecoderStream()).pipeThrough(new ZodStream({ schema: z.object().loose() }));
1017
- } });
1018
- const projectQueuedRequestSchema = z.object({
1019
- id: z.string(),
1020
- type: z.string(),
1021
- payload: z.unknown(),
1022
- requested_at: zodJsonDate,
1023
- summary: z.string()
1024
- });
1025
- const projectBackgroundTaskSchema = z.object({
1026
- task_id: z.string(),
1027
- name: z.string().nullable(),
1028
- action_type: z.enum(["execution", "exploration"]),
1029
- action_id: z.string(),
1030
- status: z.enum([
1031
- "SUCCESS",
1032
- "FAILURE",
1033
- "PENDING",
1034
- "STARTED"
1035
- ]).nullable(),
1036
- result: z.object().loose().nullable(),
1037
- retries: z.number().nullable(),
1038
- started_at: zodJsonDate.nullable(),
1039
- last_polled_at: zodJsonDate.nullable(),
1040
- ended_at: zodJsonDate.nullable()
1041
- });
1042
- var BufferedLinesStream = class extends TransformStream {
1043
- constructor(sep = "\n") {
1044
- let buffer = "";
1045
- super({
1046
- transform(chunk, controller) {
1047
- chunk = buffer += chunk;
1048
- while (true) {
1049
- const index = chunk.indexOf(sep);
1050
- if (index === -1) {
1051
- buffer = chunk;
1052
- break;
1053
- }
1054
- const line = chunk.slice(0, index).trim();
1055
- if (line) controller.enqueue(line);
1056
- chunk = chunk.slice(index + sep.length);
1057
- }
1058
- },
1059
- flush() {
1060
- if (buffer) console.warn("buffered lines stream has unprocessed lines:", buffer);
633
+ //#region ../sdk/src/lib/validator.ts
634
+ const VALIDATOR_SYMBOL = Symbol("validator");
635
+ function isValidator(object) {
636
+ return typeof object === "object" && object !== null && object[VALIDATOR_SYMBOL] === true && typeof object.parse === "function";
637
+ }
638
+
639
+ //#endregion
640
+ //#region ../../node_modules/url-template/lib/url-template.js
641
+ function encodeReserved(str) {
642
+ return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
643
+ if (!/%[0-9A-Fa-f]/.test(part)) part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
644
+ return part;
645
+ }).join("");
646
+ }
647
+ function encodeUnreserved(str) {
648
+ return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
649
+ return "%" + c.charCodeAt(0).toString(16).toUpperCase();
650
+ });
651
+ }
652
+ function encodeValue(operator, value, key) {
653
+ value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
654
+ if (key) return encodeUnreserved(key) + "=" + value;
655
+ else return value;
656
+ }
657
+ function isDefined(value) {
658
+ return value !== void 0 && value !== null;
659
+ }
660
+ function isKeyOperator(operator) {
661
+ return operator === ";" || operator === "&" || operator === "?";
662
+ }
663
+ function getValues(context, operator, key, modifier) {
664
+ var value = context[key], result = [];
665
+ if (isDefined(value) && value !== "") if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
666
+ value = value.toString();
667
+ if (modifier && modifier !== "*") value = value.substring(0, parseInt(modifier, 10));
668
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
669
+ } else if (modifier === "*") if (Array.isArray(value)) value.filter(isDefined).forEach(function(value) {
670
+ result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
671
+ });
672
+ else Object.keys(value).forEach(function(k) {
673
+ if (isDefined(value[k])) result.push(encodeValue(operator, value[k], k));
674
+ });
675
+ else {
676
+ var tmp = [];
677
+ if (Array.isArray(value)) value.filter(isDefined).forEach(function(value) {
678
+ tmp.push(encodeValue(operator, value));
679
+ });
680
+ else Object.keys(value).forEach(function(k) {
681
+ if (isDefined(value[k])) {
682
+ tmp.push(encodeUnreserved(k));
683
+ tmp.push(encodeValue(operator, value[k].toString()));
1061
684
  }
1062
685
  });
686
+ if (isKeyOperator(operator)) result.push(encodeUnreserved(key) + "=" + tmp.join(","));
687
+ else if (tmp.length !== 0) result.push(tmp.join(","));
1063
688
  }
1064
- };
1065
- var SSEDataDecoderStream = class extends TransformStream {
1066
- constructor() {
1067
- let handle = void 0;
1068
- super({ transform: (chunk, controller) => {
1069
- clearTimeout(handle);
1070
- handle = setTimeout(() => {
1071
- controller.error(/* @__PURE__ */ new Error("Read timeout, please retry."));
1072
- }, 15e3);
1073
- if (/^data:/.test(chunk)) {
1074
- const part = chunk.replace(/^data: /, "").trim();
1075
- if (part === "[DONE]") {} else try {
1076
- controller.enqueue(JSON.parse(part));
1077
- } catch (e) {
1078
- console.error("invalid sse chunk", chunk, e);
1079
- controller.error(e);
689
+ else if (operator === ";") {
690
+ if (isDefined(value)) result.push(encodeUnreserved(key));
691
+ } else if (value === "" && (operator === "&" || operator === "?")) result.push(encodeUnreserved(key) + "=");
692
+ else if (value === "") result.push("");
693
+ return result;
694
+ }
695
+ function parseTemplate(template) {
696
+ var operators = [
697
+ "+",
698
+ "#",
699
+ ".",
700
+ "/",
701
+ ";",
702
+ "?",
703
+ "&"
704
+ ];
705
+ return { expand: function(context) {
706
+ return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) {
707
+ if (expression) {
708
+ var operator = null, values = [];
709
+ if (operators.indexOf(expression.charAt(0)) !== -1) {
710
+ operator = expression.charAt(0);
711
+ expression = expression.substr(1);
1080
712
  }
1081
- }
713
+ expression.split(/,/g).forEach(function(variable) {
714
+ var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
715
+ values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
716
+ });
717
+ if (operator && operator !== "+") {
718
+ var separator = ",";
719
+ if (operator === "?") separator = "&";
720
+ else if (operator !== "#") separator = operator;
721
+ return (values.length !== 0 ? operator : "") + values.join(separator);
722
+ } else return values.join(",");
723
+ } else return encodeReserved(literal);
724
+ });
725
+ } };
726
+ }
727
+
728
+ //#endregion
729
+ //#region ../sdk/src/lib/api.ts
730
+ function typeOf() {
731
+ return null;
732
+ }
733
+ function createUrlTemplate(method) {
734
+ return function(arr, ...params) {
735
+ let url = arr[0];
736
+ let expandedPaths = false;
737
+ for (let i = 1; i < arr.length; i++) if (params[i - 1] === "path*") {
738
+ url += "<path*>";
739
+ expandedPaths = true;
740
+ } else url += "{" + params[i - 1].replace(/\?$/, "") + "}" + arr[i];
741
+ const [pathPart, searchPart] = url.split("?");
742
+ const pathPartTemplate = expandedPaths ? { expand: (context) => {
743
+ return parseTemplate(pathPart.replace(/<path\*>/, String(context["path*"]).replace(/^\//, ""))).expand(context);
744
+ } } : parseTemplate(pathPart);
745
+ const searchParamsBuilders = [];
746
+ if (searchPart) searchPart.split("&").forEach((entry) => {
747
+ const [key, value = ""] = entry.split("=").map(decodeURIComponent);
748
+ if (/^\{[^}]+}$/.test(value)) {
749
+ const templateValue = value.slice(1, -1);
750
+ searchParamsBuilders.push((usp, context) => {
751
+ if (templateValue in context) {
752
+ const value = context[templateValue];
753
+ if (value === void 0) return;
754
+ if (Array.isArray(value)) value.forEach((v) => usp.append(key, String(v)));
755
+ else usp.append(key, String(value));
756
+ }
757
+ });
758
+ } else if (value !== "") {
759
+ const template = parseTemplate(value);
760
+ searchParamsBuilders.push((usp, context) => {
761
+ usp.append(key, template.expand(context));
762
+ });
763
+ } else searchParamsBuilders.push((usp) => {
764
+ usp.append(key, "");
765
+ });
766
+ });
767
+ return {
768
+ method,
769
+ signature: `${method} ${url}`,
770
+ templateUrl: url,
771
+ template: { expand: (context) => {
772
+ const pathPart = pathPartTemplate.expand(context);
773
+ const usp = new URLSearchParams();
774
+ searchParamsBuilders.forEach((template) => {
775
+ template(usp, context);
776
+ });
777
+ if (Array.from(usp).length > 0) return pathPart + "?" + usp.toString();
778
+ else return pathPart;
779
+ } },
780
+ __params__: typeOf()
781
+ };
782
+ };
783
+ }
784
+ const get = createUrlTemplate("get");
785
+ const post = createUrlTemplate("post");
786
+ const put = createUrlTemplate("put");
787
+ const del = createUrlTemplate("delete");
788
+ const patch = createUrlTemplate("patch");
789
+ function defineApi(urlTemplate, _type, responseSchema) {
790
+ const method = urlTemplate.method;
791
+ return {
792
+ method: urlTemplate.method,
793
+ signature: urlTemplate.signature,
794
+ url: ((params) => urlTemplate.template.expand(params ?? {})),
795
+ requestInit: (body) => {
796
+ if (method === "get" || method === "delete") return { method };
797
+ if (body instanceof ReadableStream) return {
798
+ method,
799
+ body,
800
+ duplex: "half"
801
+ };
802
+ else if (body instanceof FormData) return {
803
+ method,
804
+ body
805
+ };
806
+ else return {
807
+ method,
808
+ body: JSON.stringify(body),
809
+ headers: { "Content-Type": "application/json" }
810
+ };
811
+ },
812
+ handleResponse: async (response, context) => {
813
+ if (responseSchema instanceof StreamResponseParser) return responseSchema.handleResponse(response, context);
814
+ else if (responseSchema === "text") return await response.text();
815
+ else if (responseSchema === "raw") return response;
816
+ else if (isValidator(responseSchema)) return responseSchema.parse(response);
817
+ else return responseSchema.parse(await response.json());
818
+ }
819
+ };
820
+ }
821
+
822
+ //#endregion
823
+ //#region ../sdk/src/lib/zod.ts
824
+ var ZodStream = class extends TransformStream {
825
+ constructor({ schema, onParseFailed }) {
826
+ super({ async transform(chunk, controller) {
827
+ const result = await schema.safeParseAsync(chunk);
828
+ if (result.success) controller.enqueue(result.data);
829
+ else if (onParseFailed) onParseFailed(result.error, chunk, controller);
830
+ else controller.error(result.error);
1082
831
  } });
1083
832
  }
1084
833
  };
834
+ const zodJsonDate = z.coerce.date();
1085
835
 
1086
836
  //#endregion
1087
- //#region ../sdk/src/api/projects.ts
1088
- const listProjects = defineApi(get`/api/v1/projects?page=${"page"}&size=${"size"}&user_id=${"user_id?"}&category=${"category?"}&github_source_owner_id=${"github_source_owner_id?"}&github_source_repo_id=${"github_source_repo_id?"}`, null, paged(projectSchema));
1089
- const listAdminProjects = defineApi(get`/api/v1/admin/projects?page=${"page"}&size=${"size"}&org_id=${"org_id?"}&user_id=${"user_id?"}&category=${"category?"}&github_source_owner_id=${"github_source_owner_id?"}&github_source_repo_id=${"github_source_repo_id?"}`, null, paged(projectSchema));
1090
- const getProject = defineApi(get`/api/v1/projects/${"projectId"}`, null, projectSchema);
1091
- const transferProject = defineApi(post`/api/v1/projects/${"projectId"}/transfer`, typeOf(), projectSchema);
1092
- const createProject = defineApi(post`/api/v1/projects`, typeOf(), projectSchema);
1093
- const listProjectMessages = defineApi(get`/api/v1/projects/${"projectId"}/messages`, null, z.object({
1094
- messages: projectMessageSchema.array(),
1095
- ongoing_stream_id: z.string().nullable()
1096
- }));
1097
- const deleteProjectMessage = defineApi(del`/api/v1/projects/${"projectId"}/messages/${"messageId"}`, null, "raw");
1098
- const postProjectMessage = defineApi(post`/api/v1/projects/${"projectId"}`, typeOf(), z.object({
1099
- messages: projectMessageSchema.array(),
1100
- ongoing_stream_id: z.string().nullable()
1101
- }));
1102
- const continueProject = defineApi(post`/api/v1/projects/${"projectId"}/continue`, typeOf(), "raw");
1103
- const stopProject = defineApi(post`/api/v1/projects/${"projectId"}/stop`, typeOf(), "raw");
1104
- const getProjectBranch = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}`, null, branchSchema);
1105
- const getProjectBranchOutput = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/output?full_output=${"fullOutput?"}`, null, "text");
1106
- const listProjectBranches = defineApi(get`/api/v1/projects/${"projectId"}/branches?page=${"page"}&size=${"size"}`, null, paged(branchSchema));
1107
- const listProjectBranchSnaps = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/snaps`, null, branchSnapsSchema);
1108
- const listProjectBackgroundTasks = defineApi(get`/api/v1/projects/${"projectId"}/background_tasks?statuses=${"statuses?"}`, null, z.array(projectBackgroundTaskSchema));
1109
- const createProjectExploration = defineApi(post`/api/v1/projects/${"projectId"}/explorations`, typeOf(), createExplorationResultSchema);
1110
- const listProjectExplorations = defineApi(get`/api/v1/projects/${"projectId"}/explorations`, null, explorationSchema.array());
1111
- const getProjectExplorationResult = defineApi(get`/api/v1/projects/${"projectId"}/explorations/${"explorationId"}/result`, null, explorationResultSchema);
1112
- const getProjectBranchFs = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/fs/${"path*"}`, null, FSResponseValidator);
1113
- const getProjectBranchFsPreview = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/preview/${"path*"}`, null, FSResponseValidator);
1114
-
1115
- //#endregion
1116
- //#region ../sdk/src/api/connectors.ts
1117
- const getGithubUser = defineApi(get`/api/v1/connectors/github/user`, null, z.object({ github_username: z.string() }).nullable());
1118
- const disconnectGithub = defineApi(post`/api/v1/connectors/github/disconnect`, null, z.object({ success: z.boolean() }));
1119
- const listGithubRepositories = defineApi(get`/api/v1/user/github/repositories?page=${"page"}&size=${"size"}`, null, paged(z.object({
1120
- repo_id: z.number(),
1121
- repo_name: z.string(),
1122
- public: z.boolean(),
1123
- installation_id: z.number()
1124
- })));
1125
-
1126
- //#endregion
1127
- //#region ../sdk/src/schemas/organizations.ts
1128
- const organizationItemSchema = z.object({
1129
- id: z.string(),
1130
- name: z.string(),
1131
- is_personal: z.boolean(),
1132
- created_at: z.string().nullable(),
1133
- updated_at: z.string().nullable()
1134
- });
1135
- const organizationSchema = organizationItemSchema;
1136
- const organizationDeleteSchema = z.object({ success: z.boolean() });
1137
- const organizationRoleSchema = z.enum(["owner", "member"]);
1138
- const organizationMemberSchema = z.object({
1139
- org_id: z.string(),
1140
- user_id: z.string(),
1141
- email: z.string().nullable().optional(),
1142
- github_username: z.string().nullable().optional(),
1143
- role: organizationRoleSchema,
1144
- created_at: z.string().nullable(),
1145
- updated_at: z.string().nullable()
1146
- });
1147
- const addOrgMemberResponseSchema = z.object({
1148
- member: organizationMemberSchema.nullable().optional(),
1149
- email_sent: z.boolean().nullable().optional(),
1150
- invite_link: z.string().nullable().optional()
1151
- });
1152
- const invitationStatusSchema = z.enum(["pending", "accepted"]);
1153
- const organizationInvitationSchema = z.object({
1154
- id: z.string(),
1155
- org_id: z.string(),
1156
- org_role: organizationRoleSchema,
1157
- email: z.string().nullable(),
1158
- github_username: z.string().nullable(),
1159
- invited_by: z.string(),
1160
- status: invitationStatusSchema,
1161
- created_at: z.string().nullable(),
1162
- updated_at: z.string().nullable()
1163
- });
1164
-
1165
- //#endregion
1166
- //#region ../sdk/src/schemas/github.ts
1167
- const githubAppInstallationSchema = z.object({
1168
- installation_id: z.number(),
1169
- github_account_id: z.number(),
1170
- github_account_login: z.string(),
1171
- github_account_type: z.string(),
1172
- org_id: z.string().nullable()
837
+ //#region ../sdk/src/schemas/branch.ts
838
+ const branchManifestArtifactSchema = z.object({
839
+ type: z.string(),
840
+ path: z.string(),
841
+ description: z.string()
1173
842
  });
1174
- const githubAppInstallationAdminItemSchema = z.object({
1175
- installation_id: z.number(),
1176
- github_account_id: z.number(),
1177
- github_account_login: z.string(),
1178
- github_account_type: z.string(),
1179
- org_id: z.string().nullable(),
1180
- org_name: z.string().nullable(),
1181
- installer_user_id: z.string().nullable(),
1182
- installer_email: z.string().nullable(),
1183
- created_at: z.string().nullable(),
1184
- updated_at: z.string().nullable()
843
+ const branchManifestSchema = z.object({
844
+ summary: z.string().optional(),
845
+ export: z.object({
846
+ include_patterns: z.string().array(),
847
+ exclude_patterns: z.string().array()
848
+ }).optional(),
849
+ artifacts: branchManifestArtifactSchema.array().optional()
1185
850
  });
1186
- const githubRepositorySchema = z.object({
1187
- repo_id: z.number(),
1188
- repo_name: z.string(),
1189
- public: z.boolean(),
1190
- installation_id: z.number(),
1191
- enabled: z.boolean().default(false)
851
+ const snapSchema = z.object({
852
+ snap_id: z.string(),
853
+ snap_status: z.string(),
854
+ snap_type: z.string(),
855
+ started_at: zodJsonDate,
856
+ finished_at: zodJsonDate,
857
+ exit_code: z.number().nullable(),
858
+ error: z.string().nullable(),
859
+ step_index: z.number(),
860
+ event_stream_id: z.string().nullable(),
861
+ tool_use_id: z.string().nullable(),
862
+ manifest_status: z.string().nullable(),
863
+ manifest_task_id: z.string().nullable(),
864
+ manifest_snap_id: z.string().nullable()
1192
865
  });
1193
- const githubAutoReviewConfigSchema = z.object({
1194
- enabled: z.boolean(),
1195
- enable_for_non_linked_users: z.boolean().default(false),
1196
- auto_incremental_review: z.boolean(),
1197
- labels: z.array(z.string()),
1198
- drafts: z.boolean(),
1199
- base_branches: z.array(z.string()),
1200
- ignore_usernames: z.array(z.string())
866
+ const snapDetailsSchema = snapSchema.extend({
867
+ output: z.string().nullable(),
868
+ command: z.string().array().nullable().optional()
1201
869
  });
1202
- const githubRepoSettingsConfigSchema = z.object({
1203
- allow_usernames: z.array(z.string()),
1204
- auto_review: githubAutoReviewConfigSchema
870
+ const branchStatusSchema = z.enum([
871
+ "created",
872
+ "pending",
873
+ "running",
874
+ "ready_for_manifest",
875
+ "manifesting",
876
+ "succeed",
877
+ "failed"
878
+ ]);
879
+ const branchSchema = z.object({
880
+ id: z.string(),
881
+ name: z.string(),
882
+ display_name: z.string(),
883
+ status: branchStatusSchema,
884
+ status_text: z.string().nullable(),
885
+ level: z.number(),
886
+ project_id: z.string(),
887
+ parent_id: z.string().nullable(),
888
+ created_at: zodJsonDate,
889
+ updated_at: zodJsonDate,
890
+ latest_snap_id: z.string().nullable(),
891
+ latest_snap: snapSchema.nullable(),
892
+ manifest: branchManifestSchema.nullable()
1205
893
  });
1206
- const githubRepoSettingsPublicSchema = z.object({
1207
- enabled: z.boolean(),
1208
- config: githubRepoSettingsConfigSchema
894
+ const branchSnapsSchema = z.object({
895
+ branch_id: z.string(),
896
+ branch_name: z.string(),
897
+ branch_status: branchStatusSchema,
898
+ branch_status_text: z.string().nullable(),
899
+ steps: z.array(snapDetailsSchema),
900
+ steps_total: z.number()
1209
901
  });
1210
- const githubRepoSettingsUpdateSchema = z.object({
1211
- enabled: z.boolean().optional(),
1212
- config: githubRepoSettingsConfigSchema.optional()
902
+ const branchExecutionResultSchema = z.object({
903
+ execution_id: z.string(),
904
+ status: z.string(),
905
+ status_text: z.string(),
906
+ branch_id: z.string(),
907
+ snap_id: z.string(),
908
+ background_task_id: z.string().nullable(),
909
+ started_at: zodJsonDate,
910
+ last_polled_at: zodJsonDate,
911
+ ended_at: zodJsonDate.nullable(),
912
+ exit_code: z.number().nullable()
1213
913
  });
1214
914
 
1215
915
  //#endregion
1216
- //#region ../sdk/src/api/organizations.ts
1217
- const listOrganizations = defineApi(get`/api/v1/orgs?page=${"page"}&size=${"size"}`, null, paged(organizationItemSchema));
1218
- const getOrganization = defineApi(get`/api/v1/orgs/${"orgId"}`, null, organizationSchema);
1219
- const createOrganization = defineApi(post`/api/v1/orgs`, typeOf(), organizationSchema);
1220
- const updateOrganization = defineApi(put`/api/v1/orgs/${"orgId"}`, typeOf(), organizationSchema);
1221
- const deleteOrganization = defineApi(del`/api/v1/orgs/${"orgId"}`, null, organizationDeleteSchema);
1222
- const listOrganizationMembers = defineApi(get`/api/v1/orgs/${"orgId"}/members?page=${"page"}&size=${"size"}`, null, paged(organizationMemberSchema));
1223
- const listOrganizationInvitations = defineApi(get`/api/v1/orgs/${"orgId"}/invitations?page=${"page"}&size=${"size"}&status=${"status?"}`, null, paged(organizationInvitationSchema));
1224
- const revokeOrganizationInvitation = defineApi(del`/api/v1/orgs/${"orgId"}/invitations/${"invitationId"}`, null, z.object({ success: z.boolean() }));
1225
- const addOrganizationMember = defineApi(post`/api/v1/orgs/${"orgId"}/members`, typeOf(), addOrgMemberResponseSchema);
1226
- const updateOrganizationMemberRole = defineApi(put`/api/v1/orgs/${"orgId"}/members/${"memberId"}`, typeOf(), organizationMemberSchema);
1227
- const removeOrganizationMember = defineApi(del`/api/v1/orgs/${"orgId"}/members/${"memberId"}`, null, z.object({ success: z.boolean() }));
1228
- const listOrganizationGithubInstallations = defineApi(get`/api/v1/orgs/${"orgId"}/github/installations`, null, z.array(githubAppInstallationSchema));
1229
- const listOrgLinkedAccounts = defineApi(get`/api/v1/orgs/${"orgId"}/github/linked_accounts`, null, z.array(githubAppInstallationSchema));
1230
- const listOrgLinkedRepositories = defineApi(get`/api/v1/orgs/${"orgId"}/github/linked_repositories`, null, z.array(githubRepositorySchema));
1231
- const listOrganizationGithubRepositories = defineApi(get`/api/v1/orgs/${"orgId"}/github/installations/${"installationId"}/repos`, null, z.array(githubRepositorySchema));
1232
- const listOrganizationProjects = defineApi(get`/api/v1/orgs/${"orgId"}/projects?page=${"page"}&size=${"size"}&query=${"query?"}&category=${"category?"}&github_source_owner_id=${"github_source_owner_id?"}&github_source_repo_id=${"github_source_repo_id?"}`, null, paged(projectSchema));
1233
- const createOrganizationProject = defineApi(post`/api/v1/orgs/${"orgId"}/projects`, typeOf(), projectSchema);
1234
- const getOrganizationGithubRepoSettings = defineApi(get`/api/v1/orgs/${"orgId"}/github/installations/${"installationId"}/repos/${"repoId"}/settings`, null, githubRepoSettingsPublicSchema);
1235
- const updateOrganizationGithubRepoSettings = defineApi(put`/api/v1/orgs/${"orgId"}/github/installations/${"installationId"}/repos/${"repoId"}/settings`, typeOf(), githubRepoSettingsPublicSchema);
1236
-
1237
- //#endregion
1238
- //#region ../sdk/src/api/stream-proxy.ts
1239
- const readMessageStream = defineApi(get`/ai_stream_proxy/v2/streams/${"streamId"}/stream?format=vercel-ai-ui-message-stream-v1&skip=${"skip?"}`, null, projectMessageStreamParser);
1240
- const readRawMessageStream = defineApi(get`/ai_stream_proxy/v2/streams/${"streamId"}/stream?format=opaque-stream-json`, null, projectRawMessageStreamParser);
916
+ //#region ../sdk/src/schemas/common.ts
917
+ function paged(schema) {
918
+ return z.object({
919
+ items: z.array(schema),
920
+ total: z.number(),
921
+ page: z.number(),
922
+ size: z.number(),
923
+ pages: z.number()
924
+ });
925
+ }
1241
926
 
1242
927
  //#endregion
1243
- //#region ../sdk/src/schemas/api-key.ts
1244
- const publicApiKeySchema = z.object({
1245
- id: z.union([z.string(), z.number()]).transform(String),
1246
- description: z.string().nullable().optional(),
1247
- api_key_display: z.string(),
928
+ //#region ../sdk/src/schemas/exploration.ts
929
+ const createExplorationResultSchema = z.object({
930
+ id: z.string(),
931
+ project_id: z.string(),
932
+ parent_branch_id: z.string(),
933
+ baseline_branch_id: z.string().nullable(),
934
+ background_task_id: z.string().nullable(),
935
+ status: z.string(),
936
+ status_text: z.string().nullable(),
937
+ started_at: zodJsonDate.nullable(),
938
+ ended_at: zodJsonDate.nullable(),
939
+ branches: z.object({
940
+ branch_id: z.string(),
941
+ branch_name: z.string(),
942
+ branch_display_name: z.string(),
943
+ latest_snap_id: z.string(),
944
+ execution_results: branchExecutionResultSchema.array()
945
+ }).array()
946
+ });
947
+ const explorationSchema = z.object({
948
+ id: z.string(),
949
+ project_id: z.string(),
950
+ parent_branch_id: z.string(),
951
+ tdd_baseline_branch_id: z.string().nullable(),
952
+ background_task_id: z.string().nullable(),
953
+ num_branches: z.number().int(),
954
+ shared_prompt_sequence: z.string().array(),
955
+ status_text: z.string(),
956
+ call_agent: z.string().nullable(),
957
+ started_at: zodJsonDate.nullable(),
958
+ ended_at: zodJsonDate.nullable(),
1248
959
  created_at: zodJsonDate,
1249
- updated_at: zodJsonDate.optional(),
1250
- is_active: z.boolean(),
1251
- user_id: z.string()
960
+ updated_at: zodJsonDate,
961
+ agent: z.string(),
962
+ status: z.string()
963
+ });
964
+ const explorationResultSchema = z.object({
965
+ id: z.string(),
966
+ project_id: z.string(),
967
+ parent_branch_id: z.string(),
968
+ baseline_branch_id: z.string().nullable(),
969
+ background_task_id: z.string().nullable(),
970
+ status: z.string(),
971
+ status_text: z.string(),
972
+ started_at: zodJsonDate,
973
+ ended_at: zodJsonDate.nullable(),
974
+ branches: z.object({
975
+ branch_id: z.string(),
976
+ branch_name: z.string(),
977
+ branch_display_name: z.string(),
978
+ latest_snap_id: z.string(),
979
+ execution_results: z.object({
980
+ execution_id: z.string(),
981
+ status: z.string(),
982
+ status_text: z.string(),
983
+ branch_id: z.string(),
984
+ snap_id: z.string(),
985
+ background_task_id: z.string().nullable(),
986
+ started_at: zodJsonDate,
987
+ last_polled_at: zodJsonDate,
988
+ ended_at: zodJsonDate.nullable(),
989
+ exit_code: z.number().nullable()
990
+ }).array()
991
+ }).array()
1252
992
  });
1253
- const apiKeyCreateRequestSchema = z.object({ description: z.string() });
1254
- const apiKeyCreateResponseSchema = publicApiKeySchema.extend({ api_key: z.string() });
1255
-
1256
- //#endregion
1257
- //#region ../sdk/src/api/user-api-keys.ts
1258
- const listUserApiKeys = defineApi(get`/api/v1/user/api-keys?page=${"page"}&size=${"size"}`, null, paged(publicApiKeySchema));
1259
- const createUserApiKey = defineApi(post`/api/v1/user/api-keys`, typeOf(), apiKeyCreateResponseSchema);
1260
- const deleteUserApiKey = defineApi(del`/api/v1/user/api-keys/${"apiKeyId"}`, null, "raw");
1261
-
1262
- //#endregion
1263
- //#region ../sdk/src/lib/api-executor.ts
1264
- var ApiError = class extends Error {
1265
- response;
1266
- context;
1267
- responseBody;
1268
- constructor(response, context, responseBody) {
1269
- super(`${context.request.method} ${context.url}: ${response.status} ${response.statusText} ${getServerErrorMessage(responseBody)}`);
1270
- this.response = response;
1271
- this.context = context;
1272
- this.responseBody = responseBody;
1273
- }
1274
- };
1275
- function createApiExecutor({ baseUrl, headers, validateResponse }) {
1276
- const errorCallbacks = [];
1277
- function onError(callback) {
1278
- errorCallbacks.push(callback);
1279
- return () => {
1280
- const index = errorCallbacks.indexOf(callback);
1281
- if (index !== -1) errorCallbacks.splice(index, 1);
1282
- };
1283
- }
1284
- async function execute(api, params, requestBody, requestInit) {
1285
- const url = baseUrl ? new URL(api.url(params), baseUrl).toString() : api.url(params);
1286
- const { headers: initHeaders, ...init } = api.requestInit(requestBody);
1287
- const executorHeaders = new Headers(headers);
1288
- if (initHeaders) new Headers(initHeaders).forEach((value, key) => {
1289
- executorHeaders.set(key, value);
1290
- });
1291
- const request = new Request(url, {
1292
- ...requestInit,
1293
- ...init,
1294
- headers: executorHeaders,
1295
- credentials: "include"
1296
- });
1297
- const context = Object.freeze({
1298
- api,
1299
- params,
1300
- requestBody,
1301
- url,
1302
- request
1303
- });
1304
- try {
1305
- const response = await fetch(request);
1306
- await validateResponse(response, context);
1307
- return await api.handleResponse(response, context);
1308
- } catch (error) {
1309
- for (const callback of errorCallbacks) callback(error, context);
1310
- return Promise.reject(error);
1311
- }
1312
- }
1313
- return Object.freeze({
1314
- execute,
1315
- onError
1316
- });
1317
- }
1318
- async function validateResponse(response, context) {
1319
- if (!response.ok) throw new ApiError(response, context, await response.clone().json().catch(() => response.clone().text()).catch(() => void 0));
1320
- }
1321
- function getServerErrorMessage(error) {
1322
- if (error == null) return "No error message.";
1323
- if (typeof error === "string") return error;
1324
- if (typeof error === "object") {
1325
- for (const key of [
1326
- "message",
1327
- "error",
1328
- "errMsg",
1329
- "errorMsg",
1330
- "detail",
1331
- "details"
1332
- ]) if (key in error) if (typeof error[key] === "string") return error[key];
1333
- else return JSON.stringify(error[key], void 0, 2);
1334
- return JSON.stringify(error, void 0, 2);
1335
- }
1336
- return String(error);
1337
- }
1338
993
 
1339
994
  //#endregion
1340
- //#region src/core/pantheon.ts
1341
- const executor = createApiExecutor({
1342
- baseUrl: "https://pantheon-ai.tidb.ai",
1343
- headers: { Authorization: `Bearer ${process.env.PANTHEON_API_KEY}` },
1344
- validateResponse
995
+ //#region ../sdk/src/schemas/fs.ts
996
+ const fsEntrySchema = z.object({
997
+ name: z.string(),
998
+ is_dir: z.boolean(),
999
+ size: z.number(),
1000
+ mode: z.string(),
1001
+ mod_time: zodJsonDate
1345
1002
  });
1346
- async function getPantheonProjectInfo({ projectId }) {
1347
- return await executor.execute(getProject, { projectId }, null);
1348
- }
1349
- async function getPantheonBranch({ projectId, branchId, getOutputIfFinished = false, manifestingAsSucceed = false }) {
1350
- const branch = await executor.execute(getProjectBranch, {
1351
- projectId,
1352
- branchId
1353
- }, null);
1354
- if (branch.status === "succeed" || manifestingAsSucceed && (branch.status === "manifesting" || branch.status === "ready_for_manifest")) if (getOutputIfFinished) return {
1355
- state: "succeed",
1356
- output: await executor.execute(getProjectBranchOutput, {
1357
- projectId,
1358
- branchId,
1359
- fullOutput: true
1360
- }, null)
1361
- };
1362
- else return { state: "succeed" };
1363
- else if (branch.status === "failed") {
1364
- let error = branch.latest_snap?.error;
1365
- if (!error) {
1366
- error = await executor.execute(getProjectBranchOutput, {
1367
- projectId,
1368
- branchId,
1369
- fullOutput: true
1370
- }, null);
1371
- error = `No error message, the latest output:\n\n${error}`;
1003
+ const FSResponseValidator = Object.freeze({
1004
+ [VALIDATOR_SYMBOL]: true,
1005
+ __phantom__: typeOf(),
1006
+ async parse(response) {
1007
+ if (response.headers.get("Content-Type") === "application/json+directory") {
1008
+ const data = await response.json();
1009
+ return fsEntrySchema.array().parse(data);
1010
+ } else {
1011
+ const blob = await response.blob();
1012
+ return new File([blob], response.url.split("/").pop(), { type: response.headers.get("content-type") ?? "application/octet-stream" });
1372
1013
  }
1373
- return {
1374
- state: "failed",
1375
- error
1376
- };
1377
1014
  }
1378
- return { state: "others" };
1379
- }
1380
- async function executeOnPantheon({ projectId, branchId, prompt, agent }) {
1381
- return (await executor.execute(createProjectExploration, { projectId }, {
1382
- shared_prompt_sequence: [prompt],
1383
- num_branches: 1,
1384
- agent,
1385
- parent_branch_id: branchId
1386
- })).branches[0].branch_id;
1387
- }
1015
+ });
1388
1016
 
1389
1017
  //#endregion
1390
- //#region src/core/task-list.ts
1391
- async function startTaskListLoop(agentName, { loopInterval = 5 }, logger) {
1392
- logger.info("Starting task list loop...");
1393
- let i = 0;
1394
- const abortController = new AbortController();
1395
- let sleepTimeout;
1396
- process.on("SIGINT", (signal) => {
1397
- logger.info(`Received ${signal}, shutting down gracefully...`);
1398
- clearTimeout(sleepTimeout);
1399
- abortController.abort(signal);
1400
- });
1401
- process.on("SIGTERM", (signal) => {
1402
- logger.info(`Received ${signal}, force shutting down...`);
1403
- clearTimeout(sleepTimeout);
1404
- abortController.abort(signal);
1405
- process.exit(1);
1406
- });
1407
- const provider = new TaskListTidbProvider(agentName, logger);
1408
- while (!abortController.signal.aborted) {
1409
- await loopOnce(provider, logger.child({ name: `loop:${i++}` }));
1410
- await new Promise((resolve) => {
1411
- abortController.signal.addEventListener("abort", resolve);
1412
- sleepTimeout = setTimeout(() => {
1413
- abortController.signal.removeEventListener("abort", resolve);
1414
- resolve(false);
1415
- }, loopInterval * 1e3);
1416
- });
1417
- }
1418
- await provider.close();
1419
- process.exit(0);
1420
- }
1421
- async function loopOnce(provider, logger) {
1422
- logger.info("Loop start.");
1423
- const tasks = await provider.getTasks({ status: ["pending", "running"] });
1424
- const runningTasks = tasks.filter((task) => task.status === "running");
1425
- const pendingTasks = tasks.filter((task) => task.status === "pending");
1426
- logger.info(`Found ${tasks.length} tasks, ${runningTasks.length} running, ${pendingTasks.length} pending.`);
1427
- if (runningTasks.length > 1) logger.warn("More than one task is running, this is not expected. %o", runningTasks.map((task) => task.id));
1428
- const nextTask = pendingTasks[0];
1429
- if (runningTasks.length > 0) {
1430
- if ((await Promise.allSettled(runningTasks.map(async (task) => {
1431
- await pollRunningTaskState(provider, task, logger.child({ name: `task:${task.id}:poll` }));
1432
- }))).some((result) => result.status === "rejected")) logger.warn("Failed to poll state for one or more running tasks");
1433
- } else if (nextTask) try {
1434
- await startPendingTask(provider, pendingTasks[0], logger.child({ name: `task:${nextTask.id}:start` }));
1435
- } catch (e) {
1436
- logger.error(`Failed to start task ${nextTask.id}: ${getErrorMessage(e)}`);
1437
- }
1438
- else logger.info("No tasks to process.");
1439
- }
1440
- async function pollRunningTaskState(provider, state, logger) {
1441
- const newStatus = await getPantheonBranch({
1442
- projectId: state.project_id,
1443
- branchId: state.branch_id,
1444
- getOutputIfFinished: true
1445
- });
1446
- if (newStatus.state === "succeed") {
1447
- logger.info("Task completed with output: %s", newStatus.output);
1448
- await provider.completeTask(state, newStatus.output || "(no output)");
1449
- } else if (newStatus.state === "failed") {
1450
- logger.info("Task failed with error: %s", newStatus.error);
1451
- await provider.failTask(state, newStatus.error);
1452
- } else logger.info("Task is still pending");
1453
- }
1454
- async function startPendingTask(provider, task, logger) {
1455
- const config = await provider.getAgentConfig(task.project_id);
1456
- if (!config) {
1457
- logger.warn("Agent configuration not found for project %s. Skip starting tasks.", task.project_id);
1458
- return;
1459
- }
1460
- await provider.startTask(task, async () => {
1461
- return await executeOnPantheon({
1462
- projectId: task.project_id,
1463
- branchId: task.base_branch_id,
1464
- prompt: task.task,
1465
- agent: config.execute_agent
1466
- });
1467
- });
1468
- logger.info(`Task ${task.id} started successfully.`);
1469
- }
1018
+ //#region ../sdk/src/schemas/ai.ts
1019
+ const providerMetadataSchema = z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.any()));
1020
+ const messageMetadataSchema = z$1.object().loose();
1021
+ const toolsShapeMap = { fake: {
1022
+ input: z$1.object({ fakeIn: z$1.string() }).loose(),
1023
+ output: z$1.object({ fakeOut: z$1.string() }).loose()
1024
+ } };
1025
+ const dataTypes = {
1026
+ delta: z$1.object().loose(),
1027
+ "message-metadata": z$1.object().loose(),
1028
+ "ui-collapsed": z$1.object({
1029
+ toolParts: z$1.number(),
1030
+ reasoningParts: z$1.number(),
1031
+ collapsed: z$1.boolean(),
1032
+ parts: z$1.object().loose().array()
1033
+ }),
1034
+ "ui-running-tools": z$1.object({
1035
+ toolParts: z$1.object().loose().array(),
1036
+ textParts: z$1.object().loose().array(),
1037
+ reasoningParts: z$1.object().loose().array()
1038
+ })
1039
+ };
1040
+ const chunksShapeMap = {
1041
+ "text-start": {
1042
+ id: z$1.string(),
1043
+ providerMetadata: providerMetadataSchema.optional()
1044
+ },
1045
+ "text-delta": {
1046
+ delta: z$1.string(),
1047
+ id: z$1.string(),
1048
+ providerMetadata: providerMetadataSchema.optional()
1049
+ },
1050
+ "text-end": {
1051
+ id: z$1.string(),
1052
+ providerMetadata: providerMetadataSchema.optional()
1053
+ },
1054
+ "reasoning-start": {
1055
+ id: z$1.string(),
1056
+ providerMetadata: providerMetadataSchema.optional()
1057
+ },
1058
+ "reasoning-delta": {
1059
+ delta: z$1.string(),
1060
+ id: z$1.string(),
1061
+ providerMetadata: providerMetadataSchema.optional()
1062
+ },
1063
+ "reasoning-end": {
1064
+ id: z$1.string(),
1065
+ providerMetadata: providerMetadataSchema.optional()
1066
+ },
1067
+ error: { errorText: z$1.string() },
1068
+ "tool-input-available": {
1069
+ toolCallId: z$1.string(),
1070
+ toolName: z$1.string(),
1071
+ input: z$1.unknown(),
1072
+ providerExecuted: z$1.boolean().optional(),
1073
+ providerMetadata: providerMetadataSchema.optional(),
1074
+ dynamic: z$1.boolean().optional()
1075
+ },
1076
+ "tool-input-error": {
1077
+ toolCallId: z$1.string(),
1078
+ toolName: z$1.string(),
1079
+ input: z$1.unknown(),
1080
+ providerExecuted: z$1.boolean().optional(),
1081
+ providerMetadata: providerMetadataSchema.optional(),
1082
+ dynamic: z$1.boolean().optional(),
1083
+ errorText: z$1.string()
1084
+ },
1085
+ "tool-output-available": {
1086
+ toolCallId: z$1.string(),
1087
+ output: z$1.unknown(),
1088
+ providerExecuted: z$1.boolean().optional(),
1089
+ dynamic: z$1.boolean().optional(),
1090
+ preliminary: z$1.boolean().optional()
1091
+ },
1092
+ "tool-output-error": {
1093
+ toolCallId: z$1.string(),
1094
+ providerExecuted: z$1.boolean().optional(),
1095
+ dynamic: z$1.boolean().optional(),
1096
+ errorText: z$1.string()
1097
+ },
1098
+ "tool-input-start": {
1099
+ toolCallId: z$1.string(),
1100
+ toolName: z$1.string(),
1101
+ providerExecuted: z$1.boolean().optional(),
1102
+ dynamic: z$1.boolean().optional()
1103
+ },
1104
+ "tool-input-delta": {
1105
+ toolCallId: z$1.string(),
1106
+ inputTextDelta: z$1.string()
1107
+ },
1108
+ "source-url": {
1109
+ sourceId: z$1.string(),
1110
+ url: z$1.string(),
1111
+ title: z$1.string().optional(),
1112
+ providerMetadata: providerMetadataSchema.optional()
1113
+ },
1114
+ "source-document": {
1115
+ sourceId: z$1.string(),
1116
+ mediaType: z$1.string(),
1117
+ title: z$1.string(),
1118
+ filename: z$1.string().optional(),
1119
+ providerMetadata: providerMetadataSchema.optional()
1120
+ },
1121
+ file: {
1122
+ url: z$1.string(),
1123
+ mediaType: z$1.string()
1124
+ },
1125
+ "start-step": {},
1126
+ "finish-step": {},
1127
+ start: {
1128
+ messageId: z$1.string().optional(),
1129
+ messageMetadata: messageMetadataSchema.optional()
1130
+ },
1131
+ finish: { messageMetadata: messageMetadataSchema.optional() },
1132
+ abort: {},
1133
+ "message-metadata": { messageMetadata: messageMetadataSchema }
1134
+ };
1135
+ const unknownDataChunkSchema = z$1.object({
1136
+ type: z$1.string().regex(/^data-/),
1137
+ id: z$1.string().optional(),
1138
+ data: z$1.unknown(),
1139
+ transient: z$1.boolean().optional()
1140
+ });
1141
+ const dataChunkSchema = Object.entries(dataTypes).map(([name, schema]) => z$1.object({
1142
+ type: z$1.literal(`data-${name}`),
1143
+ id: z$1.string().optional(),
1144
+ data: schema,
1145
+ transient: z$1.boolean().optional()
1146
+ }));
1147
+ const chunkSchema = Object.entries(chunksShapeMap).map(([type, schema]) => z$1.object({
1148
+ type: z$1.literal(type),
1149
+ ...schema
1150
+ }));
1151
+ const uiMessageChunkSchema = z$1.discriminatedUnion("type", [...chunkSchema, ...dataChunkSchema]);
1152
+ const partsShapeMap = {
1153
+ text: {
1154
+ text: z$1.string(),
1155
+ state: z$1.enum(["streaming", "done"]).optional(),
1156
+ providerMetadata: providerMetadataSchema.optional()
1157
+ },
1158
+ reasoning: {
1159
+ text: z$1.string(),
1160
+ state: z$1.enum(["streaming", "done"]).optional(),
1161
+ providerMetadata: providerMetadataSchema.optional()
1162
+ },
1163
+ "source-url": {
1164
+ sourceId: z$1.string(),
1165
+ url: z$1.string(),
1166
+ title: z$1.string().optional(),
1167
+ providerMetadata: providerMetadataSchema.optional()
1168
+ },
1169
+ "source-document": {
1170
+ sourceId: z$1.string(),
1171
+ mediaType: z$1.string(),
1172
+ title: z$1.string(),
1173
+ filename: z$1.string().optional(),
1174
+ providerMetadata: providerMetadataSchema.optional()
1175
+ },
1176
+ file: {
1177
+ url: z$1.string(),
1178
+ mediaType: z$1.string(),
1179
+ filename: z$1.string().optional(),
1180
+ providerMetadata: providerMetadataSchema.optional()
1181
+ },
1182
+ "step-start": {}
1183
+ };
1184
+ const dynamicToolSchema = z$1.discriminatedUnion("state", [
1185
+ z$1.object({
1186
+ type: z$1.literal("dynamic-tool"),
1187
+ toolName: z$1.string(),
1188
+ toolCallId: z$1.string(),
1189
+ state: z$1.literal("input-streaming"),
1190
+ input: z$1.unknown().optional(),
1191
+ output: z$1.never().optional(),
1192
+ errorText: z$1.never().optional()
1193
+ }),
1194
+ z$1.object({
1195
+ type: z$1.literal("dynamic-tool"),
1196
+ toolName: z$1.string(),
1197
+ toolCallId: z$1.string(),
1198
+ state: z$1.literal("input-available"),
1199
+ input: z$1.unknown(),
1200
+ output: z$1.never().optional(),
1201
+ errorText: z$1.never().optional(),
1202
+ callProviderMetadata: providerMetadataSchema.optional()
1203
+ }),
1204
+ z$1.object({
1205
+ type: z$1.literal("dynamic-tool"),
1206
+ toolName: z$1.string(),
1207
+ toolCallId: z$1.string(),
1208
+ state: z$1.literal("output-available"),
1209
+ input: z$1.unknown(),
1210
+ output: z$1.unknown(),
1211
+ errorText: z$1.never().optional(),
1212
+ callProviderMetadata: providerMetadataSchema.optional(),
1213
+ preliminary: z$1.boolean().optional()
1214
+ }),
1215
+ z$1.object({
1216
+ type: z$1.literal("dynamic-tool"),
1217
+ toolName: z$1.string(),
1218
+ toolCallId: z$1.string(),
1219
+ state: z$1.literal("output-error"),
1220
+ input: z$1.unknown(),
1221
+ output: z$1.never().optional(),
1222
+ errorText: z$1.string(),
1223
+ callProviderMetadata: providerMetadataSchema.optional()
1224
+ })
1225
+ ]);
1226
+ const dataPartSchema = Object.entries(dataTypes).map(([name, schema]) => z$1.object({
1227
+ type: z$1.literal(`data-${name}`),
1228
+ id: z$1.string().optional(),
1229
+ data: schema
1230
+ }));
1231
+ const notDefinedDataType = z$1.string().regex(/data-/).refine((type) => !Object.keys(dataTypes).includes(type.slice(5)));
1232
+ const unknownDataPartSchema = z$1.object({
1233
+ type: notDefinedDataType,
1234
+ id: z$1.string().optional(),
1235
+ data: z$1.unknown()
1236
+ });
1237
+ const notDefinedToolType = z$1.string().regex(/tool-/).refine((type) => !Object.keys(toolsShapeMap).includes(type.slice(5)));
1238
+ const unknownToolPartSchema = z$1.discriminatedUnion("state", [
1239
+ z$1.object({
1240
+ type: notDefinedToolType,
1241
+ toolCallId: z$1.string(),
1242
+ state: z$1.literal("input-streaming"),
1243
+ input: z$1.unknown().optional(),
1244
+ output: z$1.never().optional(),
1245
+ providerExecuted: z$1.boolean().optional(),
1246
+ errorText: z$1.never().optional()
1247
+ }),
1248
+ z$1.object({
1249
+ type: notDefinedToolType,
1250
+ toolCallId: z$1.string(),
1251
+ state: z$1.literal("input-available"),
1252
+ input: z$1.unknown(),
1253
+ output: z$1.never().optional(),
1254
+ providerExecuted: z$1.boolean().optional(),
1255
+ errorText: z$1.never().optional(),
1256
+ callProviderMetadata: providerMetadataSchema.optional()
1257
+ }),
1258
+ z$1.object({
1259
+ type: notDefinedToolType,
1260
+ toolCallId: z$1.string(),
1261
+ state: z$1.literal("output-available"),
1262
+ input: z$1.unknown(),
1263
+ output: z$1.unknown(),
1264
+ errorText: z$1.never().optional(),
1265
+ providerExecuted: z$1.boolean().optional(),
1266
+ callProviderMetadata: providerMetadataSchema.optional(),
1267
+ preliminary: z$1.boolean().optional()
1268
+ }),
1269
+ z$1.object({
1270
+ type: notDefinedToolType,
1271
+ toolCallId: z$1.string(),
1272
+ state: z$1.literal("output-error"),
1273
+ input: z$1.unknown().optional(),
1274
+ rawInput: z$1.unknown().optional(),
1275
+ output: z$1.never().optional(),
1276
+ errorText: z$1.string(),
1277
+ providerExecuted: z$1.boolean().optional(),
1278
+ callProviderMetadata: providerMetadataSchema.optional()
1279
+ })
1280
+ ]);
1281
+ const partSchema = Object.entries(partsShapeMap).map(([type, schema]) => z$1.object({
1282
+ type: z$1.literal(type),
1283
+ ...schema
1284
+ }));
1285
+ const toolsPartSchema = Object.entries(toolsShapeMap).map(([type, schema]) => z$1.discriminatedUnion("state", [
1286
+ z$1.object({
1287
+ type: z$1.literal(`tool-${type}`),
1288
+ toolCallId: z$1.string(),
1289
+ state: z$1.literal("input-streaming"),
1290
+ input: schema.input.partial().optional(),
1291
+ output: z$1.never().optional(),
1292
+ providerExecuted: z$1.boolean().optional(),
1293
+ errorText: z$1.never().optional()
1294
+ }),
1295
+ z$1.object({
1296
+ type: z$1.literal(`tool-${type}`),
1297
+ toolCallId: z$1.string(),
1298
+ state: z$1.literal("input-available"),
1299
+ input: schema.input,
1300
+ output: z$1.never().optional(),
1301
+ providerExecuted: z$1.boolean().optional(),
1302
+ errorText: z$1.never().optional(),
1303
+ callProviderMetadata: providerMetadataSchema.optional()
1304
+ }),
1305
+ z$1.object({
1306
+ type: z$1.literal(`tool-${type}`),
1307
+ toolCallId: z$1.string(),
1308
+ state: z$1.literal("output-available"),
1309
+ input: schema.input,
1310
+ output: schema.output,
1311
+ errorText: z$1.never().optional(),
1312
+ providerExecuted: z$1.boolean().optional(),
1313
+ callProviderMetadata: providerMetadataSchema.optional(),
1314
+ preliminary: z$1.boolean().optional()
1315
+ }),
1316
+ z$1.object({
1317
+ type: z$1.literal(`tool-${type}`),
1318
+ toolCallId: z$1.string(),
1319
+ state: z$1.literal("output-error"),
1320
+ input: schema.input.optional(),
1321
+ rawInput: z$1.unknown().optional(),
1322
+ output: z$1.never().optional(),
1323
+ errorText: z$1.string(),
1324
+ providerExecuted: z$1.boolean().optional(),
1325
+ callProviderMetadata: providerMetadataSchema.optional()
1326
+ })
1327
+ ]));
1328
+ const uiMessagePartSchema = z$1.discriminatedUnion("type", [
1329
+ ...partSchema,
1330
+ ...toolsPartSchema,
1331
+ ...dataPartSchema,
1332
+ dynamicToolSchema
1333
+ ]);
1470
1334
 
1471
1335
  //#endregion
1472
- //#region src/core/index.ts
1473
- async function runAgent(name, options, logger) {
1474
- const agentDir = path.join(options.dataDir, "agents", name);
1475
- const pidFile = path.join(agentDir, "pid");
1476
- await fs$1.promises.mkdir(agentDir, { recursive: true });
1477
- await assertsSingleton(logger, pidFile);
1478
- await startTaskListLoop(name, { loopInterval: options.loopInterval }, logger);
1479
- }
1480
- async function configAgent(name, options) {
1481
- const provider = new TaskListTidbProvider(name, pino());
1482
- const previousConfig = await provider.getAgentConfig(options.projectId);
1483
- if (previousConfig) if (previousConfig.role === options.role) {
1484
- console.log(`Agent ${name} already configured as ${options.role} for project ${options.projectId}.`);
1485
- console.log(`Base branch id: ${previousConfig.base_branch_id}`);
1486
- await provider.close();
1487
- return;
1488
- } else {
1489
- console.error(`Agent ${name} already configured as ${previousConfig.role} for project ${options.projectId}.`);
1490
- console.error(`Base branch id: ${previousConfig.base_branch_id}`);
1491
- console.error(`Cannot change role to ${options.role}`);
1492
- await provider.close();
1493
- process.exitCode = 1;
1494
- return;
1495
- }
1496
- console.log(`Configuring agent ${name} as ${options.role} for project ${options.projectId}.`);
1497
- if (!options.rootBranchId) {
1498
- console.log("No root branch id specified, using project root branch.");
1499
- const project = await getPantheonProjectInfo({ projectId: options.projectId });
1500
- if (!project.root_branch_id) {
1501
- console.error(`Project ${options.projectId} has no root branch. Project status is ${project.status}`);
1502
- await provider.close();
1503
- process.exitCode = 1;
1504
- return;
1505
- }
1506
- options.rootBranchId = project.root_branch_id;
1507
- }
1508
- if (options.bootstrap) {
1509
- const branchId = await executeOnPantheon({
1510
- projectId: options.projectId,
1511
- branchId: options.rootBranchId,
1512
- agent: "codex",
1513
- prompt: `You must follow these instructions to setup base branch for role "${options.role}":
1514
- 0. Configure Git credentials via ~/.setup-git.sh
1515
- 1. Clone the main branch from https://github.com/pingcap-inc/pantheon-agents to a temporary directory.
1516
- 2. Copy the pantheon-agents/roles/${options.role}/AGENTS.md to \`<workspace>/AGENTS.md\`.
1517
- 3. Copy the pantheon-agents/roles/${options.role}/skills directory to \`<workspace>/.codex/skills\` if exists.
1518
- ${options.skills.length > 0 ? `4. Copy the pantheon-agents/skills/\{${options.skills.join(",")}} directory to \`<workspace>/.codex/skills/\`` : ""}
1519
-
1520
- Validate <workspace>: check if files and directorys exists:
1521
- - AGENTS.md
1522
- - .codex/skills
1523
-
1524
- **You MUST NOT generate AGENTS.md and skills by yourself if clone failed.**
1525
- `
1526
- });
1527
- let retried = 0;
1528
- const maxRetries = 3;
1529
- let i = 0;
1530
- console.log(`Bootstrap branch created: ${branchId}. Waiting for ready... [poll interval = 10s]`);
1531
- while (true) {
1532
- await new Promise((resolve) => {
1533
- setTimeout(resolve, 1e4);
1534
- });
1535
- const result = await getPantheonBranch({
1536
- branchId,
1537
- projectId: options.projectId,
1538
- getOutputIfFinished: true
1539
- }).then((result) => {
1540
- retried = 0;
1541
- return result;
1542
- }).catch((reason) => {
1543
- if (retried < maxRetries) {
1544
- retried++;
1545
- return { state: "others" };
1546
- } else throw new Error(`Failed to get bootstrap branch status. Retry ${retried} times. Last error: ${getErrorMessage(reason)}`);
1547
- });
1548
- if (result.state === "failed") {
1549
- console.error("Bootstrap failed: " + result.error);
1550
- await provider.close();
1551
- process.exit(1);
1552
- }
1553
- if (result.state === "succeed") {
1554
- console.log("Bootstrap succeeded. Output is:");
1555
- console.log(result.output);
1556
- break;
1557
- }
1558
- console.log(`Bootstrap in progress... [${++i}]`);
1559
- }
1560
- await provider.setAgentConfig({
1561
- project_id: options.projectId,
1562
- base_branch_id: branchId,
1563
- execute_agent: options.executeAgent,
1564
- role: options.role,
1565
- skills: options.skills,
1566
- prototype_url: "https://github.com/pingcap-inc/pantheon-agents"
1567
- });
1568
- } else await provider.setAgentConfig({
1569
- project_id: options.projectId,
1570
- base_branch_id: options.rootBranchId,
1571
- execute_agent: options.executeAgent,
1572
- role: options.role,
1573
- skills: options.skills,
1574
- prototype_url: "https://github.com/pingcap-inc/pantheon-agents"
1575
- });
1576
- console.log(`Agent ${name} configured successfully.`);
1577
- await provider.close();
1578
- }
1579
- async function addTask(name, options) {
1580
- const provider = new TaskListTidbProvider(name, pino());
1581
- const config = await provider.getAgentConfig(options.projectId);
1582
- if (!config) throw new Error(`Agent ${name} not configured for project ${options.projectId}`);
1583
- const task = await provider.createTask({
1584
- task: options.prompt,
1585
- project_id: options.projectId,
1586
- base_branch_id: config.base_branch_id
1587
- });
1588
- console.log(`Task ${task.task} queued successfully.`);
1589
- await provider.close();
1590
- }
1591
- async function deleteTask(agentName, taskId) {
1592
- const provider = new TaskListTidbProvider(agentName, pino());
1593
- try {
1594
- const task = await provider.getTask(taskId);
1595
- if (!task) return null;
1596
- if (!await provider.deleteTask(taskId)) return null;
1597
- return task;
1598
- } finally {
1599
- await provider.close();
1600
- }
1601
- }
1602
- async function showAgentConfig(agentName, projectId) {
1603
- const provider = new TaskListTidbProvider(agentName, pino());
1604
- try {
1605
- return await provider.getAgentConfig(projectId);
1606
- } finally {
1607
- await provider.close();
1608
- }
1609
- }
1610
- async function showAgentConfigs(agentName) {
1611
- const provider = new TaskListTidbProvider(agentName, pino());
1612
- try {
1613
- return await provider.getAgentConfigs();
1614
- } finally {
1615
- await provider.close();
1616
- }
1617
- }
1618
- async function showTasks(name, options) {
1619
- const provider = new TaskListTidbProvider(name, pino());
1620
- try {
1621
- return await provider.getTasks({
1622
- status: options.status,
1623
- order_by: options.orderBy,
1624
- order_direction: options.orderDirection
1336
+ //#region ../sdk/src/schemas/project.ts
1337
+ const projectMetaGitHubSchema = z.object({
1338
+ repo_owner_login: z.string().optional(),
1339
+ repo_name: z.string().optional(),
1340
+ issue_type: z.string().optional(),
1341
+ issue_number: z.number().optional()
1342
+ }).optional();
1343
+ const projectMetaSchema = z.object({ github: projectMetaGitHubSchema }).optional().nullable();
1344
+ const projectSchema = z.object({
1345
+ id: z.string(),
1346
+ name: z.string(),
1347
+ display_name: z.string(),
1348
+ category: z.string(),
1349
+ description: z.string(),
1350
+ user_id: z.string().nullable(),
1351
+ owner_email: z.string().nullable().optional(),
1352
+ root_branch_id: z.string().nullable(),
1353
+ ongoing_stream_id: z.string().nullable(),
1354
+ status: z.enum([
1355
+ "CREATED",
1356
+ "PROVISIONING",
1357
+ "READY",
1358
+ "RUNNING",
1359
+ "PAUSED",
1360
+ "FAILED",
1361
+ "ARCHIVED"
1362
+ ]).nullable().optional(),
1363
+ error_message: z.string().nullable().optional(),
1364
+ meta: projectMetaSchema,
1365
+ github_source_owner_id: z.number().nullable().optional(),
1366
+ github_source_repo_id: z.number().nullable().optional(),
1367
+ github_source_number: z.number().nullable().optional(),
1368
+ created_at: zodJsonDate,
1369
+ updated_at: zodJsonDate,
1370
+ branches_total: z.number().int().nullable().optional(),
1371
+ background_tasks_total: z.number().int().nullable().optional()
1372
+ });
1373
+ const projectMessageSchema = z.object({
1374
+ id: z.string(),
1375
+ role: z.enum([
1376
+ "system",
1377
+ "user",
1378
+ "assistant"
1379
+ ]),
1380
+ metadata: messageMetadataSchema.nullable().optional(),
1381
+ parts: z.array(z.object().loose()),
1382
+ ordinal: z.number(),
1383
+ project_id: z.string(),
1384
+ user_id: z.string().nullable(),
1385
+ source_request_id: z.string().nullable().optional(),
1386
+ event_stream_id: z.string().nullable(),
1387
+ status: z.string().nullable(),
1388
+ is_finished: z.boolean(),
1389
+ created_at: zodJsonDate,
1390
+ updated_at: zodJsonDate
1391
+ });
1392
+ const projectMessageStreamParser = new StreamResponseParser({ pipe: (input) => {
1393
+ return input.pipeThrough(new TextDecoderStream()).pipeThrough(new BufferedLinesStream("\n\n")).pipeThrough(new SSEDataDecoderStream()).pipeThrough(new ZodStream({ schema: z.object().loose() }));
1394
+ } });
1395
+ const projectRawMessageStreamParser = new StreamResponseParser({ pipe: (input) => {
1396
+ return input.pipeThrough(new TextDecoderStream()).pipeThrough(new BufferedLinesStream("\n\n")).pipeThrough(new SSEDataDecoderStream()).pipeThrough(new ZodStream({ schema: z.object().loose() }));
1397
+ } });
1398
+ const projectQueuedRequestSchema = z.object({
1399
+ id: z.string(),
1400
+ type: z.string(),
1401
+ payload: z.unknown(),
1402
+ requested_at: zodJsonDate,
1403
+ summary: z.string()
1404
+ });
1405
+ const projectBackgroundTaskSchema = z.object({
1406
+ task_id: z.string(),
1407
+ name: z.string().nullable(),
1408
+ action_type: z.enum(["execution", "exploration"]),
1409
+ action_id: z.string(),
1410
+ status: z.enum([
1411
+ "SUCCESS",
1412
+ "FAILURE",
1413
+ "PENDING",
1414
+ "STARTED"
1415
+ ]).nullable(),
1416
+ result: z.object().loose().nullable(),
1417
+ retries: z.number().nullable(),
1418
+ started_at: zodJsonDate.nullable(),
1419
+ last_polled_at: zodJsonDate.nullable(),
1420
+ ended_at: zodJsonDate.nullable()
1421
+ });
1422
+ var BufferedLinesStream = class extends TransformStream {
1423
+ constructor(sep = "\n") {
1424
+ let buffer = "";
1425
+ super({
1426
+ transform(chunk, controller) {
1427
+ chunk = buffer += chunk;
1428
+ while (true) {
1429
+ const index = chunk.indexOf(sep);
1430
+ if (index === -1) {
1431
+ buffer = chunk;
1432
+ break;
1433
+ }
1434
+ const line = chunk.slice(0, index).trim();
1435
+ if (line) controller.enqueue(line);
1436
+ chunk = chunk.slice(index + sep.length);
1437
+ }
1438
+ },
1439
+ flush() {
1440
+ if (buffer) console.warn("buffered lines stream has unprocessed lines:", buffer);
1441
+ }
1625
1442
  });
1626
- } finally {
1627
- await provider.close();
1628
- }
1629
- }
1630
- async function listAgentNames() {
1631
- const provider = new TaskListTidbProvider("list-agents", pino());
1632
- try {
1633
- return await provider.listAgentNames();
1634
- } finally {
1635
- await provider.close();
1636
- }
1637
- }
1638
- async function showTasksForAgents(options) {
1639
- const selectedAgents = options.allAgents ? await listAgentNames() : options.agents;
1640
- const tasksWithAgent = await Promise.all(selectedAgents.map(async (agent) => {
1641
- return (await showTasks(agent, {
1642
- status: options.status,
1643
- orderBy: options.orderBy,
1644
- orderDirection: options.orderDirection
1645
- })).map((task) => ({
1646
- agent,
1647
- task
1648
- }));
1649
- })).then((groups) => groups.flat());
1650
- const orderKey = options.orderBy ?? "queued_at";
1651
- const orderDirection = options.orderDirection ?? "desc";
1652
- tasksWithAgent.sort((a, b) => {
1653
- const aValue = a.task[orderKey];
1654
- const bValue = b.task[orderKey];
1655
- const aTime = aValue instanceof Date ? aValue.getTime() : 0;
1656
- const bTime = bValue instanceof Date ? bValue.getTime() : 0;
1657
- return orderDirection === "asc" ? aTime - bTime : bTime - aTime;
1658
- });
1659
- if (options.limit != null) return tasksWithAgent.slice(0, options.limit);
1660
- return tasksWithAgent;
1661
- }
1662
- function formatRelativeTime(value) {
1663
- if (!value) return "";
1664
- const diffMs = Date.now() - value.getTime();
1665
- const absMs = Math.abs(diffMs);
1666
- const tense = diffMs >= 0 ? "ago" : "from now";
1667
- const seconds = Math.floor(absMs / 1e3);
1668
- const minutes = Math.floor(seconds / 60);
1669
- const hours = Math.floor(minutes / 60);
1670
- const days = Math.floor(hours / 24);
1671
- if (days > 0) return `${days}d ${tense}`;
1672
- if (hours > 0) return `${hours}h ${tense}`;
1673
- if (minutes > 0) return `${minutes}m ${tense}`;
1674
- return `${seconds}s ${tense}`;
1675
- }
1676
- function formatDate(value) {
1677
- return value ? value.toISOString() : "";
1678
- }
1679
- function truncateText(value, maxLength) {
1680
- if (value.length <= maxLength) return value;
1681
- return `${value.slice(0, Math.max(0, maxLength - 1))}…`;
1682
- }
1683
- function colorText(value, colorCode) {
1684
- return `\u001b[${colorCode}m${value}\u001b[0m`;
1685
- }
1686
- function formatStatus(status, useColor) {
1687
- if (!useColor) return status;
1688
- switch (status) {
1689
- case "pending": return colorText(status, 33);
1690
- case "running": return colorText(status, 36);
1691
- case "completed": return colorText(status, 32);
1692
- case "failed": return colorText(status, 31);
1693
- case "cancelled": return colorText(status, 90);
1694
1443
  }
1695
- }
1696
- function formatConciseTaskLine(options) {
1697
- const { agent, task, maxTaskLength, useColor } = options;
1698
- let timestamp = task.queued_at;
1699
- if (task.status === "running") timestamp = task.started_at;
1700
- if (task.status === "completed" || task.status === "failed") timestamp = task.ended_at;
1701
- if (task.status === "cancelled") timestamp = task.cancelled_at ?? task.queued_at;
1702
- const statusText = formatStatus(task.status, useColor);
1703
- const timeText = formatRelativeTime(timestamp);
1704
- const taskText = truncateText(task.task, maxTaskLength);
1705
- return [
1706
- agent,
1707
- statusText,
1708
- task.id,
1709
- timeText,
1710
- taskText
1711
- ].filter((part) => part !== "").join(" ");
1712
- }
1713
- function formatTaskTableRow(options) {
1714
- const { agent, task, maxTaskLength } = options;
1715
- const branchId = "branch_id" in task ? task.branch_id ?? "" : "";
1716
- const startedAt = "started_at" in task ? task.started_at : void 0;
1717
- const endedAt = "ended_at" in task ? task.ended_at : void 0;
1718
- return {
1719
- agent,
1720
- id: task.id,
1721
- status: task.status,
1722
- project_id: task.project_id,
1723
- branch_id: branchId,
1724
- queued_at: formatDate(task.queued_at),
1725
- started_at: formatDate(startedAt),
1726
- ended_at: formatDate(endedAt),
1727
- task: truncateText(task.task, maxTaskLength)
1728
- };
1729
- }
1730
- async function assertsSingleton(logger, pidFile) {
1731
- try {
1732
- const pid = await fs$1.promises.readFile(pidFile, "utf-8");
1733
- process.kill(parseInt(pid), 0);
1734
- console.error("Failed to assert singleton agent process:");
1735
- process.exit(1);
1736
- } catch (e) {
1737
- await fs$1.promises.writeFile(pidFile, process.pid.toString());
1738
- process.on("exit", () => {
1739
- fs$1.promises.rm(pidFile);
1740
- });
1444
+ };
1445
+ var SSEDataDecoderStream = class extends TransformStream {
1446
+ constructor() {
1447
+ let handle = void 0;
1448
+ super({ transform: (chunk, controller) => {
1449
+ clearTimeout(handle);
1450
+ handle = setTimeout(() => {
1451
+ controller.error(/* @__PURE__ */ new Error("Read timeout, please retry."));
1452
+ }, 15e3);
1453
+ if (/^data:/.test(chunk)) {
1454
+ const part = chunk.replace(/^data: /, "").trim();
1455
+ if (part === "[DONE]") {} else try {
1456
+ controller.enqueue(JSON.parse(part));
1457
+ } catch (e) {
1458
+ console.error("invalid sse chunk", chunk, e);
1459
+ controller.error(e);
1460
+ }
1461
+ }
1462
+ } });
1741
1463
  }
1742
- }
1464
+ };
1465
+
1466
+ //#endregion
1467
+ //#region ../sdk/src/api/projects.ts
1468
+ const listProjects = defineApi(get`/api/v1/projects?page=${"page"}&size=${"size"}&user_id=${"user_id?"}&category=${"category?"}&github_source_owner_id=${"github_source_owner_id?"}&github_source_repo_id=${"github_source_repo_id?"}`, null, paged(projectSchema));
1469
+ const listAdminProjects = defineApi(get`/api/v1/admin/projects?page=${"page"}&size=${"size"}&org_id=${"org_id?"}&user_id=${"user_id?"}&category=${"category?"}&github_source_owner_id=${"github_source_owner_id?"}&github_source_repo_id=${"github_source_repo_id?"}`, null, paged(projectSchema));
1470
+ const getProject = defineApi(get`/api/v1/projects/${"projectId"}`, null, projectSchema);
1471
+ const transferProject = defineApi(post`/api/v1/projects/${"projectId"}/transfer`, typeOf(), projectSchema);
1472
+ const createProject = defineApi(post`/api/v1/projects`, typeOf(), projectSchema);
1473
+ const listProjectMessages = defineApi(get`/api/v1/projects/${"projectId"}/messages`, null, z.object({
1474
+ messages: projectMessageSchema.array(),
1475
+ ongoing_stream_id: z.string().nullable()
1476
+ }));
1477
+ const deleteProjectMessage = defineApi(del`/api/v1/projects/${"projectId"}/messages/${"messageId"}`, null, "raw");
1478
+ const postProjectMessage = defineApi(post`/api/v1/projects/${"projectId"}`, typeOf(), z.object({
1479
+ messages: projectMessageSchema.array(),
1480
+ ongoing_stream_id: z.string().nullable()
1481
+ }));
1482
+ const continueProject = defineApi(post`/api/v1/projects/${"projectId"}/continue`, typeOf(), "raw");
1483
+ const stopProject = defineApi(post`/api/v1/projects/${"projectId"}/stop`, typeOf(), "raw");
1484
+ const getProjectBranch = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}`, null, branchSchema);
1485
+ const getProjectBranchOutput = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/output?full_output=${"fullOutput?"}`, null, "text");
1486
+ const listProjectBranches = defineApi(get`/api/v1/projects/${"projectId"}/branches?page=${"page"}&size=${"size"}`, null, paged(branchSchema));
1487
+ const listProjectBranchSnaps = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/snaps`, null, branchSnapsSchema);
1488
+ const listProjectBackgroundTasks = defineApi(get`/api/v1/projects/${"projectId"}/background_tasks?statuses=${"statuses?"}`, null, z.array(projectBackgroundTaskSchema));
1489
+ const createProjectExploration = defineApi(post`/api/v1/projects/${"projectId"}/explorations`, typeOf(), createExplorationResultSchema);
1490
+ const listProjectExplorations = defineApi(get`/api/v1/projects/${"projectId"}/explorations`, null, explorationSchema.array());
1491
+ const getProjectExplorationResult = defineApi(get`/api/v1/projects/${"projectId"}/explorations/${"explorationId"}/result`, null, explorationResultSchema);
1492
+ const getProjectBranchFs = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/fs/${"path*"}`, null, FSResponseValidator);
1493
+ const getProjectBranchFsPreview = defineApi(get`/api/v1/projects/${"projectId"}/branches/${"branchId"}/preview/${"path*"}`, null, FSResponseValidator);
1494
+
1495
+ //#endregion
1496
+ //#region ../sdk/src/api/connectors.ts
1497
+ const getGithubUser = defineApi(get`/api/v1/connectors/github/user`, null, z.object({ github_username: z.string() }).nullable());
1498
+ const disconnectGithub = defineApi(post`/api/v1/connectors/github/disconnect`, null, z.object({ success: z.boolean() }));
1499
+ const listGithubRepositories = defineApi(get`/api/v1/user/github/repositories?page=${"page"}&size=${"size"}`, null, paged(z.object({
1500
+ repo_id: z.number(),
1501
+ repo_name: z.string(),
1502
+ public: z.boolean(),
1503
+ installation_id: z.number()
1504
+ })));
1505
+
1506
+ //#endregion
1507
+ //#region ../sdk/src/schemas/organizations.ts
1508
+ const organizationItemSchema = z.object({
1509
+ id: z.string(),
1510
+ name: z.string(),
1511
+ is_personal: z.boolean(),
1512
+ created_at: z.string().nullable(),
1513
+ updated_at: z.string().nullable()
1514
+ });
1515
+ const organizationSchema = organizationItemSchema;
1516
+ const organizationDeleteSchema = z.object({ success: z.boolean() });
1517
+ const organizationRoleSchema = z.enum(["owner", "member"]);
1518
+ const organizationMemberSchema = z.object({
1519
+ org_id: z.string(),
1520
+ user_id: z.string(),
1521
+ email: z.string().nullable().optional(),
1522
+ github_username: z.string().nullable().optional(),
1523
+ role: organizationRoleSchema,
1524
+ created_at: z.string().nullable(),
1525
+ updated_at: z.string().nullable()
1526
+ });
1527
+ const addOrgMemberResponseSchema = z.object({
1528
+ member: organizationMemberSchema.nullable().optional(),
1529
+ email_sent: z.boolean().nullable().optional(),
1530
+ invite_link: z.string().nullable().optional()
1531
+ });
1532
+ const invitationStatusSchema = z.enum(["pending", "accepted"]);
1533
+ const organizationInvitationSchema = z.object({
1534
+ id: z.string(),
1535
+ org_id: z.string(),
1536
+ org_role: organizationRoleSchema,
1537
+ email: z.string().nullable(),
1538
+ github_username: z.string().nullable(),
1539
+ invited_by: z.string(),
1540
+ status: invitationStatusSchema,
1541
+ created_at: z.string().nullable(),
1542
+ updated_at: z.string().nullable()
1543
+ });
1743
1544
 
1744
1545
  //#endregion
1745
- //#region ../../node_modules/dotenv/package.json
1746
- var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1747
- module.exports = {
1748
- "name": "dotenv",
1749
- "version": "17.2.4",
1750
- "description": "Loads environment variables from .env file",
1751
- "main": "lib/main.js",
1752
- "types": "lib/main.d.ts",
1753
- "exports": {
1754
- ".": {
1755
- "types": "./lib/main.d.ts",
1756
- "require": "./lib/main.js",
1757
- "default": "./lib/main.js"
1758
- },
1759
- "./config": "./config.js",
1760
- "./config.js": "./config.js",
1761
- "./lib/env-options": "./lib/env-options.js",
1762
- "./lib/env-options.js": "./lib/env-options.js",
1763
- "./lib/cli-options": "./lib/cli-options.js",
1764
- "./lib/cli-options.js": "./lib/cli-options.js",
1765
- "./package.json": "./package.json"
1766
- },
1767
- "scripts": {
1768
- "dts-check": "tsc --project tests/types/tsconfig.json",
1769
- "lint": "standard",
1770
- "pretest": "npm run lint && npm run dts-check",
1771
- "test": "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
1772
- "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
1773
- "prerelease": "npm test",
1774
- "release": "standard-version"
1775
- },
1776
- "repository": {
1777
- "type": "git",
1778
- "url": "git://github.com/motdotla/dotenv.git"
1779
- },
1780
- "homepage": "https://github.com/motdotla/dotenv#readme",
1781
- "funding": "https://dotenvx.com",
1782
- "keywords": [
1783
- "dotenv",
1784
- "env",
1785
- ".env",
1786
- "environment",
1787
- "variables",
1788
- "config",
1789
- "settings"
1790
- ],
1791
- "readmeFilename": "README.md",
1792
- "license": "BSD-2-Clause",
1793
- "devDependencies": {
1794
- "@types/node": "^18.11.3",
1795
- "decache": "^4.6.2",
1796
- "sinon": "^14.0.1",
1797
- "standard": "^17.0.0",
1798
- "standard-version": "^9.5.0",
1799
- "tap": "^19.2.0",
1800
- "typescript": "^4.8.4"
1801
- },
1802
- "engines": { "node": ">=12" },
1803
- "browser": { "fs": false }
1804
- };
1805
- }));
1546
+ //#region ../sdk/src/schemas/github.ts
1547
+ const githubAppInstallationSchema = z.object({
1548
+ installation_id: z.number(),
1549
+ github_account_id: z.number(),
1550
+ github_account_login: z.string(),
1551
+ github_account_type: z.string(),
1552
+ org_id: z.string().nullable()
1553
+ });
1554
+ const githubAppInstallationAdminItemSchema = z.object({
1555
+ installation_id: z.number(),
1556
+ github_account_id: z.number(),
1557
+ github_account_login: z.string(),
1558
+ github_account_type: z.string(),
1559
+ org_id: z.string().nullable(),
1560
+ org_name: z.string().nullable(),
1561
+ installer_user_id: z.string().nullable(),
1562
+ installer_email: z.string().nullable(),
1563
+ created_at: z.string().nullable(),
1564
+ updated_at: z.string().nullable()
1565
+ });
1566
+ const githubRepositorySchema = z.object({
1567
+ repo_id: z.number(),
1568
+ repo_name: z.string(),
1569
+ public: z.boolean(),
1570
+ installation_id: z.number(),
1571
+ enabled: z.boolean().default(false)
1572
+ });
1573
+ const githubAutoReviewConfigSchema = z.object({
1574
+ enabled: z.boolean(),
1575
+ enable_for_non_linked_users: z.boolean().default(false),
1576
+ auto_incremental_review: z.boolean(),
1577
+ labels: z.array(z.string()),
1578
+ drafts: z.boolean(),
1579
+ base_branches: z.array(z.string()),
1580
+ ignore_usernames: z.array(z.string())
1581
+ });
1582
+ const githubRepoSettingsConfigSchema = z.object({
1583
+ allow_usernames: z.array(z.string()),
1584
+ auto_review: githubAutoReviewConfigSchema
1585
+ });
1586
+ const githubRepoSettingsPublicSchema = z.object({
1587
+ enabled: z.boolean(),
1588
+ config: githubRepoSettingsConfigSchema
1589
+ });
1590
+ const githubRepoSettingsUpdateSchema = z.object({
1591
+ enabled: z.boolean().optional(),
1592
+ config: githubRepoSettingsConfigSchema.optional()
1593
+ });
1806
1594
 
1807
1595
  //#endregion
1808
- //#region ../../node_modules/dotenv/lib/main.js
1809
- var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1810
- const fs = __require("fs");
1811
- const path$1 = __require("path");
1812
- const os = __require("os");
1813
- const crypto = __require("crypto");
1814
- const version = require_package().version;
1815
- const TIPS = [
1816
- "🔐 encrypt with Dotenvx: https://dotenvx.com",
1817
- "🔐 prevent committing .env to code: https://dotenvx.com/precommit",
1818
- "🔐 prevent building .env in docker: https://dotenvx.com/prebuild",
1819
- "📡 add observability to secrets: https://dotenvx.com/ops",
1820
- "👥 sync secrets across teammates & machines: https://dotenvx.com/ops",
1821
- "🗂️ backup and recover secrets: https://dotenvx.com/ops",
1822
- "✅ audit secrets and track compliance: https://dotenvx.com/ops",
1823
- "🔄 add secrets lifecycle management: https://dotenvx.com/ops",
1824
- "🔑 add access controls to secrets: https://dotenvx.com/ops",
1825
- "🛠️ run anywhere with `dotenvx run -- yourcommand`",
1826
- "⚙️ specify custom .env file path with { path: '/custom/path/.env' }",
1827
- "⚙️ enable debug logging with { debug: true }",
1828
- "⚙️ override existing env vars with { override: true }",
1829
- "⚙️ suppress all logs with { quiet: true }",
1830
- "⚙️ write to custom object with { processEnv: myObject }",
1831
- "⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"
1832
- ];
1833
- function _getRandomTip() {
1834
- return TIPS[Math.floor(Math.random() * TIPS.length)];
1835
- }
1836
- function parseBoolean(value) {
1837
- if (typeof value === "string") return ![
1838
- "false",
1839
- "0",
1840
- "no",
1841
- "off",
1842
- ""
1843
- ].includes(value.toLowerCase());
1844
- return Boolean(value);
1845
- }
1846
- function supportsAnsi() {
1847
- return process.stdout.isTTY;
1848
- }
1849
- function dim(text) {
1850
- return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text;
1851
- }
1852
- const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
1853
- function parse(src) {
1854
- const obj = {};
1855
- let lines = src.toString();
1856
- lines = lines.replace(/\r\n?/gm, "\n");
1857
- let match;
1858
- while ((match = LINE.exec(lines)) != null) {
1859
- const key = match[1];
1860
- let value = match[2] || "";
1861
- value = value.trim();
1862
- const maybeQuote = value[0];
1863
- value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
1864
- if (maybeQuote === "\"") {
1865
- value = value.replace(/\\n/g, "\n");
1866
- value = value.replace(/\\r/g, "\r");
1867
- }
1868
- obj[key] = value;
1869
- }
1870
- return obj;
1871
- }
1872
- function _parseVault(options) {
1873
- options = options || {};
1874
- const vaultPath = _vaultPath(options);
1875
- options.path = vaultPath;
1876
- const result = DotenvModule.configDotenv(options);
1877
- if (!result.parsed) {
1878
- const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
1879
- err.code = "MISSING_DATA";
1880
- throw err;
1881
- }
1882
- const keys = _dotenvKey(options).split(",");
1883
- const length = keys.length;
1884
- let decrypted;
1885
- for (let i = 0; i < length; i++) try {
1886
- const attrs = _instructions(result, keys[i].trim());
1887
- decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
1888
- break;
1889
- } catch (error) {
1890
- if (i + 1 >= length) throw error;
1891
- }
1892
- return DotenvModule.parse(decrypted);
1893
- }
1894
- function _warn(message) {
1895
- console.error(`[dotenv@${version}][WARN] ${message}`);
1896
- }
1897
- function _debug(message) {
1898
- console.log(`[dotenv@${version}][DEBUG] ${message}`);
1899
- }
1900
- function _log(message) {
1901
- console.log(`[dotenv@${version}] ${message}`);
1596
+ //#region ../sdk/src/api/organizations.ts
1597
+ const listOrganizations = defineApi(get`/api/v1/orgs?page=${"page"}&size=${"size"}`, null, paged(organizationItemSchema));
1598
+ const getOrganization = defineApi(get`/api/v1/orgs/${"orgId"}`, null, organizationSchema);
1599
+ const createOrganization = defineApi(post`/api/v1/orgs`, typeOf(), organizationSchema);
1600
+ const updateOrganization = defineApi(put`/api/v1/orgs/${"orgId"}`, typeOf(), organizationSchema);
1601
+ const deleteOrganization = defineApi(del`/api/v1/orgs/${"orgId"}`, null, organizationDeleteSchema);
1602
+ const listOrganizationMembers = defineApi(get`/api/v1/orgs/${"orgId"}/members?page=${"page"}&size=${"size"}`, null, paged(organizationMemberSchema));
1603
+ const listOrganizationInvitations = defineApi(get`/api/v1/orgs/${"orgId"}/invitations?page=${"page"}&size=${"size"}&status=${"status?"}`, null, paged(organizationInvitationSchema));
1604
+ const revokeOrganizationInvitation = defineApi(del`/api/v1/orgs/${"orgId"}/invitations/${"invitationId"}`, null, z.object({ success: z.boolean() }));
1605
+ const addOrganizationMember = defineApi(post`/api/v1/orgs/${"orgId"}/members`, typeOf(), addOrgMemberResponseSchema);
1606
+ const updateOrganizationMemberRole = defineApi(put`/api/v1/orgs/${"orgId"}/members/${"memberId"}`, typeOf(), organizationMemberSchema);
1607
+ const removeOrganizationMember = defineApi(del`/api/v1/orgs/${"orgId"}/members/${"memberId"}`, null, z.object({ success: z.boolean() }));
1608
+ const listOrganizationGithubInstallations = defineApi(get`/api/v1/orgs/${"orgId"}/github/installations`, null, z.array(githubAppInstallationSchema));
1609
+ const listOrgLinkedAccounts = defineApi(get`/api/v1/orgs/${"orgId"}/github/linked_accounts`, null, z.array(githubAppInstallationSchema));
1610
+ const listOrgLinkedRepositories = defineApi(get`/api/v1/orgs/${"orgId"}/github/linked_repositories`, null, z.array(githubRepositorySchema));
1611
+ const listOrganizationGithubRepositories = defineApi(get`/api/v1/orgs/${"orgId"}/github/installations/${"installationId"}/repos`, null, z.array(githubRepositorySchema));
1612
+ const listOrganizationProjects = defineApi(get`/api/v1/orgs/${"orgId"}/projects?page=${"page"}&size=${"size"}&query=${"query?"}&category=${"category?"}&github_source_owner_id=${"github_source_owner_id?"}&github_source_repo_id=${"github_source_repo_id?"}`, null, paged(projectSchema));
1613
+ const createOrganizationProject = defineApi(post`/api/v1/orgs/${"orgId"}/projects`, typeOf(), projectSchema);
1614
+ const getOrganizationGithubRepoSettings = defineApi(get`/api/v1/orgs/${"orgId"}/github/installations/${"installationId"}/repos/${"repoId"}/settings`, null, githubRepoSettingsPublicSchema);
1615
+ const updateOrganizationGithubRepoSettings = defineApi(put`/api/v1/orgs/${"orgId"}/github/installations/${"installationId"}/repos/${"repoId"}/settings`, typeOf(), githubRepoSettingsPublicSchema);
1616
+
1617
+ //#endregion
1618
+ //#region ../sdk/src/api/stream-proxy.ts
1619
+ const readMessageStream = defineApi(get`/ai_stream_proxy/v2/streams/${"streamId"}/stream?format=vercel-ai-ui-message-stream-v1&skip=${"skip?"}`, null, projectMessageStreamParser);
1620
+ const readRawMessageStream = defineApi(get`/ai_stream_proxy/v2/streams/${"streamId"}/stream?format=opaque-stream-json`, null, projectRawMessageStreamParser);
1621
+
1622
+ //#endregion
1623
+ //#region ../sdk/src/schemas/api-key.ts
1624
+ const publicApiKeySchema = z.object({
1625
+ id: z.union([z.string(), z.number()]).transform(String),
1626
+ description: z.string().nullable().optional(),
1627
+ api_key_display: z.string(),
1628
+ created_at: zodJsonDate,
1629
+ updated_at: zodJsonDate.optional(),
1630
+ is_active: z.boolean(),
1631
+ user_id: z.string()
1632
+ });
1633
+ const apiKeyCreateRequestSchema = z.object({ description: z.string() });
1634
+ const apiKeyCreateResponseSchema = publicApiKeySchema.extend({ api_key: z.string() });
1635
+
1636
+ //#endregion
1637
+ //#region ../sdk/src/api/user-api-keys.ts
1638
+ const listUserApiKeys = defineApi(get`/api/v1/user/api-keys?page=${"page"}&size=${"size"}`, null, paged(publicApiKeySchema));
1639
+ const createUserApiKey = defineApi(post`/api/v1/user/api-keys`, typeOf(), apiKeyCreateResponseSchema);
1640
+ const deleteUserApiKey = defineApi(del`/api/v1/user/api-keys/${"apiKeyId"}`, null, "raw");
1641
+
1642
+ //#endregion
1643
+ //#region ../sdk/src/lib/api-executor.ts
1644
+ var ApiError = class extends Error {
1645
+ response;
1646
+ context;
1647
+ responseBody;
1648
+ constructor(response, context, responseBody) {
1649
+ super(`${context.request.method} ${context.url}: ${response.status} ${response.statusText} ${getServerErrorMessage(responseBody)}`);
1650
+ this.response = response;
1651
+ this.context = context;
1652
+ this.responseBody = responseBody;
1902
1653
  }
1903
- function _dotenvKey(options) {
1904
- if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
1905
- if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
1906
- return "";
1654
+ };
1655
+ function createApiExecutor({ baseUrl, headers, validateResponse }) {
1656
+ const errorCallbacks = [];
1657
+ function onError(callback) {
1658
+ errorCallbacks.push(callback);
1659
+ return () => {
1660
+ const index = errorCallbacks.indexOf(callback);
1661
+ if (index !== -1) errorCallbacks.splice(index, 1);
1662
+ };
1907
1663
  }
1908
- function _instructions(result, dotenvKey) {
1909
- let uri;
1664
+ async function execute(api, params, requestBody, requestInit) {
1665
+ const url = baseUrl ? new URL(api.url(params), baseUrl).toString() : api.url(params);
1666
+ const { headers: initHeaders, ...init } = api.requestInit(requestBody);
1667
+ const executorHeaders = new Headers(headers);
1668
+ if (initHeaders) new Headers(initHeaders).forEach((value, key) => {
1669
+ executorHeaders.set(key, value);
1670
+ });
1671
+ const request = new Request(url, {
1672
+ ...requestInit,
1673
+ ...init,
1674
+ headers: executorHeaders,
1675
+ credentials: "include"
1676
+ });
1677
+ const context = Object.freeze({
1678
+ api,
1679
+ params,
1680
+ requestBody,
1681
+ url,
1682
+ request
1683
+ });
1910
1684
  try {
1911
- uri = new URL(dotenvKey);
1685
+ const response = await fetch(request);
1686
+ await validateResponse(response, context);
1687
+ return await api.handleResponse(response, context);
1912
1688
  } catch (error) {
1913
- if (error.code === "ERR_INVALID_URL") {
1914
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
1915
- err.code = "INVALID_DOTENV_KEY";
1916
- throw err;
1917
- }
1918
- throw error;
1919
- }
1920
- const key = uri.password;
1921
- if (!key) {
1922
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
1923
- err.code = "INVALID_DOTENV_KEY";
1924
- throw err;
1925
- }
1926
- const environment = uri.searchParams.get("environment");
1927
- if (!environment) {
1928
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
1929
- err.code = "INVALID_DOTENV_KEY";
1930
- throw err;
1689
+ for (const callback of errorCallbacks) callback(error, context);
1690
+ return Promise.reject(error);
1931
1691
  }
1932
- const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
1933
- const ciphertext = result.parsed[environmentKey];
1934
- if (!ciphertext) {
1935
- const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
1936
- err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
1937
- throw err;
1692
+ }
1693
+ return Object.freeze({
1694
+ execute,
1695
+ onError
1696
+ });
1697
+ }
1698
+ async function validateResponse(response, context) {
1699
+ if (!response.ok) throw new ApiError(response, context, await response.clone().json().catch(() => response.clone().text()).catch(() => void 0));
1700
+ }
1701
+ function getServerErrorMessage(error) {
1702
+ if (error == null) return "No error message.";
1703
+ if (typeof error === "string") return error;
1704
+ if (typeof error === "object") {
1705
+ for (const key of [
1706
+ "message",
1707
+ "error",
1708
+ "errMsg",
1709
+ "errorMsg",
1710
+ "detail",
1711
+ "details"
1712
+ ]) if (key in error) if (typeof error[key] === "string") return error[key];
1713
+ else return JSON.stringify(error[key], void 0, 2);
1714
+ return JSON.stringify(error, void 0, 2);
1715
+ }
1716
+ return String(error);
1717
+ }
1718
+
1719
+ //#endregion
1720
+ //#region src/core/pantheon.ts
1721
+ const executor = createApiExecutor({
1722
+ baseUrl: "https://pantheon-ai.tidb.ai",
1723
+ headers: { Authorization: `Bearer ${process.env.PANTHEON_API_KEY}` },
1724
+ validateResponse
1725
+ });
1726
+ async function getPantheonProjectInfo({ projectId }) {
1727
+ return await executor.execute(getProject, { projectId }, null);
1728
+ }
1729
+ async function getPantheonBranch({ projectId, branchId, getOutputIfFinished = false, manifestingAsSucceed = false }) {
1730
+ const branch = await executor.execute(getProjectBranch, {
1731
+ projectId,
1732
+ branchId
1733
+ }, null);
1734
+ if (branch.status === "succeed" || manifestingAsSucceed && (branch.status === "manifesting" || branch.status === "ready_for_manifest")) if (getOutputIfFinished) return {
1735
+ state: "succeed",
1736
+ output: await executor.execute(getProjectBranchOutput, {
1737
+ projectId,
1738
+ branchId,
1739
+ fullOutput: true
1740
+ }, null)
1741
+ };
1742
+ else return { state: "succeed" };
1743
+ else if (branch.status === "failed") {
1744
+ let error = branch.latest_snap?.error;
1745
+ if (!error) {
1746
+ error = await executor.execute(getProjectBranchOutput, {
1747
+ projectId,
1748
+ branchId,
1749
+ fullOutput: true
1750
+ }, null);
1751
+ error = `No error message, the latest output:\n\n${error}`;
1938
1752
  }
1939
1753
  return {
1940
- ciphertext,
1941
- key
1754
+ state: "failed",
1755
+ error
1942
1756
  };
1943
1757
  }
1944
- function _vaultPath(options) {
1945
- let possibleVaultPath = null;
1946
- if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
1947
- for (const filepath of options.path) if (fs.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
1948
- } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
1949
- else possibleVaultPath = path$1.resolve(process.cwd(), ".env.vault");
1950
- if (fs.existsSync(possibleVaultPath)) return possibleVaultPath;
1951
- return null;
1758
+ return { state: "others" };
1759
+ }
1760
+ async function executeOnPantheon({ projectId, branchId, prompt, agent }) {
1761
+ return (await executor.execute(createProjectExploration, { projectId }, {
1762
+ shared_prompt_sequence: [prompt],
1763
+ num_branches: 1,
1764
+ agent,
1765
+ parent_branch_id: branchId
1766
+ })).branches[0].branch_id;
1767
+ }
1768
+
1769
+ //#endregion
1770
+ //#region src/core/task-list.ts
1771
+ async function startTaskListLoop(agentName, { loopInterval = 5 }, logger) {
1772
+ logger.info("Starting task list loop...");
1773
+ let i = 0;
1774
+ const abortController = new AbortController();
1775
+ let sleepTimeout;
1776
+ process.on("SIGINT", (signal) => {
1777
+ logger.info(`Received ${signal}, shutting down gracefully...`);
1778
+ clearTimeout(sleepTimeout);
1779
+ abortController.abort(signal);
1780
+ });
1781
+ process.on("SIGTERM", (signal) => {
1782
+ logger.info(`Received ${signal}, force shutting down...`);
1783
+ clearTimeout(sleepTimeout);
1784
+ abortController.abort(signal);
1785
+ process.exit(1);
1786
+ });
1787
+ const provider = new TaskListTidbProvider(agentName, logger);
1788
+ while (!abortController.signal.aborted) {
1789
+ await loopOnce(provider, logger.child({ name: `loop:${i++}` }));
1790
+ await new Promise((resolve) => {
1791
+ abortController.signal.addEventListener("abort", resolve);
1792
+ sleepTimeout = setTimeout(() => {
1793
+ abortController.signal.removeEventListener("abort", resolve);
1794
+ resolve(false);
1795
+ }, loopInterval * 1e3);
1796
+ });
1952
1797
  }
1953
- function _resolveHome(envPath) {
1954
- return envPath[0] === "~" ? path$1.join(os.homedir(), envPath.slice(1)) : envPath;
1798
+ await provider.close();
1799
+ process.exit(0);
1800
+ }
1801
+ async function loopOnce(provider, logger) {
1802
+ logger.info("Loop start.");
1803
+ const tasks = await provider.getTasks({ status: ["pending", "running"] });
1804
+ const runningTasks = tasks.filter((task) => task.status === "running");
1805
+ const pendingTasks = tasks.filter((task) => task.status === "pending");
1806
+ logger.info(`Found ${tasks.length} tasks, ${runningTasks.length} running, ${pendingTasks.length} pending.`);
1807
+ if (runningTasks.length > 1) logger.warn("More than one task is running, this is not expected. %o", runningTasks.map((task) => task.id));
1808
+ const nextTask = pendingTasks[0];
1809
+ if (runningTasks.length > 0) {
1810
+ if ((await Promise.allSettled(runningTasks.map(async (task) => {
1811
+ await pollRunningTaskState(provider, task, logger.child({ name: `task:${task.id}:poll` }));
1812
+ }))).some((result) => result.status === "rejected")) logger.warn("Failed to poll state for one or more running tasks");
1813
+ } else if (nextTask) try {
1814
+ await startPendingTask(provider, pendingTasks[0], logger.child({ name: `task:${nextTask.id}:start` }));
1815
+ } catch (e) {
1816
+ logger.error(`Failed to start task ${nextTask.id}: ${getErrorMessage(e)}`);
1955
1817
  }
1956
- function _configVault(options) {
1957
- const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
1958
- const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
1959
- if (debug || !quiet) _log("Loading env from encrypted .env.vault");
1960
- const parsed = DotenvModule._parseVault(options);
1961
- let processEnv = process.env;
1962
- if (options && options.processEnv != null) processEnv = options.processEnv;
1963
- DotenvModule.populate(processEnv, parsed, options);
1964
- return { parsed };
1818
+ else logger.info("No tasks to process.");
1819
+ }
1820
+ async function pollRunningTaskState(provider, state, logger) {
1821
+ const newStatus = await getPantheonBranch({
1822
+ projectId: state.project_id,
1823
+ branchId: state.branch_id,
1824
+ getOutputIfFinished: true
1825
+ });
1826
+ if (newStatus.state === "succeed") {
1827
+ logger.info("Task completed with output: %s", newStatus.output);
1828
+ await provider.completeTask(state, newStatus.output || "(no output)");
1829
+ } else if (newStatus.state === "failed") {
1830
+ logger.info("Task failed with error: %s", newStatus.error);
1831
+ await provider.failTask(state, newStatus.error);
1832
+ } else logger.info("Task is still pending");
1833
+ }
1834
+ async function startPendingTask(provider, task, logger) {
1835
+ const config = await provider.getAgentConfig(task.project_id);
1836
+ if (!config) {
1837
+ logger.warn("Agent configuration not found for project %s. Skip starting tasks.", task.project_id);
1838
+ return;
1839
+ }
1840
+ await provider.startTask(task, async () => {
1841
+ return await executeOnPantheon({
1842
+ projectId: task.project_id,
1843
+ branchId: task.base_branch_id,
1844
+ prompt: task.task,
1845
+ agent: config.execute_agent
1846
+ });
1847
+ });
1848
+ logger.info(`Task ${task.id} started successfully.`);
1849
+ }
1850
+
1851
+ //#endregion
1852
+ //#region src/core/index.ts
1853
+ async function runAgent(name, options, logger) {
1854
+ const agentDir = path.join(options.dataDir, "agents", name);
1855
+ const pidFile = path.join(agentDir, "pid");
1856
+ await fs.promises.mkdir(agentDir, { recursive: true });
1857
+ await assertsSingleton(logger, pidFile);
1858
+ await startTaskListLoop(name, { loopInterval: options.loopInterval }, logger);
1859
+ }
1860
+ async function configAgent(name, options) {
1861
+ const provider = new TaskListTidbProvider(name, pino());
1862
+ const previousConfig = await provider.getAgentConfig(options.projectId);
1863
+ if (previousConfig) if (previousConfig.role === options.role) {
1864
+ console.log(`Agent ${name} already configured as ${options.role} for project ${options.projectId}.`);
1865
+ console.log(`Base branch id: ${previousConfig.base_branch_id}`);
1866
+ await provider.close();
1867
+ return;
1868
+ } else {
1869
+ console.error(`Agent ${name} already configured as ${previousConfig.role} for project ${options.projectId}.`);
1870
+ console.error(`Base branch id: ${previousConfig.base_branch_id}`);
1871
+ console.error(`Cannot change role to ${options.role}`);
1872
+ await provider.close();
1873
+ process.exitCode = 1;
1874
+ return;
1965
1875
  }
1966
- function configDotenv(options) {
1967
- const dotenvPath = path$1.resolve(process.cwd(), ".env");
1968
- let encoding = "utf8";
1969
- let processEnv = process.env;
1970
- if (options && options.processEnv != null) processEnv = options.processEnv;
1971
- let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
1972
- let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
1973
- if (options && options.encoding) encoding = options.encoding;
1974
- else if (debug) _debug("No encoding is specified. UTF-8 is used by default");
1975
- let optionPaths = [dotenvPath];
1976
- if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
1977
- else {
1978
- optionPaths = [];
1979
- for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
1980
- }
1981
- let lastError;
1982
- const parsedAll = {};
1983
- for (const path of optionPaths) try {
1984
- const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }));
1985
- DotenvModule.populate(parsedAll, parsed, options);
1986
- } catch (e) {
1987
- if (debug) _debug(`Failed to load ${path} ${e.message}`);
1988
- lastError = e;
1876
+ console.log(`Configuring agent ${name} as ${options.role} for project ${options.projectId}.`);
1877
+ if (!options.rootBranchId) {
1878
+ console.log("No root branch id specified, using project root branch.");
1879
+ const project = await getPantheonProjectInfo({ projectId: options.projectId });
1880
+ if (!project.root_branch_id) {
1881
+ console.error(`Project ${options.projectId} has no root branch. Project status is ${project.status}`);
1882
+ await provider.close();
1883
+ process.exitCode = 1;
1884
+ return;
1989
1885
  }
1990
- const populated = DotenvModule.populate(processEnv, parsedAll, options);
1991
- debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
1992
- quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
1993
- if (debug || !quiet) {
1994
- const keysCount = Object.keys(populated).length;
1995
- const shortPaths = [];
1996
- for (const filePath of optionPaths) try {
1997
- const relative = path$1.relative(process.cwd(), filePath);
1998
- shortPaths.push(relative);
1999
- } catch (e) {
2000
- if (debug) _debug(`Failed to load ${filePath} ${e.message}`);
2001
- lastError = e;
1886
+ options.rootBranchId = project.root_branch_id;
1887
+ }
1888
+ if (options.bootstrap) {
1889
+ const branchId = await executeOnPantheon({
1890
+ projectId: options.projectId,
1891
+ branchId: options.rootBranchId,
1892
+ agent: "codex",
1893
+ prompt: `You must follow these instructions to setup base branch for agent role "${options.role}":
1894
+ 1. Clone the main branch from https://github.com/pingcap-inc/pantheon-agents to a temporary directory.
1895
+ 2. Copy the pantheon-agents/roles/${options.role}/AGENTS.md to \`<workspace>/AGENTS.md\`.
1896
+ 3. Copy the pantheon-agents/roles/${options.role}/skills directory to \`<workspace>/.codex/skills\` if exists.
1897
+ ${options.skills.length > 0 ? `4. Copy the pantheon-agents/skills/\{${options.skills.join(",")}} directory to \`<workspace>/.codex/skills/\`` : ""}
1898
+
1899
+ Validate <workspace>: check if files and directorys exists:
1900
+ - AGENTS.md
1901
+ - .codex/skills
1902
+
1903
+ **You MUST NOT generate AGENTS.md and skills by yourself if clone failed.**
1904
+ `
1905
+ });
1906
+ let retried = 0;
1907
+ const maxRetries = 3;
1908
+ let i = 0;
1909
+ console.log(`Bootstrap branch created: ${branchId}. Waiting for ready... [poll interval = 10s]`);
1910
+ while (true) {
1911
+ await new Promise((resolve) => {
1912
+ setTimeout(resolve, 1e4);
1913
+ });
1914
+ const result = await getPantheonBranch({
1915
+ branchId,
1916
+ projectId: options.projectId,
1917
+ getOutputIfFinished: true
1918
+ }).then((result) => {
1919
+ retried = 0;
1920
+ return result;
1921
+ }).catch((reason) => {
1922
+ if (retried < maxRetries) {
1923
+ retried++;
1924
+ return { state: "others" };
1925
+ } else throw new Error(`Failed to get bootstrap branch status. Retry ${retried} times. Last error: ${getErrorMessage(reason)}`);
1926
+ });
1927
+ if (result.state === "failed") {
1928
+ console.error("Bootstrap failed: " + result.error);
1929
+ await provider.close();
1930
+ process.exit(1);
2002
1931
  }
2003
- _log(`injecting env (${keysCount}) from ${shortPaths.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`);
1932
+ if (result.state === "succeed") {
1933
+ console.log("Bootstrap succeeded. Output is:");
1934
+ console.log(result.output);
1935
+ break;
1936
+ }
1937
+ console.log(`Bootstrap in progress... [${++i}]`);
2004
1938
  }
2005
- if (lastError) return {
2006
- parsed: parsedAll,
2007
- error: lastError
2008
- };
2009
- else return { parsed: parsedAll };
1939
+ await provider.setAgentConfig({
1940
+ project_id: options.projectId,
1941
+ base_branch_id: branchId,
1942
+ execute_agent: options.executeAgent,
1943
+ role: options.role,
1944
+ skills: options.skills,
1945
+ prototype_url: "https://github.com/pingcap-inc/pantheon-agents"
1946
+ });
1947
+ } else await provider.setAgentConfig({
1948
+ project_id: options.projectId,
1949
+ base_branch_id: options.rootBranchId,
1950
+ execute_agent: options.executeAgent,
1951
+ role: options.role,
1952
+ skills: options.skills,
1953
+ prototype_url: "https://github.com/pingcap-inc/pantheon-agents"
1954
+ });
1955
+ console.log(`Agent ${name} configured successfully.`);
1956
+ await provider.close();
1957
+ }
1958
+ async function addTask(name, options) {
1959
+ const provider = new TaskListTidbProvider(name, pino());
1960
+ const config = await provider.getAgentConfig(options.projectId);
1961
+ if (!config) throw new Error(`Agent ${name} not configured for project ${options.projectId}`);
1962
+ const task = await provider.createTask({
1963
+ task: options.prompt,
1964
+ project_id: options.projectId,
1965
+ base_branch_id: config.base_branch_id
1966
+ });
1967
+ console.log(`Task ${task.task} queued successfully.`);
1968
+ await provider.close();
1969
+ }
1970
+ async function deleteTask(agentName, taskId) {
1971
+ const provider = new TaskListTidbProvider(agentName, pino());
1972
+ try {
1973
+ const task = await provider.getTask(taskId);
1974
+ if (!task) return null;
1975
+ if (!await provider.deleteTask(taskId)) return null;
1976
+ return task;
1977
+ } finally {
1978
+ await provider.close();
2010
1979
  }
2011
- function config(options) {
2012
- if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
2013
- const vaultPath = _vaultPath(options);
2014
- if (!vaultPath) {
2015
- _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
2016
- return DotenvModule.configDotenv(options);
2017
- }
2018
- return DotenvModule._configVault(options);
1980
+ }
1981
+ async function showAgentConfig(agentName, projectId) {
1982
+ const provider = new TaskListTidbProvider(agentName, pino());
1983
+ try {
1984
+ return await provider.getAgentConfig(projectId);
1985
+ } finally {
1986
+ await provider.close();
2019
1987
  }
2020
- function decrypt(encrypted, keyStr) {
2021
- const key = Buffer.from(keyStr.slice(-64), "hex");
2022
- let ciphertext = Buffer.from(encrypted, "base64");
2023
- const nonce = ciphertext.subarray(0, 12);
2024
- const authTag = ciphertext.subarray(-16);
2025
- ciphertext = ciphertext.subarray(12, -16);
2026
- try {
2027
- const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
2028
- aesgcm.setAuthTag(authTag);
2029
- return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
2030
- } catch (error) {
2031
- const isRange = error instanceof RangeError;
2032
- const invalidKeyLength = error.message === "Invalid key length";
2033
- const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
2034
- if (isRange || invalidKeyLength) {
2035
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
2036
- err.code = "INVALID_DOTENV_KEY";
2037
- throw err;
2038
- } else if (decryptionFailed) {
2039
- const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
2040
- err.code = "DECRYPTION_FAILED";
2041
- throw err;
2042
- } else throw error;
2043
- }
1988
+ }
1989
+ async function showAgentConfigs(agentName) {
1990
+ const provider = new TaskListTidbProvider(agentName, pino());
1991
+ try {
1992
+ return await provider.getAgentConfigs();
1993
+ } finally {
1994
+ await provider.close();
2044
1995
  }
2045
- function populate(processEnv, parsed, options = {}) {
2046
- const debug = Boolean(options && options.debug);
2047
- const override = Boolean(options && options.override);
2048
- const populated = {};
2049
- if (typeof parsed !== "object") {
2050
- const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
2051
- err.code = "OBJECT_REQUIRED";
2052
- throw err;
2053
- }
2054
- for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
2055
- if (override === true) {
2056
- processEnv[key] = parsed[key];
2057
- populated[key] = parsed[key];
2058
- }
2059
- if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
2060
- else _debug(`"${key}" is already defined and was NOT overwritten`);
2061
- } else {
2062
- processEnv[key] = parsed[key];
2063
- populated[key] = parsed[key];
2064
- }
2065
- return populated;
1996
+ }
1997
+ async function showTasks(name, options) {
1998
+ const provider = new TaskListTidbProvider(name, pino());
1999
+ try {
2000
+ return await provider.getTasks({
2001
+ status: options.status,
2002
+ order_by: options.orderBy,
2003
+ order_direction: options.orderDirection
2004
+ });
2005
+ } finally {
2006
+ await provider.close();
2007
+ }
2008
+ }
2009
+ async function listAgentNames() {
2010
+ const provider = new TaskListTidbProvider("list-agents", pino());
2011
+ try {
2012
+ return await provider.listAgentNames();
2013
+ } finally {
2014
+ await provider.close();
2015
+ }
2016
+ }
2017
+ async function showTasksForAgents(options) {
2018
+ const selectedAgents = options.allAgents ? await listAgentNames() : options.agents;
2019
+ const tasksWithAgent = await Promise.all(selectedAgents.map(async (agent) => {
2020
+ return (await showTasks(agent, {
2021
+ status: options.status,
2022
+ orderBy: options.orderBy,
2023
+ orderDirection: options.orderDirection
2024
+ })).map((task) => ({
2025
+ agent,
2026
+ task
2027
+ }));
2028
+ })).then((groups) => groups.flat());
2029
+ const orderKey = options.orderBy ?? "queued_at";
2030
+ const orderDirection = options.orderDirection ?? "desc";
2031
+ tasksWithAgent.sort((a, b) => {
2032
+ const aValue = a.task[orderKey];
2033
+ const bValue = b.task[orderKey];
2034
+ const aTime = aValue instanceof Date ? aValue.getTime() : 0;
2035
+ const bTime = bValue instanceof Date ? bValue.getTime() : 0;
2036
+ return orderDirection === "asc" ? aTime - bTime : bTime - aTime;
2037
+ });
2038
+ if (options.limit != null) return tasksWithAgent.slice(0, options.limit);
2039
+ return tasksWithAgent;
2040
+ }
2041
+ function formatRelativeTime(value) {
2042
+ if (!value) return "";
2043
+ const diffMs = Date.now() - value.getTime();
2044
+ const absMs = Math.abs(diffMs);
2045
+ const tense = diffMs >= 0 ? "ago" : "from now";
2046
+ const seconds = Math.floor(absMs / 1e3);
2047
+ const minutes = Math.floor(seconds / 60);
2048
+ const hours = Math.floor(minutes / 60);
2049
+ const days = Math.floor(hours / 24);
2050
+ if (days > 0) return `${days}d ${tense}`;
2051
+ if (hours > 0) return `${hours}h ${tense}`;
2052
+ if (minutes > 0) return `${minutes}m ${tense}`;
2053
+ return `${seconds}s ${tense}`;
2054
+ }
2055
+ function formatDate(value) {
2056
+ return value ? value.toISOString() : "";
2057
+ }
2058
+ function truncateText(value, maxLength) {
2059
+ if (value.length <= maxLength) return value;
2060
+ return `${value.slice(0, Math.max(0, maxLength - 1))}…`;
2061
+ }
2062
+ function colorText(value, colorCode) {
2063
+ return `\u001b[${colorCode}m${value}\u001b[0m`;
2064
+ }
2065
+ function formatStatus(status, useColor) {
2066
+ if (!useColor) return status;
2067
+ switch (status) {
2068
+ case "pending": return colorText(status, 33);
2069
+ case "running": return colorText(status, 36);
2070
+ case "completed": return colorText(status, 32);
2071
+ case "failed": return colorText(status, 31);
2072
+ case "cancelled": return colorText(status, 90);
2066
2073
  }
2067
- const DotenvModule = {
2068
- configDotenv,
2069
- _configVault,
2070
- _parseVault,
2071
- config,
2072
- decrypt,
2073
- parse,
2074
- populate
2074
+ }
2075
+ function formatConciseTaskLine(options) {
2076
+ const { agent, task, maxTaskLength, useColor } = options;
2077
+ let timestamp = task.queued_at;
2078
+ if (task.status === "running") timestamp = task.started_at;
2079
+ if (task.status === "completed" || task.status === "failed") timestamp = task.ended_at;
2080
+ if (task.status === "cancelled") timestamp = task.cancelled_at ?? task.queued_at;
2081
+ const statusText = formatStatus(task.status, useColor);
2082
+ const timeText = formatRelativeTime(timestamp);
2083
+ const taskText = truncateText(task.task, maxTaskLength);
2084
+ return [
2085
+ agent,
2086
+ statusText,
2087
+ task.id,
2088
+ timeText,
2089
+ taskText
2090
+ ].filter((part) => part !== "").join(" ");
2091
+ }
2092
+ function formatTaskTableRow(options) {
2093
+ const { agent, task, maxTaskLength } = options;
2094
+ const branchId = "branch_id" in task ? task.branch_id ?? "" : "";
2095
+ const startedAt = "started_at" in task ? task.started_at : void 0;
2096
+ const endedAt = "ended_at" in task ? task.ended_at : void 0;
2097
+ return {
2098
+ agent,
2099
+ id: task.id,
2100
+ status: task.status,
2101
+ project_id: task.project_id,
2102
+ branch_id: branchId,
2103
+ queued_at: formatDate(task.queued_at),
2104
+ started_at: formatDate(startedAt),
2105
+ ended_at: formatDate(endedAt),
2106
+ task: truncateText(task.task, maxTaskLength)
2075
2107
  };
2076
- module.exports.configDotenv = DotenvModule.configDotenv;
2077
- module.exports._configVault = DotenvModule._configVault;
2078
- module.exports._parseVault = DotenvModule._parseVault;
2079
- module.exports.config = DotenvModule.config;
2080
- module.exports.decrypt = DotenvModule.decrypt;
2081
- module.exports.parse = DotenvModule.parse;
2082
- module.exports.populate = DotenvModule.populate;
2083
- module.exports = DotenvModule;
2084
- }));
2108
+ }
2109
+ async function assertsSingleton(logger, pidFile) {
2110
+ try {
2111
+ const pid = await fs.promises.readFile(pidFile, "utf-8");
2112
+ process.kill(parseInt(pid), 0);
2113
+ console.error("Failed to assert singleton agent process:");
2114
+ process.exit(1);
2115
+ } catch (e) {
2116
+ await fs.promises.writeFile(pidFile, process.pid.toString());
2117
+ process.on("exit", () => {
2118
+ fs.promises.rm(pidFile);
2119
+ });
2120
+ }
2121
+ }
2085
2122
 
2086
2123
  //#endregion
2087
- //#region ../../node_modules/dotenv/lib/env-options.js
2088
- var require_env_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2089
- const options = {};
2090
- if (process.env.DOTENV_CONFIG_ENCODING != null) options.encoding = process.env.DOTENV_CONFIG_ENCODING;
2091
- if (process.env.DOTENV_CONFIG_PATH != null) options.path = process.env.DOTENV_CONFIG_PATH;
2092
- if (process.env.DOTENV_CONFIG_QUIET != null) options.quiet = process.env.DOTENV_CONFIG_QUIET;
2093
- if (process.env.DOTENV_CONFIG_DEBUG != null) options.debug = process.env.DOTENV_CONFIG_DEBUG;
2094
- if (process.env.DOTENV_CONFIG_OVERRIDE != null) options.override = process.env.DOTENV_CONFIG_OVERRIDE;
2095
- if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
2096
- module.exports = options;
2097
- }));
2124
+ //#region src/cli/commands/add-task.ts
2125
+ function createAddTaskCommand(version) {
2126
+ return createCommand("pantheon-agents add-task").version(version).description("Add a task to an agent").argument("<name>", "The name of the agent.").argument("<project-id>", "The project id of the agent.").argument("<task-prompt>", "The prompt of the task.").action(async function() {
2127
+ const [name, projectId, taskPrompt] = this.args;
2128
+ await addTask(name, {
2129
+ projectId,
2130
+ prompt: taskPrompt
2131
+ });
2132
+ });
2133
+ }
2098
2134
 
2099
2135
  //#endregion
2100
- //#region ../../node_modules/dotenv/lib/cli-options.js
2101
- var require_cli_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2102
- const re = /^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;
2103
- module.exports = function optionMatcher(args) {
2104
- const options = args.reduce(function(acc, cur) {
2105
- const matches = cur.match(re);
2106
- if (matches) acc[matches[1]] = matches[2];
2107
- return acc;
2108
- }, {});
2109
- if (!("quiet" in options)) options.quiet = "true";
2110
- return options;
2111
- };
2112
- }));
2136
+ //#region src/cli/commands/config.ts
2137
+ function createConfigAgentCommand(version) {
2138
+ return createCommand("pantheon-agents config").version(version).description("Configure agent for pantheon project").argument("<name>", "The name of the agent.").argument("<role>", "The role of the agent.").argument("<project-id>", "The project id of the agent.").option("--skills <skills>", "The skills of the agent. Multiple values are separated by comma.", (val) => val.split(",").map((s) => s.trim()).filter((s) => s !== ""), []).option("--execute-agent <agent>", "The execute agent of the agent.", "codex").option("--root-branch-id <branchId>", "The root branch id of the agent. Default to project root branch id.").option("--no-bootstrap", "Prevent bootstrap base branch for agent. Use the root branch as base branch.").action(async function() {
2139
+ const [name, role, projectId] = this.args;
2140
+ await configAgent(name, {
2141
+ role,
2142
+ projectId,
2143
+ ...this.opts()
2144
+ });
2145
+ });
2146
+ }
2113
2147
 
2114
2148
  //#endregion
2115
- //#region ../../node_modules/dotenv/config.js
2116
- (function() {
2117
- require_main().config(Object.assign({}, require_env_options(), require_cli_options()(process.argv)));
2118
- })();
2149
+ //#region src/cli/commands/delete-task.ts
2150
+ function createDeleteTaskCommand(version) {
2151
+ return createCommand("pantheon-agents delete-task").version(version).description("Delete a task for an agent").argument("<name>", "The name of the agent.").argument("<task-id>", "The id of the task.").action(async function() {
2152
+ const [name, taskId] = this.args;
2153
+ const rl = readline.createInterface({
2154
+ input: process$1.stdin,
2155
+ output: process$1.stdout
2156
+ });
2157
+ try {
2158
+ if ((await rl.question(`Type the task id (${taskId}) to confirm deletion: `)).trim() !== taskId) {
2159
+ console.error("Confirmation failed. Task id did not match.");
2160
+ process$1.exit(1);
2161
+ }
2162
+ if ((await rl.question("Type DELETE to permanently remove this task: ")).trim() !== "DELETE") {
2163
+ console.error("Confirmation failed. Aborting deletion.");
2164
+ process$1.exit(1);
2165
+ }
2166
+ const deletedTask = await deleteTask(name, taskId);
2167
+ if (!deletedTask) {
2168
+ console.error(`Task ${taskId} not found for agent ${name}.`);
2169
+ process$1.exit(1);
2170
+ }
2171
+ console.log(`Deleted task ${taskId} for agent ${name}. Status was ${deletedTask.status}.`);
2172
+ } finally {
2173
+ rl.close();
2174
+ }
2175
+ });
2176
+ }
2119
2177
 
2120
2178
  //#endregion
2121
- //#region package.json
2122
- var version = "0.0.6";
2179
+ //#region src/cli/commands/run.ts
2180
+ function createRunAgentCommand(version) {
2181
+ return createCommand("pantheon-agents run").version(version).description("Start a pantheon agents").argument("<name>", "The name of the agent.").option("--data-dir [dir]", "Data directory.", expandTilde("~/.pantheon-agents")).option("--mcp-port", "The port of the MCP server. Defaults to a random port.").option("--loop-interval <seconds>", "The interval of the loop in seconds. Defaults to 5.", (val) => parseInt(val, 10), 5).action(async function() {
2182
+ const [name] = this.args;
2183
+ const options = this.opts();
2184
+ const logFileTransport = transport({
2185
+ target: "pino-roll",
2186
+ options: {
2187
+ file: path.join(options.dataDir, "agents", name, "logs", "log"),
2188
+ frequency: "daily",
2189
+ mkdir: true
2190
+ }
2191
+ });
2192
+ const prettyTransport = transport({
2193
+ target: "pino-pretty",
2194
+ options: {
2195
+ colorize: true,
2196
+ ignore: "pid,hostname,level-label"
2197
+ }
2198
+ });
2199
+ await runAgent(name, options, pino({
2200
+ timestamp: pino.stdTimeFunctions.isoTime,
2201
+ formatters: { level(label) {
2202
+ return { level: label.toUpperCase() };
2203
+ } }
2204
+ }, multistream([{ stream: logFileTransport }, { stream: prettyTransport }])));
2205
+ });
2206
+ }
2123
2207
 
2124
2208
  //#endregion
2125
- //#region src/cli/index.ts
2209
+ //#region src/cli/commands/show-config.ts
2210
+ function createShowConfigCommand(version) {
2211
+ return createCommand("pantheon-agents show-config").version(version).description("Show agent config for a project").argument("<name>", "The name of the agent.").argument("[project-id]", "The project id.").option("--json", "Output config as JSON.").action(async function() {
2212
+ const [name, projectId] = this.args;
2213
+ const options = this.opts();
2214
+ if (projectId) {
2215
+ const config = await showAgentConfig(name, projectId);
2216
+ if (!config) {
2217
+ console.error(`No config found for agent ${name} and project ${projectId}.`);
2218
+ process$1.exit(1);
2219
+ }
2220
+ if (options.json) {
2221
+ console.log(JSON.stringify(config, null, 2));
2222
+ return;
2223
+ }
2224
+ console.table([{
2225
+ agent: config.agent,
2226
+ project_id: config.project_id,
2227
+ base_branch_id: config.base_branch_id,
2228
+ role: config.role,
2229
+ execute_agent: config.execute_agent,
2230
+ prototype_url: config.prototype_url,
2231
+ skills: Array.isArray(config.skills) ? config.skills.join(", ") : String(config.skills)
2232
+ }]);
2233
+ return;
2234
+ }
2235
+ const configs = await showAgentConfigs(name);
2236
+ if (!configs.length) {
2237
+ console.error(`No configs found for agent ${name}.`);
2238
+ process$1.exit(1);
2239
+ }
2240
+ if (options.json) {
2241
+ console.log(JSON.stringify(configs, null, 2));
2242
+ return;
2243
+ }
2244
+ console.table(configs.map((config) => ({
2245
+ agent: config.agent,
2246
+ project_id: config.project_id,
2247
+ base_branch_id: config.base_branch_id,
2248
+ role: config.role,
2249
+ execute_agent: config.execute_agent,
2250
+ prototype_url: config.prototype_url,
2251
+ skills: Array.isArray(config.skills) ? config.skills.join(", ") : String(config.skills)
2252
+ })));
2253
+ });
2254
+ }
2255
+
2256
+ //#endregion
2257
+ //#region src/cli/constants.ts
2126
2258
  const taskStatuses = [
2127
2259
  "pending",
2128
2260
  "running",
@@ -2136,205 +2268,113 @@ const orderByFields = [
2136
2268
  "ended_at"
2137
2269
  ];
2138
2270
  const orderDirections = ["asc", "desc"];
2271
+
2272
+ //#endregion
2273
+ //#region src/cli/utils/parse.ts
2139
2274
  function parseCommaList(value) {
2140
2275
  return value.split(",").map((item) => item.trim()).filter((item) => item !== "");
2141
2276
  }
2142
- if (!process$1.env.PANTHEON_API_KEY) console.error("PANTHEON_API_KEY environment variable is not set.");
2143
- if (!process$1.env.DATABASE_URL) console.error("DATABASE_URL environment variable is not set.");
2144
- const configAgentCommand = createCommand("pantheon-agents config").version(version).description("Configure agent for pantheon project").argument("<name>", "The name of the agent.").argument("<role>", "The role of the agent.").argument("<project-id>", "The project id of the agent.").option("--skills <skills>", "The skills of the agent. Multiple values are separated by comma.", (val) => val.split(",").map((s) => s.trim()).filter((s) => s !== ""), []).option("--execute-agent <agent>", "The execute agent of the agent.", "codex").option("--root-branch-id <branchId>", "The root branch id of the agent. Default to project root branch id.").option("--no-bootstrap", "Prevent bootstrap base branch for agent. Use the root branch as base branch.").action(async function() {
2145
- const [name, role, projectId] = this.args;
2146
- await configAgent(name, {
2147
- role,
2148
- projectId,
2149
- ...this.opts()
2150
- });
2151
- });
2152
- const addTaskCommand = createCommand("pantheon-agents add-task").version(version).description("Add a task to an agent").argument("<name>", "The name of the agent.").argument("<project-id>", "The project id of the agent.").argument("<task-prompt>", "The prompt of the task.").action(async function() {
2153
- const [name, projectId, taskPrompt] = this.args;
2154
- await addTask(name, {
2155
- projectId,
2156
- prompt: taskPrompt
2157
- });
2158
- });
2159
- const deleteTaskCommand = createCommand("pantheon-agents delete-task").version(version).description("Delete a task for an agent").argument("<name>", "The name of the agent.").argument("<task-id>", "The id of the task.").action(async function() {
2160
- const [name, taskId] = this.args;
2161
- const rl = readline.createInterface({
2162
- input: process$1.stdin,
2163
- output: process$1.stdout
2164
- });
2165
- try {
2166
- if ((await rl.question(`Type the task id (${taskId}) to confirm deletion: `)).trim() !== taskId) {
2167
- console.error("Confirmation failed. Task id did not match.");
2277
+
2278
+ //#endregion
2279
+ //#region src/cli/commands/show-tasks.ts
2280
+ function createShowTasksCommand(version) {
2281
+ return createCommand("pantheon-agents show-tasks").version(version).description("Show tasks for an agent").argument("[name]", "The name of the agent.").option("--agents <names>", "Comma-separated agent names to query in one call.", parseCommaList, []).option("--all", "Show tasks for all agents.").option("--status <status>", "Filter tasks by status. Multiple values are separated by comma.", parseCommaList, []).option("--order-by <field>", "Order by queued_at, started_at, or ended_at.", "queued_at").option("--order-direction <direction>", "Order direction: asc or desc.", "desc").option("--limit <number>", "Limit the number of tasks shown.", (val) => parseInt(val, 10)).option("--max-task-length <number>", "Maximum task length for table output.", (val) => parseInt(val, 10), 120).option("--full-task", "Do not truncate task text in output.").option("--concise", "Output concise one-line entries.", true).option("--no-color", "Disable colored output.").option("--json", "Output tasks as JSON.").action(async function() {
2282
+ const [name] = this.args;
2283
+ const options = this.opts();
2284
+ const agentNames = /* @__PURE__ */ new Set();
2285
+ if (name) agentNames.add(name);
2286
+ options.agents.forEach((agent) => agentNames.add(agent));
2287
+ if (options.all && agentNames.size > 0) {
2288
+ console.error("Use either a specific agent name or --all, not both.");
2168
2289
  process$1.exit(1);
2169
2290
  }
2170
- if ((await rl.question("Type DELETE to permanently remove this task: ")).trim() !== "DELETE") {
2171
- console.error("Confirmation failed. Aborting deletion.");
2291
+ if (!options.all && agentNames.size === 0) {
2292
+ console.error("Provide an agent name, --agents, or --all.");
2172
2293
  process$1.exit(1);
2173
2294
  }
2174
- const deletedTask = await deleteTask(name, taskId);
2175
- if (!deletedTask) {
2176
- console.error(`Task ${taskId} not found for agent ${name}.`);
2295
+ const invalidStatuses = options.status.filter((status) => !taskStatuses.includes(status));
2296
+ if (invalidStatuses.length > 0) {
2297
+ console.error(`Invalid status values: ${invalidStatuses.join(", ")}. Allowed: ${taskStatuses.join(", ")}.`);
2177
2298
  process$1.exit(1);
2178
2299
  }
2179
- console.log(`Deleted task ${taskId} for agent ${name}. Status was ${deletedTask.status}.`);
2180
- } finally {
2181
- rl.close();
2182
- }
2183
- });
2184
- const showConfigCommand = createCommand("pantheon-agents show-config").version(version).description("Show agent config for a project").argument("<name>", "The name of the agent.").argument("[project-id]", "The project id.").option("--json", "Output config as JSON.").action(async function() {
2185
- const [name, projectId] = this.args;
2186
- const options = this.opts();
2187
- if (projectId) {
2188
- const config = await showAgentConfig(name, projectId);
2189
- if (!config) {
2190
- console.error(`No config found for agent ${name} and project ${projectId}.`);
2300
+ if (!orderByFields.includes(options.orderBy)) {
2301
+ console.error(`Invalid order-by value: ${options.orderBy}. Allowed: ${orderByFields.join(", ")}.`);
2302
+ process$1.exit(1);
2303
+ }
2304
+ if (!orderDirections.includes(options.orderDirection)) {
2305
+ console.error(`Invalid order-direction value: ${options.orderDirection}. Allowed: ${orderDirections.join(", ")}.`);
2191
2306
  process$1.exit(1);
2192
2307
  }
2308
+ if (options.limit != null && Number.isNaN(options.limit)) {
2309
+ console.error("Invalid limit value. Must be a number.");
2310
+ process$1.exit(1);
2311
+ }
2312
+ if (Number.isNaN(options.maxTaskLength) || options.maxTaskLength <= 0) {
2313
+ console.error("Invalid max-task-length value. Must be a positive number.");
2314
+ process$1.exit(1);
2315
+ }
2316
+ if (options.fullTask && options.maxTaskLength) options.maxTaskLength = Number.POSITIVE_INFINITY;
2317
+ if (options.json && options.concise) {
2318
+ console.error("Use either --json or --concise, not both.");
2319
+ process$1.exit(1);
2320
+ }
2321
+ const limitedTasks = await showTasksForAgents({
2322
+ agents: Array.from(agentNames),
2323
+ allAgents: options.all,
2324
+ status: options.status,
2325
+ orderBy: options.orderBy,
2326
+ orderDirection: options.orderDirection,
2327
+ limit: options.limit
2328
+ });
2193
2329
  if (options.json) {
2194
- console.log(JSON.stringify(config, null, 2));
2330
+ const payload = limitedTasks.map(({ agent, task }) => ({
2331
+ agent,
2332
+ ...task
2333
+ }));
2334
+ console.log(JSON.stringify(payload, null, 2));
2195
2335
  return;
2196
2336
  }
2197
- console.table([{
2198
- agent: config.agent,
2199
- project_id: config.project_id,
2200
- base_branch_id: config.base_branch_id,
2201
- role: config.role,
2202
- execute_agent: config.execute_agent,
2203
- prototype_url: config.prototype_url,
2204
- skills: Array.isArray(config.skills) ? config.skills.join(", ") : String(config.skills)
2205
- }]);
2206
- return;
2207
- }
2208
- const configs = await showAgentConfigs(name);
2209
- if (!configs.length) {
2210
- console.error(`No configs found for agent ${name}.`);
2211
- process$1.exit(1);
2212
- }
2213
- if (options.json) {
2214
- console.log(JSON.stringify(configs, null, 2));
2215
- return;
2216
- }
2217
- console.table(configs.map((config) => ({
2218
- agent: config.agent,
2219
- project_id: config.project_id,
2220
- base_branch_id: config.base_branch_id,
2221
- role: config.role,
2222
- execute_agent: config.execute_agent,
2223
- prototype_url: config.prototype_url,
2224
- skills: Array.isArray(config.skills) ? config.skills.join(", ") : String(config.skills)
2225
- })));
2226
- });
2227
- const runAgentCommand = createCommand("pantheon-agents run").version(version).description("Start a pantheon agents").argument("<name>", "The name of the agent.").option("--data-dir [dir]", "Data directory.", expandTilde("~/.pantheon-agents")).option("--mcp-port", "The port of the MCP server. Defaults to a random port.").option("--loop-interval <seconds>", "The interval of the loop in seconds. Defaults to 5.", (val) => parseInt(val, 10), 5).action(async function() {
2228
- const [name] = this.args;
2229
- const options = this.opts();
2230
- const logFileTransport = transport({
2231
- target: "pino-roll",
2232
- options: {
2233
- file: path.join(options.dataDir, "agents", name, "logs", "log"),
2234
- frequency: "daily",
2235
- mkdir: true
2236
- }
2237
- });
2238
- const prettyTransport = transport({
2239
- target: "pino-pretty",
2240
- options: {
2241
- colorize: true,
2242
- ignore: "pid,hostname,level-label"
2337
+ if (options.concise) {
2338
+ for (const { agent, task } of limitedTasks) console.log(formatConciseTaskLine({
2339
+ agent,
2340
+ task,
2341
+ maxTaskLength: options.maxTaskLength,
2342
+ useColor: options.color
2343
+ }));
2344
+ return;
2243
2345
  }
2244
- });
2245
- await runAgent(name, options, pino({
2246
- timestamp: pino.stdTimeFunctions.isoTime,
2247
- formatters: { level(label) {
2248
- return { level: label.toUpperCase() };
2249
- } }
2250
- }, multistream([{ stream: logFileTransport }, { stream: prettyTransport }])));
2251
- });
2252
- const showTasksCommand = createCommand("pantheon-agents show-tasks").version(version).description("Show tasks for an agent").argument("[name]", "The name of the agent.").option("--agents <names>", "Comma-separated agent names to query in one call.", parseCommaList, []).option("--all", "Show tasks for all agents.").option("--status <status>", "Filter tasks by status. Multiple values are separated by comma.", parseCommaList, []).option("--order-by <field>", "Order by queued_at, started_at, or ended_at.", "queued_at").option("--order-direction <direction>", "Order direction: asc or desc.", "desc").option("--limit <number>", "Limit the number of tasks shown.", (val) => parseInt(val, 10)).option("--max-task-length <number>", "Maximum task length for table output.", (val) => parseInt(val, 10), 120).option("--full-task", "Do not truncate task text in output.").option("--concise", "Output concise one-line entries.", true).option("--no-color", "Disable colored output.").option("--json", "Output tasks as JSON.").action(async function() {
2253
- const [name] = this.args;
2254
- const options = this.opts();
2255
- const agentNames = /* @__PURE__ */ new Set();
2256
- if (name) agentNames.add(name);
2257
- options.agents.forEach((agent) => agentNames.add(agent));
2258
- if (options.all && agentNames.size > 0) {
2259
- console.error("Use either a specific agent name or --all, not both.");
2260
- process$1.exit(1);
2261
- }
2262
- if (!options.all && agentNames.size === 0) {
2263
- console.error("Provide an agent name, --agents, or --all.");
2264
- process$1.exit(1);
2265
- }
2266
- const invalidStatuses = options.status.filter((status) => !taskStatuses.includes(status));
2267
- if (invalidStatuses.length > 0) {
2268
- console.error(`Invalid status values: ${invalidStatuses.join(", ")}. Allowed: ${taskStatuses.join(", ")}.`);
2269
- process$1.exit(1);
2270
- }
2271
- if (!orderByFields.includes(options.orderBy)) {
2272
- console.error(`Invalid order-by value: ${options.orderBy}. Allowed: ${orderByFields.join(", ")}.`);
2273
- process$1.exit(1);
2274
- }
2275
- if (!orderDirections.includes(options.orderDirection)) {
2276
- console.error(`Invalid order-direction value: ${options.orderDirection}. Allowed: ${orderDirections.join(", ")}.`);
2277
- process$1.exit(1);
2278
- }
2279
- if (options.limit != null && Number.isNaN(options.limit)) {
2280
- console.error("Invalid limit value. Must be a number.");
2281
- process$1.exit(1);
2282
- }
2283
- if (Number.isNaN(options.maxTaskLength) || options.maxTaskLength <= 0) {
2284
- console.error("Invalid max-task-length value. Must be a positive number.");
2285
- process$1.exit(1);
2286
- }
2287
- if (options.fullTask && options.maxTaskLength) options.maxTaskLength = Number.POSITIVE_INFINITY;
2288
- if (options.json && options.concise) {
2289
- console.error("Use either --json or --concise, not both.");
2290
- process$1.exit(1);
2291
- }
2292
- const limitedTasks = await showTasksForAgents({
2293
- agents: Array.from(agentNames),
2294
- allAgents: options.all,
2295
- status: options.status,
2296
- orderBy: options.orderBy,
2297
- orderDirection: options.orderDirection,
2298
- limit: options.limit
2299
- });
2300
- if (options.json) {
2301
- const payload = limitedTasks.map(({ agent, task }) => ({
2302
- agent,
2303
- ...task
2304
- }));
2305
- console.log(JSON.stringify(payload, null, 2));
2306
- return;
2307
- }
2308
- if (options.concise) {
2309
- for (const { agent, task } of limitedTasks) console.log(formatConciseTaskLine({
2346
+ const rows = limitedTasks.map(({ agent, task }) => formatTaskTableRow({
2310
2347
  agent,
2311
2348
  task,
2312
- maxTaskLength: options.maxTaskLength,
2313
- useColor: options.color
2349
+ maxTaskLength: options.maxTaskLength
2314
2350
  }));
2315
- return;
2316
- }
2317
- const rows = limitedTasks.map(({ agent, task }) => formatTaskTableRow({
2318
- agent,
2319
- task,
2320
- maxTaskLength: options.maxTaskLength
2321
- }));
2322
- console.table(rows);
2323
- console.log(`${limitedTasks.length} task(s) shown.`);
2324
- });
2351
+ console.table(rows);
2352
+ console.log(`${limitedTasks.length} task(s) shown.`);
2353
+ });
2354
+ }
2355
+
2356
+ //#endregion
2357
+ //#region src/cli/utils/env.ts
2358
+ function warnIfMissingEnv(keys) {
2359
+ for (const key of keys) if (!process.env[key]) console.error(`${key} environment variable is not set.`);
2360
+ }
2361
+
2362
+ //#endregion
2363
+ //#region src/cli/index.ts
2364
+ warnIfMissingEnv(["PANTHEON_API_KEY", "DATABASE_URL"]);
2365
+ const commands = {
2366
+ "add-task": createAddTaskCommand(version),
2367
+ config: createConfigAgentCommand(version),
2368
+ "delete-task": createDeleteTaskCommand(version),
2369
+ run: createRunAgentCommand(version),
2370
+ "show-config": createShowConfigCommand(version),
2371
+ "show-tasks": createShowTasksCommand(version)
2372
+ };
2325
2373
  function printCommandHelpAndExit(command) {
2326
2374
  console.error(`Invalid command: ${command}. Supported commands: ${Object.keys(commands).join(", ")}.`);
2327
- console.error(` Run pantheon-agents help <command> for more information.`);
2375
+ console.error(" Run pantheon-agents help <command> for more information.");
2328
2376
  process$1.exit(1);
2329
2377
  }
2330
- const commands = {
2331
- "add-task": addTaskCommand,
2332
- config: configAgentCommand,
2333
- "delete-task": deleteTaskCommand,
2334
- run: runAgentCommand,
2335
- "show-config": showConfigCommand,
2336
- "show-tasks": showTasksCommand
2337
- };
2338
2378
  if (process$1.argv[2] === "help") {
2339
2379
  const command = process$1.argv[3];
2340
2380
  if (command in commands) commands[command].help({ error: false });