archal 0.9.19 → 0.10.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 (83) hide show
  1. package/README.md +62 -154
  2. package/agents/openclaw/.archal.json +8 -0
  3. package/agents/openclaw/Dockerfile +97 -0
  4. package/agents/openclaw/README.md +113 -0
  5. package/agents/openclaw/drive.mjs +301 -0
  6. package/agents/openclaw/extract-openclaw-response-text.mjs +49 -0
  7. package/agents/openclaw/package.json +9 -0
  8. package/agents/openclaw/scenarios/acceptance/github-escalation-and-cleanup.md +43 -0
  9. package/agents/openclaw/scenarios/acceptance/jira-linear-release-triage.md +39 -0
  10. package/agents/openclaw/scenarios/acceptance/multi-clone-customer-risk-review.md +45 -0
  11. package/agents/openclaw/scenarios/acceptance/slack-incident-handoff.md +42 -0
  12. package/agents/openclaw/scenarios/acceptance/stripe-dunning-remediation.md +40 -0
  13. package/agents/openclaw/scenarios/close-stale-issues.md +35 -0
  14. package/agents/openclaw/scenarios/github-issue-triage-read-only.md +44 -0
  15. package/agents/openclaw/workspace/AGENTS.md +23 -0
  16. package/agents/openclaw/workspace/IDENTITY.md +8 -0
  17. package/agents/openclaw/workspace/SOUL.md +14 -0
  18. package/agents/openclaw/workspace/TOOLS.md +54 -0
  19. package/clone-assets/apify/tools.json +256 -22
  20. package/clone-assets/calcom/tools.json +2062 -0
  21. package/clone-assets/clickup/tools.json +3245 -0
  22. package/clone-assets/customerio/tools.json +2350 -0
  23. package/clone-assets/datadog/tools.json +734 -0
  24. package/clone-assets/github/tools.json +307 -27
  25. package/clone-assets/gitlab/tools.json +10688 -0
  26. package/clone-assets/google-workspace/tools.json +18 -6
  27. package/clone-assets/hubspot/tools.json +1604 -0
  28. package/clone-assets/jira/fidelity.json +1 -1
  29. package/clone-assets/jira/tools.json +266 -543
  30. package/clone-assets/linear/tools.json +278 -40
  31. package/clone-assets/ownerrez/tools.json +548 -0
  32. package/clone-assets/pricelabs/tools.json +343 -0
  33. package/clone-assets/sentry/tools.json +2821 -0
  34. package/clone-assets/slack/tools.json +1 -2
  35. package/clone-assets/stripe/tools.json +299 -46
  36. package/clone-assets/supabase/tools.json +437 -0
  37. package/clone-assets/unipile/tools.json +408 -0
  38. package/clone-assets/webflow/tools.json +2185 -0
  39. package/dist/autoloop-worker-types-CHaclqtD.d.cts +160 -0
  40. package/dist/cli.cjs +127896 -84811
  41. package/dist/{vitest/chunk-L36NXAU6.js → commands/autoloop-hosted-control-plane-client.cjs} +16344 -18845
  42. package/dist/commands/autoloop-hosted-control-plane-client.d.cts +133 -0
  43. package/dist/commands/autoloop-pr-verification.cjs +4312 -0
  44. package/dist/commands/autoloop-pr-verification.d.cts +19 -0
  45. package/dist/commands/autoloop-result-parser.cjs +27058 -0
  46. package/dist/commands/autoloop-result-parser.d.cts +196 -0
  47. package/dist/commands/autoloop-worker.cjs +38488 -0
  48. package/dist/commands/autoloop-worker.d.cts +102 -0
  49. package/dist/eval-shim.mjs +216 -0
  50. package/dist/index.cjs +15 -2
  51. package/dist/index.d.cts +3 -1
  52. package/dist/layer-1-ziaLpfLr.d.cts +62 -0
  53. package/dist/metafile-cjs.json +1 -0
  54. package/dist/reporter-entry.js +3 -0
  55. package/dist/sdk/index.cjs +51630 -0
  56. package/dist/sdk/index.d.cts +626 -0
  57. package/dist/vitest/chunk-2PDHTPZC.js +4867 -0
  58. package/dist/vitest/chunk-7L4BBB6M.js +2613 -0
  59. package/dist/vitest/index.cjs +6152 -75718
  60. package/dist/vitest/index.d.ts +22 -86
  61. package/dist/vitest/index.js +45 -414
  62. package/dist/vitest/runtime/hosted-session-reaper.cjs +682 -34399
  63. package/dist/vitest/runtime/hosted-session-reaper.js +1 -1
  64. package/dist/vitest/runtime/setup-files.js +2 -2
  65. package/manifest.json +9 -0
  66. package/package.json +20 -14
  67. package/skills/archal-agent/SKILL.md +86 -0
  68. package/skills/autoloop/SKILL.md +391 -0
  69. package/skills/autoloop/references/hosted-sources.md +94 -0
  70. package/skills/autoloop/references/trace-schema-mapping.md +104 -0
  71. package/skills/eval/SKILL.md +17 -15
  72. package/skills/free-account/SKILL.md +103 -0
  73. package/skills/install-agent/SKILL.md +202 -0
  74. package/skills/onboard/SKILL.md +29 -18
  75. package/skills/scenario/SKILL.md +36 -18
  76. package/skills/seed/SKILL.md +238 -0
  77. package/skills/vitest/SKILL.md +3 -2
  78. package/dist/harness.cjs +0 -62
  79. package/dist/harness.d.cts +0 -20
  80. package/dist/seed/dynamic-generator.cjs +0 -45687
  81. package/dist/seed/dynamic-generator.d.cts +0 -106
  82. package/dist/vitest/chunk-WZ7SA4CK.js +0 -47369
  83. package/skills/attach/SKILL.md +0 -402
@@ -0,0 +1,4312 @@
1
+ const import_meta_url = require('url').pathToFileURL(__filename).href;
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/commands/autoloop-pr-verification.ts
22
+ var autoloop_pr_verification_exports = {};
23
+ __export(autoloop_pr_verification_exports, {
24
+ verifyFixResult: () => verifyFixResult,
25
+ verifyOpenFixPrPoll: () => verifyOpenFixPrPoll
26
+ });
27
+ module.exports = __toCommonJS(autoloop_pr_verification_exports);
28
+
29
+ // ../packages/contracts/src/autoloop/layer-0.ts
30
+ var AUTOLOOP_CUSTOMER_VISIBLE_ARTIFACT_TYPES = [
31
+ "grade_summary",
32
+ "seed_summary",
33
+ "reproduction_summary",
34
+ "replay_plan",
35
+ "regression_pack",
36
+ "assertion_result",
37
+ "fix_summary"
38
+ ];
39
+ var AUTOLOOP_INTERNAL_ONLY_ARTIFACT_TYPES = [
40
+ "source_snapshot",
41
+ "grade_payload",
42
+ "codex_prompt",
43
+ "codex_transcript",
44
+ "command_log",
45
+ "sandbox_bundle",
46
+ "rag_replay_package"
47
+ ];
48
+ var AUTOLOOP_CUSTOMER_VISIBLE_ARTIFACT_REDACTION_STATUSES = [
49
+ "redacted",
50
+ "not_required"
51
+ ];
52
+ var AUTOLOOP_REDACTED_STATUS = "redacted";
53
+ var AUTOLOOP_CUSTOMER_VISIBLE_VISIBILITY = "customer_visible";
54
+ var AUTOLOOP_INTERNAL_VISIBILITY = "internal";
55
+ var AUTOLOOP_CUSTOMER_VISIBLE_EVENT_TYPES = [
56
+ "grade.completed",
57
+ "seed.completed",
58
+ "reproduction.completed",
59
+ "fix.completed",
60
+ "autoloop_run.finalized"
61
+ ];
62
+ var AGENT_STREAM_DELTA_EVENT_TYPE = "agent_stream.delta";
63
+ var AGENT_STREAM_TRUNCATED_EVENT_TYPE = "agent_stream.truncated";
64
+ var AGENT_STREAM_COMPLETED_EVENT_TYPE = "agent_stream.completed";
65
+ var AUTOLOOP_EVENT_SEVERITIES = ["debug", "info", "warn", "error"];
66
+ var AUTOLOOP_PHASES = ["queued", "grade", "seed", "reproduce", "fix_pr", "done"];
67
+ var AUTOLOOP_ACTIVE_PHASES = ["grade", "seed", "reproduce", "fix_pr"];
68
+ var AUTOLOOP_PHASE_HEALTH_STATUSES = [
69
+ "running",
70
+ "completed",
71
+ "stream_reconnect_recovered",
72
+ "stalled_no_artifact",
73
+ "timeout",
74
+ "failed"
75
+ ];
76
+ var AUTOLOOP_TERMINAL_STATUSES = [
77
+ "running",
78
+ "succeeded",
79
+ "failed",
80
+ "blocked",
81
+ "cancelled"
82
+ ];
83
+ var AUTOLOOP_CODEX_SESSION_EVENT_STATUSES = [
84
+ "queued",
85
+ "running",
86
+ "succeeded",
87
+ "failed",
88
+ "blocked"
89
+ ];
90
+ var SOURCE_SNAPSHOT_EVENT_ACTIONS = ["created", "updated"];
91
+ var AUTOLOOP_FIX_RESULT_STATUSES = [
92
+ "pr_open",
93
+ "checks_passing",
94
+ "blocked",
95
+ "failed"
96
+ ];
97
+ var AUTOLOOP_CUSTOMER_SAFE_CONTROL_PLANE_MESSAGES = [
98
+ "databaseUrl is only supported for postgres and supabase trace sources",
99
+ "connectionSecretRef must be a secret reference, not a plaintext credential",
100
+ "connectionSecretRef must be an env: or AWS Secrets Manager reference",
101
+ "connectionSecretRef must be at most 500 characters",
102
+ "displayName must be a non-empty exact string",
103
+ "displayName cannot contain credential-shaped values",
104
+ "displayName must be at most 160 characters",
105
+ "repositoryFullName must be owner/repo",
106
+ "repositoryFullName must be at most 300 characters",
107
+ "sourceId must be a UUID",
108
+ "trace source filters and metadata cannot contain credential-shaped fields or values",
109
+ "trace source filters and metadata cannot contain prototype-polluting keys"
110
+ ];
111
+ var MAX_AUTOLOOP_CONTINUATION_ARTIFACT_BYTES = 1024 * 1024;
112
+ function manifestFieldIsExplicitlyFalse(record, camelKey) {
113
+ const snakeKey = camelKey.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
114
+ return record[camelKey] === false || record[snakeKey] === false;
115
+ }
116
+ var LOCAL_AUTOLOOP_LEDGER_QUEUED_LEASE_MS = 10 * 60 * 1e3;
117
+ var MAX_AGENT_STREAM_EVENT_METADATA_BYTES = 16 * 1024;
118
+
119
+ // ../packages/contracts/src/autoloop/layer-1.ts
120
+ var AUTOLOOP_ARTIFACT_TYPES = [
121
+ ...AUTOLOOP_CUSTOMER_VISIBLE_ARTIFACT_TYPES,
122
+ ...AUTOLOOP_INTERNAL_ONLY_ARTIFACT_TYPES
123
+ ];
124
+ var AUTOLOOP_REDACTION_STATUSES = [
125
+ "unreviewed",
126
+ AUTOLOOP_REDACTED_STATUS,
127
+ "not_required",
128
+ "blocked"
129
+ ];
130
+ var AUTOLOOP_VISIBILITIES = [
131
+ AUTOLOOP_CUSTOMER_VISIBLE_VISIBILITY,
132
+ AUTOLOOP_INTERNAL_VISIBILITY
133
+ ];
134
+ var AGENT_STREAM_EVENT_TYPES = [
135
+ AGENT_STREAM_DELTA_EVENT_TYPE,
136
+ AGENT_STREAM_TRUNCATED_EVENT_TYPE,
137
+ AGENT_STREAM_COMPLETED_EVENT_TYPE
138
+ ];
139
+ var AUTOLOOP_CODEX_SESSION_STATUSES = [
140
+ "queued",
141
+ ...AUTOLOOP_TERMINAL_STATUSES
142
+ ];
143
+ var AUTOLOOP_FIX_RUN_STATUSES = [
144
+ "not_started",
145
+ "running",
146
+ ...AUTOLOOP_FIX_RESULT_STATUSES
147
+ ];
148
+
149
+ // ../packages/contracts/src/autoloop/layer-2.ts
150
+ var AUTOLOOP_INTERNAL_ONLY_EVENT_TYPES = [
151
+ "worker.failed",
152
+ "codex_session.recorded",
153
+ "source_snapshot.created",
154
+ "source_snapshot.updated",
155
+ "canonical_trace_ingest.rejected",
156
+ "canonical_trace_ingest.digest_conflict",
157
+ "autoloop_run.claimed",
158
+ "autoloop_run.retry_scheduled",
159
+ "operator.requeued",
160
+ ...AGENT_STREAM_EVENT_TYPES
161
+ ];
162
+ function autoloopRunCapabilitiesFromPostFixPayload(payload) {
163
+ return {
164
+ requiresCloneEvidence: !manifestFieldIsExplicitlyFalse(
165
+ payload,
166
+ "postFixReproduceCloneEvidenceExpected"
167
+ )
168
+ };
169
+ }
170
+
171
+ // ../packages/contracts/src/autoloop/layer-3.ts
172
+ var AUTOLOOP_EVENT_TYPES = [
173
+ ...AUTOLOOP_CUSTOMER_VISIBLE_EVENT_TYPES,
174
+ ...AUTOLOOP_INTERNAL_ONLY_EVENT_TYPES
175
+ ];
176
+
177
+ // ../packages/contracts/src/autoloop/trace-source-capabilities.ts
178
+ var AUTOLOOP_TRACE_SOURCE_HOSTED_PROVIDER_CAPABILITIES = [
179
+ {
180
+ provider: "supabase",
181
+ tier: "supported",
182
+ ingestionMode: "hosted_poll",
183
+ hostedRegistration: "available",
184
+ hostedImport: "available",
185
+ summary: "Hosted workers can poll Supabase-hosted Postgres trace tables through a read-only database URL.",
186
+ nextStep: "Register with archal autoloop --source supabase and a read-only database URL secret reference."
187
+ },
188
+ {
189
+ provider: "postgres",
190
+ tier: "supported",
191
+ ingestionMode: "hosted_poll",
192
+ hostedRegistration: "available",
193
+ hostedImport: "available",
194
+ summary: "Hosted workers can poll Postgres trace tables or SQL views through a read-only database URL.",
195
+ nextStep: "Register with archal autoloop --source postgres and a read-only database URL secret reference."
196
+ },
197
+ {
198
+ provider: "http",
199
+ tier: "beta",
200
+ ingestionMode: "client_upload",
201
+ hostedRegistration: "available",
202
+ hostedImport: "available",
203
+ summary: "HTTP push traces can be normalized locally and uploaded into hosted autoloop as autoloop runs.",
204
+ nextStep: "Push traces to the workspace dashboard OTLP ingest endpoint, then run archal autoloop ./traces --repository owner/repo."
205
+ },
206
+ {
207
+ provider: "otel",
208
+ tier: "beta",
209
+ ingestionMode: "client_upload",
210
+ hostedRegistration: "available",
211
+ hostedImport: "available",
212
+ summary: "OTel traces can be normalized locally and uploaded into hosted autoloop as autoloop runs.",
213
+ nextStep: "Configure your OTel SDK to export to the workspace dashboard OTLP endpoint, then run archal autoloop ./traces --repository owner/repo."
214
+ },
215
+ {
216
+ provider: "langfuse",
217
+ tier: "import",
218
+ ingestionMode: "client_upload",
219
+ hostedRegistration: "available",
220
+ hostedImport: "available",
221
+ summary: "Langfuse exports can be normalized locally and uploaded into hosted autoloop as autoloop runs.",
222
+ nextStep: "Export traces from Langfuse and import via the dashboard, or place normalized JSON in an autoloop watch directory."
223
+ },
224
+ {
225
+ provider: "braintrust",
226
+ tier: "import",
227
+ ingestionMode: "client_upload",
228
+ hostedRegistration: "available",
229
+ hostedImport: "available",
230
+ summary: "Braintrust exports can be normalized locally and uploaded into hosted autoloop as autoloop runs.",
231
+ nextStep: "Export traces from Braintrust and import via the dashboard, or place normalized JSON in an autoloop watch directory."
232
+ },
233
+ {
234
+ provider: "s3",
235
+ tier: "import",
236
+ ingestionMode: "client_upload",
237
+ hostedRegistration: "available",
238
+ hostedImport: "available",
239
+ summary: "S3 trace exports can be mirrored locally and uploaded into hosted autoloop as autoloop runs.",
240
+ nextStep: "Configure bucket access from the dashboard Connect a trace database form, or drop normalized exports into a watch directory with archal autoloop ./traces --repository owner/repo."
241
+ },
242
+ {
243
+ provider: "gcs",
244
+ tier: "import",
245
+ ingestionMode: "client_upload",
246
+ hostedRegistration: "available",
247
+ hostedImport: "available",
248
+ summary: "GCS trace exports can be mirrored locally and uploaded into hosted autoloop as autoloop runs.",
249
+ nextStep: "Configure bucket access from the dashboard Connect a trace database form, or drop normalized exports into a watch directory with archal autoloop ./traces --repository owner/repo."
250
+ },
251
+ {
252
+ provider: "custom",
253
+ tier: "custom_contract",
254
+ ingestionMode: "client_upload",
255
+ hostedRegistration: "available",
256
+ hostedImport: "available",
257
+ summary: "Custom trace JSON can be normalized locally and uploaded into hosted autoloop as autoloop runs.",
258
+ nextStep: "Place normalized trace JSON in a watch directory and run archal autoloop ./traces --repository owner/repo."
259
+ },
260
+ {
261
+ provider: "file",
262
+ tier: "local_only",
263
+ ingestionMode: "client_upload",
264
+ hostedRegistration: "available",
265
+ hostedImport: "available",
266
+ summary: "File-backed traces can be normalized locally and uploaded into hosted autoloop as autoloop runs.",
267
+ nextStep: "Place trace JSON files in a watch directory and run archal autoloop ./traces --repository owner/repo."
268
+ }
269
+ ];
270
+ var AUTOLOOP_TRACE_SOURCE_HOSTED_PROVIDER_CAPABILITY_BY_PROVIDER = new Map(
271
+ AUTOLOOP_TRACE_SOURCE_HOSTED_PROVIDER_CAPABILITIES.map((cap) => [cap.provider, cap])
272
+ );
273
+
274
+ // ../packages/contracts/src/autoloop.ts
275
+ var AUTOLOOP_CUSTOMER_SAFE_CONTROL_PLANE_MESSAGE_SET = new Set(AUTOLOOP_CUSTOMER_SAFE_CONTROL_PLANE_MESSAGES);
276
+ var AUTOLOOP_CUSTOMER_VISIBLE_ARTIFACT_TYPE_SET = new Set(
277
+ AUTOLOOP_CUSTOMER_VISIBLE_ARTIFACT_TYPES
278
+ );
279
+ var AUTOLOOP_INTERNAL_ONLY_ARTIFACT_TYPE_SET = new Set(
280
+ AUTOLOOP_INTERNAL_ONLY_ARTIFACT_TYPES
281
+ );
282
+ var AUTOLOOP_ARTIFACT_TYPE_SET = new Set(AUTOLOOP_ARTIFACT_TYPES);
283
+ var AUTOLOOP_PHASE_HEALTH_STATUS_SET = new Set(AUTOLOOP_PHASE_HEALTH_STATUSES);
284
+ var AUTOLOOP_CODEX_SESSION_STATUS_SET = new Set(AUTOLOOP_CODEX_SESSION_STATUSES);
285
+ var AUTOLOOP_CUSTOMER_VISIBLE_ARTIFACT_REDACTION_STATUS_SET = new Set(
286
+ AUTOLOOP_CUSTOMER_VISIBLE_ARTIFACT_REDACTION_STATUSES
287
+ );
288
+ var AUTOLOOP_CUSTOMER_VISIBLE_EVENT_TYPE_SET = new Set(
289
+ AUTOLOOP_CUSTOMER_VISIBLE_EVENT_TYPES
290
+ );
291
+ var AUTOLOOP_INTERNAL_ONLY_EVENT_TYPE_SET = new Set(
292
+ AUTOLOOP_INTERNAL_ONLY_EVENT_TYPES
293
+ );
294
+ var AUTOLOOP_PHASE_SET = new Set(AUTOLOOP_PHASES);
295
+ var AUTOLOOP_ACTIVE_PHASE_SET = new Set(AUTOLOOP_ACTIVE_PHASES);
296
+ var AUTOLOOP_CODEX_SESSION_EVENT_STATUS_SET = new Set(
297
+ AUTOLOOP_CODEX_SESSION_EVENT_STATUSES
298
+ );
299
+ var AUTOLOOP_EVENT_TYPE_SET = new Set(AUTOLOOP_EVENT_TYPES);
300
+ var AUTOLOOP_EVENT_SEVERITY_SET = new Set(AUTOLOOP_EVENT_SEVERITIES);
301
+ var AUTOLOOP_VISIBILITY_SET = new Set(AUTOLOOP_VISIBILITIES);
302
+ var AUTOLOOP_REDACTION_STATUS_SET = new Set(AUTOLOOP_REDACTION_STATUSES);
303
+ var AUTOLOOP_TERMINAL_STATUS_SET = new Set(AUTOLOOP_TERMINAL_STATUSES);
304
+ var SOURCE_SNAPSHOT_EVENT_ACTION_SET = new Set(SOURCE_SNAPSHOT_EVENT_ACTIONS);
305
+ var AUTOLOOP_EXECUTION_POLICY_PHASE_COUNT = {
306
+ observe: 0,
307
+ grade: 1,
308
+ seed: 2,
309
+ reproduce: 3,
310
+ fix: AUTOLOOP_ACTIVE_PHASES.length
311
+ };
312
+ function assessAutoloopStoredFixPrEvidence(payload, input = {}) {
313
+ const localValidationStatus = autoloopFixPrEvidenceStringFromRecord(
314
+ payload,
315
+ "localValidationStatus",
316
+ "local_validation_status"
317
+ );
318
+ const fixQuality = payloadFixQuality(payload);
319
+ const postFixReproduction = autoloopPostFixReproductionEvidenceFromPayload(payload, input);
320
+ const prBodyQuality = payloadPrBodyQuality(payload);
321
+ const verifiedFixEvidence = {
322
+ localValidationStatus,
323
+ fixQuality,
324
+ postFixReproduction,
325
+ prBodyQuality
326
+ };
327
+ if (!postFixReproduction.passed) {
328
+ return {
329
+ passed: false,
330
+ reason: postFixReproduction.reason,
331
+ localValidationStatus,
332
+ fixQuality,
333
+ postFixReproduction,
334
+ prBodyQuality,
335
+ verifiedFixEvidence: null
336
+ };
337
+ }
338
+ if (fixQuality.status !== "passed") {
339
+ return {
340
+ passed: false,
341
+ reason: fixQuality.reason,
342
+ localValidationStatus,
343
+ fixQuality,
344
+ postFixReproduction,
345
+ prBodyQuality,
346
+ verifiedFixEvidence: null
347
+ };
348
+ }
349
+ if (prBodyQuality.status !== "passed") {
350
+ return {
351
+ passed: false,
352
+ reason: prBodyQuality.reason,
353
+ localValidationStatus,
354
+ fixQuality,
355
+ postFixReproduction,
356
+ prBodyQuality,
357
+ verifiedFixEvidence: null
358
+ };
359
+ }
360
+ return {
361
+ passed: true,
362
+ reason: "fix_pr_quality_passed",
363
+ localValidationStatus,
364
+ fixQuality,
365
+ postFixReproduction,
366
+ prBodyQuality,
367
+ verifiedFixEvidence
368
+ };
369
+ }
370
+ function autoloopPostFixReproductionEvidenceFromPayload(payload, input = {}) {
371
+ if (!isAutoloopFixPrEvidenceRecord(payload)) {
372
+ return failedAutoloopPostFixReproduction("postfix_reproduction_not_verified");
373
+ }
374
+ const status = autoloopFixPrEvidenceString(
375
+ payload["postFixReproduceStatus"] ?? payload["post_fix_reproduce_status"]
376
+ );
377
+ const reverified = autoloopFixPrEvidenceBoolean(
378
+ payload["reproductionReverified"] ?? payload["reproduction_reverified"]
379
+ );
380
+ const hasCloneEvidence = autoloopFixPrEvidenceBoolean(
381
+ payload["postFixReproduceHasCloneEvidence"] ?? payload["post_fix_reproduce_has_clone_evidence"]
382
+ ) === true;
383
+ const hasCriteriaEvidence = autoloopFixPrEvidenceBoolean(
384
+ payload["postFixReproduceHasCriteriaEvidence"] ?? payload["post_fix_reproduce_has_criteria_evidence"]
385
+ );
386
+ const identityMatchesPreFix = autoloopFixPrEvidenceBoolean(
387
+ payload["postFixReproduceIdentityMatchesPreFix"] ?? payload["post_fix_reproduce_identity_matches_pre_fix"] ?? payload["postFixReproduceReplayIdentityMatchesPreFix"] ?? payload["post_fix_reproduce_replay_identity_matches_pre_fix"]
388
+ );
389
+ const commitSha = autoloopFixPrEvidenceSha(
390
+ autoloopFixPrEvidenceString(
391
+ payload["postFixReproduceCommitSha"] ?? payload["post_fix_reproduce_commit_sha"]
392
+ )
393
+ );
394
+ const requiresCloneEvidence = autoloopRunCapabilitiesFromPostFixPayload(payload).requiresCloneEvidence;
395
+ const cloneEvidenceField = requiresCloneEvidence ? {} : { cloneEvidenceExpected: false };
396
+ if (status === "not_reproduced" && reverified === true && (!requiresCloneEvidence || hasCloneEvidence === true) && hasCriteriaEvidence === true && identityMatchesPreFix === true) {
397
+ if (!commitSha) {
398
+ return failedAutoloopPostFixReproduction("postfix_reproduction_commit_missing", {
399
+ status,
400
+ hasCloneEvidence,
401
+ hasCriteriaEvidence,
402
+ identityMatchesPreFix,
403
+ reproductionReverified: true,
404
+ ...cloneEvidenceField
405
+ });
406
+ }
407
+ if (input.expectedCommitSha && commitSha.toLowerCase() !== input.expectedCommitSha.toLowerCase()) {
408
+ return failedAutoloopPostFixReproduction("postfix_reproduction_commit_mismatch", {
409
+ status,
410
+ commitSha,
411
+ hasCloneEvidence,
412
+ hasCriteriaEvidence,
413
+ identityMatchesPreFix,
414
+ reproductionReverified: true,
415
+ ...cloneEvidenceField
416
+ });
417
+ }
418
+ return {
419
+ passed: true,
420
+ reason: "postfix_reproduction_passed",
421
+ status,
422
+ commitSha,
423
+ hasCloneEvidence,
424
+ hasCriteriaEvidence,
425
+ identityMatchesPreFix,
426
+ reproductionReverified: true,
427
+ ...cloneEvidenceField
428
+ };
429
+ }
430
+ if (status === "reproduced" || status === "flaky") {
431
+ return failedAutoloopPostFixReproduction("postfix_reproduction_still_failing", {
432
+ status,
433
+ commitSha
434
+ });
435
+ }
436
+ if (status === "not_reproduced" && requiresCloneEvidence && hasCloneEvidence !== true) {
437
+ return failedAutoloopPostFixReproduction("postfix_reproduction_clone_evidence_missing", {
438
+ status,
439
+ commitSha
440
+ });
441
+ }
442
+ if (status === "not_reproduced" && hasCriteriaEvidence !== true) {
443
+ return failedAutoloopPostFixReproduction("postfix_reproduction_criteria_evidence_missing", {
444
+ status,
445
+ commitSha,
446
+ hasCloneEvidence: true
447
+ });
448
+ }
449
+ if (status === "not_reproduced" && identityMatchesPreFix !== true) {
450
+ return failedAutoloopPostFixReproduction("postfix_reproduction_trace_mismatch", {
451
+ status,
452
+ commitSha,
453
+ hasCloneEvidence: true,
454
+ hasCriteriaEvidence: true,
455
+ identityMatchesPreFix: false,
456
+ reproductionReverified: reverified === true
457
+ });
458
+ }
459
+ if (status === "not_reproduced") {
460
+ return failedAutoloopPostFixReproduction(
461
+ autoloopFixPrEvidenceString(
462
+ payload["postFixReproduceReason"] ?? payload["post_fix_reproduce_reason"]
463
+ ) ?? "postfix_reproduction_not_verified",
464
+ {
465
+ status,
466
+ commitSha,
467
+ hasCloneEvidence: true,
468
+ hasCriteriaEvidence: true,
469
+ identityMatchesPreFix: true,
470
+ reproductionReverified: false
471
+ }
472
+ );
473
+ }
474
+ if (status !== null) {
475
+ return failedAutoloopPostFixReproduction(
476
+ autoloopFixPrEvidenceString(
477
+ payload["postFixReproduceReason"] ?? payload["post_fix_reproduce_reason"]
478
+ ) ?? "postfix_reproduction_not_verified",
479
+ { status, commitSha }
480
+ );
481
+ }
482
+ const nested = nestedAutoloopPostFixReproductionEvidence(
483
+ payload,
484
+ identityMatchesPreFix,
485
+ commitSha,
486
+ input
487
+ );
488
+ if (nested) return nested;
489
+ return failedAutoloopPostFixReproduction(
490
+ autoloopFixPrEvidenceString(
491
+ payload["postFixReproduceReason"] ?? payload["post_fix_reproduce_reason"]
492
+ ) ?? "postfix_reproduction_not_verified",
493
+ { status, commitSha }
494
+ );
495
+ }
496
+ function autoloopPostFixReproductionReason(input) {
497
+ if (input.hasInfrastructureFailure || input.evaluatorInfrastructureFailure) {
498
+ return "postfix_reproduction_infrastructure_failure";
499
+ }
500
+ if (input.status === "reproduced" || input.genuineFailureCount > 0) {
501
+ return "postfix_reproduction_still_failing";
502
+ }
503
+ if (input.status !== "not_reproduced") return "postfix_reproduction_not_verified";
504
+ if (input.requiresCloneEvidence !== false && !input.hasCloneEvidence) {
505
+ return "postfix_reproduction_clone_evidence_missing";
506
+ }
507
+ if (!input.hasCriteriaEvidence) return "postfix_reproduction_criteria_evidence_missing";
508
+ if (!input.identityMatchesPreFix) return "postfix_reproduction_trace_mismatch";
509
+ if (input.toolErrorCount > 0) return "postfix_reproduction_tool_errors";
510
+ if (input.inconclusiveCriteria > 0) return "postfix_reproduction_inconclusive";
511
+ if (input.satisfiedCriteria <= 0) return "postfix_reproduction_no_scored_criteria";
512
+ return "postfix_reproduction_passed";
513
+ }
514
+ function nestedAutoloopPostFixReproductionEvidence(payload, topLevelIdentityMatchesPreFix, commitSha, input) {
515
+ const reproduction = payload["postFixReproduction"] ?? payload["post_fix_reproduction"];
516
+ if (!isAutoloopFixPrEvidenceRecord(reproduction)) return null;
517
+ const attempts = reproduction["attempts"];
518
+ const commands = Array.isArray(reproduction["commands"]) ? reproduction["commands"] : [];
519
+ const hasEvidence = typeof attempts === "number" && attempts >= 1 && commands.length > 0;
520
+ const status = autoloopFixPrEvidenceString(reproduction["status"]);
521
+ const hasCloneEvidence = autoloopFixPrEvidenceBoolean(reproduction["hasCloneEvidence"]) === true;
522
+ const hasCriteriaEvidence = autoloopFixPrEvidenceBoolean(reproduction["hasCriteriaEvidence"]) === true;
523
+ const satisfiedCriteria = autoloopFixPrEvidenceNumber(reproduction["satisfiedCriteria"]);
524
+ const genuineFailureCount = Math.max(
525
+ autoloopFixPrEvidenceNumber(reproduction["genuineFailureCount"]),
526
+ autoloopFixPrEvidenceArray(reproduction["failedCriteria"]).length,
527
+ autoloopFixPrEvidenceStringArray(reproduction["failedCriterionIds"]).length
528
+ );
529
+ const inconclusiveCriteria = autoloopFixPrEvidenceNumber(reproduction["inconclusiveCriteria"]);
530
+ const toolErrorCount = Math.max(
531
+ autoloopFixPrEvidenceNumber(reproduction["toolErrorCount"]),
532
+ autoloopFixPrEvidenceArray(reproduction["toolErrors"]).length
533
+ );
534
+ const hasInfrastructureFailure = autoloopFixPrEvidenceBoolean(reproduction["hasInfrastructureFailure"]) === true;
535
+ const evaluatorInfrastructureFailure = autoloopFixPrEvidenceBoolean(reproduction["evaluatorInfrastructureFailure"]) === true;
536
+ const identityMatchesPreFix = autoloopFixPrEvidenceBoolean(
537
+ reproduction["replayIdentityMatchesPreFix"] ?? reproduction["identityMatchesPreFix"]
538
+ ) ?? topLevelIdentityMatchesPreFix ?? false;
539
+ const cleanPostFixCriteria = status === "not_reproduced" && hasCloneEvidence && hasCriteriaEvidence && satisfiedCriteria > 0 && genuineFailureCount === 0 && inconclusiveCriteria === 0 && toolErrorCount === 0 && !hasInfrastructureFailure && !evaluatorInfrastructureFailure;
540
+ if (cleanPostFixCriteria && hasEvidence) {
541
+ if (!identityMatchesPreFix) {
542
+ return failedAutoloopPostFixReproduction("postfix_reproduction_trace_mismatch", {
543
+ status,
544
+ commitSha,
545
+ hasCloneEvidence,
546
+ hasCriteriaEvidence,
547
+ identityMatchesPreFix: false,
548
+ reproductionReverified: true
549
+ });
550
+ }
551
+ if (!commitSha && input.expectedCommitSha) {
552
+ return failedAutoloopPostFixReproduction("postfix_reproduction_commit_missing", {
553
+ status,
554
+ hasCloneEvidence,
555
+ hasCriteriaEvidence,
556
+ identityMatchesPreFix,
557
+ reproductionReverified: true
558
+ });
559
+ }
560
+ if (input.expectedCommitSha && commitSha?.toLowerCase() !== input.expectedCommitSha.toLowerCase()) {
561
+ return failedAutoloopPostFixReproduction("postfix_reproduction_commit_mismatch", {
562
+ status,
563
+ commitSha,
564
+ hasCloneEvidence,
565
+ hasCriteriaEvidence,
566
+ identityMatchesPreFix,
567
+ reproductionReverified: true
568
+ });
569
+ }
570
+ return {
571
+ passed: true,
572
+ reason: "postfix_reproduction_passed",
573
+ status,
574
+ commitSha,
575
+ hasCloneEvidence,
576
+ hasCriteriaEvidence,
577
+ identityMatchesPreFix,
578
+ reproductionReverified: true
579
+ };
580
+ }
581
+ if (status === "not_reproduced" && hasEvidence) {
582
+ return failedAutoloopPostFixReproduction(
583
+ autoloopPostFixReproductionReason({
584
+ status,
585
+ genuineFailureCount,
586
+ hasCloneEvidence,
587
+ hasCriteriaEvidence,
588
+ identityMatchesPreFix,
589
+ hasInfrastructureFailure,
590
+ evaluatorInfrastructureFailure,
591
+ toolErrorCount,
592
+ inconclusiveCriteria,
593
+ satisfiedCriteria
594
+ }),
595
+ {
596
+ status,
597
+ commitSha,
598
+ hasCloneEvidence,
599
+ hasCriteriaEvidence,
600
+ identityMatchesPreFix,
601
+ reproductionReverified: false
602
+ }
603
+ );
604
+ }
605
+ const reason = autoloopFixPrEvidenceString(reproduction["reason"]);
606
+ return reason ? failedAutoloopPostFixReproduction(reason, { status, commitSha }) : null;
607
+ }
608
+ function failedAutoloopPostFixReproduction(reason, evidence = {}) {
609
+ return {
610
+ passed: false,
611
+ reason,
612
+ status: evidence.status ?? null,
613
+ commitSha: evidence.commitSha ?? null,
614
+ hasCloneEvidence: evidence.hasCloneEvidence ?? false,
615
+ hasCriteriaEvidence: evidence.hasCriteriaEvidence ?? false,
616
+ identityMatchesPreFix: evidence.identityMatchesPreFix ?? false,
617
+ reproductionReverified: evidence.reproductionReverified ?? false
618
+ };
619
+ }
620
+ function payloadFixQuality(payload) {
621
+ if (!isAutoloopFixPrEvidenceRecord(payload)) {
622
+ return failedFixQuality("fix_quality_evidence_missing");
623
+ }
624
+ const quality = payload["fixQuality"] ?? payload["fix_quality"];
625
+ if (!isAutoloopFixPrEvidenceRecord(quality)) {
626
+ return failedFixQuality("fix_quality_evidence_missing");
627
+ }
628
+ const changedFiles = autoloopFixPrEvidenceStringArray(
629
+ quality["changedFiles"] ?? quality["changed_files"]
630
+ );
631
+ const sourceFiles = autoloopFixPrEvidenceStringArray(
632
+ quality["sourceFiles"] ?? quality["source_files"]
633
+ );
634
+ const implementationFiles = autoloopFixPrEvidenceStringArray(
635
+ quality["implementationFiles"] ?? quality["implementation_files"]
636
+ );
637
+ const regressionEvidence = autoloopFixPrEvidenceStringArray(
638
+ quality["regressionEvidence"] ?? quality["regression_evidence"]
639
+ );
640
+ const runtimeEntrypointFiles = autoloopFixPrEvidenceStringArray(
641
+ quality["runtimeEntrypointFiles"] ?? quality["runtime_entrypoint_files"]
642
+ );
643
+ const prDetailsPresent = autoloopFixPrEvidenceBoolean(quality["prDetailsPresent"] ?? quality["pr_details_present"]) ?? true;
644
+ if (quality["status"] !== "passed") {
645
+ return {
646
+ status: "failed",
647
+ reason: autoloopFixPrEvidenceString(quality["reason"]) ?? "fix_quality_evidence_failed",
648
+ changedFiles,
649
+ sourceFiles,
650
+ implementationFiles,
651
+ regressionEvidence,
652
+ runtimeEntrypointFiles,
653
+ prDetailsPresent
654
+ };
655
+ }
656
+ if (changedFiles.length === 0) return failedFixQuality("fix_quality_changed_files_missing");
657
+ if (sourceFiles.length === 0) {
658
+ return failedFixQuality("fix_quality_cosmetic_only_patch", { changedFiles });
659
+ }
660
+ if (implementationFiles.length === 0) {
661
+ return failedFixQuality("fix_quality_meaningful_diff_missing", { changedFiles, sourceFiles });
662
+ }
663
+ if (isDisallowedAutoloopEvalHarnessOnlyPatch(implementationFiles, runtimeEntrypointFiles)) {
664
+ return failedFixQuality("fix_quality_eval_harness_only_patch", {
665
+ changedFiles,
666
+ sourceFiles,
667
+ implementationFiles,
668
+ runtimeEntrypointFiles
669
+ });
670
+ }
671
+ if (regressionEvidence.length === 0) {
672
+ return failedFixQuality("fix_quality_regression_evidence_missing", {
673
+ changedFiles,
674
+ sourceFiles,
675
+ implementationFiles,
676
+ runtimeEntrypointFiles
677
+ });
678
+ }
679
+ if (!prDetailsPresent) {
680
+ return failedFixQuality("fix_quality_pr_details_missing", {
681
+ changedFiles,
682
+ sourceFiles,
683
+ implementationFiles,
684
+ regressionEvidence,
685
+ runtimeEntrypointFiles,
686
+ prDetailsPresent
687
+ });
688
+ }
689
+ return {
690
+ status: "passed",
691
+ reason: "fix_quality_passed",
692
+ changedFiles,
693
+ sourceFiles,
694
+ implementationFiles,
695
+ regressionEvidence,
696
+ runtimeEntrypointFiles,
697
+ prDetailsPresent
698
+ };
699
+ }
700
+ function payloadPrBodyQuality(payload) {
701
+ if (!isAutoloopFixPrEvidenceRecord(payload)) return failedPrBody("pr_body_evidence_missing");
702
+ const quality = payload["prBodyQuality"] ?? payload["pr_body_quality"];
703
+ if (!isAutoloopFixPrEvidenceRecord(quality)) return failedPrBody("pr_body_evidence_missing");
704
+ const status = quality["status"];
705
+ const reason = autoloopFixPrEvidenceString(quality["reason"]) ?? (status === "passed" ? "pr_body_passed" : "pr_body_evidence_failed");
706
+ const textLength = autoloopFixPrEvidenceNumber(quality["textLength"] ?? quality["text_length"]);
707
+ const wordCount = autoloopFixPrEvidenceNumber(quality["wordCount"] ?? quality["word_count"]);
708
+ if (status !== "passed") return failedPrBody(reason, textLength, wordCount);
709
+ if (textLength <= 0 || wordCount < 20) {
710
+ return failedPrBody("pr_body_not_human_readable", textLength, wordCount);
711
+ }
712
+ return { status: "passed", reason: "pr_body_passed", textLength, wordCount };
713
+ }
714
+ function failedFixQuality(reason, evidence = {}) {
715
+ return {
716
+ status: "failed",
717
+ reason,
718
+ changedFiles: evidence.changedFiles ?? [],
719
+ sourceFiles: evidence.sourceFiles ?? [],
720
+ implementationFiles: evidence.implementationFiles ?? [],
721
+ regressionEvidence: evidence.regressionEvidence ?? [],
722
+ runtimeEntrypointFiles: evidence.runtimeEntrypointFiles ?? [],
723
+ prDetailsPresent: evidence.prDetailsPresent ?? false
724
+ };
725
+ }
726
+ function failedPrBody(reason, textLength = 0, wordCount = 0) {
727
+ return { status: "failed", reason, textLength, wordCount };
728
+ }
729
+ function autoloopFixPrEvidenceStringFromRecord(payload, camelCaseKey, snakeCaseKey) {
730
+ if (!isAutoloopFixPrEvidenceRecord(payload)) return null;
731
+ return autoloopFixPrEvidenceString(payload[camelCaseKey] ?? payload[snakeCaseKey]);
732
+ }
733
+ function autoloopFixPrEvidenceStringArray(value) {
734
+ if (!Array.isArray(value)) return [];
735
+ return value.filter((entry) => typeof entry === "string" && entry.length > 0);
736
+ }
737
+ function autoloopFixPrEvidenceArray(value) {
738
+ return Array.isArray(value) ? value : [];
739
+ }
740
+ function isAutoloopAttachEvalHarnessFile(file) {
741
+ return /(^|\/)archal(\/|$)/i.test(file) || /(^|\/)(evals?|evaluations?|harness)(\/|$)/i.test(file) || /(^|\/)run-[^/]*eval\.[cm]?[jt]s$/i.test(file) || /(^|\/)scripts\/.*(?:archal|eval|harness|replay).*$/i.test(file) || /(^|\/)services\/ai\/labs\//i.test(file);
742
+ }
743
+ function isDisallowedAutoloopEvalHarnessOnlyPatch(implementationFiles, runtimeEntrypointFiles) {
744
+ void runtimeEntrypointFiles;
745
+ return implementationFiles.length > 0 && implementationFiles.every(isAutoloopAttachEvalHarnessFile);
746
+ }
747
+ function autoloopFixPrEvidenceString(value) {
748
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
749
+ }
750
+ function autoloopFixPrEvidenceBoolean(value) {
751
+ return typeof value === "boolean" ? value : null;
752
+ }
753
+ function autoloopFixPrEvidenceNumber(value) {
754
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
755
+ }
756
+ function autoloopFixPrEvidenceSha(value) {
757
+ if (!value) return null;
758
+ return /^[a-f0-9]{6,40}$/i.test(value) ? value : null;
759
+ }
760
+ function isAutoloopFixPrEvidenceRecord(value) {
761
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
762
+ }
763
+
764
+ // ../packages/node-auth/src/constants.ts
765
+ var CREDENTIALS_FILE = "credentials.json";
766
+ var CREDENTIALS_KEY_FILE = "credentials.key";
767
+ var AUTH_TOKEN_ENV_VAR = "ARCHAL_TOKEN";
768
+ var TOKEN_ENCRYPTION_PREFIX = "enc-v1";
769
+ var CREDENTIALS_MASTER_KEY_ENV_VAR = "ARCHAL_CREDENTIALS_MASTER_KEY";
770
+ var KEYCHAIN_SERVICE = "archal-cli";
771
+ var KEYCHAIN_ACCOUNT = "credentials-master-key";
772
+ var WORKSPACE_API_KEY_PREFIX = "archal_ws_";
773
+ var ENV_TOKEN_FALLBACK_TTL_SECONDS = 24 * 60 * 60;
774
+
775
+ // ../packages/node-auth/src/types.ts
776
+ function isPlan(value) {
777
+ return value === "free" || value === "pro" || value === "enterprise";
778
+ }
779
+
780
+ // ../packages/node-auth/src/credential-store.ts
781
+ var import_node_child_process = require("child_process");
782
+ var import_node_crypto = require("crypto");
783
+ var import_node_fs = require("fs");
784
+ var import_node_os = require("os");
785
+ var import_node_path2 = require("path");
786
+
787
+ // ../packages/clone-catalog/src/generated-catalog.ts
788
+ var GENERATED_CLONE_CATALOG = [
789
+ {
790
+ id: "apify",
791
+ icon: "AP",
792
+ name: "Apify",
793
+ description: "Actors, runs, datasets, key-value stores, and request queues.",
794
+ stage: "preview",
795
+ toolCount: 59,
796
+ transport: "rest",
797
+ architectureClass: "domain-simulator",
798
+ domainPrimitives: [
799
+ "Apify upstream error and pagination envelopes",
800
+ "dataset, key-value store, and request-queue stateful projections",
801
+ "fixture-backed fallback semantics for uncovered REST paths"
802
+ ],
803
+ behaviorOwner: "src/upstream.ts",
804
+ opsCoverage: null
805
+ },
806
+ {
807
+ id: "calcom",
808
+ icon: "CC",
809
+ name: "Cal.com",
810
+ description: "Event types, schedules, availability slots, bookings, calendars, and webhooks.",
811
+ stage: "preview",
812
+ toolCount: 35,
813
+ transport: "both",
814
+ architectureClass: "domain-simulator",
815
+ domainPrimitives: [
816
+ "schedule and event-type availability projection",
817
+ "booking create, cancel, and reschedule lifecycle",
818
+ "host-wide busy interval and slot computation",
819
+ "webhook summary/detail lifecycle projection"
820
+ ],
821
+ behaviorOwner: "src/state/relationships.ts",
822
+ opsCoverage: null
823
+ },
824
+ {
825
+ id: "clickup",
826
+ icon: "CU",
827
+ name: "ClickUp",
828
+ description: "Teams, spaces, folders, lists, tasks, comments, tags, time tracking, and checklists.",
829
+ stage: "preview",
830
+ toolCount: 123,
831
+ transport: "both",
832
+ architectureClass: "standard-core",
833
+ domainPrimitives: [],
834
+ behaviorOwner: null,
835
+ opsCoverage: null
836
+ },
837
+ {
838
+ id: "customerio",
839
+ icon: "CI",
840
+ name: "Customer.io",
841
+ description: "Messaging automation across campaigns, broadcasts, transactional email, segments, customers, and message delivery.",
842
+ stage: "preview",
843
+ toolCount: 129,
844
+ transport: "rest",
845
+ architectureClass: "standard-core",
846
+ domainPrimitives: [],
847
+ behaviorOwner: null,
848
+ opsCoverage: null
849
+ },
850
+ {
851
+ id: "datadog",
852
+ icon: "DD",
853
+ name: "Datadog",
854
+ description: "Observability REST API \u2014 metrics, logs, monitors, dashboards, SLOs, incidents, teams, users, and service definitions.",
855
+ stage: "preview",
856
+ toolCount: 63,
857
+ transport: "rest",
858
+ architectureClass: "domain-simulator",
859
+ domainPrimitives: [
860
+ "time-series query windows",
861
+ "log query filtering",
862
+ "monitor evaluation and alert state"
863
+ ],
864
+ behaviorOwner: "src/domain/simulator.ts",
865
+ opsCoverage: null
866
+ },
867
+ {
868
+ id: "discord",
869
+ icon: "DC",
870
+ name: "Discord",
871
+ description: "Guilds, channels, messages, webhooks, threads, commands, and interaction responses.",
872
+ stage: "preview",
873
+ toolCount: 67,
874
+ transport: "both",
875
+ architectureClass: "domain-simulator",
876
+ domainPrimitives: [
877
+ "channel membership",
878
+ "message timeline ordering",
879
+ "thread and event delivery semantics"
880
+ ],
881
+ behaviorOwner: "src/domain/discord-simulator.ts",
882
+ opsCoverage: 14
883
+ },
884
+ {
885
+ id: "github",
886
+ icon: "GH",
887
+ name: "GitHub",
888
+ description: "Repos, issues, pull requests, branches, and commits.",
889
+ stage: "public",
890
+ toolCount: 26,
891
+ transport: "both",
892
+ architectureClass: "domain-simulator",
893
+ domainPrimitives: [
894
+ "repository branch, commit, tree, and diff projection",
895
+ "issue and pull-request lifecycle projection",
896
+ "review, comment, and status/check aggregation",
897
+ "permission-scoped reads and webhook event delivery"
898
+ ],
899
+ behaviorOwner: "src/state/transition-rules.ts",
900
+ opsCoverage: 96
901
+ },
902
+ {
903
+ id: "gitlab",
904
+ icon: "GL",
905
+ name: "GitLab",
906
+ description: "Projects, branches, commits, issues, merge requests, pipelines, labels, milestones, releases, and webhooks.",
907
+ stage: "preview",
908
+ toolCount: 559,
909
+ transport: "both",
910
+ architectureClass: "domain-simulator",
911
+ domainPrimitives: [
912
+ "issue and merge-request state transitions",
913
+ "note/comment ordering and count projection",
914
+ "repository branch, commit, merge, and diff projection",
915
+ "GitLab webhook subscription, payload, and header emission"
916
+ ],
917
+ behaviorOwner: "src/state/webhook-delivery-config.ts",
918
+ opsCoverage: null
919
+ },
920
+ {
921
+ id: "google-workspace",
922
+ icon: "GW",
923
+ name: "Google Workspace",
924
+ description: "Gmail, Calendar, Drive, Sheets, and Contacts.",
925
+ stage: "preview",
926
+ toolCount: 249,
927
+ transport: "both",
928
+ architectureClass: "domain-simulator",
929
+ domainPrimitives: [
930
+ "Gmail thread/history engine",
931
+ "Drive changes and permissions",
932
+ "Calendar recurrence and watch sync"
933
+ ],
934
+ behaviorOwner: "src/domain/google-workspace-simulator.ts",
935
+ opsCoverage: 64
936
+ },
937
+ {
938
+ id: "hubspot",
939
+ icon: "HS",
940
+ name: "HubSpot",
941
+ description: "CRM contacts, companies, deals, tickets, and engagements.",
942
+ stage: "preview",
943
+ toolCount: 44,
944
+ transport: "rest",
945
+ architectureClass: "replay-shell",
946
+ domainPrimitives: [
947
+ "CRM object state and associations",
948
+ "Pipeline and property schema state",
949
+ "Recording-backed REST/MCP aliases awaiting stateful lift"
950
+ ],
951
+ behaviorOwner: null,
952
+ opsCoverage: 99
953
+ },
954
+ {
955
+ id: "jira",
956
+ icon: "JR",
957
+ name: "Jira",
958
+ description: "Issues, projects, boards, sprints, and versions.",
959
+ stage: "preview",
960
+ toolCount: 49,
961
+ transport: "both",
962
+ architectureClass: "domain-simulator",
963
+ domainPrimitives: [
964
+ "issue workflow transitions and mutation history",
965
+ "JQL/search and issue field projection",
966
+ "sprint, board, version, and SLA time-based transitions",
967
+ "permission-scoped reads and Jira webhook event delivery"
968
+ ],
969
+ behaviorOwner: "src/state/transition-rules.ts",
970
+ opsCoverage: 80
971
+ },
972
+ {
973
+ id: "linear",
974
+ icon: "LN",
975
+ name: "Linear",
976
+ description: "Issues, projects, teams, cycles, and workflows.",
977
+ stage: "public",
978
+ toolCount: 53,
979
+ transport: "both",
980
+ architectureClass: "domain-simulator",
981
+ domainPrimitives: [
982
+ "GraphQL operation dispatch",
983
+ "issue workflow transitions",
984
+ "comment and history projection",
985
+ "cycle and project progress projection"
986
+ ],
987
+ behaviorOwner: "src/rest/graphql-dispatch.ts",
988
+ opsCoverage: 98
989
+ },
990
+ {
991
+ id: "ownerrez",
992
+ icon: "OR",
993
+ name: "OwnerRez",
994
+ description: "Vacation-rental PMS \u2014 properties, bookings, guests, quotes, financial reads, tags, fields, and webhook subscriptions.",
995
+ stage: "preview",
996
+ toolCount: 25,
997
+ transport: "rest",
998
+ architectureClass: "replay-shell",
999
+ domainPrimitives: [
1000
+ "recording replay cursor",
1001
+ "tag and guest stateful overlays",
1002
+ "booking/payment read projections"
1003
+ ],
1004
+ behaviorOwner: null,
1005
+ opsCoverage: 100
1006
+ },
1007
+ {
1008
+ id: "pricelabs",
1009
+ icon: "PL",
1010
+ name: "PriceLabs",
1011
+ description: "Dynamic pricing \u2014 listings, overrides, neighborhood data, rate plans, and reservations.",
1012
+ stage: "preview",
1013
+ toolCount: 11,
1014
+ transport: "rest",
1015
+ architectureClass: "replay-shell",
1016
+ domainPrimitives: [
1017
+ "recording replay cursor",
1018
+ "listing settings overlay",
1019
+ "pricing and reservation projections"
1020
+ ],
1021
+ behaviorOwner: null,
1022
+ opsCoverage: 100
1023
+ },
1024
+ {
1025
+ id: "ramp",
1026
+ icon: "RP",
1027
+ name: "Ramp",
1028
+ description: "Cards, funds, expenses, reimbursements, bills, and travel.",
1029
+ stage: "preview",
1030
+ toolCount: 46,
1031
+ transport: "mcp",
1032
+ architectureClass: "replay-shell",
1033
+ domainPrimitives: [
1034
+ "checked-in Ramp CLI fixture corpus",
1035
+ "CLI-native command routing",
1036
+ "seeded approval and comment overlays"
1037
+ ],
1038
+ behaviorOwner: null,
1039
+ opsCoverage: null
1040
+ },
1041
+ {
1042
+ id: "sentry",
1043
+ icon: "SN",
1044
+ name: "Sentry",
1045
+ description: "Error monitoring across organizations, projects, teams, issues, events, releases, and DSN keys.",
1046
+ stage: "preview",
1047
+ toolCount: 34,
1048
+ transport: "rest",
1049
+ architectureClass: "domain-simulator",
1050
+ domainPrimitives: [
1051
+ "event grouping",
1052
+ "issue state transitions",
1053
+ "release and time-window projections"
1054
+ ],
1055
+ behaviorOwner: "src/domain/sentry-simulator.ts",
1056
+ opsCoverage: null
1057
+ },
1058
+ {
1059
+ id: "slack",
1060
+ icon: "SL",
1061
+ name: "Slack",
1062
+ description: "Channels, messages, threads, users, and reactions.",
1063
+ stage: "public",
1064
+ toolCount: 9,
1065
+ transport: "both",
1066
+ architectureClass: "domain-simulator",
1067
+ domainPrimitives: [
1068
+ "channel membership and visibility",
1069
+ "message/thread ordering",
1070
+ "event delivery semantics"
1071
+ ],
1072
+ behaviorOwner: "src/domain/slack-simulator.ts",
1073
+ opsCoverage: 100
1074
+ },
1075
+ {
1076
+ id: "stripe",
1077
+ icon: "ST",
1078
+ name: "Stripe",
1079
+ description: "Customers, payments, subscriptions, invoices, and refunds.",
1080
+ stage: "preview",
1081
+ toolCount: 28,
1082
+ transport: "both",
1083
+ architectureClass: "domain-simulator",
1084
+ domainPrimitives: [
1085
+ "payment object lifecycle",
1086
+ "balance and ledger projection",
1087
+ "webhook/idempotency semantics"
1088
+ ],
1089
+ behaviorOwner: "src/domain/stripe-simulator.ts",
1090
+ opsCoverage: null
1091
+ },
1092
+ {
1093
+ id: "supabase",
1094
+ icon: "SB",
1095
+ name: "Supabase",
1096
+ description: "SQL, migrations, logs, branches, and project metadata.",
1097
+ stage: "public",
1098
+ toolCount: 29,
1099
+ transport: "both",
1100
+ architectureClass: "domain-simulator",
1101
+ domainPrimitives: [
1102
+ "Postgres schema and SQL execution",
1103
+ "RLS and API projections",
1104
+ "realtime row changes"
1105
+ ],
1106
+ behaviorOwner: "src/pg-engine.ts",
1107
+ opsCoverage: 100
1108
+ },
1109
+ {
1110
+ id: "tavily",
1111
+ icon: "TV",
1112
+ name: "Tavily",
1113
+ description: "Search, extract, crawl, map, research, usage, and API key operations.",
1114
+ stage: "preview",
1115
+ toolCount: 11,
1116
+ transport: "rest",
1117
+ architectureClass: "replay-shell",
1118
+ domainPrimitives: [
1119
+ "recording-backed REST/tool response replay",
1120
+ "deterministic search/extract response helpers",
1121
+ "research request state overlay"
1122
+ ],
1123
+ behaviorOwner: null,
1124
+ opsCoverage: 100
1125
+ },
1126
+ {
1127
+ id: "unipile",
1128
+ icon: "UP",
1129
+ name: "Unipile",
1130
+ description: "LinkedIn and email messaging, accounts, and chats.",
1131
+ stage: "preview",
1132
+ toolCount: 31,
1133
+ transport: "rest",
1134
+ architectureClass: "replay-shell",
1135
+ domainPrimitives: [
1136
+ "authenticated account and chat reads",
1137
+ "single WhatsApp send mutation",
1138
+ "future account, chat, and webhook simulator"
1139
+ ],
1140
+ behaviorOwner: null,
1141
+ opsCoverage: 100
1142
+ },
1143
+ {
1144
+ id: "webflow",
1145
+ icon: "WF",
1146
+ name: "Webflow",
1147
+ description: "Sites, pages, CMS collections, items, assets, forms, and webhooks.",
1148
+ stage: "preview",
1149
+ toolCount: 104,
1150
+ transport: "both",
1151
+ architectureClass: "standard-core",
1152
+ domainPrimitives: [],
1153
+ behaviorOwner: null,
1154
+ opsCoverage: 100
1155
+ }
1156
+ ];
1157
+ var GENERATED_STARTABLE_CLONE_IDS = [
1158
+ "apify",
1159
+ "calcom",
1160
+ "clickup",
1161
+ "customerio",
1162
+ "datadog",
1163
+ "discord",
1164
+ "github",
1165
+ "gitlab",
1166
+ "google-workspace",
1167
+ "hubspot",
1168
+ "jira",
1169
+ "linear",
1170
+ "ownerrez",
1171
+ "pricelabs",
1172
+ "ramp",
1173
+ "sentry",
1174
+ "slack",
1175
+ "stripe",
1176
+ "supabase",
1177
+ "tavily",
1178
+ "unipile",
1179
+ "webflow"
1180
+ ];
1181
+
1182
+ // ../clones/core/src/clone-architecture-values.mjs
1183
+ var CLONE_ARCHITECTURE_CLASSES = [
1184
+ "standard-core",
1185
+ "domain-simulator",
1186
+ "replay-shell",
1187
+ "redesign-before-expansion"
1188
+ ];
1189
+ var CLONE_ARCHITECTURE_PREVIEW_CLASSES = [
1190
+ "replay-shell",
1191
+ "redesign-before-expansion"
1192
+ ];
1193
+ var CLONE_ARCHITECTURE_CLASS_SET = new Set(CLONE_ARCHITECTURE_CLASSES);
1194
+ var CLONE_ARCHITECTURE_PREVIEW_CLASS_SET = new Set(CLONE_ARCHITECTURE_PREVIEW_CLASSES);
1195
+
1196
+ // ../clones/core/src/clone-architecture-field-policy.mjs
1197
+ var FIELD_POLICY = {
1198
+ behaviorOwner: {
1199
+ required: /* @__PURE__ */ new Set(["domain-simulator"]),
1200
+ allowed: /* @__PURE__ */ new Set(["domain-simulator"])
1201
+ },
1202
+ domainPrimitives: {
1203
+ required: /* @__PURE__ */ new Set(["domain-simulator", "replay-shell", "redesign-before-expansion"]),
1204
+ allowed: /* @__PURE__ */ new Set(["domain-simulator", "replay-shell", "redesign-before-expansion"])
1205
+ },
1206
+ promotionEvidence: {
1207
+ required: /* @__PURE__ */ new Set(["replay-shell"]),
1208
+ allowed: /* @__PURE__ */ new Set(["replay-shell"])
1209
+ },
1210
+ redesignContract: {
1211
+ required: /* @__PURE__ */ new Set(["redesign-before-expansion"]),
1212
+ allowed: /* @__PURE__ */ new Set(["redesign-before-expansion"])
1213
+ }
1214
+ };
1215
+ var CLONE_ARCHITECTURE_POLICY_FIELDS = Object.freeze(Object.keys(FIELD_POLICY));
1216
+ var CLONE_ARCHITECTURE_MANIFEST_FIELDS = Object.freeze([
1217
+ "class",
1218
+ "summary",
1219
+ ...CLONE_ARCHITECTURE_POLICY_FIELDS
1220
+ ]);
1221
+ var CLONE_ARCHITECTURE_MANIFEST_FIELD_SET = new Set(CLONE_ARCHITECTURE_MANIFEST_FIELDS);
1222
+
1223
+ // ../clones/core/src/clone-runtime-source-files.mjs
1224
+ var import_node_path = require("path");
1225
+ var CLONE_RUNTIME_SOURCE_EXTENSIONS = Object.freeze([
1226
+ ".cjs",
1227
+ ".cts",
1228
+ ".js",
1229
+ ".jsx",
1230
+ ".mjs",
1231
+ ".mts",
1232
+ ".ts",
1233
+ ".tsx"
1234
+ ]);
1235
+ var RUNTIME_SOURCE_EXTENSIONS = new Set(CLONE_RUNTIME_SOURCE_EXTENSIONS);
1236
+
1237
+ // ../clones/core/src/clone-launch-metadata-values.mjs
1238
+ var CLONE_STAGES = ["wip", "internal", "preview", "public", "retired"];
1239
+ var CLONE_TRANSPORTS = ["mcp", "rest", "both"];
1240
+ var CLONE_SMOKE_PROFILES = ["none", "health-and-seed", "clone-surface"];
1241
+ var STARTABLE_CLONE_STAGES = ["public", "preview"];
1242
+ var CATALOG_VISIBLE_CLONE_STAGES = ["public", "preview"];
1243
+ var CLONE_STAGE_SET = new Set(CLONE_STAGES);
1244
+ var CLONE_TRANSPORT_SET = new Set(CLONE_TRANSPORTS);
1245
+ var CLONE_SMOKE_PROFILE_SET = new Set(CLONE_SMOKE_PROFILES);
1246
+ var STARTABLE_CLONE_STAGE_SET = new Set(STARTABLE_CLONE_STAGES);
1247
+ var CATALOG_VISIBLE_CLONE_STAGE_SET = new Set(CATALOG_VISIBLE_CLONE_STAGES);
1248
+
1249
+ // ../packages/clone-catalog/src/index.ts
1250
+ var CLONE_CATALOG = GENERATED_CLONE_CATALOG;
1251
+ var ALL_CLONE_IDS = CLONE_CATALOG.map((entry) => entry.id);
1252
+ var ALL_STARTABLE_CLONE_IDS = [...GENERATED_STARTABLE_CLONE_IDS];
1253
+ var CLONE_ID_SET = new Set(ALL_CLONE_IDS);
1254
+ var STARTABLE_CLONE_ID_SET = new Set(ALL_STARTABLE_CLONE_IDS);
1255
+ var STARTABLE_CLONE_CATALOG = CLONE_CATALOG.filter(
1256
+ (entry) => STARTABLE_CLONE_ID_SET.has(entry.id)
1257
+ );
1258
+
1259
+ // ../packages/node-auth/src/credential-store.ts
1260
+ var ExpiredEnvTokenError = class extends Error {
1261
+ constructor(envVar = AUTH_TOKEN_ENV_VAR) {
1262
+ super(`${envVar} is expired. Remove it or replace it with a valid token.`);
1263
+ this.name = "ExpiredEnvTokenError";
1264
+ Object.setPrototypeOf(this, new.target.prototype);
1265
+ }
1266
+ };
1267
+ function errorMessage(error) {
1268
+ return error instanceof Error ? error.message : String(error);
1269
+ }
1270
+ var ENTITLED_CLONE_SET = new Set(ALL_STARTABLE_CLONE_IDS);
1271
+ function normalizeEntitledCloneIds(cloneIds) {
1272
+ if (!cloneIds) {
1273
+ return [];
1274
+ }
1275
+ const normalized = /* @__PURE__ */ new Set();
1276
+ for (const cloneId of cloneIds) {
1277
+ if (typeof cloneId !== "string") {
1278
+ continue;
1279
+ }
1280
+ const trimmed = cloneId.trim();
1281
+ if (ENTITLED_CLONE_SET.has(trimmed)) {
1282
+ normalized.add(trimmed);
1283
+ }
1284
+ }
1285
+ return [...normalized];
1286
+ }
1287
+ var KEYCHAIN_COMMAND_TIMEOUT_MS = 1500;
1288
+ var ARCHAL_DIR_NAME = ".archal";
1289
+ var TEST_SANDBOX_ID_ENV_VAR = "ARCHAL_TEST_SANDBOX_ID";
1290
+ var VITEST_CONFIG_ENV_VAR = "ARCHAL_VITEST_CONFIG";
1291
+ function debug(message) {
1292
+ if (process.env["ARCHAL_DEBUG"] !== "1") {
1293
+ return;
1294
+ }
1295
+ process.stderr.write(`[archal-node-auth] ${message}
1296
+ `);
1297
+ }
1298
+ function getWarn(options) {
1299
+ return options?.warn ?? console.warn;
1300
+ }
1301
+ function isExpired(expiresAt) {
1302
+ return expiresAt <= Math.floor(Date.now() / 1e3);
1303
+ }
1304
+ function isRunningUnderTests() {
1305
+ return process.env["VITEST"] === "true" || process.env["VITEST_WORKER_ID"] !== void 0 || process.env["JEST_WORKER_ID"] !== void 0 || process.env["NODE_TEST_CONTEXT"] !== void 0;
1306
+ }
1307
+ function getRealArchalDir() {
1308
+ return (0, import_node_path2.join)((0, import_node_os.homedir)(), ARCHAL_DIR_NAME);
1309
+ }
1310
+ function normalizeSandboxId(raw) {
1311
+ const trimmed = raw.trim();
1312
+ if (/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(trimmed)) {
1313
+ return trimmed;
1314
+ }
1315
+ return (0, import_node_crypto.createHash)("sha256").update(trimmed).digest("hex").slice(0, 16);
1316
+ }
1317
+ function getTestSandboxDir() {
1318
+ const sharedSandboxId = process.env[VITEST_CONFIG_ENV_VAR]?.trim() || process.env[TEST_SANDBOX_ID_ENV_VAR]?.trim();
1319
+ if (sharedSandboxId) {
1320
+ return (0, import_node_path2.join)((0, import_node_os.tmpdir)(), `archal-test-sandbox-${normalizeSandboxId(sharedSandboxId)}`);
1321
+ }
1322
+ const workerId = process.env["VITEST_WORKER_ID"] ?? process.env["JEST_WORKER_ID"] ?? String(process.pid);
1323
+ return (0, import_node_path2.join)((0, import_node_os.tmpdir)(), `archal-test-sandbox-${workerId}-${process.pid}`);
1324
+ }
1325
+ function getArchalDir() {
1326
+ const explicit = process.env["ARCHAL_HOME"]?.trim();
1327
+ if (explicit) {
1328
+ return explicit;
1329
+ }
1330
+ if (isRunningUnderTests()) {
1331
+ return getTestSandboxDir();
1332
+ }
1333
+ return getRealArchalDir();
1334
+ }
1335
+ function getCredentialsPath() {
1336
+ return (0, import_node_path2.join)(getArchalDir(), CREDENTIALS_FILE);
1337
+ }
1338
+ function ensureDir(dir) {
1339
+ if (!(0, import_node_fs.existsSync)(dir)) {
1340
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true });
1341
+ debug(`Created archal directory at ${dir}`);
1342
+ }
1343
+ return dir;
1344
+ }
1345
+ function getCredentialsKeyPathForDir(dir) {
1346
+ return (0, import_node_path2.join)(dir, CREDENTIALS_KEY_FILE);
1347
+ }
1348
+ function readCredentialsKeyFromEnv() {
1349
+ const raw = process.env[CREDENTIALS_MASTER_KEY_ENV_VAR]?.trim();
1350
+ if (!raw) {
1351
+ return null;
1352
+ }
1353
+ if (/^[a-fA-F0-9]{64}$/.test(raw)) {
1354
+ return Buffer.from(raw, "hex");
1355
+ }
1356
+ try {
1357
+ const decoded = Buffer.from(raw, "base64");
1358
+ if (decoded.length === 32) {
1359
+ return decoded;
1360
+ }
1361
+ } catch (err) {
1362
+ debug(`Base64 master key decode failed: ${errorMessage(err)}`);
1363
+ }
1364
+ return (0, import_node_crypto.createHash)("sha256").update(raw, "utf8").digest();
1365
+ }
1366
+ function readCredentialsKeyFromMacKeychain() {
1367
+ if (process.platform !== "darwin") return null;
1368
+ try {
1369
+ const result = (0, import_node_child_process.spawnSync)(
1370
+ "security",
1371
+ ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", KEYCHAIN_ACCOUNT, "-w"],
1372
+ { encoding: "utf-8", timeout: KEYCHAIN_COMMAND_TIMEOUT_MS }
1373
+ );
1374
+ if (!result || result.error || result.status !== 0 || typeof result.stdout !== "string" || result.stdout.length === 0) {
1375
+ if (result?.error) {
1376
+ debug(`Keychain lookup failed: ${result.error.message}`);
1377
+ }
1378
+ return null;
1379
+ }
1380
+ const raw = result.stdout.trim();
1381
+ if (!/^[a-fA-F0-9]{64}$/.test(raw)) {
1382
+ return null;
1383
+ }
1384
+ return Buffer.from(raw, "hex");
1385
+ } catch (err) {
1386
+ debug(`Keychain lookup threw: ${errorMessage(err)}`);
1387
+ return null;
1388
+ }
1389
+ }
1390
+ function readCredentialsKeyFromFile(dir = getArchalDir()) {
1391
+ const keyPath = getCredentialsKeyPathForDir(dir);
1392
+ if (!(0, import_node_fs.existsSync)(keyPath)) {
1393
+ return null;
1394
+ }
1395
+ try {
1396
+ const raw = (0, import_node_fs.readFileSync)(keyPath, "utf-8").trim();
1397
+ const key = Buffer.from(raw, "hex");
1398
+ if (key.length === 32) {
1399
+ return key;
1400
+ }
1401
+ } catch (err) {
1402
+ debug(`Failed to read credentials key file: ${errorMessage(err)}`);
1403
+ }
1404
+ return null;
1405
+ }
1406
+ function collectCredentialKeysForDecrypt(dir = getArchalDir()) {
1407
+ const keys = [];
1408
+ for (const candidate of [
1409
+ readCredentialsKeyFromEnv(),
1410
+ readCredentialsKeyFromMacKeychain(),
1411
+ readCredentialsKeyFromFile(dir)
1412
+ ]) {
1413
+ if (!candidate) continue;
1414
+ if (!keys.some((entry) => entry.equals(candidate))) {
1415
+ keys.push(candidate);
1416
+ }
1417
+ }
1418
+ return keys;
1419
+ }
1420
+ function writeCredentialsKeyToMacKeychain(key) {
1421
+ if (process.platform !== "darwin") return false;
1422
+ try {
1423
+ const result = (0, import_node_child_process.spawnSync)(
1424
+ "security",
1425
+ [
1426
+ "add-generic-password",
1427
+ "-U",
1428
+ "-s",
1429
+ KEYCHAIN_SERVICE,
1430
+ "-a",
1431
+ KEYCHAIN_ACCOUNT,
1432
+ "-w",
1433
+ key.toString("hex")
1434
+ ],
1435
+ { encoding: "utf-8", timeout: KEYCHAIN_COMMAND_TIMEOUT_MS }
1436
+ );
1437
+ if (result?.error) {
1438
+ debug(`Keychain write failed: ${result.error.message}`);
1439
+ }
1440
+ return !!result && !result.error && result.status === 0;
1441
+ } catch (err) {
1442
+ debug(`Keychain write threw: ${errorMessage(err)}`);
1443
+ return false;
1444
+ }
1445
+ }
1446
+ function getOrCreateCredentialsKey(dir = getArchalDir()) {
1447
+ const envKey = readCredentialsKeyFromEnv();
1448
+ if (envKey) {
1449
+ return envKey;
1450
+ }
1451
+ const keychainKey = readCredentialsKeyFromMacKeychain();
1452
+ if (keychainKey) {
1453
+ return keychainKey;
1454
+ }
1455
+ const fileKey = readCredentialsKeyFromFile(dir);
1456
+ if (fileKey) {
1457
+ if (writeCredentialsKeyToMacKeychain(fileKey)) {
1458
+ try {
1459
+ (0, import_node_fs.unlinkSync)(getCredentialsKeyPathForDir(dir));
1460
+ } catch {
1461
+ }
1462
+ }
1463
+ return fileKey;
1464
+ }
1465
+ const generated = (0, import_node_crypto.randomBytes)(32);
1466
+ if (!writeCredentialsKeyToMacKeychain(generated)) {
1467
+ ensureDir(dir);
1468
+ (0, import_node_fs.writeFileSync)(getCredentialsKeyPathForDir(dir), `${generated.toString("hex")}
1469
+ `, {
1470
+ encoding: "utf-8",
1471
+ mode: 384
1472
+ });
1473
+ }
1474
+ return generated;
1475
+ }
1476
+ function encryptToken(token, dir = getArchalDir()) {
1477
+ const key = getOrCreateCredentialsKey(dir);
1478
+ const iv = (0, import_node_crypto.randomBytes)(12);
1479
+ const cipher = (0, import_node_crypto.createCipheriv)("aes-256-gcm", key, iv);
1480
+ const encrypted = Buffer.concat([cipher.update(token, "utf-8"), cipher.final()]);
1481
+ return `${TOKEN_ENCRYPTION_PREFIX}:${iv.toString("hex")}:${cipher.getAuthTag().toString("hex")}:${encrypted.toString("hex")}`;
1482
+ }
1483
+ function decryptToken(ciphertext, dir = getArchalDir()) {
1484
+ const parts = ciphertext.split(":");
1485
+ if (parts.length !== 4 || parts[0] !== TOKEN_ENCRYPTION_PREFIX) {
1486
+ return null;
1487
+ }
1488
+ const [, ivHex, tagHex, dataHex] = parts;
1489
+ if (!ivHex || !tagHex || !dataHex) {
1490
+ return null;
1491
+ }
1492
+ const iv = Buffer.from(ivHex, "hex");
1493
+ const tag = Buffer.from(tagHex, "hex");
1494
+ const data = Buffer.from(dataHex, "hex");
1495
+ const keys = collectCredentialKeysForDecrypt(dir);
1496
+ for (const key of keys) {
1497
+ try {
1498
+ const decipher = (0, import_node_crypto.createDecipheriv)("aes-256-gcm", key, iv);
1499
+ decipher.setAuthTag(tag);
1500
+ return Buffer.concat([decipher.update(data), decipher.final()]).toString("utf-8");
1501
+ } catch {
1502
+ }
1503
+ }
1504
+ debug("Token decryption failed with all available credential keys.");
1505
+ return null;
1506
+ }
1507
+ function decodeJwtPayload(token) {
1508
+ try {
1509
+ const payloadPart = token.split(".")[1];
1510
+ if (!payloadPart) return null;
1511
+ const normalized = payloadPart.replace(/-/g, "+").replace(/_/g, "/");
1512
+ const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
1513
+ return JSON.parse(Buffer.from(padded, "base64").toString("utf-8"));
1514
+ } catch (err) {
1515
+ debug(`JWT payload decode failed (expected for non-JWT tokens): ${errorMessage(err)}`);
1516
+ return null;
1517
+ }
1518
+ }
1519
+ function hasValidSelectedClones(value) {
1520
+ return value === void 0 || Array.isArray(value) && value.every((twin) => typeof twin === "string");
1521
+ }
1522
+ function resolveStoredToken(parsed, dir = getArchalDir()) {
1523
+ if (typeof parsed.token === "string") {
1524
+ const token = parsed.token.trim();
1525
+ return { token: token.length > 0 ? token : null, source: "legacy" };
1526
+ }
1527
+ if (typeof parsed.accessToken === "string") {
1528
+ const token = parsed.accessToken.trim();
1529
+ return { token: token.length > 0 ? token : null, source: "legacy" };
1530
+ }
1531
+ if (typeof parsed.tokenEncrypted === "string") {
1532
+ const token = decryptToken(parsed.tokenEncrypted, dir)?.trim() || null;
1533
+ return { token: token?.length ? token : null, source: "encrypted" };
1534
+ }
1535
+ return { token: null, source: "legacy" };
1536
+ }
1537
+ function resolveStoredRefreshToken(parsed, dir = getArchalDir()) {
1538
+ if (typeof parsed.refreshTokenEncrypted === "string") {
1539
+ const refreshToken = decryptToken(parsed.refreshTokenEncrypted, dir)?.trim() || null;
1540
+ if (refreshToken !== null) {
1541
+ return { refreshToken, source: "encrypted" };
1542
+ }
1543
+ if (typeof parsed.refreshToken === "string") {
1544
+ return { refreshToken: parsed.refreshToken.trim(), source: "legacy" };
1545
+ }
1546
+ return { refreshToken: null, source: "encrypted" };
1547
+ }
1548
+ if (typeof parsed.refreshToken === "string") {
1549
+ return { refreshToken: parsed.refreshToken.trim(), source: "legacy" };
1550
+ }
1551
+ return { refreshToken: "", source: "none" };
1552
+ }
1553
+ function buildStoredCredentials(parsed, path, warn2, options) {
1554
+ const dir = (0, import_node_path2.dirname)(path);
1555
+ const { token, source: tokenSource } = resolveStoredToken(parsed, dir);
1556
+ const { refreshToken, source: refreshTokenSource } = resolveStoredRefreshToken(parsed, dir);
1557
+ if (token === null || refreshToken === null || parsed.refreshToken !== void 0 && typeof parsed.refreshToken !== "string" || parsed.refreshTokenEncrypted !== void 0 && typeof parsed.refreshTokenEncrypted !== "string" || !hasValidSelectedClones(parsed.selectedCloneIds)) {
1558
+ warn2(
1559
+ `Credentials file at ${path} has missing or invalid fields. Run \`archal login\` to re-authenticate.`
1560
+ );
1561
+ return null;
1562
+ }
1563
+ const { email, plan, expiresAt } = parsed;
1564
+ if (typeof email !== "string" || !isPlan(plan) || typeof expiresAt !== "number") {
1565
+ warn2(
1566
+ `Credentials file at ${path} has missing or invalid fields. Run \`archal login\` to re-authenticate.`
1567
+ );
1568
+ return null;
1569
+ }
1570
+ const creds = {
1571
+ token,
1572
+ refreshToken,
1573
+ email,
1574
+ plan,
1575
+ selectedCloneIds: normalizeEntitledCloneIds(parsed.selectedCloneIds),
1576
+ expiresAt
1577
+ };
1578
+ if (options?.migrateLegacyCredentials && (tokenSource === "legacy" || refreshTokenSource === "legacy")) {
1579
+ try {
1580
+ writeCredentialsAtPath(path, creds);
1581
+ } catch (err) {
1582
+ debug(`Credential migration failed: ${errorMessage(err)}`);
1583
+ }
1584
+ }
1585
+ return creds;
1586
+ }
1587
+ function readCredentialsFileAtPath(path, options) {
1588
+ if (!(0, import_node_fs.existsSync)(path)) {
1589
+ return null;
1590
+ }
1591
+ try {
1592
+ const warn2 = getWarn(options);
1593
+ const parsed = JSON.parse((0, import_node_fs.readFileSync)(path, "utf-8"));
1594
+ return buildStoredCredentials(parsed, path, warn2, options);
1595
+ } catch {
1596
+ const warn2 = getWarn(options);
1597
+ warn2(
1598
+ `Credentials file at ${path} exists but could not be parsed. Delete it and run \`archal login\` to re-authenticate.`
1599
+ );
1600
+ return null;
1601
+ }
1602
+ }
1603
+ function readCredentialsFile(options) {
1604
+ return readCredentialsFileAtPath(getCredentialsPath(), options);
1605
+ }
1606
+ function isWorkspaceApiKey(token) {
1607
+ return token.startsWith(WORKSPACE_API_KEY_PREFIX) || token.startsWith("archal_") && !token.includes(".");
1608
+ }
1609
+ var WORKSPACE_API_KEY_EXPIRES_SECONDS = 365 * 24 * 60 * 60;
1610
+ function parseEnvToken(token, envName = AUTH_TOKEN_ENV_VAR, nowSeconds = Math.floor(Date.now() / 1e3)) {
1611
+ const trimmed = token.trim();
1612
+ if (!trimmed) {
1613
+ return { status: "invalid", message: `${envName} is empty.` };
1614
+ }
1615
+ if (isWorkspaceApiKey(trimmed)) {
1616
+ return {
1617
+ status: "ok",
1618
+ credentials: {
1619
+ token: trimmed,
1620
+ refreshToken: "",
1621
+ email: "(workspace-api-key)",
1622
+ plan: "pro",
1623
+ selectedCloneIds: [],
1624
+ expiresAt: nowSeconds + WORKSPACE_API_KEY_EXPIRES_SECONDS
1625
+ }
1626
+ };
1627
+ }
1628
+ const claims = decodeJwtPayload(trimmed);
1629
+ if (claims === null) {
1630
+ return {
1631
+ status: "invalid",
1632
+ message: `${envName} must be a JWT with valid plan and exp claims or a workspace API key (archal_ws_...).`
1633
+ };
1634
+ }
1635
+ const email = typeof claims["email"] === "string" ? claims["email"] : `(from ${envName})`;
1636
+ if (!isPlan(claims["plan"])) {
1637
+ return {
1638
+ status: "invalid",
1639
+ message: `${envName} JWT does not contain a valid plan claim.`
1640
+ };
1641
+ }
1642
+ const plan = claims["plan"];
1643
+ if (typeof claims["exp"] !== "number" || !Number.isFinite(claims["exp"])) {
1644
+ return {
1645
+ status: "invalid",
1646
+ message: `${envName} JWT does not contain a valid exp claim.`
1647
+ };
1648
+ }
1649
+ const expiresAt = claims["exp"];
1650
+ if (expiresAt <= nowSeconds) {
1651
+ return {
1652
+ status: "expired",
1653
+ message: `${envName} is expired. Remove it or replace it with a valid token.`
1654
+ };
1655
+ }
1656
+ return {
1657
+ status: "ok",
1658
+ credentials: {
1659
+ token: trimmed,
1660
+ refreshToken: "",
1661
+ email,
1662
+ plan,
1663
+ selectedCloneIds: [],
1664
+ expiresAt
1665
+ }
1666
+ };
1667
+ }
1668
+ function readCredentialsFromEnv(options) {
1669
+ const raw = process.env[AUTH_TOKEN_ENV_VAR];
1670
+ if (typeof raw !== "string") {
1671
+ return null;
1672
+ }
1673
+ const token = raw.trim();
1674
+ if (token.length === 0) {
1675
+ return null;
1676
+ }
1677
+ const parsed = parseEnvToken(token);
1678
+ if (parsed.status === "ok") {
1679
+ if (isWorkspaceApiKey(token)) {
1680
+ debug("ARCHAL_TOKEN is a workspace API key -- skipping JWT validation.");
1681
+ }
1682
+ return parsed.credentials;
1683
+ }
1684
+ if (parsed.message.startsWith("ARCHAL_TOKEN must be a JWT")) {
1685
+ getWarn(options)(
1686
+ "ARCHAL_TOKEN must be a JWT or a workspace API key (archal_ws_...). Ignoring environment token.\nFor CI, set ARCHAL_TOKEN to a workspace API key created via `archal workspace api-key create`."
1687
+ );
1688
+ return null;
1689
+ }
1690
+ if (parsed.status === "expired") {
1691
+ if (options?.onExpiredEnvToken === "throw") {
1692
+ throw new ExpiredEnvTokenError();
1693
+ }
1694
+ debug("Ignoring expired ARCHAL_TOKEN from environment.");
1695
+ return null;
1696
+ }
1697
+ getWarn(options)(`${parsed.message} Ignoring environment token.`);
1698
+ return null;
1699
+ }
1700
+ function getCredentials(options) {
1701
+ const envValue = process.env[AUTH_TOKEN_ENV_VAR];
1702
+ const hasExplicitEnvToken = String(envValue ?? "").trim().length > 0;
1703
+ const envCredentials = readCredentialsFromEnv(options);
1704
+ const creds = envCredentials ?? (hasExplicitEnvToken ? null : getStoredCredentials(options));
1705
+ if (!creds) {
1706
+ return null;
1707
+ }
1708
+ return isExpired(creds.expiresAt) ? null : creds;
1709
+ }
1710
+ function getStoredCredentials(options) {
1711
+ const creds = readCredentialsFile(options);
1712
+ if (!creds) {
1713
+ return null;
1714
+ }
1715
+ if (options?.includeExpired) {
1716
+ return creds;
1717
+ }
1718
+ return isExpired(creds.expiresAt) ? null : creds;
1719
+ }
1720
+ function writeCredentialsAtPath(path, creds) {
1721
+ const dir = (0, import_node_path2.dirname)(path);
1722
+ ensureDir(dir);
1723
+ const payload = {
1724
+ email: creds.email,
1725
+ plan: creds.plan,
1726
+ selectedCloneIds: normalizeEntitledCloneIds(creds.selectedCloneIds),
1727
+ expiresAt: creds.expiresAt,
1728
+ tokenEncrypted: encryptToken(creds.token.trim(), dir),
1729
+ refreshTokenEncrypted: creds.refreshToken.trim().length > 0 ? encryptToken(creds.refreshToken.trim(), dir) : void 0
1730
+ };
1731
+ const tmpPath = `${path}.${(0, import_node_crypto.randomBytes)(4).toString("hex")}.tmp`;
1732
+ (0, import_node_fs.writeFileSync)(tmpPath, `${JSON.stringify(payload, null, 2)}
1733
+ `, {
1734
+ encoding: "utf-8",
1735
+ mode: 384
1736
+ });
1737
+ (0, import_node_fs.renameSync)(tmpPath, path);
1738
+ }
1739
+
1740
+ // ../packages/node-auth/src/loopback.ts
1741
+ var import_node_net = require("net");
1742
+
1743
+ // ../packages/node-auth/src/secure-token.ts
1744
+ var import_node_crypto2 = require("crypto");
1745
+
1746
+ // ../packages/evaluator/src/log/ansi.ts
1747
+ var NO_COLOR = "NO_COLOR" in process.env || process.env["TERM"] === "dumb";
1748
+ var RESET = NO_COLOR ? "" : "\x1B[0m";
1749
+ var BOLD = NO_COLOR ? "" : "\x1B[1m";
1750
+ var DIM = NO_COLOR ? "" : "\x1B[2m";
1751
+ var RED = NO_COLOR ? "" : "\x1B[31m";
1752
+ var YELLOW = NO_COLOR ? "" : "\x1B[33m";
1753
+ var CYAN = NO_COLOR ? "" : "\x1B[36m";
1754
+ var GRAY = NO_COLOR ? "" : "\x1B[90m";
1755
+
1756
+ // ../packages/evaluator/src/log/logger.ts
1757
+ var LOG_LEVEL_PRIORITY = {
1758
+ debug: 0,
1759
+ info: 1,
1760
+ warn: 2,
1761
+ error: 3
1762
+ };
1763
+ var LOG_LEVEL_COLORS = {
1764
+ debug: GRAY,
1765
+ info: CYAN,
1766
+ warn: YELLOW,
1767
+ error: RED
1768
+ };
1769
+ var globalOptions = {
1770
+ level: "info",
1771
+ quiet: false,
1772
+ json: false,
1773
+ verbose: false
1774
+ };
1775
+ var ANSI_ESCAPE_RE = new RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*m`, "g");
1776
+ function shouldLog(level) {
1777
+ if (globalOptions.quiet && level !== "error") {
1778
+ return false;
1779
+ }
1780
+ return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[globalOptions.level];
1781
+ }
1782
+ function formatTimestamp() {
1783
+ return (/* @__PURE__ */ new Date()).toISOString();
1784
+ }
1785
+ function formatLogEntry(entry) {
1786
+ if (globalOptions.json) {
1787
+ return JSON.stringify(entry);
1788
+ }
1789
+ const color = LOG_LEVEL_COLORS[entry.level];
1790
+ if (globalOptions.verbose || entry.level === "warn" || entry.level === "error") {
1791
+ const levelTag = `${color}${BOLD}${entry.level.toUpperCase().padEnd(5)}${RESET}`;
1792
+ const timestamp = `${DIM}${entry.timestamp}${RESET}`;
1793
+ let line = `${timestamp} ${levelTag} ${entry.message}`;
1794
+ if (entry.data && Object.keys(entry.data).length > 0) {
1795
+ const dataStr = Object.entries(entry.data).map(([k, v]) => `${DIM}${k}=${RESET}${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
1796
+ line += ` ${dataStr}`;
1797
+ }
1798
+ return line;
1799
+ }
1800
+ return `${DIM}${entry.message}${RESET}`;
1801
+ }
1802
+ function log(level, message, data) {
1803
+ if (!shouldLog(level)) {
1804
+ return;
1805
+ }
1806
+ const entry = {
1807
+ level,
1808
+ message,
1809
+ timestamp: formatTimestamp(),
1810
+ data
1811
+ };
1812
+ const formatted = formatLogEntry(entry);
1813
+ process.stderr.write(formatted + "\n");
1814
+ }
1815
+ function warn(message, data) {
1816
+ log("warn", message, data);
1817
+ }
1818
+
1819
+ // src/auth/cli-read-options.ts
1820
+ var CLI_CREDENTIAL_READ_OPTIONS = {
1821
+ onExpiredEnvToken: "throw",
1822
+ warn
1823
+ };
1824
+
1825
+ // src/utils/version.ts
1826
+ var import_node_fs2 = require("fs");
1827
+ var import_node_path3 = require("path");
1828
+ var CLI_PACKAGE_NAMES = /* @__PURE__ */ new Set(["@archal/cli", "archal"]);
1829
+ function resolvePackageJsonCandidates() {
1830
+ const candidates = /* @__PURE__ */ new Set();
1831
+ if (typeof __dirname === "string") {
1832
+ candidates.add((0, import_node_path3.join)(__dirname, "..", "package.json"));
1833
+ candidates.add((0, import_node_path3.join)(__dirname, "..", "..", "package.json"));
1834
+ }
1835
+ return [...candidates];
1836
+ }
1837
+ function readPackageJson(path) {
1838
+ try {
1839
+ return JSON.parse((0, import_node_fs2.readFileSync)(path, "utf-8"));
1840
+ } catch {
1841
+ return null;
1842
+ }
1843
+ }
1844
+ function loadVersion() {
1845
+ let fallbackVersion = null;
1846
+ for (const pkgPath of resolvePackageJsonCandidates()) {
1847
+ const pkg = readPackageJson(pkgPath);
1848
+ if (!pkg) {
1849
+ continue;
1850
+ }
1851
+ if (typeof pkg.name === "string" && CLI_PACKAGE_NAMES.has(pkg.name) && typeof pkg.version === "string") {
1852
+ return pkg.version;
1853
+ }
1854
+ if (fallbackVersion === null && typeof pkg.version === "string") {
1855
+ fallbackVersion = pkg.version;
1856
+ }
1857
+ }
1858
+ return fallbackVersion ?? "0.0.0";
1859
+ }
1860
+ var CLI_VERSION = loadVersion();
1861
+ var CLI_USER_AGENT = `archal-cli/${CLI_VERSION}`;
1862
+
1863
+ // src/auth/credential-store.ts
1864
+ var cachedEnvToken = null;
1865
+ var cachedEnvCredentials = null;
1866
+ var cachedEnvCredentialsResolved = false;
1867
+ function readExplicitEnvToken() {
1868
+ const raw = process.env["ARCHAL_TOKEN"];
1869
+ if (typeof raw !== "string") return null;
1870
+ const token = raw.trim();
1871
+ return token.length > 0 ? token : null;
1872
+ }
1873
+ function getCredentials2() {
1874
+ const envToken = readExplicitEnvToken();
1875
+ if (!envToken) {
1876
+ return getCredentials(CLI_CREDENTIAL_READ_OPTIONS);
1877
+ }
1878
+ if (!cachedEnvCredentialsResolved || cachedEnvToken !== envToken) {
1879
+ cachedEnvToken = envToken;
1880
+ cachedEnvCredentials = getCredentials(CLI_CREDENTIAL_READ_OPTIONS);
1881
+ cachedEnvCredentialsResolved = true;
1882
+ }
1883
+ return cachedEnvCredentials;
1884
+ }
1885
+
1886
+ // src/auth/require-auth.ts
1887
+ var import_node_child_process2 = require("child_process");
1888
+
1889
+ // src/telemetry/posthog.ts
1890
+ var import_node_fs4 = require("fs");
1891
+ var import_node_path4 = require("path");
1892
+ var import_node_crypto3 = require("crypto");
1893
+
1894
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/utils/type-utils.mjs
1895
+ var nativeIsArray = Array.isArray;
1896
+ var ObjProto = Object.prototype;
1897
+ var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
1898
+ var type_utils_toString = ObjProto.toString;
1899
+ var isArray = nativeIsArray || function(obj) {
1900
+ return "[object Array]" === type_utils_toString.call(obj);
1901
+ };
1902
+ var isObject = (x) => x === Object(x) && !isArray(x);
1903
+ var isUndefined = (x) => void 0 === x;
1904
+ var isString = (x) => "[object String]" == type_utils_toString.call(x);
1905
+ var isEmptyString = (x) => isString(x) && 0 === x.trim().length;
1906
+ var isNumber = (x) => "[object Number]" == type_utils_toString.call(x) && x === x;
1907
+ var isPlainError = (x) => x instanceof Error;
1908
+ function isPrimitive(value) {
1909
+ return null === value || "object" != typeof value;
1910
+ }
1911
+ function isBuiltin(candidate, className) {
1912
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
1913
+ }
1914
+ function isErrorEvent(event) {
1915
+ return isBuiltin(event, "ErrorEvent");
1916
+ }
1917
+ function isEvent(candidate) {
1918
+ return "undefined" != typeof Event && isInstanceOf(candidate, Event);
1919
+ }
1920
+ function isInstanceOf(candidate, base) {
1921
+ try {
1922
+ return candidate instanceof base;
1923
+ } catch {
1924
+ return false;
1925
+ }
1926
+ }
1927
+
1928
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
1929
+ var MOBILE = "Mobile";
1930
+ var IOS = "iOS";
1931
+ var ANDROID = "Android";
1932
+ var TABLET = "Tablet";
1933
+ var ANDROID_TABLET = ANDROID + " " + TABLET;
1934
+ var APPLE = "Apple";
1935
+ var APPLE_WATCH = APPLE + " Watch";
1936
+ var SAFARI = "Safari";
1937
+ var BLACKBERRY = "BlackBerry";
1938
+ var SAMSUNG = "Samsung";
1939
+ var SAMSUNG_BROWSER = SAMSUNG + "Browser";
1940
+ var SAMSUNG_INTERNET = SAMSUNG + " Internet";
1941
+ var CHROME = "Chrome";
1942
+ var CHROME_OS = CHROME + " OS";
1943
+ var CHROME_IOS = CHROME + " " + IOS;
1944
+ var INTERNET_EXPLORER = "Internet Explorer";
1945
+ var INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + " " + MOBILE;
1946
+ var OPERA = "Opera";
1947
+ var OPERA_MINI = OPERA + " Mini";
1948
+ var EDGE = "Edge";
1949
+ var MICROSOFT_EDGE = "Microsoft " + EDGE;
1950
+ var FIREFOX = "Firefox";
1951
+ var FIREFOX_IOS = FIREFOX + " " + IOS;
1952
+ var NINTENDO = "Nintendo";
1953
+ var PLAYSTATION = "PlayStation";
1954
+ var XBOX = "Xbox";
1955
+ var ANDROID_MOBILE = ANDROID + " " + MOBILE;
1956
+ var MOBILE_SAFARI = MOBILE + " " + SAFARI;
1957
+ var WINDOWS = "Windows";
1958
+ var WINDOWS_PHONE = WINDOWS + " Phone";
1959
+ var GENERIC = "Generic";
1960
+ var GENERIC_MOBILE = GENERIC + " " + MOBILE.toLowerCase();
1961
+ var GENERIC_TABLET = GENERIC + " " + TABLET.toLowerCase();
1962
+ var KONQUEROR = "Konqueror";
1963
+ var OCULUS_BROWSER = "Oculus Browser";
1964
+ var VIVALDI = "Vivaldi";
1965
+ var YANDEX = "Yandex";
1966
+ var WHALE = "Whale";
1967
+ var DUCKDUCKGO = "DuckDuckGo";
1968
+ var PALE_MOON = "Pale Moon";
1969
+ var WATERFOX = "Waterfox";
1970
+ var BRAVE = "Brave";
1971
+ var GOOGLE_SEARCH_APP = "Google Search App";
1972
+ var BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)";
1973
+ var DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
1974
+ var XBOX_REGEX = new RegExp(XBOX, "i");
1975
+ var PLAYSTATION_REGEX = new RegExp(PLAYSTATION + " \\w+", "i");
1976
+ var NINTENDO_REGEX = new RegExp(NINTENDO + " \\w+", "i");
1977
+ var BLACKBERRY_REGEX = new RegExp(BLACKBERRY + "|PlayBook|BB10", "i");
1978
+ var windowsVersionMap = {
1979
+ "NT3.51": "NT 3.11",
1980
+ "NT4.0": "NT 4.0",
1981
+ "5.0": "2000",
1982
+ "5.1": "XP",
1983
+ "5.2": "XP",
1984
+ "6.0": "Vista",
1985
+ "6.1": "7",
1986
+ "6.2": "8",
1987
+ "6.3": "8.1",
1988
+ "6.4": "10",
1989
+ "10.0": "10"
1990
+ };
1991
+ var versionRegexes = {
1992
+ [INTERNET_EXPLORER_MOBILE]: [
1993
+ new RegExp("rv:" + BROWSER_VERSION_REGEX_SUFFIX)
1994
+ ],
1995
+ [MICROSOFT_EDGE]: [
1996
+ new RegExp(EDGE + "?\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1997
+ ],
1998
+ [CHROME]: [
1999
+ new RegExp("(" + CHROME + "|CrMo)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2000
+ ],
2001
+ [CHROME_IOS]: [
2002
+ new RegExp("CriOS\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2003
+ ],
2004
+ "UC Browser": [
2005
+ new RegExp("(UCBrowser|UCWEB)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2006
+ ],
2007
+ [SAFARI]: [
2008
+ DEFAULT_BROWSER_VERSION_REGEX
2009
+ ],
2010
+ [MOBILE_SAFARI]: [
2011
+ DEFAULT_BROWSER_VERSION_REGEX
2012
+ ],
2013
+ [OPERA]: [
2014
+ new RegExp("(" + OPERA + "|OPR)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2015
+ ],
2016
+ [FIREFOX]: [
2017
+ new RegExp(FIREFOX + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2018
+ ],
2019
+ [FIREFOX_IOS]: [
2020
+ new RegExp("FxiOS\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2021
+ ],
2022
+ [KONQUEROR]: [
2023
+ new RegExp("Konqueror[:/]?" + BROWSER_VERSION_REGEX_SUFFIX, "i")
2024
+ ],
2025
+ [BLACKBERRY]: [
2026
+ new RegExp(BLACKBERRY + " " + BROWSER_VERSION_REGEX_SUFFIX),
2027
+ DEFAULT_BROWSER_VERSION_REGEX
2028
+ ],
2029
+ [ANDROID_MOBILE]: [
2030
+ new RegExp("android\\s" + BROWSER_VERSION_REGEX_SUFFIX, "i")
2031
+ ],
2032
+ [SAMSUNG_INTERNET]: [
2033
+ new RegExp(SAMSUNG_BROWSER + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2034
+ ],
2035
+ [OCULUS_BROWSER]: [
2036
+ new RegExp("OculusBrowser\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2037
+ ],
2038
+ [VIVALDI]: [
2039
+ new RegExp(VIVALDI + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2040
+ ],
2041
+ [YANDEX]: [
2042
+ new RegExp("YaBrowser\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2043
+ ],
2044
+ [WHALE]: [
2045
+ new RegExp(WHALE + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2046
+ ],
2047
+ [BRAVE]: [
2048
+ new RegExp(BRAVE + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2049
+ ],
2050
+ [DUCKDUCKGO]: [
2051
+ new RegExp("(DuckDuckGo|Ddg)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2052
+ ],
2053
+ [PALE_MOON]: [
2054
+ new RegExp("PaleMoon\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2055
+ ],
2056
+ [WATERFOX]: [
2057
+ new RegExp(WATERFOX + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2058
+ ],
2059
+ [GOOGLE_SEARCH_APP]: [
2060
+ new RegExp("GSA\\/" + BROWSER_VERSION_REGEX_SUFFIX)
2061
+ ],
2062
+ [INTERNET_EXPLORER]: [
2063
+ new RegExp("(rv:|MSIE )" + BROWSER_VERSION_REGEX_SUFFIX)
2064
+ ],
2065
+ Mozilla: [
2066
+ new RegExp("rv:" + BROWSER_VERSION_REGEX_SUFFIX)
2067
+ ]
2068
+ };
2069
+ var osMatchers = [
2070
+ [
2071
+ new RegExp(XBOX + "; " + XBOX + " (.*?)[);]", "i"),
2072
+ (match) => [
2073
+ XBOX,
2074
+ match && match[1] || ""
2075
+ ]
2076
+ ],
2077
+ [
2078
+ new RegExp(NINTENDO, "i"),
2079
+ [
2080
+ NINTENDO,
2081
+ ""
2082
+ ]
2083
+ ],
2084
+ [
2085
+ new RegExp(PLAYSTATION, "i"),
2086
+ [
2087
+ PLAYSTATION,
2088
+ ""
2089
+ ]
2090
+ ],
2091
+ [
2092
+ BLACKBERRY_REGEX,
2093
+ [
2094
+ BLACKBERRY,
2095
+ ""
2096
+ ]
2097
+ ],
2098
+ [
2099
+ new RegExp(WINDOWS, "i"),
2100
+ (_, user_agent) => {
2101
+ if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) return [
2102
+ WINDOWS_PHONE,
2103
+ ""
2104
+ ];
2105
+ if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\b/.test(user_agent)) return [
2106
+ WINDOWS + " " + MOBILE,
2107
+ ""
2108
+ ];
2109
+ const match = /Windows NT ([0-9.]+)/i.exec(user_agent);
2110
+ if (match && match[1]) {
2111
+ const version2 = match[1];
2112
+ let osVersion = windowsVersionMap[version2] || "";
2113
+ if (/arm/i.test(user_agent)) osVersion = "RT";
2114
+ return [
2115
+ WINDOWS,
2116
+ osVersion
2117
+ ];
2118
+ }
2119
+ return [
2120
+ WINDOWS,
2121
+ ""
2122
+ ];
2123
+ }
2124
+ ],
2125
+ [
2126
+ /((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,
2127
+ (match) => {
2128
+ if (match && match[3]) {
2129
+ const versionParts = [
2130
+ match[3],
2131
+ match[4],
2132
+ match[5] || "0"
2133
+ ];
2134
+ return [
2135
+ IOS,
2136
+ versionParts.join(".")
2137
+ ];
2138
+ }
2139
+ return [
2140
+ IOS,
2141
+ ""
2142
+ ];
2143
+ }
2144
+ ],
2145
+ [
2146
+ /(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,
2147
+ (match) => {
2148
+ let version2 = "";
2149
+ if (match && match.length >= 3) version2 = isUndefined(match[2]) ? match[3] : match[2];
2150
+ return [
2151
+ "watchOS",
2152
+ version2
2153
+ ];
2154
+ }
2155
+ ],
2156
+ [
2157
+ new RegExp("(" + ANDROID + " (\\d+)\\.(\\d+)\\.?(\\d+)?|" + ANDROID + ")", "i"),
2158
+ (match) => {
2159
+ if (match && match[2]) {
2160
+ const versionParts = [
2161
+ match[2],
2162
+ match[3],
2163
+ match[4] || "0"
2164
+ ];
2165
+ return [
2166
+ ANDROID,
2167
+ versionParts.join(".")
2168
+ ];
2169
+ }
2170
+ return [
2171
+ ANDROID,
2172
+ ""
2173
+ ];
2174
+ }
2175
+ ],
2176
+ [
2177
+ /Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,
2178
+ (match) => {
2179
+ const result = [
2180
+ "Mac OS X",
2181
+ ""
2182
+ ];
2183
+ if (match && match[1]) {
2184
+ const versionParts = [
2185
+ match[1],
2186
+ match[2],
2187
+ match[3] || "0"
2188
+ ];
2189
+ result[1] = versionParts.join(".");
2190
+ }
2191
+ return result;
2192
+ }
2193
+ ],
2194
+ [
2195
+ /Mac/i,
2196
+ [
2197
+ "Mac OS X",
2198
+ ""
2199
+ ]
2200
+ ],
2201
+ [
2202
+ /CrOS/,
2203
+ [
2204
+ CHROME_OS,
2205
+ ""
2206
+ ]
2207
+ ],
2208
+ [
2209
+ /Linux|debian/i,
2210
+ [
2211
+ "Linux",
2212
+ ""
2213
+ ]
2214
+ ]
2215
+ ];
2216
+
2217
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/utils/index.mjs
2218
+ var isError = (x) => x instanceof Error;
2219
+
2220
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/logs/logs-utils.mjs
2221
+ var OTLP_SEVERITY_MAP = {
2222
+ trace: {
2223
+ text: "TRACE",
2224
+ number: 1
2225
+ },
2226
+ debug: {
2227
+ text: "DEBUG",
2228
+ number: 5
2229
+ },
2230
+ info: {
2231
+ text: "INFO",
2232
+ number: 9
2233
+ },
2234
+ warn: {
2235
+ text: "WARN",
2236
+ number: 13
2237
+ },
2238
+ error: {
2239
+ text: "ERROR",
2240
+ number: 17
2241
+ },
2242
+ fatal: {
2243
+ text: "FATAL",
2244
+ number: 21
2245
+ }
2246
+ };
2247
+ var DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
2248
+
2249
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/index.mjs
2250
+ var error_tracking_exports = {};
2251
+ __export(error_tracking_exports, {
2252
+ DEFAULT_EXCEPTION_STEPS_CONFIG: () => DEFAULT_EXCEPTION_STEPS_CONFIG,
2253
+ DOMExceptionCoercer: () => DOMExceptionCoercer,
2254
+ EXCEPTION_STEP_INTERNAL_FIELDS: () => EXCEPTION_STEP_INTERNAL_FIELDS,
2255
+ ErrorCoercer: () => ErrorCoercer,
2256
+ ErrorEventCoercer: () => ErrorEventCoercer,
2257
+ ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
2258
+ EventCoercer: () => EventCoercer,
2259
+ ExceptionStepsBuffer: () => ExceptionStepsBuffer,
2260
+ ObjectCoercer: () => ObjectCoercer,
2261
+ PrimitiveCoercer: () => PrimitiveCoercer,
2262
+ PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
2263
+ ReduceableCache: () => ReduceableCache,
2264
+ StringCoercer: () => StringCoercer,
2265
+ chromeStackLineParser: () => chromeStackLineParser,
2266
+ createDefaultStackParser: () => createDefaultStackParser,
2267
+ createStackParser: () => createStackParser,
2268
+ geckoStackLineParser: () => geckoStackLineParser,
2269
+ getUtf8ByteLength: () => getUtf8ByteLength,
2270
+ nodeStackLineParser: () => nodeStackLineParser,
2271
+ opera10StackLineParser: () => opera10StackLineParser,
2272
+ opera11StackLineParser: () => opera11StackLineParser,
2273
+ resolveExceptionStepsConfig: () => resolveExceptionStepsConfig,
2274
+ reverseAndStripFrames: () => reverseAndStripFrames,
2275
+ stripReservedExceptionStepFields: () => stripReservedExceptionStepFields,
2276
+ winjsStackLineParser: () => winjsStackLineParser
2277
+ });
2278
+
2279
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
2280
+ var parsedStackResults;
2281
+ var lastKeysCount;
2282
+ var cachedFilenameChunkIds;
2283
+ function getFilenameToChunkIdMap(stackParser) {
2284
+ const chunkIdMap = globalThis._posthogChunkIds;
2285
+ if (!chunkIdMap) return;
2286
+ const chunkIdKeys = Object.keys(chunkIdMap);
2287
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;
2288
+ lastKeysCount = chunkIdKeys.length;
2289
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
2290
+ if (!parsedStackResults) parsedStackResults = {};
2291
+ const result = parsedStackResults[stackKey];
2292
+ if (result) acc[result[0]] = result[1];
2293
+ else {
2294
+ const parsedStack = stackParser(stackKey);
2295
+ for (let i = parsedStack.length - 1; i >= 0; i--) {
2296
+ const stackFrame = parsedStack[i];
2297
+ const filename = stackFrame?.filename;
2298
+ const chunkId = chunkIdMap[stackKey];
2299
+ if (filename && chunkId) {
2300
+ acc[filename] = chunkId;
2301
+ parsedStackResults[stackKey] = [
2302
+ filename,
2303
+ chunkId
2304
+ ];
2305
+ break;
2306
+ }
2307
+ }
2308
+ }
2309
+ return acc;
2310
+ }, {});
2311
+ return cachedFilenameChunkIds;
2312
+ }
2313
+
2314
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
2315
+ var MAX_CAUSE_RECURSION = 4;
2316
+ var ErrorPropertiesBuilder = class {
2317
+ constructor(coercers, stackParser, modifiers = []) {
2318
+ this.coercers = coercers;
2319
+ this.stackParser = stackParser;
2320
+ this.modifiers = modifiers;
2321
+ }
2322
+ buildFromUnknown(input, hint = {}) {
2323
+ const providedMechanism = hint && hint.mechanism;
2324
+ const mechanism = providedMechanism || {
2325
+ handled: true,
2326
+ type: "generic"
2327
+ };
2328
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
2329
+ const exceptionWithCause = coercingContext.apply(input);
2330
+ const parsingContext = this.buildParsingContext(hint);
2331
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
2332
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
2333
+ return {
2334
+ $exception_list: exceptionList,
2335
+ $exception_level: "error"
2336
+ };
2337
+ }
2338
+ async modifyFrames(exceptionList) {
2339
+ for (const exc of exceptionList) if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
2340
+ return exceptionList;
2341
+ }
2342
+ coerceFallback(ctx) {
2343
+ return {
2344
+ type: "Error",
2345
+ value: "Unknown error",
2346
+ stack: ctx.syntheticException?.stack,
2347
+ synthetic: true
2348
+ };
2349
+ }
2350
+ parseStacktrace(err, ctx) {
2351
+ let cause;
2352
+ if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);
2353
+ let stack;
2354
+ if ("" != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
2355
+ return {
2356
+ ...err,
2357
+ cause,
2358
+ stack
2359
+ };
2360
+ }
2361
+ applyChunkIds(frames, chunkIdMap) {
2362
+ return frames.map((frame) => {
2363
+ if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];
2364
+ return frame;
2365
+ });
2366
+ }
2367
+ applyCoercers(input, ctx) {
2368
+ for (const adapter of this.coercers) if (adapter.match(input)) return adapter.coerce(input, ctx);
2369
+ return this.coerceFallback(ctx);
2370
+ }
2371
+ async applyModifiers(frames) {
2372
+ let newFrames = frames;
2373
+ for (const modifier of this.modifiers) newFrames = await modifier(newFrames);
2374
+ return newFrames;
2375
+ }
2376
+ convertToExceptionList(exceptionWithStack, mechanism) {
2377
+ const currentException = {
2378
+ type: exceptionWithStack.type,
2379
+ value: exceptionWithStack.value,
2380
+ mechanism: {
2381
+ type: mechanism.type ?? "generic",
2382
+ handled: mechanism.handled ?? true,
2383
+ synthetic: exceptionWithStack.synthetic ?? false
2384
+ }
2385
+ };
2386
+ if (exceptionWithStack.stack) currentException.stacktrace = {
2387
+ type: "raw",
2388
+ frames: exceptionWithStack.stack
2389
+ };
2390
+ const exceptionList = [
2391
+ currentException
2392
+ ];
2393
+ if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
2394
+ ...mechanism,
2395
+ handled: true
2396
+ }));
2397
+ return exceptionList;
2398
+ }
2399
+ buildParsingContext(hint) {
2400
+ const context = {
2401
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
2402
+ skipFirstLines: hint.skipFirstLines ?? 1
2403
+ };
2404
+ return context;
2405
+ }
2406
+ buildCoercingContext(mechanism, hint, depth = 0) {
2407
+ const coerce = (input, depth2) => {
2408
+ if (!(depth2 <= MAX_CAUSE_RECURSION)) return;
2409
+ {
2410
+ const ctx = this.buildCoercingContext(mechanism, hint, depth2);
2411
+ return this.applyCoercers(input, ctx);
2412
+ }
2413
+ };
2414
+ const context = {
2415
+ ...hint,
2416
+ syntheticException: 0 == depth ? hint.syntheticException : void 0,
2417
+ mechanism,
2418
+ apply: (input) => coerce(input, depth),
2419
+ next: (input) => coerce(input, depth + 1)
2420
+ };
2421
+ return context;
2422
+ }
2423
+ };
2424
+
2425
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
2426
+ var UNKNOWN_FUNCTION = "?";
2427
+ function createFrame(platform, filename, func, lineno, colno) {
2428
+ const frame = {
2429
+ platform,
2430
+ filename,
2431
+ function: "<anonymous>" === func ? UNKNOWN_FUNCTION : func,
2432
+ in_app: true
2433
+ };
2434
+ if (!isUndefined(lineno)) frame.lineno = lineno;
2435
+ if (!isUndefined(colno)) frame.colno = colno;
2436
+ return frame;
2437
+ }
2438
+
2439
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
2440
+ var extractSafariExtensionDetails = (func, filename) => {
2441
+ const isSafariExtension = -1 !== func.indexOf("safari-extension");
2442
+ const isSafariWebExtension = -1 !== func.indexOf("safari-web-extension");
2443
+ return isSafariExtension || isSafariWebExtension ? [
2444
+ -1 !== func.indexOf("@") ? func.split("@")[0] : UNKNOWN_FUNCTION,
2445
+ isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
2446
+ ] : [
2447
+ func,
2448
+ filename
2449
+ ];
2450
+ };
2451
+
2452
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
2453
+ var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
2454
+ var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
2455
+ var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
2456
+ var chromeStackLineParser = (line, platform) => {
2457
+ const noFnParts = chromeRegexNoFnName.exec(line);
2458
+ if (noFnParts) {
2459
+ const [, filename, line2, col] = noFnParts;
2460
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line2, +col);
2461
+ }
2462
+ const parts = chromeRegex.exec(line);
2463
+ if (parts) {
2464
+ const isEval = parts[2] && 0 === parts[2].indexOf("eval");
2465
+ if (isEval) {
2466
+ const subMatch = chromeEvalRegex.exec(parts[2]);
2467
+ if (subMatch) {
2468
+ parts[2] = subMatch[1];
2469
+ parts[3] = subMatch[2];
2470
+ parts[4] = subMatch[3];
2471
+ }
2472
+ }
2473
+ const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
2474
+ return createFrame(platform, filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);
2475
+ }
2476
+ };
2477
+
2478
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
2479
+ var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
2480
+ var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
2481
+ var geckoStackLineParser = (line, platform) => {
2482
+ const parts = geckoREgex.exec(line);
2483
+ if (parts) {
2484
+ const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
2485
+ if (isEval) {
2486
+ const subMatch = geckoEvalRegex.exec(parts[3]);
2487
+ if (subMatch) {
2488
+ parts[1] = parts[1] || "eval";
2489
+ parts[3] = subMatch[1];
2490
+ parts[4] = subMatch[2];
2491
+ parts[5] = "";
2492
+ }
2493
+ }
2494
+ let filename = parts[3];
2495
+ let func = parts[1] || UNKNOWN_FUNCTION;
2496
+ [func, filename] = extractSafariExtensionDetails(func, filename);
2497
+ return createFrame(platform, filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);
2498
+ }
2499
+ };
2500
+
2501
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
2502
+ var winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
2503
+ var winjsStackLineParser = (line, platform) => {
2504
+ const parts = winjsRegex.exec(line);
2505
+ return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : void 0) : void 0;
2506
+ };
2507
+
2508
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
2509
+ var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
2510
+ var opera10StackLineParser = (line, platform) => {
2511
+ const parts = opera10Regex.exec(line);
2512
+ return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : void 0;
2513
+ };
2514
+ var opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
2515
+ var opera11StackLineParser = (line, platform) => {
2516
+ const parts = opera11Regex.exec(line);
2517
+ return parts ? createFrame(platform, parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : void 0;
2518
+ };
2519
+
2520
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
2521
+ var FILENAME_MATCH = /^\s*[-]{4,}$/;
2522
+ var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
2523
+ var nodeStackLineParser = (line, platform) => {
2524
+ const lineMatch = line.match(FULL_MATCH);
2525
+ if (lineMatch) {
2526
+ let object;
2527
+ let method;
2528
+ let functionName;
2529
+ let typeName;
2530
+ let methodName;
2531
+ if (lineMatch[1]) {
2532
+ functionName = lineMatch[1];
2533
+ let methodStart = functionName.lastIndexOf(".");
2534
+ if ("." === functionName[methodStart - 1]) methodStart--;
2535
+ if (methodStart > 0) {
2536
+ object = functionName.slice(0, methodStart);
2537
+ method = functionName.slice(methodStart + 1);
2538
+ const objectEnd = object.indexOf(".Module");
2539
+ if (objectEnd > 0) {
2540
+ functionName = functionName.slice(objectEnd + 1);
2541
+ object = object.slice(0, objectEnd);
2542
+ }
2543
+ }
2544
+ typeName = void 0;
2545
+ }
2546
+ if (method) {
2547
+ typeName = object;
2548
+ methodName = method;
2549
+ }
2550
+ if ("<anonymous>" === method) {
2551
+ methodName = void 0;
2552
+ functionName = void 0;
2553
+ }
2554
+ if (void 0 === functionName) {
2555
+ methodName = methodName || UNKNOWN_FUNCTION;
2556
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
2557
+ }
2558
+ let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
2559
+ const isNative = "native" === lineMatch[5];
2560
+ if (filename?.match(/\/[A-Z]:/)) filename = filename.slice(1);
2561
+ if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];
2562
+ return {
2563
+ filename: filename ? decodeURI(filename) : void 0,
2564
+ module: void 0,
2565
+ function: functionName,
2566
+ lineno: _parseIntOrUndefined(lineMatch[3]),
2567
+ colno: _parseIntOrUndefined(lineMatch[4]),
2568
+ in_app: filenameIsInApp(filename || "", isNative),
2569
+ platform
2570
+ };
2571
+ }
2572
+ if (line.match(FILENAME_MATCH)) return {
2573
+ filename: line,
2574
+ platform
2575
+ };
2576
+ };
2577
+ function filenameIsInApp(filename, isNative = false) {
2578
+ const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
2579
+ return !isInternal && void 0 !== filename && !filename.includes("node_modules/");
2580
+ }
2581
+ function _parseIntOrUndefined(input) {
2582
+ return parseInt(input || "", 10) || void 0;
2583
+ }
2584
+
2585
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
2586
+ var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
2587
+ var STACKTRACE_FRAME_LIMIT = 50;
2588
+ function reverseAndStripFrames(stack) {
2589
+ if (!stack.length) return [];
2590
+ const localStack = Array.from(stack);
2591
+ localStack.reverse();
2592
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
2593
+ ...frame,
2594
+ filename: frame.filename || getLastStackFrame(localStack).filename,
2595
+ function: frame.function || UNKNOWN_FUNCTION
2596
+ }));
2597
+ }
2598
+ function getLastStackFrame(arr) {
2599
+ return arr[arr.length - 1] || {};
2600
+ }
2601
+ function createDefaultStackParser() {
2602
+ return createStackParser("web:javascript", chromeStackLineParser, geckoStackLineParser);
2603
+ }
2604
+ function createStackParser(platform, ...parsers) {
2605
+ return (stack, skipFirstLines = 0) => {
2606
+ const frames = [];
2607
+ const lines = stack.split("\n");
2608
+ for (let i = skipFirstLines; i < lines.length; i++) {
2609
+ const line = lines[i];
2610
+ if (line.length > 1024) continue;
2611
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
2612
+ if (!cleanedLine.match(/\S*Error: /)) {
2613
+ for (const parser of parsers) {
2614
+ const frame = parser(cleanedLine, platform);
2615
+ if (frame) {
2616
+ frames.push(frame);
2617
+ break;
2618
+ }
2619
+ }
2620
+ if (frames.length >= STACKTRACE_FRAME_LIMIT) break;
2621
+ }
2622
+ }
2623
+ return reverseAndStripFrames(frames);
2624
+ };
2625
+ }
2626
+
2627
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
2628
+ var DOMExceptionCoercer = class {
2629
+ match(err) {
2630
+ return this.isDOMException(err) || this.isDOMError(err);
2631
+ }
2632
+ coerce(err, ctx) {
2633
+ const hasStack = isString(err.stack);
2634
+ return {
2635
+ type: this.getType(err),
2636
+ value: this.getValue(err),
2637
+ stack: hasStack ? err.stack : void 0,
2638
+ cause: err.cause ? ctx.next(err.cause) : void 0,
2639
+ synthetic: false
2640
+ };
2641
+ }
2642
+ getType(candidate) {
2643
+ return this.isDOMError(candidate) ? "DOMError" : "DOMException";
2644
+ }
2645
+ getValue(err) {
2646
+ const name = err.name || (this.isDOMError(err) ? "DOMError" : "DOMException");
2647
+ const message = err.message ? `${name}: ${err.message}` : name;
2648
+ return message;
2649
+ }
2650
+ isDOMException(err) {
2651
+ return isBuiltin(err, "DOMException");
2652
+ }
2653
+ isDOMError(err) {
2654
+ return isBuiltin(err, "DOMError");
2655
+ }
2656
+ };
2657
+
2658
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
2659
+ var ErrorCoercer = class {
2660
+ match(err) {
2661
+ return isPlainError(err);
2662
+ }
2663
+ coerce(err, ctx) {
2664
+ return {
2665
+ type: this.getType(err),
2666
+ value: this.getMessage(err, ctx),
2667
+ stack: this.getStack(err),
2668
+ cause: err.cause ? ctx.next(err.cause) : void 0,
2669
+ synthetic: false
2670
+ };
2671
+ }
2672
+ getType(err) {
2673
+ return err.name || err.constructor.name;
2674
+ }
2675
+ getMessage(err, _ctx) {
2676
+ const message = err.message;
2677
+ if (message.error && "string" == typeof message.error.message) return String(message.error.message);
2678
+ return String(message);
2679
+ }
2680
+ getStack(err) {
2681
+ return err.stacktrace || err.stack || void 0;
2682
+ }
2683
+ };
2684
+
2685
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
2686
+ var ErrorEventCoercer = class {
2687
+ constructor() {
2688
+ }
2689
+ match(err) {
2690
+ return isErrorEvent(err) && void 0 != err.error;
2691
+ }
2692
+ coerce(err, ctx) {
2693
+ const exceptionLike = ctx.apply(err.error);
2694
+ if (!exceptionLike) return {
2695
+ type: "ErrorEvent",
2696
+ value: err.message,
2697
+ stack: ctx.syntheticException?.stack,
2698
+ synthetic: true
2699
+ };
2700
+ return exceptionLike;
2701
+ }
2702
+ };
2703
+
2704
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
2705
+ var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
2706
+ var StringCoercer = class {
2707
+ match(input) {
2708
+ return "string" == typeof input;
2709
+ }
2710
+ coerce(input, ctx) {
2711
+ const [type, value] = this.getInfos(input);
2712
+ return {
2713
+ type: type ?? "Error",
2714
+ value: value ?? input,
2715
+ stack: ctx.syntheticException?.stack,
2716
+ synthetic: true
2717
+ };
2718
+ }
2719
+ getInfos(candidate) {
2720
+ let type = "Error";
2721
+ let value = candidate;
2722
+ const groups = candidate.match(ERROR_TYPES_PATTERN);
2723
+ if (groups) {
2724
+ type = groups[1];
2725
+ value = groups[2];
2726
+ }
2727
+ return [
2728
+ type,
2729
+ value
2730
+ ];
2731
+ }
2732
+ };
2733
+
2734
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/types.mjs
2735
+ var severityLevels = [
2736
+ "fatal",
2737
+ "error",
2738
+ "warning",
2739
+ "log",
2740
+ "info",
2741
+ "debug"
2742
+ ];
2743
+
2744
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
2745
+ function extractExceptionKeysForMessage(err, maxLength = 40) {
2746
+ const keys = Object.keys(err);
2747
+ keys.sort();
2748
+ if (!keys.length) return "[object has no keys]";
2749
+ for (let i = keys.length; i > 0; i--) {
2750
+ const serialized = keys.slice(0, i).join(", ");
2751
+ if (!(serialized.length > maxLength)) {
2752
+ if (i === keys.length) return serialized;
2753
+ return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
2754
+ }
2755
+ }
2756
+ return "";
2757
+ }
2758
+
2759
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
2760
+ var ObjectCoercer = class {
2761
+ match(candidate) {
2762
+ return "object" == typeof candidate && null !== candidate;
2763
+ }
2764
+ coerce(candidate, ctx) {
2765
+ const errorProperty = this.getErrorPropertyFromObject(candidate);
2766
+ if (errorProperty) return ctx.apply(errorProperty);
2767
+ return {
2768
+ type: this.getType(candidate),
2769
+ value: this.getValue(candidate),
2770
+ stack: ctx.syntheticException?.stack,
2771
+ level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
2772
+ synthetic: true
2773
+ };
2774
+ }
2775
+ getType(err) {
2776
+ return isEvent(err) ? err.constructor.name : "Error";
2777
+ }
2778
+ getValue(err) {
2779
+ if ("name" in err && "string" == typeof err.name) {
2780
+ let message = `'${err.name}' captured as exception`;
2781
+ if ("message" in err && "string" == typeof err.message) message += ` with message: '${err.message}'`;
2782
+ return message;
2783
+ }
2784
+ if ("message" in err && "string" == typeof err.message) return err.message;
2785
+ const className = this.getObjectClassName(err);
2786
+ const keys = extractExceptionKeysForMessage(err);
2787
+ return `${className && "Object" !== className ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
2788
+ }
2789
+ isSeverityLevel(x) {
2790
+ return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
2791
+ }
2792
+ getErrorPropertyFromObject(obj) {
2793
+ for (const prop in obj) if (Object.prototype.hasOwnProperty.call(obj, prop)) {
2794
+ const value = obj[prop];
2795
+ if (isError(value)) return value;
2796
+ }
2797
+ }
2798
+ getObjectClassName(obj) {
2799
+ try {
2800
+ const prototype = Object.getPrototypeOf(obj);
2801
+ return prototype ? prototype.constructor.name : void 0;
2802
+ } catch (e) {
2803
+ return;
2804
+ }
2805
+ }
2806
+ };
2807
+
2808
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2809
+ var EventCoercer = class {
2810
+ match(err) {
2811
+ return isEvent(err);
2812
+ }
2813
+ coerce(evt, ctx) {
2814
+ const constructorName = evt.constructor.name;
2815
+ return {
2816
+ type: constructorName,
2817
+ value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
2818
+ stack: ctx.syntheticException?.stack,
2819
+ synthetic: true
2820
+ };
2821
+ }
2822
+ };
2823
+
2824
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2825
+ var PrimitiveCoercer = class {
2826
+ match(candidate) {
2827
+ return isPrimitive(candidate);
2828
+ }
2829
+ coerce(value, ctx) {
2830
+ return {
2831
+ type: "Error",
2832
+ value: `Primitive value captured as exception: ${String(value)}`,
2833
+ stack: ctx.syntheticException?.stack,
2834
+ synthetic: true
2835
+ };
2836
+ }
2837
+ };
2838
+
2839
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
2840
+ var PromiseRejectionEventCoercer = class {
2841
+ match(err) {
2842
+ return isBuiltin(err, "PromiseRejectionEvent") || this.isCustomEventWrappingRejection(err);
2843
+ }
2844
+ isCustomEventWrappingRejection(err) {
2845
+ if (!isEvent(err)) return false;
2846
+ try {
2847
+ const detail = err.detail;
2848
+ return null != detail && "object" == typeof detail && "reason" in detail;
2849
+ } catch {
2850
+ return false;
2851
+ }
2852
+ }
2853
+ coerce(err, ctx) {
2854
+ const reason = this.getUnhandledRejectionReason(err);
2855
+ if (isPrimitive(reason)) return {
2856
+ type: "UnhandledRejection",
2857
+ value: `Non-Error promise rejection captured with value: ${String(reason)}`,
2858
+ stack: ctx.syntheticException?.stack,
2859
+ synthetic: true
2860
+ };
2861
+ return ctx.apply(reason);
2862
+ }
2863
+ getUnhandledRejectionReason(error) {
2864
+ try {
2865
+ if ("reason" in error) return error.reason;
2866
+ if ("detail" in error && null != error.detail && "object" == typeof error.detail && "reason" in error.detail) return error.detail.reason;
2867
+ } catch {
2868
+ }
2869
+ return error;
2870
+ }
2871
+ };
2872
+
2873
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2874
+ var ReduceableCache = class {
2875
+ constructor(_maxSize) {
2876
+ this._maxSize = _maxSize;
2877
+ this._cache = /* @__PURE__ */ new Map();
2878
+ }
2879
+ get(key) {
2880
+ const value = this._cache.get(key);
2881
+ if (void 0 === value) return;
2882
+ this._cache.delete(key);
2883
+ this._cache.set(key, value);
2884
+ return value;
2885
+ }
2886
+ set(key, value) {
2887
+ this._cache.set(key, value);
2888
+ }
2889
+ reduce() {
2890
+ while (this._cache.size >= this._maxSize) {
2891
+ const value = this._cache.keys().next().value;
2892
+ if (value) this._cache.delete(value);
2893
+ }
2894
+ }
2895
+ };
2896
+
2897
+ // ../node_modules/.pnpm/@posthog+core@1.31.1/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2898
+ var EXCEPTION_STEP_INTERNAL_FIELDS = {
2899
+ MESSAGE: "$message",
2900
+ TIMESTAMP: "$timestamp"
2901
+ };
2902
+ var RESERVED_EXCEPTION_STEP_KEYS = /* @__PURE__ */ new Set([
2903
+ EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,
2904
+ EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP
2905
+ ]);
2906
+ var DEFAULT_EXCEPTION_STEPS_CONFIG = {
2907
+ enabled: true,
2908
+ max_bytes: 32768
2909
+ };
2910
+ function resolveExceptionStepsConfig(config) {
2911
+ if (!config) return {
2912
+ ...DEFAULT_EXCEPTION_STEPS_CONFIG
2913
+ };
2914
+ return {
2915
+ enabled: config.enabled ?? DEFAULT_EXCEPTION_STEPS_CONFIG.enabled,
2916
+ max_bytes: normalizePositiveInteger(config.max_bytes, DEFAULT_EXCEPTION_STEPS_CONFIG.max_bytes)
2917
+ };
2918
+ }
2919
+ function stripReservedExceptionStepFields(properties) {
2920
+ if (!properties) return {
2921
+ sanitizedProperties: {},
2922
+ droppedKeys: []
2923
+ };
2924
+ const droppedKeys = [];
2925
+ const sanitizedProperties = Object.keys(properties).reduce((acc, key) => {
2926
+ if (RESERVED_EXCEPTION_STEP_KEYS.has(key)) {
2927
+ droppedKeys.push(key);
2928
+ return acc;
2929
+ }
2930
+ acc[key] = properties[key];
2931
+ return acc;
2932
+ }, {});
2933
+ return {
2934
+ sanitizedProperties,
2935
+ droppedKeys
2936
+ };
2937
+ }
2938
+ var ExceptionStepsBuffer = class {
2939
+ constructor(config) {
2940
+ this._entries = [];
2941
+ this._totalBytes = 0;
2942
+ this._config = resolveExceptionStepsConfig(config);
2943
+ }
2944
+ setConfig(config) {
2945
+ this._config = resolveExceptionStepsConfig(config);
2946
+ this._trimToMaxBytes();
2947
+ }
2948
+ add(step) {
2949
+ const serialized = normalizeAndSerializeStep(step);
2950
+ if (!serialized) return;
2951
+ const bytes = getUtf8ByteLength(serialized.json);
2952
+ if (bytes > this._config.max_bytes) return;
2953
+ this._entries.push({
2954
+ step: serialized.step,
2955
+ bytes
2956
+ });
2957
+ this._totalBytes += bytes;
2958
+ this._trimToMaxBytes();
2959
+ }
2960
+ getAttachable() {
2961
+ return this._entries.map((e) => e.step);
2962
+ }
2963
+ clear() {
2964
+ this._entries = [];
2965
+ this._totalBytes = 0;
2966
+ }
2967
+ size() {
2968
+ return this._entries.length;
2969
+ }
2970
+ _trimToMaxBytes() {
2971
+ while (this._totalBytes > this._config.max_bytes && this._entries.length > 0) {
2972
+ const evicted = this._entries.shift();
2973
+ if (evicted) this._totalBytes -= evicted.bytes;
2974
+ }
2975
+ }
2976
+ };
2977
+ function normalizePositiveInteger(input, fallback) {
2978
+ if (!isNumber(input) || input === 1 / 0 || input === -1 / 0) return fallback;
2979
+ const normalized = Math.floor(input);
2980
+ if (normalized < 0) return fallback;
2981
+ return normalized;
2982
+ }
2983
+ function normalizeAndSerializeStep(step) {
2984
+ const json = safeStringify(step);
2985
+ if (!json) return;
2986
+ try {
2987
+ const parsed = JSON.parse(json);
2988
+ if (!isObject(parsed)) return;
2989
+ const parsedStep = parsed;
2990
+ const message = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE];
2991
+ const timestamp = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP];
2992
+ if (!isString(message) || 0 === message.trim().length) return;
2993
+ if (!isString(timestamp) && !isNumber(timestamp)) return;
2994
+ return {
2995
+ step: parsedStep,
2996
+ json
2997
+ };
2998
+ } catch {
2999
+ return;
3000
+ }
3001
+ }
3002
+ function safeStringify(value) {
3003
+ const seen = /* @__PURE__ */ new WeakSet();
3004
+ try {
3005
+ return JSON.stringify(value, (_key, replacementValue) => {
3006
+ if ("bigint" == typeof replacementValue) return replacementValue.toString();
3007
+ if ("function" == typeof replacementValue || "symbol" == typeof replacementValue) return;
3008
+ if (replacementValue instanceof Date) return replacementValue.toISOString();
3009
+ if (replacementValue instanceof Error) return {
3010
+ name: replacementValue.name,
3011
+ message: replacementValue.message,
3012
+ stack: replacementValue.stack
3013
+ };
3014
+ if (replacementValue && "object" == typeof replacementValue) {
3015
+ if (seen.has(replacementValue)) return "[Circular]";
3016
+ seen.add(replacementValue);
3017
+ }
3018
+ return replacementValue;
3019
+ });
3020
+ } catch {
3021
+ return;
3022
+ }
3023
+ }
3024
+ function getUtf8ByteLength(value) {
3025
+ if ("undefined" != typeof TextEncoder) return new TextEncoder().encode(value).length;
3026
+ const encoded = encodeURIComponent(value);
3027
+ let byteLength = 0;
3028
+ for (let i = 0; i < encoded.length; i++) if ("%" === encoded[i]) {
3029
+ byteLength += 1;
3030
+ i += 2;
3031
+ } else byteLength += 1;
3032
+ return byteLength;
3033
+ }
3034
+
3035
+ // ../node_modules/.pnpm/posthog-node@5.36.10/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
3036
+ var import_node_fs3 = require("fs");
3037
+ var import_node_readline = require("readline");
3038
+ var LRU_FILE_CONTENTS_CACHE = new error_tracking_exports.ReduceableCache(25);
3039
+ var LRU_FILE_CONTENTS_FS_READ_FAILED = new error_tracking_exports.ReduceableCache(20);
3040
+
3041
+ // ../node_modules/.pnpm/posthog-node@5.36.10/node_modules/posthog-node/dist/extensions/context/context.mjs
3042
+ var import_node_async_hooks = require("async_hooks");
3043
+
3044
+ // ../node_modules/.pnpm/posthog-node@5.36.10/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
3045
+ var NAME = "posthog-node";
3046
+ function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
3047
+ "error"
3048
+ ], sendExceptionsToPostHog = true } = {}) {
3049
+ return (event) => {
3050
+ const shouldProcessLevel = "*" === severityAllowList || severityAllowList.includes(event.level);
3051
+ if (!shouldProcessLevel) return event;
3052
+ if (!event.tags) event.tags = {};
3053
+ const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];
3054
+ if (void 0 === userId) return event;
3055
+ const uiHost = _posthog.options.host ?? "https://us.i.posthog.com";
3056
+ const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();
3057
+ event.tags["PostHog Person URL"] = personUrl;
3058
+ const exceptions = event.exception?.values || [];
3059
+ const exceptionList = exceptions.map((exception) => ({
3060
+ ...exception,
3061
+ stacktrace: exception.stacktrace ? {
3062
+ ...exception.stacktrace,
3063
+ type: "raw",
3064
+ frames: (exception.stacktrace.frames || []).map((frame) => ({
3065
+ ...frame,
3066
+ platform: "node:javascript"
3067
+ }))
3068
+ } : void 0
3069
+ }));
3070
+ const properties = {
3071
+ $exception_message: exceptions[0]?.value || event.message,
3072
+ $exception_type: exceptions[0]?.type,
3073
+ $exception_level: event.level,
3074
+ $exception_list: exceptionList,
3075
+ $sentry_event_id: event.event_id,
3076
+ $sentry_exception: event.exception,
3077
+ $sentry_exception_message: exceptions[0]?.value || event.message,
3078
+ $sentry_exception_type: exceptions[0]?.type,
3079
+ $sentry_tags: event.tags
3080
+ };
3081
+ if (organization && projectId) properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
3082
+ if (sendExceptionsToPostHog) _posthog.capture({
3083
+ event: "$exception",
3084
+ distinctId: userId,
3085
+ properties
3086
+ });
3087
+ return event;
3088
+ };
3089
+ }
3090
+ var PostHogSentryIntegration = class {
3091
+ static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
3092
+ constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
3093
+ this.name = NAME;
3094
+ this.name = NAME;
3095
+ this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {
3096
+ const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;
3097
+ addGlobalEventProcessor(createEventProcessor(_posthog, {
3098
+ organization,
3099
+ projectId,
3100
+ prefix,
3101
+ severityAllowList,
3102
+ sendExceptionsToPostHog: sendExceptionsToPostHog ?? true
3103
+ }));
3104
+ };
3105
+ }
3106
+ };
3107
+
3108
+ // src/telemetry/posthog.ts
3109
+ var POSTHOG_KEY = process.env["ARCHAL_POSTHOG_KEY"] ?? "phc_OEdBZlIiJUhnj5dOBsCf9qyXQmbf6RGYIl7k5BcNKn4";
3110
+ var baseProperties = {
3111
+ cli_version: CLI_VERSION,
3112
+ os_platform: process.platform,
3113
+ node_version: process.version,
3114
+ source: "cli"
3115
+ };
3116
+
3117
+ // src/commands/autoloop-github-app.ts
3118
+ var import_node_crypto5 = require("crypto");
3119
+
3120
+ // ../packages/contracts/src/evidence-redaction.ts
3121
+ var import_node_crypto4 = require("crypto");
3122
+ var EVIDENCE_REDACTED = "[REDACTED]";
3123
+ var EVIDENCE_SENSITIVE_KEY_PARTS = /* @__PURE__ */ new Set([
3124
+ "token",
3125
+ "secret",
3126
+ "password",
3127
+ "authorization",
3128
+ "apikey",
3129
+ "api_key",
3130
+ "credential",
3131
+ "credentials",
3132
+ "cookie",
3133
+ "privatekey",
3134
+ "private_key",
3135
+ "accesskey",
3136
+ "access_key",
3137
+ "databaseurl",
3138
+ "database_url",
3139
+ "dburl",
3140
+ "db_url",
3141
+ "redisurl",
3142
+ "redis_url",
3143
+ "mongodburi",
3144
+ "mongo_uri",
3145
+ "connectionstring",
3146
+ "connection_string",
3147
+ "dsn",
3148
+ "workspacekey",
3149
+ "workspace_key",
3150
+ "workspacetoken",
3151
+ "workspace_token",
3152
+ "accesscode",
3153
+ "access_code",
3154
+ "lockboxcode",
3155
+ "lockbox_code",
3156
+ "doorcode",
3157
+ "door_code",
3158
+ "otp",
3159
+ "iban",
3160
+ "clabe",
3161
+ "swift",
3162
+ "bic",
3163
+ "secretref",
3164
+ "secret_ref",
3165
+ "secretname",
3166
+ "secret_name"
3167
+ ]);
3168
+ var EVIDENCE_SENSITIVE_ENV_KEY_PARTS = /* @__PURE__ */ new Set([
3169
+ ...EVIDENCE_SENSITIVE_KEY_PARTS,
3170
+ "apikey",
3171
+ "api_key",
3172
+ "secretkey",
3173
+ "secret_key",
3174
+ "accesstoken",
3175
+ "access_token",
3176
+ "refreshtoken",
3177
+ "refresh_token",
3178
+ "authtoken",
3179
+ "auth_token",
3180
+ "bearertoken",
3181
+ "bearer_token",
3182
+ "privatekey",
3183
+ "private_key",
3184
+ "databaseurl",
3185
+ "database_url",
3186
+ "dburl",
3187
+ "db_url",
3188
+ "redisurl",
3189
+ "redis_url",
3190
+ "mongodburi",
3191
+ "mongo_uri",
3192
+ "connectionstring",
3193
+ "connection_string",
3194
+ "dsn"
3195
+ ]);
3196
+ var EVIDENCE_SERVICE_STRING_PATTERNS = [
3197
+ {
3198
+ pattern: /https?:\/\/[^\s"'<>]+\/runtime\/session\/[^\s"'<>]*/gi,
3199
+ replacement: "[SERVICE_ENDPOINT_REDACTED]"
3200
+ },
3201
+ {
3202
+ pattern: /\/runtime\/session\/[^\s"'<>]*/gi,
3203
+ replacement: "[SERVICE_ENDPOINT_REDACTED]"
3204
+ },
3205
+ {
3206
+ pattern: /\bx-archal-[\w-]+(?::|=)\s*["']?[^"',\s}]+/gi,
3207
+ replacement: "[SERVICE_HEADER_REDACTED]"
3208
+ },
3209
+ {
3210
+ pattern: /\barchal_mcp_servers\b/gi,
3211
+ replacement: "service_tool_servers"
3212
+ },
3213
+ {
3214
+ pattern: /\bARCHAL_(?:CLONE_URLS_PATH|TWIN_URLS_PATH|PROXY_EVENTS_PATH|METRICS_FILE|AGENT_TRACE_FILE|ENABLE_PROVIDER_EGRESS_PROXY)\b/g,
3215
+ replacement: "[SERVICE_RUNTIME_CONFIG_REDACTED]"
3216
+ },
3217
+ {
3218
+ pattern: /\/archal-artifacts\/[^\s"'<>]*/gi,
3219
+ replacement: "[SERVICE_ARTIFACT_PATH_REDACTED]"
3220
+ },
3221
+ {
3222
+ pattern: /\b(?:host\.docker\.internal|localhost|127\.0\.0\.1):9100\b/gi,
3223
+ replacement: "[SERVICE_PROXY_ENDPOINT_REDACTED]"
3224
+ },
3225
+ {
3226
+ pattern: /\b(?:aws-secretsmanager:\/\/|arn:aws:secretsmanager:[^\s"'<>:]+:\d{12}:secret:)[^\s"'<>]+/gi,
3227
+ replacement: "[SECRET_REF_REDACTED]"
3228
+ },
3229
+ {
3230
+ pattern: /\benv:[A-Z0-9_]*(?:API_KEY|SECRET_KEY|SECRET_NAME|SECRET_REF|ACCESS_KEY|ACCESS_TOKEN|REFRESH_TOKEN|AUTH_TOKEN|BEARER_TOKEN|TOKEN|PASSWORD|SECRET|PRIVATE_KEY|DATABASE_URL|DB_URL|REDIS_URL|MONGO_URI|CONNECTION_STRING|DSN|WORKSPACE_TOKEN|WORKSPACE_KEY)[A-Z0-9_]*\b/g,
3231
+ replacement: "[SECRET_REF_REDACTED]"
3232
+ },
3233
+ {
3234
+ pattern: /(?:file:\/\/)?(?:\/Users\/[^/\s"'<>]+|\/home\/[^/\s"'<>]+|\/private\/tmp|\/tmp|\/var\/folders|\/workspace|\/workspaces)(?:\/[^\s"'<>]*)?/g,
3235
+ replacement: "[LOCAL_PATH_REDACTED]"
3236
+ },
3237
+ {
3238
+ pattern: /\b[A-Za-z]:\\Users\\[^\\\s"'<>]+(?:\\[^\s"'<>]*)?/g,
3239
+ replacement: "[LOCAL_PATH_REDACTED]"
3240
+ }
3241
+ ];
3242
+ var FINANCIAL_IDENTIFIER_CONTEXT = String.raw`(?:account|acct|bank|beneficiary|intermediary|payment|payout|recipient|routing|transfer|wire)`;
3243
+ var HIGH_ENTROPY_SECRET = String.raw`(?<![A-Za-z0-9_/-])(?=[A-Za-z0-9_-]{32,}(?![A-Za-z0-9_-]))(?=[A-Za-z0-9_-]*[A-Z])(?=[A-Za-z0-9_-]*[a-z])(?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]+(?![A-Za-z0-9_/-])`;
3244
+ var EVIDENCE_SECRET_LITERAL_STRING_PATTERNS = [
3245
+ {
3246
+ pattern: /\b(Bearer\s+)[A-Za-z0-9._~+/=-]+\b/gi,
3247
+ replacement: `$1${EVIDENCE_REDACTED}`
3248
+ },
3249
+ {
3250
+ pattern: /\b(gh[pousr]_[A-Za-z0-9]{16,})\b/g,
3251
+ replacement: EVIDENCE_REDACTED
3252
+ },
3253
+ {
3254
+ pattern: /\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,
3255
+ replacement: EVIDENCE_REDACTED
3256
+ },
3257
+ {
3258
+ pattern: /\b[srp]k_(?:live|test)_[A-Za-z0-9]{16,}\b/g,
3259
+ replacement: EVIDENCE_REDACTED
3260
+ },
3261
+ {
3262
+ pattern: /\bsk-proj-[A-Za-z0-9_-]{16,}\b/g,
3263
+ replacement: EVIDENCE_REDACTED
3264
+ },
3265
+ {
3266
+ pattern: /\bsk-ant-[A-Za-z0-9_-]{8,}\b/g,
3267
+ replacement: EVIDENCE_REDACTED
3268
+ },
3269
+ {
3270
+ pattern: /\bsk-[A-Za-z0-9_-]{16,}\b/g,
3271
+ replacement: EVIDENCE_REDACTED
3272
+ },
3273
+ {
3274
+ pattern: /\barchal_(?:ws|workspace|token|key|pat|secret)_[A-Za-z0-9_.-]{8,}\b/gi,
3275
+ replacement: EVIDENCE_REDACTED
3276
+ },
3277
+ {
3278
+ pattern: /\bsb_(?:secret|publishable)_[A-Za-z0-9_-]{16,}\b/g,
3279
+ replacement: EVIDENCE_REDACTED
3280
+ },
3281
+ {
3282
+ pattern: /\bpostgres(?:ql)?:\/\/[^\s"'<>]+/gi,
3283
+ replacement: "[DATABASE_URL_REDACTED]"
3284
+ },
3285
+ {
3286
+ pattern: /\b(?:redis|rediss|mysql|mariadb|mongodb(?:\+srv)?|amqp|amqps):\/\/[^\s"'<>]+/gi,
3287
+ replacement: "[CONNECTION_STRING_REDACTED]"
3288
+ },
3289
+ {
3290
+ pattern: /\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^:\s/@]+:[^@\s/]+@[^\s"'<>]+/gi,
3291
+ replacement: "[BASIC_AUTH_URL_REDACTED]"
3292
+ },
3293
+ {
3294
+ pattern: /\bAIza[0-9A-Za-z_-]{12,}\b/g,
3295
+ replacement: EVIDENCE_REDACTED
3296
+ },
3297
+ {
3298
+ pattern: /\b(?:xox[baprs]-[A-Za-z0-9-]{10,})\b/g,
3299
+ replacement: EVIDENCE_REDACTED
3300
+ },
3301
+ {
3302
+ pattern: /\bx(?:app|oxa|oxc|oxp|oxs)-[A-Za-z0-9-]{10,}\b/g,
3303
+ replacement: EVIDENCE_REDACTED
3304
+ },
3305
+ {
3306
+ pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
3307
+ replacement: EVIDENCE_REDACTED
3308
+ },
3309
+ {
3310
+ pattern: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9._-]{10,}\.[A-Za-z0-9._-]{10,}\b/g,
3311
+ replacement: EVIDENCE_REDACTED
3312
+ },
3313
+ {
3314
+ pattern: /-----BEGIN(?:[ A-Z]+)?PRIVATE KEY-----[\s\S]*?-----END(?:[ A-Z]+)?PRIVATE KEY-----/g,
3315
+ replacement: EVIDENCE_REDACTED
3316
+ },
3317
+ {
3318
+ pattern: /(^|[?&])((?:token|access_token|refresh_token|auth_token|bearer_token|client_secret|secret|api_key|apikey|password)=)[^&\s]+/gi,
3319
+ replacement: `$1$2${EVIDENCE_REDACTED}`
3320
+ },
3321
+ {
3322
+ pattern: /\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b/g,
3323
+ replacement: EVIDENCE_REDACTED
3324
+ },
3325
+ {
3326
+ pattern: new RegExp(String.raw`\b(${FINANCIAL_IDENTIFIER_CONTEXT}\s+)\d{18}\b`, "gi"),
3327
+ replacement: `$1${EVIDENCE_REDACTED}`
3328
+ },
3329
+ {
3330
+ pattern: new RegExp(
3331
+ String.raw`\b(${FINANCIAL_IDENTIFIER_CONTEXT}\s+)(?!REDACTED\b)[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b`,
3332
+ "g"
3333
+ ),
3334
+ replacement: `$1${EVIDENCE_REDACTED}`
3335
+ },
3336
+ {
3337
+ pattern: new RegExp(HIGH_ENTROPY_SECRET, "g"),
3338
+ replacement: EVIDENCE_REDACTED
3339
+ }
3340
+ ];
3341
+ var EVIDENCE_SENSITIVE_LABEL = String.raw`(?:authorization|token|access[_ -]?token|refresh[_ -]?token|id[_ -]?token|auth[_ -]?token|session[_ -]?token|client[_ -]?secret|secret|secret[_ -]?ref|secretref|secret[_ -]?name|secretname|api[_ -]?key|apikey|password|private[_ -]?key|privatekey|database[_ -]?url|databaseurl|db[_ -]?url|dburl|redis[_ -]?url|redisurl|mongo[_ -]?uri|mongodburi|connection[_ -]?string|connectionstring|dsn|workspace[_ -]?token|workspacetoken|workspace[_ -]?key|workspacekey|access[_ -]?key|credential|credentials|access[_ -]?code|lockbox[_ -]?code|door[_ -]?code|otp|one[_ -]?time[_ -]?password|iban|clabe|swift|bic)`;
3342
+ var EVIDENCE_SENSITIVE_LABEL_ASSIGNMENT = String.raw`(?:\*\*)?["']?${EVIDENCE_SENSITIVE_LABEL}["']?\s*[:=](?:\*\*)?\s*`;
3343
+ var EVIDENCE_SENSITIVE_LABEL_HINT = new RegExp(
3344
+ String.raw`\b${EVIDENCE_SENSITIVE_LABEL_ASSIGNMENT}`,
3345
+ "i"
3346
+ );
3347
+ var EVIDENCE_FINANCIAL_IDENTIFIER_HINT = new RegExp(
3348
+ String.raw`(\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b|\b${FINANCIAL_IDENTIFIER_CONTEXT}\s+\d{18}\b|\b${FINANCIAL_IDENTIFIER_CONTEXT}\s+(?!REDACTED\b)[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b)`,
3349
+ "i"
3350
+ );
3351
+ var EVIDENCE_HIGH_ENTROPY_SECRET_HINT = new RegExp(HIGH_ENTROPY_SECRET);
3352
+ var EVIDENCE_SECRET_REDACTION_MARKER = String.raw`(?:\[[A-Z0-9_]*REDACTED\]|\[FILTERED\]|\[MASKED\]|<redacted>)`;
3353
+ var EVIDENCE_KEY_VALUE_STRING_PATTERNS = [
3354
+ {
3355
+ pattern: new RegExp(
3356
+ String.raw`\b(${EVIDENCE_SENSITIVE_LABEL_ASSIGNMENT})(?!\s*(?:\[[A-Z0-9_]+\]|<redacted>))(?:"[^"\r\n]*"|'[^'\r\n]*'|Bearer\s+\[REDACTED\]|Bearer\s+.+?|.+?)(?=(?:\s+${EVIDENCE_SENSITIVE_LABEL_ASSIGNMENT})|[\r\n,}\]&]|$)`,
3357
+ "gi"
3358
+ ),
3359
+ replacement: `$1${EVIDENCE_REDACTED}`
3360
+ },
3361
+ {
3362
+ pattern: /\b((?:"?(?:authorization|token|access_token|refresh_token|client_secret|secret|secret_ref|secretref|secret_name|secretname|api_key|apikey|password|private_key|privatekey|database_url|databaseurl|db_url|dburl|redis_url|redisurl|mongo_uri|mongodburi|connection_string|connectionstring|dsn|workspace_token|workspacetoken|workspace_key|workspacekey)"?\s*[:=]\s*)(?!\[[A-Z0-9_]+\]))(?:"[^"]+"|'[^']+'|Bearer\s+\[REDACTED\]|Bearer\s+[^\s,}\]]+|[^\s,}\]]+)/gi,
3363
+ replacement: `$1${EVIDENCE_REDACTED}`
3364
+ },
3365
+ {
3366
+ pattern: /\b([A-Z0-9_]*(?:API_KEY|SECRET_KEY|SECRET_NAME|SECRET_REF|ACCESS_KEY|ACCESS_TOKEN|REFRESH_TOKEN|AUTH_TOKEN|BEARER_TOKEN|TOKEN|PASSWORD|SECRET|PRIVATE_KEY|DATABASE_URL|DB_URL|REDIS_URL|MONGO_URI|CONNECTION_STRING|DSN|WORKSPACE_TOKEN|WORKSPACE_KEY)[A-Z0-9_]*\s*[:=]\s*)(?!\[[A-Z0-9_]+\])(?:"[^"]+"|'[^']+'|[^\s,}\]]+)/g,
3367
+ replacement: `$1${EVIDENCE_REDACTED}`
3368
+ },
3369
+ {
3370
+ // Fail-open recovery. When a sensitive label's value was already replaced
3371
+ // with a redaction marker but a bare secret still trails it
3372
+ // (`password: [REDACTED] dGVzdA==`), the assignment patterns above skip the
3373
+ // match — their `(?!marker)` guard fires on the marker — and leave the tail
3374
+ // exposed. Redact the trailing token too. This fails closed but is
3375
+ // deliberately narrow to avoid mangling ordinary prose that follows a
3376
+ // redacted value (`token=[REDACTED] for /path`, `...=[REDACTED] rotated`):
3377
+ // - the marker must be a real secret marker (`[…REDACTED]`, `[FILTERED]`,
3378
+ // `[MASKED]`, `<redacted>`), NOT a semantic placeholder like `[url]` or
3379
+ // `[path]`, and a `[FILTERED]` producer is still covered;
3380
+ // - the recovered trailing token must be SECRET-SHAPED — quoted, or ≥6
3381
+ // chars containing at least one digit or base64/token symbol
3382
+ // (`0-9 + / = _ -`). base64 padding (`dGVzdA==`) qualifies; bare
3383
+ // dictionary words (`for`, `rotated`, `successfully`) do not, so prose is
3384
+ // left intact;
3385
+ // - the marker itself is skipped (idempotent) and a following sensitive
3386
+ // `key:`/`key=` assignment is deferred to the primary patterns, so this
3387
+ // does not gobble the next labeled field.
3388
+ pattern: new RegExp(
3389
+ String.raw`\b(${EVIDENCE_SENSITIVE_LABEL_ASSIGNMENT}${EVIDENCE_SECRET_REDACTION_MARKER}[ \t]+)(?!${EVIDENCE_SENSITIVE_LABEL_ASSIGNMENT})(?!${EVIDENCE_SECRET_REDACTION_MARKER})(?:"[^"\r\n]*"|'[^'\r\n]*'|(?=[^\s,}\]&]*[0-9+/=_-])[^\s,}\]&]{6,})`,
3390
+ "gi"
3391
+ ),
3392
+ replacement: `$1${EVIDENCE_REDACTED}`
3393
+ }
3394
+ ];
3395
+ var EVIDENCE_SECRET_NAME_STRING_PATTERNS = [
3396
+ {
3397
+ pattern: /(?<!\[)\b[A-Z0-9_]*(?:API_KEY|SECRET_KEY|SECRET_NAME|SECRET_REF|ACCESS_KEY|ACCESS_TOKEN|REFRESH_TOKEN|AUTH_TOKEN|BEARER_TOKEN|TOKEN|PASSWORD|SECRET|PRIVATE_KEY|DATABASE_URL|DB_URL|REDIS_URL|MONGO_URI|CONNECTION_STRING|DSN|WORKSPACE_TOKEN|WORKSPACE_KEY)[A-Z0-9_]*\b(?!\s*[:=])/g,
3398
+ replacement: "[SECRET_NAME_REDACTED]"
3399
+ }
3400
+ ];
3401
+ var EVIDENCE_STRING_PATTERNS = [
3402
+ ...EVIDENCE_SERVICE_STRING_PATTERNS,
3403
+ ...EVIDENCE_SECRET_LITERAL_STRING_PATTERNS,
3404
+ ...EVIDENCE_KEY_VALUE_STRING_PATTERNS,
3405
+ ...EVIDENCE_SECRET_NAME_STRING_PATTERNS
3406
+ ];
3407
+ function getEvidenceSecretRedactionPatterns() {
3408
+ return [...EVIDENCE_SECRET_LITERAL_STRING_PATTERNS, ...EVIDENCE_KEY_VALUE_STRING_PATTERNS].map(
3409
+ ({ pattern, replacement }) => ({
3410
+ pattern: new RegExp(pattern.source, pattern.flags),
3411
+ replacement
3412
+ })
3413
+ );
3414
+ }
3415
+ var EVIDENCE_STRING_REDACTION_HINT = new RegExp(
3416
+ String.raw`(\/runtime\/session\/|x-archal-|archal_mcp_servers|\bARCHAL_(?:CLONE_URLS_PATH|TWIN_URLS_PATH|PROXY_EVENTS_PATH|METRICS_FILE|AGENT_TRACE_FILE|ENABLE_PROVIDER_EGRESS_PROXY)\b|\/archal-artifacts\/|\b(?:host\.docker\.internal|localhost|127\.0\.0\.1):9100\b|\b(?:aws-secretsmanager:\/\/|arn:aws:secretsmanager:)|\benv:[A-Z0-9_]*(?:API_KEY|SECRET_KEY|SECRET_NAME|SECRET_REF|ACCESS_KEY|ACCESS_TOKEN|REFRESH_TOKEN|AUTH_TOKEN|BEARER_TOKEN|TOKEN|PASSWORD|SECRET|PRIVATE_KEY|DATABASE_URL|DB_URL|REDIS_URL|MONGO_URI|CONNECTION_STRING|DSN|WORKSPACE_TOKEN|WORKSPACE_KEY)[A-Z0-9_]*\b|(?:file:\/\/)?(?:\/Users\/|\/home\/|\/private\/tmp|\/tmp|\/var\/folders|\/workspace|\/workspaces)|\b[A-Za-z]:\\Users\\|bearer\s+|gh[pousr]_|github_pat_|[srp]k_(?:live|test)_|sk-proj-|sk-ant-|sk-|archal_(?:ws|workspace|token|key|pat|secret)_|sb_(?:secret|publishable)_|postgres(?:ql)?:\/\/|(?:redis|rediss|mysql|mariadb|mongodb(?:\+srv)?|amqp|amqps):\/\/|\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^:\s/@]+:[^@\s/]+@|AIza|xox[baprs]-|x(?:app|oxa|oxc|oxp|oxs)-|(?:AKIA|ASIA)|eyJ|\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b|\b${FINANCIAL_IDENTIFIER_CONTEXT}\s+\d{18}\b|\b${FINANCIAL_IDENTIFIER_CONTEXT}\s+(?!REDACTED\b)[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b|${HIGH_ENTROPY_SECRET}|private key|(?:^|[?&])(?:token|access_token|refresh_token|auth_token|bearer_token|client_secret|secret|api_key|apikey|password)=|\b${EVIDENCE_SENSITIVE_LABEL_ASSIGNMENT}|\b"?(?:authorization|token|access_token|refresh_token|client_secret|secret|secret_ref|secretref|secret_name|secretname|api_key|apikey|password|private_key|privatekey|database_url|databaseurl|db_url|dburl|redis_url|redisurl|mongo_uri|mongodburi|connection_string|connectionstring|dsn|workspace_token|workspacetoken|workspace_key|workspacekey)"?\s*[:=]|\b[A-Z0-9_]*(?:API_KEY|SECRET_KEY|SECRET_NAME|SECRET_REF|ACCESS_KEY|ACCESS_TOKEN|REFRESH_TOKEN|AUTH_TOKEN|BEARER_TOKEN|TOKEN|PASSWORD|SECRET|PRIVATE_KEY|DATABASE_URL|DB_URL|REDIS_URL|MONGO_URI|CONNECTION_STRING|DSN|WORKSPACE_TOKEN|WORKSPACE_KEY)[A-Z0-9_]*(?:\s*[:=]|\b))`,
3417
+ "i"
3418
+ );
3419
+
3420
+ // ../packages/trace-normalize/src/redaction.ts
3421
+ var TRACE_REDACTED = "[REDACTED]";
3422
+ var DEFAULT_SENSITIVE_TRACE_KEY_PARTS = [
3423
+ "token",
3424
+ "secret",
3425
+ "password",
3426
+ "authorization",
3427
+ "apikey",
3428
+ "api-key",
3429
+ "api_key",
3430
+ "credential",
3431
+ "cookie",
3432
+ "privatekey",
3433
+ "private-key",
3434
+ "private_key",
3435
+ "accesskey",
3436
+ "access-key",
3437
+ "access_key",
3438
+ "databaseurl",
3439
+ "database-url",
3440
+ "database_url",
3441
+ "dburl",
3442
+ "db-url",
3443
+ "db_url",
3444
+ "connectionstring",
3445
+ "connection-string",
3446
+ "connection_string",
3447
+ "dsn",
3448
+ "card",
3449
+ "cardnumber",
3450
+ "creditcard",
3451
+ "pan"
3452
+ ];
3453
+ var TRACE_SOURCE_URL_PATTERNS = [
3454
+ {
3455
+ pattern: /\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|rediss):\/\/[^\s"'<>]+/gi,
3456
+ replacement: "[CONNECTION_URL_REDACTED]"
3457
+ },
3458
+ {
3459
+ pattern: /\b(https?:\/\/)[^/\s"'<>@]+@/gi,
3460
+ replacement: `$1${TRACE_REDACTED}@`
3461
+ },
3462
+ {
3463
+ pattern: /(^|[?&])((?:token|access_token|refresh_token|client_secret|secret|api_key|apikey|password|signature|sig|x-amz-signature|x-goog-signature|awsaccesskeyid|sv|se|sp)=)[^&\s]+/gi,
3464
+ replacement: `$1$2${TRACE_REDACTED}`
3465
+ }
3466
+ ];
3467
+ var DEFAULT_SECRET_TRACE_STRING_PATTERNS = [
3468
+ ...TRACE_SOURCE_URL_PATTERNS,
3469
+ ...getEvidenceSecretRedactionPatterns()
3470
+ ];
3471
+ var DEFAULT_TRACE_REDACTION_POLICY = {
3472
+ enabled: true,
3473
+ mode: "mask",
3474
+ replacement: TRACE_REDACTED,
3475
+ sensitiveKeyParts: DEFAULT_SENSITIVE_TRACE_KEY_PARTS,
3476
+ stringPatterns: DEFAULT_SECRET_TRACE_STRING_PATTERNS,
3477
+ maxDepth: 24
3478
+ };
3479
+ function normalizeTraceRedactionPolicy(policy) {
3480
+ return {
3481
+ ...DEFAULT_TRACE_REDACTION_POLICY,
3482
+ ...policy,
3483
+ sensitiveKeyParts: policy?.sensitiveKeyParts ?? DEFAULT_TRACE_REDACTION_POLICY.sensitiveKeyParts,
3484
+ stringPatterns: policy?.stringPatterns ?? DEFAULT_TRACE_REDACTION_POLICY.stringPatterns
3485
+ };
3486
+ }
3487
+ function redactTraceString(value, policy = DEFAULT_TRACE_REDACTION_POLICY) {
3488
+ const normalizedPolicy = normalizeTraceRedactionPolicy(policy);
3489
+ if (!normalizedPolicy.enabled) {
3490
+ return value;
3491
+ }
3492
+ let redacted = value;
3493
+ for (const { pattern, replacement } of normalizedPolicy.stringPatterns) {
3494
+ const effectiveReplacement = replacement ? replacement.replaceAll(TRACE_REDACTED, normalizedPolicy.replacement) : normalizedPolicy.replacement;
3495
+ redacted = redacted.replace(pattern, effectiveReplacement);
3496
+ }
3497
+ return redacted;
3498
+ }
3499
+
3500
+ // src/github/github-rest.ts
3501
+ function normalizeRepositoryFullName(value) {
3502
+ const trimmed = value?.trim();
3503
+ if (!trimmed || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(trimmed)) return void 0;
3504
+ return trimmed;
3505
+ }
3506
+
3507
+ // src/commands/autoloop-github-app.ts
3508
+ var GITHUB_APP_INSTALLATION_PERMISSIONS = {
3509
+ actions: "read",
3510
+ checks: "read",
3511
+ contents: "write",
3512
+ metadata: "read",
3513
+ pull_requests: "write",
3514
+ statuses: "read"
3515
+ };
3516
+ var DEFAULT_GITHUB_APP_TOKEN_TIMEOUT_MS = 1e4;
3517
+ function isDirectGithubAppKeyAllowed(env = process.env) {
3518
+ return (env["ARCHAL_AUTOLOOP_ALLOW_DIRECT_GITHUB_APP_KEY"] ?? "").trim().toLowerCase() === "true";
3519
+ }
3520
+ async function resolveAutoloopInstallationToken(input, options = {}) {
3521
+ const resolution = await resolveAutoloopInstallationTokenWithDiagnostics(input, options);
3522
+ return resolution?.token;
3523
+ }
3524
+ async function resolveAutoloopInstallationTokenWithDiagnostics(input, options = {}) {
3525
+ const env = options.env ?? process.env;
3526
+ const explicitToken = env["GITHUB_INSTALLATION_TOKEN"]?.trim();
3527
+ if (explicitToken) return { token: explicitToken };
3528
+ const fetchImpl = withGithubAppTokenTimeout(options.fetchImpl ?? fetch, env);
3529
+ const archalToken = options.archalToken ?? env["ARCHAL_TOKEN"]?.trim();
3530
+ const archalBaseUrl = options.archalBaseUrl ?? env["ARCHAL_GITHUB_APP_BASE_URL"]?.trim() ?? env["ARCHAL_AUTH_BASE_URL"]?.trim() ?? env["ARCHAL_API_BASE_URL"]?.trim();
3531
+ const hosted = await resolveArchalGithubAppInstallationTokenWithDiagnostics({
3532
+ repository: input.repository,
3533
+ archalToken,
3534
+ archalBaseUrl,
3535
+ fetchImpl
3536
+ });
3537
+ if (hosted?.token) return hosted;
3538
+ if (isDirectGithubAppKeyAllowed(env)) {
3539
+ const direct = await resolveGithubAppInstallationToken({
3540
+ repository: input.repository,
3541
+ installationId: input.installationId,
3542
+ env,
3543
+ fetchImpl
3544
+ });
3545
+ if (direct?.token) return direct;
3546
+ }
3547
+ return hosted?.failure ? { failure: hosted.failure } : void 0;
3548
+ }
3549
+ async function resolveGithubAppInstallationToken(input) {
3550
+ const repository = normalizeRepositoryFullName(input.repository);
3551
+ if (!repository) return void 0;
3552
+ const env = input.env ?? process.env;
3553
+ const appId = env["ARCHAL_GITHUB_APP_ID"]?.trim();
3554
+ const privateKey = env["ARCHAL_GITHUB_APP_PRIVATE_KEY"]?.trim();
3555
+ if (!appId || !privateKey) return void 0;
3556
+ const installationId = input.installationId?.trim();
3557
+ if (!installationId || !/^\d+$/.test(installationId)) return void 0;
3558
+ const [, repo] = repository.split("/");
3559
+ const fetchImpl = withGithubAppTokenTimeout(input.fetchImpl ?? fetch, env);
3560
+ const jwt = buildGithubAppJwt({ appId, privateKey });
3561
+ const tokenResponse = await fetchImpl(
3562
+ `https://api.github.com/app/installations/${installationId}/access_tokens`,
3563
+ {
3564
+ method: "POST",
3565
+ headers: githubHeaders(jwt, { "content-type": "application/json" }),
3566
+ body: JSON.stringify({
3567
+ repositories: [repo],
3568
+ permissions: GITHUB_APP_INSTALLATION_PERMISSIONS
3569
+ })
3570
+ }
3571
+ );
3572
+ if (!tokenResponse.ok) return void 0;
3573
+ const payload = await tokenResponse.json().catch(() => ({}));
3574
+ const token = String(payload["token"] ?? "").trim();
3575
+ const expiresAt = String(payload["expires_at"] ?? "").trim();
3576
+ return token ? { token, expiresAt: expiresAt || void 0 } : void 0;
3577
+ }
3578
+ async function resolveArchalGithubAppInstallationTokenWithDiagnostics(input) {
3579
+ const repository = normalizeRepositoryFullName(input.repository);
3580
+ if (!repository || !input.archalToken || !input.archalBaseUrl) return void 0;
3581
+ const fetchImpl = withGithubAppTokenTimeout(input.fetchImpl ?? fetch);
3582
+ const response = await fetchImpl(
3583
+ new URL("/api/workspaces/current/integrations/github/installation-token", input.archalBaseUrl),
3584
+ {
3585
+ method: "POST",
3586
+ headers: { authorization: `Bearer ${input.archalToken}`, "content-type": "application/json" },
3587
+ body: JSON.stringify({ repository })
3588
+ }
3589
+ );
3590
+ const payload = await response.json().catch(() => ({}));
3591
+ const token = String(payload["token"] ?? "").trim();
3592
+ const expiresAt = String(payload["expiresAt"] ?? "").trim();
3593
+ if (response.ok && token) {
3594
+ return { token, expiresAt: expiresAt || void 0 };
3595
+ }
3596
+ return {
3597
+ failure: hostedGithubAppTokenFailure(response, payload)
3598
+ };
3599
+ }
3600
+ function withGithubAppTokenTimeout(fetchImpl, env = process.env) {
3601
+ return (async (input, init) => {
3602
+ const timeoutMs = resolveGithubAppTokenTimeoutMs(env);
3603
+ const controller = new AbortController();
3604
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
3605
+ timeout.unref?.();
3606
+ try {
3607
+ return await fetchImpl(input, { ...init, signal: controller.signal });
3608
+ } catch (error) {
3609
+ if (controller.signal.aborted) {
3610
+ throw new Error("autoloop_github_app_token_request_timeout");
3611
+ }
3612
+ throw error;
3613
+ } finally {
3614
+ clearTimeout(timeout);
3615
+ }
3616
+ });
3617
+ }
3618
+ function resolveGithubAppTokenTimeoutMs(env) {
3619
+ const raw = env["ARCHAL_AUTOLOOP_GITHUB_APP_TOKEN_TIMEOUT_MS"]?.trim();
3620
+ if (!raw) return DEFAULT_GITHUB_APP_TOKEN_TIMEOUT_MS;
3621
+ const timeoutMs = Number(raw);
3622
+ return Number.isInteger(timeoutMs) && timeoutMs >= 100 ? timeoutMs : DEFAULT_GITHUB_APP_TOKEN_TIMEOUT_MS;
3623
+ }
3624
+ function githubHeaders(jwt, extra = {}) {
3625
+ return {
3626
+ accept: "application/vnd.github+json",
3627
+ authorization: `Bearer ${jwt}`,
3628
+ "x-github-api-version": "2022-11-28",
3629
+ ...extra
3630
+ };
3631
+ }
3632
+ function hostedGithubAppTokenFailure(response, payload) {
3633
+ const record = isRecord(payload) ? payload : {};
3634
+ const code = safeHostedFailurePart(
3635
+ stringField(record, "error") ?? stringField(record, "code") ?? (response.ok ? "missing_token" : `http_${response.status}`),
3636
+ "unknown"
3637
+ );
3638
+ const message = safeHostedFailurePart(
3639
+ stringField(record, "detail") ?? stringField(record, "message") ?? (response.ok ? "hosted minter response did not include a token" : void 0),
3640
+ ""
3641
+ );
3642
+ return {
3643
+ source: "hosted",
3644
+ code,
3645
+ status: response.status,
3646
+ ...message ? { message } : {}
3647
+ };
3648
+ }
3649
+ function stringField(record, key) {
3650
+ const value = record[key];
3651
+ return typeof value === "string" && value.trim() ? value : void 0;
3652
+ }
3653
+ function safeHostedFailurePart(value, fallback) {
3654
+ const redacted = redactTraceString(value ?? "").replace(/\s+/g, " ").trim();
3655
+ if (!redacted) return fallback;
3656
+ return redacted.length > 220 ? `${redacted.slice(0, 217)}...` : redacted;
3657
+ }
3658
+ function isRecord(value) {
3659
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3660
+ }
3661
+ function buildGithubAppJwt(input) {
3662
+ const now = Math.floor(Date.now() / 1e3);
3663
+ const header = base64UrlJson({ alg: "RS256", typ: "JWT" });
3664
+ const payload = base64UrlJson({
3665
+ iat: now - 60,
3666
+ exp: now + 9 * 60,
3667
+ iss: input.appId
3668
+ });
3669
+ const signingInput = `${header}.${payload}`;
3670
+ const signature = (0, import_node_crypto5.createSign)("RSA-SHA256").update(signingInput).end().sign(normalizePem2(input.privateKey), "base64url");
3671
+ return `${signingInput}.${signature}`;
3672
+ }
3673
+ function base64UrlJson(value) {
3674
+ return Buffer.from(JSON.stringify(value)).toString("base64url");
3675
+ }
3676
+ function normalizePem2(value) {
3677
+ return value.replace(/\\n/g, "\n").replace(/\\\r?\n/g, "\n").replace(/\\/g, "\n");
3678
+ }
3679
+
3680
+ // src/commands/autoloop-fix-pr-quality.ts
3681
+ function assessFixPrPayload(payload, input = {}) {
3682
+ const assessment = assessAutoloopStoredFixPrEvidence(payload, {
3683
+ expectedCommitSha: input.prHeadSha ?? null
3684
+ });
3685
+ return {
3686
+ passed: assessment.passed,
3687
+ reason: assessment.reason,
3688
+ fixQuality: assessment.fixQuality,
3689
+ postFixReproduction: assessment.postFixReproduction,
3690
+ prBodyQuality: prBodyQualityWithIssues(assessment.prBodyQuality)
3691
+ };
3692
+ }
3693
+ function prBodyQualityWithIssues(evidence) {
3694
+ return {
3695
+ ...evidence,
3696
+ issues: evidence.status === "passed" ? [] : [evidence.reason]
3697
+ };
3698
+ }
3699
+
3700
+ // src/commands/autoloop-pr-verification.ts
3701
+ async function verifyFixResult(result, input) {
3702
+ if (!result.prUrl) return result;
3703
+ const pr = parseGithubPrUrl(result.prUrl);
3704
+ if (!pr || `${pr.owner}/${pr.repo}`.toLowerCase() !== input.repositoryFullName.toLowerCase()) {
3705
+ return {
3706
+ ...result,
3707
+ status: "blocked",
3708
+ prUrl: null,
3709
+ latestCheckState: "blocked",
3710
+ blockingReason: "reported_pr_repository_mismatch",
3711
+ summary: `${result.summary} Reported PR URL does not belong to ${input.repositoryFullName}.`
3712
+ };
3713
+ }
3714
+ if (result.status !== "checks_passing") {
3715
+ if (result.status === "pr_open") {
3716
+ const token2 = await resolveVerificationToken(input);
3717
+ const verdict = await confirmPrIsOpen(pr, token2);
3718
+ if (verdict.state === "not_open") {
3719
+ return {
3720
+ ...result,
3721
+ status: "blocked",
3722
+ prUrl: null,
3723
+ latestCheckState: "blocked",
3724
+ blockingReason: "reported_pr_not_found",
3725
+ summary: `${result.summary} Reported open PR could not be confirmed.`
3726
+ };
3727
+ }
3728
+ if (verdict.state === "unverifiable") {
3729
+ return {
3730
+ ...result,
3731
+ status: "pr_open",
3732
+ latestCheckState: "unknown",
3733
+ blockingReason: void 0,
3734
+ summary: `${result.summary} Reported open PR could not be verified yet.`
3735
+ };
3736
+ }
3737
+ const postFixReproduction2 = autoloopPostFixReproductionEvidenceFromPayload(result.payload, {
3738
+ expectedCommitSha: verdict.headSha
3739
+ });
3740
+ if (!postFixReproduction2.passed) {
3741
+ return blockedOpenPrResult(
3742
+ result,
3743
+ postFixReproduction2.reason,
3744
+ `PR not surfaced as ready because post-fix reproduction evidence is insufficient: ${postFixReproduction2.reason}.`
3745
+ );
3746
+ }
3747
+ const mismatch2 = prReferenceMatchFailure(result, input.repositoryFullName, verdict, input);
3748
+ if (mismatch2) {
3749
+ return blockedFixResult(
3750
+ result,
3751
+ mismatch2,
3752
+ `Reported PR repository or branch is not verified: ${mismatch2}.`
3753
+ );
3754
+ }
3755
+ }
3756
+ return result;
3757
+ }
3758
+ const initialPostFixReproduction = autoloopPostFixReproductionEvidenceFromPayload(result.payload);
3759
+ if (!initialPostFixReproduction.passed) {
3760
+ return blockedOpenPrResult(
3761
+ result,
3762
+ initialPostFixReproduction.reason,
3763
+ `Post-fix clone reproduction evidence is insufficient: ${initialPostFixReproduction.reason}.`
3764
+ );
3765
+ }
3766
+ const token = await resolveVerificationToken(input);
3767
+ const checks = token ? await fetchGithubPrChecks(pr, token).catch(() => unverifiedGithubPrChecks()) : unverifiedGithubPrChecks();
3768
+ if (checks.state === "unverified") {
3769
+ return {
3770
+ ...result,
3771
+ status: "pr_open",
3772
+ latestCheckState: "unknown",
3773
+ summary: `${result.summary} PR checks could not be verified yet.`
3774
+ };
3775
+ }
3776
+ if (checks.state === "not_open") {
3777
+ return blockedFixResult(result, "reported_pr_not_found", "Reported PR is not open.");
3778
+ }
3779
+ const postFixReproduction = autoloopPostFixReproductionEvidenceFromPayload(result.payload, {
3780
+ expectedCommitSha: checks.headSha
3781
+ });
3782
+ if (!postFixReproduction.passed) {
3783
+ return blockedOpenPrResult(
3784
+ result,
3785
+ postFixReproduction.reason,
3786
+ `Post-fix clone reproduction evidence is insufficient: ${postFixReproduction.reason}.`
3787
+ );
3788
+ }
3789
+ const mismatch = prReferenceMatchFailure(result, input.repositoryFullName, checks, input);
3790
+ if (mismatch) {
3791
+ return blockedFixResult(
3792
+ result,
3793
+ mismatch,
3794
+ `Reported PR repository or branch is not verified: ${mismatch}.`
3795
+ );
3796
+ }
3797
+ if (checks.blockingReason) {
3798
+ return blockedFixResult(
3799
+ result,
3800
+ checks.blockingReason,
3801
+ `Reported PR required-check protection is not verified: ${checks.blockingReason}.`
3802
+ );
3803
+ }
3804
+ if (checks.passing) return verifiedQualityResult(result, checks);
3805
+ if (checks.state === "no_checks" && localValidationPassed(result.payload)) {
3806
+ const qualityResult = verifiedQualityResult(result, checks, "no_checks");
3807
+ if (qualityResult.status === "blocked") return qualityResult;
3808
+ return {
3809
+ ...qualityResult,
3810
+ status: "checks_passing",
3811
+ latestCheckState: "no_checks",
3812
+ summary: `${result.summary} No remote PR checks are configured; local validation and post-fix clone reproduction are verified.`
3813
+ };
3814
+ }
3815
+ return {
3816
+ ...result,
3817
+ status: "pr_open",
3818
+ latestCheckState: checks.state,
3819
+ summary: `${result.summary} PR checks are not verified green yet.`
3820
+ };
3821
+ }
3822
+ async function verifyOpenFixPrPoll(result, input) {
3823
+ if (result.status !== "pr_open" || !result.prUrl) return result;
3824
+ const pr = parseGithubPrUrl(result.prUrl);
3825
+ if (!pr || `${pr.owner}/${pr.repo}`.toLowerCase() !== input.repositoryFullName.toLowerCase()) {
3826
+ return blockedFixResult(
3827
+ { ...result, prUrl: null },
3828
+ "reported_pr_repository_mismatch",
3829
+ `Reported PR URL does not belong to ${input.repositoryFullName}.`
3830
+ );
3831
+ }
3832
+ const token = await resolveVerificationToken(input);
3833
+ if (!token) return { ...result, latestCheckState: "unknown" };
3834
+ const checks = await fetchGithubPrChecks(pr, token).catch(() => unverifiedGithubPrChecks());
3835
+ if (checks.state === "unverified") return { ...result, latestCheckState: "unknown" };
3836
+ if (checks.state === "not_open") {
3837
+ return blockedFixResult(result, "reported_pr_not_found", "Reported PR is not open.");
3838
+ }
3839
+ const postFixReproduction = autoloopPostFixReproductionEvidenceFromPayload(result.payload, {
3840
+ expectedCommitSha: checks.headSha
3841
+ });
3842
+ if (!postFixReproduction.passed) {
3843
+ return blockedOpenPrResult(
3844
+ result,
3845
+ postFixReproduction.reason,
3846
+ `Open PR cannot become ready because post-fix clone reproduction evidence is insufficient: ${postFixReproduction.reason}.`
3847
+ );
3848
+ }
3849
+ const branchReason = prReferenceMatchFailure(result, input.repositoryFullName, checks, input);
3850
+ if (branchReason) {
3851
+ return blockedFixResult(
3852
+ result,
3853
+ branchReason,
3854
+ `Reported PR repository or branch is not verified: ${branchReason}.`
3855
+ );
3856
+ }
3857
+ if (checks.blockingReason) {
3858
+ return blockedFixResult(
3859
+ result,
3860
+ checks.blockingReason,
3861
+ `Reported PR required-check protection is not verified: ${checks.blockingReason}.`
3862
+ );
3863
+ }
3864
+ if (checks.passing) {
3865
+ const qualityResult = verifiedQualityResult(result, checks);
3866
+ if (qualityResult.status === "blocked") return qualityResult;
3867
+ return {
3868
+ ...qualityResult,
3869
+ status: "checks_passing",
3870
+ latestCheckState: "passing",
3871
+ summary: `${result.summary} PR checks are verified green.`
3872
+ };
3873
+ }
3874
+ if (checks.state === "no_checks" && localValidationPassed(result.payload)) {
3875
+ const qualityResult = verifiedQualityResult(result, checks, "no_checks");
3876
+ if (qualityResult.status === "blocked") return qualityResult;
3877
+ return {
3878
+ ...qualityResult,
3879
+ status: "checks_passing",
3880
+ latestCheckState: "no_checks",
3881
+ summary: `${result.summary} No remote PR checks are configured; local validation and post-fix clone reproduction are verified.`
3882
+ };
3883
+ }
3884
+ return {
3885
+ ...result,
3886
+ latestCheckState: checks.state,
3887
+ summary: `${result.summary} PR checks are not verified green yet.`
3888
+ };
3889
+ }
3890
+ function verifiedQualityResult(result, checks, latestCheckState = "passing") {
3891
+ const quality = assessFixPrPayload(result.payload, { prHeadSha: checks.headSha });
3892
+ if (quality.passed) return { ...result, latestCheckState };
3893
+ return blockedFixResult(
3894
+ result,
3895
+ quality.reason,
3896
+ `Generated PR evidence is insufficient: ${quality.reason}.`
3897
+ );
3898
+ }
3899
+ function blockedOpenPrResult(result, blockingReason, summary) {
3900
+ return {
3901
+ ...result,
3902
+ status: "blocked",
3903
+ latestCheckState: "blocked",
3904
+ blockingReason,
3905
+ summary: `${result.summary} ${summary}`
3906
+ };
3907
+ }
3908
+ function localValidationPassed(payload) {
3909
+ return isRecord2(payload) && payload["localValidationStatus"] === "passed";
3910
+ }
3911
+ async function resolveVerificationToken(input) {
3912
+ if (input.githubToken?.trim()) return input.githubToken.trim();
3913
+ const token = await resolveAutoloopInstallationToken(
3914
+ { repository: input.repositoryFullName, installationId: input.githubInstallationId },
3915
+ {
3916
+ archalToken: process.env["ARCHAL_TOKEN"] ?? getCredentials2()?.token,
3917
+ archalBaseUrl: input.authBaseUrl
3918
+ }
3919
+ );
3920
+ return token ?? null;
3921
+ }
3922
+ async function confirmPrIsOpen(pr, token) {
3923
+ if (!token) return unverifiedGithubPrOpenResult();
3924
+ try {
3925
+ const response = await fetch(
3926
+ `https://api.github.com/repos/${pr.owner}/${pr.repo}/pulls/${pr.number}`,
3927
+ {
3928
+ headers: {
3929
+ authorization: `Bearer ${token}`,
3930
+ accept: "application/vnd.github+json",
3931
+ "x-github-api-version": "2022-11-28"
3932
+ }
3933
+ }
3934
+ );
3935
+ if (response.status === 404)
3936
+ return notOpenGithubPrOpenResult();
3937
+ if (!response.ok) return unverifiedGithubPrOpenResult();
3938
+ const body = await response.json().catch(() => ({}));
3939
+ const head = isRecord2(body["head"]) ? body["head"] : {};
3940
+ const headRepo = isRecord2(head["repo"]) ? head["repo"] : {};
3941
+ const base = isRecord2(body["base"]) ? body["base"] : {};
3942
+ const baseRepo = isRecord2(base["repo"]) ? base["repo"] : {};
3943
+ return {
3944
+ state: body["state"] === "open" ? "open" : "not_open",
3945
+ headRefName: typeof head["ref"] === "string" ? head["ref"] : null,
3946
+ headSha: typeof head["sha"] === "string" ? head["sha"] : null,
3947
+ headRepoFullName: typeof headRepo["full_name"] === "string" ? headRepo["full_name"] : null,
3948
+ baseRefName: typeof base["ref"] === "string" ? base["ref"] : null,
3949
+ baseRepoFullName: typeof baseRepo["full_name"] === "string" ? baseRepo["full_name"] : null
3950
+ };
3951
+ } catch {
3952
+ return unverifiedGithubPrOpenResult();
3953
+ }
3954
+ }
3955
+ function unverifiedGithubPrOpenResult() {
3956
+ return {
3957
+ state: "unverifiable",
3958
+ headRefName: null,
3959
+ headSha: null,
3960
+ headRepoFullName: null,
3961
+ baseRefName: null,
3962
+ baseRepoFullName: null
3963
+ };
3964
+ }
3965
+ function notOpenGithubPrOpenResult() {
3966
+ return {
3967
+ state: "not_open",
3968
+ headRefName: null,
3969
+ headSha: null,
3970
+ headRepoFullName: null,
3971
+ baseRefName: null,
3972
+ baseRepoFullName: null
3973
+ };
3974
+ }
3975
+ function unverifiedGithubPrChecks() {
3976
+ return {
3977
+ passing: false,
3978
+ state: "unverified",
3979
+ headSha: null,
3980
+ headRefName: null,
3981
+ headRepoFullName: null,
3982
+ baseRefName: null,
3983
+ baseRepoFullName: null
3984
+ };
3985
+ }
3986
+ function parseGithubPrUrl(prUrl) {
3987
+ const match = prUrl.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)$/);
3988
+ if (!match) return null;
3989
+ const owner = match[1];
3990
+ const repo = match[2];
3991
+ const number = match[3];
3992
+ if (!owner || !repo || !number) return null;
3993
+ return { owner, repo, number };
3994
+ }
3995
+ async function fetchGithubPrChecks(pr, token) {
3996
+ const headers = {
3997
+ authorization: `Bearer ${token}`,
3998
+ accept: "application/vnd.github+json",
3999
+ "x-github-api-version": "2022-11-28"
4000
+ };
4001
+ const pull = await githubJson(
4002
+ `https://api.github.com/repos/${pr.owner}/${pr.repo}/pulls/${pr.number}`,
4003
+ headers
4004
+ );
4005
+ const head = isRecord2(pull["head"]) ? pull["head"] : {};
4006
+ const headRepo = isRecord2(head["repo"]) ? head["repo"] : {};
4007
+ const baseRef = isRecord2(pull["base"]) ? pull["base"] : {};
4008
+ const baseRepo = isRecord2(baseRef["repo"]) ? baseRef["repo"] : {};
4009
+ const sha = typeof head["sha"] === "string" ? head["sha"] : null;
4010
+ const headRefName = typeof head["ref"] === "string" ? head["ref"] : null;
4011
+ const headRepoFullName = typeof headRepo["full_name"] === "string" ? headRepo["full_name"] : null;
4012
+ const base = {
4013
+ headSha: sha,
4014
+ headRefName,
4015
+ headRepoFullName,
4016
+ baseRefName: typeof baseRef["ref"] === "string" ? baseRef["ref"] : null,
4017
+ baseRepoFullName: typeof baseRepo["full_name"] === "string" ? baseRepo["full_name"] : null
4018
+ };
4019
+ if (pull["state"] !== "open") return { passing: false, state: "not_open", ...base };
4020
+ if (!sha) return { passing: false, state: "unknown", ...base };
4021
+ const status = await githubJson(
4022
+ `https://api.github.com/repos/${pr.owner}/${pr.repo}/commits/${sha}/status`,
4023
+ headers
4024
+ );
4025
+ const runs = await fetchGithubCheckRuns(
4026
+ `https://api.github.com/repos/${pr.owner}/${pr.repo}/commits/${sha}/check-runs`,
4027
+ headers
4028
+ );
4029
+ const state = githubCommitStatusState(status["state"]);
4030
+ const statuses = Array.isArray(status["statuses"]) ? status["statuses"] : [];
4031
+ const hasSignal = runs.length > 0 || statuses.length > 0;
4032
+ if (!hasSignal) return { passing: false, state: "no_checks", ...base };
4033
+ if (state === "failure" || state === "error" || runs.some(
4034
+ (run) => ["failure", "timed_out", "cancelled", "action_required"].includes(String(run["conclusion"]))
4035
+ )) {
4036
+ return { passing: false, state: "failing", ...base };
4037
+ }
4038
+ if (statuses.length > 0 && state === "pending" || runs.some((run) => run["status"] !== void 0 && String(run["status"]) !== "completed")) {
4039
+ return { passing: false, state: "pending", ...base };
4040
+ }
4041
+ const statusesPass = statuses.length === 0 || state === "success";
4042
+ const statusSuccessSignal = statuses.length > 0 && state === "success";
4043
+ const checkRunsPass = runs.length === 0 || runs.every((run) => ["success", "skipped", "neutral"].includes(String(run["conclusion"])));
4044
+ const checkRunSuccessSignal = runs.some((run) => String(run["conclusion"]) === "success");
4045
+ if (hasSignal && statusesPass && checkRunsPass && (statusSuccessSignal || checkRunSuccessSignal)) {
4046
+ const requiredChecks = await fetchGithubRequiredCheckContexts({
4047
+ owner: pr.owner,
4048
+ repo: pr.repo,
4049
+ baseRefName: base.baseRefName,
4050
+ token
4051
+ });
4052
+ const requiredBlocker = evaluateRequiredCheckProtection(requiredChecks, status, runs);
4053
+ if (requiredBlocker) {
4054
+ return { passing: false, state: "pending", blockingReason: requiredBlocker, ...base };
4055
+ }
4056
+ return { passing: true, state: "passing", ...base };
4057
+ }
4058
+ if (state === "unknown") return { passing: false, state: "unknown", ...base };
4059
+ return { passing: false, state: "pending", ...base };
4060
+ }
4061
+ function prReferenceMatchFailure(result, repositoryFullName, checks, input) {
4062
+ const branchName = result.branchName ?? payloadString(result.payload, "branchName", "branch_name", "branch");
4063
+ if (!branchName) return "reported_pr_branch_missing";
4064
+ if (!checks.headRefName) return "reported_pr_branch_missing";
4065
+ if (checks.headRefName !== branchName) return "reported_pr_branch_mismatch";
4066
+ if (!checks.headRepoFullName) return "reported_pr_head_repository_missing";
4067
+ if (checks.headRepoFullName.toLowerCase() !== repositoryFullName.toLowerCase()) {
4068
+ return "reported_pr_head_repository_mismatch";
4069
+ }
4070
+ if (!checks.baseRepoFullName) return "reported_pr_base_repository_missing";
4071
+ if (checks.baseRepoFullName.toLowerCase() !== repositoryFullName.toLowerCase()) {
4072
+ return "reported_pr_base_repository_mismatch";
4073
+ }
4074
+ const expectedBaseBranch = input.expectedBaseBranch ?? payloadString(result.payload, "baseBranch", "base_branch");
4075
+ if (!expectedBaseBranch) return "reported_pr_base_branch_missing";
4076
+ if (!checks.baseRefName) return "reported_pr_base_branch_missing";
4077
+ if (checks.baseRefName !== expectedBaseBranch) return "reported_pr_base_branch_mismatch";
4078
+ return null;
4079
+ }
4080
+ function blockedFixResult(result, reason, message) {
4081
+ return {
4082
+ ...result,
4083
+ status: "blocked",
4084
+ latestCheckState: "blocked",
4085
+ blockingReason: reason,
4086
+ summary: `${result.summary} ${message}`
4087
+ };
4088
+ }
4089
+ function githubCommitStatusState(value) {
4090
+ return value === "success" || value === "failure" || value === "error" || value === "pending" ? value : "unknown";
4091
+ }
4092
+ async function githubJson(url, headers) {
4093
+ const response = await fetch(url, { headers });
4094
+ if (!response.ok) throw new Error(`github_api_${response.status}`);
4095
+ return await response.json();
4096
+ }
4097
+ async function fetchGithubRequiredCheckContexts(input) {
4098
+ if (!input.baseRefName) {
4099
+ return { requiredContexts: [], blockingReason: "reported_pr_base_branch_missing" };
4100
+ }
4101
+ const source = { ...input, baseRefName: input.baseRefName };
4102
+ const branchProtection = await fetchGithubBranchProtectionRequiredCheckContexts(source).catch(
4103
+ () => ({
4104
+ requiredContexts: [],
4105
+ blockingReason: "reported_pr_required_checks_unverified"
4106
+ })
4107
+ );
4108
+ const ruleset = await fetchGithubRulesetRequiredCheckContexts(source).catch(() => ({
4109
+ requiredContexts: [],
4110
+ blockingReason: "reported_pr_required_checks_unverified"
4111
+ }));
4112
+ if (branchProtection.blockingReason === "reported_pr_required_checks_unverified") {
4113
+ return branchProtection;
4114
+ }
4115
+ if (ruleset.blockingReason === "reported_pr_required_checks_unverified") {
4116
+ return ruleset;
4117
+ }
4118
+ const requiredContexts = [.../* @__PURE__ */ new Set([...branchProtection.requiredContexts, ...ruleset.requiredContexts])];
4119
+ if (requiredContexts.length > 0) return { requiredContexts };
4120
+ return { requiredContexts };
4121
+ }
4122
+ async function fetchGithubBranchProtectionRequiredCheckContexts(input) {
4123
+ const response = await fetch("https://api.github.com/graphql", {
4124
+ method: "POST",
4125
+ headers: {
4126
+ authorization: `Bearer ${input.token}`,
4127
+ accept: "application/vnd.github+json",
4128
+ "content-type": "application/json"
4129
+ },
4130
+ body: JSON.stringify({
4131
+ query: `
4132
+ query ArchalRequiredChecks($owner: String!, $repo: String!, $ref: String!) {
4133
+ repository(owner: $owner, name: $repo) {
4134
+ ref(qualifiedName: $ref) {
4135
+ branchProtectionRule {
4136
+ requiresStatusChecks
4137
+ requiredStatusCheckContexts
4138
+ requiredStatusChecks {
4139
+ context
4140
+ }
4141
+ }
4142
+ }
4143
+ }
4144
+ }
4145
+ `,
4146
+ variables: {
4147
+ owner: input.owner,
4148
+ repo: input.repo,
4149
+ ref: input.baseRefName
4150
+ }
4151
+ })
4152
+ });
4153
+ if (!response.ok) throw new Error(`github_graphql_${response.status}`);
4154
+ const body = await response.json();
4155
+ if (Array.isArray(body["errors"]) && body["errors"].length > 0) {
4156
+ throw new Error("github_graphql_errors");
4157
+ }
4158
+ const data = isRecord2(body["data"]) ? body["data"] : {};
4159
+ const repository = isRecord2(data["repository"]) ? data["repository"] : {};
4160
+ const ref = isRecord2(repository["ref"]) ? repository["ref"] : {};
4161
+ const rule = isRecord2(ref["branchProtectionRule"]) ? ref["branchProtectionRule"] : null;
4162
+ if (!rule) {
4163
+ return { requiredContexts: [], blockingReason: "reported_pr_branch_protection_missing" };
4164
+ }
4165
+ if (rule["requiresStatusChecks"] !== true) {
4166
+ return { requiredContexts: [], blockingReason: "reported_pr_required_checks_missing" };
4167
+ }
4168
+ const contexts = /* @__PURE__ */ new Set();
4169
+ const legacyContexts = rule["requiredStatusCheckContexts"];
4170
+ if (Array.isArray(legacyContexts)) {
4171
+ for (const context of legacyContexts) {
4172
+ if (typeof context === "string" && context.trim()) contexts.add(context.trim());
4173
+ }
4174
+ } else if (legacyContexts !== void 0) {
4175
+ return { requiredContexts: [], blockingReason: "reported_pr_required_checks_unverified" };
4176
+ }
4177
+ const requiredStatusChecks = rule["requiredStatusChecks"];
4178
+ const nodes = Array.isArray(requiredStatusChecks) ? requiredStatusChecks : isRecord2(requiredStatusChecks) && Array.isArray(requiredStatusChecks["nodes"]) ? requiredStatusChecks["nodes"] : requiredStatusChecks === void 0 ? [] : null;
4179
+ if (!nodes) {
4180
+ return { requiredContexts: [], blockingReason: "reported_pr_required_checks_unverified" };
4181
+ }
4182
+ for (const node of nodes) {
4183
+ if (!isRecord2(node)) continue;
4184
+ const context = node["context"];
4185
+ if (typeof context === "string" && context.trim()) contexts.add(context.trim());
4186
+ }
4187
+ const requiredContexts = [...contexts];
4188
+ if (requiredContexts.length === 0) {
4189
+ return { requiredContexts, blockingReason: "reported_pr_required_checks_missing" };
4190
+ }
4191
+ return { requiredContexts };
4192
+ }
4193
+ async function fetchGithubRulesetRequiredCheckContexts(input) {
4194
+ const branch = encodeURIComponent(input.baseRefName);
4195
+ const response = await fetch(
4196
+ `https://api.github.com/repos/${input.owner}/${input.repo}/rules/branches/${branch}?per_page=100`,
4197
+ {
4198
+ headers: {
4199
+ authorization: `Bearer ${input.token}`,
4200
+ accept: "application/vnd.github+json",
4201
+ "x-github-api-version": "2022-11-28"
4202
+ }
4203
+ }
4204
+ );
4205
+ if (response.status === 404) return { requiredContexts: [] };
4206
+ if (!response.ok) {
4207
+ return { requiredContexts: [], blockingReason: "reported_pr_required_checks_unverified" };
4208
+ }
4209
+ const body = await response.json().catch(() => null);
4210
+ if (!Array.isArray(body)) {
4211
+ return { requiredContexts: [], blockingReason: "reported_pr_required_checks_unverified" };
4212
+ }
4213
+ const contexts = /* @__PURE__ */ new Set();
4214
+ for (const item of body) {
4215
+ if (!isRecord2(item)) continue;
4216
+ const type = typeof item["type"] === "string" ? item["type"] : "";
4217
+ if (type === "required_workflows") continue;
4218
+ if (type !== "required_status_checks") continue;
4219
+ const parameters = isRecord2(item["parameters"]) ? item["parameters"] : {};
4220
+ const requiredStatusChecks = parameters["required_status_checks"] ?? parameters["requiredStatusChecks"];
4221
+ if (!Array.isArray(requiredStatusChecks)) {
4222
+ return { requiredContexts: [], blockingReason: "reported_pr_required_checks_unverified" };
4223
+ }
4224
+ for (const check of requiredStatusChecks) {
4225
+ if (typeof check === "string" && check.trim()) {
4226
+ contexts.add(check.trim());
4227
+ } else if (isRecord2(check)) {
4228
+ const context = check["context"];
4229
+ if (typeof context === "string" && context.trim()) contexts.add(context.trim());
4230
+ }
4231
+ }
4232
+ }
4233
+ return { requiredContexts: [...contexts] };
4234
+ }
4235
+ function evaluateRequiredCheckProtection(protection, status, runs) {
4236
+ if (protection.blockingReason) return protection.blockingReason;
4237
+ const required = protection.requiredContexts.map((context) => context.toLowerCase());
4238
+ const seen = /* @__PURE__ */ new Set();
4239
+ const statuses = Array.isArray(status["statuses"]) ? status["statuses"] : [];
4240
+ for (const item of statuses) {
4241
+ if (!isRecord2(item)) continue;
4242
+ const context = item["context"];
4243
+ if (typeof context !== "string" || !context.trim()) continue;
4244
+ seen.add(context.trim().toLowerCase());
4245
+ }
4246
+ for (const run of runs) {
4247
+ const name = run["name"];
4248
+ if (typeof name !== "string" || !name.trim()) continue;
4249
+ seen.add(name.trim().toLowerCase());
4250
+ }
4251
+ return required.every((context) => seen.has(context)) ? null : "reported_pr_required_checks_unverified";
4252
+ }
4253
+ async function fetchGithubCheckRuns(url, headers) {
4254
+ const runs = [];
4255
+ let nextUrl = url;
4256
+ for (let page = 0; nextUrl && page < 20; page += 1) {
4257
+ const response = await fetch(nextUrl, { headers });
4258
+ if (!response.ok) throw new Error(`github_api_${response.status}`);
4259
+ const body = await response.json();
4260
+ if (Array.isArray(body["check_runs"])) {
4261
+ runs.push(
4262
+ ...body["check_runs"].filter((run) => isRecord2(run))
4263
+ );
4264
+ }
4265
+ nextUrl = parseGithubNextLink(response.headers.get("link"));
4266
+ }
4267
+ if (nextUrl) throw new Error("github_check_runs_page_limit");
4268
+ return runs;
4269
+ }
4270
+ function parseGithubNextLink(linkHeader) {
4271
+ if (!linkHeader) return null;
4272
+ for (const part of linkHeader.split(",")) {
4273
+ const match = part.match(/<([^>]+)>;\s*rel="next"/);
4274
+ if (!match?.[1]) continue;
4275
+ try {
4276
+ const url = new URL(match[1]);
4277
+ return url.hostname === "api.github.com" ? url.toString() : null;
4278
+ } catch {
4279
+ return null;
4280
+ }
4281
+ }
4282
+ return null;
4283
+ }
4284
+ function isRecord2(value) {
4285
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4286
+ }
4287
+ function payloadString(payload, ...keys) {
4288
+ if (!isRecord2(payload)) return null;
4289
+ for (const key of keys) {
4290
+ const value = payload[key];
4291
+ if (typeof value === "string" && value.trim().length > 0 && value.trim() === value)
4292
+ return value;
4293
+ }
4294
+ return null;
4295
+ }
4296
+ // Annotate the CommonJS export names for ESM import in node:
4297
+ 0 && (module.exports = {
4298
+ verifyFixResult,
4299
+ verifyOpenFixPrPoll
4300
+ });
4301
+ /*! Bundled license information:
4302
+
4303
+ @posthog/core/dist/vendor/uuidv7.mjs:
4304
+ (*! For license information please see uuidv7.mjs.LICENSE.txt *)
4305
+ (**
4306
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
4307
+ *
4308
+ * @license Apache-2.0
4309
+ * @copyright 2021-2023 LiosK
4310
+ * @packageDocumentation
4311
+ *)
4312
+ */