@sortlist/cli 0.60.0 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/sortlist-cli/SKILL.md +139 -561
- package/skills/sortlist-cli/references/atlas.md +197 -0
- package/skills/sortlist-cli/references/billing-and-permissions.md +253 -0
- package/skills/sortlist-cli/references/identity-and-accounts.md +118 -0
- package/skills/sortlist-cli/references/outreach.md +126 -0
- package/skills/sortlist-cli/references/signals.md +104 -0
- package/skills/sortlist-cli/scripts/quote-reveals.mjs +182 -0
- package/skills/sortlist-go-to-market/SKILL.md +73 -233
- package/skills/sortlist-go-to-market/references/agency-briefing.md +22 -0
- package/skills/sortlist-go-to-market/references/campaigns.md +114 -0
- package/skills/sortlist-go-to-market/references/context-and-brief.md +92 -0
- package/skills/sortlist-go-to-market/references/prospect-list.md +115 -0
- package/skills/sortlist-go-to-market/references/search-state.md +87 -0
- package/skills/sortlist-go-to-market/references/sourcing.md +194 -0
- package/skills/sortlist-go-to-market/scripts/render-prospect-list.mjs +157 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Outreach: accounts and individual actions
|
|
2
|
+
|
|
3
|
+
Read for account connection, profile lookups, LinkedIn actions, email, events and replies. Discover
|
|
4
|
+
the caller's actual operations and read help before constructing calls. Plain login requests
|
|
5
|
+
channel-account scopes but does not establish that every customer receives them.
|
|
6
|
+
|
|
7
|
+
Outreach performs one action at a time from an account held for the user. A multi-step campaign
|
|
8
|
+
requires a separately approved durable plan and a real continuation or scheduling mechanism. Do not
|
|
9
|
+
describe planned follow-ups as scheduled merely because the plan exists. Use the go-to-market skill
|
|
10
|
+
when a campaign is requested; a shortlist request does not authorize outreach.
|
|
11
|
+
|
|
12
|
+
## Accounts and connection
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
sl outreach outbound-channel-accounts --company <slug> \
|
|
16
|
+
--fields id,channel,provider,status,externalId
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Choose the intended sender and an account that is `RUNNING`. Verify the company that owns/pays for
|
|
20
|
+
the account, not just the caller's current selection: the creating call's company pays for later
|
|
21
|
+
LinkedIn actions on that account. Use per-call `--company` when creating one. Do not create another
|
|
22
|
+
account merely because an existing one is disconnected.
|
|
23
|
+
|
|
24
|
+
Some providers use an `authenticate-outbound-channel-account` hosted sign-in link that the owner
|
|
25
|
+
opens themselves. Check current help for the supported channel/provider; do not promise email
|
|
26
|
+
connection if it has no CLI flow.
|
|
27
|
+
|
|
28
|
+
For `LINKEDIN_DIRECT`, use the owner's desktop browser session only with their authorization and
|
|
29
|
+
while they are present to sign in:
|
|
30
|
+
|
|
31
|
+
1. Create the account with `sl outreach create-outbound-channel-account --company <slug>
|
|
32
|
+
--channel LINKEDIN --provider LINKEDIN_DIRECT --external-id <sender-reference>
|
|
33
|
+
--fields channelAccount.id,channelAccount.status`. A webhook is not needed for CLI event reads.
|
|
34
|
+
2. Run `sl outreach connect-linkedin <account-id> <country-code>` in a background process. The
|
|
35
|
+
country is the owner's country, such as `BE`. The command opens a fresh supported browser
|
|
36
|
+
profile, waits for login and verification, then sends the session to Outreach and deletes the
|
|
37
|
+
temporary profile. The documented default timeout is ten minutes; check `--help` for overrides.
|
|
38
|
+
3. When it prints that the window is open, tell the owner to sign in there. Wait for a verified
|
|
39
|
+
`RUNNING` result or report the refusal. Reconnect a disconnected account using the same ID.
|
|
40
|
+
|
|
41
|
+
Never read, print or request a cookie, password or verification code yourself; the command owns
|
|
42
|
+
session transfer. It requires a desktop on the owner's machine. SSH/headless environments and
|
|
43
|
+
unsupported sandboxed browsers may not work. Use only documented browser selection configuration
|
|
44
|
+
when needed, such as `CHROME_PATH`, and respect any host restrictions on UI or keyboard interaction.
|
|
45
|
+
The direct provider checks inbox events periodically; do not promise immediate replies or a fixed
|
|
46
|
+
latency beyond the current provider's contract.
|
|
47
|
+
|
|
48
|
+
## Authorize and construct actions
|
|
49
|
+
|
|
50
|
+
Prepare recipients, sender, channel, text, purpose and costs before missing approval is requested.
|
|
51
|
+
Use the [price list](billing-and-permissions.md#prices) for each action's cost and a bounded plan.
|
|
52
|
+
Profile lookups cost credits even when they do not notify the member. A general budget does not
|
|
53
|
+
select recipients or approve their messages.
|
|
54
|
+
|
|
55
|
+
A LinkedIn profile lookup takes the public profile identifier, not the whole LinkedIn URL. Extract
|
|
56
|
+
the last nonempty path segment from the supplied profile URL: `https://www.linkedin.com/in/jane-doe/`
|
|
57
|
+
becomes `jane-doe`. The current backend rejects a whole URL. Keep the URL as source evidence, but use
|
|
58
|
+
only that public identifier in a proposed lookup as well as its execution. A lookup can resolve it
|
|
59
|
+
to a `member_id`, network distance and pending invitation status. Inspect current input/output types
|
|
60
|
+
and include its cost in the approved plan:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
sl outreach perform-outbound-channel-action --company <slug> \
|
|
64
|
+
--channel-account-id <account-id> --external-id <plan>-<prospect>-lookup \
|
|
65
|
+
--action '{"linkedinLookupProfile":{"identifier":"<public-profile-identifier>"}}' --wait
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Other LinkedIn actions commonly take `memberId` and use these action variants:
|
|
69
|
+
|
|
70
|
+
```json
|
|
71
|
+
{"linkedinInvite":{"memberId":"<id>","message":"<approved-note>"}}
|
|
72
|
+
{"linkedinSendMessage":{"memberId":"<id>","text":"<approved-text>"}}
|
|
73
|
+
{"linkedinVisit":{"memberId":"<id>"}}
|
|
74
|
+
{"linkedinCancelInvitation":{"invitationId":"<id>"}}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Check current length and account restrictions. Avoid invitations to first-degree connections or
|
|
78
|
+
members with pending invitations, even if the provider does not reject them. A free account may
|
|
79
|
+
have limits on notes; a refusal is not permission to change the message or send without a note.
|
|
80
|
+
Apply an approved fallback only when the plan covers it; otherwise prepare that alternative.
|
|
81
|
+
|
|
82
|
+
## Idempotency, timeouts and pacing
|
|
83
|
+
|
|
84
|
+
Always provide a stable, meaningful `--external-id` per logical action, for example
|
|
85
|
+
`<plan>-<prospect>-step-1`. Reusing an ID returns the existing action rather than sending twice.
|
|
86
|
+
Persist it before submission for a multi-step plan. A timeout does not mean the action failed:
|
|
87
|
+
read `outbound-channel-actions` or `outbound-channel-action --id <id>` first. Do not generate a new
|
|
88
|
+
external ID to work around an unknown result, rate limit or paused account.
|
|
89
|
+
|
|
90
|
+
`--wait` follows an accepted action until it settles. Selection then refers to the subscription
|
|
91
|
+
result, for example `channelAction.state,channelAction.result`. A later read can select
|
|
92
|
+
`state,error,result`; common states are `PENDING`, `EXECUTING`, `COMPLETED`, `FAILED`, `CANCELLED`.
|
|
93
|
+
A `FAILED` action is not automatically retried by the gateway. Determine the cause and the approved
|
|
94
|
+
retry policy before resubmission. Retrying with a new ID is a distinct action.
|
|
95
|
+
|
|
96
|
+
Actions can queue under member/provider pacing. Read `scheduledAt` and actual status; do not promise
|
|
97
|
+
immediate delivery. Use current limits instead of assuming a permanent invitations/messages quota.
|
|
98
|
+
If a provider returns `rate_limited` or account `pausedUntil`, wait according to that state.
|
|
99
|
+
Pending actions can be cancelled with the documented
|
|
100
|
+
`cancel-outbound-channel-actions --channel-account-id <id> --channel-action-ids '["<id>"]'` operation
|
|
101
|
+
when the user or approved stop policy calls for it. Verify the cancellation result.
|
|
102
|
+
|
|
103
|
+
On billing errors such as `insufficient_credits` with `INSUFFICIENT_CREDITS`, `NO_BILLING_CUSTOMER`
|
|
104
|
+
or `PRODUCT_NOT_BILLED`, stop the plan and report the account/company and error. Check whether the
|
|
105
|
+
provider was reached and whether anything was charged from the actual result rather than inferring
|
|
106
|
+
all failures are uncharged. `billing_unavailable` requires reconciliation too. Resume only under
|
|
107
|
+
the approved scope and cost ceiling after funding/service recovery; do not invent a new send ID
|
|
108
|
+
to bypass a failed billing state.
|
|
109
|
+
|
|
110
|
+
## Replies and acceptances
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
sl outreach outbound-channel-events --company <slug> --channel-account-id <id> \
|
|
114
|
+
--fields id,eventType,occurredAt,payload
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Use events such as `invitation.accepted` and `message.received`, and the available `linkedin-chats`
|
|
118
|
+
and `linkedin-chat-messages` reads. Inspect the supported unacknowledged filter, commonly
|
|
119
|
+
`'{"acknowledged":{"eq":"UNACKNOWLEDGED"}}'`, then acknowledge events actually handled under
|
|
120
|
+
the approved workflow with `acknowledge-outbound-channel-events`. Do not acknowledge merely shown
|
|
121
|
+
items or send replies without authorization.
|
|
122
|
+
|
|
123
|
+
The event feed is not the sender's entire LinkedIn inbox. It covers conversations Outreach tracks,
|
|
124
|
+
such as those it started or members it invited/wrote to; absence here does not prove that nobody
|
|
125
|
+
replied elsewhere. Do not send a message just to make an unrelated conversation observable.
|
|
126
|
+
On any reply or other approved stop event, reconcile pending follow-ups before another action.
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Signals: watchers and leads
|
|
2
|
+
|
|
3
|
+
Read when the user requests buying signals, monitoring or existing leads. Signals access is
|
|
4
|
+
permission-dependent; plain login requests watcher read/write scopes but does not grant them to
|
|
5
|
+
every customer. Use the current token's operations and help. Missing Signals access does not prevent
|
|
6
|
+
an otherwise authorized Atlas shortlist.
|
|
7
|
+
|
|
8
|
+
A watcher follows a signal for an ICP and can produce a qualified lead with the observed event.
|
|
9
|
+
A definition or a running watcher is not itself a delivered lead. Do not invent a score or probability.
|
|
10
|
+
|
|
11
|
+
## Discover and scope
|
|
12
|
+
|
|
13
|
+
Examples, after checking help and field types:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
sl signals watcher-definitions --fields slug,version,name,description,triggers
|
|
17
|
+
sl signals watcher-definition --slug <slug> --watcher-definition-version <version> \
|
|
18
|
+
--fields watcherInputSchema,canonicalEventSchema
|
|
19
|
+
sl signals watchers --company <slug> \
|
|
20
|
+
--fields id,name,lifecycleState,provisioningStatus
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Pick a definition by its description, including exclusions. Prefer its current version and pin
|
|
24
|
+
slug/version in the approved plan. `watcherInput` must match `watcherInputSchema`; do not guess
|
|
25
|
+
keys from a definition name. The event payload follows `canonicalEventSchema`.
|
|
26
|
+
|
|
27
|
+
The ICP uses Atlas-style semantic filters and Mercator IDs. Inspect the current ICP input schema;
|
|
28
|
+
for example, an organization condition can constrain industry, size and `divisionIds`, while a
|
|
29
|
+
contact condition constrains job titles. Preserve the intended geography meaning and commercial
|
|
30
|
+
exclusions from the sourcing brief.
|
|
31
|
+
|
|
32
|
+
Before creating anything, read existing watchers. Identical input/ICP can reuse a shared watcher.
|
|
33
|
+
Watchers are not generally edited into a different definition/ICP; changing these can require a new
|
|
34
|
+
watcher. Cap updates and deletion can affect other consumers of a shared watcher. Inspect ownership,
|
|
35
|
+
consumers and current state before treating one as this task's disposable resource.
|
|
36
|
+
|
|
37
|
+
## Approve ongoing cost and stopping
|
|
38
|
+
|
|
39
|
+
The company used to create a watcher pays for its delivered leads throughout its lifetime. Pass
|
|
40
|
+
the intended `--company` explicitly and verify it. Set supported lead caps, such as
|
|
41
|
+
`--lead-caps '[{"maximumLeads":20,"period":"P1D"}]'`, only after confirming the schema and matching
|
|
42
|
+
the authorized budget. Do not assume a default per-organization cap establishes the requested total.
|
|
43
|
+
|
|
44
|
+
Use [billing-and-permissions.md](billing-and-permissions.md) to establish the definition's current
|
|
45
|
+
price and approval. The plan must specify duration or an explicit ongoing choice, caps, maximum
|
|
46
|
+
customer credits, stop conditions and how stopping will actually happen. A daily lead cap limits
|
|
47
|
+
volume for a period, not total lifetime spend. If the CLI has no supported expiry or hard spending
|
|
48
|
+
cap, do not pretend it does. Explain the operational stop or obtain approval for the actual limit.
|
|
49
|
+
Persist the approved watcher IDs and stop responsibility for a task that must resume later.
|
|
50
|
+
|
|
51
|
+
`sl signals create-watcher ... --wait` provisions the watcher. With `--wait`, selected fields refer
|
|
52
|
+
to its subscription result, for example `watcher.id,watcher.provisioningStatus`. No webhook is needed
|
|
53
|
+
when leads are read from the CLI. Creation can remain in progress after a timeout: inspect existing
|
|
54
|
+
watchers and the accepted request before creating another one. Do not create duplicates to recover.
|
|
55
|
+
|
|
56
|
+
## Delivery and state
|
|
57
|
+
|
|
58
|
+
Read lifecycle, provisioning status, caps and provider state before saying "no lead yet". A watcher
|
|
59
|
+
that is still provisioning, paused, billing paused or capped is different from an active provisioned
|
|
60
|
+
watcher with no matching delivered event.
|
|
61
|
+
|
|
62
|
+
When available, select `providerStates.providerSlug,providerStates.nextRunAt`. A scheduled provider
|
|
63
|
+
can have a next run; a push provider can send asynchronously. A definition's `triggers` alone does
|
|
64
|
+
not establish when its provider will deliver. Inspect current help before `trigger-watcher` and
|
|
65
|
+
do not promise that manually triggering a push provider creates a lead or that a historical latency
|
|
66
|
+
is a delivery guarantee. Record actual observed delivery timing separately.
|
|
67
|
+
|
|
68
|
+
`BILLING_PAUSED` means billing prevented delivery. Stop downstream paid work and report the state.
|
|
69
|
+
`resume-watcher` can replay held-back leads and incur charges, so verify its current replay window
|
|
70
|
+
and include that cost in authorization before resuming. A funded balance alone is not approval
|
|
71
|
+
for an unbounded replay.
|
|
72
|
+
|
|
73
|
+
Counter selections can sit next to rows, for example `id,events.total,events.discarded,events.observedAt`.
|
|
74
|
+
Discarded slices and reasons can require service-wide read permission (`signals/*:read`); a refusal
|
|
75
|
+
is an access limit, not evidence there were no discarded events.
|
|
76
|
+
|
|
77
|
+
## Read leads without accidental reveals
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
sl signals watcher-events --company <slug> \
|
|
81
|
+
--filter '{"watcherId":{"eq":"<watcher-id>"},"qualifiedAt":{"gt":"<last-seen>"}}' \
|
|
82
|
+
--first 20 --fields id,qualifiedAt,occurredAt,payload,contact.node.id
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Inspect the current filter type to combine watcher, time and unacknowledged conditions correctly.
|
|
86
|
+
Do not select `contact.node.firstName`, email, LinkedIn or phone fields, or use a depth that reaches
|
|
87
|
+
them. Contact relations on events can reveal and bill selected reach fields when no explicit reveal
|
|
88
|
+
argument is supplied. Safe reading of a lead selects its contact ID only. Show the event and fit,
|
|
89
|
+
then reveal only approved dimensions through a bounded Atlas find for selected IDs.
|
|
90
|
+
|
|
91
|
+
Quote the actual event, company, occurrence/detection dates and relevant payload. Do not make a
|
|
92
|
+
company-level event proof that an identified person is the buyer. Keep incomplete/unknown matches
|
|
93
|
+
visible and inspect the evidence before planning an action.
|
|
94
|
+
|
|
95
|
+
Use the supported unacknowledged filter, commonly
|
|
96
|
+
`'{"acknowledged":{"eq":"UNACKNOWLEDGED"}}'`, to avoid handling the same lead twice. Acknowledge
|
|
97
|
+
only after the user or an approved plan has acted on or explicitly skipped it:
|
|
98
|
+
`sl signals acknowledge-watcher-events --ids '["<event-id>"]'`. Merely displaying it is not handling
|
|
99
|
+
it. Acknowledgement is a state change and must stay within the authorized workflow.
|
|
100
|
+
|
|
101
|
+
At the end, report created/reused watcher IDs, active or paused state, approved caps and duration,
|
|
102
|
+
and the stop mechanism. Continue an already approved watcher as agreed; ask only if the desired
|
|
103
|
+
lifetime or shared-resource effect is unresolved. Never say monitoring stopped without a verified
|
|
104
|
+
state change, or that it is scheduled when no scheduler or provider state supports that claim.
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Offline arithmetic only. This helper never authenticates, reveals data or authorizes execution.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
const SCALE = 1_000_000_000n;
|
|
8
|
+
const STATUSES = new Set(['LOCKED', 'OWNED', 'REVEALED', 'UNAVAILABLE', 'FAILED']);
|
|
9
|
+
const fail = (message) => { throw new Error(message); };
|
|
10
|
+
const object = (value, label) => {
|
|
11
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) fail(`${label} must be an object.`);
|
|
12
|
+
return value;
|
|
13
|
+
};
|
|
14
|
+
const identifier = (value, label) => {
|
|
15
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9:_-]{0,199}$/.test(value)) fail(`${label} must be an opaque ID or slug.`);
|
|
16
|
+
return value;
|
|
17
|
+
};
|
|
18
|
+
const opaqueIdentifier = (value, label) => {
|
|
19
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9:_+/=-]{0,1023}$/.test(value)) fail(`${label} must be an opaque ID without whitespace or control characters.`);
|
|
20
|
+
return value;
|
|
21
|
+
};
|
|
22
|
+
const timestamp = (value, label) => {
|
|
23
|
+
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)) fail(`${label} must be a UTC ISO timestamp.`);
|
|
24
|
+
const milliseconds = Date.parse(value);
|
|
25
|
+
const normalized = value.includes('.') ? value.replace(/\.(\d{1,3})Z$/, (_, digits) => `.${digits.padEnd(3, '0')}Z`) : value.replace('Z', '.000Z');
|
|
26
|
+
if (!Number.isFinite(milliseconds) || new Date(milliseconds).toISOString() !== normalized) fail(`${label} is invalid.`);
|
|
27
|
+
return milliseconds;
|
|
28
|
+
};
|
|
29
|
+
const decimal = (value) => {
|
|
30
|
+
if (typeof value === 'number') {
|
|
31
|
+
if (!Number.isSafeInteger(value) || value < 0) fail('Tariff rates must be nonnegative safe integers or decimal strings.');
|
|
32
|
+
value = String(value);
|
|
33
|
+
}
|
|
34
|
+
if (typeof value !== 'string' || !/^(0|[1-9]\d{0,17})(?:\.\d{1,9})?$/.test(value)) fail('Tariff rates must be nonnegative decimals with at most 9 fractional places.');
|
|
35
|
+
const [whole, fraction = ''] = value.split('.');
|
|
36
|
+
return BigInt(whole) * SCALE + BigInt(fraction.padEnd(9, '0'));
|
|
37
|
+
};
|
|
38
|
+
const credits = (value) => {
|
|
39
|
+
const whole = value / SCALE;
|
|
40
|
+
const fraction = String(value % SCALE).padStart(9, '0').replace(/0+$/, '');
|
|
41
|
+
return fraction ? `${whole}.${fraction}` : String(whole);
|
|
42
|
+
};
|
|
43
|
+
const key = (id, dimension) => JSON.stringify([id, dimension]);
|
|
44
|
+
const tariffSource = (value) => {
|
|
45
|
+
if (typeof value !== 'string') fail('Tariff source must be an HTTP(S) URL or a short label.');
|
|
46
|
+
if (!/^https?:/i.test(value)) {
|
|
47
|
+
if (!/^[\p{L}\p{N}][\p{L}\p{N} .,:()/_-]{0,199}$/u.test(value)) fail('Tariff source must be an HTTP(S) URL or a short label.');
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
let source;
|
|
51
|
+
try { source = new URL(value); } catch { fail('Tariff source must be an HTTP(S) URL or a short label.'); }
|
|
52
|
+
if (source.username || source.password) fail('Tariff source must be an HTTP(S) URL without credentials.');
|
|
53
|
+
source.search = '';
|
|
54
|
+
source.hash = '';
|
|
55
|
+
return source.href;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** A quote uses operator-verified input, not a live tariff or a billing transaction. */
|
|
59
|
+
export function quoteReveals(input) {
|
|
60
|
+
object(input, 'Input');
|
|
61
|
+
const company = identifier(input.company, 'Company');
|
|
62
|
+
const environment = identifier(input.environment, 'Environment');
|
|
63
|
+
const asOf = timestamp(input.asOf, 'asOf');
|
|
64
|
+
if (!Array.isArray(input.ids) || !input.ids.length || input.ids.length > 100_000) fail('ids must contain 1 to 100000 selected record IDs.');
|
|
65
|
+
const ids = input.ids.map((id) => opaqueIdentifier(id, 'Selected record ID'));
|
|
66
|
+
const selected = new Set(ids);
|
|
67
|
+
if (selected.size !== ids.length) fail('Duplicate selected record IDs.');
|
|
68
|
+
if (!Array.isArray(input.dimensions) || !input.dimensions.length || input.dimensions.length > 64) fail('dimensions must contain 1 to 64 exact Atlas dimension names.');
|
|
69
|
+
const dimensions = input.dimensions.map((dimension) => {
|
|
70
|
+
if (typeof dimension !== 'string' || !/^(CONTACT|ORGANIZATION)_[A-Z][A-Z0-9_]*$/.test(dimension)) fail('Invalid Atlas dimension name.');
|
|
71
|
+
return dimension;
|
|
72
|
+
});
|
|
73
|
+
const requested = new Set(dimensions);
|
|
74
|
+
if (requested.size !== dimensions.length) fail('Duplicate requested dimensions.');
|
|
75
|
+
if (new Set(dimensions.map((dimension) => dimension.split('_')[0])).size !== 1) fail('Quote contacts and organizations separately using their own selected IDs.');
|
|
76
|
+
|
|
77
|
+
const tariff = object(input.tariff, 'Tariff');
|
|
78
|
+
if (tariff.verified !== true || tariff.company !== company || tariff.environment !== environment) fail('Tariff must be operator-verified for this company and environment.');
|
|
79
|
+
const verifiedAt = timestamp(tariff.verifiedAt, 'Tariff verification date');
|
|
80
|
+
if (verifiedAt > asOf) fail('Tariff verification cannot be after asOf.');
|
|
81
|
+
if (tariff.validUntil !== undefined && timestamp(tariff.validUntil, 'Tariff expiry') <= asOf) fail('Tariff has expired.');
|
|
82
|
+
const source = tariffSource(tariff.source);
|
|
83
|
+
const rates = object(tariff.rates, 'Tariff rates');
|
|
84
|
+
const prices = new Map(dimensions.map((dimension) => {
|
|
85
|
+
if (!Object.hasOwn(rates, dimension)) fail('Missing tariff for a requested dimension.');
|
|
86
|
+
return [dimension, decimal(rates[dimension])];
|
|
87
|
+
}));
|
|
88
|
+
const validatePair = (record) => {
|
|
89
|
+
object(record, 'Reveal record');
|
|
90
|
+
if (!selected.has(record.id) || !requested.has(record.dimension)) fail('Reveal record is outside the exact selected IDs or dimensions.');
|
|
91
|
+
if (!STATUSES.has(record.status)) fail('Invalid reveal status.');
|
|
92
|
+
return key(record.id, record.dimension);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const ownership = input.ownership ?? [];
|
|
96
|
+
if (!Array.isArray(ownership)) fail('ownership must be an array.');
|
|
97
|
+
const seenOwnership = new Set();
|
|
98
|
+
const owned = new Set();
|
|
99
|
+
for (const record of ownership) {
|
|
100
|
+
const pair = validatePair(record);
|
|
101
|
+
if (seenOwnership.has(pair)) fail('Duplicate ownership record.');
|
|
102
|
+
seenOwnership.add(pair);
|
|
103
|
+
const until = record.ownedUntil === undefined ? null : timestamp(record.ownedUntil, 'Ownership expiry');
|
|
104
|
+
if (record.status === 'OWNED' && record.company === company && record.environment === environment && until !== null && until > asOf) owned.add(pair);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const observations = input.observedPages;
|
|
108
|
+
if (observations !== undefined && !Array.isArray(observations)) fail('observedPages must be an array.');
|
|
109
|
+
const pages = new Map();
|
|
110
|
+
for (const page of observations ?? []) {
|
|
111
|
+
object(page, 'Observed page');
|
|
112
|
+
if (page.company !== company || page.environment !== environment) fail('Observed page must belong to this company and environment.');
|
|
113
|
+
const pageKey = key(opaqueIdentifier(page.searchId, 'Search ID'), opaqueIdentifier(page.pageId, 'Page ID'));
|
|
114
|
+
if (!['FILLING', 'COMPLETE'].includes(page.state) || !Array.isArray(page.reveals)) fail('Observed page needs FILLING/COMPLETE state and reveal records.');
|
|
115
|
+
const pairs = new Map();
|
|
116
|
+
for (const record of page.reveals) {
|
|
117
|
+
const pair = validatePair(record);
|
|
118
|
+
if (pairs.has(pair)) fail('Duplicate reveal record within one page snapshot.');
|
|
119
|
+
pairs.set(pair, record.status);
|
|
120
|
+
}
|
|
121
|
+
const fingerprint = JSON.stringify([...pairs].sort(([a], [b]) => a.localeCompare(b)));
|
|
122
|
+
const previous = pages.get(pageKey);
|
|
123
|
+
if (previous?.state === 'COMPLETE' && page.state === 'COMPLETE' && previous.fingerprint !== fingerprint) fail('Conflicting COMPLETE snapshots for the same page.');
|
|
124
|
+
if (!previous || previous.state !== 'COMPLETE') pages.set(pageKey, { state: page.state, pairs, fingerprint });
|
|
125
|
+
}
|
|
126
|
+
const observed = new Map(dimensions.map((dimension) => [dimension, new Set()]));
|
|
127
|
+
let repeatedObservedPairs = 0;
|
|
128
|
+
for (const page of pages.values()) {
|
|
129
|
+
for (const [pair, status] of page.pairs) {
|
|
130
|
+
if (status !== 'REVEALED') continue;
|
|
131
|
+
if (owned.has(pair)) fail('A new reveal contradicts verified ownership at asOf. Reconcile the timestamps before quoting.');
|
|
132
|
+
const [, dimension] = JSON.parse(pair);
|
|
133
|
+
const seen = observed.get(dimension);
|
|
134
|
+
if (seen.has(pair)) repeatedObservedPairs++;
|
|
135
|
+
seen.add(pair);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
let ceiling = 0n;
|
|
139
|
+
let calculated = 0n;
|
|
140
|
+
const byDimension = dimensions.map((dimension) => {
|
|
141
|
+
const ownedUnits = ids.filter((id) => owned.has(key(id, dimension))).length;
|
|
142
|
+
const maximumNewUnits = ids.length - ownedUnits;
|
|
143
|
+
const observedNewUnits = observed.get(dimension).size;
|
|
144
|
+
const maximumCustomerCredits = BigInt(maximumNewUnits) * prices.get(dimension);
|
|
145
|
+
const calculatedCustomerCredits = BigInt(observedNewUnits) * prices.get(dimension);
|
|
146
|
+
ceiling += maximumCustomerCredits;
|
|
147
|
+
calculated += calculatedCustomerCredits;
|
|
148
|
+
return { dimension, creditsPerUnit: credits(prices.get(dimension)), ownedUnits, maximumNewUnits, maximumCustomerCredits: credits(maximumCustomerCredits), observedNewUnits: observations === undefined ? null : observedNewUnits, calculatedCustomerCredits: observations === undefined ? null : credits(calculatedCustomerCredits) };
|
|
149
|
+
});
|
|
150
|
+
return {
|
|
151
|
+
company, environment, asOf: input.asOf,
|
|
152
|
+
selection: { ids: [...ids], dimensions: [...dimensions] },
|
|
153
|
+
tariff: { source, verifiedAt: tariff.verifiedAt, validUntil: tariff.validUntil ?? null, verification: 'Operator supplied; not independently verified by this helper.' },
|
|
154
|
+
maximumNewUnits: byDimension.reduce((sum, row) => sum + row.maximumNewUnits, 0),
|
|
155
|
+
maximumCustomerCredits: credits(ceiling),
|
|
156
|
+
observedNewUnits: observations === undefined ? null : byDimension.reduce((sum, row) => sum + row.observedNewUnits, 0),
|
|
157
|
+
calculatedCustomerCredits: observations === undefined ? null : credits(calculated),
|
|
158
|
+
observedPageCount: pages.size,
|
|
159
|
+
allObservedPagesComplete: pages.size ? [...pages.values()].every((page) => page.state === 'COMPLETE') : null,
|
|
160
|
+
observedSpendProvisional: pages.size ? [...pages.values()].some((page) => page.state !== 'COMPLETE') : null,
|
|
161
|
+
repeatedObservedPairs,
|
|
162
|
+
byDimension,
|
|
163
|
+
authoritativeLedgerDebit: null,
|
|
164
|
+
executionAuthorized: false,
|
|
165
|
+
limitations: ['Only the selected reveal dimensions are priced; no separate provider, lead or action charges are included.', 'UNAVAILABLE or FAILED does not reduce the ceiling for a future reveal.', 'Calculated credits containing FILLING pages are provisional observations, not settled spend.', 'Observed units count distinct selected record/dimension pairs, not billing transactions. Complete pages do not establish complete pagination.', 'No action is executed. Obtain any missing authorization and recheck scope, prices and ownership before execution.'],
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
170
|
+
try {
|
|
171
|
+
const args = process.argv.slice(2);
|
|
172
|
+
if (args.length !== 2 || args[0] !== '--input') fail('Usage: node quote-reveals.mjs --input <file.json|->');
|
|
173
|
+
let raw;
|
|
174
|
+
try { raw = fs.readFileSync(args[1] === '-' ? 0 : args[1], 'utf8'); } catch { fail('Could not read JSON input.'); }
|
|
175
|
+
let input;
|
|
176
|
+
try { input = JSON.parse(raw); } catch { fail('Input must be valid JSON.'); }
|
|
177
|
+
process.stdout.write(`${JSON.stringify(quoteReveals(input), null, 2)}\n`);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
process.stderr.write(`Quote failed: ${error.message}\n`);
|
|
180
|
+
process.exitCode = 1;
|
|
181
|
+
}
|
|
182
|
+
}
|