@audienti/cli 0.2.0-exora.2 → 0.2.0-exora.20
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 +2 -2
- package/cli/account-reply-operations.mjs +27 -1
- package/cli/agents.mjs +74 -14
- package/cli/assignment-operations.mjs +12 -12
- package/cli/assignment.mjs +6 -6
- package/cli/attachment-operations.mjs +9 -0
- package/cli/attachments.mjs +28 -0
- package/cli/audience-operations.mjs +5 -0
- package/cli/audiences.mjs +7 -4
- package/cli/audienti.mjs +143 -23
- package/cli/audit-operations.mjs +17 -0
- package/cli/audit.mjs +39 -0
- package/cli/budget-operations.mjs +8 -0
- package/cli/budgets.mjs +34 -0
- package/cli/campaign-find.mjs +155 -0
- package/cli/campaign-operations.mjs +30 -0
- package/cli/campaigns.mjs +61 -0
- package/cli/cohort-operations.mjs +22 -0
- package/cli/cohorts.mjs +45 -0
- package/cli/connection-registry-operations.mjs +2 -1
- package/cli/content.mjs +2 -0
- package/cli/discovery-operations.mjs +4 -3
- package/cli/discovery.mjs +3 -2
- package/cli/file-operations.mjs +29 -0
- package/cli/files.mjs +14 -0
- package/cli/guardrails-operations.mjs +12 -0
- package/cli/guardrails.mjs +37 -0
- package/cli/hand-task-operations.mjs +11 -0
- package/cli/hand-tasks.mjs +18 -0
- package/cli/intent-operations.mjs +35 -0
- package/cli/intent.mjs +42 -0
- package/cli/json-file.mjs +1 -1
- package/cli/kv-operations.mjs +17 -0
- package/cli/kv.mjs +58 -0
- package/cli/mcp.mjs +4 -4
- package/cli/notification-operations.mjs +8 -0
- package/cli/offer-operations.mjs +1 -1
- package/cli/outbound-operations.mjs +16 -0
- package/cli/outbound.mjs +54 -0
- package/cli/outcome-operations.mjs +28 -0
- package/cli/outcomes.mjs +16 -0
- package/cli/owner-account-client.mjs +3 -3
- package/cli/playbook-help.mjs +83 -0
- package/cli/playbook-operations.mjs +38 -0
- package/cli/progress.mjs +29 -7
- package/cli/question-operations.mjs +12 -0
- package/cli/questions.mjs +32 -0
- package/cli/queue-operations.mjs +12 -0
- package/cli/queue.mjs +25 -0
- package/cli/recipient-operations.mjs +1 -1
- package/cli/recipients.mjs +6 -2
- package/cli/rooms-operations.mjs +48 -0
- package/cli/rooms.mjs +160 -0
- package/cli/search-operations.mjs +9 -0
- package/cli/secret-operations.mjs +7 -0
- package/cli/secrets.mjs +30 -0
- package/cli/sender-account-operations.mjs +7 -3
- package/cli/sender-accounts.mjs +18 -8
- package/cli/skills-mcp.mjs +13 -6
- package/cli/skills.mjs +73 -16
- package/cli/tools-operations.mjs +18 -10
- package/cli/tools.mjs +48 -20
- package/cli/usage-operations.mjs +8 -0
- package/cli/usage.mjs +41 -0
- package/cli/work-execution-operations.mjs +7 -0
- package/cli/work-execution.mjs +3 -3
- package/cli/work-operations.mjs +7 -5
- package/cli/work.mjs +11 -6
- package/cli/workspaces.mjs +132 -24
- package/package.json +2 -2
- package/skills/agent-rooms/SKILL.md +140 -0
- package/skills/agent-rooms/references/commands.md +78 -0
- package/skills/audienti/SKILL.md +112 -6
- package/skills/audienti/references/helpers.md +15 -2
- package/skills/audienti/references/profile-workflows.md +6 -4
- package/skills/audienti/scripts/contracts.mjs +1 -1
- package/skills/getting-started/SKILL.md +227 -0
- package/skills/getting-started/references/audience.md +143 -0
- package/skills/getting-started/references/campaign-draft.md +80 -0
- package/skills/getting-started/references/capabilities.md +238 -0
- package/skills/getting-started/references/mailbox-check.md +64 -0
- package/skills/getting-started/references/outcome-checks.md +125 -0
- package/skills/getting-started/references/replies.md +265 -0
- package/skills/getting-started/references/reply-checks.md +54 -0
- package/skills/playbook-design/SKILL.md +135 -0
- package/skills/playbook-design/references/fields.md +145 -0
- package/source-manifest.json +88 -40
- package/cli/approach-operations.mjs +0 -22
- package/cli/experiment-operations.mjs +0 -25
- package/cli/experiments.mjs +0 -26
package/cli/audienti.mjs
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { isAssignmentCommand, assignmentCli } from './assignment.mjs';
|
|
3
|
+
import { playbookHelp } from './playbook-help.mjs';
|
|
3
4
|
// The CLI is an HTTP client. It has no database access or separate business rules.
|
|
4
5
|
const args = process.argv.slice(2);
|
|
5
6
|
const usage = `Profiles: audienti profiles list|search|get ID | match evaluate|apply SOURCE CANDIDATE | history RESOLUTION (saved workspace records)
|
|
6
|
-
Skills: audienti skills list|show
|
|
7
|
-
Tools: audienti tools
|
|
7
|
+
Skills: audienti skills list [--compact]|show SKILL|read SKILL RESOURCE|helper NAME --file INPUT.json|- [--json]
|
|
8
|
+
Tools: audienti call TOOL ['JSON'] | tools search "WORDS"|get TOOL|list|runs|balance [--help]
|
|
8
9
|
Sender: audienti sender accounts list|get|alias|register|bind|unbind|state|automation|activity report [--profile PATH]
|
|
10
|
+
Managed LinkedIn: audienti sender managed list|connect [--workspace ID] [--profile PATH] (connect: the user only; returns a sign-in link)
|
|
11
|
+
audienti sender managed plan MANAGED_ACCOUNT_ID --plan free|premium_career|premium_business|premium_all_in_one|sales_navigator_core|sales_navigator_advanced|recruiter_lite|none [--workspace ID] (the user only; sets the connection note length; none clears it)
|
|
9
12
|
Prospecting: audienti prospecting settings show|save|accounts|account-show|account-save|history [--profile PATH]
|
|
10
13
|
Usage: audienti whoami [--json]
|
|
11
14
|
audienti workspace assignments list [--workspace ID]
|
|
12
15
|
audienti workspace prospect assignment get/set --prospect-id ID [--file INPUT.json]
|
|
13
16
|
audienti workspace routing-rules get/replace [--file INPUT.json]
|
|
14
17
|
audienti workspace routing apply --file INPUT.json
|
|
15
|
-
audienti workspace prospect
|
|
18
|
+
audienti workspace prospect campaign-fit get --prospect-id ID --campaign-id ID
|
|
16
19
|
audienti workspace prospect fit-override set/clear --file INPUT.json
|
|
17
20
|
audienti workspace prospect move --file INPUT.json
|
|
18
21
|
audienti workspace member remove --file INPUT.json
|
|
@@ -23,60 +26,170 @@ Required environment:
|
|
|
23
26
|
AUDIENTI_API_TOKEN Account API token (create it from your Account page)
|
|
24
27
|
|
|
25
28
|
Use HTTPS for remote hosts. Local HTTP is supported on loopback only.
|
|
26
|
-
Agent commands: agent connect --name NAME|poll|cancel|list|revoke ID --profile PATH
|
|
29
|
+
Agent commands: agent connect --name NAME [--write (ask for Allow workspace changes up front)] [--capabilities find,enrich,expand,research,engage,sync,notify,approve]|poll|cancel|list|revoke ID --profile PATH
|
|
27
30
|
Owner permission change: agent permission ID --scope workspace:read|workspace:access --profile USER_PROFILE
|
|
28
|
-
|
|
31
|
+
Owner capability change: agent capabilities ID --set find,enrich,expand,research,engage,sync,notify,approve --profile USER_PROFILE (agents are refused outside this set)
|
|
32
|
+
Agent capabilities: agent capabilities report --file CAPABILITIES.json --profile AGENT_PROFILE (capability rows; the old per-account shape still works)
|
|
33
|
+
What the agent can do: agent capabilities [--workspace ID] [--json] --profile AGENT_PROFILE (works now, and works with Audienti tools)
|
|
29
34
|
Read capabilities: agent capabilities show [--id AGENT_ID] --profile PROFILE
|
|
35
|
+
Getting started: skills show getting-started, then agent capabilities report --file CAPABILITIES.json --profile AGENT_PROFILE
|
|
36
|
+
Read tool inventory: agent inventory show [--id AGENT_ID] --profile PROFILE (agent inventory report still works; capabilities report is current)
|
|
30
37
|
Account authorization: agent accounts show [--id AGENT_ID] --profile PROFILE
|
|
31
38
|
Authorize/revoke: agent accounts authorize --id AGENT_ID --provider email|linkedin --account REF --authorized true|false --profile OWNER_PROFILE
|
|
32
39
|
Sharing: agent capabilities sharing --id AGENT_ID --profile OWNER_PROFILE
|
|
33
40
|
Share/unshare: agent capabilities share --id AGENT_ID --provider email|linkedin --account REF --workspace ID --shared true|false --profile OWNER_PROFILE
|
|
34
41
|
Team member: workspace member USER_ID [--workspace ID] --profile PROFILE
|
|
35
|
-
Work execution: work execution claim|start|get PLAN --action ID; release|lookup --claim ID; report --attempt ID
|
|
42
|
+
Work execution: work execution claim|start|send|get PLAN --action ID (send: managed LinkedIn accounts, --file with claimId and requestId); release|lookup --claim ID; report --attempt ID
|
|
36
43
|
Work feedback: work changes request|list|get|respond|withdraw PLAN --workspace ID
|
|
37
|
-
Work: work plan save|list|show|approve|withdraw-approval|cancel|eligibility
|
|
44
|
+
Work: work plan save|list|show|approve|withdraw-approval|cancel|skip|eligibility
|
|
45
|
+
Activity: work activity --workspace ID [--search TEXT] [--cursor-at ISO --cursor-id ID]
|
|
46
|
+
Work list: work list --workspace ID [--order oldest|priority] [--queue review|blocked|activity]
|
|
47
|
+
a plan that only waits for its cadence is in neither review nor blocked; it returns to review when the wait ends
|
|
38
48
|
Work writes: --file INPUT.json; human review needs a human workspace:access token
|
|
39
|
-
Audiences: audience options --kind industries|locations|sizes|types|seniorities|titles|functions
|
|
49
|
+
Audiences: audience options --kind industries|locations|sizes|types|seniorities|titles|functions [--q TEXT]
|
|
40
50
|
audience list|show ID|create|update ID|archive ID|restore ID
|
|
51
|
+
audience summary [--audience ID]|people ID|companies ID
|
|
52
|
+
audience test ID --url LINKEDIN_URL --request-id UUID (spends hosted credits unless the profile is saved)
|
|
53
|
+
Files: file upload PATH --type MIME|list|prepare|register|download|delete ID (personal files, human token only)
|
|
54
|
+
Hand tasks: hand-tasks [list [--state open|ready|done|skipped]]|show ID|done ID --outcome TEXT [--notes TEXT] [--result replied|meeting_booked]|skip ID --reason TEXT|event ID [--name TEXT] (a person does a Custom step by hand and records what happened)
|
|
55
|
+
Queue: audienti queue [list]|next|claim ID [--note TEXT]|done ID [--note TEXT]|skip ID --note TEXT|release ID [--workspace ID] (start here after you connect; without --workspace an agent reads every workspace its user approved it in; done or skip again with a new --note corrects the note of a finished task)
|
|
56
|
+
Attachments: audienti attachments upload FILE [--duration SECONDS] (store an image or voice note, get its id for content.attachments)
|
|
57
|
+
Outcome checks: audienti outcomes report TASK_ID --file RESULTS.json (results for the people an outcomes.check task lists)
|
|
58
|
+
Saved posts: audienti posts list [--topic-id ID]|get ID (savedByOperationId names the tool run that saved a post; read it with audienti tools runs get ID)
|
|
59
|
+
Saved topics: audienti topics list|get ID|create --input FILE --request-id UUID
|
|
60
|
+
Questions: audienti ask "QUESTION" [--context TEXT] [--option TEXT]... [--campaign ID] [--task ID] (questions for your user go to Operator, not chat)
|
|
61
|
+
audienti questions [list] [--state open|answered|withdrawn|all] | show ID | withdraw ID | answer ID --answer TEXT
|
|
62
|
+
Rooms: audienti rooms directory|inbox|ack|send|thread|threads|create|list|read|retire|restore|redact|resume|pause|profile|hook|watch|wait (audienti rooms help)
|
|
63
|
+
KV: audienti kv get KEY|set KEY VALUE [--json] [--nx] [--if-version N] [--ttl 7d|--expires-at TIME]|list [--prefix P]|search [--key TEXT] [--value TEXT]|delete KEY (small state between runs; never credentials)
|
|
41
64
|
Offers: offer list|show ID|create|update ID|archive ID|restore ID
|
|
42
65
|
Offer options: --file FIELDS.json --request-id UUID --expected-revision N --revision N --archived true|false
|
|
43
66
|
audienti prospects replies set|get|list PERSON --workspace ID [--evidence EVIDENCE] [--file INPUT.json]
|
|
44
67
|
Account intake: prospects intake --workspace ID --file INPUT.json
|
|
45
68
|
prospects conversation append|list PERSON --workspace ID
|
|
46
|
-
Discovery: prospects list|get ID|observation create|citation create|evidence create
|
|
47
|
-
prospects contacts list|record PERSON --workspace ID
|
|
69
|
+
Discovery: prospects list|get ID|timeline ID [--limit N]|observation create|citation create|evidence create
|
|
70
|
+
prospects contacts list|record PERSON [--file INPUT.json] [--request-id UUID] --workspace ID
|
|
48
71
|
prospects contacts get|retire PERSON CONTACT --workspace ID
|
|
49
72
|
prospects suppression get|set ID --workspace ID
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
73
|
+
guardrails show|pause|resume --workspace ID
|
|
74
|
+
dnc list|add VALUE|remove VALUE --workspace ID
|
|
75
|
+
dnc import --file LIST.csv --workspace ID (at most 5,000 rows; reports added, skipped and invalid rows)
|
|
76
|
+
dnc export [--output FILE.csv] --workspace ID
|
|
77
|
+
secret list [--workspace ID] (names only)
|
|
78
|
+
secret get NAME [--workspace ID] [--json] (prints the value; the secret records who read it last and when)
|
|
79
|
+
budgets show --workspace ID
|
|
80
|
+
budgets alerts --workspace ID [--limit N]
|
|
81
|
+
usage breakdown [--workspace ID] [--since month|7d|30d|90d] [--by tool|provider|model|caller|day] [--format json|csv]
|
|
82
|
+
workspace usage summary|callers|calls [--after ID] [--caller user:ID|agent:ID|key:ID] [--status all|succeeded|failed|pending]|call ID [--workspace ID] (paid tool use, last 30 days, and single calls)
|
|
83
|
+
intent list [--workspace ID] (the closed set of message labels: name, direction, event, channels, typed detail; output is JSON)
|
|
84
|
+
intent record --person ID --evidence ID --label NAME --quote TEXT --reason TEXT [--confidence high|medium|low] [--request-id UUID] [--participation ID] [--workspace ID] (what a stored message means; get EVIDENCE from prospects conversation append|list; --file LABELS.json for several labels or a typed detail such as a stop result or a meeting time; every label is checked and a refusal says what to fix; a message you sent that asks for a meeting takes --label meeting_requested on its outbound evidence)
|
|
85
|
+
audit list [--workspace ID] [--since 7d] [--actor agent|person] [--category NAME] [--format json|csv]
|
|
86
|
+
budgets set --workspace ID [--agent ID --cap N|none] [--new-agent-cap N|none] [--at-limit pause|ask] [--alert80 on|off] (alert80 covers Operator and email at 80%)
|
|
87
|
+
Qualification: campaigns qualification submit --file INPUT.json
|
|
88
|
+
Campaign summary: campaign summary [--workspace ID] (campaign counts per state, and per campaign its audience, offer, playbook, goal stage, people, engaged and at-goal counts)
|
|
89
|
+
Find prospects: campaign find CAMPAIGN_ID --count N --max-credits C (searches with the audience filters, checks each person, admits only fits; stops at N fits or the credit cap and reports the spend)
|
|
90
|
+
campaign check CAMPAIGN_ID --url LINKEDIN_URL [--request-id UUID] (checks one person the same way; reuse the request ID after an interruption)
|
|
91
|
+
Target companies: campaign targets CAMPAIGN_ID [--limit N --after CURSOR] (reads the companies people must work at to join)
|
|
92
|
+
campaign targets CAMPAIGN_ID --add acme.com,linkedin.com/company/globex [--remove old.com] | --set FILE|- (one company per line; saves a new revision)
|
|
93
|
+
Playbooks: playbook list [--archived] [--limit N --cursor ID]|actions|show ID [--revision N]|save --file REQUEST.json|archive ID|restore ID|draft show ID|save ID --file REQUEST.json|discard ID [--expected-updated-at T]|publish ID [--request-id UUID]|delete ID|progress PARTICIPATION_ID|record --file REQUEST.json (audienti playbook SUBCOMMAND --help for the request shape)
|
|
94
|
+
Analytics: analytics show --from ISO --to ISO [--campaign ID] [--playbook-version ID] [--format json|csv]
|
|
95
|
+
analytics outbound [--workspace ID] [--days N | --from ISO --to ISO] [--by sender|action|day] [--format json|csv]
|
|
96
|
+
analytics activity [--workspace ID] [--days N | --from ISO --to ISO] [--format json|csv]
|
|
97
|
+
analytics cohorts [--workspace ID] [--stage goal|KEY] [--cohorts N] [--horizon N] [filters] [--format json|csv]
|
|
98
|
+
analytics aging [--workspace ID] [--threshold-days N] [filters] [--format json|csv]
|
|
99
|
+
analytics filters [--workspace ID] (lists campaign, owner, offer, audience and tag values)
|
|
100
|
+
(filters: --campaign ID --owner ID --offer ID --audience ID --tag TAG; also accepted by analytics show)
|
|
101
|
+
Pipeline: pipeline show [--campaign ID] [--playbook-version ID]
|
|
53
102
|
Connections: connections list|register --file REQUEST.json|report --file REQUEST.json
|
|
54
103
|
Discovery writes use --file INPUT.json, --workspace ID and stable --request-id UUID
|
|
55
|
-
Workspace commands: workspace init|list|create|show|invite|invitations|use
|
|
56
|
-
|
|
104
|
+
Workspace commands: workspace init|list|create|show|search|invite|invitations|use
|
|
105
|
+
Notifications: workspace notifications --workspace ID [--unread-only true] [--cursor FILE.json]
|
|
106
|
+
Read state: workspace notification-read --workspace ID --key KEY --read true|false [--through OBSERVED_AT]
|
|
107
|
+
Search: workspace search --workspace ID --query TEXT [--people-only true] [--recent FILE.json]
|
|
108
|
+
Invitation commands: workspace invitation show|accept|decline|retry|cancel ID
|
|
57
109
|
Options: --workspace ID --name NAME --request-id UUID --email EMAIL --generation N
|
|
58
|
-
Optional private profile: --profile PATH (outside this repository)
|
|
110
|
+
Optional private profile: --profile PATH (outside this repository), or the AUDIENTI_PROFILE variable. --profile wins.
|
|
59
111
|
Save an environment token: profile save --scope account:read|workspace:access|agents:manage --profile PATH
|
|
60
|
-
Start local MCP stdio server: mcp
|
|
112
|
+
Start local MCP stdio server: mcp (audienti mcp --help for the settings)
|
|
61
113
|
--json writes the API response envelope.
|
|
62
114
|
`;
|
|
63
115
|
|
|
116
|
+
const MCP_HELP = `audienti mcp starts the MCP server on stdio. An agent app runs it as a command; do not type it in a shell.
|
|
117
|
+
Settings come from the environment of that command:
|
|
118
|
+
AUDIENTI_PROFILE the profile file made by agent connect or profile save (the usual way)
|
|
119
|
+
AUDIENTI_API_URL and AUDIENTI_API_TOKEN instead of a profile: the API URL ending in /api/v1 and a token
|
|
120
|
+
The workspace: a tool that works in a workspace takes workspaceId in its input. Call workspace_select once with a workspaceId to set a default for the session.
|
|
121
|
+
Tool names follow the commands: playbook_get for playbook show, playbook_draft_get for playbook draft show.
|
|
122
|
+
Errors name the MCP tool to call next, not the command.`;
|
|
123
|
+
// Example inputs for the commands that save prospects, so `--help` shows a working shape.
|
|
124
|
+
const examples = {
|
|
125
|
+
'prospects conversation append': { requestId: 'UUID', item: { source: { provider: 'email', accountRef: 'you@yourcompany.com', itemId: 'PROVIDER_MESSAGE_ID', threadId: null }, payload: { direction: 'outbound', conversationType: 'direct', occurredAt: '2026-11-06T14:00:00Z', subject: 'Ten minutes on late invoices?', body: 'Hi Jordan, could we find 20 minutes next week?', participants: null } } },
|
|
126
|
+
'intent record': [{ label: 'stop', quote: 'please stop writing to me', reason: 'They ask us to stop.', result: { type: 'reply.stop', scope: 'person' } }],
|
|
127
|
+
'prospects observation create': { requestId: 'UUID', kind: 'person', source: { provider: 'linkedin', url: 'https://www.linkedin.com/in/jane-doe' }, fields: { name: 'Jane Doe', title: 'VP Sales', imageUrl: 'https://media.licdn.com/dms/image/PHOTO_ID' }, provenance: { url: 'https://example.com/team/jane' }, observedAt: '2026-01-01T00:00:00Z', skill: { id: 'signal-prospect-research', version: '1' } },
|
|
128
|
+
'prospects citation create': { requestId: 'UUID', source: { kind: 'prospect', id: 'PERSON_PROSPECT_ID' }, target: { kind: 'prospect', id: 'COMPANY_PROSPECT_ID' }, edgeType: 'works_at', roles: [{ roleId: 'role-1', title: 'VP Sales', current: true, observedAt: '2026-01-01T00:00:00Z' }] },
|
|
129
|
+
'prospects evidence create': { requestId: 'UUID', subject: { kind: 'person', prospectId: 'PROSPECT_ID' }, campaignId: 'CAMPAIGN_ID', campaignRevision: 1, kind: 'interpretation', data: { conclusion: 'Leads a 40-person sales team', reason: 'Team page lists her as VP Sales' }, sourceUrl: 'https://example.com/team', observedAt: '2026-01-01T00:00:00Z', skill: { id: 'signal-prospect-research', version: '1' } },
|
|
130
|
+
'prospects contacts record': { kind: 'email|linkedin|mobile|phone', value: 'jane@example.com, or +15551234567 for a mobile or a direct office phone', reason: 'Published on https://example.com/contact', requestId: 'UUID', provenance: { observationId: 'OBSERVATION_ID' } },
|
|
131
|
+
'campaigns qualification submit': { requestId: 'UUID', campaignId: 'CAMPAIGN_ID', campaignRevision: 1, prospectId: 'PERSON_PROSPECT_ID', companyProspectId: 'COMPANY_PROSPECT_ID', companyIcp: { status: 'pass|fail|unverified', evidenceIds: ['COMPANY_EVIDENCE_ID'] }, personIcp: { status: 'pass|fail|unverified', evidenceIds: ['PERSON_EVIDENCE_ID'] }, signal: { status: 'match|no_match|unverified|not_required', evidenceIds: [] }, fit: { status: 'high|moderate|low|no_fit|unscored', evidenceIds: ['PERSON_EVIDENCE_ID'], reason: 'why' }, skill: { id: 'signal-prospect-research', version: '1' } },
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
function commandHelp() {
|
|
135
|
+
const words = args.slice(0, args.findIndex(value => value.startsWith('-'))).filter(Boolean);
|
|
136
|
+
const lines = usage.split('\n');
|
|
137
|
+
let shown = [];
|
|
138
|
+
for (let n = Math.min(words.length, 2); n > 0 && shown.length === 0; n--) {
|
|
139
|
+
const prefix = words.slice(0, n).join(' ');
|
|
140
|
+
shown = lines.filter(line => line.includes(prefix));
|
|
141
|
+
}
|
|
142
|
+
console.log(shown.length ? shown.map(line => line.trim()).join('\n') : usage);
|
|
143
|
+
const example = Object.entries(examples).find(([command]) => words.join(' ').startsWith(command) || (words.length > 0 && command.startsWith(words.join(' '))));
|
|
144
|
+
if (example) console.log(`\nExample --file INPUT.json for ${example[0]}:\n${JSON.stringify(example[1], null, 1)}\n${example[0].startsWith('intent') ? `\nA message you sent that asks for a meeting (store it first with prospects conversation append, direction outbound):\naudienti intent record --person PERSON --evidence EVIDENCE --label meeting_requested --quote "find 20 minutes next week" --reason "We ask for a call next week."\nRules: the "Label a message with its words" and "Label a message you sent" sections of the getting-started replies reference.` : 'Steps and rules: the "Save prospects and contacts" section of llms.txt.'}`);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Says what is wrong with a command no handler took, instead of one message for every case. */
|
|
148
|
+
function unknownCommandMessage(words) {
|
|
149
|
+
const first = words[0];
|
|
150
|
+
if (first === undefined) return 'Give a command. Use audienti --help.';
|
|
151
|
+
if (first.startsWith('-')) return `Put the command first, then its options: audienti COMMAND [--workspace ID] [--profile PATH]. "${first}" is an option, not a command. Use audienti --help.`;
|
|
152
|
+
if (first === 'mcp') return 'mcp starts the local MCP server and takes no options. Run: audienti mcp';
|
|
153
|
+
return `"${first}" is not an audienti command. Use audienti --help for the commands. Most commands also take --workspace ID, and --profile PATH when the profile is not set in AUDIENTI_PROFILE.`;
|
|
154
|
+
}
|
|
155
|
+
|
|
64
156
|
async function main() {
|
|
157
|
+
if (args[0] === 'playbook' && args.slice(1).some(value => value === '--help' || value === '-h')) { console.log(playbookHelp(args[1]?.startsWith('-') ? undefined : args[1] === 'draft' && args[2] && !args[2].startsWith('-') ? `draft_${args[2]}` : args[1])); return; }
|
|
158
|
+
if (args[0] === 'mcp' && args.length === 2 && (args[1] === '--help' || args[1] === '-h')) { console.log(MCP_HELP); return; }
|
|
159
|
+
if (args.length > 1 && args.slice(1).some(value => value === '--help' || value === '-h') && !['tools', 'call', 'skills'].includes(args[0])) { commandHelp(); return; }
|
|
65
160
|
if(args[0]==='prospects'&&['intake','conversation'].includes(args[1])){const {accountIntakeCli}=await import('./account-intake.mjs');await accountIntakeCli(args);return;}
|
|
66
161
|
if(args[0]==='sender'){const {senderAccountsCli}=await import('./sender-accounts.mjs');await senderAccountsCli(args);return;}
|
|
67
162
|
if(args[0]==='prospecting'){const {prospectingSettingsCli}=await import('./prospecting-settings.mjs');await prospectingSettingsCli(args);return;}
|
|
68
163
|
if(args[0]==='prospects'&&args[1]==='replies'){const {accountRepliesCli}=await import('./account-replies.mjs');await accountRepliesCli(args);return;}
|
|
69
164
|
if(args[0]==='prospects'&&args[1]==='contacts'){const {recipientsCli}=await import('./recipients.mjs');await recipientsCli(args);return;}
|
|
165
|
+
if(args[0]==='usage'){const {usageCli}=await import('./usage.mjs');await usageCli(args);return;}
|
|
166
|
+
if(args[0]==='intent'){const {intentCli}=await import('./intent.mjs');await intentCli(args);return;}
|
|
167
|
+
if(args[0]==='audit'){const {auditCli}=await import('./audit.mjs');await auditCli(args);return;}
|
|
168
|
+
if(args[0]==='secret'||args[0]==='secrets'){const {secretsCli}=await import('./secrets.mjs');await secretsCli(args);return;}
|
|
169
|
+
if(args[0]==='budgets'){const {budgetsCli}=await import('./budgets.mjs');await budgetsCli(args);return;}
|
|
170
|
+
if(args[0]==='guardrails'||args[0]==='dnc'){const {guardrailsCli}=await import('./guardrails.mjs');await guardrailsCli(args);return;}
|
|
70
171
|
if(args[0]==='prospects'&&args[1]==='suppression'){const {suppressionCli}=await import('./suppression.mjs');await suppressionCli(args);return;}
|
|
172
|
+
if(args[0]==='call'){const {callCli}=await import('./tools.mjs');await callCli(args);return;}
|
|
71
173
|
if(args[0]==='tools'){const {toolsCli}=await import('./tools.mjs');await toolsCli(args);return;}
|
|
72
174
|
if(['topics','posts'].includes(args[0])){const {contentCli}=await import('./content.mjs');await contentCli(args);return;}
|
|
73
175
|
if(args[0]==='work'&&args[1]==='execution'){const {workExecutionCli}=await import('./work-execution.mjs');await workExecutionCli(args);return;}
|
|
74
176
|
if(args[0]==='work'&&args[1]==='changes'){const {workFeedbackCli}=await import('./work-feedback.mjs');await workFeedbackCli(args);return;}
|
|
75
177
|
if(args[0]==='work'){const {workCli}=await import('./work.mjs');await workCli(args);return;}
|
|
76
|
-
if(['prospects','
|
|
77
|
-
if(['
|
|
78
|
-
if(args[0]==='
|
|
178
|
+
if(['prospects','campaigns'].includes(args[0])){const {discoveryCli}=await import('./discovery.mjs');await discoveryCli(args);return;}
|
|
179
|
+
if(args[0]==='analytics'&&['cohorts','aging','filters'].includes(args[1])){const {cohortCli}=await import('./cohorts.mjs');await cohortCli(args);return;}
|
|
180
|
+
if(args[0]==='analytics'&&['outbound','activity'].includes(args[1])){const {outboundCli}=await import('./outbound.mjs');await outboundCli(args);return;}
|
|
181
|
+
if(['playbook','analytics','pipeline','connections'].includes(args[0])){const {progressCli}=await import('./progress.mjs');await progressCli(args);return;}
|
|
182
|
+
if(args[0]==='campaign'){const {campaignCli}=await import('./campaigns.mjs');await campaignCli(args);return;}
|
|
79
183
|
if(args[0]==='audience'){const {audienceCli}=await import('./audiences.mjs');await audienceCli(args);return;}
|
|
184
|
+
if(args[0]==='file'){const {fileCli}=await import('./files.mjs');await fileCli(args);return;}
|
|
185
|
+
if(args[0]==='ask'){const {askCli}=await import('./questions.mjs');await askCli(args);return;}
|
|
186
|
+
if(args[0]==='questions'){const {questionsCli}=await import('./questions.mjs');await questionsCli(args);return;}
|
|
187
|
+
if(args[0]==='hand-tasks'){const {handTasksCli}=await import('./hand-tasks.mjs');await handTasksCli(args);return;}
|
|
188
|
+
if(args[0]==='queue'){const {queueCli}=await import('./queue.mjs');await queueCli(args);return;}
|
|
189
|
+
if(args[0]==='attachments'){const {attachmentsCli}=await import('./attachments.mjs');await attachmentsCli(args);return;}
|
|
190
|
+
if(args[0]==='outcomes'){const {outcomesCli}=await import('./outcomes.mjs');await outcomesCli(args);return;}
|
|
191
|
+
if(args[0]==='rooms'){const {roomsCli}=await import('./rooms.mjs');await roomsCli(args);return;}
|
|
192
|
+
if(args[0]==='kv'){const {kvCli}=await import('./kv.mjs');await kvCli(args);return;}
|
|
80
193
|
if(args[0]==='offer'){const {offerCli}=await import('./offers.mjs');await offerCli(args);return;}
|
|
81
194
|
if (args[0] === 'agent') { const { agentCli } = await import('./agents.mjs'); await agentCli(args); return; }
|
|
82
195
|
if (isAssignmentCommand(args)) { await assignmentCli(args); return; }
|
|
@@ -90,12 +203,19 @@ async function main() {
|
|
|
90
203
|
if (args[0] === 'whoami' && profileIndex > 0 && args[profileIndex + 1]) {
|
|
91
204
|
const { configuration } = await import('./workspaces.mjs');
|
|
92
205
|
profileConfig = configuration(args[profileIndex + 1], 'account:read');
|
|
206
|
+
if (!profileConfig.token) throw new Error('whoami needs a human account token. Agents confirm their connection with: audienti workspace list --profile PATH');
|
|
93
207
|
args.splice(profileIndex, 2);
|
|
208
|
+
} else if (args[0] === 'whoami' && profileIndex < 0 && process.env.AUDIENTI_PROFILE && !(process.env.AUDIENTI_API_URL && process.env.AUDIENTI_API_TOKEN)) {
|
|
209
|
+
// The profile named by AUDIENTI_PROFILE (#448), unless the URL and token are in the environment.
|
|
210
|
+
const { configuration } = await import('./workspaces.mjs');
|
|
211
|
+
profileConfig = configuration(undefined, 'account:read');
|
|
212
|
+
if (!profileConfig.token) throw new Error('whoami needs a human account token, and AUDIENTI_PROFILE holds none. Agents confirm their connection with: audienti workspace list');
|
|
94
213
|
}
|
|
95
|
-
if (args[0] !== 'whoami'
|
|
214
|
+
if (args[0] !== 'whoami') throw new Error(unknownCommandMessage(args));
|
|
215
|
+
if (args.length > 2 || (args[1] && args[1] !== '--json')) throw new Error('whoami takes only --json and --profile PATH. Use audienti --help.');
|
|
96
216
|
const rawUrl = profileConfig ? profileConfig.url : process.env.AUDIENTI_API_URL;
|
|
97
217
|
const token = profileConfig ? profileConfig.token : process.env.AUDIENTI_API_TOKEN;
|
|
98
|
-
if (!rawUrl || !token) throw new Error('Set AUDIENTI_API_URL and AUDIENTI_API_TOKEN. Create a token from your Account page.');
|
|
218
|
+
if (!rawUrl || !token) throw new Error('Set AUDIENTI_API_URL and AUDIENTI_API_TOKEN, or pass --profile PATH (or set AUDIENTI_PROFILE) to a profile with an account:read token. Create a token from your Account page.');
|
|
99
219
|
let base;
|
|
100
220
|
try { base = new URL(rawUrl); } catch { throw new Error('AUDIENTI_API_URL must be a valid API base URL.'); }
|
|
101
221
|
if (base.username || base.password || base.search || base.hash) throw new Error('The API URL must not contain credentials, query parameters, or a fragment.');
|
|
@@ -121,4 +241,4 @@ async function main() {
|
|
|
121
241
|
console.log(args[1] === '--json' ? JSON.stringify({ data: profile }) : `${profile.email ?? profile.username ?? profile.id}\nAccount ID: ${profile.id}`);
|
|
122
242
|
}
|
|
123
243
|
|
|
124
|
-
main().catch(error => { console.error(
|
|
244
|
+
main().catch(error => { console.error(JSON.stringify({ error: error.toJSON ? error.toJSON() : { code: 'client_error', message: error.message } })); process.exitCode = 1; });
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const query = a => new URLSearchParams(Object.entries(a).filter(([k, v]) => k !== 'workspaceId' && v !== undefined).map(([k, v]) => [k, String(v)]));
|
|
3
|
+
export const auditOperations = {
|
|
4
|
+
workspace_audit_log_list: {
|
|
5
|
+
schema: z.object({
|
|
6
|
+
workspaceId: z.string().uuid().optional(),
|
|
7
|
+
actor: z.enum(['person', 'agent']).optional(),
|
|
8
|
+
category: z.enum(['guardrails', 'budgets', 'approvals', 'suppression', 'members', 'agents', 'replies', 'billing', 'playbooks']).optional(),
|
|
9
|
+
since: z.string().datetime().optional(),
|
|
10
|
+
until: z.string().datetime().optional(),
|
|
11
|
+
cursor: z.string().max(500).optional(),
|
|
12
|
+
limit: z.number().int().min(1).max(200).optional(),
|
|
13
|
+
}).strict(),
|
|
14
|
+
method: 'GET', path: a => `/workspaces/${a.workspaceId}/audit-events?${query(a)}`, scoped: true,
|
|
15
|
+
description: 'List the read-only workspace audit log: who changed guardrails, budgets, approvals, suppression, members, agent access and playbooks (who saved which version), newest first. Admin only. Page with cursor.',
|
|
16
|
+
},
|
|
17
|
+
};
|
package/cli/audit.mjs
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { callWorkspace, configuration } from './workspaces.mjs';
|
|
2
|
+
|
|
3
|
+
const UNITS = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 };
|
|
4
|
+
export function sinceToIso(value, now = Date.now()) {
|
|
5
|
+
const match = /^(\d{1,4})([mhdw])$/.exec(value);
|
|
6
|
+
if (match) return new Date(now - Number(match[1]) * UNITS[match[2]]).toISOString();
|
|
7
|
+
const date = new Date(value);
|
|
8
|
+
if (Number.isNaN(date.getTime())) throw Error('--since must look like 7d, 12h or an ISO date.');
|
|
9
|
+
return date.toISOString();
|
|
10
|
+
}
|
|
11
|
+
const cell = value => /[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
|
|
12
|
+
export function auditCsv(items) {
|
|
13
|
+
const rows = items.map(item => [item.at, item.actor?.kind ?? '', item.actor?.name ?? '', item.category, item.action, item.summary, item.object?.label ?? '', item.object?.href ?? '']);
|
|
14
|
+
return [['when', 'actor_kind', 'actor', 'category', 'action', 'summary', 'object', 'link'], ...rows].map(row => row.map(cell).join(',')).join('\n') + '\n';
|
|
15
|
+
}
|
|
16
|
+
export async function auditCli(args) {
|
|
17
|
+
const flags = {}, positions = [];
|
|
18
|
+
for (let i = 0; i < args.length; i++) {
|
|
19
|
+
const arg = args[i];
|
|
20
|
+
if (arg === '--json') continue;
|
|
21
|
+
if (!arg.startsWith('--')) { positions.push(arg); continue; }
|
|
22
|
+
const key = arg.slice(2);
|
|
23
|
+
if (!['workspace', 'profile', 'since', 'until', 'actor', 'category', 'limit', 'cursor', 'format'].includes(key) || Object.hasOwn(flags, key) || i + 1 >= args.length) throw Error(`Invalid flag --${key}.`);
|
|
24
|
+
flags[key] = args[++i];
|
|
25
|
+
}
|
|
26
|
+
if (positions.length !== 2 || positions[1] !== 'list') throw Error('Use audit list [--workspace ID] [--since 7d] [--actor agent|person] [--format json|csv].');
|
|
27
|
+
if (flags.actor && !['agent', 'person'].includes(flags.actor)) throw Error('--actor must be agent or person.');
|
|
28
|
+
if (flags.format && !['json', 'csv'].includes(flags.format)) throw Error('--format must be json or csv.');
|
|
29
|
+
const input = { workspaceId: flags.workspace };
|
|
30
|
+
if (flags.actor) input.actor = flags.actor;
|
|
31
|
+
if (flags.category) input.category = flags.category;
|
|
32
|
+
if (flags.since) input.since = sinceToIso(flags.since);
|
|
33
|
+
if (flags.until) input.until = sinceToIso(flags.until);
|
|
34
|
+
if (flags.cursor) input.cursor = flags.cursor;
|
|
35
|
+
if (flags.limit) { input.limit = Number(flags.limit); if (!Number.isInteger(input.limit)) throw Error('--limit must be a whole number.'); }
|
|
36
|
+
const result = await callWorkspace('workspace_audit_log_list', input, configuration(flags.profile));
|
|
37
|
+
if (flags.format === 'csv') { process.stdout.write(auditCsv((result?.data ?? result)?.items ?? [])); return; }
|
|
38
|
+
console.log(JSON.stringify(result));
|
|
39
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const workspace = { workspaceId: z.string().uuid().optional() };
|
|
3
|
+
const cap = z.number().int().min(0).max(10000000).nullable();
|
|
4
|
+
export const budgetOperations = {
|
|
5
|
+
workspace_budgets_get: { schema: z.object(workspace).strict(), method: 'GET', path: a => `/workspaces/${a.workspaceId}/budgets`, scoped: true, description: 'Read spend budgets: credits used this UTC month, each agent’s monthly cap (null means unlimited), the cap for newly registered agents, what happens at a cap and the 80% warning switch (Operator and email) and the ten latest alerts.' },
|
|
6
|
+
workspace_budget_alerts: { schema: z.object({ ...workspace, limit: z.number().int().min(1).max(200).optional() }).strict(), method: 'GET', path: a => `/workspaces/${a.workspaceId}/budget-alerts${a.limit ? `?limit=${a.limit}` : ''}`, scoped: true, description: 'List recent low-credit and budget alerts, newest first. Workspace credits and each agent’s monthly cap alert once per UTC month at 80% and at 100%; owners and admins are emailed and see them in Operator.' },
|
|
7
|
+
workspace_budgets_set: { schema: z.object({ ...workspace, agentCaps: z.array(z.object({ agentId: z.string().uuid(), monthlyCap: cap }).strict()).max(200).optional(), newAgentCap: cap.optional(), atLimit: z.enum(['pause', 'ask']).optional(), alert80: z.boolean().optional(), expectedVersion: z.number().int().min(0).optional() }).strict(), method: 'POST', path: a => `/workspaces/${a.workspaceId}/budgets`, body: ({ workspaceId, ...rest }) => rest, scoped: true, description: 'Change spend budgets. Send only the fields to change; null removes a cap. Admin only and only a person: an agent cannot raise its own cap. An agent at its cap gets budget_exceeded on hosted tool calls until the month resets or the cap is raised.' },
|
|
8
|
+
};
|
package/cli/budgets.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { callWorkspace, configuration } from './workspaces.mjs';
|
|
2
|
+
const cap = (name, value) => {
|
|
3
|
+
if (value === 'none' || value === 'unlimited') return null;
|
|
4
|
+
if (!/^\d+$/.test(value ?? '')) throw Error(`--${name} needs a whole number of credits, or "none" for no cap.`);
|
|
5
|
+
return Number(value);
|
|
6
|
+
};
|
|
7
|
+
export async function budgetsCli(args) {
|
|
8
|
+
const flags = {}, positions = [];
|
|
9
|
+
for (let i = 0; i < args.length; i++) {
|
|
10
|
+
const arg = args[i];
|
|
11
|
+
if (arg === '--json') continue;
|
|
12
|
+
if (!arg.startsWith('--')) { positions.push(arg); continue; }
|
|
13
|
+
const key = arg.slice(2);
|
|
14
|
+
if (!['workspace', 'profile', 'agent', 'cap', 'new-agent-cap', 'at-limit', 'alert80', 'limit'].includes(key) || Object.hasOwn(flags, key) || i + 1 >= args.length) throw Error(`Invalid flag --${key}.`);
|
|
15
|
+
flags[key] = args[++i];
|
|
16
|
+
}
|
|
17
|
+
if (positions.length !== 2 || positions[0] !== 'budgets' || !['show', 'set', 'alerts'].includes(positions[1])) throw Error('Use budgets show|set|alerts --workspace ID. See audienti help.');
|
|
18
|
+
const input = { workspaceId: flags.workspace };
|
|
19
|
+
let name = 'workspace_budgets_get';
|
|
20
|
+
if (positions[1] === 'alerts') {
|
|
21
|
+
name = 'workspace_budget_alerts';
|
|
22
|
+
if (flags.limit !== undefined) { if (!/^\d+$/.test(flags.limit) || Number(flags.limit) < 1 || Number(flags.limit) > 200) throw Error('--limit is a whole number from 1 to 200.'); input.limit = Number(flags.limit); }
|
|
23
|
+
}
|
|
24
|
+
if (positions[1] === 'set') {
|
|
25
|
+
name = 'workspace_budgets_set';
|
|
26
|
+
if ((flags.agent === undefined) !== (flags.cap === undefined)) throw Error('--agent and --cap go together.');
|
|
27
|
+
if (flags.agent) input.agentCaps = [{ agentId: flags.agent, monthlyCap: cap('cap', flags.cap) }];
|
|
28
|
+
if (flags['new-agent-cap'] !== undefined) input.newAgentCap = cap('new-agent-cap', flags['new-agent-cap']);
|
|
29
|
+
if (flags['at-limit'] !== undefined) { if (!['pause', 'ask'].includes(flags['at-limit'])) throw Error('--at-limit is pause or ask.'); input.atLimit = flags['at-limit']; }
|
|
30
|
+
if (flags.alert80 !== undefined) { if (!['on', 'off'].includes(flags.alert80)) throw Error('--alert80 is on or off.'); input.alert80 = flags.alert80 === 'on'; }
|
|
31
|
+
if (Object.keys(input).length < 2) throw Error('Nothing to change. Use --agent ID --cap N, --new-agent-cap N, --at-limit pause|ask or --alert80 on|off.');
|
|
32
|
+
}
|
|
33
|
+
console.log(JSON.stringify(await callWorkspace(name, input, configuration(flags.profile))));
|
|
34
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import {HostedResponseUnknown} from './workspaces.mjs';
|
|
3
|
+
// #257: find N prospects for a Campaign. Searches LinkedIn with the Audience filters, then asks the server
|
|
4
|
+
// to check each new person. The server fetches, runs the rules and records the result; this file only
|
|
5
|
+
// drives the loop and adds up the spend. Amounts are pico USD (1 credit = 10,000,000,000).
|
|
6
|
+
export const PICO_PER_CREDIT=10_000_000_000n;
|
|
7
|
+
// Waits before each retry of a check whose outcome is unknown, in milliseconds.
|
|
8
|
+
const RECOVERY_WAITS=[2000,5000,15000];
|
|
9
|
+
const OUTCOMES=['fit','held','not_fit','already_found'];
|
|
10
|
+
// Only a definite answer lets the run go on. A check that is still open, a lost response or a server
|
|
11
|
+
// error may still be paying, so the same request ID is retried; anything else unexpected stops the run.
|
|
12
|
+
const pending=error=>error instanceof HostedResponseUnknown||error?.code==='check_running'||error?.status>=500&&!['tool_unavailable','history_policy_unavailable'].includes(error?.code);
|
|
13
|
+
// A refusal about this one person (a bad URL, no LinkedIn profile) is final, and the run moves on.
|
|
14
|
+
const skippable=error=>[400,404,422].includes(error?.status);
|
|
15
|
+
const MAX_SEARCHES=12,MAX_PAGES=10;
|
|
16
|
+
const positive=list=>(list??[]).filter(item=>!item.negative);
|
|
17
|
+
const numeric=value=>typeof value==='string'&&/^\d{1,20}$/.test(value);
|
|
18
|
+
// A charge the server reported for one request. Charges are cumulative per request ID, so the largest one
|
|
19
|
+
// seen across attempts is the request's charge so far.
|
|
20
|
+
const reportedCharge=value=>numeric(value)?BigInt(value):0n;
|
|
21
|
+
|
|
22
|
+
/** One profiles.search input per title, location and keyword combination the Audience and Campaign name. */
|
|
23
|
+
export function planSearches(audience,signals=[]){
|
|
24
|
+
const titles=positive(audience.person?.currentTitles).map(item=>item.name).filter(Boolean).slice(0,5);
|
|
25
|
+
// #281: the people search has no company region filter, so with no person location the company's region is
|
|
26
|
+
// searched as where the person is. Without it the search pays to check people anywhere in the world.
|
|
27
|
+
const places=positive(audience.person?.locations).length?positive(audience.person?.locations):positive(audience.company?.locations);
|
|
28
|
+
const locations=places.slice(0,3).map(item=>numeric(item.providerId)?{geoId:item.providerId}:{location:item.name});
|
|
29
|
+
// #322: the search takes 20 industry ids at a time, so a longer list is split across searches, never cut.
|
|
30
|
+
const industryIds=[...new Set(positive(audience.company?.industries).map(item=>item.providerId).filter(numeric))];
|
|
31
|
+
const industryChunks=[];for(let i=0;i<industryIds.length;i+=20)industryChunks.push(industryIds.slice(i,i+20));
|
|
32
|
+
// A topic signal is a keyword people use; research and profile signals are judged after the fetch, not searched.
|
|
33
|
+
const queries=[...new Set([audience.discoveryKeyword,...signals.filter(signal=>signal.kind==='topic').map(signal=>signal.topic)].map(value=>value?.trim()).filter(Boolean))].slice(0,3);
|
|
34
|
+
// At most MAX_SEARCHES title, place and keyword combinations. Each one is searched across every industry chunk, so
|
|
35
|
+
// a long industry list never pushes a title out of the plan. The credit cap still bounds what the searches cost.
|
|
36
|
+
const combos=[];
|
|
37
|
+
for(const title of titles.length?titles:[undefined])for(const place of locations.length?locations:[{}])for(const query of queries.length?queries:[undefined])combos.push({kind:'person',...(title?{title}:{}),...place,...(query?{query}:{})});
|
|
38
|
+
const searches=[];
|
|
39
|
+
for(const combo of combos.slice(0,MAX_SEARCHES))for(const ids of industryChunks.length?industryChunks:[undefined]){
|
|
40
|
+
const input={...combo,...(ids?{industryIds:ids}:{})};
|
|
41
|
+
if(input.title||input.query||input.geoId||input.location||input.industryIds)searches.push(input);
|
|
42
|
+
}
|
|
43
|
+
return searches;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function parseCredits(value){
|
|
47
|
+
if(typeof value!=='string'||!/^\d{1,7}(\.\d{1,4})?$/.test(value))throw new Error('Set --max-credits to a number of credits, like 50 or 12.5.');
|
|
48
|
+
const [whole,fraction='']=value.split('.');
|
|
49
|
+
return BigInt(whole)*PICO_PER_CREDIT+BigInt(fraction.padEnd(4,'0'))*(PICO_PER_CREDIT/10_000n);
|
|
50
|
+
}
|
|
51
|
+
export const credits=pico=>{const whole=pico/PICO_PER_CREDIT,rest=(pico%PICO_PER_CREDIT)*10_000n/PICO_PER_CREDIT;return rest?`${whole}.${rest.toString().padStart(4,'0').replace(/0+$/,'')}`:`${whole}`;};
|
|
52
|
+
const charged=data=>data?.billing?.status==='charged'&&/^\d+$/.test(data.billing.amount??'')?BigInt(data.billing.amount):0n;
|
|
53
|
+
// A search is final once its outcome is known and its charge has settled.
|
|
54
|
+
const searchSettled=data=>['succeeded','failed','rejected'].includes(data?.status)&&(data.billing?.status==='not_charged'||charged(data)>0n||data.billing?.status==='charged'&&data.billing.amount==='0');
|
|
55
|
+
const personUrl=url=>typeof url==='string'&&/^https:\/\/([a-z]{2,3}\.)?(www\.)?linkedin\.com\/in\//i.test(url);
|
|
56
|
+
|
|
57
|
+
async function settled(call,workspaceId,data,wait){
|
|
58
|
+
for(let tries=0;data?.operationId&&!searchSettled(data)&&data.status!=='uncertain'&&tries<30;tries++){await wait(2000);data=(await call('tools_runs_get',{workspaceId,operationId:data.operationId})).data;}
|
|
59
|
+
return data;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Searches and checks until `count` new fits are found, the searches run out, or the next paid call could pass
|
|
64
|
+
* `maxCredits`. A search runs only when its published price fits what is left. Each check sends what is left as
|
|
65
|
+
* `maxCharge`, and the server refuses a check whose worst case (both profile fetches paid) could pass it.
|
|
66
|
+
*/
|
|
67
|
+
export async function findCampaignProspects(call,{workspaceId,campaignId,count,maxCredits},{wait=ms=>new Promise(resolve=>setTimeout(resolve,ms)),progress=()=>{}}={}){
|
|
68
|
+
const {data:campaign}=await call('campaign_get',{workspaceId,campaignId});
|
|
69
|
+
const fields=campaign.revision.fields;
|
|
70
|
+
if(!['Draft','Preparing','Active'].includes(campaign.campaign.state))throw new Error('This campaign is not finding prospects. Pick a Draft, Preparing or Active campaign.');
|
|
71
|
+
const {data:audience}=await call('audience_get',{workspaceId,audienceId:fields.audienceId,revision:fields.audienceRevision});
|
|
72
|
+
// #322: the search cannot apply an older audience's industry group, so it would pay to check people in any
|
|
73
|
+
// industry. Refuse before any paid call; named industries are searched.
|
|
74
|
+
const company=audience.revision.fields.company;
|
|
75
|
+
if(company?.industryGroups?.length&&!positive(company.industries).length)throw new Error("This campaign's audience uses an older industry group, which the LinkedIn search cannot apply. Name the industries in the audience instead (audienti audience options --kind industries --q TEXT), then try again.");
|
|
76
|
+
const searches=planSearches(audience.revision.fields,fields.signals);
|
|
77
|
+
// #323: rules that will reject people (a named title below the seniority floor) are shown before the first paid call.
|
|
78
|
+
const warnings=audience.revision.warnings??[];
|
|
79
|
+
for(const warning of warnings)progress({warning});
|
|
80
|
+
if(!searches.length)throw new Error("This campaign's audience has no title, location, industry or keyword to search by. Add one, then try again.");
|
|
81
|
+
const {data:tool}=await call('tools_get',{workspaceId,tool:'profiles.search'});
|
|
82
|
+
if(!/^\d{1,20}$/.test(tool?.price?.picoUsd??''))throw new Error('The LinkedIn search has no fixed price right now, so the credit cap cannot be kept. Try again later.');
|
|
83
|
+
const searchPrice=BigInt(tool.price.picoUsd);
|
|
84
|
+
const report={campaignId,state:campaign.campaign.state,target:count,maxCredits:credits(maxCredits),spentCredits:'0',spent:'0',searches:0,checked:0,fit:0,held:0,notFit:0,alreadyFound:0,failed:0,stoppedBecause:'searches_exhausted',fits:[],heldPeople:[],...(warnings.length?{audienceWarnings:warnings}:{})};
|
|
85
|
+
let spent=0n;const seen=new Set();
|
|
86
|
+
const finish=reason=>{report.stoppedBecause=reason;report.spent=spent.toString();report.spentCredits=credits(spent);return report;};
|
|
87
|
+
// The check may have paid more than it reported; the rest is recovered with the same request ID.
|
|
88
|
+
const unknown=(url,requestId,error)=>{report.unknownCheck={url,requestId,code:error?.code??'response_unknown'};return finish('outcome_unknown');};
|
|
89
|
+
for(const input of searches){
|
|
90
|
+
for(let page=1;page&&page<=MAX_PAGES;){
|
|
91
|
+
if(report.fit>=count)return finish('count_reached');
|
|
92
|
+
if(spent+searchPrice>maxCredits)return finish('credit_cap');
|
|
93
|
+
// Search results are not saved as People; only a person the check fetches joins People.
|
|
94
|
+
// Nothing else pays until this search has settled: a search still running, uncertain or with a charge not
|
|
95
|
+
// yet final is retried with the same request ID, and if it never settles the run stops and names it.
|
|
96
|
+
const search={workspaceId,requestId:randomUUID(),input:{...input,...(page>1?{page}:{}),saveProfiles:false}};
|
|
97
|
+
let data=null,failure=null,paid=0n;
|
|
98
|
+
for(let attempt=0;;attempt++){
|
|
99
|
+
try{data=await settled(call,workspaceId,(await call('tools_profiles_search',search)).data,wait);failure=null;}
|
|
100
|
+
catch(error){if(!pending(error))throw error;failure=error;}
|
|
101
|
+
if(!failure&&charged(data)>paid)paid=charged(data);
|
|
102
|
+
if(!failure&&searchSettled(data))break;
|
|
103
|
+
if(attempt>=RECOVERY_WAITS.length){
|
|
104
|
+
spent+=paid;report.searches++;
|
|
105
|
+
report.unknownSearch={requestId:search.requestId,operationId:data?.operationId??null,code:failure?.code??data?.error?.code??data?.status??'response_unknown'};
|
|
106
|
+
return finish('outcome_unknown');
|
|
107
|
+
}
|
|
108
|
+
await wait(RECOVERY_WAITS[attempt]);
|
|
109
|
+
}
|
|
110
|
+
spent+=paid;report.searches++;
|
|
111
|
+
if(data?.status!=='succeeded'){if(data?.error?.code==='insufficient_credits')return finish('no_credits');break;}
|
|
112
|
+
const items=(data.result?.items??[]).filter(item=>personUrl(item.url)&&!seen.has(item.url));
|
|
113
|
+
for(const item of items){
|
|
114
|
+
seen.add(item.url);
|
|
115
|
+
if(report.fit>=count)return finish('count_reached');
|
|
116
|
+
if(spent>=maxCredits)return finish('credit_cap');
|
|
117
|
+
// Nothing else pays until this check has a definite answer. The same request ID replays the stored
|
|
118
|
+
// outcome and charge; if no definite answer comes, the run stops and names the check to recover.
|
|
119
|
+
const args={workspaceId,campaignId,url:item.url,requestId:randomUUID(),maxCharge:(maxCredits-spent).toString()};
|
|
120
|
+
// Every attempt's reported charge is kept, and the largest is counted once on every way out.
|
|
121
|
+
let result,failure,paid=0n;
|
|
122
|
+
for(let attempt=0;;attempt++){
|
|
123
|
+
try{result=(await call('campaign_prospect_check',args)).data;failure=null;}
|
|
124
|
+
catch(error){result=null;failure=error;}
|
|
125
|
+
const reported=reportedCharge(failure?failure.charged:result?.charged);
|
|
126
|
+
if(reported>paid)paid=reported;
|
|
127
|
+
if(!failure&&!OUTCOMES.includes(result?.outcome)){failure={code:'invalid_response'};break;}
|
|
128
|
+
if(!failure||!pending(failure)||attempt>=RECOVERY_WAITS.length)break;
|
|
129
|
+
await wait(RECOVERY_WAITS[attempt]);
|
|
130
|
+
}
|
|
131
|
+
spent+=paid;
|
|
132
|
+
if(failure){
|
|
133
|
+
const error=failure;
|
|
134
|
+
if(pending(error)||error.code==='invalid_response')return unknown(item.url,args.requestId,error);
|
|
135
|
+
if(error.code==='check_over_budget')return finish('credit_cap');
|
|
136
|
+
if(error.status===402)return finish('no_credits');
|
|
137
|
+
if(error.code==='campaign_not_active')return finish('campaign_not_active');
|
|
138
|
+
if(['tool_unavailable','history_policy_unavailable'].includes(error.code))return finish('tool_unavailable');
|
|
139
|
+
if(!skippable(error))return unknown(item.url,args.requestId,error);
|
|
140
|
+
report.failed++;progress({url:item.url,outcome:'failed',code:error.code,spent:credits(spent)});continue;
|
|
141
|
+
}
|
|
142
|
+
report.checked++;
|
|
143
|
+
const who={prospectId:result.prospectId,url:item.url,name:item.name??null,reason:result.assessment?.fit?.reason??null};
|
|
144
|
+
if(result.outcome==='fit'){report.fit++;report.fits.push({...who,admission:result.assessment?.admission});}
|
|
145
|
+
else if(result.outcome==='held'){report.held++;report.heldPeople.push({...who,reason:result.assessment?.reason??null});}
|
|
146
|
+
else if(result.outcome==='not_fit')report.notFit++;
|
|
147
|
+
else report.alreadyFound++;
|
|
148
|
+
progress({url:item.url,outcome:result.outcome,spent:credits(spent)});
|
|
149
|
+
}
|
|
150
|
+
// Follow the next page even when this one had only people already seen; MAX_PAGES still bounds it.
|
|
151
|
+
page=data.result?.nextPage>page?data.result.nextPage:0;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return finish(report.fit>=count?'count_reached':'searches_exhausted');
|
|
155
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {z} from 'zod';
|
|
2
|
+
const uuid=z.string().uuid(),workspace={workspaceId:uuid.optional()},locator={...workspace,campaignId:uuid};
|
|
3
|
+
const state=z.enum(['Draft','Preparing','Active','Paused','Closing','Archived']);
|
|
4
|
+
const signalBase={id:uuid,scope:z.enum(['company','person']),details:z.string().optional()};
|
|
5
|
+
const signal=z.discriminatedUnion('kind',[
|
|
6
|
+
z.object({...signalBase,kind:z.literal('research'),question:z.string(),expected:z.boolean().optional()}).strict(),
|
|
7
|
+
z.object({...signalBase,kind:z.literal('topic'),topic:z.string()}).strict(),
|
|
8
|
+
z.object({...signalBase,kind:z.literal('profile'),url:z.string(),track:z.enum(['audience','activity']).optional(),interactions:z.array(z.enum(['comments','reactions'])).optional()}).strict(),
|
|
9
|
+
]);
|
|
10
|
+
const fields=z.object({name:z.string(),audienceId:uuid,audienceRevision:z.number().int(),offerId:uuid,offerRevision:z.number().int(),premise:z.string().optional(),playbookPin:z.object({id:uuid,revision:z.number().int().positive()}).strict().optional(),notes:z.string().optional(),ownerUserId:uuid.nullable().optional(),tags:z.array(z.string()).optional(),signalMatch:z.enum(['any','all']).optional(),signals:z.array(signal).optional(),method:z.enum(['signals','listen','track-audience','track-engagement','custom']).optional(),findingInstructions:z.string().optional(),targets:z.discriminatedUnion('kind',[
|
|
11
|
+
z.object({kind:z.literal('none'),values:z.array(z.never())}).strict(),
|
|
12
|
+
z.object({kind:z.literal('companies'),values:z.array(z.object({type:z.enum(['domain','linkedin-company']),value:z.string()}).strict())}).strict(),
|
|
13
|
+
]).optional(),channels:z.array(z.enum(['email','linkedin'])).optional(),approvalMode:z.literal('manual').optional(),contentOpsEnabled:z.boolean().optional(),schedule:z.object({startAt:z.string().nullable().optional(),endAt:z.string().nullable().optional(),maxCompanies:z.number().int().nullable().optional()}).strict().optional()}).strict();
|
|
14
|
+
const path=a=>`/workspaces/${a.workspaceId}/campaigns`,detail=a=>path(a)+`/${a.campaignId}`;
|
|
15
|
+
const qs=a=>new URLSearchParams(Object.fromEntries(Object.entries(a).filter(([k,v])=>!['workspaceId','campaignId'].includes(k)&&v!==undefined).map(([k,v])=>[k,String(v)])));
|
|
16
|
+
export const campaignOperations={
|
|
17
|
+
campaign_summary:{schema:z.object({...workspace}).strict(),method:'GET',path:a=>`/workspaces/${a.workspaceId}/campaign-summary`,scoped:true,description:'Counts of Campaigns per state, and per Campaign its Audience, offer, playbook, goal stage, methods, people, engaged and at-goal counts since start.'},
|
|
18
|
+
campaign_list:{schema:z.object({...workspace,state:state.optional(),archived:z.boolean().optional(),q:z.string().optional(),limit:z.number().int().optional(),after:uuid.optional()}).strict(),method:'GET',path:a=>path(a)+'?'+qs(a),scoped:true},
|
|
19
|
+
campaign_get:{schema:z.object({...locator,revision:z.number().int().optional()}).strict(),method:'GET',path:a=>detail(a)+'?'+qs(a),scoped:true},
|
|
20
|
+
campaign_events:{schema:z.object({...locator,limit:z.number().int().optional(),after:uuid.optional()}).strict(),method:'GET',path:a=>detail(a)+'/events?'+qs(a),scoped:true},
|
|
21
|
+
campaign_create:{schema:z.object({...workspace,requestId:uuid,fields}).strict(),method:'POST',path,body:a=>({requestId:a.requestId,fields:a.fields}),scoped:true},
|
|
22
|
+
campaign_update:{schema:z.object({...locator,expectedRevision:z.number().int(),fields}).strict(),method:'POST',path:a=>detail(a)+'/revisions',body:a=>({expectedRevision:a.expectedRevision,fields:a.fields}),scoped:true},
|
|
23
|
+
campaign_transition:{schema:z.object({...locator,expectedState:state,operation:z.enum(['prepare','activate','pause','resume','close','archive','restore']),reason:z.string().optional()}).strict(),method:'POST',path:a=>detail(a)+'/transitions',body:a=>({expectedState:a.expectedState,operation:a.operation,...(a.reason===undefined?{}:{reason:a.reason})}),scoped:true,description:'Move a Campaign through its lifecycle. prepare: Draft to Preparing (signal tracking and prospect finding run, no engagement). activate: Draft or Preparing to Active (finding and engagement run). pause: stop automation. resume: back to the paused state. close: Active to Closing (finding stops, engagement continues). archive: stop everything and hide it. restore: Archived to Paused, or Draft for a draft. Agents do not start or activate campaigns; the user does. A campaign that cannot run is refused with campaign_not_ready and its missing items in blockers.'},
|
|
24
|
+
campaign_pace_get:{schema:z.object({...locator}).strict(),method:'GET',path:a=>detail(a)+'/pace',scoped:true,description:'Read a Campaign pace: new people a day. Derived is 25 a day per confirmed LinkedIn account, each capped by its reported connection-request limit; an email-only Campaign uses its own number, 50 by default, within mailbox limits. The reply names the LinkedIn accounts, the weekly figure and the expected daily credits for hosted lookups.'},
|
|
25
|
+
campaign_pace_set:{schema:z.object({...locator,perDay:z.union([z.number().int().min(1).max(1000),z.literal('derived')]).optional(),maxCredits:z.number().int().min(1).max(100000).nullable().optional()}).strict().refine(a=>a.perDay!==undefined||a.maxCredits!==undefined,{message:'Send perDay, maxCredits or both.'}),method:'POST',path:a=>detail(a)+'/pace',body:a=>({...(a.perDay===undefined?{}:{perDay:a.perDay}),...(a.maxCredits===undefined?{}:{maxCredits:a.maxCredits})}),scoped:true,description:'Save a Campaign pace. Pass the number the user gave, or "derived" to follow the confirmed sending accounts. An owner number stays until changed and is still capped by LinkedIn account and mailbox limits. maxCredits saves the credits a day the user approved for finding (null removes it); each day\'s find task carries it.'},
|
|
26
|
+
campaign_targets_get:{schema:z.object({...locator,limit:z.number().int().min(1).max(500).optional(),after:z.string().regex(/^\d{1,7}$/).optional()}).strict(),method:'GET',path:a=>detail(a)+'/targets?'+qs(a),scoped:true,description:'Read a Campaign\'s target companies in pages of up to 500: domains and LinkedIn company URLs. Only people whose current company is one of them can join.'},
|
|
27
|
+
campaign_targets_change:{schema:z.object({...locator,expectedRevision:z.number().int().positive(),add:z.array(z.string()).optional(),remove:z.array(z.string()).optional(),set:z.array(z.string()).optional()}).strict().refine(a=>(a.set===undefined)!==(a.add===undefined&&a.remove===undefined),{message:'Send set, or add and or remove.'}),method:'POST',path:a=>detail(a)+'/targets',body:a=>({expectedRevision:a.expectedRevision,...Object.fromEntries(['add','remove','set'].filter(k=>a[k]!==undefined).map(k=>[k,a[k]]))}),scoped:true,description:'Change a Campaign\'s target companies: add or remove domains (acme.com) and LinkedIn company URLs, or replace them all with set. Saves a new Campaign revision; an empty set removes the targets.'},
|
|
28
|
+
campaign_prospect_check:{schema:z.object({...locator,url:z.string().max(1024),requestId:uuid,maxCharge:z.string().regex(/^\d{1,20}$/).optional()}).strict(),method:'POST',path:a=>detail(a)+'/prospect-checks',body:a=>({url:a.url,requestId:a.requestId,...(a.maxCharge!==undefined?{maxCharge:a.maxCharge}:{})}),scoped:true,recoverable:true,timeoutMs:90000,description:'Check one LinkedIn person URL for a Campaign and record the result. Fetches the person and current company (saved profiles are reused free; otherwise each fetch spends hosted credits), runs the pinned Audience rules and records a qualification with the profiles as evidence. outcome fit: admitted, or shortlisted while the Campaign is a Draft. held: an agent must judge a smart rule, a signal or an undecided rule. not_fit: a rule failed. already_found: already in or shortlisted for this Campaign; nothing written. charged and balance are pico USD (1 credit = 10,000,000,000). Generate requestId once and reuse it after an interruption so a retry never pays twice.'},
|
|
29
|
+
campaign_successor:{schema:z.object({...locator,requestId:uuid,expectedRevision:z.number().int(),fields}).strict(),method:'POST',path:a=>detail(a)+'/successors',body:a=>({requestId:a.requestId,expectedRevision:a.expectedRevision,fields:a.fields}),scoped:true},
|
|
30
|
+
};
|