paperclip-github-plugin 0.6.1 → 0.7.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.
package/README.md CHANGED
@@ -44,11 +44,11 @@ The plugin adds a full in-host workflow instead of a one-off import script:
44
44
  2. Connect one or more GitHub repositories to Paperclip projects.
45
45
  3. Run a sync manually or let the scheduled job keep things up to date.
46
46
 
47
- During sync, the plugin imports one top-level Paperclip issue per GitHub issue, updates already imported issues instead of recreating them, maps GitHub labels into Paperclip labels, and keeps GitHub-specific metadata in dedicated Paperclip surfaces rather than stuffing everything into the issue description.
47
+ During sync, the plugin imports one top-level Paperclip issue per GitHub issue, stamps it with a namespaced GitHub Sync plugin origin, updates already imported issues instead of recreating them, maps GitHub labels into Paperclip labels, and keeps GitHub-specific metadata in dedicated Paperclip surfaces rather than stuffing everything into the issue description.
48
48
 
49
49
  When the host exposes plugin issue creation, imported GitHub issues are created through the Paperclip plugin SDK path so they are not attributed to the connected board user. The worker still uses direct local Paperclip REST calls for label sync and for description, assignee, or status repair paths when those routes are available.
50
50
 
51
- Long-running syncs continue in the background, so quick actions do not have to wait for the whole import to finish. Once a sync has started, the settings page, dashboard widget, and toolbar actions can request cancellation; the worker stops cooperatively after the current repository or issue step finishes. If the worker restarts mid-run, GitHub Sync now recovers that orphaned `running` state on the next read or control action instead of leaving the UI stuck in `running` or silently restarting the old run.
51
+ Long-running syncs continue in the background, so quick actions do not have to wait for the whole import to finish. Once a sync has started, the settings page, dashboard widget, and toolbar actions can request cancellation; the worker stops cooperatively after the current repository or issue step finishes. If the worker restarts mid-run, GitHub Sync now recovers that orphaned `running` state on the next read or control action instead of leaving the UI stuck in `running` or silently restarting the old run. When sync needs to wake an assigned agent, it uses Paperclip's host-owned issue wakeup API first so blocker, liveness, budget, and auth checks stay centralized, then falls back to the local wakeup route only when an older or partial host bridge cannot service the SDK call.
52
52
 
53
53
  ## Highlights
54
54
 
@@ -68,9 +68,9 @@ The plugin does more than mirror issue text. It looks at linked pull requests, m
68
68
 
69
69
  GitHub Sync exposes a dedicated KPI dashboard widget alongside the operational sync widget. During full company syncs, the worker snapshots the current open GitHub backlog and records when already-imported GitHub issues move from open to closed. The KPI widget turns that worker-owned state into backlog, issue-closure, and Paperclip PR-creation cards with recent history and comparisons against older periods.
70
70
 
71
- Because GitHub alone cannot tell which pull requests came from a Paperclip company, the plugin uses explicit Paperclip attribution for delivery activity. `create_pull_request` automatically records a Paperclip-created PR event, and agents that use `gh` or another non-plugin GitHub client can post pull-request-created events to the plugin webhook so the KPI history stays specific to Paperclip work.
71
+ Because GitHub alone cannot tell which pull requests came from a Paperclip company, the plugin uses explicit Paperclip attribution for delivery activity. `create_pull_request` automatically records a Paperclip-created PR event, and agents that use `gh` or another non-plugin GitHub client can post pull-request-created events to the plugin API route so the KPI history stays specific to Paperclip work.
72
72
 
73
- That webhook path matters on authenticated Paperclip deployments today because a current host bug blocks agents from calling plugin tools unless the instance runs in `local_trusted` mode. Those agents can still use `gh` with the propagated `GITHUB_TOKEN`, then call the plugin-owned webhook from the shell after they create a PR. KPI webhook requests instead authenticate with `Authorization: Bearer <PAPERCLIP_API_KEY>`, which the deployment validates through `GET /api/agents/me`, so anonymous POSTs are rejected.
73
+ That API route path matters on authenticated Paperclip deployments today because a current host bug blocks agents from calling plugin tools unless the instance runs in `local_trusted` mode. Those agents can still use `gh` with the propagated `GITHUB_TOKEN`, then call the agent-authenticated plugin API route from the shell after they create a PR. The Paperclip host authenticates `Authorization: Bearer <PAPERCLIP_API_KEY>`, scopes the request to the calling agent's company, and rejects anonymous or non-agent calls before dispatching to the worker.
74
74
 
75
75
  ### Project pull request command center
76
76
 
@@ -89,7 +89,7 @@ Paperclip agents can search GitHub for duplicates, read and update issues, post
89
89
  ## Requirements
90
90
 
91
91
  - Node.js 20+
92
- - a Paperclip host that supports plugin installation
92
+ - a Paperclip host on `2026.427.0` or newer with plugin installation enabled
93
93
  - a GitHub token with API access to the repositories you want to sync
94
94
 
95
95
  ## Install from npm
@@ -178,7 +178,7 @@ The plugin is designed to avoid persisting raw credentials in plugin state.
178
178
  - On authenticated deployments, any selected propagation agents receive `GITHUB_TOKEN` as an agent env secret-ref binding that points at the same saved GitHub token secret instead of a copied raw token.
179
179
  - The worker resolves those secret references at runtime instead of storing raw tokens in plugin state.
180
180
  - On authenticated Paperclip deployments, sync is blocked until the relevant company has connected Paperclip board access.
181
- - KPI webhook requests must include `Authorization: Bearer <PAPERCLIP_API_KEY>`, and the worker validates that agent-scoped Paperclip token against `GET /api/agents/me` before it records any metric event.
181
+ - KPI API route requests must include `Authorization: Bearer <PAPERCLIP_API_KEY>` from an agent run; the Paperclip host authenticates the token and supplies the agent company before the worker records any metric event.
182
182
 
183
183
  ### Optional worker-local token file
184
184
 
@@ -208,14 +208,14 @@ The plugin exposes GitHub workflow tools to Paperclip agents, including:
208
208
 
209
209
  When an agent sends GitHub body content through the plugin, including issue bodies, pull request descriptions, comments, and review-thread replies, the plugin adds a GitHub-flavored Markdown footer with a horizontal rule and compact heading that discloses AI authorship. If the tool caller supplies `llmModel`, the footer also includes the model name, for example `###### ✨ This comment was AI-generated using gpt-5.4`.
210
210
 
211
- ### KPI attribution webhook
211
+ ### KPI attribution API route
212
212
 
213
- The `create_pull_request` tool automatically records a company-level Paperclip PR creation metric. For delivery flows that use `gh` or another non-plugin GitHub client, post a JSON payload to `/api/plugins/paperclip-github-plugin/webhooks/record-company-metric-event` after the PR is created.
213
+ The `create_pull_request` tool automatically records a company-level Paperclip PR creation metric. For delivery flows that use `gh` or another non-plugin GitHub client, post a JSON payload to `/api/plugins/paperclip-github-plugin/api/company-metrics/events` after the PR is created.
214
214
 
215
215
  Supported payload fields:
216
216
 
217
217
  - `metric` required: `pull_request_created`
218
- - `companyId` optional when `repository` maps to exactly one company
218
+ - `companyId` optional; when present it must match the authenticated agent's company
219
219
  - `repository` optional: `owner/repo` or `https://github.com/owner/repo`
220
220
  - `pullRequestNumber` optional
221
221
  - `pullRequestUrl` optional
@@ -223,18 +223,18 @@ Supported payload fields:
223
223
  - `eventKey` optional custom dedupe key
224
224
  - `count` optional positive integer
225
225
 
226
- Each request must include:
226
+ Each request must be made by a Paperclip agent run and include:
227
227
 
228
228
  - `Authorization: Bearer <PAPERCLIP_API_KEY>`
229
229
 
230
- The worker validates that bearer token against Paperclip's built-in `GET /api/agents/me` endpoint on the trusted Paperclip API origin (`PAPERCLIP_API_URL` when available, otherwise the saved plugin origin). Requests are rejected when the token is missing, invalid, expired, or belongs to a different company than the metric target.
230
+ The Paperclip host validates that bearer token and passes the authenticated agent company to the plugin worker. Requests are rejected before worker dispatch when the token is missing, invalid, expired, or not an agent token.
231
231
 
232
232
  Example:
233
233
 
234
234
  ```bash
235
235
  payload='{"metric":"pull_request_created","repository":"paperclipai/example-repo","pullRequestNumber":21}'
236
236
 
237
- curl -X POST "${PAPERCLIP_API_URL%/}/api/plugins/paperclip-github-plugin/webhooks/record-company-metric-event" \
237
+ curl -X POST "${PAPERCLIP_API_URL%/}/api/plugins/paperclip-github-plugin/api/company-metrics/events" \
238
238
  -H "content-type: application/json" \
239
239
  -H "authorization: Bearer ${PAPERCLIP_API_KEY}" \
240
240
  -d "${payload}"
@@ -244,14 +244,14 @@ The worker deduplicates repeated PR events by preferring the pull request URL, t
244
244
 
245
245
  Current host caveat: on authenticated Paperclip deployments, the Paperclip host currently guards `GET /api/plugins/tools` and `POST /api/plugins/tools/execute` with board authentication before dispatching to any plugin worker. If an agent run does not have board access for the target company, GitHub Sync tool discovery and execution fail with `403 {"error":"Board access required"}` before this plugin's worker code runs.
246
246
 
247
- Because the KPI attribution endpoint is a normal plugin webhook rather than a plugin tool, authenticated agent runs can still call it directly with `PAPERCLIP_API_KEY` even while that host bug blocks the GitHub Sync tool surface.
247
+ Because the KPI attribution endpoint is a native plugin JSON route rather than a plugin tool, authenticated agent runs can still call it directly with `PAPERCLIP_API_KEY` even while that host bug blocks the GitHub Sync tool surface.
248
248
 
249
249
  ## Troubleshooting
250
250
 
251
251
  - If setup is reported as incomplete, confirm that a GitHub token has been saved or that `${PAPERCLIP_HOME:-~/.paperclip}/plugins/github-sync/config.json` contains `githubToken`, and make sure at least one mapping has a created Paperclip project.
252
252
  - If Paperclip says board access is required, open plugin settings inside the affected company and complete the Paperclip board access flow before retrying sync.
253
253
  - If GitHub Sync agent tools fail with `403 {"error":"Board access required"}` on `/api/plugins/tools` or `/api/plugins/tools/execute`, the current Paperclip host rejected the request before the plugin worker ran. Re-run from a board-authenticated session or agent run that has board access to the target company.
254
- - If a KPI webhook call is rejected, make sure the request includes `Authorization: Bearer ${PAPERCLIP_API_KEY}`, that the token is still valid for the current run, and that it belongs to the same company the metric event targets.
254
+ - If a KPI API route call is rejected, make sure the request includes `Authorization: Bearer ${PAPERCLIP_API_KEY}`, that the token is still valid for the current run, and that any `companyId` in the payload matches the calling agent's company.
255
255
  - If the worker reaches an authenticated HTML page instead of the Paperclip API JSON responses it expects, connect Paperclip board access for that company or set `PAPERCLIP_API_URL` to a worker-accessible Paperclip API origin.
256
256
  - If a sync run finishes with partial failures, open the saved troubleshooting panel in GitHub Sync to inspect the repository, issue number, raw error, and suggested fix for each recorded failure.
257
257
  - If sync says the Paperclip API URL is not trusted, reopen the plugin from the current Paperclip host so the settings UI can refresh the saved origin, or set `PAPERCLIP_API_URL` for the worker.
package/dist/manifest.js CHANGED
@@ -508,19 +508,20 @@ var GITHUB_AGENT_TOOLS = [
508
508
 
509
509
  // src/kpi-contract.ts
510
510
  var GITHUB_SYNC_PLUGIN_ID = "paperclip-github-plugin";
511
- var COMPANY_METRIC_WEBHOOK_ENDPOINT_KEY = "record-company-metric-event";
512
- var COMPANY_METRIC_WEBHOOK_PATH = `/api/plugins/${GITHUB_SYNC_PLUGIN_ID}/webhooks/${COMPANY_METRIC_WEBHOOK_ENDPOINT_KEY}`;
511
+ var COMPANY_METRIC_API_ROUTE_KEY = "record-company-metric-event";
512
+ var COMPANY_METRIC_API_ROUTE_PATH = "/company-metrics/events";
513
+ var COMPANY_METRIC_API_ROUTE_URL_PATH = `/api/plugins/${GITHUB_SYNC_PLUGIN_ID}/api${COMPANY_METRIC_API_ROUTE_PATH}`;
513
514
 
514
515
  // src/manifest.ts
515
516
  var require2 = createRequire(import.meta.url);
516
517
  var packageJson = require2("../package.json");
517
- var DASHBOARD_WIDGET_CAPABILITY = "ui.dashboardWidget.register";
518
518
  var SCHEDULE_TICK_CRON = "* * * * *";
519
- var MANIFEST_VERSION = "0.6.1"?.trim() || typeof packageJson.version === "string" && packageJson.version.trim() || process.env.npm_package_version?.trim() || "0.0.0-dev";
519
+ var MANIFEST_VERSION = "0.7.0"?.trim() || typeof packageJson.version === "string" && packageJson.version.trim() || process.env.npm_package_version?.trim() || "0.0.0-dev";
520
520
  var manifest = {
521
521
  id: GITHUB_SYNC_PLUGIN_ID,
522
522
  apiVersion: 1,
523
523
  version: MANIFEST_VERSION,
524
+ minimumHostVersion: "2026.427.0",
524
525
  displayName: "GitHub Sync",
525
526
  description: "Synchronize GitHub issues into Paperclip projects.",
526
527
  author: "\xC1lvaro S\xE1nchez-Mariscal",
@@ -528,7 +529,7 @@ var manifest = {
528
529
  capabilities: [
529
530
  "ui.sidebar.register",
530
531
  "ui.page.register",
531
- DASHBOARD_WIDGET_CAPABILITY,
532
+ "ui.dashboardWidget.register",
532
533
  "ui.detailTab.register",
533
534
  "ui.commentAnnotation.register",
534
535
  "ui.action.register",
@@ -539,11 +540,12 @@ var manifest = {
539
540
  "issues.read",
540
541
  "issues.create",
541
542
  "issues.update",
543
+ "issues.wakeup",
542
544
  "issue.comments.read",
543
545
  "issue.comments.create",
544
546
  "agents.read",
545
547
  "jobs.schedule",
546
- "webhooks.receive",
548
+ "api.routes.register",
547
549
  "http.outbound",
548
550
  "secrets.read-ref",
549
551
  "agent.tools.register"
@@ -579,11 +581,13 @@ var manifest = {
579
581
  schedule: SCHEDULE_TICK_CRON
580
582
  }
581
583
  ],
582
- webhooks: [
584
+ apiRoutes: [
583
585
  {
584
- endpointKey: COMPANY_METRIC_WEBHOOK_ENDPOINT_KEY,
585
- displayName: "Record Company KPI Event",
586
- description: "Record Paperclip-attributed pull request activity from agent flows that use gh or other non-plugin GitHub clients."
586
+ routeKey: COMPANY_METRIC_API_ROUTE_KEY,
587
+ method: "POST",
588
+ path: COMPANY_METRIC_API_ROUTE_PATH,
589
+ auth: "agent",
590
+ capability: "api.routes.register"
587
591
  }
588
592
  ],
589
593
  tools: GITHUB_AGENT_TOOLS,
package/dist/worker.js CHANGED
@@ -563,9 +563,9 @@ function parseRepositoryReference(repositoryInput) {
563
563
 
564
564
  // src/kpi-contract.ts
565
565
  var GITHUB_SYNC_PLUGIN_ID = "paperclip-github-plugin";
566
- var COMPANY_METRIC_WEBHOOK_ENDPOINT_KEY = "record-company-metric-event";
567
- var COMPANY_METRIC_WEBHOOK_PATH = `/api/plugins/${GITHUB_SYNC_PLUGIN_ID}/webhooks/${COMPANY_METRIC_WEBHOOK_ENDPOINT_KEY}`;
568
- var COMPANY_METRIC_WEBHOOK_AUTH_HEADER = "authorization";
566
+ var COMPANY_METRIC_API_ROUTE_KEY = "record-company-metric-event";
567
+ var COMPANY_METRIC_API_ROUTE_PATH = "/company-metrics/events";
568
+ var COMPANY_METRIC_API_ROUTE_URL_PATH = `/api/plugins/${GITHUB_SYNC_PLUGIN_ID}/api${COMPANY_METRIC_API_ROUTE_PATH}`;
569
569
 
570
570
  // src/paperclip-health.ts
571
571
  function normalizeOptionalString(value) {
@@ -594,6 +594,8 @@ function requiresPaperclipBoardAccess(value) {
594
594
  }
595
595
 
596
596
  // src/worker.ts
597
+ var GITHUB_ISSUE_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}:github-issue`;
598
+ var GITHUB_PULL_REQUEST_ORIGIN_KIND = `plugin:${GITHUB_SYNC_PLUGIN_ID}:github-pull-request`;
597
599
  var SETTINGS_SCOPE = {
598
600
  scopeKind: "instance",
599
601
  stateKey: "paperclip-github-plugin-settings"
@@ -6773,9 +6775,6 @@ function getPaperclipIssueEndpoint(baseUrl, issueId) {
6773
6775
  function getPaperclipHealthEndpoint(baseUrl) {
6774
6776
  return new URL("/api/health", baseUrl).toString();
6775
6777
  }
6776
- function getPaperclipCurrentAgentEndpoint(baseUrl) {
6777
- return new URL("/api/agents/me", baseUrl).toString();
6778
- }
6779
6778
  function getPaperclipAgentWakeupEndpoint(baseUrl, agentId) {
6780
6779
  return new URL(`/api/agents/${agentId}/wakeup`, baseUrl).toString();
6781
6780
  }
@@ -6824,7 +6823,38 @@ async function detectPaperclipBoardAccessRequirement(paperclipApiBaseUrl) {
6824
6823
  }
6825
6824
  }
6826
6825
  async function wakePaperclipIssueAssignee(ctx, params) {
6827
- if (!params.assigneeAgentId || !params.paperclipApiBaseUrl) {
6826
+ if (!params.assigneeAgentId) {
6827
+ return;
6828
+ }
6829
+ if (ctx.issues && typeof ctx.issues.requestWakeup === "function" && params.companyId) {
6830
+ try {
6831
+ await ctx.issues.requestWakeup(params.paperclipIssueId, params.companyId, {
6832
+ reason: params.reason,
6833
+ contextSource: `github-sync.${params.mutation}`,
6834
+ ...params.mutation === "import" ? { idempotencyKey: ["github-sync", params.mutation, params.paperclipIssueId].join(":") } : {}
6835
+ });
6836
+ return;
6837
+ } catch (error) {
6838
+ if (!params.paperclipApiBaseUrl) {
6839
+ ctx.logger.warn("GitHub sync could not wake the assignee for a Paperclip issue through the SDK.", {
6840
+ issueId: params.paperclipIssueId,
6841
+ agentId: params.assigneeAgentId,
6842
+ companyId: params.companyId,
6843
+ mutation: params.mutation,
6844
+ error: error instanceof Error ? error.message : String(error)
6845
+ });
6846
+ return;
6847
+ }
6848
+ ctx.logger.warn("GitHub sync could not wake the assignee through the SDK. Falling back to the local Paperclip API.", {
6849
+ issueId: params.paperclipIssueId,
6850
+ agentId: params.assigneeAgentId,
6851
+ companyId: params.companyId,
6852
+ mutation: params.mutation,
6853
+ error: error instanceof Error ? error.message : String(error)
6854
+ });
6855
+ }
6856
+ }
6857
+ if (!params.paperclipApiBaseUrl) {
6828
6858
  return;
6829
6859
  }
6830
6860
  try {
@@ -7773,6 +7803,8 @@ async function createPaperclipIssue(ctx, mapping, advancedSettings, issue, avail
7773
7803
  projectId: mapping.paperclipProjectId,
7774
7804
  title,
7775
7805
  ...description ? { description } : {},
7806
+ originKind: GITHUB_ISSUE_ORIGIN_KIND,
7807
+ originId: normalizeGitHubIssueHtmlUrl(issue.htmlUrl) ?? issue.htmlUrl,
7776
7808
  ...defaultAssignee?.kind === "agent" ? { assigneeAgentId: defaultAssignee.id } : defaultAssignee?.kind === "user" ? { assigneeUserId: defaultAssignee.id } : {}
7777
7809
  });
7778
7810
  const ensuredCreatedIssueId = createdIssue.id;
@@ -8626,156 +8658,38 @@ async function persistCompanyActivityMetricEvent(ctx, params, options = {}) {
8626
8658
  ...result.eventKey ? { eventKey: result.eventKey } : {}
8627
8659
  };
8628
8660
  }
8629
- function parseWebhookPayloadRecord(input) {
8630
- if (input.parsedBody && typeof input.parsedBody === "object" && !Array.isArray(input.parsedBody)) {
8631
- return input.parsedBody;
8632
- }
8633
- const rawBody = input.rawBody.trim();
8634
- if (!rawBody) {
8635
- throw new Error("Webhook body must be a JSON object.");
8636
- }
8637
- let parsed;
8638
- try {
8639
- parsed = JSON.parse(rawBody);
8640
- } catch {
8641
- throw new Error("Webhook body must be valid JSON.");
8642
- }
8643
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
8644
- throw new Error("Webhook body must be a JSON object.");
8645
- }
8646
- return parsed;
8647
- }
8648
- async function resolveCompanyIdForCompanyMetricEvent(ctx, params) {
8649
- const requestedCompanyId = normalizeCompanyId(params.companyId);
8650
- if (requestedCompanyId) {
8651
- return requestedCompanyId;
8652
- }
8653
- if (!params.repositoryUrl) {
8654
- return void 0;
8661
+ function parseCompanyMetricApiRouteBody(input) {
8662
+ if (!input.body || typeof input.body !== "object" || Array.isArray(input.body)) {
8663
+ throw new Error("Company KPI route body must be a JSON object.");
8655
8664
  }
8656
- const settings = normalizeSettings(await ctx.state.get(SETTINGS_SCOPE));
8657
- const matchingCompanyIds = [
8658
- ...new Set(
8659
- settings.mappings.filter((mapping) => getNormalizedMappingRepositoryUrl(mapping) === params.repositoryUrl).map((mapping) => normalizeCompanyId(mapping.companyId)).filter((companyId) => Boolean(companyId))
8660
- )
8661
- ];
8662
- return matchingCompanyIds.length === 1 ? matchingCompanyIds[0] : void 0;
8665
+ return input.body;
8663
8666
  }
8664
- function getWebhookHeaderValue(headers, name) {
8665
- const normalizedName = name.trim().toLowerCase();
8666
- for (const [headerName, headerValue] of Object.entries(headers)) {
8667
- if (headerName.trim().toLowerCase() !== normalizedName) {
8668
- continue;
8669
- }
8670
- if (typeof headerValue === "string") {
8671
- const trimmedValue = headerValue.trim();
8672
- return trimmedValue || void 0;
8673
- }
8674
- if (!Array.isArray(headerValue)) {
8675
- continue;
8676
- }
8677
- for (const entry of headerValue) {
8678
- if (typeof entry !== "string") {
8679
- continue;
8680
- }
8681
- const trimmedValue = entry.trim();
8682
- if (trimmedValue) {
8683
- return trimmedValue;
8667
+ async function handleCompanyMetricApiRoute(ctx, input) {
8668
+ if (input.routeKey !== COMPANY_METRIC_API_ROUTE_KEY) {
8669
+ return {
8670
+ status: 404,
8671
+ body: {
8672
+ error: `Unsupported plugin API route: ${input.routeKey}.`
8684
8673
  }
8685
- }
8686
- }
8687
- return void 0;
8688
- }
8689
- function normalizeCompanyMetricWebhookBearerToken(value) {
8690
- if (!value) {
8691
- return void 0;
8692
- }
8693
- const trimmedValue = value.trim();
8694
- if (!trimmedValue) {
8695
- return void 0;
8696
- }
8697
- const bearerMatch = trimmedValue.match(/^Bearer\s+(.+)$/i);
8698
- if (!bearerMatch) {
8699
- return void 0;
8700
- }
8701
- const token = bearerMatch[1]?.trim();
8702
- return token || void 0;
8703
- }
8704
- function normalizePaperclipCurrentAgentRecord(value) {
8705
- if (!value || typeof value !== "object") {
8706
- return null;
8707
- }
8708
- const record = value;
8709
- const id = normalizeOptionalString2(record.id);
8710
- const companyId = normalizeCompanyId(record.companyId);
8711
- return id && companyId ? {
8712
- id,
8713
- companyId
8714
- } : null;
8715
- }
8716
- async function readCompanyMetricWebhookCurrentAgent(paperclipApiBaseUrl, bearerToken) {
8717
- const response = await fetchPaperclipApi(getPaperclipCurrentAgentEndpoint(paperclipApiBaseUrl), {
8718
- method: "GET",
8719
- headers: {
8720
- accept: "application/json",
8721
- authorization: `Bearer ${bearerToken}`
8722
- }
8723
- });
8724
- const payloadResult = await readPaperclipApiJsonResponse(response, {
8725
- operationLabel: "current agent"
8726
- });
8727
- if (payloadResult.failure) {
8728
- if (payloadResult.failure.requiresAuthentication) {
8729
- throw new Error("Company KPI webhook Authorization must be a valid PAPERCLIP_API_KEY bearer token.");
8730
- }
8731
- const detail = payloadResult.failure.errorMessage ? ` ${payloadResult.failure.errorMessage}` : "";
8732
- throw new Error(`Could not validate the KPI webhook Paperclip API key.${detail}`);
8733
- }
8734
- const agent = normalizePaperclipCurrentAgentRecord(payloadResult.data);
8735
- if (!agent) {
8736
- throw new Error("Paperclip did not return a usable current agent record while validating the KPI webhook caller.");
8737
- }
8738
- return agent;
8739
- }
8740
- async function assertCompanyMetricWebhookAuthenticated(ctx, input, companyId) {
8741
- const rawAuthorization = getWebhookHeaderValue(input.headers, COMPANY_METRIC_WEBHOOK_AUTH_HEADER);
8742
- const bearerToken = normalizeCompanyMetricWebhookBearerToken(rawAuthorization);
8743
- if (!bearerToken) {
8744
- throw new Error(
8745
- `Missing or invalid ${COMPANY_METRIC_WEBHOOK_AUTH_HEADER} header. Use Bearer <PAPERCLIP_API_KEY>.`
8746
- );
8674
+ };
8747
8675
  }
8748
- const settings = normalizeSettings(await ctx.state.get(SETTINGS_SCOPE));
8749
- const config = await getResolvedConfig(ctx);
8750
- const paperclipApiBaseUrl = getConfiguredPaperclipApiBaseUrl(settings, config, companyId);
8751
- if (!paperclipApiBaseUrl) {
8752
- throw new Error(
8753
- "A trusted Paperclip API origin is required to validate PAPERCLIP_API_KEY. Set PAPERCLIP_API_URL or save the Paperclip host origin before sending KPI webhook events."
8754
- );
8676
+ if (input.actor.actorType !== "agent") {
8677
+ throw new Error("Company KPI metric events must be recorded by an authenticated Paperclip agent.");
8755
8678
  }
8756
- const currentAgent = await readCompanyMetricWebhookCurrentAgent(paperclipApiBaseUrl, bearerToken);
8757
- if (normalizeCompanyId(currentAgent.companyId) !== companyId) {
8758
- throw new Error("Company KPI webhook Paperclip API key belongs to a different company.");
8679
+ const companyId = normalizeCompanyId(input.companyId);
8680
+ if (!companyId) {
8681
+ throw new Error("Company KPI metric events require the host to provide the authenticated agent company.");
8759
8682
  }
8760
- }
8761
- async function handleCompanyMetricWebhook(ctx, input) {
8762
- if (input.endpointKey !== COMPANY_METRIC_WEBHOOK_ENDPOINT_KEY) {
8763
- throw new Error(`Unsupported webhook endpoint: ${input.endpointKey}.`);
8683
+ const payload = parseCompanyMetricApiRouteBody(input);
8684
+ const requestedCompanyId = normalizeCompanyId(payload.companyId);
8685
+ if (requestedCompanyId && requestedCompanyId !== companyId) {
8686
+ throw new Error("companyId must match the authenticated Paperclip agent company.");
8764
8687
  }
8765
- const payload = parseWebhookPayloadRecord(input);
8766
8688
  const repositoryInput = normalizeOptionalString2(payload.repository);
8767
8689
  const repository = repositoryInput ? parseRepositoryReference(repositoryInput) : null;
8768
8690
  if (repositoryInput && !repository) {
8769
8691
  throw new Error("repository must be owner/repo or https://github.com/owner/repo.");
8770
8692
  }
8771
- const companyId = await resolveCompanyIdForCompanyMetricEvent(ctx, {
8772
- companyId: payload.companyId,
8773
- repositoryUrl: repository?.url
8774
- });
8775
- if (!companyId) {
8776
- throw new Error("companyId is required unless repository maps to exactly one company.");
8777
- }
8778
- await assertCompanyMetricWebhookAuthenticated(ctx, input, companyId);
8779
8693
  const metric = normalizeCompanyActivityMetricInputValue(payload.metric);
8780
8694
  if (!metric) {
8781
8695
  throw new Error('metric must be "pull_request_created".');
@@ -8792,7 +8706,7 @@ async function handleCompanyMetricWebhook(ctx, input) {
8792
8706
  });
8793
8707
  if (!dedupeKey) {
8794
8708
  throw new Error(
8795
- "Company KPI webhook requires pullRequestUrl, repository plus pullRequestNumber, or eventKey so duplicate deliveries can be ignored."
8709
+ "Company KPI metric events require pullRequestUrl, repository plus pullRequestNumber, or eventKey so duplicate deliveries can be ignored."
8796
8710
  );
8797
8711
  }
8798
8712
  const recordedMetric = await persistCompanyActivityMetricEvent(
@@ -8812,17 +8726,27 @@ async function handleCompanyMetricWebhook(ctx, input) {
8812
8726
  }
8813
8727
  );
8814
8728
  ctx.logger.info(
8815
- recordedMetric.recorded ? "GitHub Sync recorded a company KPI webhook event." : "GitHub Sync ignored a duplicate company KPI webhook event.",
8729
+ recordedMetric.recorded ? "GitHub Sync recorded a company KPI API route event." : "GitHub Sync ignored a duplicate company KPI API route event.",
8816
8730
  {
8817
- endpointKey: input.endpointKey,
8731
+ routeKey: input.routeKey,
8818
8732
  companyId,
8819
8733
  metric,
8820
8734
  repositoryUrl: repository?.url,
8821
8735
  pullRequestNumber,
8822
8736
  pullRequestUrl,
8823
- requestId: input.requestId
8737
+ agentId: input.actor.agentId ?? null,
8738
+ runId: input.actor.runId ?? null
8824
8739
  }
8825
8740
  );
8741
+ return {
8742
+ status: recordedMetric.recorded ? 201 : 200,
8743
+ body: {
8744
+ status: recordedMetric.recorded ? "recorded" : "duplicate",
8745
+ recorded: recordedMetric.recorded,
8746
+ companyId,
8747
+ metric: "pull_request_created"
8748
+ }
8749
+ };
8826
8750
  }
8827
8751
  async function createGitHubToolOctokit(ctx, companyId) {
8828
8752
  const token = (await resolveGithubToken(ctx, { companyId })).trim();
@@ -11149,6 +11073,8 @@ async function createProjectPullRequestPaperclipIssue(ctx, input) {
11149
11073
  companyId: scope.companyId,
11150
11074
  projectId: scope.projectId,
11151
11075
  title: requestedTitle,
11076
+ originKind: GITHUB_PULL_REQUEST_ORIGIN_KIND,
11077
+ originId: pullRequestUrl,
11152
11078
  description: buildPaperclipIssueDescriptionFromPullRequest({
11153
11079
  repository: scope.repository,
11154
11080
  pullRequestNumber,
@@ -13676,11 +13602,11 @@ var plugin = definePlugin({
13676
13602
  }
13677
13603
  });
13678
13604
  },
13679
- async onWebhook(input) {
13605
+ async onApiRequest(input) {
13680
13606
  if (!pluginRuntimeContext) {
13681
- throw new Error("GitHub Sync worker is not ready to handle webhooks yet.");
13607
+ throw new Error("GitHub Sync worker is not ready to handle API routes yet.");
13682
13608
  }
13683
- await handleCompanyMetricWebhook(pluginRuntimeContext, input);
13609
+ return handleCompanyMetricApiRoute(pluginRuntimeContext, input);
13684
13610
  },
13685
13611
  async onShutdown() {
13686
13612
  pluginRuntimeContext = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paperclip-github-plugin",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Paperclip plugin for synchronizing GitHub issues into Paperclip projects.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "dependencies": {
43
43
  "@octokit/rest": "^22.0.1",
44
- "@paperclipai/plugin-sdk": "^2026.416.0",
44
+ "@paperclipai/plugin-sdk": "^2026.427.0",
45
45
  "react": "^19.2.5",
46
46
  "react-markdown": "^10.1.0",
47
47
  "rehype-raw": "^7.0.0",