@sellable/mcp 0.1.501 → 0.1.503
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/api.d.ts +5 -5
- package/dist/api.js +10 -10
- package/dist/index-dev.js +0 -0
- package/dist/index.js +0 -0
- package/dist/server.js +2 -2
- package/dist/tools/campaign-fill-routing.d.ts +5 -0
- package/dist/tools/campaign-fill-routing.js +13 -3
- package/dist/tools/campaign-message-preparation.d.ts +7 -13
- package/dist/tools/campaign-message-preparation.js +21 -24
- package/dist/tools/campaign-processing.d.ts +19 -0
- package/dist/tools/campaign-processing.js +31 -8
- package/dist/tools/campaign-refill-state.d.ts +5 -0
- package/dist/tools/campaign-refill-state.js +13 -3
- package/dist/tools/leads.d.ts +6 -47
- package/dist/tools/leads.js +26 -30
- package/dist/tools/prompts.js +1 -1
- package/dist/tools/readiness.d.ts +6 -0
- package/dist/tools/readiness.js +12 -5
- package/dist/tools/refill-sends.d.ts +34 -32
- package/dist/tools/refill-sends.js +67 -586
- package/dist/tools/refill-target-plan.d.ts +5 -0
- package/dist/tools/refill-target-plan.js +24 -50
- package/dist/tools/registry.d.ts +205 -47
- package/dist/tools/scheduler-fill-capacity.d.ts +5 -0
- package/dist/tools/scheduler-fill-capacity.js +13 -3
- package/dist/tools/sender-routing.d.ts +8 -1
- package/dist/tools/sender-routing.js +12 -3
- package/dist/tools/senders.d.ts +14 -1
- package/dist/tools/senders.js +31 -5
- package/dist/tools/workspace-context.d.ts +36 -0
- package/dist/tools/workspace-context.js +39 -0
- package/package.json +1 -1
- package/skills/refill-sends/SKILL.md +49 -28
- package/skills/refill-sends-workflow/SKILL.md +15 -10
|
@@ -1,15 +1,7 @@
|
|
|
1
|
-
import { getApi, SellableApiError } from "../api.js";
|
|
2
|
-
import { startPrepareCampaignMessages } from "./campaign-message-preparation.js";
|
|
3
|
-
import { confirmLeadList, importLeads, searchSignals, selectPromisingPosts, } from "./leads.js";
|
|
4
|
-
import { markProviderPromptLoaded } from "./provider-preflight.js";
|
|
5
1
|
import { getRefillTargetPlan } from "./refill-target-plan.js";
|
|
6
2
|
import { refreshPaidInmailCredits } from "./senders.js";
|
|
3
|
+
import { createWorkspaceContext, normalizeExplicitWorkspaceId, } from "./workspace-context.js";
|
|
7
4
|
const DEFAULT_SCHEDULER_FORWARD_HOURS = 48;
|
|
8
|
-
const PAID_INMAIL_REFRESH_MAX_ATTEMPTS = 3;
|
|
9
|
-
const PAID_INMAIL_REFRESH_RETRY_DELAY_MS = Number(process.env.SELLABLE_MCP_PAID_REFRESH_RETRY_DELAY_MS ?? "1000");
|
|
10
|
-
const SIGNAL_DISCOVERY_MIN_REFILL_POSTS = 3;
|
|
11
|
-
const SIGNAL_DISCOVERY_MAX_REFILL_POSTS = 10;
|
|
12
|
-
const SIGNAL_DISCOVERY_TARGET_ROWS_PER_POST = 150;
|
|
13
5
|
function normalizeStrings(values) {
|
|
14
6
|
if (!Array.isArray(values))
|
|
15
7
|
return [];
|
|
@@ -19,11 +11,6 @@ function normalizeStrings(values) {
|
|
|
19
11
|
.filter(Boolean)),
|
|
20
12
|
];
|
|
21
13
|
}
|
|
22
|
-
function sleep(ms) {
|
|
23
|
-
if (!Number.isFinite(ms) || ms <= 0)
|
|
24
|
-
return Promise.resolve();
|
|
25
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
26
|
-
}
|
|
27
14
|
function normalizeHorizonSendDays(value) {
|
|
28
15
|
if (value === undefined || value === null)
|
|
29
16
|
return null;
|
|
@@ -69,24 +56,10 @@ function normalizeTargetDate(value) {
|
|
|
69
56
|
}
|
|
70
57
|
return trimmed;
|
|
71
58
|
}
|
|
72
|
-
function userAddedRowsLimitPayloadFromError(error) {
|
|
73
|
-
if (!(error instanceof SellableApiError) || error.status !== 400) {
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
try {
|
|
77
|
-
const parsed = JSON.parse(error.body);
|
|
78
|
-
if (parsed?.code !== "USER_ADDED_ROWS_LIMIT_EXCEEDED")
|
|
79
|
-
return null;
|
|
80
|
-
return parsed;
|
|
81
|
-
}
|
|
82
|
-
catch {
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
59
|
export const refillSendsToolDefinitions = [
|
|
87
60
|
{
|
|
88
61
|
name: "refill_sends",
|
|
89
|
-
description: "Typed command entrypoint for Sellable refill sends. Accepts --yolo semantics and optional sender selectors, then returns the bounded execution contract for the skill-led refill workflow. In --yolo, it may refresh stale paid InMail credit cache facts
|
|
62
|
+
description: "Typed command entrypoint for Sellable refill sends. Accepts --yolo semantics and optional sender selectors, then returns the bounded execution contract for the skill-led refill workflow. In --yolo, it may refresh stale paid InMail credit cache facts for exact selected senders once, then rerun and return the post-refresh target plan. This tool does not mutate campaigns, import leads, approve messages, schedule sends, launch, archive, delete, or write scheduler rows.",
|
|
90
63
|
inputSchema: {
|
|
91
64
|
type: "object",
|
|
92
65
|
properties: {
|
|
@@ -94,6 +67,19 @@ export const refillSendsToolDefinitions = [
|
|
|
94
67
|
type: "boolean",
|
|
95
68
|
description: "When true, auto-accept the rendered bounded refill packet after the required fresh state reread. Without sender selectors, yolo means all eligible healthy senders enrolled in active campaign-backed sequence campaigns.",
|
|
96
69
|
},
|
|
70
|
+
executionMode: {
|
|
71
|
+
type: "string",
|
|
72
|
+
enum: ["manual", "scheduled", "yolo"],
|
|
73
|
+
description: "Explicit run mode. scheduled and yolo require workspaceId and never fall back to the shared active workspace.",
|
|
74
|
+
},
|
|
75
|
+
requireWorkspace: {
|
|
76
|
+
type: "boolean",
|
|
77
|
+
description: "When true, require an explicit request-scoped workspaceId before any refill API call. Scheduled automation should set this.",
|
|
78
|
+
},
|
|
79
|
+
workspaceId: {
|
|
80
|
+
type: "string",
|
|
81
|
+
description: "Explicit request-scoped workspace id for scheduled/yolo refill automation. Pass this on every refill call instead of switching the shared active workspace.",
|
|
82
|
+
},
|
|
97
83
|
senders: {
|
|
98
84
|
type: "array",
|
|
99
85
|
items: { type: "string" },
|
|
@@ -150,11 +136,13 @@ export const refillSendsToolDefinitions = [
|
|
|
150
136
|
},
|
|
151
137
|
];
|
|
152
138
|
export function refillSendsCommand(input = {}) {
|
|
139
|
+
const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
|
|
153
140
|
const senders = normalizeStrings(input.senders);
|
|
154
141
|
const senderIds = normalizeStrings(input.senderIds);
|
|
155
142
|
const senderNames = normalizeStrings(input.senderNames);
|
|
156
143
|
const hasSenderSelectors = senders.length > 0 || senderIds.length > 0 || senderNames.length > 0;
|
|
157
144
|
const yolo = input.yolo === true;
|
|
145
|
+
const executionMode = input.executionMode ?? (yolo ? "yolo" : "manual");
|
|
158
146
|
const targetDate = normalizeTargetDate(input.targetDate);
|
|
159
147
|
const untilDate = targetDate ? null : normalizeUntilDate(input.untilDate);
|
|
160
148
|
const horizonSendDays = targetDate || untilDate
|
|
@@ -173,6 +161,9 @@ export function refillSendsCommand(input = {}) {
|
|
|
173
161
|
promptName: "refill-sends",
|
|
174
162
|
workflowPromptName: "refill-sends-workflow",
|
|
175
163
|
yolo,
|
|
164
|
+
executionMode,
|
|
165
|
+
workspaceId,
|
|
166
|
+
workspaceResolution: workspaceId ? "explicit" : "active_config",
|
|
176
167
|
intent,
|
|
177
168
|
targetDate,
|
|
178
169
|
untilDate,
|
|
@@ -211,7 +202,9 @@ export function refillSendsCommand(input = {}) {
|
|
|
211
202
|
firstOperationalSteps: [
|
|
212
203
|
'Load get_subskill_prompt({ subskillName: "refill-sends-workflow" }) before any product operation.',
|
|
213
204
|
"A skill cannot create or invoke /goal by itself. If this refill is already running inside an active Codex goal, keep that goal open until every selected sender lane is horizon-filled by projected coverage (sent + scheduled), Christian explicitly stops/statuses the run, or a concrete non-scheduler blocker appears.",
|
|
214
|
-
`Call get_refill_target_plan({ intent: "${intent}"${
|
|
205
|
+
`Call get_refill_target_plan({ intent: "${intent}"${workspaceId ? `, workspaceId: "${workspaceId}"` : ""}${input.campaignId ? `, campaignId: "${input.campaignId}"` : ""}${input.tableId ? `, tableId: "${input.tableId}"` : ""}${senderIds.length > 0
|
|
206
|
+
? `, senderIds: ${JSON.stringify(senderIds)}`
|
|
207
|
+
: ""}${senderNames.length > 0
|
|
215
208
|
? `, senderNames: ${JSON.stringify(senderNames)}`
|
|
216
209
|
: ""}${senders.length > 0 ? `, senders: ${JSON.stringify(senders)}` : ""}${targetDate
|
|
217
210
|
? `, targetDate: "${targetDate}"`
|
|
@@ -225,9 +218,11 @@ export function refillSendsCommand(input = {}) {
|
|
|
225
218
|
"If get_refill_target_plan returns status complete, report eligible sender ledger, target.senderRefillPlans, gross target, selected days, sent count, scheduled count, projected count, campaign ids, targetShapeRevision, and no-op proof without asking for approval.",
|
|
226
219
|
"Refill target lanes are connection invites (send_invite), standalone paid InMails (send_inmail_closed), or unified Sales Nav cascades represented publicly as send_inmail_closed with campaign classification sales_nav_cascade. For a Sales Nav cascade, refill the selected campaign first; its sequence can route prospects to Open InMail, paid InMail while fresh credits are >= 5, or same-campaign connection fallback without asking for separate open/paid/connection campaigns. Do not count send_dm as horizon target capacity.",
|
|
227
220
|
"If remainingReadyOrProjectedGap is 0 but remainingProjectedGap is positive, run only a persistent read-only scheduler wait/reread loop; do not ask for prep/import/approval and do not close out while scheduler pickup is the only remaining state.",
|
|
228
|
-
`Resolve route with resolve_campaign_fill_route({ intent: "${intent}"${input.campaignId ? `, campaignId: "${input.campaignId}"` : ""}${input.tableId ? `, tableId: "${input.tableId}"` : ""} }).`,
|
|
229
|
-
|
|
230
|
-
|
|
221
|
+
`Resolve route with resolve_campaign_fill_route({ intent: "${intent}"${workspaceId ? `, workspaceId: "${workspaceId}"` : ""}${input.campaignId ? `, campaignId: "${input.campaignId}"` : ""}${input.tableId ? `, tableId: "${input.tableId}"` : ""} }).`,
|
|
222
|
+
`If the plain route shows stale managed waterfall evidence, archived/completed shared slots, or targets that do not cover the selected sender set, immediately call resolve_campaign_fill_route({ intent: "active"${workspaceId ? `, workspaceId: "${workspaceId}"` : ""} }) and inspect current dashboard-active ACTIVE/PAUSED campaign-backed sequence campaigns before declaring a sender blocked.`,
|
|
223
|
+
workspaceId
|
|
224
|
+
? `Call list_senders({ workspaceId: "${workspaceId}" }) and get_sender_routing({ workspaceId: "${workspaceId}" }), then resolve sender selectors against active enrolled campaign-backed sequence senders.`
|
|
225
|
+
: "Call list_senders and get_sender_routing, then resolve sender selectors against active enrolled campaign-backed sequence senders.",
|
|
231
226
|
targetDate
|
|
232
227
|
? `Use fill window targetDate="${targetDate}" as one exact sender-local date; prepare rows only for scheduler-fillable slots on that date. Do not treat it as an inclusive through-date.`
|
|
233
228
|
: untilDate
|
|
@@ -239,14 +234,14 @@ export function refillSendsCommand(input = {}) {
|
|
|
239
234
|
"Treat current dashboard-active PAUSED campaign-backed sequence campaigns as start-eligible candidates: read refill state before deciding whether to prep, approve, start, or skip.",
|
|
240
235
|
"Fresh reread get_campaign_refill_state immediately before any import, prep, approval, or horizon-fill mutation.",
|
|
241
236
|
"Maintain a target-window saturation ledger per selected sender from get_refill_target_plan: selected days, gross capacity, actual sent counts, future scheduler-owned scheduled counts, projected counts, ready-to-schedule buffer, remaining projected gap, paid InMail threshold feasibility, targetShapeRevision, stateRevision, and next MCP primitive.",
|
|
242
|
-
"In --yolo, this tool automatically maintains a run-local refreshedPaidInmailSenderIds set: when the first target plan returns refresh_paid_inmail_credits candidates for selected paid-InMail lanes, it refreshes each exact sender at most once, reruns get_refill_target_plan, and returns the post-refresh targetPlan before any prep/
|
|
237
|
+
"In --yolo, this tool automatically maintains a run-local refreshedPaidInmailSenderIds set: when the first target plan returns refresh_paid_inmail_credits candidates for selected paid-InMail lanes, it refreshes each exact sender at most once, reruns get_refill_target_plan, and returns the post-refresh targetPlan before any prep/import/approval/start action is chosen.",
|
|
243
238
|
"Do not present paid-credit refresh as the next operator action after refill_sends returns autoPaidInmailRefresh and the post-refresh targetPlan.",
|
|
244
239
|
"If paid InMail feasibility remains below threshold after that automatic refresh, report the exact sender/campaign/table/column threshold action or same-campaign connection fallback; --yolo must not lower paid InMail thresholds or create campaigns.",
|
|
245
240
|
"In --yolo or after one Accept, continue through every safe selected sender/campaign action covered by the rendered target packet; sent/scheduled-count progress changes stateRevision and should continue while targetShapeRevision is stable.",
|
|
246
241
|
"Do not complete a fill/schedule request until a final get_refill_target_plan or refill-state reread proves projected coverage (sent + scheduled) fills the scheduler-forward target window. Treat awaiting_scheduler_after_ready_buffer as loaded, awaiting scheduler when ready buffer covers the gap; do not import/prep more rows in that state, and keep polling unless Christian stops/statuses the run or a concrete non-scheduler blocker such as paid_inmail_below_threshold appears.",
|
|
247
242
|
],
|
|
248
243
|
approvalContract: yolo
|
|
249
|
-
? "Auto-accept only the rendered bounded refill target packet after get_refill_target_plan and fresh reread. Execute one globally ranked primitive from target.globalActionQueue at a time, then rerun get_refill_target_plan before taking another action. Continue through every safe prep/
|
|
244
|
+
? "Auto-accept only the rendered bounded refill target packet after get_refill_target_plan and fresh reread. Execute one globally ranked primitive from target.globalActionQueue at a time, then rerun get_refill_target_plan before taking another action. Continue through every safe apply/prep/start action inside that packet, including start_campaign only for exact selected PAUSED campaign-backed sequence refill targets named in the packet. After each action, rerun get_refill_target_plan; keep going while targetShapeRevision is stable and projected coverage (sent + scheduled) progresses toward the target, even though stateRevision changes. Ready-to-schedule rows are buffer, not completion. If ready buffer covers the projected gap, use only persistent read-only scheduler wait/reread and keep the run open until projected coverage fills or Christian stops/statuses it. Stop immediately if targetShapeRevision changes because sender set, route, ids, caps, dates, blockers, action class, paid InMail threshold feasibility, or side-effect class drifts. --yolo does not authorize lowering paid InMail thresholds or creating connection campaigns."
|
|
250
245
|
: hasSenderSelectors
|
|
251
246
|
? "Before mutation, post the full bounded refill packet in normal chat as Markdown, including workspace, sender scope, campaign table, exact ids, caps/dates, gross target, sent count, scheduled count, projected count, ready buffer, remaining projected gap, paid InMail threshold feasibility, targetShapeRevision/stateRevision, side effects, forbidden actions, and stop condition. Then ask the final Accept/Decline structured approval question with a compact body that refers back to the posted packet instead of duplicating it. Only ask when get_refill_target_plan reports a positive remaining projected/ready gap. If target is complete by projected coverage, no-op without approval. If ready buffer covers the projected gap, run only persistent read-only scheduler wait/reread and keep the run open until projected coverage fills or Christian stops/statuses it. Threshold changes and campaign creation need separate explicit approval."
|
|
252
247
|
: "Ask which eligible enrolled senders to refill first, then, before mutation, post the full bounded refill packet in normal chat as Markdown and ask the final Accept/Decline structured approval question with a compact body that refers back to the posted packet.",
|
|
@@ -288,12 +283,14 @@ export function refillSendsCommand(input = {}) {
|
|
|
288
283
|
tableId: input.tableId,
|
|
289
284
|
intent,
|
|
290
285
|
approvalMode,
|
|
286
|
+
workspaceId,
|
|
291
287
|
},
|
|
292
288
|
},
|
|
293
289
|
},
|
|
294
290
|
};
|
|
295
291
|
}
|
|
296
292
|
function targetPlanInputFor(input = {}) {
|
|
293
|
+
const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
|
|
297
294
|
const senders = normalizeStrings(input.senders);
|
|
298
295
|
const senderIds = normalizeStrings(input.senderIds);
|
|
299
296
|
const senderNames = normalizeStrings(input.senderNames);
|
|
@@ -318,6 +315,7 @@ function targetPlanInputFor(input = {}) {
|
|
|
318
315
|
? {}
|
|
319
316
|
: { horizonSendDays }),
|
|
320
317
|
approvalMode,
|
|
318
|
+
...(workspaceId ? { workspaceId } : {}),
|
|
321
319
|
};
|
|
322
320
|
}
|
|
323
321
|
function recordValue(value) {
|
|
@@ -328,29 +326,6 @@ function recordValue(value) {
|
|
|
328
326
|
function stringValue(value) {
|
|
329
327
|
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
330
328
|
}
|
|
331
|
-
function numberValue(value) {
|
|
332
|
-
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
333
|
-
}
|
|
334
|
-
function stringArray(value) {
|
|
335
|
-
if (!Array.isArray(value))
|
|
336
|
-
return [];
|
|
337
|
-
return value.filter((item) => typeof item === "string");
|
|
338
|
-
}
|
|
339
|
-
function uniqueStrings(values) {
|
|
340
|
-
const seen = new Set();
|
|
341
|
-
const result = [];
|
|
342
|
-
for (const value of values) {
|
|
343
|
-
const normalized = typeof value === "string" ? value.trim() : "";
|
|
344
|
-
if (!normalized)
|
|
345
|
-
continue;
|
|
346
|
-
const key = normalized.toLowerCase();
|
|
347
|
-
if (seen.has(key))
|
|
348
|
-
continue;
|
|
349
|
-
seen.add(key);
|
|
350
|
-
result.push(normalized);
|
|
351
|
-
}
|
|
352
|
-
return result;
|
|
353
|
-
}
|
|
354
329
|
function paidRefreshActionFrom(value) {
|
|
355
330
|
const action = recordValue(value);
|
|
356
331
|
if (!action || action.type !== "refresh_paid_inmail_credits")
|
|
@@ -398,487 +373,25 @@ function collectPaidInmailRefreshActions(plan) {
|
|
|
398
373
|
add(action);
|
|
399
374
|
return [...bySender.values()];
|
|
400
375
|
}
|
|
401
|
-
function firstGlobalAction(plan) {
|
|
402
|
-
const root = recordValue(plan);
|
|
403
|
-
const target = recordValue(root?.target);
|
|
404
|
-
const globalActionQueue = Array.isArray(target?.globalActionQueue)
|
|
405
|
-
? target.globalActionQueue
|
|
406
|
-
: [];
|
|
407
|
-
const [first] = globalActionQueue;
|
|
408
|
-
return recordValue(first);
|
|
409
|
-
}
|
|
410
|
-
function actionIds(action) {
|
|
411
|
-
return recordValue(action.ids) ?? {};
|
|
412
|
-
}
|
|
413
|
-
function actionToolInput(action) {
|
|
414
|
-
return recordValue(action.toolInput) ?? {};
|
|
415
|
-
}
|
|
416
|
-
function actionCampaignId(action) {
|
|
417
|
-
const ids = actionIds(action);
|
|
418
|
-
const toolInput = actionToolInput(action);
|
|
419
|
-
return (stringValue(toolInput.campaignId) ??
|
|
420
|
-
stringValue(toolInput.campaignOfferId) ??
|
|
421
|
-
stringValue(ids.campaignId) ??
|
|
422
|
-
stringValue(action.campaignId));
|
|
423
|
-
}
|
|
424
|
-
function actionTableId(action) {
|
|
425
|
-
const ids = actionIds(action);
|
|
426
|
-
const toolInput = actionToolInput(action);
|
|
427
|
-
return (stringValue(toolInput.tableId) ??
|
|
428
|
-
stringValue(ids.tableId) ??
|
|
429
|
-
stringValue(action.tableId));
|
|
430
|
-
}
|
|
431
|
-
function actionSourceLeadListId(action) {
|
|
432
|
-
const ids = actionIds(action);
|
|
433
|
-
const toolInput = actionToolInput(action);
|
|
434
|
-
return (stringValue(toolInput.sourceLeadListId) ??
|
|
435
|
-
stringValue(ids.sourceLeadListId) ??
|
|
436
|
-
stringValue(action.sourceLeadListId));
|
|
437
|
-
}
|
|
438
|
-
function actionSenderId(action) {
|
|
439
|
-
const ids = actionIds(action);
|
|
440
|
-
const toolInput = actionToolInput(action);
|
|
441
|
-
return (stringValue(toolInput.senderId) ??
|
|
442
|
-
stringValue(ids.senderId) ??
|
|
443
|
-
stringValue(action.senderId));
|
|
444
|
-
}
|
|
445
|
-
function actionActionType(action) {
|
|
446
|
-
const ids = actionIds(action);
|
|
447
|
-
const toolInput = actionToolInput(action);
|
|
448
|
-
return (stringValue(toolInput.actionType) ??
|
|
449
|
-
stringValue(toolInput.selectedLane) ??
|
|
450
|
-
stringValue(ids.actionType) ??
|
|
451
|
-
stringValue(action.actionType) ??
|
|
452
|
-
stringValue(action.selectedLane));
|
|
453
|
-
}
|
|
454
|
-
function actionSourceFingerprint(action) {
|
|
455
|
-
const ids = actionIds(action);
|
|
456
|
-
const toolInput = actionToolInput(action);
|
|
457
|
-
return (stringValue(toolInput.sourceFingerprint) ??
|
|
458
|
-
stringValue(ids.sourceFingerprint) ??
|
|
459
|
-
stringValue(action.sourceFingerprint));
|
|
460
|
-
}
|
|
461
|
-
function actionLeadSourceProvider(action) {
|
|
462
|
-
const ids = actionIds(action);
|
|
463
|
-
const toolInput = actionToolInput(action);
|
|
464
|
-
return (stringValue(toolInput.leadSourceProvider) ??
|
|
465
|
-
stringValue(toolInput.provider) ??
|
|
466
|
-
stringValue(ids.leadSourceProvider) ??
|
|
467
|
-
stringValue(action.leadSourceProvider));
|
|
468
|
-
}
|
|
469
|
-
function normalizedSignalKeyword(value) {
|
|
470
|
-
if (typeof value !== "string")
|
|
471
|
-
return null;
|
|
472
|
-
const keyword = value.trim();
|
|
473
|
-
if (!keyword)
|
|
474
|
-
return null;
|
|
475
|
-
if (/^(https?:\/\/|www\.|linkedin\.com\/|\/?in\/)/i.test(keyword)) {
|
|
476
|
-
return null;
|
|
477
|
-
}
|
|
478
|
-
return keyword;
|
|
479
|
-
}
|
|
480
|
-
function keywordsFromSignalTabs(tabs) {
|
|
481
|
-
const selectedKeywords = [];
|
|
482
|
-
const fallbackKeywords = [];
|
|
483
|
-
for (const tab of tabs) {
|
|
484
|
-
const keyword = normalizedSignalKeyword(tab.keyword);
|
|
485
|
-
if (!keyword)
|
|
486
|
-
continue;
|
|
487
|
-
const selected = (tab.posts ?? []).some((post) => post.isSelected === true);
|
|
488
|
-
if (selected) {
|
|
489
|
-
selectedKeywords.push(keyword);
|
|
490
|
-
}
|
|
491
|
-
else {
|
|
492
|
-
fallbackKeywords.push(keyword);
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
return uniqueStrings([...selectedKeywords, ...fallbackKeywords]).slice(0, 5);
|
|
496
|
-
}
|
|
497
|
-
function selectedPostIdsFromSignalTabs(tabs) {
|
|
498
|
-
return uniqueStrings(tabs.flatMap((tab) => (tab.posts ?? [])
|
|
499
|
-
.filter((post) => post.isSelected === true)
|
|
500
|
-
.map((post) => post.id)));
|
|
501
|
-
}
|
|
502
|
-
function postIdsFromSignalSearch(summary, maxPosts, options = {}) {
|
|
503
|
-
const excludedPostIds = new Set((options.excludePostIds ?? []).map((postId) => postId.toLowerCase()));
|
|
504
|
-
const recommendedPostIds = stringArray(summary?.recommendedPostIds);
|
|
505
|
-
const topPostIds = Array.isArray(summary?.topPosts)
|
|
506
|
-
? summary.topPosts
|
|
507
|
-
.map((post) => post && typeof post === "object"
|
|
508
|
-
? stringValue(post.id)
|
|
509
|
-
: null)
|
|
510
|
-
.filter((id) => Boolean(id))
|
|
511
|
-
: [];
|
|
512
|
-
return uniqueStrings([...recommendedPostIds, ...topPostIds])
|
|
513
|
-
.filter((postId) => !excludedPostIds.has(postId.toLowerCase()))
|
|
514
|
-
.slice(0, Math.max(1, maxPosts));
|
|
515
|
-
}
|
|
516
|
-
function maxSignalDiscoveryPostsForSourceLimit(sourceRowLimit) {
|
|
517
|
-
return Math.min(SIGNAL_DISCOVERY_MAX_REFILL_POSTS, Math.max(SIGNAL_DISCOVERY_MIN_REFILL_POSTS, Math.ceil(sourceRowLimit / SIGNAL_DISCOVERY_TARGET_ROWS_PER_POST)));
|
|
518
|
-
}
|
|
519
|
-
function refillPrepareRequestHash(params) {
|
|
520
|
-
return [
|
|
521
|
-
"refill_sends",
|
|
522
|
-
"prepare_messages",
|
|
523
|
-
params.campaignId,
|
|
524
|
-
params.tableId ?? "no-table",
|
|
525
|
-
actionSenderId(params.action) ?? "all-senders",
|
|
526
|
-
actionSourceLeadListId(params.action) ?? "no-source-list",
|
|
527
|
-
actionActionType(params.action) ?? "no-action-type",
|
|
528
|
-
params.approvalMode,
|
|
529
|
-
].join(":");
|
|
530
|
-
}
|
|
531
|
-
function boundedApprovalLimit(action) {
|
|
532
|
-
const toolInput = actionToolInput(action);
|
|
533
|
-
const rowSelector = recordValue(toolInput.rowSelector);
|
|
534
|
-
const selectorLimit = numberValue(rowSelector?.limit);
|
|
535
|
-
const inputLimit = numberValue(toolInput.limit);
|
|
536
|
-
const limit = selectorLimit ?? inputLimit;
|
|
537
|
-
if (!limit || limit <= 0)
|
|
538
|
-
return null;
|
|
539
|
-
return Math.floor(limit);
|
|
540
|
-
}
|
|
541
|
-
async function approveGeneratedMessagesBatch(action) {
|
|
542
|
-
const tableId = actionTableId(action);
|
|
543
|
-
const toolInput = actionToolInput(action);
|
|
544
|
-
const columnId = stringValue(toolInput.columnId) ?? stringValue(actionIds(action).columnId);
|
|
545
|
-
const limit = boundedApprovalLimit(action);
|
|
546
|
-
if (!tableId || !limit) {
|
|
547
|
-
return {
|
|
548
|
-
status: "refused",
|
|
549
|
-
refusalReason: "approve_messages action is missing tableId or a bounded rowSelector.limit",
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
const api = getApi();
|
|
553
|
-
const result = await api.post("/api/v3/workflow-tables/cells/approve-batch", {
|
|
554
|
-
tableId,
|
|
555
|
-
...(columnId ? { columnId } : {}),
|
|
556
|
-
limit,
|
|
557
|
-
scope: "generated_unapproved",
|
|
558
|
-
});
|
|
559
|
-
return { status: "executed_and_reread", result };
|
|
560
|
-
}
|
|
561
|
-
async function continueSignalDiscoverySource(action) {
|
|
562
|
-
const campaignOfferId = actionCampaignId(action);
|
|
563
|
-
const sourceLeadListId = actionSourceLeadListId(action);
|
|
564
|
-
const sourceFingerprint = actionSourceFingerprint(action);
|
|
565
|
-
const toolInput = actionToolInput(action);
|
|
566
|
-
const sourceRowLimit = Math.min(1500, Math.max(100, Math.floor(numberValue(toolInput.sourceRowLimit) ??
|
|
567
|
-
numberValue(toolInput.targetRows) ??
|
|
568
|
-
numberValue(action.targetRows) ??
|
|
569
|
-
100)));
|
|
570
|
-
const maxPostsToScrape = maxSignalDiscoveryPostsForSourceLimit(sourceRowLimit);
|
|
571
|
-
if (!campaignOfferId || !sourceLeadListId || !sourceFingerprint) {
|
|
572
|
-
return {
|
|
573
|
-
status: "refused",
|
|
574
|
-
refusalReason: "continue_signal_discovery_source action is missing campaignOfferId, sourceLeadListId, or sourceFingerprint",
|
|
575
|
-
};
|
|
576
|
-
}
|
|
577
|
-
const requestedProvider = actionLeadSourceProvider(action);
|
|
578
|
-
if (requestedProvider &&
|
|
579
|
-
requestedProvider !== "signal-discovery" &&
|
|
580
|
-
requestedProvider !== "campaign-tracked-post") {
|
|
581
|
-
return {
|
|
582
|
-
status: "refused",
|
|
583
|
-
refusalReason: "continue_signal_discovery_source can only run for Signal Discovery source families",
|
|
584
|
-
};
|
|
585
|
-
}
|
|
586
|
-
const api = getApi();
|
|
587
|
-
const campaign = await api.get(`/api/v2/campaign-offers/${campaignOfferId}`);
|
|
588
|
-
if (campaign.leadSourceProvider !== "signal-discovery" &&
|
|
589
|
-
campaign.leadSourceProvider !== "campaign-tracked-post") {
|
|
590
|
-
return {
|
|
591
|
-
status: "refused",
|
|
592
|
-
refusalReason: "campaign leadSourceProvider is not Signal Discovery; refusing same-source continuation",
|
|
593
|
-
};
|
|
594
|
-
}
|
|
595
|
-
if (campaign.selectedLeadListId &&
|
|
596
|
-
campaign.selectedLeadListId !== sourceLeadListId) {
|
|
597
|
-
return {
|
|
598
|
-
status: "refused",
|
|
599
|
-
refusalReason: "campaign selectedLeadListId changed since the plan packet; rerun get_refill_target_plan before source continuation",
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
const sourceMeta = await api.get(`/api/v3/workflow-tables/${sourceLeadListId}?mode=meta`);
|
|
603
|
-
const sourceConfig = sourceMeta.table?.config ?? null;
|
|
604
|
-
const headlineICPCriteria = stringArray(sourceConfig?.headlineICPCriteria).length > 0
|
|
605
|
-
? stringArray(sourceConfig?.headlineICPCriteria)
|
|
606
|
-
: stringArray(sourceConfig?.rubricGuidelines);
|
|
607
|
-
const tabsResponse = await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/tabs`);
|
|
608
|
-
const signalTabs = tabsResponse.tabs ?? [];
|
|
609
|
-
const keywords = keywordsFromSignalTabs(signalTabs);
|
|
610
|
-
const excludedPostIds = selectedPostIdsFromSignalTabs(signalTabs);
|
|
611
|
-
if (keywords.length === 0) {
|
|
612
|
-
return {
|
|
613
|
-
status: "refused",
|
|
614
|
-
refusalReason: "no reusable Signal Discovery keywords were found on the campaign tabs",
|
|
615
|
-
};
|
|
616
|
-
}
|
|
617
|
-
markProviderPromptLoaded({
|
|
618
|
-
provider: "signal-discovery",
|
|
619
|
-
campaignOfferId,
|
|
620
|
-
});
|
|
621
|
-
const searchSummary = await searchSignals({
|
|
622
|
-
type: "keywords",
|
|
623
|
-
keywords: keywords.map((keyword) => ({
|
|
624
|
-
keyword,
|
|
625
|
-
source: "refill-sends-source-continuation",
|
|
626
|
-
})),
|
|
627
|
-
campaignOfferId,
|
|
628
|
-
currentStep: null,
|
|
629
|
-
headlineICPCriteria,
|
|
630
|
-
rubricGuidelines: headlineICPCriteria,
|
|
631
|
-
confirmed: true,
|
|
632
|
-
limit: 50,
|
|
633
|
-
});
|
|
634
|
-
const selectedPostIds = postIdsFromSignalSearch(searchSummary, maxPostsToScrape, { excludePostIds: excludedPostIds });
|
|
635
|
-
if (selectedPostIds.length === 0) {
|
|
636
|
-
return {
|
|
637
|
-
status: "refused",
|
|
638
|
-
refusalReason: "Signal Discovery search returned no new recommended posts to continue the source",
|
|
639
|
-
result: { keywords, excludedPostIds, searchSummary },
|
|
640
|
-
};
|
|
641
|
-
}
|
|
642
|
-
const selectionResult = await selectPromisingPosts({
|
|
643
|
-
campaignOfferId,
|
|
644
|
-
selections: selectedPostIds.map((postId) => ({
|
|
645
|
-
postId,
|
|
646
|
-
reason: "refill_sends same-source continuation: recent post from the campaign's existing Signal Discovery keyword family",
|
|
647
|
-
})),
|
|
648
|
-
headlineICPCriteria,
|
|
649
|
-
currentStep: null,
|
|
650
|
-
selectionMode: "replace",
|
|
651
|
-
scrapePlanMode: "all-selected",
|
|
652
|
-
});
|
|
653
|
-
if (selectionResult.success === false) {
|
|
654
|
-
return {
|
|
655
|
-
status: "refused",
|
|
656
|
-
refusalReason: stringValue(selectionResult.message) ??
|
|
657
|
-
"select_promising_posts did not select any posts",
|
|
658
|
-
result: { keywords, selectedPostIds, selectionResult },
|
|
659
|
-
};
|
|
660
|
-
}
|
|
661
|
-
const importResult = await importLeads({
|
|
662
|
-
campaignOfferId,
|
|
663
|
-
provider: "signal-discovery",
|
|
664
|
-
sourceLeadListId,
|
|
665
|
-
currentStep: null,
|
|
666
|
-
headlineICPCriteria,
|
|
667
|
-
rubricGuidelines: headlineICPCriteria,
|
|
668
|
-
confirmed: true,
|
|
669
|
-
maxPostsToScrape: selectedPostIds.length,
|
|
670
|
-
allowInvalidSignalPosts: true,
|
|
671
|
-
});
|
|
672
|
-
const importRecord = recordValue(importResult);
|
|
673
|
-
if (importRecord?.error) {
|
|
674
|
-
return {
|
|
675
|
-
status: "refused",
|
|
676
|
-
refusalReason: stringValue(importRecord.message) ??
|
|
677
|
-
`Signal Discovery import returned ${String(importRecord.error)}`,
|
|
678
|
-
result: {
|
|
679
|
-
keywords,
|
|
680
|
-
excludedPostIds,
|
|
681
|
-
selectedPostIds,
|
|
682
|
-
selectionResult,
|
|
683
|
-
importResult,
|
|
684
|
-
},
|
|
685
|
-
};
|
|
686
|
-
}
|
|
687
|
-
return {
|
|
688
|
-
status: "executed_and_reread",
|
|
689
|
-
result: {
|
|
690
|
-
provider: "signal-discovery",
|
|
691
|
-
campaignOfferId,
|
|
692
|
-
previousSourceLeadListId: sourceLeadListId,
|
|
693
|
-
sourceFingerprint,
|
|
694
|
-
keywords,
|
|
695
|
-
excludedPostIds,
|
|
696
|
-
selectedPostIds,
|
|
697
|
-
sourceRowLimit,
|
|
698
|
-
maxPostsToScrape: selectedPostIds.length,
|
|
699
|
-
searchSummary,
|
|
700
|
-
selectionResult,
|
|
701
|
-
importResult,
|
|
702
|
-
},
|
|
703
|
-
};
|
|
704
|
-
}
|
|
705
|
-
async function refreshPaidInmailCreditsWithRetry(senderId) {
|
|
706
|
-
const errors = [];
|
|
707
|
-
for (let attempt = 1; attempt <= PAID_INMAIL_REFRESH_MAX_ATTEMPTS; attempt += 1) {
|
|
708
|
-
try {
|
|
709
|
-
const receipt = await refreshPaidInmailCredits({ senderId });
|
|
710
|
-
return { receipt, attempts: attempt, errors };
|
|
711
|
-
}
|
|
712
|
-
catch (error) {
|
|
713
|
-
errors.push(error instanceof Error ? error.message : String(error));
|
|
714
|
-
if (attempt < PAID_INMAIL_REFRESH_MAX_ATTEMPTS) {
|
|
715
|
-
await sleep(PAID_INMAIL_REFRESH_RETRY_DELAY_MS);
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
return {
|
|
720
|
-
receipt: null,
|
|
721
|
-
attempts: PAID_INMAIL_REFRESH_MAX_ATTEMPTS,
|
|
722
|
-
errors,
|
|
723
|
-
};
|
|
724
|
-
}
|
|
725
|
-
async function executeOneYoloPrimitive(action) {
|
|
726
|
-
if (!action)
|
|
727
|
-
return { status: "no_action" };
|
|
728
|
-
if (action.yoloEligible === false) {
|
|
729
|
-
return {
|
|
730
|
-
status: "refused",
|
|
731
|
-
refusalReason: "first global action is not yolo eligible",
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
switch (action.type) {
|
|
735
|
-
case "wait_for_scheduler":
|
|
736
|
-
case "wait_for_active_work":
|
|
737
|
-
case "wait_for_source_import":
|
|
738
|
-
return { status: "read_only_reread", result: { waited: true } };
|
|
739
|
-
case "prepare_messages": {
|
|
740
|
-
const campaignId = actionCampaignId(action);
|
|
741
|
-
const tableId = actionTableId(action) ?? undefined;
|
|
742
|
-
const toolInput = actionToolInput(action);
|
|
743
|
-
const targetPreparedMessages = numberValue(toolInput.targetPreparedMessages);
|
|
744
|
-
const approvalMode = toolInput.approvalMode === "approve" ? "approve" : "mark_ready";
|
|
745
|
-
if (!campaignId ||
|
|
746
|
-
!targetPreparedMessages ||
|
|
747
|
-
targetPreparedMessages <= 0) {
|
|
748
|
-
return {
|
|
749
|
-
status: "refused",
|
|
750
|
-
refusalReason: "prepare_messages action is missing campaignId or bounded targetPreparedMessages",
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
const result = await startPrepareCampaignMessages({
|
|
754
|
-
campaignId,
|
|
755
|
-
tableId,
|
|
756
|
-
targetPreparedMessages,
|
|
757
|
-
maxRowsToCheck: numberValue(toolInput.maxRowsToCheck) ?? 300,
|
|
758
|
-
approvalMode,
|
|
759
|
-
autoContinue: true,
|
|
760
|
-
disableLowPassRateStop: true,
|
|
761
|
-
senderId: actionSenderId(action) ?? undefined,
|
|
762
|
-
actionType: actionActionType(action) ?? undefined,
|
|
763
|
-
requestHash: refillPrepareRequestHash({
|
|
764
|
-
action,
|
|
765
|
-
campaignId,
|
|
766
|
-
tableId,
|
|
767
|
-
approvalMode,
|
|
768
|
-
}),
|
|
769
|
-
requestSource: "refill_sends",
|
|
770
|
-
});
|
|
771
|
-
return { status: "executed_and_reread", result };
|
|
772
|
-
}
|
|
773
|
-
case "copy_selected_source_rows": {
|
|
774
|
-
const campaignOfferId = actionCampaignId(action);
|
|
775
|
-
const sourceLeadListId = actionSourceLeadListId(action);
|
|
776
|
-
const toolInput = actionToolInput(action);
|
|
777
|
-
const sourceRowIds = stringArray(toolInput.sourceRowIds);
|
|
778
|
-
const sourceRowLimit = numberValue(toolInput.sourceRowLimit);
|
|
779
|
-
const sourceFingerprint = stringValue(toolInput.sourceFingerprint) ??
|
|
780
|
-
stringValue(actionIds(action).sourceFingerprint);
|
|
781
|
-
if (!campaignOfferId || !sourceLeadListId || !sourceFingerprint) {
|
|
782
|
-
return {
|
|
783
|
-
status: "refused",
|
|
784
|
-
refusalReason: "copy_selected_source_rows action is missing campaignOfferId, sourceLeadListId, or sourceFingerprint",
|
|
785
|
-
};
|
|
786
|
-
}
|
|
787
|
-
if (sourceRowIds.length === 0 &&
|
|
788
|
-
(!sourceRowLimit || sourceRowLimit <= 0)) {
|
|
789
|
-
return {
|
|
790
|
-
status: "refused",
|
|
791
|
-
refusalReason: "copy_selected_source_rows action is missing exact sourceRowIds or a bounded sourceRowLimit",
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
const copyInput = {
|
|
795
|
-
campaignOfferId,
|
|
796
|
-
sourceLeadListId,
|
|
797
|
-
currentStep: null,
|
|
798
|
-
confirmed: true,
|
|
799
|
-
sourceRowIds: sourceRowIds.length > 0 ? sourceRowIds : undefined,
|
|
800
|
-
sourceRowLimit: sourceRowIds.length > 0 ? undefined : (sourceRowLimit ?? undefined),
|
|
801
|
-
reviewBatchLimit: sourceRowIds.length > 0
|
|
802
|
-
? sourceRowIds.length
|
|
803
|
-
: (sourceRowLimit ?? undefined),
|
|
804
|
-
};
|
|
805
|
-
let result;
|
|
806
|
-
try {
|
|
807
|
-
result = await confirmLeadList(copyInput);
|
|
808
|
-
}
|
|
809
|
-
catch (error) {
|
|
810
|
-
const rowLimitPayload = userAddedRowsLimitPayloadFromError(error);
|
|
811
|
-
if (!rowLimitPayload)
|
|
812
|
-
throw error;
|
|
813
|
-
const remainingRows = typeof rowLimitPayload.remainingRows === "number" &&
|
|
814
|
-
Number.isFinite(rowLimitPayload.remainingRows)
|
|
815
|
-
? Math.floor(rowLimitPayload.remainingRows)
|
|
816
|
-
: 0;
|
|
817
|
-
if (remainingRows <= 0) {
|
|
818
|
-
return {
|
|
819
|
-
status: "refused",
|
|
820
|
-
refusalReason: rowLimitPayload.error ??
|
|
821
|
-
"selected campaign table is at the workflow row limit",
|
|
822
|
-
};
|
|
823
|
-
}
|
|
824
|
-
const retrySourceRowIds = sourceRowIds.length > 0 ? sourceRowIds.slice(0, remainingRows) : [];
|
|
825
|
-
const retrySourceRowLimit = retrySourceRowIds.length > 0
|
|
826
|
-
? undefined
|
|
827
|
-
: Math.min(sourceRowLimit ?? remainingRows, remainingRows);
|
|
828
|
-
const retryReviewBatchLimit = retrySourceRowIds.length > 0
|
|
829
|
-
? retrySourceRowIds.length
|
|
830
|
-
: retrySourceRowLimit;
|
|
831
|
-
if (!retryReviewBatchLimit || retryReviewBatchLimit <= 0) {
|
|
832
|
-
return {
|
|
833
|
-
status: "refused",
|
|
834
|
-
refusalReason: rowLimitPayload.error ??
|
|
835
|
-
"selected campaign table cannot accept more workflow rows",
|
|
836
|
-
};
|
|
837
|
-
}
|
|
838
|
-
const retryResult = await confirmLeadList({
|
|
839
|
-
...copyInput,
|
|
840
|
-
sourceRowIds: retrySourceRowIds.length > 0 ? retrySourceRowIds : undefined,
|
|
841
|
-
sourceRowLimit: retrySourceRowIds.length > 0 ? undefined : retrySourceRowLimit,
|
|
842
|
-
reviewBatchLimit: retryReviewBatchLimit,
|
|
843
|
-
});
|
|
844
|
-
result =
|
|
845
|
-
retryResult && typeof retryResult === "object"
|
|
846
|
-
? {
|
|
847
|
-
...retryResult,
|
|
848
|
-
rowLimitRetry: {
|
|
849
|
-
code: rowLimitPayload.code,
|
|
850
|
-
maxRows: rowLimitPayload.maxRows,
|
|
851
|
-
currentRows: rowLimitPayload.currentRows,
|
|
852
|
-
requestedRows: rowLimitPayload.requestedRows,
|
|
853
|
-
remainingRows,
|
|
854
|
-
retriedRows: retryReviewBatchLimit,
|
|
855
|
-
},
|
|
856
|
-
}
|
|
857
|
-
: {
|
|
858
|
-
result: retryResult,
|
|
859
|
-
rowLimitRetry: {
|
|
860
|
-
code: rowLimitPayload.code,
|
|
861
|
-
remainingRows,
|
|
862
|
-
retriedRows: retryReviewBatchLimit,
|
|
863
|
-
},
|
|
864
|
-
};
|
|
865
|
-
}
|
|
866
|
-
return { status: "executed_and_reread", result };
|
|
867
|
-
}
|
|
868
|
-
case "continue_signal_discovery_source":
|
|
869
|
-
return continueSignalDiscoverySource(action);
|
|
870
|
-
case "approve_messages":
|
|
871
|
-
return approveGeneratedMessagesBatch(action);
|
|
872
|
-
default:
|
|
873
|
-
return {
|
|
874
|
-
status: "refused",
|
|
875
|
-
refusalReason: `action ${String(action.type)} is not a safe yolo primitive`,
|
|
876
|
-
};
|
|
877
|
-
}
|
|
878
|
-
}
|
|
879
376
|
export async function executeRefillSendsCommand(input = {}) {
|
|
880
|
-
const
|
|
881
|
-
|
|
377
|
+
const yolo = input.yolo === true;
|
|
378
|
+
const executionMode = input.executionMode ?? (yolo ? "yolo" : "manual");
|
|
379
|
+
const mustHaveWorkspace = yolo || input.requireWorkspace === true || executionMode === "scheduled";
|
|
380
|
+
const workspaceContext = mustHaveWorkspace
|
|
381
|
+
? createWorkspaceContext({
|
|
382
|
+
workspaceId: input.workspaceId,
|
|
383
|
+
executionMode,
|
|
384
|
+
toolName: "refill_sends",
|
|
385
|
+
})
|
|
386
|
+
: null;
|
|
387
|
+
if (workspaceContext && !workspaceContext.ok) {
|
|
388
|
+
return workspaceContext;
|
|
389
|
+
}
|
|
390
|
+
const scopedInput = workspaceContext && workspaceContext.ok
|
|
391
|
+
? { ...input, workspaceId: workspaceContext.context.workspaceId }
|
|
392
|
+
: input;
|
|
393
|
+
const command = refillSendsCommand(scopedInput);
|
|
394
|
+
if (!yolo) {
|
|
882
395
|
return {
|
|
883
396
|
...command,
|
|
884
397
|
autoPaidInmailRefresh: {
|
|
@@ -888,60 +401,44 @@ export async function executeRefillSendsCommand(input = {}) {
|
|
|
888
401
|
failedPaidInmailRefreshes: [],
|
|
889
402
|
note: "Automatic paid InMail credit refresh only runs for --yolo refill_sends calls.",
|
|
890
403
|
},
|
|
891
|
-
yoloExecution: {
|
|
892
|
-
enabled: false,
|
|
893
|
-
status: "not_run_without_yolo",
|
|
894
|
-
selectedAction: null,
|
|
895
|
-
targetPlanReread: false,
|
|
896
|
-
},
|
|
897
404
|
};
|
|
898
405
|
}
|
|
899
|
-
const
|
|
406
|
+
const workspaceId = workspaceContext && workspaceContext.ok
|
|
407
|
+
? workspaceContext.context.workspaceId
|
|
408
|
+
: normalizeExplicitWorkspaceId(scopedInput.workspaceId);
|
|
409
|
+
const targetPlanInput = targetPlanInputFor(scopedInput);
|
|
900
410
|
const targetPlanBeforePaidRefresh = await getRefillTargetPlan(targetPlanInput);
|
|
901
411
|
const refreshActions = collectPaidInmailRefreshActions(targetPlanBeforePaidRefresh);
|
|
902
412
|
const refreshedPaidInmailSenderIds = [];
|
|
903
413
|
const failedPaidInmailRefreshes = [];
|
|
904
414
|
const refreshReceipts = [];
|
|
905
415
|
for (const action of refreshActions) {
|
|
906
|
-
|
|
907
|
-
|
|
416
|
+
try {
|
|
417
|
+
const receipt = await refreshPaidInmailCredits({
|
|
418
|
+
senderId: action.senderId,
|
|
419
|
+
...(workspaceId ? { workspaceId } : {}),
|
|
420
|
+
});
|
|
908
421
|
refreshedPaidInmailSenderIds.push(action.senderId);
|
|
909
422
|
refreshReceipts.push({
|
|
910
423
|
senderId: action.senderId,
|
|
911
424
|
actionKey: action.actionKey ?? null,
|
|
912
|
-
|
|
913
|
-
retryErrors: refreshResult.errors,
|
|
914
|
-
receipt: refreshResult.receipt,
|
|
425
|
+
receipt,
|
|
915
426
|
});
|
|
916
427
|
}
|
|
917
|
-
|
|
428
|
+
catch (error) {
|
|
918
429
|
failedPaidInmailRefreshes.push({
|
|
919
430
|
senderId: action.senderId,
|
|
920
|
-
|
|
921
|
-
error: refreshResult.errors[refreshResult.errors.length - 1] ??
|
|
922
|
-
"paid InMail credit refresh failed",
|
|
923
|
-
errors: refreshResult.errors,
|
|
431
|
+
error: error instanceof Error ? error.message : String(error),
|
|
924
432
|
});
|
|
925
433
|
}
|
|
926
434
|
}
|
|
927
435
|
const targetPlan = refreshActions.length > 0
|
|
928
436
|
? await getRefillTargetPlan(targetPlanInput)
|
|
929
437
|
: targetPlanBeforePaidRefresh;
|
|
930
|
-
const selectedAction = refreshActions.length > 0 ? null : firstGlobalAction(targetPlan);
|
|
931
|
-
const primitiveAttempt = refreshActions.length > 0
|
|
932
|
-
? null
|
|
933
|
-
: await executeOneYoloPrimitive(selectedAction);
|
|
934
|
-
const shouldRereadAfterPrimitive = primitiveAttempt?.status === "executed_and_reread" ||
|
|
935
|
-
primitiveAttempt?.status === "read_only_reread";
|
|
936
|
-
const postActionTargetPlan = shouldRereadAfterPrimitive
|
|
937
|
-
? await getRefillTargetPlan(targetPlanInput)
|
|
938
|
-
: null;
|
|
939
|
-
const finalTargetPlan = postActionTargetPlan ?? targetPlan;
|
|
940
438
|
return {
|
|
941
439
|
...command,
|
|
942
|
-
targetPlan
|
|
440
|
+
targetPlan,
|
|
943
441
|
targetPlanBeforePaidRefresh: refreshActions.length > 0 ? targetPlanBeforePaidRefresh : null,
|
|
944
|
-
targetPlanBeforeYoloPrimitive: refreshActions.length === 0 && postActionTargetPlan ? targetPlan : null,
|
|
945
442
|
autoPaidInmailRefresh: {
|
|
946
443
|
enabled: true,
|
|
947
444
|
status: refreshActions.length === 0
|
|
@@ -954,27 +451,11 @@ export async function executeRefillSendsCommand(input = {}) {
|
|
|
954
451
|
refreshReceipts,
|
|
955
452
|
attemptedSenderIds: refreshActions.map((action) => action.senderId),
|
|
956
453
|
targetPlanReread: refreshActions.length > 0,
|
|
454
|
+
workspaceId,
|
|
455
|
+
workspaceResolution: workspaceId ? "explicit" : "active_config",
|
|
957
456
|
note: refreshActions.length > 0
|
|
958
|
-
? "refill_sends refreshed stale paid InMail credit facts internally
|
|
457
|
+
? "refill_sends refreshed stale paid InMail credit facts internally, once per sender, then returned the post-refresh targetPlan."
|
|
959
458
|
: "No stale or missing paid InMail credit refresh candidates were present in the initial target plan.",
|
|
960
459
|
},
|
|
961
|
-
yoloExecution: refreshActions.length > 0
|
|
962
|
-
? {
|
|
963
|
-
enabled: true,
|
|
964
|
-
status: "skipped_after_paid_refresh",
|
|
965
|
-
selectedAction: null,
|
|
966
|
-
targetPlanReread: true,
|
|
967
|
-
}
|
|
968
|
-
: {
|
|
969
|
-
enabled: true,
|
|
970
|
-
status: primitiveAttempt?.status ?? "no_action",
|
|
971
|
-
selectedAction,
|
|
972
|
-
result: primitiveAttempt?.result,
|
|
973
|
-
targetPlanReread: shouldRereadAfterPrimitive,
|
|
974
|
-
refusalReason: primitiveAttempt?.refusalReason,
|
|
975
|
-
postActionFirstAction: postActionTargetPlan
|
|
976
|
-
? firstGlobalAction(postActionTargetPlan)
|
|
977
|
-
: null,
|
|
978
|
-
},
|
|
979
460
|
};
|
|
980
461
|
}
|