@koda-sl/baker-cli 0.851.0-dev.38f83ef80 → 0.851.0-dev.914922aaf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5283,7 +5283,7 @@ baker hubspot meetings view <slug> --as-node # the form.external blob for a f
5283
5283
  **`contacts summary` flags:** `--days <1-365>` (default 30) over contact creation date. Returns counts only — total contacts, how many have an owner, and the lifecycle-stage split — never a name or an email. `truncated: true` means the page budget ran out, so the counts are floors.
5284
5284
  **`contacts lookup`:** positional `<email>`; returns that contact's lifecycle stage, owner, the account (company) it was filed under, and associated deals with their stage. `dealsReadable: false` / `companyReadable: false` mean the connection does not cover deals or accounts, so an empty `deals` or a null `company` is unknown rather than absent. `found: false` means no contact with that email — the lead never reached the CRM, which is a finding rather than an error. `--properties utm_campaign,utm_source` (up to 25) also returns those contact properties under `contact.properties`, each value or `null`; a name the account does not define is left out and named in a hint.
5285
5285
  **`contacts properties`:** no flags; returns every contact property with a closed list of values — `{ name, label, groupName, options: [{ value, label }] }` — the ones a HubSpot-read source can watch. Names are HubSpot's internal ones; hand them to `baker analytics sources --create-hubspot --property <name> --value <value>` as printed. No personal data.
5286
- **`meetings list` flags:** `--search <text>`, `--redirecting-only`.
5286
+ **`meetings list` flags:** `--search <text>` (a piece of the calendar's name or slug, or a pasted booking link such as `meetings.hubspot.com/<slug>`), `--redirecting-only`.
5287
5287
  **`meetings view`:** positional `<slug>` — the only reliable source for a calendar's booking fields (HubSpot omits `customParams` from the list endpoint, so `fieldCount: null` there means unknown, not zero); `--as-node` as above.
5288
5288
 
5289
5289
  **`HUBSPOT_RECONNECT_REQUIRED`** is returned when HubSpot is connected but that account never granted access to what the command needs — a HubSpot grant is fixed at the moment the user approves it, so an account connected before a capability shipped cannot serve it. It is not the same as `NO_HUBSPOT_CONNECTION`: the connection works, and only the user can widen it by reconnecting from Brain → Integrations → Platforms. The error carries a `fix` describing exactly that.
@@ -5462,8 +5462,7 @@ baker accounts company acme.com # or a LinkedIn company i
5462
5462
  baker accounts campaigns --last-months 6 --output md # per campaign: reached, engaged, influenced pipeline (--basis revenue)
5463
5463
  baker accounts influenced --model awareness --threshold 10 --output csv # another rule, this call only
5464
5464
  baker accounts warm --min 0 # every New/Rising company, below the threshold too
5465
- baker accounts warm --accounts targets # the warm target accounts, read from the target-accounts Knowledge
5466
- baker accounts engagement --targets targets.csv # only the target accounts; targets: reached/engaged per tier (--full lists notReached)
5465
+ baker accounts engagement --targets targets.csv # only the target accounts; targets: reached/engaged per tier, notReached
5467
5466
  baker accounts people acme.com --roles "CMO,Marketing Director" # who we already know there: CRM, earlier finds, Form leads
5468
5467
  baker accounts alerts --since 2026-10-01 # every company a warm-account alert fired on (--company, --limit, --full)
5469
5468
  baker accounts crm status # deals from HubSpot or sent by the client; what arrived, linked Google Sheets
@@ -5472,7 +5471,7 @@ baker accounts crm check --file deals.csv # judge a deals or compan
5472
5471
  baker accounts crm contract # the send-your-CRM contract, as Markdown for a developer
5473
5472
  ```
5474
5473
 
5475
- A deal is **influenced** when its company reached the company's influence rule — by default 3+ LinkedIn ad engagements (Awareness: 7+ impressions; Intent: 3+ clicks) — in the 12 months up to and including the month the deal was created (`--basis pipeline`, deals not won) or closed won (`--basis revenue`). It is a labelled rule, not credit: campaign rows overlap, and money is reported per currency, never summed across currencies. Deals whose company match is only a guess come back under `lowConfidence` and stay out of `summary` until the match is confirmed in Measure → Accounts. Without the deals set up there — HubSpot's pipelines and won/lost stages, or Another CRM — `influenced` and `campaigns` exit 1 with `ACCOUNTS_NOT_SET_UP`. A CRM Baker cannot read sends its companies and deals to `POST /v1/accounts/crm` (a `crm_ingest` key, `X-Baker-Mode: test` to rehearse, up to 500 records per request, records naming a person refused), is uploaded as a CSV in Measure → Accounts, or lives in a Google Sheet linked there that Baker reads every night (a row deleted from the sheet leaves Baker). A file is a deals export or a company list — a company needs only its website or LinkedIn page; `crm check` runs the same rules offline and `crm contract` prints the whole contract. The CLI never sends deals or links a sheet of the client's; `crm sheet` creates the empty deals sheet in their Google Drive and links it, applied at once (asking again returns the same sheet). `--model engagement|awareness|intent` and `--threshold N` on `influenced`, `campaigns` and `warm` read with another rule for that call only; the saved setting is unchanged. A **warm** account is New or Rising, reached the company's influence threshold this period on the rule's metric (`--min N` overrides, `--min 0` drops it), and has no open deal, no won deal and no deal lost in the last 6 months; `engagement` and `warm` rows carry `dealStatus` (`won` > `open` > `lost` > `none`), `engagement --output csv` adds `lastMonth` and `previousImpressions/Clicks/Engagements`, and `campaigns` / `company` carry each campaign's `campaignName` (null when LinkedIn could not name it). `company` returns `months` (the company's totals), `byCampaign` (the same numbers per campaign — overlapping, never add them) and its `deals` with `touchValue` and `influenced`. `warm --output csv` is the file `baker ads linkedin audiences create --type company-list --list-file` takes. `--targets <file>` on `engagement`, `influenced`, `campaigns` and `warm` narrows the report to an ABM target list — a CSV with a domain or website column (name and tier optional) or a JSON array of domains or `{domain, name, tier}` — reduced to registrable domains; rows, totals and pages count the targets only, and the answer adds `targets` `{total, reached, engaged, byTier}` (`engagement --full` adds `notReached`, the targets never reached). `warm --accounts targets` keeps the warm target accounts of `--targets`, else of the published target-accounts Knowledge. `people <domain> [--roles "A,B"]` lists who Baker already knows at one company, for free — HubSpot contacts (never their email), ActiveCampaign contacts at the domain and earlier `baker data` finds — each with its `source`, plus the count of Form leads from the domain, each source's state (`read`, `not_connected`, `failed`) and, with `--roles`, `roleMatch` per person and the `missingRoles` nobody known holds. Company rows carry `isTarget`, `tier` and `alertedAt`; targets come from `--targets` or the published target-accounts Knowledge, matched on LinkedIn page, website or name, and with `--targets` `engagement` and `influenced` add `comparison.{targets,others}`. `alerts [--since YYYY-MM-DD] [--company <LinkedIn id|urn>] [--limit 1-1000] [--full]` lists every company a warm-account alert fired on (`orgId, name, domain, alertedAt, isTarget, tier, agent`; `--full` adds `scheduledAgentId, runChatId, month`), as `{alerts, truncated}`.
5474
+ A deal is **influenced** when its company reached the company's influence rule — by default 3+ LinkedIn ad engagements (Awareness: 7+ impressions; Intent: 3+ clicks) — in the 12 months up to and including the month the deal was created (`--basis pipeline`, deals not won) or closed won (`--basis revenue`). It is a labelled rule, not credit: campaign rows overlap, and money is reported per currency, never summed across currencies. Deals whose company match is only a guess come back under `lowConfidence` and stay out of `summary` until the match is confirmed in Measure → Accounts. Without the deals set up there — HubSpot's pipelines and won/lost stages, or Another CRM — `influenced` and `campaigns` exit 1 with `ACCOUNTS_NOT_SET_UP`. A CRM Baker cannot read sends its companies and deals to `POST /v1/accounts/crm` (a `crm_ingest` key, `X-Baker-Mode: test` to rehearse, up to 500 records per request, records naming a person refused), is uploaded as a CSV in Measure → Accounts, or lives in a Google Sheet linked there that Baker reads every night (a row deleted from the sheet leaves Baker). A file is a deals export or a company list — a company needs only its website or LinkedIn page; `crm check` runs the same rules offline and `crm contract` prints the whole contract. The CLI never sends deals or links a sheet of the client's; `crm sheet` creates the empty deals sheet in their Google Drive and links it, applied at once (asking again returns the same sheet). `--model engagement|awareness|intent` and `--threshold N` on `influenced`, `campaigns` and `warm` read with another rule for that call only; the saved setting is unchanged. A **warm** account is New or Rising, reached the company's influence threshold this period on the rule's metric (`--min N` overrides, `--min 0` drops it), and has no open deal, no won deal and no deal lost in the last 6 months; `engagement` and `warm` rows carry `dealStatus` (`won` > `open` > `lost` > `none`), `engagement --output csv` adds `lastMonth` and `previousImpressions/Clicks/Engagements`, and `campaigns` / `company` carry each campaign's `campaignName` (null when LinkedIn could not name it). `company` returns `months` (the company's totals), `byCampaign` (the same numbers per campaign — overlapping, never add them) and its `deals` with `touchValue` and `influenced`. `warm --output csv` is the file `baker ads linkedin audiences create --type company-list --list-file` takes. `--targets <file>` on `engagement`, `influenced`, `campaigns` and `warm` narrows the report to an ABM target list — a CSV with a domain or website column (name and tier optional) or a JSON array of domains or `{domain, name, tier}` — reduced to registrable domains; rows, totals and pages count the targets only, and the answer adds `targets` `{total, reached, engaged, notReached, byTier}`. `people <domain> [--roles "A,B"]` lists who Baker already knows at one company, for free — HubSpot contacts (never their email), ActiveCampaign contacts at the domain and earlier `baker data` finds — each with its `source`, plus the count of Form leads from the domain, each source's state (`read`, `not_connected`, `failed`) and, with `--roles`, `roleMatch` per person and the `missingRoles` nobody known holds. Company rows carry `isTarget`, `tier` and `alertedAt`; targets come from `--targets` or the published target-accounts Knowledge, matched on LinkedIn page, website or name, and with `--targets` `engagement` and `influenced` add `comparison.{targets,others}`. `alerts [--since YYYY-MM-DD] [--company <LinkedIn id|urn>] [--limit 1-1000] [--full]` lists every company a warm-account alert fired on (`orgId, name, domain, alertedAt, isTarget, tier, agent`; `--full` adds `scheduledAgentId, runChatId, month`), as `{alerts, truncated}`.
5476
5475
 
5477
5476
  ---
5478
5477
 
@@ -10,13 +10,12 @@ import {
10
10
  invalidArgsMessage,
11
11
  setupHint,
12
12
  targetsHints,
13
- targetsView,
14
13
  warmAccountsCsv,
15
14
  warmHints,
16
15
  warmMetric,
17
16
  warmMinimum,
18
17
  withDealStatus
19
- } from "./chunk-HS5NGBXW.js";
18
+ } from "./chunk-4X6QBNIB.js";
20
19
  import {
21
20
  ACCOUNTS_ENGAGEMENT_MAX_LIMIT,
22
21
  INFLUENCE_MODEL_KINDS,
@@ -131,7 +130,7 @@ var WINDOW_ARGS = withWindowSpellings({
131
130
  var TARGETS_ARG = {
132
131
  targets: {
133
132
  type: "string",
134
- description: 'Only these target accounts: a .csv (a domain or website column; name, tier and organizationUrn optional) or a .json file (["acme.com", \u2026] or [{"domain": "acme.com", "tier": 1}, \u2026]). A company is a target by its LinkedIn page, its website or its name \u2014 the same match as `baker ads linkedin companies --targets` and the warm-account alerts. Rows and numbers narrow to them, `targets` says how many were reached and engaged, per tier (`baker accounts engagement --targets <file> --full` lists the ones never reached), and `comparison` sets the targets beside every other company. Build one from the Knowledge with `node __tooling__/scripts/target-accounts.mjs --out targets.csv`',
133
+ description: 'Only these target accounts: a .csv (a domain or website column; name, tier and organizationUrn optional) or a .json file (["acme.com", \u2026] or [{"domain": "acme.com", "tier": 1}, \u2026]). A company is a target by its LinkedIn page, its website or its name \u2014 the same match as `baker ads linkedin companies --targets` and the warm-account alerts. Rows and numbers narrow to them, `targets` says how many were reached and engaged, per tier, and which were never reached, and `comparison` sets the targets beside every other company. Build one from the Knowledge with `node __tooling__/scripts/target-accounts.mjs --out targets.csv`',
135
134
  required: false
136
135
  }
137
136
  };
@@ -147,11 +146,8 @@ function targetsInput(args) {
147
146
  if (read.targets.length === 0) failInvalidArgs(`--targets: ${path} names no company website.`);
148
147
  return read;
149
148
  }
150
- function withTargetsHints(hints, read, summary, listed = false) {
151
- return read === null ? hints : [...targetsHints(summary, read.unreadable, listed), ...hints];
152
- }
153
- function targetsBlock(summary, listed = false) {
154
- return summary ? { targets: targetsView(summary, listed) } : {};
149
+ function withTargetsHints(hints, read, summary) {
150
+ return read === null ? hints : [...targetsHints(summary, read.unreadable), ...hints];
155
151
  }
156
152
  function windowInput(args) {
157
153
  return {
@@ -239,12 +235,7 @@ var influencedCommand = defineCommand({
239
235
  writeAdsOutput(rows, format, DEAL_TABLE_FIELDS, [influencedSummaryLine(response.data), ...hints]);
240
236
  return;
241
237
  }
242
- writeJson({
243
- ...response,
244
- data: { ...response.data, ...targetsBlock(response.data.targets) },
245
- meta: { count: response.data.deals.length },
246
- ...hints.length > 0 ? { hints } : {}
247
- });
238
+ writeJson({ ...response, meta: { count: response.data.deals.length }, ...hints.length > 0 ? { hints } : {} });
248
239
  } catch (err) {
249
240
  failAccounts(err);
250
241
  }
@@ -264,17 +255,11 @@ var ENGAGEMENT_ARGS = {
264
255
  required: false
265
256
  },
266
257
  ...TARGETS_ARG,
267
- full: {
268
- type: "boolean",
269
- description: "With --targets: also list every target account never reached (targets.notReached)",
270
- required: false,
271
- default: false
272
- },
273
258
  output: OUTPUT_ARG
274
259
  };
275
260
  registerSchema({
276
261
  command: "accounts.engagement",
277
- description: "Every company the LinkedIn ads reached, most engaged first, with the period before for comparison, New/Rising flags, and where it stands in the CRM (matched company; dealStatus won > open > lost > none, lost meaning every deal it had was lost; lastLostAt). Default the last 3 calendar months. From the nightly sync, so it is fast and covers up to 24 months; for a live read of one ad account use `baker ads linkedin companies`. Paged: --limit companies per page, --page N; pageInfo {page, pageSize, total, hasMore}. --targets <file> keeps the target accounts only and adds `targets` {total, reached, engaged, byTier}; --full adds notReached, the targets never reached.",
262
+ description: "Every company the LinkedIn ads reached, most engaged first, with the period before for comparison, New/Rising flags, and where it stands in the CRM (matched company; dealStatus won > open > lost > none, lost meaning every deal it had was lost; lastLostAt). Default the last 3 calendar months. From the nightly sync, so it is fast and covers up to 24 months; for a live read of one ad account use `baker ads linkedin companies`. Paged: --limit companies per page, --page N; pageInfo {page, pageSize, total, hasMore}. --targets <file> keeps the target accounts only and adds `targets` {total, reached, engaged, notReached, byTier}.",
278
263
  args: ENGAGEMENT_ARGS
279
264
  });
280
265
  function engagementInput(args, targets, limit) {
@@ -306,8 +291,7 @@ var engagementCommand = defineCommand({
306
291
  ...engagementHints(response.data, parsed.data)
307
292
  ],
308
293
  targets,
309
- response.data.targets,
310
- Boolean(args.full)
294
+ response.data.targets
311
295
  );
312
296
  if (format !== "json") {
313
297
  writeAdsOutput(engagementTableRows(response.data.companies), format, ENGAGEMENT_TABLE_FIELDS, hints);
@@ -316,7 +300,7 @@ var engagementCommand = defineCommand({
316
300
  const companies = withDealStatus(response.data.companies);
317
301
  writeJson({
318
302
  ...response,
319
- data: { ...response.data, ...targetsBlock(response.data.targets, Boolean(args.full)), companies },
303
+ data: { ...response.data, companies },
320
304
  meta: { count: companies.length, ...response.data.pageInfo ? { total: response.data.pageInfo.total } : {} },
321
305
  ...hints.length > 0 ? { hints } : {}
322
306
  });
@@ -328,8 +312,7 @@ var engagementCommand = defineCommand({
328
312
  var warmRuleSchema = z.object({
329
313
  model: z.enum(INFLUENCE_MODEL_KINDS).optional(),
330
314
  threshold: z.number().int().min(1).optional(),
331
- min: z.number().int().min(0).optional(),
332
- accounts: z.enum(["all", "targets"]).default("all")
315
+ min: z.number().int().min(0).optional()
333
316
  });
334
317
  var WARM_ARGS = {
335
318
  ...WINDOW_ARGS,
@@ -341,11 +324,6 @@ var WARM_ARGS = {
341
324
  },
342
325
  ...RULE_ARGS,
343
326
  ...TARGETS_ARG,
344
- accounts: {
345
- type: "string",
346
- description: "all (default) or targets: only the target accounts \u2014 those of --targets, else of the published target-accounts Knowledge (each row's isTarget), so no file is needed",
347
- required: false
348
- },
349
327
  output: {
350
328
  type: "string",
351
329
  description: "json (default) or csv \u2014 csv prints companyName,domain,organizationUrn, the file `baker ads linkedin audiences create --type company-list --list-file` takes",
@@ -355,7 +333,7 @@ var WARM_ARGS = {
355
333
  };
356
334
  registerSchema({
357
335
  command: "accounts.warm",
358
- description: "Warm accounts: companies engaging with the LinkedIn ads more than in the period before (New: nothing before; Rising: engagements at least doubled) that reached the company's influence threshold this period (e.g. 3+ engagements; --min overrides, --min 0 drops it) and are not already somebody's deal: no open deal, never won (customers are left out), and no deal lost in the last 6 months (an older loss no longer counts). Default the current calendar month against the one before. `--output csv > warm.csv` writes a company list ready for `baker ads linkedin audiences create --type company-list --list-file warm.csv` (LinkedIn needs 300+ matched members to serve). Start here for 'which target accounts are warming': --accounts targets keeps the warm target accounts of the published target-accounts Knowledge, no file needed. --targets <file> keeps those of an ad-hoc list instead and adds `targets` (how many were reached and engaged; `baker accounts engagement --targets <file> --full` lists the ones never reached).",
336
+ description: "Warm accounts: companies engaging with the LinkedIn ads more than in the period before (New: nothing before; Rising: engagements at least doubled) that reached the company's influence threshold this period (e.g. 3+ engagements; --min overrides, --min 0 drops it) and are not already somebody's deal: no open deal, never won (customers are left out), and no deal lost in the last 6 months (an older loss no longer counts). Default the current calendar month against the one before. `--output csv > warm.csv` writes a company list ready for `baker ads linkedin audiences create --type company-list --list-file warm.csv` (LinkedIn needs 300+ matched members to serve). --targets <file> keeps the warm target accounts only and adds `targets` (reached and engaged among them).",
359
337
  args: WARM_ARGS
360
338
  });
361
339
  var warmCommand = defineCommand({
@@ -366,11 +344,7 @@ var warmCommand = defineCommand({
366
344
  args: WARM_ARGS,
367
345
  run: async ({ args }) => {
368
346
  const format = outputFormat(args, ["json", "csv"]);
369
- const rule = warmRuleSchema.safeParse({
370
- ...ruleInput(args),
371
- min: optionalNumber(args.min),
372
- accounts: optionalString(args.accounts)
373
- });
347
+ const rule = warmRuleSchema.safeParse({ ...ruleInput(args), min: optionalNumber(args.min) });
374
348
  if (!rule.success) failInvalid(rule.error.issues);
375
349
  const targets = targetsInput(args);
376
350
  const input = engagementInput(args, targets, ACCOUNTS_ENGAGEMENT_MAX_LIMIT);
@@ -382,14 +356,9 @@ var warmCommand = defineCommand({
382
356
  const response = await apiPost("/api/accounts/engagement", parsed.data);
383
357
  const minimum = warmMinimum(response.data.rule, rule.data);
384
358
  const metric = warmMetric(response.data.rule, rule.data);
385
- const warming = warmAccounts(response.data.companies, (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), { minimum, metric });
386
- const warm = rule.data.accounts === "targets" ? warming.filter((row) => row.isTarget === true) : warming;
359
+ const warm = warmAccounts(response.data.companies, (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), { minimum, metric });
387
360
  const hints = withTargetsHints(
388
- [
389
- ...setupHint(response.data.setupIssues),
390
- ...rule.data.accounts === "targets" ? targetAccountsHint(response.data.companies) : [],
391
- ...warmHints(response.data, warm, minimum)
392
- ],
361
+ [...setupHint(response.data.setupIssues), ...warmHints(response.data, warm, minimum)],
393
362
  targets,
394
363
  response.data.targets
395
364
  );
@@ -405,7 +374,7 @@ var warmCommand = defineCommand({
405
374
  window: response.data.window,
406
375
  previousWindow: response.data.previousWindow,
407
376
  minimum: minimum ?? null,
408
- ...targetsBlock(response.data.targets),
377
+ ...response.data.targets ? { targets: response.data.targets } : {},
409
378
  companies: withDealStatus(warm)
410
379
  },
411
380
  meta: { count: warm.length },
@@ -416,11 +385,6 @@ var warmCommand = defineCommand({
416
385
  }
417
386
  }
418
387
  });
419
- function targetAccountsHint(companies) {
420
- return companies.length > 0 && !companies.some((row) => row.isTarget === true) ? [
421
- "No company in this read is a target account: no target-accounts Knowledge is published, or none of its accounts was reached in the period. Publish the target accounts, or pass the list with --targets <file>."
422
- ] : [];
423
- }
424
388
  var COMPANY_ARGS = {
425
389
  company: {
426
390
  type: "positional",
@@ -513,12 +477,7 @@ var campaignsCommand = defineCommand({
513
477
  writeAdsOutput(rows, format, CAMPAIGN_TABLE_FIELDS, hints);
514
478
  return;
515
479
  }
516
- writeJson({
517
- ...response,
518
- data: { ...response.data, ...targetsBlock(response.data.targets) },
519
- meta: { count: response.data.campaigns.length },
520
- hints
521
- });
480
+ writeJson({ ...response, meta: { count: response.data.campaigns.length }, hints });
522
481
  } catch (err) {
523
482
  failAccounts(err);
524
483
  }
@@ -535,7 +494,7 @@ var accountsCommand = defineCommand({
535
494
  warm: warmCommand,
536
495
  company: companyCommand,
537
496
  campaigns: campaignsCommand,
538
- alerts: () => import("./alerts-RILIANHX.js").then((m) => m.alertsCommand),
497
+ alerts: () => import("./alerts-RJBTQ2OX.js").then((m) => m.alertsCommand),
539
498
  people: () => import("./people-A3YXUYUR.js").then((m) => m.peopleCommand),
540
499
  crm: () => import("./crm-OO2WO6OG.js").then((m) => m.crmCommand)
541
500
  }
@@ -543,4 +502,4 @@ var accountsCommand = defineCommand({
543
502
  export {
544
503
  accountsCommand
545
504
  };
546
- //# sourceMappingURL=accounts-74THO66A.js.map
505
+ //# sourceMappingURL=accounts-FGWJDM52.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/accounts/index.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n ACCOUNTS_ENGAGEMENT_MAX_LIMIT,\n type AccountsCampaignsResponse,\n type AccountsCompanyRequest,\n type AccountsCompanyResponse,\n type AccountsEngagementRequest,\n type AccountsEngagementResponse,\n type AccountsInfluencedResponse,\n accountsCampaignsRequestSchema,\n accountsCompanyRequestSchema,\n accountsEngagementRequestSchema,\n accountsInfluencedRequestSchema,\n INFLUENCE_MODEL_KINDS,\n influenceMetricWords,\n type MoneyByCurrency,\n type TargetsSummary,\n warmAccounts,\n} from \"@baker/api/accounts\";\nimport { defineCommand } from \"citty\";\nimport { z } from \"zod\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { withWindowSpellings } from \"../../date-window.ts\";\nimport { writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failApi } from \"../actions/shared.ts\";\nimport { outputFormatRefusal, TABLE_OUTPUT_FORMATS, writeAdsOutput } from \"../ads/output.ts\";\nimport {\n accountsRefusal,\n companyView,\n comparisonHints,\n ENGAGEMENT_TABLE_FIELDS,\n engagementHints,\n engagementTableRows,\n influencedHints,\n influencedTableRows,\n invalidArgsMessage,\n setupHint,\n targetsHints,\n warmAccountsCsv,\n warmHints,\n warmMetric,\n warmMinimum,\n withDealStatus,\n} from \"./report.ts\";\nimport { readTargetsFile, type TargetsFile } from \"./targets.ts\";\n\n/**\n * `baker accounts` — which companies the LinkedIn ads are warming, and which\n * CRM deals they influenced. Reads the nightly Account insights sync; nothing\n * here calls LinkedIn or the CRM, and nothing changes anywhere.\n */\n\nfunction optionalNumber(raw: unknown): number | undefined {\n return typeof raw === \"string\" && raw.trim() !== \"\" ? Number(raw) : undefined;\n}\n\nfunction optionalString(raw: unknown): string | undefined {\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : undefined;\n}\n\nfunction failInvalidArgs(message: string): never {\n writeJson({ ok: false, error: { code: \"INVALID_ARGS\", message } });\n process.exit(1);\n}\n\n/** A request the schema refuses never reaches the store; say which flag, in the envelope. */\nfunction failInvalid(issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>): never {\n failInvalidArgs(invalidArgsMessage(issues));\n}\n\n/** `--output` as asked, refused with the supported list instead of quietly printing JSON. */\nfunction outputFormat(args: Record<string, unknown>, supported: readonly string[]): string {\n const format = optionalString(args.output) ?? \"json\";\n const refusal = outputFormatRefusal(format, supported);\n if (refusal !== null) failInvalidArgs(refusal);\n return format;\n}\n\nconst OUTPUT_ARG = {\n type: \"string\",\n description: \"json|csv|jsonl|md (default json). csv/jsonl/md print the rows only; the summary and hints go to stderr\",\n required: false,\n default: \"json\",\n} as const;\n\nconst RULE_ARGS = {\n model: {\n type: \"string\",\n description:\n \"Read this report with another influence model, for this call only (the saved settings stay): engagement (engagements), awareness (impressions), intent (clicks) or attention (engagements and video views together — LinkedIn counts no video view as an engagement)\",\n required: false,\n },\n threshold: {\n type: \"string\",\n description:\n \"Read this report with another threshold on the model's metric, for this call only (a whole number, 1 or more)\",\n required: false,\n },\n} as const;\n\nfunction ruleInput(args: Record<string, unknown>): { model?: string; threshold?: number } {\n return { model: optionalString(args.model), threshold: optionalNumber(args.threshold) };\n}\n\nfunction moneyText(value: MoneyByCurrency): string {\n return Object.entries(value)\n .map(([currency, amount]) => `${Math.round(amount)} ${currency}`)\n .join(\" + \");\n}\n\n/** \"Not set up\" becomes the fix the agent relays; everything else is the ordinary error envelope. */\nfunction failAccounts(err: unknown): never {\n const refusal = err instanceof ApiError ? accountsRefusal(err.code, err.message) : null;\n if (err instanceof ApiError && refusal !== null) {\n writeJson({ ok: false, error: { code: refusal.code, message: err.message, fix: refusal.fix } });\n process.exit(1);\n }\n failApi(err);\n}\n\nconst WINDOW_ARGS = withWindowSpellings({\n \"last-months\": {\n type: \"string\",\n description: \"Calendar months to read, the current one included (1-24)\",\n required: false,\n },\n start: { type: \"string\", description: \"First day, YYYY-MM-DD (instead of --last-months)\", required: false },\n end: { type: \"string\", description: \"Last day, YYYY-MM-DD (default today; needs --start)\", required: false },\n});\n\nconst TARGETS_ARG = {\n targets: {\n type: \"string\",\n description:\n 'Only these target accounts: a .csv (a domain or website column; name, tier and organizationUrn optional) or a .json file ([\"acme.com\", …] or [{\"domain\": \"acme.com\", \"tier\": 1}, …]). A company is a target by its LinkedIn page, its website or its name — the same match as `baker ads linkedin companies --targets` and the warm-account alerts. Rows and numbers narrow to them, `targets` says how many were reached and engaged, per tier, and which were never reached, and `comparison` sets the targets beside every other company. Build one from the Knowledge with `node __tooling__/scripts/target-accounts.mjs --out targets.csv`',\n required: false,\n },\n} as const;\n\n/** `--targets` read and reduced to domains; refused in the envelope when the file cannot be read or names none. */\nfunction targetsInput(args: Record<string, unknown>): TargetsFile | null {\n const path = optionalString(args.targets);\n if (path === undefined) return null;\n let read: TargetsFile;\n try {\n read = readTargetsFile(path, readFileSync(path, \"utf8\"));\n } catch (err) {\n failInvalidArgs(`--targets: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (read.targets.length === 0) failInvalidArgs(`--targets: ${path} names no company website.`);\n return read;\n}\n\n/** The hints a `--targets` read adds; none without one. */\nfunction withTargetsHints(hints: string[], read: TargetsFile | null, summary: TargetsSummary | undefined): string[] {\n return read === null ? hints : [...targetsHints(summary, read.unreadable), ...hints];\n}\n\nfunction windowInput(args: Record<string, unknown>): { lastMonths?: number; start?: string; end?: string } {\n return {\n lastMonths: optionalNumber(args[\"last-months\"]),\n start: optionalString(args.start),\n end: optionalString(args.end),\n };\n}\n\n// --- influenced ---\n\nconst INFLUENCED_ARGS = {\n basis: {\n type: \"string\",\n description:\n \"pipeline (default): deals created in the period and not won. revenue: deals closed won in the period. open: deals open now, whenever created, that the ads engaged after they opened (in the period) — the pipeline an ABM campaign is warming\",\n required: false,\n default: \"pipeline\",\n },\n ...WINDOW_ARGS,\n full: {\n type: \"boolean\",\n description: \"Every deal in the period, influenced or not, instead of the influenced ones\",\n required: false,\n default: false,\n },\n ...RULE_ARGS,\n ...TARGETS_ARG,\n output: OUTPUT_ARG,\n} as const;\n\nconst DEAL_TABLE_FIELDS = [\n \"dealId\",\n \"dealName\",\n \"companyName\",\n \"domain\",\n \"amount\",\n \"currency\",\n \"status\",\n \"referenceAt\",\n \"touchValue\",\n \"firstTouchMonth\",\n \"matchConfidence\",\n \"influenced\",\n \"crmCompanyId\",\n];\n\nfunction influencedSummaryLine(data: AccountsInfluencedResponse[\"data\"]): string {\n const { summary, rule } = data;\n const value = moneyText(summary.influencedValue) || \"no amount\";\n if (data.basis === \"open\") {\n return `${summary.influencedDeals} of ${summary.deals} open deals reached (${value}) — ${rule.threshold}+ ${influenceMetricWords(rule.metric, rule.threshold)} after each deal opened, ${data.window.start} to ${data.window.end}.`;\n }\n return `${summary.influencedDeals} of ${summary.deals} ${data.basis} deals influenced (${value}) — ${rule.threshold}+ ${influenceMetricWords(rule.metric, rule.threshold)} in the ${rule.lookbackMonths} months before each deal, its own month up to the day before, ${data.window.start} to ${data.window.end}.`;\n}\n\nregisterSchema({\n command: \"accounts.influenced\",\n description:\n \"Start here for 'what pipeline / revenue did our LinkedIn ads influence'. A deal is influenced when its company reached the company's influence rule (default: 3+ LinkedIn ad engagements) before it: the 12 months up to the deal's month, and that month only up to the day before the deal was created (pipeline) or closed won (revenue). --basis open is the other ABM half: open deals, whenever created, that the ads engaged after they opened. A labelled rule, not credit: never call it 'attributed' or split it. Returns {summary: {deals, influencedDeals, influencedValue per currency, lowConfidenceDeals, spend, valuePerSpend}, deals, lowConfidence}. Amounts in different currencies are never added. Default the last 12 calendar months. --model/--threshold read it with another rule for this call only (\\\"what if we counted 5+ engagements\\\"); --targets <file> narrows it to the target accounts' deals; --output csv|md|jsonl prints the deals.\",\n args: INFLUENCED_ARGS,\n});\n\nconst influencedCommand = defineCommand({\n meta: {\n name: \"influenced\",\n description:\n \"Deals the LinkedIn ads influenced, with influenced pipeline or revenue. Example: baker accounts influenced --basis revenue --last-months 6\",\n },\n args: INFLUENCED_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, TABLE_OUTPUT_FORMATS);\n const targets = targetsInput(args);\n const parsed = accountsInfluencedRequestSchema.safeParse({\n ...windowInput(args),\n ...ruleInput(args),\n basis: optionalString(args.basis),\n full: Boolean(args.full),\n targets: targets?.targets,\n });\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsInfluencedResponse>(\"/api/accounts/influenced\", parsed.data);\n const hints = withTargetsHints(\n [\n ...setupHint(response.data.setupIssues),\n ...comparisonHints(response.data.comparison),\n ...influencedHints(response.data),\n ],\n targets,\n response.data.targets,\n );\n if (format !== \"json\") {\n const rows = influencedTableRows(response.data, parsed.data.full);\n writeAdsOutput(rows, format, DEAL_TABLE_FIELDS, [influencedSummaryLine(response.data), ...hints]);\n return;\n }\n writeJson({ ...response, meta: { count: response.data.deals.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n// --- engagement ---\n\nconst ENGAGEMENT_ARGS = {\n ...WINDOW_ARGS,\n \"campaign-id\": { type: \"string\", description: \"Only this campaign's companies (numeric id)\", required: false },\n limit: {\n type: \"string\",\n description: `Companies per page, 1-${ACCOUNTS_ENGAGEMENT_MAX_LIMIT} (default 500)`,\n required: false,\n },\n page: {\n type: \"string\",\n description:\n \"Which page to read, 1-based, most engaged first (default 1). pageInfo.hasMore says another page follows; pageInfo.total counts every company reached\",\n required: false,\n },\n ...TARGETS_ARG,\n output: OUTPUT_ARG,\n} as const;\n\nregisterSchema({\n command: \"accounts.engagement\",\n description:\n \"Every company the LinkedIn ads reached, most engaged first, with the period before for comparison, New/Rising flags, and where it stands in the CRM (matched company; dealStatus won > open > lost > none, lost meaning every deal it had was lost; lastLostAt). Default the last 3 calendar months. From the nightly sync, so it is fast and covers up to 24 months; for a live read of one ad account use `baker ads linkedin companies`. Paged: --limit companies per page, --page N; pageInfo {page, pageSize, total, hasMore}. --targets <file> keeps the target accounts only and adds `targets` {total, reached, engaged, notReached, byTier}.\",\n args: ENGAGEMENT_ARGS,\n});\n\nfunction engagementInput(\n args: Record<string, unknown>,\n targets: TargetsFile | null,\n limit?: number,\n): AccountsEngagementRequest {\n return {\n ...windowInput(args),\n campaignId: optionalString(args[\"campaign-id\"])?.replace(/^urn:li:sponsoredCampaign:/, \"\"),\n limit: limit ?? optionalNumber(args.limit),\n page: limit === undefined ? optionalNumber(args.page) : undefined,\n targets: targets?.targets,\n };\n}\n\nconst engagementCommand = defineCommand({\n meta: {\n name: \"engagement\",\n description:\n \"Companies the LinkedIn ads reached, with New/Rising flags and CRM status. Example: baker accounts engagement --last-months 3 --limit 50\",\n },\n args: ENGAGEMENT_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, TABLE_OUTPUT_FORMATS);\n const targets = targetsInput(args);\n const parsed = accountsEngagementRequestSchema.safeParse(engagementInput(args, targets));\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsEngagementResponse>(\"/api/accounts/engagement\", parsed.data);\n const hints = withTargetsHints(\n [\n ...setupHint(response.data.setupIssues),\n ...comparisonHints(response.data.comparison),\n ...engagementHints(response.data, parsed.data),\n ],\n targets,\n response.data.targets,\n );\n if (format !== \"json\") {\n writeAdsOutput(engagementTableRows(response.data.companies), format, ENGAGEMENT_TABLE_FIELDS, hints);\n return;\n }\n const companies = withDealStatus(response.data.companies);\n writeJson({\n ...response,\n data: { ...response.data, companies },\n meta: { count: companies.length, ...(response.data.pageInfo ? { total: response.data.pageInfo.total } : {}) },\n ...(hints.length > 0 ? { hints } : {}),\n });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n// --- warm ---\n\nconst warmRuleSchema = z.object({\n model: z.enum(INFLUENCE_MODEL_KINDS).optional(),\n threshold: z.number().int().min(1).optional(),\n min: z.number().int().min(0).optional(),\n});\n\nconst WARM_ARGS = {\n ...WINDOW_ARGS,\n \"campaign-id\": ENGAGEMENT_ARGS[\"campaign-id\"],\n min: {\n type: \"string\",\n description:\n \"Least a company must have done this period on the rule's metric to count as warm (default: the company's influence threshold, e.g. 3 engagements; 0 keeps every New/Rising company)\",\n required: false,\n },\n ...RULE_ARGS,\n ...TARGETS_ARG,\n output: {\n type: \"string\",\n description:\n \"json (default) or csv — csv prints companyName,domain,organizationUrn, the file `baker ads linkedin audiences create --type company-list --list-file` takes\",\n required: false,\n default: \"json\",\n },\n} as const;\n\nregisterSchema({\n command: \"accounts.warm\",\n description:\n \"Warm accounts: companies engaging with the LinkedIn ads more than in the period before (New: nothing before; Rising: engagements at least doubled) that reached the company's influence threshold this period (e.g. 3+ engagements; --min overrides, --min 0 drops it) and are not already somebody's deal: no open deal, never won (customers are left out), and no deal lost in the last 6 months (an older loss no longer counts). Default the current calendar month against the one before. `--output csv > warm.csv` writes a company list ready for `baker ads linkedin audiences create --type company-list --list-file warm.csv` (LinkedIn needs 300+ matched members to serve). --targets <file> keeps the warm target accounts only and adds `targets` (reached and engaged among them).\",\n args: WARM_ARGS,\n});\n\nconst warmCommand = defineCommand({\n meta: {\n name: \"warm\",\n description:\n \"Companies warming up that are not in pipeline, customers, or recently lost. Example: baker accounts warm --last-months 1 --output csv > warm.csv\",\n },\n args: WARM_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, [\"json\", \"csv\"]);\n const rule = warmRuleSchema.safeParse({ ...ruleInput(args), min: optionalNumber(args.min) });\n if (!rule.success) failInvalid(rule.error.issues);\n const targets = targetsInput(args);\n const input = engagementInput(args, targets, ACCOUNTS_ENGAGEMENT_MAX_LIMIT);\n const parsed = accountsEngagementRequestSchema.safeParse(\n input.start === undefined && input.lastMonths === undefined ? { ...input, lastMonths: 1 } : input,\n );\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsEngagementResponse>(\"/api/accounts/engagement\", parsed.data);\n const minimum = warmMinimum(response.data.rule, rule.data);\n const metric = warmMetric(response.data.rule, rule.data);\n const warm = warmAccounts(response.data.companies, new Date().toISOString().slice(0, 10), { minimum, metric });\n const hints = withTargetsHints(\n [...setupHint(response.data.setupIssues), ...warmHints(response.data, warm, minimum)],\n targets,\n response.data.targets,\n );\n if (format === \"csv\") {\n process.stdout.write(warmAccountsCsv(warm));\n for (const hint of hints) process.stderr.write(`${hint}\\n`);\n return;\n }\n writeJson({\n ok: true,\n data: {\n window: response.data.window,\n previousWindow: response.data.previousWindow,\n minimum: minimum ?? null,\n ...(response.data.targets ? { targets: response.data.targets } : {}),\n companies: withDealStatus(warm),\n },\n meta: { count: warm.length },\n ...(hints.length > 0 ? { hints } : {}),\n });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n// --- company ---\n\nconst COMPANY_ARGS = {\n company: {\n type: \"positional\",\n description: \"LinkedIn company id (1035), its urn:li:organization URN, or a website domain (acme.com)\",\n required: true,\n },\n} as const;\n\nregisterSchema({\n command: \"accounts.company\",\n description:\n \"One company's story: its month-by-month totals (`months`), the same numbers split by LinkedIn campaign (`byCampaign` — overlapping, never add it to the totals), the CRM company it matched and how surely, and that company's deals, each with `touchValue` and `influenced` under the company's rule. Use it to show why a deal counts as influenced.\",\n args: COMPANY_ARGS,\n});\n\n/** A bare number or an organization URN is a LinkedIn id; anything else is a domain. */\nfunction companyRequest(raw: string): AccountsCompanyRequest {\n const value = raw.trim();\n return /^(urn:li:organization:)?\\d+$/.test(value) ? { orgId: value } : { domain: value };\n}\n\nconst companyCommand = defineCommand({\n meta: {\n name: \"company\",\n description: \"One company's monthly LinkedIn ad activity and its deals. Example: baker accounts company acme.com\",\n },\n args: COMPANY_ARGS,\n run: async ({ args }) => {\n const parsed = accountsCompanyRequestSchema.safeParse(companyRequest(String(args.company ?? \"\")));\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsCompanyResponse>(\"/api/accounts/company\", parsed.data);\n const view = companyView(response.data);\n const hints = [...setupHint(response.data.setupIssues), ...view.hints];\n writeJson({ ok: true, data: view.data, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n// --- campaigns ---\n\nconst CAMPAIGNS_ARGS = {\n basis: {\n type: \"string\",\n description: \"pipeline (default): deals created in the period and not won. revenue: deals closed won in the period\",\n required: false,\n default: \"pipeline\",\n },\n ...WINDOW_ARGS,\n ...RULE_ARGS,\n ...TARGETS_ARG,\n output: OUTPUT_ARG,\n} as const;\n\nconst CAMPAIGN_TABLE_FIELDS = [\n \"campaignId\",\n \"campaignName\",\n \"companiesReached\",\n \"companiesEngaged\",\n \"influencedDeals\",\n \"influencedValue\",\n];\n\nregisterSchema({\n command: \"accounts.campaigns\",\n description:\n \"Per LinkedIn campaign: companies reached and engaged in the period, and the influenced deals it touched in their lookback — pipeline (default: deals created and not won) or, with --basis revenue, deals closed won. Overlapping by design — a deal counts for every campaign that touched it, so the rows never sum to the total; read them as a comparison, not a split. Default the last 12 calendar months. --model/--threshold read it with another rule for this call only; --targets <file> counts the target accounts only.\",\n args: CAMPAIGNS_ARGS,\n});\n\nconst campaignsCommand = defineCommand({\n meta: {\n name: \"campaigns\",\n description:\n \"Companies reached and influenced pipeline or revenue per campaign. Example: baker accounts campaigns --basis revenue --last-months 6\",\n },\n args: CAMPAIGNS_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, TABLE_OUTPUT_FORMATS);\n const targets = targetsInput(args);\n const input = {\n basis: optionalString(args.basis),\n ...windowInput(args),\n ...ruleInput(args),\n targets: targets?.targets,\n };\n const parsed = accountsCampaignsRequestSchema.safeParse(input);\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsCampaignsResponse>(\"/api/accounts/campaigns\", parsed.data);\n const hints = withTargetsHints(\n [\"Campaign rows overlap: a deal counts for every campaign that touched it. Never add them up.\"],\n targets,\n response.data.targets,\n );\n if (format !== \"json\") {\n const rows = response.data.campaigns.map((row) => ({\n ...row,\n influencedValue: moneyText(row.influencedValue),\n }));\n writeAdsOutput(rows, format, CAMPAIGN_TABLE_FIELDS, hints);\n return;\n }\n writeJson({ ...response, meta: { count: response.data.campaigns.length }, hints });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\nexport const accountsCommand = defineCommand({\n meta: {\n name: \"accounts\",\n description:\n \"Account insights: which companies the LinkedIn ads are warming, and which CRM deals they influenced. Start with `baker accounts influenced` or `baker accounts warm`.\",\n },\n subCommands: {\n influenced: influencedCommand,\n engagement: engagementCommand,\n warm: warmCommand,\n company: companyCommand,\n campaigns: campaignsCommand,\n alerts: () => import(\"./alerts.ts\").then((m) => m.alertsCommand),\n people: () => import(\"./people.ts\").then((m) => m.peopleCommand),\n crm: () => import(\"./crm.ts\").then((m) => m.crmCommand),\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAmB7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS;AAiClB,SAAS,eAAe,KAAkC;AACxD,SAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,MAAM,KAAK,OAAO,GAAG,IAAI;AACtE;AAEA,SAAS,eAAe,KAAkC;AACxD,SAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,MAAM,KAAK,IAAI,KAAK,IAAI;AACrE;AAEA,SAAS,gBAAgB,SAAwB;AAC/C,YAAU,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,gBAAgB,QAAQ,EAAE,CAAC;AACjE,UAAQ,KAAK,CAAC;AAChB;AAGA,SAAS,YAAY,QAAwE;AAC3F,kBAAgB,mBAAmB,MAAM,CAAC;AAC5C;AAGA,SAAS,aAAa,MAA+B,WAAsC;AACzF,QAAM,SAAS,eAAe,KAAK,MAAM,KAAK;AAC9C,QAAM,UAAU,oBAAoB,QAAQ,SAAS;AACrD,MAAI,YAAY,KAAM,iBAAgB,OAAO;AAC7C,SAAO;AACT;AAEA,IAAM,aAAa;AAAA,EACjB,MAAM;AAAA,EACN,aAAa;AAAA,EACb,UAAU;AAAA,EACV,SAAS;AACX;AAEA,IAAM,YAAY;AAAA,EAChB,OAAO;AAAA,IACL,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AAAA,EACA,WAAW;AAAA,IACT,MAAM;AAAA,IACN,aACE;AAAA,IACF,UAAU;AAAA,EACZ;AACF;AAEA,SAAS,UAAU,MAAuE;AACxF,SAAO,EAAE,OAAO,eAAe,KAAK,KAAK,GAAG,WAAW,eAAe,KAAK,SAAS,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AA,QAChD,EAAE;AACF,uBAAe,MAAM,QAAQ,uBAAuB,KAAK;AACzD;AAAA,MACF;AACA,gBAAU,EAAE,GAAG,UAAU,MAAM,EAAE,OAAO,SAAS,KAAK,UAAU,OAAO,GAAG,MAAM,CAAC;AAAA,IACnF,SAAS,KAAK;AACZ,mBAAa,GAAG;AAAA,IAClB;AAAA,EACF;AACF,CAAC;AAEM,IAAM,kBAAkB,cAAc;AAAA,EAC3C,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aACE;AAAA,EACJ;AAAA,EACA,aAAa;AAAA,IACX,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,WAAW;AAAA,IACX,QAAQ,MAAM,OAAO,sBAAa,EAAE,KAAK,CAAC,MAAM,EAAE,aAAa;AAAA,IAC/D,QAAQ,MAAM,OAAO,sBAAa,EAAE,KAAK,CAAC,MAAM,EAAE,aAAa;AAAA,IAC/D,KAAK,MAAM,OAAO,mBAAU,EAAE,KAAK,CAAC,MAAM,EAAE,UAAU;AAAA,EACxD;AACF,CAAC;","names":[]}
@@ -35,7 +35,7 @@ Full guides: __tooling__/docs/tools/baker/ads-<platform>.md (google|meta|linkedi
35
35
  subCommands: {
36
36
  google: () => import("./google-GBGLPAP5.js").then((m) => m.googleCommand),
37
37
  meta: () => import("./meta-2ZQ3CWLF.js").then((m) => m.metaCommand),
38
- linkedin: () => import("./linkedin-66QNH2HH.js").then((m) => m.linkedinCommand),
38
+ linkedin: () => import("./linkedin-BD63QPGK.js").then((m) => m.linkedinCommand),
39
39
  x: () => import("./x-WVWMOUAQ.js").then((m) => m.xCommand),
40
40
  chatgpt: () => import("./chatgpt-DPLD452Q.js").then((m) => m.chatgptCommand),
41
41
  performance: () => import("./performance-6I57ZQTD.js").then((m) => m.performanceCommand),
@@ -45,4 +45,4 @@ Full guides: __tooling__/docs/tools/baker/ads-<platform>.md (google|meta|linkedi
45
45
  export {
46
46
  adsCommand
47
47
  };
48
- //# sourceMappingURL=ads-NCG5TKFA.js.map
48
+ //# sourceMappingURL=ads-BYETTX2Y.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  invalidArgsMessage
3
- } from "./chunk-HS5NGBXW.js";
3
+ } from "./chunk-4X6QBNIB.js";
4
4
  import "./chunk-5OXVEKML.js";
5
5
  import "./chunk-IPEQHZ5H.js";
6
6
  import "./chunk-GRQ2AXDX.js";
@@ -150,4 +150,4 @@ export {
150
150
  alertsCommand,
151
151
  alertsHints
152
152
  };
153
- //# sourceMappingURL=alerts-RILIANHX.js.map
153
+ //# sourceMappingURL=alerts-RJBTQ2OX.js.map
@@ -33,8 +33,7 @@ var FLAG_OF_FIELD = {
33
33
  orgId: "company",
34
34
  domain: "company",
35
35
  targets: "--targets",
36
- since: "--since",
37
- accounts: "--accounts"
36
+ since: "--since"
38
37
  };
39
38
  function invalidArgsMessage(issues) {
40
39
  return issues.map((issue) => {
@@ -205,11 +204,7 @@ var plural = (count, one, many) => `${count} ${count === 1 ? one : many}`;
205
204
  function reachText(counts2) {
206
205
  return `${counts2.reached} of ${counts2.total} reached, ${counts2.engaged} engaged`;
207
206
  }
208
- function targetsView(summary, listNotReached) {
209
- const { notReached: _notReached, ...counts2 } = summary;
210
- return listNotReached ? summary : counts2;
211
- }
212
- function targetsHints(summary, unreadable, listed = true) {
207
+ function targetsHints(summary, unreadable) {
213
208
  if (summary === void 0) {
214
209
  return [
215
210
  "This Baker server does not narrow reports to target accounts yet: the rows cover every company the ads reached."
@@ -220,19 +215,15 @@ function targetsHints(summary, unreadable, listed = true) {
220
215
  `Target accounts: ${reachText(summary)}${tiers.length > 0 ? ` (${tiers.join("; ")})` : ""}. Rows and numbers cover the target accounts only.`
221
216
  ];
222
217
  const missed = summary.notReached.length;
223
- if (missed > 0 && !listed) {
224
- hints.push(
225
- `${plural(missed, "target account was", "target accounts were")} never reached in the period. To list ${missed === 1 ? "it" : "them"}: \`baker accounts engagement --targets <file> --full\` (targets.notReached).`
226
- );
227
- } else if (missed > 0) {
218
+ if (missed > 0) {
228
219
  hints.push(
229
220
  `${plural(missed, "target account was", "target accounts were")} never reached in the period (targets.notReached). Check ${missed === 1 ? "its domain is the website on its LinkedIn page" : "their domains are the websites on their LinkedIn pages"}, or advertise to ${missed === 1 ? "it" : "them"} with a company list.`
230
221
  );
231
222
  }
232
223
  if (unreadable.length > 0) {
233
- const listed2 = unreadable.map((entry) => `"${entry}"`).join(", ");
224
+ const listed = unreadable.map((entry) => `"${entry}"`).join(", ");
234
225
  hints.push(
235
- `Skipped ${plural(unreadable.length, "entry", "entries")} of the targets file that ${unreadable.length === 1 ? "is" : "are"} not a website: ${listed2}.`
226
+ `Skipped ${plural(unreadable.length, "entry", "entries")} of the targets file that ${unreadable.length === 1 ? "is" : "are"} not a website: ${listed}.`
236
227
  );
237
228
  }
238
229
  return hints;
@@ -321,10 +312,9 @@ export {
321
312
  warmMetric,
322
313
  warmHints,
323
314
  warmAccountsCsv,
324
- targetsView,
325
315
  targetsHints,
326
316
  comparisonHints,
327
317
  withDealStatus,
328
318
  companyView
329
319
  };
330
- //# sourceMappingURL=chunk-HS5NGBXW.js.map
320
+ //# sourceMappingURL=chunk-4X6QBNIB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/accounts/report.ts"],"sourcesContent":["/**\n * The pure half of `baker accounts`: the warm-account list file, and what the\n * agent should take from a report that the rows alone don't say.\n */\n\nimport {\n ACCOUNTS_NO_SETTINGS_MESSAGE,\n type AccountCompanyMonth,\n type AccountDealRow,\n type AccountDealStatus,\n type AccountEngagementRow,\n type AccountsCompanyResponse,\n type AccountsEngagementResponse,\n type AccountsInfluencedResponse,\n type AccountsSetupIssue,\n accountDealStatus,\n type DealsComparison,\n type InfluenceMetric,\n type InfluenceModelKind,\n type InfluenceParams,\n type InfluenceRuleOverride,\n influenceMetricWords,\n influenceParams,\n type MoneyByCurrency,\n type WarmAccountsOptions,\n} from \"@baker/api/accounts\";\nimport type { EngagementComparison, TargetsSummary } from \"@baker/api/accounts/targets\";\nimport { toCsvRow } from \"../ads/output.ts\";\n\nexport type AccountsRefusal = { code: \"ACCOUNTS_NOT_SET_UP\"; fix: { action: \"ask_user\"; explanation: string } };\n\n/**\n * The refusal the agent cannot clear, as the fix it acts on: not set up (only\n * the user can say which stages mean won). Matched on the backend's own\n * sentence (shared from `@baker/api/accounts`), because it is a CONFLICT.\n * Null for every other refusal.\n */\nexport function accountsRefusal(code: string, message: string): AccountsRefusal | null {\n if (code === \"CONFLICT\" && message.includes(ACCOUNTS_NO_SETTINGS_MESSAGE)) {\n return {\n code: \"ACCOUNTS_NOT_SET_UP\",\n fix: {\n action: \"ask_user\",\n explanation:\n \"The user sets up where the deals are in Measure → Accounts first: HubSpot (then its pipelines and won/lost stages), or Another CRM, whose deals they send by spreadsheet or from their system (`baker accounts crm status`). Only the user can say which stages mean won and lost; do not guess them. Until then `baker accounts engagement` and `baker accounts warm` still work — they need no deals.\",\n },\n };\n }\n return null;\n}\n\n/** Request fields as the flags that set them. */\nconst FLAG_OF_FIELD: Record<string, string> = {\n lastMonths: \"--last-months\",\n start: \"--start\",\n end: \"--end\",\n campaignId: \"--campaign-id\",\n limit: \"--limit\",\n basis: \"--basis\",\n model: \"--model\",\n threshold: \"--threshold\",\n orgId: \"company\",\n domain: \"company\",\n targets: \"--targets\",\n since: \"--since\",\n};\n\n/** A refused request in the agent's own words: which flag, and why. */\nexport function invalidArgsMessage(issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>): string {\n return issues\n .map((issue) => {\n const field = issue.path.map(String).join(\".\");\n return `${FLAG_OF_FIELD[field] ?? (field || \"args\")}: ${issue.message}`;\n })\n .join(\"; \");\n}\n\nfunction money(value: MoneyByCurrency): string {\n const parts = Object.entries(value).map(\n ([currency, amount]) => `${Math.round(amount).toLocaleString(\"en\")} ${currency}`,\n );\n return parts.length > 0 ? parts.join(\" + \") : \"no amount\";\n}\n\n/** Each setup problem as the fix an admin makes in Measure → Accounts or Integrations. */\nconst SETUP_FIX: Record<AccountsSetupIssue, string> = {\n pipelines_not_chosen: \"choose the HubSpot pipelines (customers and open deals are not left out yet)\",\n deals_not_received:\n \"send the deals from the company's CRM (none has arrived, so warm-account alerts are paused and no deal counts as influenced)\",\n sync_failing: \"reconnect the platform the last nightly sync failed on\",\n source_disconnected: \"reconnect LinkedIn Ads or HubSpot in Integrations\",\n stale: \"check why the numbers have not updated for two days\",\n};\n\n/**\n * One hint when Account insights is not set up soundly: the admins already\n * got an email, so the agent says it once to the user and hedges the numbers.\n */\nexport function setupHint(issues: readonly AccountsSetupIssue[] | undefined): string[] {\n if (!issues || issues.length === 0) return [];\n const fixes = issues.map((issue) => SETUP_FIX[issue]).join(\"; \");\n return [\n `Account insights setup needs an admin: ${fixes}. Until then warm and influenced are less accurate — say so once when you report them, and never try to fix the setup yourself.`,\n ];\n}\n\n/** What the agent should take from an influenced report that the rows alone don't say. */\nexport function influencedHints(data: AccountsInfluencedResponse[\"data\"]): string[] {\n const hints: string[] = [];\n const { summary } = data;\n if (summary.lowConfidenceDeals > 0) {\n const deals = summary.lowConfidenceDeals === 1 ? \"deal\" : \"deals\";\n const look = summary.lowConfidenceDeals === 1 ? \"looks\" : \"look\";\n hints.push(\n `${summary.lowConfidenceDeals} more ${deals} (${money(summary.lowConfidenceValue)}) ${look} influenced through a company match that is only a guess (a subdomain or a name). They are not counted in the numbers until someone confirms the match in Measure → Accounts; they are listed under lowConfidence.`,\n );\n }\n const valued = Object.keys(summary.influencedValue).length > 0;\n const spent = Object.values(summary.spend).some((amount) => amount > 0);\n if (summary.valuePerSpend === null && valued && spent) {\n hints.push(\n `valuePerSpend is null because the influenced value (${money(summary.influencedValue)}) and the LinkedIn spend (${money(summary.spend)}) are not in one single currency — amounts in different currencies are never converted or added. Report them side by side.`,\n );\n }\n return hints;\n}\n\n/**\n * The deals a table output prints: the counted ones, then the unconfirmed. With\n * `--full` the backend already lists the unconfirmed among `deals`, so they are\n * not added twice — a total taken from the table would count them double.\n */\nexport function influencedTableRows(data: AccountsInfluencedResponse[\"data\"], full: boolean): AccountDealRow[] {\n return full ? data.deals : [...data.deals, ...data.lowConfidence];\n}\n\n/** What the agent should take from an engagement read that the rows alone don't say. */\nexport function engagementHints(data: AccountsEngagementResponse[\"data\"], request: { limit: number }): string[] {\n if (data.companies.length === 0) {\n return [\n `No company the LinkedIn ads reached shows up for ${data.window.start} to ${data.window.end}. The nightly sync may not have run since the campaigns started delivering, or LinkedIn left the companies out (fewer than 3 events in a month). Try a longer period (--last-months 12), or read the ad account live with \\`baker ads linkedin companies\\`.`,\n ];\n }\n const page = data.pageInfo;\n if (page?.hasMore) {\n const first = (page.page - 1) * page.pageSize + 1;\n const last = first + data.companies.length - 1;\n return [\n `Companies ${first}-${last} of ${page.total.toLocaleString(\"en\")} shown. Read the next ones with --page ${page.page + 1} --limit ${page.pageSize}.`,\n ];\n }\n return data.truncated ? [`More companies were reached than --limit ${request.limit}; raise it to see the tail.`] : [];\n}\n\n/** The columns `baker accounts engagement --output csv|md` prints, in order. */\nexport const ENGAGEMENT_TABLE_FIELDS = [\n \"orgId\",\n \"name\",\n \"domain\",\n \"impressions\",\n \"clicks\",\n \"engagements\",\n \"videoViews\",\n \"estimatedSpend\",\n \"spendCurrency\",\n \"costLocal\",\n \"currency\",\n \"monthsActive\",\n \"lastMonth\",\n \"previousImpressions\",\n \"previousClicks\",\n \"previousEngagements\",\n \"previousVideoViews\",\n \"flag\",\n \"crmCompanyId\",\n \"matchConfidence\",\n \"dealStatus\",\n \"hasOpenDeal\",\n \"hasWonDeal\",\n \"hasLostDeal\",\n \"lastLostAt\",\n \"websitePeople\",\n \"websiteLeads\",\n \"websiteVisits\",\n \"websitePagesRead\",\n \"websiteLastVisit\",\n \"isTarget\",\n \"tier\",\n \"alertedAt\",\n];\n\n/** Engagement rows flat for a table: the estimated spend as two columns, the period before as four, the website people as two and the company's own-network visits as three, not JSON cells. */\nexport function engagementTableRows(rows: readonly AccountEngagementRow[]): Array<Record<string, unknown>> {\n return withDealStatus(rows).map(({ previous, website, visitorCompany, estimatedSpend, ...row }) => ({\n ...row,\n estimatedSpend: estimatedSpend?.amount ?? 0,\n spendCurrency: estimatedSpend?.currency ?? \"\",\n previousImpressions: previous.impressions,\n previousClicks: previous.clicks,\n previousEngagements: previous.engagements,\n previousVideoViews: previous.videoViews ?? 0,\n websitePeople: website?.people ?? 0,\n websiteLeads: website?.leads ?? 0,\n websiteVisits: visitorCompany?.visits ?? 0,\n websitePagesRead: visitorCompany?.pages ?? 0,\n websiteLastVisit: visitorCompany?.lastSeen ?? null,\n }));\n}\n\nconst MODEL_OF_METRIC: Record<InfluenceMetric, InfluenceModelKind> = {\n engagements: \"engagement\",\n impressions: \"awareness\",\n clicks: \"intent\",\n attention: \"attention\",\n};\n\n/**\n * The least a warm company must have done this period: the company's\n * influence rule (the default one when the backend sent none), read for this\n * call with `--model`/`--threshold`, or `--min` on the rule's metric. `--min 0`\n * drops it, so one engagement after none reads as warm again.\n */\nexport function warmMinimum(\n rule: InfluenceParams | undefined,\n override: InfluenceRuleOverride & { min?: number },\n): WarmAccountsOptions[\"minimum\"] {\n const read = warmRule(rule, override);\n const value = override.min ?? read.threshold;\n return value > 0 ? { metric: read.metric, value } : undefined;\n}\n\n/** The metric New and Rising are read on for this call — kept when `--min 0` drops the minimum. */\nexport function warmMetric(\n rule: InfluenceParams | undefined,\n override: InfluenceRuleOverride & { min?: number },\n): InfluenceMetric {\n return warmRule(rule, override).metric;\n}\n\nfunction warmRule(rule: InfluenceParams | undefined, override: InfluenceRuleOverride): InfluenceParams {\n const saved = { model: { kind: rule ? MODEL_OF_METRIC[rule.metric] : \"engagement\", threshold: rule?.threshold } };\n return influenceParams(saved, { model: override.model, threshold: override.threshold });\n}\n\n/** What the agent should take from a warm list that the rows alone don't say. */\nexport function warmHints(\n read: Pick<AccountsEngagementResponse[\"data\"], \"companies\" | \"truncated\">,\n warm: readonly AccountEngagementRow[],\n minimum: WarmAccountsOptions[\"minimum\"],\n): string[] {\n const hints: string[] = [];\n if (read.truncated) {\n hints.push(\n `The ads reached more companies than one read returns (${read.companies.length.toLocaleString(\"en\")}, the most engaged first), so warm companies with little engagement may be missing. Read a shorter period with --last-months 1 to see them.`,\n );\n }\n if (warm.length === 0 && read.companies.length > 0 && minimum !== undefined) {\n hints.push(\n `No company both warmed up and reached ${minimum.value}+ ${influenceMetricWords(minimum.metric, minimum.value)} in the period. Try a longer period with --last-months, or a lower bar with --min (--min 0 drops it).`,\n );\n }\n if (warm.some((row) => row.name === \"\")) {\n hints.push(\"Some companies have no name yet — the nightly sync looks them up; the organizationUrn still matches.\");\n }\n if (warm.length > 0) {\n hints.push(\n 'To advertise to them: `baker accounts warm --output csv > warm.csv`, then `baker ads linkedin audiences create --name \"Warm accounts\" --type company-list --list-file warm.csv` (staged until publish).',\n );\n }\n return hints;\n}\n\n/** The header `baker ads linkedin audiences create --type company-list --list-file` reads. */\nconst WARM_CSV_COLUMNS = [\"companyName\", \"domain\", \"organizationUrn\"];\n\n/**\n * Warm accounts as a company-list file, one company a line. The list reader\n * splits on line breaks, so a name carrying one is flattened.\n */\nexport function warmAccountsCsv(rows: readonly AccountEngagementRow[]): string {\n const lines = [toCsvRow(WARM_CSV_COLUMNS)];\n for (const row of rows) {\n const name = row.name.replace(/\\s*[\\r\\n]+\\s*/g, \" \");\n lines.push(toCsvRow([name, row.domain, `urn:li:organization:${row.orgId}`]));\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`;\n\nfunction reachText(counts: { total: number; reached: number; engaged: number }): string {\n return `${counts.reached} of ${counts.total} reached, ${counts.engaged} engaged`;\n}\n\n/**\n * What a `--targets` read means beyond its rows: how far the ads got with the\n * list, the targets never reached, and the file entries that were skipped.\n * No summary back means a server that ignored the list.\n */\nexport function targetsHints(summary: TargetsSummary | undefined, unreadable: readonly string[]): string[] {\n if (summary === undefined) {\n return [\n \"This Baker server does not narrow reports to target accounts yet: the rows cover every company the ads reached.\",\n ];\n }\n const tiers = Object.entries(summary.byTier ?? {})\n .sort(([a], [b]) => a.localeCompare(b, \"en\", { numeric: true }))\n .map(([tier, counts]) => `tier ${tier}: ${reachText(counts)}`);\n const hints = [\n `Target accounts: ${reachText(summary)}${tiers.length > 0 ? ` (${tiers.join(\"; \")})` : \"\"}. Rows and numbers cover the target accounts only.`,\n ];\n const missed = summary.notReached.length;\n if (missed > 0) {\n hints.push(\n `${plural(missed, \"target account was\", \"target accounts were\")} never reached in the period (targets.notReached). Check ${missed === 1 ? \"its domain is the website on its LinkedIn page\" : \"their domains are the websites on their LinkedIn pages\"}, or advertise to ${missed === 1 ? \"it\" : \"them\"} with a company list.`,\n );\n }\n if (unreadable.length > 0) {\n const listed = unreadable.map((entry) => `\"${entry}\"`).join(\", \");\n hints.push(\n `Skipped ${plural(unreadable.length, \"entry\", \"entries\")} of the targets file that ${unreadable.length === 1 ? \"is\" : \"are\"} not a website: ${listed}.`,\n );\n }\n return hints;\n}\n\nconst percent = (part: number, whole: number) => `${whole > 0 ? Math.round((part / whole) * 100) : 0}%`;\nconst perCompany = (total: number, companies: number) =>\n companies > 0 ? String(Math.round((total / companies) * 10) / 10) : \"0\";\n\n/**\n * \"Did the ABM work\" in one line: the target accounts beside every other\n * company in the same read — engagement for the companies reached, influenced\n * deals for a deal read. Nothing without a `--targets` read.\n */\nexport function comparisonHints(comparison: EngagementComparison | DealsComparison | undefined): string[] {\n if (comparison === undefined) return [];\n if (\"companies\" in comparison.targets && \"companies\" in comparison.others) {\n const { targets, others } = comparison as EngagementComparison;\n return [\n `Targets vs everyone else: ${targets.engaged} of ${targets.companies} target accounts engaged (${percent(targets.engaged, targets.companies)}) against ${others.engaged} of ${others.companies} other companies (${percent(others.engaged, others.companies)}); ${perCompany(targets.engagements, targets.companies)} engagements per target, ${perCompany(others.engagements, others.companies)} per other company (\\`comparison\\`).`,\n ];\n }\n const { targets, others } = comparison as DealsComparison;\n return [\n `Targets vs everyone else: ${targets.influencedDeals} of ${targets.deals} target-account deals influenced (${money(targets.influencedValue)}) against ${others.influencedDeals} of ${others.deals} other deals (${money(others.influencedValue)}) (\\`comparison\\`).`,\n ];\n}\n\n/** Each company with where it stands in the CRM spelled out, so the agent never has to combine the flags. */\nexport function withDealStatus(\n rows: readonly AccountEngagementRow[],\n): Array<AccountEngagementRow & { dealStatus: AccountDealStatus }> {\n return rows.map((row) => ({ ...row, dealStatus: accountDealStatus(row) }));\n}\n\ntype CompanyData = AccountsCompanyResponse[\"data\"];\ntype MonthCounts = Pick<AccountCompanyMonth, \"month\" | \"impressions\" | \"clicks\" | \"engagements\">;\n\nexport interface CompanyView {\n orgs: CompanyData[\"orgs\"];\n /** The company's own totals, month by month: the account-wide rows. */\n months: Array<MonthCounts & { orgId: string }>;\n /** The same numbers split by campaign. Overlapping: never add them to `months` or to each other. */\n byCampaign: Array<{ orgId: string; campaignId: string; campaignName: string | null; months: MonthCounts[] }>;\n deals: CompanyData[\"deals\"];\n rule?: CompanyData[\"rule\"];\n}\n\nconst counts = (row: AccountCompanyMonth): MonthCounts => ({\n month: row.month,\n impressions: row.impressions,\n clicks: row.clicks,\n engagements: row.engagements,\n});\n\n/**\n * One company as the agent should read it. The store answers the account-wide\n * row and every campaign's row for the same month side by side, which reads\n * as double the activity; here the account-wide months are the totals and\n * the campaign split sits apart, labelled. A company the ads never reached\n * comes back from the store as an unnamed echo of the id asked for — dropped,\n * and said in words.\n */\n/** Why a company lookup shows no LinkedIn company: an id the ads never reached, a CRM-only company, or no match at all. */\nfunction unreachedHint(unreached: ReadonlyArray<{ orgId: string }>, deals: number): string {\n if (unreached.length > 0) {\n return `The LinkedIn ads have not reached LinkedIn company ${unreached.map((org) => org.orgId).join(\", \")} in the months the nightly sync keeps (up to 24), so there is nothing to show. Check the id against \\`baker accounts engagement\\`, or try the company's website domain.`;\n }\n if (deals > 0) {\n return `That company is in the CRM with ${deals === 1 ? \"1 deal\" : `${deals} deals`}, but the LinkedIn ads have not reached it in the months the nightly sync keeps, so none of its deals can count as influenced.`;\n }\n return \"The ads have not reached that company, or it is named differently: try its LinkedIn id from `baker accounts engagement`.\";\n}\n\nexport function companyView(data: CompanyData): { data: CompanyView; hints: string[] } {\n const reachedOrgs = new Set(data.months.map((row) => row.orgId));\n const orgs = data.orgs.filter((org) => reachedOrgs.has(org.orgId) || org.name !== \"\" || org.crmCompanyId !== null);\n const months = data.months\n .filter((row) => row.campaignId === \"\")\n .map((row) => ({ orgId: row.orgId, ...counts(row) }));\n const byCampaign: CompanyView[\"byCampaign\"] = [];\n for (const row of data.months) {\n if (row.campaignId === \"\") continue;\n let entry = byCampaign.find((item) => item.orgId === row.orgId && item.campaignId === row.campaignId);\n if (entry === undefined) {\n entry = { orgId: row.orgId, campaignId: row.campaignId, campaignName: row.campaignName, months: [] };\n byCampaign.push(entry);\n }\n entry.months.push(counts(row));\n }\n\n const hints: string[] = [];\n const unreached = unreachedHint(\n data.orgs.filter((org) => !orgs.includes(org)),\n data.deals.length,\n );\n if (orgs.length === 0) hints.push(unreached);\n if (byCampaign.length > 0) {\n hints.push(\n \"`months` are the company's totals. `byCampaign` splits the same numbers by campaign, and a company several campaigns reached shows up under each — never add byCampaign to the totals or to each other.\",\n );\n }\n if (orgs.some((org) => org.matchConfidence === \"low\")) {\n hints.push(\n \"The CRM match is only a guess (a subdomain or a name) until someone confirms it in Measure → Accounts.\",\n );\n }\n if (data.rule !== undefined && data.deals.length > 0) {\n hints.push(\n `\\`influenced\\` on each deal: ${data.rule.threshold}+ ${influenceMetricWords(data.rule.metric, data.rule.threshold)} (\\`touchValue\\`) in the ${data.rule.lookbackMonths} months up to the month the deal was created (closed, for a won deal), counted from this company's months above.`,\n );\n }\n return { data: { orgs, months, byCampaign, deals: data.deals, ...(data.rule ? { rule: data.rule } : {}) }, hints };\n}\n"],"mappings":";;;;;;;;;;;AAqCO,SAAS,gBAAgB,MAAc,SAAyC;AACrF,MAAI,SAAS,cAAc,QAAQ,SAAS,4BAA4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AAM;AAAA,MACJ,gCAAgC,KAAK,KAAK,SAAS,KAAK,qBAAqB,KAAK,KAAK,QAAQ,KAAK,KAAK,SAAS,CAAC,4BAA4B,KAAK,KAAK,cAAc;AAAA,IACzK;AAAA,EACF;AACA,SAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,YAAY,OAAO,KAAK,OAAO,GAAI,KAAK,OAAO,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC,EAAG,GAAG,MAAM;AACnH;","names":["counts","targets","others"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  targetsHints
3
- } from "./chunk-HS5NGBXW.js";
3
+ } from "./chunk-4X6QBNIB.js";
4
4
  import {
5
5
  readTargetsFile,
6
6
  targetsOfTier
@@ -259,4 +259,4 @@ export {
259
259
  targetsArg,
260
260
  companiesCommand
261
261
  };
262
- //# sourceMappingURL=chunk-RDTSLMSJ.js.map
262
+ //# sourceMappingURL=chunk-63XEBJIX.js.map
package/dist/cli.js CHANGED
@@ -694,7 +694,7 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
694
694
  capabilities: () => import("./capabilities-U53QPNBQ.js").then((m) => m.capabilitiesCommand),
695
695
  actions: () => import("./actions-Q7DDN427.js").then((m) => m.actionsCommand),
696
696
  "scheduled-agents": () => import("./scheduled-agents-YHZUPS2I.js").then((m) => m.scheduledAgentsCommand),
697
- ads: () => import("./ads-NCG5TKFA.js").then((m) => m.adsCommand),
697
+ ads: () => import("./ads-BYETTX2Y.js").then((m) => m.adsCommand),
698
698
  brand: () => import("./brand-SDDWXOOT.js").then((m) => m.brandCommand),
699
699
  analytics: () => import("./analytics-SVV7JZ2J.js").then((m) => m.analyticsCommand),
700
700
  experiment: () => import("./experiment-WEWASTVO.js").then((m) => m.experimentCommand),
@@ -721,10 +721,10 @@ Introspection: Run 'baker schema <command>' to inspect argument schemas.`
721
721
  chats: () => import("./chats-QVGXEYT6.js").then((m) => m.chatsCommand),
722
722
  history: () => import("./history-M6VLA7TD.js").then((m) => m.historyCommand),
723
723
  credentials: () => import("./credentials-T7F2PFNY.js").then((m) => m.credentialsCommand),
724
- hubspot: () => import("./hubspot-W5LYFWTH.js").then((m) => m.hubspotCommand),
724
+ hubspot: () => import("./hubspot-XZYXZ24P.js").then((m) => m.hubspotCommand),
725
725
  activecampaign: () => import("./activecampaign-BAWTDTSA.js").then((m) => m.activecampaignCommand),
726
726
  pipedrive: () => import("./pipedrive-7AA7ZD7M.js").then((m) => m.pipedriveCommand),
727
- accounts: () => import("./accounts-74THO66A.js").then((m) => m.accountsCommand),
727
+ accounts: () => import("./accounts-FGWJDM52.js").then((m) => m.accountsCommand),
728
728
  shopify: () => import("./shopify-ZQFONX3R.js").then((m) => m.shopifyCommand),
729
729
  "winning-ads": () => import("./winning-ads-274QKPKB.js").then((m) => m.winningAdsCommand),
730
730
  "media-sources": () => import("./media-sources-NI6U2YWV.js").then((m) => m.mediaSourcesCommand),
@@ -3,8 +3,8 @@ import {
3
3
  companiesHints,
4
4
  knowledgeTargetsHint,
5
5
  targetsArg
6
- } from "./chunk-RDTSLMSJ.js";
7
- import "./chunk-HS5NGBXW.js";
6
+ } from "./chunk-63XEBJIX.js";
7
+ import "./chunk-4X6QBNIB.js";
8
8
  import "./chunk-5OXVEKML.js";
9
9
  import "./chunk-2DGJKIHF.js";
10
10
  import "./chunk-IPEQHZ5H.js";
@@ -33,4 +33,4 @@ export {
33
33
  knowledgeTargetsHint,
34
34
  targetsArg
35
35
  };
36
- //# sourceMappingURL=companies-M7LWFZK3.js.map
36
+ //# sourceMappingURL=companies-ITNWR5Q4.js.map
@@ -153,7 +153,11 @@ registerSchema({
153
153
  command: "hubspot.meetings.list",
154
154
  description: "Every HubSpot meeting link (calendar) on the connected account, with just enough to choose one: name, slug, link type (personal / group / round-robin), whether booking redirects somewhere, and how many booking fields it asks for (null = unknown, read it with `meetings view`). Next step is usually `hubspot meetings view <slug> --as-node`, which gives you the blob to write straight into a hubspotMeeting step.",
155
155
  args: {
156
- search: { type: "string", description: "Case-insensitive substring match on the meeting name", required: false },
156
+ search: {
157
+ type: "string",
158
+ description: "Case-insensitive match on the meeting name or slug, or a pasted booking link (meetings.hubspot.com/<slug>)",
159
+ required: false
160
+ },
157
161
  "redirecting-only": {
158
162
  type: "boolean",
159
163
  description: "Only meeting links that redirect after booking",
@@ -299,7 +303,7 @@ var meetingsListCommand = defineCommand({
299
303
  description: "List HubSpot meeting links (calendars). Example: baker hubspot meetings list"
300
304
  },
301
305
  args: {
302
- search: { type: "string", description: "Match on meeting name", required: false },
306
+ search: { type: "string", description: "Match on meeting name, slug or a pasted booking link", required: false },
303
307
  "redirecting-only": { type: "boolean", description: "Only links that redirect after booking", required: false }
304
308
  },
305
309
  run: async ({ args }) => {
@@ -315,7 +319,9 @@ var meetingsListCommand = defineCommand({
315
319
  const { meetings } = response.data;
316
320
  const hints = [];
317
321
  if (meetings.length === 0) {
318
- hints.push("No meeting links matched. Drop --search, or check the connected HubSpot account.");
322
+ hints.push(
323
+ args.search ? `No meeting link's name, slug or booking link matched "${args.search}". Drop --search to see every calendar on the connected account.` : "No meeting links matched. Check the connected HubSpot account."
324
+ );
319
325
  } else {
320
326
  hints.push(
321
327
  "To put one on a page: `baker hubspot meetings view <slug> --as-node` returns the object to write into the step's form.external."
@@ -850,4 +856,4 @@ export {
850
856
  hubspotCommand,
851
857
  workflowViewHints
852
858
  };
853
- //# sourceMappingURL=hubspot-W5LYFWTH.js.map
859
+ //# sourceMappingURL=hubspot-XZYXZ24P.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/hubspot/index.ts"],"sourcesContent":["import type {\n HubspotContactFieldsListResponse,\n HubspotContactLookupResponse,\n HubspotContactPropertiesListResponse,\n HubspotContactsSummaryResponse,\n HubspotFormSubmissionsResponse,\n HubspotFormsListResponse,\n HubspotFormsViewResponse,\n HubspotMeetingsListResponse,\n HubspotMeetingsViewResponse,\n HubspotPipelinesListResponse,\n HubspotWorkflowsListResponse,\n HubspotWorkflowsViewResponse,\n} from \"@baker/api\";\nimport { HUBSPOT_OPERATORS } from \"@baker/api/event-sources\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { rowsAsData, writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failNotConnected } from \"./refusal.ts\";\n\nconst EMBED_TYPES = [\"legacy\", \"v4\", \"unknown\"] as const;\n\nfunction assertEmbedType(value: string | undefined): (typeof EMBED_TYPES)[number] | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!(EMBED_TYPES as readonly string[]).includes(value)) {\n throw new Error(`--embed-type must be one of: ${EMBED_TYPES.join(\"|\")}`);\n }\n return value as (typeof EMBED_TYPES)[number];\n}\n\nregisterSchema({\n command: \"hubspot.forms.list\",\n routes: [\"POST /api/hubspot/forms/list\"],\n effect: \"read_live\",\n description:\n \"Start here for HubSpot forms: every form on the connected account, with just enough to choose one — embed type (legacy vs v4), field count, its post-submit action (inline thank-you vs redirect to a URL), and whether spam prevention (captcha) is on. A form with captcha on can be embedded on a page but can never receive a submission from a Form, so check it before wiring one as a destination. Answers 'which of my forms redirect after submit?' and 'is this form legacy or v4?'. portalId is returned once on meta, not per row. Next step is usually `hubspot forms view <id> --as-node`, which gives you the blob to write straight into a Form step — you do not need request_flow_input for HubSpot.\",\n args: {\n search: { type: \"string\", description: \"Case-insensitive substring match on the form name\", required: false },\n \"redirecting-only\": {\n type: \"boolean\",\n description: \"Only forms whose post-submit action redirects away\",\n required: false,\n default: false,\n },\n \"embed-type\": { type: \"string\", description: \"Filter: legacy|v4|unknown\", required: false, enum: [...EMBED_TYPES] },\n },\n});\n\nregisterSchema({\n command: \"hubspot.forms.view\",\n description:\n \"One HubSpot form in detail: every field (name, label, type, required, hidden, options), the legal-consent mode, the post-submit action, captcha, and language. Read it before wiring a form into a Form (flow) so you know what fields exist to autofill. Add --full for the untouched HubSpot payload, or --as-node to get the object to write into the step's form.external instead.\",\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id (from `baker hubspot forms list`)\", required: true },\n full: { type: \"boolean\", description: \"Include the raw HubSpot payload\", required: false, default: false },\n \"as-node\": {\n type: \"boolean\",\n description:\n \"Emit the resource blob to write into a flow node's form.external, instead of the readable view. Write it into the node yourself; no need for request_flow_input when the account is connected and the form is unambiguous.\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.forms.submissions\",\n routes: [\"POST /api/hubspot/forms/submissions\"],\n effect: \"read_live\",\n description:\n \"How many leads a form actually received over a window, and on which days — the difference between 'this form is live' and 'this form is working'. Start here when asked whether a form or a campaign is producing leads. Returns counts and dates only; the leads' own answers need --full and are personal data, so do not put them in a report. Pair with `hubspot pipelines list` to see whether those leads were then worked.\",\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id (from `baker hubspot forms list`)\", required: true },\n days: { type: \"string\", description: \"Window in days, 1-365 (default 30)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Include each submission's field values — personal data, request only when actually needed\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.contacts.summary\",\n routes: [\"POST /api/hubspot/contacts/summary\"],\n effect: \"read_live\",\n description:\n \"Whether the leads that arrived recently are actually being worked, as counts: how many contacts were created in the window, how many have someone assigned, and how they split across lifecycle stages. This is the 'have these leads been treated?' answer. Returns no names or emails — use `hubspot contacts lookup` for one specific person.\",\n args: {\n days: { type: \"string\", description: \"Window in days, 1-365 (default 30)\", required: false },\n },\n});\n\nregisterSchema({\n command: \"hubspot.contacts.properties\",\n description:\n \"Every contact property a HubSpot event can watch, with its `kind` (select, string, number, date, boolean) — which decides the operators the trigger takes — and, for a select, the `options` its values come from. Start here to make a HubSpot event: pick the property and condition that mean the outcome (a deal won is usually `lifecyclestage` is `customer`, a custom property the client's team sets, or a number crossing a threshold), then `baker analytics sources --create-hubspot --property <name> [--operator <op>] --value <value>…` reads it every five minutes. Names are HubSpot's internal ones; use them as printed.\",\n args: {},\n});\n\nregisterSchema({\n command: \"hubspot.contacts.fields\",\n description:\n \"Every contact property on the connected HubSpot account — name, label, group and HubSpot's type — which is what a HubSpot event's rows can read: `baker analytics sources --create-hubspot … --field email={{work_email}} --field value={{deal_value}} --field currency=EUR`, or `--map` on an existing one. Names are HubSpot's internal ones; use them as printed, and `{{id}}` for the contact's own id. No personal data.\",\n args: {},\n});\n\nregisterSchema({\n command: \"hubspot.contacts.lookup\",\n routes: [\"POST /api/hubspot/contacts/lookup\"],\n effect: \"read_live\",\n description:\n \"One contact by email: lifecycle stage, whether anyone is assigned, its account (company) and deals with their stage — settles whether a lead was picked up. `--properties utm_campaign,utm_source` also reads those into `contact.properties`, to check a form's tracking reached it: each value, or null when empty; a name the account does not define is left out, never null. `found: false` means the lead never reached the CRM at all — that is a finding, not an error. `dealsReadable: false` / `companyReadable: false` mean deals or account details were not readable on this connection, so an empty deals list or a null company is unknown rather than absent.\",\n args: {\n email: { type: \"positional\", description: \"The contact's email address\", required: true },\n properties: {\n type: \"string\",\n description:\n \"Comma-separated contact properties to read, by HubSpot's internal name (up to 25; `baker hubspot contacts fields` lists them): --properties utm_campaign,utm_source\",\n required: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.workflows.list\",\n description:\n \"Every workflow on the connected account, with whether it is switched on. Read it when auditing what happens to a lead after it is captured — a form wired to a workflow that is off looks connected and does nothing.\",\n args: {\n search: { type: \"string\", description: \"Case-insensitive substring match on the workflow name\", required: false },\n \"enabled-only\": { type: \"boolean\", description: \"Only workflows that are on\", required: false, default: false },\n },\n});\n\nregisterSchema({\n command: \"hubspot.workflows.view\",\n description:\n \"One workflow's actual configuration: what enrols a record, whether it re-enrols, and every step with the property it writes. Read it before saying a workflow is correct — `workflows list` only tells you it exists and whether it is on. Branches come back in HubSpot's order, and on a LIST_BRANCH step that is evaluation order (`order: 1` wins over `order: 2`) — which is where this kind of setup silently breaks: a broad branch placed above a narrow one swallows the records the narrow one was written for, and nothing reports it. A STATIC_BRANCH matches on a value instead, so its order carries no precedence. Steps are NOT in execution order — follow `nextActionId` from step to step. Add --full for the branch filter criteria (which property is compared to which value).\",\n args: {\n workflowId: {\n type: \"positional\",\n description: \"Workflow id (from `baker hubspot workflows list`)\",\n required: true,\n },\n full: {\n type: \"boolean\",\n description: \"Include the raw HubSpot payload — the only place the branch filter criteria can be read\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.pipelines.list\",\n description:\n \"The account's deal pipelines and their stages, in the order they run, each stage with `isClosed` / `isWon` (HubSpot's closed-won is closed with probability 1). Use it to answer where a lead lands once captured and whether it moved — the 'have these leads been worked?' half of a form audit — and to pick the pipeline ids for `hubspot deals list --pipeline`.\",\n args: {},\n});\n\nregisterSchema({\n command: \"hubspot.meetings.list\",\n description:\n \"Every HubSpot meeting link (calendar) on the connected account, with just enough to choose one: name, slug, link type (personal / group / round-robin), whether booking redirects somewhere, and how many booking fields it asks for (null = unknown, read it with `meetings view`). Next step is usually `hubspot meetings view <slug> --as-node`, which gives you the blob to write straight into a hubspotMeeting step.\",\n args: {\n search: {\n type: \"string\",\n description:\n \"Case-insensitive match on the meeting name or slug, or a pasted booking link (meetings.hubspot.com/<slug>)\",\n required: false,\n },\n \"redirecting-only\": {\n type: \"boolean\",\n description: \"Only meeting links that redirect after booking\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.meetings.view\",\n description:\n \"One HubSpot meeting link in detail: its booking-form fields (name, label, type, required, custom), link, and redirect URL. This is the source of truth for a calendar's fields — the list command cannot see them reliably. Add --as-node to get the object to write into the step's form.external instead.\",\n args: {\n slug: { type: \"positional\", description: \"Meeting slug (from `baker hubspot meetings list`)\", required: true },\n \"as-node\": {\n type: \"boolean\",\n description: \"Emit the resource blob to write into a flow node's form.external, instead of the readable view.\",\n required: false,\n default: false,\n },\n },\n});\n\nconst formsListCommand = defineCommand({\n meta: {\n name: \"list\",\n description:\n \"List HubSpot forms with embed type and post-submit action. Example: baker hubspot forms list --redirecting-only\",\n },\n args: {\n search: { type: \"string\", description: \"Match on form name\", required: false },\n \"redirecting-only\": { type: \"boolean\", description: \"Only forms that redirect on submit\", required: false },\n \"embed-type\": { type: \"string\", description: \"Filter: legacy|v4|unknown\", required: false },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args[\"redirecting-only\"]) {\n body.redirectingOnly = true;\n }\n const embedType = assertEmbedType(args[\"embed-type\"]);\n if (embedType) {\n body.embedType = embedType;\n }\n\n const response = await apiPost<HubspotFormsListResponse>(\"/api/hubspot/forms/list\", body, { read: true });\n const { forms } = response.data;\n const redirecting = forms.filter((form) => form.postSubmitAction?.type === \"redirect_url\");\n const hints: string[] = [];\n if (forms.length === 0) {\n hints.push(\"No forms matched. Drop --search/--embed-type, or check the connected HubSpot account.\");\n } else {\n hints.push(\n \"To put one on a page: `baker hubspot forms view <id> --as-node` returns the object to write into the step's form.external. No request_flow_input needed for HubSpot.\",\n );\n }\n if (redirecting.length > 0) {\n hints.push(\n `${redirecting.length} form(s) redirect after submit. That is fine mid-Form: the renderer suppresses the redirect whenever a step follows the form, and honors it when the form is the last step.`,\n );\n }\n const blocked = forms.filter((form) => form.captchaEnabled);\n if (blocked.length > 0) {\n // Named rather than counted, because the next thing the agent does with\n // this is tell a person which of their forms is the problem — but\n // bounded, since every row already carries `captchaEnabled` and an\n // account with forty blocked forms would otherwise print forty names.\n const shown = blocked.slice(0, 3).map((form) => form.name);\n const rest = blocked.length - shown.length;\n hints.push(\n `${blocked.length} form(s) have spam prevention (captcha) on: ${shown.join(\", \")}${rest > 0 ? `, and ${rest} more` : \"\"}. HubSpot refuses every submission sent to those, so they can be embedded on a page but never wired as a Form's destination. Only the user can switch it off, on the form in HubSpot.`,\n );\n }\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"forms\"), ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/**\n * The one HubSpot setting that decides whether a form can receive a lead at\n * all. HubSpot refuses every API submission to a form with spam prevention on\n * (`FORM_HAS_RECAPTCHA_ENABLED`) and there is no token to attach, so the answer\n * is never \"send it differently\" — it is a switch only the client can flip.\n */\nconst CAPTCHA_VIEW_HINT =\n \"This form has spam prevention (captcha) on. HubSpot refuses every submission sent to it, so it cannot be a Form's destination — embedding it on a page still works, because the visitor solves the captcha in the browser. Only the user can switch it off, on the form in HubSpot; do not wire a delivery to it, and tell them what has to change.\";\n\nconst CAPTCHA_NODE_HINT =\n \"This form has spam prevention (captcha) on. That is fine for embedding it on a page — the visitor solves it in the browser — but it can never be a Form's delivery destination, so do not also wire a hubspotForm side effect to this form.\";\n\n/**\n * What to say about one form beyond its fields.\n *\n * Pure and exported so the wording is testable: these are the three facts about\n * a HubSpot form that decide whether wiring it works, and each of them is\n * invisible in the form's own field list.\n */\nexport function formViewHints(form: {\n postSubmitAction: { type: string; value: string } | null;\n captchaEnabled: boolean;\n embedType: string;\n}): string[] {\n const hints: string[] = [];\n if (form.postSubmitAction?.type === \"redirect_url\") {\n hints.push(\n `This form redirects to ${form.postSubmitAction.value} on submit. Placed anywhere but the last step of a Form, that redirect is suppressed so the next step can render.`,\n );\n }\n if (form.captchaEnabled) {\n hints.push(CAPTCHA_VIEW_HINT);\n }\n if (form.embedType === \"unknown\") {\n hints.push(\"Embed type could not be determined from HubSpot's response; the renderer treats it as legacy.\");\n }\n return hints;\n}\n\n/**\n * The same for the `--as-node` blob, where the reader is about to *embed* the\n * form. Captcha reads the opposite way here and has to say so: an embedded form\n * with captcha works, because the visitor solves it in the browser. Silence\n * would leave an agent that just read the refusal elsewhere to conclude the\n * form is unusable and quietly pick another.\n */\nexport function formNodeHints(\n external:\n | {\n captchaEnabled: boolean;\n embedType?: string;\n region?: string;\n configuration?: { postSubmitAction: { type: string } };\n }\n | undefined,\n): string[] {\n return [\n \"Write this object into the node's `form.external` in the flow's _data.json, keeping the rest of the node as-is. No request_flow_input needed — the account is already connected.\",\n ...(external?.captchaEnabled ? [CAPTCHA_NODE_HINT] : []),\n ...(external?.configuration?.postSubmitAction.type === \"redirect_url\"\n ? [\n \"This form redirects on submit. Safe unless it is the last step: the renderer suppresses the redirect whenever a step follows it.\",\n ]\n : []),\n ...(external?.embedType === \"v4\" && !external.region\n ? [\n \"WARNING: this is a v4 form and the connected account has no region recorded, so the step will load HubSpot's na1 script host. That is correct for US portals and breaks the form on eu1/ap1 ones. If it renders blank, have the user reconnect HubSpot from Brain -> Integrations -> Tools, then re-run this command.\",\n ]\n : []),\n ];\n}\n\nconst formsViewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Show one HubSpot form's fields and configuration. Example: baker hubspot forms view 1a2b3c\",\n },\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id\", required: true },\n full: { type: \"boolean\", description: \"Include the raw HubSpot payload\", required: false },\n \"as-node\": { type: \"boolean\", description: \"Emit the node-ready form.external blob\", required: false },\n },\n run: async ({ args }) => {\n try {\n const response = await apiPost<HubspotFormsViewResponse>(\n \"/api/hubspot/forms/view\",\n {\n formId: args.formId,\n ...(args.full ? { full: true } : {}),\n ...(args[\"as-node\"] ? { asNode: true } : {}),\n },\n { read: true },\n );\n\n if (args[\"as-node\"]) {\n writeJson({ ...response, hints: formNodeHints(response.data.external) });\n return;\n }\n\n const form = response.data.form;\n if (!form) {\n throw new Error(\"Response did not include the form view\");\n }\n const hints = formViewHints(form);\n\n writeJson({ ...response, meta: { count: form.fields.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst meetingsListCommand = defineCommand({\n meta: {\n name: \"list\",\n description: \"List HubSpot meeting links (calendars). Example: baker hubspot meetings list\",\n },\n args: {\n search: { type: \"string\", description: \"Match on meeting name, slug or a pasted booking link\", required: false },\n \"redirecting-only\": { type: \"boolean\", description: \"Only links that redirect after booking\", required: false },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args[\"redirecting-only\"]) {\n body.redirectingOnly = true;\n }\n\n const response = await apiPost<HubspotMeetingsListResponse>(\"/api/hubspot/meetings/list\", body, { read: true });\n const { meetings } = response.data;\n const hints: string[] = [];\n if (meetings.length === 0) {\n hints.push(\n args.search\n ? `No meeting link's name, slug or booking link matched \"${args.search}\". Drop --search to see every calendar on the connected account.`\n : \"No meeting links matched. Check the connected HubSpot account.\",\n );\n } else {\n hints.push(\n \"To put one on a page: `baker hubspot meetings view <slug> --as-node` returns the object to write into the step's form.external.\",\n );\n }\n const unknown = meetings.filter((meeting) => !meeting.redirectKnown);\n if (unknown.length > 0) {\n hints.push(\n `HubSpot did not report booking settings for ${unknown.length} of these (${unknown\n .map((meeting) => meeting.slug)\n .join(\n \", \",\n )}), so their redirect and field count are UNKNOWN, not absent. Run \\`baker hubspot meetings view <slug>\\` before concluding one does not redirect.`,\n );\n }\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"meetings\"), ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst meetingsViewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Show one HubSpot meeting link's booking fields. Example: baker hubspot meetings view discovery-call\",\n },\n args: {\n slug: { type: \"positional\", description: \"Meeting slug\", required: true },\n \"as-node\": { type: \"boolean\", description: \"Emit the node-ready form.external blob\", required: false },\n },\n run: async ({ args }) => {\n try {\n const response = await apiPost<HubspotMeetingsViewResponse>(\n \"/api/hubspot/meetings/view\",\n {\n slug: args.slug,\n ...(args[\"as-node\"] ? { asNode: true } : {}),\n },\n { read: true },\n );\n\n if (args[\"as-node\"]) {\n const { external } = response.data;\n writeJson({\n ...response,\n hints: [\n \"Write this object into the node's `form.external` in the flow's _data.json, keeping the rest of the node as-is. No request_flow_input needed — the account is already connected.\",\n ...(external?.customParams.redirectUrl\n ? [\n `This calendar redirects to ${external.customParams.redirectUrl} after booking, and that redirect is NOT suppressed — any step placed after it is unreachable. Keep it as the last step, or ask the user to clear the redirect in HubSpot.`,\n ]\n : []),\n ],\n });\n return;\n }\n\n const meeting = response.data.meeting;\n if (!meeting) {\n throw new Error(\"Response did not include the meeting view\");\n }\n const hints: string[] = [];\n if (meeting.redirectUrl) {\n hints.push(\n `This calendar redirects to ${meeting.redirectUrl} after booking. A step placed after it will not be reached — keep it as the last step, or clear the redirect in HubSpot.`,\n );\n }\n\n writeJson({ ...response, meta: { count: meeting.fields.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst formsSubmissionsCommand = defineCommand({\n meta: {\n name: \"submissions\",\n description:\n \"How many leads a form received, and when. Example: baker hubspot forms submissions <formId> --days 30\",\n },\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id\", required: true },\n days: { type: \"string\", description: \"Window in days (default 30)\", required: false },\n full: { type: \"boolean\", description: \"Include each lead's answers\", required: false },\n },\n run: async ({ args }) => {\n try {\n const days = args.days === undefined ? 30 : Number(args.days);\n if (!Number.isInteger(days) || days < 1 || days > 365) {\n throw new ApiError(\"VALIDATION_ERROR\", \"--days must be a whole number between 1 and 365.\");\n }\n\n const response = await apiPost<HubspotFormSubmissionsResponse>(\n \"/api/hubspot/forms/submissions\",\n {\n formId: args.formId,\n days,\n ...(args.full ? { full: true } : {}),\n },\n { read: true },\n );\n const { inWindow, total, truncated, lastSubmittedAt } = response.data;\n\n const hints: string[] = [];\n if (inWindow === 0) {\n hints.push(\n total === 0\n ? \"This form has received nothing at all — check it is the form actually embedded on the page before concluding the campaign is at fault.\"\n : `No leads in the last ${days} days, though the form has ${total} older submission(s). It worked once and has gone quiet.`,\n );\n }\n if (truncated) {\n hints.push(\n \"Stopped before reaching the end of the window, so `inWindow` is a floor, not a count. Say so rather than reporting it as exact.\",\n );\n }\n if (!args.full && inWindow > 0) {\n hints.push(\n \"Counts only — the leads' own answers are not included. Add --full if you genuinely need the field values; it returns personal data, so do not paste it into a report or a chat message.\",\n );\n }\n if (lastSubmittedAt !== null) {\n hints.push(\n \"To find out whether these leads were worked, cross-check the deal pipeline: `baker hubspot pipelines list`.\",\n );\n }\n\n writeJson({ ...response, meta: { count: inWindow }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst workflowsListCommand = defineCommand({\n meta: {\n name: \"list\",\n description: \"List HubSpot workflows. Example: baker hubspot workflows list --enabled-only\",\n },\n args: {\n search: { type: \"string\", description: \"Match on workflow name\", required: false },\n \"enabled-only\": { type: \"boolean\", description: \"Only workflows that are on\", required: false },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args[\"enabled-only\"]) {\n body.enabledOnly = true;\n }\n\n const response = await apiPost<HubspotWorkflowsListResponse>(\"/api/hubspot/workflows/list\", body, { read: true });\n const { workflows } = response.data;\n const off = workflows.filter((workflow) => !workflow.enabled);\n const hints: string[] = [];\n if (workflows.length === 0) {\n hints.push(\"No workflows matched. Drop --search/--enabled-only, or the account genuinely has none.\");\n }\n if (off.length > 0) {\n hints.push(\n `${off.length} of these are switched off. A form wired to a workflow that is off looks connected and does nothing — worth flagging to the user.`,\n );\n }\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"workflows\"), ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/**\n * What the agent should take from one workflow read.\n *\n * All three of these are silent failures in HubSpot — the workflow saves, looks\n * right in the editor, and runs. Nothing surfaces them but reading the order and\n * the flags, so they are stated rather than left for the agent to notice.\n */\nexport function workflowViewHints(workflow: HubspotWorkflowsViewResponse[\"data\"][\"workflow\"]): string[] {\n const hints: string[] = [];\n if (!workflow.enabled) {\n hints.push(\n \"This workflow is switched off, so nothing below it is running now — it may still have run while it was on. Say so before reporting on what it does.\",\n );\n }\n\n // Only a LIST_BRANCH is evaluated top down. A STATIC_BRANCH splits on a value\n // and matches by equality, so \"a broad branch above a narrow one\" cannot\n // happen there — and both arrive here as `branches`, so the kind has to be\n // read off the step rather than off the list.\n const ordered = workflow.steps.filter((step) => step.type === \"LIST_BRANCH\" && (step.branches?.length ?? 0) > 1);\n if (ordered.length > 0) {\n hints.push(\n \"Branches are listed in evaluation order and the first match wins. Check that no broad branch sits above a narrower one — if it does, the narrow branch never runs and nothing in HubSpot reports it.\",\n );\n }\n if (workflow.raw === undefined && ordered.length > 0) {\n hints.push(\n \"This view names the branches but not what they compare. Re-run with --full to read the filter criteria before judging whether a branch matches what it was meant to match.\",\n );\n }\n\n if (workflow.enrollment.reEnrollment === false) {\n hints.push(\n \"Re-enrolment is off: a record that meets the criteria a second time will not run through this again. That is a real choice, not necessarily a fault — but confirm it is the intended one.\",\n );\n } else if (workflow.enrollment.reEnrollment === null) {\n hints.push(\n \"Whether this re-enrols is not reported for this kind of enrolment, so do not state it either way — read it in HubSpot if it matters.\",\n );\n }\n return hints;\n}\n\nconst workflowsViewCommand = defineCommand({\n meta: {\n name: \"view\",\n description:\n \"Read one workflow's real configuration — enrolment, branches in order, and what each step writes. Example: baker hubspot workflows view 121183594 --full\",\n },\n args: {\n workflowId: {\n type: \"positional\",\n description: \"Workflow id (from `baker hubspot workflows list`)\",\n required: true,\n },\n full: { type: \"boolean\", description: \"Include the raw HubSpot payload with the filter criteria\", required: false },\n },\n run: async ({ args }) => {\n try {\n const response = await apiPost<HubspotWorkflowsViewResponse>(\n \"/api/hubspot/workflows/view\",\n {\n workflowId: args.workflowId,\n ...(args.full ? { full: true } : {}),\n },\n { read: true },\n );\n const { workflow } = response.data;\n const hints = workflowViewHints(workflow);\n\n writeJson({ ...response, meta: { count: workflow.steps.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst pipelinesListCommand = defineCommand({\n meta: {\n name: \"list\",\n description: \"List HubSpot deal pipelines and their stages. Example: baker hubspot pipelines list\",\n },\n args: {},\n run: async () => {\n try {\n const response = await apiPost<HubspotPipelinesListResponse>(\"/api/hubspot/pipelines/list\", {}, { read: true });\n const { pipelines } = response.data;\n const hints: string[] =\n pipelines.length === 0\n ? [\"This account has no deal pipelines, so there is nowhere for a lead to be worked.\"]\n : [\"Stages are listed in the order they run in HubSpot, so the first stage is where a new lead lands.\"];\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"pipelines\"), hints });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\ntype HubspotObjectWord = \"contact\" | \"deal\" | \"lead\";\n\nconst OBJECT_WORDS: Record<HubspotObjectWord, { plural: string; command: string; rows: string }> = {\n contact: {\n plural: \"contacts\",\n command: \"baker hubspot contacts\",\n rows: '`--field email={{work_email}}`, `--field currency=EUR`, `--field first_name=\"{{firstname}} {{lastname}}\"`; `{{id}}` is the contact\\'s own id',\n },\n deal: {\n plural: \"deals\",\n command: \"baker hubspot deals\",\n rows: \"`--field value={{amount}}`, `--field currency={{deal_currency_code}}`, `--field email={{contact.email}}` — a deal's own properties bare, its contact's as `contact.<name>`; `{{id}}` is the deal's own id, `{{contact.id}}` the contact's\",\n },\n lead: {\n plural: \"leads\",\n command: \"baker hubspot leads\",\n rows: \"`--field email={{contact.email}}`, `--field properties.stage={{hs_pipeline_stage}}` — a lead's own properties bare, its contact's as `contact.<name>`; `{{id}}` is the lead's own id, `{{contact.id}}` the contact's. A lead carries no amount of its own, so `value` is empty unless you point it at a property\",\n },\n};\n\n/** `properties`, for contacts and for deals: what a HubSpot event can watch. */\nfunction propertiesCommand(object: HubspotObjectWord) {\n const words = OBJECT_WORDS[object];\n return defineCommand({\n meta: {\n name: \"properties\",\n description: `List every ${object} property a HubSpot event can watch, with its kind, the operators that kind takes, and a select's values. Example: ${words.command} properties`,\n },\n args: {},\n run: async () => {\n try {\n const response = await apiPost<HubspotContactPropertiesListResponse>(\n \"/api/hubspot/contacts/properties\",\n {\n object,\n },\n { read: true },\n );\n const { properties } = response.data;\n const operators = Object.entries(HUBSPOT_OPERATORS)\n .map(([kind, list]) => `${kind}: ${list.map((operator) => operator.value).join(\", \")}`)\n .join(\" · \");\n const objectFlag = object === \"contact\" ? \"\" : ` --object ${object}`;\n const hints =\n properties.length === 0\n ? [`This account has no visible ${object} property, so there is nothing an event could watch.`]\n : [\n `Pick the property and the condition that mean the outcome, then \\`baker analytics sources --create-hubspot${objectFlag} --property <name> [--operator <op>] --value <value>…\\` (\\`--value\\` repeats for a list). Operators by kind — ${operators}. Counting starts from creation: a ${object} already satisfying it is not counted until it leaves and comes back.`,\n ];\n writeJson({ ok: true, ...rowsAsData(response.data, \"properties\"), hints });\n } catch (err) {\n failNotConnected(err);\n }\n },\n });\n}\n\nconst contactsPropertiesCommand = propertiesCommand(\"contact\");\n\nconst contactsSummaryCommand = defineCommand({\n meta: {\n name: \"summary\",\n description: \"Whether recent leads are being worked, as counts. Example: baker hubspot contacts summary --days 30\",\n },\n args: {\n days: { type: \"string\", description: \"Window in days (default 30)\", required: false },\n },\n run: async ({ args }) => {\n try {\n const days = args.days === undefined ? 30 : Number(args.days);\n if (!Number.isInteger(days) || days < 1 || days > 365) {\n throw new ApiError(\"VALIDATION_ERROR\", \"--days must be a whole number between 1 and 365.\");\n }\n\n const response = await apiPost<HubspotContactsSummaryResponse>(\n \"/api/hubspot/contacts/summary\",\n { days },\n { read: true },\n );\n const { total, withOwner, withoutOwner, byStage, truncated } = response.data;\n\n const hints: string[] = [];\n if (total === 0) {\n hints.push(`No contacts were created in the last ${days} days — nothing reached the CRM in that window.`);\n } else if (withOwner === 0) {\n hints.push(\n `None of these ${total} contacts has anyone assigned. That is the strongest available signal that the leads are arriving and nobody is picking them up — worth raising with the user.`,\n );\n } else if (withoutOwner > withOwner) {\n hints.push(`${withoutOwner} of ${total} contacts have nobody assigned — more unworked than worked.`);\n }\n const unset = byStage.find((entry) => entry.stage === \"unset\");\n if (unset && unset.count > 0) {\n hints.push(\n `${unset.count} contact(s) have no lifecycle stage set at all, so they were created and never staged.`,\n );\n }\n if (truncated) {\n hints.push(\"Stopped before reading every contact in the window, so these counts are floors, not totals.\");\n }\n\n writeJson({ ...response, meta: { count: total }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/**\n * What the agent should take from one contact lookup.\n *\n * An empty `deals` or a null `company` means two different things depending on\n * whether the connection could read them at all, and the wrong reading — \"this\n * lead was never worked\" — is the one conclusion the command exists to settle.\n * So each is paired with its readability flag rather than reported bare.\n */\nexport function contactLookupHints(\n data: HubspotContactLookupResponse[\"data\"],\n askedProperties: readonly string[] = [],\n): string[] {\n const { found, contact, deals, dealsReadable, company, companyReadable } = data;\n if (!found) {\n return [\n \"No contact with that email. The lead never reached the CRM — check the form's submissions before assuming the CRM lost it.\",\n ];\n }\n\n const hints: string[] = [];\n if (contact?.ownerId === null) {\n hints.push(\"Nobody is assigned to this contact.\");\n }\n const undefinedProperties = askedProperties.filter((name) => !Object.hasOwn(contact?.properties ?? {}, name));\n if (undefinedProperties.length > 0) {\n hints.push(\n `No contact property named ${undefinedProperties.join(\", \")} on this account, so there is nothing to read — this is not an empty value. \\`baker hubspot contacts fields\\` lists the names this account uses.`,\n );\n }\n if (!dealsReadable) {\n hints.push(\n \"Deals were not read: this HubSpot connection does not cover them. Do not report the lead as having no deal — you cannot tell. The user can enable it by reconnecting HubSpot.\",\n );\n } else if (deals.length === 0) {\n hints.push(\"No deal is associated, so this contact was never taken into the pipeline.\");\n }\n if (!companyReadable) {\n hints.push(\n \"Account details were not read: this HubSpot connection does not cover them. Do not report the lead as having no account — you cannot tell. The user can enable it by reconnecting HubSpot.\",\n );\n } else if (company === null) {\n hints.push(\n \"No account is associated either. Most B2B setups create one automatically when a contact arrives, so this usually means the lead was never processed at all — not that the account is missing.\",\n );\n }\n return hints;\n}\n\nfunction commaList(raw: string): string[] {\n return [\n ...new Set(\n raw\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ),\n ];\n}\n\nconst contactsLookupCommand = defineCommand({\n meta: {\n name: \"lookup\",\n description:\n \"Find one contact by email and see whether it was worked; --properties reads named contact properties too. Example: baker hubspot contacts lookup a@b.com --properties utm_campaign,utm_source\",\n },\n args: {\n email: { type: \"positional\", description: \"The contact's email address\", required: true },\n properties: {\n type: \"string\",\n description:\n \"Comma-separated contact properties to read, by HubSpot's internal name: --properties utm_campaign,utm_source\",\n required: false,\n },\n },\n run: async ({ args }) => {\n try {\n const properties = typeof args.properties === \"string\" ? commaList(args.properties) : [];\n const response = await apiPost<HubspotContactLookupResponse>(\n \"/api/hubspot/contacts/lookup\",\n {\n email: args.email,\n ...(properties.length > 0 ? { properties } : {}),\n },\n { read: true },\n );\n const hints = contactLookupHints(response.data, properties);\n\n writeJson({\n ...response,\n meta: { count: response.data.found ? 1 : 0 },\n ...(hints.length > 0 ? { hints } : {}),\n });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/** `fields`, for contacts and for deals: what a HubSpot event's rows can read. */\nfunction fieldsCommand(object: HubspotObjectWord) {\n const words = OBJECT_WORDS[object];\n return defineCommand({\n meta: {\n name: \"fields\",\n description: `List every property a HubSpot event on a ${object} can read into its rows, with HubSpot's type${object === \"contact\" ? \"\" : ` — the ${object}'s own, and its contact's as contact.<name>`}. Example: ${words.command} fields`,\n },\n args: {},\n run: async () => {\n try {\n const response = await apiPost<HubspotContactFieldsListResponse>(\n \"/api/hubspot/contacts/fields\",\n { object },\n { read: true },\n );\n writeJson({\n ok: true,\n ...rowsAsData(response.data, \"fields\"),\n hints: [\n `A row of a HubSpot event is a template over these names: ${words.rows}. \\`baker analytics sources --preview${object === \"contact\" ? \"\" : ` --object ${object}`} --property <p> --value <v> --field <row>…\\` reads one real ${object} to check the rows against.`,\n ],\n });\n } catch (err) {\n failNotConnected(err);\n }\n },\n });\n}\n\nconst contactsFieldsCommand = fieldsCommand(\"contact\");\n\nconst dealsCommand = defineCommand({\n meta: {\n name: \"deals\",\n description:\n \"Deals on the connected HubSpot account: the deals themselves with amount and stage (`list`), one deal found by its name (`lookup`), and what a HubSpot event on a deal can watch (`properties`) and read (`fields`).\",\n },\n subCommands: {\n list: () => import(\"./crm.ts\").then((m) => m.dealsListCommand),\n lookup: () => import(\"./crm.ts\").then((m) => m.dealsLookupCommand),\n properties: propertiesCommand(\"deal\"),\n fields: fieldsCommand(\"deal\"),\n },\n});\n\nconst leadsCommand = defineCommand({\n meta: {\n name: \"leads\",\n description:\n \"Leads on the connected HubSpot account: what a HubSpot event on a lead can watch (`properties`) and read (`fields`). Start here for qualification and disqualification — a lead's stage is where HubSpot records both, and `hs_pipeline_stage` lists the account's own stages with their labels. Needs Sales Hub Professional or Enterprise; on any other plan the account has no leads to read.\",\n },\n subCommands: { properties: propertiesCommand(\"lead\"), fields: fieldsCommand(\"lead\") },\n});\n\nconst contactsCommand = defineCommand({\n meta: { name: \"contacts\", description: \"Contacts on the connected HubSpot account.\" },\n subCommands: {\n summary: contactsSummaryCommand,\n lookup: contactsLookupCommand,\n properties: contactsPropertiesCommand,\n fields: contactsFieldsCommand,\n },\n});\n\nconst companiesCommand = defineCommand({\n meta: { name: \"companies\", description: \"Companies (accounts) in the connected HubSpot CRM.\" },\n subCommands: {\n search: () => import(\"./crm.ts\").then((m) => m.companiesSearchCommand),\n contacts: () => import(\"./crm.ts\").then((m) => m.companiesContactsCommand),\n },\n});\n\nconst formsCommand = defineCommand({\n meta: { name: \"forms\", description: \"HubSpot forms on the connected account.\" },\n subCommands: { list: formsListCommand, view: formsViewCommand, submissions: formsSubmissionsCommand },\n});\n\nconst workflowsCommand = defineCommand({\n meta: { name: \"workflows\", description: \"HubSpot workflows on the connected account.\" },\n subCommands: { list: workflowsListCommand, view: workflowsViewCommand },\n});\n\nconst pipelinesCommand = defineCommand({\n meta: { name: \"pipelines\", description: \"HubSpot deal pipelines on the connected account.\" },\n subCommands: { list: pipelinesListCommand },\n});\n\nconst meetingsCommand = defineCommand({\n meta: { name: \"meetings\", description: \"HubSpot meeting links (calendars) on the connected account.\" },\n subCommands: { list: meetingsListCommand, view: meetingsViewCommand },\n});\n\nexport const hubspotCommand = defineCommand({\n meta: {\n name: \"hubspot\",\n description: `Read the connected HubSpot account — forms, the leads they received, workflows, deal pipelines, CRM\ncompanies and deals, and meeting links (calendars) — and get the blob to wire a form into a Form step yourself.\n\nExamples:\n baker hubspot forms list # every form: embed type + post-submit action\n baker hubspot forms list --redirecting-only # which forms redirect away on submit\n baker hubspot forms view <formId> # fields, consent mode, full configuration\n baker hubspot forms view <formId> --as-node # the form.external blob -> write into the step\n baker hubspot forms submissions <formId> # how many leads it got, and when\n baker hubspot workflows list --enabled-only # what runs after a lead is captured\n baker hubspot workflows view <workflowId> # its real branches, in order, and what each step writes\n baker hubspot pipelines list # where a lead lands, and the stages after it\n baker hubspot contacts summary --days 30 # are recent leads being worked? (counts only)\n baker hubspot contacts lookup a@b.com # was this one lead picked up? --properties utm_campaign,… reads those too\n baker hubspot companies search --domains acme.com,globex.io --with-deals # which are accounts, with deals\n baker hubspot deals list --modified-since 2026-01-01 # deals: amount, stage, closed won\n baker hubspot deals lookup --search \"Acme\" # is this sale in the CRM? (by deal name)\n baker hubspot deals properties # what a HubSpot event on a deal can watch (dealstage, amount…)\n baker hubspot deals fields # what its rows can read: the deal's own, its contact's as contact.<name>\n baker hubspot meetings list # every calendar + whether booking redirects\n baker hubspot meetings view <slug> --as-node # same, for a hubspotMeeting step\n\nAn account connected before one of these existed cannot serve it — you get HUBSPOT_RECONNECT_REQUIRED, which\nmeans HubSpot IS connected and the user has to reconnect it to widen what Baker may read. Report that and\ncarry on with the rest; never call it broken and never retry.\n\nNothing here is secret, so HubSpot steps do not need request_flow_input: take --as-node and edit the\nflow's _data.json. Use the approval form only when no account is connected or the right form is unclear.\nFull guide: __tooling__/docs/tools/baker/hubspot.md`,\n },\n subCommands: {\n forms: formsCommand,\n workflows: workflowsCommand,\n pipelines: pipelinesCommand,\n contacts: contactsCommand,\n companies: companiesCommand,\n deals: dealsCommand,\n leads: leadsCommand,\n meetings: meetingsCommand,\n },\n});\n"],"mappings":";;;;;;;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6Bf;AAAA,EACA,aAAa;AAAA,IACX,OAAO;AAAA,IACP,WAAW;AAAA,IACX,WAAW;AAAA,IACX,UAAU;AAAA,IACV,WAAW;AAAA,IACX,OAAO;AAAA,IACP,OAAO;AAAA,IACP,UAAU;AAAA,EACZ;AACF,CAAC;","names":[]}
@@ -1477,8 +1477,8 @@ Full guide: __tooling__/docs/tools/baker/ads-linkedin.md`
1477
1477
  draft: () => import("./draft-JGEZVDAS.js").then((m) => m.linkedinDraftCommand),
1478
1478
  analytics: () => import("./analytics-WLFBQOO4.js").then((m) => m.analyticsCommand),
1479
1479
  demographics: () => import("./demographics-K5WTHZCW.js").then((m) => m.demographicsCommand),
1480
- companies: () => import("./companies-M7LWFZK3.js").then((m) => m.companiesCommand),
1481
- "top-companies": () => import("./top-companies-PDVHM7XC.js").then((m) => m.topCompaniesCommand),
1480
+ companies: () => import("./companies-ITNWR5Q4.js").then((m) => m.companiesCommand),
1481
+ "top-companies": () => import("./top-companies-KEV55RME.js").then((m) => m.topCompaniesCommand),
1482
1482
  resolve: () => import("./resolve-NVL3FTQU.js").then((m) => m.resolveCommand),
1483
1483
  facets: () => import("./facets-GXBTQCAW.js").then((m) => m.facetsCommand),
1484
1484
  "audience-size": () => import("./audience-size-ISJSPSRW.js").then((m) => m.audienceSizeCommand),
@@ -1495,4 +1495,4 @@ Full guide: __tooling__/docs/tools/baker/ads-linkedin.md`
1495
1495
  export {
1496
1496
  linkedinCommand
1497
1497
  };
1498
- //# sourceMappingURL=linkedin-66QNH2HH.js.map
1498
+ //# sourceMappingURL=linkedin-BD63QPGK.js.map
@@ -4,10 +4,10 @@ import {
4
4
  import {
5
5
  knowledgeTargetsHint,
6
6
  targetsArg
7
- } from "./chunk-RDTSLMSJ.js";
7
+ } from "./chunk-63XEBJIX.js";
8
8
  import {
9
9
  targetsHints
10
- } from "./chunk-HS5NGBXW.js";
10
+ } from "./chunk-4X6QBNIB.js";
11
11
  import "./chunk-5OXVEKML.js";
12
12
  import "./chunk-2DGJKIHF.js";
13
13
  import "./chunk-IPEQHZ5H.js";
@@ -247,4 +247,4 @@ export {
247
247
  topTargetCompanies,
248
248
  topTargetsHint
249
249
  };
250
- //# sourceMappingURL=top-companies-PDVHM7XC.js.map
250
+ //# sourceMappingURL=top-companies-KEV55RME.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koda-sl/baker-cli",
3
- "version": "0.851.0-dev.38f83ef80",
3
+ "version": "0.851.0-dev.914922aaf",
4
4
  "description": "AI-agent-first CLI for interacting with Baker, including the Baker creative canvas.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/accounts/index.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n ACCOUNTS_ENGAGEMENT_MAX_LIMIT,\n type AccountEngagementRow,\n type AccountsCampaignsResponse,\n type AccountsCompanyRequest,\n type AccountsCompanyResponse,\n type AccountsEngagementRequest,\n type AccountsEngagementResponse,\n type AccountsInfluencedResponse,\n accountsCampaignsRequestSchema,\n accountsCompanyRequestSchema,\n accountsEngagementRequestSchema,\n accountsInfluencedRequestSchema,\n INFLUENCE_MODEL_KINDS,\n influenceMetricWords,\n type MoneyByCurrency,\n type TargetsSummary,\n warmAccounts,\n} from \"@baker/api/accounts\";\nimport { defineCommand } from \"citty\";\nimport { z } from \"zod\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { withWindowSpellings } from \"../../date-window.ts\";\nimport { writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failApi } from \"../actions/shared.ts\";\nimport { outputFormatRefusal, TABLE_OUTPUT_FORMATS, writeAdsOutput } from \"../ads/output.ts\";\nimport {\n accountsRefusal,\n companyView,\n comparisonHints,\n ENGAGEMENT_TABLE_FIELDS,\n engagementHints,\n engagementTableRows,\n influencedHints,\n influencedTableRows,\n invalidArgsMessage,\n setupHint,\n targetsHints,\n targetsView,\n warmAccountsCsv,\n warmHints,\n warmMetric,\n warmMinimum,\n withDealStatus,\n} from \"./report.ts\";\nimport { readTargetsFile, type TargetsFile } from \"./targets.ts\";\n\n/**\n * `baker accounts` — which companies the LinkedIn ads are warming, and which\n * CRM deals they influenced. Reads the nightly Account insights sync; nothing\n * here calls LinkedIn or the CRM, and nothing changes anywhere.\n */\n\nfunction optionalNumber(raw: unknown): number | undefined {\n return typeof raw === \"string\" && raw.trim() !== \"\" ? Number(raw) : undefined;\n}\n\nfunction optionalString(raw: unknown): string | undefined {\n return typeof raw === \"string\" && raw.trim() !== \"\" ? raw.trim() : undefined;\n}\n\nfunction failInvalidArgs(message: string): never {\n writeJson({ ok: false, error: { code: \"INVALID_ARGS\", message } });\n process.exit(1);\n}\n\n/** A request the schema refuses never reaches the store; say which flag, in the envelope. */\nfunction failInvalid(issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>): never {\n failInvalidArgs(invalidArgsMessage(issues));\n}\n\n/** `--output` as asked, refused with the supported list instead of quietly printing JSON. */\nfunction outputFormat(args: Record<string, unknown>, supported: readonly string[]): string {\n const format = optionalString(args.output) ?? \"json\";\n const refusal = outputFormatRefusal(format, supported);\n if (refusal !== null) failInvalidArgs(refusal);\n return format;\n}\n\nconst OUTPUT_ARG = {\n type: \"string\",\n description: \"json|csv|jsonl|md (default json). csv/jsonl/md print the rows only; the summary and hints go to stderr\",\n required: false,\n default: \"json\",\n} as const;\n\nconst RULE_ARGS = {\n model: {\n type: \"string\",\n description:\n \"Read this report with another influence model, for this call only (the saved settings stay): engagement (engagements), awareness (impressions), intent (clicks) or attention (engagements and video views together — LinkedIn counts no video view as an engagement)\",\n required: false,\n },\n threshold: {\n type: \"string\",\n description:\n \"Read this report with another threshold on the model's metric, for this call only (a whole number, 1 or more)\",\n required: false,\n },\n} as const;\n\nfunction ruleInput(args: Record<string, unknown>): { model?: string; threshold?: number } {\n return { model: optionalString(args.model), threshold: optionalNumber(args.threshold) };\n}\n\nfunction moneyText(value: MoneyByCurrency): string {\n return Object.entries(value)\n .map(([currency, amount]) => `${Math.round(amount)} ${currency}`)\n .join(\" + \");\n}\n\n/** \"Not set up\" becomes the fix the agent relays; everything else is the ordinary error envelope. */\nfunction failAccounts(err: unknown): never {\n const refusal = err instanceof ApiError ? accountsRefusal(err.code, err.message) : null;\n if (err instanceof ApiError && refusal !== null) {\n writeJson({ ok: false, error: { code: refusal.code, message: err.message, fix: refusal.fix } });\n process.exit(1);\n }\n failApi(err);\n}\n\nconst WINDOW_ARGS = withWindowSpellings({\n \"last-months\": {\n type: \"string\",\n description: \"Calendar months to read, the current one included (1-24)\",\n required: false,\n },\n start: { type: \"string\", description: \"First day, YYYY-MM-DD (instead of --last-months)\", required: false },\n end: { type: \"string\", description: \"Last day, YYYY-MM-DD (default today; needs --start)\", required: false },\n});\n\nconst TARGETS_ARG = {\n targets: {\n type: \"string\",\n description:\n 'Only these target accounts: a .csv (a domain or website column; name, tier and organizationUrn optional) or a .json file ([\"acme.com\", …] or [{\"domain\": \"acme.com\", \"tier\": 1}, …]). A company is a target by its LinkedIn page, its website or its name — the same match as `baker ads linkedin companies --targets` and the warm-account alerts. Rows and numbers narrow to them, `targets` says how many were reached and engaged, per tier (`baker accounts engagement --targets <file> --full` lists the ones never reached), and `comparison` sets the targets beside every other company. Build one from the Knowledge with `node __tooling__/scripts/target-accounts.mjs --out targets.csv`',\n required: false,\n },\n} as const;\n\n/** `--targets` read and reduced to domains; refused in the envelope when the file cannot be read or names none. */\nfunction targetsInput(args: Record<string, unknown>): TargetsFile | null {\n const path = optionalString(args.targets);\n if (path === undefined) return null;\n let read: TargetsFile;\n try {\n read = readTargetsFile(path, readFileSync(path, \"utf8\"));\n } catch (err) {\n failInvalidArgs(`--targets: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (read.targets.length === 0) failInvalidArgs(`--targets: ${path} names no company website.`);\n return read;\n}\n\n/** The hints a `--targets` read adds; none without one. `listed`: the answer prints the targets never reached. */\nfunction withTargetsHints(\n hints: string[],\n read: TargetsFile | null,\n summary: TargetsSummary | undefined,\n listed = false,\n): string[] {\n return read === null ? hints : [...targetsHints(summary, read.unreadable, listed), ...hints];\n}\n\n/** The answer's `targets` block, its never-reached list only when `listed`; nothing without one. */\nfunction targetsBlock(summary: TargetsSummary | undefined, listed = false) {\n return summary ? { targets: targetsView(summary, listed) } : {};\n}\n\nfunction windowInput(args: Record<string, unknown>): { lastMonths?: number; start?: string; end?: string } {\n return {\n lastMonths: optionalNumber(args[\"last-months\"]),\n start: optionalString(args.start),\n end: optionalString(args.end),\n };\n}\n\n// --- influenced ---\n\nconst INFLUENCED_ARGS = {\n basis: {\n type: \"string\",\n description:\n \"pipeline (default): deals created in the period and not won. revenue: deals closed won in the period. open: deals open now, whenever created, that the ads engaged after they opened (in the period) — the pipeline an ABM campaign is warming\",\n required: false,\n default: \"pipeline\",\n },\n ...WINDOW_ARGS,\n full: {\n type: \"boolean\",\n description: \"Every deal in the period, influenced or not, instead of the influenced ones\",\n required: false,\n default: false,\n },\n ...RULE_ARGS,\n ...TARGETS_ARG,\n output: OUTPUT_ARG,\n} as const;\n\nconst DEAL_TABLE_FIELDS = [\n \"dealId\",\n \"dealName\",\n \"companyName\",\n \"domain\",\n \"amount\",\n \"currency\",\n \"status\",\n \"referenceAt\",\n \"touchValue\",\n \"firstTouchMonth\",\n \"matchConfidence\",\n \"influenced\",\n \"crmCompanyId\",\n];\n\nfunction influencedSummaryLine(data: AccountsInfluencedResponse[\"data\"]): string {\n const { summary, rule } = data;\n const value = moneyText(summary.influencedValue) || \"no amount\";\n if (data.basis === \"open\") {\n return `${summary.influencedDeals} of ${summary.deals} open deals reached (${value}) — ${rule.threshold}+ ${influenceMetricWords(rule.metric, rule.threshold)} after each deal opened, ${data.window.start} to ${data.window.end}.`;\n }\n return `${summary.influencedDeals} of ${summary.deals} ${data.basis} deals influenced (${value}) — ${rule.threshold}+ ${influenceMetricWords(rule.metric, rule.threshold)} in the ${rule.lookbackMonths} months before each deal, its own month up to the day before, ${data.window.start} to ${data.window.end}.`;\n}\n\nregisterSchema({\n command: \"accounts.influenced\",\n description:\n \"Start here for 'what pipeline / revenue did our LinkedIn ads influence'. A deal is influenced when its company reached the company's influence rule (default: 3+ LinkedIn ad engagements) before it: the 12 months up to the deal's month, and that month only up to the day before the deal was created (pipeline) or closed won (revenue). --basis open is the other ABM half: open deals, whenever created, that the ads engaged after they opened. A labelled rule, not credit: never call it 'attributed' or split it. Returns {summary: {deals, influencedDeals, influencedValue per currency, lowConfidenceDeals, spend, valuePerSpend}, deals, lowConfidence}. Amounts in different currencies are never added. Default the last 12 calendar months. --model/--threshold read it with another rule for this call only (\\\"what if we counted 5+ engagements\\\"); --targets <file> narrows it to the target accounts' deals; --output csv|md|jsonl prints the deals.\",\n args: INFLUENCED_ARGS,\n});\n\nconst influencedCommand = defineCommand({\n meta: {\n name: \"influenced\",\n description:\n \"Deals the LinkedIn ads influenced, with influenced pipeline or revenue. Example: baker accounts influenced --basis revenue --last-months 6\",\n },\n args: INFLUENCED_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, TABLE_OUTPUT_FORMATS);\n const targets = targetsInput(args);\n const parsed = accountsInfluencedRequestSchema.safeParse({\n ...windowInput(args),\n ...ruleInput(args),\n basis: optionalString(args.basis),\n full: Boolean(args.full),\n targets: targets?.targets,\n });\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsInfluencedResponse>(\"/api/accounts/influenced\", parsed.data);\n const hints = withTargetsHints(\n [\n ...setupHint(response.data.setupIssues),\n ...comparisonHints(response.data.comparison),\n ...influencedHints(response.data),\n ],\n targets,\n response.data.targets,\n );\n if (format !== \"json\") {\n const rows = influencedTableRows(response.data, parsed.data.full);\n writeAdsOutput(rows, format, DEAL_TABLE_FIELDS, [influencedSummaryLine(response.data), ...hints]);\n return;\n }\n writeJson({\n ...response,\n data: { ...response.data, ...targetsBlock(response.data.targets) },\n meta: { count: response.data.deals.length },\n ...(hints.length > 0 ? { hints } : {}),\n });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n// --- engagement ---\n\nconst ENGAGEMENT_ARGS = {\n ...WINDOW_ARGS,\n \"campaign-id\": { type: \"string\", description: \"Only this campaign's companies (numeric id)\", required: false },\n limit: {\n type: \"string\",\n description: `Companies per page, 1-${ACCOUNTS_ENGAGEMENT_MAX_LIMIT} (default 500)`,\n required: false,\n },\n page: {\n type: \"string\",\n description:\n \"Which page to read, 1-based, most engaged first (default 1). pageInfo.hasMore says another page follows; pageInfo.total counts every company reached\",\n required: false,\n },\n ...TARGETS_ARG,\n full: {\n type: \"boolean\",\n description: \"With --targets: also list every target account never reached (targets.notReached)\",\n required: false,\n default: false,\n },\n output: OUTPUT_ARG,\n} as const;\n\nregisterSchema({\n command: \"accounts.engagement\",\n description:\n \"Every company the LinkedIn ads reached, most engaged first, with the period before for comparison, New/Rising flags, and where it stands in the CRM (matched company; dealStatus won > open > lost > none, lost meaning every deal it had was lost; lastLostAt). Default the last 3 calendar months. From the nightly sync, so it is fast and covers up to 24 months; for a live read of one ad account use `baker ads linkedin companies`. Paged: --limit companies per page, --page N; pageInfo {page, pageSize, total, hasMore}. --targets <file> keeps the target accounts only and adds `targets` {total, reached, engaged, byTier}; --full adds notReached, the targets never reached.\",\n args: ENGAGEMENT_ARGS,\n});\n\nfunction engagementInput(\n args: Record<string, unknown>,\n targets: TargetsFile | null,\n limit?: number,\n): AccountsEngagementRequest {\n return {\n ...windowInput(args),\n campaignId: optionalString(args[\"campaign-id\"])?.replace(/^urn:li:sponsoredCampaign:/, \"\"),\n limit: limit ?? optionalNumber(args.limit),\n page: limit === undefined ? optionalNumber(args.page) : undefined,\n targets: targets?.targets,\n };\n}\n\nconst engagementCommand = defineCommand({\n meta: {\n name: \"engagement\",\n description:\n \"Companies the LinkedIn ads reached, with New/Rising flags and CRM status. Example: baker accounts engagement --last-months 3 --limit 50\",\n },\n args: ENGAGEMENT_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, TABLE_OUTPUT_FORMATS);\n const targets = targetsInput(args);\n const parsed = accountsEngagementRequestSchema.safeParse(engagementInput(args, targets));\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsEngagementResponse>(\"/api/accounts/engagement\", parsed.data);\n const hints = withTargetsHints(\n [\n ...setupHint(response.data.setupIssues),\n ...comparisonHints(response.data.comparison),\n ...engagementHints(response.data, parsed.data),\n ],\n targets,\n response.data.targets,\n Boolean(args.full),\n );\n if (format !== \"json\") {\n writeAdsOutput(engagementTableRows(response.data.companies), format, ENGAGEMENT_TABLE_FIELDS, hints);\n return;\n }\n const companies = withDealStatus(response.data.companies);\n writeJson({\n ...response,\n data: { ...response.data, ...targetsBlock(response.data.targets, Boolean(args.full)), companies },\n meta: { count: companies.length, ...(response.data.pageInfo ? { total: response.data.pageInfo.total } : {}) },\n ...(hints.length > 0 ? { hints } : {}),\n });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n// --- warm ---\n\nconst warmRuleSchema = z.object({\n model: z.enum(INFLUENCE_MODEL_KINDS).optional(),\n threshold: z.number().int().min(1).optional(),\n min: z.number().int().min(0).optional(),\n accounts: z.enum([\"all\", \"targets\"]).default(\"all\"),\n});\n\nconst WARM_ARGS = {\n ...WINDOW_ARGS,\n \"campaign-id\": ENGAGEMENT_ARGS[\"campaign-id\"],\n min: {\n type: \"string\",\n description:\n \"Least a company must have done this period on the rule's metric to count as warm (default: the company's influence threshold, e.g. 3 engagements; 0 keeps every New/Rising company)\",\n required: false,\n },\n ...RULE_ARGS,\n ...TARGETS_ARG,\n accounts: {\n type: \"string\",\n description:\n \"all (default) or targets: only the target accounts — those of --targets, else of the published target-accounts Knowledge (each row's isTarget), so no file is needed\",\n required: false,\n },\n output: {\n type: \"string\",\n description:\n \"json (default) or csv — csv prints companyName,domain,organizationUrn, the file `baker ads linkedin audiences create --type company-list --list-file` takes\",\n required: false,\n default: \"json\",\n },\n} as const;\n\nregisterSchema({\n command: \"accounts.warm\",\n description:\n \"Warm accounts: companies engaging with the LinkedIn ads more than in the period before (New: nothing before; Rising: engagements at least doubled) that reached the company's influence threshold this period (e.g. 3+ engagements; --min overrides, --min 0 drops it) and are not already somebody's deal: no open deal, never won (customers are left out), and no deal lost in the last 6 months (an older loss no longer counts). Default the current calendar month against the one before. `--output csv > warm.csv` writes a company list ready for `baker ads linkedin audiences create --type company-list --list-file warm.csv` (LinkedIn needs 300+ matched members to serve). Start here for 'which target accounts are warming': --accounts targets keeps the warm target accounts of the published target-accounts Knowledge, no file needed. --targets <file> keeps those of an ad-hoc list instead and adds `targets` (how many were reached and engaged; `baker accounts engagement --targets <file> --full` lists the ones never reached).\",\n args: WARM_ARGS,\n});\n\nconst warmCommand = defineCommand({\n meta: {\n name: \"warm\",\n description:\n \"Companies warming up that are not in pipeline, customers, or recently lost. Example: baker accounts warm --last-months 1 --output csv > warm.csv\",\n },\n args: WARM_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, [\"json\", \"csv\"]);\n const rule = warmRuleSchema.safeParse({\n ...ruleInput(args),\n min: optionalNumber(args.min),\n accounts: optionalString(args.accounts),\n });\n if (!rule.success) failInvalid(rule.error.issues);\n const targets = targetsInput(args);\n const input = engagementInput(args, targets, ACCOUNTS_ENGAGEMENT_MAX_LIMIT);\n const parsed = accountsEngagementRequestSchema.safeParse(\n input.start === undefined && input.lastMonths === undefined ? { ...input, lastMonths: 1 } : input,\n );\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsEngagementResponse>(\"/api/accounts/engagement\", parsed.data);\n const minimum = warmMinimum(response.data.rule, rule.data);\n const metric = warmMetric(response.data.rule, rule.data);\n const warming = warmAccounts(response.data.companies, new Date().toISOString().slice(0, 10), { minimum, metric });\n const warm = rule.data.accounts === \"targets\" ? warming.filter((row) => row.isTarget === true) : warming;\n const hints = withTargetsHints(\n [\n ...setupHint(response.data.setupIssues),\n ...(rule.data.accounts === \"targets\" ? targetAccountsHint(response.data.companies) : []),\n ...warmHints(response.data, warm, minimum),\n ],\n targets,\n response.data.targets,\n );\n if (format === \"csv\") {\n process.stdout.write(warmAccountsCsv(warm));\n for (const hint of hints) process.stderr.write(`${hint}\\n`);\n return;\n }\n writeJson({\n ok: true,\n data: {\n window: response.data.window,\n previousWindow: response.data.previousWindow,\n minimum: minimum ?? null,\n ...targetsBlock(response.data.targets),\n companies: withDealStatus(warm),\n },\n meta: { count: warm.length },\n ...(hints.length > 0 ? { hints } : {}),\n });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n/** `--accounts targets` on a read that marks no company a target: no list to narrow to, said rather than an empty answer. */\nfunction targetAccountsHint(companies: readonly AccountEngagementRow[]): string[] {\n return companies.length > 0 && !companies.some((row) => row.isTarget === true)\n ? [\n \"No company in this read is a target account: no target-accounts Knowledge is published, or none of its accounts was reached in the period. Publish the target accounts, or pass the list with --targets <file>.\",\n ]\n : [];\n}\n\n// --- company ---\n\nconst COMPANY_ARGS = {\n company: {\n type: \"positional\",\n description: \"LinkedIn company id (1035), its urn:li:organization URN, or a website domain (acme.com)\",\n required: true,\n },\n} as const;\n\nregisterSchema({\n command: \"accounts.company\",\n description:\n \"One company's story: its month-by-month totals (`months`), the same numbers split by LinkedIn campaign (`byCampaign` — overlapping, never add it to the totals), the CRM company it matched and how surely, and that company's deals, each with `touchValue` and `influenced` under the company's rule. Use it to show why a deal counts as influenced.\",\n args: COMPANY_ARGS,\n});\n\n/** A bare number or an organization URN is a LinkedIn id; anything else is a domain. */\nfunction companyRequest(raw: string): AccountsCompanyRequest {\n const value = raw.trim();\n return /^(urn:li:organization:)?\\d+$/.test(value) ? { orgId: value } : { domain: value };\n}\n\nconst companyCommand = defineCommand({\n meta: {\n name: \"company\",\n description: \"One company's monthly LinkedIn ad activity and its deals. Example: baker accounts company acme.com\",\n },\n args: COMPANY_ARGS,\n run: async ({ args }) => {\n const parsed = accountsCompanyRequestSchema.safeParse(companyRequest(String(args.company ?? \"\")));\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsCompanyResponse>(\"/api/accounts/company\", parsed.data);\n const view = companyView(response.data);\n const hints = [...setupHint(response.data.setupIssues), ...view.hints];\n writeJson({ ok: true, data: view.data, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\n// --- campaigns ---\n\nconst CAMPAIGNS_ARGS = {\n basis: {\n type: \"string\",\n description: \"pipeline (default): deals created in the period and not won. revenue: deals closed won in the period\",\n required: false,\n default: \"pipeline\",\n },\n ...WINDOW_ARGS,\n ...RULE_ARGS,\n ...TARGETS_ARG,\n output: OUTPUT_ARG,\n} as const;\n\nconst CAMPAIGN_TABLE_FIELDS = [\n \"campaignId\",\n \"campaignName\",\n \"companiesReached\",\n \"companiesEngaged\",\n \"influencedDeals\",\n \"influencedValue\",\n];\n\nregisterSchema({\n command: \"accounts.campaigns\",\n description:\n \"Per LinkedIn campaign: companies reached and engaged in the period, and the influenced deals it touched in their lookback — pipeline (default: deals created and not won) or, with --basis revenue, deals closed won. Overlapping by design — a deal counts for every campaign that touched it, so the rows never sum to the total; read them as a comparison, not a split. Default the last 12 calendar months. --model/--threshold read it with another rule for this call only; --targets <file> counts the target accounts only.\",\n args: CAMPAIGNS_ARGS,\n});\n\nconst campaignsCommand = defineCommand({\n meta: {\n name: \"campaigns\",\n description:\n \"Companies reached and influenced pipeline or revenue per campaign. Example: baker accounts campaigns --basis revenue --last-months 6\",\n },\n args: CAMPAIGNS_ARGS,\n run: async ({ args }) => {\n const format = outputFormat(args, TABLE_OUTPUT_FORMATS);\n const targets = targetsInput(args);\n const input = {\n basis: optionalString(args.basis),\n ...windowInput(args),\n ...ruleInput(args),\n targets: targets?.targets,\n };\n const parsed = accountsCampaignsRequestSchema.safeParse(input);\n if (!parsed.success) failInvalid(parsed.error.issues);\n try {\n const response = await apiPost<AccountsCampaignsResponse>(\"/api/accounts/campaigns\", parsed.data);\n const hints = withTargetsHints(\n [\"Campaign rows overlap: a deal counts for every campaign that touched it. Never add them up.\"],\n targets,\n response.data.targets,\n );\n if (format !== \"json\") {\n const rows = response.data.campaigns.map((row) => ({\n ...row,\n influencedValue: moneyText(row.influencedValue),\n }));\n writeAdsOutput(rows, format, CAMPAIGN_TABLE_FIELDS, hints);\n return;\n }\n writeJson({\n ...response,\n data: { ...response.data, ...targetsBlock(response.data.targets) },\n meta: { count: response.data.campaigns.length },\n hints,\n });\n } catch (err) {\n failAccounts(err);\n }\n },\n});\n\nexport const accountsCommand = defineCommand({\n meta: {\n name: \"accounts\",\n description:\n \"Account insights: which companies the LinkedIn ads are warming, and which CRM deals they influenced. Start with `baker accounts influenced` or `baker accounts warm`.\",\n },\n subCommands: {\n influenced: influencedCommand,\n engagement: engagementCommand,\n warm: warmCommand,\n company: companyCommand,\n campaigns: campaignsCommand,\n alerts: () => import(\"./alerts.ts\").then((m) => m.alertsCommand),\n people: () => import(\"./people.ts\").then((m) => m.peopleCommand),\n crm: () => import(\"./crm.ts\").then((m) => m.crmCommand),\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAoB7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS;AAkClB,SAAS,eAAe,KAAkC;AACxD,SAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,MAAM,KAAK,OAAO,GAAG,IAAI;AACtE;AAEA,SAAS,eAAe,KAAkC;AACxD,SAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,MAAM,KAAK,IAAI,KAAK,IAAI;AACrE;AAEA,SAAS,gBAAgB,SAAwB;AAC/C,YAAU,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,gBAAgB,QAAQ,EAAE,CAAC;AACjE,UAAQ,KAAK,CAAC;AAChB;AAGA,SAAS,YAAY,QAAwE;AAC3F,kBAAgB,mBAAmB,MAAM,CAAC;AAC5C;AAGA,SAAS,aAAa,MAA+B,WAAsC;AACzF,QAAM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,QAC9F;AAAA,QACA,SAAS,KAAK;AAAA,MAChB;AACA,UAAI,WAAW,QAAQ;AACrB,cAAM,OAAO,SAAS,KAAK,UAAU,IAAI,CAAC,SAAS;AAAA,UACjD,GAAG;AAAA,UACH,iBAAiB,UAAU,IAAI,eAAe;AAAA,QAChD,EAAE;AACF,uBAAe,MAAM,QAAQ,uBAAuB,KAAK;AACzD;AAAA,MACF;AACA,gBAAU;AAAA,QACR,GAAG;AAAA,QACH,MAAM,EAAE,GAAG,SAAS,MAAM,GAAG,aAAa,SAAS,KAAK,OAAO,EAAE;AAAA,QACjE,MAAM,EAAE,OAAO,SAAS,KAAK,UAAU,OAAO;AAAA,QAC9C;AAAA,MACF,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,mBAAa,GAAG;AAAA,IAClB;AAAA,EACF;AACF,CAAC;AAEM,IAAM,kBAAkB,cAAc;AAAA,EAC3C,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aACE;AAAA,EACJ;AAAA,EACA,aAAa;AAAA,IACX,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,WAAW;AAAA,IACX,QAAQ,MAAM,OAAO,sBAAa,EAAE,KAAK,CAAC,MAAM,EAAE,aAAa;AAAA,IAC/D,QAAQ,MAAM,OAAO,sBAAa,EAAE,KAAK,CAAC,MAAM,EAAE,aAAa;AAAA,IAC/D,KAAK,MAAM,OAAO,mBAAU,EAAE,KAAK,CAAC,MAAM,EAAE,UAAU;AAAA,EACxD;AACF,CAAC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/accounts/report.ts"],"sourcesContent":["/**\n * The pure half of `baker accounts`: the warm-account list file, and what the\n * agent should take from a report that the rows alone don't say.\n */\n\nimport {\n ACCOUNTS_NO_SETTINGS_MESSAGE,\n type AccountCompanyMonth,\n type AccountDealRow,\n type AccountDealStatus,\n type AccountEngagementRow,\n type AccountsCompanyResponse,\n type AccountsEngagementResponse,\n type AccountsInfluencedResponse,\n type AccountsSetupIssue,\n accountDealStatus,\n type DealsComparison,\n type InfluenceMetric,\n type InfluenceModelKind,\n type InfluenceParams,\n type InfluenceRuleOverride,\n influenceMetricWords,\n influenceParams,\n type MoneyByCurrency,\n type WarmAccountsOptions,\n} from \"@baker/api/accounts\";\nimport type { EngagementComparison, TargetAccount, TargetsSummary } from \"@baker/api/accounts/targets\";\nimport { toCsvRow } from \"../ads/output.ts\";\n\nexport type AccountsRefusal = { code: \"ACCOUNTS_NOT_SET_UP\"; fix: { action: \"ask_user\"; explanation: string } };\n\n/**\n * The refusal the agent cannot clear, as the fix it acts on: not set up (only\n * the user can say which stages mean won). Matched on the backend's own\n * sentence (shared from `@baker/api/accounts`), because it is a CONFLICT.\n * Null for every other refusal.\n */\nexport function accountsRefusal(code: string, message: string): AccountsRefusal | null {\n if (code === \"CONFLICT\" && message.includes(ACCOUNTS_NO_SETTINGS_MESSAGE)) {\n return {\n code: \"ACCOUNTS_NOT_SET_UP\",\n fix: {\n action: \"ask_user\",\n explanation:\n \"The user sets up where the deals are in Measure → Accounts first: HubSpot (then its pipelines and won/lost stages), or Another CRM, whose deals they send by spreadsheet or from their system (`baker accounts crm status`). Only the user can say which stages mean won and lost; do not guess them. Until then `baker accounts engagement` and `baker accounts warm` still work — they need no deals.\",\n },\n };\n }\n return null;\n}\n\n/** Request fields as the flags that set them. */\nconst FLAG_OF_FIELD: Record<string, string> = {\n lastMonths: \"--last-months\",\n start: \"--start\",\n end: \"--end\",\n campaignId: \"--campaign-id\",\n limit: \"--limit\",\n basis: \"--basis\",\n model: \"--model\",\n threshold: \"--threshold\",\n orgId: \"company\",\n domain: \"company\",\n targets: \"--targets\",\n since: \"--since\",\n accounts: \"--accounts\",\n};\n\n/** A refused request in the agent's own words: which flag, and why. */\nexport function invalidArgsMessage(issues: ReadonlyArray<{ path: PropertyKey[]; message: string }>): string {\n return issues\n .map((issue) => {\n const field = issue.path.map(String).join(\".\");\n return `${FLAG_OF_FIELD[field] ?? (field || \"args\")}: ${issue.message}`;\n })\n .join(\"; \");\n}\n\nfunction money(value: MoneyByCurrency): string {\n const parts = Object.entries(value).map(\n ([currency, amount]) => `${Math.round(amount).toLocaleString(\"en\")} ${currency}`,\n );\n return parts.length > 0 ? parts.join(\" + \") : \"no amount\";\n}\n\n/** Each setup problem as the fix an admin makes in Measure → Accounts or Integrations. */\nconst SETUP_FIX: Record<AccountsSetupIssue, string> = {\n pipelines_not_chosen: \"choose the HubSpot pipelines (customers and open deals are not left out yet)\",\n deals_not_received:\n \"send the deals from the company's CRM (none has arrived, so warm-account alerts are paused and no deal counts as influenced)\",\n sync_failing: \"reconnect the platform the last nightly sync failed on\",\n source_disconnected: \"reconnect LinkedIn Ads or HubSpot in Integrations\",\n stale: \"check why the numbers have not updated for two days\",\n};\n\n/**\n * One hint when Account insights is not set up soundly: the admins already\n * got an email, so the agent says it once to the user and hedges the numbers.\n */\nexport function setupHint(issues: readonly AccountsSetupIssue[] | undefined): string[] {\n if (!issues || issues.length === 0) return [];\n const fixes = issues.map((issue) => SETUP_FIX[issue]).join(\"; \");\n return [\n `Account insights setup needs an admin: ${fixes}. Until then warm and influenced are less accurate — say so once when you report them, and never try to fix the setup yourself.`,\n ];\n}\n\n/** What the agent should take from an influenced report that the rows alone don't say. */\nexport function influencedHints(data: AccountsInfluencedResponse[\"data\"]): string[] {\n const hints: string[] = [];\n const { summary } = data;\n if (summary.lowConfidenceDeals > 0) {\n const deals = summary.lowConfidenceDeals === 1 ? \"deal\" : \"deals\";\n const look = summary.lowConfidenceDeals === 1 ? \"looks\" : \"look\";\n hints.push(\n `${summary.lowConfidenceDeals} more ${deals} (${money(summary.lowConfidenceValue)}) ${look} influenced through a company match that is only a guess (a subdomain or a name). They are not counted in the numbers until someone confirms the match in Measure → Accounts; they are listed under lowConfidence.`,\n );\n }\n const valued = Object.keys(summary.influencedValue).length > 0;\n const spent = Object.values(summary.spend).some((amount) => amount > 0);\n if (summary.valuePerSpend === null && valued && spent) {\n hints.push(\n `valuePerSpend is null because the influenced value (${money(summary.influencedValue)}) and the LinkedIn spend (${money(summary.spend)}) are not in one single currency — amounts in different currencies are never converted or added. Report them side by side.`,\n );\n }\n return hints;\n}\n\n/**\n * The deals a table output prints: the counted ones, then the unconfirmed. With\n * `--full` the backend already lists the unconfirmed among `deals`, so they are\n * not added twice — a total taken from the table would count them double.\n */\nexport function influencedTableRows(data: AccountsInfluencedResponse[\"data\"], full: boolean): AccountDealRow[] {\n return full ? data.deals : [...data.deals, ...data.lowConfidence];\n}\n\n/** What the agent should take from an engagement read that the rows alone don't say. */\nexport function engagementHints(data: AccountsEngagementResponse[\"data\"], request: { limit: number }): string[] {\n if (data.companies.length === 0) {\n return [\n `No company the LinkedIn ads reached shows up for ${data.window.start} to ${data.window.end}. The nightly sync may not have run since the campaigns started delivering, or LinkedIn left the companies out (fewer than 3 events in a month). Try a longer period (--last-months 12), or read the ad account live with \\`baker ads linkedin companies\\`.`,\n ];\n }\n const page = data.pageInfo;\n if (page?.hasMore) {\n const first = (page.page - 1) * page.pageSize + 1;\n const last = first + data.companies.length - 1;\n return [\n `Companies ${first}-${last} of ${page.total.toLocaleString(\"en\")} shown. Read the next ones with --page ${page.page + 1} --limit ${page.pageSize}.`,\n ];\n }\n return data.truncated ? [`More companies were reached than --limit ${request.limit}; raise it to see the tail.`] : [];\n}\n\n/** The columns `baker accounts engagement --output csv|md` prints, in order. */\nexport const ENGAGEMENT_TABLE_FIELDS = [\n \"orgId\",\n \"name\",\n \"domain\",\n \"impressions\",\n \"clicks\",\n \"engagements\",\n \"videoViews\",\n \"estimatedSpend\",\n \"spendCurrency\",\n \"costLocal\",\n \"currency\",\n \"monthsActive\",\n \"lastMonth\",\n \"previousImpressions\",\n \"previousClicks\",\n \"previousEngagements\",\n \"previousVideoViews\",\n \"flag\",\n \"crmCompanyId\",\n \"matchConfidence\",\n \"dealStatus\",\n \"hasOpenDeal\",\n \"hasWonDeal\",\n \"hasLostDeal\",\n \"lastLostAt\",\n \"websitePeople\",\n \"websiteLeads\",\n \"websiteVisits\",\n \"websitePagesRead\",\n \"websiteLastVisit\",\n \"isTarget\",\n \"tier\",\n \"alertedAt\",\n];\n\n/** Engagement rows flat for a table: the estimated spend as two columns, the period before as four, the website people as two and the company's own-network visits as three, not JSON cells. */\nexport function engagementTableRows(rows: readonly AccountEngagementRow[]): Array<Record<string, unknown>> {\n return withDealStatus(rows).map(({ previous, website, visitorCompany, estimatedSpend, ...row }) => ({\n ...row,\n estimatedSpend: estimatedSpend?.amount ?? 0,\n spendCurrency: estimatedSpend?.currency ?? \"\",\n previousImpressions: previous.impressions,\n previousClicks: previous.clicks,\n previousEngagements: previous.engagements,\n previousVideoViews: previous.videoViews ?? 0,\n websitePeople: website?.people ?? 0,\n websiteLeads: website?.leads ?? 0,\n websiteVisits: visitorCompany?.visits ?? 0,\n websitePagesRead: visitorCompany?.pages ?? 0,\n websiteLastVisit: visitorCompany?.lastSeen ?? null,\n }));\n}\n\nconst MODEL_OF_METRIC: Record<InfluenceMetric, InfluenceModelKind> = {\n engagements: \"engagement\",\n impressions: \"awareness\",\n clicks: \"intent\",\n attention: \"attention\",\n};\n\n/**\n * The least a warm company must have done this period: the company's\n * influence rule (the default one when the backend sent none), read for this\n * call with `--model`/`--threshold`, or `--min` on the rule's metric. `--min 0`\n * drops it, so one engagement after none reads as warm again.\n */\nexport function warmMinimum(\n rule: InfluenceParams | undefined,\n override: InfluenceRuleOverride & { min?: number },\n): WarmAccountsOptions[\"minimum\"] {\n const read = warmRule(rule, override);\n const value = override.min ?? read.threshold;\n return value > 0 ? { metric: read.metric, value } : undefined;\n}\n\n/** The metric New and Rising are read on for this call — kept when `--min 0` drops the minimum. */\nexport function warmMetric(\n rule: InfluenceParams | undefined,\n override: InfluenceRuleOverride & { min?: number },\n): InfluenceMetric {\n return warmRule(rule, override).metric;\n}\n\nfunction warmRule(rule: InfluenceParams | undefined, override: InfluenceRuleOverride): InfluenceParams {\n const saved = { model: { kind: rule ? MODEL_OF_METRIC[rule.metric] : \"engagement\", threshold: rule?.threshold } };\n return influenceParams(saved, { model: override.model, threshold: override.threshold });\n}\n\n/** What the agent should take from a warm list that the rows alone don't say. */\nexport function warmHints(\n read: Pick<AccountsEngagementResponse[\"data\"], \"companies\" | \"truncated\">,\n warm: readonly AccountEngagementRow[],\n minimum: WarmAccountsOptions[\"minimum\"],\n): string[] {\n const hints: string[] = [];\n if (read.truncated) {\n hints.push(\n `The ads reached more companies than one read returns (${read.companies.length.toLocaleString(\"en\")}, the most engaged first), so warm companies with little engagement may be missing. Read a shorter period with --last-months 1 to see them.`,\n );\n }\n if (warm.length === 0 && read.companies.length > 0 && minimum !== undefined) {\n hints.push(\n `No company both warmed up and reached ${minimum.value}+ ${influenceMetricWords(minimum.metric, minimum.value)} in the period. Try a longer period with --last-months, or a lower bar with --min (--min 0 drops it).`,\n );\n }\n if (warm.some((row) => row.name === \"\")) {\n hints.push(\"Some companies have no name yet — the nightly sync looks them up; the organizationUrn still matches.\");\n }\n if (warm.length > 0) {\n hints.push(\n 'To advertise to them: `baker accounts warm --output csv > warm.csv`, then `baker ads linkedin audiences create --name \"Warm accounts\" --type company-list --list-file warm.csv` (staged until publish).',\n );\n }\n return hints;\n}\n\n/** The header `baker ads linkedin audiences create --type company-list --list-file` reads. */\nconst WARM_CSV_COLUMNS = [\"companyName\", \"domain\", \"organizationUrn\"];\n\n/**\n * Warm accounts as a company-list file, one company a line. The list reader\n * splits on line breaks, so a name carrying one is flattened.\n */\nexport function warmAccountsCsv(rows: readonly AccountEngagementRow[]): string {\n const lines = [toCsvRow(WARM_CSV_COLUMNS)];\n for (const row of rows) {\n const name = row.name.replace(/\\s*[\\r\\n]+\\s*/g, \" \");\n lines.push(toCsvRow([name, row.domain, `urn:li:organization:${row.orgId}`]));\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`;\n\nfunction reachText(counts: { total: number; reached: number; engaged: number }): string {\n return `${counts.reached} of ${counts.total} reached, ${counts.engaged} engaged`;\n}\n\nexport type TargetsView = Omit<TargetsSummary, \"notReached\"> & { notReached?: TargetAccount[] };\n\n/**\n * The `targets` block as printed: the reach counts, and the targets never\n * reached only when asked for — on a list of thousands they are most of the\n * answer, and only a coverage read needs them.\n */\nexport function targetsView(summary: TargetsSummary, listNotReached: boolean): TargetsView {\n const { notReached: _notReached, ...counts } = summary;\n return listNotReached ? summary : counts;\n}\n\n/**\n * What a `--targets` read means beyond its rows: how far the ads got with the\n * list, the targets never reached (or where to list them, when `listed` is\n * false and the answer left them out), and the file entries that were skipped.\n * No summary back means a server that ignored the list.\n */\nexport function targetsHints(\n summary: TargetsSummary | undefined,\n unreadable: readonly string[],\n listed = true,\n): string[] {\n if (summary === undefined) {\n return [\n \"This Baker server does not narrow reports to target accounts yet: the rows cover every company the ads reached.\",\n ];\n }\n const tiers = Object.entries(summary.byTier ?? {})\n .sort(([a], [b]) => a.localeCompare(b, \"en\", { numeric: true }))\n .map(([tier, counts]) => `tier ${tier}: ${reachText(counts)}`);\n const hints = [\n `Target accounts: ${reachText(summary)}${tiers.length > 0 ? ` (${tiers.join(\"; \")})` : \"\"}. Rows and numbers cover the target accounts only.`,\n ];\n const missed = summary.notReached.length;\n if (missed > 0 && !listed) {\n hints.push(\n `${plural(missed, \"target account was\", \"target accounts were\")} never reached in the period. To list ${missed === 1 ? \"it\" : \"them\"}: \\`baker accounts engagement --targets <file> --full\\` (targets.notReached).`,\n );\n } else if (missed > 0) {\n hints.push(\n `${plural(missed, \"target account was\", \"target accounts were\")} never reached in the period (targets.notReached). Check ${missed === 1 ? \"its domain is the website on its LinkedIn page\" : \"their domains are the websites on their LinkedIn pages\"}, or advertise to ${missed === 1 ? \"it\" : \"them\"} with a company list.`,\n );\n }\n if (unreadable.length > 0) {\n const listed = unreadable.map((entry) => `\"${entry}\"`).join(\", \");\n hints.push(\n `Skipped ${plural(unreadable.length, \"entry\", \"entries\")} of the targets file that ${unreadable.length === 1 ? \"is\" : \"are\"} not a website: ${listed}.`,\n );\n }\n return hints;\n}\n\nconst percent = (part: number, whole: number) => `${whole > 0 ? Math.round((part / whole) * 100) : 0}%`;\nconst perCompany = (total: number, companies: number) =>\n companies > 0 ? String(Math.round((total / companies) * 10) / 10) : \"0\";\n\n/**\n * \"Did the ABM work\" in one line: the target accounts beside every other\n * company in the same read — engagement for the companies reached, influenced\n * deals for a deal read. Nothing without a `--targets` read.\n */\nexport function comparisonHints(comparison: EngagementComparison | DealsComparison | undefined): string[] {\n if (comparison === undefined) return [];\n if (\"companies\" in comparison.targets && \"companies\" in comparison.others) {\n const { targets, others } = comparison as EngagementComparison;\n return [\n `Targets vs everyone else: ${targets.engaged} of ${targets.companies} target accounts engaged (${percent(targets.engaged, targets.companies)}) against ${others.engaged} of ${others.companies} other companies (${percent(others.engaged, others.companies)}); ${perCompany(targets.engagements, targets.companies)} engagements per target, ${perCompany(others.engagements, others.companies)} per other company (\\`comparison\\`).`,\n ];\n }\n const { targets, others } = comparison as DealsComparison;\n return [\n `Targets vs everyone else: ${targets.influencedDeals} of ${targets.deals} target-account deals influenced (${money(targets.influencedValue)}) against ${others.influencedDeals} of ${others.deals} other deals (${money(others.influencedValue)}) (\\`comparison\\`).`,\n ];\n}\n\n/** Each company with where it stands in the CRM spelled out, so the agent never has to combine the flags. */\nexport function withDealStatus(\n rows: readonly AccountEngagementRow[],\n): Array<AccountEngagementRow & { dealStatus: AccountDealStatus }> {\n return rows.map((row) => ({ ...row, dealStatus: accountDealStatus(row) }));\n}\n\ntype CompanyData = AccountsCompanyResponse[\"data\"];\ntype MonthCounts = Pick<AccountCompanyMonth, \"month\" | \"impressions\" | \"clicks\" | \"engagements\">;\n\nexport interface CompanyView {\n orgs: CompanyData[\"orgs\"];\n /** The company's own totals, month by month: the account-wide rows. */\n months: Array<MonthCounts & { orgId: string }>;\n /** The same numbers split by campaign. Overlapping: never add them to `months` or to each other. */\n byCampaign: Array<{ orgId: string; campaignId: string; campaignName: string | null; months: MonthCounts[] }>;\n deals: CompanyData[\"deals\"];\n rule?: CompanyData[\"rule\"];\n}\n\nconst counts = (row: AccountCompanyMonth): MonthCounts => ({\n month: row.month,\n impressions: row.impressions,\n clicks: row.clicks,\n engagements: row.engagements,\n});\n\n/**\n * One company as the agent should read it. The store answers the account-wide\n * row and every campaign's row for the same month side by side, which reads\n * as double the activity; here the account-wide months are the totals and\n * the campaign split sits apart, labelled. A company the ads never reached\n * comes back from the store as an unnamed echo of the id asked for — dropped,\n * and said in words.\n */\n/** Why a company lookup shows no LinkedIn company: an id the ads never reached, a CRM-only company, or no match at all. */\nfunction unreachedHint(unreached: ReadonlyArray<{ orgId: string }>, deals: number): string {\n if (unreached.length > 0) {\n return `The LinkedIn ads have not reached LinkedIn company ${unreached.map((org) => org.orgId).join(\", \")} in the months the nightly sync keeps (up to 24), so there is nothing to show. Check the id against \\`baker accounts engagement\\`, or try the company's website domain.`;\n }\n if (deals > 0) {\n return `That company is in the CRM with ${deals === 1 ? \"1 deal\" : `${deals} deals`}, but the LinkedIn ads have not reached it in the months the nightly sync keeps, so none of its deals can count as influenced.`;\n }\n return \"The ads have not reached that company, or it is named differently: try its LinkedIn id from `baker accounts engagement`.\";\n}\n\nexport function companyView(data: CompanyData): { data: CompanyView; hints: string[] } {\n const reachedOrgs = new Set(data.months.map((row) => row.orgId));\n const orgs = data.orgs.filter((org) => reachedOrgs.has(org.orgId) || org.name !== \"\" || org.crmCompanyId !== null);\n const months = data.months\n .filter((row) => row.campaignId === \"\")\n .map((row) => ({ orgId: row.orgId, ...counts(row) }));\n const byCampaign: CompanyView[\"byCampaign\"] = [];\n for (const row of data.months) {\n if (row.campaignId === \"\") continue;\n let entry = byCampaign.find((item) => item.orgId === row.orgId && item.campaignId === row.campaignId);\n if (entry === undefined) {\n entry = { orgId: row.orgId, campaignId: row.campaignId, campaignName: row.campaignName, months: [] };\n byCampaign.push(entry);\n }\n entry.months.push(counts(row));\n }\n\n const hints: string[] = [];\n const unreached = unreachedHint(\n data.orgs.filter((org) => !orgs.includes(org)),\n data.deals.length,\n );\n if (orgs.length === 0) hints.push(unreached);\n if (byCampaign.length > 0) {\n hints.push(\n \"`months` are the company's totals. `byCampaign` splits the same numbers by campaign, and a company several campaigns reached shows up under each — never add byCampaign to the totals or to each other.\",\n );\n }\n if (orgs.some((org) => org.matchConfidence === \"low\")) {\n hints.push(\n \"The CRM match is only a guess (a subdomain or a name) until someone confirms it in Measure → Accounts.\",\n );\n }\n if (data.rule !== undefined && data.deals.length > 0) {\n hints.push(\n `\\`influenced\\` on each deal: ${data.rule.threshold}+ ${influenceMetricWords(data.rule.metric, data.rule.threshold)} (\\`touchValue\\`) in the ${data.rule.lookbackMonths} months up to the month the deal was created (closed, for a won deal), counted from this company's months above.`,\n );\n }\n return { data: { orgs, months, byCampaign, deals: data.deals, ...(data.rule ? { rule: data.rule } : {}) }, hints };\n}\n"],"mappings":";;;;;;;;;;;AAqCO,SAAS,gBAAgB,MAAc,SAAyC;AACrF,MAAI,SAAS,cAAc,QAAQ,SAAS,4BAA4B,GAAG;AACzE,WAAO;AAAA,MACL,MAAM;AAAA,MACN,KAAK;AAAA,QACH,QAAQ;AAAA,QACR,aACE;AAAA,MACJ;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAGA,IAAM,gBAAwC;AAAA,EAC5C,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,KAAK;AAAA,EACL,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,WAAW;AAAA,EACX,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,OAAO;AAAA,EACP,UAAU;AACZ;AAGO,SAAS,mBAAmB,QAAyE;AAC1G,SAAO,OACJ,IAAI,CAAC,UAAU;AACd,UAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,EAAE,KAAK,GAAG;AAC7C,WAAO,GAAG,cAAc,KAAK,MAAM,SAAS,OAAO,K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,EAAG,GAAG,MAAM;AACnH;","names":["counts","listed","targets","others"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/hubspot/index.ts"],"sourcesContent":["import type {\n HubspotContactFieldsListResponse,\n HubspotContactLookupResponse,\n HubspotContactPropertiesListResponse,\n HubspotContactsSummaryResponse,\n HubspotFormSubmissionsResponse,\n HubspotFormsListResponse,\n HubspotFormsViewResponse,\n HubspotMeetingsListResponse,\n HubspotMeetingsViewResponse,\n HubspotPipelinesListResponse,\n HubspotWorkflowsListResponse,\n HubspotWorkflowsViewResponse,\n} from \"@baker/api\";\nimport { HUBSPOT_OPERATORS } from \"@baker/api/event-sources\";\nimport { defineCommand } from \"citty\";\nimport { ApiError, apiPost } from \"../../client.ts\";\nimport { rowsAsData, writeJson } from \"../../output.ts\";\nimport { registerSchema } from \"../../schemas.ts\";\nimport { failNotConnected } from \"./refusal.ts\";\n\nconst EMBED_TYPES = [\"legacy\", \"v4\", \"unknown\"] as const;\n\nfunction assertEmbedType(value: string | undefined): (typeof EMBED_TYPES)[number] | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!(EMBED_TYPES as readonly string[]).includes(value)) {\n throw new Error(`--embed-type must be one of: ${EMBED_TYPES.join(\"|\")}`);\n }\n return value as (typeof EMBED_TYPES)[number];\n}\n\nregisterSchema({\n command: \"hubspot.forms.list\",\n routes: [\"POST /api/hubspot/forms/list\"],\n effect: \"read_live\",\n description:\n \"Start here for HubSpot forms: every form on the connected account, with just enough to choose one — embed type (legacy vs v4), field count, its post-submit action (inline thank-you vs redirect to a URL), and whether spam prevention (captcha) is on. A form with captcha on can be embedded on a page but can never receive a submission from a Form, so check it before wiring one as a destination. Answers 'which of my forms redirect after submit?' and 'is this form legacy or v4?'. portalId is returned once on meta, not per row. Next step is usually `hubspot forms view <id> --as-node`, which gives you the blob to write straight into a Form step — you do not need request_flow_input for HubSpot.\",\n args: {\n search: { type: \"string\", description: \"Case-insensitive substring match on the form name\", required: false },\n \"redirecting-only\": {\n type: \"boolean\",\n description: \"Only forms whose post-submit action redirects away\",\n required: false,\n default: false,\n },\n \"embed-type\": { type: \"string\", description: \"Filter: legacy|v4|unknown\", required: false, enum: [...EMBED_TYPES] },\n },\n});\n\nregisterSchema({\n command: \"hubspot.forms.view\",\n description:\n \"One HubSpot form in detail: every field (name, label, type, required, hidden, options), the legal-consent mode, the post-submit action, captcha, and language. Read it before wiring a form into a Form (flow) so you know what fields exist to autofill. Add --full for the untouched HubSpot payload, or --as-node to get the object to write into the step's form.external instead.\",\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id (from `baker hubspot forms list`)\", required: true },\n full: { type: \"boolean\", description: \"Include the raw HubSpot payload\", required: false, default: false },\n \"as-node\": {\n type: \"boolean\",\n description:\n \"Emit the resource blob to write into a flow node's form.external, instead of the readable view. Write it into the node yourself; no need for request_flow_input when the account is connected and the form is unambiguous.\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.forms.submissions\",\n routes: [\"POST /api/hubspot/forms/submissions\"],\n effect: \"read_live\",\n description:\n \"How many leads a form actually received over a window, and on which days — the difference between 'this form is live' and 'this form is working'. Start here when asked whether a form or a campaign is producing leads. Returns counts and dates only; the leads' own answers need --full and are personal data, so do not put them in a report. Pair with `hubspot pipelines list` to see whether those leads were then worked.\",\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id (from `baker hubspot forms list`)\", required: true },\n days: { type: \"string\", description: \"Window in days, 1-365 (default 30)\", required: false },\n full: {\n type: \"boolean\",\n description: \"Include each submission's field values — personal data, request only when actually needed\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.contacts.summary\",\n routes: [\"POST /api/hubspot/contacts/summary\"],\n effect: \"read_live\",\n description:\n \"Whether the leads that arrived recently are actually being worked, as counts: how many contacts were created in the window, how many have someone assigned, and how they split across lifecycle stages. This is the 'have these leads been treated?' answer. Returns no names or emails — use `hubspot contacts lookup` for one specific person.\",\n args: {\n days: { type: \"string\", description: \"Window in days, 1-365 (default 30)\", required: false },\n },\n});\n\nregisterSchema({\n command: \"hubspot.contacts.properties\",\n description:\n \"Every contact property a HubSpot event can watch, with its `kind` (select, string, number, date, boolean) — which decides the operators the trigger takes — and, for a select, the `options` its values come from. Start here to make a HubSpot event: pick the property and condition that mean the outcome (a deal won is usually `lifecyclestage` is `customer`, a custom property the client's team sets, or a number crossing a threshold), then `baker analytics sources --create-hubspot --property <name> [--operator <op>] --value <value>…` reads it every five minutes. Names are HubSpot's internal ones; use them as printed.\",\n args: {},\n});\n\nregisterSchema({\n command: \"hubspot.contacts.fields\",\n description:\n \"Every contact property on the connected HubSpot account — name, label, group and HubSpot's type — which is what a HubSpot event's rows can read: `baker analytics sources --create-hubspot … --field email={{work_email}} --field value={{deal_value}} --field currency=EUR`, or `--map` on an existing one. Names are HubSpot's internal ones; use them as printed, and `{{id}}` for the contact's own id. No personal data.\",\n args: {},\n});\n\nregisterSchema({\n command: \"hubspot.contacts.lookup\",\n routes: [\"POST /api/hubspot/contacts/lookup\"],\n effect: \"read_live\",\n description:\n \"One contact by email: lifecycle stage, whether anyone is assigned, its account (company) and deals with their stage — settles whether a lead was picked up. `--properties utm_campaign,utm_source` also reads those into `contact.properties`, to check a form's tracking reached it: each value, or null when empty; a name the account does not define is left out, never null. `found: false` means the lead never reached the CRM at all — that is a finding, not an error. `dealsReadable: false` / `companyReadable: false` mean deals or account details were not readable on this connection, so an empty deals list or a null company is unknown rather than absent.\",\n args: {\n email: { type: \"positional\", description: \"The contact's email address\", required: true },\n properties: {\n type: \"string\",\n description:\n \"Comma-separated contact properties to read, by HubSpot's internal name (up to 25; `baker hubspot contacts fields` lists them): --properties utm_campaign,utm_source\",\n required: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.workflows.list\",\n description:\n \"Every workflow on the connected account, with whether it is switched on. Read it when auditing what happens to a lead after it is captured — a form wired to a workflow that is off looks connected and does nothing.\",\n args: {\n search: { type: \"string\", description: \"Case-insensitive substring match on the workflow name\", required: false },\n \"enabled-only\": { type: \"boolean\", description: \"Only workflows that are on\", required: false, default: false },\n },\n});\n\nregisterSchema({\n command: \"hubspot.workflows.view\",\n description:\n \"One workflow's actual configuration: what enrols a record, whether it re-enrols, and every step with the property it writes. Read it before saying a workflow is correct — `workflows list` only tells you it exists and whether it is on. Branches come back in HubSpot's order, and on a LIST_BRANCH step that is evaluation order (`order: 1` wins over `order: 2`) — which is where this kind of setup silently breaks: a broad branch placed above a narrow one swallows the records the narrow one was written for, and nothing reports it. A STATIC_BRANCH matches on a value instead, so its order carries no precedence. Steps are NOT in execution order — follow `nextActionId` from step to step. Add --full for the branch filter criteria (which property is compared to which value).\",\n args: {\n workflowId: {\n type: \"positional\",\n description: \"Workflow id (from `baker hubspot workflows list`)\",\n required: true,\n },\n full: {\n type: \"boolean\",\n description: \"Include the raw HubSpot payload — the only place the branch filter criteria can be read\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.pipelines.list\",\n description:\n \"The account's deal pipelines and their stages, in the order they run, each stage with `isClosed` / `isWon` (HubSpot's closed-won is closed with probability 1). Use it to answer where a lead lands once captured and whether it moved — the 'have these leads been worked?' half of a form audit — and to pick the pipeline ids for `hubspot deals list --pipeline`.\",\n args: {},\n});\n\nregisterSchema({\n command: \"hubspot.meetings.list\",\n description:\n \"Every HubSpot meeting link (calendar) on the connected account, with just enough to choose one: name, slug, link type (personal / group / round-robin), whether booking redirects somewhere, and how many booking fields it asks for (null = unknown, read it with `meetings view`). Next step is usually `hubspot meetings view <slug> --as-node`, which gives you the blob to write straight into a hubspotMeeting step.\",\n args: {\n search: { type: \"string\", description: \"Case-insensitive substring match on the meeting name\", required: false },\n \"redirecting-only\": {\n type: \"boolean\",\n description: \"Only meeting links that redirect after booking\",\n required: false,\n default: false,\n },\n },\n});\n\nregisterSchema({\n command: \"hubspot.meetings.view\",\n description:\n \"One HubSpot meeting link in detail: its booking-form fields (name, label, type, required, custom), link, and redirect URL. This is the source of truth for a calendar's fields — the list command cannot see them reliably. Add --as-node to get the object to write into the step's form.external instead.\",\n args: {\n slug: { type: \"positional\", description: \"Meeting slug (from `baker hubspot meetings list`)\", required: true },\n \"as-node\": {\n type: \"boolean\",\n description: \"Emit the resource blob to write into a flow node's form.external, instead of the readable view.\",\n required: false,\n default: false,\n },\n },\n});\n\nconst formsListCommand = defineCommand({\n meta: {\n name: \"list\",\n description:\n \"List HubSpot forms with embed type and post-submit action. Example: baker hubspot forms list --redirecting-only\",\n },\n args: {\n search: { type: \"string\", description: \"Match on form name\", required: false },\n \"redirecting-only\": { type: \"boolean\", description: \"Only forms that redirect on submit\", required: false },\n \"embed-type\": { type: \"string\", description: \"Filter: legacy|v4|unknown\", required: false },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args[\"redirecting-only\"]) {\n body.redirectingOnly = true;\n }\n const embedType = assertEmbedType(args[\"embed-type\"]);\n if (embedType) {\n body.embedType = embedType;\n }\n\n const response = await apiPost<HubspotFormsListResponse>(\"/api/hubspot/forms/list\", body, { read: true });\n const { forms } = response.data;\n const redirecting = forms.filter((form) => form.postSubmitAction?.type === \"redirect_url\");\n const hints: string[] = [];\n if (forms.length === 0) {\n hints.push(\"No forms matched. Drop --search/--embed-type, or check the connected HubSpot account.\");\n } else {\n hints.push(\n \"To put one on a page: `baker hubspot forms view <id> --as-node` returns the object to write into the step's form.external. No request_flow_input needed for HubSpot.\",\n );\n }\n if (redirecting.length > 0) {\n hints.push(\n `${redirecting.length} form(s) redirect after submit. That is fine mid-Form: the renderer suppresses the redirect whenever a step follows the form, and honors it when the form is the last step.`,\n );\n }\n const blocked = forms.filter((form) => form.captchaEnabled);\n if (blocked.length > 0) {\n // Named rather than counted, because the next thing the agent does with\n // this is tell a person which of their forms is the problem — but\n // bounded, since every row already carries `captchaEnabled` and an\n // account with forty blocked forms would otherwise print forty names.\n const shown = blocked.slice(0, 3).map((form) => form.name);\n const rest = blocked.length - shown.length;\n hints.push(\n `${blocked.length} form(s) have spam prevention (captcha) on: ${shown.join(\", \")}${rest > 0 ? `, and ${rest} more` : \"\"}. HubSpot refuses every submission sent to those, so they can be embedded on a page but never wired as a Form's destination. Only the user can switch it off, on the form in HubSpot.`,\n );\n }\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"forms\"), ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/**\n * The one HubSpot setting that decides whether a form can receive a lead at\n * all. HubSpot refuses every API submission to a form with spam prevention on\n * (`FORM_HAS_RECAPTCHA_ENABLED`) and there is no token to attach, so the answer\n * is never \"send it differently\" — it is a switch only the client can flip.\n */\nconst CAPTCHA_VIEW_HINT =\n \"This form has spam prevention (captcha) on. HubSpot refuses every submission sent to it, so it cannot be a Form's destination — embedding it on a page still works, because the visitor solves the captcha in the browser. Only the user can switch it off, on the form in HubSpot; do not wire a delivery to it, and tell them what has to change.\";\n\nconst CAPTCHA_NODE_HINT =\n \"This form has spam prevention (captcha) on. That is fine for embedding it on a page — the visitor solves it in the browser — but it can never be a Form's delivery destination, so do not also wire a hubspotForm side effect to this form.\";\n\n/**\n * What to say about one form beyond its fields.\n *\n * Pure and exported so the wording is testable: these are the three facts about\n * a HubSpot form that decide whether wiring it works, and each of them is\n * invisible in the form's own field list.\n */\nexport function formViewHints(form: {\n postSubmitAction: { type: string; value: string } | null;\n captchaEnabled: boolean;\n embedType: string;\n}): string[] {\n const hints: string[] = [];\n if (form.postSubmitAction?.type === \"redirect_url\") {\n hints.push(\n `This form redirects to ${form.postSubmitAction.value} on submit. Placed anywhere but the last step of a Form, that redirect is suppressed so the next step can render.`,\n );\n }\n if (form.captchaEnabled) {\n hints.push(CAPTCHA_VIEW_HINT);\n }\n if (form.embedType === \"unknown\") {\n hints.push(\"Embed type could not be determined from HubSpot's response; the renderer treats it as legacy.\");\n }\n return hints;\n}\n\n/**\n * The same for the `--as-node` blob, where the reader is about to *embed* the\n * form. Captcha reads the opposite way here and has to say so: an embedded form\n * with captcha works, because the visitor solves it in the browser. Silence\n * would leave an agent that just read the refusal elsewhere to conclude the\n * form is unusable and quietly pick another.\n */\nexport function formNodeHints(\n external:\n | {\n captchaEnabled: boolean;\n embedType?: string;\n region?: string;\n configuration?: { postSubmitAction: { type: string } };\n }\n | undefined,\n): string[] {\n return [\n \"Write this object into the node's `form.external` in the flow's _data.json, keeping the rest of the node as-is. No request_flow_input needed — the account is already connected.\",\n ...(external?.captchaEnabled ? [CAPTCHA_NODE_HINT] : []),\n ...(external?.configuration?.postSubmitAction.type === \"redirect_url\"\n ? [\n \"This form redirects on submit. Safe unless it is the last step: the renderer suppresses the redirect whenever a step follows it.\",\n ]\n : []),\n ...(external?.embedType === \"v4\" && !external.region\n ? [\n \"WARNING: this is a v4 form and the connected account has no region recorded, so the step will load HubSpot's na1 script host. That is correct for US portals and breaks the form on eu1/ap1 ones. If it renders blank, have the user reconnect HubSpot from Brain -> Integrations -> Tools, then re-run this command.\",\n ]\n : []),\n ];\n}\n\nconst formsViewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Show one HubSpot form's fields and configuration. Example: baker hubspot forms view 1a2b3c\",\n },\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id\", required: true },\n full: { type: \"boolean\", description: \"Include the raw HubSpot payload\", required: false },\n \"as-node\": { type: \"boolean\", description: \"Emit the node-ready form.external blob\", required: false },\n },\n run: async ({ args }) => {\n try {\n const response = await apiPost<HubspotFormsViewResponse>(\n \"/api/hubspot/forms/view\",\n {\n formId: args.formId,\n ...(args.full ? { full: true } : {}),\n ...(args[\"as-node\"] ? { asNode: true } : {}),\n },\n { read: true },\n );\n\n if (args[\"as-node\"]) {\n writeJson({ ...response, hints: formNodeHints(response.data.external) });\n return;\n }\n\n const form = response.data.form;\n if (!form) {\n throw new Error(\"Response did not include the form view\");\n }\n const hints = formViewHints(form);\n\n writeJson({ ...response, meta: { count: form.fields.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst meetingsListCommand = defineCommand({\n meta: {\n name: \"list\",\n description: \"List HubSpot meeting links (calendars). Example: baker hubspot meetings list\",\n },\n args: {\n search: { type: \"string\", description: \"Match on meeting name\", required: false },\n \"redirecting-only\": { type: \"boolean\", description: \"Only links that redirect after booking\", required: false },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args[\"redirecting-only\"]) {\n body.redirectingOnly = true;\n }\n\n const response = await apiPost<HubspotMeetingsListResponse>(\"/api/hubspot/meetings/list\", body, { read: true });\n const { meetings } = response.data;\n const hints: string[] = [];\n if (meetings.length === 0) {\n hints.push(\"No meeting links matched. Drop --search, or check the connected HubSpot account.\");\n } else {\n hints.push(\n \"To put one on a page: `baker hubspot meetings view <slug> --as-node` returns the object to write into the step's form.external.\",\n );\n }\n const unknown = meetings.filter((meeting) => !meeting.redirectKnown);\n if (unknown.length > 0) {\n hints.push(\n `HubSpot did not report booking settings for ${unknown.length} of these (${unknown\n .map((meeting) => meeting.slug)\n .join(\n \", \",\n )}), so their redirect and field count are UNKNOWN, not absent. Run \\`baker hubspot meetings view <slug>\\` before concluding one does not redirect.`,\n );\n }\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"meetings\"), ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst meetingsViewCommand = defineCommand({\n meta: {\n name: \"view\",\n description: \"Show one HubSpot meeting link's booking fields. Example: baker hubspot meetings view discovery-call\",\n },\n args: {\n slug: { type: \"positional\", description: \"Meeting slug\", required: true },\n \"as-node\": { type: \"boolean\", description: \"Emit the node-ready form.external blob\", required: false },\n },\n run: async ({ args }) => {\n try {\n const response = await apiPost<HubspotMeetingsViewResponse>(\n \"/api/hubspot/meetings/view\",\n {\n slug: args.slug,\n ...(args[\"as-node\"] ? { asNode: true } : {}),\n },\n { read: true },\n );\n\n if (args[\"as-node\"]) {\n const { external } = response.data;\n writeJson({\n ...response,\n hints: [\n \"Write this object into the node's `form.external` in the flow's _data.json, keeping the rest of the node as-is. No request_flow_input needed — the account is already connected.\",\n ...(external?.customParams.redirectUrl\n ? [\n `This calendar redirects to ${external.customParams.redirectUrl} after booking, and that redirect is NOT suppressed — any step placed after it is unreachable. Keep it as the last step, or ask the user to clear the redirect in HubSpot.`,\n ]\n : []),\n ],\n });\n return;\n }\n\n const meeting = response.data.meeting;\n if (!meeting) {\n throw new Error(\"Response did not include the meeting view\");\n }\n const hints: string[] = [];\n if (meeting.redirectUrl) {\n hints.push(\n `This calendar redirects to ${meeting.redirectUrl} after booking. A step placed after it will not be reached — keep it as the last step, or clear the redirect in HubSpot.`,\n );\n }\n\n writeJson({ ...response, meta: { count: meeting.fields.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst formsSubmissionsCommand = defineCommand({\n meta: {\n name: \"submissions\",\n description:\n \"How many leads a form received, and when. Example: baker hubspot forms submissions <formId> --days 30\",\n },\n args: {\n formId: { type: \"positional\", description: \"HubSpot form id\", required: true },\n days: { type: \"string\", description: \"Window in days (default 30)\", required: false },\n full: { type: \"boolean\", description: \"Include each lead's answers\", required: false },\n },\n run: async ({ args }) => {\n try {\n const days = args.days === undefined ? 30 : Number(args.days);\n if (!Number.isInteger(days) || days < 1 || days > 365) {\n throw new ApiError(\"VALIDATION_ERROR\", \"--days must be a whole number between 1 and 365.\");\n }\n\n const response = await apiPost<HubspotFormSubmissionsResponse>(\n \"/api/hubspot/forms/submissions\",\n {\n formId: args.formId,\n days,\n ...(args.full ? { full: true } : {}),\n },\n { read: true },\n );\n const { inWindow, total, truncated, lastSubmittedAt } = response.data;\n\n const hints: string[] = [];\n if (inWindow === 0) {\n hints.push(\n total === 0\n ? \"This form has received nothing at all — check it is the form actually embedded on the page before concluding the campaign is at fault.\"\n : `No leads in the last ${days} days, though the form has ${total} older submission(s). It worked once and has gone quiet.`,\n );\n }\n if (truncated) {\n hints.push(\n \"Stopped before reaching the end of the window, so `inWindow` is a floor, not a count. Say so rather than reporting it as exact.\",\n );\n }\n if (!args.full && inWindow > 0) {\n hints.push(\n \"Counts only — the leads' own answers are not included. Add --full if you genuinely need the field values; it returns personal data, so do not paste it into a report or a chat message.\",\n );\n }\n if (lastSubmittedAt !== null) {\n hints.push(\n \"To find out whether these leads were worked, cross-check the deal pipeline: `baker hubspot pipelines list`.\",\n );\n }\n\n writeJson({ ...response, meta: { count: inWindow }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst workflowsListCommand = defineCommand({\n meta: {\n name: \"list\",\n description: \"List HubSpot workflows. Example: baker hubspot workflows list --enabled-only\",\n },\n args: {\n search: { type: \"string\", description: \"Match on workflow name\", required: false },\n \"enabled-only\": { type: \"boolean\", description: \"Only workflows that are on\", required: false },\n },\n run: async ({ args }) => {\n try {\n const body: Record<string, unknown> = {};\n if (args.search) {\n body.search = args.search;\n }\n if (args[\"enabled-only\"]) {\n body.enabledOnly = true;\n }\n\n const response = await apiPost<HubspotWorkflowsListResponse>(\"/api/hubspot/workflows/list\", body, { read: true });\n const { workflows } = response.data;\n const off = workflows.filter((workflow) => !workflow.enabled);\n const hints: string[] = [];\n if (workflows.length === 0) {\n hints.push(\"No workflows matched. Drop --search/--enabled-only, or the account genuinely has none.\");\n }\n if (off.length > 0) {\n hints.push(\n `${off.length} of these are switched off. A form wired to a workflow that is off looks connected and does nothing — worth flagging to the user.`,\n );\n }\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"workflows\"), ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/**\n * What the agent should take from one workflow read.\n *\n * All three of these are silent failures in HubSpot — the workflow saves, looks\n * right in the editor, and runs. Nothing surfaces them but reading the order and\n * the flags, so they are stated rather than left for the agent to notice.\n */\nexport function workflowViewHints(workflow: HubspotWorkflowsViewResponse[\"data\"][\"workflow\"]): string[] {\n const hints: string[] = [];\n if (!workflow.enabled) {\n hints.push(\n \"This workflow is switched off, so nothing below it is running now — it may still have run while it was on. Say so before reporting on what it does.\",\n );\n }\n\n // Only a LIST_BRANCH is evaluated top down. A STATIC_BRANCH splits on a value\n // and matches by equality, so \"a broad branch above a narrow one\" cannot\n // happen there — and both arrive here as `branches`, so the kind has to be\n // read off the step rather than off the list.\n const ordered = workflow.steps.filter((step) => step.type === \"LIST_BRANCH\" && (step.branches?.length ?? 0) > 1);\n if (ordered.length > 0) {\n hints.push(\n \"Branches are listed in evaluation order and the first match wins. Check that no broad branch sits above a narrower one — if it does, the narrow branch never runs and nothing in HubSpot reports it.\",\n );\n }\n if (workflow.raw === undefined && ordered.length > 0) {\n hints.push(\n \"This view names the branches but not what they compare. Re-run with --full to read the filter criteria before judging whether a branch matches what it was meant to match.\",\n );\n }\n\n if (workflow.enrollment.reEnrollment === false) {\n hints.push(\n \"Re-enrolment is off: a record that meets the criteria a second time will not run through this again. That is a real choice, not necessarily a fault — but confirm it is the intended one.\",\n );\n } else if (workflow.enrollment.reEnrollment === null) {\n hints.push(\n \"Whether this re-enrols is not reported for this kind of enrolment, so do not state it either way — read it in HubSpot if it matters.\",\n );\n }\n return hints;\n}\n\nconst workflowsViewCommand = defineCommand({\n meta: {\n name: \"view\",\n description:\n \"Read one workflow's real configuration — enrolment, branches in order, and what each step writes. Example: baker hubspot workflows view 121183594 --full\",\n },\n args: {\n workflowId: {\n type: \"positional\",\n description: \"Workflow id (from `baker hubspot workflows list`)\",\n required: true,\n },\n full: { type: \"boolean\", description: \"Include the raw HubSpot payload with the filter criteria\", required: false },\n },\n run: async ({ args }) => {\n try {\n const response = await apiPost<HubspotWorkflowsViewResponse>(\n \"/api/hubspot/workflows/view\",\n {\n workflowId: args.workflowId,\n ...(args.full ? { full: true } : {}),\n },\n { read: true },\n );\n const { workflow } = response.data;\n const hints = workflowViewHints(workflow);\n\n writeJson({ ...response, meta: { count: workflow.steps.length }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\nconst pipelinesListCommand = defineCommand({\n meta: {\n name: \"list\",\n description: \"List HubSpot deal pipelines and their stages. Example: baker hubspot pipelines list\",\n },\n args: {},\n run: async () => {\n try {\n const response = await apiPost<HubspotPipelinesListResponse>(\"/api/hubspot/pipelines/list\", {}, { read: true });\n const { pipelines } = response.data;\n const hints: string[] =\n pipelines.length === 0\n ? [\"This account has no deal pipelines, so there is nowhere for a lead to be worked.\"]\n : [\"Stages are listed in the order they run in HubSpot, so the first stage is where a new lead lands.\"];\n\n writeJson({ ok: true, ...rowsAsData(response.data, \"pipelines\"), hints });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\ntype HubspotObjectWord = \"contact\" | \"deal\" | \"lead\";\n\nconst OBJECT_WORDS: Record<HubspotObjectWord, { plural: string; command: string; rows: string }> = {\n contact: {\n plural: \"contacts\",\n command: \"baker hubspot contacts\",\n rows: '`--field email={{work_email}}`, `--field currency=EUR`, `--field first_name=\"{{firstname}} {{lastname}}\"`; `{{id}}` is the contact\\'s own id',\n },\n deal: {\n plural: \"deals\",\n command: \"baker hubspot deals\",\n rows: \"`--field value={{amount}}`, `--field currency={{deal_currency_code}}`, `--field email={{contact.email}}` — a deal's own properties bare, its contact's as `contact.<name>`; `{{id}}` is the deal's own id, `{{contact.id}}` the contact's\",\n },\n lead: {\n plural: \"leads\",\n command: \"baker hubspot leads\",\n rows: \"`--field email={{contact.email}}`, `--field properties.stage={{hs_pipeline_stage}}` — a lead's own properties bare, its contact's as `contact.<name>`; `{{id}}` is the lead's own id, `{{contact.id}}` the contact's. A lead carries no amount of its own, so `value` is empty unless you point it at a property\",\n },\n};\n\n/** `properties`, for contacts and for deals: what a HubSpot event can watch. */\nfunction propertiesCommand(object: HubspotObjectWord) {\n const words = OBJECT_WORDS[object];\n return defineCommand({\n meta: {\n name: \"properties\",\n description: `List every ${object} property a HubSpot event can watch, with its kind, the operators that kind takes, and a select's values. Example: ${words.command} properties`,\n },\n args: {},\n run: async () => {\n try {\n const response = await apiPost<HubspotContactPropertiesListResponse>(\n \"/api/hubspot/contacts/properties\",\n {\n object,\n },\n { read: true },\n );\n const { properties } = response.data;\n const operators = Object.entries(HUBSPOT_OPERATORS)\n .map(([kind, list]) => `${kind}: ${list.map((operator) => operator.value).join(\", \")}`)\n .join(\" · \");\n const objectFlag = object === \"contact\" ? \"\" : ` --object ${object}`;\n const hints =\n properties.length === 0\n ? [`This account has no visible ${object} property, so there is nothing an event could watch.`]\n : [\n `Pick the property and the condition that mean the outcome, then \\`baker analytics sources --create-hubspot${objectFlag} --property <name> [--operator <op>] --value <value>…\\` (\\`--value\\` repeats for a list). Operators by kind — ${operators}. Counting starts from creation: a ${object} already satisfying it is not counted until it leaves and comes back.`,\n ];\n writeJson({ ok: true, ...rowsAsData(response.data, \"properties\"), hints });\n } catch (err) {\n failNotConnected(err);\n }\n },\n });\n}\n\nconst contactsPropertiesCommand = propertiesCommand(\"contact\");\n\nconst contactsSummaryCommand = defineCommand({\n meta: {\n name: \"summary\",\n description: \"Whether recent leads are being worked, as counts. Example: baker hubspot contacts summary --days 30\",\n },\n args: {\n days: { type: \"string\", description: \"Window in days (default 30)\", required: false },\n },\n run: async ({ args }) => {\n try {\n const days = args.days === undefined ? 30 : Number(args.days);\n if (!Number.isInteger(days) || days < 1 || days > 365) {\n throw new ApiError(\"VALIDATION_ERROR\", \"--days must be a whole number between 1 and 365.\");\n }\n\n const response = await apiPost<HubspotContactsSummaryResponse>(\n \"/api/hubspot/contacts/summary\",\n { days },\n { read: true },\n );\n const { total, withOwner, withoutOwner, byStage, truncated } = response.data;\n\n const hints: string[] = [];\n if (total === 0) {\n hints.push(`No contacts were created in the last ${days} days — nothing reached the CRM in that window.`);\n } else if (withOwner === 0) {\n hints.push(\n `None of these ${total} contacts has anyone assigned. That is the strongest available signal that the leads are arriving and nobody is picking them up — worth raising with the user.`,\n );\n } else if (withoutOwner > withOwner) {\n hints.push(`${withoutOwner} of ${total} contacts have nobody assigned — more unworked than worked.`);\n }\n const unset = byStage.find((entry) => entry.stage === \"unset\");\n if (unset && unset.count > 0) {\n hints.push(\n `${unset.count} contact(s) have no lifecycle stage set at all, so they were created and never staged.`,\n );\n }\n if (truncated) {\n hints.push(\"Stopped before reading every contact in the window, so these counts are floors, not totals.\");\n }\n\n writeJson({ ...response, meta: { count: total }, ...(hints.length > 0 ? { hints } : {}) });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/**\n * What the agent should take from one contact lookup.\n *\n * An empty `deals` or a null `company` means two different things depending on\n * whether the connection could read them at all, and the wrong reading — \"this\n * lead was never worked\" — is the one conclusion the command exists to settle.\n * So each is paired with its readability flag rather than reported bare.\n */\nexport function contactLookupHints(\n data: HubspotContactLookupResponse[\"data\"],\n askedProperties: readonly string[] = [],\n): string[] {\n const { found, contact, deals, dealsReadable, company, companyReadable } = data;\n if (!found) {\n return [\n \"No contact with that email. The lead never reached the CRM — check the form's submissions before assuming the CRM lost it.\",\n ];\n }\n\n const hints: string[] = [];\n if (contact?.ownerId === null) {\n hints.push(\"Nobody is assigned to this contact.\");\n }\n const undefinedProperties = askedProperties.filter((name) => !Object.hasOwn(contact?.properties ?? {}, name));\n if (undefinedProperties.length > 0) {\n hints.push(\n `No contact property named ${undefinedProperties.join(\", \")} on this account, so there is nothing to read — this is not an empty value. \\`baker hubspot contacts fields\\` lists the names this account uses.`,\n );\n }\n if (!dealsReadable) {\n hints.push(\n \"Deals were not read: this HubSpot connection does not cover them. Do not report the lead as having no deal — you cannot tell. The user can enable it by reconnecting HubSpot.\",\n );\n } else if (deals.length === 0) {\n hints.push(\"No deal is associated, so this contact was never taken into the pipeline.\");\n }\n if (!companyReadable) {\n hints.push(\n \"Account details were not read: this HubSpot connection does not cover them. Do not report the lead as having no account — you cannot tell. The user can enable it by reconnecting HubSpot.\",\n );\n } else if (company === null) {\n hints.push(\n \"No account is associated either. Most B2B setups create one automatically when a contact arrives, so this usually means the lead was never processed at all — not that the account is missing.\",\n );\n }\n return hints;\n}\n\nfunction commaList(raw: string): string[] {\n return [\n ...new Set(\n raw\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ),\n ];\n}\n\nconst contactsLookupCommand = defineCommand({\n meta: {\n name: \"lookup\",\n description:\n \"Find one contact by email and see whether it was worked; --properties reads named contact properties too. Example: baker hubspot contacts lookup a@b.com --properties utm_campaign,utm_source\",\n },\n args: {\n email: { type: \"positional\", description: \"The contact's email address\", required: true },\n properties: {\n type: \"string\",\n description:\n \"Comma-separated contact properties to read, by HubSpot's internal name: --properties utm_campaign,utm_source\",\n required: false,\n },\n },\n run: async ({ args }) => {\n try {\n const properties = typeof args.properties === \"string\" ? commaList(args.properties) : [];\n const response = await apiPost<HubspotContactLookupResponse>(\n \"/api/hubspot/contacts/lookup\",\n {\n email: args.email,\n ...(properties.length > 0 ? { properties } : {}),\n },\n { read: true },\n );\n const hints = contactLookupHints(response.data, properties);\n\n writeJson({\n ...response,\n meta: { count: response.data.found ? 1 : 0 },\n ...(hints.length > 0 ? { hints } : {}),\n });\n } catch (err) {\n failNotConnected(err);\n }\n },\n});\n\n/** `fields`, for contacts and for deals: what a HubSpot event's rows can read. */\nfunction fieldsCommand(object: HubspotObjectWord) {\n const words = OBJECT_WORDS[object];\n return defineCommand({\n meta: {\n name: \"fields\",\n description: `List every property a HubSpot event on a ${object} can read into its rows, with HubSpot's type${object === \"contact\" ? \"\" : ` — the ${object}'s own, and its contact's as contact.<name>`}. Example: ${words.command} fields`,\n },\n args: {},\n run: async () => {\n try {\n const response = await apiPost<HubspotContactFieldsListResponse>(\n \"/api/hubspot/contacts/fields\",\n { object },\n { read: true },\n );\n writeJson({\n ok: true,\n ...rowsAsData(response.data, \"fields\"),\n hints: [\n `A row of a HubSpot event is a template over these names: ${words.rows}. \\`baker analytics sources --preview${object === \"contact\" ? \"\" : ` --object ${object}`} --property <p> --value <v> --field <row>…\\` reads one real ${object} to check the rows against.`,\n ],\n });\n } catch (err) {\n failNotConnected(err);\n }\n },\n });\n}\n\nconst contactsFieldsCommand = fieldsCommand(\"contact\");\n\nconst dealsCommand = defineCommand({\n meta: {\n name: \"deals\",\n description:\n \"Deals on the connected HubSpot account: the deals themselves with amount and stage (`list`), one deal found by its name (`lookup`), and what a HubSpot event on a deal can watch (`properties`) and read (`fields`).\",\n },\n subCommands: {\n list: () => import(\"./crm.ts\").then((m) => m.dealsListCommand),\n lookup: () => import(\"./crm.ts\").then((m) => m.dealsLookupCommand),\n properties: propertiesCommand(\"deal\"),\n fields: fieldsCommand(\"deal\"),\n },\n});\n\nconst leadsCommand = defineCommand({\n meta: {\n name: \"leads\",\n description:\n \"Leads on the connected HubSpot account: what a HubSpot event on a lead can watch (`properties`) and read (`fields`). Start here for qualification and disqualification — a lead's stage is where HubSpot records both, and `hs_pipeline_stage` lists the account's own stages with their labels. Needs Sales Hub Professional or Enterprise; on any other plan the account has no leads to read.\",\n },\n subCommands: { properties: propertiesCommand(\"lead\"), fields: fieldsCommand(\"lead\") },\n});\n\nconst contactsCommand = defineCommand({\n meta: { name: \"contacts\", description: \"Contacts on the connected HubSpot account.\" },\n subCommands: {\n summary: contactsSummaryCommand,\n lookup: contactsLookupCommand,\n properties: contactsPropertiesCommand,\n fields: contactsFieldsCommand,\n },\n});\n\nconst companiesCommand = defineCommand({\n meta: { name: \"companies\", description: \"Companies (accounts) in the connected HubSpot CRM.\" },\n subCommands: {\n search: () => import(\"./crm.ts\").then((m) => m.companiesSearchCommand),\n contacts: () => import(\"./crm.ts\").then((m) => m.companiesContactsCommand),\n },\n});\n\nconst formsCommand = defineCommand({\n meta: { name: \"forms\", description: \"HubSpot forms on the connected account.\" },\n subCommands: { list: formsListCommand, view: formsViewCommand, submissions: formsSubmissionsCommand },\n});\n\nconst workflowsCommand = defineCommand({\n meta: { name: \"workflows\", description: \"HubSpot workflows on the connected account.\" },\n subCommands: { list: workflowsListCommand, view: workflowsViewCommand },\n});\n\nconst pipelinesCommand = defineCommand({\n meta: { name: \"pipelines\", description: \"HubSpot deal pipelines on the connected account.\" },\n subCommands: { list: pipelinesListCommand },\n});\n\nconst meetingsCommand = defineCommand({\n meta: { name: \"meetings\", description: \"HubSpot meeting links (calendars) on the connected account.\" },\n subCommands: { list: meetingsListCommand, view: meetingsViewCommand },\n});\n\nexport const hubspotCommand = defineCommand({\n meta: {\n name: \"hubspot\",\n description: `Read the connected HubSpot account — forms, the leads they received, workflows, deal pipelines, CRM\ncompanies and deals, and meeting links (calendars) — and get the blob to wire a form into a Form step yourself.\n\nExamples:\n baker hubspot forms list # every form: embed type + post-submit action\n baker hubspot forms list --redirecting-only # which forms redirect away on submit\n baker hubspot forms view <formId> # fields, consent mode, full configuration\n baker hubspot forms view <formId> --as-node # the form.external blob -> write into the step\n baker hubspot forms submissions <formId> # how many leads it got, and when\n baker hubspot workflows list --enabled-only # what runs after a lead is captured\n baker hubspot workflows view <workflowId> # its real branches, in order, and what each step writes\n baker hubspot pipelines list # where a lead lands, and the stages after it\n baker hubspot contacts summary --days 30 # are recent leads being worked? (counts only)\n baker hubspot contacts lookup a@b.com # was this one lead picked up? --properties utm_campaign,… reads those too\n baker hubspot companies search --domains acme.com,globex.io --with-deals # which are accounts, with deals\n baker hubspot deals list --modified-since 2026-01-01 # deals: amount, stage, closed won\n baker hubspot deals lookup --search \"Acme\" # is this sale in the CRM? (by deal name)\n baker hubspot deals properties # what a HubSpot event on a deal can watch (dealstage, amount…)\n baker hubspot deals fields # what its rows can read: the deal's own, its contact's as contact.<name>\n baker hubspot meetings list # every calendar + whether booking redirects\n baker hubspot meetings view <slug> --as-node # same, for a hubspotMeeting step\n\nAn account connected before one of these existed cannot serve it — you get HUBSPOT_RECONNECT_REQUIRED, which\nmeans HubSpot IS connected and the user has to reconnect it to widen what Baker may read. Report that and\ncarry on with the rest; never call it broken and never retry.\n\nNothing here is secret, so HubSpot steps do not need request_flow_input: take --as-node and edit the\nflow's _data.json. Use the approval form only when no account is connected or the right form is unclear.\nFull guide: __tooling__/docs/tools/baker/hubspot.md`,\n },\n subCommands: {\n forms: formsCommand,\n workflows: workflowsCommand,\n pipelines: pipelinesCommand,\n contacts: contactsCommand,\n companies: companiesCommand,\n deals: dealsCommand,\n leads: leadsCommand,\n meetings: meetingsCommand,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,qBAAqB;AAM9B,IAAM,cAAc,CAAC,UAAU,MAAM,SAAS;AAE9C,SAAS,gBAAgB,OAAqE;AAC5F,MAAI,UAAU,QAAW;AACvB,WAAO;AAAA,EACT;AACA,MAAI,CAAE,YAAkC,SAAS,KAAK,GAAG;AACvD,UAAM,IAAI,MAAM,gCAAgC,YAAY,KAAK,GAAG,CAAC,EAAE;AAAA,EACzE;AACA,SAAO;AACT;AAEA,eAAe;AAAA,EACb,SAAS;AAAA,EACT,QAAQ,CAAC,8BAA8B;AAAA,EACvC,QAAQ;AAAA,EACR,aACE;AAAA,EACF,MAAM;AAAA,IACJ,QAAQ,EAAE,MAAM,UAAU,aAAa,qDAAqD,UAAU,MAAM;AAAA,IAC5G,oBAAoB;AAAA,MAClB,MAAM;AAAA,MACN,aAAa;AAAA,MACb,UAAU;AAAA,MACV,SAAS;AAAA,IACX;AAAA,IACA,cAAc,EAAE,MAAM,UAAU,aAAa,6BAA6B,UAAU,OAAO,MAAM,CAAC,GAAG,WAAW,EAAE;AAAA,EACpH;AACF,CAAC;AAED,eAAe;AAAA,EACb,SAAS;AAAA,EACT,aACE;AAAA,EACF,MAAM;AAAA,IACJ,QAAQ,EAAE,MAAM,cAAc,aAAa,qDAAqD,UAAU,KAAK;AAAA,IAC/G,MAAM,EAAE,MAAM,WAAW,aAAa,mCAAmC,UAAU,OAAO,SAAS,MAAM;AAAA,IACzG,WAAW;AAAA,MACT,MAAM;AAAA,MACN,aACE;AAAA,MACF,UAAU;AAAA,MACV,SAAS;AAAA,IACX;AAAA,EACF;A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