@sellable/mcp 0.1.471 → 0.1.473

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.
@@ -373,7 +373,7 @@ export function getPostFindLeadsScoutRegistry() {
373
373
  codex: 'After confirm_lead_list copies source rows and the initial campaign-table execution slice exists, ask the filter-choice question immediately. Do not spawn anything before that question. After the answer, launch only Message Drafting. The filter-choice answer is the post-import user gate for this single worker; do not ask another question about starting it in step-wise or YOLO mode. The registry lookup is not a launch: after get_post_find_leads_scout_registry, immediately invoke Task/spawn_agent or the host background-agent mechanism before loading filter-leads.md, before saving rubrics, and before treating skip-filters as ready for message review. Both choices route through this kickoff; do not let filters_skipped jump straight from filter-choice to message-generation. If filters are chosen, the parent stays on Filter Rules and drafts/saves rubrics with MCP tools while Message Drafting runs in the background. If filters are skipped, move to Messages/message review only after Message Drafting has started or is ready; update_campaign(currentStep=messages) is not proof of launch. If the named Message Drafting custom agent is unavailable, spawn a generic gpt-5.5 xhigh Message Drafting background agent with the same lean campaign/table basis. When the background worker starts, persist workerDetails.messageDraftBuilder with statusSource "branch", status "branch-running", runId, startedAt, updatedAt, basisToken when known, and basis containing campaignId, selectedLeadListId, workflowTableId, filterChoice, and reviewBatchRowHash or reviewBatchRowIds; workerStatuses.messageDraftBuilder may be "running" as a simple badge only. Never put rich proof under workerStatuses and never use workerStatuses.messageDrafting. If no background-agent tool is callable, start the same full message branch inline before filter drafting or before skip-filter message review, record workerDetails.messageDraftBuilder with statusSource "parent-thread-fallback" and status "fallback-active", and require the same live context, prompt, assets, and validation gate before message review; do not wait until filters are saved and then call the registry.',
374
374
  claude: "After confirm_lead_list copies source rows and the initial campaign-table execution slice exists, ask the filter-choice question immediately. Do not invoke any Task/Agent before that question. After the answer, invoke only Message Drafting. If filters are chosen, parent drafts/saves rubrics with MCP tools while Message Drafting runs, asks filter approval, then joins Message Drafting. If filters are skipped, invoke only Message Drafting and move to Messages/message review.",
375
375
  parentThreadRule: 'Named agents are optional acceleration, but message drafting is not optional. The only normal background worker is Message Drafting. The filter-choice answer is the campaign-scoped go-ahead for this single post-import worker; do not ask another question to start it in step-wise or YOLO mode. If a named agent is unavailable, use a generic gpt-5.5 xhigh Message Drafting background agent. source work and filter work stay in the parent thread with MCP tools. If post-find-leads-message-scout is available, run it as the background Message Draft Builder after the filter-choice answer. The registry lookup is not a launch: get_post_find_leads_scout_registry only identifies the worker, and Message Drafting counts as started only after Task/spawn_agent or the host background-agent tool is invoked, or after the parent begins the same full message branch inline because no background-agent tool is callable. This launch must happen before loading filter-leads.md, save_rubrics, filter approval, or skip-filter message review; currentStep=messages is not proof of launch. If post-find-leads-message-scout is absent, do not customer-surface install status. Do not silently treat message drafting as started; the main thread must either launch the background worker or execute the same message branch from CampaignOffer state, selected source state, workflowTableId, and initial campaign-table execution slice rows. For a spawned worker, record workerDetails.messageDraftBuilder with statusSource branch / status branch-running, runId, startedAt, updatedAt, and basis containing campaignId, selectedLeadListId, workflowTableId, filterChoice, and reviewBatchRowHash or reviewBatchRowIds. workerStatuses.messageDraftBuilder is optional simple badge text only ("running", "ready", "blocked", "idle"); never put runId/statusSource/basis under workerStatuses and never use workerStatuses.messageDrafting. If no background-agent tool is callable, start that same full message branch inline before filter drafting or before skip-filter message review, record workerDetails.messageDraftBuilder with statusSource parent-thread-fallback / status fallback-active then ready, and require the same live context, prompt, assets, and validation gate before message review; do not report that as a background worker failure. If neither branch nor inline fallback can run, return blocked/retry-needed; do not wait until filters are saved and then call the registry. The Message Drafting handoff must be lean. Do not paste copied row counts, brief hashes, review-batch hashes, full reviewBatchRowIds, broad row data, or local debug artifacts into the spawn prompt. Local markdown/json files are not normal-path inputs. The filter-choice question is the first post-import user gate; do not load post-lead registries or filter references before it. Message drafting starts after the filter-choice answer, must load get_subskill_prompt({ subskillName: "generate-messages" }), and must load every required message asset named by generate-messages Mode 0 through get_subskill_asset before drafting. Reference Asset Loading means loading the required pre-draft reference pack before drafting; return blocked/retry-needed if required assets cannot be loaded; load ai-tells.md because it is never optional. The branch or parent-thread fallback loads the full generate-messages prompt and every referenced asset through get_subskill_asset. After generating/revising the candidate and before returning ready, must load get_subskill_prompt({ subskillName: "create-campaign-v2-validation" }) as the final internal validation gate, must read live campaign table state through scoped MCP/product tools, and must reject mismatched selectedLeadListId/workflowTableId/campaign/workspace input. Do not block when filters were chosen but leadScoringRubrics are not yet visible in the branch read; the parent owns save_rubrics and filter approval in parallel, so Message Drafting should return status ready with basisStatus usable_initial when campaign/list/table identity and the non-empty execution slice match. Do not use any alternate, local-artifact, or examples-only message prompt. User copy feedback, message QA, or rewrite requests before approve-message must be routed back to Message Drafting with the current recommendation, lean campaign/table basis, and latest user text; the parent must not rewrite or QA the template from memory and must not call update_campaign_brief before approve-message. The worker validates internally and returns only templateRecommendation, tokenFillRules, renderedGoodSample, status, approveOrReviseRecommendation, validationStatus, outputAt, outputHash, and blocked/retry detail. Do not render renderedFallbackSample, risk notes, or a qaReceipt on the normal happy path. On the filter path, save_rubrics keeps the browser on Filter Rules after save_rubrics so the user can approve the saved criteria; after saved-filter approval, move to Filter Leads with currentStep=apply-icp-rubric whether Message Drafting is ready or still running. Wait there for message approval. Enrichment, filtering, Generate Message cells, sender setup, sequence attach, and launch wait for template approval on the Use Template path. On the skip path, move to Messages/message review after Message Drafting has started or is ready and wait for message approval before enrichment or Settings. Do not render message review from checklist or shortcut instructions; message review requires a messageDraftRecommendation whose basis proves the generate-messages prompt, required message assets, and validation gate ran for the current campaign/table execution slice. Do not automatically rerun Message Drafting after filters/enrichment finish; show the initial draft by default and offer an enriched rewrite only with explicit user opt-in. Handoff and recommendation output are Markdown with labeled fields, not raw JSON.',
376
- prepareMessagesRule: `Default create-campaign stays on the existing reviewBatchLimit:15 first campaign-table execution slice. For plain post-mint fill/load/refill requests, load get_subskill_prompt({ subskillName: "refill-sends-workflow" }), then call resolve_campaign_fill_route({ intent:"plain" }), list_senders, and get_campaign_refill_state for enough candidate campaigns to identify the campaign that most recently had scheduler-owned sends for the relevant sender set before any mutation. Route outcomes are route:"evergreen_horizon", route:"active_campaigns", and route:"ask_create"; if a plain managed-waterfall route has archived/completed skipped slots or does not cover the named sender set, immediately refetch with resolve_campaign_fill_route({ intent:"active" }) and inspect current dashboard-active ACTIVE/PAUSED campaign-backed sequence campaigns before declaring a sender blocked; stay in the same campaignOfferId/campaignId context after minting. Plain fill is not an alias for fill_campaign_horizon or campaign creation. fill_campaign_horizon is evergreen-only and is not the generic regular-campaign fill path. Campaign creation is allowed only after route:"ask_create" and explicit user selection; it is never the default response to plain fill. Treat "fill up/load sends" as capacity-fill preparation, and treat "refill senders", "fill senders", "max out senders", and "load everyone up" as sender-scoped capacity-fill preparation. For sender-scoped requests with no named senders, --yolo means all eligible healthy senders enrolled in active campaign-backed sequence campaigns in the active workspace; without --yolo, ask which eligible enrolled senders to refill before choosing campaigns or mutating. In non-yolo interactive Codex or Claude Code sessions, post the full sender/campaign/action approval packet in normal chat as Markdown first, then ask request_user_input/AskUserQuestion with exactly Accept and Decline and a compact body that refers back to the posted packet; do not duplicate the campaign table or full operator packet inside the structured question. The chat packet must show workspace, sender scope, a campaign-by-campaign table, exact ids/caps/dates, side effects, forbidden actions, and stop condition before mutation. Default --yolo target is the scheduler-forward 48-hour target window: sender-local send days whose configured sending windows overlap the rolling target window, skipping no-send-hour days. For campaign-scoped fill/refill, select the best recent-send campaign and calculate the bounded gap from healthy sender daily capacity minus projected coverage (actual sent plus future scheduler-owned scheduled sends) and ready-to-schedule rows, then prepare only that gap. For sender-scoped fill/refill, calculate the bounded gap per eligible sender across active enrolled campaigns, counting actual sent coverage, future scheduled rows, and ready-to-schedule rows across those campaigns, then choose the best same-sender campaign to fill each sender gap: prefer recent/future scheduler-owned sends for that sender, then strongest recent result evidence, then source health. Maintain a target-window saturation ledger per selected sender with selected send days, gross capacity, actual sent counts, future scheduler-owned scheduled counts, projected coverage, ready-to-schedule buffer, remaining projected gap, paid-InMail threshold feasibility, and the next MCP primitive. Do not stop after filling only one sender when the request was sender-scoped. In --yolo, continue through every safe selected sender/campaign action covered by the rendered packet, reread after each terminal apply/prep/start result, recompute the target-window saturation ledger, and keep going until projected coverage (sent + scheduled) fills the scheduler-forward target window or a concrete non-scheduler blocker is proven. Ready-to-schedule rows are buffer, not completion; if ready covers the projected gap but scheduled cells do not, report loaded, awaiting scheduler and run a persistent read-only scheduler wait/reread loop and keep the run open while awaiting_scheduler_after_ready_buffer is the only remaining state. Paid-InMail threshold changes and connection-campaign creation are explicit continuation options, never --yolo side effects. When no safe in-packet action remains return concrete continuation options with campaign names, exact ids, and which options require a new approval packet; do not return final completion for scheduler wait unless Christian explicitly asks for status or stops the run. Use the refill workflow to decide whether to enrich/prep more rows in that same recent-send/best-result campaign, add/import more rows to that same campaign/source path, use a different existing campaign only when the selected same-sender lane is blocked/exhausted/already loaded while the sender still has a gap, or ask what to create. Do not create warm-post-engager side campaigns. Surface sender-health blockers and paid-InMail threshold blockers separately from prepared/approved/scheduled counts. User-facing refill decisions must be campaign-name-first and sender-name-first, with ids as proof/execution targets only. For already-running regular campaigns that need Signal Discovery source replenishment, use the guarded currentStep clear with clearCurrentStepIfMatches:"running", campaign-scoped provider prompt/search/select, and import_leads with the existing sourceLeadListId when a newly approved selected-post scrape would otherwise return reusedExistingSourceList. Before prep, inspect get_campaign_refill_state.preparationFrontier. If hasLaterPreparedIsland:true or earliestUnpreparedRow exists before later successful enrichment, use rowSelector:{type:"needsEnrichment"} with columnRole:"enrich" in table-position order or start_campaign_message_preparation adaptive defaults; do not use the UI Jump anchor or needsGeneratedMessage as the refill cursor. After confirm_lead_list copies rows into an existing table, avoid fixed maxRowsToCheck:100; if confirm_lead_list returns USER_ADDED_ROWS_LIMIT_EXCEEDED, create a bounded same-source split from selectedLeadListId with get_rows_minimal/load_csv_linkedin_leads, confirm that smaller source list into the same campaign, and inspect reviewBatch only as diagnostics unless the approved packet explicitly prioritizes the just-copied split and earlier needsEnrichment rows are exhausted, dependency-blocked, or excluded. For approval diagnostics use rowSelector:{type:"needsApproval"} after current generated messages exist; mutating Approved cells still requires approvalMode:approve and exact bounded approval. Do not interpret checkedRows as enriched rows; it is only the table cursor. Prepared, approved, and ready_to_schedule rows are intermediate states; never call them scheduled unless a re-read proves scheduler-owned scheduled cells with non-null scheduledFor contribute to projected coverage, and never call them complete unless a final re-read proves projected coverage fills the scheduler-forward target window. Before source import, prep, approval, or selected paused campaign start, require exact visible approval or --yolo packet auto-accept and a fresh get_campaign_refill_state reread; stop if freshness.stateHash or exact ids changed. For "approve X messages", use approvalMode:approve only when explicitly requested. For "schedule X sends" or "fill sender sends", approve only when explicitly requested, then re-read campaign/table scheduled counts; if projected coverage does not fill the horizon, keep polling when ready buffer covers the gap and report only interim prepared/approved/ready - awaiting scheduler status if Christian asks. Do not call start_campaign as part of fill/schedule horizon. start_campaign is allowed in refill only for exact selected PAUSED, dashboard-active, campaign-backed sequence targets named in the bounded packet, and the packet must state that starting can let the product scheduler schedule/send approved eligible sequence actions. Never start unrelated, archived, completed, draft, direct, or non-selected campaigns, never broad approve-all, and never use direct scheduler writes. campaignId is CampaignOffer.id. If the user asks to stop preparation, the target is wrong, or status shows the wrong campaign/table, use cancel_campaign_message_preparation only for the exact active job. Low-level selectors are diagnostics and recovery only for this lane.`,
376
+ prepareMessagesRule: `Default create-campaign stays on the existing reviewBatchLimit:15 first campaign-table execution slice. For plain post-mint fill/load/refill requests, load get_subskill_prompt({ subskillName: "refill-sends-workflow" }), then call resolve_campaign_fill_route({ intent:"plain" }), list_senders, and get_campaign_refill_state for enough candidate campaigns to identify the campaign that most recently had scheduler-owned sends for the relevant sender set before any mutation. Route outcomes are route:"evergreen_horizon", route:"active_campaigns", and route:"ask_create"; if a plain managed-waterfall route has archived/completed skipped slots or does not cover the named sender set, immediately refetch with resolve_campaign_fill_route({ intent:"active" }) and inspect current dashboard-active ACTIVE/PAUSED campaign-backed sequence campaigns before declaring a sender blocked; stay in the same campaignOfferId/campaignId context after minting. Plain fill is not an alias for fill_campaign_horizon or campaign creation. fill_campaign_horizon is evergreen-only and is not the generic regular-campaign fill path. Campaign creation is allowed only after route:"ask_create" and explicit user selection; it is never the default response to plain fill. Treat "fill up/load sends" as capacity-fill preparation, and treat "refill senders", "fill senders", "max out senders", and "load everyone up" as sender-scoped capacity-fill preparation. For sender-scoped requests with no named senders, --yolo means all eligible healthy senders enrolled in active campaign-backed sequence campaigns in the active workspace; without --yolo, ask which eligible enrolled senders to refill before choosing campaigns or mutating. In non-yolo interactive Codex or Claude Code sessions, post the full sender/campaign/action approval packet in normal chat as Markdown first, then ask request_user_input/AskUserQuestion with exactly Accept and Decline and a compact body that refers back to the posted packet; do not duplicate the campaign table or full operator packet inside the structured question. The chat packet must show workspace, sender scope, a campaign-by-campaign table, exact ids/caps/dates, side effects, forbidden actions, and stop condition before mutation. Default --yolo target is the scheduler-forward 48-hour target window: sender-local send days whose configured sending windows overlap the rolling target window, skipping no-send-hour days. For campaign-scoped fill/refill, select the best recent-send campaign and calculate the bounded gap from healthy sender daily capacity minus projected coverage (actual sent plus future scheduler-owned scheduled sends) and ready-to-schedule rows, then prepare only that gap. For sender-scoped fill/refill, calculate the bounded gap per eligible sender across active enrolled campaigns, counting actual sent coverage, future scheduled rows, and ready-to-schedule rows across those campaigns, then choose the best same-sender campaign to fill each sender gap: prefer recent/future scheduler-owned sends for that sender, then strongest recent result evidence, then source health. Maintain a target-window saturation ledger per selected sender with selected send days, gross capacity, actual sent counts, future scheduler-owned scheduled counts, projected coverage, ready-to-schedule buffer, remaining projected gap, paid-InMail threshold feasibility, and the next MCP primitive. The structured packet lives in target.senderRefillPlans[] with target.eligibleSenderLedger, campaignRanking.options, sourcePlan, nextActions, manualAlternates, and target.globalActionQueue; preserve Need to prepare, Goal, Already sent, Scheduled, Ready and waiting to be scheduled, and Still need labels. In --yolo, execute exactly one globally ranked primitive from target.globalActionQueue[0], then rerun get_refill_target_plan before choosing another action. Maintain a run-local refreshedPaidInmailSenderIds set and refresh each selected paid-InMail sender at most once before falling back to an existing connection lane or manual continuation. Do not stop after filling only one sender when the request was sender-scoped. In --yolo, continue through every safe selected sender/campaign action covered by the rendered packet, reread after each terminal apply/prep/start result, recompute the target-window saturation ledger, and keep going until projected coverage (sent + scheduled) fills the scheduler-forward target window or a concrete non-scheduler blocker is proven. Ready-to-schedule rows are buffer, not completion; if ready covers the projected gap but scheduled cells do not, report loaded, awaiting scheduler and run a persistent read-only scheduler wait/reread loop and keep the run open while awaiting_scheduler_after_ready_buffer is the only remaining state. Paid-InMail threshold changes and connection-campaign creation are explicit continuation options, never --yolo side effects. When no safe in-packet action remains return concrete continuation options with campaign names, exact ids, and which options require a new approval packet; do not return final completion for scheduler wait unless Christian explicitly asks for status or stops the run. Use the refill workflow to decide whether to enrich/prep more rows in that same recent-send/best-result campaign, add/import more rows to that same campaign/source path, use a different existing campaign only when the selected same-sender lane is blocked/exhausted/already loaded while the sender still has a gap, or ask what to create. Do not create warm-post-engager side campaigns. Surface sender-health blockers and paid-InMail threshold blockers separately from prepared/approved/scheduled counts. User-facing refill decisions must be campaign-name-first and sender-name-first, with ids as proof/execution targets only. Trust schedulerGate.sendable and scheduler blockers over raw unipileAccountStatus labels alone. For long-running prep use compact prep status checks, reread target plans after prep or cancel, avoid huge parallel target-plan reads when output is large, and if prepared/ready rows grow but sender-level projected coverage does not move after one bounded settle loop, pivot to compact prep status or a scheduler-proven lane instead of waiting on campaign-level ready counts. For already-running regular campaigns that need Signal Discovery source replenishment, use the guarded currentStep clear with clearCurrentStepIfMatches:"running", campaign-scoped provider prompt/search/select, and import_leads with the existing sourceLeadListId when a newly approved selected-post scrape would otherwise return reusedExistingSourceList. Before prep, inspect get_campaign_refill_state.preparationFrontier. If hasLaterPreparedIsland:true or earliestUnpreparedRow exists before later successful enrichment, use rowSelector:{type:"needsEnrichment"} with columnRole:"enrich" in table-position order or start_campaign_message_preparation adaptive defaults; do not use the UI Jump anchor or needsGeneratedMessage as the refill cursor. After confirm_lead_list copies rows into an existing table, avoid fixed maxRowsToCheck:100; if confirm_lead_list returns USER_ADDED_ROWS_LIMIT_EXCEEDED, create a bounded same-source split from selectedLeadListId with get_rows_minimal/load_csv_linkedin_leads, confirm that smaller source list into the same campaign, and inspect reviewBatch only as diagnostics unless the approved packet explicitly prioritizes the just-copied split and earlier needsEnrichment rows are exhausted, dependency-blocked, or excluded. For approval diagnostics use rowSelector:{type:"needsApproval"} after current generated messages exist; mutating Approved cells still requires approvalMode:approve and exact bounded approval. Do not interpret checkedRows as enriched rows; it is only the table cursor. Prepared, approved, and ready_to_schedule rows are intermediate states; never call them scheduled unless a re-read proves scheduler-owned scheduled cells with non-null scheduledFor contribute to projected coverage, and never call them complete unless a final re-read proves projected coverage fills the scheduler-forward target window. Before source import, prep, approval, or selected paused campaign start, require exact visible approval or --yolo packet auto-accept and a fresh get_campaign_refill_state reread; stop if freshness.stateHash or exact ids changed. For "approve X messages", use approvalMode:approve only when explicitly requested. For "schedule X sends" or "fill sender sends", approve only when explicitly requested, then re-read campaign/table scheduled counts; if projected coverage does not fill the horizon, keep polling when ready buffer covers the gap and report only interim prepared/approved/ready - awaiting scheduler status if Christian asks. Do not call start_campaign as part of fill/schedule horizon. start_campaign is allowed in refill only for exact selected PAUSED, dashboard-active, campaign-backed sequence targets named in the bounded packet, and the packet must state that starting can let the product scheduler schedule/send approved eligible sequence actions. Never start unrelated, archived, completed, draft, direct, or non-selected campaigns, never broad approve-all, and never use direct scheduler writes. campaignId is CampaignOffer.id. If the user asks to stop preparation, the target is wrong, or status shows the wrong campaign/table, use cancel_campaign_message_preparation only for the exact active job. Low-level selectors are diagnostics and recovery only for this lane.`,
377
377
  },
378
378
  };
379
379
  }
@@ -192,7 +192,9 @@ export function refillSendsCommand(input = {}) {
192
192
  : horizonSendDays === null
193
193
  ? ""
194
194
  : `, horizonSendDays: ${horizonSendDays}`}, approvalMode: "${approvalMode}" }) before any import, prep, approval, start, or schedule-affecting action.`,
195
- "If get_refill_target_plan returns status complete, report eligible sender ledger, gross target, selected days, sent count, scheduled count, projected count, campaign ids, targetShapeRevision, and no-op proof without asking for approval.",
195
+ "Render target.eligibleSenderLedger and target.senderRefillPlans before mutation. Preserve the coverage labels Need to prepare, Goal, Already sent, Scheduled, Ready and waiting to be scheduled, and Still need.",
196
+ "Use target.globalActionQueue as the only cross-sender yolo queue: execute only target.globalActionQueue[0], one globally ranked primitive, then rerun get_refill_target_plan before choosing another action.",
197
+ "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.",
196
198
  "Refill target lanes are only connection invites (send_invite) or paid InMails (send_inmail_closed). Do not count send_dm or send_inmail_open as horizon target capacity; they may exist in sequences, but the planner must pick the refill lane from the most recent active campaign-backed send evidence for each sender.",
197
199
  "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.",
198
200
  `Resolve route with resolve_campaign_fill_route({ intent: "${intent}"${input.campaignId ? `, campaignId: "${input.campaignId}"` : ""}${input.tableId ? `, tableId: "${input.tableId}"` : ""} }).`,
@@ -209,12 +211,13 @@ export function refillSendsCommand(input = {}) {
209
211
  "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.",
210
212
  "Fresh reread get_campaign_refill_state immediately before any import, prep, approval, or horizon-fill mutation.",
211
213
  "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.",
214
+ "Maintain a run-local refreshedPaidInmailSenderIds set. When get_refill_target_plan returns refresh_paid_inmail_credits candidates for selected paid-InMail lanes, refresh each exact sender at most once for this refill run, then rerun get_refill_target_plan before any prep/import/approval/start action.",
212
215
  "If paid InMail feasibility is below threshold, stale, or missing, report the exact sender/campaign/table/column threshold action or connection fallback; --yolo must not lower paid InMail thresholds or create campaigns.",
213
216
  "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.",
214
217
  "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.",
215
218
  ],
216
219
  approvalContract: yolo
217
- ? "Auto-accept only the rendered bounded refill target packet after get_refill_target_plan and fresh reread. 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."
220
+ ? "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."
218
221
  : hasSenderSelectors
219
222
  ? "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."
220
223
  : "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.",
@@ -4,6 +4,33 @@ const REFILL_TARGET_ACTION_TYPES = [
4
4
  "send_inmail_closed",
5
5
  ];
6
6
  const REFILL_TARGET_ACTION_SET = new Set(REFILL_TARGET_ACTION_TYPES);
7
+ const SAFE_PACKET_ACTION_TYPES = new Set([
8
+ "prepare_messages",
9
+ "approve_messages",
10
+ "start_paused_campaign",
11
+ "wait_for_scheduler",
12
+ "refresh_paid_inmail_credits",
13
+ "lower_paid_inmail_threshold",
14
+ "switch_to_connection_lane",
15
+ "create_connection_campaign",
16
+ ]);
17
+ const MANUAL_ONLY_PACKET_ACTION_TYPES = new Set([
18
+ "lower_paid_inmail_threshold",
19
+ "switch_to_connection_lane",
20
+ "create_connection_campaign",
21
+ ]);
22
+ const SOURCE_PLAN_STATES = new Set([
23
+ "not_needed",
24
+ "use_existing_rows",
25
+ "needs_signal_selection",
26
+ "needs_signal_import",
27
+ "waiting_for_import",
28
+ "needs_confirm",
29
+ "source_shortfall",
30
+ "provider_exhausted",
31
+ "provider_missing",
32
+ "blocked",
33
+ ]);
7
34
  async function postRefillTargetPlan(body) {
8
35
  const api = getApi();
9
36
  return api.post("/api/v3/mcp/refill-target-plan", body);
@@ -24,6 +51,17 @@ function actionTypesFrom(value) {
24
51
  function numberValue(value) {
25
52
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
26
53
  }
54
+ function stringValue(value) {
55
+ return typeof value === "string" ? value : undefined;
56
+ }
57
+ function booleanValue(value) {
58
+ return typeof value === "boolean" ? value : undefined;
59
+ }
60
+ function stringArray(value) {
61
+ if (!Array.isArray(value))
62
+ return [];
63
+ return value.filter((item) => typeof item === "string");
64
+ }
27
65
  function evidenceLatestMs(evidence) {
28
66
  const latestAt = evidence.latestAt;
29
67
  if (typeof latestAt !== "string")
@@ -72,9 +110,14 @@ function sanitizeCounts(counts, selectedKeys) {
72
110
  }
73
111
  function sanitizeActionCandidates(candidates, selectedKeys, status, remainingReadyOrProjectedGap, remainingProjectedGap) {
74
112
  const filtered = Array.isArray(candidates)
75
- ? candidates.filter((item) => {
113
+ ? candidates
114
+ .filter((item) => {
76
115
  if (!isRecord(item))
77
116
  return false;
117
+ if (typeof item.type !== "string" ||
118
+ !SAFE_PACKET_ACTION_TYPES.has(item.type)) {
119
+ return false;
120
+ }
78
121
  const actionType = item.actionType;
79
122
  if (actionType === undefined)
80
123
  return item.type === "wait_for_scheduler";
@@ -82,6 +125,7 @@ function sanitizeActionCandidates(candidates, selectedKeys, status, remainingRea
82
125
  const key = senderActionKey(item.senderId, allowed);
83
126
  return Boolean(key && selectedKeys.has(key));
84
127
  })
128
+ .map(sanitizeActionCandidate)
85
129
  : [];
86
130
  if (status === "awaiting_scheduler_after_ready_buffer" &&
87
131
  remainingProjectedGap > 0 &&
@@ -94,6 +138,344 @@ function sanitizeActionCandidates(candidates, selectedKeys, status, remainingRea
94
138
  }
95
139
  return filtered;
96
140
  }
141
+ function sanitizeActionCandidate(candidate) {
142
+ return {
143
+ type: candidate.type,
144
+ senderId: stringValue(candidate.senderId),
145
+ senderName: stringValue(candidate.senderName),
146
+ actionType: stringValue(candidate.actionType),
147
+ campaignId: stringValue(candidate.campaignId),
148
+ campaignName: stringValue(candidate.campaignName),
149
+ tableId: stringValue(candidate.tableId),
150
+ tableName: stringValue(candidate.tableName) ?? null,
151
+ columnId: stringValue(candidate.columnId) ?? null,
152
+ targetRows: typeof candidate.targetRows === "number" ? candidate.targetRows : undefined,
153
+ columnRole: stringValue(candidate.columnRole),
154
+ rowSelector: sanitizeRowSelector(candidate.rowSelector),
155
+ actionKey: stringValue(candidate.actionKey),
156
+ rereadAfter: candidate.rereadAfter === "get_refill_target_plan"
157
+ ? "get_refill_target_plan"
158
+ : undefined,
159
+ reason: stringValue(candidate.reason),
160
+ };
161
+ }
162
+ function sanitizeRowSelector(value) {
163
+ if (!isRecord(value) || typeof value.type !== "string")
164
+ return undefined;
165
+ if (![
166
+ "needsApproval",
167
+ "needsEnrichment",
168
+ "needsGeneratedMessage",
169
+ "staleGeneratedMessages",
170
+ "reviewBatch",
171
+ "rowIds",
172
+ ].includes(value.type)) {
173
+ return undefined;
174
+ }
175
+ return {
176
+ type: value.type,
177
+ ...(typeof value.limit === "number" ? { limit: value.limit } : {}),
178
+ ...(Array.isArray(value.rowIds) ? { rowIds: stringArray(value.rowIds) } : {}),
179
+ };
180
+ }
181
+ function sanitizeToolInput(value) {
182
+ if (!isRecord(value))
183
+ return {};
184
+ return {
185
+ senderId: stringValue(value.senderId),
186
+ campaignId: stringValue(value.campaignId),
187
+ tableId: stringValue(value.tableId),
188
+ columnId: stringValue(value.columnId) ?? null,
189
+ targetPreparedMessages: typeof value.targetPreparedMessages === "number"
190
+ ? value.targetPreparedMessages
191
+ : undefined,
192
+ approvalMode: value.approvalMode === "approve" || value.approvalMode === "mark_ready"
193
+ ? value.approvalMode
194
+ : undefined,
195
+ columnRole: stringValue(value.columnRole),
196
+ rowSelector: sanitizeRowSelector(value.rowSelector),
197
+ oldThreshold: typeof value.oldThreshold === "number" ? value.oldThreshold : undefined,
198
+ suggestedThreshold: typeof value.suggestedThreshold === "number"
199
+ ? value.suggestedThreshold
200
+ : undefined,
201
+ availableCredits: typeof value.availableCredits === "number"
202
+ ? value.availableCredits
203
+ : undefined,
204
+ threshold: typeof value.threshold === "number" ? value.threshold : undefined,
205
+ };
206
+ }
207
+ function sanitizePacketIds(value) {
208
+ if (!isRecord(value))
209
+ return {};
210
+ return {
211
+ senderId: stringValue(value.senderId),
212
+ campaignId: stringValue(value.campaignId),
213
+ tableId: stringValue(value.tableId),
214
+ columnId: stringValue(value.columnId) ?? null,
215
+ };
216
+ }
217
+ function sanitizeStructuredAction(action, selectedBySender, mode, rank) {
218
+ if (!isRecord(action) || typeof action.type !== "string")
219
+ return null;
220
+ if (!SAFE_PACKET_ACTION_TYPES.has(action.type))
221
+ return null;
222
+ if (mode === "next" && MANUAL_ONLY_PACKET_ACTION_TYPES.has(action.type)) {
223
+ return null;
224
+ }
225
+ const ids = sanitizePacketIds(action.ids);
226
+ const senderId = stringValue(ids.senderId);
227
+ if (senderId && !selectedBySender.has(senderId))
228
+ return null;
229
+ if (!senderId && action.type !== "wait_for_scheduler")
230
+ return null;
231
+ const yoloEligible = mode === "manual" || MANUAL_ONLY_PACKET_ACTION_TYPES.has(action.type)
232
+ ? false
233
+ : action.yoloEligible !== false;
234
+ return {
235
+ rank,
236
+ type: action.type,
237
+ toolName: stringValue(action.toolName) ?? null,
238
+ sideEffectClass: stringValue(action.sideEffectClass),
239
+ ids,
240
+ toolInput: sanitizeToolInput(action.toolInput),
241
+ inputSummary: stringValue(action.inputSummary) ?? "",
242
+ reason: stringValue(action.reason) ?? "",
243
+ prerequisites: stringArray(action.prerequisites),
244
+ rereadAfter: action.rereadAfter === "get_refill_target_plan"
245
+ ? "get_refill_target_plan"
246
+ : null,
247
+ stopCondition: stringValue(action.stopCondition) ?? "",
248
+ yoloEligible,
249
+ };
250
+ }
251
+ function sanitizeLedgerBlockers(value) {
252
+ if (!Array.isArray(value))
253
+ return [];
254
+ return value
255
+ .filter((blocker) => isRecord(blocker))
256
+ .filter((blocker) => !blocker.actionType || allowedActionType(blocker.actionType))
257
+ .map((blocker) => ({
258
+ code: stringValue(blocker.code) ?? "blocked",
259
+ detail: stringValue(blocker.detail),
260
+ actionType: stringValue(blocker.actionType),
261
+ campaignId: stringValue(blocker.campaignId),
262
+ tableId: stringValue(blocker.tableId),
263
+ message: stringValue(blocker.message),
264
+ }));
265
+ }
266
+ function sanitizeEligibleSenderLedger(value, selectedBySender) {
267
+ if (!Array.isArray(value))
268
+ return [];
269
+ return value
270
+ .filter((row) => {
271
+ if (!isRecord(row) || typeof row.senderId !== "string")
272
+ return false;
273
+ return selectedBySender.has(row.senderId);
274
+ })
275
+ .map((row) => {
276
+ const selectedLane = selectedBySender.get(row.senderId);
277
+ const eligibleActionTypes = actionTypesFrom(row.eligibleActionTypes).filter((actionType) => actionType === selectedLane);
278
+ return {
279
+ senderId: row.senderId,
280
+ senderName: stringValue(row.senderName) ?? "",
281
+ connected: row.connected === true,
282
+ salesNavConnected: booleanValue(row.salesNavConnected) ?? false,
283
+ status: stringValue(row.status) ?? "eligible",
284
+ eligibleActionTypes,
285
+ attachedCampaignIds: stringArray(row.attachedCampaignIds),
286
+ blockers: sanitizeLedgerBlockers(row.blockers),
287
+ };
288
+ });
289
+ }
290
+ function sanitizeCampaignRanking(value) {
291
+ if (!isRecord(value)) {
292
+ return {
293
+ selectedCampaignId: null,
294
+ selectedTableId: null,
295
+ selectedCampaignName: null,
296
+ selectedTableName: null,
297
+ options: [],
298
+ };
299
+ }
300
+ const options = Array.isArray(value.options)
301
+ ? value.options
302
+ .filter((option) => isRecord(option))
303
+ .map((option) => ({
304
+ rank: numberValue(option.rank),
305
+ campaignId: stringValue(option.campaignId) ?? "",
306
+ campaignName: stringValue(option.campaignName) ?? "",
307
+ tableId: stringValue(option.tableId) ?? "",
308
+ tableName: stringValue(option.tableName) ?? null,
309
+ campaignStatus: stringValue(option.campaignStatus) ?? null,
310
+ supportsSelectedLane: option.supportsSelectedLane === true,
311
+ rankSignals: stringArray(option.rankSignals),
312
+ rankReason: stringValue(option.rankReason) ?? "",
313
+ blockers: sanitizeLedgerBlockers(option.blockers),
314
+ }))
315
+ : [];
316
+ return {
317
+ selectedCampaignId: stringValue(value.selectedCampaignId) ?? null,
318
+ selectedTableId: stringValue(value.selectedTableId) ?? null,
319
+ selectedCampaignName: stringValue(value.selectedCampaignName) ?? null,
320
+ selectedTableName: stringValue(value.selectedTableName) ?? null,
321
+ options,
322
+ };
323
+ }
324
+ function sanitizeSourcePlan(value) {
325
+ if (!isRecord(value) || typeof value.state !== "string") {
326
+ return { state: "not_needed" };
327
+ }
328
+ return {
329
+ state: SOURCE_PLAN_STATES.has(value.state) ? value.state : "blocked",
330
+ reason: stringValue(value.reason),
331
+ campaignId: stringValue(value.campaignId),
332
+ tableId: stringValue(value.tableId),
333
+ remainingRowsNeeded: typeof value.remainingRowsNeeded === "number"
334
+ ? value.remainingRowsNeeded
335
+ : undefined,
336
+ };
337
+ }
338
+ function sanitizePaidInmail(value) {
339
+ if (!isRecord(value))
340
+ return null;
341
+ return {
342
+ status: stringValue(value.status) ?? "missing_credit_facts",
343
+ reason: stringValue(value.reason) ?? "",
344
+ checkedAt: stringValue(value.checkedAt) ?? null,
345
+ balance: typeof value.balance === "number" ? value.balance : null,
346
+ sentSince: numberValue(value.sentSince),
347
+ availableCredits: numberValue(value.availableCredits),
348
+ threshold: numberValue(value.threshold),
349
+ campaignId: stringValue(value.campaignId) ?? null,
350
+ campaignName: stringValue(value.campaignName) ?? null,
351
+ tableId: stringValue(value.tableId) ?? null,
352
+ tableName: stringValue(value.tableName) ?? null,
353
+ columnId: stringValue(value.columnId) ?? null,
354
+ suggestedThreshold: typeof value.suggestedThreshold === "number"
355
+ ? value.suggestedThreshold
356
+ : null,
357
+ };
358
+ }
359
+ function sanitizeStructuredSenderPlans(value, selectedBySender) {
360
+ if (!Array.isArray(value))
361
+ return [];
362
+ return value
363
+ .filter((plan) => {
364
+ if (!isRecord(plan) || typeof plan.senderId !== "string")
365
+ return false;
366
+ const selectedLane = allowedActionType(plan.selectedLane);
367
+ return Boolean(selectedLane && selectedBySender.get(plan.senderId) === selectedLane);
368
+ })
369
+ .map((plan) => {
370
+ const nextActions = Array.isArray(plan.nextActions)
371
+ ? plan.nextActions
372
+ .map((action, index) => sanitizeStructuredAction(action, selectedBySender, "next", index + 1))
373
+ .filter((action) => Boolean(action))
374
+ : [];
375
+ const manualAlternates = Array.isArray(plan.manualAlternates)
376
+ ? plan.manualAlternates
377
+ .map((action, index) => sanitizeStructuredAction(action, selectedBySender, "manual", index + 1))
378
+ .filter((action) => Boolean(action))
379
+ : [];
380
+ return {
381
+ senderId: plan.senderId,
382
+ senderName: stringValue(plan.senderName) ?? "",
383
+ status: stringValue(plan.status) ?? "needs_refill",
384
+ selectedLane: allowedActionType(plan.selectedLane),
385
+ horizon: isRecord(plan.horizon)
386
+ ? {
387
+ selectedDays: Array.isArray(plan.horizon.selectedDays)
388
+ ? plan.horizon.selectedDays
389
+ : [],
390
+ grossTarget: numberValue(plan.horizon.grossTarget),
391
+ schedulerFillableSlots: typeof plan.horizon.schedulerFillableSlots === "number"
392
+ ? plan.horizon.schedulerFillableSlots
393
+ : null,
394
+ schedulerFillableSlotsKnown: plan.horizon.schedulerFillableSlotsKnown === true,
395
+ capacityConfidence: stringValue(plan.horizon.capacityConfidence) ?? "unknown",
396
+ schedulerCapacityMode: stringValue(plan.horizon.schedulerCapacityMode),
397
+ }
398
+ : {},
399
+ coverage: isRecord(plan.coverage)
400
+ ? {
401
+ goal: numberValue(plan.coverage.goal),
402
+ alreadySent: numberValue(plan.coverage.alreadySent),
403
+ scheduled: numberValue(plan.coverage.scheduled),
404
+ readyAndWaitingToBeScheduled: numberValue(plan.coverage.readyAndWaitingToBeScheduled),
405
+ stillNeed: numberValue(plan.coverage.stillNeed),
406
+ needToPrepare: numberValue(plan.coverage.needToPrepare),
407
+ coveredTotal: typeof plan.coverage.coveredTotal === "number"
408
+ ? plan.coverage.coveredTotal
409
+ : undefined,
410
+ }
411
+ : {},
412
+ coverageDisplay: stringArray(plan.coverageDisplay),
413
+ campaignRanking: sanitizeCampaignRanking(plan.campaignRanking),
414
+ paidInmail: sanitizePaidInmail(plan.paidInmail),
415
+ sourcePlan: sanitizeSourcePlan(plan.sourcePlan),
416
+ nextActions,
417
+ manualAlternates,
418
+ ...(isRecord(plan.emptyState)
419
+ ? {
420
+ emptyState: {
421
+ code: stringValue(plan.emptyState.code) ?? "blocked",
422
+ reason: stringValue(plan.emptyState.reason) ?? "",
423
+ blockerCodes: stringArray(plan.emptyState.blockerCodes),
424
+ },
425
+ }
426
+ : {}),
427
+ };
428
+ });
429
+ }
430
+ function buildSanitizedGlobalActionQueue(senderRefillPlans) {
431
+ return senderRefillPlans
432
+ .flatMap((plan) => Array.isArray(plan.nextActions) ? plan.nextActions.slice(0, 1) : [])
433
+ .filter((action) => isRecord(action))
434
+ .map((action, index) => ({
435
+ ...action,
436
+ rank: index + 1,
437
+ }));
438
+ }
439
+ function emptyUnsupportedResult(result) {
440
+ if (!isRecord(result) || !isRecord(result.target))
441
+ return result;
442
+ return {
443
+ ...result,
444
+ status: "blocked",
445
+ request: isRecord(result.request)
446
+ ? { ...result.request, actionTypes: [] }
447
+ : result.request,
448
+ target: {
449
+ ...result.target,
450
+ actionSelections: [],
451
+ selectedDays: [],
452
+ senderPlans: [],
453
+ eligibleSenderLedger: [],
454
+ senderRefillPlans: [],
455
+ globalActionQueue: [],
456
+ grossTarget: 0,
457
+ sent: 0,
458
+ scheduled: 0,
459
+ projected: 0,
460
+ readyBuffer: 0,
461
+ remainingScheduledGap: 0,
462
+ remainingProjectedGap: 0,
463
+ remainingReadyOrProjectedGap: 0,
464
+ remainingReadyOrScheduledGap: 0,
465
+ },
466
+ coverage: isRecord(result.coverage)
467
+ ? {
468
+ ...result.coverage,
469
+ sentCounts: [],
470
+ scheduledCounts: [],
471
+ readyCounts: [],
472
+ }
473
+ : result.coverage,
474
+ actionCandidates: [],
475
+ blockers: [],
476
+ mcpSanitizedRefillLanes: true,
477
+ };
478
+ }
97
479
  function sanitizeBlockers(blockers, selectedKeys) {
98
480
  if (!Array.isArray(blockers))
99
481
  return [];
@@ -157,7 +539,7 @@ function sanitizeRefillTargetPlanResult(result) {
157
539
  const selectedKeys = new Set([...selectedBySender.entries()].map(([senderId, actionType]) => `${senderId}:${actionType}`));
158
540
  const actionTypes = [...new Set(selectedBySender.values())];
159
541
  if (selectedKeys.size === 0)
160
- return result;
542
+ return emptyUnsupportedResult(result);
161
543
  const senderPlans = rawSenderPlans.filter((plan) => isRecord(plan) &&
162
544
  selectedKeys.has(`${String(plan.senderId)}:${String(plan.actionType)}`));
163
545
  const selectedDays = Array.isArray(target.selectedDays)
@@ -188,13 +570,18 @@ function sanitizeRefillTargetPlanResult(result) {
188
570
  const remainingProjectedGap = senderPlans.reduce((sum, plan) => sum + numberValue(plan.remainingProjectedGap), 0);
189
571
  const remainingReadyOrProjectedGap = senderPlans.reduce((sum, plan) => sum + numberValue(plan.remainingReadyOrProjectedGap), 0);
190
572
  const blockers = sanitizeBlockers(result.blockers, selectedKeys);
191
- const status = blockers.some((blocker) => ["sender_disconnected", "sender_sales_nav_disconnected"].includes(String(blocker.code))) || grossTarget <= 0
573
+ const eligibleSenderLedger = sanitizeEligibleSenderLedger(target.eligibleSenderLedger, selectedBySender);
574
+ const senderRefillPlans = sanitizeStructuredSenderPlans(target.senderRefillPlans, selectedBySender);
575
+ const globalActionQueue = buildSanitizedGlobalActionQueue(senderRefillPlans);
576
+ const status = blockers.some((blocker) => ["sender_disconnected", "sender_sales_nav_disconnected"].includes(String(blocker.code)))
192
577
  ? "blocked"
193
578
  : remainingProjectedGap === 0
194
579
  ? "complete"
195
- : remainingReadyOrProjectedGap === 0
196
- ? "awaiting_scheduler_after_ready_buffer"
197
- : "needs_refill";
580
+ : grossTarget <= 0
581
+ ? "blocked"
582
+ : remainingReadyOrProjectedGap === 0
583
+ ? "awaiting_scheduler_after_ready_buffer"
584
+ : "needs_refill";
198
585
  return {
199
586
  ...result,
200
587
  status,
@@ -206,6 +593,9 @@ function sanitizeRefillTargetPlanResult(result) {
206
593
  actionSelections,
207
594
  selectedDays,
208
595
  senderPlans,
596
+ eligibleSenderLedger,
597
+ senderRefillPlans,
598
+ globalActionQueue,
209
599
  grossTarget,
210
600
  sent,
211
601
  scheduled,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sellable/mcp",
3
- "version": "0.1.471",
3
+ "version": "0.1.473",
4
4
  "type": "module",
5
5
  "description": "Sellable MCP server for Claude Code and Codex campaign workflows",
6
6
  "main": "dist/index.js",
@@ -143,6 +143,39 @@ two lanes to fill. If a stale target plan selects `send_dm` or
143
143
  `send_inmail_open`, stop and re-plan with the current planner before mutation.
144
144
  Short form: trust the target plan's inferred lane only when it is a
145
145
  connection-invite or paid-InMail refill lane.
146
+
147
+ Structured planner packet:
148
+
149
+ - `target.eligibleSenderLedger` is the public sender eligibility ledger.
150
+ - `target.senderRefillPlans[]` is the canonical sender-level packet; read and
151
+ display it before mutation.
152
+ - Each sender packet includes `campaignRanking.options`, `sourcePlan`,
153
+ `nextActions`, and `manualAlternates`.
154
+ - Preserve these coverage labels exactly: `Need to prepare`, `Goal`,
155
+ `Already sent`, `Scheduled`, `Ready and waiting to be scheduled`, and
156
+ `Still need`.
157
+ - `target.globalActionQueue` is the only cross-sender yolo execution queue.
158
+ Execute exactly one globally ranked primitive from
159
+ `target.globalActionQueue[0]`, then rerun `get_refill_target_plan` before
160
+ choosing another action.
161
+ - `manualAlternates` are not yolo actions. Threshold lowering and campaign
162
+ creation are manual continuations only.
163
+
164
+ Run-local paid-credit guard: maintain a `refreshedPaidInmailSenderIds` set for
165
+ the current command call. Refresh each selected sender at most once per refill
166
+ command call, then rerun `get_refill_target_plan`. If fresh facts are still
167
+ below threshold, below-threshold paid-InMail facts fall back to an existing
168
+ connection lane or a manual continuation.
169
+
170
+ Compact refill lessons: sender-level target plan is final truth; trust
171
+ `schedulerGate.sendable` and scheduler gate blockers, not raw
172
+ `unipileAccountStatus` labels alone; use compact prep status checks for
173
+ long-running jobs; reread target plans after prep or cancel; treat ready rows as
174
+ intermediate; avoid huge parallel target-plan reads when output is large. If a
175
+ campaign produces prepared/ready rows but sender-level projected coverage does
176
+ not move after one bounded settle loop, pivot to compact prep status or a
177
+ scheduler-proven lane. Do not keep waiting on campaign-level ready counts.
178
+
146
179
  For exact-date requests, pass `targetDate` to `get_refill_target_plan`. If you
147
180
  need raw proof, call the read-only `get_scheduler_fill_capacity` query for the
148
181
  same sender/action/date; it tells the MCP how many cells the product scheduler
@@ -160,10 +193,11 @@ state, not a close-out condition.
160
193
  If paid InMail credit facts are stale or missing and the target plan returns a
161
194
  `refresh_paid_inmail_credits` action candidate, include the exact sender id,
162
195
  campaign/table/column proof, expected sender-credit-cache writes, and rerun plan
163
- step in the bounded packet. After `refresh_paid_inmail_credits`, rerun
164
- `get_refill_target_plan` before any prep/import/approval/start action. If paid
165
- InMail is below threshold after a fresh credit read, report the exact
166
- campaign/table/column threshold action or connection fallback; `--yolo` does not lower paid-InMail thresholds or create campaigns.
196
+ step in the bounded packet. In `--yolo`, refresh each exact selected sender at
197
+ most once for the current refill run, then rerun `get_refill_target_plan` before
198
+ any prep/import/approval/start action. If paid InMail is below threshold after a
199
+ fresh credit read, report the exact campaign/table/column threshold action or
200
+ connection fallback; `--yolo` does not lower paid-InMail thresholds or create campaigns.
167
201
 
168
202
  If the plain route's managed waterfall targets are stale, for example skipped
169
203
  targets show archived/completed shared slots or the returned targets do not cover
@@ -219,7 +253,7 @@ apply/prep/start result, reread state, settle processing when needed, and move t
219
253
  the next selected sender or start-eligible same-packet campaign instead of
220
254
  stopping after the first partial result. If no in-packet safe action remains,
221
255
  return concrete continuation options with campaign names, exact ids, which option
222
- is already covered by the current packet, and which option needs a new approval
256
+ is still covered by the current packet, and which option needs a new approval
223
257
  packet.
224
258
 
225
259
  For `--yolo` fill/schedule requests, completion means projected saturation
@@ -89,6 +89,36 @@ in-progress wait state, not a reason to mark the goal complete or blocked.
89
89
  mutation.
90
90
  Short form: trust the target plan's inferred lane only when it is a
91
91
  connection-invite or paid-InMail refill lane.
92
+ Structured planner packet:
93
+ - `target.eligibleSenderLedger` is the public sender eligibility ledger.
94
+ - `target.senderRefillPlans[]` is the canonical sender-level packet; read and
95
+ display it before mutation.
96
+ - Each sender packet includes `campaignRanking.options`, `sourcePlan`,
97
+ `nextActions`, and `manualAlternates`.
98
+ - Preserve these coverage labels exactly: `Need to prepare`, `Goal`,
99
+ `Already sent`, `Scheduled`, `Ready and waiting to be scheduled`, and
100
+ `Still need`.
101
+ - `target.globalActionQueue` is the only cross-sender yolo execution queue.
102
+ execute exactly one globally ranked primitive from
103
+ `target.globalActionQueue[0]`, then rerun `get_refill_target_plan` before
104
+ choosing another action.
105
+ - `nextActions[0]` is the current sender's smallest safe primitive.
106
+ - `manualAlternates` are not yolo actions. Threshold lowering and campaign
107
+ creation are manual continuations only.
108
+ Run-local paid-credit guard: maintain a `refreshedPaidInmailSenderIds` set
109
+ for the current command call. refresh each selected sender at most once per
110
+ refill command call, then rerun `get_refill_target_plan`. If fresh facts are
111
+ still below threshold, below-threshold paid-InMail facts fall back to an
112
+ existing connection lane or a manual continuation.
113
+ Compact refill lessons: sender-level target plan is final truth; trust
114
+ `schedulerGate.sendable` and scheduler gate blockers, not raw
115
+ `unipileAccountStatus` labels alone; use compact prep status checks for
116
+ long-running jobs; reread target plans after prep or cancel; treat ready rows
117
+ as intermediate; avoid huge parallel target-plan reads when output is large.
118
+ If a campaign produces prepared/ready rows but sender-level projected
119
+ coverage does not move after one bounded settle loop, pivot to compact prep
120
+ status or a scheduler-proven lane. Do not keep waiting on campaign-level
121
+ ready counts.
92
122
  For exact-date requests, pass `targetDate` to `get_refill_target_plan`.
93
123
  When you need raw diagnostic proof, call `get_scheduler_fill_capacity` for
94
124
  the same exact sender/action/date. That query is read-only and tells the MCP
@@ -109,10 +139,11 @@ in-progress wait state, not a reason to mark the goal complete or blocked.
109
139
  If paid InMail credit facts are stale or missing and the target plan returns a
110
140
  `refresh_paid_inmail_credits` action candidate, include the exact sender id,
111
141
  campaign/table/column proof, expected sender-credit-cache write, and rerun plan
112
- step in the bounded packet. After `refresh_paid_inmail_credits`, rerun
113
- `get_refill_target_plan` before any prep/import/approval/start action. If paid
114
- InMail is below threshold after a fresh credit read, report the exact
115
- campaign/table/column threshold action or connection fallback; `--yolo` does not lower paid-InMail thresholds or create campaigns.
142
+ step in the bounded packet. In `--yolo`, refresh each exact selected sender at
143
+ most once for the current refill run, then rerun `get_refill_target_plan` before
144
+ any prep/import/approval/start action. If paid InMail is below threshold after a
145
+ fresh credit read, report the exact campaign/table/column threshold action or
146
+ connection fallback; `--yolo` does not lower paid-InMail thresholds or create campaigns.
116
147
  2. Call `resolve_campaign_fill_route`. Use `intent:"plain"` for generic
117
148
  fill/load language, `intent:"active"` only when the user explicitly narrowed
118
149
  to active regular campaigns or when the plain route has stale managed