@ever-works/make-plugin 1.0.0 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,3451 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ MakePlugin: () => MakePlugin,
24
+ default: () => make_plugin_default
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // ../../../node_modules/.pnpm/@ever-co+connect-contracts@1.0.0-rc.2/node_modules/@ever-co/connect-contracts/dist/index.js
29
+ var CONSTANTS = {
30
+ "$comment": "Wire constants of the Ever Platform modules. tools/split-integrations.mjs refreshes the fields read from the contract (contracts_version, code patterns, install_sources, products, stats_headers, feed_event_types, integration_keys, root_keys); every other value is a default a product may override by its own configuration.",
31
+ "contracts_version": "1.0.0-rc.2",
32
+ "connect_code_pattern": "^EVC(-[0-9A-HJKMNP-TV-Za-hj-kmnp-tv-z]{4}){3}$",
33
+ "link_code_pattern": "^EVL(-[0-9A-HJKMNP-TV-Za-hj-kmnp-tv-z]{4}){3}$",
34
+ "install_sources": "^(cloud|self-hosted|ever\\.sh|works_app|desktop|partner:[a-z0-9-]{2,32})$",
35
+ "products": [
36
+ "gauzy",
37
+ "teams",
38
+ "works",
39
+ "rec",
40
+ "traduora",
41
+ "demand"
42
+ ],
43
+ "instance_kinds": [
44
+ "cloud",
45
+ "self_hosted",
46
+ "works_app"
47
+ ],
48
+ "instance_token_prefix": "evit_",
49
+ "entitlement_typ": "ever-entitlement+jwt",
50
+ "intent_typ": "ever-intent+jwt",
51
+ "assertion_typ": "ever-assertion+jwt",
52
+ "key_manifest_typ": "ever-key-manifest+jwt",
53
+ "stats_link_typ": "ever-stats-link+jwt",
54
+ "client_assertion_typ": "JWT",
55
+ "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
56
+ "entitlement_aud": "ever-connect",
57
+ "stats_headers": {
58
+ "key": "Ever-Stats-Key",
59
+ "signature": "Ever-Stats-Signature",
60
+ "key_id": "Ever-Stats-Key-Id"
61
+ },
62
+ "stats_signature_prefix": "ed25519=",
63
+ "feed_event_types": [
64
+ "ever.consent.consent.granted",
65
+ "ever.consent.consent.revoked",
66
+ "ever.consent.integration.disabled",
67
+ "ever.consent.integration.enabled",
68
+ "ever.consent.integration.scope_bumped",
69
+ "ever.entitlements.entitlement.issued",
70
+ "ever.entitlements.entitlement.revoked",
71
+ "ever.entitlements.usage.limit_reached",
72
+ "ever.registry.instance.approved",
73
+ "ever.registry.instance.connected",
74
+ "ever.registry.instance.disconnected",
75
+ "ever.registry.instance.key_rotated",
76
+ "ever.registry.instance.revoked",
77
+ "ever.registry.instance.seen",
78
+ "ever.registry.managed_operation.requested",
79
+ "ever.registry.managed_operation.state_changed",
80
+ "ever.registry.membership.created",
81
+ "ever.registry.membership.removed",
82
+ "ever.registry.membership.role_changed",
83
+ "ever.registry.person.deletion_requested",
84
+ "ever.registry.person.export_requested",
85
+ "ever.registry.tenant_link.created",
86
+ "ever.registry.tenant_link.orphaned",
87
+ "ever.registry.tenant_link.resumed",
88
+ "ever.registry.tenant_link.suspended",
89
+ "ever.registry.tenant_link.unlinked"
90
+ ],
91
+ "integration_keys": [
92
+ "instance_url",
93
+ "stats_link",
94
+ "ever_id_login",
95
+ "counterparty_lookup",
96
+ "counterparty_discoverable",
97
+ "profile_import",
98
+ "usage_reporting",
99
+ "app_sync",
100
+ "billing_link",
101
+ "webhooks",
102
+ "managed_operations",
103
+ "provider_access",
104
+ "marketplace_installs"
105
+ ],
106
+ "key_manifest_path": "/.well-known/ever-keys.json",
107
+ "assertion_audience_path": "/v1/instances/token",
108
+ "assertion_max_ttl_s": 300,
109
+ "assertion_max_skew_s": 300,
110
+ "token_ttl_s": 3600,
111
+ "token_refresh_after_s": 3e3,
112
+ "key_rotation_overlap_s": 604800,
113
+ "entitlement": {
114
+ "validity_s": 604800,
115
+ "refresh_after_s": 21600,
116
+ "grace_s": 2592e3,
117
+ "max_reads_per_hour": 6
118
+ },
119
+ "key_manifest": {
120
+ "refresh_s": 86400,
121
+ "unknown_kid_refresh_min_s": 600,
122
+ "lifetime_s": 2592e3
123
+ },
124
+ "heartbeat_interval_s": 86400,
125
+ "heartbeat_after_boot_max_s": 300,
126
+ "heartbeat_min_interval_s": 60,
127
+ "feed": {
128
+ "wait_s": 25,
129
+ "interval_fallback_s": 900,
130
+ "page_limit": 50
131
+ },
132
+ "stats": {
133
+ "send_interval_s": 86400,
134
+ "min_interval_s": 3600,
135
+ "max_bytes": 16384,
136
+ "final_resend_days": [
137
+ 1,
138
+ 2,
139
+ 3
140
+ ],
141
+ "reports_per_day": 24
142
+ },
143
+ "lookup": {
144
+ "normalization_version": 1,
145
+ "max_hashes_per_query": 100,
146
+ "cache_positive_s": 86400,
147
+ "cache_negative_s": 3600,
148
+ "salt_cache_s": 86400
149
+ },
150
+ "mirror": {
151
+ "max_bytes": 4194304,
152
+ "interval_s": 30
153
+ },
154
+ "step_up_max_age_s": 300,
155
+ "stats_link_statement_max_age_s": 600,
156
+ "timeouts_ms": {
157
+ "read": 6e3,
158
+ "write": 1e4
159
+ },
160
+ "user_agent_pattern": "ever-connect-sdk/<sdk version> (<product>/<product version>)",
161
+ "root_keys": [
162
+ {
163
+ "kid": "ever-202610-0d77",
164
+ "iss": "https://api-dev.ever.co",
165
+ "kty": "OKP",
166
+ "crv": "Ed25519",
167
+ "x": "cgULEqOov0n4s9I8luZboIgJp9mIGusmsSdSL4oCjKk",
168
+ "use": "sig",
169
+ "alg": "EdDSA"
170
+ },
171
+ {
172
+ "kid": "ever-202610-8704",
173
+ "iss": "https://api-stage.ever.co",
174
+ "kty": "OKP",
175
+ "crv": "Ed25519",
176
+ "x": "Ync-MW21JL72GOiS-RVrlvS3gyFH5Krh5f6I66jw1Qc",
177
+ "use": "sig",
178
+ "alg": "EdDSA"
179
+ }
180
+ ],
181
+ "root_keys_file_env": "EVER_PLATFORM_ROOT_KEYS_FILE",
182
+ "root_keys_file_hosts": [
183
+ "localhost",
184
+ "127.0.0.0/8",
185
+ "::1",
186
+ "10.0.0.0/8",
187
+ "172.16.0.0/12",
188
+ "192.168.0.0/16",
189
+ "*.localhost"
190
+ ]
191
+ };
192
+ var FEED_EVENT_TYPES = CONSTANTS.feed_event_types;
193
+ var PROBLEM_CODES = [
194
+ "validation_failed",
195
+ "not_found",
196
+ "unauthorized",
197
+ "forbidden_role",
198
+ "forbidden_scope",
199
+ "ambiguous_credentials",
200
+ "credential_revoked",
201
+ "instance_disconnected",
202
+ "instance_pending_approval",
203
+ "not_connection_owner",
204
+ "integration_disabled",
205
+ "integration_revoked",
206
+ "denied_by_policy",
207
+ "integration_not_available",
208
+ "entitlement_required",
209
+ "tier_required",
210
+ "limit_exceeded",
211
+ "rate_limited",
212
+ "idempotency_mismatch",
213
+ "idempotency_in_progress",
214
+ "stale_version",
215
+ "module_disabled",
216
+ "handle_taken",
217
+ "handle_reserved",
218
+ "handle_retired",
219
+ "handle_invalid",
220
+ "handle_held",
221
+ "handle_held_by_you",
222
+ "code_invalid",
223
+ "code_expired",
224
+ "product_mismatch",
225
+ "product_not_supported",
226
+ "key_mismatch",
227
+ "signature_invalid",
228
+ "unlinked_org",
229
+ "schema_violation",
230
+ "mirror_owned_field",
231
+ "illegal_transition",
232
+ "already_exists",
233
+ "already_completed",
234
+ "billing_active",
235
+ "sso_required",
236
+ "reauth_required",
237
+ "session_required",
238
+ "step_up_required",
239
+ "session_bound",
240
+ "authorization_pending",
241
+ "slow_down",
242
+ "expired_token",
243
+ "already_connected",
244
+ "already_linked",
245
+ "already_claimed",
246
+ "invalid_client",
247
+ "public_jwk_invalid",
248
+ "identifier_claimed",
249
+ "salt_version_unknown",
250
+ "salt_version_retired",
251
+ "hashes_invalid",
252
+ "lookup_key_required",
253
+ "required_component",
254
+ "resync_required",
255
+ "last_owner",
256
+ "last_auth_method",
257
+ "instances_linked",
258
+ "install_in_progress",
259
+ "slug_reserved",
260
+ "checklist_incomplete",
261
+ "scope_version_outdated",
262
+ "method_not_allowed",
263
+ "payload_too_large",
264
+ "unsupported_media_type",
265
+ "gone",
266
+ "unavailable",
267
+ "upstream",
268
+ "database_absent",
269
+ "database_unreachable",
270
+ "topic_private",
271
+ "keys_unavailable",
272
+ "internal_error"
273
+ ];
274
+ var CODES = new Set(PROBLEM_CODES);
275
+
276
+ // ../../contracts/dist/index.js
277
+ var USER_SELECTABLE_WORK_KINDS = [
278
+ "website",
279
+ "landing-page",
280
+ "blog",
281
+ "directory",
282
+ "awesome-repo",
283
+ "repo",
284
+ "app"
285
+ ];
286
+ var WORK_KINDS = [...USER_SELECTABLE_WORK_KINDS, "company", "campaign", "default"];
287
+ var WORK_KIND_SET = new Set(WORK_KINDS);
288
+ var GOAL_KINDS = ["metric", "delivery"];
289
+ var GOAL_KIND_SET = new Set(GOAL_KINDS);
290
+ var APP_DEPENDENCY_BACKUP_OVERDUE_MS = 26 * 36e5;
291
+ var APP_DEPENDENCY_MANAGED = {
292
+ pgRoleConnectionLimit: 20,
293
+ pgDatabaseConnectionLimit: 25,
294
+ pgStatementTimeoutMs: 6e4,
295
+ pgIdleInTransactionTimeoutMs: 6e4,
296
+ bucketQuotaGiB: 10,
297
+ redisMaxMemoryMiB: 256,
298
+ backupMaxAgeMs: 864e5
299
+ };
300
+ var APP_ENV_VALIDATION_REFUSAL_CODES = [
301
+ "invalidName",
302
+ "reservedName",
303
+ "valueTooLarge",
304
+ "controlCharacter",
305
+ "lengthMismatch",
306
+ "tooShort",
307
+ "tooLong",
308
+ "patternMismatch"
309
+ ];
310
+ var APP_ENV_API_ERROR_CODES = [
311
+ "generatedValueUseRotate",
312
+ "neverRotateNotAcknowledged",
313
+ "rotateConfirmationMismatch",
314
+ "secureStorageUnavailable",
315
+ "tooManyValues",
316
+ "valuesTooLarge",
317
+ "malformedLine",
318
+ "rotateRateLimited"
319
+ ];
320
+ var APP_ENV_ERROR_CODES = [...APP_ENV_VALIDATION_REFUSAL_CODES, ...APP_ENV_API_ERROR_CODES];
321
+ var APP_LAUNCHER_CLIENT_CACHE_MS = 5 * 6e4;
322
+ var MANAGED_HOSTING_REASONS = [
323
+ "licenseNotGreen",
324
+ "upstreamAgreementMissing",
325
+ "entryDisallows",
326
+ "blueprintNotVerified",
327
+ "managedTierDisabled"
328
+ ];
329
+ var MANAGED_HOSTING_AVAILABILITIES = ["available", ...MANAGED_HOSTING_REASONS];
330
+ var APP_PRIVATE_COPY_MAX_SIZE_KB = 512e3;
331
+ var APP_DEPLOY_MAX_DURATION_S = 7200;
332
+ var APP_DEPLOY_LOCK_STALE_S = APP_DEPLOY_MAX_DURATION_S + 60;
333
+ var APPS_CATALOG_LAST_GOOD_REGISTRY_MS = 7 * 864e5;
334
+ var APP_REPOSITORY_STAGE_LIMITS = {
335
+ "private-copy": {
336
+ maxSizeKb: APP_PRIVATE_COPY_MAX_SIZE_KB,
337
+ fetchesLfs: false,
338
+ refusalCodes: ["too_large_for_private_copy", "uses_lfs"]
339
+ },
340
+ provisioning: {
341
+ maxSizeKb: 3 * 1024 * 1024,
342
+ refusalCodes: ["repository-too-large"]
343
+ },
344
+ build: {
345
+ refusalCodes: []
346
+ },
347
+ sandbox: {
348
+ refusalCodes: []
349
+ }
350
+ };
351
+ var TENANT_POSTGRES_ROLE_CONNECTION_LIMIT = APP_DEPENDENCY_MANAGED.pgRoleConnectionLimit;
352
+ var TENANT_POSTGRES_DATABASE_CONNECTION_LIMIT = APP_DEPENDENCY_MANAGED.pgDatabaseConnectionLimit;
353
+ var TENANT_POSTGRES_STATEMENT_TIMEOUT_MS = APP_DEPENDENCY_MANAGED.pgStatementTimeoutMs;
354
+ var TENANT_POSTGRES_IDLE_IN_TRANSACTION_TIMEOUT_MS = APP_DEPENDENCY_MANAGED.pgIdleInTransactionTimeoutMs;
355
+ var APP_PROVISION_LIMITS = {
356
+ attemptsDefault: 3,
357
+ attemptsMin: 1,
358
+ attemptsMax: 5,
359
+ attemptsPerAnswer: 2,
360
+ questionsMax: 3,
361
+ attemptsCeiling: 9,
362
+ optionsMax: 4,
363
+ tokenCapDefault: 3e6,
364
+ tokenCapMin: 5e5,
365
+ tokenCapMax: 1e7,
366
+ runnerMinuteCapDefault: 240,
367
+ runnerMinuteCapMin: 60,
368
+ runnerMinuteCapMax: 600,
369
+ /** Two starts of the same App Work inside this window yield one row (§4 "Start semantics"). */
370
+ startDedupeMs: 1e4,
371
+ analysisRunMs: 45 * 6e4,
372
+ iterateRunMs: 30 * 6e4,
373
+ forkWaitMs: 30 * 6e4,
374
+ activeDeadlineMs: 8 * 36e5,
375
+ /**
376
+ * Verification-Build reservation: `min(headSpec.build.resources.timeoutMinutes, buildMinutesMax)
377
+ * + runnerBootMinutesMax` — 90 minutes at the defaults, and the number §6.4 compares against the cap.
378
+ */
379
+ buildMinutesMax: 60,
380
+ jobSecondsMax: 900,
381
+ startupSecondsMax: 900,
382
+ smokeRequestMs: 3e4,
383
+ smokeTotalMs: 3e5,
384
+ runnerBootMinutesMax: 30,
385
+ runnerBootMemoryGiB: 12,
386
+ buildMemoryGiBMax: 14,
387
+ namespaceTtlMinutes: 90,
388
+ repoMaxBytes: 3 * 1024 ** 3,
389
+ diffMaxFiles: 12,
390
+ diffMaxLines: 3e3,
391
+ fileMaxBytes: 128 * 1024,
392
+ outputMaxBytes: 512 * 1024,
393
+ reportMaxChars: 4e4,
394
+ instructionFileMaxBytes: 32 * 1024,
395
+ logTailLines: 200,
396
+ logTailBytes: 16 * 1024,
397
+ evidenceCommentMaxChars: 6e4,
398
+ chatMessagesMax: 12,
399
+ questionReminderMs: 72 * 36e5,
400
+ questionExpiryMs: 14 * 864e5,
401
+ activePerUser: 3,
402
+ activePerOrg: 10,
403
+ startsPerHour: 10,
404
+ pollMs: 5e3,
405
+ infraRetries: 3,
406
+ infraRetryWindowMs: 30 * 6e4,
407
+ suggestionsPer30Days: 5,
408
+ autoReprovisionPerSync: 1,
409
+ autoReprovisionPer7Days: 2,
410
+ clusterProbeMs: 1e4,
411
+ podPendingInfraMs: 10 * 6e4
412
+ };
413
+ var MAX_CANDIDATE_OPTIONS = APP_PROVISION_LIMITS.optionsMax - 1;
414
+ var KB_EXPORT_MAX_BYTES = 200 * 1024 * 1024;
415
+ var TERMINAL_MAX_FRAME_BYTES = 1024 * 1024;
416
+ var COMPUTER_MAX_FRAME_BYTES = 512 * 1024;
417
+ var COMPUTER_MAX_BATCH_BYTES = 512 * 1024;
418
+ var COMPUTER_MAX_WIRE_FRAME_BYTES = Math.ceil(COMPUTER_MAX_FRAME_BYTES * 4 / 3) + 4096;
419
+ var COMPUTER_QUALITY_PRESETS = Object.freeze({
420
+ sharp: Object.freeze({ width: 1280, maxFps: 8, keyframeMs: 5e3, q: 70 }),
421
+ smooth: Object.freeze({ width: 960, maxFps: 15, keyframeMs: 5e3, q: 55 }),
422
+ steady: Object.freeze({ width: 800, maxFps: 2, keyframeMs: 2e3, q: 45 })
423
+ });
424
+ var COMPUTER_CONTROL_IDLE_MS_DEFAULT = 10 * 6e4;
425
+ var COMPUTER_CONTROL_CEILING_MS_DEFAULT = 60 * 6e4;
426
+ var COMPUTER_KEY_MODIFIER_ALT = 1;
427
+ var COMPUTER_KEY_MODIFIER_CTRL = 2;
428
+ var COMPUTER_KEY_MODIFIER_META = 4;
429
+ var CTRL = COMPUTER_KEY_MODIFIER_CTRL;
430
+ var META = COMPUTER_KEY_MODIFIER_META;
431
+ var ALT = COMPUTER_KEY_MODIFIER_ALT;
432
+ function withCtrlOrMeta(code, key) {
433
+ return [
434
+ { code, requires: CTRL, label: `Ctrl/\u2318+${key}` },
435
+ { code, requires: META, label: `Ctrl/\u2318+${key}` }
436
+ ];
437
+ }
438
+ var COMPUTER_BLOCKED_SHORTCUTS = Object.freeze([
439
+ ...withCtrlOrMeta("KeyC", "C"),
440
+ ...withCtrlOrMeta("KeyX", "X"),
441
+ ...withCtrlOrMeta("KeyV", "V"),
442
+ ...withCtrlOrMeta("KeyW", "W"),
443
+ ...withCtrlOrMeta("KeyT", "T"),
444
+ ...withCtrlOrMeta("KeyN", "N"),
445
+ ...withCtrlOrMeta("KeyQ", "Q"),
446
+ ...withCtrlOrMeta("Tab", "Tab"),
447
+ { code: "Tab", requires: ALT, label: "Alt+Tab" },
448
+ { code: "F4", requires: ALT, label: "Alt+F4" },
449
+ { code: "Delete", requires: CTRL | ALT, label: "Ctrl+Alt+Delete" },
450
+ { code: "MetaLeft", requires: 0, label: "\u2318/Win" },
451
+ { code: "MetaRight", requires: 0, label: "\u2318/Win" }
452
+ ]);
453
+ var TASK_BOARD_STATUSES = [
454
+ "backlog",
455
+ "todo",
456
+ "in_progress",
457
+ "in_review",
458
+ "blocked",
459
+ "done",
460
+ "cancelled"
461
+ ];
462
+ var TASK_BOARD_TERMINAL_STATUSES = ["done", "cancelled"];
463
+ var TASK_BOARD_STATUS_COLUMNS = TASK_BOARD_STATUSES.map((status) => ({
464
+ key: status,
465
+ statuses: [status],
466
+ terminal: TASK_BOARD_TERMINAL_STATUSES.includes(status),
467
+ toggleOnly: false
468
+ }));
469
+ var PLATFORM_DEFAULT_MERGE_POLICY = Object.freeze({
470
+ allowAgentMerge: false,
471
+ requireGreenGate: true,
472
+ requireHumanApproval: true,
473
+ allowedMergeMethods: ["squash"],
474
+ protectedBranches: ["main", "master", "develop", "stage"]
475
+ });
476
+ var MERGE_APPROVAL_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
477
+ var TOOL_GRANT_SCOPE_PRECEDENCE = Object.freeze([
478
+ "tenant",
479
+ "organization",
480
+ "work",
481
+ "agent"
482
+ ]);
483
+ var PLATFORM_DEFAULT_TOOL_GRANT = Object.freeze({
484
+ allow: Object.freeze(["*"]),
485
+ deny: Object.freeze([])
486
+ });
487
+ var AGENT_INIT_SCRIPT_MAX_BYTES = 16 * 1024;
488
+ var INGEST_EVENT_PAYLOAD_MAX_BYTES = 32 * 1024;
489
+ var VERSION = "1.0.0";
490
+ var GTM_SKILLS = [
491
+ // ── research ────────────────────────────────────────────────────────
492
+ {
493
+ slug: "lead-research",
494
+ title: "Lead research",
495
+ description: "Build a candidate lead list from seed criteria and public sources, recording a supporting source for every contact.",
496
+ stage: "research",
497
+ tags: ["gtm", "sales", "research"],
498
+ version: VERSION,
499
+ inputs: [
500
+ { key: "icp", description: "Ideal-customer description: segment, size, geography, role titles." },
501
+ { key: "seed_sources", description: "Seed lists, domains, or saved searches to start from." },
502
+ { key: "max_leads", description: "Hard cap on how many candidates this run may collect." }
503
+ ],
504
+ outputs: [
505
+ { key: "contacts", description: "Candidate contacts with name, company, title, and a source reference." }
506
+ ],
507
+ allowedTools: ["search", "content-extractor"],
508
+ body: [
509
+ "Build a candidate lead list from the supplied criteria and seed sources.",
510
+ "",
511
+ "## Rules",
512
+ "- NEVER invent a contact detail. An email address, phone number, or title is recorded only",
513
+ " when a source supports it; otherwise leave the field empty.",
514
+ "- Record `source` on every contact \u2014 the URL or seed list the entry came from. A contact",
515
+ " without a source is not a lead, it is a guess.",
516
+ "- Respect `max_leads` exactly. Stop collecting when the cap is reached and say how many",
517
+ " candidates were left unexamined.",
518
+ "- De-duplicate by email when present, otherwise by (company, name).",
519
+ "- Exclude anyone who has asked not to be contacted, and any source that forbids collection.",
520
+ "",
521
+ "## Output",
522
+ "Write `contacts`. Each entry carries `name`, and any of `email`, `company`, `title`,",
523
+ "`source`, `notes` that a source supports. Report the counts examined, kept, and dropped,",
524
+ "with the reason for each drop category."
525
+ ].join("\n")
526
+ },
527
+ {
528
+ slug: "competitor-watch",
529
+ title: "Competitor watch",
530
+ description: "Monitor a watchlist of companies across public sources and emit dated, source-linked change signals.",
531
+ stage: "research",
532
+ tags: ["gtm", "marketing", "research"],
533
+ version: VERSION,
534
+ inputs: [
535
+ { key: "watchlist", description: "Companies to monitor: name, website, public repositories." },
536
+ { key: "focus_areas", description: "What to watch: pricing, features, positioning, hiring." },
537
+ { key: "since", description: "Only report changes observed after this date." }
538
+ ],
539
+ outputs: [{ key: "signals", description: "Dated observations with a source URL and the focus area they hit." }],
540
+ allowedTools: ["search", "content-extractor"],
541
+ body: [
542
+ "Monitor the watchlist across public sources and report what changed.",
543
+ "",
544
+ "## Rules",
545
+ "- Public sources only: published pages, public announcements, public repositories.",
546
+ "- Every signal carries a source URL and an observation date. No date or no URL means the",
547
+ " signal is not reportable.",
548
+ "- Separate FACT (what the source says) from ANALYSIS (what you infer). Never blend them in",
549
+ " the same sentence.",
550
+ "- Report only changes since `since`. If a focus area produced nothing, say so explicitly \u2014",
551
+ " an empty period is a finding, not a gap to fill.",
552
+ "- Do not speculate about unannounced plans, internal metrics, or private information.",
553
+ "",
554
+ "## Output",
555
+ "Write `signals`. Each entry carries `title`, `url`, `publishedDate`, the focus area, and a",
556
+ "one-line factual summary."
557
+ ].join("\n")
558
+ },
559
+ {
560
+ slug: "news-signal-detection",
561
+ title: "News signal detection",
562
+ description: "Scan configured topics for newsworthy events and rank them by relevance to the campaign, discarding noise.",
563
+ stage: "research",
564
+ tags: ["gtm", "marketing", "research"],
565
+ version: VERSION,
566
+ inputs: [
567
+ { key: "topics", description: "Topics, keywords, or accounts to scan." },
568
+ { key: "lookback_days", description: "How far back the scan reaches." },
569
+ { key: "relevance_threshold", description: "Minimum relevance (0-1) an item must clear to be kept." }
570
+ ],
571
+ outputs: [{ key: "signals", description: "Relevance-ranked news items with source URL and publish date." }],
572
+ allowedTools: ["search", "content-extractor"],
573
+ body: [
574
+ "Scan the configured topics and keep only what is genuinely newsworthy for this campaign.",
575
+ "",
576
+ "## Rules",
577
+ "- Score each candidate 0-1 for relevance to the campaign brief and drop anything below",
578
+ " `relevance_threshold`. State the score and the one-line reason for every item you keep.",
579
+ "- Prefer primary sources over aggregators; when both exist, link the primary.",
580
+ "- Collapse duplicate coverage of the same event into one signal with the best source.",
581
+ "- Nothing older than `lookback_days`. Undated items are dropped, not guessed at.",
582
+ "- Never restate a headline as fact when the source hedges it \u2014 carry the hedge through.",
583
+ "",
584
+ "## Output",
585
+ "Write `signals` ordered by descending relevance, each with `title`, `url`, `publishedDate`,",
586
+ "the relevance score, and the reason it matters here."
587
+ ].join("\n")
588
+ },
589
+ // ── qualify ─────────────────────────────────────────────────────────
590
+ {
591
+ slug: "lead-scoring",
592
+ title: "Lead scoring",
593
+ description: "Score contacts 0-100 against a declarative weight table and attach an explainable reason per point awarded.",
594
+ stage: "qualify",
595
+ tags: ["gtm", "sales", "scoring"],
596
+ version: VERSION,
597
+ inputs: [
598
+ { key: "contacts", description: "Candidate contacts to score." },
599
+ { key: "score_weights", description: "Weight table: signal name \u2192 points awarded." }
600
+ ],
601
+ outputs: [
602
+ { key: "scored_contacts", description: "Contacts with `score` (0-100) and `scoreReasons` per contact." }
603
+ ],
604
+ allowedTools: [],
605
+ body: [
606
+ "Score every contact against the supplied weight table.",
607
+ "",
608
+ "## Rules",
609
+ "- The weight table is the whole model. Award points ONLY for signals it names; never invent",
610
+ " a bonus, and never award points for a signal the contact data does not actually support.",
611
+ "- Clamp the final score to 0-100. Record one `scoreReasons` line per point awarded, in the",
612
+ " form `<signal> +<points>`, so any score can be re-derived by hand.",
613
+ "- A missing field is worth zero points, never an assumed value.",
614
+ "- Scoring is deterministic: the same contact and the same weight table must always produce",
615
+ " the same score. Do not break ties with judgement calls \u2014 leave ties tied.",
616
+ "",
617
+ "## Output",
618
+ "Write `scored_contacts` sorted by descending score, then report the score distribution and",
619
+ "the three signals that moved the list most."
620
+ ].join("\n")
621
+ },
622
+ {
623
+ slug: "risk-filter",
624
+ title: "Risk filter",
625
+ description: "Flag low-quality or unsafe contacts against a risk weight table and exclude those at or above the threshold.",
626
+ stage: "qualify",
627
+ tags: ["gtm", "sales", "safety"],
628
+ version: VERSION,
629
+ inputs: [
630
+ { key: "scored_contacts", description: "Contacts already carrying a priority score." },
631
+ { key: "risk_weights", description: "Risk weight table: risk signal \u2192 points." },
632
+ { key: "risk_threshold", description: "Risk score at or above which a contact is excluded." }
633
+ ],
634
+ outputs: [
635
+ {
636
+ key: "scored_contacts",
637
+ description: "The same contacts, now carrying `riskScore`, `riskReasons`, and an excluded flag."
638
+ }
639
+ ],
640
+ allowedTools: [],
641
+ body: [
642
+ "Assess each scored contact for risk and mark \u2014 never silently delete \u2014 the excluded ones.",
643
+ "",
644
+ "## Rules",
645
+ "- Apply the risk weight table exactly as given; record one `riskReasons` line per point.",
646
+ "- Contacts at or above `risk_threshold` are EXCLUDED from outbound, but they stay in the",
647
+ " data set with their reasons attached so a human can overturn the call.",
648
+ '- Never drop a contact without a recorded reason. "Looked wrong" is not a reason.',
649
+ "- Risk is about deliverability and safety (unverifiable identity, throwaway domains,",
650
+ " do-not-contact signals) \u2014 it is not a second opinion on fit. Fit is `lead-scoring`.",
651
+ "",
652
+ "## Output",
653
+ "Write the enriched `scored_contacts` and report how many were excluded, grouped by the",
654
+ "dominant risk reason."
655
+ ].join("\n")
656
+ },
657
+ // ── draft ───────────────────────────────────────────────────────────
658
+ {
659
+ slug: "outreach-personalization",
660
+ title: "Outreach personalization",
661
+ description: "Write one 80-120 word personalized outbound draft per qualified contact, grounded only in known facts.",
662
+ stage: "draft",
663
+ tags: ["gtm", "sales", "writing"],
664
+ version: VERSION,
665
+ inputs: [
666
+ { key: "scored_contacts", description: "Qualified, non-excluded contacts to write for." },
667
+ { key: "campaign_brief", description: "Offer, proof points, and the single ask." },
668
+ { key: "tone", description: "Configured tone for the campaign." }
669
+ ],
670
+ outputs: [{ key: "drafts", description: "One draft per contact with `ref`, `channel`, `subject`, `body`." }],
671
+ allowedTools: [],
672
+ body: [
673
+ "Write one outbound draft per qualified contact.",
674
+ "",
675
+ "## Rules",
676
+ "- HARD CONSTRAINT: drafts only. Nothing is sent, scheduled, or queued for delivery here.",
677
+ '- 80-120 words in the body. One ask. No multi-part asks, no "quick question" openers that',
678
+ " the rest of the message contradicts.",
679
+ "- Personalize ONLY from fields and signals actually present on the contact. If there is no",
680
+ " personalization material, write the generic version and say so \u2014 a fabricated detail is",
681
+ " worse than a generic opener.",
682
+ "- Write a subject line only for channels that carry one.",
683
+ "- No invented metrics, customer names, or mutual connections. Ever.",
684
+ "",
685
+ "## Output",
686
+ "Write `drafts`, ordered by descending contact score so the review gate sees the best",
687
+ "candidates first. Each draft carries a stable `ref` used later by review and the action log."
688
+ ].join("\n")
689
+ },
690
+ {
691
+ slug: "newsletter-drafting",
692
+ title: "Newsletter drafting",
693
+ description: "Turn briefs, notes, and collected signals into a scannable newsletter issue with one clear call to action.",
694
+ stage: "draft",
695
+ tags: ["gtm", "marketing", "content", "writing"],
696
+ version: VERSION,
697
+ inputs: [
698
+ { key: "campaign_brief", description: "Issue theme, audience, and the call to action." },
699
+ { key: "signals", description: "Collected source material for the issue." },
700
+ { key: "tone", description: "Configured editorial tone." }
701
+ ],
702
+ outputs: [{ key: "drafts", description: "A single newsletter draft: subject line plus sectioned body." }],
703
+ allowedTools: ["content-extractor"],
704
+ body: [
705
+ "Draft one newsletter issue from the brief and the collected material.",
706
+ "",
707
+ "## Rules",
708
+ "- Draft-first: the issue is produced for human review. Never send or schedule it.",
709
+ "- Structure: subject line, one-sentence hook, 3-5 short sections, one call to action.",
710
+ " Scannable beats comprehensive.",
711
+ "- Every claim traces to the brief, the knowledge base, or a supplied signal. Link the",
712
+ " source when the section rests on one.",
713
+ "- Never invent metrics, quotes, or customer names.",
714
+ "- When the source material is thin, say so and list what extra input would raise quality",
715
+ " rather than padding the issue.",
716
+ "",
717
+ "## Output",
718
+ "Write `drafts` with a single entry: `subject` plus the sectioned `body`."
719
+ ].join("\n")
720
+ },
721
+ {
722
+ slug: "social-scheduling",
723
+ title: "Social scheduling",
724
+ description: "Plan a channel-fit social calendar and stage each post for review, respecting cadence and angle variety.",
725
+ stage: "draft",
726
+ tags: ["gtm", "marketing", "social", "writing"],
727
+ version: VERSION,
728
+ inputs: [
729
+ { key: "campaign_brief", description: "Campaign themes, channels, and cadence." },
730
+ { key: "signals", description: "Source material and trends to build posts from." },
731
+ { key: "cadence", description: "Posts per channel per period." }
732
+ ],
733
+ outputs: [
734
+ { key: "drafts", description: "Channel-fit post drafts, each with its planned slot in the calendar." }
735
+ ],
736
+ allowedTools: [],
737
+ body: [
738
+ "Plan the social calendar for the cadence window and draft each post.",
739
+ "",
740
+ "## Rules",
741
+ "- Draft-first: posts are STAGED for review. Never publish, never schedule to a live channel.",
742
+ "- Fit each draft to its channel: length, hashtag conventions, and link placement differ and",
743
+ " a cross-posted body is a tell.",
744
+ "- Do not repeat the same angle inside one cadence window. Track the angle per slot and vary",
745
+ " it deliberately.",
746
+ "- Build only from the brief, the content Works, and supplied signals. Never invent product",
747
+ " claims or engagement numbers.",
748
+ "- Respect `cadence` exactly \u2014 proposing more slots than the operator configured is not",
749
+ " ambition, it is a spam risk.",
750
+ "",
751
+ "## Output",
752
+ "Write `drafts` with the planned slot (channel + relative day) on each entry, plus a compact",
753
+ "calendar view of the window."
754
+ ].join("\n")
755
+ },
756
+ {
757
+ slug: "digest-compilation",
758
+ title: "Digest compilation",
759
+ description: "Compile collected signals into a recurring digest that separates facts from analysis and highlights change.",
760
+ stage: "draft",
761
+ tags: ["gtm", "marketing", "reporting", "writing"],
762
+ version: VERSION,
763
+ inputs: [
764
+ { key: "signals", description: "Signals collected this period." },
765
+ { key: "previous_digest", description: "The prior issue, used to compute what changed." },
766
+ { key: "focus_areas", description: "Sections the digest must cover." }
767
+ ],
768
+ outputs: [{ key: "drafts", description: "A digest draft: sections, change highlights, and a trend view." }],
769
+ allowedTools: [],
770
+ body: [
771
+ "Compile the period digest from the collected signals.",
772
+ "",
773
+ "## Rules",
774
+ "- One section per focus area, in the configured order, every issue. A stable shape is what",
775
+ " makes a recurring digest readable.",
776
+ "- Every section splits FACTS (sourced, dated, linked) from ANALYSIS (your interpretation),",
777
+ " under those labels.",
778
+ "- Lead with what CHANGED since `previous_digest`. Unchanged areas get one line, not a",
779
+ " restatement of last issue.",
780
+ "- No fabrication and no padding: if a focus area produced no signal this period, write",
781
+ " exactly that.",
782
+ "- Close with a short trend view over the recent periods \u2014 direction, not prophecy.",
783
+ "",
784
+ "## Output",
785
+ "Write `drafts` with a single digest entry for review."
786
+ ].join("\n")
787
+ },
788
+ // ── act ─────────────────────────────────────────────────────────────
789
+ {
790
+ slug: "crm-sync-hygiene",
791
+ title: "CRM sync hygiene",
792
+ description: "Prepare reviewed records for a customer-record sync: normalized fields, no duplicates, no destructive overwrites.",
793
+ stage: "act",
794
+ tags: ["gtm", "sales", "operations"],
795
+ version: VERSION,
796
+ inputs: [
797
+ { key: "approved_drafts", description: "Records cleared by the review gate." },
798
+ { key: "field_map", description: "Local field \u2192 destination field mapping." }
799
+ ],
800
+ outputs: [
801
+ { key: "action_log", description: "Prepared record writes with the field diff and the reason for each." }
802
+ ],
803
+ allowedTools: ["connector"],
804
+ body: [
805
+ "Prepare reviewed records for the destination system without losing data.",
806
+ "",
807
+ "## Rules",
808
+ "- Only records that passed the review gate are eligible. Nothing else, no exceptions.",
809
+ "- NEVER overwrite a populated destination field with an empty local value. Blank does not",
810
+ ' mean "clear it", it means "we do not know".',
811
+ "- Match before you create: search by the destination key (email, then domain + name) and",
812
+ " update the existing record rather than minting a duplicate.",
813
+ "- Normalize on the way out \u2014 casing, phone format, domain form \u2014 per `field_map`.",
814
+ "- Record every intended write in `action_log` with its field-level diff BEFORE it is",
815
+ " applied, so the change is auditable and reversible.",
816
+ "",
817
+ "## Output",
818
+ "Write `action_log` with one entry per record, status `prepared` or `skipped`, and the",
819
+ "reason for every skip."
820
+ ].join("\n")
821
+ },
822
+ // ── follow-up ───────────────────────────────────────────────────────
823
+ {
824
+ slug: "follow-up-cadence",
825
+ title: "Follow-up cadence",
826
+ description: "Schedule timed re-engagement for quiet threads, with strict caps and an unconditional stop on any reply.",
827
+ stage: "follow-up",
828
+ tags: ["gtm", "sales", "cadence"],
829
+ version: VERSION,
830
+ inputs: [
831
+ { key: "action_log", description: "What was prepared, for whom, and when." },
832
+ { key: "reply_state", description: "Which threads have received a reply." },
833
+ { key: "cadence", description: "Follow-up spacing and the maximum number of touches." }
834
+ ],
835
+ outputs: [
836
+ { key: "follow_up_queue", description: "Queued follow-ups with a due offset and the rationale for each." }
837
+ ],
838
+ allowedTools: [],
839
+ body: [
840
+ "Queue follow-ups for threads that have gone quiet.",
841
+ "",
842
+ "## Rules",
843
+ "- HARD STOP on any reply, bounce, or opt-out: that thread leaves the cadence immediately and",
844
+ " permanently. This overrides every other rule here.",
845
+ "- Never exceed the configured maximum touches per contact, and never shorten the configured",
846
+ " spacing to fit more in.",
847
+ "- Each follow-up must add something \u2014 a new angle, a new proof point, a genuine deadline.",
848
+ ' "Bumping this to the top of your inbox" is not a follow-up.',
849
+ "- Follow-ups are drafts like any other outbound: they re-enter the review gate before",
850
+ " anything is prepared for delivery.",
851
+ "",
852
+ "## Output",
853
+ "Write `follow_up_queue` with `draftRef`, `channel`, `dueAfterDays`, and the rationale."
854
+ ].join("\n")
855
+ },
856
+ {
857
+ slug: "reply-detection",
858
+ title: "Reply detection",
859
+ description: "Classify inbound replies into interested / not-now / decline / opt-out and route each to the right next step.",
860
+ stage: "follow-up",
861
+ tags: ["gtm", "sales", "classification"],
862
+ version: VERSION,
863
+ inputs: [
864
+ { key: "inbound_messages", description: "Replies received against prepared outbound." },
865
+ { key: "action_log", description: "The outbound each reply responds to." }
866
+ ],
867
+ outputs: [
868
+ { key: "reply_state", description: "Per-thread classification, confidence, and the routing decision." }
869
+ ],
870
+ allowedTools: ["connector"],
871
+ body: [
872
+ "Classify each inbound reply and decide what happens to its thread.",
873
+ "",
874
+ "## Classes",
875
+ "`interested` \xB7 `not_now` \xB7 `decline` \xB7 `opt_out` \xB7 `auto_reply` \xB7 `unclear`",
876
+ "",
877
+ "## Rules",
878
+ "- `opt_out` and `decline` stop the cadence permanently. When in doubt between `opt_out` and",
879
+ " anything else, choose `opt_out` \u2014 the cost of a wrong stop is far below the cost of a",
880
+ " wrong send.",
881
+ "- `auto_reply` (out-of-office, autoresponder) does NOT count as a reply for cadence",
882
+ " purposes, but it does update the contact record if it names a new owner.",
883
+ "- Use `unclear` rather than guessing; unclear threads route to a human, they do not route",
884
+ " to the next touch.",
885
+ "- Record a confidence value and the phrase that drove the classification.",
886
+ "",
887
+ "## Output",
888
+ "Write `reply_state` with the class, confidence, evidence phrase, and routing decision per",
889
+ "thread."
890
+ ].join("\n")
891
+ },
892
+ // ── enrich ──────────────────────────────────────────────────────────
893
+ {
894
+ slug: "contact-enrichment",
895
+ title: "Contact enrichment",
896
+ description: "Backfill missing contact and account fields from verifiable sources, recording the evidence for each fill.",
897
+ stage: "enrich",
898
+ tags: ["gtm", "sales", "data"],
899
+ version: VERSION,
900
+ inputs: [
901
+ { key: "contacts", description: "Contacts with gaps to fill." },
902
+ { key: "enrichment_fields", description: "Which fields this run is allowed to fill." }
903
+ ],
904
+ outputs: [
905
+ { key: "enriched_contacts", description: "Contacts with filled fields and a source note per filled field." }
906
+ ],
907
+ allowedTools: ["search", "content-extractor", "connector"],
908
+ body: [
909
+ "Fill the requested gaps on each contact \u2014 and only those gaps.",
910
+ "",
911
+ "## Rules",
912
+ "- Evidence-bound: a field is filled ONLY when a source supports it, and the source goes in",
913
+ " the contact notes alongside the value. No source, no fill.",
914
+ "- NEVER guess or pattern-generate an email address. Constructing `first.last@domain` because",
915
+ " it usually works is fabrication, and it is the single most damaging thing this Skill can do.",
916
+ "- Never overwrite an existing non-empty value. Enrichment fills gaps; corrections are a",
917
+ " human decision.",
918
+ "- Only touch fields named in `enrichment_fields`.",
919
+ "- When two sources disagree, leave the field empty and flag the conflict.",
920
+ "",
921
+ "## Output",
922
+ "Write `enriched_contacts` and report fill rate per field plus every conflict flagged."
923
+ ].join("\n")
924
+ },
925
+ // ── measure ─────────────────────────────────────────────────────────
926
+ {
927
+ slug: "seo-audit",
928
+ title: "Search-visibility audit",
929
+ description: "Audit a site or content Work for search visibility and return a prioritized, evidence-cited fix list.",
930
+ stage: "measure",
931
+ tags: ["gtm", "marketing", "seo", "audit"],
932
+ version: VERSION,
933
+ inputs: [
934
+ { key: "pages", description: "Pages or posts in scope, with their current metadata and headings." },
935
+ { key: "target_keywords", description: "Keywords or topics the Work is meant to rank for." },
936
+ { key: "previous_audit", description: "The prior audit, used to report movement and regressions." }
937
+ ],
938
+ outputs: [
939
+ { key: "campaign_report", description: "Prioritized findings with page reference, impact, and fix." }
940
+ ],
941
+ allowedTools: ["content-extractor", "search"],
942
+ body: [
943
+ "Audit the in-scope pages for search visibility and propose fixes.",
944
+ "",
945
+ "## What to check",
946
+ "Title and description metadata \xB7 heading structure and hierarchy \xB7 internal linking and",
947
+ "orphan pages \xB7 keyword coverage against `target_keywords` and the gaps between them \xB7",
948
+ "duplicate or thin content \xB7 canonical and indexability signals.",
949
+ "",
950
+ "## Rules",
951
+ "- Every finding cites the specific page or setting it applies to and states the expected",
952
+ " impact. A finding without a page reference is an opinion.",
953
+ "- Return a prioritized top 5-10, quick wins first \u2014 not an exhaustive dump.",
954
+ "- Propose changes as reviewable edits or tasks. Never modify published pages directly.",
955
+ "- When `previous_audit` is present, report movement honestly, INCLUDING regressions. A",
956
+ " clean report that hides a regression is worse than no report.",
957
+ "- No traffic or ranking projections. Estimate effort and impact qualitatively instead.",
958
+ "",
959
+ "## Output",
960
+ "Write `campaign_report` with the prioritized findings and the movement summary."
961
+ ].join("\n")
962
+ },
963
+ {
964
+ slug: "campaign-reporting",
965
+ title: "Campaign reporting",
966
+ description: "Summarize a campaign period into counted totals, honest insights, and concrete hints for the next cycle.",
967
+ stage: "measure",
968
+ tags: ["gtm", "reporting"],
969
+ version: VERSION,
970
+ inputs: [
971
+ { key: "action_log", description: "What the campaign prepared and skipped." },
972
+ { key: "reply_state", description: "How recipients responded." },
973
+ { key: "scored_contacts", description: "The qualified population the period worked from." }
974
+ ],
975
+ outputs: [{ key: "campaign_report", description: "Totals, insights, and next-cycle variant hints." }],
976
+ allowedTools: [],
977
+ body: [
978
+ "Report the campaign period and close the loop into the next one.",
979
+ "",
980
+ "## Rules",
981
+ "- Totals are COUNTED from the supplied data, never estimated: contacts, qualified, excluded,",
982
+ " drafts, approved, prepared, follow-ups queued.",
983
+ "- State the denominator on every rate. A percentage without its base is not a metric.",
984
+ "- Below roughly 30 observations, report counts and refuse to draw a conclusion \u2014 small",
985
+ " samples produce confident nonsense.",
986
+ "- Insights must be falsifiable and tied to a number in the totals.",
987
+ "- End with `nextVariantHints`: concrete, testable changes for the next draft cycle, one per",
988
+ " line. This is the loop closing \u2014 a report that ends at description wasted the period.",
989
+ "",
990
+ "## Output",
991
+ "Write `campaign_report` with `summary`, `totals`, `insights`, and `nextVariantHints`."
992
+ ].join("\n")
993
+ },
994
+ {
995
+ slug: "engagement-analysis",
996
+ title: "Engagement analysis",
997
+ description: "Compare engagement across variants, channels, and segments, and say which differences are real.",
998
+ stage: "measure",
999
+ tags: ["gtm", "marketing", "reporting"],
1000
+ version: VERSION,
1001
+ inputs: [
1002
+ { key: "engagement_events", description: "Per-item engagement observations for the period." },
1003
+ { key: "drafts", description: "The variants the events belong to." },
1004
+ { key: "comparison_window", description: "Prior period to compare against." }
1005
+ ],
1006
+ outputs: [
1007
+ { key: "campaign_report", description: "Per-variant and per-segment engagement with a confidence call." }
1008
+ ],
1009
+ allowedTools: ["metrics"],
1010
+ body: [
1011
+ "Analyze engagement and report what actually differs.",
1012
+ "",
1013
+ "## Rules",
1014
+ "- Compare like with like: same channel, same audience segment, comparable send window.",
1015
+ " Cross-channel comparisons need an explicit caveat.",
1016
+ "- Report absolute counts alongside every rate.",
1017
+ "- Say plainly when a difference is within noise. Declaring a winner on a handful of",
1018
+ " observations is the most common way this analysis misleads a campaign for months.",
1019
+ "- Separate what changed (observation) from why (hypothesis), and label hypotheses as such.",
1020
+ "- Surface the losing variants too \u2014 a variant that consistently underperforms is the",
1021
+ " cheapest thing to stop doing.",
1022
+ "",
1023
+ "## Output",
1024
+ "Write `campaign_report` with the per-variant table, the segment breakdown, and an explicit",
1025
+ "confidence statement per comparison."
1026
+ ].join("\n")
1027
+ }
1028
+ ];
1029
+ var GTM_SKILL_SLUGS = GTM_SKILLS.map((skill) => skill.slug);
1030
+ var GTM_SKILL_BY_SLUG = new Map(
1031
+ GTM_SKILLS.map((skill) => [skill.slug, skill])
1032
+ );
1033
+ var SKILL_READINESS_STATES = [
1034
+ "ready",
1035
+ "needs_setup",
1036
+ "missing_requirements",
1037
+ "blocked_by_access",
1038
+ "unknown",
1039
+ "check_failed"
1040
+ ];
1041
+ var SKILL_CARD_STATES = [...SKILL_READINESS_STATES, "disabled", "needs_review"];
1042
+ var SKILL_READINESS_FILTERS = [...SKILL_CARD_STATES, "attention"];
1043
+ var FLEET_AGENT_CREDENTIAL_FAMILIES = [
1044
+ {
1045
+ cli: "claude-code",
1046
+ // CLAUDE_CODE_OAUTH_TOKEN (a Claude plan) before ANTHROPIC_API_KEY
1047
+ // (per-token Console billing) — deliberately the REVERSE of the CLI's
1048
+ // own precedence, so the cheaper credential wins rather than the one
1049
+ // that silently spends money.
1050
+ envNames: ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY"]
1051
+ },
1052
+ {
1053
+ cli: "codex",
1054
+ // CODEX_ACCESS_TOKEN draws the ChatGPT workspace entitlement;
1055
+ // OPENAI_API_KEY is per-token platform billing.
1056
+ envNames: ["CODEX_ACCESS_TOKEN", "OPENAI_API_KEY"]
1057
+ }
1058
+ ];
1059
+ var FLEET_AGENT_CREDENTIAL_ENV_NAMES = FLEET_AGENT_CREDENTIAL_FAMILIES.flatMap(
1060
+ (family) => family.envNames
1061
+ );
1062
+ var FLEET_RUN_ENV_FILE_MAX_CONTENT_BYTES = 32 * 1024;
1063
+ var FLEET_RUN_ENV_FILES_MAX_TOTAL_BYTES = 256 * 1024;
1064
+ var FLEET_JOB_MAX_PAYLOAD_BYTES = 256 * 1024;
1065
+ var FLEET_JOB_MAX_RESULT_BYTES = 256 * 1024;
1066
+ var FLEET_JOB_DEFAULT_QUEUED_MAX_AGE_SEC = Object.freeze({
1067
+ "agent-task": 24 * 60 * 60,
1068
+ "acceptance-checks": 2 * 60 * 60,
1069
+ "browser-check": 2 * 60 * 60,
1070
+ // A live view nobody claimed is abandoned by the session service after
1071
+ // 40 seconds, which cancels its job there and then. The queue SLA is only
1072
+ // the backstop behind that, so it deliberately does not undercut the
1073
+ // shortest existing default (the fallback an unknown kind fails closed to).
1074
+ "computer-session": 2 * 60 * 60
1075
+ });
1076
+ var FLEET_JOB_MAX_QUEUED_MAX_AGE_SEC = 7 * 24 * 60 * 60;
1077
+ var FLEET_AGENT_EXECUTION_MAX_INSTRUCTIONS_BYTES = 160 * 1024;
1078
+ var FLEET_AGENT_TASK_TIMELINE_MAX_BYTES = 48 * 1024;
1079
+ var FLEET_AGENT_TASK_TRANSCRIPT_MAX_BYTES = 64 * 1024;
1080
+ var FLEET_AGENT_TASK_QUESTION_MAX_FILE_BYTES = 64 * 1024;
1081
+ var FLEET_AGENT_TASK_QUESTION_MAX_CONTEXT_BYTES = 6 * 1024;
1082
+ var FLEET_NODE_MAX_MEMORY_MB = 1024 * 1024;
1083
+ var FLEET_MAX_DAILY_COST_CEILING_CENTS = 1e5 * 100;
1084
+ var FLEET_MAX_DISK_FREE_BYTES = 2 ** 60;
1085
+ var FLEET_DEFAULT_ENROLLMENT_TOKEN_TTL_MS = 15 * 6e4;
1086
+ var FLEET_DEFAULT_NODE_OFFLINE_AFTER_MS = 5 * 6e4;
1087
+ var FLEET_DEFAULT_NODE_OFFLINE_NOTICE_AFTER_MS = 30 * 6e4;
1088
+ var FLEET_DEFAULT_CREDENTIAL_ROTATION_OVERLAP_MS = 15 * 6e4;
1089
+ var FLEET_MAX_CREDENTIAL_ROTATION_OVERLAP_MS = 24 * 60 * 6e4;
1090
+ var EMAIL_INBOX_DEFAULT_DAILY_CAP = 100;
1091
+ var EMAIL_INBOX_BURST_SENDS = 10;
1092
+ var EMAIL_INBOX_BURST_RECIPIENTS = 20;
1093
+ var EMAIL_WORKSPACE_DAILY_CAP = 500;
1094
+ var EMAIL_WORKSPACE_MONTHLY_CAP = 1e4;
1095
+ var EMAIL_MAX_RECIPIENTS_PER_MESSAGE = 50;
1096
+ var EMAIL_SEND_CAP_RECOMMENDED_DEFAULTS = Object.freeze({
1097
+ inboxDailySends: EMAIL_INBOX_DEFAULT_DAILY_CAP,
1098
+ inboxBurstSends: EMAIL_INBOX_BURST_SENDS,
1099
+ inboxBurstRecipients: EMAIL_INBOX_BURST_RECIPIENTS,
1100
+ recipientsPerMessage: EMAIL_MAX_RECIPIENTS_PER_MESSAGE,
1101
+ workspaceDailySends: EMAIL_WORKSPACE_DAILY_CAP,
1102
+ workspaceMonthlySends: EMAIL_WORKSPACE_MONTHLY_CAP
1103
+ });
1104
+ var EMAIL_DAY_WINDOW_MS = 24 * 60 * 60 * 1e3;
1105
+ var EMAIL_MONTH_WINDOW_MS = 30 * EMAIL_DAY_WINDOW_MS;
1106
+ var EMAIL_INBOX_CAP_FIELDS = [
1107
+ "inboxDailySends",
1108
+ "inboxBurstSends",
1109
+ "inboxBurstRecipients",
1110
+ "recipientsPerMessage"
1111
+ ];
1112
+ var EMAIL_SEND_CAP_FIELDS = [
1113
+ ...EMAIL_INBOX_CAP_FIELDS,
1114
+ "workspaceDailySends",
1115
+ "workspaceMonthlySends"
1116
+ ];
1117
+ var INBOX_CAP_FIELD_SET = new Set(EMAIL_INBOX_CAP_FIELDS);
1118
+ var DAY_MS2 = 24 * 60 * 60 * 1e3;
1119
+ var PROMOTION_GATE_DECISION_GRACE_MS = 20 * 60 * 1e3;
1120
+ var RELEASE_VERIFY_ATTEMPT_INTERVAL_MS = 10 * 60 * 1e3;
1121
+ var RELEASE_VERIFY_BUDGET_MS = 8 * 60 * 60 * 1e3;
1122
+ var MAX_CONVERSATION_BODY_BYTES = 16 * 1024;
1123
+ var CONNECTION_CREDENTIAL_ERROR_CODES = Object.freeze([
1124
+ "credential_rejected",
1125
+ "credential_missing",
1126
+ "https_required"
1127
+ ]);
1128
+ var CONNECTION_HEALTH_WARNING_CODES = Object.freeze([
1129
+ "insecure_transport"
1130
+ ]);
1131
+ var BACKUP_TRIM_POLICIES = Object.freeze({
1132
+ activity: Object.freeze({ field: "createdAt", defaultDays: 365, fullHistoryDays: 1095 }),
1133
+ runLogs: Object.freeze({ field: "createdAt", defaultDays: 90, fullHistoryDays: 1095 }),
1134
+ terminalTranscripts: Object.freeze({ field: "createdAt", defaultDays: 30, fullHistoryDays: 365 }),
1135
+ notifications: Object.freeze({ field: "createdAt", defaultDays: 180, fullHistoryDays: 1095 }),
1136
+ // `occurredAt`, not `createdAt`: `PluginUsageEvent` names its
1137
+ // `@CreateDateColumn` `occurredAt` and has no `createdAt` at all. The trim
1138
+ // resolver fails OPEN on an unknown column, so the wrong name here did not
1139
+ // error — it silently exported every plugin usage event for the lifetime
1140
+ // of the workspace, from the archive's single largest history table, while
1141
+ // the docs page published a 180-day window.
1142
+ pluginUsageEvents: Object.freeze({ field: "occurredAt", defaultDays: 180, fullHistoryDays: 1095 }),
1143
+ deliveryLogs: Object.freeze({ field: "createdAt", defaultDays: 30, fullHistoryDays: 365 }),
1144
+ // `firedAt`, for the same reason: `InboundTriggerFire`'s creation
1145
+ // timestamp is `firedAt` and it has no `createdAt`, so the declared
1146
+ // 90-day window was never applied to `data/schedules/trigger-fires.jsonl`
1147
+ // and the `schedules` domain reported `complete` where the docs promise a
1148
+ // trim.
1149
+ triggerFires: Object.freeze({ field: "firedAt", defaultDays: 90, fullHistoryDays: 1095 }),
1150
+ retrievalTrail: Object.freeze({ field: "createdAt", defaultDays: 30, fullHistoryDays: 365 }),
1151
+ fleetJobs: Object.freeze({ field: "createdAt", defaultDays: 30, fullHistoryDays: 365 })
1152
+ });
1153
+ var BACKUP_DOMAINS = Object.freeze([
1154
+ Object.freeze({
1155
+ key: "account",
1156
+ restorability: "restorable",
1157
+ collectorId: "account",
1158
+ dataDir: "account"
1159
+ }),
1160
+ Object.freeze({
1161
+ key: "organizations",
1162
+ restorability: "restorable",
1163
+ collectorId: "organizations",
1164
+ dataDir: "organizations"
1165
+ }),
1166
+ Object.freeze({
1167
+ key: "agents",
1168
+ restorability: "restorable",
1169
+ collectorId: "agents",
1170
+ dataDir: "agents"
1171
+ }),
1172
+ Object.freeze({
1173
+ key: "missions",
1174
+ restorability: "restorable",
1175
+ collectorId: "missions",
1176
+ dataDir: "missions"
1177
+ }),
1178
+ Object.freeze({
1179
+ key: "tasks",
1180
+ restorability: "restorable",
1181
+ collectorId: "tasks",
1182
+ dataDir: "tasks"
1183
+ }),
1184
+ Object.freeze({
1185
+ key: "works",
1186
+ restorability: "restorable",
1187
+ collectorId: "works",
1188
+ dataDir: "works"
1189
+ }),
1190
+ Object.freeze({
1191
+ key: "knowledge",
1192
+ restorability: "restorable",
1193
+ collectorId: "knowledge",
1194
+ dataDir: "knowledge"
1195
+ }),
1196
+ Object.freeze({
1197
+ key: "schedules",
1198
+ restorability: "restorable",
1199
+ collectorId: "schedules",
1200
+ dataDir: "schedules"
1201
+ }),
1202
+ Object.freeze({
1203
+ key: "runs",
1204
+ restorability: "record-only",
1205
+ collectorId: "runs",
1206
+ dataDir: "runs"
1207
+ }),
1208
+ Object.freeze({
1209
+ key: "decisions",
1210
+ restorability: "record-only",
1211
+ collectorId: "decisions",
1212
+ dataDir: "decisions"
1213
+ }),
1214
+ Object.freeze({
1215
+ key: "communication",
1216
+ restorability: "partly-restorable",
1217
+ collectorId: "communication",
1218
+ dataDir: "communication"
1219
+ }),
1220
+ Object.freeze({
1221
+ key: "connections",
1222
+ restorability: "restorable",
1223
+ collectorId: "connections",
1224
+ dataDir: "connections"
1225
+ }),
1226
+ Object.freeze({
1227
+ key: "fleet",
1228
+ restorability: "partly-restorable",
1229
+ collectorId: "fleet",
1230
+ dataDir: "fleet"
1231
+ }),
1232
+ Object.freeze({
1233
+ key: "billing",
1234
+ restorability: "record-only",
1235
+ collectorId: "billing",
1236
+ dataDir: "billing"
1237
+ }),
1238
+ Object.freeze({
1239
+ key: "activity",
1240
+ restorability: "record-only",
1241
+ collectorId: "activity",
1242
+ dataDir: "activity",
1243
+ trim: BACKUP_TRIM_POLICIES.activity
1244
+ })
1245
+ ]);
1246
+ var BACKUP_DOMAIN_KEYS = Object.freeze(BACKUP_DOMAINS.map((domain) => domain.key));
1247
+ var BACKUP_DOMAIN_COUNT = BACKUP_DOMAINS.length;
1248
+ var BACKUP_EXCLUSIONS = Object.freeze([
1249
+ Object.freeze({
1250
+ code: "auth_tokens",
1251
+ summary: "Password hashes, password-reset tokens, magic-link tokens and email-verification tokens."
1252
+ }),
1253
+ Object.freeze({
1254
+ code: "sessions",
1255
+ summary: "Sessions, refresh tokens, and third-party auth provider access and refresh tokens."
1256
+ }),
1257
+ Object.freeze({
1258
+ code: "api_key_material",
1259
+ summary: "API key material. Keys appear as name, prefix, created date and active flag only."
1260
+ }),
1261
+ Object.freeze({
1262
+ code: "stored_credentials",
1263
+ summary: "Every stored credential, in plaintext or ciphertext \u2014 plugin secrets, connection headers, deployment secrets, webhook and trigger signing secrets, and encrypted runtime credentials. Only the names of the fields that were set are exported."
1264
+ }),
1265
+ Object.freeze({
1266
+ code: "node_enrolment_secrets",
1267
+ summary: "Node enrolment and heartbeat secrets."
1268
+ }),
1269
+ Object.freeze({
1270
+ code: "payment_identifiers",
1271
+ summary: "Payment-provider customer, subscription, payment-method and meter identifiers."
1272
+ }),
1273
+ Object.freeze({
1274
+ code: "platform_admin_flag",
1275
+ summary: "The platform-administrator flag."
1276
+ }),
1277
+ Object.freeze({
1278
+ code: "vector_embeddings",
1279
+ summary: "Vector embeddings and their coordinates, because they are derived and regenerate on demand."
1280
+ }),
1281
+ Object.freeze({
1282
+ code: "internal_caches",
1283
+ summary: "Internal caches and the delivery outbox."
1284
+ })
1285
+ ]);
1286
+ var BACKUP_DEFAULT_LIMITS = Object.freeze({
1287
+ /** Ready archives kept for this long before their bytes are deleted. */
1288
+ retentionDays: 14,
1289
+ /** The record outlives its bytes by this long, so history stays legible. */
1290
+ recordRetentionDays: 90,
1291
+ /** Ready outcomes allowed per rolling 24 hours. Failures do not count. */
1292
+ dailyAllowance: 3,
1293
+ /** Rows the history list shows before "Show all". */
1294
+ historyPageSize: 20,
1295
+ /** Hard ceiling on a single history page. */
1296
+ historyPageLimit: 50,
1297
+ /** Bytes of one uploaded file that may be carried (200 MiB). */
1298
+ maxFileBytes: 200 * 1024 * 1024,
1299
+ /** Bytes of uploaded files in total (2 GiB). */
1300
+ maxAttachmentBytes: 2 * 1024 * 1024 * 1024,
1301
+ /** Bytes the finished archive may not exceed with a streaming backend (5 GiB). */
1302
+ maxArchiveBytes: 5 * 1024 * 1024 * 1024,
1303
+ /**
1304
+ * The ceiling when the active storage backend cannot accept a stream and
1305
+ * the archive has to be handed over as one buffer (512 MiB). A backend
1306
+ * without streaming is a smaller limit, never a wrong result.
1307
+ */
1308
+ maxBufferedArchiveBytes: 512 * 1024 * 1024,
1309
+ /** A manifest larger than this is refused by the check without being read (8 MiB). */
1310
+ maxManifestBytes: 8 * 1024 * 1024,
1311
+ /** Minutes a download link stays valid before the client re-mints it. */
1312
+ downloadLinkTtlMinutes: 15,
1313
+ /** Minutes without a heartbeat before a running backup is called stalled. */
1314
+ stallMinutes: 10,
1315
+ /** Minutes a queued backup may wait before it is called stalled. */
1316
+ queuedStallMinutes: 15,
1317
+ /** Minutes a backup may run before it is stopped. */
1318
+ timeoutMinutes: 60,
1319
+ /** Retries a single domain gets before it is marked failed and the archive finishes without it. */
1320
+ domainRetries: 2,
1321
+ /** Retries a storage write gets before the backup fails as `storage_unavailable`. */
1322
+ storageRetries: 3
1323
+ });
1324
+ var HOUR_MS = 60 * 60 * 1e3;
1325
+ var MINUTE_MS = 60 * 1e3;
1326
+ var ACTION_CATEGORIES = Object.freeze([
1327
+ "read.internal",
1328
+ "read.external",
1329
+ "write.internal",
1330
+ "write.destructive",
1331
+ "message.internal",
1332
+ "message.external",
1333
+ "publish.external",
1334
+ "spend.metered",
1335
+ "spend.commitment",
1336
+ "access.grant",
1337
+ "machine.run",
1338
+ "machine.admin",
1339
+ "agent.fanout"
1340
+ ]);
1341
+ var LADDERED_CATEGORIES = Object.freeze(
1342
+ ACTION_CATEGORIES.filter((c) => c !== "read.internal")
1343
+ );
1344
+ var DRAFTABLE_CATEGORIES = Object.freeze([
1345
+ "write.internal",
1346
+ "write.destructive",
1347
+ "message.external",
1348
+ "publish.external",
1349
+ "machine.run",
1350
+ "machine.admin"
1351
+ ]);
1352
+ var ACTION_CATEGORY_CEILING = Object.freeze({
1353
+ "read.external": "auto",
1354
+ "write.internal": "auto",
1355
+ "write.destructive": "ask",
1356
+ "message.internal": "auto",
1357
+ "message.external": "ask",
1358
+ "publish.external": "ask",
1359
+ "spend.metered": "auto",
1360
+ "spend.commitment": "off",
1361
+ "access.grant": "ask",
1362
+ "machine.run": "auto",
1363
+ "machine.admin": "ask",
1364
+ "agent.fanout": "auto"
1365
+ });
1366
+ var ACTION_CATEGORY_DEFAULT = Object.freeze({
1367
+ "read.external": "auto",
1368
+ "write.internal": "auto",
1369
+ "write.destructive": "ask",
1370
+ "message.internal": "auto",
1371
+ "message.external": "draft",
1372
+ "publish.external": "ask",
1373
+ "spend.metered": "auto",
1374
+ "spend.commitment": "off",
1375
+ "access.grant": "ask",
1376
+ "machine.run": "ask",
1377
+ "machine.admin": "ask",
1378
+ "agent.fanout": "ask"
1379
+ });
1380
+ var ACTION_CATEGORY_RESTRICTIVENESS = Object.freeze([
1381
+ "spend.commitment",
1382
+ "access.grant",
1383
+ "machine.admin",
1384
+ "publish.external",
1385
+ "message.external",
1386
+ "write.destructive",
1387
+ "machine.run",
1388
+ "agent.fanout",
1389
+ "spend.metered",
1390
+ "write.internal",
1391
+ "message.internal",
1392
+ "read.external",
1393
+ "read.internal"
1394
+ ]);
1395
+ var ACTION_CATEGORY_I18N_KEY = Object.freeze({
1396
+ "read.internal": "readInternal",
1397
+ "read.external": "readExternal",
1398
+ "write.internal": "writeInternal",
1399
+ "write.destructive": "writeDestructive",
1400
+ "message.internal": "messageInternal",
1401
+ "message.external": "messageExternal",
1402
+ "publish.external": "publishExternal",
1403
+ "spend.metered": "spendMetered",
1404
+ "spend.commitment": "spendCommitment",
1405
+ "access.grant": "accessGrant",
1406
+ "machine.run": "machineRun",
1407
+ "machine.admin": "machineAdmin",
1408
+ "agent.fanout": "agentFanout"
1409
+ });
1410
+ var TRUST_RUNG_ORDER = Object.freeze([
1411
+ "off",
1412
+ "draft",
1413
+ "ask",
1414
+ "auto"
1415
+ ]);
1416
+ var SAFETY_RAIL_ORDER = Object.freeze([
1417
+ "platform-stop",
1418
+ "workspace-pause",
1419
+ "scope-pause",
1420
+ "grants",
1421
+ "ladder",
1422
+ "caps",
1423
+ "rules"
1424
+ ]);
1425
+ var SAFETY_REASON_CODES = Object.freeze([
1426
+ "platform-stopped",
1427
+ "workspace-paused",
1428
+ "scope-paused",
1429
+ "rung-off",
1430
+ "rung-held",
1431
+ "ceiling-refused",
1432
+ "cap-reached",
1433
+ "grant-denied",
1434
+ "rule-blocked",
1435
+ "policy-refused",
1436
+ "unclassified-action",
1437
+ "instruction-widening-attempt",
1438
+ "non-human-actor",
1439
+ "safe-mode"
1440
+ ]);
1441
+ var SAFETY_ALLOW = Object.freeze({
1442
+ decision: "allow",
1443
+ railId: null,
1444
+ category: null,
1445
+ rung: null,
1446
+ reasonCode: null,
1447
+ summary: null
1448
+ });
1449
+ var AUTONOMY_GRANT_SCOPE_PRECEDENCE = Object.freeze([
1450
+ "workspace",
1451
+ "agent"
1452
+ ]);
1453
+ var RAIL_REFUSAL_SUBJECT_TYPES = Object.freeze([
1454
+ "run",
1455
+ "agent",
1456
+ "mission",
1457
+ "task",
1458
+ "schedule",
1459
+ "trigger"
1460
+ ]);
1461
+ var WORKSPACE_RUNNING = Object.freeze({
1462
+ paused: false,
1463
+ unverified: false,
1464
+ reason: null,
1465
+ pausedByUserId: null,
1466
+ pausedAt: null,
1467
+ refusedStarts: 0,
1468
+ cleanlyStopped: 0
1469
+ });
1470
+ var WORKSPACE_PAUSED_UNVERIFIED = Object.freeze({
1471
+ paused: true,
1472
+ unverified: true,
1473
+ reason: null,
1474
+ pausedByUserId: null,
1475
+ pausedAt: null,
1476
+ refusedStarts: 0,
1477
+ cleanlyStopped: 0
1478
+ });
1479
+ var READINESS_BLOCKERS = Object.freeze([
1480
+ "at-ceiling",
1481
+ "too-few-decisions",
1482
+ "approval-rate",
1483
+ "withdrawn",
1484
+ "other-refusals"
1485
+ ]);
1486
+ var EVER_STATS_KEY_HEADER = CONSTANTS.stats_headers.key;
1487
+ var EVER_STATS_SIGNATURE_HEADER = CONSTANTS.stats_headers.signature;
1488
+ var EVER_STATS_KEY_ID_HEADER = CONSTANTS.stats_headers.key_id;
1489
+ var EVER_STATS_SIGNATURE_PREFIX = CONSTANTS.stats_signature_prefix;
1490
+ var EVER_STATS_MAX_BODY_BYTES = CONSTANTS.stats.max_bytes;
1491
+
1492
+ // ../../plugin/dist/index.js
1493
+ var DEFAULT_DIFF_MAX_BYTES = 256 * 1024;
1494
+ var HARD_DIFF_MAX_BYTES = 1024 * 1024;
1495
+ var PLUGIN_CAPABILITIES = {
1496
+ AI_PROVIDER: "ai-provider",
1497
+ SEARCH: "search",
1498
+ SCREENSHOT: "screenshot",
1499
+ CONTENT_EXTRACTOR: "content-extractor",
1500
+ DATA_SOURCE: "data-source",
1501
+ PIPELINE: "pipeline",
1502
+ PIPELINE_MODIFIER: "pipeline-modifier",
1503
+ CODE_EDIT: "code-edit",
1504
+ FORM_SCHEMA_PROVIDER: "form-schema-provider",
1505
+ DEPLOYMENT: "deployment",
1506
+ GIT_PROVIDER: "git-provider",
1507
+ OAUTH: "oauth",
1508
+ DEVICE_AUTH: "device-auth",
1509
+ PROMPT_PROVIDER: "prompt-provider",
1510
+ // EW-637 — pluggable object storage. `put-object` + `get-object` are the
1511
+ // floor; `presigned-put` is opt-in for backends that can hand the
1512
+ // browser a direct-upload URL (S3, MinIO).
1513
+ STORAGE: "storage",
1514
+ PUT_OBJECT: "put-object",
1515
+ GET_OBJECT: "get-object",
1516
+ PRESIGNED_PUT: "presigned-put",
1517
+ // Agents/Skills/Tasks PR #1017 — Phase 8 (ADR-012). Plugin
1518
+ // category for Skill catalog providers. "Ever Works Skills" is
1519
+ // the first-party default; community plugins implement the same
1520
+ // `ISkillsProviderPlugin` contract to surface other catalogs.
1521
+ SKILLS_PROVIDER: "skills-provider",
1522
+ // Agents/Skills/Tasks PR #1017 — Phase 11 (ADR-013). Plugin
1523
+ // category for external task trackers. "Ever Works Task Tracker"
1524
+ // is the first-party default. Community plugins (Linear / Jira /
1525
+ // GitHub Issues) implement the same contract.
1526
+ TASK_TRACKER: "task-tracker",
1527
+ // Notifications v2 (EW-650) — Email Providers. Plugins MAY declare
1528
+ // `EMAIL_OUTBOUND`, `EMAIL_INBOUND`, or both. See
1529
+ // `capabilities/email-provider.interface.ts` for the contract.
1530
+ EMAIL_OUTBOUND: "email-outbound",
1531
+ EMAIL_INBOUND: "email-inbound",
1532
+ // Notifications v2 (sibling of EW-650) — Notification Channels.
1533
+ // Plugins declare `NOTIFICATION_CHANNEL` (umbrella) plus the
1534
+ // channel-specific constant for plugin discovery + UI grouping.
1535
+ // See `capabilities/notification-channel.interface.ts`.
1536
+ NOTIFICATION_CHANNEL: "notification-channel",
1537
+ NOTIFICATION_CHANNEL_DISCORD: "notification-channel-discord",
1538
+ NOTIFICATION_CHANNEL_SLACK: "notification-channel-slack",
1539
+ NOTIFICATION_CHANNEL_TELEGRAM: "notification-channel-telegram",
1540
+ NOTIFICATION_CHANNEL_WHATSAPP: "notification-channel-whatsapp",
1541
+ NOTIFICATION_CHANNEL_NOVU: "notification-channel-novu",
1542
+ // Connectors ("Connector fabric") — first-party BIDIRECTIONAL
1543
+ // communication-channel plugins. Each connector declares `CONNECTOR`
1544
+ // (umbrella, for discovery/grouping) plus its `CONNECTOR_<provider>`
1545
+ // constant. Superset of the outbound-only notification channels; see
1546
+ // `capabilities/connector.interface.ts`.
1547
+ CONNECTOR: "connector",
1548
+ CONNECTOR_SLACK: "connector-slack",
1549
+ CONNECTOR_DISCORD: "connector-discord",
1550
+ CONNECTOR_WHATSAPP: "connector-whatsapp",
1551
+ CONNECTOR_LINEAR: "connector-linear",
1552
+ CONNECTOR_NOTION: "connector-notion",
1553
+ CONNECTOR_MICROSOFT_365: "connector-microsoft-365",
1554
+ // CRM / enrichment connectors — first-party native connectors over
1555
+ // the vendors' own Node SDKs. Outbound writes CRM records/notes,
1556
+ // the event-source leg streams record changes into the ingest spine.
1557
+ CONNECTOR_HUBSPOT: "connector-hubspot",
1558
+ CONNECTOR_PIPEDRIVE: "connector-pipedrive",
1559
+ // Social connectors — public-timeline surfaces. Outbound publishes a
1560
+ // post; the event-source leg streams mentions/replies + the account's
1561
+ // own timeline into the ingest spine.
1562
+ CONNECTOR_BLUESKY: "connector-bluesky",
1563
+ CONNECTOR_MASTODON: "connector-mastodon",
1564
+ // Pluggable persistent memory for AI coding / generation agents.
1565
+ // First-party implementation: `@ever-works/agentmemory-plugin`
1566
+ // (talks to the `agentmemory` standalone Node server on :3111 —
1567
+ // runs locally OR hosted via a configurable `baseUrl` + bearer
1568
+ // token). Community plugins (mem0, zep, langmem) implement the
1569
+ // same `IAgentMemoryPlugin` contract.
1570
+ AGENT_MEMORY: "agent-memory",
1571
+ // Goals feature PR-7 — read-only metrics collectors. First-party
1572
+ // providers: `custom-http` (GET-only, SSRF-guarded) and `stripe`
1573
+ // (official SDK; balance + income windows). See
1574
+ // `capabilities/metrics-provider.interface.ts` for the contract.
1575
+ METRICS_PROVIDER: "metrics-provider",
1576
+ // Streaming-terminal session hosts (Wave 1 M5). First-party:
1577
+ // pty-local (node-pty in the executing job-runtime worker, with a
1578
+ // child_process pipe floor). Future: pty-ssh (user's own box),
1579
+ // k8s-exec. See capabilities/terminal-stream.interface.ts.
1580
+ TERMINAL_STREAM: "terminal-stream",
1581
+ // Isolated git working contexts for agent Tasks (Wave 2).
1582
+ WORKSPACE: "workspace",
1583
+ // Headless browser drivers (audit item G22). navigate / extract /
1584
+ // screenshot / act, headless by default, behind a default-deny
1585
+ // navigation allowlist re-checked on every redirect hop. First-party:
1586
+ // `browser-automation` (Playwright). See
1587
+ // capabilities/browser-automation.interface.ts.
1588
+ BROWSER_AUTOMATION: "browser-automation",
1589
+ // Event-ingest spine (Wave 6) — plugins that pull/push normalized
1590
+ // external events into the platform ingest pipeline. See
1591
+ // capabilities/event-source.interface.ts.
1592
+ EVENT_SOURCE: "event-source",
1593
+ // Capability & playbook catalogue (AW-21) — plugins that supply Playbook
1594
+ // catalogue entries (packaged outcomes: trigger, steps, required
1595
+ // capabilities, artefacts, escalation points). Consumed only through
1596
+ // PlaybookCatalogFacadeService. See
1597
+ // capabilities/playbook-provider.interface.ts.
1598
+ PLAYBOOK_PROVIDER: "playbook-provider",
1599
+ // AW-15 — optional access-level declaration ("Read only" / "Read and
1600
+ // write") mapped onto the tool-grant lattice. Declared alongside a
1601
+ // provider's main capability; see
1602
+ // capabilities/connection-scopes.interface.ts.
1603
+ CONNECTION_SCOPES: "connection-scopes",
1604
+ // App Works (APW-07 T3) — App dependency providers: the `k8s` plugin serves
1605
+ // the three in-cluster ids, `app-dependencies-external` the external ones,
1606
+ // and P2's `apps-tier-dependencies` the managed ones. Consumed only through
1607
+ // `AppDependencyFacadeService`; see
1608
+ // capabilities/app-dependency.interface.ts.
1609
+ APP_DEPENDENCY: "app-dependency",
1610
+ // App Works (APW-05 T2) — producing a container image from a commit. The
1611
+ // `github-actions-build` plugin declares it (`IBuildPlugin`, `buildKind
1612
+ // 'github-actions'`), and P3's `apps-builder` declares the same capability
1613
+ // with the other `buildKind`. Consumed only through `BuildFacadeService`
1614
+ // (APW-05 T16); see `capabilities/build.interface.ts`. Resolution R-13 keeps
1615
+ // `build` a CAPABILITY while the strategy (`dockerfile` / `image` / `auto` /
1616
+ // `none`) stays the App spec's own choice.
1617
+ BUILD: "build",
1618
+ // App Works (APW-12 T4) — the Ever ID relying-party capability. The
1619
+ // `oidc-identity` plugin declares it (APW-12 T5/T6), and it is consumed only
1620
+ // through `IdentityProviderFacadeService` (APW-12 plan §4.4); see
1621
+ // `capabilities/identity-provider.interface.ts`. Appended after `build`, and
1622
+ // landed in the same change as the `identity` category in
1623
+ // `plugin-manifest.types.ts` — a plugin contract with no category to be
1624
+ // discovered under is a manifest the loader rejects.
1625
+ IDENTITY_PROVIDER: "identity-provider",
1626
+ // App Works (APW-10 T2) — the managed hosting tier's zone capability. The
1627
+ // `ever-works-apps` plugin declares it together with `deployment`
1628
+ // (plan §5.2:602) and is consumed only through `AppsTierFacadeService`
1629
+ // (APW-10 plan §5.3:655); see `capabilities/apps-tier.interface.ts`.
1630
+ // Appended after `identity-provider`, and appended **last** on purpose:
1631
+ // every existing constant keeps its value and its position, because the
1632
+ // capability list is an append-only surface — a member that moves silently
1633
+ // changes what a persisted manifest means. Deliberately NOT paired with a
1634
+ // new category: the tier's plugin is a `deployment` plugin, so
1635
+ // `PLUGIN_CATEGORIES` is untouched and every exhaustive map over it in
1636
+ // `apps/web` stays total.
1637
+ APPS_TIER: "apps-tier"
1638
+ };
1639
+ var ALL_PLUGIN_CAPABILITIES = Object.values(PLUGIN_CAPABILITIES);
1640
+ function initializePipelineState(stepDefinitions) {
1641
+ const steps = /* @__PURE__ */ new Map();
1642
+ for (const def of stepDefinitions) {
1643
+ steps.set(def.id, { definition: def, status: "pending" });
1644
+ }
1645
+ return {
1646
+ steps,
1647
+ completedSteps: [],
1648
+ failedSteps: [],
1649
+ isRunning: true,
1650
+ isCancelled: false,
1651
+ startedAt: Date.now()
1652
+ };
1653
+ }
1654
+ function updatePipelineStepState(state, stepId, status, error) {
1655
+ const existing = state.steps.get(stepId);
1656
+ if (!existing) return state;
1657
+ const now = Date.now();
1658
+ const isTerminal = status === "completed" || status === "failed" || status === "skipped";
1659
+ const updated = {
1660
+ ...existing,
1661
+ status,
1662
+ startedAt: status === "running" ? now : existing.startedAt,
1663
+ completedAt: isTerminal ? now : existing.completedAt,
1664
+ error: error ?? existing.error
1665
+ };
1666
+ const steps = new Map(state.steps);
1667
+ steps.set(stepId, updated);
1668
+ const completedSteps = status === "completed" || status === "skipped" ? [...state.completedSteps, stepId] : state.completedSteps;
1669
+ const failedSteps = status === "failed" ? [...state.failedSteps, stepId] : state.failedSteps;
1670
+ return {
1671
+ ...state,
1672
+ steps,
1673
+ currentStep: status === "running" ? stepId : state.currentStep === stepId ? void 0 : state.currentStep,
1674
+ completedSteps,
1675
+ failedSteps
1676
+ };
1677
+ }
1678
+ function reportPipelineProgress(onProgress, totalSteps, stepIndex, percent, stepName, message, itemsProcessed) {
1679
+ onProgress?.({
1680
+ percent,
1681
+ currentStepIndex: stepIndex,
1682
+ totalSteps,
1683
+ currentStepName: stepName,
1684
+ message,
1685
+ itemsProcessed
1686
+ });
1687
+ }
1688
+ function reportPipelineItemProgress(onProgress, totalSteps, newItemCount, targetItems, stepIndex, stepName = "Generate Items") {
1689
+ const ratio = newItemCount / Math.max(targetItems, 1);
1690
+ const percent = Math.min(30 + Math.round(ratio * 53), 83);
1691
+ onProgress?.({
1692
+ percent,
1693
+ currentStepIndex: stepIndex,
1694
+ totalSteps,
1695
+ currentStepName: stepName,
1696
+ message: `${newItemCount} items generated`,
1697
+ itemsProcessed: newItemCount
1698
+ });
1699
+ }
1700
+ async function resolveScopedSettings(context, userId, workId) {
1701
+ if (!context) return {};
1702
+ try {
1703
+ const [userSettings, workSettings] = await Promise.all([
1704
+ context.getSettings("user", userId),
1705
+ context.getSettings("work", workId)
1706
+ ]);
1707
+ const merged = { ...userSettings };
1708
+ for (const key in workSettings) {
1709
+ if (workSettings[key] !== void 0 && workSettings[key] !== null) {
1710
+ merged[key] = workSettings[key];
1711
+ }
1712
+ }
1713
+ return merged;
1714
+ } catch (err) {
1715
+ const isAuthError = err instanceof Error && (/unauthorized|forbidden|access denied/i.test(err.message) || "status" in err && err.status === 401 || "status" in err && err.status === 403 || "statusCode" in err && err.statusCode === 401 || "statusCode" in err && err.statusCode === 403);
1716
+ if (isAuthError) {
1717
+ throw err;
1718
+ }
1719
+ context.logger?.warn(
1720
+ `resolveScopedSettings: failed to load settings for user=${userId} work=${workId}: ${err instanceof Error ? err.message : String(err)}`
1721
+ );
1722
+ return {};
1723
+ }
1724
+ }
1725
+ function buildPipelineMetrics(startTime, duration, itemCount, custom) {
1726
+ return {
1727
+ startTime,
1728
+ duration,
1729
+ itemsProcessed: itemCount,
1730
+ steps: {},
1731
+ ...custom ? { custom } : {}
1732
+ };
1733
+ }
1734
+ function finalizePipelineState(state) {
1735
+ return {
1736
+ ...state,
1737
+ isRunning: false,
1738
+ isCancelled: false,
1739
+ currentStep: void 0,
1740
+ completedAt: Date.now()
1741
+ };
1742
+ }
1743
+ function buildPipelineErrorResult(state, error, startTime, totalSteps, initializeState2) {
1744
+ let currentState = state ?? initializeState2();
1745
+ for (const [stepId, stepState] of currentState.steps) {
1746
+ if (stepState.status === "running") {
1747
+ currentState = updatePipelineStepState(currentState, stepId, "failed", error.message);
1748
+ break;
1749
+ }
1750
+ }
1751
+ currentState = {
1752
+ ...currentState,
1753
+ isRunning: false,
1754
+ isCancelled: false,
1755
+ currentStep: void 0,
1756
+ completedAt: Date.now()
1757
+ };
1758
+ return {
1759
+ state: currentState,
1760
+ result: buildErrorPipelineResult(error, {
1761
+ outputs: createEmptyPipelineOutputs(),
1762
+ duration: Date.now() - startTime,
1763
+ stepsCompleted: currentState.completedSteps.length,
1764
+ totalSteps,
1765
+ failedStep: currentState.failedSteps[currentState.failedSteps.length - 1],
1766
+ state: currentState
1767
+ })
1768
+ };
1769
+ }
1770
+ function buildPipelineCancelledResult(state, startTime, totalSteps, initializeState2) {
1771
+ const currentState = {
1772
+ ...state ?? initializeState2(),
1773
+ isRunning: false,
1774
+ isCancelled: true,
1775
+ currentStep: void 0,
1776
+ completedAt: Date.now()
1777
+ };
1778
+ return {
1779
+ state: currentState,
1780
+ result: buildCancelledPipelineResult({
1781
+ outputs: createEmptyPipelineOutputs(),
1782
+ duration: Date.now() - startTime,
1783
+ stepsCompleted: currentState.completedSteps.length,
1784
+ totalSteps,
1785
+ state: currentState
1786
+ })
1787
+ };
1788
+ }
1789
+ function delay(ms) {
1790
+ return new Promise((resolve) => setTimeout(resolve, ms));
1791
+ }
1792
+ function createPipelineRuntimeHelpers(options) {
1793
+ const initializeState2 = () => initializePipelineState(options.stepDefinitions);
1794
+ const updateStepState2 = (state, stepId, status, error) => updatePipelineStepState(state, stepId, status, error);
1795
+ const reportProgress2 = (onProgress, stepIndex, percent, stepName, message, itemsProcessed) => {
1796
+ reportPipelineProgress(onProgress, options.totalSteps, stepIndex, percent, stepName, message, itemsProcessed);
1797
+ };
1798
+ const reportItemProgress = (onProgress, newItemCount, targetItems, stepIndex, stepName = options.itemProgressStepName ?? "Generate Items") => {
1799
+ reportPipelineItemProgress(onProgress, options.totalSteps, newItemCount, targetItems, stepIndex, stepName);
1800
+ };
1801
+ const buildMetrics2 = (startTime, duration, itemCount, custom) => buildPipelineMetrics(startTime, duration, itemCount, custom);
1802
+ const finalizeCompletedState2 = (state) => finalizePipelineState(state);
1803
+ const buildErrorResult2 = (state, error, startTime) => buildPipelineErrorResult(state, error, startTime, options.totalSteps, initializeState2);
1804
+ const buildCancelledResult2 = (state, startTime) => buildPipelineCancelledResult(state, startTime, options.totalSteps, initializeState2);
1805
+ return {
1806
+ initializeState: initializeState2,
1807
+ updateStepState: updateStepState2,
1808
+ reportProgress: reportProgress2,
1809
+ reportItemProgress,
1810
+ resolveSettings: resolveScopedSettings,
1811
+ buildMetrics: buildMetrics2,
1812
+ finalizeCompletedState: finalizeCompletedState2,
1813
+ buildErrorResult: buildErrorResult2,
1814
+ buildCancelledResult: buildCancelledResult2,
1815
+ delay
1816
+ };
1817
+ }
1818
+ var ITEM_SCHEMA_PROMPT_TEXT = `
1819
+ Each item must be a JSON file with the following structure:
1820
+
1821
+ {
1822
+ "name": "string (required) - The item's canonical display name",
1823
+ "description": "string (required) - A concise, informative summary of the item and its relevance to the work topic (2-4 sentences). Generate from page content if not directly available.",
1824
+ "source_url": "string (required) - The most direct, canonical URL for the item itself (homepage or official page). Must be real and working. Never use blog posts or articles *about* the item.",
1825
+ "category": "string (required) - ONE primary category based on the item's core function (e.g., 'Monitoring', 'CI/CD', 'Data Visualization')",
1826
+ "tags": ["string"] - 1-3 specific, descriptive tags (e.g., "open-source", "real-time", "cloud-native"),
1827
+ "featured": boolean - Whether this is a notable/featured item (optional, default false),
1828
+ "slug": "string - URL-friendly identifier (optional, auto-generated from name if omitted)",
1829
+ "brand": "string - At most one brand/company name per item (optional)",
1830
+ "brand_logo_url": "string - Canonical logo URL from official domain, prefer SVG/PNG (optional)",
1831
+ "images": ["string"] - Multiple high-quality image URLs (screenshots, product imagery) from official sources (optional),
1832
+ "markdown": "string - Detailed product/service information in markdown: features, pricing, use cases (see Markdown Rules below). Do not repeat category, tags, or other metadata fields."
1833
+ }
1834
+
1835
+ Required fields: name, description, source_url, category
1836
+
1837
+ ### Example
1838
+
1839
+ \`\`\`json
1840
+ {
1841
+ "name": "Prometheus",
1842
+ "description": "Open-source monitoring and alerting toolkit designed for reliability and scalability, widely adopted in cloud-native environments.",
1843
+ "source_url": "https://prometheus.io",
1844
+ "category": "Monitoring",
1845
+ "tags": ["open-source", "metrics", "cloud-native"],
1846
+ "featured": false,
1847
+ "brand": "Cloud Native Computing Foundation",
1848
+ "brand_logo_url": "https://www.cncf.io/wp-content/uploads/2022/07/cncf-color-bg.svg",
1849
+ "images": ["https://prometheus.io/assets/architecture.png"],
1850
+ "markdown": "## Overview\\n\\nPrometheus is an open-source systems monitoring and alerting toolkit originally built at SoundCloud.\\n\\n## Features\\n\\n- Multi-dimensional data model with time series data identified by metric name and key/value pairs\\n- PromQL, a flexible query language\\n- No reliance on distributed storage; single server nodes are autonomous\\n- Time series collection via a pull model over HTTP\\n- Targets discovered via service discovery or static configuration\\n\\n## Pricing\\n\\nFree and open-source under the Apache 2.0 license."
1851
+ }
1852
+ \`\`\`
1853
+ `.trim();
1854
+ function createEmptyPipelineOutputs() {
1855
+ return {
1856
+ items: [],
1857
+ categories: [],
1858
+ tags: [],
1859
+ collections: [],
1860
+ brands: []
1861
+ };
1862
+ }
1863
+ function buildSuccessPipelineResult(outputs, base) {
1864
+ return {
1865
+ success: true,
1866
+ outputs,
1867
+ duration: base.duration,
1868
+ stepsCompleted: base.stepsCompleted,
1869
+ totalSteps: base.totalSteps,
1870
+ state: base.state,
1871
+ metrics: base.metrics,
1872
+ warnings: base.warnings
1873
+ };
1874
+ }
1875
+ function buildErrorPipelineResult(error, base) {
1876
+ return {
1877
+ success: false,
1878
+ outputs: base.outputs ?? createEmptyPipelineOutputs(),
1879
+ duration: base.duration,
1880
+ stepsCompleted: base.stepsCompleted,
1881
+ totalSteps: base.totalSteps,
1882
+ state: base.state,
1883
+ metrics: base.metrics,
1884
+ warnings: base.warnings,
1885
+ error,
1886
+ failedStep: base.failedStep
1887
+ };
1888
+ }
1889
+ function buildCancelledPipelineResult(base) {
1890
+ return buildErrorPipelineResult("Pipeline cancelled", base);
1891
+ }
1892
+
1893
+ // src/types.ts
1894
+ var MAKE_STEP_IDS = [
1895
+ "validate-make",
1896
+ "prepare-payload",
1897
+ "execute-scenario",
1898
+ "collect-results",
1899
+ "capture-screenshots",
1900
+ "cleanup"
1901
+ ];
1902
+ var DEFAULT_BASE_URL = "https://us2.make.com/api/v2";
1903
+ var DEFAULT_TARGET_ITEMS = 50;
1904
+ var DEFAULT_POLL_INTERVAL_MS = 3e3;
1905
+ var DEFAULT_MAX_POLL_ATTEMPTS = 600;
1906
+
1907
+ // src/steps.ts
1908
+ var STEP_DEFINITIONS = [
1909
+ {
1910
+ id: "validate-make",
1911
+ name: "Validate Make.com Connection",
1912
+ description: "Verify API key and check that the scenario or hook is reachable",
1913
+ position: { type: "first" },
1914
+ dependencies: [],
1915
+ optional: false,
1916
+ parallelizable: false,
1917
+ estimatedDuration: 3
1918
+ },
1919
+ {
1920
+ id: "prepare-payload",
1921
+ name: "Prepare Scenario Payload",
1922
+ description: "Build input payload from work context, existing items, and config",
1923
+ position: { type: "after", stepId: "validate-make" },
1924
+ dependencies: [{ stepId: "validate-make", required: true }],
1925
+ optional: false,
1926
+ parallelizable: false,
1927
+ estimatedDuration: 2
1928
+ },
1929
+ {
1930
+ id: "execute-scenario",
1931
+ name: "Execute Make.com Scenario",
1932
+ description: "Run the scenario via REST API (with polling) or invoke a webhook URL",
1933
+ position: { type: "after", stepId: "prepare-payload" },
1934
+ dependencies: [{ stepId: "prepare-payload", required: true }],
1935
+ optional: false,
1936
+ parallelizable: false,
1937
+ estimatedDuration: 120
1938
+ },
1939
+ {
1940
+ id: "collect-results",
1941
+ name: "Collect & Validate Results",
1942
+ description: "Parse Make.com scenario output, validate items, and deduplicate",
1943
+ position: { type: "after", stepId: "execute-scenario" },
1944
+ dependencies: [{ stepId: "execute-scenario", required: true }],
1945
+ optional: false,
1946
+ parallelizable: false,
1947
+ estimatedDuration: 5
1948
+ },
1949
+ {
1950
+ id: "capture-screenshots",
1951
+ name: "Capture Screenshots",
1952
+ description: "Capture screenshots for generated items",
1953
+ position: { type: "after", stepId: "collect-results" },
1954
+ dependencies: [{ stepId: "collect-results", required: true }],
1955
+ optional: true,
1956
+ parallelizable: false,
1957
+ estimatedDuration: 30
1958
+ },
1959
+ {
1960
+ id: "cleanup",
1961
+ name: "Cleanup",
1962
+ description: "Release resources and clear temporary data",
1963
+ position: { type: "last" },
1964
+ dependencies: [{ stepId: "capture-screenshots", required: false }],
1965
+ optional: true,
1966
+ parallelizable: false,
1967
+ estimatedDuration: 1
1968
+ }
1969
+ ];
1970
+
1971
+ // ../../plugin/dist/helpers/ssrf-guard.js
1972
+ var import_net = require("net");
1973
+ function isSafeWebhookUrl(rawUrl) {
1974
+ let url;
1975
+ try {
1976
+ url = new URL(rawUrl);
1977
+ } catch {
1978
+ return false;
1979
+ }
1980
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
1981
+ return false;
1982
+ }
1983
+ let host = url.hostname.toLowerCase();
1984
+ if (host.startsWith("[") && host.endsWith("]")) {
1985
+ host = host.slice(1, -1);
1986
+ }
1987
+ if (CLOUD_METADATA_HOSTNAMES.has(host)) {
1988
+ return false;
1989
+ }
1990
+ const ipKind = (0, import_net.isIP)(host);
1991
+ if (ipKind === 4 && isPrivateIPv4(host)) return false;
1992
+ if (ipKind === 6 && isPrivateIPv6(host)) return false;
1993
+ return true;
1994
+ }
1995
+ var CLOUD_METADATA_HOSTNAMES = /* @__PURE__ */ new Set([
1996
+ // GCP
1997
+ "metadata.google.internal",
1998
+ "metadata.goog",
1999
+ // AWS
2000
+ "instance-data",
2001
+ "instance-data.ec2.internal",
2002
+ // Azure
2003
+ "metadata.azure.internal"
2004
+ ]);
2005
+ function isPrivateIPv4(ip) {
2006
+ const parts = ip.split(".").map((p) => Number(p));
2007
+ if (parts.length !== 4 || parts.some((n) => Number.isNaN(n))) return false;
2008
+ const [a, b] = parts;
2009
+ if (a === 10) return true;
2010
+ if (a === 127) return true;
2011
+ if (a === 0) return true;
2012
+ if (a === 169 && b === 254) return true;
2013
+ if (a === 172 && b >= 16 && b <= 31) return true;
2014
+ if (a === 192 && b === 168) return true;
2015
+ if (a === 192 && b === 0 && parts[2] === 0) return true;
2016
+ if (a === 100 && b >= 64 && b <= 127) return true;
2017
+ if (a >= 224) return true;
2018
+ return false;
2019
+ }
2020
+ function isPrivateIPv6(ip) {
2021
+ const lower = ip.toLowerCase();
2022
+ if (lower === "::1" || lower === "::") return true;
2023
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
2024
+ const firstHextet = lower.split(":", 1)[0];
2025
+ if (/^[0-9a-f]{1,4}$/.test(firstHextet)) {
2026
+ const group0 = parseInt(firstHextet, 16);
2027
+ if ((group0 & 65472) === 65152) return true;
2028
+ }
2029
+ if (lower.startsWith("::ffff:")) {
2030
+ const v4 = lower.slice("::ffff:".length);
2031
+ if ((0, import_net.isIP)(v4) === 4) return isPrivateIPv4(v4);
2032
+ }
2033
+ return false;
2034
+ }
2035
+
2036
+ // src/utils/make-client.ts
2037
+ var MakeClient = class {
2038
+ constructor(options) {
2039
+ this.apiKey = options.apiKey;
2040
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
2041
+ this.teamId = options.teamId;
2042
+ this.organizationId = options.organizationId;
2043
+ this.logger = options.logger;
2044
+ }
2045
+ // ── Auth check / "who am I" ───────────────────────────────────────────
2046
+ async whoAmI(signal) {
2047
+ return this.request("/users/me", { signal });
2048
+ }
2049
+ // ── Scenarios ────────────────────────────────────────────────────────
2050
+ async listScenarios(signal) {
2051
+ const query = {};
2052
+ if (this.teamId) query.teamId = this.teamId;
2053
+ else if (this.organizationId) query.organizationId = this.organizationId;
2054
+ const data = await this.request("/scenarios", { query, signal });
2055
+ return Array.isArray(data?.scenarios) ? data.scenarios : [];
2056
+ }
2057
+ async getScenario(scenarioId, signal) {
2058
+ const data = await this.request(`/scenarios/${scenarioId}`, { signal });
2059
+ if (!data?.scenario) {
2060
+ throw new Error(`Scenario "${scenarioId}" not found`);
2061
+ }
2062
+ return data.scenario;
2063
+ }
2064
+ /**
2065
+ * Validates that a scenario exists and is ready to run.
2066
+ * Throws with a user-friendly message when the scenario is missing or inactive.
2067
+ */
2068
+ async validateScenario(scenarioId, signal) {
2069
+ const scenario = await this.getScenario(scenarioId, signal);
2070
+ if (scenario.isActive === false) {
2071
+ throw new Error(
2072
+ `Make.com scenario "${scenarioId}" is not active. Activate it in the Make.com dashboard first.`
2073
+ );
2074
+ }
2075
+ if (scenario.isPaused === true) {
2076
+ this.logger.warn(`Make.com scenario "${scenarioId}" is paused. Resuming may be required.`);
2077
+ }
2078
+ return scenario;
2079
+ }
2080
+ /**
2081
+ * Triggers a scenario run and returns the raw response.
2082
+ * Make exposes this as POST /scenarios/{scenarioId}/run
2083
+ */
2084
+ async runScenario(scenarioId, input, signal) {
2085
+ return await this.request(`/scenarios/${scenarioId}/run`, {
2086
+ method: "POST",
2087
+ body: { data: input, responsive: true },
2088
+ signal
2089
+ });
2090
+ }
2091
+ /**
2092
+ * Polls the execution status of a scenario run until it succeeds, errors,
2093
+ * the caller aborts, or we exceed the maximum number of attempts.
2094
+ *
2095
+ * Returns the final execution status alongside the number of poll attempts
2096
+ * made, so callers can surface polling telemetry.
2097
+ */
2098
+ async pollExecution(scenarioId, executionId, settings, onProgress, signal) {
2099
+ const intervalMs = settings.pollIntervalMs || DEFAULT_POLL_INTERVAL_MS;
2100
+ const maxAttempts = settings.maxPollAttempts || DEFAULT_MAX_POLL_ATTEMPTS;
2101
+ const deadline = Date.now() + (settings.timeoutMs || maxAttempts * intervalMs);
2102
+ let attempt = 0;
2103
+ while (attempt < maxAttempts) {
2104
+ if (signal?.aborted) throw new Error("Pipeline execution was cancelled");
2105
+ if (Date.now() > deadline) {
2106
+ throw new Error(
2107
+ `Make.com scenario execution timed out after ${Math.round((settings.timeoutMs || 0) / 1e3)}s`
2108
+ );
2109
+ }
2110
+ attempt += 1;
2111
+ const status = await this.request(`/scenarios/${scenarioId}/executions/${executionId}`, { signal });
2112
+ const exec = status?.execution ?? status;
2113
+ const normalizedStatus = String(exec?.status ?? "unknown").toLowerCase();
2114
+ onProgress?.(attempt, normalizedStatus);
2115
+ if (normalizedStatus === "success" || normalizedStatus === "completed") {
2116
+ return { status: exec, attempts: attempt };
2117
+ }
2118
+ if (normalizedStatus === "error" || normalizedStatus === "stopped" || normalizedStatus === "failed") {
2119
+ throw new Error(exec?.error || `Make.com scenario execution ${normalizedStatus}`);
2120
+ }
2121
+ await this.sleep(intervalMs, signal);
2122
+ }
2123
+ throw new Error(`Make.com scenario execution did not complete after ${maxAttempts} poll attempts`);
2124
+ }
2125
+ // ── Hooks (webhooks) ──────────────────────────────────────────────────
2126
+ async listHooks(signal) {
2127
+ const query = {};
2128
+ if (this.teamId) query.teamId = this.teamId;
2129
+ const data = await this.request("/hooks", { query, signal });
2130
+ return Array.isArray(data?.hooks) ? data.hooks : [];
2131
+ }
2132
+ async getHook(hookId, signal) {
2133
+ const data = await this.request(`/hooks/${hookId}`, { signal });
2134
+ if (!data?.hook) {
2135
+ throw new Error(`Hook "${hookId}" not found`);
2136
+ }
2137
+ return data.hook;
2138
+ }
2139
+ async pingHook(hookId, signal) {
2140
+ await this.request(`/hooks/${hookId}/ping`, { signal });
2141
+ }
2142
+ /**
2143
+ * Invokes a Make.com webhook URL with the given input.
2144
+ * Webhook URLs are independent of the REST API and return the scenario's
2145
+ * final output inline when the scenario uses a "Webhook Response" module.
2146
+ */
2147
+ async invokeWebhook(webhookUrl, input, signal) {
2148
+ if (!isSafeWebhookUrl(webhookUrl)) {
2149
+ throw new Error("Make.com webhook URL is not safe to call (SSRF guard blocked the destination host).");
2150
+ }
2151
+ const response = await fetch(webhookUrl, {
2152
+ method: "POST",
2153
+ headers: { "Content-Type": "application/json" },
2154
+ body: JSON.stringify(input),
2155
+ signal
2156
+ });
2157
+ const text = await response.text();
2158
+ if (!response.ok) {
2159
+ throw new Error(this.describeWebhookError(response.status, response.statusText, text));
2160
+ }
2161
+ try {
2162
+ return text ? JSON.parse(text) : {};
2163
+ } catch {
2164
+ return text;
2165
+ }
2166
+ }
2167
+ describeWebhookError(status, statusText, rawBody) {
2168
+ const body = truncate(rawBody);
2169
+ const base = `Make.com webhook returned ${status} ${statusText}`;
2170
+ if (status === 401 || status === 403) {
2171
+ return `${base}. The webhook rejected the request. Verify in the Make.com dashboard that (1) the scenario tied to this webhook is active, (2) the webhook URL zone matches your workspace (e.g. us2 vs eu1), and (3) the webhook module does not require an API key / mandatory headers. Response: ${body}`;
2172
+ }
2173
+ if (status === 404) {
2174
+ return `${base}. The webhook URL was not found. It may have been deleted or regenerated in Make.com. Response: ${body}`;
2175
+ }
2176
+ if (status === 410) {
2177
+ return `${base}. The webhook has been disabled in Make.com. Re-enable it or recreate the scenario. Response: ${body}`;
2178
+ }
2179
+ return `${base}: ${body}`;
2180
+ }
2181
+ // ── Internal HTTP helpers ────────────────────────────────────────────
2182
+ async request(path, options = {}) {
2183
+ const { method = "GET", query, body, signal } = options;
2184
+ const url = this.buildUrl(path, query);
2185
+ const response = await fetch(url, {
2186
+ method,
2187
+ headers: {
2188
+ Authorization: `Token ${this.apiKey}`,
2189
+ "Content-Type": "application/json",
2190
+ Accept: "application/json"
2191
+ },
2192
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
2193
+ signal
2194
+ });
2195
+ const text = await response.text();
2196
+ if (!response.ok) {
2197
+ throw this.wrapHttpError(response.status, response.statusText, text);
2198
+ }
2199
+ if (!text) return {};
2200
+ try {
2201
+ return JSON.parse(text);
2202
+ } catch {
2203
+ return text;
2204
+ }
2205
+ }
2206
+ buildUrl(path, query) {
2207
+ const url = new URL(`${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`);
2208
+ if (query) {
2209
+ for (const [key, value] of Object.entries(query)) {
2210
+ if (value !== void 0 && value !== null && value !== "") {
2211
+ url.searchParams.append(key, String(value));
2212
+ }
2213
+ }
2214
+ }
2215
+ const finalUrl = url.toString();
2216
+ if (!isSafeWebhookUrl(finalUrl)) {
2217
+ throw new Error("Make.com API base URL is not safe to call (SSRF guard blocked the destination host).");
2218
+ }
2219
+ return finalUrl;
2220
+ }
2221
+ wrapHttpError(status, statusText, rawBody) {
2222
+ const message = extractErrorMessage(rawBody) || statusText || "Unknown error";
2223
+ if (status === 401 || status === 403) {
2224
+ return new Error("Invalid Make.com API key or insufficient permissions. Please check the API key scopes.");
2225
+ }
2226
+ if (status === 404) {
2227
+ return new Error(`Make.com resource not found: ${message}`);
2228
+ }
2229
+ if (status === 429) {
2230
+ return new Error("Make.com rate limit exceeded. Please wait and try again.");
2231
+ }
2232
+ if (status >= 500) {
2233
+ return new Error(`Make.com service error (${status}): ${message}`);
2234
+ }
2235
+ return new Error(`Make.com request failed (${status}): ${message}`);
2236
+ }
2237
+ async sleep(ms, signal) {
2238
+ return new Promise((resolve, reject) => {
2239
+ if (signal?.aborted) {
2240
+ reject(new Error("Pipeline execution was cancelled"));
2241
+ return;
2242
+ }
2243
+ const timer = setTimeout(() => {
2244
+ signal?.removeEventListener("abort", onAbort);
2245
+ resolve();
2246
+ }, ms);
2247
+ const onAbort = () => {
2248
+ clearTimeout(timer);
2249
+ reject(new Error("Pipeline execution was cancelled"));
2250
+ };
2251
+ signal?.addEventListener("abort", onAbort, { once: true });
2252
+ });
2253
+ }
2254
+ };
2255
+ function extractErrorMessage(body) {
2256
+ if (!body) return void 0;
2257
+ try {
2258
+ const parsed = JSON.parse(body);
2259
+ return parsed.message || parsed.detail || parsed.error || void 0;
2260
+ } catch {
2261
+ return void 0;
2262
+ }
2263
+ }
2264
+ function truncate(str, max = 300) {
2265
+ if (!str) return "";
2266
+ return str.length > max ? `${str.slice(0, max)}\u2026` : str;
2267
+ }
2268
+
2269
+ // src/utils/payload-builder.ts
2270
+ var MAX_SCENARIO_PARAMS_DEPTH = 8;
2271
+ var MAX_SCENARIO_PARAMS_NODES = 5e3;
2272
+ function assertScenarioParamsWithinLimits(params) {
2273
+ let nodeCount = 0;
2274
+ const stack = [{ value: params, depth: 0 }];
2275
+ while (stack.length > 0) {
2276
+ const { value, depth } = stack.pop();
2277
+ if (depth > MAX_SCENARIO_PARAMS_DEPTH) {
2278
+ throw new Error(
2279
+ `Custom scenario parameters are nested too deeply (max ${MAX_SCENARIO_PARAMS_DEPTH} levels).`
2280
+ );
2281
+ }
2282
+ if (value === null || typeof value !== "object") {
2283
+ continue;
2284
+ }
2285
+ const entries = Array.isArray(value) ? value : Object.values(value);
2286
+ for (const child of entries) {
2287
+ nodeCount += 1;
2288
+ if (nodeCount > MAX_SCENARIO_PARAMS_NODES) {
2289
+ throw new Error(`Custom scenario parameters are too large (max ${MAX_SCENARIO_PARAMS_NODES} values).`);
2290
+ }
2291
+ if (child !== null && typeof child === "object") {
2292
+ stack.push({ value: child, depth: depth + 1 });
2293
+ }
2294
+ }
2295
+ }
2296
+ }
2297
+ function buildWorkflowPayload(options) {
2298
+ const { work, request, existing, config } = options;
2299
+ const payload = {
2300
+ metadata: {
2301
+ workId: work.id,
2302
+ workName: work.name,
2303
+ workSlug: work.slug,
2304
+ workDescription: work.description,
2305
+ prompt: request.prompt,
2306
+ generationMethod: request.generationMethod,
2307
+ targetItems: config.target_items ?? DEFAULT_TARGET_ITEMS
2308
+ }
2309
+ };
2310
+ if (config.pass_existing_items !== false && existing.items.length > 0) {
2311
+ payload.existingSummary = {
2312
+ totalItems: existing.items.length,
2313
+ categories: existing.categories.map((c) => c.name),
2314
+ tags: existing.tags.map((t) => t.name),
2315
+ sampleItems: existing.items.slice(0, 20).map((item) => ({
2316
+ name: item.name,
2317
+ url: item.source_url
2318
+ }))
2319
+ };
2320
+ }
2321
+ if (config.pass_repo_access && config.repo_url && isSafeWebhookUrl(config.repo_url)) {
2322
+ payload.dataSource = {
2323
+ type: "github-repo",
2324
+ repoUrl: config.repo_url,
2325
+ accessToken: config.repo_access_token,
2326
+ branch: config.repo_branch || "data",
2327
+ path: "items/"
2328
+ };
2329
+ }
2330
+ if (config.scenario_params && typeof config.scenario_params === "object") {
2331
+ const scenarioParams = config.scenario_params;
2332
+ assertScenarioParamsWithinLimits(scenarioParams);
2333
+ payload.scenarioParams = scenarioParams;
2334
+ }
2335
+ return payload;
2336
+ }
2337
+
2338
+ // src/utils/result-parser.ts
2339
+ function parseMakeOutput(raw) {
2340
+ if (!raw || typeof raw !== "object" && typeof raw !== "string") {
2341
+ throw new Error("Make.com scenario returned empty or non-object output");
2342
+ }
2343
+ const output = normalizeOutput(raw);
2344
+ const items = parseItems(output.items ?? []);
2345
+ if (items.length === 0) {
2346
+ throw new Error(
2347
+ "Make.com scenario returned a valid response but with no usable items. Ensure the final module emits a JSON object with an { items: [...] } array. Check the scenario execution logs in the Make.com dashboard."
2348
+ );
2349
+ }
2350
+ const categories = parseCategories(output.categories, items);
2351
+ const tags = parseTags(output.tags, items);
2352
+ const brands = parseBrands(output.brands, items);
2353
+ return { items, categories, tags, brands };
2354
+ }
2355
+ function normalizeOutput(raw) {
2356
+ if (typeof raw === "string") {
2357
+ const trimmed = raw.trim();
2358
+ if (/^accepted\.?$/i.test(trimmed)) {
2359
+ throw new Error(
2360
+ 'Make.com returned the default "Accepted" response, which means the scenario did not run a "Webhook Response" module. In the Make dashboard: (1) add a Webhooks \u2192 Webhook response module at the end of the scenario, (2) set Status=200 and Body to JSON like { "items": [...] }, (3) set a Content-Type: application/json custom header, (4) make sure the response module is connected on the same branch as the Webhook trigger and is reached on every run.'
2361
+ );
2362
+ }
2363
+ const unfenced = stripCodeFence(trimmed);
2364
+ const parsed = tryParse(unfenced);
2365
+ if (parsed !== null && typeof parsed === "object") {
2366
+ return normalizeOutput(parsed);
2367
+ }
2368
+ if (trimmed.startsWith("<")) {
2369
+ throw new Error(
2370
+ "Make.com webhook returned HTML instead of JSON. This typically means the scenario or webhook URL is proxied by an auth/CDN layer, or the URL is wrong. Verify the Webhook Response module returns Content-Type: application/json and that the URL points directly at hook.<zone>.make.com."
2371
+ );
2372
+ }
2373
+ const preview = trimmed.length > 200 ? trimmed.slice(0, 200) + "\u2026" : trimmed;
2374
+ throw new Error(
2375
+ `Make.com scenario returned a string that is not valid JSON. Ensure the Webhook Response module returns a JSON object with { items: [...] } and Content-Type: application/json. Received: ${preview}`
2376
+ );
2377
+ }
2378
+ if (Array.isArray(raw)) {
2379
+ return { items: raw };
2380
+ }
2381
+ const obj = raw;
2382
+ if ("items" in obj) {
2383
+ const items = Array.isArray(obj.items) ? obj.items : [];
2384
+ return {
2385
+ items,
2386
+ categories: obj.categories,
2387
+ tags: obj.tags,
2388
+ brands: obj.brands
2389
+ };
2390
+ }
2391
+ for (const key of ["output", "result", "data", "response", "body", "payload"]) {
2392
+ if (obj[key] != null && obj[key] !== "") {
2393
+ return normalizeOutput(obj[key]);
2394
+ }
2395
+ }
2396
+ if (typeof obj.message === "string") {
2397
+ const parsed = tryParse(obj.message);
2398
+ if (parsed !== null && typeof parsed === "object") {
2399
+ return normalizeOutput(parsed);
2400
+ }
2401
+ }
2402
+ throw new Error(
2403
+ `Make.com scenario output does not contain an "items" array. Expected format: { items: [...] } or a direct array of items. Received keys: ${Object.keys(obj).join(", ")}`
2404
+ );
2405
+ }
2406
+ function tryParse(str) {
2407
+ try {
2408
+ return JSON.parse(str);
2409
+ } catch {
2410
+ return null;
2411
+ }
2412
+ }
2413
+ function stripCodeFence(str) {
2414
+ const fence = /^```(?:json)?\s*([\s\S]*?)\s*```$/i;
2415
+ const match = str.match(fence);
2416
+ return match ? match[1].trim() : str;
2417
+ }
2418
+ function parseItems(rawItems) {
2419
+ const items = [];
2420
+ for (const raw of rawItems) {
2421
+ if (!raw || typeof raw !== "object") continue;
2422
+ const name = typeof raw.name === "string" ? raw.name.trim() : "";
2423
+ if (!name) continue;
2424
+ const description = typeof raw.description === "string" ? raw.description.trim() : "";
2425
+ const sourceUrl = typeof raw.url === "string" && raw.url.trim() ? raw.url.trim() : typeof raw.source_url === "string" && raw.source_url.trim() ? raw.source_url.trim() : "";
2426
+ const category = typeof raw.category === "string" ? raw.category.trim() : "";
2427
+ if (!description || !sourceUrl || !category) continue;
2428
+ const item = {
2429
+ name,
2430
+ description,
2431
+ source_url: sourceUrl,
2432
+ markdown: typeof raw.content === "string" ? raw.content : void 0,
2433
+ category,
2434
+ tags: Array.isArray(raw.tags) ? raw.tags.filter((t) => typeof t === "string") : [],
2435
+ brand: typeof raw.brand === "string" ? raw.brand.trim() : void 0,
2436
+ images: Array.isArray(raw.images) ? raw.images.filter((i) => typeof i === "string") : void 0
2437
+ };
2438
+ items.push(item);
2439
+ }
2440
+ return items;
2441
+ }
2442
+ function parseCategories(rawCategories, items) {
2443
+ const categoryNames = /* @__PURE__ */ new Set();
2444
+ if (Array.isArray(rawCategories)) {
2445
+ for (const cat of rawCategories) {
2446
+ if (cat && typeof cat.name === "string" && cat.name.trim()) {
2447
+ categoryNames.add(cat.name.trim());
2448
+ }
2449
+ }
2450
+ }
2451
+ for (const item of items) {
2452
+ if (typeof item.category === "string" && item.category) {
2453
+ categoryNames.add(item.category);
2454
+ } else if (Array.isArray(item.category)) {
2455
+ for (const c of item.category) {
2456
+ if (typeof c === "string" && c.trim()) categoryNames.add(c.trim());
2457
+ }
2458
+ }
2459
+ }
2460
+ return Array.from(categoryNames).map((name) => {
2461
+ const explicit = rawCategories?.find((c) => c.name === name);
2462
+ return {
2463
+ id: name.toLowerCase().replace(/\s+/g, "-"),
2464
+ name,
2465
+ description: explicit?.description
2466
+ };
2467
+ });
2468
+ }
2469
+ function parseTags(rawTags, items) {
2470
+ const tagNames = /* @__PURE__ */ new Set();
2471
+ if (Array.isArray(rawTags)) {
2472
+ for (const tag of rawTags) {
2473
+ if (tag && typeof tag.name === "string" && tag.name.trim()) {
2474
+ tagNames.add(tag.name.trim());
2475
+ }
2476
+ }
2477
+ }
2478
+ for (const item of items) {
2479
+ if (Array.isArray(item.tags)) {
2480
+ for (const t of item.tags) {
2481
+ if (typeof t === "string") tagNames.add(t);
2482
+ }
2483
+ }
2484
+ }
2485
+ return Array.from(tagNames).map((name) => ({
2486
+ id: name.toLowerCase().replace(/\s+/g, "-"),
2487
+ name
2488
+ }));
2489
+ }
2490
+ function parseBrands(rawBrands, items) {
2491
+ const brandNames = /* @__PURE__ */ new Set();
2492
+ if (Array.isArray(rawBrands)) {
2493
+ for (const brand of rawBrands) {
2494
+ if (brand && typeof brand.name === "string" && brand.name.trim()) {
2495
+ brandNames.add(brand.name.trim());
2496
+ }
2497
+ }
2498
+ }
2499
+ for (const item of items) {
2500
+ if (item.brand) {
2501
+ if (typeof item.brand === "string") {
2502
+ brandNames.add(item.brand);
2503
+ } else if (typeof item.brand === "object" && item.brand.name) {
2504
+ brandNames.add(item.brand.name);
2505
+ }
2506
+ }
2507
+ }
2508
+ return Array.from(brandNames).map((name) => {
2509
+ const explicit = rawBrands?.find((b) => b.name === name);
2510
+ return {
2511
+ id: name.toLowerCase().replace(/\s+/g, "-"),
2512
+ name,
2513
+ website: explicit?.url
2514
+ };
2515
+ });
2516
+ }
2517
+ function deduplicateItems(newItems, existingItemNames) {
2518
+ const existingSet = new Set(existingItemNames.map((n) => n.toLowerCase().trim()));
2519
+ return newItems.filter((item) => !existingSet.has(item.name.toLowerCase().trim()));
2520
+ }
2521
+
2522
+ // src/utils/pipeline-helpers.ts
2523
+ var runtime = createPipelineRuntimeHelpers({
2524
+ stepDefinitions: STEP_DEFINITIONS,
2525
+ totalSteps: MAKE_STEP_IDS.length
2526
+ });
2527
+ var initializeState = runtime.initializeState;
2528
+ var updateStepState = runtime.updateStepState;
2529
+ var reportProgress = runtime.reportProgress;
2530
+ var resolveSettings = runtime.resolveSettings;
2531
+ var finalizeCompletedState = runtime.finalizeCompletedState;
2532
+ var buildErrorResult = runtime.buildErrorResult;
2533
+ var buildCancelledResult = runtime.buildCancelledResult;
2534
+ function buildMetrics(startTime, duration, itemCount, makeMetrics) {
2535
+ return runtime.buildMetrics(startTime, duration, itemCount, makeMetrics);
2536
+ }
2537
+
2538
+ // src/form-schema.ts
2539
+ var REPO_ACCESS_CONDITION = { field: "pass_repo_access", operator: "eq", value: true };
2540
+ var SCENARIO_MODE_CONDITION = { field: "execution_mode", operator: "eq", value: "scenario" };
2541
+ var WEBHOOK_MODE_CONDITION = { field: "execution_mode", operator: "eq", value: "webhook" };
2542
+ function getFormFields() {
2543
+ return [
2544
+ {
2545
+ name: "execution_mode",
2546
+ type: "select",
2547
+ label: "Execution Mode",
2548
+ description: "How to trigger Make.com: REST scenario run (polled) or direct webhook URL",
2549
+ defaultValue: "scenario",
2550
+ options: [
2551
+ { value: "scenario", label: "Scenario (REST API)" },
2552
+ { value: "webhook", label: "Webhook URL" }
2553
+ ],
2554
+ group: "scenario"
2555
+ },
2556
+ {
2557
+ name: "scenario_id",
2558
+ type: "text",
2559
+ label: "Scenario ID",
2560
+ description: "Override the default scenario for this generation (optional if set in plugin settings)",
2561
+ placeholder: "e.g., 123456",
2562
+ group: "scenario",
2563
+ showIf: SCENARIO_MODE_CONDITION
2564
+ },
2565
+ {
2566
+ name: "hook_id",
2567
+ type: "text",
2568
+ label: "Hook ID",
2569
+ description: "Optional Make.com hook (webhook) ID to ping before the scenario runs",
2570
+ placeholder: "e.g., 987654",
2571
+ group: "scenario",
2572
+ showIf: SCENARIO_MODE_CONDITION
2573
+ },
2574
+ {
2575
+ name: "webhook_url",
2576
+ type: "text",
2577
+ label: "Webhook URL",
2578
+ description: "Override the default Make.com webhook URL",
2579
+ placeholder: "https://hook.us2.make.com/...",
2580
+ group: "scenario",
2581
+ showIf: WEBHOOK_MODE_CONDITION,
2582
+ requiredIf: WEBHOOK_MODE_CONDITION
2583
+ },
2584
+ {
2585
+ name: "target_items",
2586
+ type: "number",
2587
+ label: "Target Items",
2588
+ description: "Target number of new items to generate",
2589
+ defaultValue: DEFAULT_TARGET_ITEMS,
2590
+ validation: { min: 1, max: 500 },
2591
+ group: "scenario"
2592
+ },
2593
+ {
2594
+ name: "scenario_timeout",
2595
+ type: "number",
2596
+ label: "Scenario Timeout (minutes)",
2597
+ description: "Maximum time to wait for the Make.com scenario to complete",
2598
+ defaultValue: 30,
2599
+ validation: { min: 1, max: 120 },
2600
+ group: "scenario"
2601
+ },
2602
+ {
2603
+ name: "pass_existing_items",
2604
+ type: "boolean",
2605
+ label: "Pass Existing Items Summary",
2606
+ description: "Include a summary of existing work items in scenario input for deduplication",
2607
+ defaultValue: true,
2608
+ group: "data"
2609
+ },
2610
+ {
2611
+ name: "pass_repo_access",
2612
+ type: "boolean",
2613
+ label: "Pass Data Repository Access",
2614
+ description: "\u26A0\uFE0F Forwards your repository access token to Make.com (a third-party service) so its scenario can read the data repository. The token leaves Ever Works. Only enable for repos you trust Make.com with, and use a short-lived, read-only token.",
2615
+ defaultValue: false,
2616
+ group: "data"
2617
+ },
2618
+ {
2619
+ name: "repo_url",
2620
+ type: "text",
2621
+ label: "Data Repository URL",
2622
+ description: "GitHub repository URL containing work data",
2623
+ placeholder: "e.g., https://github.com/org/repo",
2624
+ group: "data",
2625
+ showIf: REPO_ACCESS_CONDITION,
2626
+ requiredIf: REPO_ACCESS_CONDITION
2627
+ },
2628
+ {
2629
+ name: "repo_access_token",
2630
+ type: "password",
2631
+ label: "Repository Access Token",
2632
+ description: "Read-only access token for the data repository (short-lived recommended)",
2633
+ placeholder: "ghp_...",
2634
+ group: "data",
2635
+ showIf: REPO_ACCESS_CONDITION,
2636
+ requiredIf: REPO_ACCESS_CONDITION
2637
+ },
2638
+ {
2639
+ name: "repo_branch",
2640
+ type: "text",
2641
+ label: "Repository Branch",
2642
+ description: "Branch to read from",
2643
+ defaultValue: "data",
2644
+ group: "data",
2645
+ showIf: REPO_ACCESS_CONDITION
2646
+ },
2647
+ {
2648
+ name: "capture_screenshots",
2649
+ type: "boolean",
2650
+ label: "Capture Screenshots",
2651
+ description: "Take screenshots for generated items (requires a screenshot plugin)",
2652
+ defaultValue: false,
2653
+ group: "features"
2654
+ },
2655
+ {
2656
+ name: "scenario_params",
2657
+ type: "json",
2658
+ label: "Custom Scenario Parameters",
2659
+ description: "Additional key-value parameters to pass to the Make.com scenario",
2660
+ defaultValue: {},
2661
+ group: "advanced"
2662
+ }
2663
+ ];
2664
+ }
2665
+ function getFormGroups() {
2666
+ return [
2667
+ {
2668
+ name: "scenario",
2669
+ title: "Scenario Configuration",
2670
+ description: "Configure which Make.com scenario or webhook to execute",
2671
+ order: 0
2672
+ },
2673
+ {
2674
+ name: "data",
2675
+ title: "Data Passing",
2676
+ description: "Configure how data is passed to the Make.com scenario",
2677
+ order: 1,
2678
+ collapsible: true,
2679
+ collapsed: false
2680
+ },
2681
+ {
2682
+ name: "features",
2683
+ title: "Features",
2684
+ description: "Optional generation features",
2685
+ order: 2,
2686
+ collapsible: true,
2687
+ collapsed: true
2688
+ },
2689
+ {
2690
+ name: "advanced",
2691
+ title: "Advanced",
2692
+ description: "Advanced scenario parameters",
2693
+ order: 3,
2694
+ collapsible: true,
2695
+ collapsed: true
2696
+ }
2697
+ ];
2698
+ }
2699
+ function validateFormInput(values) {
2700
+ const mode = values.execution_mode ?? "scenario";
2701
+ if (mode === "webhook") {
2702
+ if (!values.webhook_url || typeof values.webhook_url !== "string" || values.webhook_url.trim() === "") {
2703
+ return {
2704
+ valid: false,
2705
+ errors: [{ path: "webhook_url", message: "Webhook URL is required in webhook mode" }]
2706
+ };
2707
+ }
2708
+ if (!isSafeWebhookUrl(values.webhook_url.trim())) {
2709
+ return {
2710
+ valid: false,
2711
+ errors: [
2712
+ {
2713
+ path: "webhook_url",
2714
+ message: "Webhook URL must be a public https URL. Private, loopback, link-local, and cloud-metadata hosts are not allowed."
2715
+ }
2716
+ ]
2717
+ };
2718
+ }
2719
+ }
2720
+ if (values.pass_repo_access) {
2721
+ if (!values.repo_url || typeof values.repo_url !== "string" || values.repo_url.trim() === "") {
2722
+ return {
2723
+ valid: false,
2724
+ errors: [{ path: "repo_url", message: "Repository URL is required when repository access is enabled" }]
2725
+ };
2726
+ }
2727
+ if (!isSafeWebhookUrl(values.repo_url.trim())) {
2728
+ return {
2729
+ valid: false,
2730
+ errors: [
2731
+ {
2732
+ path: "repo_url",
2733
+ message: "Repository URL must be a public https URL. Private, loopback, link-local, and cloud-metadata hosts are not allowed."
2734
+ }
2735
+ ]
2736
+ };
2737
+ }
2738
+ if (!values.repo_access_token || typeof values.repo_access_token !== "string" || values.repo_access_token.trim() === "") {
2739
+ return {
2740
+ valid: false,
2741
+ errors: [
2742
+ {
2743
+ path: "repo_access_token",
2744
+ message: "Repository access token is required when repository access is enabled"
2745
+ }
2746
+ ]
2747
+ };
2748
+ }
2749
+ }
2750
+ return { valid: true };
2751
+ }
2752
+ function getDefaultValues(fields) {
2753
+ const defaults = {};
2754
+ for (const field of fields) {
2755
+ if (field.defaultValue !== void 0) {
2756
+ defaults[field.name] = field.defaultValue;
2757
+ }
2758
+ }
2759
+ return defaults;
2760
+ }
2761
+
2762
+ // src/readme.ts
2763
+ var README = [
2764
+ "## What is the Make.com Workflows plugin?",
2765
+ "",
2766
+ "This plugin delegates the work generation process to a [Make.com](https://www.make.com) scenario or webhook.",
2767
+ "Make.com (formerly Integromat) is a visual automation platform that lets you connect apps and services into powerful workflows (\u201Cscenarios\u201D).",
2768
+ "Instead of using the built-in generation pipeline, you design your own scenario on Make.com and this plugin triggers it at the right stage of the pipeline.",
2769
+ "",
2770
+ "## Why use it?",
2771
+ "",
2772
+ "- **Full control** \u2014 design your generation logic visually in Make.com",
2773
+ "- **Hundreds of integrations** \u2014 Make.com ships with 2,000+ pre-built app connectors",
2774
+ "- **Scenarios and webhooks** \u2014 trigger via REST API (with polling) or directly via webhook URL",
2775
+ "- **Hook management** \u2014 optionally ping a Make.com hook before running the scenario",
2776
+ "- **Deduplication** \u2014 existing work items are summarized and passed to the scenario to avoid duplicates",
2777
+ "",
2778
+ "## How it works",
2779
+ "",
2780
+ "1. **Validate** \u2014 checks your API key and verifies the scenario/hook is reachable",
2781
+ "2. **Prepare Payload** \u2014 builds the input with work metadata, existing items summary, and custom parameters",
2782
+ "3. **Execute Scenario** \u2014 runs the scenario via the REST API (`POST /scenarios/{id}/run` and polls `GET /scenarios/{id}/executions/{executionId}`) or invokes the webhook URL directly",
2783
+ "4. **Collect Results** \u2014 parses the scenario output into structured work items with categories, tags, and brands",
2784
+ "5. **Capture Screenshots** \u2014 optionally captures screenshots for generated items using the configured screenshot provider",
2785
+ "6. **Cleanup** \u2014 releases resources",
2786
+ "",
2787
+ "## Data passing strategies",
2788
+ "",
2789
+ "- **Inline summary** (default) \u2014 work metadata and a sample of existing items are sent in the scenario input payload",
2790
+ "- **GitHub repository** \u2014 pass a repo URL and access token so the scenario can read the full dataset directly",
2791
+ "",
2792
+ "## Scenario input & output",
2793
+ "",
2794
+ "Your Make.com scenario receives structured input fields and must return structured items.",
2795
+ "",
2796
+ "<details>",
2797
+ "<summary><strong>Input your scenario receives</strong></summary>",
2798
+ "",
2799
+ "```json",
2800
+ "{",
2801
+ ' "metadata": {',
2802
+ ' "workId": "dir-123",',
2803
+ ' "workName": "Best AI Tools",',
2804
+ ' "workSlug": "best-ai-tools",',
2805
+ ' "workDescription": "A curated list of the best AI tools",',
2806
+ ' "prompt": "Find the best AI writing tools",',
2807
+ ' "generationMethod": "create-update",',
2808
+ ' "targetItems": 50',
2809
+ " },",
2810
+ ' "existingSummary": {',
2811
+ ' "totalItems": 10,',
2812
+ ' "categories": ["Writing", "Image Generation"],',
2813
+ ' "tags": ["free", "open-source"],',
2814
+ ' "sampleItems": [',
2815
+ ' { "name": "ChatGPT", "url": "https://chat.openai.com" }',
2816
+ " ]",
2817
+ " },",
2818
+ ' "scenarioParams": {}',
2819
+ "}",
2820
+ "```",
2821
+ "",
2822
+ "- `existingSummary` is optional \u2014 absent if the work is empty or the user disabled it",
2823
+ "- `scenarioParams` contains any custom key-value pairs passed from the Advanced form section",
2824
+ "- `metadata.targetItems` is the number of new items the user wants",
2825
+ "",
2826
+ "</details>",
2827
+ "",
2828
+ "<details>",
2829
+ "<summary><strong>Output your scenario must return</strong></summary>",
2830
+ "",
2831
+ "Return a JSON object with an `items` array:",
2832
+ "",
2833
+ "```json",
2834
+ "{",
2835
+ ' "items": [',
2836
+ " {",
2837
+ ' "name": "Tool Name",',
2838
+ ' "description": "A concise description (1-3 sentences)",',
2839
+ ' "url": "https://example.com",',
2840
+ ' "category": "Category Name",',
2841
+ ' "tags": ["tag1", "tag2"],',
2842
+ ' "content": "Optional longer markdown content",',
2843
+ ' "brand": "Optional brand name",',
2844
+ ' "images": ["https://example.com/screenshot.png"]',
2845
+ " }",
2846
+ " ]",
2847
+ "}",
2848
+ "```",
2849
+ "",
2850
+ "**Required fields:** `name`, `description`, `url`, `category`, `tags`",
2851
+ "",
2852
+ "**Optional fields:** `content` (stored as markdown), `brand`, `images`",
2853
+ "",
2854
+ "</details>",
2855
+ "",
2856
+ "## Getting started",
2857
+ "",
2858
+ "1. Build and activate a scenario in [Make.com](https://www.make.com) (us2 zone)",
2859
+ "2. Generate an API key with all scopes enabled from the Make.com dashboard",
2860
+ "3. Enable this plugin and enter your API key and (optionally) team/organization ID in the settings",
2861
+ "4. When generating a work, select Make.com as the pipeline and provide the scenario ID or webhook URL"
2862
+ ].join("\n");
2863
+
2864
+ // src/make.plugin.ts
2865
+ var MakePlugin = class {
2866
+ constructor() {
2867
+ this.id = "make";
2868
+ this.name = "Make.com Workflows";
2869
+ this.version = "1.0.0";
2870
+ this.category = "pipeline";
2871
+ this.capabilities = ["pipeline", "form-schema-provider"];
2872
+ this.configurationMode = "user-required";
2873
+ this.handledConfigFields = ["*"];
2874
+ this.settingsSchema = {
2875
+ type: "object",
2876
+ properties: {
2877
+ apiKey: {
2878
+ type: "string",
2879
+ title: "Make.com API Key",
2880
+ description: "API token generated from your Make.com dashboard (with all scopes enabled).",
2881
+ "x-secret": true,
2882
+ "x-scope": "user",
2883
+ "x-envVar": "MAKE_API_KEY"
2884
+ },
2885
+ baseUrl: {
2886
+ type: "string",
2887
+ title: "Make.com API Base URL",
2888
+ description: "Zone-specific API base URL (e.g., https://us2.make.com/api/v2).",
2889
+ default: DEFAULT_BASE_URL,
2890
+ "x-scope": "user"
2891
+ },
2892
+ teamId: {
2893
+ type: "string",
2894
+ title: "Team ID",
2895
+ description: "Optional Make.com team ID used to scope scenario and hook queries.",
2896
+ "x-scope": "user"
2897
+ },
2898
+ organizationId: {
2899
+ type: "string",
2900
+ title: "Organization ID",
2901
+ description: "Optional Make.com organization ID used when no team ID is provided.",
2902
+ "x-scope": "user"
2903
+ },
2904
+ defaultScenarioId: {
2905
+ type: "string",
2906
+ title: "Default Scenario ID",
2907
+ description: "Default Make.com scenario to run when not specified in the generator form.",
2908
+ "x-scope": "user"
2909
+ },
2910
+ defaultHookId: {
2911
+ type: "string",
2912
+ title: "Default Hook ID",
2913
+ description: "Optional default Make.com hook (webhook) ID to ping during the pipeline.",
2914
+ "x-scope": "user"
2915
+ },
2916
+ defaultWebhookUrl: {
2917
+ type: "string",
2918
+ title: "Default Webhook URL",
2919
+ description: "Default webhook URL for webhook-mode execution (e.g. https://hook.us2.make.com/xyz).",
2920
+ "x-scope": "user"
2921
+ }
2922
+ },
2923
+ required: ["apiKey"]
2924
+ };
2925
+ this.context = null;
2926
+ this._lastState = null;
2927
+ this._lastAbortController = null;
2928
+ }
2929
+ // ── IPlugin lifecycle ──────────────────────────────────────────────
2930
+ async onLoad(context) {
2931
+ this.context = context;
2932
+ context.logger.log("Make.com Workflows plugin loaded");
2933
+ }
2934
+ async onUnload() {
2935
+ await this.cancel();
2936
+ this.context = null;
2937
+ }
2938
+ async healthCheck() {
2939
+ return {
2940
+ status: "healthy",
2941
+ message: "Make.com Workflows plugin is ready",
2942
+ checkedAt: Date.now()
2943
+ };
2944
+ }
2945
+ async isAvailable(settings) {
2946
+ const resolved = settings || {};
2947
+ const apiKey = resolved.apiKey;
2948
+ return !!apiKey && apiKey.trim().length > 0;
2949
+ }
2950
+ async validateSettings(settings) {
2951
+ const apiKey = settings.apiKey;
2952
+ if (!apiKey || apiKey.trim() === "") {
2953
+ return { valid: false, errors: [{ path: "apiKey", message: "Make.com API key is required" }] };
2954
+ }
2955
+ return { valid: true };
2956
+ }
2957
+ async validateConnection(rawSettings) {
2958
+ const settings = this.flattenSettings(rawSettings);
2959
+ const apiKey = settings.apiKey;
2960
+ if (!apiKey) {
2961
+ return { success: false, message: "Make.com API key is required" };
2962
+ }
2963
+ try {
2964
+ const baseUrl = settings.baseUrl || DEFAULT_BASE_URL;
2965
+ if (!isSafeWebhookUrl(baseUrl)) {
2966
+ return {
2967
+ success: false,
2968
+ message: "Make.com API base URL is not allowed (must be a public HTTPS host)."
2969
+ };
2970
+ }
2971
+ if (!isMakeHost(baseUrl)) {
2972
+ return {
2973
+ success: false,
2974
+ message: "Make.com API base URL must be an HTTPS make.com host (e.g. https://us2.make.com/api/v2)."
2975
+ };
2976
+ }
2977
+ const client = new MakeClient({
2978
+ apiKey,
2979
+ baseUrl,
2980
+ teamId: settings.teamId,
2981
+ organizationId: settings.organizationId,
2982
+ logger: this.context?.logger ?? console
2983
+ });
2984
+ const scenarioId = settings.defaultScenarioId;
2985
+ if (scenarioId) {
2986
+ await client.validateScenario(scenarioId);
2987
+ return {
2988
+ success: true,
2989
+ message: `Connected to Make.com. Scenario "${scenarioId}" is active and ready.`
2990
+ };
2991
+ }
2992
+ await client.whoAmI();
2993
+ return { success: true, message: "Connected to Make.com successfully." };
2994
+ } catch (error) {
2995
+ const message = error instanceof Error ? error.message : "Connection validation failed";
2996
+ return { success: false, message };
2997
+ }
2998
+ }
2999
+ getManifest() {
3000
+ return {
3001
+ id: this.id,
3002
+ name: this.name,
3003
+ version: this.version,
3004
+ description: "Pipeline plugin that delegates work generation to Make.com scenarios and webhooks",
3005
+ category: this.category,
3006
+ capabilities: [...this.capabilities],
3007
+ author: { name: "Ever Works Team" },
3008
+ license: "AGPL-3.0",
3009
+ builtIn: true,
3010
+ autoEnable: false,
3011
+ visibility: "public",
3012
+ selectableProviderCategories: ["screenshot"],
3013
+ uiHints: {
3014
+ includeInOnboarding: true,
3015
+ onboardingPriority: 2,
3016
+ completionFields: ["apiKey"],
3017
+ onboardingDescription: "Connect Make.com to delegate work generation to visual automation scenarios and webhooks."
3018
+ },
3019
+ readme: README,
3020
+ homepage: "https://developers.make.com/api-documentation",
3021
+ icon: {
3022
+ type: "url",
3023
+ value: "https://www.make.com/favicon.ico"
3024
+ }
3025
+ };
3026
+ }
3027
+ // ── IFormSchemaProvider ─────────────────────────────────────────────
3028
+ getFormFields() {
3029
+ return getFormFields();
3030
+ }
3031
+ getFormGroups() {
3032
+ return getFormGroups();
3033
+ }
3034
+ validateFormInput(values) {
3035
+ return validateFormInput(values);
3036
+ }
3037
+ getDefaultValues() {
3038
+ return getDefaultValues(this.getFormFields());
3039
+ }
3040
+ // ── IPipelinePlugin ─────────────────────────────────────────────────
3041
+ getStepDefinitions() {
3042
+ return STEP_DEFINITIONS;
3043
+ }
3044
+ async execute(work, request, existing, options, onProgress) {
3045
+ const startTime = Date.now();
3046
+ const abortController = new AbortController();
3047
+ if (options?.signal) {
3048
+ if (options.signal.aborted) {
3049
+ abortController.abort();
3050
+ } else {
3051
+ options.signal.addEventListener("abort", () => abortController.abort(), { once: true });
3052
+ }
3053
+ }
3054
+ const signal = abortController.signal;
3055
+ let state = initializeState();
3056
+ this._lastState = state;
3057
+ this._lastAbortController = abortController;
3058
+ const setState = (stepId, status, error) => {
3059
+ state = updateStepState(state, stepId, status, error);
3060
+ this._lastState = state;
3061
+ };
3062
+ const handleError = (error) => {
3063
+ const { result, state: s } = buildErrorResult(state, error, startTime);
3064
+ state = s;
3065
+ this._lastState = state;
3066
+ return result;
3067
+ };
3068
+ const handleCancel = () => {
3069
+ const { result, state: s } = buildCancelledResult(state, startTime);
3070
+ state = s;
3071
+ this._lastState = state;
3072
+ return result;
3073
+ };
3074
+ const logger = this.context?.logger ?? console;
3075
+ const userId = work.user?.id;
3076
+ if (!userId) {
3077
+ return handleError(new Error("User ID is required"));
3078
+ }
3079
+ try {
3080
+ const pluginSettings = await resolveSettings(this.context, userId, work.id);
3081
+ const config = request.config || {};
3082
+ const makeSettings = this.resolveMakeSettings(pluginSettings, config);
3083
+ const { mode, scenarioId, hookId, webhookUrl } = this.resolveExecutionTarget(config, makeSettings);
3084
+ if (mode === "scenario" && !scenarioId) {
3085
+ return handleError(
3086
+ new Error(
3087
+ "No Make.com scenario ID provided. Set it in the generator form or in plugin settings (defaultScenarioId)."
3088
+ )
3089
+ );
3090
+ }
3091
+ if (mode === "webhook" && !webhookUrl) {
3092
+ return handleError(
3093
+ new Error(
3094
+ "No Make.com webhook URL provided. Set it in the generator form or in plugin settings (defaultWebhookUrl)."
3095
+ )
3096
+ );
3097
+ }
3098
+ const client = new MakeClient({
3099
+ apiKey: makeSettings.apiKey,
3100
+ baseUrl: makeSettings.baseUrl,
3101
+ teamId: makeSettings.teamId,
3102
+ organizationId: makeSettings.organizationId,
3103
+ logger
3104
+ });
3105
+ setState("validate-make", "running");
3106
+ reportProgress(onProgress, 0, 5, "Validate Make.com Connection");
3107
+ if (mode === "scenario" && scenarioId) {
3108
+ await client.validateScenario(scenarioId, signal);
3109
+ } else if (mode === "webhook") {
3110
+ await client.whoAmI(signal);
3111
+ }
3112
+ if (hookId) {
3113
+ try {
3114
+ await client.pingHook(hookId, signal);
3115
+ } catch (error) {
3116
+ const reason = error instanceof Error ? error.message : "Unknown error";
3117
+ logger.warn(`Make.com hook ping failed for "${hookId}": ${reason}`);
3118
+ }
3119
+ }
3120
+ setState("validate-make", "completed");
3121
+ if (signal.aborted) return handleCancel();
3122
+ setState("prepare-payload", "running");
3123
+ reportProgress(onProgress, 1, 10, "Prepare Scenario Payload");
3124
+ const payload = buildWorkflowPayload({ work, request, existing, config });
3125
+ logger.log(
3126
+ `Payload prepared: ${payload.metadata.targetItems} target items, ${payload.existingSummary?.totalItems ?? 0} existing items, dataSource=${payload.dataSource?.type ?? "none"}`
3127
+ );
3128
+ setState("prepare-payload", "completed");
3129
+ if (signal.aborted) return handleCancel();
3130
+ setState("execute-scenario", "running");
3131
+ let execResult;
3132
+ if (mode === "scenario" && scenarioId) {
3133
+ reportProgress(onProgress, 2, 15, "Execute Make.com Scenario", `Starting scenario "${scenarioId}"...`);
3134
+ const runStart = Date.now();
3135
+ if (hookId) {
3136
+ reportProgress(onProgress, 2, 30, "Execute Make.com Scenario", "Resolving webhook URL...");
3137
+ const hook = await client.getHook(hookId, signal);
3138
+ if (!hook.url) {
3139
+ throw new Error(
3140
+ `Make.com hook "${hookId}" does not expose a URL. Switch to webhook execution mode and set the webhook URL directly, or remove the hook ID to rely on REST /run.`
3141
+ );
3142
+ }
3143
+ reportProgress(onProgress, 2, 45, "Execute Make.com Scenario", "Invoking scenario...");
3144
+ const output = await client.invokeWebhook(hook.url, payload, signal);
3145
+ execResult = {
3146
+ output,
3147
+ pollingAttempts: 0,
3148
+ makeDuration: Date.now() - runStart
3149
+ };
3150
+ } else {
3151
+ const run = await client.runScenario(scenarioId, payload, signal);
3152
+ const executionId = run.executionId ?? this.extractExecutionId(run);
3153
+ const inlineOutput = extractInlineOutput(run);
3154
+ if (inlineOutput !== void 0) {
3155
+ execResult = {
3156
+ output: inlineOutput,
3157
+ pollingAttempts: 0,
3158
+ makeDuration: Date.now() - runStart,
3159
+ executionId
3160
+ };
3161
+ } else if (executionId) {
3162
+ const { status, attempts } = await client.pollExecution(
3163
+ scenarioId,
3164
+ executionId,
3165
+ makeSettings,
3166
+ (attempt, statusName) => {
3167
+ const percent = Math.min(15 + Math.round(attempt / 60 * 55), 70);
3168
+ reportProgress(
3169
+ onProgress,
3170
+ 2,
3171
+ percent,
3172
+ "Execute Make.com Scenario",
3173
+ `Execution ${statusName} (poll #${attempt})...`
3174
+ );
3175
+ },
3176
+ signal
3177
+ );
3178
+ execResult = {
3179
+ output: status.output ?? status.result ?? status.data ?? status,
3180
+ pollingAttempts: attempts,
3181
+ makeDuration: Date.now() - runStart,
3182
+ executionId
3183
+ };
3184
+ } else {
3185
+ execResult = {
3186
+ output: run.output ?? run.result ?? run.data ?? run,
3187
+ pollingAttempts: 0,
3188
+ makeDuration: Date.now() - runStart
3189
+ };
3190
+ }
3191
+ }
3192
+ } else {
3193
+ reportProgress(onProgress, 2, 15, "Execute Make.com Scenario", "Invoking webhook...");
3194
+ const runStart = Date.now();
3195
+ const output = await client.invokeWebhook(webhookUrl, payload, signal);
3196
+ execResult = {
3197
+ output,
3198
+ pollingAttempts: 0,
3199
+ makeDuration: Date.now() - runStart
3200
+ };
3201
+ }
3202
+ logger.log(
3203
+ `Make.com execution completed. Mode: ${mode}, duration: ${execResult.makeDuration ?? "unknown"}ms`
3204
+ );
3205
+ setState("execute-scenario", "completed");
3206
+ if (signal.aborted) return handleCancel();
3207
+ setState("collect-results", "running");
3208
+ reportProgress(onProgress, 3, 75, "Collect & Validate Results");
3209
+ logger.log(`Received Make.com output (${describeOutputShape(execResult.output)})`);
3210
+ const parsed = parseMakeOutput(execResult.output);
3211
+ const existingNames = existing.items.map((i) => i.name);
3212
+ const items = deduplicateItems(parsed.items, existingNames);
3213
+ logger.log(
3214
+ `Collected ${parsed.items.length} items from Make.com, ${parsed.items.length - items.length} duplicates removed, ${items.length} new items`
3215
+ );
3216
+ setState("collect-results", "completed");
3217
+ const screenshotWarnings = await this.captureScreenshots(
3218
+ setState,
3219
+ request,
3220
+ options?.execContext,
3221
+ items,
3222
+ { userId, workId: work.id },
3223
+ signal,
3224
+ onProgress,
3225
+ logger
3226
+ );
3227
+ setState("cleanup", "running");
3228
+ reportProgress(onProgress, 5, 95, "Cleanup");
3229
+ setState("cleanup", "completed");
3230
+ reportProgress(onProgress, 6, 100, "Complete");
3231
+ const duration = Date.now() - startTime;
3232
+ const metrics = {
3233
+ executionMode: mode,
3234
+ scenarioId,
3235
+ hookId,
3236
+ executionId: execResult.executionId,
3237
+ makeDuration: execResult.makeDuration
3238
+ };
3239
+ state = finalizeCompletedState(state);
3240
+ this._lastState = state;
3241
+ return buildSuccessPipelineResult(
3242
+ {
3243
+ items,
3244
+ categories: parsed.categories,
3245
+ tags: parsed.tags,
3246
+ brands: parsed.brands,
3247
+ collections: []
3248
+ },
3249
+ {
3250
+ metrics: buildMetrics(startTime, duration, items.length, metrics),
3251
+ duration,
3252
+ stepsCompleted: state.completedSteps.length,
3253
+ totalSteps: MAKE_STEP_IDS.length,
3254
+ state,
3255
+ warnings: screenshotWarnings.length > 0 ? screenshotWarnings : void 0
3256
+ }
3257
+ );
3258
+ } catch (error) {
3259
+ const err = error instanceof Error ? error : new Error(String(error));
3260
+ logger.error(`Make.com pipeline failed: ${err.message}`);
3261
+ return handleError(err);
3262
+ } finally {
3263
+ if (this._lastAbortController === abortController) {
3264
+ this._lastAbortController = null;
3265
+ }
3266
+ }
3267
+ }
3268
+ async cancel() {
3269
+ this._lastAbortController?.abort();
3270
+ }
3271
+ getState() {
3272
+ return this._lastState;
3273
+ }
3274
+ // ── Private helpers ────────────────────────────────────────────────
3275
+ resolveMakeSettings(pluginSettings, config) {
3276
+ const apiKey = pluginSettings.apiKey;
3277
+ if (!apiKey) {
3278
+ throw new Error("Make.com API key is not configured. Please set it in plugin settings.");
3279
+ }
3280
+ const timeoutMinutes = config.scenario_timeout || 30;
3281
+ const mode = config.execution_mode || "scenario";
3282
+ const baseUrl = pluginSettings.baseUrl || DEFAULT_BASE_URL;
3283
+ if (!isSafeWebhookUrl(baseUrl)) {
3284
+ throw new Error("Make.com API base URL is not allowed (must be a public HTTPS host).");
3285
+ }
3286
+ if (!isMakeHost(baseUrl)) {
3287
+ throw new Error("Make.com API base URL must be an HTTPS make.com host (e.g. https://us2.make.com/api/v2).");
3288
+ }
3289
+ return {
3290
+ apiKey,
3291
+ baseUrl,
3292
+ teamId: pluginSettings.teamId || void 0,
3293
+ organizationId: pluginSettings.organizationId || void 0,
3294
+ defaultScenarioId: pluginSettings.defaultScenarioId,
3295
+ defaultHookId: pluginSettings.defaultHookId,
3296
+ defaultWebhookUrl: pluginSettings.defaultWebhookUrl,
3297
+ executionMode: mode,
3298
+ timeoutMs: timeoutMinutes * 60 * 1e3,
3299
+ pollIntervalMs: DEFAULT_POLL_INTERVAL_MS,
3300
+ maxPollAttempts: DEFAULT_MAX_POLL_ATTEMPTS
3301
+ };
3302
+ }
3303
+ resolveExecutionTarget(config, settings) {
3304
+ const mode = config.execution_mode || settings.executionMode || "scenario";
3305
+ const scenarioFromConfig = config.scenario_id?.trim();
3306
+ const hookFromConfig = config.hook_id?.trim();
3307
+ const webhookFromConfig = config.webhook_url?.trim();
3308
+ return {
3309
+ mode,
3310
+ scenarioId: scenarioFromConfig || settings.defaultScenarioId,
3311
+ hookId: hookFromConfig || settings.defaultHookId,
3312
+ webhookUrl: webhookFromConfig || settings.defaultWebhookUrl
3313
+ };
3314
+ }
3315
+ extractExecutionId(run) {
3316
+ const candidates = ["executionId", "execution_id", "imtId", "id"];
3317
+ for (const key of candidates) {
3318
+ const value = run[key];
3319
+ if (typeof value === "string" && value.trim()) return value;
3320
+ if (typeof value === "number") return String(value);
3321
+ }
3322
+ const execution = run.execution;
3323
+ if (execution) {
3324
+ const nested = execution.id ?? execution.imtId ?? execution.executionId;
3325
+ if (typeof nested === "string" && nested.trim()) return nested;
3326
+ if (typeof nested === "number") return String(nested);
3327
+ }
3328
+ return void 0;
3329
+ }
3330
+ async captureScreenshots(setState, request, execContext, items, facadeOptions, signal, onProgress, logger) {
3331
+ const shouldCapture = (request.config || {}).capture_screenshots === true;
3332
+ const screenshotFacade = execContext?.screenshotFacade;
3333
+ if (!shouldCapture || items.length === 0 || signal.aborted || !screenshotFacade) {
3334
+ setState("capture-screenshots", "skipped");
3335
+ return [];
3336
+ }
3337
+ if (!screenshotFacade.isAvailable()) {
3338
+ setState("capture-screenshots", "skipped");
3339
+ return ["Screenshot provider is not configured. Enable a screenshot plugin to capture item images."];
3340
+ }
3341
+ setState("capture-screenshots", "running");
3342
+ reportProgress(onProgress, 4, 80, "Capture Screenshots");
3343
+ const errors = [];
3344
+ const itemsNeedingImages = items.filter(
3345
+ (item) => item.source_url && (!item.images || item.images.length === 0)
3346
+ );
3347
+ for (const item of itemsNeedingImages) {
3348
+ if (signal.aborted) break;
3349
+ try {
3350
+ const result = await screenshotFacade.getSmartImage(
3351
+ { url: item.source_url, itemName: item.name },
3352
+ facadeOptions
3353
+ );
3354
+ if (result.primaryImage) {
3355
+ item.images = [result.primaryImage, ...item.images || []];
3356
+ }
3357
+ } catch (error) {
3358
+ const reason = error instanceof Error ? error.message : "Unknown error";
3359
+ logger.warn(`Failed to capture image for ${item.name}: ${reason}`);
3360
+ errors.push(reason);
3361
+ }
3362
+ }
3363
+ setState(
3364
+ "capture-screenshots",
3365
+ errors.length > 0 && errors.length === itemsNeedingImages.length ? "failed" : "completed"
3366
+ );
3367
+ if (errors.length > 0) {
3368
+ const providerName = await screenshotFacade.getActiveProviderName?.(facadeOptions);
3369
+ const label = providerName ? `Screenshot capture (${providerName})` : "Screenshot capture";
3370
+ const unique = [...new Set(errors)];
3371
+ return [`${label} failed for ${errors.length} item(s): ${unique.join("; ")}`];
3372
+ }
3373
+ return [];
3374
+ }
3375
+ /**
3376
+ * Flatten a ResolvedSettings map into plain key->value pairs.
3377
+ */
3378
+ flattenSettings(settings) {
3379
+ const flat = {};
3380
+ for (const [key, entry] of Object.entries(settings)) {
3381
+ if (entry && typeof entry === "object" && "value" in entry) {
3382
+ flat[key] = entry.value;
3383
+ } else {
3384
+ flat[key] = entry;
3385
+ }
3386
+ }
3387
+ return flat;
3388
+ }
3389
+ };
3390
+ function isMakeHost(url) {
3391
+ let parsed;
3392
+ try {
3393
+ parsed = new URL(url);
3394
+ } catch {
3395
+ return false;
3396
+ }
3397
+ if (parsed.protocol !== "https:") return false;
3398
+ const host = parsed.hostname.toLowerCase();
3399
+ return host === "make.com" || host.endsWith(".make.com");
3400
+ }
3401
+ function extractInlineOutput(run) {
3402
+ const candidateKeys = ["outputs", "output", "result", "data", "body", "payload", "response"];
3403
+ for (const key of candidateKeys) {
3404
+ const value = run[key];
3405
+ if (value === void 0 || value === null) continue;
3406
+ if (key === "response" && typeof value === "object") {
3407
+ const body = value.body;
3408
+ if (body !== void 0 && body !== null) return unwrapJsonString(body);
3409
+ continue;
3410
+ }
3411
+ return unwrapJsonString(value);
3412
+ }
3413
+ return void 0;
3414
+ }
3415
+ function unwrapJsonString(value) {
3416
+ if (typeof value !== "string") return value;
3417
+ const trimmed = value.trim();
3418
+ if (!trimmed) return value;
3419
+ try {
3420
+ return JSON.parse(trimmed);
3421
+ } catch {
3422
+ return value;
3423
+ }
3424
+ }
3425
+ function describeOutputShape(output) {
3426
+ if (output === null) return "type=null";
3427
+ if (output === void 0) return "type=undefined";
3428
+ if (Array.isArray(output)) return `type=array, length=${output.length}`;
3429
+ if (typeof output === "string") return `type=string, length=${output.length}`;
3430
+ if (typeof output === "object") {
3431
+ const keys = Object.keys(output);
3432
+ return `type=object, keys=[${keys.slice(0, 10).join(", ")}${keys.length > 10 ? ", \u2026" : ""}]`;
3433
+ }
3434
+ return `type=${typeof output}`;
3435
+ }
3436
+ var make_plugin_default = MakePlugin;
3437
+ // Annotate the CommonJS export names for ESM import in node:
3438
+ 0 && (module.exports = {
3439
+ MakePlugin
3440
+ });
3441
+ /**
3442
+ * One header finding of the licence scan (plan §2.6:324-325, FR-54): the
3443
+ * `SPDX-License-Identifier:` / `@license` tag a file declares in its first
3444
+ * `LICENSE_HEADER_SCAN_BYTES` bytes.
3445
+ *
3446
+ * **Gap, named rather than guessed:** plan §3.1:437 writes the column's third
3447
+ * field as `headerFindings: …` without a shape. `path` is certain — it is the
3448
+ * first field of the scan's input — and the detected identifier is the second
3449
+ * fact the scan produces, so both are declared; anything further an
3450
+ * implementation adds is additive.
3451
+ */