@sellable/mcp 0.1.510 → 0.1.512

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.
@@ -1259,7 +1259,7 @@ function serializeInvalidSignalPosts(posts) {
1259
1259
  reason: post.reason,
1260
1260
  }));
1261
1261
  }
1262
- async function validateSelectedSignalPostsForImport(api, posts, requestOptions) {
1262
+ async function validateSelectedSignalPostsForImport(api, posts) {
1263
1263
  const results = await Promise.all(posts.map(async (post) => {
1264
1264
  if (!post.url.trim()) {
1265
1265
  return {
@@ -1269,15 +1269,10 @@ async function validateSelectedSignalPostsForImport(api, posts, requestOptions)
1269
1269
  };
1270
1270
  }
1271
1271
  try {
1272
- const response = requestOptions
1273
- ? await api.post("/api/v1/signal-discovery/search-signals", {
1274
- type: "post",
1275
- postUrl: post.url,
1276
- }, requestOptions)
1277
- : await api.post("/api/v1/signal-discovery/search-signals", {
1278
- type: "post",
1279
- postUrl: post.url,
1280
- });
1272
+ const response = await api.post("/api/v1/signal-discovery/search-signals", {
1273
+ type: "post",
1274
+ postUrl: post.url,
1275
+ });
1281
1276
  const valid = response.success !== false &&
1282
1277
  Array.isArray(response.posts) &&
1283
1278
  response.posts.some(hasUsableSignalValidationPost);
@@ -1975,6 +1970,10 @@ export const leadToolDefinitions = [
1975
1970
  type: "string",
1976
1971
  description: "Campaign offer ID to associate search",
1977
1972
  },
1973
+ workspaceId: {
1974
+ type: "string",
1975
+ description: "Explicit request-scoped workspace id. Pass this instead of switching the shared active workspace.",
1976
+ },
1978
1977
  searchName: {
1979
1978
  type: "string",
1980
1979
  description: "Optional name for the search. Use descriptive names that encode ICP intent (e.g., 'Fintech Compliance Directors 201-1000 US').",
@@ -2082,6 +2081,10 @@ export const leadToolDefinitions = [
2082
2081
  type: "string",
2083
2082
  description: "Campaign offer ID",
2084
2083
  },
2084
+ workspaceId: {
2085
+ type: "string",
2086
+ description: "Explicit request-scoped workspace id. Pass this instead of switching the shared active workspace.",
2087
+ },
2085
2088
  provider: {
2086
2089
  type: "string",
2087
2090
  enum: ["apollo", "sales-nav", "prospeo", "signal-discovery"],
@@ -2156,6 +2159,10 @@ export const leadToolDefinitions = [
2156
2159
  type: "string",
2157
2160
  description: "Campaign offer ID. Required for audit context; not used to resolve provider or tableId.",
2158
2161
  },
2162
+ workspaceId: {
2163
+ type: "string",
2164
+ description: "Explicit request-scoped workspace id. Pass this instead of switching the shared active workspace.",
2165
+ },
2159
2166
  tableId: {
2160
2167
  type: "string",
2161
2168
  description: "Lead list (workflow table) ID to cancel. Required; callers have this from campaign context.",
@@ -2179,6 +2186,10 @@ export const leadToolDefinitions = [
2179
2186
  type: "string",
2180
2187
  description: "Campaign offer ID",
2181
2188
  },
2189
+ workspaceId: {
2190
+ type: "string",
2191
+ description: "Explicit request-scoped workspace id. Pass this instead of switching the shared active workspace.",
2192
+ },
2182
2193
  sourceLeadListId: {
2183
2194
  type: "string",
2184
2195
  description: "Lead list ID to import into campaign. If omitted, uses campaign.selectedLeadListId.",
@@ -3123,6 +3134,8 @@ export async function searchProspeo(input) {
3123
3134
  campaignOfferId: input?.campaignOfferId,
3124
3135
  });
3125
3136
  const api = getApi();
3137
+ const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
3138
+ const requestOptions = workspaceRequestOptions(workspaceId);
3126
3139
  const rawInput = input;
3127
3140
  if ("domains" in rawInput) {
3128
3141
  throw new Error("search_prospeo does not accept raw domains. Use load_csv_domains or save_domain_filters for known domain lists. For generated company/account lookalikes, use search_prospeo_companies, then confirm_prospeo_company_accounts, then pass the returned domainFilterId.");
@@ -3133,9 +3146,11 @@ export async function searchProspeo(input) {
3133
3146
  nestedCompany?.names !== undefined) {
3134
3147
  throw new Error("search_prospeo does not accept filters.company.websites or filters.company.names. For known accounts, resolve names/domains into a domainFilterId with load_csv_domains or save_domain_filters. For company/account lookalikes, use search_prospeo_companies first, then confirm_prospeo_company_accounts.");
3135
3148
  }
3136
- const safeInput = normalizeProspeoSearchInputForMcp(input);
3149
+ const { workspaceId: _workspaceId, ...safeInput } = normalizeProspeoSearchInputForMcp(input);
3137
3150
  try {
3138
- const response = await api.post(`/api/v3/prospeo/search`, safeInput);
3151
+ const response = requestOptions
3152
+ ? await api.post(`/api/v3/prospeo/search`, safeInput, requestOptions)
3153
+ : await api.post(`/api/v3/prospeo/search`, safeInput);
3139
3154
  return compactProspeoSearchResponse(response);
3140
3155
  }
3141
3156
  catch (error) {
@@ -3143,7 +3158,9 @@ export async function searchProspeo(input) {
3143
3158
  if (!fallbackInput) {
3144
3159
  throw error;
3145
3160
  }
3146
- const fallbackResponse = await api.post(`/api/v3/prospeo/search`, fallbackInput);
3161
+ const fallbackResponse = requestOptions
3162
+ ? await api.post(`/api/v3/prospeo/search`, fallbackInput, requestOptions)
3163
+ : await api.post(`/api/v3/prospeo/search`, fallbackInput);
3147
3164
  const keyword = String(fallbackInput.filters.person_name_or_job_title ?? "title keyword");
3148
3165
  return compactProspeoSearchResponse(fallbackResponse, {
3149
3166
  warnings: [
@@ -3638,8 +3655,6 @@ export async function searchSignals(input) {
3638
3655
  campaignOfferId: input?.campaignOfferId,
3639
3656
  });
3640
3657
  const api = getApi();
3641
- const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
3642
- const requestOptions = workspaceRequestOptions(workspaceId);
3643
3658
  const { campaignOfferId, headlineICPCriteria, rubricGuidelines, currentStepTransition, } = input;
3644
3659
  const searchRequest = { ...input };
3645
3660
  delete searchRequest.currentStepTransition;
@@ -3650,54 +3665,31 @@ export async function searchSignals(input) {
3650
3665
  ? headlineICPCriteria
3651
3666
  : rubricGuidelines;
3652
3667
  if (campaignOfferId && searchCurrentStep) {
3653
- const body = {
3668
+ await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, {
3654
3669
  leadSourceType: "new",
3655
3670
  leadSourceProvider: "signal-discovery",
3656
3671
  currentStep: searchCurrentStep,
3657
3672
  ...(currentStepTransition ? { currentStepTransition } : {}),
3658
3673
  watchNarration: buildSignalDiscoverySearchWatchNarration(),
3659
- ...(workspaceId ? { workspaceId } : {}),
3660
- };
3661
- if (requestOptions) {
3662
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, body, requestOptions);
3663
- }
3664
- else {
3665
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, body);
3666
- }
3674
+ });
3667
3675
  }
3668
3676
  // Persist criteria early so user take-over has filters ready.
3669
3677
  if (campaignOfferId && effectiveHeadlineICPCriteria?.length) {
3670
- const body = {
3678
+ await api.patch(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts`, {
3671
3679
  selectedIds: [],
3672
3680
  unselectedIds: [],
3673
3681
  headlineICPCriteria: effectiveHeadlineICPCriteria,
3674
3682
  rubricGuidelines: effectiveHeadlineICPCriteria,
3675
- ...(workspaceId ? { workspaceId } : {}),
3676
- };
3677
- if (requestOptions) {
3678
- await api.patch(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts`, body, requestOptions);
3679
- }
3680
- else {
3681
- await api.patch(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts`, body);
3682
- }
3683
+ });
3683
3684
  }
3684
- const response = requestOptions
3685
- ? await api.post(`/api/v1/signal-discovery/search-signals`, searchRequest, requestOptions)
3686
- : await api.post(`/api/v1/signal-discovery/search-signals`, searchRequest);
3685
+ const response = await api.post(`/api/v1/signal-discovery/search-signals`, searchRequest);
3687
3686
  const summary = summarizeSignalSearchResponse(response);
3688
3687
  if (campaignOfferId && searchCurrentStep) {
3689
- const body = {
3688
+ await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, {
3690
3689
  currentStep: searchCurrentStep,
3691
3690
  ...(currentStepTransition ? { currentStepTransition } : {}),
3692
3691
  watchNarration: buildSignalDiscoveryResultsWatchNarration(summary.postsReturned),
3693
- ...(workspaceId ? { workspaceId } : {}),
3694
- };
3695
- if (requestOptions) {
3696
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, body, requestOptions);
3697
- }
3698
- else {
3699
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, body);
3700
- }
3692
+ });
3701
3693
  }
3702
3694
  return summary;
3703
3695
  }
@@ -3705,6 +3697,13 @@ export async function importLeads(input) {
3705
3697
  const api = getApi();
3706
3698
  const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
3707
3699
  const requestOptions = workspaceRequestOptions(workspaceId);
3700
+ const apiGet = (path) => requestOptions ? api.get(path, requestOptions) : api.get(path);
3701
+ const apiPost = (path, body) => requestOptions
3702
+ ? api.post(path, body, requestOptions)
3703
+ : api.post(path, body);
3704
+ const apiPut = (path, body) => requestOptions
3705
+ ? api.put(path, body, requestOptions)
3706
+ : api.put(path, body);
3708
3707
  const { campaignOfferId, currentStep, sourceLeadListId: inputSourceLeadListId, searchId, targetLeadCount, mode, searchName, leadListName, headlineICPCriteria, targetEngagerCount, maxPostsToScrape, allowInvalidSignalPosts, rubricGuidelines, confirmed, } = input;
3709
3708
  assertInteractionApproval({
3710
3709
  campaignId: campaignOfferId,
@@ -3717,11 +3716,12 @@ export async function importLeads(input) {
3717
3716
  let provider = input.provider;
3718
3717
  let campaignCurrentStep;
3719
3718
  let campaignSelectedLeadListId;
3720
- if (!provider || currentStep === undefined || mode === undefined) {
3719
+ if (!provider ||
3720
+ currentStep === undefined ||
3721
+ mode === undefined ||
3722
+ Boolean(inputSourceLeadListId)) {
3721
3723
  // Pull campaign once when we need provider or to determine default step behavior.
3722
- const campaign = requestOptions
3723
- ? await api.get(`/api/v2/campaign-offers/${campaignOfferId}`, requestOptions)
3724
- : await api.get(`/api/v2/campaign-offers/${campaignOfferId}`);
3724
+ const campaign = await apiGet(`/api/v2/campaign-offers/${campaignOfferId}`);
3725
3725
  if (!provider) {
3726
3726
  provider = normalizeImportProvider(campaign.leadSourceProvider);
3727
3727
  }
@@ -3843,9 +3843,7 @@ export async function importLeads(input) {
3843
3843
  const effectiveTargetEngagerCount = normalizePositiveInteger(targetEngagerCount) ?? null;
3844
3844
  // Get selected posts from the campaign's signal search tabs
3845
3845
  // Note: API returns flat fields (postUrl, postContent, authorName, etc.)
3846
- const tabsResponse = requestOptions
3847
- ? await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/tabs`, requestOptions)
3848
- : await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/tabs`);
3846
+ const tabsResponse = await apiGet(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/tabs`);
3849
3847
  // Collect all selected posts, mapping from API format to signal-leads/create format
3850
3848
  const selectedPosts = [];
3851
3849
  for (const tab of tabsResponse.tabs || []) {
@@ -3900,7 +3898,7 @@ export async function importLeads(input) {
3900
3898
  : " Select/promote more right-content posts, run another narrow Signal Discovery search, or switch to Sales Nav recent activity if the lane cannot produce enough source candidates.";
3901
3899
  throw new Error(`Signal Discovery selected posts only cover about ${importSelection.estimatedEngagers.toLocaleString("en-US")} people to check, below the approved ${importSelection.targetEngagerCount.toLocaleString("en-US")} source-candidate target. Do not scrape this under-capacity post set.${capClause}`);
3902
3900
  }
3903
- const postValidation = await validateSelectedSignalPostsForImport(api, uniqueSelectedPosts, requestOptions);
3901
+ const postValidation = await validateSelectedSignalPostsForImport(api, uniqueSelectedPosts);
3904
3902
  const plannedPostKeys = new Set(postsToScrape.map(signalImportPostKey));
3905
3903
  const invalidPlannedPosts = postValidation.invalidPosts.filter((post) => plannedPostKeys.has(signalImportPostKey(post)));
3906
3904
  const skippedInvalidPostWarning = postValidation.invalidPosts.length > 0
@@ -3971,7 +3969,7 @@ export async function importLeads(input) {
3971
3969
  ? headlineICPCriteria
3972
3970
  : rubricGuidelines;
3973
3971
  // Start the scrape job
3974
- const createBody = {
3972
+ const result = await apiPost(`/api/v3/campaigns/${campaignOfferId}/signal-leads/create`, {
3975
3973
  posts: postsToScrape,
3976
3974
  targetEngagerCount: importSelection.targetEngagerCount ?? undefined,
3977
3975
  ...(effectiveHeadlineICPCriteria &&
@@ -3981,14 +3979,10 @@ export async function importLeads(input) {
3981
3979
  rubricGuidelines: effectiveHeadlineICPCriteria,
3982
3980
  }
3983
3981
  : {}),
3984
- ...(workspaceId ? { workspaceId } : {}),
3985
- };
3986
- const result = requestOptions
3987
- ? await api.post(`/api/v3/campaigns/${campaignOfferId}/signal-leads/create`, createBody, requestOptions)
3988
- : await api.post(`/api/v3/campaigns/${campaignOfferId}/signal-leads/create`, createBody);
3982
+ });
3989
3983
  // CRITICAL: Update selectedLeadListId so UI subscribes to correct table
3990
3984
  // This enables realtime updates in LeadListCanvas
3991
- const updateBody = {
3985
+ await apiPut(`/api/v2/campaign-offers/${campaignOfferId}`, {
3992
3986
  selectedLeadListId: result.tableId,
3993
3987
  ...(shouldSetCurrentStep ? { currentStep: postImportCurrentStep } : {}),
3994
3988
  ...(shouldSetCurrentStep
@@ -4001,14 +3995,7 @@ export async function importLeads(input) {
4001
3995
  }),
4002
3996
  }
4003
3997
  : {}),
4004
- ...(workspaceId ? { workspaceId } : {}),
4005
- };
4006
- if (requestOptions) {
4007
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, updateBody, requestOptions);
4008
- }
4009
- else {
4010
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, updateBody);
4011
- }
3998
+ });
4012
3999
  return {
4013
4000
  provider: "signal-discovery",
4014
4001
  leadListId: result.tableId,
@@ -4039,14 +4026,10 @@ export async function importLeads(input) {
4039
4026
  const fallbackName = leadListName ||
4040
4027
  (searchName ? `${providerLabel} - ${searchName}` : undefined) ||
4041
4028
  `${providerLabel} Import ${new Date().toISOString().slice(0, 10)}`;
4042
- const createBody = {
4029
+ const createResult = await apiPost(`/api/v3/lead-lists`, {
4043
4030
  name: fallbackName,
4044
4031
  templateType: "lead_list",
4045
- ...(workspaceId ? { workspaceId } : {}),
4046
- };
4047
- const createResult = requestOptions
4048
- ? await api.post(`/api/v3/lead-lists`, createBody, requestOptions)
4049
- : await api.post(`/api/v3/lead-lists`, createBody);
4032
+ });
4050
4033
  leadListId = createResult.leadList?.id;
4051
4034
  createdLeadList = createResult.leadList;
4052
4035
  }
@@ -4060,29 +4043,21 @@ export async function importLeads(input) {
4060
4043
  const startImport = async () => {
4061
4044
  if (provider === "sales-nav") {
4062
4045
  // Sales Nav export flow
4063
- const body = {
4046
+ return apiPost(`/api/v3/sales-nav/export`, {
4064
4047
  searchId,
4065
4048
  workflowTableId: leadListId,
4066
4049
  campaignOfferId,
4067
4050
  targetLeadCount: cappedTargetLeadCount ?? defaultProviderSourceListTarget,
4068
4051
  ...(normalizedMode ? { mode: normalizedMode } : {}),
4069
- ...(workspaceId ? { workspaceId } : {}),
4070
- };
4071
- return requestOptions
4072
- ? api.post(`/api/v3/sales-nav/export`, body, requestOptions)
4073
- : api.post(`/api/v3/sales-nav/export`, body);
4052
+ });
4074
4053
  }
4075
4054
  if (provider === "prospeo") {
4076
- const body = {
4055
+ return apiPost(`/api/v3/lead-lists/${leadListId}/prospeo-import/start`, {
4077
4056
  searchId,
4078
4057
  campaignOfferId,
4079
4058
  targetLeadCount: cappedTargetLeadCount ?? defaultProviderSourceListTarget,
4080
4059
  ...(normalizedMode ? { mode: normalizedMode } : {}),
4081
- ...(workspaceId ? { workspaceId } : {}),
4082
- };
4083
- return requestOptions
4084
- ? api.post(`/api/v3/lead-lists/${leadListId}/prospeo-import/start`, body, requestOptions)
4085
- : api.post(`/api/v3/lead-lists/${leadListId}/prospeo-import/start`, body);
4060
+ });
4086
4061
  }
4087
4062
  throw new Error(`Unsupported import provider ${provider}. Choose sales-nav, prospeo, or signal-discovery.`);
4088
4063
  };
@@ -4128,31 +4103,30 @@ export async function importLeads(input) {
4128
4103
  throw error;
4129
4104
  }
4130
4105
  }
4131
- // Update selectedLeadListId so UI subscribes to the source lead list
4132
- // This enables realtime updates while the import job runs.
4133
- const updateBody = {
4134
- selectedLeadListId: leadListId,
4135
- ...(shouldSetCurrentStep ? { currentStep: effectiveCurrentStep } : {}),
4136
- ...(shouldSetCurrentStep
4137
- ? {
4138
- watchNarration: buildSourceImportWatchNarration({
4139
- provider,
4140
- targetLeadCount: cappedTargetLeadCount ?? null,
4141
- }),
4142
- }
4143
- : {}),
4144
- ...(workspaceId ? { workspaceId } : {}),
4145
- };
4146
- if (requestOptions) {
4147
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, updateBody, requestOptions);
4148
- }
4149
- else {
4150
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, updateBody);
4106
+ const selectedLeadListAlreadyCurrent = campaignSelectedLeadListId === leadListId;
4107
+ const shouldUpdateSelectedLeadList = !selectedLeadListAlreadyCurrent || shouldSetCurrentStep;
4108
+ if (shouldUpdateSelectedLeadList) {
4109
+ // Update selectedLeadListId so UI subscribes to the source lead list.
4110
+ // For refill same-source continuations with currentStep:null this is often
4111
+ // already true, so avoid a redundant campaign write.
4112
+ await apiPut(`/api/v2/campaign-offers/${campaignOfferId}`, {
4113
+ selectedLeadListId: leadListId,
4114
+ ...(shouldSetCurrentStep ? { currentStep: effectiveCurrentStep } : {}),
4115
+ ...(shouldSetCurrentStep
4116
+ ? {
4117
+ watchNarration: buildSourceImportWatchNarration({
4118
+ provider,
4119
+ targetLeadCount: cappedTargetLeadCount ?? null,
4120
+ }),
4121
+ }
4122
+ : {}),
4123
+ });
4151
4124
  }
4152
4125
  return {
4153
4126
  provider,
4154
4127
  leadListId,
4155
4128
  createdLeadList,
4129
+ selectedLeadListIdUpdated: shouldUpdateSelectedLeadList,
4156
4130
  jobResult,
4157
4131
  jobId,
4158
4132
  targetLeadCount: cappedTargetLeadCount ?? null,
@@ -4172,13 +4146,17 @@ export async function cancelLeadImport(input) {
4172
4146
  throw new Error(`cancel_lead_import: provider must be 'apollo', 'prospeo', or 'sales-nav' (got '${input.provider}'). Signal Discovery is not supported.`);
4173
4147
  }
4174
4148
  const api = getApi();
4149
+ const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
4150
+ const requestOptions = workspaceRequestOptions(workspaceId);
4175
4151
  const path = input.provider === "apollo"
4176
4152
  ? `/api/v3/lead-lists/${input.tableId}/apollo-import/cancel`
4177
4153
  : input.provider === "sales-nav"
4178
4154
  ? `/api/v3/lead-lists/${input.tableId}/sales-nav-import/cancel`
4179
4155
  : `/api/v3/lead-lists/${input.tableId}/prospeo-import/cancel`;
4180
4156
  try {
4181
- const result = await api.post(path, {});
4157
+ const result = await (requestOptions
4158
+ ? api.post(path, {}, requestOptions)
4159
+ : api.post(path, {}));
4182
4160
  return {
4183
4161
  cancelled: true,
4184
4162
  provider: input.provider,
@@ -4213,7 +4191,7 @@ export async function confirmLeadList(input) {
4213
4191
  });
4214
4192
  let resolvedLeadListId = sourceLeadListId;
4215
4193
  let resolvedProvider;
4216
- if (!resolvedLeadListId || currentStep === undefined || !resolvedProvider) {
4194
+ if (!resolvedLeadListId || currentStep === undefined) {
4217
4195
  const campaign = requestOptions
4218
4196
  ? await api.get(`/api/v2/campaign-offers/${campaignOfferId}`, requestOptions)
4219
4197
  : await api.get(`/api/v2/campaign-offers/${campaignOfferId}`);
@@ -4268,6 +4246,9 @@ export async function confirmLeadList(input) {
4268
4246
  ? await api.get(`/api/v3/workflow-tables/${resolvedLeadListId}?mode=meta`, requestOptions)
4269
4247
  : await api.get(`/api/v3/workflow-tables/${resolvedLeadListId}?mode=meta`);
4270
4248
  const leadListConfig = leadListMeta.table?.config ?? null;
4249
+ if (!resolvedProvider) {
4250
+ resolvedProvider = normalizeImportProvider(leadListConfig?.importProvider);
4251
+ }
4271
4252
  const leadListRowCount = leadListMeta.rowCount ?? 0;
4272
4253
  const importProgress = leadListConfig?.importProgress ?? null;
4273
4254
  const signalSourceTargetLeadCount = resolvedProvider === "signal-discovery" &&
@@ -4497,12 +4478,16 @@ export async function confirmLeadList(input) {
4497
4478
  .filter((cellId) => typeof cellId === "string");
4498
4479
  let recordedReviewBatch = null;
4499
4480
  if (campaignTableId && reviewBatchRowIds.length > 0) {
4500
- const recordResult = await api.post("/api/v3/mcp/campaign-processing", {
4481
+ const recordBody = {
4501
4482
  action: "recordReviewBatch",
4502
4483
  tableId: campaignTableId,
4503
4484
  rowIds: reviewBatchRowIds,
4504
4485
  enrichCellIds: reviewBatchEnrichCellIds,
4505
- });
4486
+ ...(workspaceId ? { workspaceId } : {}),
4487
+ };
4488
+ const recordResult = await (requestOptions
4489
+ ? api.post("/api/v3/mcp/campaign-processing", recordBody, requestOptions)
4490
+ : api.post("/api/v3/mcp/campaign-processing", recordBody));
4506
4491
  recordedReviewBatch = recordResult.reviewBatch ?? null;
4507
4492
  }
4508
4493
  const compactReviewBatch = {
@@ -4540,7 +4525,7 @@ export async function confirmLeadList(input) {
4540
4525
  // campaign table id makes that endpoint 404 with "Lead list not found"
4541
4526
  // and silently breaks the Leads → Filter Continue button.
4542
4527
  if (shouldSetCurrentStep) {
4543
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, {
4528
+ const updateBody = {
4544
4529
  currentStep: effectiveCurrentStep,
4545
4530
  ...(effectiveCurrentStep === "filter-choice"
4546
4531
  ? {
@@ -4551,7 +4536,11 @@ export async function confirmLeadList(input) {
4551
4536
  }),
4552
4537
  }
4553
4538
  : {}),
4554
- });
4539
+ ...(workspaceId ? { workspaceId } : {}),
4540
+ };
4541
+ await (requestOptions
4542
+ ? api.put(`/api/v2/campaign-offers/${campaignOfferId}`, updateBody, requestOptions)
4543
+ : api.put(`/api/v2/campaign-offers/${campaignOfferId}`, updateBody));
4555
4544
  }
4556
4545
  return {
4557
4546
  sourceLeadListId: resolvedLeadListId,
@@ -4648,8 +4637,6 @@ export function getProviderPrompt(input) {
4648
4637
  }
4649
4638
  export async function selectPromisingPosts(input) {
4650
4639
  const api = getApi();
4651
- const workspaceId = normalizeExplicitWorkspaceId(input.workspaceId);
4652
- const requestOptions = workspaceRequestOptions(workspaceId);
4653
4640
  const { campaignOfferId, selections, headlineICPCriteria, currentStep, selectionMode, mode, scrapePlanMode, targetEngagerCount, maxPostsToScrape, } = input;
4654
4641
  const effectiveMode = selectionMode ?? mode ?? "replace";
4655
4642
  const effectiveScrapePlanMode = scrapePlanMode ??
@@ -4669,25 +4656,19 @@ export async function selectPromisingPosts(input) {
4669
4656
  const postIds = selections.map((s) => s.postId);
4670
4657
  let unselectedIds = [];
4671
4658
  if (effectiveMode === "replace") {
4672
- const existing = requestOptions
4673
- ? await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts?selected=true`, requestOptions)
4674
- : await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts?selected=true`);
4659
+ const existing = await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts?selected=true`);
4675
4660
  const existingIds = existing?.posts
4676
4661
  ?.map((post) => post.id)
4677
4662
  .filter((id) => Boolean(id)) ?? [];
4678
4663
  const selectedSet = new Set(postIds);
4679
4664
  unselectedIds = existingIds.filter((id) => !selectedSet.has(id));
4680
4665
  }
4681
- const selectionBody = {
4666
+ const selectionResult = await api.patch(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts`, {
4682
4667
  selectedIds: postIds,
4683
4668
  unselectedIds,
4684
4669
  headlineICPCriteria,
4685
4670
  rubricGuidelines: headlineICPCriteria,
4686
- ...(workspaceId ? { workspaceId } : {}),
4687
- };
4688
- const selectionResult = requestOptions
4689
- ? await api.patch(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts`, selectionBody, requestOptions)
4690
- : await api.patch(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/posts`, selectionBody);
4671
+ });
4691
4672
  if (selectionResult.selectedCount <= 0) {
4692
4673
  return {
4693
4674
  success: false,
@@ -4701,9 +4682,7 @@ export async function selectPromisingPosts(input) {
4701
4682
  let recommendedPostCount = selectionResult.selectedCount;
4702
4683
  let recommendationTargetEngagerCount = null;
4703
4684
  try {
4704
- const tabsResponse = requestOptions
4705
- ? await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/tabs`, requestOptions)
4706
- : await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/tabs`);
4685
+ const tabsResponse = await api.get(`/api/v3/campaigns/${campaignOfferId}/signal-discovery/tabs`);
4707
4686
  const reasonsByPostId = new Map(selections.map((selection) => [selection.postId, selection.reason]));
4708
4687
  const selectedByUrl = new Map();
4709
4688
  for (const tab of tabsResponse.tabs ?? []) {
@@ -4760,17 +4739,10 @@ Approval card should say:
4760
4739
  }
4761
4740
  const selectionCurrentStep = currentStep === null ? undefined : (currentStep ?? "signal-discovery");
4762
4741
  if (selectionCurrentStep) {
4763
- const body = {
4742
+ await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, {
4764
4743
  currentStep: selectionCurrentStep,
4765
4744
  watchNarration: buildSelectedPostApprovalWatchNarration(selectionResult.selectedCount, recommendedPostCount, recommendationTargetEngagerCount),
4766
- ...(workspaceId ? { workspaceId } : {}),
4767
- };
4768
- if (requestOptions) {
4769
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, body, requestOptions);
4770
- }
4771
- else {
4772
- await api.put(`/api/v2/campaign-offers/${campaignOfferId}`, body);
4773
- }
4745
+ });
4774
4746
  }
4775
4747
  return {
4776
4748
  success: true,
@@ -137,7 +137,7 @@ export interface PostFindLeadsScoutRegistryResponse {
137
137
  }
138
138
  export declare const DEFAULT_SUBSKILL_PROMPT_CHUNK_CHARS = 48000;
139
139
  export declare const MAX_SUBSKILL_PROMPT_CHUNK_CHARS = 48000;
140
- export declare const ALLOWED_SUBSKILL_PROMPT_NAMES: readonly ["building-gtm-tables", "content", "create-ab-test", "create-campaign", "create-campaign-brief", "create-campaign-v2", "create-campaign-v2-tail", "create-campaign-v2-validation", "create-evergreen-campaigns", "create-post", "create-rubric", "engage", "enrich-prospects", "fill-send-horizon", "find-leads", "foundation", "generate-messages", "interview", "load-voice", "refresh-sender-engagement", "refill-sends", "refill-sends-workflow", "research", "research-prospect", "research-sender", "weekly-campaign-summary", "workflow-sequences"];
140
+ export declare const ALLOWED_SUBSKILL_PROMPT_NAMES: readonly ["building-gtm-tables", "content", "create-ab-test", "create-campaign", "create-campaign-brief", "create-campaign-v2", "create-campaign-v2-tail", "create-campaign-v2-validation", "create-evergreen-campaigns", "create-post", "create-rubric", "engage", "enrich-prospects", "fill-send-horizon", "find-leads", "foundation", "generate-messages", "interview", "load-voice", "refresh-sender-engagement", "refill-sends", "refill-sends-evergreen", "refill-sends-evergreen-workflow", "refill-sends-workflow", "research", "research-prospect", "research-sender", "weekly-campaign-summary", "workflow-sequences"];
141
141
  export declare const promptToolDefinitions: ({
142
142
  name: string;
143
143
  description: string;
@@ -181,7 +181,7 @@ export declare const promptToolDefinitions: ({
181
181
  properties: {
182
182
  subskillName: {
183
183
  type: string;
184
- enum: readonly ["building-gtm-tables", "content", "create-ab-test", "create-campaign", "create-campaign-brief", "create-campaign-v2", "create-campaign-v2-tail", "create-campaign-v2-validation", "create-evergreen-campaigns", "create-post", "create-rubric", "engage", "enrich-prospects", "fill-send-horizon", "find-leads", "foundation", "generate-messages", "interview", "load-voice", "refresh-sender-engagement", "refill-sends", "refill-sends-workflow", "research", "research-prospect", "research-sender", "weekly-campaign-summary", "workflow-sequences"];
184
+ enum: readonly ["building-gtm-tables", "content", "create-ab-test", "create-campaign", "create-campaign-brief", "create-campaign-v2", "create-campaign-v2-tail", "create-campaign-v2-validation", "create-evergreen-campaigns", "create-post", "create-rubric", "engage", "enrich-prospects", "fill-send-horizon", "find-leads", "foundation", "generate-messages", "interview", "load-voice", "refresh-sender-engagement", "refill-sends", "refill-sends-evergreen", "refill-sends-evergreen-workflow", "refill-sends-workflow", "research", "research-prospect", "research-sender", "weekly-campaign-summary", "workflow-sequences"];
185
185
  description: string;
186
186
  };
187
187
  offset: {
@@ -216,7 +216,7 @@ export declare const promptToolDefinitions: ({
216
216
  properties: {
217
217
  subskillName: {
218
218
  type: string;
219
- enum: readonly ["building-gtm-tables", "content", "create-ab-test", "create-campaign", "create-campaign-brief", "create-campaign-v2", "create-campaign-v2-tail", "create-campaign-v2-validation", "create-evergreen-campaigns", "create-post", "create-rubric", "engage", "enrich-prospects", "fill-send-horizon", "find-leads", "foundation", "generate-messages", "interview", "load-voice", "refresh-sender-engagement", "refill-sends", "refill-sends-workflow", "research", "research-prospect", "research-sender", "weekly-campaign-summary", "workflow-sequences"];
219
+ enum: readonly ["building-gtm-tables", "content", "create-ab-test", "create-campaign", "create-campaign-brief", "create-campaign-v2", "create-campaign-v2-tail", "create-campaign-v2-validation", "create-evergreen-campaigns", "create-post", "create-rubric", "engage", "enrich-prospects", "fill-send-horizon", "find-leads", "foundation", "generate-messages", "interview", "load-voice", "refresh-sender-engagement", "refill-sends", "refill-sends-evergreen", "refill-sends-evergreen-workflow", "refill-sends-workflow", "research", "research-prospect", "research-sender", "weekly-campaign-summary", "workflow-sequences"];
220
220
  description: string;
221
221
  };
222
222
  assetPath: {
@@ -38,6 +38,8 @@ export const ALLOWED_SUBSKILL_PROMPT_NAMES = [
38
38
  "load-voice",
39
39
  "refresh-sender-engagement",
40
40
  "refill-sends",
41
+ "refill-sends-evergreen",
42
+ "refill-sends-evergreen-workflow",
41
43
  "refill-sends-workflow",
42
44
  "research",
43
45
  "research-prospect",
@@ -373,7 +375,7 @@ export function getPostFindLeadsScoutRegistry() {
373
375
  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
376
  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
377
  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. 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. 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.`,
378
+ 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.`,
377
379
  },
378
380
  };
379
381
  }