@hasna/testers 0.0.1 → 0.0.2

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.
package/dist/mcp/index.js CHANGED
@@ -4083,6 +4083,26 @@ function screenshotFromRow(row) {
4083
4083
  timestamp: row.timestamp
4084
4084
  };
4085
4085
  }
4086
+ function scheduleFromRow(row) {
4087
+ return {
4088
+ id: row.id,
4089
+ projectId: row.project_id,
4090
+ name: row.name,
4091
+ cronExpression: row.cron_expression,
4092
+ url: row.url,
4093
+ scenarioFilter: JSON.parse(row.scenario_filter),
4094
+ model: row.model,
4095
+ headed: row.headed === 1,
4096
+ parallel: row.parallel,
4097
+ timeoutMs: row.timeout_ms,
4098
+ enabled: row.enabled === 1,
4099
+ lastRunId: row.last_run_id,
4100
+ lastRunAt: row.last_run_at,
4101
+ nextRunAt: row.next_run_at,
4102
+ createdAt: row.created_at,
4103
+ updatedAt: row.updated_at
4104
+ };
4105
+ }
4086
4106
  class VersionConflictError extends Error {
4087
4107
  constructor(entity, id) {
4088
4108
  super(`Version conflict on ${entity}: ${id}`);
@@ -4110,6 +4130,12 @@ class TodosConnectionError extends Error {
4110
4130
  this.name = "TodosConnectionError";
4111
4131
  }
4112
4132
  }
4133
+ class ScheduleNotFoundError extends Error {
4134
+ constructor(id) {
4135
+ super(`Schedule not found: ${id}`);
4136
+ this.name = "ScheduleNotFoundError";
4137
+ }
4138
+ }
4113
4139
 
4114
4140
  // src/db/database.ts
4115
4141
  import { Database } from "bun:sqlite";
@@ -4239,6 +4265,30 @@ var MIGRATIONS = [
4239
4265
  `
4240
4266
  ALTER TABLE projects ADD COLUMN scenario_prefix TEXT DEFAULT 'TST';
4241
4267
  ALTER TABLE projects ADD COLUMN scenario_counter INTEGER DEFAULT 0;
4268
+ `,
4269
+ `
4270
+ CREATE TABLE IF NOT EXISTS schedules (
4271
+ id TEXT PRIMARY KEY,
4272
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
4273
+ name TEXT NOT NULL,
4274
+ cron_expression TEXT NOT NULL,
4275
+ url TEXT NOT NULL,
4276
+ scenario_filter TEXT NOT NULL DEFAULT '{}',
4277
+ model TEXT,
4278
+ headed INTEGER NOT NULL DEFAULT 0,
4279
+ parallel INTEGER NOT NULL DEFAULT 1,
4280
+ timeout_ms INTEGER,
4281
+ enabled INTEGER NOT NULL DEFAULT 1,
4282
+ last_run_id TEXT REFERENCES runs(id) ON DELETE SET NULL,
4283
+ last_run_at TEXT,
4284
+ next_run_at TEXT,
4285
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
4286
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
4287
+ );
4288
+
4289
+ CREATE INDEX IF NOT EXISTS idx_schedules_project ON schedules(project_id);
4290
+ CREATE INDEX IF NOT EXISTS idx_schedules_enabled ON schedules(enabled);
4291
+ CREATE INDEX IF NOT EXISTS idx_schedules_next_run ON schedules(next_run_at);
4242
4292
  `
4243
4293
  ];
4244
4294
  function applyMigrations(database) {
@@ -5016,6 +5066,127 @@ var BROWSER_TOOLS = [
5016
5066
  required: ["text"]
5017
5067
  }
5018
5068
  },
5069
+ {
5070
+ name: "scroll",
5071
+ description: "Scroll the page up or down by a given amount of pixels.",
5072
+ input_schema: {
5073
+ type: "object",
5074
+ properties: {
5075
+ direction: {
5076
+ type: "string",
5077
+ enum: ["up", "down"],
5078
+ description: "Direction to scroll."
5079
+ },
5080
+ amount: {
5081
+ type: "number",
5082
+ description: "Number of pixels to scroll (default: 500)."
5083
+ }
5084
+ },
5085
+ required: ["direction"]
5086
+ }
5087
+ },
5088
+ {
5089
+ name: "get_page_html",
5090
+ description: "Get simplified HTML of the page body content, truncated to 8000 characters.",
5091
+ input_schema: {
5092
+ type: "object",
5093
+ properties: {},
5094
+ required: []
5095
+ }
5096
+ },
5097
+ {
5098
+ name: "get_elements",
5099
+ description: "List elements matching a CSS selector with their text, tag name, and key attributes (max 20 results).",
5100
+ input_schema: {
5101
+ type: "object",
5102
+ properties: {
5103
+ selector: {
5104
+ type: "string",
5105
+ description: "CSS selector to match elements."
5106
+ }
5107
+ },
5108
+ required: ["selector"]
5109
+ }
5110
+ },
5111
+ {
5112
+ name: "wait_for_navigation",
5113
+ description: "Wait for page navigation/load to complete (network idle).",
5114
+ input_schema: {
5115
+ type: "object",
5116
+ properties: {
5117
+ timeout: {
5118
+ type: "number",
5119
+ description: "Maximum time to wait in milliseconds (default: 10000)."
5120
+ }
5121
+ },
5122
+ required: []
5123
+ }
5124
+ },
5125
+ {
5126
+ name: "get_page_title",
5127
+ description: "Get the document title of the current page.",
5128
+ input_schema: {
5129
+ type: "object",
5130
+ properties: {},
5131
+ required: []
5132
+ }
5133
+ },
5134
+ {
5135
+ name: "count_elements",
5136
+ description: "Count the number of elements matching a CSS selector.",
5137
+ input_schema: {
5138
+ type: "object",
5139
+ properties: {
5140
+ selector: {
5141
+ type: "string",
5142
+ description: "CSS selector to count matching elements."
5143
+ }
5144
+ },
5145
+ required: ["selector"]
5146
+ }
5147
+ },
5148
+ {
5149
+ name: "hover",
5150
+ description: "Hover over an element matching the given CSS selector.",
5151
+ input_schema: {
5152
+ type: "object",
5153
+ properties: {
5154
+ selector: {
5155
+ type: "string",
5156
+ description: "CSS selector of the element to hover over."
5157
+ }
5158
+ },
5159
+ required: ["selector"]
5160
+ }
5161
+ },
5162
+ {
5163
+ name: "check",
5164
+ description: "Check a checkbox matching the given CSS selector.",
5165
+ input_schema: {
5166
+ type: "object",
5167
+ properties: {
5168
+ selector: {
5169
+ type: "string",
5170
+ description: "CSS selector of the checkbox to check."
5171
+ }
5172
+ },
5173
+ required: ["selector"]
5174
+ }
5175
+ },
5176
+ {
5177
+ name: "uncheck",
5178
+ description: "Uncheck a checkbox matching the given CSS selector.",
5179
+ input_schema: {
5180
+ type: "object",
5181
+ properties: {
5182
+ selector: {
5183
+ type: "string",
5184
+ description: "CSS selector of the checkbox to uncheck."
5185
+ }
5186
+ },
5187
+ required: ["selector"]
5188
+ }
5189
+ },
5019
5190
  {
5020
5191
  name: "report_result",
5021
5192
  description: "Report the final test result. Call this when you have completed testing the scenario. This MUST be the last tool you call.",
@@ -5147,6 +5318,113 @@ async function executeTool(page, screenshotter, toolName, toolInput, context) {
5147
5318
  return { result: "false" };
5148
5319
  }
5149
5320
  }
5321
+ case "scroll": {
5322
+ const direction = toolInput.direction;
5323
+ const amount = typeof toolInput.amount === "number" ? toolInput.amount : 500;
5324
+ const scrollY = direction === "down" ? amount : -amount;
5325
+ await page.evaluate((y) => window.scrollBy(0, y), scrollY);
5326
+ const screenshot = await screenshotter.capture(page, {
5327
+ runId: context.runId,
5328
+ scenarioSlug: context.scenarioSlug,
5329
+ stepNumber: context.stepNumber,
5330
+ action: "scroll"
5331
+ });
5332
+ return {
5333
+ result: `Scrolled ${direction} by ${amount}px`,
5334
+ screenshot
5335
+ };
5336
+ }
5337
+ case "get_page_html": {
5338
+ const html = await page.evaluate(() => document.body.innerHTML);
5339
+ const truncated = html.length > 8000 ? html.slice(0, 8000) + "..." : html;
5340
+ return {
5341
+ result: truncated
5342
+ };
5343
+ }
5344
+ case "get_elements": {
5345
+ const selector = toolInput.selector;
5346
+ const allElements = await page.locator(selector).all();
5347
+ const elements = allElements.slice(0, 20);
5348
+ const results = [];
5349
+ for (let i = 0;i < elements.length; i++) {
5350
+ const el = elements[i];
5351
+ const tagName = await el.evaluate((e) => e.tagName.toLowerCase());
5352
+ const textContent = await el.textContent() ?? "";
5353
+ const trimmedText = textContent.trim().slice(0, 100);
5354
+ const id = await el.getAttribute("id");
5355
+ const className = await el.getAttribute("class");
5356
+ const href = await el.getAttribute("href");
5357
+ const type = await el.getAttribute("type");
5358
+ const placeholder = await el.getAttribute("placeholder");
5359
+ const ariaLabel = await el.getAttribute("aria-label");
5360
+ const attrs = [];
5361
+ if (id)
5362
+ attrs.push(`id="${id}"`);
5363
+ if (className)
5364
+ attrs.push(`class="${className}"`);
5365
+ if (href)
5366
+ attrs.push(`href="${href}"`);
5367
+ if (type)
5368
+ attrs.push(`type="${type}"`);
5369
+ if (placeholder)
5370
+ attrs.push(`placeholder="${placeholder}"`);
5371
+ if (ariaLabel)
5372
+ attrs.push(`aria-label="${ariaLabel}"`);
5373
+ results.push(`[${i}] <${tagName}${attrs.length ? " " + attrs.join(" ") : ""}> ${trimmedText}`);
5374
+ }
5375
+ return {
5376
+ result: results.length > 0 ? results.join(`
5377
+ `) : `No elements found matching "${selector}"`
5378
+ };
5379
+ }
5380
+ case "wait_for_navigation": {
5381
+ const timeout = typeof toolInput.timeout === "number" ? toolInput.timeout : 1e4;
5382
+ await page.waitForLoadState("networkidle", { timeout });
5383
+ return {
5384
+ result: "Navigation/load completed"
5385
+ };
5386
+ }
5387
+ case "get_page_title": {
5388
+ const title = await page.title();
5389
+ return {
5390
+ result: title || "(no title)"
5391
+ };
5392
+ }
5393
+ case "count_elements": {
5394
+ const selector = toolInput.selector;
5395
+ const count = await page.locator(selector).count();
5396
+ return {
5397
+ result: `${count} element(s) matching "${selector}"`
5398
+ };
5399
+ }
5400
+ case "hover": {
5401
+ const selector = toolInput.selector;
5402
+ await page.hover(selector);
5403
+ const screenshot = await screenshotter.capture(page, {
5404
+ runId: context.runId,
5405
+ scenarioSlug: context.scenarioSlug,
5406
+ stepNumber: context.stepNumber,
5407
+ action: "hover"
5408
+ });
5409
+ return {
5410
+ result: `Hovered over: ${selector}`,
5411
+ screenshot
5412
+ };
5413
+ }
5414
+ case "check": {
5415
+ const selector = toolInput.selector;
5416
+ await page.check(selector);
5417
+ return {
5418
+ result: `Checked checkbox: ${selector}`
5419
+ };
5420
+ }
5421
+ case "uncheck": {
5422
+ const selector = toolInput.selector;
5423
+ await page.uncheck(selector);
5424
+ return {
5425
+ result: `Unchecked checkbox: ${selector}`
5426
+ };
5427
+ }
5150
5428
  case "report_result": {
5151
5429
  const status = toolInput.status;
5152
5430
  const reasoning = toolInput.reasoning;
@@ -5173,13 +5451,26 @@ async function runAgentLoop(options) {
5173
5451
  maxTurns = 30
5174
5452
  } = options;
5175
5453
  const systemPrompt = [
5176
- "You are a QA testing agent. Test the following scenario by interacting with the browser.",
5177
- "Use the provided tools to navigate, click, fill forms, and verify results.",
5178
- "When done, call report_result with your findings.",
5179
- "Be methodical: navigate to the target page first, then follow the test steps.",
5180
- "If a step fails, try reasonable alternatives before reporting failure.",
5181
- "Always report a final result \u2014 never leave a test incomplete."
5182
- ].join(" ");
5454
+ "You are an expert QA testing agent. Your job is to thoroughly test web application scenarios.",
5455
+ "You have browser tools to navigate, interact with, and inspect web pages.",
5456
+ "",
5457
+ "Strategy:",
5458
+ "1. First navigate to the target page and take a screenshot to understand the layout",
5459
+ "2. If you can't find an element, use get_elements or get_page_html to discover selectors",
5460
+ "3. Use scroll to discover content below the fold",
5461
+ "4. Use wait_for or wait_for_navigation after actions that trigger page loads",
5462
+ "5. Take screenshots after every meaningful state change",
5463
+ "6. Use assert_text and assert_visible to verify expected outcomes",
5464
+ "7. When done testing, call report_result with detailed pass/fail reasoning",
5465
+ "",
5466
+ "Tips:",
5467
+ "- Try multiple selector strategies: by text, by role, by class, by id",
5468
+ "- If a click triggers navigation, use wait_for_navigation after",
5469
+ "- For forms, fill all fields before submitting",
5470
+ "- Check for error messages after form submissions",
5471
+ "- Verify both positive and negative states"
5472
+ ].join(`
5473
+ `);
5183
5474
  const userParts = [
5184
5475
  `**Scenario:** ${scenario.name}`,
5185
5476
  `**Description:** ${scenario.description}`
@@ -5591,6 +5882,345 @@ function importFromTodos(options = {}) {
5591
5882
  return { imported, skipped };
5592
5883
  }
5593
5884
 
5885
+ // src/db/schedules.ts
5886
+ function createSchedule(input) {
5887
+ const db2 = getDatabase();
5888
+ const id = uuid();
5889
+ const timestamp = now();
5890
+ db2.query(`
5891
+ INSERT INTO schedules (id, project_id, name, cron_expression, url, scenario_filter, model, headed, parallel, timeout_ms, enabled, created_at, updated_at)
5892
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
5893
+ `).run(id, input.projectId ?? null, input.name, input.cronExpression, input.url, JSON.stringify(input.scenarioFilter ?? {}), input.model ?? null, input.headed ? 1 : 0, input.parallel ?? 1, input.timeoutMs ?? null, timestamp, timestamp);
5894
+ return getSchedule(id);
5895
+ }
5896
+ function getSchedule(id) {
5897
+ const db2 = getDatabase();
5898
+ let row = db2.query("SELECT * FROM schedules WHERE id = ?").get(id);
5899
+ if (row)
5900
+ return scheduleFromRow(row);
5901
+ const fullId = resolvePartialId("schedules", id);
5902
+ if (fullId) {
5903
+ row = db2.query("SELECT * FROM schedules WHERE id = ?").get(fullId);
5904
+ if (row)
5905
+ return scheduleFromRow(row);
5906
+ }
5907
+ return null;
5908
+ }
5909
+ function listSchedules(filter) {
5910
+ const db2 = getDatabase();
5911
+ const conditions = [];
5912
+ const params = [];
5913
+ if (filter?.projectId) {
5914
+ conditions.push("project_id = ?");
5915
+ params.push(filter.projectId);
5916
+ }
5917
+ if (filter?.enabled !== undefined) {
5918
+ conditions.push("enabled = ?");
5919
+ params.push(filter.enabled ? 1 : 0);
5920
+ }
5921
+ let sql = "SELECT * FROM schedules";
5922
+ if (conditions.length > 0) {
5923
+ sql += " WHERE " + conditions.join(" AND ");
5924
+ }
5925
+ sql += " ORDER BY created_at DESC";
5926
+ if (filter?.limit) {
5927
+ sql += " LIMIT ?";
5928
+ params.push(filter.limit);
5929
+ }
5930
+ if (filter?.offset) {
5931
+ sql += " OFFSET ?";
5932
+ params.push(filter.offset);
5933
+ }
5934
+ const rows = db2.query(sql).all(...params);
5935
+ return rows.map(scheduleFromRow);
5936
+ }
5937
+ function updateSchedule(id, input) {
5938
+ const db2 = getDatabase();
5939
+ const existing = getSchedule(id);
5940
+ if (!existing) {
5941
+ throw new ScheduleNotFoundError(id);
5942
+ }
5943
+ const sets = [];
5944
+ const params = [];
5945
+ if (input.name !== undefined) {
5946
+ sets.push("name = ?");
5947
+ params.push(input.name);
5948
+ }
5949
+ if (input.cronExpression !== undefined) {
5950
+ sets.push("cron_expression = ?");
5951
+ params.push(input.cronExpression);
5952
+ }
5953
+ if (input.url !== undefined) {
5954
+ sets.push("url = ?");
5955
+ params.push(input.url);
5956
+ }
5957
+ if (input.scenarioFilter !== undefined) {
5958
+ sets.push("scenario_filter = ?");
5959
+ params.push(JSON.stringify(input.scenarioFilter));
5960
+ }
5961
+ if (input.model !== undefined) {
5962
+ sets.push("model = ?");
5963
+ params.push(input.model);
5964
+ }
5965
+ if (input.headed !== undefined) {
5966
+ sets.push("headed = ?");
5967
+ params.push(input.headed ? 1 : 0);
5968
+ }
5969
+ if (input.parallel !== undefined) {
5970
+ sets.push("parallel = ?");
5971
+ params.push(input.parallel);
5972
+ }
5973
+ if (input.timeoutMs !== undefined) {
5974
+ sets.push("timeout_ms = ?");
5975
+ params.push(input.timeoutMs);
5976
+ }
5977
+ if (input.enabled !== undefined) {
5978
+ sets.push("enabled = ?");
5979
+ params.push(input.enabled ? 1 : 0);
5980
+ }
5981
+ if (sets.length === 0) {
5982
+ return existing;
5983
+ }
5984
+ sets.push("updated_at = ?");
5985
+ params.push(now());
5986
+ params.push(existing.id);
5987
+ db2.query(`UPDATE schedules SET ${sets.join(", ")} WHERE id = ?`).run(...params);
5988
+ return getSchedule(existing.id);
5989
+ }
5990
+ function deleteSchedule(id) {
5991
+ const db2 = getDatabase();
5992
+ const schedule = getSchedule(id);
5993
+ if (!schedule)
5994
+ return false;
5995
+ const result = db2.query("DELETE FROM schedules WHERE id = ?").run(schedule.id);
5996
+ return result.changes > 0;
5997
+ }
5998
+ function getEnabledSchedules() {
5999
+ const db2 = getDatabase();
6000
+ const rows = db2.query("SELECT * FROM schedules WHERE enabled = 1 ORDER BY created_at DESC").all();
6001
+ return rows.map(scheduleFromRow);
6002
+ }
6003
+ function updateLastRun(id, runId, nextRunAt) {
6004
+ const db2 = getDatabase();
6005
+ const timestamp = now();
6006
+ db2.query(`
6007
+ UPDATE schedules SET last_run_id = ?, last_run_at = ?, next_run_at = ?, updated_at = ? WHERE id = ?
6008
+ `).run(runId, timestamp, nextRunAt, timestamp, id);
6009
+ }
6010
+
6011
+ // src/lib/scheduler.ts
6012
+ function parseCronField(field, min, max) {
6013
+ const results = new Set;
6014
+ const parts = field.split(",");
6015
+ for (const part of parts) {
6016
+ const trimmed = part.trim();
6017
+ if (trimmed.includes("/")) {
6018
+ const slashParts = trimmed.split("/");
6019
+ const rangePart = slashParts[0] ?? "*";
6020
+ const stepStr = slashParts[1] ?? "1";
6021
+ const step = parseInt(stepStr, 10);
6022
+ if (isNaN(step) || step <= 0) {
6023
+ throw new Error(`Invalid step value in cron field: ${field}`);
6024
+ }
6025
+ let start;
6026
+ let end;
6027
+ if (rangePart === "*") {
6028
+ start = min;
6029
+ end = max;
6030
+ } else if (rangePart.includes("-")) {
6031
+ const dashParts = rangePart.split("-");
6032
+ start = parseInt(dashParts[0] ?? "0", 10);
6033
+ end = parseInt(dashParts[1] ?? "0", 10);
6034
+ } else {
6035
+ start = parseInt(rangePart, 10);
6036
+ end = max;
6037
+ }
6038
+ for (let i = start;i <= end; i += step) {
6039
+ if (i >= min && i <= max)
6040
+ results.add(i);
6041
+ }
6042
+ } else if (trimmed === "*") {
6043
+ for (let i = min;i <= max; i++) {
6044
+ results.add(i);
6045
+ }
6046
+ } else if (trimmed.includes("-")) {
6047
+ const dashParts = trimmed.split("-");
6048
+ const lo = parseInt(dashParts[0] ?? "0", 10);
6049
+ const hi = parseInt(dashParts[1] ?? "0", 10);
6050
+ if (isNaN(lo) || isNaN(hi)) {
6051
+ throw new Error(`Invalid range in cron field: ${field}`);
6052
+ }
6053
+ for (let i = lo;i <= hi; i++) {
6054
+ if (i >= min && i <= max)
6055
+ results.add(i);
6056
+ }
6057
+ } else {
6058
+ const val = parseInt(trimmed, 10);
6059
+ if (isNaN(val)) {
6060
+ throw new Error(`Invalid value in cron field: ${field}`);
6061
+ }
6062
+ if (val >= min && val <= max)
6063
+ results.add(val);
6064
+ }
6065
+ }
6066
+ return Array.from(results).sort((a, b) => a - b);
6067
+ }
6068
+ function parseCron(expression) {
6069
+ const fields = expression.trim().split(/\s+/);
6070
+ if (fields.length !== 5) {
6071
+ throw new Error(`Invalid cron expression "${expression}": expected 5 fields, got ${fields.length}`);
6072
+ }
6073
+ return {
6074
+ minutes: parseCronField(fields[0], 0, 59),
6075
+ hours: parseCronField(fields[1], 0, 23),
6076
+ daysOfMonth: parseCronField(fields[2], 1, 31),
6077
+ months: parseCronField(fields[3], 1, 12),
6078
+ daysOfWeek: parseCronField(fields[4], 0, 6)
6079
+ };
6080
+ }
6081
+ function shouldRunAt(cronExpression, date) {
6082
+ const cron = parseCron(cronExpression);
6083
+ const minute = date.getMinutes();
6084
+ const hour = date.getHours();
6085
+ const dayOfMonth = date.getDate();
6086
+ const month = date.getMonth() + 1;
6087
+ const dayOfWeek = date.getDay();
6088
+ return cron.minutes.includes(minute) && cron.hours.includes(hour) && cron.daysOfMonth.includes(dayOfMonth) && cron.months.includes(month) && cron.daysOfWeek.includes(dayOfWeek);
6089
+ }
6090
+ function getNextRunTime(cronExpression, after) {
6091
+ parseCron(cronExpression);
6092
+ const start = after ? new Date(after.getTime()) : new Date;
6093
+ start.setSeconds(0, 0);
6094
+ start.setMinutes(start.getMinutes() + 1);
6095
+ const maxDate = new Date(start.getTime() + 366 * 24 * 60 * 60 * 1000);
6096
+ const cursor = new Date(start.getTime());
6097
+ while (cursor.getTime() <= maxDate.getTime()) {
6098
+ if (shouldRunAt(cronExpression, cursor)) {
6099
+ return cursor;
6100
+ }
6101
+ cursor.setMinutes(cursor.getMinutes() + 1);
6102
+ }
6103
+ throw new Error(`No matching time found for cron expression "${cronExpression}" within 366 days`);
6104
+ }
6105
+
6106
+ class Scheduler {
6107
+ interval = null;
6108
+ running = new Set;
6109
+ checkIntervalMs;
6110
+ onEvent;
6111
+ constructor(options) {
6112
+ this.checkIntervalMs = options?.checkIntervalMs ?? 60000;
6113
+ this.onEvent = options?.onEvent;
6114
+ }
6115
+ start() {
6116
+ if (this.interval)
6117
+ return;
6118
+ this.tick().catch(() => {});
6119
+ this.interval = setInterval(() => {
6120
+ this.tick().catch(() => {});
6121
+ }, this.checkIntervalMs);
6122
+ }
6123
+ stop() {
6124
+ if (this.interval) {
6125
+ clearInterval(this.interval);
6126
+ this.interval = null;
6127
+ }
6128
+ }
6129
+ async tick() {
6130
+ const now2 = new Date;
6131
+ now2.setSeconds(0, 0);
6132
+ const schedules = getEnabledSchedules();
6133
+ for (const schedule of schedules) {
6134
+ if (this.running.has(schedule.id))
6135
+ continue;
6136
+ if (shouldRunAt(schedule.cronExpression, now2)) {
6137
+ this.running.add(schedule.id);
6138
+ this.emit({
6139
+ type: "schedule:triggered",
6140
+ scheduleId: schedule.id,
6141
+ scheduleName: schedule.name,
6142
+ timestamp: new Date().toISOString()
6143
+ });
6144
+ this.executeSchedule(schedule).then(({ runId }) => {
6145
+ const nextRun = getNextRunTime(schedule.cronExpression, new Date);
6146
+ updateLastRun(schedule.id, runId, nextRun.toISOString());
6147
+ this.emit({
6148
+ type: "schedule:completed",
6149
+ scheduleId: schedule.id,
6150
+ scheduleName: schedule.name,
6151
+ runId,
6152
+ timestamp: new Date().toISOString()
6153
+ });
6154
+ }).catch((err) => {
6155
+ this.emit({
6156
+ type: "schedule:failed",
6157
+ scheduleId: schedule.id,
6158
+ scheduleName: schedule.name,
6159
+ error: err instanceof Error ? err.message : String(err),
6160
+ timestamp: new Date().toISOString()
6161
+ });
6162
+ }).finally(() => {
6163
+ this.running.delete(schedule.id);
6164
+ });
6165
+ }
6166
+ }
6167
+ }
6168
+ async runScheduleNow(scheduleId) {
6169
+ const schedule = getSchedule(scheduleId);
6170
+ if (!schedule) {
6171
+ throw new ScheduleNotFoundError(scheduleId);
6172
+ }
6173
+ this.running.add(schedule.id);
6174
+ this.emit({
6175
+ type: "schedule:triggered",
6176
+ scheduleId: schedule.id,
6177
+ scheduleName: schedule.name,
6178
+ timestamp: new Date().toISOString()
6179
+ });
6180
+ try {
6181
+ const { runId } = await this.executeSchedule(schedule);
6182
+ const nextRun = getNextRunTime(schedule.cronExpression, new Date);
6183
+ updateLastRun(schedule.id, runId, nextRun.toISOString());
6184
+ this.emit({
6185
+ type: "schedule:completed",
6186
+ scheduleId: schedule.id,
6187
+ scheduleName: schedule.name,
6188
+ runId,
6189
+ timestamp: new Date().toISOString()
6190
+ });
6191
+ } catch (err) {
6192
+ this.emit({
6193
+ type: "schedule:failed",
6194
+ scheduleId: schedule.id,
6195
+ scheduleName: schedule.name,
6196
+ error: err instanceof Error ? err.message : String(err),
6197
+ timestamp: new Date().toISOString()
6198
+ });
6199
+ throw err;
6200
+ } finally {
6201
+ this.running.delete(schedule.id);
6202
+ }
6203
+ }
6204
+ async executeSchedule(schedule) {
6205
+ const { run } = await runByFilter({
6206
+ url: schedule.url,
6207
+ model: schedule.model ?? undefined,
6208
+ headed: schedule.headed,
6209
+ parallel: schedule.parallel,
6210
+ timeout: schedule.timeoutMs ?? undefined,
6211
+ tags: schedule.scenarioFilter.tags,
6212
+ priority: schedule.scenarioFilter.priority,
6213
+ scenarioIds: schedule.scenarioFilter.scenarioIds
6214
+ });
6215
+ return { runId: run.id };
6216
+ }
6217
+ emit(event) {
6218
+ if (this.onEvent) {
6219
+ this.onEvent(event);
6220
+ }
6221
+ }
6222
+ }
6223
+
5594
6224
  // src/mcp/index.ts
5595
6225
  var server = new McpServer({
5596
6226
  name: "testers-mcp",
@@ -5893,6 +6523,70 @@ server.tool("get_status", "Get system status: DB path, API key, scenario and run
5893
6523
  return { content: [{ type: "text", text: `${e.name}: ${e.message}` }], isError: true };
5894
6524
  }
5895
6525
  });
6526
+ server.tool("create_schedule", {
6527
+ name: exports_external.string().describe("Schedule name"),
6528
+ cronExpression: exports_external.string().describe("Cron expression (5-field)"),
6529
+ url: exports_external.string().describe("Target URL to test"),
6530
+ tags: exports_external.array(exports_external.string()).optional().describe("Filter scenarios by tags"),
6531
+ priority: exports_external.string().optional().describe("Filter scenarios by priority"),
6532
+ model: exports_external.string().optional().describe("AI model"),
6533
+ headed: exports_external.boolean().optional().describe("Run headed"),
6534
+ parallel: exports_external.number().optional().describe("Parallel count"),
6535
+ projectId: exports_external.string().optional().describe("Project ID")
6536
+ }, async (params) => {
6537
+ try {
6538
+ const schedule = createSchedule({
6539
+ name: params.name,
6540
+ cronExpression: params.cronExpression,
6541
+ url: params.url,
6542
+ scenarioFilter: { tags: params.tags, priority: params.priority },
6543
+ model: params.model,
6544
+ headed: params.headed,
6545
+ parallel: params.parallel,
6546
+ projectId: params.projectId
6547
+ });
6548
+ const nextRun = getNextRunTime(schedule.cronExpression);
6549
+ return { content: [{ type: "text", text: `Schedule created: ${schedule.id.slice(0, 8)} | ${schedule.name} | cron: ${schedule.cronExpression} | next: ${nextRun.toISOString()}` }] };
6550
+ } catch (e) {
6551
+ return { content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
6552
+ }
6553
+ });
6554
+ server.tool("list_schedules", {
6555
+ projectId: exports_external.string().optional(),
6556
+ enabled: exports_external.boolean().optional(),
6557
+ limit: exports_external.number().optional()
6558
+ }, async (params) => {
6559
+ const schedules = listSchedules({ projectId: params.projectId, enabled: params.enabled, limit: params.limit });
6560
+ if (schedules.length === 0)
6561
+ return { content: [{ type: "text", text: "No schedules found." }] };
6562
+ const lines = schedules.map((s) => `${s.id.slice(0, 8)} | ${s.name} | ${s.cronExpression} | ${s.url} | ${s.enabled ? "enabled" : "disabled"} | next: ${s.nextRunAt ?? "N/A"}`);
6563
+ return { content: [{ type: "text", text: lines.join(`
6564
+ `) }] };
6565
+ });
6566
+ server.tool("enable_schedule", { id: exports_external.string().describe("Schedule ID") }, async (params) => {
6567
+ try {
6568
+ const schedule = updateSchedule(params.id, { enabled: true });
6569
+ return { content: [{ type: "text", text: `Schedule ${schedule.name} enabled.` }] };
6570
+ } catch (e) {
6571
+ return { content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
6572
+ }
6573
+ });
6574
+ server.tool("disable_schedule", { id: exports_external.string().describe("Schedule ID") }, async (params) => {
6575
+ try {
6576
+ const schedule = updateSchedule(params.id, { enabled: false });
6577
+ return { content: [{ type: "text", text: `Schedule ${schedule.name} disabled.` }] };
6578
+ } catch (e) {
6579
+ return { content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
6580
+ }
6581
+ });
6582
+ server.tool("delete_schedule", { id: exports_external.string().describe("Schedule ID") }, async (params) => {
6583
+ try {
6584
+ const deleted = deleteSchedule(params.id);
6585
+ return { content: [{ type: "text", text: deleted ? "Schedule deleted." : "Schedule not found." }] };
6586
+ } catch (e) {
6587
+ return { content: [{ type: "text", text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true };
6588
+ }
6589
+ });
5896
6590
  async function main() {
5897
6591
  const transport = new StdioServerTransport;
5898
6592
  await server.connect(transport);