@sellable/mcp 0.1.534 → 0.1.535

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index-dev.js CHANGED
File without changes
package/dist/index.js CHANGED
File without changes
@@ -1,6 +1,6 @@
1
1
  import { SellableApiError } from "./api.js";
2
2
  import { buildRunStateFromLocalHints } from "./tools/evergreen-refill-plan.js";
3
- import { prepareRowSelectorValue as defaultPrepareRowSelectorValue, refillPrepareRequestHash as defaultRefillPrepareRequestHash, } from "./tools/refill-executors.js";
3
+ import { classifyPaidInmailRefreshReceipt, prepareRowSelectorValue as defaultPrepareRowSelectorValue, refillPrepareRequestHash as defaultRefillPrepareRequestHash, } from "./tools/refill-executors.js";
4
4
  const DEFAULT_BUDGETS = {
5
5
  maxGateCyclesPerInvocation: 8,
6
6
  pollIntervalMs: 15_000,
@@ -19,43 +19,6 @@ const REFILL_DONE_REASONS = new Set([
19
19
  "not_an_evergreen_workspace",
20
20
  "no_refillable_campaigns",
21
21
  ]);
22
- const SCHEDULER_RUN_ENVELOPE_STATUSES = new Set([
23
- "ran",
24
- "attached",
25
- "backoff",
26
- "window_closed_noop",
27
- "failed",
28
- ]);
29
- const SCHEDULER_RUN_RECEIPT_STATUSES = new Set([
30
- "ran",
31
- "window_closed_noop",
32
- "failed",
33
- ]);
34
- const SCHEDULER_RUN_SKIP_REASONS = [
35
- "window_closed",
36
- "daily_limit",
37
- "cooldown",
38
- "sender_gate",
39
- "credit_threshold",
40
- "billing_blocked",
41
- "duplicate_lead",
42
- "no_senders",
43
- "other",
44
- ];
45
- const SCHEDULER_RUN_HARD_BLOCK_REASONS = new Set([
46
- "billing_blocked",
47
- "credit_threshold",
48
- "cooldown",
49
- ]);
50
- const SCHEDULER_RUN_NEXT_ACTIONS = new Set([
51
- "refresh_paid_inmail_credits_then_rerun",
52
- "wait_for_capacity_or_window",
53
- "inspect_sender_mismatch",
54
- "no_ready_cells_continue_refill_prep",
55
- "scheduled_cells",
56
- "investigate_deferred_reasons",
57
- "investigate_scheduler_failure",
58
- ]);
59
22
  function isRecord(value) {
60
23
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
61
24
  }
@@ -77,253 +40,6 @@ function arrayValue(value) {
77
40
  function hasBlocker(value, blocker) {
78
41
  return isRecord(value) && value.blocker === blocker;
79
42
  }
80
- function schedulerRunSkipReasons(value) {
81
- const raw = recordValue(value) ?? {};
82
- const normalized = {};
83
- for (const reason of SCHEDULER_RUN_SKIP_REASONS) {
84
- normalized[reason] = numberValue(raw[reason]) ?? 0;
85
- }
86
- return normalized;
87
- }
88
- function schedulerRunCountMap(value) {
89
- const raw = recordValue(value) ?? {};
90
- return Object.fromEntries(Object.entries(raw)
91
- .map(([key, rawCount]) => [key, numberValue(rawCount) ?? 0])
92
- .filter(([, count]) => count > 0)
93
- .sort(([left], [right]) => left.localeCompare(right)));
94
- }
95
- function schedulerRunNestedCountMap(value) {
96
- const raw = recordValue(value) ?? {};
97
- return Object.fromEntries(Object.entries(raw)
98
- .map(([key, nested]) => [key, schedulerRunCountMap(nested)])
99
- .filter(([, nested]) => Object.keys(nested).length > 0)
100
- .sort(([left], [right]) => left.localeCompare(right)));
101
- }
102
- function dominantSchedulerRunSkipReason(skipReasons) {
103
- let dominant = null;
104
- let dominantCount = 0;
105
- for (const reason of SCHEDULER_RUN_SKIP_REASONS) {
106
- const count = skipReasons[reason] ?? 0;
107
- if (count > dominantCount) {
108
- dominant = reason;
109
- dominantCount = count;
110
- }
111
- }
112
- return dominantCount > 0 ? dominant : null;
113
- }
114
- function dominantSchedulerRunCountReason(counts) {
115
- let dominant = null;
116
- let dominantCount = 0;
117
- for (const reason of Object.keys(counts).sort()) {
118
- const count = counts[reason] ?? 0;
119
- if (count > dominantCount) {
120
- dominant = reason;
121
- dominantCount = count;
122
- }
123
- }
124
- return dominantCount > 0 ? dominant : null;
125
- }
126
- function schedulerRunReasonLooksLike(reasons, pattern) {
127
- return Object.keys(reasons).some((reason) => (reasons[reason] ?? 0) > 0 && pattern.test(reason));
128
- }
129
- function schedulerRunHasReason(reasons, reason) {
130
- return (reasons[reason] ?? 0) > 0;
131
- }
132
- function schedulerRunRecommendedAction(params) {
133
- if (params.rawAction && SCHEDULER_RUN_NEXT_ACTIONS.has(params.rawAction)) {
134
- return params.rawAction;
135
- }
136
- if (schedulerRunReasonLooksLike(params.prefilterReasons, /(credit|paid[_ -]?inmail|stale[_ -]?credit|missing[_ -]?credit)/i) ||
137
- schedulerRunHasReason(params.skippedReasons, "credit_threshold") ||
138
- schedulerRunHasReason(params.deferredReasons, "credit_threshold")) {
139
- return "refresh_paid_inmail_credits_then_rerun";
140
- }
141
- if (schedulerRunReasonLooksLike(params.prefilterReasons, /sender[_ -]?mismatch/i)) {
142
- return "inspect_sender_mismatch";
143
- }
144
- if (schedulerRunReasonLooksLike(params.prefilterReasons, /(no[_ -]?capacity|capacity|window|daily[_ -]?limit|cooldown)/i) ||
145
- schedulerRunHasReason(params.skippedReasons, "window_closed") ||
146
- schedulerRunHasReason(params.skippedReasons, "daily_limit") ||
147
- schedulerRunHasReason(params.skippedReasons, "cooldown") ||
148
- schedulerRunHasReason(params.deferredReasons, "window_closed") ||
149
- schedulerRunHasReason(params.deferredReasons, "daily_limit") ||
150
- schedulerRunHasReason(params.deferredReasons, "cooldown")) {
151
- return "wait_for_capacity_or_window";
152
- }
153
- if (params.cellsScheduled > 0)
154
- return "scheduled_cells";
155
- if (params.readyCellsFound === 0)
156
- return "no_ready_cells_continue_refill_prep";
157
- if (params.cellsConsidered > 0)
158
- return "investigate_deferred_reasons";
159
- return null;
160
- }
161
- function schedulerRunCampaignScopeSummary(value) {
162
- const raw = recordValue(value);
163
- if (!raw) {
164
- return {
165
- totalEligibleTables: 0,
166
- tablesWithReadyCells: 0,
167
- returnedTables: 0,
168
- omittedTables: 0,
169
- truncated: false,
170
- tables: [],
171
- };
172
- }
173
- const rawTables = arrayValue(raw.tables).slice(0, 25);
174
- const tables = rawTables
175
- .map((entry) => {
176
- const table = recordValue(entry);
177
- if (!table)
178
- return null;
179
- const tableId = stringValue(table.tableId);
180
- if (!tableId)
181
- return null;
182
- return {
183
- tableId,
184
- tableName: stringValue(table.tableName),
185
- workspaceId: stringValue(table.workspaceId),
186
- campaignOfferId: stringValue(table.campaignOfferId),
187
- campaignName: stringValue(table.campaignName),
188
- readyCells: numberValue(table.readyCells) ?? 0,
189
- readyCellsByType: schedulerRunCountMap(table.readyCellsByType),
190
- consideredCells: numberValue(table.consideredCells) ?? 0,
191
- consideredCellsByType: schedulerRunCountMap(table.consideredCellsByType),
192
- prefilteredCells: numberValue(table.prefilteredCells) ?? 0,
193
- prefilterReasons: schedulerRunCountMap(table.prefilterReasons),
194
- prefilterReasonsByType: schedulerRunNestedCountMap(table.prefilterReasonsByType),
195
- };
196
- })
197
- .filter((entry) => entry != null);
198
- return {
199
- totalEligibleTables: numberValue(raw.totalEligibleTables) ?? 0,
200
- tablesWithReadyCells: numberValue(raw.tablesWithReadyCells) ?? tables.length,
201
- returnedTables: tables.length,
202
- omittedTables: numberValue(raw.omittedTables) ?? 0,
203
- truncated: booleanValue(raw.truncated) ?? false,
204
- tables,
205
- };
206
- }
207
- function sanitizeSchedulerRunReceipt(raw) {
208
- const envelope = recordValue(raw);
209
- if (!envelope)
210
- return null;
211
- const status = stringValue(envelope.status);
212
- if (!status || !SCHEDULER_RUN_ENVELOPE_STATUSES.has(status))
213
- return null;
214
- const retryAfterMs = envelope.retryAfterMs == null ? null : numberValue(envelope.retryAfterMs);
215
- if (envelope.retryAfterMs != null && retryAfterMs == null)
216
- return null;
217
- const receiptInput = envelope.receipt;
218
- let receipt = null;
219
- let dominantSkipReason = null;
220
- let dominantPrefilterReason = null;
221
- let dominantDeferredReason = null;
222
- let recommendedNextAction = null;
223
- if (receiptInput != null) {
224
- const rawReceipt = recordValue(receiptInput);
225
- if (!rawReceipt)
226
- return null;
227
- const receiptStatus = stringValue(rawReceipt.status);
228
- if (!receiptStatus || !SCHEDULER_RUN_RECEIPT_STATUSES.has(receiptStatus)) {
229
- return null;
230
- }
231
- const cellsConsidered = numberValue(rawReceipt.cellsConsidered);
232
- const cellsScheduled = numberValue(rawReceipt.cellsScheduled);
233
- const cellsSkipped = numberValue(rawReceipt.cellsSkipped);
234
- const cellsDeferred = numberValue(rawReceipt.cellsDeferred);
235
- const tablesFilteredForNoCapacity = numberValue(rawReceipt.tablesFilteredForNoCapacity);
236
- if (cellsConsidered == null ||
237
- cellsScheduled == null ||
238
- cellsSkipped == null ||
239
- cellsDeferred == null ||
240
- tablesFilteredForNoCapacity == null) {
241
- return null;
242
- }
243
- const skipReasons = schedulerRunSkipReasons(rawReceipt.skipReasons);
244
- const skippedReasons = rawReceipt.skippedReasons
245
- ? schedulerRunSkipReasons(rawReceipt.skippedReasons)
246
- : skipReasons;
247
- const deferredReasons = rawReceipt.deferredReasons
248
- ? schedulerRunSkipReasons(rawReceipt.deferredReasons)
249
- : schedulerRunSkipReasons(null);
250
- const prefilterReasons = schedulerRunCountMap(rawReceipt.prefilterReasons);
251
- const prefilterReasonsByType = schedulerRunNestedCountMap(rawReceipt.prefilterReasonsByType);
252
- const readyCellsByType = schedulerRunCountMap(rawReceipt.readyCellsByType);
253
- const consideredCellsByType = schedulerRunCountMap(rawReceipt.consideredCellsByType);
254
- const prefilteredCellsByType = schedulerRunCountMap(rawReceipt.prefilteredCellsByType);
255
- const readyCellsFound = numberValue(rawReceipt.readyCellsFound) ?? cellsConsidered;
256
- const prefilteredCells = numberValue(rawReceipt.prefilteredCells) ?? 0;
257
- const tablesFilteredForSenderMismatch = numberValue(rawReceipt.tablesFilteredForSenderMismatch) ?? 0;
258
- dominantSkipReason = dominantSchedulerRunSkipReason(skipReasons);
259
- dominantPrefilterReason =
260
- dominantSchedulerRunCountReason(prefilterReasons);
261
- dominantDeferredReason =
262
- dominantSchedulerRunSkipReason(deferredReasons);
263
- recommendedNextAction = schedulerRunRecommendedAction({
264
- rawAction: stringValue(rawReceipt.nextAction),
265
- readyCellsFound,
266
- cellsConsidered,
267
- cellsScheduled,
268
- prefilterReasons,
269
- skippedReasons,
270
- deferredReasons,
271
- });
272
- receipt = {
273
- status: receiptStatus,
274
- ...(numberValue(rawReceipt.receiptVersion) != null
275
- ? { receiptVersion: numberValue(rawReceipt.receiptVersion) }
276
- : {}),
277
- ...(numberValue(rawReceipt.diagnosticsVersion) != null
278
- ? { diagnosticsVersion: numberValue(rawReceipt.diagnosticsVersion) }
279
- : {}),
280
- readyCellsFound,
281
- readyCellsByType,
282
- cellsConsidered,
283
- consideredCellsByType,
284
- cellsScheduled,
285
- cellsSkipped,
286
- cellsDeferred,
287
- prefilteredCells,
288
- prefilteredCellsByType,
289
- tablesFilteredForNoCapacity,
290
- tablesFilteredForSenderMismatch,
291
- prefilterReasons,
292
- prefilterReasonsByType,
293
- skippedReasons,
294
- deferredReasons,
295
- skipReasons,
296
- campaignScopeSummary: schedulerRunCampaignScopeSummary(rawReceipt.campaignScopeSummary),
297
- ...(stringValue(rawReceipt.summary)
298
- ? { summary: stringValue(rawReceipt.summary) }
299
- : {}),
300
- ...(recommendedNextAction ? { nextAction: recommendedNextAction } : {}),
301
- };
302
- }
303
- return {
304
- status,
305
- retryAfterMs,
306
- receipt,
307
- dominantSkipReason,
308
- dominantPrefilterReason,
309
- dominantDeferredReason,
310
- recommendedNextAction,
311
- hardBlocked: (dominantSkipReason != null &&
312
- SCHEDULER_RUN_HARD_BLOCK_REASONS.has(dominantSkipReason)) ||
313
- (dominantDeferredReason != null &&
314
- SCHEDULER_RUN_HARD_BLOCK_REASONS.has(dominantDeferredReason)) ||
315
- recommendedNextAction === "refresh_paid_inmail_credits_then_rerun",
316
- };
317
- }
318
- function schedulerRunReceiptIsFreshZeroScheduled(schedulerRunReceipt) {
319
- const status = stringValue(schedulerRunReceipt?.status);
320
- const fresh = status === "ran" || status === "window_closed_noop";
321
- if (!fresh)
322
- return false;
323
- const receipt = recordValue(schedulerRunReceipt?.receipt);
324
- return (status === "window_closed_noop" ||
325
- numberValue(receipt?.cellsScheduled) === 0);
326
- }
327
43
  function isLeaseLost(value) {
328
44
  return hasBlocker(value, "lease_lost");
329
45
  }
@@ -760,22 +476,31 @@ async function gateBootstrap(input, deps, ctx) {
760
476
  const refreshedSenderIds = new Set(arrayValue(recordValue(ctx.runState.creditTrust)?.senderIds)
761
477
  .map((entry) => stringValue(entry))
762
478
  .filter((entry) => Boolean(entry)));
479
+ const attemptedSenderIds = new Set(arrayValue(recordValue(ctx.runState.creditTrust)?.attemptedSenderIds)
480
+ .map((entry) => stringValue(entry))
481
+ .filter((entry) => Boolean(entry)));
763
482
  const receipts = [];
764
483
  for (const entry of paidCredit) {
765
484
  const senderId = stringValue(entry.senderId);
766
485
  if (!senderId ||
767
486
  !entry.plannedJitRefresh ||
768
- refreshedSenderIds.has(senderId)) {
487
+ refreshedSenderIds.has(senderId) ||
488
+ attemptedSenderIds.has(senderId)) {
769
489
  continue;
770
490
  }
771
491
  const receipt = await deps.executors.refreshPaidInmailCreditsWithRetry(senderId, input.workspaceId);
772
- receipts.push({ senderId, receipt });
773
- refreshedSenderIds.add(senderId);
492
+ attemptedSenderIds.add(senderId);
493
+ const classification = classifyPaidInmailRefreshReceipt(receipt.receipt);
494
+ receipts.push({ senderId, receipt, classification });
495
+ if (classification.usableCurrentFacts) {
496
+ refreshedSenderIds.add(senderId);
497
+ }
774
498
  }
775
499
  const nextRunState = mergeRunState(ctx.runState, {
776
500
  creditTrust: {
777
501
  refreshedAt: (deps.now?.() ?? new Date()).toISOString(),
778
502
  senderIds: [...refreshedSenderIds],
503
+ attemptedSenderIds: [...attemptedSenderIds],
779
504
  receipts,
780
505
  },
781
506
  });
@@ -1297,34 +1022,42 @@ async function verifySchedulerWait(input, deps, ctx, action, budgets) {
1297
1022
  const enteredAt = stringValue(progress.schedulerWaitEnteredAt) ??
1298
1023
  (deps.now?.() ?? new Date()).toISOString();
1299
1024
  const jitFired = booleanValue(progress.schedulerJitFired) ?? false;
1300
- let schedulerRunReceipt = recordValue(progress.schedulerRunReceipt) ?? null;
1301
1025
  if (!jitFired) {
1302
1026
  const senderId = actionSenderId(action);
1303
1027
  if (senderId) {
1304
- await deps.executors.refreshPaidInmailCreditsWithRetry(senderId, input.workspaceId);
1028
+ const refresh = await deps.executors.refreshPaidInmailCreditsWithRetry(senderId, input.workspaceId);
1029
+ const classification = classifyPaidInmailRefreshReceipt(refresh.receipt);
1030
+ if (!classification.usableCurrentFacts) {
1031
+ return {
1032
+ status: "blocked",
1033
+ blocker: "paid_inmail_refresh_failed",
1034
+ runId: ctx.runId,
1035
+ fence: ctx.fence,
1036
+ gate: ctx.gate,
1037
+ guidance: "Paid InMail credit refresh did not return usable current facts, so scheduler JIT was not requested.",
1038
+ report: {
1039
+ senderId,
1040
+ receiptStatus: classification.status,
1041
+ error: classification.error,
1042
+ receipt: refresh.receipt,
1043
+ attempts: refresh.attempts,
1044
+ errors: refresh.errors,
1045
+ },
1046
+ journalPath: ctx.journalPath,
1047
+ };
1048
+ }
1305
1049
  }
1306
1050
  if (deps.requestSchedulerRun) {
1307
- try {
1308
- schedulerRunReceipt = sanitizeSchedulerRunReceipt(await deps.requestSchedulerRun(input.workspaceId));
1309
- }
1310
- catch {
1311
- schedulerRunReceipt = null;
1312
- }
1051
+ await deps.requestSchedulerRun(input.workspaceId);
1313
1052
  }
1314
1053
  ctx.runState = mergeRunState(ctx.runState, {
1315
1054
  progress: mergeProgress(ctx, {
1316
1055
  schedulerWaitEnteredAt: enteredAt,
1317
1056
  schedulerJitFired: true,
1318
- ...(schedulerRunReceipt ? { schedulerRunReceipt } : {}),
1319
1057
  }),
1320
1058
  });
1321
1059
  }
1322
- const zeroScheduledFresh = schedulerRunReceiptIsFreshZeroScheduled(schedulerRunReceipt);
1323
- // EDGE-2: the on-demand run only executes placement; cron can still process
1324
- // due/timed-out cells later. We still do one readback, then avoid burning the
1325
- // full wait budget when the fresh receipt says nothing was placeable now.
1326
- const readbackBudget = zeroScheduledFresh ? 1 : budgets.maxSchedulerReadbacks;
1327
- for (let poll = 0; poll < readbackBudget; poll += 1) {
1060
+ for (let poll = 0; poll < budgets.maxSchedulerReadbacks; poll += 1) {
1328
1061
  const fresh = await deps.readPlan({
1329
1062
  workspaceId: input.workspaceId,
1330
1063
  intent: input.intent,
package/dist/server.js CHANGED
@@ -45,7 +45,6 @@ import { allTools } from "./tools/registry.js";
45
45
  import { getRows, getTableRows, getTableRowsMinimal } from "./tools/rows.js";
46
46
  import { addRubricItem, checkRubric, deleteRubricItem, draftRubrics, saveRubrics, selectNecessaryRubrics, updateRubricItem, waitForRubricResults, } from "./tools/rubrics.js";
47
47
  import { getSchedulerFillCapacity } from "./tools/scheduler-fill-capacity.js";
48
- import { runSchedulerSweep } from "./tools/scheduler-run.js";
49
48
  import { getSenderRoutingTool, setSenderRoutingTool, } from "./tools/sender-routing.js";
50
49
  import { getSender, listSenders, refreshPaidInmailCredits, } from "./tools/senders.js";
51
50
  import { attachRecommendedSequence, attachSequence, createWorkflowTable, } from "./tools/sequencer.js";
@@ -236,9 +235,6 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
236
235
  case "get_scheduler_fill_capacity":
237
236
  result = await getSchedulerFillCapacity(args);
238
237
  break;
239
- case "run_scheduler_sweep":
240
- result = await runSchedulerSweep(args);
241
- break;
242
238
  case "refill_sends":
243
239
  result = await executeRefillSendsCommand(args);
244
240
  break;
@@ -82,7 +82,6 @@ export interface SourceScoutRegistryResponse {
82
82
  codex: string;
83
83
  claude: string;
84
84
  parentThreadRule: string;
85
- schedulerRunReceiptRule?: string;
86
85
  prepareMessagesRule?: string;
87
86
  };
88
87
  }
@@ -133,7 +132,6 @@ export interface PostFindLeadsScoutRegistryResponse {
133
132
  codex: string;
134
133
  claude: string;
135
134
  parentThreadRule: string;
136
- schedulerRunReceiptRule?: string;
137
135
  prepareMessagesRule?: string;
138
136
  };
139
137
  }
@@ -379,7 +379,6 @@ export function getPostFindLeadsScoutRegistry() {
379
379
  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.',
380
380
  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.",
381
381
  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.',
382
- schedulerRunReceiptRule: "For refill prompt handoffs, scheduler-run receipt interpretation is mandatory: cellsConsidered is allocation-attempt count, not total ready supply, while readyCellsFound is ready inventory found before prefilters. Inspect campaignScopeSummary before assuming the selected refill campaign/table was included. Interpret prefiltered, skipped, and deferred separately. For ready closed-InMail cells with stale paid-credit prefilter/defer reasons, route to refresh_paid_inmail_credits_then_rerun once, then rerun/status. wait_for_capacity_or_window means report loaded/capped/waiting and do not source or prep more rows. no_ready_cells_continue_refill_prep means return to the refill/prep ladder. Do not treat cellsScheduled:0 alone as failure.",
383
382
  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" }) and get_subskill_asset({ subskillName: "refill-sends-workflow", assetPath: "core/flow.v1.json" }) to hasMore:false before operational steps, 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 the post-refresh target.globalActionQueue[0], then rerun get_refill_target_plan before choosing another action. Refill action ladder: approve generated rows only when an explicit bounded approval gate exists, process all existing same-campaign unenriched/unprepared rows in bounded batches before any source work, then copy bounded net-new rows from the selected source (selectedLeadListId, provider, and source fingerprint preserved), then use provider-aligned source-more. A new source or provider switch changes the reply-rate baseline and is a manual alternate, not a --yolo side effect. The refill_sends MCP command maintains a run-local refreshedPaidInmailSenderIds set: if the first target plan contains refresh_paid_inmail_credits for stale/missing paid-InMail facts, refill_sends refreshes each selected paid-InMail sender at most once, reruns get_refill_target_plan, and returns autoPaidInmailRefresh plus the post-refresh targetPlan before the operator chooses prep/source-copy/bounded-approval/read-only wait. Freshness gate precedes scheduler wait: if any selected target.senderRefillPlans[].paidInmail.status is missing_credit_facts or stale_credit_facts, or the target plan contains refresh_paid_inmail_credits, do not enter wait_for_scheduler even when remainingReadyOrProjectedGap is 0; refresh exact sender credit facts once, reread get_refill_target_plan, then choose scheduler wait only if freshness is clean. Do not present paid-credit refresh as the next operator action after refill_sends has returned a post-refresh targetPlan. 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/source-copy/bounded-approval/read-only wait 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.`,
384
383
  },
385
384
  };
@@ -14,6 +14,12 @@ export type PaidInmailCreditRefreshOptions = {
14
14
  maxStalenessSeconds?: number | null;
15
15
  paidInmailCreditsMaxStalenessSeconds?: number | null;
16
16
  };
17
+ export type PaidInmailRefreshReceiptClassification = {
18
+ usableCurrentFacts: boolean;
19
+ status: string;
20
+ error: string | null;
21
+ refreshed: boolean;
22
+ };
17
23
  export type YoloPrimitiveExecution = {
18
24
  enabled: true;
19
25
  status: "no_action" | "read_only_reread" | "executed_and_reread" | "refused" | "skipped_after_paid_refresh";
@@ -135,6 +141,7 @@ export declare function userAddedRowsLimitPayloadFromError(error: unknown): User
135
141
  export declare function sourceImportInProgressPayloadFromError(error: unknown): SourceImportInProgressPayload | null;
136
142
  export declare function paidRefreshActionFrom(value: unknown): PaidInmailRefreshAction | null;
137
143
  export declare function collectPaidInmailRefreshActions(plan: unknown): PaidInmailRefreshAction[];
144
+ export declare function classifyPaidInmailRefreshReceipt(value: unknown): PaidInmailRefreshReceiptClassification;
138
145
  export declare function firstGlobalAction(plan: unknown): Record<string, unknown> | null;
139
146
  export declare function actionIds(action: Record<string, unknown>): Record<string, unknown>;
140
147
  export declare function actionToolInput(action: Record<string, unknown>): Record<string, unknown>;
@@ -10,6 +10,11 @@ const PAID_INMAIL_REFRESH_RETRY_DELAY_MS = Number(process.env.SELLABLE_MCP_PAID_
10
10
  const SIGNAL_DISCOVERY_MIN_REFILL_POSTS = 3;
11
11
  const SIGNAL_DISCOVERY_MAX_REFILL_POSTS = 10;
12
12
  const SIGNAL_DISCOVERY_TARGET_ROWS_PER_POST = 150;
13
+ const USABLE_PAID_INMAIL_REFRESH_RECEIPT_STATUSES = new Set([
14
+ "fresh",
15
+ "refreshed",
16
+ "below_threshold",
17
+ ]);
13
18
  export function normalizeStrings(values) {
14
19
  if (!Array.isArray(values))
15
20
  return [];
@@ -206,6 +211,23 @@ export function collectPaidInmailRefreshActions(plan) {
206
211
  add(action);
207
212
  return [...bySender.values()];
208
213
  }
214
+ export function classifyPaidInmailRefreshReceipt(value) {
215
+ const response = recordValue(value);
216
+ const nestedReceipt = recordValue(response?.receipt);
217
+ const status = stringValue(nestedReceipt?.status) ??
218
+ stringValue(response?.status) ??
219
+ (response?.refreshed === true ? "refreshed" : "not_refreshed");
220
+ const refreshed = response?.refreshed === true || nestedReceipt?.refreshed === true;
221
+ const usableCurrentFacts = refreshed || USABLE_PAID_INMAIL_REFRESH_RECEIPT_STATUSES.has(status);
222
+ return {
223
+ usableCurrentFacts,
224
+ status,
225
+ refreshed,
226
+ error: stringValue(response?.error) ??
227
+ stringValue(nestedReceipt?.error) ??
228
+ (usableCurrentFacts ? null : "paid InMail credit refresh did not return usable current facts"),
229
+ };
230
+ }
209
231
  export function firstGlobalAction(plan) {
210
232
  const root = recordValue(plan);
211
233
  const target = recordValue(root?.target);
@@ -5,7 +5,6 @@ import { runRefillV2Loop } from "../refill-run-loop.js";
5
5
  import { getPrepareCampaignMessagesStatus } from "./campaign-message-preparation.js";
6
6
  import { getRefillPlanV2 } from "./evergreen-refill-plan.js";
7
7
  import { executeOneYoloPrimitive, executeStartCampaignPrimitive, prepareRowSelectorValue, refillPrepareRequestHash, refreshPaidInmailCreditsWithRetry, } from "./refill-executors.js";
8
- import { runSchedulerSweep } from "./scheduler-run.js";
9
8
  const FORBIDDEN_ACTIONS = [
10
9
  "Do not schedule sends.",
11
10
  "Do not send messages.",
@@ -153,7 +152,6 @@ export async function refillSendsV2Command(input) {
153
152
  localState: {
154
153
  writeRefillWorkspaceState,
155
154
  },
156
- requestSchedulerRun: (workspaceId) => runSchedulerSweep({ workspaceId, action: "run" }),
157
155
  });
158
156
  return {
159
157
  ...(await maybeAddLostFenceGuidance(result, { ...input, workspaceId })),
@@ -292,6 +292,8 @@ export declare function executeRefillSendsCommand(input?: RefillSendsCommandInpu
292
292
  attempts?: number;
293
293
  error: string;
294
294
  errors?: string[];
295
+ receiptStatus?: string;
296
+ receipt?: unknown;
295
297
  }[];
296
298
  refreshReceipts: {
297
299
  senderId: string;
@@ -301,6 +303,8 @@ export declare function executeRefillSendsCommand(input?: RefillSendsCommandInpu
301
303
  approvalSource: string;
302
304
  approvalPacket: PaidInmailRefreshApprovalPacket;
303
305
  receipt: import("./senders.js").RefreshPaidInmailCreditsResponse;
306
+ receiptStatus: string;
307
+ usableCurrentFacts: boolean;
304
308
  }[];
305
309
  attemptedSenderIds: string[];
306
310
  targetPlanReread: boolean;
@@ -309,6 +313,14 @@ export declare function executeRefillSendsCommand(input?: RefillSendsCommandInpu
309
313
  note: string;
310
314
  };
311
315
  yoloExecution: {
316
+ enabled: false;
317
+ status: "not_run_without_yolo";
318
+ selectedAction: null;
319
+ targetPlanReread: false;
320
+ result?: undefined;
321
+ refusalReason?: undefined;
322
+ postActionFirstAction?: undefined;
323
+ } | {
312
324
  enabled: true;
313
325
  status: "skipped_after_paid_refresh";
314
326
  selectedAction: null;
@@ -1,4 +1,4 @@
1
- import { actionIds, collectPaidInmailRefreshActions, executeOneYoloPrimitive, firstGlobalAction, normalizeStrings, numberValue, recordValue, refreshPaidInmailCreditsWithRetry, stringValue, } from "./refill-executors.js";
1
+ import { actionIds, classifyPaidInmailRefreshReceipt, collectPaidInmailRefreshActions, executeOneYoloPrimitive, firstGlobalAction, normalizeStrings, numberValue, recordValue, refreshPaidInmailCreditsWithRetry, stringValue, } from "./refill-executors.js";
2
2
  import { getRefillTargetPlan } from "./refill-target-plan.js";
3
3
  import { createWorkspaceContext, normalizeExplicitWorkspaceId, } from "./workspace-context.js";
4
4
  const DEFAULT_SCHEDULER_FORWARD_HOURS = 48;
@@ -231,9 +231,8 @@ export function refillSendsCommand(input = {}) {
231
231
  "Fresh reread get_campaign_refill_state immediately before any import, prep, approval, or horizon-fill mutation.",
232
232
  "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.",
233
233
  "Source/fallback primitives require receipt-proven exhaustion: existingRowFrontier.hasMoreFrontierRows:false, approvalCandidates:0, no fresh active prep, no stuckActiveCells, and no non-terminal approvedNotDispatched rows. Treat anomalies, stuckActiveCells, and non-terminal approvedNotDispatched as diagnose-and-report gates, not exhaustion. Terminal approvedNotDispatched blockers may be reported and then the ladder can proceed.",
234
- "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/source-copy/bounded-approval/read-only wait action is chosen.",
234
+ "In manual/non-yolo, scheduled, and --yolo modes, this tool may automatically refresh stale or missing paid-InMail credit facts once per selected sender when the first target plan returns refresh_paid_inmail_credits candidates. This is the only newly allowed automatic write in manual/non-yolo mode; it reruns get_refill_target_plan and returns autoPaidInmailRefresh with attemptedSenderIds, refreshedPaidInmailSenderIds, failedPaidInmailRefreshes, and the post-refresh targetPlan before any prep/source-copy/bounded-approval/read-only wait action is chosen.",
235
235
  "Freshness gate precedes scheduler wait: if any selected target.senderRefillPlans[].paidInmail.status is missing_credit_facts or stale_credit_facts, or the target plan contains refresh_paid_inmail_credits, do not enter wait_for_scheduler even when remainingReadyOrProjectedGap is 0; refresh exact sender credit facts once, reread get_refill_target_plan, then choose scheduler wait only if freshness is clean.",
236
- "Scheduler-run receipt interpretation: cellsConsidered is allocation-attempt count, readyCellsFound is ready inventory before prefilters, and campaignScopeSummary must include the selected campaign/table before inferring it was ready-but-blocked. Read prefiltered, skipped, and deferred separately. For ready closed-InMail cells with stale paid-credit facts, route to refresh_paid_inmail_credits_then_rerun once, then rerun/status. wait_for_capacity_or_window means report loaded/capped/waiting and do not source or prep more rows. no_ready_cells_continue_refill_prep means return to the refill/prep ladder.",
237
236
  "For wait_for_active_work and wait_for_scheduler, honor the receipt's absolute wait.deadlineAt when present. If the deadline is expired on this call, escalate to diagnostics with the receipt evidence instead of issuing another blind wait.",
238
237
  "Do not present paid-credit refresh as the next operator action after refill_sends returns autoPaidInmailRefresh and the post-refresh targetPlan.",
239
238
  "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.",
@@ -375,7 +374,11 @@ export async function executeRefillSendsCommand(input = {}) {
375
374
  ? { ...input, workspaceId: workspaceContext.context.workspaceId }
376
375
  : input;
377
376
  const command = refillSendsCommand(scopedInput);
378
- if (!yolo) {
377
+ const workspaceId = workspaceContext && workspaceContext.ok
378
+ ? workspaceContext.context.workspaceId
379
+ : normalizeExplicitWorkspaceId(scopedInput.workspaceId);
380
+ const canRefreshPaidInmailFacts = yolo || executionMode === "scheduled" || Boolean(workspaceId);
381
+ if (!canRefreshPaidInmailFacts) {
379
382
  return {
380
383
  ...command,
381
384
  autoPaidInmailRefresh: {
@@ -383,7 +386,7 @@ export async function executeRefillSendsCommand(input = {}) {
383
386
  status: "not_run_without_yolo",
384
387
  refreshedPaidInmailSenderIds: [],
385
388
  failedPaidInmailRefreshes: [],
386
- note: "Automatic paid InMail credit refresh only runs for --yolo refill_sends calls.",
389
+ note: "Automatic paid InMail credit refresh requires --yolo, scheduled mode, or an explicit workspaceId so the request can refresh exact sender facts safely.",
387
390
  },
388
391
  yoloExecution: {
389
392
  enabled: false,
@@ -393,9 +396,6 @@ export async function executeRefillSendsCommand(input = {}) {
393
396
  },
394
397
  };
395
398
  }
396
- const workspaceId = workspaceContext && workspaceContext.ok
397
- ? workspaceContext.context.workspaceId
398
- : normalizeExplicitWorkspaceId(scopedInput.workspaceId);
399
399
  const targetPlanInput = targetPlanInputFor(scopedInput);
400
400
  const targetPlanBeforePaidRefresh = await getRefillTargetPlan(targetPlanInput);
401
401
  const refreshActions = collectPaidInmailRefreshActions(targetPlanBeforePaidRefresh);
@@ -421,7 +421,7 @@ export async function executeRefillSendsCommand(input = {}) {
421
421
  }
422
422
  const refreshResult = await refreshPaidInmailCreditsWithRetry(action.senderId, workspaceId, paidRefreshOptionsFromApprovalPacket(approvalPacket));
423
423
  if (refreshResult.receipt) {
424
- refreshedPaidInmailSenderIds.push(action.senderId);
424
+ const classification = classifyPaidInmailRefreshReceipt(refreshResult.receipt);
425
425
  refreshReceipts.push({
426
426
  senderId: action.senderId,
427
427
  actionKey: action.actionKey ?? null,
@@ -430,7 +430,23 @@ export async function executeRefillSendsCommand(input = {}) {
430
430
  approvalSource: "explicit_yolo_flag",
431
431
  approvalPacket,
432
432
  receipt: refreshResult.receipt,
433
+ receiptStatus: classification.status,
434
+ usableCurrentFacts: classification.usableCurrentFacts,
433
435
  });
436
+ if (classification.usableCurrentFacts) {
437
+ refreshedPaidInmailSenderIds.push(action.senderId);
438
+ }
439
+ else {
440
+ failedPaidInmailRefreshes.push({
441
+ senderId: action.senderId,
442
+ attempts: refreshResult.attempts,
443
+ error: classification.error ??
444
+ "paid InMail credit refresh did not return usable current facts",
445
+ errors: refreshResult.errors,
446
+ receiptStatus: classification.status,
447
+ receipt: refreshResult.receipt,
448
+ });
449
+ }
434
450
  }
435
451
  else {
436
452
  failedPaidInmailRefreshes.push({
@@ -445,8 +461,8 @@ export async function executeRefillSendsCommand(input = {}) {
445
461
  const targetPlan = refreshActions.length > 0
446
462
  ? await getRefillTargetPlan(targetPlanInput)
447
463
  : targetPlanBeforePaidRefresh;
448
- const selectedAction = refreshActions.length > 0 ? null : firstGlobalAction(targetPlan);
449
- const primitiveAttempt = refreshActions.length > 0
464
+ const selectedAction = yolo && refreshActions.length === 0 ? firstGlobalAction(targetPlan) : null;
465
+ const primitiveAttempt = !yolo || refreshActions.length > 0
450
466
  ? null
451
467
  : await executeOneYoloPrimitive(selectedAction, workspaceId ?? undefined);
452
468
  const shouldRereadAfterPrimitive = primitiveAttempt?.status === "executed_and_reread" ||
@@ -459,7 +475,9 @@ export async function executeRefillSendsCommand(input = {}) {
459
475
  ...command,
460
476
  targetPlan: finalTargetPlan,
461
477
  targetPlanBeforePaidRefresh: refreshActions.length > 0 ? targetPlanBeforePaidRefresh : null,
462
- targetPlanBeforeYoloPrimitive: refreshActions.length === 0 && postActionTargetPlan ? targetPlan : null,
478
+ targetPlanBeforeYoloPrimitive: yolo && refreshActions.length === 0 && postActionTargetPlan
479
+ ? targetPlan
480
+ : null,
463
481
  autoPaidInmailRefresh: {
464
482
  enabled: true,
465
483
  status: refreshActions.length === 0
@@ -478,23 +496,30 @@ export async function executeRefillSendsCommand(input = {}) {
478
496
  ? "refill_sends refreshed stale paid InMail credit facts internally with bounded retries, once per sender, then returned the post-refresh targetPlan."
479
497
  : "No stale or missing paid InMail credit refresh candidates were present in the initial target plan.",
480
498
  },
481
- yoloExecution: refreshActions.length > 0
499
+ yoloExecution: !yolo
482
500
  ? {
483
- enabled: true,
484
- status: "skipped_after_paid_refresh",
501
+ enabled: false,
502
+ status: "not_run_without_yolo",
485
503
  selectedAction: null,
486
- targetPlanReread: true,
504
+ targetPlanReread: false,
487
505
  }
488
- : {
489
- enabled: true,
490
- status: primitiveAttempt?.status ?? "no_action",
491
- selectedAction,
492
- result: primitiveAttempt?.result,
493
- targetPlanReread: shouldRereadAfterPrimitive,
494
- refusalReason: primitiveAttempt?.refusalReason,
495
- postActionFirstAction: postActionTargetPlan
496
- ? firstGlobalAction(postActionTargetPlan)
497
- : null,
498
- },
506
+ : refreshActions.length > 0
507
+ ? {
508
+ enabled: true,
509
+ status: "skipped_after_paid_refresh",
510
+ selectedAction: null,
511
+ targetPlanReread: true,
512
+ }
513
+ : {
514
+ enabled: true,
515
+ status: primitiveAttempt?.status ?? "no_action",
516
+ selectedAction,
517
+ result: primitiveAttempt?.result,
518
+ targetPlanReread: shouldRereadAfterPrimitive,
519
+ refusalReason: primitiveAttempt?.refusalReason,
520
+ postActionFirstAction: postActionTargetPlan
521
+ ? firstGlobalAction(postActionTargetPlan)
522
+ : null,
523
+ },
499
524
  };
500
525
  }
@@ -7370,25 +7370,6 @@ export declare const allTools: ({
7370
7370
  };
7371
7371
  required: string[];
7372
7372
  };
7373
- } | {
7374
- name: string;
7375
- description: string;
7376
- inputSchema: {
7377
- type: string;
7378
- properties: {
7379
- workspaceId: {
7380
- type: string;
7381
- description: string;
7382
- };
7383
- action: {
7384
- type: string;
7385
- enum: string[];
7386
- description: string;
7387
- };
7388
- };
7389
- required: string[];
7390
- additionalProperties: boolean;
7391
- };
7392
7373
  } | {
7393
7374
  name: string;
7394
7375
  description: string;
@@ -40,7 +40,6 @@ import { refillTargetPlanToolDefinitions } from "./refill-target-plan.js";
40
40
  import { rowToolDefinitions } from "./rows.js";
41
41
  import { rubricToolDefinitions } from "./rubrics.js";
42
42
  import { schedulerFillCapacityToolDefinitions } from "./scheduler-fill-capacity.js";
43
- import { schedulerRunToolDefinitions } from "./scheduler-run.js";
44
43
  import { senderRoutingToolDefinitions } from "./sender-routing.js";
45
44
  import { senderToolDefinitions } from "./senders.js";
46
45
  import { sequencerToolDefinitions } from "./sequencer.js";
@@ -58,7 +57,6 @@ export const allTools = [
58
57
  ...refillPlanV2ToolDefinitions,
59
58
  ...refillTargetPlanToolDefinitions,
60
59
  ...schedulerFillCapacityToolDefinitions,
61
- ...schedulerRunToolDefinitions,
62
60
  ...refillSendsToolDefinitions,
63
61
  ...refillSendsV2ToolDefinitions,
64
62
  ...setupEvergreenCampaignsToolDefinitions,
@@ -52,16 +52,22 @@ export type PaidInmailCreditStatus = {
52
52
  };
53
53
  export type RefreshPaidInmailCreditsResponse = {
54
54
  senderId: string;
55
- refreshed: true;
55
+ refreshed: boolean;
56
+ error?: string | null;
56
57
  credits: PaidInmailCreditStatus;
57
- receipt?: unknown;
58
+ receipt?: {
59
+ status?: string;
60
+ refreshed?: boolean;
61
+ error?: string;
62
+ [key: string]: unknown;
63
+ } | null;
58
64
  sideEffects: {
59
- refreshedLinkedInDerivedCreditFacts: true;
60
- updatedSenderCreditCache: true;
61
- campaignMutation: false;
62
- schedulerMutation: false;
63
- thresholdMutation: false;
64
- sendMutation: false;
65
+ refreshedLinkedInDerivedCreditFacts: boolean;
66
+ updatedSenderCreditCache: boolean;
67
+ campaignMutation: boolean;
68
+ schedulerMutation: boolean;
69
+ thresholdMutation: boolean;
70
+ sendMutation: boolean;
65
71
  };
66
72
  };
67
73
  export declare const senderToolDefinitions: ({
@@ -237,6 +237,21 @@ function normalizeCreditStatus(raw) {
237
237
  needsRefresh: raw?.needsRefresh === true,
238
238
  };
239
239
  }
240
+ function normalizeRefreshReceipt(raw) {
241
+ if (!raw || typeof raw !== "object")
242
+ return null;
243
+ return raw;
244
+ }
245
+ function normalizeCreditRefreshSideEffects(raw, receiptRefreshed) {
246
+ return {
247
+ refreshedLinkedInDerivedCreditFacts: raw?.refreshedLinkedInDerivedCreditFacts === true || receiptRefreshed,
248
+ updatedSenderCreditCache: raw?.updatedSenderCreditCache === true || receiptRefreshed,
249
+ campaignMutation: raw?.campaignMutation === true,
250
+ schedulerMutation: raw?.schedulerMutation === true,
251
+ thresholdMutation: raw?.thresholdMutation === true,
252
+ sendMutation: raw?.sendMutation === true,
253
+ };
254
+ }
240
255
  export async function refreshPaidInmailCredits(input) {
241
256
  const senderId = input.senderId?.trim();
242
257
  if (!senderId) {
@@ -268,18 +283,14 @@ export async function refreshPaidInmailCredits(input) {
268
283
  if (threshold !== null)
269
284
  body.threshold = threshold;
270
285
  const result = await api.post(`/api/v3/mcp/senders/${encodeURIComponent(senderId)}/refresh-inmail-credits`, body, requestOptions);
286
+ const receipt = normalizeRefreshReceipt(result?.receipt);
287
+ const receiptRefreshed = result?.refreshed === true || receipt?.refreshed === true;
271
288
  return {
272
289
  senderId,
273
- refreshed: true,
290
+ refreshed: receiptRefreshed,
291
+ error: pickString(result?.error, receipt?.error),
274
292
  credits: normalizeCreditStatus(result?.credits),
275
- receipt: result?.receipt,
276
- sideEffects: {
277
- refreshedLinkedInDerivedCreditFacts: true,
278
- updatedSenderCreditCache: true,
279
- campaignMutation: false,
280
- schedulerMutation: false,
281
- thresholdMutation: false,
282
- sendMutation: false,
283
- },
293
+ receipt,
294
+ sideEffects: normalizeCreditRefreshSideEffects(result?.sideEffects, receiptRefreshed),
284
295
  };
285
296
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sellable/mcp",
3
- "version": "0.1.534",
3
+ "version": "0.1.535",
4
4
  "type": "module",
5
5
  "description": "Sellable MCP server for Claude Code, Codex, and Hermes campaign workflows",
6
6
  "main": "dist/index.js",
@@ -6,7 +6,6 @@ allowed-tools:
6
6
  - mcp__sellable__refill_sends
7
7
  - mcp__sellable__get_refill_target_plan
8
8
  - mcp__sellable__get_scheduler_fill_capacity
9
- - mcp__sellable__run_scheduler_sweep
10
9
  - mcp__sellable__refresh_paid_inmail_credits
11
10
  - mcp__sellable__get_subskill_asset
12
11
  - mcp__sellable__get_auth_status
@@ -115,11 +114,10 @@ or install-time workspace mapping. Pass `workspaceId` on every scheduled or
115
114
  `--yolo` refill tool call, including setup/read calls such as
116
115
  `refill_sends`, `get_refill_target_plan`, `list_senders`,
117
116
  `get_sender_routing`, `resolve_campaign_fill_route`,
118
- `get_campaign_refill_state`, `get_scheduler_fill_capacity`,
119
- `run_scheduler_sweep`, and any later refill mutation covered by the packet.
120
- Missing `workspaceId` in scheduled or `--yolo` mode is a blocker; stop with
121
- `WORKSPACE_REQUIRED` instead of running against an implicit or guessed
122
- workspace.
117
+ `get_campaign_refill_state`, `get_scheduler_fill_capacity`, and any later
118
+ refill mutation covered by the packet. Missing `workspaceId` in scheduled or
119
+ `--yolo` mode is a blocker; stop with `WORKSPACE_REQUIRED` instead of running
120
+ against an implicit or guessed workspace.
123
121
 
124
122
  Do not solve scheduled or `--yolo` workspace uncertainty by changing the shared
125
123
  active workspace. Manual interactive workspace switching remains a separate
@@ -271,23 +269,6 @@ need raw proof, call the read-only `get_scheduler_fill_capacity` query for the
271
269
  same sender/action/date; it tells the MCP how many cells the product scheduler
272
270
  will try to place and does not import, approve, schedule, refresh credits, or
273
271
  mutate.
274
- When the refill loop has ready rows and needs scheduler pickup now, use
275
- `run_scheduler_sweep` with the same explicit `workspaceId`; it can place cells
276
- within existing scheduler gates and returns the receipt, but it never sends or
277
- bypasses limits.
278
- Scheduler-run receipt interpretation: `cellsConsidered is allocation-attempt
279
- count`, not total ready supply, while `readyCellsFound` is ready inventory found
280
- before prefilters. Inspect `campaignScopeSummary` before assuming the selected
281
- refill campaign/table was included; if absent, do not infer that target was
282
- ready-but-blocked. Interpret `prefiltered` as ready cells removed before
283
- allocation, `skipped` as considered cells blocked by scheduler gates, and
284
- `deferred` as considered cells waiting on windows/capacity/cooldown. For ready
285
- closed-InMail cells with stale paid-credit prefilter/defer reasons, refresh
286
- paid-InMail credits once through existing tools, then rerun `run_scheduler_sweep`
287
- or read `action:"status"`; `refresh_paid_inmail_credits_then_rerun` is that
288
- path. `wait_for_capacity_or_window` means report loaded/capped/waiting and do
289
- not source or prep more rows; `no_ready_cells_continue_refill_prep` means return
290
- to the refill/prep ladder. Do not treat `cellsScheduled:0` alone as failure.
291
272
  If the target plan is complete by projected coverage, report that the selected
292
273
  target is already filled and no-op without asking for approval. If the ready
293
274
  buffer covers the projected gap, paid InMail credit facts are fresh for every
@@ -128,17 +128,6 @@ Reinvoke with that handle. The approximately five minute scheduler budget is at
128
128
  the run level, not one tool call. A window-closed or loaded-awaiting scheduler
129
129
  report must include remaining-ready count, exact expected pickup time, and the
130
130
  resume handle; never treat bare "awaiting scheduler" copy as a final answer.
131
- Scheduler-run receipt interpretation still applies to terminal progress:
132
- `cellsConsidered is allocation-attempt count`, not total ready supply, while
133
- `readyCellsFound` is ready inventory found before prefilters. Inspect
134
- `campaignScopeSummary` before assuming the selected refill campaign/table was
135
- included; if absent, do not infer that target was ready-but-blocked. Interpret
136
- `prefiltered`, `skipped`, and `deferred` separately. For ready closed-InMail
137
- cells with stale paid-credit reasons, route to
138
- `refresh_paid_inmail_credits_then_rerun` once, then rerun/status.
139
- `wait_for_capacity_or_window` means report loaded/capped/waiting and do not
140
- source or prep more rows; `no_ready_cells_continue_refill_prep` means return to
141
- the refill/prep ladder. Do not treat `cellsScheduled:0` alone as failure.
142
131
 
143
132
  After the first prep batch, read the conversion-verdict journal line. It is
144
133
  rendered from packet facts: `supplyCensus`, `censusReason`, and
@@ -117,17 +117,6 @@ Scheduler wait is cross-invocation. If the tool returns `in_progress` with
117
117
  sweep guidance, re-invoke `refill_sends_v2` with `{runId, fence}`. The scheduler
118
118
  budget is cumulative at the run level. Zero pickup after a confirmed sweep is
119
119
  debugged from `pipelineDiagnosis`; it is not waited out forever.
120
- Scheduler-run receipt interpretation still applies to terminal progress:
121
- `cellsConsidered is allocation-attempt count`, not total ready supply, while
122
- `readyCellsFound` is ready inventory found before prefilters. Inspect
123
- `campaignScopeSummary` before assuming the selected refill campaign/table was
124
- included; if absent, do not infer that target was ready-but-blocked. Interpret
125
- `prefiltered`, `skipped`, and `deferred` separately. For ready closed-InMail
126
- cells with stale paid-credit reasons, route to
127
- `refresh_paid_inmail_credits_then_rerun` once, then rerun/status.
128
- `wait_for_capacity_or_window` means report loaded/capped/waiting and do not
129
- source or prep more rows; `no_ready_cells_continue_refill_prep` means return to
130
- the refill/prep ladder. Do not treat `cellsScheduled:0` alone as failure.
131
120
 
132
121
  ## G4 Report
133
122
 
@@ -6,7 +6,6 @@ allowed-tools:
6
6
  - mcp__sellable__get_subskill_asset
7
7
  - mcp__sellable__get_refill_target_plan
8
8
  - mcp__sellable__get_scheduler_fill_capacity
9
- - mcp__sellable__run_scheduler_sweep
10
9
  - mcp__sellable__refresh_paid_inmail_credits
11
10
  - mcp__sellable__list_senders
12
11
  - mcp__sellable__get_sender_routing
@@ -68,12 +67,11 @@ request-scoped `workspaceId`. Pass that same `workspaceId` on every refill tool
68
67
  call in this workflow: `get_refill_target_plan`, `list_senders`,
69
68
  `get_sender_routing`, `resolve_campaign_fill_route`,
70
69
  `get_campaign_refill_state`, `get_scheduler_fill_capacity`,
71
- `run_scheduler_sweep`, `refresh_paid_inmail_credits`, source import/readiness
72
- calls, preparation calls, approval calls, and campaign start calls. Missing
73
- `workspaceId` in scheduled or `--yolo` mode is a blocker; return or report
74
- `WORKSPACE_REQUIRED` instead of falling back to shared config state. Manual
75
- interactive workspace switching is diagnostic setup only and is not an
76
- automation control path.
70
+ `refresh_paid_inmail_credits`, source import/readiness calls, preparation calls,
71
+ approval calls, and campaign start calls. Missing `workspaceId` in scheduled or
72
+ `--yolo` mode is a blocker; return or report `WORKSPACE_REQUIRED` instead of
73
+ falling back to shared config state. Manual interactive workspace switching is
74
+ diagnostic setup only and is not an automation control path.
77
75
 
78
76
  Goal-mode continuation: a skill cannot create or invoke `/goal` by itself. When
79
77
  this workflow is already running inside an active Codex goal, keep that goal
@@ -188,24 +186,6 @@ files or memory.
188
186
  how many cells the product scheduler will try to place for that sender; it
189
187
  does not create rows, import, approve, schedule, refresh paid-InMail credits,
190
188
  or mutate thresholds.
191
- When ready rows exist and the wait is for scheduler pickup, call
192
- `run_scheduler_sweep` with the same explicit `workspaceId` to request the
193
- product scheduler placement pass now and read its receipt. This may place
194
- cells within existing gates, never sends messages, and never bypasses limits.
195
- Scheduler-run receipt interpretation: `cellsConsidered is
196
- allocation-attempt count`, not total ready supply, while `readyCellsFound`
197
- is ready inventory found before prefilters. Inspect `campaignScopeSummary`
198
- before assuming the selected refill campaign/table was included; if absent,
199
- do not infer that target was ready-but-blocked. Interpret `prefiltered` as
200
- ready cells removed before allocation, `skipped` as considered cells blocked
201
- by scheduler gates, and `deferred` as considered cells waiting on
202
- windows/capacity/cooldown. For ready closed-InMail cells with stale
203
- paid-credit prefilter/defer reasons, refresh paid-InMail credits once through
204
- existing tools, then rerun `run_scheduler_sweep` or read `action:"status"`;
205
- `refresh_paid_inmail_credits_then_rerun` is that path.
206
- `wait_for_capacity_or_window` means report loaded/capped/waiting and do not
207
- source or prep more rows; `no_ready_cells_continue_refill_prep` means return
208
- to the refill/prep ladder. Do not treat `cellsScheduled:0` alone as failure.
209
189
  If `status:"complete"`, report the target, selected dates, sent count,
210
190
  scheduled count, projected count, campaign ids, and no-op proof without
211
191
  asking for approval or mutating.
@@ -191,8 +191,7 @@
191
191
  "description": "Read-only scheduler polling after rows are ready and paid-credit facts are fresh.",
192
192
  "allowedTools": [
193
193
  "get_refill_target_plan",
194
- "get_scheduler_fill_capacity",
195
- "run_scheduler_sweep"
194
+ "get_scheduler_fill_capacity"
196
195
  ],
197
196
  "entryConditions": [
198
197
  "remainingReadyOrProjectedGap == 0",
@@ -202,10 +201,6 @@
202
201
  ],
203
202
  "rules": [
204
203
  "Poll every 60-120 seconds or on the host continuation interval.",
205
- "Use run_scheduler_sweep with the explicit workspaceId when ready rows need scheduler pickup now; it places cells only inside existing gates and never sends.",
206
- "cellsConsidered is allocation-attempt count; inspect campaignScopeSummary before assuming the selected refill campaign/table was included or ready-but-blocked.",
207
- "Read prefiltered, skipped, and deferred separately: prefiltered ready closed-InMail cells with stale paid-credit facts require refresh_paid_inmail_credits_then_rerun once, then rerun/status.",
208
- "wait_for_capacity_or_window means report loaded/capped/waiting and do not source or prep more rows; no_ready_cells_continue_refill_prep means return to the refill/prep ladder.",
209
204
  "Stop waiting when projected coverage fills the target.",
210
205
  "Leave wait if a concrete non-scheduler blocker appears.",
211
206
  "Do not mark complete or blocked only because awaiting_scheduler_after_ready_buffer persists."
@@ -1,28 +0,0 @@
1
- type RefillSendsEvergreenInput = {
2
- workspaceId?: string;
3
- };
4
- export declare const refillSendsEvergreenToolDefinitions: {
5
- name: string;
6
- description: string;
7
- inputSchema: {
8
- type: string;
9
- properties: {
10
- workspaceId: {
11
- type: string;
12
- description: string;
13
- };
14
- };
15
- required: string[];
16
- additionalProperties: boolean;
17
- };
18
- }[];
19
- export declare function refillSendsEvergreenCommand(input: RefillSendsEvergreenInput): {
20
- readOnly: boolean;
21
- workspaceId: string | null;
22
- firstOperationalSteps: string[];
23
- approvalContract: string;
24
- forbiddenActions: string[];
25
- fillWindow: string;
26
- hostExamples: string[];
27
- };
28
- export {};
@@ -1,47 +0,0 @@
1
- export const refillSendsEvergreenToolDefinitions = [
2
- {
3
- name: "refill_sends_evergreen",
4
- description: "Read-only Phase 85 evergreen refill command contract. It performs no mutations and only tells the operator to call get_evergreen_refill_plan for a dry-run packet and journal.",
5
- inputSchema: {
6
- type: "object",
7
- properties: {
8
- workspaceId: {
9
- type: "string",
10
- description: "Explicit request-scoped workspace id.",
11
- },
12
- },
13
- required: ["workspaceId"],
14
- additionalProperties: false,
15
- },
16
- },
17
- ];
18
- export function refillSendsEvergreenCommand(input) {
19
- return {
20
- readOnly: true,
21
- workspaceId: input.workspaceId ?? null,
22
- firstOperationalSteps: [
23
- "Call get_evergreen_refill_plan with the explicit workspaceId.",
24
- "Read the returned packet, globalActionQueue, per-sender plans, and itinerary before taking any action.",
25
- "Review the dry-run journal file path returned by get_evergreen_refill_plan.",
26
- "Phase 85 is PLAN-ONLY; execution arrives in Phase 86.",
27
- ],
28
- approvalContract: "Nothing is approved or executable in Phase 85. The evergreen command is read-only; Phase 86 introduces execution approval.",
29
- forbiddenActions: [
30
- "Do not schedule sends.",
31
- "Do not send messages.",
32
- "Do not approve messages.",
33
- "Do not prepare messages.",
34
- "Do not start or launch campaigns.",
35
- "Do not create campaigns.",
36
- "Do not switch providers or source families.",
37
- "Do not lower paid InMail thresholds.",
38
- "Do not refresh paid InMail credits.",
39
- "Do not write scheduler fields.",
40
- ],
41
- fillWindow: "Use only the target window and caps returned by get_evergreen_refill_plan.",
42
- hostExamples: [
43
- "refill_sends_evergreen({ workspaceId })",
44
- "get_evergreen_refill_plan({ workspaceId })",
45
- ],
46
- };
47
- }
@@ -1,27 +0,0 @@
1
- type SchedulerRunAction = "run" | "status";
2
- type RunSchedulerSweepInput = {
3
- workspaceId: string;
4
- action?: SchedulerRunAction;
5
- };
6
- export declare const schedulerRunToolDefinitions: {
7
- name: string;
8
- description: string;
9
- inputSchema: {
10
- type: string;
11
- properties: {
12
- workspaceId: {
13
- type: string;
14
- description: string;
15
- };
16
- action: {
17
- type: string;
18
- enum: string[];
19
- description: string;
20
- };
21
- };
22
- required: string[];
23
- additionalProperties: boolean;
24
- };
25
- }[];
26
- export declare function runSchedulerSweep(input: RunSchedulerSweepInput): Promise<unknown>;
27
- export {};
@@ -1,45 +0,0 @@
1
- import { getApi } from "../api.js";
2
- import { normalizeExplicitWorkspaceId, workspaceRequestOptions, } from "./workspace-context.js";
3
- async function postSchedulerRun(body, workspaceId) {
4
- const api = getApi();
5
- const requestOptions = workspaceRequestOptions(workspaceId);
6
- return requestOptions
7
- ? api.post("/api/v3/mcp/scheduler-run", body, requestOptions)
8
- : api.post("/api/v3/mcp/scheduler-run", body);
9
- }
10
- export const schedulerRunToolDefinitions = [
11
- {
12
- name: "run_scheduler_sweep",
13
- description: 'Trigger the product scheduler placement sweep for one explicit workspace now, or read the last on-demand scheduler run status with action "status". A run is workspace-wide, not a scoped run for one campaign/table, and returns a synchronous envelope with status ran, attached, backoff, window_closed_noop, or failed; retryAfterMs for backoff replays; and a backward-compatible receipt. In v2 receipts, readyCellsFound is total scheduler-ready supply found before filters, cellsConsidered is the allocation-attempt count that survived prefilters, prefiltered means ready cells removed before allocation such as no capacity, stale paid InMail credit facts, or sender mismatch, skipped means considered cells rejected by hard scheduler gates, and deferred means considered cells waiting on windows/capacity/cooldown. campaignScopeSummary lists bounded tables/campaigns the workspace-wide run inspected; absence there is not a scoped-run guarantee that the target was ready. The receipt can include readyCellsByType, consideredCellsByType, prefilterReasons, skippedReasons, deferredReasons, summary, and nextAction. It places cells within existing scheduler gates only: it can move placement earlier, but it cannot bypass sending windows, daily limits, cooldowns, sender gates, billing, or credit thresholds, and it never sends messages directly. Repeated calls inside the backoff window replay the last receipt verbatim. Status is read-only and scoped to the last on-demand run only; cron sweeps are not recorded here.',
14
- inputSchema: {
15
- type: "object",
16
- properties: {
17
- workspaceId: {
18
- type: "string",
19
- description: "Explicit request-scoped workspace id for scheduled/yolo refill automation. Pass this instead of switching the shared active workspace.",
20
- },
21
- action: {
22
- type: "string",
23
- enum: ["run", "status"],
24
- description: 'Use "run" to trigger a placement sweep now. Use "status" for a read-only view of the last on-demand run. Defaults to "run".',
25
- },
26
- },
27
- required: ["workspaceId"],
28
- additionalProperties: false,
29
- },
30
- },
31
- ];
32
- export async function runSchedulerSweep(input) {
33
- const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
34
- if (!workspaceId) {
35
- throw new Error("workspaceId is required for run_scheduler_sweep.");
36
- }
37
- const action = input.action ?? "run";
38
- if (action !== "run" && action !== "status") {
39
- throw new Error('action must be "run" or "status" for run_scheduler_sweep.');
40
- }
41
- return postSchedulerRun({
42
- workspaceId,
43
- action,
44
- }, workspaceId);
45
- }