mastracode 0.22.2 → 0.22.3-alpha.0

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