mastracode 0.22.2 → 0.22.3-alpha.1

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 (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/HarnessCompat.d.ts +21 -2
  3. package/dist/HarnessCompat.d.ts.map +1 -1
  4. package/dist/agents/tools.d.ts +4 -3
  5. package/dist/agents/tools.d.ts.map +1 -1
  6. package/dist/agents/workspace.d.ts.map +1 -1
  7. package/dist/{chunk-NFF7IH5X.cjs → chunk-A4W5D25I.cjs} +2 -1096
  8. package/dist/chunk-A4W5D25I.cjs.map +1 -0
  9. package/dist/{chunk-DPPFZEZI.cjs → chunk-AGLPYB76.cjs} +193 -325
  10. package/dist/chunk-AGLPYB76.cjs.map +1 -0
  11. package/dist/{chunk-BOZ3JCCI.cjs → chunk-AXKWCXEW.cjs} +961 -937
  12. package/dist/chunk-AXKWCXEW.cjs.map +1 -0
  13. package/dist/{chunk-7ARENXCP.js → chunk-CD6DZEX6.js} +38 -14
  14. package/dist/chunk-CD6DZEX6.js.map +1 -0
  15. package/dist/{chunk-EXBGEHMR.js → chunk-TWAOLBVC.js} +3 -1094
  16. package/dist/chunk-TWAOLBVC.js.map +1 -0
  17. package/dist/{chunk-AB4G5527.js → chunk-VCIVJV7J.js} +163 -295
  18. package/dist/chunk-VCIVJV7J.js.map +1 -0
  19. package/dist/cli.cjs +18 -18
  20. package/dist/cli.js +3 -3
  21. package/dist/harness-tui-v1.d.ts +2 -0
  22. package/dist/harness-tui-v1.d.ts.map +1 -0
  23. package/dist/index.cjs +3 -3
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/schema.d.ts +11 -4
  28. package/dist/schema.d.ts.map +1 -1
  29. package/dist/tui/event-dispatch.d.ts.map +1 -1
  30. package/dist/tui/handlers/message.d.ts.map +1 -1
  31. package/dist/tui/mastra-tui.d.ts.map +1 -1
  32. package/dist/tui/state.d.ts +3 -1
  33. package/dist/tui/state.d.ts.map +1 -1
  34. package/dist/tui/status-line.d.ts.map +1 -1
  35. package/dist/tui.cjs +19 -19
  36. package/dist/tui.js +2 -2
  37. package/package.json +13 -11
  38. package/dist/chunk-7ARENXCP.js.map +0 -1
  39. package/dist/chunk-AB4G5527.js.map +0 -1
  40. package/dist/chunk-BOZ3JCCI.cjs.map +0 -1
  41. package/dist/chunk-DPPFZEZI.cjs.map +0 -1
  42. package/dist/chunk-EXBGEHMR.js.map +0 -1
  43. package/dist/chunk-NFF7IH5X.cjs.map +0 -1
  44. package/dist/github-signals/index.d.ts +0 -217
  45. package/dist/github-signals/index.d.ts.map +0 -1
@@ -9,12 +9,6 @@ var openaiCompatible = require('@ai-sdk/openai-compatible');
9
9
  var schemaCompat = require('@mastra/schema-compat');
10
10
  var openai = require('@ai-sdk/openai');
11
11
  var llm = require('@mastra/core/llm');
12
- var crypto = require('crypto');
13
- var promises = require('fs/promises');
14
- var os = require('os');
15
- var util = require('util');
16
- var tools = require('@mastra/core/tools');
17
- var z = require('zod');
18
12
  var chalk = require('chalk');
19
13
 
20
14
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -39,7 +33,6 @@ function _interopNamespace(e) {
39
33
 
40
34
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
41
35
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
42
- var z__default = /*#__PURE__*/_interopDefault(z);
43
36
  var chalk__default = /*#__PURE__*/_interopDefault(chalk);
44
37
 
45
38
  var MEMORY_GATEWAY_PROVIDER = "mastra-gateway";
@@ -1284,1091 +1277,6 @@ function getDynamicModel({ requestContext }) {
1284
1277
  const thinkingLevel = harnessContext?.state?.thinkingLevel;
1285
1278
  return resolveModel(modelId, { thinkingLevel, requestContext });
1286
1279
  }
1287
- var _execFileAsync;
1288
- async function execFileAsync(file, args, options) {
1289
- if (!_execFileAsync) {
1290
- const cp = await import('child_process');
1291
- _execFileAsync = util.promisify(cp.execFile);
1292
- }
1293
- return _execFileAsync(file, args, options);
1294
- }
1295
- var GITHUB_SUBSCRIBE_PR_TAG = "github-subscribe-pr";
1296
- var GITHUB_UNSUBSCRIBE_PR_TAG = "github-unsubscribe-pr";
1297
- var GITHUB_SYNC_STATUS_TAG = "github-sync-status";
1298
- var GITHUB_SIGNALS_METADATA_KEY = "githubSignals";
1299
- var createGithubTool = tools.createTool;
1300
- function isPlainObject(value) {
1301
- return typeof value === "object" && value !== null && !Array.isArray(value);
1302
- }
1303
- function readString(value) {
1304
- return typeof value === "string" && value.length > 0 ? value : void 0;
1305
- }
1306
- function readNumber(value) {
1307
- if (typeof value === "number" && Number.isInteger(value) && value > 0) return value;
1308
- if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
1309
- return void 0;
1310
- }
1311
- function stableJson(value) {
1312
- if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
1313
- if (isPlainObject(value)) {
1314
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
1315
- }
1316
- return JSON.stringify(value);
1317
- }
1318
- function snapshotHash(value) {
1319
- return crypto.createHash("sha256").update(stableJson(value)).digest("hex");
1320
- }
1321
- function resolveHomePath(path2) {
1322
- return path2.startsWith("~/") ? path.join(os.homedir(), path2.slice(2)) : path2;
1323
- }
1324
- async function getGitcrawlDbPath() {
1325
- if (process.env.GITCRAWL_DB_PATH) return resolveHomePath(process.env.GITCRAWL_DB_PATH);
1326
- const configPath = process.env.GITCRAWL_CONFIG_PATH ?? path.join(os.homedir(), ".config", "gitcrawl", "config.toml");
1327
- try {
1328
- const config = await promises.readFile(resolveHomePath(configPath), "utf8");
1329
- const match = /^\s*db_path\s*=\s*['\"]([^'\"]+)['\"]/m.exec(config);
1330
- if (match?.[1]) return resolveHomePath(match[1]);
1331
- } catch {
1332
- }
1333
- return path.join(os.homedir(), ".config", "gitcrawl", "gitcrawl.db");
1334
- }
1335
- async function queryGitcrawlDb(sql) {
1336
- const dbPath = await getGitcrawlDbPath();
1337
- const { stdout } = await execFileAsync("sqlite3", ["-json", dbPath, sql], { maxBuffer: 10 * 1024 * 1024 });
1338
- return JSON.parse(stdout || "[]");
1339
- }
1340
- function sqlString(value) {
1341
- return `'${value.replaceAll("'", "''")}'`;
1342
- }
1343
- function getSignalMetadata(message) {
1344
- if (message.role !== "signal") return void 0;
1345
- const signal = message.content.metadata?.signal;
1346
- return isPlainObject(signal) ? signal : void 0;
1347
- }
1348
- function getGithubMetadata(threadMetadata) {
1349
- const mastra2 = isPlainObject(threadMetadata?.mastra) ? threadMetadata.mastra : {};
1350
- const githubSignals = isPlainObject(mastra2[GITHUB_SIGNALS_METADATA_KEY]) ? mastra2[GITHUB_SIGNALS_METADATA_KEY] : {};
1351
- const rawSubscriptions = Array.isArray(githubSignals.subscriptions) ? githubSignals.subscriptions : [];
1352
- const subscriptions = [];
1353
- for (const rawSubscription of rawSubscriptions) {
1354
- if (!isPlainObject(rawSubscription)) continue;
1355
- const owner = readString(rawSubscription.owner);
1356
- const repo = readString(rawSubscription.repo);
1357
- const number = readNumber(rawSubscription.number);
1358
- const subscribedAt = readString(rawSubscription.subscribedAt);
1359
- const updatedAt = readString(rawSubscription.updatedAt);
1360
- const lastSubscribeSignalId = readString(rawSubscription.lastSubscribeSignalId);
1361
- if (!owner || !repo || !number || !subscribedAt || !updatedAt || !lastSubscribeSignalId) continue;
1362
- subscriptions.push({
1363
- owner,
1364
- repo,
1365
- number,
1366
- subscribedAt,
1367
- updatedAt,
1368
- lastSubscribeSignalId,
1369
- ...readString(rawSubscription.lastSyncAt) ? { lastSyncAt: readString(rawSubscription.lastSyncAt) } : {},
1370
- ...rawSubscription.lastSyncStatus === "success" || rawSubscription.lastSyncStatus === "error" || rawSubscription.lastSyncStatus === "skipped" ? { lastSyncStatus: rawSubscription.lastSyncStatus } : {},
1371
- ...readString(rawSubscription.lastSyncError) ? { lastSyncError: readString(rawSubscription.lastSyncError) } : {},
1372
- ...readString(rawSubscription.lastObservedGithubUpdatedAt) ? { lastObservedGithubUpdatedAt: readString(rawSubscription.lastObservedGithubUpdatedAt) } : {},
1373
- ...readString(rawSubscription.lastObservedContentHash) ? { lastObservedContentHash: readString(rawSubscription.lastObservedContentHash) } : {},
1374
- ...readString(rawSubscription.lastObservedThreadContentHash) ? { lastObservedThreadContentHash: readString(rawSubscription.lastObservedThreadContentHash) } : {},
1375
- ...readString(rawSubscription.lastObservedHeadSha) ? { lastObservedHeadSha: readString(rawSubscription.lastObservedHeadSha) } : {},
1376
- ...readString(rawSubscription.lastObservedState) ? { lastObservedState: readString(rawSubscription.lastObservedState) } : {},
1377
- ...readString(rawSubscription.lastObservedMergeableState) ? { lastObservedMergeableState: readString(rawSubscription.lastObservedMergeableState) } : {},
1378
- ...readString(rawSubscription.lastObservedCiState) ? { lastObservedCiState: readString(rawSubscription.lastObservedCiState) } : {},
1379
- ...readString(rawSubscription.lastObservedReviewStateHash) ? { lastObservedReviewStateHash: readString(rawSubscription.lastObservedReviewStateHash) } : {},
1380
- ...readString(rawSubscription.lastNotificationAt) ? { lastNotificationAt: readString(rawSubscription.lastNotificationAt) } : {},
1381
- ...readString(rawSubscription.lastNotificationKind) ? { lastNotificationKind: readString(rawSubscription.lastNotificationKind) } : {},
1382
- ...rawSubscription.lastNotificationPriority === "medium" || rawSubscription.lastNotificationPriority === "high" ? { lastNotificationPriority: rawSubscription.lastNotificationPriority } : {},
1383
- ...readString(rawSubscription.lastNotificationSummary) ? { lastNotificationSummary: readString(rawSubscription.lastNotificationSummary) } : {}
1384
- });
1385
- }
1386
- return {
1387
- subscriptions,
1388
- ...githubSignals.subscriptionHintShown === true ? { subscriptionHintShown: true } : {}
1389
- };
1390
- }
1391
- function setGithubMetadata(threadMetadata, githubSignals) {
1392
- const existing = threadMetadata ?? {};
1393
- const mastra2 = isPlainObject(existing.mastra) ? existing.mastra : {};
1394
- const existingGithubSignals = isPlainObject(mastra2[GITHUB_SIGNALS_METADATA_KEY]) ? mastra2[GITHUB_SIGNALS_METADATA_KEY] : {};
1395
- return {
1396
- ...existing,
1397
- mastra: {
1398
- ...mastra2,
1399
- [GITHUB_SIGNALS_METADATA_KEY]: {
1400
- ...existingGithubSignals,
1401
- ...githubSignals
1402
- }
1403
- }
1404
- };
1405
- }
1406
- function getFailingChecks(snapshot) {
1407
- return (snapshot.checks ?? []).filter((check) => check.conclusion === "failure" || check.conclusion === "timed_out");
1408
- }
1409
- function getPendingChecks(snapshot) {
1410
- return (snapshot.checks ?? []).filter((check) => check.status && check.status !== "completed");
1411
- }
1412
- function getPrLabel(subscription, snapshot) {
1413
- const pr = `${subscription.owner}/${subscription.repo}#${subscription.number}`;
1414
- return snapshot?.title ? `${pr}: ${snapshot.title}` : pr;
1415
- }
1416
- function getMergedNotificationSummary(label) {
1417
- return `${label} was merged. This thread has been automatically unsubscribed from this PR. Resubscribe if you still need updates.`;
1418
- }
1419
- function getCheckUpdatedTime(check) {
1420
- const value = check.updatedAt ? Date.parse(check.updatedAt) : Number.NaN;
1421
- return Number.isFinite(value) ? value : 0;
1422
- }
1423
- function getCheckKey(check) {
1424
- return `${check.name || "check"}:${check.detailsUrl || check.workflowName || ""}`;
1425
- }
1426
- function normalizeGithubChecksForSnapshot(input) {
1427
- const latestCheckUpdatedAt = input.checkRows.reduce(
1428
- (latest, check) => Math.max(latest, getCheckUpdatedTime(check)),
1429
- 0
1430
- );
1431
- const rows = [
1432
- ...input.checkRows,
1433
- ...input.workflowRows.filter(
1434
- (workflow) => input.checkRows.length === 0 || getCheckUpdatedTime(workflow) >= latestCheckUpdatedAt
1435
- )
1436
- ];
1437
- const byKey = /* @__PURE__ */ new Map();
1438
- for (const row of rows) {
1439
- const key = getCheckKey(row);
1440
- const existing = byKey.get(key);
1441
- if (!existing) {
1442
- byKey.set(key, row);
1443
- continue;
1444
- }
1445
- const rowTime = getCheckUpdatedTime(row);
1446
- const existingTime = getCheckUpdatedTime(existing);
1447
- if (rowTime > existingTime || rowTime === existingTime && existing.source === "workflow" && row.source === "check") {
1448
- byKey.set(key, row);
1449
- }
1450
- }
1451
- return [...byKey.values()].map(({ source: _source, ...check }) => check).sort((a, b) => `${a.name}:${a.detailsUrl ?? ""}`.localeCompare(`${b.name}:${b.detailsUrl ?? ""}`));
1452
- }
1453
- function isBotOnlyActivity(snapshot) {
1454
- return snapshot.latestCommentIsBot === true && (!snapshot.ciState || snapshot.ciState === "unknown");
1455
- }
1456
- function stringifyEvidence(value) {
1457
- if (typeof value === "string") return value;
1458
- try {
1459
- return JSON.stringify(value);
1460
- } catch {
1461
- return "";
1462
- }
1463
- }
1464
- function detectPrWorkEvidence(input) {
1465
- const evidence = [
1466
- input.text ?? "",
1467
- ...(input.toolCalls ?? []).map((toolCall) => `${toolCall.toolName} ${stringifyEvidence(toolCall.args)}`)
1468
- ].join("\n");
1469
- if (!evidence.trim()) return void 0;
1470
- const url = /github\.com\/([^\s/#]+)\/([^\s/#]+)\/pull\/(\d+)/i.exec(evidence);
1471
- if (url?.[1] && url[2] && url[3]) return { owner: url[1], repo: url[2], number: Number(url[3]) };
1472
- const repoRef = /\b([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(\d+)\b/.exec(evidence);
1473
- if (repoRef?.[1] && repoRef[2] && repoRef[3])
1474
- return { owner: repoRef[1], repo: repoRef[2], number: Number(repoRef[3]) };
1475
- const ghCommand = /\bgh\s+(?:pr\s+(?:view|checks|status|comment|diff|checkout)|run\s+(?:rerun|view))\b/i.test(
1476
- evidence
1477
- );
1478
- if (!ghCommand) return void 0;
1479
- const numberMatch = /(?:^|\s)#?(\d{2,})(?:\s|$)/.exec(evidence);
1480
- return numberMatch?.[1] ? { number: Number(numberMatch[1]) } : void 0;
1481
- }
1482
- function classifyGithubActivityNotification(input) {
1483
- const pr = `${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}`;
1484
- const label = getPrLabel(input.subscription, input.snapshot);
1485
- if (input.snapshot.state && input.subscription.lastObservedState !== input.snapshot.state) {
1486
- if (input.snapshot.state === "merged")
1487
- return {
1488
- kind: "pull-request-merged",
1489
- priority: "high",
1490
- summary: getMergedNotificationSummary(label)
1491
- };
1492
- if (input.snapshot.state === "closed")
1493
- return { kind: "pull-request-closed", priority: "high", summary: `${label} was closed` };
1494
- if (input.subscription.lastObservedState && input.snapshot.state === "open")
1495
- return { kind: "pull-request-reopened", priority: "medium", summary: `${label} was reopened` };
1496
- }
1497
- const failingChecks = getFailingChecks(input.snapshot);
1498
- if (input.snapshot.ciState === "failure" && input.subscription.lastObservedCiState !== "failure") {
1499
- const names = failingChecks.slice(0, 3).map((check) => check.name).join(", ");
1500
- return {
1501
- kind: "pull-request-ci-failure",
1502
- priority: "high",
1503
- summary: `${pr} has failing CI${names ? `: ${names}` : ""}`
1504
- };
1505
- }
1506
- if (input.snapshot.mergeableState === "dirty" && input.subscription.lastObservedMergeableState !== "dirty") {
1507
- return {
1508
- kind: "pull-request-conflict",
1509
- priority: "high",
1510
- summary: `${pr} has merge conflicts${input.snapshot.title ? `: ${input.snapshot.title}` : ""}`
1511
- };
1512
- }
1513
- if (input.snapshot.mergeableState && input.subscription.lastObservedMergeableState === "dirty" && input.snapshot.mergeableState !== "dirty") {
1514
- return {
1515
- kind: "pull-request-conflict-resolved",
1516
- priority: "medium",
1517
- summary: `${pr} merge conflicts were resolved`
1518
- };
1519
- }
1520
- if (input.snapshot.mergeableState === "dirty") return void 0;
1521
- if (input.snapshot.ciState === "success" && input.subscription.lastObservedCiState && input.subscription.lastObservedCiState !== "success") {
1522
- return { kind: "pull-request-ci-recovered", priority: "medium", summary: `${pr} CI recovered` };
1523
- }
1524
- if (input.snapshot.reviewStateHash && input.subscription.lastObservedReviewStateHash && input.snapshot.reviewStateHash !== input.subscription.lastObservedReviewStateHash && (input.snapshot.unresolvedReviewThreads ?? 0) > 0) {
1525
- return {
1526
- kind: "pull-request-review-activity",
1527
- priority: "medium",
1528
- summary: `${pr} has ${input.snapshot.unresolvedReviewThreads} unresolved review thread${input.snapshot.unresolvedReviewThreads === 1 ? "" : "s"}`
1529
- };
1530
- }
1531
- const pendingChecks = getPendingChecks(input.snapshot);
1532
- if (input.snapshot.ciState === "pending" && input.subscription.lastObservedCiState !== "pending" && pendingChecks.length > 0) {
1533
- const names = pendingChecks.slice(0, 3).map((check) => check.name).join(", ");
1534
- return {
1535
- kind: "pull-request-ci-pending",
1536
- priority: "medium",
1537
- summary: `${pr} has CI still running${names ? `: ${names}` : ""}`
1538
- };
1539
- }
1540
- if (input.snapshot.ciState === "pending" && input.subscription.lastObservedCiState === "pending") return void 0;
1541
- if (isBotOnlyActivity(input.snapshot)) return void 0;
1542
- return {
1543
- kind: "pull-request-activity",
1544
- priority: "medium",
1545
- summary: `${pr} has new activity${input.snapshot.title ? `: ${input.snapshot.title}` : ""}`
1546
- };
1547
- }
1548
- function classifyGithubBaselineNotification(input) {
1549
- const pr = `${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}`;
1550
- const failingChecks = getFailingChecks(input.snapshot);
1551
- const reviewCount = input.snapshot.unresolvedReviewThreads ?? 0;
1552
- const high = input.snapshot.ciState === "failure" || input.snapshot.mergeableState === "dirty";
1553
- const details = [
1554
- input.snapshot.state ? `state: ${input.snapshot.state}` : void 0,
1555
- input.snapshot.ciState && input.snapshot.ciState !== "unknown" ? `CI: ${input.snapshot.ciState}` : void 0,
1556
- input.snapshot.mergeableState ? `mergeability: ${input.snapshot.mergeableState}` : void 0,
1557
- reviewCount > 0 ? `${reviewCount} unresolved review thread${reviewCount === 1 ? "" : "s"}` : void 0,
1558
- failingChecks.length > 0 ? `failing: ${failingChecks.slice(0, 3).map((check) => check.name).join(", ")}` : void 0
1559
- ].filter(Boolean);
1560
- return {
1561
- kind: "pull-request-baseline",
1562
- priority: high ? "high" : "medium",
1563
- summary: `${pr} subscribed${input.snapshot.title ? `: ${input.snapshot.title}` : ""}${details.length ? ` (${details.join("; ")})` : ""}`
1564
- };
1565
- }
1566
- function applySnapshotCursor(subscription, snapshot) {
1567
- if (snapshot.githubUpdatedAt) subscription.lastObservedGithubUpdatedAt = snapshot.githubUpdatedAt;
1568
- if (snapshot.contentHash) subscription.lastObservedContentHash = snapshot.contentHash;
1569
- if (snapshot.threadContentHash) subscription.lastObservedThreadContentHash = snapshot.threadContentHash;
1570
- if (snapshot.headSha) subscription.lastObservedHeadSha = snapshot.headSha;
1571
- if (snapshot.state) subscription.lastObservedState = snapshot.state;
1572
- if (snapshot.mergeableState) subscription.lastObservedMergeableState = snapshot.mergeableState;
1573
- if (snapshot.ciState) subscription.lastObservedCiState = snapshot.ciState;
1574
- if (snapshot.reviewStateHash) subscription.lastObservedReviewStateHash = snapshot.reviewStateHash;
1575
- }
1576
- function parseGitHubRemoteUrl(remoteUrl) {
1577
- const trimmed = remoteUrl.trim().replace(/\.git$/, "");
1578
- const httpsMatch = /^https:\/\/github\.com\/([^/]+)\/([^/]+)$/.exec(trimmed);
1579
- if (httpsMatch?.[1] && httpsMatch[2]) return { owner: httpsMatch[1], repo: httpsMatch[2] };
1580
- const sshMatch = /^git@github\.com:([^/]+)\/([^/]+)$/.exec(trimmed);
1581
- if (sshMatch?.[1] && sshMatch[2]) return { owner: sshMatch[1], repo: sshMatch[2] };
1582
- return void 0;
1583
- }
1584
- var GitRemoteRepositoryResolver = class {
1585
- async resolveRepository(input) {
1586
- try {
1587
- const { stdout } = await execFileAsync("git", ["remote", "get-url", "origin"], {
1588
- cwd: input.cwd,
1589
- signal: input.abortSignal
1590
- });
1591
- return parseGitHubRemoteUrl(stdout);
1592
- } catch {
1593
- return void 0;
1594
- }
1595
- }
1596
- };
1597
- var GitcrawlSyncClient = class {
1598
- #command;
1599
- constructor(options = {}) {
1600
- this.#command = options.command ?? "gitcrawl";
1601
- }
1602
- async syncPullRequest(input) {
1603
- try {
1604
- const args = [
1605
- "sync",
1606
- `${input.owner}/${input.repo}`,
1607
- "--numbers",
1608
- String(input.number),
1609
- ...input.includeComments === false ? [] : ["--include-comments"],
1610
- "--with",
1611
- "pr-details",
1612
- "--json"
1613
- ];
1614
- const { stdout, stderr } = await execFileAsync(this.#command, args, {
1615
- cwd: input.cwd,
1616
- signal: input.abortSignal,
1617
- maxBuffer: 10 * 1024 * 1024
1618
- });
1619
- return { ok: true, stdout, stderr };
1620
- } catch (error) {
1621
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
1622
- }
1623
- }
1624
- async getPullRequestSnapshot(input) {
1625
- try {
1626
- const { stdout } = await execFileAsync(
1627
- this.#command,
1628
- ["threads", `${input.owner}/${input.repo}`, "--numbers", String(input.number), "--json"],
1629
- {
1630
- cwd: input.cwd,
1631
- signal: input.abortSignal,
1632
- maxBuffer: 10 * 1024 * 1024
1633
- }
1634
- );
1635
- const parsed = JSON.parse(stdout);
1636
- const thread = parsed.threads?.find((item) => readNumber(item.number) === input.number);
1637
- if (!thread) return void 0;
1638
- const owner = sqlString(input.owner);
1639
- const repo = sqlString(input.repo);
1640
- const number = input.number;
1641
- const [threadDetails] = await queryGitcrawlDb(`select t.state, t.closed_at_gh, t.merged_at_gh
1642
- from threads t
1643
- join repositories r on r.id=t.repo_id
1644
- where r.owner=${owner} and r.name=${repo} and t.number=${number}
1645
- limit 1`);
1646
- const [details] = await queryGitcrawlDb(`select d.head_sha, d.head_ref, d.mergeable_state,
1647
- json_extract(d.raw_json, '$.merged_at') as merged_at
1648
- from pull_request_details d
1649
- join threads t on t.id=d.thread_id
1650
- join repositories r on r.id=t.repo_id
1651
- where r.owner=${owner} and r.name=${repo} and t.number=${number}
1652
- limit 1`);
1653
- const headSha = readString(details?.head_sha);
1654
- const checkRows = await queryGitcrawlDb(`select c.name, c.status, c.conclusion, c.workflow_name, c.details_url,
1655
- coalesce(c.completed_at, c.started_at, c.fetched_at) as updated_at
1656
- from pull_request_checks c
1657
- join threads t on t.id=c.thread_id
1658
- join repositories r on r.id=t.repo_id
1659
- where r.owner=${owner} and r.name=${repo} and t.number=${number}${headSha ? ` and json_extract(c.raw_json, '$.head_sha')=${sqlString(headSha)}` : ""}`);
1660
- const workflowRows = details?.head_sha ? await queryGitcrawlDb(`select workflow_name, status, conclusion, html_url, updated_at_gh
1661
- from github_workflow_runs w
1662
- join repositories r on r.id=w.repo_id
1663
- where r.owner=${owner} and r.name=${repo} and w.head_sha=${sqlString(details.head_sha)}`) : [];
1664
- const [reviewState] = await queryGitcrawlDb(`select count(*) as unresolved_count,
1665
- max(coalesce(first_comment_updated_at, first_comment_created_at, fetched_at)) as latest_review_thread_at
1666
- from pull_request_review_threads rt
1667
- join threads t on t.id=rt.thread_id
1668
- join repositories r on r.id=t.repo_id
1669
- where r.owner=${owner} and r.name=${repo} and t.number=${number} and rt.is_resolved=0`);
1670
- const [latestComment] = await queryGitcrawlDb(`select c.author_login, c.author_type, c.is_bot
1671
- from comments c
1672
- join threads t on t.id=c.thread_id
1673
- join repositories r on r.id=t.repo_id
1674
- where r.owner=${owner} and r.name=${repo} and t.number=${number}
1675
- order by coalesce(c.updated_at_gh, c.created_at_gh) desc
1676
- limit 1`);
1677
- const checks = normalizeGithubChecksForSnapshot({
1678
- checkRows: checkRows.map((row) => ({
1679
- source: "check",
1680
- name: readString(row.name) ?? "check",
1681
- status: readString(row.status),
1682
- conclusion: readString(row.conclusion),
1683
- workflowName: readString(row.workflow_name),
1684
- detailsUrl: readString(row.details_url),
1685
- updatedAt: readString(row.updated_at)
1686
- })),
1687
- workflowRows: workflowRows.map((row) => ({
1688
- source: "workflow",
1689
- name: readString(row.workflow_name) ?? "workflow",
1690
- status: readString(row.status),
1691
- conclusion: readString(row.conclusion),
1692
- workflowName: readString(row.workflow_name),
1693
- detailsUrl: readString(row.html_url),
1694
- updatedAt: readString(row.updated_at_gh)
1695
- }))
1696
- });
1697
- const ciState = checks.some((check) => check.conclusion === "failure" || check.conclusion === "timed_out") ? "failure" : checks.some((check) => check.status && check.status !== "completed") ? "pending" : checks.length > 0 ? "success" : "unknown";
1698
- const threadContentHash = readString(thread.content_hash);
1699
- const unresolvedReviewThreads = Number(reviewState?.unresolved_count ?? 0);
1700
- const reviewStateHash = snapshotHash({
1701
- unresolvedReviewThreads,
1702
- latestReviewThreadAt: reviewState?.latest_review_thread_at
1703
- });
1704
- const contentHash = snapshotHash({
1705
- threadContentHash,
1706
- state: thread.state,
1707
- headSha: details?.head_sha,
1708
- mergeableState: details?.mergeable_state,
1709
- ciState,
1710
- reviewStateHash,
1711
- checks: checks.map((check) => ({
1712
- name: check.name,
1713
- status: check.status,
1714
- conclusion: check.conclusion,
1715
- detailsUrl: check.detailsUrl,
1716
- updatedAt: check.updatedAt
1717
- }))
1718
- });
1719
- return {
1720
- title: readString(thread.title),
1721
- state: readString(details?.merged_at) || readString(threadDetails?.merged_at_gh) ? "merged" : readString(threadDetails?.state) ?? readString(thread.state),
1722
- htmlUrl: readString(thread.html_url),
1723
- githubUpdatedAt: readString(thread.updated_at_gh),
1724
- closedAt: readString(threadDetails?.closed_at_gh),
1725
- mergedAt: readString(details?.merged_at) ?? readString(threadDetails?.merged_at_gh),
1726
- threadContentHash,
1727
- contentHash,
1728
- headSha: readString(details?.head_sha),
1729
- headRef: readString(details?.head_ref),
1730
- mergeableState: readString(details?.mergeable_state),
1731
- checks,
1732
- ciState,
1733
- unresolvedReviewThreads,
1734
- reviewStateHash,
1735
- latestReviewThreadAt: readString(reviewState?.latest_review_thread_at),
1736
- latestCommentAuthor: readString(latestComment?.author_login),
1737
- latestCommentAuthorType: readString(latestComment?.author_type),
1738
- latestCommentIsBot: latestComment?.is_bot === 1
1739
- };
1740
- } catch {
1741
- return void 0;
1742
- }
1743
- }
1744
- };
1745
- var GithubSignals = class {
1746
- id = "github-signals";
1747
- name = "GitHub Signals";
1748
- mastra;
1749
- static signals = {
1750
- subscribeToPR(input) {
1751
- const normalized = typeof input === "number" ? { number: input } : input;
1752
- return {
1753
- type: "reactive",
1754
- tagName: GITHUB_SUBSCRIBE_PR_TAG,
1755
- contents: `Subscribe to GitHub PR #${normalized.number}`,
1756
- attributes: {
1757
- ...normalized.owner ? { owner: normalized.owner } : {},
1758
- ...normalized.repo ? { repo: normalized.repo } : {},
1759
- number: normalized.number
1760
- },
1761
- metadata: {
1762
- github: {
1763
- action: "subscribeToPR",
1764
- ...normalized
1765
- }
1766
- }
1767
- };
1768
- },
1769
- unsubscribeFromPR(input) {
1770
- const normalized = typeof input === "number" ? { number: input } : input;
1771
- return {
1772
- type: "reactive",
1773
- tagName: GITHUB_UNSUBSCRIBE_PR_TAG,
1774
- contents: `Unsubscribe from GitHub PR #${normalized.number}`,
1775
- attributes: {
1776
- ...normalized.owner ? { owner: normalized.owner } : {},
1777
- ...normalized.repo ? { repo: normalized.repo } : {},
1778
- number: normalized.number
1779
- },
1780
- metadata: {
1781
- github: {
1782
- action: "unsubscribeFromPR",
1783
- ...normalized
1784
- }
1785
- }
1786
- };
1787
- }
1788
- };
1789
- #options;
1790
- #syncClient;
1791
- #repositoryResolver;
1792
- #polling = /* @__PURE__ */ new Map();
1793
- #agent;
1794
- #agentOptions = {};
1795
- #subscriptionsChangedHandler;
1796
- constructor(options = {}) {
1797
- this.#options = options;
1798
- this.#syncClient = options.syncClient ?? new GitcrawlSyncClient({ command: options.gitcrawlCommand });
1799
- this.#repositoryResolver = options.repositoryResolver ?? new GitRemoteRepositoryResolver();
1800
- }
1801
- addAgent(agent, options = {}) {
1802
- this.#agent = agent;
1803
- this.#agentOptions = options;
1804
- }
1805
- onSubscriptionsChanged(handler) {
1806
- this.#subscriptionsChangedHandler = handler;
1807
- }
1808
- __registerMastra(mastra2) {
1809
- this.mastra = mastra2;
1810
- }
1811
- async syncThreadNow(input) {
1812
- return this.#pollThread(input, { includeComments: true });
1813
- }
1814
- async subscribeThreadToPR(input) {
1815
- const pr = typeof input.pr === "number" ? { number: input.pr } : input.pr;
1816
- return this.#subscribe({
1817
- id: `github-command-subscribe-${crypto.randomUUID()}`,
1818
- ...pr,
1819
- threadId: input.threadId,
1820
- resourceId: input.resourceId
1821
- });
1822
- }
1823
- async unsubscribeThreadFromPR(input) {
1824
- const pr = typeof input.pr === "number" ? { number: input.pr } : input.pr;
1825
- return this.#unsubscribe({
1826
- id: `github-command-unsubscribe-${crypto.randomUUID()}`,
1827
- ...pr,
1828
- threadId: input.threadId,
1829
- resourceId: input.resourceId
1830
- });
1831
- }
1832
- async startPollingForThread(input, options = {}) {
1833
- const subscriptions = await this.#getThreadSubscriptions(input);
1834
- if (subscriptions.length === 0) {
1835
- this.stopPollingForThread(input);
1836
- return false;
1837
- }
1838
- const key = this.#pollingKey(input);
1839
- for (const [pollingKey, state] of this.#polling.entries()) {
1840
- if (pollingKey === key) continue;
1841
- clearInterval(state.timer);
1842
- this.#polling.delete(pollingKey);
1843
- }
1844
- if (this.#polling.has(key)) return true;
1845
- let scheduledPollCount = options.pollImmediately ? 1 : 0;
1846
- const runPoll = (pollOptions = {}) => {
1847
- void this.#pollThread(input, pollOptions).catch((error) => {
1848
- console.warn("GitHub PR polling failed:", error);
1849
- });
1850
- };
1851
- const timer = setInterval(() => {
1852
- scheduledPollCount += 1;
1853
- runPoll({ includeComments: scheduledPollCount % 2 === 1 });
1854
- }, this.#options.pollIntervalMs ?? 3e5);
1855
- if (options.pollImmediately) runPoll({ includeComments: true });
1856
- timer.unref?.();
1857
- this.#polling.set(key, { ...input, timer, running: false });
1858
- return true;
1859
- }
1860
- stopPollingForThread(input) {
1861
- const key = this.#pollingKey(input);
1862
- const state = this.#polling.get(key);
1863
- if (!state) return;
1864
- clearInterval(state.timer);
1865
- this.#polling.delete(key);
1866
- }
1867
- isPollingThread(input) {
1868
- return this.#polling.has(this.#pollingKey(input));
1869
- }
1870
- getPollIntervalMs() {
1871
- return this.#options.pollIntervalMs ?? 3e5;
1872
- }
1873
- stopAllPolling() {
1874
- for (const state of this.#polling.values()) clearInterval(state.timer);
1875
- this.#polling.clear();
1876
- }
1877
- async pollThreadNow(input) {
1878
- return this.#pollThread(input, { includeComments: true });
1879
- }
1880
- async processInputStep(args) {
1881
- const tools = this.#createTools(args);
1882
- if (args.stepNumber !== 0) return { tools };
1883
- const signal = this.#findLatestGithubSignal(args.messages);
1884
- if (!signal) return { tools };
1885
- const threadContext = this.#getThreadContext(args);
1886
- if (signal.tagName === GITHUB_UNSUBSCRIBE_PR_TAG) {
1887
- const result2 = await this.#unsubscribe({ ...signal, ...threadContext, abortSignal: args.abortSignal });
1888
- await this.#sendStatus(args, result2, {
1889
- status: result2.removed ? "unsubscribed" : "not_subscribed",
1890
- action: "unsubscribeFromPR",
1891
- message: result2.removed ? `Unsubscribed from ${result2.owner}/${result2.repo}#${result2.number}.` : `No GitHub subscription found for ${result2.owner}/${result2.repo}#${result2.number}.`
1892
- });
1893
- return { tools };
1894
- }
1895
- const result = await this.#subscribe({ ...signal, ...threadContext, abortSignal: args.abortSignal });
1896
- if (result.alreadyProcessed) return { tools };
1897
- await this.#sendStatus(args, result, {
1898
- status: result.syncResult?.ok === false ? "sync_error" : "subscribed",
1899
- action: "subscribeToPR",
1900
- message: result.syncResult?.ok === false ? `Subscribed to ${result.owner}/${result.repo}#${result.number}, but gitcrawl sync failed: ${result.syncResult.error}` : `Subscribed to ${result.owner}/${result.repo}#${result.number}.`
1901
- });
1902
- return { tools };
1903
- }
1904
- async processOutputStep(args) {
1905
- const evidence = detectPrWorkEvidence({ text: args.text, toolCalls: args.toolCalls });
1906
- if (!evidence) return args.messages;
1907
- const threadContext = this.#getThreadContext(args);
1908
- if (!threadContext.threadId || !threadContext.resourceId) return args.messages;
1909
- const { threadStore, loadedThread } = await this.#loadThread(threadContext);
1910
- const githubMetadata = getGithubMetadata(loadedThread.metadata);
1911
- if (githubMetadata.subscriptionHintShown || githubMetadata.subscriptions.length > 0) return args.messages;
1912
- let repository;
1913
- try {
1914
- repository = await this.#resolveRepository({
1915
- id: "github-subscription-hint",
1916
- owner: evidence.owner,
1917
- repo: evidence.repo,
1918
- number: evidence.number
1919
- });
1920
- } catch {
1921
- return args.messages;
1922
- }
1923
- await threadStore.saveThread({
1924
- thread: {
1925
- ...loadedThread,
1926
- id: threadContext.threadId,
1927
- resourceId: threadContext.resourceId,
1928
- createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
1929
- updatedAt: /* @__PURE__ */ new Date(),
1930
- metadata: setGithubMetadata(loadedThread.metadata, { ...githubMetadata, subscriptionHintShown: true })
1931
- }
1932
- });
1933
- await args.sendSignal?.({
1934
- type: "reactive",
1935
- tagName: "system-reminder",
1936
- contents: `Looks like you're working with ${repository.owner}/${repository.repo}#${evidence.number}. Use /github subscribe ${evidence.number} or the github_subscribe_pr tool to follow updates.`,
1937
- attributes: { type: "github-subscription-hint" },
1938
- metadata: {
1939
- github: {
1940
- action: "subscriptionHint",
1941
- owner: repository.owner,
1942
- repo: repository.repo,
1943
- number: evidence.number
1944
- }
1945
- }
1946
- });
1947
- return args.messages;
1948
- }
1949
- async #resolveThreadStore() {
1950
- if (this.#options.threadStore) return this.#options.threadStore;
1951
- const storage = this.mastra?.getStorage?.();
1952
- const memoryStore = storage?.getStore ? await storage.getStore("memory") : void 0;
1953
- return memoryStore;
1954
- }
1955
- #getThreadContext(args) {
1956
- const memoryContext = args.requestContext?.get("MastraMemory");
1957
- return { threadId: memoryContext?.thread?.id, resourceId: memoryContext?.resourceId };
1958
- }
1959
- #createTools(args) {
1960
- const threadContext = this.#getThreadContext(args);
1961
- return {
1962
- ...args.tools,
1963
- github_subscribe_pr: createGithubTool({
1964
- id: "github_subscribe_pr",
1965
- description: "Subscribe this thread to a GitHub pull request. Syncs only the requested PR with gitcrawl and stores the subscription on the thread.",
1966
- inputSchema: z__default.default.object({
1967
- number: z__default.default.number().int().positive(),
1968
- owner: z__default.default.string().optional(),
1969
- repo: z__default.default.string().optional()
1970
- }),
1971
- execute: async (input) => {
1972
- const result = await this.#subscribe({
1973
- id: `github-tool-subscribe-${crypto.randomUUID()}`,
1974
- owner: input.owner,
1975
- repo: input.repo,
1976
- number: input.number,
1977
- threadId: threadContext.threadId,
1978
- resourceId: threadContext.resourceId
1979
- });
1980
- return {
1981
- subscribed: true,
1982
- owner: result.owner,
1983
- repo: result.repo,
1984
- number: result.number,
1985
- syncStatus: result.syncResult?.ok === false ? "error" : result.syncResult ? "success" : void 0,
1986
- message: result.syncResult?.ok === false ? `Subscribed to ${result.owner}/${result.repo}#${result.number}, but gitcrawl sync failed: ${result.syncResult.error}` : `Subscribed to ${result.owner}/${result.repo}#${result.number}.`
1987
- };
1988
- }
1989
- }),
1990
- github_unsubscribe_pr: createGithubTool({
1991
- id: "github_unsubscribe_pr",
1992
- description: "Unsubscribe this thread from a GitHub pull request.",
1993
- inputSchema: z__default.default.object({
1994
- number: z__default.default.number().int().positive(),
1995
- owner: z__default.default.string().optional(),
1996
- repo: z__default.default.string().optional()
1997
- }),
1998
- execute: async (input) => {
1999
- const result = await this.#unsubscribe({
2000
- id: `github-tool-unsubscribe-${crypto.randomUUID()}`,
2001
- owner: input.owner,
2002
- repo: input.repo,
2003
- number: input.number,
2004
- threadId: threadContext.threadId,
2005
- resourceId: threadContext.resourceId
2006
- });
2007
- return {
2008
- unsubscribed: result.removed ?? false,
2009
- owner: result.owner,
2010
- repo: result.repo,
2011
- number: result.number,
2012
- remainingSubscriptions: result.remainingSubscriptions,
2013
- message: result.removed ? `Unsubscribed from ${result.owner}/${result.repo}#${result.number}.` : `No GitHub subscription found for ${result.owner}/${result.repo}#${result.number}.`
2014
- };
2015
- }
2016
- })
2017
- };
2018
- }
2019
- async #resolveRepository(input) {
2020
- const resolvedRepository = input.owner && input.repo ? { owner: input.owner, repo: input.repo } : this.#options.owner && this.#options.repo ? { owner: this.#options.owner, repo: this.#options.repo } : await this.#repositoryResolver.resolveRepository({
2021
- cwd: this.#options.cwd,
2022
- abortSignal: input.abortSignal
2023
- });
2024
- if (!resolvedRepository?.owner || !resolvedRepository.repo) {
2025
- throw new Error(
2026
- "GitHub PR subscription requires owner and repo. Run inside a GitHub repo or pass owner and repo."
2027
- );
2028
- }
2029
- return resolvedRepository;
2030
- }
2031
- async #loadThread(input) {
2032
- const threadStore = await this.#resolveThreadStore();
2033
- if (!threadStore) throw new Error("GitHub PR subscription requires memory-backed thread storage.");
2034
- if (!input.threadId || !input.resourceId)
2035
- throw new Error("GitHub PR subscription requires threadId and resourceId.");
2036
- const loadedThread = await threadStore.getThreadById({ threadId: input.threadId, resourceId: input.resourceId }) ?? void 0;
2037
- if (!loadedThread) throw new Error(`Could not load thread ${input.threadId}.`);
2038
- return { threadStore, loadedThread };
2039
- }
2040
- #pollingKey(input) {
2041
- return `${input.resourceId}:${input.threadId}`;
2042
- }
2043
- #getNotificationAgent(_input) {
2044
- if (this.#agent) return this.#agent;
2045
- const agentId = _input?.agentId ?? this.#options.agentId;
2046
- return agentId ? this.mastra?.getAgentById?.(agentId) : void 0;
2047
- }
2048
- async #getThreadSubscriptions(input) {
2049
- const { loadedThread } = await this.#loadThread(input);
2050
- return getGithubMetadata(loadedThread.metadata).subscriptions;
2051
- }
2052
- #notifySubscriptionsChanged(input) {
2053
- this.#subscriptionsChangedHandler?.(input);
2054
- }
2055
- async #pollThread(input, options = {}) {
2056
- const key = this.#pollingKey(input);
2057
- const state = this.#polling.get(key);
2058
- if (state?.running) {
2059
- return 0;
2060
- }
2061
- if (state) state.running = true;
2062
- try {
2063
- const { threadStore, loadedThread } = await this.#loadThread(input);
2064
- const githubMetadata = getGithubMetadata(loadedThread.metadata);
2065
- if (githubMetadata.subscriptions.length === 0) {
2066
- this.stopPollingForThread(input);
2067
- return 0;
2068
- }
2069
- const now = (/* @__PURE__ */ new Date()).toISOString();
2070
- const subscriptions = [];
2071
- for (const subscription of githubMetadata.subscriptions) {
2072
- const syncInput = {
2073
- owner: subscription.owner,
2074
- repo: subscription.repo,
2075
- number: subscription.number,
2076
- cwd: this.#options.cwd,
2077
- includeComments: options.includeComments
2078
- };
2079
- const syncResult = await this.#syncClient.syncPullRequest(syncInput);
2080
- const snapshot = syncResult.ok ? await this.#syncClient.getPullRequestSnapshot?.(syncInput) : void 0;
2081
- const nextSubscription = {
2082
- ...subscription,
2083
- updatedAt: now,
2084
- lastSyncAt: now,
2085
- lastSyncStatus: syncResult.ok ? "success" : "error"
2086
- };
2087
- if (syncResult.error) nextSubscription.lastSyncError = syncResult.error;
2088
- else delete nextSubscription.lastSyncError;
2089
- const previousGithubUpdatedAt = subscription.lastObservedGithubUpdatedAt;
2090
- const previousContentHash = subscription.lastObservedContentHash;
2091
- const previousThreadContentHash = subscription.lastObservedThreadContentHash;
2092
- const previousHeadSha = subscription.lastObservedHeadSha;
2093
- if (snapshot) applySnapshotCursor(nextSubscription, snapshot);
2094
- const isFirstObservation = syncResult.ok && snapshot && !previousGithubUpdatedAt && !previousContentHash;
2095
- const legacyAggregateChanged = previousContentHash && snapshot?.contentHash && previousContentHash !== snapshot.contentHash && !previousThreadContentHash && !previousHeadSha;
2096
- const changed = isFirstObservation || syncResult.ok && snapshot && (legacyAggregateChanged || previousThreadContentHash && snapshot.threadContentHash && previousThreadContentHash !== snapshot.threadContentHash || previousHeadSha && snapshot.headSha && previousHeadSha !== snapshot.headSha || subscription.lastObservedState && snapshot.state && subscription.lastObservedState !== snapshot.state || subscription.lastObservedMergeableState && snapshot.mergeableState && subscription.lastObservedMergeableState !== snapshot.mergeableState || subscription.lastObservedCiState && snapshot.ciState && subscription.lastObservedCiState !== snapshot.ciState || subscription.lastObservedReviewStateHash && snapshot.reviewStateHash && subscription.lastObservedReviewStateHash !== snapshot.reviewStateHash);
2097
- let shouldKeepSubscription = true;
2098
- if (changed) {
2099
- const notification = await this.#sendActivityNotification({
2100
- polling: input,
2101
- subscription,
2102
- snapshot,
2103
- previousGithubUpdatedAt,
2104
- previousContentHash
2105
- });
2106
- if (notification) {
2107
- nextSubscription.lastNotificationAt = now;
2108
- nextSubscription.lastNotificationKind = notification.kind;
2109
- nextSubscription.lastNotificationPriority = notification.priority;
2110
- nextSubscription.lastNotificationSummary = notification.summary;
2111
- shouldKeepSubscription = notification.kind !== "pull-request-merged";
2112
- }
2113
- }
2114
- if (shouldKeepSubscription) subscriptions.push(nextSubscription);
2115
- }
2116
- await threadStore.saveThread({
2117
- thread: {
2118
- ...loadedThread,
2119
- id: input.threadId,
2120
- resourceId: input.resourceId,
2121
- createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
2122
- updatedAt: /* @__PURE__ */ new Date(),
2123
- metadata: setGithubMetadata(loadedThread.metadata, { subscriptions })
2124
- }
2125
- });
2126
- this.#notifySubscriptionsChanged({ threadId: input.threadId, resourceId: input.resourceId, subscriptions });
2127
- if (subscriptions.length === 0) this.stopPollingForThread(input);
2128
- return subscriptions.length;
2129
- } catch (error) {
2130
- throw error;
2131
- } finally {
2132
- const latestState = this.#polling.get(key);
2133
- if (latestState) latestState.running = false;
2134
- }
2135
- }
2136
- async #sendGithubNotification(input) {
2137
- const failingChecks = getFailingChecks(input.snapshot);
2138
- const pendingChecks = getPendingChecks(input.snapshot);
2139
- const notificationInput = {
2140
- source: "github",
2141
- kind: input.notification.kind,
2142
- priority: input.notification.priority,
2143
- summary: input.notification.summary,
2144
- dedupeKey: `github:${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}:${input.dedupeSuffix}`,
2145
- coalesceKey: `github:${input.subscription.owner}/${input.subscription.repo}#${input.subscription.number}:${input.notification.kind}`,
2146
- attributes: {
2147
- owner: input.subscription.owner,
2148
- repo: input.subscription.repo,
2149
- number: input.subscription.number,
2150
- ...input.snapshot.title ? { title: input.snapshot.title } : {},
2151
- ...input.snapshot.state ? { state: input.snapshot.state } : {},
2152
- ...input.snapshot.htmlUrl ? { url: input.snapshot.htmlUrl } : {},
2153
- ...input.snapshot.githubUpdatedAt ? { githubUpdatedAt: input.snapshot.githubUpdatedAt } : {},
2154
- ...input.previousGithubUpdatedAt ? { previousGithubUpdatedAt: input.previousGithubUpdatedAt } : {},
2155
- ...input.snapshot.mergeableState ? { mergeableState: input.snapshot.mergeableState } : {},
2156
- ...input.snapshot.ciState ? { ciState: input.snapshot.ciState } : {},
2157
- ...input.snapshot.unresolvedReviewThreads !== void 0 ? { unresolvedReviewThreads: input.snapshot.unresolvedReviewThreads } : {},
2158
- ...failingChecks.length > 0 ? { failingChecks: failingChecks.map((check) => check.name).join(", ") } : {},
2159
- ...pendingChecks.length > 0 ? { pendingChecks: pendingChecks.map((check) => check.name).join(", ") } : {}
2160
- },
2161
- metadata: {
2162
- github: {
2163
- owner: input.subscription.owner,
2164
- repo: input.subscription.repo,
2165
- number: input.subscription.number,
2166
- title: input.snapshot.title,
2167
- state: input.snapshot.state,
2168
- htmlUrl: input.snapshot.htmlUrl,
2169
- githubUpdatedAt: input.snapshot.githubUpdatedAt,
2170
- previousGithubUpdatedAt: input.previousGithubUpdatedAt,
2171
- contentHash: input.snapshot.contentHash,
2172
- previousContentHash: input.previousContentHash,
2173
- threadContentHash: input.snapshot.threadContentHash,
2174
- headSha: input.snapshot.headSha,
2175
- headRef: input.snapshot.headRef,
2176
- mergeableState: input.snapshot.mergeableState,
2177
- ciState: input.snapshot.ciState,
2178
- closedAt: input.snapshot.closedAt,
2179
- mergedAt: input.snapshot.mergedAt,
2180
- unresolvedReviewThreads: input.snapshot.unresolvedReviewThreads,
2181
- reviewStateHash: input.snapshot.reviewStateHash,
2182
- latestReviewThreadAt: input.snapshot.latestReviewThreadAt,
2183
- latestCommentAuthor: input.snapshot.latestCommentAuthor,
2184
- latestCommentAuthorType: input.snapshot.latestCommentAuthorType,
2185
- latestCommentIsBot: input.snapshot.latestCommentIsBot,
2186
- failingChecks,
2187
- pendingChecks
2188
- }
2189
- }
2190
- };
2191
- const streamOptions = await this.#agentOptions.getNotificationStreamOptions?.(input.target);
2192
- await input.agent?.sendNotificationSignal?.(
2193
- notificationInput,
2194
- streamOptions ? { ...input.target, ifIdle: { streamOptions } } : input.target
2195
- );
2196
- }
2197
- async #sendBaselineNotification(input) {
2198
- const agent = this.#getNotificationAgent({});
2199
- if (!agent?.sendNotificationSignal) return;
2200
- await this.#sendGithubNotification({
2201
- agent,
2202
- subscription: input.subscription,
2203
- snapshot: input.snapshot,
2204
- notification: classifyGithubBaselineNotification({ subscription: input.subscription, snapshot: input.snapshot }),
2205
- target: { resourceId: input.resourceId, threadId: input.threadId },
2206
- dedupeSuffix: `baseline:${input.subscription.lastSubscribeSignalId}`
2207
- });
2208
- }
2209
- async #sendActivityNotification(input) {
2210
- const agent = this.#getNotificationAgent(input.polling);
2211
- if (!agent?.sendNotificationSignal) return void 0;
2212
- const notification = classifyGithubActivityNotification({
2213
- subscription: input.subscription,
2214
- snapshot: input.snapshot
2215
- });
2216
- if (!notification) return void 0;
2217
- await this.#sendGithubNotification({
2218
- agent,
2219
- subscription: input.subscription,
2220
- snapshot: input.snapshot,
2221
- notification,
2222
- target: { resourceId: input.polling.resourceId, threadId: input.polling.threadId },
2223
- dedupeSuffix: input.snapshot.contentHash ?? input.snapshot.githubUpdatedAt ?? String(Date.now()),
2224
- previousGithubUpdatedAt: input.previousGithubUpdatedAt,
2225
- previousContentHash: input.previousContentHash
2226
- });
2227
- return notification;
2228
- }
2229
- async #subscribe(input) {
2230
- const { owner, repo } = await this.#resolveRepository(input);
2231
- const { threadStore, loadedThread } = await this.#loadThread(input);
2232
- const githubMetadata = getGithubMetadata(loadedThread.metadata);
2233
- const existingIndex = githubMetadata.subscriptions.findIndex(
2234
- (subscription2) => subscription2.owner === owner && subscription2.repo === repo && subscription2.number === input.number
2235
- );
2236
- const existing = existingIndex >= 0 ? githubMetadata.subscriptions[existingIndex] : void 0;
2237
- if (existing?.lastSubscribeSignalId === input.id) {
2238
- return { owner, repo, number: input.number, subscription: existing, alreadyProcessed: true };
2239
- }
2240
- const now = (/* @__PURE__ */ new Date()).toISOString();
2241
- const subscription = {
2242
- owner,
2243
- repo,
2244
- number: input.number,
2245
- subscribedAt: existing?.subscribedAt ?? now,
2246
- updatedAt: now,
2247
- lastSubscribeSignalId: input.id,
2248
- ...existing?.lastSyncAt ? { lastSyncAt: existing.lastSyncAt } : {},
2249
- ...existing?.lastSyncStatus ? { lastSyncStatus: existing.lastSyncStatus } : {},
2250
- ...existing?.lastSyncError ? { lastSyncError: existing.lastSyncError } : {},
2251
- ...existing?.lastObservedGithubUpdatedAt ? { lastObservedGithubUpdatedAt: existing.lastObservedGithubUpdatedAt } : {},
2252
- ...existing?.lastObservedContentHash ? { lastObservedContentHash: existing.lastObservedContentHash } : {},
2253
- ...existing?.lastObservedThreadContentHash ? { lastObservedThreadContentHash: existing.lastObservedThreadContentHash } : {},
2254
- ...existing?.lastObservedHeadSha ? { lastObservedHeadSha: existing.lastObservedHeadSha } : {},
2255
- ...existing?.lastObservedState ? { lastObservedState: existing.lastObservedState } : {},
2256
- ...existing?.lastObservedMergeableState ? { lastObservedMergeableState: existing.lastObservedMergeableState } : {},
2257
- ...existing?.lastObservedCiState ? { lastObservedCiState: existing.lastObservedCiState } : {},
2258
- ...existing?.lastObservedReviewStateHash ? { lastObservedReviewStateHash: existing.lastObservedReviewStateHash } : {}
2259
- };
2260
- let syncResult;
2261
- let baselineSnapshot;
2262
- if (this.#options.syncOnSubscribe !== false) {
2263
- const syncInput = {
2264
- owner,
2265
- repo,
2266
- number: input.number,
2267
- cwd: this.#options.cwd,
2268
- abortSignal: input.abortSignal
2269
- };
2270
- syncResult = await this.#syncClient.syncPullRequest(syncInput);
2271
- subscription.lastSyncAt = (/* @__PURE__ */ new Date()).toISOString();
2272
- subscription.lastSyncStatus = syncResult.ok ? "success" : "error";
2273
- if (syncResult.error) subscription.lastSyncError = syncResult.error;
2274
- else delete subscription.lastSyncError;
2275
- const snapshot = syncResult.ok ? await this.#syncClient.getPullRequestSnapshot?.(syncInput) : void 0;
2276
- baselineSnapshot = snapshot;
2277
- if (snapshot) applySnapshotCursor(subscription, snapshot);
2278
- } else {
2279
- subscription.lastSyncStatus = "skipped";
2280
- }
2281
- const subscriptions = [subscription];
2282
- await threadStore.saveThread({
2283
- thread: {
2284
- ...loadedThread,
2285
- id: input.threadId,
2286
- resourceId: input.resourceId,
2287
- createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
2288
- updatedAt: /* @__PURE__ */ new Date(),
2289
- metadata: setGithubMetadata(loadedThread.metadata, { subscriptions })
2290
- }
2291
- });
2292
- this.#notifySubscriptionsChanged({ threadId: input.threadId, resourceId: input.resourceId, subscriptions });
2293
- if (baselineSnapshot) {
2294
- await this.#sendBaselineNotification({
2295
- threadId: input.threadId,
2296
- resourceId: input.resourceId,
2297
- subscription,
2298
- snapshot: baselineSnapshot
2299
- });
2300
- }
2301
- await this.startPollingForThread({ threadId: input.threadId, resourceId: input.resourceId });
2302
- return { owner, repo, number: input.number, subscription, syncResult };
2303
- }
2304
- async #unsubscribe(input) {
2305
- const { owner, repo } = await this.#resolveRepository(input);
2306
- const { threadStore, loadedThread } = await this.#loadThread(input);
2307
- const githubMetadata = getGithubMetadata(loadedThread.metadata);
2308
- const subscriptions = githubMetadata.subscriptions.filter(
2309
- (subscription) => !(subscription.owner === owner && subscription.repo === repo && subscription.number === input.number)
2310
- );
2311
- const removed = subscriptions.length !== githubMetadata.subscriptions.length;
2312
- if (removed) {
2313
- await threadStore.saveThread({
2314
- thread: {
2315
- ...loadedThread,
2316
- id: input.threadId,
2317
- resourceId: input.resourceId,
2318
- createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
2319
- updatedAt: /* @__PURE__ */ new Date(),
2320
- metadata: setGithubMetadata(loadedThread.metadata, { subscriptions })
2321
- }
2322
- });
2323
- this.#notifySubscriptionsChanged({ threadId: input.threadId, resourceId: input.resourceId, subscriptions });
2324
- if (subscriptions.length === 0)
2325
- this.stopPollingForThread({ threadId: input.threadId, resourceId: input.resourceId });
2326
- }
2327
- return { owner, repo, number: input.number, removed, remainingSubscriptions: subscriptions.length };
2328
- }
2329
- #findLatestGithubSignal(messages) {
2330
- const message = messages.at(-1);
2331
- if (!message) return void 0;
2332
- const signal = getSignalMetadata(message);
2333
- if (!signal || signal.tagName !== GITHUB_SUBSCRIBE_PR_TAG && signal.tagName !== GITHUB_UNSUBSCRIBE_PR_TAG) {
2334
- return void 0;
2335
- }
2336
- const attributes = isPlainObject(signal.attributes) ? signal.attributes : {};
2337
- const metadata = isPlainObject(signal.metadata) ? signal.metadata : {};
2338
- const github = isPlainObject(metadata.github) ? metadata.github : {};
2339
- const number = readNumber(attributes.number) ?? readNumber(github.number);
2340
- if (!number) return void 0;
2341
- return {
2342
- tagName: String(signal.tagName),
2343
- id: readString(signal.id) ?? message.id,
2344
- owner: readString(attributes.owner) ?? readString(github.owner),
2345
- repo: readString(attributes.repo) ?? readString(github.repo),
2346
- number
2347
- };
2348
- }
2349
- async #sendStatus(args, signal, status) {
2350
- await args.sendSignal?.({
2351
- type: "reactive",
2352
- tagName: GITHUB_SYNC_STATUS_TAG,
2353
- contents: status.message,
2354
- attributes: {
2355
- status: status.status,
2356
- owner: signal.owner,
2357
- repo: signal.repo,
2358
- number: signal.number
2359
- },
2360
- metadata: {
2361
- github: {
2362
- action: status.action,
2363
- status: status.status,
2364
- owner: signal.owner,
2365
- repo: signal.repo,
2366
- number: signal.number
2367
- }
2368
- }
2369
- });
2370
- }
2371
- };
2372
1280
 
2373
1281
  // src/onboarding/packs.ts
2374
1282
  function getAvailableModePacks(access, savedCustomPacks = []) {
@@ -3014,8 +1922,6 @@ function releaseAllThreadLocks() {
3014
1922
  exports.BOX_INDENT = BOX_INDENT;
3015
1923
  exports.BOX_INDENT_STR = BOX_INDENT_STR;
3016
1924
  exports.CHAT_INDENT = CHAT_INDENT;
3017
- exports.GITHUB_SIGNALS_METADATA_KEY = GITHUB_SIGNALS_METADATA_KEY;
3018
- exports.GithubSignals = GithubSignals;
3019
1925
  exports.MEMORY_GATEWAY_DEFAULT_URL = MEMORY_GATEWAY_DEFAULT_URL;
3020
1926
  exports.MEMORY_GATEWAY_PROVIDER = MEMORY_GATEWAY_PROVIDER;
3021
1927
  exports.OBSERVABILITY_AUTH_PREFIX = OBSERVABILITY_AUTH_PREFIX;
@@ -3059,5 +1965,5 @@ exports.setProfileProvider = setProfileProvider;
3059
1965
  exports.theme = theme;
3060
1966
  exports.tintHex = tintHex;
3061
1967
  exports.toCustomProviderModelId = toCustomProviderModelId;
3062
- //# sourceMappingURL=chunk-NFF7IH5X.cjs.map
3063
- //# sourceMappingURL=chunk-NFF7IH5X.cjs.map
1968
+ //# sourceMappingURL=chunk-A4W5D25I.cjs.map
1969
+ //# sourceMappingURL=chunk-A4W5D25I.cjs.map