@adport/provider-microsoft 0.9.0 → 0.10.0
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.js +6 -6
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/csv.ts","../src/children.ts","../src/images.ts","../src/extensions.ts","../src/native.ts","../src/targeting.ts","../src/targeting-schemas.ts","../src/negative-keywords.ts","../src/budgets.ts","../src/planning.ts","../src/conversions.ts","../src/audiences.ts","../src/audience-targeting.ts","../src/offline-reports.ts","../src/offline-conversions.ts","../src/offline-conversion-schemas.ts","../src/general-targeting.ts","../src/general-targeting-schemas.ts","../src/experiments.ts","../src/tools.ts","../src/child-tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\n\nexport interface MicrosoftCredentials {\n developerToken: string;\n clientId: string;\n refreshToken: string;\n /** Only for confidential (web) apps; native/CLI public clients have no secret. */\n clientSecret?: string;\n sandbox?: boolean;\n}\n\nconst TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';\nexport const MSADS_SCOPE = 'https://ads.microsoft.com/msads.manage offline_access';\n/** Published universal sandbox developer token (anyone may use it in sandbox). */\nexport const SANDBOX_DEVELOPER_TOKEN = 'BBD37VB98';\n\nfunction hosts(sandbox: boolean) {\n const infix = sandbox ? '.sandbox' : '';\n return {\n campaign: `https://campaign.api${infix}.bingads.microsoft.com/CampaignManagement/v13`,\n customer: `https://clientcenter.api${infix}.bingads.microsoft.com/CustomerManagement/v13`,\n reporting: `https://reporting.api${infix}.bingads.microsoft.com/Reporting/v13`,\n adinsight: `https://adinsight.api${infix}.bingads.microsoft.com/AdInsight/v13`,\n };\n}\n\nexport type MicrosoftService = 'campaign' | 'customer' | 'reporting' | 'adinsight';\n\nexport interface RequestScope {\n /** Manager account (customer) id header. */\n customerId?: string;\n /** Ad account id header. */\n customerAccountId?: string;\n}\n\n/**\n * Microsoft Advertising REST v13 client. Public-client refresh tokens rotate —\n * onRefreshTokenRotated lets the credential store persist the replacement.\n */\nexport class MicrosoftAdsClient {\n private accessToken?: { token: string; expiresAt: number };\n private refreshToken: string;\n readonly sandbox: boolean;\n\n constructor(\n private readonly credentials: MicrosoftCredentials,\n private readonly onRefreshTokenRotated?: (token: string) => Promise<void>,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.refreshToken = credentials.refreshToken;\n this.sandbox = credentials.sandbox ?? false;\n }\n\n async getAccessToken(): Promise<string> {\n if (this.accessToken && this.accessToken.expiresAt > Date.now()) {\n return this.accessToken.token;\n }\n const body = new URLSearchParams({\n client_id: this.credentials.clientId,\n scope: 'https://ads.microsoft.com/msads.manage',\n refresh_token: this.refreshToken,\n grant_type: 'refresh_token',\n });\n if (this.credentials.clientSecret) body.set('client_secret', this.credentials.clientSecret);\n const response = await this.fetchImpl(TOKEN_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body,\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Microsoft OAuth refresh failed (${response.status}). Public-client refresh tokens expire after ~90 days — re-run \\`adport connect microsoft\\`.`,\n safeJson(raw),\n );\n }\n const data = JSON.parse(raw) as { access_token: string; expires_in: number; refresh_token?: string };\n this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1000 };\n if (data.refresh_token && data.refresh_token !== this.refreshToken) {\n this.refreshToken = data.refresh_token;\n await this.onRefreshTokenRotated?.(data.refresh_token);\n }\n return this.accessToken.token;\n }\n\n async request<T>(\n service: MicrosoftService,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body: unknown,\n scope: RequestScope = {},\n options: { privatePayload?: boolean } = {},\n ): Promise<T> {\n const token = await this.getAccessToken();\n const headers: Record<string, string> = {\n authorization: `Bearer ${token}`,\n DeveloperToken: this.sandbox ? SANDBOX_DEVELOPER_TOKEN : this.credentials.developerToken,\n 'content-type': 'application/json',\n };\n if (scope.customerId) headers.CustomerId = scope.customerId;\n if (scope.customerAccountId) headers.CustomerAccountId = scope.customerAccountId;\n const response = await this.fetchImpl(`${hosts(this.sandbox)[service]}/${path.replace(/^\\//, '')}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const raw = await response.text();\n if (!response.ok || options.privatePayload && response.status !== 200) {\n if (options.privatePayload) throw new AdportError('PROVIDER_ERROR', `microsoft: private request failed (HTTP ${response.status}); native response values omitted`);\n throw new AdportError('PROVIDER_ERROR', formatMicrosoftError(response.status, raw), safeJson(raw));\n }\n if (options.privatePayload) {\n try {\n if (!raw.trim()) throw new Error('Empty receipt');\n return JSON.parse(raw) as T;\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: private request returned an unrecognized JSON receipt; native values omitted'); }\n }\n return (raw ? JSON.parse(raw) : {}) as T;\n }\n\n /** Plain authorized download (report files); returns raw bytes. */\n async download(url: string): Promise<Uint8Array> {\n const response = await this.fetchImpl(url, {});\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', `Microsoft report download failed (HTTP ${response.status})`);\n }\n return new Uint8Array(await response.arrayBuffer());\n }\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\ninterface BatchErrorItem {\n Code?: number;\n ErrorCode?: string;\n Message?: string;\n FieldPath?: string;\n Index?: number;\n Details?: string;\n Detail?: string;\n}\n\n/**\n * REST errors are serialized fault objects: ApiFaultDetail\n * {OperationErrors, BatchErrors}, AdApiFaultDetail {Errors}, plus TrackingId.\n */\nexport function formatMicrosoftError(status: number, raw: string): string {\n const parsed = safeJson(raw) as {\n TrackingId?: string;\n Type?: string;\n OperationErrors?: BatchErrorItem[];\n BatchErrors?: BatchErrorItem[];\n Errors?: BatchErrorItem[];\n };\n if (!parsed || typeof parsed !== 'object' || (!parsed.OperationErrors && !parsed.Errors && !parsed.BatchErrors)) {\n return `Microsoft Advertising API error (HTTP ${status})`;\n }\n const items = [...(parsed.OperationErrors ?? []), ...(parsed.BatchErrors ?? []), ...(parsed.Errors ?? [])];\n const lines = items.map((e) => {\n const where = e.Index !== undefined ? ` [item ${e.Index}${e.FieldPath ? ` ${e.FieldPath}` : ''}]` : '';\n return `${e.Code ?? '?'} ${e.ErrorCode ?? ''}: ${e.Message ?? e.Details ?? e.Detail ?? ''}${where}`;\n });\n let message = `Microsoft Advertising API error (HTTP ${status}, ${parsed.Type ?? 'fault'}):\\n ${lines.join('\\n ')}`;\n if (items.some((e) => e.Code === 105)) {\n message += '\\n Code 105 InvalidCredentials: check the developer token matches the environment (sandbox vs production).';\n }\n if (items.some((e) => e.Code === 117)) {\n message += '\\n Code 117 CallRateExceeded: wait 60s before retrying.';\n }\n if (parsed.TrackingId) message += ` [TrackingId: ${parsed.TrackingId}]`;\n return message;\n}\n\nexport function formatPartialErrors(partialErrors: Array<BatchErrorItem | null> | undefined): string | undefined {\n const errors = partialErrors?.filter((error): error is BatchErrorItem => error !== null) ?? [];\n if (errors.length === 0) return undefined;\n return errors\n .map((e) => `item ${e.Index ?? '?'}: ${e.Code ?? ''} ${e.ErrorCode ?? ''} ${e.Message ?? ''}${e.FieldPath ? ` (${e.FieldPath})` : ''}`)\n .join('; ');\n}\n","import {\n AdportError,\n LocalMediaResolver,\n METRICS,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type MediaResolver,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { unzipSync } from 'fflate';\nimport { formatPartialErrors, MicrosoftAdsClient, type MicrosoftService } from './client.js';\nimport { parseCsv } from './csv.js';\nimport { MicrosoftChildService } from './children.js';\nimport { MicrosoftImageService, MICROSOFT_IMAGE_WRITES } from './images.js';\nimport { MicrosoftExtensionService, MICROSOFT_EXTENSION_WRITES } from './extensions.js';\nimport { MicrosoftTargetingService, MICROSOFT_TARGETING_WRITES } from './targeting.js';\nimport { MicrosoftNegativeKeywordService, MICROSOFT_NEGATIVE_KEYWORD_WRITES } from './negative-keywords.js';\nimport { MicrosoftBudgetService, MICROSOFT_BUDGET_WRITES } from './budgets.js';\nimport { MicrosoftPlanningService } from './planning.js';\nimport { MicrosoftConversionService, MICROSOFT_CONVERSION_WRITES } from './conversions.js';\nimport { MicrosoftAudienceService, MICROSOFT_AUDIENCE_WRITES } from './audiences.js';\nimport { MicrosoftAudienceTargetingService, MICROSOFT_AUDIENCE_TARGETING_WRITES } from './audience-targeting.js';\nimport { MicrosoftOfflineReportService } from './offline-reports.js';\nimport { MicrosoftOfflineConversionService, MICROSOFT_OFFLINE_CONVERSION_WRITES } from './offline-conversions.js';\nimport { MicrosoftGeneralTargetingService, MICROSOFT_GENERAL_TARGETING_WRITES } from './general-targeting.js';\nimport { MicrosoftExperimentService, MICROSOFT_EXPERIMENT_WRITES } from './experiments.js';\n\n/** DailyBudget is a double in whole account-currency units. */\nexport const UNITS_TO_MICROS = 1_000_000;\n// Omitting CampaignType silently returns Search only. REST flags are comma-separated.\nexport const MICROSOFT_CAMPAIGN_TYPES = 'App, Audience, DynamicSearchAds, Hotel, ObjectiveBased, PerformanceMax, Search, Shopping';\n\ninterface MicrosoftCampaign {\n Id: number | string;\n Name: string;\n Status: string;\n DailyBudget?: number;\n BudgetType?: string;\n BudgetId?: number | string | null;\n TimeZone?: string;\n CampaignType?: string;\n SubType?: string | null;\n ExperimentId?: number | string | null;\n}\n\ninterface WritePlan extends Omit<WritePreview, 'serverValidated'> {\n execute: () => Promise<string[]>;\n resultDetails?: () => unknown;\n resultWarnings?: () => string[];\n}\n\nexport class MicrosoftAdsProvider implements AdProvider {\n readonly id = 'microsoft';\n /** accountId → parent customer id, learned from SearchAccounts. */\n private customerIds = new Map<string, string>();\n private currencies = new Map<string, string>();\n readonly children: MicrosoftChildService;\n readonly images: MicrosoftImageService;\n readonly extensions: MicrosoftExtensionService;\n readonly targeting: MicrosoftTargetingService;\n readonly generalTargeting: MicrosoftGeneralTargetingService;\n readonly negativeKeywords: MicrosoftNegativeKeywordService;\n readonly budgets: MicrosoftBudgetService;\n readonly planning: MicrosoftPlanningService;\n readonly conversions: MicrosoftConversionService;\n readonly audiences: MicrosoftAudienceService;\n readonly audienceTargeting: MicrosoftAudienceTargetingService;\n readonly offlineReports: MicrosoftOfflineReportService;\n readonly offlineConversions: MicrosoftOfflineConversionService;\n readonly experiments: MicrosoftExperimentService;\n\n constructor(\n private readonly client: MicrosoftAdsClient,\n private readonly options: { pollIntervalMs?: number; pollMaxAttempts?: number } = {},\n media: MediaResolver = new LocalMediaResolver(),\n ) {\n this.children = new MicrosoftChildService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));\n this.images = new MicrosoftImageService(client, account => this.scopeFor(account), media);\n this.extensions = new MicrosoftExtensionService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), (account, ids) => this.images.lookupMany(account, ids));\n this.targeting = new MicrosoftTargetingService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));\n this.generalTargeting = new MicrosoftGeneralTargetingService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));\n this.negativeKeywords = new MicrosoftNegativeKeywordService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));\n this.budgets = new MicrosoftBudgetService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), account => this.listCampaigns(account), async account => { await this.scopeFor(account); return this.currencies.get(account); });\n this.planning = new MicrosoftPlanningService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), account => this.currencies.get(account));\n this.conversions = new MicrosoftConversionService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));\n this.audiences = new MicrosoftAudienceService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), account => this.listCampaigns(account));\n this.audienceTargeting = new MicrosoftAudienceTargetingService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), (account, audience, type) => this.audiences.get(account, audience, type));\n this.offlineReports = new MicrosoftOfflineReportService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));\n this.offlineConversions = new MicrosoftOfflineConversionService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), this.conversions);\n this.experiments = new MicrosoftExperimentService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), account => this.listCampaigns(account), async account => { await this.scopeFor(account); return this.currencies.get(account); });\n }\n\n capabilities(): ProviderCapabilities {\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'microsoft_set_campaign_status',\n input: { account_id: accountId, campaign_id: campaignId, status: 'Paused' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const user = await this.client.request<{ User?: { Id?: number | string } }>(\n 'customer',\n 'POST',\n 'User/Query',\n { UserId: null },\n );\n const userId = user.User?.Id;\n if (userId === undefined) {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: GetUser returned no user id');\n }\n const search = await this.client.request<{\n Accounts?: Array<{\n Id: number | string;\n Name?: string;\n Number?: string;\n CurrencyCode?: string;\n AccountLifeCycleStatus?: string;\n ParentCustomerId?: number | string;\n }>;\n }>('customer', 'POST', 'Accounts/Search', {\n Predicates: [{ Field: 'UserId', Operator: 'Equals', Value: String(userId) }],\n PageInfo: { Index: 0, Size: 100 },\n });\n const accounts = search.Accounts ?? [];\n for (const account of accounts) {\n if (account.CurrencyCode) this.currencies.set(String(account.Id), account.CurrencyCode);\n if (account.ParentCustomerId !== undefined) {\n this.customerIds.set(String(account.Id), String(account.ParentCustomerId));\n }\n }\n return accounts.map((a) => ({\n provider: this.id,\n id: String(a.Id),\n name: a.Name ?? a.Number ?? String(a.Id),\n currency: a.CurrencyCode,\n status: a.AccountLifeCycleStatus,\n }));\n }\n\n private async scopeFor(accountId: string, refresh = false) {\n if (refresh) { this.customerIds.delete(accountId); this.currencies.delete(accountId); }\n if (refresh || !this.customerIds.has(accountId)) await this.listAccounts();\n return { customerId: this.customerIds.get(accountId), customerAccountId: accountId };\n }\n\n async listCampaigns(accountId: string): Promise<MicrosoftCampaign[]> {\n const scope = await this.scopeFor(accountId);\n const data = await this.client.request<{ Campaigns?: MicrosoftCampaign[] | null }>(\n 'campaign',\n 'POST',\n 'Campaigns/QueryByAccountId',\n { AccountId: accountId, CampaignType: MICROSOFT_CAMPAIGN_TYPES, ReturnAdditionalFields: null },\n scope,\n );\n return data.Campaigns ?? [];\n }\n\n async apiRead(input: {\n account_id: string;\n service: MicrosoftService;\n path: string;\n body?: Record<string, unknown>;\n }): Promise<unknown> {\n const path = validateMicrosoftReadPath(input.path);\n validateMicrosoftAccountScope(input.body, input.account_id);\n const scope = await this.scopeFor(input.account_id);\n return this.client.request(input.service, 'POST', path, input.body ?? {}, scope);\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n const providerRows = await this.performanceReport(accountId, range.start, range.end, query.level === 'account' ? { ...query, level: 'campaign', metrics: [...METRICS] } : query);\n if (query.level === 'account') {\n if (providerRows.length > 0) {\n const aggregate = aggregateAccountRows(providerRows, this.id, accountId);\n aggregate.metrics = Object.fromEntries(query.metrics.filter(metric => aggregate.metrics[metric] !== undefined).map(metric => [metric, aggregate.metrics[metric]]));\n rows.push(aggregate);\n }\n } else {\n rows.push(...providerRows);\n }\n }\n const limit = query.limit ?? 1000;\n return { rows: rows.slice(0, limit), truncated: rows.length > limit };\n }\n\n private async performanceReport(accountId: string, start: string, end: string, query: NormalizedQuery): Promise<ReportRow[]> {\n const selection = query.level === 'ad_group'\n ? { type: 'AdGroupPerformanceReportRequest', columns: ['AdGroupId', 'AdGroupName', 'Status'] }\n : query.level === 'ad' ? { type: 'AdPerformanceReportRequest', columns: ['AdId', 'AdTitle', 'AdStatus'] }\n : { type: 'CampaignPerformanceReportRequest', columns: ['CampaignId', 'CampaignName', 'CampaignStatus'] };\n const bytes = await this.reportCsv(accountId, start, end, selection.type, [...selection.columns, 'Spend', 'Impressions', 'Clicks', 'Conversions', 'Revenue']);\n return bytes ? this.parseReport(bytes, accountId, query) : [];\n }\n\n async nativeReport(input: { account_id: string; kind: 'keyword' | 'search_term'; date_range: NormalizedQuery['dateRange']; limit: number }) {\n const range = resolveDateRange(input.date_range);\n const type = input.kind === 'keyword' ? 'KeywordPerformanceReportRequest' : 'SearchQueryPerformanceReportRequest';\n const columns = input.kind === 'keyword' ? ['CampaignId', 'AdGroupId', 'KeywordId', 'Keyword', 'BidMatchType'] : ['CampaignId', 'AdGroupId', 'AdId', 'KeywordId', 'Keyword', 'SearchQuery'];\n const bytes = await this.reportCsv(input.account_id, range.start, range.end, type, [...columns, 'Spend', 'Impressions', 'Clicks', 'Conversions', 'Revenue']);\n const records = bytes ? this.reportObjects(bytes) : [];\n return { rows: records.slice(0, input.limit), truncated: records.length > input.limit, report_type: type };\n }\n\n private async reportCsv(\n accountId: string,\n start: string,\n end: string,\n type: string,\n columns: string[],\n ): Promise<Uint8Array | undefined> {\n const scope = await this.scopeFor(accountId);\n const toDate = (iso: string) => {\n const [year, month, day] = iso.split('-').map(Number);\n return { Day: day, Month: month, Year: year };\n };\n // Async flow: Submit → Poll until Success → download zipped CSV.\n const submit = await this.client.request<{ ReportRequestId?: string }>(\n 'reporting',\n 'POST',\n 'GenerateReport/Submit',\n {\n ReportRequest: {\n Type: type,\n Format: 'Csv',\n FormatVersion: '2.0',\n ReportName: 'adport campaign report',\n ExcludeReportHeader: true,\n ExcludeReportFooter: true,\n ExcludeColumnHeaders: false,\n ReturnOnlyCompleteData: false,\n Aggregation: 'Summary',\n Columns: columns,\n Scope: { AccountIds: [accountId] },\n Time: { CustomDateRangeStart: toDate(start), CustomDateRangeEnd: toDate(end) },\n },\n },\n scope,\n );\n if (!submit.ReportRequestId) {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: SubmitGenerateReport returned no ReportRequestId');\n }\n\n const maxAttempts = this.options.pollMaxAttempts ?? 30;\n const interval = this.options.pollIntervalMs ?? 5_000;\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const poll = await this.client.request<{\n ReportRequestStatus?: { Status?: string; ReportDownloadUrl?: string | null };\n }>('reporting', 'POST', 'GenerateReport/Poll', { ReportRequestId: submit.ReportRequestId }, scope);\n const status = poll.ReportRequestStatus?.Status;\n if (status === 'Error') {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: report generation failed (Status: Error)');\n }\n if (status === 'Success') {\n const url = poll.ReportRequestStatus?.ReportDownloadUrl;\n if (!url) return undefined; // Success with null URL = no data for the range.\n return this.client.download(url);\n }\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n throw new AdportError('PROVIDER_ERROR', `microsoft: report not ready after ${maxAttempts} polls`);\n }\n\n private reportObjects(zipBytes: Uint8Array): Array<Record<string, string>> {\n const files = unzipSync(zipBytes);\n const selected = Object.entries(files).find(([name]) => name.toLowerCase().endsWith('.csv'))?.[1] ?? Object.values(files)[0];\n if (!selected) return [];\n const rows = parseCsv(new TextDecoder().decode(selected).replace(/^\\uFEFF/, ''));\n const header = rows[0];\n return header ? rows.slice(1).map(row => Object.fromEntries(header.map((key, index) => [key, row[index] ?? '']))) : [];\n }\n\n private parseReport(zipBytes: Uint8Array, accountId: string, query: NormalizedQuery): ReportRow[] {\n return this.reportObjects(zipBytes).map(row => {\n const numeric = (key: string) => {\n const text = row[key]?.trim();\n if (!text) return undefined;\n const number = Number(text);\n return Number.isFinite(number) ? number : undefined;\n };\n const metrics = performanceMetrics({ spend: numeric('Spend'), impressions: numeric('Impressions'), clicks: numeric('Clicks'), conversions: numeric('Conversions'), conversion_value: numeric('Revenue') });\n const identity = query.level === 'ad_group' ? ['AdGroupId', 'AdGroupName', 'Status'] : query.level === 'ad' ? ['AdId', 'AdTitle', 'AdStatus'] : ['CampaignId', 'CampaignName', 'CampaignStatus'];\n return { provider: this.id, accountId, entity: { level: query.level, id: row[identity[0]!] ?? '', name: row[identity[1]!] ?? '', status: row[identity[2]!] || undefined },\n metrics: Object.fromEntries(query.metrics.filter(metric => metrics[metric] !== undefined).map(metric => [metric, metrics[metric]])) };\n });\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n return {\n summary: plan.summary,\n changes: plan.changes,\n ...(plan.fieldChanges ? { fieldChanges: plan.fieldChanges } : {}),\n ...(plan.notes ? { notes: plan.notes } : {}),\n ...(plan.review ? { review: plan.review } : {}),\n coercions: plan.coercions,\n budgetDeltas: plan.budgetDeltas,\n serverValidated: false,\n };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const resourceIds = await plan.execute();\n return { applied: true, resourceIds, ...(plan.resultDetails ? { details: plan.resultDetails() } : {}), ...(plan.resultWarnings ? { warnings: plan.resultWarnings() } : {}) };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n if (MICROSOFT_IMAGE_WRITES.has(op.tool)) return this.images.plan(op);\n if (MICROSOFT_EXTENSION_WRITES.has(op.tool)) return this.extensions.plan(op, guard);\n if (MICROSOFT_TARGETING_WRITES.has(op.tool)) return this.targeting.plan(op, guard);\n if (MICROSOFT_GENERAL_TARGETING_WRITES.has(op.tool)) return this.generalTargeting.plan(op, guard);\n if (MICROSOFT_NEGATIVE_KEYWORD_WRITES.has(op.tool)) return this.negativeKeywords.plan(op);\n if (MICROSOFT_BUDGET_WRITES.has(op.tool)) return this.budgets.plan(op);\n if (MICROSOFT_CONVERSION_WRITES.has(op.tool)) return this.conversions.plan(op, guard);\n if (MICROSOFT_OFFLINE_CONVERSION_WRITES.has(op.tool)) return this.offlineConversions.plan(op);\n if (MICROSOFT_AUDIENCE_WRITES.has(op.tool)) return this.audiences.plan(op);\n if (MICROSOFT_AUDIENCE_TARGETING_WRITES.has(op.tool)) return this.audienceTargeting.plan(op, guard);\n if (MICROSOFT_EXPERIMENT_WRITES.has(op.tool)) return this.experiments.plan(op, guard);\n const payload = op.payload as never;\n switch (op.tool) {\n case 'microsoft_create_campaign':\n return this.planCreateCampaign(op.accountId, payload, guard);\n case 'microsoft_set_campaign_status':\n return this.planSetStatus(op.accountId, payload);\n case 'microsoft_set_budget':\n return this.planSetBudget(op.accountId, payload);\n case 'microsoft_api_create':\n return this.planApiCreate(op.accountId, payload, guard);\n case 'microsoft_api_update':\n return this.planApiUpdate(op.accountId, payload);\n case 'microsoft_api_delete':\n return this.planApiDelete(op.accountId, payload);\n default:\n return this.children.plan(op, guard);\n }\n }\n\n private async planApiCreate(\n accountId: string,\n payload: { resource: string; body: Record<string, unknown> },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const resource = validateMicrosoftResource(payload.resource);\n requireTypedMutationTool(resource, payload.body);\n const body = structuredClone(payload.body);\n validateMicrosoftAccountScope(body, accountId);\n const coercions: string[] = [];\n if (guard.forcePausedCreation) {\n const collection = resource.toLowerCase();\n if (['campaigns', 'adgroups', 'ads', 'keywords'].includes(collection)) {\n const keys = Object.keys(body).filter(key => key.toLowerCase() === collection);\n if (!keys.length || keys.some(key => !Array.isArray(body[key]))) throw new AdportError('INVALID_INPUT', `microsoft: ${resource} creation needs its native collection array so paused_creation can be enforced`);\n for (const key of keys) for (const [index, item] of (body[key] as unknown[]).entries()) {\n if (!isRecord(item)) throw new AdportError('INVALID_INPUT', `microsoft: ${resource} creation needs resource objects`);\n const statuses = Object.keys(item).filter(key => key.toLowerCase() === 'status');\n if (statuses.length === 1 && statuses[0] === 'Status' && item.Status === 'Paused') continue;\n for (const status of statuses) delete item[status];\n item.Status = 'Paused';\n coercions.push(`body.${key}[${index}].Status coerced to Paused by policy (paused_creation)`);\n }\n }\n coerceMicrosoftCreatedStatuses(body, coercions);\n }\n return {\n summary: `Create Microsoft Advertising ${resource} resource(s)`,\n changes: [`+ POST /${resource} ${JSON.stringify(body)}`],\n coercions,\n budgetDeltas: collectMicrosoftBudgets(body),\n execute: async () => this.executeMicrosoftMutation(accountId, 'POST', resource, body),\n };\n }\n\n private async planApiUpdate(\n accountId: string,\n payload: { resource: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const resource = validateMicrosoftResource(payload.resource);\n requireTypedMutationTool(resource, payload.body);\n validateMicrosoftAccountScope(payload.body, accountId);\n if (containsMicrosoftBudget(payload.body)) {\n throw new AdportError('INVALID_INPUT', 'microsoft: budget updates require microsoft_set_budget for policy checks');\n }\n return {\n summary: `Update Microsoft Advertising ${resource} resource(s)`,\n changes: [`~ PUT /${resource} ${JSON.stringify(payload.body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => this.executeMicrosoftMutation(accountId, 'PUT', resource, payload.body),\n };\n }\n\n private async planApiDelete(\n accountId: string,\n payload: { resource: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const resource = validateMicrosoftResource(payload.resource);\n requireTypedMutationTool(resource, payload.body);\n validateMicrosoftAccountScope(payload.body, accountId);\n return {\n summary: `Permanently delete Microsoft Advertising ${resource} resource(s)`,\n changes: [`- DELETE /${resource} ${JSON.stringify(payload.body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => this.executeMicrosoftMutation(accountId, 'DELETE', resource, payload.body),\n };\n }\n\n private async executeMicrosoftMutation(\n accountId: string,\n method: 'POST' | 'PUT' | 'DELETE',\n resource: string,\n body: Record<string, unknown>,\n ): Promise<string[]> {\n const scope = await this.scopeFor(accountId);\n const result = await this.client.request<Record<string, unknown>>('campaign', method, resource, body, scope);\n const partial = formatPartialErrors(result.PartialErrors as Parameters<typeof formatPartialErrors>[0]);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: ${resource} partial errors — ${partial}`);\n return extractMicrosoftIds(result);\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: { name: string; daily_budget: number; time_zone?: string; status?: string },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n // The API's own default status on Add is Paused; we only coerce an explicit Active.\n let status = payload.status ?? 'Paused';\n if (guard.forcePausedCreation && status === 'Active') {\n status = 'Paused';\n coercions.push('status coerced to Paused by policy (paused_creation)');\n }\n const campaign = {\n Name: payload.name,\n CampaignType: 'Search',\n DailyBudget: payload.daily_budget,\n BudgetType: 'DailyBudgetStandard',\n TimeZone: payload.time_zone ?? 'PacificTimeUSCanadaTijuana',\n Status: status,\n };\n return {\n summary: `Create Microsoft Advertising campaign \"${payload.name}\" (${status}), daily budget ${payload.daily_budget}`,\n changes: [`+ campaign \"${payload.name}\" type=Search daily_budget=${payload.daily_budget} status=${status}`],\n coercions,\n budgetDeltas: [\n { target: `new campaign \"${payload.name}\" daily budget`, toMicros: payload.daily_budget * UNITS_TO_MICROS },\n ],\n execute: async () => {\n const scope = await this.scopeFor(accountId);\n const result = await this.client.request<{\n CampaignIds?: Array<number | string | null>;\n PartialErrors?: Array<{ Index?: number; Code?: number; ErrorCode?: string; Message?: string; FieldPath?: string }>;\n }>('campaign', 'POST', 'Campaigns', { AccountId: accountId, Campaigns: [campaign] }, scope);\n const partial = formatPartialErrors(result.PartialErrors);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: AddCampaigns partial errors — ${partial}`);\n return (result.CampaignIds ?? []).filter((id): id is number | string => id !== null).map(String);\n },\n };\n }\n\n private async lookupCampaign(accountId: string, campaignId: string): Promise<MicrosoftCampaign> {\n const campaigns = await this.listCampaigns(accountId);\n const campaign = campaigns.find((c) => String(c.Id) === campaignId);\n if (!campaign) {\n throw new AdportError('PROVIDER_ERROR', `microsoft: campaign ${campaignId} not found in account ${accountId}`);\n }\n return campaign;\n }\n\n private async updateCampaign(\n accountId: string,\n fields: Record<string, unknown> & { Id: number | string },\n ): Promise<void> {\n const scope = await this.scopeFor(accountId);\n // UpdateCampaigns is PUT; omitted fields stay unchanged.\n const result = await this.client.request<{\n PartialErrors?: Array<{ Index?: number; Code?: number; ErrorCode?: string; Message?: string }>;\n }>('campaign', 'PUT', 'Campaigns', { AccountId: accountId, Campaigns: [fields] }, scope);\n const partial = formatPartialErrors(result.PartialErrors);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: UpdateCampaigns partial errors — ${partial}`);\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_id: string; status: 'Active' | 'Paused' },\n ): Promise<WritePlan> {\n const current = await this.lookupCampaign(accountId, payload.campaign_id);\n if (current.ExperimentId && String(current.ExperimentId) !== '0') throw new AdportError('INVALID_INPUT', 'microsoft: experiment campaign status is inherited; change the base campaign status instead');\n return {\n summary: `Set Microsoft campaign \"${current.Name}\" status ${current.Status} → ${payload.status}`,\n changes: [`~ campaign ${payload.campaign_id} Status ${current.Status} → ${payload.status}`],\n notes: ['Related active or scheduled campaign-copy experiments follow the base serving status. Completed experiments cannot be restarted by unpausing the base.'],\n coercions: [],\n budgetDeltas: [],\n execute: async () => {\n await this.updateCampaign(accountId, { Id: current.Id, Status: payload.status });\n return [payload.campaign_id];\n },\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; daily_budget: number },\n ): Promise<WritePlan> {\n const current = await this.lookupCampaign(accountId, payload.campaign_id);\n if (current.ExperimentId && String(current.ExperimentId) !== '0') throw new AdportError('INVALID_INPUT', 'microsoft: experiment campaign budget is inherited; change the base campaign budget instead');\n if (current.BudgetId && Number(current.BudgetId) > 0) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `microsoft: campaign \"${current.Name}\" uses a SHARED budget (BudgetId ${current.BudgetId}) — ` +\n 'its DailyBudget cannot be changed per-campaign (CampaignServiceCannotUpdateSharedBudget).',\n );\n }\n return {\n summary: `Change Microsoft campaign \"${current.Name}\" daily budget ${current.DailyBudget ?? '(unset)'} → ${payload.daily_budget}`,\n changes: [`~ campaign ${payload.campaign_id} DailyBudget ${current.DailyBudget ?? '(unset)'} → ${payload.daily_budget}`],\n notes: ['For related campaign-copy experiments, this changes the base total daily allocation before its traffic/budget split. The experiment campaign inherits that budget rather than receiving an additional independent pool.'],\n coercions: [],\n budgetDeltas: [\n {\n target: `campaign \"${current.Name}\" daily budget`,\n ...(current.DailyBudget !== undefined ? { fromMicros: current.DailyBudget * UNITS_TO_MICROS } : {}),\n toMicros: payload.daily_budget * UNITS_TO_MICROS,\n },\n ],\n execute: async () => {\n await this.updateCampaign(accountId, { Id: current.Id, DailyBudget: payload.daily_budget });\n return [payload.campaign_id];\n },\n };\n }\n}\n\nfunction performanceMetrics(base: Partial<Record<MetricName, number>>): Partial<Record<MetricName, number>> {\n const ratio = (numerator: number | undefined, denominator: number | undefined, scale = 1) => numerator === undefined || denominator === undefined ? undefined : denominator > 0 ? round2(numerator / denominator * scale) : 0;\n return Object.fromEntries(Object.entries({ ...base,\n ctr: ratio(base.clicks, base.impressions, 100), cpc: ratio(base.spend, base.clicks), cpm: ratio(base.spend, base.impressions, 1000),\n cpa: ratio(base.spend, base.conversions), roas: ratio(base.conversion_value, base.spend),\n }).filter(([, value]) => value !== undefined).map(([key, value]) => [key, round2(value!)]));\n}\n\nfunction aggregateAccountRows(rows: ReportRow[], provider: string, accountId: string): ReportRow {\n const totals: Partial<Record<MetricName, number>> = {};\n for (const metric of ['spend', 'impressions', 'clicks', 'conversions', 'conversion_value'] as const) {\n if (rows.every(row => row.metrics[metric] !== undefined)) totals[metric] = rows.reduce((sum, row) => sum + row.metrics[metric]!, 0);\n }\n return { provider, accountId, entity: { level: 'account', id: accountId, name: accountId }, metrics: performanceMetrics(totals) };\n}\n\nfunction validateMicrosoftReadPath(path: string): string {\n const normalized = path.replace(/^\\/+|\\/+$/g, '').trim();\n const action = normalized.split('/').at(-1) ?? '';\n if (\n !/^[A-Za-z][A-Za-z0-9]*(?:\\/[A-Za-z][A-Za-z0-9]*){1,2}$/.test(normalized) ||\n !/^(?:Query|Search|Get|Submit|Poll)/.test(action)\n ) {\n throw new AdportError('INVALID_INPUT', `microsoft: unsupported read operation path \"${path}\"`);\n }\n return normalized;\n}\n\nfunction validateMicrosoftResource(resource: string): string {\n const normalized = resource.trim();\n if (!/^[A-Z][A-Za-z0-9]{1,80}$/.test(normalized)) {\n throw new AdportError('INVALID_INPUT', `microsoft: invalid Campaign Management resource \"${resource}\"`);\n }\n return normalized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction requireTypedMutationTool(resource: string, body: unknown): void {\n const collection = resource.toLowerCase();\n const hasFieldValue = (value: unknown, key: string, matches: (value: string) => boolean): boolean => Array.isArray(value) ? value.some(child => hasFieldValue(child, key, matches)) : isRecord(value) && Object.entries(value).some(([field, child]) => field.toLowerCase() === key && typeof child === 'string' && matches(child.trim().toLowerCase()) || hasFieldValue(child, key, matches));\n const audienceSelectors = new Set(['audience', 'audiencecriterion', 'custom', 'customaudience', 'inmarket', 'inmarketaudience', 'product', 'productaudience', 'remarketinglist', 'similarremarketinglist', 'combinedlist', 'customerlist', 'impressionbasedremarketinglist', 'customsegment', 'aiprompt']);\n if (['campaigncriterions', 'adgroupcriterions'].includes(collection) && (hasFieldValue(body, 'criteriontype', value => value.split(/[,\\s]+/).some(value => audienceSelectors.has(value))) || hasFieldValue(body, 'type', value => ['audience', 'audiencecriterion'].includes(value)))) throw new AdportError('INVALID_INPUT', 'microsoft: audience criteria require typed audience-targeting tools for hierarchy, target-mode and opposite-level checks');\n const generalSelectors = new Set(['targets', 'age', 'agecriterion', 'gender', 'gendercriterion', 'device', 'devicecriterion', 'daytime', 'daytimecriterion', 'location', 'locationcriterion', 'locationintent', 'locationintentcriterion', 'radius', 'radiuscriterion']);\n if (['campaigncriterions', 'adgroupcriterions'].includes(collection) && (hasFieldValue(body, 'criteriontype', value => value.split(/[,\\s]+/).some(value => generalSelectors.has(value))) || hasFieldValue(body, 'type', value => generalSelectors.has(value)))) throw new AdportError('INVALID_INPUT', 'microsoft: general targets require microsoft_update_targeting for scope, inheritance, schedule-clock and preservation checks');\n const hasKey = (value: unknown, name: string): boolean => Array.isArray(value) ? value.some(child => hasKey(child, name)) : isRecord(value) && Object.entries(value).some(([key, child]) => key.toLowerCase() === name || hasKey(child, name));\n if (['campaigns', 'adgroups'].includes(collection) && hasKey(body, 'adscheduleusesearchertimezone')) throw new AdportError('INVALID_INPUT', 'microsoft: schedule clocks require microsoft_update_targeting with native account time-zone and inheritance context');\n if (['campaigns', 'adgroups'].includes(collection) && hasFieldValue(body, 'type', value => ['target', 'targetsetting'].includes(value))) throw new AdportError('INVALID_INPUT', 'microsoft: target-setting changes require microsoft_set_audience_target_mode to preserve other targeting details');\n if (collection === 'audiences') throw new AdportError('INVALID_INPUT', 'microsoft: audience mutations require typed audience tools for Account ownership, replacement-rule semantics and deletion reference checks');\n if (collection === 'experiments') throw new AdportError('INVALID_INPUT', 'microsoft: experiments require typed tools for inherited pause/budget policy, ownership, snapshots and coupled campaign effects; promotion and graduation need separate reviewed workflows');\n if (collection === 'uettags') throw new AdportError('INVALID_INPUT', 'microsoft: use microsoft_create_uet_tag for new uninstalled tags; customer-wide tag edits, deletion and sharing are not exposed through single-account generic tools');\n if (collection === 'conversiongoals') throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal mutations require typed conversion tools for account scope, native auto-tagging side effects and event-criteria preservation');\n if (['offlineconversions', 'offlineconversionadjustments'].includes(collection)) throw new AdportError('INVALID_INPUT', 'microsoft: offline events require typed upload tools for private previews, goal binding and indexed receipt handling');\n const referencesSharedBudget = (value: unknown): boolean => Array.isArray(value) ? value.some(referencesSharedBudget) : isRecord(value) && Object.entries(value).some(([key, child]) => key.toLowerCase() === 'budgetid' && child !== null && child !== undefined && String(child) !== '0' || referencesSharedBudget(child));\n if (collection === 'budgets' || referencesSharedBudget(body)) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget changes require the typed microsoft shared-budget tools for membership, snapshot and monetary policy checks');\n}\n\nfunction validateMicrosoftAccountScope(value: unknown, accountId: string): void {\n if (Array.isArray(value)) return value.forEach((item) => validateMicrosoftAccountScope(item, accountId));\n if (!isRecord(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (key.toLowerCase() === 'accountid' && String(child) !== accountId) {\n throw new AdportError('INVALID_INPUT', `microsoft: body AccountId ${String(child)} does not match selected account ${accountId}`);\n }\n if (key.toLowerCase() === 'accountids' && (!Array.isArray(child) || child.some((id) => String(id) !== accountId))) {\n throw new AdportError('INVALID_INPUT', `microsoft: body AccountIds must contain only selected account ${accountId}`);\n }\n validateMicrosoftAccountScope(child, accountId);\n }\n}\n\nfunction coerceMicrosoftCreatedStatuses(value: unknown, coercions: string[], path = 'body'): void {\n if (Array.isArray(value)) return value.forEach((item, index) => coerceMicrosoftCreatedStatuses(item, coercions, `${path}[${index}]`));\n if (!isRecord(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (key.toLowerCase() === 'status' && typeof child === 'string' && ['active', 'paused'].includes(child.toLowerCase()) && (key !== 'Status' || child !== 'Paused')) {\n delete value[key];\n value.Status = 'Paused';\n coercions.push(`${path}.${key} coerced to Paused by policy (paused_creation)`);\n } else coerceMicrosoftCreatedStatuses(child, coercions, `${path}.${key}`);\n }\n}\n\nfunction containsMicrosoftBudget(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsMicrosoftBudget);\n if (!isRecord(value)) return false;\n return Object.entries(value).some(([key, child]) => /budget/i.test(key) || containsMicrosoftBudget(child));\n}\n\nfunction collectMicrosoftBudgets(value: unknown, path = 'body'): WritePreview['budgetDeltas'] {\n const deltas: WritePreview['budgetDeltas'] = [];\n if (Array.isArray(value)) {\n value.forEach((item, index) => deltas.push(...collectMicrosoftBudgets(item, `${path}[${index}]`)));\n return deltas;\n }\n if (!isRecord(value)) return deltas;\n for (const [key, child] of Object.entries(value)) {\n const childPath = `${path}.${key}`;\n if (/budget/i.test(key) && !/type|id/i.test(key)) {\n const amount = Number(child);\n if (Number.isFinite(amount) && amount > 0) {\n deltas.push({ target: childPath, toMicros: Math.round(amount * UNITS_TO_MICROS) });\n }\n }\n deltas.push(...collectMicrosoftBudgets(child, childPath));\n }\n return deltas;\n}\n\nfunction extractMicrosoftIds(value: unknown): string[] {\n const ids: string[] = [];\n const visit = (item: unknown): void => {\n if (Array.isArray(item)) return item.forEach(visit);\n if (!isRecord(item)) return;\n for (const [key, child] of Object.entries(item)) {\n if (/Ids?$/.test(key)) {\n if (Array.isArray(child)) child.forEach((id) => { if (id !== null) ids.push(String(id)); });\n else if (typeof child === 'string' || typeof child === 'number') ids.push(String(child));\n } else visit(child);\n }\n };\n visit(value);\n return [...new Set(ids)];\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100;\n}\n","/** Minimal RFC-4180-ish CSV parser (quotes, escaped quotes, CRLF). */\nexport function parseCsv(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = '';\n let inQuotes = false;\n for (let i = 0; i < text.length; i++) {\n const char = text[i]!;\n if (inQuotes) {\n if (char === '\"') {\n if (text[i + 1] === '\"') {\n field += '\"';\n i++;\n } else {\n inQuotes = false;\n }\n } else {\n field += char;\n }\n continue;\n }\n if (char === '\"') {\n inQuotes = true;\n } else if (char === ',') {\n row.push(field);\n field = '';\n } else if (char === '\\n' || char === '\\r') {\n if (char === '\\r' && text[i + 1] === '\\n') i++;\n row.push(field);\n field = '';\n if (row.length > 1 || row[0] !== '') rows.push(row);\n row = [];\n } else {\n field += char;\n }\n }\n if (field !== '' || row.length > 0) {\n row.push(field);\n if (row.length > 1 || row[0] !== '') rows.push(row);\n }\n return rows;\n}\n","import { AdportError, creativeStatusAction, type Creative, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { formatPartialErrors, MicrosoftAdsClient, type RequestScope } from './client.js';\n\ntype Row = Record<string, unknown>;\ninterface Plan { summary: string; changes: string[]; coercions: string[]; budgetDeltas: WritePreview['budgetDeltas']; execute: () => Promise<string[]> }\ntype Parent = { account_id: string; campaign_id: string; ad_group_id: string };\nconst object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nconst objects = (value: unknown): Row[] => Array.isArray(value) ? value.filter(row => row && typeof row === 'object') as Row[] : [];\nconst texts = (value: unknown): string[] => objects(value).flatMap(link => typeof object(link.Asset).Text === 'string' ? [String(object(link.Asset).Text)] : []);\n\n/** REST wire shapes pinned in MicrosoftDocs/Advertising (2026-11-02). */\nexport class MicrosoftChildService {\n constructor(private readonly client: MicrosoftAdsClient, private readonly scope: (accountId: string) => Promise<RequestScope>,\n private readonly campaign: (accountId: string, campaignId: string) => Promise<unknown>) {}\n\n private async request(account: string, path: string, body: Row, method: 'POST' | 'PUT' | 'DELETE' = 'POST'): Promise<Row> {\n const result = await this.client.request<Row>('campaign', method, path, body, await this.scope(account));\n const partial = formatPartialErrors(result.PartialErrors as Parameters<typeof formatPartialErrors>[0]);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: ${path} partial errors — ${partial}. Check successful resource IDs before retrying.`, {\n resourceIds: Object.entries(result).filter(([key]) => /Ids$/.test(key)).flatMap(([, value]) => Array.isArray(value) ? value.filter(id => id !== null).map(String) : []), partialErrors: result.PartialErrors,\n });\n return result;\n }\n\n async listGroups(input: { account_id: string; campaign_id: string }) {\n await this.campaign(input.account_id, input.campaign_id);\n const result = await this.request(input.account_id, 'AdGroups/QueryByCampaignId', { CampaignId: input.campaign_id, ReturnAdditionalFields: 'AdGroupType' });\n return { rows: objects(result.AdGroups), truncated: false };\n }\n\n private async group(input: Parent): Promise<Row> {\n await this.campaign(input.account_id, input.campaign_id);\n const result = await this.request(input.account_id, 'AdGroups/QueryByIds', { CampaignId: input.campaign_id, AdGroupIds: [input.ad_group_id], ReturnAdditionalFields: 'AdGroupType' });\n const group = objects(result.AdGroups).find(row => String(row.Id) === input.ad_group_id);\n if (!group) throw new AdportError('INVALID_INPUT', 'Microsoft ad group was not found in the selected campaign/account.');\n return group;\n }\n\n async listKeywords(input: Parent) {\n await this.group(input);\n const result = await this.request(input.account_id, 'Keywords/QueryByAdGroupId', { AdGroupId: input.ad_group_id, ReturnAdditionalFields: null });\n return { rows: objects(result.Keywords), truncated: false };\n }\n\n async listAds(input: Parent & { ad_types: string[]; limit: number }) {\n await this.group(input);\n const result = await this.request(input.account_id, 'Ads/QueryByAdGroupId', { AdGroupId: input.ad_group_id, AdTypes: input.ad_types, ReturnAdditionalFields: null });\n const ads = objects(result.Ads);\n return { ads: ads.slice(0, input.limit), truncated: ads.length > input.limit, creatives: ads.slice(0, input.limit).map(ad => this.card(input, ad)) };\n }\n\n private card(input: Parent, ad: Row): Creative {\n const adId = String(ad.Id), headlines = texts(ad.Headlines), descriptions = texts(ad.Descriptions), args = { account_id: input.account_id, campaign_id: input.campaign_id, ad_group_id: input.ad_group_id, ad_id: adId };\n if (!/^\\d+$/.test(adId)) throw new AdportError('PROVIDER_ERROR', 'Microsoft returned an ad without a valid ID.');\n const actions: Creative['actions'] = ['Active', 'Paused'].includes(String(ad.Status)) ? [creativeStatusAction('microsoft_set_ad_status', { ...args, ad_type: ad.Type }, String(ad.Status), ['Active', 'Paused'])] : [];\n if (ad.Type === 'ResponsiveSearch') actions.push({ label: 'Edit ad copy', tool: 'microsoft_update_responsive_search_ad', arguments: args,\n fields: [\n { key: 'headlines', label: 'Headlines (one per line)', type: 'text_list', value: headlines },\n { key: 'descriptions', label: 'Descriptions (one per line)', type: 'text_list', value: descriptions },\n { key: 'final_urls', label: 'Landing pages (one per line)', type: 'url_list', value: Array.isArray(ad.FinalUrls) ? ad.FinalUrls.map(String) : [] },\n ] });\n const destinations = Array.isArray(ad.FinalUrls) ? ad.FinalUrls.map(String).filter(value => { try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; } catch { return false; } }) : [];\n return { id: adId, provider: 'microsoft', account_id: input.account_id, campaign_id: input.campaign_id, ad_group_id: input.ad_group_id,\n name: headlines[0] || String(ad.Title ?? ad.TitlePart1 ?? `Ad ${adId}`), type: String(ad.Type), status: String(ad.Status),\n headlines, descriptions, landing_urls: destinations, media: [], actions };\n }\n\n private async ad(input: Parent, id: string, type: string): Promise<Row> {\n await this.group(input);\n const result = await this.request(input.account_id, 'Ads/QueryByIds', { AdGroupId: input.ad_group_id, AdIds: [id], AdTypes: [type], ReturnAdditionalFields: null });\n const ad = objects(result.Ads).find(row => String(row.Id) === id && row.Type === type);\n if (!ad) throw new AdportError('INVALID_INPUT', 'Microsoft ad was not found with this type in the selected ad group/account.');\n return ad;\n }\n\n private async keywords(input: Parent, ids: string[]): Promise<Row[]> {\n await this.group(input);\n const result = await this.request(input.account_id, 'Keywords/QueryByIds', { AdGroupId: input.ad_group_id, KeywordIds: ids, ReturnAdditionalFields: null });\n const rows = objects(result.Keywords);\n if (ids.some(id => !rows.some(row => String(row.Id) === id))) throw new AdportError('INVALID_INPUT', 'A keyword was not found in the selected ad group/account.');\n return rows;\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const p = op.payload as Row, parent: Parent = { account_id: op.accountId, campaign_id: String(p.campaign_id), ad_group_id: String(p.ad_group_id) };\n const mutate = (collection: string, body: Row, changes: string[], ids: string[] = [], coercions: string[] = []): Plan => ({\n summary: changes[0]!, changes, coercions, budgetDeltas: [], execute: async () => {\n const method = op.kind === 'create' ? 'POST' : op.kind === 'remove' ? 'DELETE' : 'PUT';\n const result = await this.request(op.accountId, collection, body, method);\n if (op.kind !== 'create') return ids;\n const values = result[`${collection === 'AdGroups' ? 'AdGroup' : collection === 'Keywords' ? 'Keyword' : 'Ad'}Ids`];\n const created = Array.isArray(values) ? values.filter(id => id !== null).map(String) : [];\n if (created.length !== objects(body[collection]).length) throw new AdportError('PROVIDER_ERROR', 'Microsoft did not return an ID for every requested resource. Check creation status before retrying.', { resourceIds: created });\n return created;\n },\n });\n const creationStatus = (requested: unknown) => guard.forcePausedCreation ? 'Paused' : requested ?? 'Paused';\n const creationCoercion = (requested: unknown) => guard.forcePausedCreation && requested === 'Active' ? ['status coerced to Paused by policy (paused_creation)'] : [];\n const assetLinks = (value: unknown, current: unknown = []): Row[] => (value as string[]).map((text, index) => {\n const previous = objects(current)[index];\n // Text asset IDs are read-only; Microsoft deduplicates assets by text.\n return { Asset: { Type: 'TextAsset', Text: text }, ...(previous?.PinnedField ? { PinnedField: previous.PinnedField } : {}) };\n });\n switch (op.tool) {\n case 'microsoft_create_ad_group':\n await this.campaign(op.accountId, String(p.campaign_id));\n return mutate('AdGroups', { CampaignId: p.campaign_id, AdGroups: [{ Name: p.name, AdGroupType: 'SearchStandard', Language: p.language, Status: creationStatus(p.status), ...(p.cpc_bid !== undefined ? { CpcBid: { Amount: p.cpc_bid } } : {}) }] },\n [`+ SearchStandard ad group \"${p.name}\" (${creationStatus(p.status)}), language=${p.language}`, ...(p.cpc_bid !== undefined ? [`CPC bid ${p.cpc_bid} whole currency units`] : [])], [], creationCoercion(p.status));\n case 'microsoft_set_ad_group_status':\n case 'microsoft_update_ad_group': {\n const current = await this.group(parent), fields = op.tool === 'microsoft_set_ad_group_status' ? { Status: p.status } : { ...(p.name !== undefined ? { Name: p.name } : {}), ...(p.cpc_bid !== undefined ? { CpcBid: { Amount: p.cpc_bid } } : {}) };\n return mutate('AdGroups', { CampaignId: p.campaign_id, AdGroups: [{ Id: p.ad_group_id, ...fields }] }, [`~ ad group ${p.ad_group_id}: ${JSON.stringify({ Name: current.Name, Status: current.Status, CpcBid: current.CpcBid })} → ${JSON.stringify(fields)}`], [String(p.ad_group_id)]);\n }\n case 'microsoft_create_responsive_search_ad': {\n const group = await this.group(parent);\n if (group.AdGroupType !== 'SearchStandard') throw new AdportError('INVALID_INPUT', 'Responsive search ads require a SearchStandard ad group.');\n const fields = { Type: 'ResponsiveSearch', Status: creationStatus(p.status), Headlines: assetLinks(p.headlines), Descriptions: assetLinks(p.descriptions), FinalUrls: p.final_urls,\n ...(p.path1 !== undefined ? { Path1: p.path1 } : {}), ...(p.path2 !== undefined ? { Path2: p.path2 } : {}) };\n return mutate('Ads', { AdGroupId: p.ad_group_id, Ads: [fields] }, [`+ responsive search ad ${JSON.stringify(fields)}`], [], creationCoercion(p.status));\n }\n case 'microsoft_update_responsive_search_ad':\n case 'microsoft_set_ad_status': {\n const type = op.tool === 'microsoft_set_ad_status' ? String(p.ad_type) : 'ResponsiveSearch';\n const current = await this.ad(parent, String(p.ad_id), type);\n const fields: Row = { Id: p.ad_id, Type: type };\n if (op.tool === 'microsoft_set_ad_status') fields.Status = p.status;\n else {\n if (p.headlines !== undefined) fields.Headlines = assetLinks(p.headlines, current.Headlines);\n if (p.descriptions !== undefined) fields.Descriptions = assetLinks(p.descriptions, current.Descriptions);\n if (p.final_urls !== undefined) fields.FinalUrls = p.final_urls;\n if (p.path1 !== undefined) fields.Path1 = p.path1;\n if (p.path2 !== undefined) fields.Path2 = p.path2;\n }\n return mutate('Ads', { AdGroupId: p.ad_group_id, Ads: [fields] }, [`~ ad ${p.ad_id}: ${JSON.stringify(current)} → ${JSON.stringify(fields)}`,\n ...(op.tool === 'microsoft_update_responsive_search_ad' ? [`Serving status remains ${current.Status}. Omitted content fields remain unchanged.`] : [])], [String(p.ad_id)]);\n }\n case 'microsoft_add_keywords': {\n await this.group(parent);\n const keywords = (p.keywords as Array<{ text: string; match_type: string; bid?: number; status: string }>).map(keyword => ({ Text: keyword.text, MatchType: keyword.match_type, Status: creationStatus(keyword.status), ...(keyword.bid !== undefined ? { Bid: { Amount: keyword.bid } } : {}) }));\n return mutate('Keywords', { AdGroupId: p.ad_group_id, Keywords: keywords }, [`+ keywords ${JSON.stringify(keywords)}`], [], guard.forcePausedCreation && (p.keywords as Array<{ status: string }>).some(keyword => keyword.status === 'Active') ? ['keyword statuses coerced to Paused by policy (paused_creation)'] : []);\n }\n case 'microsoft_set_keyword_status':\n case 'microsoft_set_keyword_bid': {\n const [current] = await this.keywords(parent, [String(p.keyword_id)]);\n const fields = op.tool === 'microsoft_set_keyword_status' ? { Status: p.status } : { Bid: { Amount: p.bid } };\n return mutate('Keywords', { AdGroupId: p.ad_group_id, Keywords: [{ Id: p.keyword_id, ...fields }] }, [`~ keyword ${p.keyword_id}: ${JSON.stringify(current)} → ${JSON.stringify(fields)}`], [String(p.keyword_id)]);\n }\n case 'microsoft_remove_keywords':\n await this.keywords(parent, p.keyword_ids as string[]);\n return mutate('Keywords', { AdGroupId: p.ad_group_id, KeywordIds: p.keyword_ids }, [`- keywords ${(p.keyword_ids as string[]).join(', ')}; cannot be undone`], p.keyword_ids as string[]);\n default: throw new AdportError('PROVIDER_ERROR', `microsoft: unsupported write tool ${op.tool}`);\n }\n }\n}\n","import { AdportError, LocalMediaResolver, creativesOutput, defineTool, guardedWriteTool, mediaSourceFields, type AnyToolDefinition, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, formatPartialErrors, type RequestScope } from './client.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\ntype Row = Record<string, unknown>;\ntype ImagePlan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\nconst id = z.string().regex(/^[1-9]\\d*$/);\nconst imageType = z.enum(['GenericImage', 'Image16x9', 'Image15x10', 'Image4x3', 'Image12x10', 'Image1x1', 'Image191x100', 'Image4x1']);\nconst upload = z.object({ ...mediaSourceFields, image_type: imageType.default('GenericImage'), alt_text: z.string().max(1000).optional() })\n .refine(value => Boolean(value.media_id) !== Boolean(value.file_path), 'Choose media_id or file_path');\nconst image = z.object({ image_id: id });\nconst output = creativesOutput.extend({ images: z.array(z.record(z.string(), z.unknown())), next_page_index: z.number().int().nonnegative().optional() });\nexport const MICROSOFT_IMAGE_WRITES = new Set(['microsoft_upload_image', 'microsoft_delete_image']);\nconst rows = (value: unknown): Row[] => z.array(z.record(z.string(), z.unknown())).parse(value ?? []);\nconst nativeId = (value: unknown): string => {\n if (typeof value === 'number' && (!Number.isSafeInteger(value) || value <= 0)) throw new AdportError('PROVIDER_ERROR', 'microsoft: unsafe native media ID');\n const parsed = id.safeParse(typeof value === 'number' ? String(value) : value);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid native media ID');\n return parsed.data;\n};\n\n/** MicrosoftDocs/Advertising@fdee2fcf and official Python SDK@4b6fb31c; live-verified CSV flags. */\nexport class MicrosoftImageService {\n constructor(private readonly client: MicrosoftAdsClient, private readonly scope: (account: string) => Promise<RequestScope>, private readonly media: MediaResolver = new LocalMediaResolver()) {}\n\n private async request(account: string, path: string, body: Row, method: 'POST' | 'DELETE' = 'POST'): Promise<Row> {\n id.parse(account);\n const scope = await this.scope(account);\n if (!scope.customerId || scope.customerAccountId !== account) throw new AdportError('INVALID_INPUT', 'microsoft: account ownership could not be verified');\n const result = await this.client.request<Row>('campaign', method, path, body, scope);\n const errors = formatPartialErrors(result.PartialErrors as Parameters<typeof formatPartialErrors>[0]);\n if (errors) throw new AdportError('PROVIDER_ERROR', `microsoft: ${path}: ${errors}. Reconcile before retrying.`, { resourceIds: Array.isArray(result.MediaIds) ? result.MediaIds.filter(value => value !== null).map(nativeId) : [], partialErrors: result.PartialErrors });\n return result;\n }\n\n private async page(account: string, pageIndex: number, pageSize: number): Promise<Row[]> {\n const result = await this.request(account, 'MediaMetaData/QueryByAccountId', {\n MediaEnabledEntities: 'ImageAdExtension, ResponsiveAd', PageInfo: { Index: pageIndex, Size: pageSize }, ReturnAdditionalFields: 'Text',\n });\n if (!Object.hasOwn(result, 'MediaMetaData')) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-library metadata was not returned');\n const images = rows(result.MediaMetaData);\n if (images.length > pageSize || new Set(images.map(value => nativeId(value.Id))).size !== images.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid image-library page');\n return images;\n }\n\n private async find(account: string, imageId: string): Promise<Row | undefined> {\n id.parse(imageId);\n const seen = new Set<string>();\n for (let page = 0; page < 5; page++) {\n const values = await this.page(account, page, 1000);\n for (const value of values) {\n const key = nativeId(value.Id);\n if (seen.has(key)) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-library pagination did not advance');\n seen.add(key);\n }\n const found = values.find(value => nativeId(value.Id) === imageId);\n if (found) return found;\n if (values.length < 1000) return;\n }\n throw new AdportError('PROVIDER_ERROR', 'microsoft: cannot verify image ownership within the 5000-image library scan limit');\n }\n\n private async owned(account: string, imageId: string): Promise<Row> {\n const result = await this.find(account, imageId);\n if (!result) throw new AdportError('INVALID_INPUT', 'microsoft: image was not found in the selected account library');\n return result;\n }\n\n private gallery(account: string, images: Row[], truncated: boolean, nextPage?: number) {\n const creatives: Creative[] = images.map(value => {\n const imageId = nativeId(value.Id), alt = typeof value.Text === 'string' ? value.Text : undefined;\n const representations = rows(value.Representations);\n const media: Creative['media'] = representations.flatMap(item => {\n if (typeof item.Url !== 'string') return [];\n try {\n const url = new URL(item.Url);\n if (url.protocol === 'https:' && !url.username && !url.password && url.hostname === 'www.bing.com') return [{ type: 'image' as const, url: item.Url, ...(alt ? { alt } : {}) }];\n } catch { /* Unsupported previews remain in native metadata. */ }\n return [];\n });\n return { id: imageId, account_id: account, provider: 'microsoft', name: `Image ${imageId}`, type: String(value.MediaType ?? 'IMAGE'), headlines: [], descriptions: alt ? [alt] : [], landing_urls: [], media, actions: [] };\n });\n return output.parse({ images, creatives, truncated, ...(nextPage !== undefined ? { next_page_index: nextPage } : {}) });\n }\n\n async list(input: { account_id: string; page_index: number; page_size: number }) {\n const images = await this.page(input.account_id, input.page_index, input.page_size);\n const truncated = images.length === input.page_size;\n return this.gallery(input.account_id, images, truncated, truncated ? input.page_index + 1 : undefined);\n }\n\n async get(input: { account_id: string; image_id: string }) {\n return this.gallery(input.account_id, [await this.owned(input.account_id, input.image_id)], false);\n }\n\n async lookupMany(account: string, imageIds: string[]) {\n const wanted = new Set(imageIds.map(value => id.parse(value))), found: Row[] = [], seen = new Set<string>();\n for (let page = 0; wanted.size && page < 5; page++) {\n const values = await this.page(account, page, 1000);\n for (const value of values) {\n const key = nativeId(value.Id);\n if (seen.has(key)) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-library pagination did not advance');\n seen.add(key);\n if (wanted.delete(key)) found.push(value);\n }\n if (values.length < 1000) break;\n }\n return { ...this.gallery(account, found, wanted.size > 0), missing_image_ids: [...wanted] };\n }\n\n async extensionUses(input: { account_id: string; image_id: string }) {\n await this.owned(input.account_id, input.image_id);\n const result = await this.request(input.account_id, 'MediaAssociations/Query', { MediaEnabledEntities: 'ImageAdExtension', MediaIds: [input.image_id] });\n // The native response is one array of associations per requested media ID.\n if (!Array.isArray(result.MediaAssociations) || result.MediaAssociations.length !== 1 || !Array.isArray(result.MediaAssociations[0])) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-extension associations were not returned');\n const associations = rows(result.MediaAssociations[0]);\n for (const value of associations) {\n nativeId(value.EntityId);\n if (nativeId(value.MediaId) !== input.image_id || value.MediaEnabledEntity !== 'ImageAdExtension') throw new AdportError('PROVIDER_ERROR', 'microsoft: image-extension association identity mismatch');\n }\n return { image_id: input.image_id, associations, coverage: 'ImageAdExtension only; ResponsiveAd uses are not returned by this API', truncated: false };\n }\n\n async plan(op: WriteOperation): Promise<ImagePlan> {\n id.parse(op.accountId);\n const expectedKind = op.tool === 'microsoft_upload_image' ? 'create' : 'remove';\n if (op.provider !== 'microsoft' || !MICROSOFT_IMAGE_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: image operation kind mismatch');\n if (op.tool === 'microsoft_upload_image') {\n const input = upload.parse(op.payload);\n // The native Image.Data limit is 102400 base64 characters.\n const file = await this.media.read(input, { maxBytes: 76800, contentTypes: ['image/png', 'image/jpeg', 'image/gif'] });\n return { summary: `Upload Microsoft image ${file.name}`, changes: [`+ ${input.image_type}; ${file.contentType}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}`, ...(input.alt_text !== undefined ? [`Image alt text: ${JSON.stringify(input.alt_text)}`] : []), 'Creates an unattached image. Microsoft validates dimensions and rejects animation; PNG images are converted to JPEG.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'Media', { AccountId: op.accountId, Media: [{ Type: 'Image', MediaType: input.image_type, ...(input.alt_text !== undefined ? { Text: input.alt_text } : {}), Data: Buffer.from(file.bytes).toString('base64') }] });\n const created = Array.isArray(result.MediaIds) ? result.MediaIds.filter(value => value !== null).map(nativeId) : [];\n if (created.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: image upload receipt mismatch; reconcile before retrying', { resourceIds: created });\n let readback: Row;\n try { readback = await this.owned(op.accountId, created[0]!); }\n catch { throw new AdportError('PROVIDER_ERROR', `microsoft: image ${created[0]} upload was accepted but library readback failed; reconcile before retrying`, { resourceIds: created }); }\n if (input.alt_text !== undefined && readback.Text !== input.alt_text) throw new AdportError('PROVIDER_ERROR', 'microsoft: uploaded image alt text was not confirmed; reconcile before retrying', { resourceIds: created });\n return created;\n } };\n }\n const input = image.parse(op.payload), current = await this.owned(op.accountId, input.image_id);\n const uses = await this.extensionUses({ account_id: op.accountId, image_id: input.image_id });\n if (uses.associations.length) throw new AdportError('INVALID_INPUT', 'microsoft: image is assigned to an image extension; remove the reference before deletion');\n return { summary: `Delete Microsoft image ${input.image_id}`, changes: [`- ${input.image_id}; type ${String(current.MediaType)}; alt text ${JSON.stringify(current.Text ?? null)}`, 'Permanent deletion. Microsoft atomically rejects images assigned to any image extension or responsive ad. The preflight association API covers image extensions only.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'Media', { AccountId: op.accountId, MediaIds: [input.image_id] }, 'DELETE');\n if (await this.find(op.accountId, input.image_id)) throw new AdportError('PROVIDER_ERROR', 'microsoft: image deletion was not confirmed; reconcile before retrying', { resourceIds: [input.image_id] });\n return [input.image_id];\n } };\n }\n}\n\nexport function microsoftImageTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_images', namespace: 'microsoft', description: 'View account-library image metadata, alt text and native image previews. Native page indexes start at zero; a full page may have a continuation.', input: z.object({ account_id: id, page_index: z.number().int().nonnegative().max(100000).default(0), page_size: z.number().int().positive().max(1000).default(20) }), output, presentation: 'creatives', pagination: { cursorInput: 'page_index', cursorOutput: 'next_page_index' }, annotations: { readOnly: true }, handler: input => provider.images.list(input) }),\n defineTool({ name: 'microsoft_get_library_image', namespace: 'microsoft', description: 'Read one image through the selected account library finder, including native alt text and previews. Ownership lookup is bounded to 5000 images.', input: z.object({ account_id: id, image_id: id }), output, presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.images.get(input) }),\n defineTool({ name: 'microsoft_image_extension_associations', namespace: 'microsoft', description: 'Read image-extension references for an account-owned image. This API does not return responsive-ad references; an empty result does not prove global non-use.', input: z.object({ account_id: id, image_id: id }), output: z.object({ image_id: id, associations: z.array(z.record(z.string(), z.unknown())), coverage: z.string(), truncated: z.boolean() }), annotations: { readOnly: true }, handler: input => provider.images.extensionUses(input) }),\n guardedWriteTool({ name: 'microsoft_upload_image', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Upload a SHA-256-bound static image as an unattached account asset. Hosted calls require project media_id. Native cap 76800 bytes; PNG converts to JPEG. Alt text is set at creation; no serving association is created.', payload: upload }),\n guardedWriteTool({ name: 'microsoft_delete_image', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Permanently delete an account-owned image only if Microsoft verifies it is unassigned. Preflight checks image-extension uses; native deletion also rejects responsive-ad assignments.', payload: image }),\n ];\n}\n","import { AdportError, creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition, type Creative, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { type MicrosoftAdsClient, type RequestScope } from './client.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst extensionType = z.enum(['CalloutAdExtension', 'SitelinkAdExtension', 'StructuredSnippetAdExtension', 'ImageAdExtension']);\nconst url = z.string().url().max(2048).refine(value => { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password; });\nconst urls = z.array(url).min(1).max(10);\nconst sitelink = { display_text: z.string().min(1).max(35), final_urls: urls, description1: z.string().max(35).optional(), description2: z.string().max(35).optional() };\nconst image = { alternative_text: z.string().min(1).max(35), image_ids: z.array(id).min(1).max(4), description: z.string().max(100).optional(), final_urls: urls.optional() };\nconst content = z.discriminatedUnion('extension_type', [\n z.object({ extension_type: z.literal('CalloutAdExtension'), text: z.string().min(1).max(25) }),\n z.object({ extension_type: z.literal('SitelinkAdExtension'), ...sitelink }),\n z.object({ extension_type: z.literal('StructuredSnippetAdExtension'), header: z.string().min(1).max(100), values: z.array(z.string().min(1).max(25)).min(3).max(10) }),\n z.object({ extension_type: z.literal('ImageAdExtension'), ...image }),\n]);\nconst fields: Record<string, string> = { text: 'Text', display_text: 'DisplayText', final_urls: 'FinalUrls', description1: 'Description1', description2: 'Description2', header: 'Header', values: 'Values', alternative_text: 'AlternativeText', image_ids: 'ImageMediaIds', description: 'Description' };\nconst labels: Record<string, string> = { Text: 'Callout text', DisplayText: 'Link text', FinalUrls: 'Landing pages', Description1: 'Description 1', Description2: 'Description 2', Header: 'Localized header', Values: 'Snippet values', AlternativeText: 'Alternative text', ImageMediaIds: 'Source images', Description: 'Internal description' };\nconst reviewValue = (value: unknown): string => value === null || value === undefined ? '—' : typeof value === 'string' ? value : JSON.stringify(value);\nconst reference = z.object({ extension_id: id, extension_type: extensionType });\nconst versioned = reference.extend({ expected_version: z.number().int().positive() });\nconst update = versioned.extend({\n text: z.string().min(1).max(25).optional(), ...z.object(sitelink).partial().shape,\n header: z.string().min(1).max(100).optional(), values: z.array(z.string().min(1).max(25)).min(3).max(10).optional(), ...z.object(image).partial().shape,\n}).superRefine((value, ctx) => {\n const allowed: Record<string, string[]> = { CalloutAdExtension: ['text'], SitelinkAdExtension: Object.keys(sitelink), StructuredSnippetAdExtension: ['header', 'values'], ImageAdExtension: Object.keys(image) };\n const supplied = Object.keys(fields).filter(key => value[key as keyof typeof value] !== undefined);\n if (!supplied.length || supplied.some(key => !allowed[value.extension_type]!.includes(key))) ctx.addIssue({ code: 'custom', message: 'Supply content changes supported by this extension type' });\n});\nconst target = z.discriminatedUnion('type', [z.object({ type: z.literal('Account') }), z.object({ type: z.literal('Campaign'), campaign_id: id }), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id })]);\ntype Target = z.infer<typeof target>;\nconst mutable: Record<z.infer<typeof extensionType>, string[]> = {\n CalloutAdExtension: ['Text', 'Scheduling'],\n SitelinkAdExtension: ['DisplayText', 'Description1', 'Description2', 'DestinationUrl', 'DevicePreference', 'Scheduling', 'FinalUrls', 'FinalMobileUrls', 'FinalUrlSuffix', 'TrackingUrlTemplate', 'UrlCustomParameters'],\n StructuredSnippetAdExtension: ['Header', 'Values', 'Scheduling'],\n ImageAdExtension: ['AlternativeText', 'Description', 'DestinationUrl', 'DisplayText', 'FinalUrls', 'FinalMobileUrls', 'FinalUrlSuffix', 'TrackingUrlTemplate', 'UrlCustomParameters', 'ImageMediaIds', 'Images', 'Layouts', 'Scheduling'],\n};\nconst allowedReadOnly = ['Id', 'Version', 'Type', 'Status', 'ForwardCompatibilityMap', 'FinalAppUrls', 'SourceType', 'DevicePreference'];\nconst extensionOutput = creativesOutput.extend({ extensions: z.array(z.record(z.string(), z.unknown())) });\nexport const MICROSOFT_EXTENSION_WRITES = new Set(['microsoft_create_ad_extension', 'microsoft_update_ad_extension', 'microsoft_delete_ad_extension', 'microsoft_link_ad_extension', 'microsoft_unlink_ad_extension']);\n\n/** REST contracts pinned at MicrosoftDocs/Advertising@fdee2fcf; flags use native REST CSV. */\nexport class MicrosoftExtensionService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string) => Promise<RequestScope>, campaign: (account: string, campaign: string) => Promise<unknown>, private readonly imageLookup: (account: string, ids: string[]) => Promise<{ creatives: Creative[]; missing_image_ids: string[] }>) { super(client, scope, campaign); }\n\n async getRaw(account: string, extensionId: string, type: z.infer<typeof extensionType>): Promise<Row> {\n const result = await this.request(account, 'AdExtensions/QueryByIds', { AccountId: account, AdExtensionIds: [extensionId], AdExtensionType: type });\n const values = rows(result.AdExtensions);\n if (values.length !== 1 || nativeId(values[0]!.Id) !== extensionId || values[0]!.Type !== type) throw new AdportError('INVALID_INPUT', 'microsoft: extension was not found with this type in the selected account');\n if (!Number.isSafeInteger(values[0]!.Version) || Number(values[0]!.Version) < 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension version was not returned');\n return values[0]!;\n }\n\n private card(account: string, value: Row): Creative {\n if (!Number.isSafeInteger(value.Version) || Number(value.Version) < 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension version was not returned');\n const type = extensionType.parse(value.Type), extensionId = nativeId(value.Id), args = { account_id: account, extension_id: extensionId, extension_type: type, expected_version: value.Version };\n const text = (key: string) => typeof value[key] === 'string' ? String(value[key]) : '';\n const edit: Creative['actions'][number] = { label: 'Edit shared extension', tool: 'microsoft_update_ad_extension', arguments: args, fields: [] };\n if (type === 'CalloutAdExtension') edit.fields = [{ key: 'text', label: 'Callout text', type: 'text', value: text('Text'), max_length: 25 }];\n if (type === 'SitelinkAdExtension') edit.fields = [{ key: 'display_text', label: 'Link text', type: 'text', value: text('DisplayText'), max_length: 35 }, { key: 'description1', label: 'Description 1', type: 'text', value: text('Description1'), max_length: 35 }, { key: 'description2', label: 'Description 2', type: 'text', value: text('Description2'), max_length: 35 }, { key: 'final_urls', label: 'Landing pages (one per line)', type: 'url_list', value: Array.isArray(value.FinalUrls) ? value.FinalUrls.map(String) : [] }];\n if (type === 'StructuredSnippetAdExtension') edit.fields = [{ key: 'header', label: 'Localized header', type: 'text', value: text('Header') }, { key: 'values', label: 'Values (one per line)', type: 'text_list', value: Array.isArray(value.Values) ? value.Values.map(String) : [] }];\n if (type === 'ImageAdExtension') edit.fields = [{ key: 'alternative_text', label: 'Extension alternative text', type: 'text', value: text('AlternativeText'), max_length: 35 }, { key: 'description', label: 'Internal description', type: 'text', value: text('Description'), max_length: 100 }, { key: 'image_ids', label: 'Account image IDs (one per line)', type: 'text_list', value: this.imageIds(value) }];\n return { id: extensionId, provider: 'microsoft', account_id: account, type, name: text('Text') || text('DisplayText') || text('Header') || text('Description') || `Extension ${extensionId}`, status: typeof value.Status === 'string' ? value.Status : undefined, headlines: [text('Text') || text('DisplayText') || text('Header')].filter(Boolean), descriptions: [text('Description1'), text('Description2'), text('AlternativeText'), ...(Array.isArray(value.Values) ? value.Values.map(String) : [])].filter(Boolean), landing_urls: Array.isArray(value.FinalUrls) ? value.FinalUrls.filter(item => url.safeParse(item).success) as string[] : [], media: [], actions: [edit] };\n }\n\n private imageIds(value: Row): string[] {\n const ids = Array.isArray(value.ImageMediaIds) && value.ImageMediaIds.length ? value.ImageMediaIds.map(nativeId) : rows(value.Images).map(link => nativeId(row(link.Asset).Id));\n return [...new Set(ids)];\n }\n\n private async gallery(account: string, values: Row[], truncated: boolean, next?: string) {\n const creatives = values.map(value => this.card(account, value));\n const imageIds = [...new Set(values.filter(value => value.Type === 'ImageAdExtension').flatMap(value => this.imageIds(value)))];\n if (imageIds.length) {\n const previews = await this.imageLookup(account, imageIds), media = new Map(previews.creatives.map(value => [value.id, value.media]));\n for (const [index, value] of values.entries()) if (value.Type === 'ImageAdExtension') creatives[index]!.media = this.imageIds(value).flatMap(image => media.get(image) ?? []).map(preview => ({ ...preview, ...(typeof value.AlternativeText === 'string' ? { alt: value.AlternativeText } : {}) }));\n }\n return extensionOutput.parse({ extensions: values, creatives, truncated, ...(next ? { next_cursor: next } : {}) });\n }\n\n async get(input: { account_id: string; extension_id: string; extension_type: z.infer<typeof extensionType> }) {\n const value = await this.getRaw(input.account_id, input.extension_id, input.extension_type);\n return this.gallery(input.account_id, [value], false);\n }\n\n async list(input: { account_id: string; extension_types: Array<z.infer<typeof extensionType>>; after_extension_id?: string; limit: number }) {\n const result = await this.request(input.account_id, 'AdExtensionIds/QueryByAccountId', { AccountId: input.account_id, AdExtensionType: input.extension_types.join(', '), AssociationType: null });\n if (!Array.isArray(result.AdExtensionIds)) throw new AdportError('PROVIDER_ERROR', 'microsoft: account extension IDs were not returned');\n const ids = result.AdExtensionIds.map(nativeId).sort((a, b) => BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0);\n if (new Set(ids).size !== ids.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate native extension IDs');\n const remaining = ids.filter(value => !input.after_extension_id || BigInt(value) > BigInt(input.after_extension_id)), selected = remaining.slice(0, input.limit);\n let values: Row[] = [];\n if (selected.length) {\n const detail = await this.request(input.account_id, 'AdExtensions/QueryByIds', { AccountId: input.account_id, AdExtensionIds: selected, AdExtensionType: input.extension_types.join(', ') });\n values = rows(detail.AdExtensions);\n if (values.length !== selected.length || values.some((value, index) => nativeId(value.Id) !== selected[index] || !input.extension_types.includes(extensionType.parse(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension page identity mismatch');\n }\n const truncated = remaining.length > selected.length;\n return this.gallery(input.account_id, values, truncated, truncated ? selected.at(-1) : undefined);\n }\n\n private async entity(account: string, value: Target) {\n if (value.type === 'Account') return { entityId: account, paused: false };\n const campaign = await this.campaign(account, value.campaign_id);\n if (value.type === 'Campaign') return { entityId: value.campaign_id, paused: campaign.Status === 'Paused' };\n const result = await this.request(account, 'AdGroups/QueryByIds', { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id] });\n const groups = rows(result.AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== value.ad_group_id) throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n return { entityId: value.ad_group_id, paused: campaign.Status === 'Paused' || groups[0]!.Status === 'Paused' };\n }\n\n async associations(input: { account_id: string; target: Target; extension_type: z.infer<typeof extensionType> }) {\n const entity = await this.entity(input.account_id, input.target);\n const result = await this.request(input.account_id, 'AdExtensionsAssociations/Query', { AccountId: input.account_id, AdExtensionType: input.extension_type, AssociationType: input.target.type, EntityIds: [entity.entityId] });\n const collections = rows(result.AdExtensionAssociationCollection);\n if (collections.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension associations were not returned');\n const associations = rows(collections[0]!.AdExtensionAssociations);\n for (const value of associations) if (nativeId(value.EntityId) !== entity.entityId || value.AssociationType !== input.target.type || row(value.AdExtension).Type !== input.extension_type) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension association identity mismatch');\n return { associations, truncated: false };\n }\n\n private nativeContent(value: Record<string, unknown>) {\n const result: Row = { Type: value.extension_type };\n for (const [key, native] of Object.entries(fields)) if (value[key] !== undefined) result[native] = value[key];\n if (result.Type === 'SitelinkAdExtension') {\n const first = String(result.Description1 ?? ''), second = String(result.Description2 ?? '');\n if (Boolean(first) !== Boolean(second) || ((first || second) && String(result.DisplayText).length > 25)) throw new AdportError('INVALID_INPUT', 'microsoft: sitelink descriptions must be supplied together; links with descriptions have a 25-character text limit');\n }\n return result;\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_create_ad_extension' || op.tool === 'microsoft_link_ad_extension' ? 'create' : op.tool === 'microsoft_delete_ad_extension' || op.tool === 'microsoft_unlink_ad_extension' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_EXTENSION_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: extension operation kind mismatch');\n if (op.tool === 'microsoft_create_ad_extension') {\n const input = content.parse(op.payload.content), value = this.nativeContent(input);\n await this.verifyImages(op.accountId, value);\n return { summary: `Create unattached Microsoft ${input.extension_type}`, changes: [`+ ${JSON.stringify(value)}`, 'Extension status is natively Active; it cannot serve until associated. No association is created.', ...(input.extension_type === 'ImageAdExtension' ? ['Microsoft validates placement crop dimensions: an accepted library image can still be too small for an extension. This preview is not server-validated.'] : [])], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'AdExtensions', { AccountId: op.accountId, AdExtensions: [value] });\n const identities = rows(result.AdExtensionIdentities), created = identities.map(value => nativeId(value.Id));\n if (created.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension creation receipt mismatch; reconcile before retrying', { resourceIds: created });\n await this.confirm(op.accountId, created[0]!, input.extension_type, value);\n return created;\n } };\n }\n const input = versioned.parse(op.payload), current = await this.getRaw(op.accountId, input.extension_id, input.extension_type);\n if (current.Version !== input.expected_version) throw new AdportError('PENDING_MISMATCH', 'microsoft: extension version changed; read it and request a fresh preview');\n if (op.tool === 'microsoft_update_ad_extension') {\n const change = update.parse(op.payload), supplied = this.nativeContent(change);\n if (Object.keys(supplied).length === 1) throw new AdportError('INVALID_INPUT', 'microsoft: supply at least one extension content change');\n const supported = mutable[input.extension_type];\n if (Object.keys(current).some(key => current[key] !== null && !supported.includes(key) && !allowedReadOnly.includes(key))) throw new AdportError('INVALID_INPUT', 'microsoft: extension contains unsupported fields; a safe full replacement cannot be built');\n const value: Row = { Type: input.extension_type, Id: input.extension_id, ...Object.fromEntries(supported.filter(key => current[key] !== undefined).map(key => [key, current[key]])), ...supplied };\n // Replacing ImageMediaIds must not retain the old Images array, which can override it.\n if (supplied.ImageMediaIds && JSON.stringify((supplied.ImageMediaIds as string[]).slice().sort()) !== JSON.stringify(this.imageIds(current).sort())) delete value.Images;\n if (Array.isArray(value.Images)) value.Images = value.Images.map(link => {\n const current = row(link), asset = row(current.Asset);\n const allowed = ['Id', 'Type', 'Name', 'CropHeight', 'CropWidth', 'CropX', 'CropY', 'CroppingType', 'SubType', 'TargetHeight', 'TargetWidth'];\n if (Object.keys(asset).some(key => asset[key] != null && !allowed.includes(key) && key !== 'Excluded')) throw new AdportError('INVALID_INPUT', 'microsoft: unsupported image crop fields prevent a safe extension update');\n return { Asset: Object.fromEntries(allowed.filter(key => asset[key] !== undefined).map(key => [key, asset[key]])), ...(current.PinnedField != null ? { PinnedField: current.PinnedField } : {}) };\n });\n await this.verifyImages(op.accountId, value);\n if (input.extension_type === 'SitelinkAdExtension') this.nativeContent({ extension_type: input.extension_type, display_text: value.DisplayText, description1: value.Description1, description2: value.Description2 });\n const impact = 'Every entity using this extension can change, including active ads. Existing scheduling, device preference and tracking fields are preserved. Native extension Version is read-only.';\n const fieldChanges = Object.keys(supplied).filter(key => key !== 'Type').flatMap(key => {\n const before = key === 'ImageMediaIds' ? this.imageIds(current) : current[key], after = supplied[key];\n return JSON.stringify(before ?? null) === JSON.stringify(after ?? null) ? [] : [{ field: labels[key] ?? key, before: reviewValue(before), after: reviewValue(after) }];\n });\n return { summary: `Update shared Microsoft extension ${input.extension_id}`, changes: [`~ ${JSON.stringify(current)} → ${JSON.stringify(value)}`, impact], fieldChanges, notes: [impact], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'AdExtensions', { AccountId: op.accountId, AdExtensions: [value] }, 'PUT');\n await this.confirm(op.accountId, input.extension_id, input.extension_type, value, input.expected_version);\n return [input.extension_id];\n } };\n }\n if (op.tool === 'microsoft_delete_ad_extension') return { summary: `Delete shared Microsoft extension ${input.extension_id}`, changes: [`- ${JSON.stringify(current)}`, 'Permanent deletion removes this shared extension and affects every associated entity. Uploaded source images remain in the media library.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'AdExtensions', { AccountId: op.accountId, AdExtensionIds: [input.extension_id] }, 'DELETE');\n const result = await this.request(op.accountId, 'AdExtensionIds/QueryByAccountId', { AccountId: op.accountId, AdExtensionType: input.extension_type, AssociationType: null });\n if (!Array.isArray(result.AdExtensionIds) || result.AdExtensionIds.map(nativeId).includes(input.extension_id)) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension deletion was not confirmed; reconcile before retrying', { resourceIds: [input.extension_id] });\n return [input.extension_id];\n } };\n const value = target.parse((op.payload as Row).target), entity = await this.entity(op.accountId, value), linking = op.tool === 'microsoft_link_ad_extension';\n if (linking && guard.forcePausedCreation && !entity.paused) throw new AdportError('POLICY_VIOLATION', 'microsoft: extension associations cannot be paused; paused_creation requires a paused campaign or ad group target');\n return { summary: `${linking ? 'Associate' : 'Remove'} Microsoft extension ${input.extension_id} ${linking ? 'with' : 'from'} ${value.type} ${entity.entityId}`, changes: [`${linking ? '+' : '-'} explicit association; extension ${input.extension_id}; ${value.type} ${entity.entityId}`, 'Associations have no pause state. No campaign/ad group status is changed; other associations are preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, linking ? 'AdExtensionsAssociations/Set' : 'AdExtensionsAssociations', { AccountId: op.accountId, AdExtensionIdToEntityIdAssociations: [{ AdExtensionId: input.extension_id, EntityId: entity.entityId }], AssociationType: value.type }, linking ? 'POST' : 'DELETE');\n const readback = await this.associations({ account_id: op.accountId, target: value, extension_type: input.extension_type });\n const exists = readback.associations.some(value => nativeId(row(value.AdExtension).Id) === input.extension_id);\n if (exists !== linking) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension association change was not confirmed; reconcile before retrying', { resourceIds: [input.extension_id] });\n return [input.extension_id];\n } };\n }\n\n private async confirm(account: string, extension: string, type: z.infer<typeof extensionType>, expected: Row, previousVersion?: number) {\n try {\n const actual = await this.getRaw(account, extension, type);\n if (previousVersion !== undefined && Number(actual.Version) <= previousVersion) throw new Error('Version did not advance');\n for (const key of Object.keys(expected).filter(key => !['Id', 'Type', 'ImageMediaIds', 'Images'].includes(key))) {\n if (JSON.stringify(actual[key] ?? null) !== JSON.stringify(expected[key] ?? null)) throw new Error(`Readback mismatch: ${key}`);\n }\n if (type === 'ImageAdExtension' && JSON.stringify(this.imageIds(actual).sort()) !== JSON.stringify(this.imageIds(expected).sort())) throw new Error('Image references were not confirmed');\n } catch { throw new AdportError('PROVIDER_ERROR', `microsoft: extension ${extension} mutation was accepted but content readback was not confirmed; reconcile before retrying`, { resourceIds: [extension] }); }\n }\n\n private async verifyImages(account: string, value: Row) {\n if (value.Type !== 'ImageAdExtension') return;\n const ids = this.imageIds(value);\n if (!ids.length || (await this.imageLookup(account, ids)).missing_image_ids.length) throw new AdportError('INVALID_INPUT', 'microsoft: image references could not be verified in the selected account library');\n }\n}\n\nexport function microsoftExtensionTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_ad_extensions', namespace: 'microsoft', description: 'View account-owned callout, sitelink, structured-snippet and image extensions, including native versions and shared-content edit actions. Continue with next_cursor as after_extension_id.', input: z.object({ account_id: id, extension_types: z.array(extensionType).min(1).max(4).default([...extensionType.options]), after_extension_id: id.optional(), limit: z.number().int().positive().max(100).default(20) }), output: extensionOutput, presentation: 'creatives', pagination: { cursorInput: 'after_extension_id' }, annotations: { readOnly: true }, handler: input => provider.extensions.list(input) }),\n defineTool({ name: 'microsoft_get_ad_extension', namespace: 'microsoft', description: 'Read one extension by exact ID and type in the selected account, including the native version required for edits.', input: reference.extend({ account_id: id }), output: extensionOutput, presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.extensions.get(input) }),\n defineTool({ name: 'microsoft_ad_extension_associations', namespace: 'microsoft', description: 'Read direct extension associations for an account, campaign or verified ad group. Native editorial status is preserved; inherited associations are not combined.', input: z.object({ account_id: id, target, extension_type: extensionType }), output: z.object({ associations: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() }), annotations: { readOnly: true }, handler: input => provider.extensions.associations(input) }),\n guardedWriteTool({ name: 'microsoft_create_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create an unattached callout, sitelink, structured-snippet or image extension. Native status is Active but no serving association is created. Uses full native content readback.', payload: z.object({ content }) }),\n guardedWriteTool({ name: 'microsoft_update_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit supplied shared extension content with expected_version. Preserves omitted mutable fields and scheduling; all associated entities can change. Image alt text here belongs to the extension, not the source media.', payload: update }),\n guardedWriteTool({ name: 'microsoft_delete_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Permanently delete an account-owned shared extension and its associations. Requires its latest native version. Source images remain in the account library.', payload: versioned }),\n guardedWriteTool({ name: 'microsoft_link_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Associate a version-verified extension with one owned entity. Associations cannot be paused; default paused_creation requires a paused parent campaign or ad group. Account-wide associations are blocked under that policy.', payload: versioned.extend({ target }) }),\n guardedWriteTool({ name: 'microsoft_unlink_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove one explicit extension association, preserving its source extension and other associations. Does not alter inherited associations or serving statuses.', payload: versioned.extend({ target }) }),\n ];\n}\n","import { AdportError, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, type MicrosoftService, type RequestScope } from './client.js';\n\nexport type MicrosoftRow = Record<string, unknown>;\nexport type MicrosoftPlan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]>; resultDetails?: () => unknown; resultWarnings?: () => string[] };\nexport const microsoftId = z.string().regex(/^[1-9]\\d*$/);\nexport const microsoftRows = (value: unknown): MicrosoftRow[] => z.array(z.record(z.string(), z.unknown())).parse(value ?? []);\nexport const microsoftRow = (value: unknown): MicrosoftRow => z.record(z.string(), z.unknown()).parse(value);\nexport function microsoftNativeId(value: unknown): string {\n if (typeof value === 'number' && (!Number.isSafeInteger(value) || value <= 0)) throw new AdportError('PROVIDER_ERROR', 'microsoft: unsafe native resource ID');\n const parsed = microsoftId.safeParse(typeof value === 'number' ? String(value) : value);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid native resource ID');\n return parsed.data;\n}\n\nfunction compactErrors(errors: unknown[]): MicrosoftRow[] {\n const grouped = new Map<string, MicrosoftRow>();\n for (const value of errors) {\n const error = microsoftRow(value), { PublisherCountry, ...base } = error;\n if (typeof PublisherCountry !== 'string') { grouped.set(`item:${grouped.size}`, error); continue; }\n const key = JSON.stringify(base), previous = grouped.get(key);\n if (previous) previous.PublisherCountries = [...new Set([...(previous.PublisherCountries as string[]), PublisherCountry])];\n else grouped.set(key, { ...base, PublisherCountries: [PublisherCountry] });\n }\n return [...grouped.values()];\n}\n\n/** Shared scoped REST access. NestedPartialErrors are not interchangeable with PartialErrors. */\nexport class MicrosoftNativeService {\n constructor(protected readonly client: MicrosoftAdsClient, private readonly scope: (account: string, refresh?: boolean) => Promise<RequestScope>, private readonly lookupCampaign: (account: string, campaign: string) => Promise<unknown>) {}\n\n protected async accountScope(account: string, refresh = false): Promise<RequestScope> {\n microsoftId.parse(account);\n const scope = await this.scope(account, refresh);\n if (!scope.customerId || scope.customerAccountId !== account) throw new AdportError('INVALID_INPUT', 'microsoft: selected account ownership could not be verified');\n return scope;\n }\n\n protected async request(account: string, path: string, body: MicrosoftRow, method: 'POST' | 'PUT' | 'DELETE' = 'POST', service: MicrosoftService = 'campaign'): Promise<MicrosoftRow> {\n const scope = await this.accountScope(account);\n const result = await this.client.request<MicrosoftRow>(service, method, path, body, scope);\n const errors = ['PartialErrors', 'NestedPartialErrors'].flatMap(key => {\n if (result[key] === undefined || result[key] === null) return [];\n if (!Array.isArray(result[key])) throw new AdportError('PROVIDER_ERROR', 'microsoft: malformed native error receipt');\n return result[key].filter(value => value !== null);\n });\n if (errors.length) {\n const negativeIds = Array.isArray(result.NegativeKeywordIds) ? result.NegativeKeywordIds.flatMap(group => group && typeof group === 'object' && Array.isArray(microsoftRow(group).Ids) ? [microsoftRow(group).Ids] : []) : [];\n const ids = [result.CampaignCriterionIds, result.AdGroupCriterionIds, result.AdExtensionIdentities, result.BudgetIds, result.ConversionGoalIds, result.UetTags, result.AudienceIds, result.ExperimentIds, ...negativeIds].flatMap(value => Array.isArray(value) ? value.flatMap(item => {\n const id = item && typeof item === 'object' ? microsoftRow(item).Id : item;\n return id === null || id === undefined ? [] : [microsoftNativeId(id)];\n }) : []);\n const compact = compactErrors(errors), summary = [...new Set(compact.map(value => `${value.Code ?? '?'} ${value.ErrorCode ?? ''}: ${value.Message ?? 'nested native error'}`))].slice(0, 5).join('; ');\n throw new AdportError('PROVIDER_ERROR', `microsoft: ${path} returned partial errors (${summary}); reconcile successful resource IDs before retrying`, { resourceIds: ids, errors: compact, nativeErrorCount: errors.length });\n }\n return result;\n }\n\n protected async campaign(account: string, campaign: string): Promise<MicrosoftRow> {\n microsoftId.parse(account);\n microsoftId.parse(campaign);\n const result = microsoftRow(await this.lookupCampaign(account, campaign));\n if (microsoftNativeId(result.Id) !== campaign) throw new AdportError('INVALID_INPUT', 'microsoft: campaign ownership mismatch');\n return result;\n }\n}\n","import { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nimport { criterionType, target, add, reference, remove, bid, intentUpdate, nativeTarget } from './targeting-schemas.js';\n\nexport const MICROSOFT_TARGETING_WRITES = new Set(['microsoft_add_campaign_targets', 'microsoft_set_campaign_target_bid', 'microsoft_set_campaign_location_intent', 'microsoft_remove_campaign_targets']);\n\n/** Native REST uses concrete read selectors, Targets mutation selector and percentage bid adjustments. */\nexport class MicrosoftTargetingService extends MicrosoftNativeService {\n private subtype(value: Row) { return criterionType.parse(String(row(value.Criterion).Type).replace(/Criterion$/, '')); }\n\n private key(type: z.infer<typeof criterionType>, criterion: Row) {\n const keys: Record<z.infer<typeof criterionType>, string[]> = { Age: ['AgeRange'], Gender: ['GenderType'], Device: ['DeviceName'], DayTime: ['Day', 'FromHour', 'FromMinute', 'ToHour', 'ToMinute'], Location: ['LocationId'], LocationIntent: [], Radius: ['LatitudeDegrees', 'LongitudeDegrees', 'Radius', 'RadiusUnit'] };\n return JSON.stringify(keys[type].map(key => String(criterion[key] ?? '')));\n }\n\n private async confirm(criterion: string | string[], change: string, check: () => Promise<boolean>) {\n try { if (await check()) return; } catch { /* An accepted mutation is not retried when readback is unavailable. */ }\n throw new AdportError('PROVIDER_ERROR', `microsoft: ${change} was not confirmed; reconcile before retrying`, { resourceIds: Array.isArray(criterion) ? criterion : [criterion] });\n }\n\n private async query(account: string, campaign: string, type: z.infer<typeof criterionType>) {\n const result = await this.request(account, 'CampaignCriterions/QueryByIds', { CampaignId: campaign, CampaignCriterionIds: null, CriterionType: type });\n if (!Object.hasOwn(result, 'CampaignCriterions')) throw new AdportError('PROVIDER_ERROR', 'microsoft: campaign targeting was not returned');\n const values = rows(result.CampaignCriterions);\n if (values.some(value => nativeId(value.CampaignId) !== campaign || this.subtype(value) !== type || !['BiddableCampaignCriterion', 'NegativeCampaignCriterion'].includes(String(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: campaign target identity mismatch');\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate campaign criterion IDs');\n return values;\n }\n\n async list(input: { account_id: string; campaign_id: string; criterion_type: z.infer<typeof criterionType> }) {\n await this.campaign(input.account_id, input.campaign_id);\n return { rows: await this.query(input.account_id, input.campaign_id, input.criterion_type), truncated: false };\n }\n\n private async owned(account: string, input: z.infer<typeof reference>) {\n await this.campaign(account, input.campaign_id);\n const result = (await this.query(account, input.campaign_id, input.criterion_type)).find(value => nativeId(value.Id) === input.criterion_id);\n if (!result) throw new AdportError('INVALID_INPUT', 'microsoft: target was not found with this type in the selected campaign/account');\n return result;\n }\n\n async geoFile(input: { account_id: string; language_locale: string }) {\n const result = await this.request(input.account_id, 'GeoLocationsFileUrl/Query', { Version: '2.0', LanguageLocale: input.language_locale });\n return z.object({ FileUrl: z.string().url(), FileUrlExpiryTimeUtc: z.string(), LastModifiedTimeUtc: z.string() }).parse(result);\n }\n\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_add_campaign_targets' ? 'create' : op.tool === 'microsoft_remove_campaign_targets' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_TARGETING_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: targeting operation kind mismatch');\n if (op.tool === 'microsoft_add_campaign_targets') {\n const input = add.parse(op.payload), campaign = await this.campaign(op.accountId, input.campaign_id), values = input.targets.map(value => nativeTarget({ CampaignId: input.campaign_id }, value));\n if (guard.forcePausedCreation && campaign.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: campaign targets are natively Active and cannot be paused; paused_creation requires a paused campaign');\n const seen = new Map<string, Set<string>>();\n for (const [index, value] of values.entries()) {\n const type = input.targets[index]!.type;\n if (!seen.has(type)) seen.set(type, new Set((await this.query(op.accountId, input.campaign_id, type)).map(value => this.key(type, row(value.Criterion)))));\n const key = this.key(type, row(value.Criterion));\n if (seen.get(type)!.has(key)) throw new AdportError('INVALID_INPUT', 'microsoft: this campaign target already exists; use its explicit bid/intent edit or remove it first');\n seen.get(type)!.add(key);\n }\n return { summary: `Add ${values.length} Microsoft campaign target(s)`, changes: [`+ ${JSON.stringify(values)}`, `Campaign ${input.campaign_id} remains ${campaign.Status}. Targets have native Active status; no parent status changes. Bid adjustments are whole percentages, not multipliers.`, 'Location IDs must be current in the geographical file; Microsoft rejects deprecated targets. Schedule timezone follows the native AdScheduleUseSearcherTimeZone flag: searcher or account time. The deprecated campaign TimeZone is not authoritative.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'CampaignCriterions', { CampaignCriterions: values, CriterionType: 'Targets' });\n const created = Array.isArray(result.CampaignCriterionIds) ? result.CampaignCriterionIds.filter(value => value !== null).map(nativeId) : [];\n if (created.length !== values.length || new Set(created).size !== created.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: target creation receipt mismatch; reconcile before retrying', { resourceIds: created });\n try {\n const byType = new Map<string, Row[]>();\n for (const [index, expected] of values.entries()) {\n const type = input.targets[index]!.type;\n if (!byType.has(type)) byType.set(type, await this.query(op.accountId, input.campaign_id, type));\n const actual = byType.get(type)!.find(value => nativeId(value.Id) === created[index]);\n if (!actual || actual.Type !== expected.Type) throw new Error('Created target missing');\n const actualCriterion = row(actual.Criterion);\n for (const [key, value] of Object.entries(row(expected.Criterion))) if (key !== 'Type' && (key === 'LocationId' ? nativeId(actualCriterion[key]) !== value : actualCriterion[key] !== value)) throw new Error('Created target content mismatch');\n if (expected.CriterionBid && row(actual.CriterionBid).Multiplier !== row(expected.CriterionBid).Multiplier) throw new Error('Created target bid mismatch');\n }\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: targets were accepted but native readback was not confirmed; reconcile before retrying', { resourceIds: created }); }\n return created;\n } };\n }\n if (op.tool === 'microsoft_set_campaign_target_bid') {\n const input = bid.parse(op.payload), current = await this.owned(op.accountId, input);\n if (current.Type !== 'BiddableCampaignCriterion' || row(current.CriterionBid).Type !== 'BidMultiplier') throw new AdportError('INVALID_INPUT', 'microsoft: only biddable campaign targets with BidMultiplier support this edit');\n if (row(current.CriterionBid).Multiplier !== input.expected_current_percent) throw new AdportError('PENDING_MISMATCH', 'microsoft: target bid changed; request a fresh preview');\n const value = { CampaignId: input.campaign_id, Id: input.criterion_id, Type: 'BiddableCampaignCriterion', CriterionBid: { Type: 'BidMultiplier', Multiplier: input.bid_adjustment_percent } };\n return { summary: `Set Microsoft ${input.criterion_type} target bid adjustment`, changes: [`~ ${input.criterion_id}: ${input.expected_current_percent}% → ${input.bid_adjustment_percent}%`, 'Changes the percentage adjustment, preserving the criterion and campaign serving status. Automated bidding may use this as a signal rather than a direct override.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'CampaignCriterions', { CampaignCriterions: [value], CriterionType: 'Targets' }, 'PUT');\n await this.confirm(input.criterion_id, 'target bid update', async () => row((await this.owned(op.accountId, input)).CriterionBid).Multiplier === input.bid_adjustment_percent);\n return [input.criterion_id];\n } };\n }\n if (op.tool === 'microsoft_set_campaign_location_intent') {\n const input = intentUpdate.parse(op.payload), reference = { ...input, criterion_type: 'LocationIntent' as const }, current = await this.owned(op.accountId, reference);\n if (current.Type !== 'BiddableCampaignCriterion' || row(current.Criterion).IntentOption !== input.expected_current_intent) throw new AdportError('PENDING_MISMATCH', 'microsoft: location intent changed; request a fresh preview');\n const value = { CampaignId: input.campaign_id, Id: input.criterion_id, Type: 'BiddableCampaignCriterion', Criterion: { Type: 'LocationIntentCriterion', IntentOption: input.intent_option } };\n return { summary: 'Update Microsoft campaign location intent', changes: [`~ ${input.criterion_id}: ${input.expected_current_intent} → ${input.intent_option}`, 'No bid is sent: Microsoft ignores bid multipliers for location intent. Campaign status is preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'CampaignCriterions', { CampaignCriterions: [value], CriterionType: 'Targets' }, 'PUT');\n await this.confirm(input.criterion_id, 'location intent update', async () => row((await this.owned(op.accountId, reference)).Criterion).IntentOption === input.intent_option);\n return [input.criterion_id];\n } };\n }\n const input = remove.parse(op.payload);\n await this.campaign(op.accountId, input.campaign_id);\n const current = await this.query(op.accountId, input.campaign_id, input.criterion_type), selected = input.criterion_ids.map(id => current.find(value => nativeId(value.Id) === id));\n if (selected.some(value => !value)) throw new AdportError('INVALID_INPUT', 'microsoft: a target was not found with this type in the selected campaign/account');\n // Native code2957 requires the complete set on deletion too, not just creation.\n if (input.criterion_type === 'Device' && (input.criterion_ids.length !== 3 || current.length !== 3 || !['Computers', 'Smartphones', 'Tablets'].every(name => current.some(value => row(value.Criterion).DeviceName === name)))) throw new AdportError('INVALID_INPUT', 'microsoft: remove all three device criterion IDs together (Computers, Smartphones, Tablets)');\n return { summary: `Remove ${input.criterion_ids.length} Microsoft ${input.criterion_type} campaign target(s)`, changes: [`- ${JSON.stringify(selected)}`, 'Removing a target or exclusion can broaden or narrow delivery for this campaign. Other criterion IDs and parent serving status are preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'CampaignCriterions', { CampaignId: input.campaign_id, CampaignCriterionIds: input.criterion_ids, CriterionType: 'Targets' }, 'DELETE');\n await this.confirm(input.criterion_ids, 'target removal', async () => !(await this.query(op.accountId, input.campaign_id, input.criterion_type)).some(value => input.criterion_ids.includes(nativeId(value.Id)) && value.Status !== 'Deleted'));\n return input.criterion_ids;\n } };\n }\n}\n\nexport function microsoftTargetingTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_campaign_targets', namespace: 'microsoft', description: 'Read one concrete campaign targeting subtype with verified campaign/account ownership. Native criterion and percent bid adjustments are preserved. Targets is a mutation selector and cannot be used for reads.', input: z.object({ account_id: id, campaign_id: id, criterion_type: criterionType }), output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() }), annotations: { readOnly: true }, handler: input => provider.targeting.list(input) }),\n defineTool({ name: 'microsoft_geo_locations_file', namespace: 'microsoft', description: 'Get the native geographical-location file URL, server expiration and modification time. Use current non-deprecated location IDs for targeting; returns metadata without downloading or caching the file.', input: z.object({ account_id: id, language_locale: z.enum(['zh-Hant', 'en', 'fr', 'de', 'it', 'ja-JP', 'pt-BR', 'es']).default('en') }), annotations: { readOnly: true }, handler: input => provider.targeting.geoFile(input) }),\n guardedWriteTool({ name: 'microsoft_add_campaign_targets', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Add age, gender, device, day/time, location, location-intent or radius targets; locations can be excluded. Native targets are Active; default paused_creation requires a paused campaign. Device creation requires all three device types together. Bids are integer percent adjustments.', payload: add }),\n guardedWriteTool({ name: 'microsoft_set_campaign_target_bid', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Change a biddable target percentage adjustment with an expected current value. Device range -100..900; other supported targets -90..900. Excluded locations and location-intent criteria do not accept bids.', payload: bid }),\n guardedWriteTool({ name: 'microsoft_set_campaign_location_intent', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Change campaign location intent with an expected current value. PeopleInOrSearchingForOrViewingPages restores the API default; this criterion cannot be deleted. Preserves status and omits the inapplicable bid multiplier.', payload: intentUpdate }),\n guardedWriteTool({ name: 'microsoft_remove_campaign_targets', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove exact owned criterion IDs of one subtype. Devices require all three IDs together. Location intent cannot be deleted; use its edit tool instead. Other targets remain; removing restrictions can broaden delivery. Confirms native disappearance.', payload: remove }),\n ];\n}\n","import { z } from 'zod';\nimport { microsoftId as id, type MicrosoftRow as Row } from './native.js';\n\nexport const criterionType = z.enum(['Age', 'Gender', 'Device', 'DayTime', 'Location', 'LocationIntent', 'Radius']);\nexport const bidType = criterionType.exclude(['LocationIntent']);\nexport const adjustment = z.number().int().min(-90).max(900);\nexport const deviceAdjustment = z.number().int().min(-100).max(900);\nexport const minute = z.enum(['Zero', 'Fifteen', 'Thirty', 'FortyFive']);\nexport const intent = z.enum(['PeopleIn', 'PeopleInOrSearchingForOrViewingPages']);\nexport const target = z.discriminatedUnion('type', [\n z.object({ type: z.literal('Age'), age_range: z.enum(['EighteenToTwentyFour', 'TwentyFiveToThirtyFour', 'ThirtyFiveToFourtyNine', 'FiftyToSixtyFour', 'SixtyFiveAndAbove', 'ThirtyFiveToFiftyFour', 'FiftyFiveAndAbove', 'Unknown']), bid_adjustment_percent: adjustment.default(0) }).strict(),\n z.object({ type: z.literal('Gender'), gender: z.enum(['Male', 'Female']), bid_adjustment_percent: adjustment.default(0) }).strict(),\n z.object({ type: z.literal('Device'), device_name: z.enum(['Computers', 'Smartphones', 'Tablets']), bid_adjustment_percent: deviceAdjustment.default(0) }).strict(),\n z.object({ type: z.literal('DayTime'), day: z.enum(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']), from_hour: z.number().int().min(0).max(23), from_minute: minute, to_hour: z.number().int().min(0).max(24), to_minute: minute, bid_adjustment_percent: adjustment.default(0) }).strict(),\n z.object({ type: z.literal('Location'), location_id: id, exclude: z.boolean().default(false), bid_adjustment_percent: adjustment.optional() }).strict(),\n z.object({ type: z.literal('LocationIntent'), intent_option: intent }).strict(),\n z.object({ type: z.literal('Radius'), latitude: z.number().min(-85).max(85), longitude: z.number().min(-180).max(180), radius: z.number().int().positive().max(800), radius_unit: z.enum(['Miles', 'Kilometers']), name: z.string().max(50).optional(), bid_adjustment_percent: adjustment.default(0) }).strict(),\n]);\nexport const minutes = { Zero: 0, Fifteen: 15, Thirty: 30, FortyFive: 45 };\nexport function validateTargetBatch(value: { targets: Array<z.infer<typeof target>> }, ctx: z.RefinementCtx) {\n const devices = value.targets.filter(value => value.type === 'Device');\n if (devices.length && (devices.length !== 3 || new Set(devices.map(value => value.device_name)).size !== 3 || devices.every(value => value.bid_adjustment_percent === -100))) ctx.addIssue({ code: 'custom', message: 'Add all three distinct device types together, leaving at least one device included' });\n for (const item of value.targets) {\n if (item.type === 'Location' && item.exclude && item.bid_adjustment_percent !== undefined) ctx.addIssue({ code: 'custom', message: 'Excluded locations cannot have a bid adjustment' });\n if (item.type === 'Radius' && item.radius_unit === 'Miles' && item.radius > 500) ctx.addIssue({ code: 'custom', message: 'Radius in miles cannot exceed 500' });\n if (item.type === 'DayTime' && (item.to_hour === 24 && item.to_minute !== 'Zero' || item.from_hour * 60 + minutes[item.from_minute] >= item.to_hour * 60 + minutes[item.to_minute])) ctx.addIssue({ code: 'custom', message: 'DayTime must end after its start within one day; hour 24 requires minute Zero' });\n }\n}\nexport const add = z.object({ campaign_id: id, targets: z.array(target).min(1).max(100) }).superRefine(validateTargetBatch);\nexport const reference = z.object({ campaign_id: id, criterion_id: id, criterion_type: criterionType });\n// Native code2965 forbids deleting LocationIntent; restore its default through the edit tool.\nexport const remove = z.object({ campaign_id: id, criterion_type: criterionType.exclude(['LocationIntent']), criterion_ids: z.array(id).min(1).max(100).refine(value => new Set(value).size === value.length, 'Criterion IDs must be unique') });\nexport const bid = reference.extend({ criterion_type: bidType, bid_adjustment_percent: deviceAdjustment, expected_current_percent: z.number() }).superRefine((value, ctx) => {\n if (value.criterion_type !== 'Device' && value.bid_adjustment_percent < -90) ctx.addIssue({ code: 'custom', message: 'Only devices support a bid adjustment below -90 percent' });\n});\nexport const intentUpdate = z.object({ campaign_id: id, criterion_id: id, intent_option: intent, expected_current_intent: intent });\n\nexport function nativeTarget(parent: Row, input: z.infer<typeof target>): Row {\n const criterion: Row = { Type: `${input.type}Criterion` };\n if (input.type === 'Age') criterion.AgeRange = input.age_range;\n if (input.type === 'Gender') criterion.GenderType = input.gender;\n if (input.type === 'Device') criterion.DeviceName = input.device_name;\n if (input.type === 'DayTime') Object.assign(criterion, { Day: input.day, FromHour: input.from_hour, FromMinute: input.from_minute, ToHour: input.to_hour, ToMinute: input.to_minute });\n if (input.type === 'Location') criterion.LocationId = input.location_id;\n if (input.type === 'LocationIntent') criterion.IntentOption = input.intent_option;\n // REST long values are decimal strings, including Radius (live-verified).\n if (input.type === 'Radius') Object.assign(criterion, { LatitudeDegrees: input.latitude, LongitudeDegrees: input.longitude, Radius: String(input.radius), RadiusUnit: input.radius_unit, ...(input.name !== undefined ? { Name: input.name } : {}) });\n const excluded = input.type === 'Location' && input.exclude;\n return { ...parent, Type: excluded ? `Negative${'AdGroupId' in parent ? 'AdGroup' : 'Campaign'}Criterion` : `Biddable${'AdGroupId' in parent ? 'AdGroup' : 'Campaign'}Criterion`, Criterion: criterion, ...(!excluded && input.type !== 'LocationIntent' ? { CriterionBid: { Type: 'BidMultiplier', Multiplier: input.bid_adjustment_percent ?? 0 } } : {}) };\n }\n","import { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst target = z.discriminatedUnion('type', [z.object({ type: z.literal('Campaign'), campaign_id: id }), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id })]);\nconst keyword = z.object({ text: z.string().min(1).max(100).refine(value => value.trim().length > 0, 'Keyword text cannot be blank'), match_type: z.enum(['Exact', 'Phrase']) });\nconst add = z.object({ target, keywords: z.array(keyword).min(1).max(1000) }).refine(value => new Set(value.keywords.map(value => JSON.stringify([value.text, value.match_type]))).size === value.keywords.length, 'Negative keywords must be unique');\nconst remove = z.object({ target, keyword_ids: z.array(id).min(1).max(1000).refine(value => new Set(value).size === value.length, 'Keyword IDs must be unique') });\ntype Target = z.infer<typeof target>;\ntype Entity = { EntityId: string; EntityType: 'Campaign' | 'AdGroup'; ParentEntityId: string | null };\nexport const MICROSOFT_NEGATIVE_KEYWORD_WRITES = new Set(['microsoft_add_negative_keywords', 'microsoft_remove_negative_keywords']);\n\n/** MicrosoftDocs/Advertising@fdee2fcf; campaign empty-list envelope also live-verified. */\nexport class MicrosoftNegativeKeywordService extends MicrosoftNativeService {\n private async entity(account: string, value: Target): Promise<Entity> {\n await this.campaign(account, value.campaign_id);\n if (value.type === 'Campaign') return { EntityId: value.campaign_id, EntityType: 'Campaign', ParentEntityId: null };\n const result = await this.request(account, 'AdGroups/QueryByIds', { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id] });\n const groups = rows(result.AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== value.ad_group_id) throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n return { EntityId: value.ad_group_id, EntityType: 'AdGroup', ParentEntityId: value.campaign_id };\n }\n\n private async query(account: string, entity: Entity) {\n const result = await this.request(account, 'NegativeKeywords/QueryByEntityIds', { EntityIds: [entity.EntityId], EntityType: entity.EntityType, ParentEntityId: entity.ParentEntityId });\n const collections = rows(result.EntityNegativeKeywords);\n if (collections.length !== 1 || nativeId(collections[0]!.EntityId) !== entity.EntityId || collections[0]!.EntityType !== entity.EntityType || !Object.hasOwn(collections[0]!, 'NegativeKeywords')) throw new AdportError('PROVIDER_ERROR', 'microsoft: negative-keyword entity identity mismatch');\n const values = rows(collections[0]!.NegativeKeywords);\n if (values.length > 20_000 || new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => !keyword.safeParse({ text: value.Text, match_type: value.MatchType }).success)) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid native negative-keyword list');\n return values;\n }\n\n async list(input: { account_id: string; target: Target; after_keyword_id?: string; limit: number }) {\n const entity = await this.entity(input.account_id, input.target), values = await this.query(input.account_id, entity);\n const remaining = values.filter(value => !input.after_keyword_id || BigInt(nativeId(value.Id)) > BigInt(input.after_keyword_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : BigInt(nativeId(a.Id)) > BigInt(nativeId(b.Id)) ? 1 : 0);\n const page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { rows: page, truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n if (op.provider !== 'microsoft' || !MICROSOFT_NEGATIVE_KEYWORD_WRITES.has(op.tool) || op.kind !== (op.tool === 'microsoft_add_negative_keywords' ? 'create' : 'remove')) throw new AdportError('INVALID_INPUT', 'microsoft: negative-keyword operation kind mismatch');\n const input = op.tool === 'microsoft_add_negative_keywords' ? add.parse(op.payload) : remove.parse(op.payload), entity = await this.entity(op.accountId, input.target), current = await this.query(op.accountId, entity);\n if ('keywords' in input) {\n const existing = new Set(current.map(value => JSON.stringify([value.Text, value.MatchType])));\n if (input.keywords.some(value => existing.has(JSON.stringify([value.text, value.match_type])))) throw new AdportError('INVALID_INPUT', 'microsoft: an exact negative-keyword entry already exists; do not replay the create operation');\n if (current.length + input.keywords.length > 20_000) throw new AdportError('INVALID_INPUT', 'microsoft: this request exceeds the native 20000 direct-negative-keyword limit');\n const values = input.keywords.map(value => ({ Text: value.text, MatchType: value.match_type }));\n return { summary: `Add ${values.length} Microsoft ${entity.EntityType} negative keyword(s)`, changes: [`+ exclusions ${JSON.stringify(values)} in ${entity.EntityType} ${entity.EntityId}`, 'Appends direct exclusions. Native negative keywords have no individual serving status; parent status is preserved. Shared and inherited exclusions are separate.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'EntityNegativeKeywords', { EntityNegativeKeywords: [{ EntityId: entity.EntityId, EntityType: entity.EntityType, NegativeKeywords: values }] });\n const groups = rows(result.NegativeKeywordIds), ids = groups.length === 1 && Array.isArray(groups[0]!.Ids) ? groups[0]!.Ids.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== values.length || new Set(ids).size !== ids.length || ids.some(id => current.some(value => nativeId(value.Id) === id))) throw new AdportError('PROVIDER_ERROR', 'microsoft: negative-keyword creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n try {\n const actual = await this.query(op.accountId, entity);\n if (ids.some((id, index) => !actual.some(value => nativeId(value.Id) === id && value.Text === values[index]!.Text && value.MatchType === values[index]!.MatchType))) throw new Error('Created exclusion was not confirmed');\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: negative keywords were accepted but content readback was not confirmed; reconcile before retrying', { resourceIds: ids }); }\n return ids;\n } };\n }\n const selected = input.keyword_ids.map(id => current.find(value => nativeId(value.Id) === id));\n if (selected.some(value => !value)) throw new AdportError('INVALID_INPUT', 'microsoft: a negative keyword was not found in the selected entity/account');\n return { summary: `Remove ${selected.length} Microsoft ${entity.EntityType} negative keyword(s)`, changes: [`- direct exclusions ${JSON.stringify(selected)}`, 'Removing exclusions can broaden delivery. Other direct, inherited and shared-list exclusions and parent serving statuses are preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'EntityNegativeKeywords', { EntityNegativeKeywords: [{ EntityId: entity.EntityId, EntityType: entity.EntityType, NegativeKeywords: input.keyword_ids.map(Id => ({ Id })) }] }, 'DELETE');\n try {\n if ((await this.query(op.accountId, entity)).some(value => input.keyword_ids.includes(nativeId(value.Id)))) throw new Error('Deleted exclusion remains');\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: negative-keyword removal was not confirmed; reconcile before retrying', { resourceIds: input.keyword_ids }); }\n return input.keyword_ids;\n } };\n }\n}\n\nexport function microsoftNegativeKeywordTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_negative_keywords', namespace: 'microsoft', description: 'Read direct campaign or ad-group negative keywords after verifying the full account/parent hierarchy. Shared-list and inherited exclusions are separate. Continue with next_cursor as after_keyword_id.', input: z.object({ account_id: id, target, after_keyword_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_keyword_id' }, annotations: { readOnly: true }, handler: input => provider.negativeKeywords.list(input) }),\n guardedWriteTool({ name: 'microsoft_add_negative_keywords', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Append up to 1000 direct Exact/Phrase exclusions to an owned campaign or ad group. Native negative keywords have no pause state and only restrict delivery; parent status is preserved. Verifies every created ID and its text/match type.', payload: add }),\n guardedWriteTool({ name: 'microsoft_remove_negative_keywords', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove exact owned direct exclusion IDs. This can broaden delivery. Text and match type are immutable: add and confirm a replacement before removing its predecessor. Shared and inherited exclusions are separate.', payload: remove }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, type RequestScope } from './client.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst name = z.string().min(1).max(255).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst amount = z.number().positive().refine(value => Number.isSafeInteger(Math.round(value * 1_000_000)) && Math.abs(value * 1_000_000 - Math.round(value * 1_000_000)) < 0.000001, 'Amount must fit safe integer micros with at most six decimal places');\nconst create = z.object({ name, amount });\nconst selected = z.object({ budget_id: id, expected_snapshot_hash: hash });\nconst update = selected.extend({ name: name.optional(), amount: amount.optional() }).refine(value => value.name !== undefined || value.amount !== undefined, 'Supply a name or amount');\nconst assign = z.object({ campaign_id: id, budget_id: id, expected_campaign_hash: hash, expected_budget_hash: hash });\nconst unassign = z.object({ campaign_id: id, daily_budget: amount, expected_campaign_hash: hash });\nconst budgetSchema = z.object({ Id: id, Name: z.string(), Amount: z.number().positive(), BudgetType: z.string(), AssociationCount: z.number().int().nonnegative() });\nconst memberSchema = z.object({ Id: id, Name: z.string(), Status: z.string(), CampaignType: z.string(), SubType: z.string().nullable(), ExperimentId: id.nullable() });\nconst viewSchema = z.object({ budget: budgetSchema, currency: z.string().optional(), members: z.array(memberSchema), membership_complete: z.boolean(), snapshot_hash: hash });\nconst contextSchema = z.object({ campaign: memberSchema, budget_id: id.nullable(), effective_daily_amount: z.number().positive(), budget_type: z.string(), currency: z.string().optional(), shared_budget: viewSchema.optional(), snapshot_hash: hash });\ntype Budget = z.infer<typeof budgetSchema>;\ntype Member = z.infer<typeof memberSchema>;\ntype View = z.infer<typeof viewSchema>;\ntype Context = z.infer<typeof contextSchema>;\ntype Inventory = { budgets: Budget[]; campaigns: Row[]; currency?: string };\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');\nconst micros = (value: number) => { const result = Math.round(value * 1_000_000); if (!Number.isSafeInteger(result) || result <= 0) throw new AdportError('PROVIDER_ERROR', 'microsoft: native budget amount cannot be represented safely in micros'); return result; };\nconst sharedId = (value: unknown) => value === null || value === undefined || value === '0' || value === 0 ? null : nativeId(value);\nconst member = (value: Row): Member => memberSchema.parse({ Id: nativeId(value.Id), Name: value.Name, Status: value.Status, CampaignType: value.CampaignType, SubType: value.SubType ?? null, ExperimentId: sharedId(value.ExperimentId) });\nconst order = (a: { Id: string }, b: { Id: string }) => BigInt(a.Id) < BigInt(b.Id) ? -1 : BigInt(a.Id) > BigInt(b.Id) ? 1 : 0;\nconst notes = ['Snapshot checks detect changed amounts and campaign membership before sending the write. Microsoft has no atomic compare-and-set for these operations; concurrent changes can still occur.', 'Campaign status is preserved. Shared budgets are account-scoped; the amount is one daily pool, not an amount multiplied by its campaign count.'];\n\nexport const MICROSOFT_BUDGET_WRITES = new Set(['microsoft_create_shared_budget', 'microsoft_update_shared_budget', 'microsoft_delete_shared_budget', 'microsoft_assign_shared_budget', 'microsoft_unassign_shared_budget']);\n\n/** MicrosoftDocs/Advertising@fdee2fcf, Budget and Campaign REST v13 contracts. */\nexport class MicrosoftBudgetService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string) => Promise<RequestScope>, lookupCampaign: (account: string, campaign: string) => Promise<unknown>, private readonly campaigns: (account: string) => Promise<unknown>, private readonly currency: (account: string) => Promise<string | undefined>) { super(client, scope, lookupCampaign); }\n\n private async inventory(account: string): Promise<Inventory> {\n const result = await this.request(account, 'Budgets/QueryByIds', { BudgetIds: null });\n const budgets = rows(result.Budgets).map(value => budgetSchema.parse({ ...value, Id: nativeId(value.Id) }));\n if (new Set(budgets.map(value => value.Id)).size !== budgets.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate budget IDs in native inventory');\n budgets.forEach(value => micros(value.Amount));\n const campaigns = rows(await this.campaigns(account));\n if (new Set(campaigns.map(value => nativeId(value.Id))).size !== campaigns.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate campaign IDs in native inventory');\n const currency = await this.currency(account);\n return { budgets, campaigns, ...(currency ? { currency } : {}) };\n }\n\n private view(account: string, budgetId: string, inventory: Inventory): View {\n const budget = inventory.budgets.find(value => value.Id === budgetId);\n if (!budget) throw new AdportError('INVALID_INPUT', 'microsoft: shared budget was not found in the selected account');\n const members = inventory.campaigns.filter(value => sharedId(value.BudgetId) === budgetId).map(member).sort(order);\n const value = { budget, ...(inventory.currency ? { currency: inventory.currency } : {}), members, membership_complete: members.length === budget.AssociationCount };\n return { ...value, snapshot_hash: digest({ account, ...value }) };\n }\n\n private context(account: string, campaignId: string, inventory: Inventory): Context {\n const current = inventory.campaigns.find(value => nativeId(value.Id) === campaignId);\n if (!current) throw new AdportError('INVALID_INPUT', 'microsoft: campaign was not found in the selected account');\n const campaign = member(current), budget_id = sharedId(current.BudgetId), shared_budget = budget_id ? this.view(account, budget_id, inventory) : undefined;\n // The Budget object is authoritative; a campaign's replicated DailyBudget can lag.\n const effective_daily_amount = shared_budget?.budget.Amount ?? amount.parse(current.DailyBudget);\n micros(effective_daily_amount);\n const value = { campaign, budget_id, effective_daily_amount, budget_type: z.string().parse(shared_budget?.budget.BudgetType ?? current.BudgetType), ...(inventory.currency ? { currency: inventory.currency } : {}), ...(shared_budget ? { shared_budget } : {}) };\n return { ...value, snapshot_hash: digest({ account, ...value }) };\n }\n\n async list(input: { account_id: string; after_budget_id?: string; limit: number }) {\n const inventory = await this.inventory(input.account_id), remaining = inventory.budgets.filter(value => !input.after_budget_id || BigInt(value.Id) > BigInt(input.after_budget_id)).sort(order), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { rows: page.map(value => this.view(input.account_id, value.Id, inventory)), truncated, ...(truncated ? { next_cursor: page.at(-1)!.Id } : {}) };\n }\n\n async get(account: string, budgetId: string): Promise<View> { id.parse(budgetId); return this.view(account, budgetId, await this.inventory(account)); }\n async campaignBudget(account: string, campaignId: string): Promise<Context> { id.parse(campaignId); return this.context(account, campaignId, await this.inventory(account)); }\n\n private complete(value: View): void {\n if (!value.membership_complete) throw new AdportError('INVALID_INPUT', 'microsoft: campaign membership does not match native AssociationCount; refresh and reconcile all campaign types before writing');\n if (value.budget.BudgetType !== 'DailyBudgetStandard') throw new AdportError('INVALID_INPUT', 'microsoft: only native DailyBudgetStandard shared budgets can be changed');\n }\n\n private expected(actual: string, expected: string): void {\n if (actual !== expected) throw new AdportError('INVALID_INPUT', 'microsoft: budget or campaign snapshot changed; read fresh context and request a new preview');\n }\n\n private eligible(value: Member): void {\n if (value.CampaignType === 'PerformanceMax' || value.SubType === 'ShoppingSmartAds' || value.ExperimentId) throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max, Smart Shopping and experiment campaigns cannot be assigned or directly detached with shared-budget tools');\n if (!['Active', 'Paused', 'BudgetPaused'].includes(value.Status)) throw new AdportError('INVALID_INPUT', 'microsoft: campaign serving status is not recognized for a budget change');\n }\n\n private async verify(account: string, ids: string[], test: (inventory: Inventory) => boolean): Promise<string[]> {\n try { if (!test(await this.inventory(account))) throw new Error('Native readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: budget write was accepted but readback was not confirmed; reconcile these resource IDs before retrying', { resourceIds: ids }); }\n return ids;\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n const kinds = { microsoft_create_shared_budget: 'create', microsoft_update_shared_budget: 'update', microsoft_delete_shared_budget: 'remove', microsoft_assign_shared_budget: 'update', microsoft_unassign_shared_budget: 'update' } as const;\n if (op.provider !== 'microsoft' || !MICROSOFT_BUDGET_WRITES.has(op.tool) || op.kind !== kinds[op.tool as keyof typeof kinds]) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget operation kind mismatch');\n const input = op.tool === 'microsoft_create_shared_budget' ? create.parse(op.payload) : op.tool === 'microsoft_update_shared_budget' ? update.parse(op.payload) : op.tool === 'microsoft_delete_shared_budget' ? selected.parse(op.payload) : op.tool === 'microsoft_assign_shared_budget' ? assign.parse(op.payload) : unassign.parse(op.payload);\n const account = op.accountId, inventory = await this.inventory(account);\n const delta = (target: string, from: number, to: number) => ({ target, ...(inventory.currency ? { currency: inventory.currency } : {}), fromMicros: from === 0 ? 0 : micros(from), toMicros: micros(to) });\n const unique = (value: string, except?: string) => { if (inventory.budgets.some(budget => budget.Id !== except && budget.Name.toLowerCase() === value.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget name already exists in this account'); };\n if (op.tool === 'microsoft_create_shared_budget' && 'name' in input && 'amount' in input) {\n const value = create.parse(input); unique(value.name);\n return { summary: `Create Microsoft shared daily budget \"${value.name}\"`, changes: [`+ unattached shared budget ${JSON.stringify(value)}`, 'No campaigns are assigned by this operation.'], fieldChanges: [{ field: 'Name', before: '(new)', after: value.name }], notes, coercions: [], budgetDeltas: [delta(`new shared budget \"${value.name}\" daily pool`, 0, value.amount)], execute: async () => {\n const result = await this.request(account, 'Budgets', { Budgets: [{ Name: value.name, Amount: value.amount, BudgetType: 'DailyBudgetStandard' }] });\n const ids = Array.isArray(result.BudgetIds) ? result.BudgetIds.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1 || inventory.budgets.some(value => value.Id === ids[0])) throw new AdportError('PROVIDER_ERROR', 'microsoft: budget creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.verify(account, ids, actual => { const view = this.view(account, ids[0]!, actual); return view.budget.Name === value.name && view.budget.Amount === value.amount && view.budget.BudgetType === 'DailyBudgetStandard' && view.membership_complete && !view.members.length; });\n } };\n }\n if (op.tool === 'microsoft_update_shared_budget' || op.tool === 'microsoft_delete_shared_budget') {\n const value = selected.parse(input), current = this.view(account, value.budget_id, inventory);\n this.complete(current); this.expected(current.snapshot_hash, value.expected_snapshot_hash);\n if (op.tool === 'microsoft_delete_shared_budget') {\n if (current.members.length) throw new AdportError('INVALID_INPUT', 'microsoft: detach all campaigns before deleting a shared budget');\n return { summary: `Delete unused Microsoft shared budget \"${current.budget.Name}\"`, changes: [`- shared budget ${current.budget.Id}; native AssociationCount and discovered membership are both zero`], notes, coercions: [], budgetDeltas: [], execute: async () => { await this.request(account, 'Budgets', { BudgetIds: [current.budget.Id] }, 'DELETE'); return this.verify(account, [current.budget.Id], actual => !actual.budgets.some(value => value.Id === current.budget.Id)); } };\n }\n const edit = update.parse(input); if (edit.name !== undefined) unique(edit.name, current.budget.Id);\n const fields = { ...(edit.name !== undefined && edit.name !== current.budget.Name ? { Name: edit.name } : {}), ...(edit.amount !== undefined && edit.amount !== current.budget.Amount ? { Amount: edit.amount } : {}) };\n if (!Object.keys(fields).length) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget update has no changes');\n const fieldChanges = Object.entries(fields).map(([field, after]) => ({ field, before: String(current.budget[field as keyof Budget]), after: String(after) }));\n return { summary: `Update Microsoft shared budget \"${current.budget.Name}\" (${current.members.length} campaign(s))`, changes: [`~ shared budget ${current.budget.Id} ${JSON.stringify(fields)}`, `Affected campaigns: ${JSON.stringify(current.members)}`], fieldChanges, notes: [...notes, `Affected campaigns: ${current.members.map(value => `${value.Id} ${value.Name} (${value.Status})`).join('; ') || '(none)'}`], coercions: [], budgetDeltas: fields.Amount !== undefined ? [delta(`shared budget ${current.budget.Id} daily pool`, current.budget.Amount, fields.Amount)] : [], execute: async () => { await this.request(account, 'Budgets', { Budgets: [{ Id: current.budget.Id, ...fields }] }, 'PUT'); return this.verify(account, [current.budget.Id], actual => { const after = this.view(account, current.budget.Id, actual); return after.membership_complete && JSON.stringify(after.members) === JSON.stringify(current.members) && Object.entries(fields).every(([key, value]) => after.budget[key as keyof Budget] === value); }); } };\n }\n if (op.tool === 'microsoft_assign_shared_budget') {\n const value = assign.parse(input), current = this.context(account, value.campaign_id, inventory), destination = this.view(account, value.budget_id, inventory);\n this.eligible(current.campaign); this.complete(destination); if (current.shared_budget) this.complete(current.shared_budget);\n this.expected(current.snapshot_hash, value.expected_campaign_hash); this.expected(destination.snapshot_hash, value.expected_budget_hash);\n if (current.budget_id === value.budget_id) throw new AdportError('INVALID_INPUT', 'microsoft: campaign already uses this shared budget');\n return { summary: `Assign Microsoft campaign \"${current.campaign.Name}\" to shared budget \"${destination.budget.Name}\"`, changes: [`~ campaign ${value.campaign_id} BudgetId ${current.budget_id ?? '(individual)'} → ${value.budget_id}`, `Source members before assignment: ${JSON.stringify(current.shared_budget?.members ?? [current.campaign])}`, `Destination members before assignment: ${JSON.stringify(destination.members)}`, 'Policy compares the campaign’s current effective daily limit with the destination pool amount. Pool membership changes can redistribute spend among its campaigns.'], fieldChanges: [{ field: 'Budget', before: current.budget_id ?? '(individual)', after: value.budget_id }], notes: [...notes, `Source campaigns: ${(current.shared_budget?.members ?? [current.campaign]).map(value => `${value.Id} ${value.Name} (${value.Status})`).join('; ')}`, `Destination campaigns: ${destination.members.map(value => `${value.Id} ${value.Name} (${value.Status})`).join('; ') || '(none)'}`], coercions: [], budgetDeltas: [delta(`campaign ${value.campaign_id} effective daily budget`, current.effective_daily_amount, destination.budget.Amount)], execute: async () => {\n await this.request(account, 'Campaigns', { AccountId: account, Campaigns: [{ Id: value.campaign_id, BudgetId: value.budget_id }] }, 'PUT');\n return this.verify(account, [value.campaign_id, value.budget_id], actual => { const after = this.context(account, value.campaign_id, actual), target = this.view(account, value.budget_id, actual); return after.budget_id === value.budget_id && after.campaign.Status === current.campaign.Status && target.membership_complete && target.budget.Amount === destination.budget.Amount && JSON.stringify(target.members) === JSON.stringify([...destination.members, current.campaign].sort(order)) && (!current.budget_id || this.view(account, current.budget_id, actual).membership_complete); });\n } };\n }\n const value = unassign.parse(input), current = this.context(account, value.campaign_id, inventory);\n this.eligible(current.campaign); this.expected(current.snapshot_hash, value.expected_campaign_hash);\n if (!current.shared_budget) throw new AdportError('INVALID_INPUT', 'microsoft: campaign is not using a shared budget');\n this.complete(current.shared_budget);\n return { summary: `Detach Microsoft campaign \"${current.campaign.Name}\" to its own daily budget`, changes: [`~ campaign ${value.campaign_id} BudgetId ${current.budget_id} → 0; DailyBudget → ${value.daily_budget}; BudgetType → DailyBudgetStandard`, 'The remaining shared pool amount is preserved. Detaching adds an independent daily allocation alongside that pool.'], fieldChanges: [{ field: 'Budget', before: current.budget_id!, after: '(individual DailyBudgetStandard)' }], notes, coercions: [], budgetDeltas: [delta(`campaign ${value.campaign_id} effective daily budget`, current.effective_daily_amount, value.daily_budget)], execute: async () => {\n // Clearing BudgetId starts an individual budget: native REST also requires its type (1121 if omitted).\n await this.request(account, 'Campaigns', { AccountId: account, Campaigns: [{ Id: value.campaign_id, BudgetId: '0', DailyBudget: value.daily_budget, BudgetType: 'DailyBudgetStandard' }] }, 'PUT');\n return this.verify(account, [value.campaign_id, current.budget_id!], actual => { const after = this.context(account, value.campaign_id, actual), previous = this.view(account, current.budget_id!, actual); return after.budget_id === null && after.effective_daily_amount === value.daily_budget && after.campaign.Status === current.campaign.Status && previous.membership_complete && previous.budget.Amount === current.shared_budget!.budget.Amount && JSON.stringify(previous.members) === JSON.stringify(current.shared_budget!.members.filter(value => value.Id !== current.campaign.Id)); });\n } };\n }\n}\n\nexport function microsoftBudgetTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_shared_budgets', namespace: 'microsoft', description: 'List native daily pools with all-type campaign membership, completeness and snapshot hashes. Continue next_cursor as after_budget_id.', input: z.object({ account_id: id, after_budget_id: id.optional(), limit: z.number().int().positive().max(100).default(50) }), output: z.object({ rows: z.array(viewSchema), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_budget_id' }, annotations: { readOnly: true }, handler: input => provider.budgets.list(input) }),\n defineTool({ name: 'microsoft_get_shared_budget', namespace: 'microsoft', description: 'Read an owned daily pool, its campaign members and snapshot_hash for update, assignment or deletion. Writes reject incomplete membership.', input: z.object({ account_id: id, budget_id: id }), output: viewSchema, annotations: { readOnly: true }, handler: input => provider.budgets.get(input.account_id, input.budget_id) }),\n defineTool({ name: 'microsoft_campaign_budget', namespace: 'microsoft', description: 'Read an owned campaign’s effective daily limit, individual/shared budget, members and snapshot_hash. Use this hash as expected_campaign_hash when assigning or detaching.', input: z.object({ account_id: id, campaign_id: id }), output: contextSchema, annotations: { readOnly: true }, handler: input => provider.budgets.campaignBudget(input.account_id, input.campaign_id) }),\n guardedWriteTool({ name: 'microsoft_create_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create an unattached DailyBudgetStandard pool in account currency. Checks its amount in policy micros. Does not assign or activate campaigns.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Rename or change one shared daily pool after binding its amount and all campaign members/statuses with expected_snapshot_hash. Monetary caps apply once to the pool; no atomic native compare-and-set.', payload: update }),\n guardedWriteTool({ name: 'microsoft_delete_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', destructive: true, description: 'Permanently delete an owned unused shared budget. Requires matching snapshot and both native and discovered campaign counts zero; verifies disappearance.', payload: selected }),\n guardedWriteTool({ name: 'microsoft_assign_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Assign a campaign to an owned daily pool using campaign and destination snapshot hashes. Compares current effective limit with the pool amount for policy; preserves status. Excludes Performance Max, Smart Shopping and experiments.', payload: assign }),\n guardedWriteTool({ name: 'microsoft_unassign_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Detach to an explicit individual DailyBudgetStandard budget in account currency. Requires campaign snapshot, preserves status and remaining pool amount, and checks monetary policy. Excludes experiment campaigns.', payload: unassign }),\n ];\n}\n","import { AdportError, defineTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, type RequestScope } from './client.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftRows as rows, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst text = z.string().min(1).max(100).refine(value => value.trim().length > 0, 'Keyword cannot be blank');\nconst keywords = z.array(text).min(1).max(200);\nconst date = z.iso.date();\nconst dateRange = z.object({ start: date, end: date }).refine(value => value.start <= value.end, 'Start date must not follow end date');\nconst targeting = z.object({ account_id: id, language: z.enum(['English', 'French', 'German']), location_ids: z.array(id).min(1).max(2000).refine(value => new Set(value).size === value.length, 'Location IDs must be unique'), network: z.enum(['OwnedAndOperatedAndSyndicatedSearch', 'OwnedAndOperatedOnly']).default('OwnedAndOperatedAndSyndicatedSearch') });\nconst baseIdeas = targeting.extend({ date_range: dateRange.optional(), limit: z.number().int().positive().max(3000).default(100) });\nconst ideas = baseIdeas.extend({ keywords: keywords.optional(), url: z.url().refine(value => { const url = new URL(value); return url.protocol === 'https:' && !url.username && !url.password; }, 'Use an HTTPS URL without credentials').optional(), category_id: id.optional() }).refine(value => value.keywords !== undefined || value.url !== undefined || value.category_id !== undefined, 'Supply keyword, URL or category seeds');\nconst historical = baseIdeas.extend({ keywords });\nconst traffic = targeting.extend({ keywords: z.array(z.object({ text, match_type: z.enum(['Phrase', 'Broad']), max_cpc: z.number().positive().optional() })).min(1).max(1000), max_cpc: z.number().positive(), daily_budget: z.number().positive().optional(), negative_keywords: z.array(z.object({ text, match_type: z.enum(['Exact', 'Phrase']) })).max(1000).optional() });\nconst ideasOutput = z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean(), returned_count: z.number().int().nonnegative(), native_result_count: z.number().int().nonnegative(), currency: z.string().optional(), date_range: dateRange.optional(), notes: z.array(z.string()) });\nconst parts = (value: string) => { const [Year, Month, Day] = value.split('-').map(Number); return { Year, Month, Day }; };\nfunction criteria(input: z.infer<typeof targeting>): Row[] {\n return [{ Type: 'LanguageCriterion', Language: input.language }, { Type: 'NetworkCriterion', Network: input.network }, ...input.location_ids.map(LocationId => ({ Type: 'LocationCriterion', LocationId }))];\n}\n\n/** Ad Insight REST v13 shapes from MicrosoftDocs/Advertising@fdee2fcf. */\nexport class MicrosoftPlanningService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string) => Promise<RequestScope>, lookupCampaign: (account: string, campaign: string) => Promise<unknown>, private readonly currency: (account: string) => string | undefined) { super(client, scope, lookupCampaign); }\n async keywordIdeas(input: z.infer<typeof ideas> | z.infer<typeof historical>, expand: boolean) {\n const value = expand ? ideas.parse(input) : historical.parse(input);\n const parameters: Row[] = [{ Type: 'LanguageSearchParameter', Languages: [{ Type: 'LanguageCriterion', Language: value.language }] }, { Type: 'LocationSearchParameter', Locations: value.location_ids.map(LocationId => ({ Type: 'LocationCriterion', LocationId })) }, { Type: 'NetworkSearchParameter', Network: { Type: 'NetworkCriterion', Network: value.network } }];\n if (value.keywords) parameters.push({ Type: 'QuerySearchParameter', Queries: value.keywords });\n if ('url' in value && value.url) parameters.push({ Type: 'UrlSearchParameter', Url: value.url });\n if ('category_id' in value && value.category_id) parameters.push({ Type: 'CategorySearchParameter', CategoryId: value.category_id });\n if (value.date_range) parameters.push({ Type: 'DateRangeSearchParameter', StartDate: parts(value.date_range.start), EndDate: parts(value.date_range.end) });\n const result = await this.request(value.account_id, 'KeywordIdeas/Query', { ExpandIdeas: expand, IdeaAttributes: ['Keyword', 'Competition', 'MonthlySearchCounts', 'SuggestedBid', 'AdImpressionShare', 'Relevance', 'Source', 'AdGroupId', 'AdGroupName'], SearchParameters: parameters }, 'POST', 'adinsight');\n if (!Object.hasOwn(result, 'KeywordIdeas')) throw new AdportError('PROVIDER_ERROR', 'microsoft: keyword-idea response did not contain the native result envelope');\n const values = rows(result.KeywordIdeas);\n const currency = this.currency(value.account_id);\n const page = values.slice(0, value.limit);\n return { rows: page, truncated: values.length > page.length, returned_count: page.length, native_result_count: values.length, ...(currency ? { currency } : {}), ...(value.date_range ? { date_range: value.date_range } : {}), notes: ['returned_count is the number of rows displayed here. native_result_count is the native response size before the requested limit. Native results are currently capped at 3000 with no continuation cursor; neither count proves the full search universe.', 'MonthlySearchCounts is newest-first. Without an explicit date range, its exact calendar months cannot be identified; the latest month may lag by up to 72 hours.', 'Suggested bids are estimates in account currency, not observed campaign performance. Missing native metrics remain missing; native numeric zero is preserved without inferring availability.', 'Negative AdGroupId values identify suggested planning groups; they are not existing campaign ad-group IDs.'] };\n }\n\n async trafficEstimates(input: z.infer<typeof traffic>) {\n const value = traffic.parse(input);\n const estimator = { AdGroupEstimators: [{ KeywordEstimators: value.keywords.map(value => ({ Keyword: { Text: value.text, MatchType: value.match_type }, ...(value.max_cpc !== undefined ? { MaxCpc: value.max_cpc } : {}) })), MaxCpc: value.max_cpc }], Criteria: criteria(value), ...(value.daily_budget !== undefined ? { DailyBudget: value.daily_budget } : {}), ...(value.negative_keywords !== undefined ? { NegativeKeywords: value.negative_keywords.map(value => ({ Text: value.text, MatchType: value.match_type })) } : {}) };\n const result = await this.request(value.account_id, 'KeywordTrafficEstimates/Query', { CampaignEstimators: [estimator] }, 'POST', 'adinsight');\n if (!Object.hasOwn(result, 'CampaignEstimates')) throw new AdportError('PROVIDER_ERROR', 'microsoft: traffic-estimate response did not contain the native result envelope');\n const currency = this.currency(value.account_id);\n return { rows: rows(result.CampaignEstimates), estimate_period: 'week' as const, deprecated_metrics: ['AveragePosition'], ...(currency ? { currency } : {}), notes: ['Clicks, impressions and total cost are estimated per week. The optional DailyBudget input is a daily filter, not the estimate period.', 'AveragePosition is deprecated and native values have been fixed at zero since 2021-03-31; it is not a valid position estimate.', 'These are hypothetical traffic estimates in account currency, not a forecast guarantee or observed performance. No campaigns, ads or keywords are created or edited.', 'CampaignId and AdGroupId are reserved by this API and are intentionally omitted. Only Phrase and Broad keyword estimates are supported.'] };\n }\n}\n\nexport function microsoftPlanningTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_keyword_ideas', namespace: 'microsoft', description: 'Read Ad Insight keyword ideas from keyword, HTTPS URL or native category seeds. Requires language and location IDs; suggested bids use account currency. Native cap 3000, no pagination; monthly counts newest-first and undated unless date_range supplied.', input: ideas, output: ideasOutput, annotations: { readOnly: true }, handler: input => provider.planning.keywordIdeas(input, true) }),\n defineTool({ name: 'microsoft_keyword_historical_metrics', namespace: 'microsoft', description: 'Read native keyword attributes without expanding seeds: demand history, competition and estimated bids. Monthly counts newest-first; missing values remain unavailable. Exact month labels require explicit date_range.', input: historical, output: ideasOutput, annotations: { readOnly: true }, handler: input => provider.planning.keywordIdeas(input, false) }),\n defineTool({ name: 'microsoft_keyword_traffic_estimates', namespace: 'microsoft', description: 'Estimate hypothetical weekly Phrase/Broad keyword traffic from bids, language, locations and network, optionally daily budget and exclusions. Read-only; no campaign changes. Cost/bids use account currency. AveragePosition is deprecated and always zero.', input: traffic, output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), estimate_period: z.literal('week'), deprecated_metrics: z.array(z.string()), currency: z.string().optional(), notes: z.array(z.string()) }), annotations: { readOnly: true }, handler: input => provider.planning.trafficEstimates(input) }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst goalType = z.enum(['AppDownload', 'AppInstall', 'Duration', 'Event', 'InStoreTransaction', 'OfflineConversion', 'PagesViewedPerVisit', 'Url']);\nconst supportedType = z.enum(['Url', 'Event', 'OfflineConversion']);\nconst standardTypes = ['AppDownload', 'AppInstall', 'Duration', 'Event', 'OfflineConversion', 'PagesViewedPerVisit', 'Url'] as const;\nconst name = z.string().min(1).max(100).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst category = z.enum(['AddToCart', 'BeginCheckout', 'BookAppointment', 'Contact', 'GetDirections', 'Other', 'OutboundClick', 'PageView', 'Purchase', 'RequestQuote', 'Signup', 'SubmitLeadForm', 'Subscribe']);\nconst expression = z.object({ operator: z.enum(['BeginsWith', 'Contains', 'Equals', 'RegularExpression']), text: z.string().min(1).max(100) });\nconst event = z.object({ action: expression.optional(), category: expression.optional(), label: expression.optional(), value: z.object({ operator: z.enum(['Equals', 'GreaterThan', 'LessThan']), amount: z.number() }).optional() }).refine(value => Object.values(value).some(value => value !== undefined), 'At least one complete event condition is required');\nconst url = z.object({ operator: expression.shape.operator, expression: z.string().min(1).max(1000) });\nconst revenue = z.discriminatedUnion('type', [z.object({ type: z.literal('NoValue') }), z.object({ type: z.literal('FixedValue'), value: z.number().nonnegative(), currency: z.string().regex(/^[A-Z]{3}$/).optional() }), z.object({ type: z.literal('VariableValue'), value: z.number().nonnegative().optional(), currency: z.string().regex(/^[A-Z]{3}$/).optional() })]);\nconst common = z.object({ name, goal_category: category, status: z.enum(['Active', 'Paused']).default('Paused'), exclude_from_bidding: z.boolean().default(true), count_type: z.enum(['All', 'Unique']).default('All'), conversion_window_minutes: z.number().int().min(1).max(129600).default(43200), revenue: revenue.default({ type: 'NoValue' }), expected_auto_tagging_enabled: z.boolean() });\nconst create = z.object({ goal: z.discriminatedUnion('type', [common.extend({ type: z.literal('OfflineConversion'), is_externally_attributed: z.boolean().default(false) }), common.extend({ type: z.literal('Url'), tag_id: id, url_rule: url }), common.extend({ type: z.literal('Event'), tag_id: id, event_conditions: event })]) });\nconst update = z.object({ goal_id: id, goal_type: supportedType, expected_snapshot_hash: z.string().regex(/^[a-f0-9]{64}$/), name: name.optional(), goal_category: category.optional(), status: z.enum(['Active', 'Paused']).optional(), exclude_from_bidding: z.boolean().optional(), count_type: z.enum(['All', 'Unique']).optional(), conversion_window_minutes: z.number().int().min(1).max(129600).optional(), revenue: revenue.optional(), is_externally_attributed: z.boolean().optional(), url_rule: url.optional(), event_conditions: event.optional() }).refine(value => Object.entries(value).some(([key, value]) => !['goal_id', 'goal_type', 'expected_snapshot_hash'].includes(key) && value !== undefined), 'Supply an editable field');\nconst createTag = z.object({ name, description: z.string().min(1).max(1000).optional(), expected_customer_id: id.describe('native_customer_id from microsoft_linked_uet_tags') });\nconst view = z.object({ account_id: id, goal: z.record(z.string(), z.unknown()), auto_tagging_enabled: z.boolean().describe('MSCLKIDAutoTaggingEnabled on the selected account, separate from the goal Scope'), auto_tagging_scope: z.literal('Account'), snapshot_hash: z.string().regex(/^[a-f0-9]{64}$/) });\nconst additional = 'GoalCategory, IsExternallyAttributed, IsAutoGoal, IsEnhancedConversionsEnabled, ViewThroughConversionWindowInMinutes, AttributionModelType, ApplicationDownloadGoal';\nconst pairs = [['ActionExpression', 'ActionOperator', 'action'], ['CategoryExpression', 'CategoryOperator', 'category'], ['LabelExpression', 'LabelOperator', 'label'], ['Value', 'ValueOperator', 'value']] as const;\nconst notes = ['Microsoft automatically enables MSCLKIDAutoTaggingEnabled when adding or updating this goal, including paused goals. This tool does not install a UET tag or send conversion events.', 'Account scope is fixed. Native Deleted status is internal-only; no permanent goal-deletion operation is exposed. Use Paused to stop tracking.', 'Goal snapshots detect changed configuration before submission; Microsoft provides no atomic compare-and-set. Conversion settings can affect reporting and automated bidding.'];\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nconst wireRevenue = (value: z.infer<typeof revenue>) => ({ Type: value.type, ...('value' in value && value.value !== undefined ? { Value: value.value } : {}), ...('currency' in value && value.currency ? { CurrencyCode: value.currency } : {}) });\nfunction eventFields(value: z.infer<typeof event>): Row {\n const fields: Row = {};\n for (const [field, operator, key] of pairs) { const condition = value[key]; fields[field] = condition ? 'text' in condition ? condition.text : condition.amount : null; fields[operator] = condition?.operator ?? null; }\n return fields;\n}\nfunction matches(actual: Row, fields: Row): boolean {\n return Object.entries(fields).every(([key, value]) => value === null ? actual[key] === null || actual[key] === undefined : value && typeof value === 'object' && !Array.isArray(value) ? actual[key] && typeof actual[key] === 'object' && matches(actual[key] as Row, value as Row) : String(actual[key]) === String(value));\n}\nexport const MICROSOFT_CONVERSION_WRITES = new Set(['microsoft_create_conversion_goal', 'microsoft_update_conversion_goal', 'microsoft_create_uet_tag']);\n\n/** Campaign Management v13; EventGoal omissions delete criteria, unlike ordinary optional update fields. */\nexport class MicrosoftConversionService extends MicrosoftNativeService {\n private async autoTagging(account: string): Promise<boolean> {\n const result = await this.request(account, 'AccountProperties/Query', { AccountPropertyNames: ['MSCLKIDAutoTaggingEnabled'] });\n const properties = rows(result.AccountProperties).filter(value => value.Name === 'MSCLKIDAutoTaggingEnabled');\n if (properties.length !== 1 || !['true', 'false'].includes(String(properties[0]!.Value))) throw new AdportError('PROVIDER_ERROR', 'microsoft: native click-ID auto-tagging state is unavailable');\n return String(properties[0]!.Value) === 'true';\n }\n\n private async query(account: string, types: z.infer<typeof goalType>[]): Promise<Row[]> {\n const result = await this.request(account, 'ConversionGoals/QueryByIds', { ConversionGoalIds: null, ConversionGoalTypes: types.join(', '), ReturnAdditionalFields: additional });\n if (!Object.hasOwn(result, 'ConversionGoals')) throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion goals response envelope is missing');\n const values = rows(result.ConversionGoals);\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => !types.includes(goalType.parse(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion-goal native identities or types mismatch');\n return values;\n }\n\n private snapshot(account: string, goal: Row, enabled: boolean) {\n const { TrackingStatus: _tracking, ...configuration } = goal;\n return { account_id: account, goal, auto_tagging_enabled: enabled, auto_tagging_scope: 'Account' as const, snapshot_hash: createHash('sha256').update(JSON.stringify(canonical({ account, configuration, enabled }))).digest('hex') };\n }\n\n async list(input: { account_id: string; goal_types: z.infer<typeof goalType>[]; after_goal_id?: string; limit: number }) {\n const values = await this.query(input.account_id, input.goal_types), enabled = await this.autoTagging(input.account_id), remaining = values.filter(value => !input.after_goal_id || BigInt(nativeId(value.Id)) > BigInt(input.after_goal_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { account_id: input.account_id, rows: page.map(value => this.snapshot(input.account_id, value, enabled)), auto_tagging_enabled: enabled, auto_tagging_scope: 'Account' as const, truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n async get(account: string, goalId: string, type: z.infer<typeof goalType>) {\n id.parse(goalId); const values = await this.query(account, [type]), enabled = await this.autoTagging(account), current = values.find(value => nativeId(value.Id) === goalId);\n if (!current) throw new AdportError('INVALID_INPUT', 'microsoft: conversion goal was not found for the selected account/type');\n return this.snapshot(account, current, enabled);\n }\n\n async linkedTags(input: { account_id: string; after_tag_id?: string; limit: number }) {\n const scope = await this.accountScope(input.account_id, true);\n const goals = await this.query(input.account_id, [...standardTypes]), links = new Map<string, string[]>();\n for (const goal of goals) {\n if (goal.TagId === null || goal.TagId === undefined || goal.TagId === '0' || goal.TagId === 0) continue;\n const tag = nativeId(goal.TagId); links.set(tag, [...(links.get(tag) ?? []), nativeId(goal.Id)]);\n }\n const ids = [...links.keys()].filter(value => !input.after_tag_id || BigInt(value) > BigInt(input.after_tag_id)).sort((a, b) => BigInt(a) < BigInt(b) ? -1 : 1), page = ids.slice(0, input.limit), truncated = ids.length > page.length;\n if (!page.length) return { native_customer_id: scope.customerId!, rows: [], truncated: false };\n const result = await this.request(input.account_id, 'UetTags/QueryByIds', { TagIds: page }), tags = rows(result.UetTags);\n if (tags.length !== page.length || new Set(tags.map(value => nativeId(value.Id))).size !== page.length || tags.some(value => !page.includes(nativeId(value.Id)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: linked UET tag readback does not match the selected account’s goal references');\n // CustomerShare is a customer-wide graph; this account-linked view exposes installation metadata only.\n return { native_customer_id: scope.customerId!, rows: tags.sort((a, b) => page.indexOf(nativeId(a.Id)) - page.indexOf(nativeId(b.Id))).map(tag => ({ tag: { ...Object.fromEntries(['Name', 'Description', 'TrackingStatus', 'TrackingScript', 'TrackingNoScript'].filter(key => Object.hasOwn(tag, key)).map(key => [key, tag[key]])), Id: nativeId(tag.Id) }, goal_ids: links.get(nativeId(tag.Id))!, native_scope: 'Customer' as const })), truncated, ...(truncated ? { next_cursor: page.at(-1)! } : {}) };\n }\n\n private async tag(account: string, tagId: string): Promise<void> {\n const result = await this.request(account, 'UetTags/QueryByIds', { TagIds: [tagId] });\n const values = rows(result.UetTags);\n if (values.length !== 1 || nativeId(values[0]!.Id) !== tagId) throw new AdportError('INVALID_INPUT', 'microsoft: UET tag is unavailable in the selected native customer/account context');\n }\n\n private async verify(account: string, goalId: string, type: z.infer<typeof supportedType>, expected: Row): Promise<string[]> {\n try { const current = await this.get(account, goalId, type); if (current.goal.Scope !== 'Account' || !current.auto_tagging_enabled || !matches(current.goal, expected)) throw new Error('Goal readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion-goal write was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: [goalId] }); }\n return [goalId];\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n if (op.provider !== 'microsoft' || !MICROSOFT_CONVERSION_WRITES.has(op.tool) || op.kind !== (op.tool === 'microsoft_update_conversion_goal' ? 'update' : 'create')) throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_create_uet_tag') {\n // AddUetTags is customer-scoped: re-resolve parent ownership, even in a long-lived stdio runtime.\n const value = createTag.parse(op.payload), scope = await this.accountScope(account, true), fields = { Name: value.name, ...(value.description ? { Description: value.description } : {}) };\n if (scope.customerId !== value.expected_customer_id) throw new AdportError('INVALID_INPUT', 'microsoft: parent customer changed; read fresh linked-tag context and request a new preview');\n return { summary: `Create Microsoft UET tag \"${value.name}\"`, changes: [`+ uninstalled UET tag in native customer ${scope.customerId} library ${JSON.stringify(fields)}`], fieldChanges: [{ field: 'Name', before: '(new)', after: value.name }, { field: 'Resource scope', before: '(new)', after: 'Customer' }], notes: [`UET tags belong to native customer ${scope.customerId}'s shared library. The new tag is uninstalled and creates no serving campaign, tracking event or account-share update.`, 'Native tags have no pause state. Associate its ID with a paused account-scoped conversion goal, then use microsoft_linked_uet_tags to read its tracking code. Installation is a separate action.', 'This tool creates a new tag only. Customer-wide tag edits, sharing and permanent deletion are not exposed.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(account, 'UetTags', { UetTags: [fields] }), created = rows(result.UetTags), ids = created.map(value => nativeId(value.Id));\n if (created.length !== 1 || !matches(created[0]!, fields)) throw new AdportError('PROVIDER_ERROR', 'microsoft: UET creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n try { const actual = rows((await this.request(account, 'UetTags/QueryByIds', { TagIds: ids })).UetTags); if (actual.length !== 1 || nativeId(actual[0]!.Id) !== ids[0] || !matches(actual[0]!, fields)) throw new Error('UET readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: UET tag was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: ids }); }\n return ids;\n } };\n }\n if (op.tool === 'microsoft_create_conversion_goal') {\n const value = create.parse(op.payload).goal, enabled = await this.autoTagging(account);\n if (value.expected_auto_tagging_enabled !== enabled) throw new AdportError('INVALID_INPUT', 'microsoft: auto-tagging state changed; read fresh conversion context before previewing');\n const existing = await this.query(account, [...standardTypes]);\n if (existing.some(goal => typeof goal.Name === 'string' && goal.Name.toLowerCase() === value.name.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: conversion goal name already exists; do not replay creation');\n if ('tag_id' in value) await this.tag(account, value.tag_id);\n const status = guard.forcePausedCreation ? 'Paused' : value.status;\n const fields: Row = { Type: value.type, Scope: 'Account', Name: value.name, Status: status, GoalCategory: value.goal_category, ExcludeFromBidding: value.exclude_from_bidding, CountType: value.count_type, ConversionWindowInMinutes: value.conversion_window_minutes, Revenue: wireRevenue(value.revenue), ...(value.type === 'OfflineConversion' ? { IsExternallyAttributed: value.is_externally_attributed } : { TagId: value.tag_id }), ...(value.type === 'Url' ? { UrlExpression: value.url_rule.expression, UrlOperator: value.url_rule.operator } : value.type === 'Event' ? eventFields(value.event_conditions) : {}) };\n return { summary: `Create Microsoft ${value.type} goal \"${value.name}\"`, changes: [`+ account-scoped conversion goal ${JSON.stringify(fields)}`, `MSCLKIDAutoTaggingEnabled ${enabled} → true (native side effect)`], fieldChanges: [{ field: 'Name', before: '(new)', after: value.name }, { field: 'Status', before: '(new)', after: status }, { field: 'MSCLKIDAutoTaggingEnabled', before: String(enabled), after: 'true' }], notes, coercions: status !== value.status ? ['Status coerced to Paused by policy (paused_creation)'] : [], budgetDeltas: [], execute: async () => {\n const result = await this.request(account, 'ConversionGoals', { ConversionGoals: [fields] });\n const ids = Array.isArray(result.ConversionGoalIds) ? result.ConversionGoalIds.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1 || existing.some(goal => nativeId(goal.Id) === ids[0])) throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion-goal creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.verify(account, ids[0]!, value.type, fields);\n } };\n }\n const value = update.parse(op.payload), current = await this.get(account, value.goal_id, value.goal_type);\n if (current.goal.Scope !== 'Account') throw new AdportError('INVALID_INPUT', 'microsoft: customer-wide conversion goals require authorization covering every affected account; single-account tools cannot mutate them');\n if (current.snapshot_hash !== value.expected_snapshot_hash) throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal snapshot changed; read fresh context and request a new preview');\n if (value.url_rule && value.goal_type !== 'Url' || value.event_conditions && value.goal_type !== 'Event' || value.is_externally_attributed !== undefined && value.goal_type !== 'OfflineConversion') throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal subtype fields mismatch');\n const fields: Row = {};\n for (const [key, field] of [['name', 'Name'], ['goal_category', 'GoalCategory'], ['status', 'Status'], ['exclude_from_bidding', 'ExcludeFromBidding'], ['count_type', 'CountType'], ['conversion_window_minutes', 'ConversionWindowInMinutes'], ['is_externally_attributed', 'IsExternallyAttributed']] as const) if (value[key] !== undefined && value[key] !== current.goal[field]) fields[field] = value[key];\n if (value.revenue) fields.Revenue = wireRevenue(value.revenue);\n if (value.url_rule) Object.assign(fields, { UrlExpression: value.url_rule.expression, UrlOperator: value.url_rule.operator });\n if (value.event_conditions) Object.assign(fields, eventFields(value.event_conditions));\n const changed = Object.entries(fields).filter(([key, value]) => !matches(current.goal, { [key]: value }));\n if (!changed.length) throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal update has no changes');\n // Native EventGoal updates delete any omitted criterion pair, even when only changing name/status.\n if (value.goal_type === 'Event' && !value.event_conditions) for (const [expression, operator] of pairs) {\n const expressionValue = current.goal[expression], operatorValue = current.goal[operator];\n if ((expressionValue === null || expressionValue === undefined) !== (operatorValue === null || operatorValue === undefined)) throw new AdportError('INVALID_INPUT', 'microsoft: existing event condition is incomplete; refusing a partial update');\n fields[expression] = expressionValue ?? null; fields[operator] = operatorValue ?? null;\n }\n const fieldChanges = changed.map(([field, after]) => ({ field, before: JSON.stringify(current.goal[field] ?? null), after: JSON.stringify(after) }));\n return { summary: `Update Microsoft ${value.goal_type} goal \"${String(current.goal.Name)}\"`, changes: [`~ goal ${value.goal_id} ${JSON.stringify(fields)}`, `MSCLKIDAutoTaggingEnabled ${current.auto_tagging_enabled} → true (native side effect)`], fieldChanges: [...fieldChanges, { field: 'MSCLKIDAutoTaggingEnabled', before: String(current.auto_tagging_enabled), after: 'true' }], notes, coercions: [], budgetDeltas: [], execute: async () => { await this.request(account, 'ConversionGoals', { ConversionGoals: [{ Id: value.goal_id, Type: value.goal_type, ...fields }] }, 'PUT'); return this.verify(account, value.goal_id, value.goal_type, { ...fields, Status: fields.Status ?? current.goal.Status }); } };\n }\n}\n\nexport function microsoftConversionTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_linked_uet_tags', namespace: 'microsoft', description: 'Read current native_customer_id plus UET metadata/code only for tags referenced by selected-account goals. Tags are customer-scoped; the entire library and sharing graph are not exposed. Continue next_cursor as after_tag_id.', input: z.object({ account_id: id, after_tag_id: id.optional(), limit: z.number().int().positive().max(100).default(50) }), output: z.object({ native_customer_id: id, rows: z.array(z.object({ tag: z.record(z.string(), z.unknown()), goal_ids: z.array(id), native_scope: z.literal('Customer') })), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_tag_id' }, annotations: { readOnly: true }, handler: input => provider.conversions.linkedTags(input) }),\n guardedWriteTool({ name: 'microsoft_create_uet_tag', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create one uninstalled UET tag in the selected account’s native customer library. Requires expected_customer_id from linked-tag reads; rechecks current parent ownership. Returns its ID for paused goal setup. No installation or event sending; tags have no pause state.', payload: createTag }),\n defineTool({ name: 'microsoft_conversion_goals', namespace: 'microsoft', description: 'Read account-associated native goals, tracking state, configuration hashes and account-level click-ID auto-tagging. Default excludes pilot-only InStoreTransaction, whose inclusion can reject the entire query. Continue next_cursor as after_goal_id.', input: z.object({ account_id: id, goal_types: z.array(goalType).min(1).refine(value => new Set(value).size === value.length, 'Goal types must be unique').default([...standardTypes]), after_goal_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ account_id: id, rows: z.array(view), auto_tagging_enabled: z.boolean(), auto_tagging_scope: z.literal('Account'), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_goal_id' }, annotations: { readOnly: true }, handler: input => provider.conversions.list(input) }),\n defineTool({ name: 'microsoft_get_conversion_goal', namespace: 'microsoft', description: 'Read one account-associated native goal and snapshot_hash. TrackingStatus is system-owned and excluded from the configuration hash. Customer-scoped goals cannot be edited through single-account tools.', input: z.object({ account_id: id, goal_id: id, goal_type: goalType }), output: view, annotations: { readOnly: true }, handler: input => provider.conversions.get(input.account_id, input.goal_id, input.goal_type) }),\n guardedWriteTool({ name: 'microsoft_create_conversion_goal', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create an account-scoped URL, Event or OfflineConversion goal. Defaults Paused and excluded from bidding. Native add automatically enables click-ID auto-tagging; supply its expected state from conversion-goal reads. Does not install tracking or send events. Goals cannot be permanently deleted through this API.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_conversion_goal', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit an Account-scoped URL/Event/Offline goal with expected_snapshot_hash. Preserves omitted event criteria, status and other optional settings. Native update enables click-ID auto-tagging. Event conditions, when supplied, replace the full condition set. Use Paused to stop tracking; Deleted is internal-only.', payload: update }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nexport const microsoftAudienceType = z.enum(['RemarketingList', 'Custom', 'InMarket', 'Product', 'SimilarRemarketingList', 'CombinedList', 'CustomerList', 'ImpressionBasedRemarketingList', 'CustomSegment']);\nconst audienceType = microsoftAudienceType;\nconst standardTypes = audienceType.options.filter(value => value !== 'CustomSegment');\nconst name = z.string().min(1).max(128).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst description = z.string().max(1024);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst stringOperator = z.enum(['Equals', 'Contains', 'BeginsWith', 'EndsWith', 'NotEquals', 'DoesNotContain', 'DoesNotBeginWith', 'DoesNotEndWith']);\nconst numberOperator = z.enum(['Equals', 'GreaterThan', 'LessThan', 'GreaterThanEqualTo', 'LessThanEqualTo', 'NotEquals']);\nconst groups = z.array(z.object({ items: z.array(z.object({ operand: z.enum(['Url', 'ReferrerUrl']), operator: stringOperator, value: z.string().min(1) })).min(1).max(100) })).min(1).max(100);\nconst eventExpression = z.object({ operator: stringOperator, text: z.string().min(1) });\nconst rule = z.discriminatedUnion('type', [\n z.object({ type: z.literal('PageVisitors'), normal_form: z.enum(['Conjunctive', 'Disjunctive']).default('Disjunctive'), groups }),\n z.object({ type: z.literal('PageVisitorsWhoVisitedAnotherPage'), groups, another_groups: groups }),\n z.object({ type: z.literal('PageVisitorsWhoDidNotVisitAnotherPage'), include_groups: groups, exclude_groups: groups }),\n z.object({ type: z.literal('CustomEvents'), action: eventExpression.optional(), category: eventExpression.optional(), label: eventExpression.optional(), value: z.object({ operator: numberOperator, amount: z.number().int().positive() }).optional() }).refine(value => Object.values(value).some(value => value !== undefined && value !== 'CustomEvents'), 'At least one complete event condition is required'),\n]);\nconst create = z.object({ name, description: description.optional(), membership_duration_days: z.number().int().min(1).max(180).default(30), tag_id: id, rule });\nconst reference = z.object({ audience_id: id, expected_snapshot_hash: hash });\nconst update = reference.extend({ name: name.optional(), description: description.optional(), membership_duration_days: z.number().int().min(1).max(180).optional(), tag_id: id.optional(), rule: rule.optional() }).refine(value => Object.entries(value).some(([key, value]) => !['audience_id', 'expected_snapshot_hash'].includes(key) && value !== undefined), 'Supply an editable field');\nconst view = z.object({ account_id: id, audience: z.record(z.string(), z.unknown()), shared: z.boolean(), snapshot_hash: hash });\nconst notes = ['Remarketing lists have no independent pause state. Creation is account-scoped and unattached; it does not install UET, send events or upload customer records.', 'Omitted rules and tag settings are preserved. Supplying a rule replaces its entire condition set. Conjunctive means OR within each group, AND across groups; Disjunctive means AND within each group, OR across groups.', 'Audience changes can affect existing targeting and exclusions in the selected account. Configuration hashes detect drift before submission; Microsoft has no atomic compare-and-set. Customer scope and sharing changes are not exposed.'];\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nfunction matches(actual: unknown, expected: unknown): boolean {\n if (expected === null || expected === undefined) return actual === null || actual === undefined;\n if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => matches(actual[index], value));\n if (typeof expected === 'object') {\n if (actual === null || typeof actual !== 'object') return false;\n if ((expected as Row).Type === 'CustomEvents') {\n for (const field of ['Action', 'Category', 'Label', 'Value']) if (!Object.hasOwn(expected, field) && ![undefined, null, 'None'].includes((actual as Row)[`${field}Operator`] as undefined | null | string)) return false;\n }\n return Object.entries(expected).every(([key, value]) => matches((actual as Row)[key], value));\n }\n return String(actual) === String(expected);\n}\nconst nativeGroups = (value: z.infer<typeof groups>) => value.map(group => ({ Items: group.items.map(item => ({ Type: 'String', Operand: item.operand, Operator: item.operator, Value: item.value })) }));\nfunction nativeRule(value: z.infer<typeof rule>): Row {\n if (value.type === 'PageVisitors') return { Type: value.type, NormalForm: value.normal_form, RuleItemGroups: nativeGroups(value.groups) };\n if (value.type === 'PageVisitorsWhoVisitedAnotherPage') return { Type: value.type, RuleItemGroups: nativeGroups(value.groups), AnotherRuleItemGroups: nativeGroups(value.another_groups) };\n if (value.type === 'PageVisitorsWhoDidNotVisitAnotherPage') return { Type: value.type, IncludeRuleItemGroups: nativeGroups(value.include_groups), ExcludeRuleItemGroups: nativeGroups(value.exclude_groups) };\n const result: Row = { Type: value.type };\n for (const [key, field] of [['action', 'Action'], ['category', 'Category'], ['label', 'Label'], ['value', 'Value']] as const) { const condition = value[key]; if (condition) { result[field] = 'text' in condition ? condition.text : condition.amount; result[`${field}Operator`] = condition.operator; } }\n return result;\n}\nexport const MICROSOFT_AUDIENCE_WRITES = new Set(['microsoft_create_remarketing_list', 'microsoft_update_remarketing_list', 'microsoft_delete_remarketing_list']);\n\n/** Campaign Management v13: explicit Account ownership, replacement-rule semantics and bounded deletion-use checks. */\nexport class MicrosoftAudienceService extends MicrosoftNativeService {\n constructor(...args: [...ConstructorParameters<typeof MicrosoftNativeService>, (account: string) => Promise<unknown[]>]) {\n const [client, scope, campaign, campaigns] = args; super(client, scope, campaign); this.campaigns = campaigns;\n }\n private readonly campaigns: (account: string) => Promise<unknown[]>;\n\n private async query(account: string, types: z.infer<typeof audienceType>[], ids: string[] | null = null): Promise<Row[]> {\n const result = await this.request(account, 'Audiences/QueryByIds', { AudienceIds: ids, Type: types.join(', '), ReturnAdditionalFields: 'NormalForm, NumberRuleItem, ImpressionBasedRemarketingList, CampaignIdsAdGroupIds' });\n if (!Object.hasOwn(result, 'Audiences')) throw new AdportError('PROVIDER_ERROR', 'microsoft: native audience response envelope is missing');\n const values = rows(result.Audiences);\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => !types.includes(audienceType.parse(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: native audience identities or types mismatch');\n return values;\n }\n\n private shared(value: Row): boolean {\n return value.CustomerShare !== null && value.CustomerShare !== undefined && rows(row(value.CustomerShare).CustomerAccountShares).length > 0;\n }\n\n private snapshot(account: string, value: Row) {\n const { SearchSize: _search, AudienceNetworkSize: _network, SupportedCampaignTypes: _supported, ...configuration } = value;\n const { CustomerShare: _sharing, ...audience } = value;\n return { account_id: account, audience, shared: this.shared(value), snapshot_hash: createHash('sha256').update(JSON.stringify(canonical({ account, configuration }))).digest('hex') };\n }\n\n async list(input: { account_id: string; audience_types: z.infer<typeof audienceType>[]; after_audience_id?: string; limit: number }) {\n const values = (await this.query(input.account_id, input.audience_types)).filter(value => !input.after_audience_id || BigInt(nativeId(value.Id)) > BigInt(input.after_audience_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = values.slice(0, input.limit), truncated = values.length > page.length;\n return { rows: page.map(value => this.snapshot(input.account_id, value)), truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n private async find(account: string, audience: string, type: z.infer<typeof audienceType>): Promise<Row> {\n const found = (await this.query(account, [type], [audience])).find(value => nativeId(value.Id) === audience);\n if (!found) throw new AdportError('INVALID_INPUT', 'microsoft: audience was not found for the selected account/type');\n return found;\n }\n\n async get(account: string, audience: string, type: z.infer<typeof audienceType>) { id.parse(audience); return this.snapshot(account, await this.find(account, audience, type)); }\n\n private async owned(account: string, audience: string): Promise<Row> {\n await this.accountScope(account, true);\n const current = await this.find(account, audience, 'RemarketingList');\n if (current.Scope !== 'Account' || nativeId(current.ParentId) !== account || this.shared(current)) throw new AdportError('INVALID_INPUT', 'microsoft: remarketing mutations require an unshared Account-scoped list owned by the selected account');\n return current;\n }\n\n private async tag(account: string, tag: string) {\n const result = await this.request(account, 'UetTags/QueryByIds', { TagIds: [tag] }), values = rows(result.UetTags);\n if (values.length !== 1 || nativeId(values[0]!.Id) !== tag) throw new AdportError('INVALID_INPUT', 'microsoft: UET tag is unavailable in the selected customer/account context');\n }\n\n async usage(account: string, audience: string) {\n await this.owned(account, audience);\n const lists = await this.query(account, ['SimilarRemarketingList', 'CombinedList']), derivedLists = lists.filter(value => value.Type === 'SimilarRemarketingList' && String(value.SourceId) === audience);\n if (derivedLists.some(value => value.Scope !== 'Account' || nativeId(value.ParentId) !== account || this.shared(value))) throw new AdportError('INVALID_INPUT', 'microsoft: a derived similar audience has wider or unverifiable ownership/sharing; single-account deletion use check is incomplete');\n const derived = derivedLists.map(value => nativeId(value.Id)), ids = [audience, ...derived];\n const combined = lists.filter(value => value.Type === 'CombinedList' && rows(value.CombinationRules).some(rule => Array.isArray(rule.AudienceIds) && rule.AudienceIds.some(value => ids.includes(nativeId(value))))).map(value => nativeId(value.Id));\n const groupsResult = await this.request(account, 'AudienceGroups/QueryByIds', { AudienceGroupIds: null });\n if (!Object.hasOwn(groupsResult, 'AudienceGroups')) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience-signal inventory is unavailable; deletion use check is incomplete');\n const signals = rows(groupsResult.AudienceGroups);\n if (signals.length >= 100) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience-signal inventory reached the documented result boundary; deletion use check is incomplete');\n const signalIds = signals.filter(value => rows(value.Dimensions).some(dimension => dimension.Type === 'Audience' && rows(dimension.Audiences).some(value => ids.includes(nativeId(value.Id))))).map(value => nativeId(value.Id));\n const campaigns = rows(await this.campaigns(account)), associations: Row[] = [];\n if (campaigns.length > 200) throw new AdportError('INVALID_INPUT', 'microsoft: audience use check exceeds 200 campaigns; no deletion was submitted');\n let groupCount = 0;\n for (const campaign of campaigns) {\n if (!['Search', 'Audience', 'DynamicSearchAds', 'Shopping', 'PerformanceMax'].includes(String(campaign.CampaignType))) throw new AdportError('INVALID_INPUT', 'microsoft: audience use check encountered an unsupported campaign type; no deletion was submitted');\n const campaignId = nativeId(campaign.Id);\n let groups: Row[] = [];\n // Performance Max uses audience signals and negative campaign criteria, without ordinary ad groups.\n if (campaign.CampaignType !== 'PerformanceMax') {\n const result = await this.request(account, 'AdGroups/QueryByCampaignId', { CampaignId: campaignId });\n if (!Object.hasOwn(result, 'AdGroups')) throw new AdportError('PROVIDER_ERROR', 'microsoft: ad-group inventory is unavailable; audience use check is incomplete');\n groups = rows(result.AdGroups);\n }\n groupCount += groups.length;\n if (groupCount > 2000) throw new AdportError('INVALID_INPUT', 'microsoft: audience use check exceeds 2000 ad groups; no deletion was submitted');\n for (const type of ['RemarketingList', ...(derived.length ? ['SimilarRemarketingList'] : [])]) {\n for (const group of [undefined, ...groups]) {\n const prefix = group ? 'AdGroup' : 'Campaign', parentId = group ? nativeId(group.Id) : campaignId;\n const result = await this.request(account, `${prefix}Criterions/QueryByIds`, { [`${prefix}Id`]: parentId, [`${prefix}CriterionIds`]: null, CriterionType: type });\n if (!Object.hasOwn(result, `${prefix}Criterions`)) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience association response is unavailable; use check is incomplete');\n for (const criterion of rows(result[`${prefix}Criterions`])) {\n // The REST JSON contract says AudienceCriterion; the inherited Type table says Audience.\n if (nativeId(criterion[`${prefix}Id`]) !== parentId || !['AudienceCriterion', 'Audience'].includes(String(row(criterion.Criterion).Type)) || row(criterion.Criterion).AudienceType !== type) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience association ownership/type mismatch');\n if (ids.includes(nativeId(row(criterion.Criterion).AudienceId)) && criterion.Status !== 'Deleted') associations.push({ campaign_id: campaignId, ...(group ? { ad_group_id: parentId } : {}), criterion });\n }\n }\n }\n }\n return { audience_id: audience, derived_audience_ids: derived, associations, combined_list_ids: combined, audience_signal_ids: signalIds, campaigns_scanned: campaigns.length, ad_groups_scanned: groupCount, complete: true as const };\n }\n\n private async confirm(account: string, audience: string, expected: Row) {\n try { const actual = await this.owned(account, audience); if (!matches(actual, expected)) throw new Error('Audience readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: audience write was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: [audience] }); }\n return [audience];\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_create_remarketing_list' ? 'create' : op.tool === 'microsoft_delete_remarketing_list' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_AUDIENCE_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: audience operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_create_remarketing_list') {\n const input = create.parse(op.payload); await this.accountScope(account, true); await this.tag(account, input.tag_id);\n if ((await this.query(account, ['RemarketingList'])).some(value => String(value.Name).toLowerCase() === input.name.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: a remarketing list with this name already exists');\n const fields = { Type: 'RemarketingList', Scope: 'Account', ParentId: account, Name: input.name, MembershipDuration: input.membership_duration_days, TagId: input.tag_id, Rule: nativeRule(input.rule), ...(input.description !== undefined ? { Description: input.description } : {}) };\n return { summary: `Create Microsoft remarketing list \"${input.name}\"`, changes: [`+ ${JSON.stringify(fields)}`], notes, coercions: [], budgetDeltas: [], fieldChanges: [{ field: 'Name', before: '(new)', after: input.name }, { field: 'Scope', before: '(new)', after: 'Account' }, { field: 'Rule', before: '(new)', after: JSON.stringify(fields.Rule) }], execute: async () => {\n const result = await this.request(account, 'Audiences', { Audiences: [fields] }), ids = Array.isArray(result.AudienceIds) ? result.AudienceIds.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.confirm(account, ids[0]!, fields);\n } };\n }\n const input = (op.kind === 'remove' ? reference : update).parse(op.payload), current = await this.owned(account, input.audience_id);\n if (this.snapshot(account, current).snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience configuration snapshot changed; request a fresh preview');\n if (op.kind === 'remove') {\n const usage = await this.usage(account, input.audience_id);\n if (usage.associations.length || usage.combined_list_ids.length || usage.audience_signal_ids.length) throw new AdportError('INVALID_INPUT', 'microsoft: audience or derived similar audience is referenced; remove its targeting, combined-list and signal references before deleting');\n return { summary: `Delete Microsoft remarketing list ${input.audience_id}`, changes: [`- ${JSON.stringify(this.snapshot(account, current).audience)}`, `Also deletes derived similar lists: ${JSON.stringify(usage.derived_audience_ids)}. No campaign/ad-group, combined-list or audience-signal references were found in the bounded account scan.`], notes: ['Deletion is permanent. Use checks are repeated before submission; native concurrent association changes cannot be locked.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, 'Audiences', { AudienceIds: [input.audience_id] }, 'DELETE');\n try { const remaining = await this.query(account, ['RemarketingList', 'SimilarRemarketingList']); if (remaining.some(value => [input.audience_id, ...usage.derived_audience_ids].includes(nativeId(value.Id)))) throw new Error('Audience still present'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: audience deletion readback was not confirmed; reconcile before retrying', { resourceIds: [input.audience_id, ...usage.derived_audience_ids] }); }\n return [input.audience_id, ...usage.derived_audience_ids];\n } };\n }\n const value = update.parse(input), fields: Row = { Id: value.audience_id, Type: 'RemarketingList' };\n for (const [key, field] of [['name', 'Name'], ['description', 'Description'], ['membership_duration_days', 'MembershipDuration'], ['tag_id', 'TagId']] as const) if (value[key] !== undefined) fields[field] = value[key];\n if (value.tag_id) await this.tag(account, value.tag_id);\n if (value.rule) fields.Rule = nativeRule(value.rule);\n const expected = Object.fromEntries(Object.entries({ ...current, ...fields }).filter(([key]) => !['CustomerShare', 'SearchSize', 'AudienceNetworkSize', 'SupportedCampaignTypes'].includes(key)));\n return { summary: `Update Microsoft remarketing list ${value.audience_id}`, changes: [`~ ${JSON.stringify(fields)}`], fieldChanges: Object.entries(fields).filter(([key]) => !['Id', 'Type'].includes(key)).map(([field, value]) => ({ field, before: typeof current[field] === 'object' ? JSON.stringify(current[field]) : String(current[field] ?? '(unset)'), after: typeof value === 'object' ? JSON.stringify(value) : String(value) })), notes, coercions: [], budgetDeltas: [], execute: async () => { await this.request(account, 'Audiences', { Audiences: [fields] }, 'PUT'); return this.confirm(account, value.audience_id, expected); } };\n }\n}\n\nexport function microsoftAudienceTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_audiences', namespace: 'microsoft', description: 'Read account-associated native audiences with configuration hashes. Preserves unavailable sizes. Sharing graphs are omitted; shared is reported. System-generated visitor/converter/Smart lists are not supported by this API. CustomSegment is opt-in; reserved AIPrompt is excluded. Continue next_cursor as after_audience_id.', input: z.object({ account_id: id, audience_types: z.array(audienceType).min(1).refine(value => new Set(value).size === value.length, 'Audience types must be unique').default(standardTypes), after_audience_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ rows: z.array(view), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_audience_id' }, annotations: { readOnly: true }, handler: input => provider.audiences.list(input) }),\n defineTool({ name: 'microsoft_get_audience', namespace: 'microsoft', description: 'Read one account-associated native audience and snapshot_hash. Customer-scoped or shared lists are readable but cannot be changed by single-account remarketing tools. System-owned sizes are excluded from the hash.', input: z.object({ account_id: id, audience_id: id, audience_type: audienceType }), output: view, annotations: { readOnly: true }, handler: input => provider.audiences.get(input.account_id, input.audience_id, input.audience_type) }),\n defineTool({ name: 'microsoft_audience_usage', namespace: 'microsoft', description: 'Check an owned unshared Account remarketing list and its derived similar lists for campaign/ad-group criteria, combined-list and audience-signal references. Bounded to 200 campaigns, 2000 ad groups and fewer than 100 signals; incomplete/unsupported scans fail closed.', input: z.object({ account_id: id, audience_id: id }), annotations: { readOnly: true }, handler: input => provider.audiences.usage(input.account_id, input.audience_id) }),\n guardedWriteTool({ name: 'microsoft_create_remarketing_list', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create one unattached Account-scoped remarketing list using an available UET tag and PageVisitors, visited-another-page, excluded-page or CustomEvents rule. No pause state, installation, event sending or customer-record upload. Membership is 1..180 days.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_remarketing_list', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit an owned unshared Account remarketing list with expected_snapshot_hash. Preserves omitted rule/tag/settings; supplying rule replaces its entire condition set. Scope/parent/sharing are immutable here. Existing audience targeting and exclusions can be affected.', payload: update }),\n guardedWriteTool({ name: 'microsoft_delete_remarketing_list', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', destructive: true, description: 'Permanently delete an owned unshared Account remarketing list and its derived similar lists. Requires expected_snapshot_hash and a complete bounded scan with no targeting, combined-list or signal references. Confirms disappearance; never retries an uncertain deletion.', payload: reference }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { microsoftAudienceType } from './audiences.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst audienceType = microsoftAudienceType.exclude(['CustomSegment']);\nconst selectors = { Custom: 'CustomAudience', InMarket: 'InMarketAudience', Product: 'ProductAudience', RemarketingList: 'RemarketingList', SimilarRemarketingList: 'SimilarRemarketingList', CombinedList: 'CombinedList', CustomerList: 'CustomerList', ImpressionBasedRemarketingList: 'ImpressionBasedRemarketingList' } as const;\nconst target = z.discriminatedUnion('type', [z.object({ type: z.literal('Campaign'), campaign_id: id }), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id })]);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), adjustment = z.number().int().min(-90).max(900);\nconst add = z.object({ target, audience_id: id, audience_type: audienceType, expected_audience_snapshot_hash: hash, exclude: z.boolean().default(false), bid_adjustment_percent: adjustment.optional(), expected_target_and_bid: z.boolean().optional() }).superRefine((value, ctx) => {\n if (value.exclude && (value.bid_adjustment_percent !== undefined || value.expected_target_and_bid !== undefined)) ctx.addIssue({ code: 'custom', message: 'Exclusions have no bid adjustment and are independent of positive target mode' });\n if (!value.exclude && value.expected_target_and_bid === undefined) ctx.addIssue({ code: 'custom', message: 'Positive associations require expected_target_and_bid from microsoft_audience_targets' });\n});\nconst reference = z.object({ target, audience_type: audienceType, criterion_id: id, expected_snapshot_hash: hash });\nconst bid = reference.extend({ bid_adjustment_percent: adjustment });\nconst mode = z.object({ target, expected_context_hash: hash, target_and_bid: z.boolean() });\nconst context = z.object({ account_id: id, target, campaign_status: z.string(), ad_group_status: z.string().optional(), target_and_bid: z.boolean(), audience_target_option: z.enum(['TargetAndBid', 'BidOnly']), context_hash: hash });\ntype Target = z.infer<typeof target>;\ntype AudienceType = z.infer<typeof audienceType>;\ntype Source = { audience: Row; snapshot_hash: string };\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst prefix = (value: Target) => value.type;\nconst entityId = (value: Target) => value.type === 'Campaign' ? value.campaign_id : value.ad_group_id;\nconst isTargetSetting = (value: Row) => ['Target', 'TargetSetting'].includes(String(value.Type));\nconst orderedDetails = (value: Row[]) => [...value].sort((a, b) => String(a.CriterionTypeGroup).localeCompare(String(b.CriterionTypeGroup)));\nconst notices = ['Audience criteria have native Active status, without an independent pause. Default paused_creation requires an effectively paused parent for new associations.', 'Positive audiences can be associated at campaign or ad-group level, but not both within one campaign. Exclusions can exist at both levels and Microsoft applies their union.', 'TargetAndBid restricts positive audience delivery; BidOnly adjusts bids without adding that restriction. Exclusions apply regardless. Automated bidding can treat bid percentages as signals. Snapshots detect changes before submission; Microsoft has no atomic compare-and-set.'];\nexport const MICROSOFT_AUDIENCE_TARGETING_WRITES = new Set(['microsoft_add_audience_target', 'microsoft_set_audience_target_bid', 'microsoft_remove_audience_target', 'microsoft_set_audience_target_mode']);\n\n/** Audience selector on mutations; concrete native selectors on reads. TargetSetting.Details updates replace the complete list. */\nexport class MicrosoftAudienceTargetingService extends MicrosoftNativeService {\n constructor(...args: [...ConstructorParameters<typeof MicrosoftNativeService>, (account: string, audience: string, type: AudienceType) => Promise<Source>]) {\n const [client, scope, campaign, source] = args; super(client, scope, campaign); this.source = source;\n }\n private readonly source: (account: string, audience: string, type: AudienceType) => Promise<Source>;\n\n private async entity(account: string, value: Target, refresh = false) {\n await this.accountScope(account, refresh);\n const known = await this.campaign(account, value.campaign_id);\n const result = await this.request(account, 'Campaigns/QueryByIds', { AccountId: account, CampaignIds: [value.campaign_id], CampaignType: known.CampaignType, ReturnAdditionalFields: 'TargetSetting' }), campaigns = rows(result.Campaigns);\n if (campaigns.length !== 1 || nativeId(campaigns[0]!.Id) !== value.campaign_id || campaigns[0]!.CampaignType !== known.CampaignType || typeof campaigns[0]!.Status !== 'string') throw new AdportError('PROVIDER_ERROR', 'microsoft: audience target campaign context is unavailable or mismatched');\n const campaign = campaigns[0]!;\n let group: Row | undefined;\n if (value.type === 'AdGroup') {\n if (campaign.CampaignType === 'PerformanceMax') throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max audiences use campaign exclusions or asset-group signals, not ordinary ad-group criteria');\n const groups = rows((await this.request(account, 'AdGroups/QueryByIds', { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id], ReturnAdditionalFields: 'AdGroupType' })).AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== value.ad_group_id || typeof groups[0]!.Status !== 'string') throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n group = groups[0]!;\n }\n const entity = group ?? campaign, settings = rows(entity.Settings), targetSettings = settings.filter(isTargetSetting);\n if (targetSettings.length > 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate target settings in the selected entity');\n const details = orderedDetails(rows(targetSettings[0]?.Details));\n if (details.some(value => typeof value.CriterionTypeGroup !== 'string' || typeof value.TargetAndBid !== 'boolean') || new Set(details.map(value => value.CriterionTypeGroup)).size !== details.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: target-setting details are incomplete or duplicated');\n const targetAndBid = details.find(value => value.CriterionTypeGroup === 'Audience')?.TargetAndBid === true;\n const visible = { account_id: account, target: value, campaign_status: campaign.Status, ...(group ? { ad_group_status: String(group.Status) } : {}), target_and_bid: targetAndBid, audience_target_option: targetAndBid ? 'TargetAndBid' as const : 'BidOnly' as const };\n return { campaign, group, entity, settings, targetSettings, details, context: { ...visible, context_hash: digest({ ...visible, targetSettings }) } };\n }\n\n private async query(account: string, value: Target, type: AudienceType) {\n const kind = prefix(value), result = await this.request(account, `${kind}Criterions/QueryByIds`, { [`${kind}Id`]: entityId(value), [`${kind}CriterionIds`]: null, CriterionType: selectors[type] });\n if (!Object.hasOwn(result, `${kind}Criterions`)) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience criterion response envelope is missing');\n const values = rows(result[`${kind}Criterions`]);\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(criterion => nativeId(criterion[`${kind}Id`]) !== entityId(value) || ![`Biddable${kind}Criterion`, `Negative${kind}Criterion`].includes(String(criterion.Type)) || !['Audience', 'AudienceCriterion'].includes(String(row(criterion.Criterion).Type)) || row(criterion.Criterion).AudienceType !== type)) throw new AdportError('PROVIDER_ERROR', 'microsoft: native audience criterion ownership or type mismatch');\n return values.filter(value => value.Status !== 'Deleted');\n }\n\n private snapshot(value: Row, contextHash: string) { return digest({ contextHash, value }); }\n\n async list(input: { account_id: string; target: Target; audience_type: AudienceType; after_criterion_id?: string; limit: number }) {\n const current = await this.entity(input.account_id, input.target), values = (await this.query(input.account_id, input.target, input.audience_type)).filter(value => !input.after_criterion_id || BigInt(nativeId(value.Id)) > BigInt(input.after_criterion_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = values.slice(0, input.limit), truncated = values.length > page.length;\n return { context: current.context, rows: page.map(value => ({ criterion: value, snapshot_hash: this.snapshot(value, current.context.context_hash) })), truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n private async all(account: string, value: Target) {\n const results: Row[] = [];\n for (let i = 0; i < audienceType.options.length; i += 4) results.push(...(await Promise.all(audienceType.options.slice(i, i + 4).map(type => this.query(account, value, type)))).flat());\n return results;\n }\n\n private async exclusive(account: string, value: Target) {\n let opposite: Target[];\n if (value.type === 'AdGroup') opposite = [{ type: 'Campaign', campaign_id: value.campaign_id }];\n else {\n const result = await this.request(account, 'AdGroups/QueryByCampaignId', { CampaignId: value.campaign_id });\n if (!Object.hasOwn(result, 'AdGroups')) throw new AdportError('PROVIDER_ERROR', 'microsoft: opposite-level audience check lacks the ad-group inventory');\n const groups = rows(result.AdGroups);\n if (groups.length > 50 || new Set(groups.map(value => nativeId(value.Id))).size !== groups.length) throw new AdportError('INVALID_INPUT', 'microsoft: opposite-level audience check exceeds 50 ad groups or contains duplicate IDs; no association submitted');\n opposite = groups.map(group => ({ type: 'AdGroup', campaign_id: value.campaign_id, ad_group_id: nativeId(group.Id) }));\n }\n for (const entity of opposite) if ((await this.all(account, entity)).some(value => String(value.Type).startsWith('Biddable'))) throw new AdportError('INVALID_INPUT', 'microsoft: positive audience targets already exist at the opposite campaign/ad-group level; remove them before changing levels');\n }\n\n private async confirm(ids: string[], check: () => Promise<boolean>) {\n try { if (await check()) return ids; } catch { /* Accepted writes are never replayed to repair an uncertain readback. */ }\n throw new AdportError('PROVIDER_ERROR', 'microsoft: audience targeting write was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: ids });\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_add_audience_target' ? 'create' : op.tool === 'microsoft_remove_audience_target' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_AUDIENCE_TARGETING_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: audience targeting operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_set_audience_target_mode') {\n const input = mode.parse(op.payload), current = await this.entity(account, input.target, true);\n if (current.campaign.CampaignType === 'PerformanceMax') throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max does not support TargetSetting; use campaign exclusions or asset-group signals');\n if (current.context.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience parent context changed; request a fresh preview');\n if (current.targetSettings.some(setting => Object.entries(setting).some(([key, value]) => !['Type', 'Details'].includes(key) && value !== null && value !== undefined))) throw new AdportError('INVALID_INPUT', 'microsoft: an unsupported target-setting property prevents a safe replacement');\n const details = orderedDetails([...current.details.filter(value => value.CriterionTypeGroup !== 'Audience'), ...(input.target_and_bid ? [{ CriterionTypeGroup: 'Audience', TargetAndBid: true }] : [])]), fields = { Id: entityId(input.target), Settings: [{ Type: 'TargetSetting', Details: details.length ? details : null }] };\n const body = input.target.type === 'Campaign' ? { AccountId: account, Campaigns: [fields] } : { CampaignId: input.target.campaign_id, AdGroups: [fields] };\n return { summary: `Set Microsoft ${input.target.type} \"${String(current.entity.Name ?? entityId(input.target))}\" audience delivery option`, changes: [`~ ${JSON.stringify(fields)}`, 'Applies to every positive audience on this entity. Other target groups and other settings are preserved; exclusions and serving status are unchanged.'], fieldChanges: [{ field: 'Audience delivery option', before: current.context.audience_target_option, after: input.target_and_bid ? 'TargetAndBid' : 'BidOnly' }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, input.target.type === 'Campaign' ? 'Campaigns' : 'AdGroups', body, 'PUT');\n return this.confirm([entityId(input.target)], async () => { const after = await this.entity(account, input.target); return after.context.target_and_bid === input.target_and_bid && digest(after.details.filter(value => value.CriterionTypeGroup !== 'Audience')) === digest(current.details.filter(value => value.CriterionTypeGroup !== 'Audience')) && digest(after.settings.filter(value => !isTargetSetting(value))) === digest(current.settings.filter(value => !isTargetSetting(value))) && after.context.campaign_status === current.context.campaign_status && after.context.ad_group_status === current.context.ad_group_status; });\n } };\n }\n if (op.tool === 'microsoft_add_audience_target') {\n const input = add.parse(op.payload), current = await this.entity(account, input.target, true), source = await this.source(account, input.audience_id, input.audience_type);\n if (source.snapshot_hash !== input.expected_audience_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience definition changed; read its current snapshot and request a fresh preview');\n if (current.campaign.CampaignType === 'PerformanceMax' && !input.exclude) throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max audience criteria support exclusions only; positive audiences use asset-group signals');\n if (guard.forcePausedCreation && current.campaign.Status !== 'Paused' && current.group?.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: audience criteria are natively Active; paused_creation requires a paused campaign or ad group');\n if (!input.exclude && current.context.target_and_bid !== input.expected_target_and_bid) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience target mode changed; request a fresh preview');\n if ((await this.query(account, input.target, input.audience_type)).some(value => nativeId(row(value.Criterion).AudienceId) === input.audience_id)) throw new AdportError('INVALID_INPUT', 'microsoft: this audience is already associated or excluded at the selected level');\n if (!input.exclude) await this.exclusive(account, input.target);\n const kind = prefix(input.target), percent = input.bid_adjustment_percent ?? 0, fields = { [`${kind}Id`]: entityId(input.target), Type: `${input.exclude ? 'Negative' : 'Biddable'}${kind}Criterion`, Criterion: { Type: 'AudienceCriterion', AudienceId: input.audience_id }, ...(!input.exclude ? { CriterionBid: { Type: 'BidMultiplier', Multiplier: percent } } : {}) };\n return { summary: `${input.exclude ? 'Exclude' : 'Associate'} Microsoft audience \"${String(source.audience.Name ?? input.audience_id)}\"`, changes: [`+ ${JSON.stringify(fields)}`, `Parent audience delivery option remains ${current.context.audience_target_option}. No source-definition, target-mode or parent-status changes.`], fieldChanges: [{ field: 'Audience', before: '(unattached)', after: `${String(source.audience.Name ?? '')} (${input.audience_id})` }, { field: 'Parent', before: '(unattached)', after: `${input.target.type} ${String(current.entity.Name ?? '')} (${entityId(input.target)})` }, { field: 'Association', before: '(none)', after: input.exclude ? 'Exclude' : `${current.context.audience_target_option}, bid adjustment ${percent}%` }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(account, `${kind}Criterions`, { [`${kind}Criterions`]: [fields], CriterionType: 'Audience' }), ids = Array.isArray(result[`${kind}CriterionIds`]) ? (result[`${kind}CriterionIds`] as unknown[]).filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience criterion receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.confirm(ids, async () => { const actual = (await this.query(account, input.target, input.audience_type)).find(value => nativeId(value.Id) === ids[0]); return !!actual && actual.Type === fields.Type && nativeId(row(actual.Criterion).AudienceId) === input.audience_id && (input.exclude || row(actual.CriterionBid).Type === 'BidMultiplier' && row(actual.CriterionBid).Multiplier === percent); });\n } };\n }\n const input = (op.tool === 'microsoft_set_audience_target_bid' ? bid : reference).parse(op.payload), current = await this.entity(account, input.target, true), criterion = (await this.query(account, input.target, input.audience_type)).find(value => nativeId(value.Id) === input.criterion_id);\n if (!criterion) throw new AdportError('INVALID_INPUT', 'microsoft: audience criterion was not found in the selected entity/account/type');\n if (this.snapshot(criterion, current.context.context_hash) !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience criterion or parent context changed; request a fresh preview');\n const kind = prefix(input.target);\n if (op.tool === 'microsoft_set_audience_target_bid') {\n const value = bid.parse(input);\n if (criterion.Type !== `Biddable${kind}Criterion` || row(criterion.CriterionBid).Type !== 'BidMultiplier') throw new AdportError('INVALID_INPUT', 'microsoft: only biddable audience criteria with BidMultiplier accept a bid edit');\n const fields = { [`${kind}Id`]: entityId(input.target), Id: input.criterion_id, Type: `Biddable${kind}Criterion`, CriterionBid: { Type: 'BidMultiplier', Multiplier: value.bid_adjustment_percent } };\n return { summary: `Set Microsoft audience ${nativeId(row(criterion.Criterion).AudienceId)} bid adjustment on ${kind} \"${String(current.entity.Name ?? entityId(input.target))}\"`, changes: [`~ ${JSON.stringify(fields)}`], fieldChanges: [{ field: 'Bid adjustment', before: `${row(criterion.CriterionBid).Multiplier}%`, after: `${value.bid_adjustment_percent}%` }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, `${kind}Criterions`, { [`${kind}Criterions`]: [fields], CriterionType: 'Audience' }, 'PUT');\n return this.confirm([input.criterion_id], async () => { const actual = (await this.query(account, input.target, input.audience_type)).find(value => nativeId(value.Id) === input.criterion_id); return !!actual && actual.Type === criterion.Type && digest(actual.Criterion) === digest(criterion.Criterion) && row(actual.CriterionBid).Multiplier === value.bid_adjustment_percent; });\n } };\n }\n return { summary: `Remove Microsoft audience association from ${kind} \"${String(current.entity.Name ?? entityId(input.target))}\"`, changes: [`- ${JSON.stringify(criterion)}`, 'Removing a positive association or an exclusion can change delivery. Parent target mode, status and other criterion IDs are preserved.'], fieldChanges: [{ field: 'Audience association', before: `${String(criterion.Type).startsWith('Negative') ? 'Exclude' : 'Positive'} audience ${nativeId(row(criterion.Criterion).AudienceId)} (criterion ${input.criterion_id})`, after: 'Removed' }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, `${kind}Criterions`, { [`${kind}Id`]: entityId(input.target), [`${kind}CriterionIds`]: [input.criterion_id], CriterionType: 'Audience' }, 'DELETE');\n return this.confirm([input.criterion_id], async () => !(await this.query(account, input.target, input.audience_type)).some(value => nativeId(value.Id) === input.criterion_id));\n } };\n }\n}\n\nexport function microsoftAudienceTargetingTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_audience_targets', namespace: 'microsoft', description: 'Read campaign or ad-group audience associations/exclusions of one concrete audience type. Returns native criteria, snapshots and verified parent target-mode/status context. Campaign TargetSetting is explicitly requested. Continue next_cursor as after_criterion_id.', input: z.object({ account_id: id, target, audience_type: audienceType, after_criterion_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ context, rows: z.array(z.object({ criterion: z.record(z.string(), z.unknown()), snapshot_hash: hash })), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_criterion_id' }, annotations: { readOnly: true }, handler: input => provider.audienceTargeting.list(input) }),\n guardedWriteTool({ name: 'microsoft_add_audience_target', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Associate or exclude an account-available audience with expected_audience_snapshot_hash. Positive criteria require expected_target_and_bid from target reads and a complete opposite-level check, bounded to 50 ad groups. Preserves parent mode/status; native Active criteria require an effectively paused parent under paused_creation. Performance Max supports campaign exclusions only.', payload: add }),\n guardedWriteTool({ name: 'microsoft_set_audience_target_bid', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit an owned positive audience criterion percentage adjustment (-90..900, integer) with expected_snapshot_hash. Preserves audience identity, delivery mode and parent status. Exclusions do not accept bids.', payload: bid }),\n guardedWriteTool({ name: 'microsoft_remove_audience_target', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove an exact owned audience association/exclusion with expected_snapshot_hash. This can broaden or narrow delivery; preserves target mode and other criteria. Confirms disappearance before reporting success.', payload: reference }),\n guardedWriteTool({ name: 'microsoft_set_audience_target_mode', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Set TargetAndBid (restrict positive audience delivery) or BidOnly (bid adjustment without that restriction) with expected_context_hash from target reads. Preserves all other target-setting details and other settings; affects all positive audiences on that entity. Performance Max uses signals and exclusions instead.', payload: mode }),\n ];\n}\n","import { AdportError, defineTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst range = z.object({ start_utc: z.iso.datetime(), end_utc: z.iso.datetime() }).refine(value => {\n const span = Date.parse(value.end_utc) - Date.parse(value.start_utc);\n return span >= 0 && span <= 7 * 86400000;\n}, 'Use an ordered UTC interval of at most seven days');\nconst accountInput = z.object({ account_id: id, date_range: range });\nconst channels = z.enum(['CampaignManagementAPI', 'BulkAPI', 'WebUpload', 'Unknown']);\nconst goalInput = accountInput.extend({ goal_ids: z.array(id).min(1).max(20).refine(value => new Set(value).size === value.length, 'Goal IDs must be unique'), upload_channels: z.array(channels).min(1).refine(value => new Set(value).size === value.length && (!value.includes('Unknown') || value.length === 1), 'Use unique channels; Unknown cannot be combined with other channels').optional() });\nconst count = z.union([z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), z.string().regex(/^\\d+$/)]);\nconst rate = z.union([z.number().min(0).max(1), z.string().regex(/^(?:0(?:\\.\\d+)?|1(?:\\.0+)?)$/)]);\nconst optionalCount = count.nullable().optional();\nconst alert = z.object({ Count: optionalCount, UnattributedReason: z.string().nullable().optional() });\nconst goalId = z.preprocess(nativeId, id);\nconst day = z.object({ GoalId: goalId, UploadDate: z.string(), SuccessCount: optionalCount, UnattributedCount: optionalCount, SuccessRate: rate.nullable().optional(), Alerts: z.array(alert).nullable().optional() });\nconst summary = z.object({ GoalId: goalId, ConversionName: z.string().nullable().optional(), OverallSuccessCount: optionalCount, OverallUnattributedCount: optionalCount, OverallSuccessRate: rate.nullable().optional(), OverallAlerts: z.array(alert).nullable().optional(), DailySummaries: z.array(day).nullable().optional() });\nconst daily = z.object({ UploadDate: z.string(), SuccessCount: optionalCount, FailureCount: optionalCount, FileUrlExpiryTimeUtc: z.string().nullable().optional(), file_available: z.boolean() });\nconst partialError = z.object({ index: z.number().int().nonnegative().optional(), goal_id: id.optional(), code: z.number().int().optional(), error_code: z.string().optional() });\nconst accountOutput = z.object({ account_id: id, date_range: range, rows: z.array(daily), notes: z.array(z.string()) });\nconst goalOutput = z.object({ account_id: id, date_range: range, rows: z.array(summary), errors: z.array(partialError), not_returned_goal_ids: z.array(id), notes: z.array(z.string()) });\nconst notes = ['Read-only upload diagnostics, not campaign performance or proof of incremental attribution. Counts preserve native strings and missing values; success rates are ratios, not percentages.', 'Input boundaries are UTC. Native UploadDate values are preserved; Microsoft documents DailySummary.UploadDate as local time. No conversion events are submitted.'];\n\n/** Campaign Management v13 report aggregates only; never expose signed report files or pilot event records. */\nexport class MicrosoftOfflineReportService extends MicrosoftNativeService {\n async daily(input: z.infer<typeof accountInput>) {\n const result = await this.request(input.account_id, 'OfflineConversionReports/Query', { StartDateUtc: input.date_range.start_utc, EndDateUtc: input.date_range.end_utc });\n if (!Object.hasOwn(result, 'DailySummaries')) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline upload report envelope is missing');\n const values = rows(result.DailySummaries).map(value => {\n if (!Object.hasOwn(value, 'SuccessCount') && !Object.hasOwn(value, 'FailureCount')) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline report lacks aggregate counts; event-level records are not exposed by this tool');\n return daily.parse({ ...value, file_available: typeof value.FileUrl === 'string' && value.FileUrl.length > 0 });\n });\n return accountOutput.parse({ account_id: input.account_id, date_range: input.date_range, rows: values, notes: [...notes, 'Signed FileUrl values and pilot event/customer fields are omitted. This tool does not download raw conversion files.'] });\n }\n\n async goals(input: z.infer<typeof goalInput>) {\n const available = rows((await this.request(input.account_id, 'ConversionGoals/QueryByIds', { ConversionGoalIds: input.goal_ids, ConversionGoalTypes: 'OfflineConversion' })).ConversionGoals);\n if (available.length !== input.goal_ids.length || new Set(available.map(value => nativeId(value.Id))).size !== available.length || available.some(value => value.Type !== 'OfflineConversion' || !input.goal_ids.includes(nativeId(value.Id)))) throw new AdportError('INVALID_INPUT', 'microsoft: requested offline goals are not all available in the selected account');\n const scope = await this.accountScope(input.account_id);\n // This read can return successful summaries alongside per-goal failures.\n // Preserve those failures explicitly instead of the mutation helper's throw.\n const result = await this.client.request<Record<string, unknown>>('campaign', 'POST', 'OfflineConversionReport/QueryByGoalIds', { StartDateUtc: input.date_range.start_utc, EndDateUtc: input.date_range.end_utc, GoalIds: input.goal_ids, UploadChannelFilter: input.upload_channels?.join(', ') ?? null }, scope);\n if (!Object.hasOwn(result, 'OfflineGoalConversionSummaries') || result.NestedPartialErrors !== undefined && result.NestedPartialErrors !== null && (!Array.isArray(result.NestedPartialErrors) || result.NestedPartialErrors.some(Boolean))) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline goal report envelope is missing or contains unsupported nested errors');\n const values = rows(result.OfflineGoalConversionSummaries).map(value => summary.parse(value));\n if (new Set(values.map(value => value.GoalId)).size !== values.length || values.some(value => !input.goal_ids.includes(value.GoalId) || value.DailySummaries?.some(day => day.GoalId !== value.GoalId))) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline report returned an unexpected or duplicate goal identity');\n const errors = z.array(z.record(z.string(), z.unknown()).nullable()).parse(result.PartialErrors ?? []).filter(value => value !== null).map(value => {\n if (value.Index !== undefined && value.Index !== null && (!Number.isInteger(value.Index) || Number(value.Index) < 0 || Number(value.Index) >= input.goal_ids.length)) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline report error index is outside the requested goals');\n if (typeof value.Code !== 'number' && typeof value.ErrorCode !== 'string') throw new AdportError('PROVIDER_ERROR', 'microsoft: malformed offline report partial error');\n const index = typeof value.Index === 'number' ? value.Index : undefined;\n return partialError.parse({ ...(index !== undefined ? { index, goal_id: input.goal_ids[index] } : {}), ...(value.Code !== undefined ? { code: value.Code } : {}), ...(value.ErrorCode !== undefined ? { error_code: value.ErrorCode } : {}) });\n });\n return goalOutput.parse({ account_id: input.account_id, date_range: input.date_range, rows: values, errors, not_returned_goal_ids: input.goal_ids.filter(goal => !values.some(value => value.GoalId === goal)), notes: [...notes, 'Missing summaries and per-goal errors are explicit; absence does not mean zero conversions. Error messages, details and event/customer fields are omitted.'] });\n }\n}\n\nexport function microsoftOfflineReportTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_offline_conversion_reports', namespace: 'microsoft', description: 'Read daily offline-conversion upload success/failure counts in an explicit UTC interval (tool bound: seven days). Preserves native dates/counts; omits signed file URLs and pilot event/customer records. Downloads and event ingestion are separate workflows.', input: accountInput, output: accountOutput, annotations: { readOnly: true }, handler: input => provider.offlineReports.daily(input) }),\n defineTool({ name: 'microsoft_offline_conversion_goal_report', namespace: 'microsoft', description: 'Read offline conversion attribution diagnostics for up to 20 unique account-available OfflineConversion goals and at most seven days in UTC. Native channel flags are optional CSV filters. Returns aggregate/daily ratios and counts, explicit per-goal errors and missing summaries; never infers zero for missing data.', input: goalInput, output: goalOutput, annotations: { readOnly: true }, handler: input => provider.offlineReports.goals(input) }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { offlineAdjustments, offlineTimeTicks, offlineUpload } from './offline-conversion-schemas.js';\nimport { MicrosoftNativeService, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsClient, RequestScope } from './client.js';\nimport type { MicrosoftConversionService } from './conversions.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nexport const MICROSOFT_OFFLINE_CONVERSION_WRITES = new Set(['microsoft_upload_offline_conversions', 'microsoft_upload_offline_conversion_adjustments']);\nconst record = (value: unknown): value is Row => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : record(value) ? Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst wireFields = { microsoft_click_id: 'MicrosoftClickId', hashed_email_address: 'HashedEmailAddress', hashed_phone_number: 'HashedPhoneNumber', conversion_time: 'ConversionTime', conversion_value: 'ConversionValue', conversion_currency_code: 'ConversionCurrencyCode', external_attribution_credit: 'ExternalAttributionCredit', external_attribution_model: 'ExternalAttributionModel', adjustment_time: 'AdjustmentTime', adjustment_type: 'AdjustmentType', adjustment_value: 'AdjustmentValue', adjustment_currency_code: 'AdjustmentCurrencyCode' } as const;\nconst notes = [\n 'This is a local preview. Microsoft has no dry run for offline imports or adjustments; no event is sent until apply.',\n 'Events and adjustments can affect measured revenue, conversion counts and automated bidding. This tool preserves goal configuration, account auto-tagging, campaign status and budgets.',\n 'Wait two hours after creating a goal. Receipt acceptance does not prove matching, attribution or reporting; reporting can take six hours. Click time and conversion-window eligibility cannot be checked from these inputs.',\n 'Native deduplication retains the first original conversion for the same goal/click/time. Use a restatement or retraction to change a prior conversion. No global Adport event ledger or per-event readback is available.',\n 'Approval is single-attempt. Failed or unknown rows are never retried automatically; reconcile batch SHA-256, original row indexes and aggregate upload diagnostics before requesting another preview.',\n 'Private identifiers are omitted from previews, receipts and audit summaries. Full arguments are stored in the private pending approval; the agent applies them without copying them into the widget.',\n];\n\n/** PartialErrors is sparse and indexed into the request, not positional. No native messages/values are exposed. */\nfunction outcome(value: unknown, count: number) {\n const errors: Array<{ index: number; code: number }> = [];\n let unmapped = 0, verified = record(value) && Object.keys(value).every(key => key === 'PartialErrors');\n const partial = record(value) ? value.PartialErrors : undefined;\n if (partial !== undefined && partial !== null && !Array.isArray(partial)) verified = false;\n if (Array.isArray(partial)) {\n if (partial.length > 20_000) { verified = false;unmapped++; }\n for (const item of partial.slice(0, 20_000)) {\n if (item === null) continue;\n if (!record(item) || !Number.isInteger(item.Index) || Number(item.Index) < 0 || Number(item.Index) >= count || !Number.isSafeInteger(item.Code) || Number(item.Code) <= 0) { unmapped++;continue; }\n errors.push({ index: Number(item.Index), code: Number(item.Code) });\n }\n }\n const failed = new Set(errors.map(error => error.index));\n const rows = Array.from({ length: count }, (_, index) => ({ index, status: failed.has(index) ? 'FAILED' : verified && !unmapped ? 'ACCEPTED' : 'UNKNOWN' }));\n return { receipt_verified: verified && !unmapped, accepted_count: rows.filter(row => row.status === 'ACCEPTED').length, failed_count: failed.size, unknown_count: rows.filter(row => row.status === 'UNKNOWN').length, rows, errors, unmapped_error_count: unmapped };\n}\n\n/** Official MicrosoftDocs@5bde65c3 and BingAds Python REST SDK@4b6fb31c, refreshed2026-11-06. */\nexport class MicrosoftOfflineConversionService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string, refresh?: boolean) => Promise<RequestScope>, campaign: (account: string, campaign: string) => Promise<unknown>, private readonly conversions: MicrosoftConversionService) {\n super(client, scope, campaign);\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n const adjusting = op.tool === 'microsoft_upload_offline_conversion_adjustments';\n if (op.provider !== 'microsoft' || !MICROSOFT_OFFLINE_CONVERSION_WRITES.has(op.tool) || op.kind !== (adjusting ? 'update' : 'create')) throw new AdportError('INVALID_INPUT', 'microsoft: offline conversion operation provider/kind mismatch');\n const input = adjusting ? offlineAdjustments.parse(op.payload) : offlineUpload.parse(op.payload);\n const scope = await this.accountScope(op.accountId, true), current = await this.conversions.get(op.accountId, input.goal_id, 'OfflineConversion');\n if (current.snapshot_hash !== input.expected_goal_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: offline goal or auto-tagging configuration changed; read it and preview again');\n const goal = current.goal;\n if (goal.Type !== 'OfflineConversion' || !['Account', 'Customer'].includes(String(goal.Scope)) || !['Active', 'Paused'].includes(String(goal.Status)) || typeof goal.Name !== 'string' || !goal.Name.trim()) throw new AdportError('INVALID_INPUT', 'microsoft: an available Account/Customer offline goal with a concrete name and status is required');\n const source: Row[] = 'conversions' in input ? input.conversions : input.adjustments;\n const now = BigInt(Date.now()) * 10_000n, maxAge = 90n * 86400n * 10_000_000n, identities = new Set<string>();\n for (const row of source) {\n const time = offlineTimeTicks(String(row.conversion_time));\n if (time > now || time < now - maxAge) throw new AdportError('INVALID_INPUT', 'microsoft: original conversion times must be in UTC within the last90days and not in the future');\n if (adjusting && (offlineTimeTicks(String(row.adjustment_time)) < time || offlineTimeTicks(String(row.adjustment_time)) > now)) throw new AdportError('INVALID_INPUT', 'microsoft: adjustment time must be at/after the original conversion and not in the future');\n if ((row.hashed_email_address || row.hashed_phone_number) && goal.IsEnhancedConversionsEnabled !== true) throw new AdportError('INVALID_INPUT', 'microsoft: hashed identifiers require an already enabled enhanced-conversion goal; no setting or terms are changed');\n if ((row.external_attribution_credit !== undefined || row.external_attribution_model !== undefined) && goal.IsExternallyAttributed !== true) throw new AdportError('INVALID_INPUT', 'microsoft: external attribution fields require a verified externally attributed goal');\n const identity = digest({ time: time.toString(), ...(row.microsoft_click_id ? { click: row.microsoft_click_id } : { email: row.hashed_email_address, phone: row.hashed_phone_number }) });\n if (identities.has(identity)) throw new AdportError('INVALID_INPUT', 'microsoft: duplicate original conversion identities in this batch; submit at most one operation per original identity');\n identities.add(identity);\n }\n const bodyRows = source.map(row => ({ ConversionName: goal.Name, ...Object.fromEntries(Object.entries(row).map(([key, value]) => [wireFields[key as keyof typeof wireFields], value])) }));\n const path = adjusting ? 'OfflineConversionAdjustments/Apply' : 'OfflineConversions/Apply';\n const body = { [adjusting ? 'OfflineConversionAdjustments' : 'OfflineConversions']: bodyRows };\n const batchHash = digest({ account: op.accountId, path, body }), count = source.length;\n const valueRanges = new Map<string, { currency: string; records: number; minimum: number; maximum: number }>();\n for (const row of source) {\n const value = adjusting ? row.adjustment_value : row.conversion_value;\n if (typeof value !== 'number') continue;\n const currency = String((adjusting ? row.adjustment_currency_code : row.conversion_currency_code) ?? '(goal default)'), previous = valueRanges.get(currency);\n valueRanges.set(currency, { currency, records: (previous?.records ?? 0) + 1, minimum: Math.min(previous?.minimum ?? value, value), maximum: Math.max(previous?.maximum ?? value, value) });\n }\n const changes = [`${count} ${adjusting ? 'adjustments' : 'conversions'} for offline goal ${input.goal_id}.`, `Approved native batch SHA-256: ${batchHash}.`, adjusting ? 'Restatements replace recorded values; retractions remove previously recorded conversions. Original conversion time identifies the record; adjustment time records the adjustment.' : 'Omitted conversion value and currency use the goal revenue defaults. Values are whole currency units, not budget micros.'];\n const notices = [...notes, ...(goal.Status === 'Paused' ? ['This goal is Paused. It stays paused; receipt acceptance does not imply that these records will be counted.'] : []), ...(record(goal.Revenue) && goal.Revenue.Type === 'NoValue' ? ['Goal revenue is NoValue; supplying monetary values does not change the goal into a revenue-tracking goal.'] : []), ...(!current.auto_tagging_enabled ? ['Click-ID auto-tagging is disabled and remains disabled. An uploaded click ID must already identify a real native click.'] : [])];\n let details: unknown, warnings: string[] = [];\n return { summary: `${adjusting ? 'Adjust' : 'Import'} ${count} Microsoft offline conversion${count === 1 ? '' : 's'} · batch ${batchHash}`, changes, notes: notices, coercions: [], budgetDeltas: [],\n review: { provider: 'microsoft', accountId: op.accountId, kind: op.kind, title: adjusting ? 'Adjust offline conversions' : 'Import offline conversions', fields: [\n { label: 'Goal', after: `${goal.Name} [${input.goal_id}]` }, { label: 'Goal scope', after: goal.Scope }, { label: 'Goal status', after: goal.Status }, { label: 'Records', after: count },\n { label: 'Identifier matching', after: { click_ids: source.filter(row => row.microsoft_click_id).length, hashed_emails: source.filter(row => row.hashed_email_address).length, hashed_phones: source.filter(row => row.hashed_phone_number).length } },\n ...(adjusting ? [{ label: 'Adjustments', after: { restatements: source.filter(row => row.adjustment_type === 'Restate').length, retractions: source.filter(row => row.adjustment_type === 'Retract').length } }] : [{ label: 'Goal revenue defaults', after: goal.Revenue ?? 'Not reported' }]),\n { label: 'Explicit value ranges (whole currency units)', after: [...valueRanges.values()] },\n { label: 'Batch SHA-256', after: batchHash },\n ], notices }, resultDetails: () => details, resultWarnings: () => warnings,\n execute: async () => {\n let result: unknown;\n try { result = await this.client.request<unknown>('campaign', 'POST', path, body, scope, { privatePayload: true }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: offline batch outcome is unknown; private native response details were omitted. Reconcile upload diagnostics before another preview. No request was retried.', { batch_sha256: batchHash, target_goal_id: input.goal_id, record_count: count, ...outcome(null, count), processed: false }); }\n const receipt = outcome(result, count);\n details = { status: receipt.accepted_count ? 'ACCEPTED_FOR_PROCESSING' : 'PARTIAL_OR_UNCONFIRMED', receipt_status: receipt.accepted_count === count ? 'ALL_ACCEPTED' : receipt.unknown_count ? 'UNCONFIRMED' : 'PARTIAL', processed: false, account_id: op.accountId, target_goal_id: input.goal_id, batch_sha256: batchHash, record_count: count, ...receipt, next_tool: 'microsoft_offline_conversion_goal_report' };\n if (!receipt.accepted_count) throw new AdportError('PROVIDER_ERROR', 'microsoft: no offline records were confirmed accepted. Reconcile the returned row outcomes and native upload diagnostics; no automatic retry.', details);\n if (receipt.accepted_count < count) warnings = [`Microsoft accepted ${receipt.accepted_count} of ${count} rows for processing; ${receipt.failed_count} failed and ${receipt.unknown_count} remain unknown. Acceptance is not attribution. Inspect original row indexes before a new upload.`];\n // The API assigns no event IDs. This ID names the existing target goal only.\n return [input.goal_id];\n },\n };\n }\n}\n\nexport function microsoftOfflineConversionTools(_provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'measurement' as const, exposure: 'specialist' as const };\n return [\n guardedWriteTool({ name: 'microsoft_upload_offline_conversions', namespace: 'microsoft', provider: 'microsoft', catalog, kind: 'create', sensitiveInputs: ['conversions'], description: 'Import 1–1,000 offline conversions into an existing goal with expected_goal_hash. Local preview sends no events; apply returns sparse indexed failures and acceptance for processing, not attribution. Uses the current exact goal name, preserves its configuration and never retries. Already hashed identifiers require enhanced conversions to be enabled.', payload: offlineUpload }),\n guardedWriteTool({ name: 'microsoft_upload_offline_conversion_adjustments', namespace: 'microsoft', provider: 'microsoft', catalog, kind: 'update', sensitiveInputs: ['adjustments'], description: 'Restate or retract 1–1,000 previously imported offline conversions with expected_goal_hash. Original conversion_time identifies each record; adjustment_time records the adjustment. Local preview sends nothing. Returns indexed failures and processing acceptance; no automatic retry or per-event readback.', payload: offlineAdjustments }),\n ];\n}\n","import { z } from 'zod';\nimport { microsoftId } from './native.js';\n\n// Preserve Microsoft's dateTime precision (100ns) rather than truncating identities to JS milliseconds.\nexport const offlineTime = z.iso.datetime().regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,7})?Z$/, 'Use a UTC timestamp with seconds and at most seven fractional digits');\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst identifier = z.string().min(1).max(512).regex(/^[^\\s\\x00-\\x1f\\x7f]+$/);\nconst currency = z.string().regex(/^[A-Z]{3}$/);\nconst identity = z.object({\n microsoft_click_id: identifier.optional(),\n hashed_email_address: hash.optional(),\n hashed_phone_number: hash.optional(),\n conversion_time: offlineTime,\n}).strict();\nconst identified = (value: z.infer<typeof identity>) => !!(value.microsoft_click_id || value.hashed_email_address || value.hashed_phone_number);\nexport const offlineConversion = identity.extend({\n conversion_value: z.number().finite().optional(),\n conversion_currency_code: currency.optional(),\n external_attribution_credit: z.number().finite().gt(0).max(1).optional(),\n external_attribution_model: z.string().min(1).max(512).optional(),\n}).strict().refine(identified, 'Supply a Microsoft click ID or an already hashed email/phone identifier');\nconst adjustment = identity.extend({ adjustment_time: offlineTime });\nexport const offlineAdjustment = z.discriminatedUnion('adjustment_type', [\n adjustment.extend({ adjustment_type: z.literal('Restate'), adjustment_value: z.number().finite(), adjustment_currency_code: currency }).strict(),\n adjustment.extend({ adjustment_type: z.literal('Retract') }).strict(),\n]).refine(identified, 'Supply the original Microsoft click ID or already hashed email/phone identifiers');\nconst binding = z.object({\n goal_id: microsoftId,\n expected_goal_hash: hash,\n acknowledge_measurement_effects: z.literal(true),\n}).strict();\nexport const offlineUpload = binding.extend({ conversions: z.array(offlineConversion).min(1).max(1000) }).strict();\nexport const offlineAdjustments = binding.extend({ adjustments: z.array(offlineAdjustment).min(1).max(1000) }).strict();\n\nexport function offlineTimeTicks(value: string): bigint {\n const [whole, fraction = ''] = value.slice(0, -1).split('.');\n return BigInt(Date.parse(`${whole}Z`)) * 10_000n + BigInt(fraction.padEnd(7, '0'));\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type ReviewField, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { MicrosoftNativeService, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport { criterionType, minutes, nativeTarget } from './targeting-schemas.js';\nimport { targetSelection, targetingRead, targetingWrite } from './general-targeting-schemas.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\ntype Target = z.infer<typeof targetSelection>;\ntype Kind = z.infer<typeof criterionType>;\nconst BOUND = 20_000;\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value)) ?? 'undefined').digest('hex');\nconst same = (a: unknown, b: unknown) => digest(a) === digest(b);\nconst pick = (value: Row, fields: string[]) => Object.fromEntries(fields.filter(field => Object.hasOwn(value, field)).map(field => [field, value[field]]));\nconst optionalRow = (value: unknown): Row => value === undefined || value === null ? {} : row(value);\nconst kind = (value: Row) => criterionType.parse(String(row(value.Criterion).Type).replace(/Criterion$/, ''));\nconst entityId = (target: Target) => target.type === 'Campaign' ? target.campaign_id : target.ad_group_id;\nconst geo = (value: Row) => ['Location', 'Radius'].includes(kind(value));\nfunction title(value: Row): string {\n const data = row(value.Criterion), type = kind(value), text = (field: string) => data[field] === undefined || data[field] === null ? 'Not reported' : String(data[field]);\n if (type === 'Device') return text('DeviceName');\n if (type === 'Location') return `Location ${text('LocationId')}`;\n if (type === 'Radius') return `${data.Name || 'Radius'} · ${text('Radius')} ${text('RadiusUnit')} · ${text('LatitudeDegrees')}, ${text('LongitudeDegrees')}`;\n if (type === 'Age') return text('AgeRange').replace(/([a-z])([A-Z])/g, '$1 $2');\n if (type === 'Gender') return text('GenderType');\n if (type === 'LocationIntent') return text('IntentOption').replace(/([a-z])([A-Z])/g, '$1 $2');\n const time = (end: boolean) => { const hour = data[end ? 'ToHour' : 'FromHour'], minute = data[end ? 'ToMinute' : 'FromMinute'];return typeof hour === 'number' && typeof minute === 'string' && Object.hasOwn(minutes, minute) ? `${String(hour).padStart(2, '0')}:${String(minutes[minute as keyof typeof minutes]).padStart(2, '0')}` : 'Not reported'; };\n return `${text('Day')} ${time(false)}–${time(true)}`;\n}\nconst identity = (value: Row) => {\n const fields: Record<Kind, string[]> = { Age: ['AgeRange'], Gender: ['GenderType'], Device: ['DeviceName'], DayTime: ['Day', 'FromHour', 'FromMinute', 'ToHour', 'ToMinute'], Location: ['LocationId'], LocationIntent: [], Radius: ['LatitudeDegrees', 'LongitudeDegrees', 'Radius', 'RadiusUnit'] };\n const criterion = row(value.Criterion);return digest({ type: kind(value), fields: fields[kind(value)].map(field => String(criterion[field] ?? '')) });\n};\nconst notices = ['Ad-group criteria override campaign criteria of the same type. Locations, negative locations and radii form one geo family: any ad-group geo criterion disables inheritance of ALL campaign geo criteria. Location intent alone does not change the geo source.', 'Device and schedule criteria override rather than combine with campaign settings. Removing the last ad-group criterion can restore inherited targeting; adding the first can broaden or narrow delivery.', 'BidMultiplier carries whole percentage points, not a ratio or currency micros. Automated bidding can treat it as a signal. Location intent has no bid. Criteria have native Active status without an independent pause.', 'A configuration hash detects observed changes before submission, not concurrent changes during a native request. Reads and preservation checks cover these seven criterion families and selected parent/account configuration, not every native targeting feature.'];\nexport const MICROSOFT_GENERAL_TARGETING_WRITES = new Set(['microsoft_update_targeting']);\n\n/** MicrosoftDocs@5bde65c3, BingAds REST SDK@4b6fb31c; one native mutation per approval. */\nexport class MicrosoftGeneralTargetingService extends MicrosoftNativeService {\n private async query(account: string, target: Target, type: Kind) {\n const prefix = target.type, result = await this.request(account, `${prefix}Criterions/QueryByIds`, { [`${prefix}Id`]: entityId(target), [`${prefix}CriterionIds`]: null, CriterionType: type });\n if (!Object.hasOwn(result, `${prefix}Criterions`)) throw new AdportError('PROVIDER_ERROR', 'microsoft: complete target criteria were not returned');\n const values = rows(result[`${prefix}Criterions`]);\n if (values.length > BOUND || new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => nativeId(value[`${prefix}Id`]) !== entityId(target) || kind(value) !== type || ![`Biddable${prefix}Criterion`, `Negative${prefix}Criterion`].includes(String(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: targeting response identity, scope or safety bound mismatch');\n return values.filter(value => value.Status !== 'Deleted');\n }\n private async all(account: string, target: Target) {\n const values: Row[] = [];\n for (let i = 0; i < criterionType.options.length; i += 3) values.push(...(await Promise.all(criterionType.options.slice(i, i + 3).map(type => this.query(account, target, type)))).flat());\n if (values.length > BOUND || new Set(values.map(value => nativeId(value.Id))).size !== values.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: targeting snapshot exceeds its bound or contains duplicate IDs');\n return values.sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1);\n }\n private async context(account: string, target: Target) {\n const scope = await this.accountScope(account, true), known = await this.campaign(account, target.campaign_id);\n const accountResult = await this.request(account, 'Account/Query', { AccountId: account }, 'POST', 'customer'), nativeAccount = row(accountResult.Account);\n if (nativeId(nativeAccount.Id) !== account || nativeId(nativeAccount.ParentCustomerId) !== scope.customerId) throw new AdportError('PROVIDER_ERROR', 'microsoft: account/timezone ownership could not be verified');\n const accountContext = pick(nativeAccount, ['Id', 'ParentCustomerId', 'CurrencyCode', 'TimeZone', 'AccountLifeCycleStatus']);\n const parents = rows((await this.request(account, 'Campaigns/QueryByIds', { AccountId: account, CampaignIds: [target.campaign_id], CampaignType: known.CampaignType, ReturnAdditionalFields: 'TargetSetting, AdScheduleUseSearcherTimeZone' })).Campaigns);\n if (parents.length !== 1 || nativeId(parents[0]!.Id) !== target.campaign_id || parents[0]!.CampaignType !== known.CampaignType || !['Active', 'Paused'].includes(String(parents[0]!.Status))) throw new AdportError('INVALID_INPUT', 'microsoft: campaign context is unavailable or mismatched');\n const campaign = pick(parents[0]!, ['Id', 'Name', 'Status', 'CampaignType', 'SubType', 'DailyBudget', 'BudgetType', 'BudgetId', 'BiddingScheme', 'ExperimentId', 'Settings', 'AdScheduleUseSearcherTimeZone']);\n let group: Row | undefined;\n if (target.type === 'AdGroup') {\n if (campaign.CampaignType === 'PerformanceMax') throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max has asset groups, not ordinary ad-group targeting');\n const groups = rows((await this.request(account, 'AdGroups/QueryByIds', { CampaignId: target.campaign_id, AdGroupIds: [target.ad_group_id], ReturnAdditionalFields: 'AdGroupType, AdScheduleUseSearcherTimeZone' })).AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== target.ad_group_id || !['Active', 'Paused'].includes(String(groups[0]!.Status))) throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n group = pick(groups[0]!, ['Id', 'Name', 'Status', 'AdGroupType', 'Language', 'CpcBid', 'CpmBid', 'CpvBid', 'BiddingScheme', 'StartDate', 'EndDate', 'Settings', 'AdScheduleUseSearcherTimeZone']);\n }\n const campaignCriteria = await this.all(account, { type: 'Campaign', campaign_id: target.campaign_id }), ownCriteria = target.type === 'AdGroup' ? await this.all(account, target) : campaignCriteria;\n const data = { account_id: account, target, account: accountContext, campaign, group, campaignCriteria, ownCriteria };\n return { ...data, context_hash: digest(data) };\n }\n private inherited(context: Awaited<ReturnType<MicrosoftGeneralTargetingService['context']>>, own = context.ownCriteria) {\n return Object.fromEntries(criterionType.options.map(type => {\n const useOwn = context.target.type === 'Campaign' || (['Location', 'Radius', 'LocationIntent'].includes(type) ? own.some(geo) : own.some(value => kind(value) === type));\n const source = useOwn ? context.target.type : 'Campaign', selected = useOwn ? own : context.campaignCriteria;\n return [type, { source, criterion_count: selected.filter(value => kind(value) === type).length }];\n }));\n }\n private clock(context: Awaited<ReturnType<MicrosoftGeneralTargetingService['context']>>, own = context.ownCriteria) {\n const source = this.inherited(context, own).DayTime!.source, parent = source === 'AdGroup' ? context.group! : context.campaign, flag = parent.AdScheduleUseSearcherTimeZone;\n return { source, use_searcher_time_zone: typeof flag === 'boolean' ? flag : null, timezone: flag === true ? 'Searcher local time' : flag === false ? context.account.TimeZone ?? 'Account time zone not reported' : 'Schedule clock not reported' };\n }\n private geography(context: Awaited<ReturnType<MicrosoftGeneralTargetingService['context']>>, own = context.ownCriteria) {\n const source = this.inherited(context, own).Location!.source, selected = source === context.target.type ? own : context.campaignCriteria, included = selected.filter(value => kind(value) === 'Location' && String(value.Type).startsWith('Biddable')), excluded = selected.filter(value => kind(value) === 'Location' && String(value.Type).startsWith('Negative')), radii = selected.filter(value => kind(value) === 'Radius');\n return { source, included_location_count: included.length, excluded_location_count: excluded.length, radius_count: radii.length, included_location_ids: included.slice(0, 20).map(value => row(value.Criterion).LocationId), ids_truncated: included.length > 20, ...(!included.length && !radii.length ? { reach: 'No positive location/radius restriction; exclusions and native campaign eligibility still apply.' } : {}) };\n }\n async list(raw: z.input<typeof targetingRead>) {\n const input = targetingRead.parse(raw), context = await this.context(input.account_id, input.target), types = [...input.criterion_types].sort(), visible = [...context.ownCriteria.map(criterion => ({ source: input.target.type, criterion })), ...(input.target.type === 'AdGroup' ? context.campaignCriteria.map(criterion => ({ source: 'Campaign' as const, criterion })) : [])].filter(value => input.criterion_types.includes(kind(value.criterion)));\n let offset = 0;\n if (input.cursor) try {\n const cursor = z.object({ account: z.string(), target: targetSelection, hash: z.string(), types: z.array(z.string()), size: z.number().int().positive(), offset: z.number().int().positive() }).strict().parse(JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8')));\n if (cursor.account !== input.account_id || !same(cursor.target, input.target) || cursor.hash !== context.context_hash || !same(cursor.types, types) || cursor.size !== input.page_size || cursor.offset >= visible.length || cursor.offset % cursor.size) throw new Error('Selection changed');offset = cursor.offset;\n } catch { throw new AdportError('PENDING_MISMATCH', 'microsoft: targeting continuation is stale or belongs to another selection; refresh the first page'); }\n const inheritance = this.inherited(context), page = visible.slice(offset, offset + input.page_size), end = offset + page.length;\n return { account_id: input.account_id, target: input.target, context_hash: context.context_hash, account: context.account, campaign: context.campaign, ad_group: context.group, inheritance, schedule_clock: this.clock(context), total_criteria: visible.length, criteria: page,\n records: page.map(({ source, criterion }) => { const type = kind(criterion), bid = optionalRow(criterion.CriterionBid).Multiplier, selected = inheritance[type]!.source === source, hasGeo = inheritance.Location!.criterion_count + inheritance.Radius!.criterion_count > 0;return { id: `${source}:${nativeId(criterion.Id)}`, criterion_id: nativeId(criterion.Id), kind: type, name: title(criterion), source, effective: selected && (type !== 'LocationIntent' || hasGeo), status: criterion.Status ?? 'Not reported', bid_adjustment: typeof bid === 'number' ? `${bid}%${type === 'Device' && bid === -100 ? ' · device excluded' : ''}` : type === 'LocationIntent' || String(criterion.Type).startsWith('Negative') ? 'Not applicable' : 'Not reported' }; }),\n truncated: end < visible.length, ...(end < visible.length ? { next_cursor: Buffer.from(JSON.stringify({ account: input.account_id, target: input.target, hash: context.context_hash, types, size: input.page_size, offset: end })).toString('base64url') } : {}), notes: [...notices, 'Both owned and campaign criteria are shown. Effective identifies the selected source, not eligibility or delivery; false marks overridden/inapplicable rows. Intent without geographic criteria is inapplicable. Only owned IDs can be edited at the selected scope.'] };\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n if (op.tool !== 'microsoft_update_targeting' || op.provider !== 'microsoft' || op.kind !== 'update') throw new AdportError('INVALID_INPUT', 'microsoft: scoped targeting operation provider/kind mismatch');\n const input = targetingWrite.parse(op.payload), before = await this.context(op.accountId, input.target), change = input.change, prefix = input.target.type, parentKey = `${prefix}Id`, selectedParent = before.group ?? before.campaign;\n if (before.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: targeting, inheritance or parent/account configuration changed; read and preview again');\n let method: 'POST' | 'PUT' | 'DELETE' = 'PUT', path = `${prefix}Criterions`, body: Row = {}, creates: Row[] = [], removed: string[] = [], updated: Row | undefined, clock: boolean | undefined;\n const selected = (id: string) => { const found = before.ownCriteria.find(value => nativeId(value.Id) === id);if (!found) throw new AdportError('INVALID_INPUT', 'microsoft: criterion is not owned by the selected entity; inherited criterion IDs cannot be edited here');return found; };\n if (change.action === 'add') {\n if (guard.forcePausedCreation && before.campaign.Status !== 'Paused' && before.group?.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: new targets are natively Active; paused_creation requires an effectively paused parent');\n creates = change.targets.map(value => nativeTarget({ [parentKey]: entityId(input.target) }, value));\n const seen = new Set(before.ownCriteria.map(identity));\n for (const value of creates) { if (seen.has(identity(value))) throw new AdportError('INVALID_INPUT', 'microsoft: target already exists or is duplicated in this request; use an explicit edit');seen.add(identity(value)); }\n method = 'POST';body = { [`${prefix}Criterions`]: creates, CriterionType: 'Targets' };\n } else if (change.action === 'remove') {\n removed = change.criterion_ids;const values = removed.map(selected);\n if (values.some(value => kind(value) === 'LocationIntent')) throw new AdportError('INVALID_INPUT', 'microsoft: location intent cannot be deleted; restore its default with set_location_intent');\n if (values.some(value => kind(value) === 'Device') && before.ownCriteria.some(value => kind(value) === 'Device' && !removed.includes(nativeId(value.Id)))) throw new AdportError('INVALID_INPUT', 'microsoft: remove the complete device set together');\n method = 'DELETE';body = { [parentKey]: entityId(input.target), [`${prefix}CriterionIds`]: removed, CriterionType: 'Targets' };\n } else if (change.action === 'set_schedule_clock') {\n if (selectedParent.AdScheduleUseSearcherTimeZone === change.use_searcher_time_zone) throw new AdportError('INVALID_INPUT', 'microsoft: schedule clock already has this value');clock = change.use_searcher_time_zone;\n path = prefix === 'Campaign' ? 'Campaigns' : 'AdGroups';body = { [prefix === 'Campaign' ? 'AccountId' : 'CampaignId']: prefix === 'Campaign' ? op.accountId : input.target.campaign_id, [path]: [{ Id: entityId(input.target), AdScheduleUseSearcherTimeZone: clock }] };\n } else {\n const current = selected(change.criterion_id), type = kind(current);\n if (current.Type !== `Biddable${prefix}Criterion`) throw new AdportError('INVALID_INPUT', 'microsoft: excluded targets cannot have a bid or intent edit');\n updated = { ...current };\n if (change.action === 'set_bid') {\n const bid = optionalRow(current.CriterionBid);\n if (type !== change.criterion_type || bid.Type !== 'BidMultiplier' || typeof bid.Multiplier !== 'number' || !Number.isFinite(bid.Multiplier)) throw new AdportError('INVALID_INPUT', 'microsoft: owned biddable criterion with a verified native percentage is required');\n if (bid.Multiplier === change.bid_adjustment_percent) throw new AdportError('INVALID_INPUT', 'microsoft: bid adjustment is unchanged');updated.CriterionBid = { Type: 'BidMultiplier', Multiplier: change.bid_adjustment_percent };\n body = { [`${prefix}Criterions`]: [{ [parentKey]: entityId(input.target), Id: change.criterion_id, Type: current.Type, CriterionBid: updated.CriterionBid }], CriterionType: 'Targets' };\n } else {\n if (type !== 'LocationIntent') throw new AdportError('INVALID_INPUT', 'microsoft: location intent requires its exact criterion ID');if (row(current.Criterion).IntentOption === change.intent_option) throw new AdportError('INVALID_INPUT', 'microsoft: location intent is unchanged');updated.Criterion = { ...row(current.Criterion), IntentOption: change.intent_option };\n body = { [`${prefix}Criterions`]: [{ [parentKey]: entityId(input.target), Id: change.criterion_id, Type: current.Type, Criterion: updated.Criterion }], CriterionType: 'Targets' };\n }\n }\n const afterOwn = [...before.ownCriteria.filter(value => !removed.includes(nativeId(value.Id))).map(value => updated && nativeId(updated.Id) === nativeId(value.Id) ? updated : value), ...creates];\n const touched = new Set<Kind>([...creates.map(kind), ...before.ownCriteria.filter(value => removed.includes(nativeId(value.Id))).map(kind), ...(updated ? [kind(updated)] : [])]);\n this.validateResultingCriteria(afterOwn, touched);\n const touchesSchedule = clock !== undefined || creates.some(value => kind(value) === 'DayTime') || before.ownCriteria.some(value => removed.includes(nativeId(value.Id)) && kind(value) === 'DayTime');\n if (touchesSchedule && (clock ?? selectedParent.AdScheduleUseSearcherTimeZone) !== true && (typeof (clock ?? selectedParent.AdScheduleUseSearcherTimeZone) !== 'boolean' || typeof before.account.TimeZone !== 'string' || !before.account.TimeZone)) throw new AdportError('INVALID_INPUT', 'microsoft: schedule clock/account time zone is not verified; set an explicit clock and read fresh context');\n const projected = { ...before, campaign: { ...before.campaign, ...(prefix === 'Campaign' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) }, group: before.group ? { ...before.group, ...(prefix === 'AdGroup' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) } : undefined };\n const effectiveBefore = this.inherited(before), effectiveAfter = this.inherited(before, afterOwn), fields: ReviewField[] = [{ label: 'Campaign', after: `${before.campaign.Name ?? 'Not reported'} [${input.target.campaign_id}]` }, ...(before.group ? [{ label: 'Ad group', after: `${before.group.Name ?? 'Not reported'} [${entityId(input.target)}]` }] : []), { label: 'Scope', after: input.target }, { label: 'Campaign status', after: before.campaign.Status }, ...(before.group ? [{ label: 'Ad group status', after: before.group.Status }] : []), { label: 'Change', after: change }, { label: 'Effective targeting', before: effectiveBefore, after: effectiveAfter }, { label: 'Geographic reach', before: this.geography(before), after: this.geography(before, afterOwn) }, { label: 'Schedule clock', before: this.clock(before), after: this.clock(projected, afterOwn) }, ...(clock !== undefined ? [{ label: 'Use searcher timezone', before: selectedParent.AdScheduleUseSearcherTimeZone ?? 'Not reported', after: clock }] : [])];\n let details: unknown;const known = new Set<string>([...removed, ...(updated ? [nativeId(updated.Id)] : []), ...(clock !== undefined ? [entityId(input.target)] : [])]);\n return { summary: `Update Microsoft ${prefix} targeting · ${change.action}`, changes: [`${method} ${path}; only approved target fields are submitted.`, `${creates.length} additions, ${removed.length} removals, ${updated ? 1 : 0} criterion updates.`, 'Other returned criteria and parent statuses/budgets/settings are preserved. Immutable schedule intervals require separate reviewed remove/add operations; pause delivery before a multi-step replacement.'], coercions: [], budgetDeltas: [], notes: notices, review: { provider: 'microsoft', accountId: op.accountId, kind: 'update', title: 'Update targeting', fields, notices }, resultDetails: () => details,\n execute: async () => {\n try {\n const result = await this.request(op.accountId, path, body, method), acknowledged = result[`${prefix}CriterionIds`];\n if (Array.isArray(acknowledged)) for (const id of acknowledged) try { known.add(nativeId(id)); } catch { /* Retain the other acknowledged IDs. */ }\n const createdIds = method === 'POST' ? rowsOfIds(acknowledged) : [];\n if (method === 'POST' && (createdIds.length !== creates.length || new Set(createdIds).size !== createdIds.length || createdIds.some(id => before.ownCriteria.some(value => nativeId(value.Id) === id)))) throw new Error('Creation receipt mismatch');\n const after = await this.context(op.accountId, input.target), expectedCampaign = { ...before.campaign, ...(prefix === 'Campaign' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) }, expectedGroup = before.group ? { ...before.group, ...(prefix === 'AdGroup' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) } : undefined;\n if (!same(after.account, before.account) || !same(after.campaign, expectedCampaign) || !same(after.group, expectedGroup) || prefix === 'AdGroup' && !same(after.campaignCriteria, before.campaignCriteria)) throw new Error('Parent preservation mismatch');\n const expectedIds = new Set([...before.ownCriteria.filter(value => !removed.includes(nativeId(value.Id))).map(value => nativeId(value.Id)), ...createdIds]);\n if (after.ownCriteria.length !== expectedIds.size || after.ownCriteria.some(value => !expectedIds.has(nativeId(value.Id)))) throw new Error('Criterion inventory mismatch');\n for (const previous of before.ownCriteria) {\n if (removed.includes(nativeId(previous.Id))) continue;\n const observed = after.ownCriteria.find(value => nativeId(value.Id) === nativeId(previous.Id)), expected = updated && nativeId(updated.Id) === nativeId(previous.Id) ? updated : previous;\n if (!same(observed, expected)) throw new Error('Criterion preservation mismatch');\n }\n for (let i = 0; i < creates.length; i++) { const observed = after.ownCriteria.find(value => nativeId(value.Id) === createdIds[i]);if (!observed || !contains(observed, creates[i]!)) throw new Error('Created criterion mismatch'); }\n details = { snapshot_hash: after.context_hash, created_criterion_ids: createdIds, removed_criterion_ids: removed, updated_criterion_ids: updated ? [nativeId(updated.Id)] : [], independent_readback_verified: true, inheritance: this.inherited(after), schedule_clock: this.clock(after) };return [...known];\n } catch (error) {\n if (error instanceof AdportError && error.details && typeof error.details === 'object' && Array.isArray((error.details as Row).resourceIds)) for (const id of (error.details as Row).resourceIds as unknown[]) try { known.add(nativeId(id)); } catch { /* Ignore invalid IDs. */ }\n throw new AdportError('PROVIDER_ERROR', 'microsoft: targeting outcome was not confirmed. Reconcile known IDs and current configuration before another mutation; no write was retried.', { resourceIds: [...known] });\n }\n },\n };\n }\n private validateResultingCriteria(values: Row[], touched: Set<Kind>) {\n const devices = values.filter(value => kind(value) === 'Device');\n if (touched.has('Device') && devices.length && (devices.length !== 3 || !['Computers', 'Smartphones', 'Tablets'].every(name => devices.some(value => row(value.Criterion).DeviceName === name)) || devices.some(value => !String(value.Type).startsWith('Biddable') || optionalRow(value.CriterionBid).Type !== 'BidMultiplier' || typeof optionalRow(value.CriterionBid).Multiplier !== 'number') || devices.every(value => optionalRow(value.CriterionBid).Multiplier === -100))) throw new AdportError('INVALID_INPUT', 'microsoft: targeting requires a complete supported three-device set with at least one device included');\n const schedule = values.filter(value => kind(value) === 'DayTime').map(value => row(value.Criterion));\n if (touched.has('DayTime') && schedule.length > 49) throw new AdportError('INVALID_INPUT', 'microsoft: maximum49weekly schedules');\n const number = (value: Row, end: boolean) => { const hour = value[end ? 'ToHour' : 'FromHour'], minute = value[end ? 'ToMinute' : 'FromMinute'];if (typeof hour !== 'number' || !Number.isInteger(hour) || typeof minute !== 'string' || !Object.hasOwn(minutes, minute)) throw new AdportError('PROVIDER_ERROR', 'microsoft: native schedule interval is incomplete');return hour * 60 + minutes[minute as keyof typeof minutes]; };\n if (touched.has('DayTime')) for (const day of new Set(schedule.map(value => value.Day))) { const entries = schedule.filter(value => value.Day === day).sort((a, b) => number(a, false) - number(b, false));if (entries.length > 7 || entries.some((value, index) => number(value, true) <= number(value, false) || index > 0 && number(value, false) < number(entries[index - 1]!, true))) throw new AdportError('INVALID_INPUT', 'microsoft: schedules must not overlap or exceed seven per day'); }\n if (touched.has('Location') && values.filter(value => kind(value) === 'Location').length > 10_000) throw new AdportError('INVALID_INPUT', 'microsoft: combined included/excluded locations exceed10000');\n }\n}\nfunction rowsOfIds(value: unknown): string[] { if (!Array.isArray(value)) return [];return value.map(nativeId); }\nfunction contains(actual: Row, expected: Row): boolean { return Object.entries(expected).every(([key, value]) => value && typeof value === 'object' && !Array.isArray(value) ? actual[key] && typeof actual[key] === 'object' && contains(row(actual[key]), row(value)) : key === 'Type' ? String(actual[key]).replace(/Criterion$/, '') === String(value).replace(/Criterion$/, '') : String(actual[key]) === String(value)); }\nexport function microsoftGeneralTargetingTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'audiences' as const, exposure: 'specialist' as const };\n return [\n defineTool({ name: 'microsoft_targeting_context', namespace: 'microsoft', catalog, description: 'Read owned and inherited campaign/ad-group general targets, effective sources, schedule clock and context_hash. Seven concrete types, complete bounded context and stable paging; bid values are percentages. This is not audience targeting or every native targeting family.', input: targetingRead, presentation: 'records', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: input => provider.generalTargeting.list(input) }),\n guardedWriteTool({ name: 'microsoft_update_targeting', namespace: 'microsoft', provider: 'microsoft', catalog, kind: 'update', description: 'Edit scoped targeting with expected_context_hash and delivery-effects acknowledgement. One native add, remove, bid, location-intent or schedule-clock operation per approval. Preserves unmentioned criteria/status/budgets; checks inheritance, full devices and schedule limits. New criteria require an effectively paused parent under paused_creation.', payload: targetingWrite }),\n ];\n}\n","import { z } from 'zod';\nimport { microsoftId as id } from './native.js';\nimport { bidType, criterionType, deviceAdjustment, intent, target, validateTargetBatch } from './targeting-schemas.js';\n\nexport const targetSelection = z.discriminatedUnion('type', [z.object({ type: z.literal('Campaign'), campaign_id: id }).strict(), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id }).strict()]);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const targetingRead = z.object({ account_id: id, target: targetSelection, criterion_types: z.array(criterionType).min(1).max(7).refine(values => new Set(values).size === values.length, 'Use unique types').default([...criterionType.options]), page_size: z.number().int().min(1).max(200).default(50), cursor: z.string().max(2048).optional() }).strict();\nconst change = z.discriminatedUnion('action', [\n z.object({ action: z.literal('add'), targets: z.array(target).min(1).max(1000) }).strict().superRefine(validateTargetBatch),\n z.object({ action: z.literal('set_bid'), criterion_id: id, criterion_type: bidType, bid_adjustment_percent: deviceAdjustment }).strict().refine(value => value.criterion_type === 'Device' || value.bid_adjustment_percent >= -90, 'Only devices support adjustments below -90 percent'),\n z.object({ action: z.literal('remove'), criterion_ids: z.array(id).min(1).max(1000).refine(values => new Set(values).size === values.length, 'Use unique IDs') }).strict(),\n z.object({ action: z.literal('set_location_intent'), criterion_id: id, intent_option: intent }).strict(),\n z.object({ action: z.literal('set_schedule_clock'), use_searcher_time_zone: z.boolean() }).strict(),\n]);\nexport const targetingWrite = z.object({ target: targetSelection, expected_context_hash: hash, acknowledge_delivery_effects: z.literal(true), change }).strict();\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), name = z.string().min(1).max(128).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst date = z.iso.date(), split = z.number().int().min(1).max(99);\nconst create = z.object({ base_campaign_id: id, expected_base_context_hash: hash, name, start_date: date, end_date: date.optional(), traffic_split_percent: split, experiment_type: z.enum(['TrafficBased', 'CookieBased']).default('TrafficBased') }).refine(value => !value.end_date || value.start_date <= value.end_date, 'End date must be on or after start date');\nconst reference = z.object({ experiment_id: id, expected_snapshot_hash: hash });\nconst update = reference.extend({ name: name.optional(), start_date: date.optional(), end_date: date.nullable().optional(), traffic_split_percent: split.optional() }).refine(value => ['name', 'start_date', 'end_date', 'traffic_split_percent'].some(key => value[key as keyof typeof value] !== undefined), 'Supply an editable experiment field');\nconst additional = 'ExperimentSubType, ExperimentArms, ExperimentCampaignType';\nconst notes = ['Microsoft copies eligible base-campaign settings and child entities into an experiment campaign. Expired ad groups, legacy ad formats and some legacy keyword/audience settings are not copied; native copy diagnostics can report omissions.', 'The experiment campaign inherits the base budget, BudgetType, status and timezone. TrafficSplitPercent divides the existing base budget/traffic; the branch is not an additional independent daily pool. Pause or change budget through the base campaign.', 'Dates are calendar dates in the base campaign timezone; end dates are inclusive. Setup is asynchronous. A returned experiment ID or Creating status does not prove the campaign copy is ready.', 'Snapshots cover the experiment and parent/branch campaign configuration plus the visible active experiment inventory, not every child entity. Microsoft provides no atomic compare-and-set; external changes can race submission.'];\nconst contextSchema = z.object({ account_id: id, base_campaign: z.record(z.string(), z.unknown()), active_experiments: z.array(z.record(z.string(), z.unknown())), currency: z.string().optional(), snapshot_hash: hash });\nconst viewSchema = z.object({ account_id: id, experiment: z.record(z.string(), z.unknown()), base_context: contextSchema, experiment_campaign: z.record(z.string(), z.unknown()).optional(), snapshot_hash: hash, notes: z.array(z.string()) });\ntype Context = z.infer<typeof contextSchema>;\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst optionalId = (value: unknown) => value === null || value === undefined || value === '0' || value === 0 ? undefined : nativeId(value);\nfunction nativeDate(value: string): Row { const [Year, Month, Day] = value.split('-').map(Number); return { Day, Month, Year }; }\nfunction calendarDate(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n const row = z.object({ Year: z.number().int(), Month: z.number().int(), Day: z.number().int() }).parse(value);\n if (row.Year === 0 && row.Month === 0 && row.Day === 0) return undefined;\n return date.parse(`${String(row.Year).padStart(4, '0')}-${String(row.Month).padStart(2, '0')}-${String(row.Day).padStart(2, '0')}`);\n}\nconst micros = (value: unknown) => { if (typeof value !== 'number' || value <= 0 || !Number.isSafeInteger(Math.round(value * 1_000_000)) || Math.abs(value * 1_000_000 - Math.round(value * 1_000_000)) > 0.000001) throw new AdportError('PROVIDER_ERROR', 'microsoft: base campaign daily budget cannot be represented safely in micros'); return Math.round(value * 1_000_000); };\nexport const MICROSOFT_EXPERIMENT_WRITES = new Set(['microsoft_create_experiment', 'microsoft_update_experiment', 'microsoft_end_experiment', 'microsoft_delete_experiment']);\n\n/** Native v13 experiments: Active is the required setup input, not an independently pausable branch status. */\nexport class MicrosoftExperimentService extends MicrosoftNativeService {\n constructor(...args: [...ConstructorParameters<typeof MicrosoftNativeService>, (account: string) => Promise<unknown>, (account: string) => Promise<string | undefined>]) {\n const [client, scope, campaign, campaigns, currency] = args; super(client, scope, campaign); this.campaigns = campaigns; this.currency = currency;\n }\n private readonly campaigns: (account: string) => Promise<unknown>;\n private readonly currency: (account: string) => Promise<string | undefined>;\n\n private async query(account: string, ids: string[] | null): Promise<Row[]> {\n const result = await this.request(account, 'Experiments/QueryByIds', { ExperimentIds: ids, ReturnAdditionalFields: additional });\n if (!Object.hasOwn(result, 'Experiments') || result.Experiments !== null && !Array.isArray(result.Experiments)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment response envelope is missing or malformed');\n const values = rows((result.Experiments as unknown[] | null)?.filter(value => value !== null));\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => ids && !ids.includes(nativeId(value.Id)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate or unexpected experiment identities');\n return values;\n }\n\n private async campaignById(account: string, campaignId: string, type: unknown): Promise<Row | undefined> {\n const result = await this.request(account, 'Campaigns/QueryByIds', { AccountId: account, CampaignIds: [campaignId], CampaignType: type, ReturnAdditionalFields: 'TargetSetting' });\n if (!Object.hasOwn(result, 'Campaigns') || result.Campaigns !== null && !Array.isArray(result.Campaigns)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment campaign response envelope is missing');\n const campaigns = rows((result.Campaigns as unknown[] | null)?.filter(value => value !== null));\n if (campaigns.length > 1 || campaigns.some(value => nativeId(value.Id) !== campaignId || value.CampaignType !== type)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment campaign identity/type mismatch');\n return campaigns[0];\n }\n\n async base(account: string, campaignId: string, refresh = false): Promise<Context> {\n await this.accountScope(account, refresh);\n const known = await this.campaign(account, campaignId), base = await this.campaignById(account, campaignId, known.CampaignType);\n if (!base || typeof base.Name !== 'string' || typeof base.Status !== 'string' || typeof base.TimeZone !== 'string') throw new AdportError('PROVIDER_ERROR', 'microsoft: base campaign configuration is incomplete');\n const active = (await this.query(account, null)).filter(value => nativeId(value.BaseCampaignId) === campaignId).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), currency = await this.currency(account);\n const visible = { account_id: account, base_campaign: base, active_experiments: active, ...(currency ? { currency } : {}) };\n return { ...visible, snapshot_hash: digest(visible) };\n }\n\n async list(input: { account_id: string; after_experiment_id?: string; limit: number }) {\n const remaining = (await this.query(input.account_id, null)).filter(value => !input.after_experiment_id || BigInt(nativeId(value.Id)) > BigInt(input.after_experiment_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { rows: page, truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}), visibility: 'Native active inventory only; use microsoft_get_experiment for an exact known historical ID.', notes };\n }\n\n async get(account: string, experimentId: string, refresh = false) {\n await this.accountScope(account, refresh);\n const values = await this.query(account, [experimentId]), experiment = values[0];\n if (!experiment) throw new AdportError('INVALID_INPUT', 'microsoft: experiment was not found in the selected account');\n const context = await this.base(account, nativeId(experiment.BaseCampaignId)), branchId = optionalId(experiment.ExperimentCampaignId), branch = branchId ? await this.campaignById(account, branchId, context.base_campaign.CampaignType) : undefined;\n if (branchId && (!branch || optionalId(branch.ExperimentId) !== experimentId)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment campaign ownership could not be verified');\n const visible = { account_id: account, experiment, base_context: context, ...(branch ? { experiment_campaign: branch } : {}) };\n return { ...visible, snapshot_hash: digest(visible), notes };\n }\n\n private eligible(context: Context) {\n const base = context.base_campaign;\n if (!['Audience', 'Search', 'Shopping', 'PerformanceMax'].includes(String(base.CampaignType)) || optionalId(base.ExperimentId) || !Object.hasOwn(base, 'ExperimentId') || optionalId(base.BudgetId) || base.SubType !== undefined && base.SubType !== null && base.SubType !== '' || rows(base.Settings).some(value => /dynamicsearch/i.test(String(value.Type)))) throw new AdportError('INVALID_INPUT', 'microsoft: experiments require a verified non-experiment base without shared budgets, Dynamic Search Ads, mixed or other specialized subtypes');\n if (base.BudgetType !== 'DailyBudgetStandard') throw new AdportError('INVALID_INPUT', 'microsoft: experiment base must use DailyBudgetStandard');\n micros(base.DailyBudget);\n }\n\n private budget(context: Context) {\n const value = micros(context.base_campaign.DailyBudget);\n return [{ target: `base campaign ${nativeId(context.base_campaign.Id)} inherited total daily pool (split, not additional)`, ...(context.currency ? { currency: context.currency } : {}), fromMicros: value, toMicros: value }];\n }\n\n private async unique(account: string, value: string, exceptExperiment?: string, exceptCampaign?: string) {\n const campaigns = rows(await this.campaigns(account)), experiments = await this.query(account, null);\n if (campaigns.some(row => nativeId(row.Id) !== exceptCampaign && typeof row.Name === 'string' && row.Name.toLowerCase() === value.toLowerCase()) || experiments.some(row => nativeId(row.Id) !== exceptExperiment && typeof row.Name === 'string' && row.Name.toLowerCase() === value.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: experiment name conflicts with a visible campaign or experiment');\n }\n\n private interval(context: Context, start: string, end?: string, except?: string) {\n if (context.active_experiments.some(value => {\n if (nativeId(value.Id) === except) return false;\n const from = calendarDate(value.StartDate), to = calendarDate(value.EndDate) ?? '9999-12-31';\n return !from || start <= to && from <= (end ?? '9999-12-31');\n })) throw new AdportError('INVALID_INPUT', 'microsoft: experiment date range overlaps the visible active inventory or an existing range is unverifiable');\n }\n\n private async confirmed(ids: string[], verify: () => Promise<boolean>): Promise<string[]> {\n try { if (!await verify()) throw new Error('Native readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment write was accepted but its readback is unconfirmed; reconcile these IDs before retrying', { resourceIds: ids }); }\n return ids;\n }\n\n private async removedAfterDelete(account: string, kind: 'experiment' | 'campaign', targetId: string, campaignType?: unknown): Promise<boolean> {\n const experiment = kind === 'experiment', collection = experiment ? 'Experiments' : 'Campaigns';\n const result = await this.client.request<Row>('campaign', 'POST', `${collection}/QueryByIds`, experiment\n ? { ExperimentIds: [targetId], ReturnAdditionalFields: additional }\n : { AccountId: account, CampaignIds: [targetId], CampaignType: campaignType, ReturnAdditionalFields: 'TargetSetting' }, await this.accountScope(account));\n const values = result[collection];\n if (!Array.isArray(values) || values.length > 1 || result.NestedPartialErrors !== undefined && result.NestedPartialErrors !== null && (!Array.isArray(result.NestedPartialErrors) || result.NestedPartialErrors.some(Boolean))) return false;\n const errors = z.array(z.record(z.string(), z.unknown()).nullable()).parse(result.PartialErrors ?? []).filter(value => value !== null);\n if (!errors.length) return values.every(value => value === null || nativeId(value.Id) === targetId && value[experiment ? 'ExperimentStatus' : 'Status'] === 'Deleted');\n // Live-confirmed receipts after deleting previously verified owned IDs:\n // 6110/null experiment and 1120/null campaign. Neither error is a general\n // not-found signal: ordinary reads still fail, and independent inventories\n // plus the preserved base are checked before reporting deletion success.\n return values.length === 1 && values[0] === null && errors.length === 1 && errors[0]!.Index === 0\n && errors[0]!.Code === (experiment ? 6110 : 1120)\n && errors[0]!.ErrorCode === (experiment ? 'ExperimentIdInvalid' : 'CampaignServiceInvalidCampaignStatus');\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const kinds = { microsoft_create_experiment: 'create', microsoft_update_experiment: 'update', microsoft_end_experiment: 'update', microsoft_delete_experiment: 'remove' } as const;\n if (op.provider !== 'microsoft' || !MICROSOFT_EXPERIMENT_WRITES.has(op.tool) || op.kind !== kinds[op.tool as keyof typeof kinds]) throw new AdportError('INVALID_INPUT', 'microsoft: experiment operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_create_experiment') {\n const input = create.parse(op.payload), context = await this.base(account, input.base_campaign_id, true); this.eligible(context);\n if (context.snapshot_hash !== input.expected_base_context_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: experiment base context changed; read fresh context and request a new preview');\n if (guard.forcePausedCreation && context.base_campaign.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: experiment campaign status is inherited; paused_creation requires a currently Paused base campaign');\n await this.unique(account, input.name);\n const start = input.start_date;\n if (context.active_experiments.length >= 10) throw new AdportError('INVALID_INPUT', 'microsoft: visible experiment inventory has reached the native ten-experiment limit for this base');\n this.interval(context, start, input.end_date);\n const fields = { BaseCampaignId: input.base_campaign_id, Name: input.name, StartDate: nativeDate(start), ...(input.end_date ? { EndDate: nativeDate(input.end_date) } : {}), TrafficSplitPercent: input.traffic_split_percent, ExperimentType: input.experiment_type, ExperimentStatus: 'Active' };\n return { summary: `Create Microsoft experiment \"${input.name}\" from \"${String(context.base_campaign.Name)}\"`, changes: [`+ ${JSON.stringify(fields)}`, `Creates an asynchronous campaign copy inheriting base ${context.base_campaign.Status} status, ${context.base_campaign.DailyBudget} daily budget and ${context.base_campaign.TimeZone} timezone. Required native Active setup input transitions to Creating; it is not an independent branch activation.`, 'Existing total base daily allocation is split, not increased. Native name/history and experiment limits remain authoritative.'], fieldChanges: [{ field: 'Experiment', before: '(new)', after: input.name }, { field: 'Base campaign', before: '(none)', after: `${String(context.base_campaign.Name)} (${input.base_campaign_id})` }, { field: 'Experiment traffic/budget share', before: '0%', after: `${input.traffic_split_percent}% of existing base pool` }, { field: 'Inherited serving status', before: String(context.base_campaign.Status), after: String(context.base_campaign.Status) }], notes, coercions: [], budgetDeltas: this.budget(context), execute: async () => {\n const result = await this.request(account, 'Experiments', { Experiments: [fields] }), ids = z.array(z.unknown()).parse(result.ExperimentIds).filter(value => value !== null).map(nativeId);\n if (ids.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.confirmed(ids, async () => { const after = await this.get(account, ids[0]!); return nativeId(after.experiment.BaseCampaignId) === input.base_campaign_id && after.experiment.Name === input.name && ['Creating', 'Active', 'Paused', 'Scheduled'].includes(String(after.experiment.ExperimentStatus)) && (!guard.forcePausedCreation || after.base_context.base_campaign.Status === 'Paused' && (!after.experiment_campaign || after.experiment_campaign.Status === 'Paused')); });\n } };\n }\n const input = (op.tool === 'microsoft_update_experiment' ? update : reference).parse(op.payload), current = await this.get(account, input.experiment_id, true), experiment = current.experiment, context = current.base_context, status = String(experiment.ExperimentStatus);\n if (input.expected_snapshot_hash !== current.snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: experiment or coupled campaign context changed; request a fresh preview');\n if (['Promoting', 'Graduating'].includes(status)) throw new AdportError('INVALID_INPUT', 'microsoft: reconcile the in-progress experiment transition before another mutation');\n if (op.tool === 'microsoft_delete_experiment') {\n const branchId = optionalId(experiment.ExperimentCampaignId), baseId = nativeId(experiment.BaseCampaignId);\n return { summary: `Delete Microsoft experiment \"${String(experiment.Name)}\" and its campaign copy`, changes: [`- experiment ${input.experiment_id}${branchId ? ` and experiment campaign ${branchId}` : ' (no experiment campaign ID returned yet)'}`, 'Native deletion is coupled to the experiment campaign. The base campaign is preserved.'], fieldChanges: [{ field: 'Experiment and campaign copy', before: `${String(experiment.Name)} (${input.experiment_id})`, after: 'Deleted together' }], notes, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, 'Experiments', { ExperimentIds: [input.experiment_id] }, 'DELETE');\n return this.confirmed([input.experiment_id, ...(branchId ? [branchId] : [])], async () => {\n if (!await this.removedAfterDelete(account, 'experiment', input.experiment_id) || branchId && !await this.removedAfterDelete(account, 'campaign', branchId, context.base_campaign.CampaignType)) return false;\n const base = await this.campaignById(account, baseId, context.base_campaign.CampaignType), active = await this.query(account, null), campaigns = rows(await this.campaigns(account));\n return !!base && base.Status === context.base_campaign.Status && base.DailyBudget === context.base_campaign.DailyBudget && !active.some(value => nativeId(value.Id) === input.experiment_id) && !campaigns.some(value => value.Status !== 'Deleted' && (nativeId(value.Id) === branchId || optionalId(value.ExperimentId) === input.experiment_id));\n });\n } };\n }\n if (!['Active', 'Paused', 'Scheduled', 'Ended'].includes(status)) throw new AdportError('INVALID_INPUT', 'microsoft: experiment is not in a supported settled state for this edit');\n let fields: Row, fieldChanges: Array<{ field: string; before: string; after: string }>;\n if (op.tool === 'microsoft_end_experiment') {\n if (status === 'Ended') throw new AdportError('INVALID_INPUT', 'microsoft: experiment is already ended');\n fields = { Id: input.experiment_id, ExperimentStatus: 'Ended' }; fieldChanges = [{ field: 'Experiment status', before: status, after: 'Ended (cannot restart)' }];\n } else {\n const edit = update.parse(input);\n if (status === 'Ended') throw new AdportError('INVALID_INPUT', 'microsoft: ended experiments cannot be edited; deletion is a separate operation');\n if ((edit.start_date !== undefined || edit.traffic_split_percent !== undefined) && status !== 'Scheduled') throw new AdportError('INVALID_INPUT', 'microsoft: start-date and split edits require native Scheduled status; Paused does not prove the experiment never started');\n const from = edit.start_date ?? calendarDate(experiment.StartDate), to = edit.end_date === null ? undefined : edit.end_date ?? calendarDate(experiment.EndDate);\n if (!from || to && from > to) throw new AdportError('INVALID_INPUT', 'microsoft: experiment date interval is invalid or unavailable');\n if (edit.start_date !== undefined || edit.end_date !== undefined) this.interval(context, from, to, input.experiment_id);\n if (edit.name !== undefined) await this.unique(account, edit.name, input.experiment_id, optionalId(experiment.ExperimentCampaignId));\n fields = { Id: input.experiment_id, ...(edit.name !== undefined ? { Name: edit.name } : {}), ...(edit.start_date !== undefined ? { StartDate: nativeDate(edit.start_date) } : {}), ...(edit.end_date !== undefined ? { EndDate: edit.end_date === null ? { Day: 0, Month: 0, Year: 0 } : nativeDate(edit.end_date) } : {}), ...(edit.traffic_split_percent !== undefined ? { TrafficSplitPercent: edit.traffic_split_percent } : {}) };\n fieldChanges = Object.entries(fields).filter(([key]) => key !== 'Id').map(([field, value]) => ({ field, before: JSON.stringify(experiment[field] ?? null), after: JSON.stringify(value) }));\n }\n return { summary: `${op.tool === 'microsoft_end_experiment' ? 'End' : 'Update'} Microsoft experiment \"${String(experiment.Name)}\"`, changes: [`~ ${JSON.stringify(fields)}`, 'Names are coupled to the experiment campaign; other branch settings, base status and the inherited total budget are preserved. Ending is irreversible and pauses the experiment campaign.'], fieldChanges, notes, coercions: [], budgetDeltas: this.budget(context), execute: async () => {\n await this.request(account, 'Experiments', { Experiments: [fields] }, 'PUT');\n return this.confirmed([input.experiment_id], async () => { const after = await this.get(account, input.experiment_id); return Object.entries(fields).filter(([key]) => key !== 'Id').every(([key, value]) => key === 'EndDate' ? calendarDate(after.experiment.EndDate) === calendarDate(value) : key === 'StartDate' ? calendarDate(after.experiment.StartDate) === calendarDate(value) : after.experiment[key] === value) && after.base_context.base_campaign.Status === context.base_campaign.Status && after.base_context.base_campaign.DailyBudget === context.base_campaign.DailyBudget && (op.tool !== 'microsoft_end_experiment' || !after.experiment_campaign || after.experiment_campaign.Status === 'Paused'); });\n } };\n }\n}\n\nexport function microsoftExperimentTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_experiments', namespace: 'microsoft', description: 'Read native active experiments only; this inventory does not establish absence of historical experiments. Use get for an exact known ID. Continue next_cursor as after_experiment_id.', input: z.object({ account_id: id, after_experiment_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean(), next_cursor: id.optional(), visibility: z.string(), notes: z.array(z.string()) }), pagination: { cursorInput: 'after_experiment_id' }, annotations: { readOnly: true }, handler: input => provider.experiments.list(input) }),\n defineTool({ name: 'microsoft_experiment_base_context', namespace: 'microsoft', description: 'Read an owned base campaign, its native active experiments, currency and snapshot_hash for creation. Budgets/status/timezone are inherited by experiment copies. Snapshot covers campaign configuration and visible active inventory, not every child entity.', input: z.object({ account_id: id, base_campaign_id: id }), output: contextSchema, annotations: { readOnly: true }, handler: input => provider.experiments.base(input.account_id, input.base_campaign_id) }),\n defineTool({ name: 'microsoft_get_experiment', namespace: 'microsoft', description: 'Read an exact known experiment, verified base/experiment campaign ownership, native setup state and coupled snapshot_hash. Creating is asynchronous acceptance, not readiness.', input: z.object({ account_id: id, experiment_id: id }), output: viewSchema, annotations: { readOnly: true }, handler: input => provider.experiments.get(input.account_id, input.experiment_id) }),\n guardedWriteTool({ name: 'microsoft_create_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create a native campaign-copy experiment with expected_base_context_hash. Paused creation requires a currently Paused base; native Active setup input becomes Creating. Dates use base timezone. Splits existing daily budget/traffic rather than adding a pool. Shared-budget, DSA, mixed/specialized or experiment bases are rejected. Setup is asynchronous.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit experiment name or calendar schedule with expected_snapshot_hash. Name changes rename the campaign copy. Native Scheduled status is required before changing start/split; Paused alone is insufficient. end_date:null clears expiry with the native zero Date. No promotion or graduation.', payload: update }),\n guardedWriteTool({ name: 'microsoft_end_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'End an owned settled experiment early with expected_snapshot_hash. This cannot be restarted and pauses its campaign copy; the base campaign is preserved. Pausing temporarily is instead coupled to pausing the base campaign.', payload: reference }),\n guardedWriteTool({ name: 'microsoft_delete_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Delete an exact owned experiment and its coupled campaign copy with expected_snapshot_hash; preserve the base. Confirms disappearance before success. Do not retry accepted-but-unconfirmed receipts without reconciling their IDs.', payload: reference }),\n ];\n}\n","import { DATE_PRESETS, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { MicrosoftAdsProvider } from './provider.js';\nimport { microsoftChildTools } from './child-tools.js';\nimport { microsoftImageTools } from './images.js';\nimport { microsoftExtensionTools } from './extensions.js';\nimport { microsoftTargetingTools } from './targeting.js';\nimport { microsoftGeneralTargetingTools } from './general-targeting.js';\nimport { microsoftNegativeKeywordTools } from './negative-keywords.js';\nimport { microsoftBudgetTools } from './budgets.js';\nimport { microsoftPlanningTools } from './planning.js';\nimport { microsoftConversionTools } from './conversions.js';\nimport { microsoftAudienceTools } from './audiences.js';\nimport { microsoftAudienceTargetingTools } from './audience-targeting.js';\nimport { microsoftOfflineReportTools } from './offline-reports.js';\nimport { microsoftOfflineConversionTools } from './offline-conversions.js';\nimport { microsoftExperimentTools } from './experiments.js';\n\nconst statusSchema = z.enum(['Active', 'Paused']);\n\nexport function microsoftTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n ...microsoftChildTools(provider),\n ...microsoftImageTools(provider),\n ...microsoftExtensionTools(provider),\n ...microsoftTargetingTools(provider),\n ...microsoftGeneralTargetingTools(provider),\n ...microsoftNegativeKeywordTools(provider),\n ...microsoftBudgetTools(provider),\n ...microsoftPlanningTools(provider),\n ...microsoftConversionTools(provider),\n ...microsoftAudienceTools(provider),\n ...microsoftAudienceTargetingTools(provider),\n ...microsoftOfflineReportTools(provider),\n ...microsoftOfflineConversionTools(provider),\n ...microsoftExperimentTools(provider),\n ...(['keyword', 'search_term'] as const).map(kind => defineTool({\n name: `microsoft_${kind}_report`, namespace: 'microsoft',\n description: `Read the native Microsoft ${kind.replace('_', ' ')} performance report through Submit/Poll/CSV. Native numeric values remain strings; empty or unavailable values are preserved.`,\n input: z.object({ account_id: z.string().regex(/^\\d+$/), date_range: z.union([z.enum(DATE_PRESETS), z.object({ start: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/), end: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/) })]).default('last_7_days'), limit: z.number().int().positive().max(5000).default(1000) }),\n output: z.object({ rows: z.array(z.record(z.string(), z.string())), truncated: z.boolean(), report_type: z.string() }),\n annotations: { readOnly: true }, handler: input => provider.nativeReport({ ...input, kind }),\n })),\n defineTool({\n name: 'microsoft_api_read',\n namespace: 'microsoft',\n description:\n 'Call any documented Microsoft Advertising v13 query, search, get, or reporting submit/poll operation with selected-account headers.',\n input: z.object({\n account_id: z.string(),\n service: z.enum(['campaign', 'customer', 'reporting', 'adinsight']),\n path: z.string().min(3).describe('REST operation path, e.g. AdGroups/QueryByCampaignId or GenerateReport/Submit'),\n body: z.record(z.string(), z.unknown()).optional(),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n return provider.apiRead(input);\n },\n }),\n defineTool({\n name: 'microsoft_campaigns',\n namespace: 'microsoft',\n description:\n 'List all eight Microsoft Advertising campaign types (Id, Name, Status, DailyBudget in account currency, BudgetId when shared).',\n input: z.object({ account_id: z.string().describe('Ad account id') }),\n annotations: { readOnly: true },\n async handler(input) {\n const campaigns = await provider.listCampaigns(input.account_id);\n return { campaigns };\n },\n }),\n guardedWriteTool({\n name: 'microsoft_create_campaign',\n namespace: 'microsoft',\n description:\n 'Create a Microsoft Advertising Search campaign. daily_budget is a float in account currency. ' +\n \"The API's own default status is Paused. No server dry-run — previews are client-side diffs.\",\n provider: 'microsoft',\n kind: 'create',\n payload: z.object({\n name: z.string().min(1).max(128),\n daily_budget: z.number().positive(),\n time_zone: z.string().optional().describe('Bing Ads time zone name, default PacificTimeUSCanadaTijuana'),\n status: statusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'microsoft_set_campaign_status',\n namespace: 'microsoft',\n description: 'Activate or pause a Microsoft Advertising base campaign; related active/scheduled experiments inherit its serving status. Direct experiment-campaign status edits are refused.',\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), status: statusSchema }),\n }),\n guardedWriteTool({\n name: 'microsoft_set_budget',\n namespace: 'microsoft',\n description:\n \"Change a Microsoft base campaign's DailyBudget (float, account currency). Related campaign-copy experiments split this total pool. Direct experiment-campaign edits and shared budgets are refused.\",\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), daily_budget: z.number().positive() }),\n }),\n guardedWriteTool({\n name: 'microsoft_api_create',\n namespace: 'microsoft',\n description:\n 'Create through Microsoft Campaign Management v13 using its documented API body. Under paused creation, campaigns/ad groups/ads/keywords receive explicit Paused status, including omitted status. Budget fields are policy-checked; shared budgets, conversion goals, UET tags and audiences require typed tools.',\n provider: 'microsoft',\n kind: 'create',\n payload: z.object({ resource: z.string().min(2), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'microsoft_api_update',\n namespace: 'microsoft',\n description: 'Update non-budget fields through any Microsoft Advertising Campaign Management v13 collection.',\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ resource: z.string().min(2), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'microsoft_api_delete',\n namespace: 'microsoft',\n description: 'Permanently delete through any Microsoft Advertising Campaign Management v13 collection.',\n provider: 'microsoft',\n kind: 'remove',\n destructive: true,\n payload: z.object({ resource: z.string().min(2), body: z.record(z.string(), z.unknown()) }),\n }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst id = z.string().regex(/^\\d+$/);\nconst parent = { campaign_id: id, ad_group_id: id };\nconst status = z.enum(['Active', 'Paused']);\nexport const microsoftAdTypes = ['ResponsiveSearch', 'Responsive', 'DynamicSearch', 'ExpandedText', 'AppInstall', 'Product'] as const;\nconst headlines = z.array(z.string().min(1).max(30)).min(3).max(15).refine(value => new Set(value).size === value.length, 'Headlines must be unique');\nconst descriptions = z.array(z.string().min(1).max(90)).min(2).max(4).refine(value => new Set(value).size === value.length, 'Descriptions must be unique');\nconst urls = z.array(z.string().url().refine(value => ['http:', 'https:'].includes(new URL(value).protocol))).min(1).max(10);\nconst copy = { headlines, descriptions, final_urls: urls, path1: z.string().max(15).optional(), path2: z.string().max(15).optional() };\nconst rows = z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() });\n\nexport function microsoftChildTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n const write = (name: string, description: string, payload: z.ZodObject<z.ZodRawShape>, kind: 'create' | 'update' | 'remove' = 'update') =>\n guardedWriteTool({ name, namespace: 'microsoft', provider: 'microsoft', description, payload, kind });\n return [\n defineTool({ name: 'microsoft_ad_groups', namespace: 'microsoft', description: 'Read ad groups and their bids/statuses after verifying the campaign belongs to the selected account.',\n input: z.object({ account_id: id, campaign_id: id }), output: rows, annotations: { readOnly: true }, handler: input => provider.children.listGroups(input) }),\n defineTool({ name: 'microsoft_ads', namespace: 'microsoft', description: 'Read ad configuration and creative copy with visual edit actions. Verifies the campaign/ad-group hierarchy in the selected account.',\n input: z.object({ account_id: id, ...parent, ad_types: z.array(z.enum(microsoftAdTypes)).min(1).default(['ResponsiveSearch']), limit: z.number().int().positive().max(200).default(50) }),\n output: creativesOutput.extend({ ads: z.array(z.record(z.string(), z.unknown())) }), presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.children.listAds(input) }),\n defineTool({ name: 'microsoft_keywords', namespace: 'microsoft', description: 'Read ad-group keywords, including bids, match types, statuses and URLs, within the selected campaign/account.',\n input: z.object({ account_id: id, ...parent }), output: rows, annotations: { readOnly: true }, handler: input => provider.children.listKeywords(input) }),\n write('microsoft_create_ad_group', 'Create a SearchStandard ad group in an account-owned campaign. CPC bid uses whole account-currency units; policy may force Paused.',\n z.object({ campaign_id: id, name: z.string().min(1).max(256), language: z.string().min(1).describe('Microsoft language name, e.g. English or German; chosen explicitly for ad-group targeting'), cpc_bid: z.number().positive().optional(), status: status.default('Paused') }), 'create'),\n write('microsoft_set_ad_group_status', 'Activate or pause an account-owned ad group; the parent campaign status remains unchanged.', z.object({ ...parent, status })),\n write('microsoft_update_ad_group', 'Rename an ad group or change its CPC bid in whole currency units. Campaign and ad-group status remain unchanged.',\n z.object({ ...parent, name: z.string().min(1).max(256).optional(), cpc_bid: z.number().positive().optional() }).refine(value => value.name !== undefined || value.cpc_bid !== undefined, 'Provide name or cpc_bid')),\n write('microsoft_create_responsive_search_ad', 'Create a responsive search ad using 3–15 unique headlines and 2–4 unique descriptions in a SearchStandard ad group. Policy may force Paused.',\n z.object({ ...parent, ...copy, status: status.default('Paused') }), 'create'),\n write('microsoft_update_responsive_search_ad', 'Edit supplied responsive search ad fields. Omitted fields and serving status are preserved; existing positional pinning is retained.',\n z.object({ ...parent, ad_id: id, headlines: headlines.optional(), descriptions: descriptions.optional(), final_urls: urls.optional(), path1: copy.path1, path2: copy.path2 })\n .refine(value => ['headlines', 'descriptions', 'final_urls', 'path1', 'path2'].some(key => value[key as keyof typeof value] !== undefined), 'Provide a content field')),\n write('microsoft_set_ad_status', 'Activate or pause an ad after verifying its exact parent hierarchy. Parent delivery settings remain unchanged.',\n z.object({ ...parent, ad_id: id, ad_type: z.enum(microsoftAdTypes).default('ResponsiveSearch'), status })),\n write('microsoft_add_keywords', 'Create up to 100 keywords in an account-owned ad group. Bids use whole currency units. Policy may force Paused.',\n z.object({ ...parent, keywords: z.array(z.object({ text: z.string().min(1).max(100), match_type: z.enum(['Broad', 'Phrase', 'Exact']), bid: z.number().positive().optional(), status: status.default('Paused') })).min(1).max(100) }), 'create'),\n write('microsoft_set_keyword_status', 'Activate or pause one verified keyword without replacing its text, match type or bid.', z.object({ ...parent, keyword_id: id, status })),\n write('microsoft_set_keyword_bid', 'Change one verified keyword bid in whole currency units; keyword and parent statuses remain unchanged.', z.object({ ...parent, keyword_id: id, bid: z.number().positive() })),\n write('microsoft_remove_keywords', 'Permanently remove verified keyword IDs from an ad group. This cannot be undone; use microsoft_set_keyword_status to pause instead.',\n z.object({ ...parent, keyword_ids: z.array(id).min(1).max(100).refine(value => new Set(value).size === value.length, 'Keyword IDs must be unique') }), 'remove'),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { MicrosoftAdsClient, type MicrosoftCredentials } from './client.js';\nimport { MicrosoftAdsProvider } from './provider.js';\nimport { microsoftTools } from './tools.js';\n\nexport {\n MicrosoftAdsClient,\n MSADS_SCOPE,\n SANDBOX_DEVELOPER_TOKEN,\n formatMicrosoftError,\n formatPartialErrors,\n type MicrosoftCredentials,\n} from './client.js';\nexport { MicrosoftAdsProvider, UNITS_TO_MICROS } from './provider.js';\nexport { microsoftTools } from './tools.js';\nexport { parseCsv } from './csv.js';\n\nexport async function resolveMicrosoftCredentials(store: CredentialStore): Promise<MicrosoftCredentials | undefined> {\n const record = await store.get('microsoft');\n if (record?.data.developer_token && record.data.client_id && record.data.refresh_token) {\n return {\n developerToken: record.data.developer_token,\n clientId: record.data.client_id,\n refreshToken: record.data.refresh_token,\n clientSecret: record.data.client_secret || undefined,\n sandbox: record.data.sandbox === 'true',\n };\n }\n const env = process.env;\n if (env.MICROSOFT_ADS_DEVELOPER_TOKEN && env.MICROSOFT_ADS_CLIENT_ID && env.MICROSOFT_ADS_REFRESH_TOKEN) {\n return {\n developerToken: env.MICROSOFT_ADS_DEVELOPER_TOKEN,\n clientId: env.MICROSOFT_ADS_CLIENT_ID,\n refreshToken: env.MICROSOFT_ADS_REFRESH_TOKEN,\n clientSecret: env.MICROSOFT_ADS_CLIENT_SECRET || undefined,\n sandbox: env.MICROSOFT_ADS_SANDBOX === 'true',\n };\n }\n return undefined;\n}\n\nexport async function createMicrosoftModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveMicrosoftCredentials(store);\n if (!credentials) return undefined;\n const client = new MicrosoftAdsClient(credentials, async (rotated) => {\n // Public-client refresh tokens rotate; persist the replacement immediately.\n const record = await store.get('microsoft');\n if (record) {\n await store.set({ ...record, data: { ...record.data, refresh_token: rotated } });\n }\n });\n const provider = new MicrosoftAdsProvider(client);\n return { provider, tools: microsoftTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAW5B,IAAM,YAAY;AACX,IAAM,cAAc;AAEpB,IAAM,0BAA0B;AAEvC,SAAS,MAAM,SAAkB;AAC/B,QAAM,QAAQ,UAAU,aAAa;AACrC,SAAO;AAAA,IACL,UAAU,uBAAuB,KAAK;AAAA,IACtC,UAAU,2BAA2B,KAAK;AAAA,IAC1C,WAAW,wBAAwB,KAAK;AAAA,IACxC,WAAW,wBAAwB,KAAK;AAAA,EAC1C;AACF;AAeO,IAAM,qBAAN,MAAyB;AAAA,EAK9B,YACmB,aACA,uBACA,YAA0B,OAC3C;AAHiB;AACA;AACA;AAEjB,SAAK,eAAe,YAAY;AAChC,SAAK,UAAU,YAAY,WAAW;AAAA,EACxC;AAAA,EANmB;AAAA,EACA;AAAA,EACA;AAAA,EAPX;AAAA,EACA;AAAA,EACC;AAAA,EAWT,MAAM,iBAAkC;AACtC,QAAI,KAAK,eAAe,KAAK,YAAY,YAAY,KAAK,IAAI,GAAG;AAC/D,aAAO,KAAK,YAAY;AAAA,IAC1B;AACA,UAAM,OAAO,IAAI,gBAAgB;AAAA,MAC/B,WAAW,KAAK,YAAY;AAAA,MAC5B,OAAO;AAAA,MACP,eAAe,KAAK;AAAA,MACpB,YAAY;AAAA,IACd,CAAC;AACD,QAAI,KAAK,YAAY,aAAc,MAAK,IAAI,iBAAiB,KAAK,YAAY,YAAY;AAC1F,UAAM,WAAW,MAAM,KAAK,UAAU,WAAW;AAAA,MAC/C,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,MAC/D;AAAA,IACF,CAAC;AACD,UAAM,MAAM,MAAM,SAAS,KAAK;AAChC,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,IAAI;AAAA,QACR;AAAA,QACA,mCAAmC,SAAS,MAAM;AAAA,QAClD,SAAS,GAAG;AAAA,MACd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;AACT;AAEA,eAAsB,sBAAsB,OAA6D;AACvG,QAAM,cAAc,MAAM,4BAA4B,KAAK;AAC3D,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,SAAS,IAAI,mBAAmB,aAAa,OAAO,YAAY;AAEpE,UAAMA,UAAS,MAAM,MAAM,IAAI,WAAW;AAC1C,QAAIA,SAAQ;AACV,YAAM,MAAM,IAAI,EAAE,GAAGA,SAAQ,MAAM,EAAE,GAAGA,QAAO,MAAM,eAAe,QAAQ,EAAE,CAAC;AAAA,IACjF;AAAA,EACF,CAAC;AACD,QAAM,WAAW,IAAI,qBAAqB,MAAM;AAChD,SAAO,EAAE,UAAU,OAAO,eAAe,QAAQ,EAAE;AACrD;","names":["url","status","AdportError","LocalMediaResolver","text","rows","AdportError","AdportError","id","headlines","descriptions","url","rows","parent","text","fields","keywords","keyword","AdportError","AdportError","url","input","AdportError","creativesOutput","defineTool","guardedWriteTool","z","AdportError","z","id","summary","z","image","creativesOutput","AdportError","text","selected","groups","input","value","change","current","key","defineTool","guardedWriteTool","AdportError","defineTool","guardedWriteTool","z","z","z","target","value","reference","parent","change","AdportError","z","input","value","current","reference","selected","id","name","defineTool","guardedWriteTool","AdportError","defineTool","guardedWriteTool","z","target","z","add","value","remove","groups","AdportError","id","selected","defineTool","guardedWriteTool","AdportError","defineTool","guardedWriteTool","z","z","update","AdportError","currency","value","target","view","current","fields","defineTool","guardedWriteTool","AdportError","defineTool","z","z","url","currency","AdportError","value","defineTool","createHash","AdportError","defineTool","guardedWriteTool","z","z","name","value","url","create","update","notes","fields","AdportError","createHash","goalId","status","expression","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","z","standardTypes","name","hash","value","create","reference","update","view","notes","canonical","matches","AdportError","createHash","rule","groups","prefix","input","fields","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","audienceType","target","z","hash","adjustment","add","reference","bid","canonical","value","digest","createHash","AdportError","groups","kind","input","current","fields","defineTool","guardedWriteTool","AdportError","defineTool","z","z","notes","AdportError","day","defineTool","createHash","AdportError","guardedWriteTool","z","z","hash","adjustment","canonical","digest","createHash","notes","count","rows","AdportError","identity","currency","notices","guardedWriteTool","createHash","z","AdportError","defineTool","guardedWriteTool","z","z","hash","target","canonical","digest","createHash","fields","entityId","target","text","minute","identity","notices","prefix","AdportError","groups","context","selected","parent","z","bid","change","id","name","day","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","hash","z","name","date","create","reference","update","additional","notes","contextSchema","viewSchema","canonical","value","digest","createHash","micros","AdportError","currency","context","kind","input","fields","status","defineTool","guardedWriteTool","LocalMediaResolver","AdportError","range","rows","day","status","url","selected","name","text","identity","key","id","fields","matches","value","amount","defineTool","guardedWriteTool","z","creativesOutput","defineTool","guardedWriteTool","z","id","urls","rows","name","description","kind","z","kind","defineTool","guardedWriteTool","record"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/csv.ts","../src/children.ts","../src/images.ts","../src/extensions.ts","../src/native.ts","../src/targeting.ts","../src/targeting-schemas.ts","../src/negative-keywords.ts","../src/budgets.ts","../src/planning.ts","../src/conversions.ts","../src/audiences.ts","../src/audience-targeting.ts","../src/offline-reports.ts","../src/offline-conversions.ts","../src/offline-conversion-schemas.ts","../src/general-targeting.ts","../src/general-targeting-schemas.ts","../src/experiments.ts","../src/tools.ts","../src/child-tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\n\nexport interface MicrosoftCredentials {\n developerToken: string;\n clientId: string;\n refreshToken: string;\n /** Only for confidential (web) apps; native/CLI public clients have no secret. */\n clientSecret?: string;\n sandbox?: boolean;\n}\n\nconst TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';\nexport const MSADS_SCOPE = 'https://ads.microsoft.com/msads.manage offline_access';\n/** Published universal sandbox developer token (anyone may use it in sandbox). */\nexport const SANDBOX_DEVELOPER_TOKEN = 'BBD37VB98';\n\nfunction hosts(sandbox: boolean) {\n const infix = sandbox ? '.sandbox' : '';\n return {\n campaign: `https://campaign.api${infix}.bingads.microsoft.com/CampaignManagement/v13`,\n customer: `https://clientcenter.api${infix}.bingads.microsoft.com/CustomerManagement/v13`,\n reporting: `https://reporting.api${infix}.bingads.microsoft.com/Reporting/v13`,\n adinsight: `https://adinsight.api${infix}.bingads.microsoft.com/AdInsight/v13`,\n };\n}\n\nexport type MicrosoftService = 'campaign' | 'customer' | 'reporting' | 'adinsight';\n\nexport interface RequestScope {\n /** Manager account (customer) id header. */\n customerId?: string;\n /** Ad account id header. */\n customerAccountId?: string;\n}\n\n/**\n * Microsoft Advertising REST v13 client. Public-client refresh tokens rotate —\n * onRefreshTokenRotated lets the credential store persist the replacement.\n */\nexport class MicrosoftAdsClient {\n private accessToken?: { token: string; expiresAt: number };\n private refreshToken: string;\n readonly sandbox: boolean;\n\n constructor(\n private readonly credentials: MicrosoftCredentials,\n private readonly onRefreshTokenRotated?: (token: string) => Promise<void>,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.refreshToken = credentials.refreshToken;\n this.sandbox = credentials.sandbox ?? false;\n }\n\n async getAccessToken(): Promise<string> {\n if (this.accessToken && this.accessToken.expiresAt > Date.now()) {\n return this.accessToken.token;\n }\n const body = new URLSearchParams({\n client_id: this.credentials.clientId,\n scope: 'https://ads.microsoft.com/msads.manage',\n refresh_token: this.refreshToken,\n grant_type: 'refresh_token',\n });\n if (this.credentials.clientSecret) body.set('client_secret', this.credentials.clientSecret);\n const response = await this.fetchImpl(TOKEN_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body,\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Microsoft OAuth refresh failed (${response.status}). Public-client refresh tokens expire after ~90 days — re-run \\`adport connect microsoft\\`.`,\n safeJson(raw),\n );\n }\n const data = JSON.parse(raw) as { access_token: string; expires_in: number; refresh_token?: string };\n this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1000 };\n if (data.refresh_token && data.refresh_token !== this.refreshToken) {\n this.refreshToken = data.refresh_token;\n await this.onRefreshTokenRotated?.(data.refresh_token);\n }\n return this.accessToken.token;\n }\n\n async request<T>(\n service: MicrosoftService,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body: unknown,\n scope: RequestScope = {},\n options: { privatePayload?: boolean } = {},\n ): Promise<T> {\n const token = await this.getAccessToken();\n const headers: Record<string, string> = {\n authorization: `Bearer ${token}`,\n DeveloperToken: this.sandbox ? SANDBOX_DEVELOPER_TOKEN : this.credentials.developerToken,\n 'content-type': 'application/json',\n };\n if (scope.customerId) headers.CustomerId = scope.customerId;\n if (scope.customerAccountId) headers.CustomerAccountId = scope.customerAccountId;\n const response = await this.fetchImpl(`${hosts(this.sandbox)[service]}/${path.replace(/^\\//, '')}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const raw = await response.text();\n if (!response.ok || options.privatePayload && response.status !== 200) {\n if (options.privatePayload) throw new AdportError('PROVIDER_ERROR', `microsoft: private request failed (HTTP ${response.status}); native response values omitted`);\n throw new AdportError('PROVIDER_ERROR', formatMicrosoftError(response.status, raw), safeJson(raw));\n }\n if (options.privatePayload) {\n try {\n if (!raw.trim()) throw new Error('Empty receipt');\n return JSON.parse(raw) as T;\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: private request returned an unrecognized JSON receipt; native values omitted'); }\n }\n return (raw ? JSON.parse(raw) : {}) as T;\n }\n\n /** Plain authorized download (report files); returns raw bytes. */\n async download(url: string): Promise<Uint8Array> {\n const response = await this.fetchImpl(url, {});\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', `Microsoft report download failed (HTTP ${response.status})`);\n }\n return new Uint8Array(await response.arrayBuffer());\n }\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\ninterface BatchErrorItem {\n Code?: number;\n ErrorCode?: string;\n Message?: string;\n FieldPath?: string;\n Index?: number;\n Details?: string;\n Detail?: string;\n}\n\n/**\n * REST errors are serialized fault objects: ApiFaultDetail\n * {OperationErrors, BatchErrors}, AdApiFaultDetail {Errors}, plus TrackingId.\n */\nexport function formatMicrosoftError(status: number, raw: string): string {\n const parsed = safeJson(raw) as {\n TrackingId?: string;\n Type?: string;\n OperationErrors?: BatchErrorItem[];\n BatchErrors?: BatchErrorItem[];\n Errors?: BatchErrorItem[];\n };\n if (!parsed || typeof parsed !== 'object' || (!parsed.OperationErrors && !parsed.Errors && !parsed.BatchErrors)) {\n return `Microsoft Advertising API error (HTTP ${status})`;\n }\n const items = [...(parsed.OperationErrors ?? []), ...(parsed.BatchErrors ?? []), ...(parsed.Errors ?? [])];\n const lines = items.map((e) => {\n const where = e.Index !== undefined ? ` [item ${e.Index}${e.FieldPath ? ` ${e.FieldPath}` : ''}]` : '';\n return `${e.Code ?? '?'} ${e.ErrorCode ?? ''}: ${e.Message ?? e.Details ?? e.Detail ?? ''}${where}`;\n });\n let message = `Microsoft Advertising API error (HTTP ${status}, ${parsed.Type ?? 'fault'}):\\n ${lines.join('\\n ')}`;\n if (items.some((e) => e.Code === 105)) {\n message += '\\n Code 105 InvalidCredentials: check the developer token matches the environment (sandbox vs production).';\n }\n if (items.some((e) => e.Code === 117)) {\n message += '\\n Code 117 CallRateExceeded: wait 60s before retrying.';\n }\n if (parsed.TrackingId) message += ` [TrackingId: ${parsed.TrackingId}]`;\n return message;\n}\n\nexport function formatPartialErrors(partialErrors: Array<BatchErrorItem | null> | undefined): string | undefined {\n const errors = partialErrors?.filter((error): error is BatchErrorItem => error !== null) ?? [];\n if (errors.length === 0) return undefined;\n return errors\n .map((e) => `item ${e.Index ?? '?'}: ${e.Code ?? ''} ${e.ErrorCode ?? ''} ${e.Message ?? ''}${e.FieldPath ? ` (${e.FieldPath})` : ''}`)\n .join('; ');\n}\n","import {\n AdportError,\n LocalMediaResolver,\n METRICS,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type MediaResolver,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { unzipSync } from 'fflate';\nimport { formatPartialErrors, MicrosoftAdsClient, type MicrosoftService } from './client.js';\nimport { parseCsv } from './csv.js';\nimport { MicrosoftChildService } from './children.js';\nimport { MicrosoftImageService, MICROSOFT_IMAGE_WRITES } from './images.js';\nimport { MicrosoftExtensionService, MICROSOFT_EXTENSION_WRITES } from './extensions.js';\nimport { MicrosoftTargetingService, MICROSOFT_TARGETING_WRITES } from './targeting.js';\nimport { MicrosoftNegativeKeywordService, MICROSOFT_NEGATIVE_KEYWORD_WRITES } from './negative-keywords.js';\nimport { MicrosoftBudgetService, MICROSOFT_BUDGET_WRITES } from './budgets.js';\nimport { MicrosoftPlanningService } from './planning.js';\nimport { MicrosoftConversionService, MICROSOFT_CONVERSION_WRITES } from './conversions.js';\nimport { MicrosoftAudienceService, MICROSOFT_AUDIENCE_WRITES } from './audiences.js';\nimport { MicrosoftAudienceTargetingService, MICROSOFT_AUDIENCE_TARGETING_WRITES } from './audience-targeting.js';\nimport { MicrosoftOfflineReportService } from './offline-reports.js';\nimport { MicrosoftOfflineConversionService, MICROSOFT_OFFLINE_CONVERSION_WRITES } from './offline-conversions.js';\nimport { MicrosoftGeneralTargetingService, MICROSOFT_GENERAL_TARGETING_WRITES } from './general-targeting.js';\nimport { MicrosoftExperimentService, MICROSOFT_EXPERIMENT_WRITES } from './experiments.js';\n\n/** DailyBudget is a double in whole account-currency units. */\nexport const UNITS_TO_MICROS = 1_000_000;\n// Omitting CampaignType silently returns Search only. REST flags are comma-separated.\nexport const MICROSOFT_CAMPAIGN_TYPES = 'App, Audience, DynamicSearchAds, Hotel, ObjectiveBased, PerformanceMax, Search, Shopping';\n\ninterface MicrosoftCampaign {\n Id: number | string;\n Name: string;\n Status: string;\n DailyBudget?: number;\n BudgetType?: string;\n BudgetId?: number | string | null;\n TimeZone?: string;\n CampaignType?: string;\n SubType?: string | null;\n ExperimentId?: number | string | null;\n}\n\ninterface WritePlan extends Omit<WritePreview, 'serverValidated'> {\n execute: () => Promise<string[]>;\n resultDetails?: () => unknown;\n resultWarnings?: () => string[];\n}\n\nexport class MicrosoftAdsProvider implements AdProvider {\n readonly id = 'microsoft';\n /** accountId → parent customer id, learned from SearchAccounts. */\n private customerIds = new Map<string, string>();\n private currencies = new Map<string, string>();\n readonly children: MicrosoftChildService;\n readonly images: MicrosoftImageService;\n readonly extensions: MicrosoftExtensionService;\n readonly targeting: MicrosoftTargetingService;\n readonly generalTargeting: MicrosoftGeneralTargetingService;\n readonly negativeKeywords: MicrosoftNegativeKeywordService;\n readonly budgets: MicrosoftBudgetService;\n readonly planning: MicrosoftPlanningService;\n readonly conversions: MicrosoftConversionService;\n readonly audiences: MicrosoftAudienceService;\n readonly audienceTargeting: MicrosoftAudienceTargetingService;\n readonly offlineReports: MicrosoftOfflineReportService;\n readonly offlineConversions: MicrosoftOfflineConversionService;\n readonly experiments: MicrosoftExperimentService;\n\n constructor(\n private readonly client: MicrosoftAdsClient,\n private readonly options: { pollIntervalMs?: number; pollMaxAttempts?: number } = {},\n media: MediaResolver = new LocalMediaResolver(),\n ) {\n this.children = new MicrosoftChildService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));\n this.images = new MicrosoftImageService(client, account => this.scopeFor(account), media);\n this.extensions = new MicrosoftExtensionService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), (account, ids) => this.images.lookupMany(account, ids));\n this.targeting = new MicrosoftTargetingService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));\n this.generalTargeting = new MicrosoftGeneralTargetingService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));\n this.negativeKeywords = new MicrosoftNegativeKeywordService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign));\n this.budgets = new MicrosoftBudgetService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), account => this.listCampaigns(account), async account => { await this.scopeFor(account); return this.currencies.get(account); });\n this.planning = new MicrosoftPlanningService(client, account => this.scopeFor(account), (account, campaign) => this.lookupCampaign(account, campaign), account => this.currencies.get(account));\n this.conversions = new MicrosoftConversionService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));\n this.audiences = new MicrosoftAudienceService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), account => this.listCampaigns(account));\n this.audienceTargeting = new MicrosoftAudienceTargetingService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), (account, audience, type) => this.audiences.get(account, audience, type));\n this.offlineReports = new MicrosoftOfflineReportService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign));\n this.offlineConversions = new MicrosoftOfflineConversionService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), this.conversions);\n this.experiments = new MicrosoftExperimentService(client, (account, refresh) => this.scopeFor(account, refresh), (account, campaign) => this.lookupCampaign(account, campaign), account => this.listCampaigns(account), async account => { await this.scopeFor(account); return this.currencies.get(account); });\n }\n\n capabilities(): ProviderCapabilities {\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'microsoft_set_campaign_status',\n input: { account_id: accountId, campaign_id: campaignId, status: 'Paused' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const user = await this.client.request<{ User?: { Id?: number | string } }>(\n 'customer',\n 'POST',\n 'User/Query',\n { UserId: null },\n );\n const userId = user.User?.Id;\n if (userId === undefined) {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: GetUser returned no user id');\n }\n const search = await this.client.request<{\n Accounts?: Array<{\n Id: number | string;\n Name?: string;\n Number?: string;\n CurrencyCode?: string;\n AccountLifeCycleStatus?: string;\n ParentCustomerId?: number | string;\n }>;\n }>('customer', 'POST', 'Accounts/Search', {\n Predicates: [{ Field: 'UserId', Operator: 'Equals', Value: String(userId) }],\n PageInfo: { Index: 0, Size: 100 },\n });\n const accounts = search.Accounts ?? [];\n for (const account of accounts) {\n if (account.CurrencyCode) this.currencies.set(String(account.Id), account.CurrencyCode);\n if (account.ParentCustomerId !== undefined) {\n this.customerIds.set(String(account.Id), String(account.ParentCustomerId));\n }\n }\n return accounts.map((a) => ({\n provider: this.id,\n id: String(a.Id),\n name: a.Name ?? a.Number ?? String(a.Id),\n currency: a.CurrencyCode,\n status: a.AccountLifeCycleStatus,\n }));\n }\n\n private async scopeFor(accountId: string, refresh = false) {\n if (refresh) { this.customerIds.delete(accountId); this.currencies.delete(accountId); }\n if (refresh || !this.customerIds.has(accountId)) await this.listAccounts();\n return { customerId: this.customerIds.get(accountId), customerAccountId: accountId };\n }\n\n async listCampaigns(accountId: string): Promise<MicrosoftCampaign[]> {\n const scope = await this.scopeFor(accountId);\n const data = await this.client.request<{ Campaigns?: MicrosoftCampaign[] | null }>(\n 'campaign',\n 'POST',\n 'Campaigns/QueryByAccountId',\n { AccountId: accountId, CampaignType: MICROSOFT_CAMPAIGN_TYPES, ReturnAdditionalFields: null },\n scope,\n );\n return data.Campaigns ?? [];\n }\n\n async apiRead(input: {\n account_id: string;\n service: MicrosoftService;\n path: string;\n body?: Record<string, unknown>;\n }): Promise<unknown> {\n const path = validateMicrosoftReadPath(input.path);\n validateMicrosoftAccountScope(input.body, input.account_id);\n const scope = await this.scopeFor(input.account_id);\n return this.client.request(input.service, 'POST', path, input.body ?? {}, scope);\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n const providerRows = await this.performanceReport(accountId, range.start, range.end, query.level === 'account' ? { ...query, level: 'campaign', metrics: [...METRICS] } : query);\n if (query.level === 'account') {\n if (providerRows.length > 0) {\n const aggregate = aggregateAccountRows(providerRows, this.id, accountId);\n aggregate.metrics = Object.fromEntries(query.metrics.filter(metric => aggregate.metrics[metric] !== undefined).map(metric => [metric, aggregate.metrics[metric]]));\n rows.push(aggregate);\n }\n } else {\n rows.push(...providerRows);\n }\n }\n const limit = query.limit ?? 1000;\n return { rows: rows.slice(0, limit), truncated: rows.length > limit };\n }\n\n private async performanceReport(accountId: string, start: string, end: string, query: NormalizedQuery): Promise<ReportRow[]> {\n const selection = query.level === 'ad_group'\n ? { type: 'AdGroupPerformanceReportRequest', columns: ['AdGroupId', 'AdGroupName', 'Status'] }\n : query.level === 'ad' ? { type: 'AdPerformanceReportRequest', columns: ['AdId', 'AdTitle', 'AdStatus'] }\n : { type: 'CampaignPerformanceReportRequest', columns: ['CampaignId', 'CampaignName', 'CampaignStatus'] };\n const bytes = await this.reportCsv(accountId, start, end, selection.type, [...selection.columns, 'Spend', 'Impressions', 'Clicks', 'Conversions', 'Revenue']);\n return bytes ? this.parseReport(bytes, accountId, query) : [];\n }\n\n async nativeReport(input: { account_id: string; kind: 'keyword' | 'search_term'; date_range: NormalizedQuery['dateRange']; limit: number }) {\n const range = resolveDateRange(input.date_range);\n const type = input.kind === 'keyword' ? 'KeywordPerformanceReportRequest' : 'SearchQueryPerformanceReportRequest';\n const columns = input.kind === 'keyword' ? ['CampaignId', 'AdGroupId', 'KeywordId', 'Keyword', 'BidMatchType'] : ['CampaignId', 'AdGroupId', 'AdId', 'KeywordId', 'Keyword', 'SearchQuery'];\n const bytes = await this.reportCsv(input.account_id, range.start, range.end, type, [...columns, 'Spend', 'Impressions', 'Clicks', 'Conversions', 'Revenue']);\n const records = bytes ? this.reportObjects(bytes) : [];\n return { rows: records.slice(0, input.limit), truncated: records.length > input.limit, report_type: type };\n }\n\n private async reportCsv(\n accountId: string,\n start: string,\n end: string,\n type: string,\n columns: string[],\n ): Promise<Uint8Array | undefined> {\n const scope = await this.scopeFor(accountId);\n const toDate = (iso: string) => {\n const [year, month, day] = iso.split('-').map(Number);\n return { Day: day, Month: month, Year: year };\n };\n // Async flow: Submit → Poll until Success → download zipped CSV.\n const submit = await this.client.request<{ ReportRequestId?: string }>(\n 'reporting',\n 'POST',\n 'GenerateReport/Submit',\n {\n ReportRequest: {\n Type: type,\n Format: 'Csv',\n FormatVersion: '2.0',\n ReportName: 'adport campaign report',\n ExcludeReportHeader: true,\n ExcludeReportFooter: true,\n ExcludeColumnHeaders: false,\n ReturnOnlyCompleteData: false,\n Aggregation: 'Summary',\n Columns: columns,\n Scope: { AccountIds: [accountId] },\n Time: { CustomDateRangeStart: toDate(start), CustomDateRangeEnd: toDate(end) },\n },\n },\n scope,\n );\n if (!submit.ReportRequestId) {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: SubmitGenerateReport returned no ReportRequestId');\n }\n\n const maxAttempts = this.options.pollMaxAttempts ?? 30;\n const interval = this.options.pollIntervalMs ?? 5_000;\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const poll = await this.client.request<{\n ReportRequestStatus?: { Status?: string; ReportDownloadUrl?: string | null };\n }>('reporting', 'POST', 'GenerateReport/Poll', { ReportRequestId: submit.ReportRequestId }, scope);\n const status = poll.ReportRequestStatus?.Status;\n if (status === 'Error') {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: report generation failed (Status: Error)');\n }\n if (status === 'Success') {\n const url = poll.ReportRequestStatus?.ReportDownloadUrl;\n if (!url) return undefined; // Success with null URL = no data for the range.\n return this.client.download(url);\n }\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n throw new AdportError('PROVIDER_ERROR', `microsoft: report not ready after ${maxAttempts} polls`);\n }\n\n private reportObjects(zipBytes: Uint8Array): Array<Record<string, string>> {\n const files = unzipSync(zipBytes);\n const selected = Object.entries(files).find(([name]) => name.toLowerCase().endsWith('.csv'))?.[1] ?? Object.values(files)[0];\n if (!selected) return [];\n const rows = parseCsv(new TextDecoder().decode(selected).replace(/^\\uFEFF/, ''));\n const header = rows[0];\n return header ? rows.slice(1).map(row => Object.fromEntries(header.map((key, index) => [key, row[index] ?? '']))) : [];\n }\n\n private parseReport(zipBytes: Uint8Array, accountId: string, query: NormalizedQuery): ReportRow[] {\n return this.reportObjects(zipBytes).map(row => {\n const numeric = (key: string) => {\n const text = row[key]?.trim();\n if (!text) return undefined;\n const number = Number(text);\n return Number.isFinite(number) ? number : undefined;\n };\n const metrics = performanceMetrics({ spend: numeric('Spend'), impressions: numeric('Impressions'), clicks: numeric('Clicks'), conversions: numeric('Conversions'), conversion_value: numeric('Revenue') });\n const identity = query.level === 'ad_group' ? ['AdGroupId', 'AdGroupName', 'Status'] : query.level === 'ad' ? ['AdId', 'AdTitle', 'AdStatus'] : ['CampaignId', 'CampaignName', 'CampaignStatus'];\n return { provider: this.id, accountId, entity: { level: query.level, id: row[identity[0]!] ?? '', name: row[identity[1]!] ?? '', status: row[identity[2]!] || undefined },\n metrics: Object.fromEntries(query.metrics.filter(metric => metrics[metric] !== undefined).map(metric => [metric, metrics[metric]])) };\n });\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n return {\n summary: plan.summary,\n changes: plan.changes,\n ...(plan.fieldChanges ? { fieldChanges: plan.fieldChanges } : {}),\n ...(plan.notes ? { notes: plan.notes } : {}),\n ...(plan.review ? { review: plan.review } : {}),\n coercions: plan.coercions,\n budgetDeltas: plan.budgetDeltas,\n serverValidated: false,\n };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const resourceIds = await plan.execute();\n return { applied: true, resourceIds, ...(plan.resultDetails ? { details: plan.resultDetails() } : {}), ...(plan.resultWarnings ? { warnings: plan.resultWarnings() } : {}) };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n if (MICROSOFT_IMAGE_WRITES.has(op.tool)) return this.images.plan(op);\n if (MICROSOFT_EXTENSION_WRITES.has(op.tool)) return this.extensions.plan(op, guard);\n if (MICROSOFT_TARGETING_WRITES.has(op.tool)) return this.targeting.plan(op, guard);\n if (MICROSOFT_GENERAL_TARGETING_WRITES.has(op.tool)) return this.generalTargeting.plan(op, guard);\n if (MICROSOFT_NEGATIVE_KEYWORD_WRITES.has(op.tool)) return this.negativeKeywords.plan(op);\n if (MICROSOFT_BUDGET_WRITES.has(op.tool)) return this.budgets.plan(op);\n if (MICROSOFT_CONVERSION_WRITES.has(op.tool)) return this.conversions.plan(op, guard);\n if (MICROSOFT_OFFLINE_CONVERSION_WRITES.has(op.tool)) return this.offlineConversions.plan(op);\n if (MICROSOFT_AUDIENCE_WRITES.has(op.tool)) return this.audiences.plan(op);\n if (MICROSOFT_AUDIENCE_TARGETING_WRITES.has(op.tool)) return this.audienceTargeting.plan(op, guard);\n if (MICROSOFT_EXPERIMENT_WRITES.has(op.tool)) return this.experiments.plan(op, guard);\n const payload = op.payload as never;\n switch (op.tool) {\n case 'microsoft_create_campaign':\n return this.planCreateCampaign(op.accountId, payload, guard);\n case 'microsoft_set_campaign_status':\n return this.planSetStatus(op.accountId, payload);\n case 'microsoft_set_budget':\n return this.planSetBudget(op.accountId, payload);\n case 'microsoft_api_create':\n return this.planApiCreate(op.accountId, payload, guard);\n case 'microsoft_api_update':\n return this.planApiUpdate(op.accountId, payload);\n case 'microsoft_api_delete':\n return this.planApiDelete(op.accountId, payload);\n default:\n return this.children.plan(op, guard);\n }\n }\n\n private async planApiCreate(\n accountId: string,\n payload: { resource: string; body: Record<string, unknown> },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const resource = validateMicrosoftResource(payload.resource);\n requireTypedMutationTool(resource, payload.body);\n const body = structuredClone(payload.body);\n validateMicrosoftAccountScope(body, accountId);\n const coercions: string[] = [];\n if (guard.forcePausedCreation) {\n const collection = resource.toLowerCase();\n if (['campaigns', 'adgroups', 'ads', 'keywords'].includes(collection)) {\n const keys = Object.keys(body).filter(key => key.toLowerCase() === collection);\n if (!keys.length || keys.some(key => !Array.isArray(body[key]))) throw new AdportError('INVALID_INPUT', `microsoft: ${resource} creation needs its native collection array so paused_creation can be enforced`);\n for (const key of keys) for (const [index, item] of (body[key] as unknown[]).entries()) {\n if (!isRecord(item)) throw new AdportError('INVALID_INPUT', `microsoft: ${resource} creation needs resource objects`);\n const statuses = Object.keys(item).filter(key => key.toLowerCase() === 'status');\n if (statuses.length === 1 && statuses[0] === 'Status' && item.Status === 'Paused') continue;\n for (const status of statuses) delete item[status];\n item.Status = 'Paused';\n coercions.push(`body.${key}[${index}].Status coerced to Paused by policy (paused_creation)`);\n }\n }\n coerceMicrosoftCreatedStatuses(body, coercions);\n }\n return {\n summary: `Create Microsoft Advertising ${resource} resource(s)`,\n changes: [`+ POST /${resource} ${JSON.stringify(body)}`],\n coercions,\n budgetDeltas: collectMicrosoftBudgets(body),\n execute: async () => this.executeMicrosoftMutation(accountId, 'POST', resource, body),\n };\n }\n\n private async planApiUpdate(\n accountId: string,\n payload: { resource: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const resource = validateMicrosoftResource(payload.resource);\n requireTypedMutationTool(resource, payload.body);\n validateMicrosoftAccountScope(payload.body, accountId);\n if (containsMicrosoftBudget(payload.body)) {\n throw new AdportError('INVALID_INPUT', 'microsoft: budget updates require microsoft_set_budget for policy checks');\n }\n return {\n summary: `Update Microsoft Advertising ${resource} resource(s)`,\n changes: [`~ PUT /${resource} ${JSON.stringify(payload.body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => this.executeMicrosoftMutation(accountId, 'PUT', resource, payload.body),\n };\n }\n\n private async planApiDelete(\n accountId: string,\n payload: { resource: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const resource = validateMicrosoftResource(payload.resource);\n requireTypedMutationTool(resource, payload.body);\n validateMicrosoftAccountScope(payload.body, accountId);\n return {\n summary: `Permanently delete Microsoft Advertising ${resource} resource(s)`,\n changes: [`- DELETE /${resource} ${JSON.stringify(payload.body)}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => this.executeMicrosoftMutation(accountId, 'DELETE', resource, payload.body),\n };\n }\n\n private async executeMicrosoftMutation(\n accountId: string,\n method: 'POST' | 'PUT' | 'DELETE',\n resource: string,\n body: Record<string, unknown>,\n ): Promise<string[]> {\n const scope = await this.scopeFor(accountId);\n const result = await this.client.request<Record<string, unknown>>('campaign', method, resource, body, scope);\n const partial = formatPartialErrors(result.PartialErrors as Parameters<typeof formatPartialErrors>[0]);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: ${resource} partial errors — ${partial}`);\n return extractMicrosoftIds(result);\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: { name: string; daily_budget: number; time_zone?: string; status?: string },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n // The API's own default status on Add is Paused; we only coerce an explicit Active.\n let status = payload.status ?? 'Paused';\n if (guard.forcePausedCreation && status === 'Active') {\n status = 'Paused';\n coercions.push('status coerced to Paused by policy (paused_creation)');\n }\n const campaign = {\n Name: payload.name,\n CampaignType: 'Search',\n DailyBudget: payload.daily_budget,\n BudgetType: 'DailyBudgetStandard',\n TimeZone: payload.time_zone ?? 'PacificTimeUSCanadaTijuana',\n Status: status,\n };\n return {\n summary: `Create Microsoft Advertising campaign \"${payload.name}\" (${status}), daily budget ${payload.daily_budget}`,\n changes: [`+ campaign \"${payload.name}\" type=Search daily_budget=${payload.daily_budget} status=${status}`],\n coercions,\n budgetDeltas: [\n { target: `new campaign \"${payload.name}\" daily budget`, toMicros: payload.daily_budget * UNITS_TO_MICROS },\n ],\n execute: async () => {\n const scope = await this.scopeFor(accountId);\n const result = await this.client.request<{\n CampaignIds?: Array<number | string | null>;\n PartialErrors?: Array<{ Index?: number; Code?: number; ErrorCode?: string; Message?: string; FieldPath?: string }>;\n }>('campaign', 'POST', 'Campaigns', { AccountId: accountId, Campaigns: [campaign] }, scope);\n const partial = formatPartialErrors(result.PartialErrors);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: AddCampaigns partial errors — ${partial}`);\n return (result.CampaignIds ?? []).filter((id): id is number | string => id !== null).map(String);\n },\n };\n }\n\n private async lookupCampaign(accountId: string, campaignId: string): Promise<MicrosoftCampaign> {\n const campaigns = await this.listCampaigns(accountId);\n const campaign = campaigns.find((c) => String(c.Id) === campaignId);\n if (!campaign) {\n throw new AdportError('PROVIDER_ERROR', `microsoft: campaign ${campaignId} not found in account ${accountId}`);\n }\n return campaign;\n }\n\n private async updateCampaign(\n accountId: string,\n fields: Record<string, unknown> & { Id: number | string },\n ): Promise<void> {\n const scope = await this.scopeFor(accountId);\n // UpdateCampaigns is PUT; omitted fields stay unchanged.\n const result = await this.client.request<{\n PartialErrors?: Array<{ Index?: number; Code?: number; ErrorCode?: string; Message?: string }>;\n }>('campaign', 'PUT', 'Campaigns', { AccountId: accountId, Campaigns: [fields] }, scope);\n const partial = formatPartialErrors(result.PartialErrors);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: UpdateCampaigns partial errors — ${partial}`);\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_id: string; status: 'Active' | 'Paused' },\n ): Promise<WritePlan> {\n const current = await this.lookupCampaign(accountId, payload.campaign_id);\n if (current.ExperimentId && String(current.ExperimentId) !== '0') throw new AdportError('INVALID_INPUT', 'microsoft: experiment campaign status is inherited; change the base campaign status instead');\n return {\n summary: `Set Microsoft campaign \"${current.Name}\" status ${current.Status} → ${payload.status}`,\n changes: [`~ campaign ${payload.campaign_id} Status ${current.Status} → ${payload.status}`],\n notes: ['Related active or scheduled campaign-copy experiments follow the base serving status. Completed experiments cannot be restarted by unpausing the base.'],\n coercions: [],\n budgetDeltas: [],\n execute: async () => {\n await this.updateCampaign(accountId, { Id: current.Id, Status: payload.status });\n return [payload.campaign_id];\n },\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; daily_budget: number },\n ): Promise<WritePlan> {\n const current = await this.lookupCampaign(accountId, payload.campaign_id);\n if (current.ExperimentId && String(current.ExperimentId) !== '0') throw new AdportError('INVALID_INPUT', 'microsoft: experiment campaign budget is inherited; change the base campaign budget instead');\n if (current.BudgetId && Number(current.BudgetId) > 0) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `microsoft: campaign \"${current.Name}\" uses a SHARED budget (BudgetId ${current.BudgetId}) — ` +\n 'its DailyBudget cannot be changed per-campaign (CampaignServiceCannotUpdateSharedBudget).',\n );\n }\n return {\n summary: `Change Microsoft campaign \"${current.Name}\" daily budget ${current.DailyBudget ?? '(unset)'} → ${payload.daily_budget}`,\n changes: [`~ campaign ${payload.campaign_id} DailyBudget ${current.DailyBudget ?? '(unset)'} → ${payload.daily_budget}`],\n notes: ['For related campaign-copy experiments, this changes the base total daily allocation before its traffic/budget split. The experiment campaign inherits that budget rather than receiving an additional independent pool.'],\n coercions: [],\n budgetDeltas: [\n {\n target: `campaign \"${current.Name}\" daily budget`,\n ...(current.DailyBudget !== undefined ? { fromMicros: current.DailyBudget * UNITS_TO_MICROS } : {}),\n toMicros: payload.daily_budget * UNITS_TO_MICROS,\n },\n ],\n execute: async () => {\n await this.updateCampaign(accountId, { Id: current.Id, DailyBudget: payload.daily_budget });\n return [payload.campaign_id];\n },\n };\n }\n}\n\nfunction performanceMetrics(base: Partial<Record<MetricName, number>>): Partial<Record<MetricName, number>> {\n const ratio = (numerator: number | undefined, denominator: number | undefined, scale = 1) => numerator === undefined || denominator === undefined ? undefined : denominator > 0 ? round2(numerator / denominator * scale) : 0;\n return Object.fromEntries(Object.entries({ ...base,\n ctr: ratio(base.clicks, base.impressions, 100), cpc: ratio(base.spend, base.clicks), cpm: ratio(base.spend, base.impressions, 1000),\n cpa: ratio(base.spend, base.conversions), roas: ratio(base.conversion_value, base.spend),\n }).filter(([, value]) => value !== undefined).map(([key, value]) => [key, round2(value!)]));\n}\n\nfunction aggregateAccountRows(rows: ReportRow[], provider: string, accountId: string): ReportRow {\n const totals: Partial<Record<MetricName, number>> = {};\n for (const metric of ['spend', 'impressions', 'clicks', 'conversions', 'conversion_value'] as const) {\n if (rows.every(row => row.metrics[metric] !== undefined)) totals[metric] = rows.reduce((sum, row) => sum + row.metrics[metric]!, 0);\n }\n return { provider, accountId, entity: { level: 'account', id: accountId, name: accountId }, metrics: performanceMetrics(totals) };\n}\n\nfunction validateMicrosoftReadPath(path: string): string {\n const normalized = path.replace(/^\\/+|\\/+$/g, '').trim();\n const action = normalized.split('/').at(-1) ?? '';\n if (\n !/^[A-Za-z][A-Za-z0-9]*(?:\\/[A-Za-z][A-Za-z0-9]*){1,2}$/.test(normalized) ||\n !/^(?:Query|Search|Get|Submit|Poll)/.test(action)\n ) {\n throw new AdportError('INVALID_INPUT', `microsoft: unsupported read operation path \"${path}\"`);\n }\n return normalized;\n}\n\nfunction validateMicrosoftResource(resource: string): string {\n const normalized = resource.trim();\n if (!/^[A-Z][A-Za-z0-9]{1,80}$/.test(normalized)) {\n throw new AdportError('INVALID_INPUT', `microsoft: invalid Campaign Management resource \"${resource}\"`);\n }\n return normalized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction requireTypedMutationTool(resource: string, body: unknown): void {\n const collection = resource.toLowerCase();\n const hasFieldValue = (value: unknown, key: string, matches: (value: string) => boolean): boolean => Array.isArray(value) ? value.some(child => hasFieldValue(child, key, matches)) : isRecord(value) && Object.entries(value).some(([field, child]) => field.toLowerCase() === key && typeof child === 'string' && matches(child.trim().toLowerCase()) || hasFieldValue(child, key, matches));\n const audienceSelectors = new Set(['audience', 'audiencecriterion', 'custom', 'customaudience', 'inmarket', 'inmarketaudience', 'product', 'productaudience', 'remarketinglist', 'similarremarketinglist', 'combinedlist', 'customerlist', 'impressionbasedremarketinglist', 'customsegment', 'aiprompt']);\n if (['campaigncriterions', 'adgroupcriterions'].includes(collection) && (hasFieldValue(body, 'criteriontype', value => value.split(/[,\\s]+/).some(value => audienceSelectors.has(value))) || hasFieldValue(body, 'type', value => ['audience', 'audiencecriterion'].includes(value)))) throw new AdportError('INVALID_INPUT', 'microsoft: audience criteria require typed audience-targeting tools for hierarchy, target-mode and opposite-level checks');\n const generalSelectors = new Set(['targets', 'age', 'agecriterion', 'gender', 'gendercriterion', 'device', 'devicecriterion', 'daytime', 'daytimecriterion', 'location', 'locationcriterion', 'locationintent', 'locationintentcriterion', 'radius', 'radiuscriterion']);\n if (['campaigncriterions', 'adgroupcriterions'].includes(collection) && (hasFieldValue(body, 'criteriontype', value => value.split(/[,\\s]+/).some(value => generalSelectors.has(value))) || hasFieldValue(body, 'type', value => generalSelectors.has(value)))) throw new AdportError('INVALID_INPUT', 'microsoft: general targets require microsoft_update_targeting for scope, inheritance, schedule-clock and preservation checks');\n const hasKey = (value: unknown, name: string): boolean => Array.isArray(value) ? value.some(child => hasKey(child, name)) : isRecord(value) && Object.entries(value).some(([key, child]) => key.toLowerCase() === name || hasKey(child, name));\n if (['campaigns', 'adgroups'].includes(collection) && hasKey(body, 'adscheduleusesearchertimezone')) throw new AdportError('INVALID_INPUT', 'microsoft: schedule clocks require microsoft_update_targeting with native account time-zone and inheritance context');\n if (['campaigns', 'adgroups'].includes(collection) && hasFieldValue(body, 'type', value => ['target', 'targetsetting'].includes(value))) throw new AdportError('INVALID_INPUT', 'microsoft: target-setting changes require microsoft_set_audience_target_mode to preserve other targeting details');\n if (collection === 'audiences') throw new AdportError('INVALID_INPUT', 'microsoft: audience mutations require typed audience tools for Account ownership, replacement-rule semantics and deletion reference checks');\n if (collection === 'experiments') throw new AdportError('INVALID_INPUT', 'microsoft: experiments require typed tools for inherited pause/budget policy, ownership, snapshots and coupled campaign effects; promotion and graduation need separate reviewed workflows');\n if (collection === 'uettags') throw new AdportError('INVALID_INPUT', 'microsoft: use microsoft_create_uet_tag for new uninstalled tags; customer-wide tag edits, deletion and sharing are not exposed through single-account generic tools');\n if (collection === 'conversiongoals') throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal mutations require typed conversion tools for account scope, native auto-tagging side effects and event-criteria preservation');\n if (['offlineconversions', 'offlineconversionadjustments'].includes(collection)) throw new AdportError('INVALID_INPUT', 'microsoft: offline events require typed upload tools for private previews, goal binding and indexed receipt handling');\n const referencesSharedBudget = (value: unknown): boolean => Array.isArray(value) ? value.some(referencesSharedBudget) : isRecord(value) && Object.entries(value).some(([key, child]) => key.toLowerCase() === 'budgetid' && child !== null && child !== undefined && String(child) !== '0' || referencesSharedBudget(child));\n if (collection === 'budgets' || referencesSharedBudget(body)) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget changes require the typed microsoft shared-budget tools for membership, snapshot and monetary policy checks');\n}\n\nfunction validateMicrosoftAccountScope(value: unknown, accountId: string): void {\n if (Array.isArray(value)) return value.forEach((item) => validateMicrosoftAccountScope(item, accountId));\n if (!isRecord(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (key.toLowerCase() === 'accountid' && String(child) !== accountId) {\n throw new AdportError('INVALID_INPUT', `microsoft: body AccountId ${String(child)} does not match selected account ${accountId}`);\n }\n if (key.toLowerCase() === 'accountids' && (!Array.isArray(child) || child.some((id) => String(id) !== accountId))) {\n throw new AdportError('INVALID_INPUT', `microsoft: body AccountIds must contain only selected account ${accountId}`);\n }\n validateMicrosoftAccountScope(child, accountId);\n }\n}\n\nfunction coerceMicrosoftCreatedStatuses(value: unknown, coercions: string[], path = 'body'): void {\n if (Array.isArray(value)) return value.forEach((item, index) => coerceMicrosoftCreatedStatuses(item, coercions, `${path}[${index}]`));\n if (!isRecord(value)) return;\n for (const [key, child] of Object.entries(value)) {\n if (key.toLowerCase() === 'status' && typeof child === 'string' && ['active', 'paused'].includes(child.toLowerCase()) && (key !== 'Status' || child !== 'Paused')) {\n delete value[key];\n value.Status = 'Paused';\n coercions.push(`${path}.${key} coerced to Paused by policy (paused_creation)`);\n } else coerceMicrosoftCreatedStatuses(child, coercions, `${path}.${key}`);\n }\n}\n\nfunction containsMicrosoftBudget(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsMicrosoftBudget);\n if (!isRecord(value)) return false;\n return Object.entries(value).some(([key, child]) => /budget/i.test(key) || containsMicrosoftBudget(child));\n}\n\nfunction collectMicrosoftBudgets(value: unknown, path = 'body'): WritePreview['budgetDeltas'] {\n const deltas: WritePreview['budgetDeltas'] = [];\n if (Array.isArray(value)) {\n value.forEach((item, index) => deltas.push(...collectMicrosoftBudgets(item, `${path}[${index}]`)));\n return deltas;\n }\n if (!isRecord(value)) return deltas;\n for (const [key, child] of Object.entries(value)) {\n const childPath = `${path}.${key}`;\n if (/budget/i.test(key) && !/type|id/i.test(key)) {\n const amount = Number(child);\n if (Number.isFinite(amount) && amount > 0) {\n deltas.push({ target: childPath, toMicros: Math.round(amount * UNITS_TO_MICROS) });\n }\n }\n deltas.push(...collectMicrosoftBudgets(child, childPath));\n }\n return deltas;\n}\n\nfunction extractMicrosoftIds(value: unknown): string[] {\n const ids: string[] = [];\n const visit = (item: unknown): void => {\n if (Array.isArray(item)) return item.forEach(visit);\n if (!isRecord(item)) return;\n for (const [key, child] of Object.entries(item)) {\n if (/Ids?$/.test(key)) {\n if (Array.isArray(child)) child.forEach((id) => { if (id !== null) ids.push(String(id)); });\n else if (typeof child === 'string' || typeof child === 'number') ids.push(String(child));\n } else visit(child);\n }\n };\n visit(value);\n return [...new Set(ids)];\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100;\n}\n","/** Minimal RFC-4180-ish CSV parser (quotes, escaped quotes, CRLF). */\nexport function parseCsv(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = '';\n let inQuotes = false;\n for (let i = 0; i < text.length; i++) {\n const char = text[i]!;\n if (inQuotes) {\n if (char === '\"') {\n if (text[i + 1] === '\"') {\n field += '\"';\n i++;\n } else {\n inQuotes = false;\n }\n } else {\n field += char;\n }\n continue;\n }\n if (char === '\"') {\n inQuotes = true;\n } else if (char === ',') {\n row.push(field);\n field = '';\n } else if (char === '\\n' || char === '\\r') {\n if (char === '\\r' && text[i + 1] === '\\n') i++;\n row.push(field);\n field = '';\n if (row.length > 1 || row[0] !== '') rows.push(row);\n row = [];\n } else {\n field += char;\n }\n }\n if (field !== '' || row.length > 0) {\n row.push(field);\n if (row.length > 1 || row[0] !== '') rows.push(row);\n }\n return rows;\n}\n","import { AdportError, creativeStatusAction, type Creative, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { formatPartialErrors, MicrosoftAdsClient, type RequestScope } from './client.js';\n\ntype Row = Record<string, unknown>;\ninterface Plan { summary: string; changes: string[]; coercions: string[]; budgetDeltas: WritePreview['budgetDeltas']; execute: () => Promise<string[]> }\ntype Parent = { account_id: string; campaign_id: string; ad_group_id: string };\nconst object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nconst objects = (value: unknown): Row[] => Array.isArray(value) ? value.filter(row => row && typeof row === 'object') as Row[] : [];\nconst texts = (value: unknown): string[] => objects(value).flatMap(link => typeof object(link.Asset).Text === 'string' ? [String(object(link.Asset).Text)] : []);\n\n/** REST wire shapes pinned in MicrosoftDocs/Advertising (2026-11-02). */\nexport class MicrosoftChildService {\n constructor(private readonly client: MicrosoftAdsClient, private readonly scope: (accountId: string) => Promise<RequestScope>,\n private readonly campaign: (accountId: string, campaignId: string) => Promise<unknown>) {}\n\n private async request(account: string, path: string, body: Row, method: 'POST' | 'PUT' | 'DELETE' = 'POST'): Promise<Row> {\n const result = await this.client.request<Row>('campaign', method, path, body, await this.scope(account));\n const partial = formatPartialErrors(result.PartialErrors as Parameters<typeof formatPartialErrors>[0]);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: ${path} partial errors — ${partial}. Check successful resource IDs before retrying.`, {\n resourceIds: Object.entries(result).filter(([key]) => /Ids$/.test(key)).flatMap(([, value]) => Array.isArray(value) ? value.filter(id => id !== null).map(String) : []), partialErrors: result.PartialErrors,\n });\n return result;\n }\n\n async listGroups(input: { account_id: string; campaign_id: string }) {\n await this.campaign(input.account_id, input.campaign_id);\n const result = await this.request(input.account_id, 'AdGroups/QueryByCampaignId', { CampaignId: input.campaign_id, ReturnAdditionalFields: 'AdGroupType' });\n return { rows: objects(result.AdGroups), truncated: false };\n }\n\n private async group(input: Parent): Promise<Row> {\n await this.campaign(input.account_id, input.campaign_id);\n const result = await this.request(input.account_id, 'AdGroups/QueryByIds', { CampaignId: input.campaign_id, AdGroupIds: [input.ad_group_id], ReturnAdditionalFields: 'AdGroupType' });\n const group = objects(result.AdGroups).find(row => String(row.Id) === input.ad_group_id);\n if (!group) throw new AdportError('INVALID_INPUT', 'Microsoft ad group was not found in the selected campaign/account.');\n return group;\n }\n\n async listKeywords(input: Parent) {\n await this.group(input);\n const result = await this.request(input.account_id, 'Keywords/QueryByAdGroupId', { AdGroupId: input.ad_group_id, ReturnAdditionalFields: null });\n return { rows: objects(result.Keywords), truncated: false };\n }\n\n async listAds(input: Parent & { ad_types: string[]; limit: number }) {\n await this.group(input);\n const result = await this.request(input.account_id, 'Ads/QueryByAdGroupId', { AdGroupId: input.ad_group_id, AdTypes: input.ad_types, ReturnAdditionalFields: null });\n const ads = objects(result.Ads);\n return { ads: ads.slice(0, input.limit), truncated: ads.length > input.limit, creatives: ads.slice(0, input.limit).map(ad => this.card(input, ad)) };\n }\n\n private card(input: Parent, ad: Row): Creative {\n const adId = String(ad.Id), headlines = texts(ad.Headlines), descriptions = texts(ad.Descriptions), args = { account_id: input.account_id, campaign_id: input.campaign_id, ad_group_id: input.ad_group_id, ad_id: adId };\n if (!/^\\d+$/.test(adId)) throw new AdportError('PROVIDER_ERROR', 'Microsoft returned an ad without a valid ID.');\n const actions: Creative['actions'] = ['Active', 'Paused'].includes(String(ad.Status)) ? [creativeStatusAction('microsoft_set_ad_status', { ...args, ad_type: ad.Type }, String(ad.Status), ['Active', 'Paused'])] : [];\n if (ad.Type === 'ResponsiveSearch') actions.push({ label: 'Edit ad copy', tool: 'microsoft_update_responsive_search_ad', arguments: args,\n fields: [\n { key: 'headlines', label: 'Headlines (one per line)', type: 'text_list', value: headlines },\n { key: 'descriptions', label: 'Descriptions (one per line)', type: 'text_list', value: descriptions },\n { key: 'final_urls', label: 'Landing pages (one per line)', type: 'url_list', value: Array.isArray(ad.FinalUrls) ? ad.FinalUrls.map(String) : [] },\n ] });\n const destinations = Array.isArray(ad.FinalUrls) ? ad.FinalUrls.map(String).filter(value => { try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; } catch { return false; } }) : [];\n return { id: adId, provider: 'microsoft', account_id: input.account_id, campaign_id: input.campaign_id, ad_group_id: input.ad_group_id,\n name: headlines[0] || String(ad.Title ?? ad.TitlePart1 ?? `Ad ${adId}`), type: String(ad.Type), status: String(ad.Status),\n headlines, descriptions, landing_urls: destinations, media: [], actions };\n }\n\n private async ad(input: Parent, id: string, type: string): Promise<Row> {\n await this.group(input);\n const result = await this.request(input.account_id, 'Ads/QueryByIds', { AdGroupId: input.ad_group_id, AdIds: [id], AdTypes: [type], ReturnAdditionalFields: null });\n const ad = objects(result.Ads).find(row => String(row.Id) === id && row.Type === type);\n if (!ad) throw new AdportError('INVALID_INPUT', 'Microsoft ad was not found with this type in the selected ad group/account.');\n return ad;\n }\n\n private async keywords(input: Parent, ids: string[]): Promise<Row[]> {\n await this.group(input);\n const result = await this.request(input.account_id, 'Keywords/QueryByIds', { AdGroupId: input.ad_group_id, KeywordIds: ids, ReturnAdditionalFields: null });\n const rows = objects(result.Keywords);\n if (ids.some(id => !rows.some(row => String(row.Id) === id))) throw new AdportError('INVALID_INPUT', 'A keyword was not found in the selected ad group/account.');\n return rows;\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const p = op.payload as Row, parent: Parent = { account_id: op.accountId, campaign_id: String(p.campaign_id), ad_group_id: String(p.ad_group_id) };\n const mutate = (collection: string, body: Row, changes: string[], ids: string[] = [], coercions: string[] = []): Plan => ({\n summary: changes[0]!, changes, coercions, budgetDeltas: [], execute: async () => {\n const method = op.kind === 'create' ? 'POST' : op.kind === 'remove' ? 'DELETE' : 'PUT';\n const result = await this.request(op.accountId, collection, body, method);\n if (op.kind !== 'create') return ids;\n const values = result[`${collection === 'AdGroups' ? 'AdGroup' : collection === 'Keywords' ? 'Keyword' : 'Ad'}Ids`];\n const created = Array.isArray(values) ? values.filter(id => id !== null).map(String) : [];\n if (created.length !== objects(body[collection]).length) throw new AdportError('PROVIDER_ERROR', 'Microsoft did not return an ID for every requested resource. Check creation status before retrying.', { resourceIds: created });\n return created;\n },\n });\n const creationStatus = (requested: unknown) => guard.forcePausedCreation ? 'Paused' : requested ?? 'Paused';\n const creationCoercion = (requested: unknown) => guard.forcePausedCreation && requested === 'Active' ? ['status coerced to Paused by policy (paused_creation)'] : [];\n const assetLinks = (value: unknown, current: unknown = []): Row[] => (value as string[]).map((text, index) => {\n const previous = objects(current)[index];\n // Text asset IDs are read-only; Microsoft deduplicates assets by text.\n return { Asset: { Type: 'TextAsset', Text: text }, ...(previous?.PinnedField ? { PinnedField: previous.PinnedField } : {}) };\n });\n switch (op.tool) {\n case 'microsoft_create_ad_group':\n await this.campaign(op.accountId, String(p.campaign_id));\n return mutate('AdGroups', { CampaignId: p.campaign_id, AdGroups: [{ Name: p.name, AdGroupType: 'SearchStandard', Language: p.language, Status: creationStatus(p.status), ...(p.cpc_bid !== undefined ? { CpcBid: { Amount: p.cpc_bid } } : {}) }] },\n [`+ SearchStandard ad group \"${p.name}\" (${creationStatus(p.status)}), language=${p.language}`, ...(p.cpc_bid !== undefined ? [`CPC bid ${p.cpc_bid} whole currency units`] : [])], [], creationCoercion(p.status));\n case 'microsoft_set_ad_group_status':\n case 'microsoft_update_ad_group': {\n const current = await this.group(parent), fields = op.tool === 'microsoft_set_ad_group_status' ? { Status: p.status } : { ...(p.name !== undefined ? { Name: p.name } : {}), ...(p.cpc_bid !== undefined ? { CpcBid: { Amount: p.cpc_bid } } : {}) };\n return mutate('AdGroups', { CampaignId: p.campaign_id, AdGroups: [{ Id: p.ad_group_id, ...fields }] }, [`~ ad group ${p.ad_group_id}: ${JSON.stringify({ Name: current.Name, Status: current.Status, CpcBid: current.CpcBid })} → ${JSON.stringify(fields)}`], [String(p.ad_group_id)]);\n }\n case 'microsoft_create_responsive_search_ad': {\n const group = await this.group(parent);\n if (group.AdGroupType !== 'SearchStandard') throw new AdportError('INVALID_INPUT', 'Responsive search ads require a SearchStandard ad group.');\n const fields = { Type: 'ResponsiveSearch', Status: creationStatus(p.status), Headlines: assetLinks(p.headlines), Descriptions: assetLinks(p.descriptions), FinalUrls: p.final_urls,\n ...(p.path1 !== undefined ? { Path1: p.path1 } : {}), ...(p.path2 !== undefined ? { Path2: p.path2 } : {}) };\n return mutate('Ads', { AdGroupId: p.ad_group_id, Ads: [fields] }, [`+ responsive search ad ${JSON.stringify(fields)}`], [], creationCoercion(p.status));\n }\n case 'microsoft_update_responsive_search_ad':\n case 'microsoft_set_ad_status': {\n const type = op.tool === 'microsoft_set_ad_status' ? String(p.ad_type) : 'ResponsiveSearch';\n const current = await this.ad(parent, String(p.ad_id), type);\n const fields: Row = { Id: p.ad_id, Type: type };\n if (op.tool === 'microsoft_set_ad_status') fields.Status = p.status;\n else {\n if (p.headlines !== undefined) fields.Headlines = assetLinks(p.headlines, current.Headlines);\n if (p.descriptions !== undefined) fields.Descriptions = assetLinks(p.descriptions, current.Descriptions);\n if (p.final_urls !== undefined) fields.FinalUrls = p.final_urls;\n if (p.path1 !== undefined) fields.Path1 = p.path1;\n if (p.path2 !== undefined) fields.Path2 = p.path2;\n }\n return mutate('Ads', { AdGroupId: p.ad_group_id, Ads: [fields] }, [`~ ad ${p.ad_id}: ${JSON.stringify(current)} → ${JSON.stringify(fields)}`,\n ...(op.tool === 'microsoft_update_responsive_search_ad' ? [`Serving status remains ${current.Status}. Omitted content fields remain unchanged.`] : [])], [String(p.ad_id)]);\n }\n case 'microsoft_add_keywords': {\n await this.group(parent);\n const keywords = (p.keywords as Array<{ text: string; match_type: string; bid?: number; status: string }>).map(keyword => ({ Text: keyword.text, MatchType: keyword.match_type, Status: creationStatus(keyword.status), ...(keyword.bid !== undefined ? { Bid: { Amount: keyword.bid } } : {}) }));\n return mutate('Keywords', { AdGroupId: p.ad_group_id, Keywords: keywords }, [`+ keywords ${JSON.stringify(keywords)}`], [], guard.forcePausedCreation && (p.keywords as Array<{ status: string }>).some(keyword => keyword.status === 'Active') ? ['keyword statuses coerced to Paused by policy (paused_creation)'] : []);\n }\n case 'microsoft_set_keyword_status':\n case 'microsoft_set_keyword_bid': {\n const [current] = await this.keywords(parent, [String(p.keyword_id)]);\n const fields = op.tool === 'microsoft_set_keyword_status' ? { Status: p.status } : { Bid: { Amount: p.bid } };\n return mutate('Keywords', { AdGroupId: p.ad_group_id, Keywords: [{ Id: p.keyword_id, ...fields }] }, [`~ keyword ${p.keyword_id}: ${JSON.stringify(current)} → ${JSON.stringify(fields)}`], [String(p.keyword_id)]);\n }\n case 'microsoft_remove_keywords':\n await this.keywords(parent, p.keyword_ids as string[]);\n return mutate('Keywords', { AdGroupId: p.ad_group_id, KeywordIds: p.keyword_ids }, [`- keywords ${(p.keyword_ids as string[]).join(', ')}; cannot be undone`], p.keyword_ids as string[]);\n default: throw new AdportError('PROVIDER_ERROR', `microsoft: unsupported write tool ${op.tool}`);\n }\n }\n}\n","import { AdportError, LocalMediaResolver, creativesOutput, defineTool, guardedWriteTool, mediaSourceFields, type AnyToolDefinition, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, formatPartialErrors, type RequestScope } from './client.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\ntype Row = Record<string, unknown>;\ntype ImagePlan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\nconst id = z.string().regex(/^[1-9]\\d*$/);\nconst imageType = z.enum(['GenericImage', 'Image16x9', 'Image15x10', 'Image4x3', 'Image12x10', 'Image1x1', 'Image191x100', 'Image4x1']);\nconst upload = z.object({ ...mediaSourceFields, image_type: imageType.default('GenericImage'), alt_text: z.string().max(1000).optional() })\n .refine(value => Boolean(value.media_id) !== Boolean(value.file_path), 'Choose media_id or file_path');\nconst image = z.object({ image_id: id });\nconst output = creativesOutput.extend({ images: z.array(z.record(z.string(), z.unknown())), next_page_index: z.number().int().nonnegative().optional() });\nexport const MICROSOFT_IMAGE_WRITES = new Set(['microsoft_upload_image', 'microsoft_delete_image']);\nconst rows = (value: unknown): Row[] => z.array(z.record(z.string(), z.unknown())).parse(value ?? []);\nconst nativeId = (value: unknown): string => {\n if (typeof value === 'number' && (!Number.isSafeInteger(value) || value <= 0)) throw new AdportError('PROVIDER_ERROR', 'microsoft: unsafe native media ID');\n const parsed = id.safeParse(typeof value === 'number' ? String(value) : value);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid native media ID');\n return parsed.data;\n};\n\n/** MicrosoftDocs/Advertising@fdee2fcf and official Python SDK@4b6fb31c; live-verified CSV flags. */\nexport class MicrosoftImageService {\n constructor(private readonly client: MicrosoftAdsClient, private readonly scope: (account: string) => Promise<RequestScope>, private readonly media: MediaResolver = new LocalMediaResolver()) {}\n\n private async request(account: string, path: string, body: Row, method: 'POST' | 'DELETE' = 'POST'): Promise<Row> {\n id.parse(account);\n const scope = await this.scope(account);\n if (!scope.customerId || scope.customerAccountId !== account) throw new AdportError('INVALID_INPUT', 'microsoft: account ownership could not be verified');\n const result = await this.client.request<Row>('campaign', method, path, body, scope);\n const errors = formatPartialErrors(result.PartialErrors as Parameters<typeof formatPartialErrors>[0]);\n if (errors) throw new AdportError('PROVIDER_ERROR', `microsoft: ${path}: ${errors}. Reconcile before retrying.`, { resourceIds: Array.isArray(result.MediaIds) ? result.MediaIds.filter(value => value !== null).map(nativeId) : [], partialErrors: result.PartialErrors });\n return result;\n }\n\n private async page(account: string, pageIndex: number, pageSize: number): Promise<Row[]> {\n const result = await this.request(account, 'MediaMetaData/QueryByAccountId', {\n MediaEnabledEntities: 'ImageAdExtension, ResponsiveAd', PageInfo: { Index: pageIndex, Size: pageSize }, ReturnAdditionalFields: 'Text',\n });\n if (!Object.hasOwn(result, 'MediaMetaData')) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-library metadata was not returned');\n const images = rows(result.MediaMetaData);\n if (images.length > pageSize || new Set(images.map(value => nativeId(value.Id))).size !== images.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid image-library page');\n return images;\n }\n\n private async find(account: string, imageId: string): Promise<Row | undefined> {\n id.parse(imageId);\n const seen = new Set<string>();\n for (let page = 0; page < 5; page++) {\n const values = await this.page(account, page, 1000);\n for (const value of values) {\n const key = nativeId(value.Id);\n if (seen.has(key)) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-library pagination did not advance');\n seen.add(key);\n }\n const found = values.find(value => nativeId(value.Id) === imageId);\n if (found) return found;\n if (values.length < 1000) return;\n }\n throw new AdportError('PROVIDER_ERROR', 'microsoft: cannot verify image ownership within the 5000-image library scan limit');\n }\n\n private async owned(account: string, imageId: string): Promise<Row> {\n const result = await this.find(account, imageId);\n if (!result) throw new AdportError('INVALID_INPUT', 'microsoft: image was not found in the selected account library');\n return result;\n }\n\n private gallery(account: string, images: Row[], truncated: boolean, nextPage?: number) {\n const creatives: Creative[] = images.map(value => {\n const imageId = nativeId(value.Id), alt = typeof value.Text === 'string' ? value.Text : undefined;\n const representations = rows(value.Representations);\n const media: Creative['media'] = representations.flatMap(item => {\n if (typeof item.Url !== 'string') return [];\n try {\n const url = new URL(item.Url);\n if (url.protocol === 'https:' && !url.username && !url.password && url.hostname === 'www.bing.com') return [{ type: 'image' as const, url: item.Url, ...(alt ? { alt } : {}) }];\n } catch { /* Unsupported previews remain in native metadata. */ }\n return [];\n });\n return { id: imageId, account_id: account, provider: 'microsoft', name: `Image ${imageId}`, type: String(value.MediaType ?? 'IMAGE'), headlines: [], descriptions: alt ? [alt] : [], landing_urls: [], media, actions: [] };\n });\n return output.parse({ images, creatives, truncated, ...(nextPage !== undefined ? { next_page_index: nextPage } : {}) });\n }\n\n async list(input: { account_id: string; page_index: number; page_size: number }) {\n const images = await this.page(input.account_id, input.page_index, input.page_size);\n const truncated = images.length === input.page_size;\n return this.gallery(input.account_id, images, truncated, truncated ? input.page_index + 1 : undefined);\n }\n\n async get(input: { account_id: string; image_id: string }) {\n return this.gallery(input.account_id, [await this.owned(input.account_id, input.image_id)], false);\n }\n\n async lookupMany(account: string, imageIds: string[]) {\n const wanted = new Set(imageIds.map(value => id.parse(value))), found: Row[] = [], seen = new Set<string>();\n for (let page = 0; wanted.size && page < 5; page++) {\n const values = await this.page(account, page, 1000);\n for (const value of values) {\n const key = nativeId(value.Id);\n if (seen.has(key)) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-library pagination did not advance');\n seen.add(key);\n if (wanted.delete(key)) found.push(value);\n }\n if (values.length < 1000) break;\n }\n return { ...this.gallery(account, found, wanted.size > 0), missing_image_ids: [...wanted] };\n }\n\n async extensionUses(input: { account_id: string; image_id: string }) {\n await this.owned(input.account_id, input.image_id);\n const result = await this.request(input.account_id, 'MediaAssociations/Query', { MediaEnabledEntities: 'ImageAdExtension', MediaIds: [input.image_id] });\n // The native response is one array of associations per requested media ID.\n if (!Array.isArray(result.MediaAssociations) || result.MediaAssociations.length !== 1 || !Array.isArray(result.MediaAssociations[0])) throw new AdportError('PROVIDER_ERROR', 'microsoft: image-extension associations were not returned');\n const associations = rows(result.MediaAssociations[0]);\n for (const value of associations) {\n nativeId(value.EntityId);\n if (nativeId(value.MediaId) !== input.image_id || value.MediaEnabledEntity !== 'ImageAdExtension') throw new AdportError('PROVIDER_ERROR', 'microsoft: image-extension association identity mismatch');\n }\n return { image_id: input.image_id, associations, coverage: 'ImageAdExtension only; ResponsiveAd uses are not returned by this API', truncated: false };\n }\n\n async plan(op: WriteOperation): Promise<ImagePlan> {\n id.parse(op.accountId);\n const expectedKind = op.tool === 'microsoft_upload_image' ? 'create' : 'remove';\n if (op.provider !== 'microsoft' || !MICROSOFT_IMAGE_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: image operation kind mismatch');\n if (op.tool === 'microsoft_upload_image') {\n const input = upload.parse(op.payload);\n // The native Image.Data limit is 102400 base64 characters.\n const file = await this.media.read(input, { maxBytes: 76800, contentTypes: ['image/png', 'image/jpeg', 'image/gif'] });\n return { summary: `Upload Microsoft image ${file.name}`, changes: [`+ ${input.image_type}; ${file.contentType}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}`, ...(input.alt_text !== undefined ? [`Image alt text: ${JSON.stringify(input.alt_text)}`] : []), 'Creates an unattached image. Microsoft validates dimensions and rejects animation; PNG images are converted to JPEG.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'Media', { AccountId: op.accountId, Media: [{ Type: 'Image', MediaType: input.image_type, ...(input.alt_text !== undefined ? { Text: input.alt_text } : {}), Data: Buffer.from(file.bytes).toString('base64') }] });\n const created = Array.isArray(result.MediaIds) ? result.MediaIds.filter(value => value !== null).map(nativeId) : [];\n if (created.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: image upload receipt mismatch; reconcile before retrying', { resourceIds: created });\n let readback: Row;\n try { readback = await this.owned(op.accountId, created[0]!); }\n catch { throw new AdportError('PROVIDER_ERROR', `microsoft: image ${created[0]} upload was accepted but library readback failed; reconcile before retrying`, { resourceIds: created }); }\n if (input.alt_text !== undefined && readback.Text !== input.alt_text) throw new AdportError('PROVIDER_ERROR', 'microsoft: uploaded image alt text was not confirmed; reconcile before retrying', { resourceIds: created });\n return created;\n } };\n }\n const input = image.parse(op.payload), current = await this.owned(op.accountId, input.image_id);\n const uses = await this.extensionUses({ account_id: op.accountId, image_id: input.image_id });\n if (uses.associations.length) throw new AdportError('INVALID_INPUT', 'microsoft: image is assigned to an image extension; remove the reference before deletion');\n return { summary: `Delete Microsoft image ${input.image_id}`, changes: [`- ${input.image_id}; type ${String(current.MediaType)}; alt text ${JSON.stringify(current.Text ?? null)}`, 'Permanent deletion. Microsoft atomically rejects images assigned to any image extension or responsive ad. The preflight association API covers image extensions only.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'Media', { AccountId: op.accountId, MediaIds: [input.image_id] }, 'DELETE');\n if (await this.find(op.accountId, input.image_id)) throw new AdportError('PROVIDER_ERROR', 'microsoft: image deletion was not confirmed; reconcile before retrying', { resourceIds: [input.image_id] });\n return [input.image_id];\n } };\n }\n}\n\nexport function microsoftImageTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_images', namespace: 'microsoft', description: 'View account-library image metadata, alt text and native image previews. Native page indexes start at zero; a full page may have a continuation.', input: z.object({ account_id: id, page_index: z.number().int().nonnegative().max(100000).default(0), page_size: z.number().int().positive().max(1000).default(20) }), output, presentation: 'creatives', pagination: { cursorInput: 'page_index', cursorOutput: 'next_page_index' }, annotations: { readOnly: true }, handler: input => provider.images.list(input) }),\n defineTool({ name: 'microsoft_get_library_image', namespace: 'microsoft', description: 'Read one image through the selected account library finder, including native alt text and previews. Ownership lookup is bounded to 5000 images.', input: z.object({ account_id: id, image_id: id }), output, presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.images.get(input) }),\n defineTool({ name: 'microsoft_image_extension_associations', namespace: 'microsoft', description: 'Read image-extension references for an account-owned image. This API does not return responsive-ad references; an empty result does not prove global non-use.', input: z.object({ account_id: id, image_id: id }), output: z.object({ image_id: id, associations: z.array(z.record(z.string(), z.unknown())), coverage: z.string(), truncated: z.boolean() }), annotations: { readOnly: true }, handler: input => provider.images.extensionUses(input) }),\n guardedWriteTool({ name: 'microsoft_upload_image', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Upload a SHA-256-bound static image as an unattached account asset. Hosted calls require project media_id. Native cap 76800 bytes; PNG converts to JPEG. Alt text is set at creation; no serving association is created.', payload: upload }),\n guardedWriteTool({ name: 'microsoft_delete_image', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Permanently delete an account-owned image only if Microsoft verifies it is unassigned. Preflight checks image-extension uses; native deletion also rejects responsive-ad assignments.', payload: image }),\n ];\n}\n","import { AdportError, creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition, type Creative, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { type MicrosoftAdsClient, type RequestScope } from './client.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst extensionType = z.enum(['CalloutAdExtension', 'SitelinkAdExtension', 'StructuredSnippetAdExtension', 'ImageAdExtension']);\nconst url = z.string().url().max(2048).refine(value => { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password; });\nconst urls = z.array(url).min(1).max(10);\nconst sitelink = { display_text: z.string().min(1).max(35), final_urls: urls, description1: z.string().max(35).optional(), description2: z.string().max(35).optional() };\nconst image = { alternative_text: z.string().min(1).max(35), image_ids: z.array(id).min(1).max(4), description: z.string().max(100).optional(), final_urls: urls.optional() };\nconst content = z.discriminatedUnion('extension_type', [\n z.object({ extension_type: z.literal('CalloutAdExtension'), text: z.string().min(1).max(25) }),\n z.object({ extension_type: z.literal('SitelinkAdExtension'), ...sitelink }),\n z.object({ extension_type: z.literal('StructuredSnippetAdExtension'), header: z.string().min(1).max(100), values: z.array(z.string().min(1).max(25)).min(3).max(10) }),\n z.object({ extension_type: z.literal('ImageAdExtension'), ...image }),\n]);\nconst fields: Record<string, string> = { text: 'Text', display_text: 'DisplayText', final_urls: 'FinalUrls', description1: 'Description1', description2: 'Description2', header: 'Header', values: 'Values', alternative_text: 'AlternativeText', image_ids: 'ImageMediaIds', description: 'Description' };\nconst labels: Record<string, string> = { Text: 'Callout text', DisplayText: 'Link text', FinalUrls: 'Landing pages', Description1: 'Description 1', Description2: 'Description 2', Header: 'Localized header', Values: 'Snippet values', AlternativeText: 'Alternative text', ImageMediaIds: 'Source images', Description: 'Internal description' };\nconst reviewValue = (value: unknown): string => value === null || value === undefined ? '—' : typeof value === 'string' ? value : JSON.stringify(value);\nconst reference = z.object({ extension_id: id, extension_type: extensionType });\nconst versioned = reference.extend({ expected_version: z.number().int().positive() });\nconst update = versioned.extend({\n text: z.string().min(1).max(25).optional(), ...z.object(sitelink).partial().shape,\n header: z.string().min(1).max(100).optional(), values: z.array(z.string().min(1).max(25)).min(3).max(10).optional(), ...z.object(image).partial().shape,\n}).superRefine((value, ctx) => {\n const allowed: Record<string, string[]> = { CalloutAdExtension: ['text'], SitelinkAdExtension: Object.keys(sitelink), StructuredSnippetAdExtension: ['header', 'values'], ImageAdExtension: Object.keys(image) };\n const supplied = Object.keys(fields).filter(key => value[key as keyof typeof value] !== undefined);\n if (!supplied.length || supplied.some(key => !allowed[value.extension_type]!.includes(key))) ctx.addIssue({ code: 'custom', message: 'Supply content changes supported by this extension type' });\n});\nconst target = z.discriminatedUnion('type', [z.object({ type: z.literal('Account') }), z.object({ type: z.literal('Campaign'), campaign_id: id }), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id })]);\ntype Target = z.infer<typeof target>;\nconst mutable: Record<z.infer<typeof extensionType>, string[]> = {\n CalloutAdExtension: ['Text', 'Scheduling'],\n SitelinkAdExtension: ['DisplayText', 'Description1', 'Description2', 'DestinationUrl', 'DevicePreference', 'Scheduling', 'FinalUrls', 'FinalMobileUrls', 'FinalUrlSuffix', 'TrackingUrlTemplate', 'UrlCustomParameters'],\n StructuredSnippetAdExtension: ['Header', 'Values', 'Scheduling'],\n ImageAdExtension: ['AlternativeText', 'Description', 'DestinationUrl', 'DisplayText', 'FinalUrls', 'FinalMobileUrls', 'FinalUrlSuffix', 'TrackingUrlTemplate', 'UrlCustomParameters', 'ImageMediaIds', 'Images', 'Layouts', 'Scheduling'],\n};\nconst allowedReadOnly = ['Id', 'Version', 'Type', 'Status', 'ForwardCompatibilityMap', 'FinalAppUrls', 'SourceType', 'DevicePreference'];\nconst extensionOutput = creativesOutput.extend({ extensions: z.array(z.record(z.string(), z.unknown())) });\nexport const MICROSOFT_EXTENSION_WRITES = new Set(['microsoft_create_ad_extension', 'microsoft_update_ad_extension', 'microsoft_delete_ad_extension', 'microsoft_link_ad_extension', 'microsoft_unlink_ad_extension']);\n\n/** REST contracts pinned at MicrosoftDocs/Advertising@fdee2fcf; flags use native REST CSV. */\nexport class MicrosoftExtensionService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string) => Promise<RequestScope>, campaign: (account: string, campaign: string) => Promise<unknown>, private readonly imageLookup: (account: string, ids: string[]) => Promise<{ creatives: Creative[]; missing_image_ids: string[] }>) { super(client, scope, campaign); }\n\n async getRaw(account: string, extensionId: string, type: z.infer<typeof extensionType>): Promise<Row> {\n const result = await this.request(account, 'AdExtensions/QueryByIds', { AccountId: account, AdExtensionIds: [extensionId], AdExtensionType: type });\n const values = rows(result.AdExtensions);\n if (values.length !== 1 || nativeId(values[0]!.Id) !== extensionId || values[0]!.Type !== type) throw new AdportError('INVALID_INPUT', 'microsoft: extension was not found with this type in the selected account');\n if (!Number.isSafeInteger(values[0]!.Version) || Number(values[0]!.Version) < 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension version was not returned');\n return values[0]!;\n }\n\n private card(account: string, value: Row): Creative {\n if (!Number.isSafeInteger(value.Version) || Number(value.Version) < 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension version was not returned');\n const type = extensionType.parse(value.Type), extensionId = nativeId(value.Id), args = { account_id: account, extension_id: extensionId, extension_type: type, expected_version: value.Version };\n const text = (key: string) => typeof value[key] === 'string' ? String(value[key]) : '';\n const edit: Creative['actions'][number] = { label: 'Edit shared extension', tool: 'microsoft_update_ad_extension', arguments: args, fields: [] };\n if (type === 'CalloutAdExtension') edit.fields = [{ key: 'text', label: 'Callout text', type: 'text', value: text('Text'), max_length: 25 }];\n if (type === 'SitelinkAdExtension') edit.fields = [{ key: 'display_text', label: 'Link text', type: 'text', value: text('DisplayText'), max_length: 35 }, { key: 'description1', label: 'Description 1', type: 'text', value: text('Description1'), max_length: 35 }, { key: 'description2', label: 'Description 2', type: 'text', value: text('Description2'), max_length: 35 }, { key: 'final_urls', label: 'Landing pages (one per line)', type: 'url_list', value: Array.isArray(value.FinalUrls) ? value.FinalUrls.map(String) : [] }];\n if (type === 'StructuredSnippetAdExtension') edit.fields = [{ key: 'header', label: 'Localized header', type: 'text', value: text('Header') }, { key: 'values', label: 'Values (one per line)', type: 'text_list', value: Array.isArray(value.Values) ? value.Values.map(String) : [] }];\n if (type === 'ImageAdExtension') edit.fields = [{ key: 'alternative_text', label: 'Extension alternative text', type: 'text', value: text('AlternativeText'), max_length: 35 }, { key: 'description', label: 'Internal description', type: 'text', value: text('Description'), max_length: 100 }, { key: 'image_ids', label: 'Account image IDs (one per line)', type: 'text_list', value: this.imageIds(value) }];\n return { id: extensionId, provider: 'microsoft', account_id: account, type, name: text('Text') || text('DisplayText') || text('Header') || text('Description') || `Extension ${extensionId}`, status: typeof value.Status === 'string' ? value.Status : undefined, headlines: [text('Text') || text('DisplayText') || text('Header')].filter(Boolean), descriptions: [text('Description1'), text('Description2'), text('AlternativeText'), ...(Array.isArray(value.Values) ? value.Values.map(String) : [])].filter(Boolean), landing_urls: Array.isArray(value.FinalUrls) ? value.FinalUrls.filter(item => url.safeParse(item).success) as string[] : [], media: [], actions: [edit] };\n }\n\n private imageIds(value: Row): string[] {\n const ids = Array.isArray(value.ImageMediaIds) && value.ImageMediaIds.length ? value.ImageMediaIds.map(nativeId) : rows(value.Images).map(link => nativeId(row(link.Asset).Id));\n return [...new Set(ids)];\n }\n\n private async gallery(account: string, values: Row[], truncated: boolean, next?: string) {\n const creatives = values.map(value => this.card(account, value));\n const imageIds = [...new Set(values.filter(value => value.Type === 'ImageAdExtension').flatMap(value => this.imageIds(value)))];\n if (imageIds.length) {\n const previews = await this.imageLookup(account, imageIds), media = new Map(previews.creatives.map(value => [value.id, value.media]));\n for (const [index, value] of values.entries()) if (value.Type === 'ImageAdExtension') creatives[index]!.media = this.imageIds(value).flatMap(image => media.get(image) ?? []).map(preview => ({ ...preview, ...(typeof value.AlternativeText === 'string' ? { alt: value.AlternativeText } : {}) }));\n }\n return extensionOutput.parse({ extensions: values, creatives, truncated, ...(next ? { next_cursor: next } : {}) });\n }\n\n async get(input: { account_id: string; extension_id: string; extension_type: z.infer<typeof extensionType> }) {\n const value = await this.getRaw(input.account_id, input.extension_id, input.extension_type);\n return this.gallery(input.account_id, [value], false);\n }\n\n async list(input: { account_id: string; extension_types: Array<z.infer<typeof extensionType>>; after_extension_id?: string; limit: number }) {\n const result = await this.request(input.account_id, 'AdExtensionIds/QueryByAccountId', { AccountId: input.account_id, AdExtensionType: input.extension_types.join(', '), AssociationType: null });\n if (!Array.isArray(result.AdExtensionIds)) throw new AdportError('PROVIDER_ERROR', 'microsoft: account extension IDs were not returned');\n const ids = result.AdExtensionIds.map(nativeId).sort((a, b) => BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0);\n if (new Set(ids).size !== ids.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate native extension IDs');\n const remaining = ids.filter(value => !input.after_extension_id || BigInt(value) > BigInt(input.after_extension_id)), selected = remaining.slice(0, input.limit);\n let values: Row[] = [];\n if (selected.length) {\n const detail = await this.request(input.account_id, 'AdExtensions/QueryByIds', { AccountId: input.account_id, AdExtensionIds: selected, AdExtensionType: input.extension_types.join(', ') });\n values = rows(detail.AdExtensions);\n if (values.length !== selected.length || values.some((value, index) => nativeId(value.Id) !== selected[index] || !input.extension_types.includes(extensionType.parse(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension page identity mismatch');\n }\n const truncated = remaining.length > selected.length;\n return this.gallery(input.account_id, values, truncated, truncated ? selected.at(-1) : undefined);\n }\n\n private async entity(account: string, value: Target) {\n if (value.type === 'Account') return { entityId: account, paused: false };\n const campaign = await this.campaign(account, value.campaign_id);\n if (value.type === 'Campaign') return { entityId: value.campaign_id, paused: campaign.Status === 'Paused' };\n const result = await this.request(account, 'AdGroups/QueryByIds', { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id] });\n const groups = rows(result.AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== value.ad_group_id) throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n return { entityId: value.ad_group_id, paused: campaign.Status === 'Paused' || groups[0]!.Status === 'Paused' };\n }\n\n async associations(input: { account_id: string; target: Target; extension_type: z.infer<typeof extensionType> }) {\n const entity = await this.entity(input.account_id, input.target);\n const result = await this.request(input.account_id, 'AdExtensionsAssociations/Query', { AccountId: input.account_id, AdExtensionType: input.extension_type, AssociationType: input.target.type, EntityIds: [entity.entityId] });\n const collections = rows(result.AdExtensionAssociationCollection);\n if (collections.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension associations were not returned');\n const associations = rows(collections[0]!.AdExtensionAssociations);\n for (const value of associations) if (nativeId(value.EntityId) !== entity.entityId || value.AssociationType !== input.target.type || row(value.AdExtension).Type !== input.extension_type) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension association identity mismatch');\n return { associations, truncated: false };\n }\n\n private nativeContent(value: Record<string, unknown>) {\n const result: Row = { Type: value.extension_type };\n for (const [key, native] of Object.entries(fields)) if (value[key] !== undefined) result[native] = value[key];\n if (result.Type === 'SitelinkAdExtension') {\n const first = String(result.Description1 ?? ''), second = String(result.Description2 ?? '');\n if (Boolean(first) !== Boolean(second) || ((first || second) && String(result.DisplayText).length > 25)) throw new AdportError('INVALID_INPUT', 'microsoft: sitelink descriptions must be supplied together; links with descriptions have a 25-character text limit');\n }\n return result;\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_create_ad_extension' || op.tool === 'microsoft_link_ad_extension' ? 'create' : op.tool === 'microsoft_delete_ad_extension' || op.tool === 'microsoft_unlink_ad_extension' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_EXTENSION_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: extension operation kind mismatch');\n if (op.tool === 'microsoft_create_ad_extension') {\n const input = content.parse(op.payload.content), value = this.nativeContent(input);\n await this.verifyImages(op.accountId, value);\n return { summary: `Create unattached Microsoft ${input.extension_type}`, changes: [`+ ${JSON.stringify(value)}`, 'Extension status is natively Active; it cannot serve until associated. No association is created.', ...(input.extension_type === 'ImageAdExtension' ? ['Microsoft validates placement crop dimensions: an accepted library image can still be too small for an extension. This preview is not server-validated.'] : [])], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'AdExtensions', { AccountId: op.accountId, AdExtensions: [value] });\n const identities = rows(result.AdExtensionIdentities), created = identities.map(value => nativeId(value.Id));\n if (created.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension creation receipt mismatch; reconcile before retrying', { resourceIds: created });\n await this.confirm(op.accountId, created[0]!, input.extension_type, value);\n return created;\n } };\n }\n const input = versioned.parse(op.payload), current = await this.getRaw(op.accountId, input.extension_id, input.extension_type);\n if (current.Version !== input.expected_version) throw new AdportError('PENDING_MISMATCH', 'microsoft: extension version changed; read it and request a fresh preview');\n if (op.tool === 'microsoft_update_ad_extension') {\n const change = update.parse(op.payload), supplied = this.nativeContent(change);\n if (Object.keys(supplied).length === 1) throw new AdportError('INVALID_INPUT', 'microsoft: supply at least one extension content change');\n const supported = mutable[input.extension_type];\n if (Object.keys(current).some(key => current[key] !== null && !supported.includes(key) && !allowedReadOnly.includes(key))) throw new AdportError('INVALID_INPUT', 'microsoft: extension contains unsupported fields; a safe full replacement cannot be built');\n const value: Row = { Type: input.extension_type, Id: input.extension_id, ...Object.fromEntries(supported.filter(key => current[key] !== undefined).map(key => [key, current[key]])), ...supplied };\n // Replacing ImageMediaIds must not retain the old Images array, which can override it.\n if (supplied.ImageMediaIds && JSON.stringify((supplied.ImageMediaIds as string[]).slice().sort()) !== JSON.stringify(this.imageIds(current).sort())) delete value.Images;\n if (Array.isArray(value.Images)) value.Images = value.Images.map(link => {\n const current = row(link), asset = row(current.Asset);\n const allowed = ['Id', 'Type', 'Name', 'CropHeight', 'CropWidth', 'CropX', 'CropY', 'CroppingType', 'SubType', 'TargetHeight', 'TargetWidth'];\n if (Object.keys(asset).some(key => asset[key] != null && !allowed.includes(key) && key !== 'Excluded')) throw new AdportError('INVALID_INPUT', 'microsoft: unsupported image crop fields prevent a safe extension update');\n return { Asset: Object.fromEntries(allowed.filter(key => asset[key] !== undefined).map(key => [key, asset[key]])), ...(current.PinnedField != null ? { PinnedField: current.PinnedField } : {}) };\n });\n await this.verifyImages(op.accountId, value);\n if (input.extension_type === 'SitelinkAdExtension') this.nativeContent({ extension_type: input.extension_type, display_text: value.DisplayText, description1: value.Description1, description2: value.Description2 });\n const impact = 'Every entity using this extension can change, including active ads. Existing scheduling, device preference and tracking fields are preserved. Native extension Version is read-only.';\n const fieldChanges = Object.keys(supplied).filter(key => key !== 'Type').flatMap(key => {\n const before = key === 'ImageMediaIds' ? this.imageIds(current) : current[key], after = supplied[key];\n return JSON.stringify(before ?? null) === JSON.stringify(after ?? null) ? [] : [{ field: labels[key] ?? key, before: reviewValue(before), after: reviewValue(after) }];\n });\n return { summary: `Update shared Microsoft extension ${input.extension_id}`, changes: [`~ ${JSON.stringify(current)} → ${JSON.stringify(value)}`, impact], fieldChanges, notes: [impact], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'AdExtensions', { AccountId: op.accountId, AdExtensions: [value] }, 'PUT');\n await this.confirm(op.accountId, input.extension_id, input.extension_type, value, input.expected_version);\n return [input.extension_id];\n } };\n }\n if (op.tool === 'microsoft_delete_ad_extension') return { summary: `Delete shared Microsoft extension ${input.extension_id}`, changes: [`- ${JSON.stringify(current)}`, 'Permanent deletion removes this shared extension and affects every associated entity. Uploaded source images remain in the media library.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'AdExtensions', { AccountId: op.accountId, AdExtensionIds: [input.extension_id] }, 'DELETE');\n const result = await this.request(op.accountId, 'AdExtensionIds/QueryByAccountId', { AccountId: op.accountId, AdExtensionType: input.extension_type, AssociationType: null });\n if (!Array.isArray(result.AdExtensionIds) || result.AdExtensionIds.map(nativeId).includes(input.extension_id)) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension deletion was not confirmed; reconcile before retrying', { resourceIds: [input.extension_id] });\n return [input.extension_id];\n } };\n const value = target.parse((op.payload as Row).target), entity = await this.entity(op.accountId, value), linking = op.tool === 'microsoft_link_ad_extension';\n if (linking && guard.forcePausedCreation && !entity.paused) throw new AdportError('POLICY_VIOLATION', 'microsoft: extension associations cannot be paused; paused_creation requires a paused campaign or ad group target');\n return { summary: `${linking ? 'Associate' : 'Remove'} Microsoft extension ${input.extension_id} ${linking ? 'with' : 'from'} ${value.type} ${entity.entityId}`, changes: [`${linking ? '+' : '-'} explicit association; extension ${input.extension_id}; ${value.type} ${entity.entityId}`, 'Associations have no pause state. No campaign/ad group status is changed; other associations are preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, linking ? 'AdExtensionsAssociations/Set' : 'AdExtensionsAssociations', { AccountId: op.accountId, AdExtensionIdToEntityIdAssociations: [{ AdExtensionId: input.extension_id, EntityId: entity.entityId }], AssociationType: value.type }, linking ? 'POST' : 'DELETE');\n const readback = await this.associations({ account_id: op.accountId, target: value, extension_type: input.extension_type });\n const exists = readback.associations.some(value => nativeId(row(value.AdExtension).Id) === input.extension_id);\n if (exists !== linking) throw new AdportError('PROVIDER_ERROR', 'microsoft: extension association change was not confirmed; reconcile before retrying', { resourceIds: [input.extension_id] });\n return [input.extension_id];\n } };\n }\n\n private async confirm(account: string, extension: string, type: z.infer<typeof extensionType>, expected: Row, previousVersion?: number) {\n try {\n const actual = await this.getRaw(account, extension, type);\n if (previousVersion !== undefined && Number(actual.Version) <= previousVersion) throw new Error('Version did not advance');\n for (const key of Object.keys(expected).filter(key => !['Id', 'Type', 'ImageMediaIds', 'Images'].includes(key))) {\n if (JSON.stringify(actual[key] ?? null) !== JSON.stringify(expected[key] ?? null)) throw new Error(`Readback mismatch: ${key}`);\n }\n if (type === 'ImageAdExtension' && JSON.stringify(this.imageIds(actual).sort()) !== JSON.stringify(this.imageIds(expected).sort())) throw new Error('Image references were not confirmed');\n } catch { throw new AdportError('PROVIDER_ERROR', `microsoft: extension ${extension} mutation was accepted but content readback was not confirmed; reconcile before retrying`, { resourceIds: [extension] }); }\n }\n\n private async verifyImages(account: string, value: Row) {\n if (value.Type !== 'ImageAdExtension') return;\n const ids = this.imageIds(value);\n if (!ids.length || (await this.imageLookup(account, ids)).missing_image_ids.length) throw new AdportError('INVALID_INPUT', 'microsoft: image references could not be verified in the selected account library');\n }\n}\n\nexport function microsoftExtensionTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_ad_extensions', namespace: 'microsoft', description: 'View account-owned callout, sitelink, structured-snippet and image extensions, including native versions and shared-content edit actions. Continue with next_cursor as after_extension_id.', input: z.object({ account_id: id, extension_types: z.array(extensionType).min(1).max(4).default([...extensionType.options]), after_extension_id: id.optional(), limit: z.number().int().positive().max(100).default(20) }), output: extensionOutput, presentation: 'creatives', pagination: { cursorInput: 'after_extension_id' }, annotations: { readOnly: true }, handler: input => provider.extensions.list(input) }),\n defineTool({ name: 'microsoft_get_ad_extension', namespace: 'microsoft', description: 'Read one extension by exact ID and type in the selected account, including the native version required for edits.', input: reference.extend({ account_id: id }), output: extensionOutput, presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.extensions.get(input) }),\n defineTool({ name: 'microsoft_ad_extension_associations', namespace: 'microsoft', description: 'Read direct extension associations for an account, campaign or verified ad group. Native editorial status is preserved; inherited associations are not combined.', input: z.object({ account_id: id, target, extension_type: extensionType }), output: z.object({ associations: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() }), annotations: { readOnly: true }, handler: input => provider.extensions.associations(input) }),\n guardedWriteTool({ name: 'microsoft_create_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create an unattached callout, sitelink, structured-snippet or image extension. Native status is Active but no serving association is created. Uses full native content readback.', payload: z.object({ content }) }),\n guardedWriteTool({ name: 'microsoft_update_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit supplied shared extension content with expected_version. Preserves omitted mutable fields and scheduling; all associated entities can change. Image alt text here belongs to the extension, not the source media.', payload: update }),\n guardedWriteTool({ name: 'microsoft_delete_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Permanently delete an account-owned shared extension and its associations. Requires its latest native version. Source images remain in the account library.', payload: versioned }),\n guardedWriteTool({ name: 'microsoft_link_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Associate a version-verified extension with one owned entity. Associations cannot be paused; default paused_creation requires a paused parent campaign or ad group. Account-wide associations are blocked under that policy.', payload: versioned.extend({ target }) }),\n guardedWriteTool({ name: 'microsoft_unlink_ad_extension', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove one explicit extension association, preserving its source extension and other associations. Does not alter inherited associations or serving statuses.', payload: versioned.extend({ target }) }),\n ];\n}\n","import { AdportError, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, type MicrosoftService, type RequestScope } from './client.js';\n\nexport type MicrosoftRow = Record<string, unknown>;\nexport type MicrosoftPlan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]>; resultDetails?: () => unknown; resultWarnings?: () => string[] };\nexport const microsoftId = z.string().regex(/^[1-9]\\d*$/);\nexport const microsoftRows = (value: unknown): MicrosoftRow[] => z.array(z.record(z.string(), z.unknown())).parse(value ?? []);\nexport const microsoftRow = (value: unknown): MicrosoftRow => z.record(z.string(), z.unknown()).parse(value);\nexport function microsoftNativeId(value: unknown): string {\n if (typeof value === 'number' && (!Number.isSafeInteger(value) || value <= 0)) throw new AdportError('PROVIDER_ERROR', 'microsoft: unsafe native resource ID');\n const parsed = microsoftId.safeParse(typeof value === 'number' ? String(value) : value);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid native resource ID');\n return parsed.data;\n}\n\nfunction compactErrors(errors: unknown[]): MicrosoftRow[] {\n const grouped = new Map<string, MicrosoftRow>();\n for (const value of errors) {\n const error = microsoftRow(value), { PublisherCountry, ...base } = error;\n if (typeof PublisherCountry !== 'string') { grouped.set(`item:${grouped.size}`, error); continue; }\n const key = JSON.stringify(base), previous = grouped.get(key);\n if (previous) previous.PublisherCountries = [...new Set([...(previous.PublisherCountries as string[]), PublisherCountry])];\n else grouped.set(key, { ...base, PublisherCountries: [PublisherCountry] });\n }\n return [...grouped.values()];\n}\n\n/** Shared scoped REST access. NestedPartialErrors are not interchangeable with PartialErrors. */\nexport class MicrosoftNativeService {\n constructor(protected readonly client: MicrosoftAdsClient, private readonly scope: (account: string, refresh?: boolean) => Promise<RequestScope>, private readonly lookupCampaign: (account: string, campaign: string) => Promise<unknown>) {}\n\n protected async accountScope(account: string, refresh = false): Promise<RequestScope> {\n microsoftId.parse(account);\n const scope = await this.scope(account, refresh);\n if (!scope.customerId || scope.customerAccountId !== account) throw new AdportError('INVALID_INPUT', 'microsoft: selected account ownership could not be verified');\n return scope;\n }\n\n protected async request(account: string, path: string, body: MicrosoftRow, method: 'POST' | 'PUT' | 'DELETE' = 'POST', service: MicrosoftService = 'campaign'): Promise<MicrosoftRow> {\n const scope = await this.accountScope(account);\n const result = await this.client.request<MicrosoftRow>(service, method, path, body, scope);\n const errors = ['PartialErrors', 'NestedPartialErrors'].flatMap(key => {\n if (result[key] === undefined || result[key] === null) return [];\n if (!Array.isArray(result[key])) throw new AdportError('PROVIDER_ERROR', 'microsoft: malformed native error receipt');\n return result[key].filter(value => value !== null);\n });\n if (errors.length) {\n const negativeIds = Array.isArray(result.NegativeKeywordIds) ? result.NegativeKeywordIds.flatMap(group => group && typeof group === 'object' && Array.isArray(microsoftRow(group).Ids) ? [microsoftRow(group).Ids] : []) : [];\n const ids = [result.CampaignCriterionIds, result.AdGroupCriterionIds, result.AdExtensionIdentities, result.BudgetIds, result.ConversionGoalIds, result.UetTags, result.AudienceIds, result.ExperimentIds, ...negativeIds].flatMap(value => Array.isArray(value) ? value.flatMap(item => {\n const id = item && typeof item === 'object' ? microsoftRow(item).Id : item;\n return id === null || id === undefined ? [] : [microsoftNativeId(id)];\n }) : []);\n const compact = compactErrors(errors), summary = [...new Set(compact.map(value => `${value.Code ?? '?'} ${value.ErrorCode ?? ''}: ${value.Message ?? 'nested native error'}`))].slice(0, 5).join('; ');\n throw new AdportError('PROVIDER_ERROR', `microsoft: ${path} returned partial errors (${summary}); reconcile successful resource IDs before retrying`, { resourceIds: ids, errors: compact, nativeErrorCount: errors.length });\n }\n return result;\n }\n\n protected async campaign(account: string, campaign: string): Promise<MicrosoftRow> {\n microsoftId.parse(account);\n microsoftId.parse(campaign);\n const result = microsoftRow(await this.lookupCampaign(account, campaign));\n if (microsoftNativeId(result.Id) !== campaign) throw new AdportError('INVALID_INPUT', 'microsoft: campaign ownership mismatch');\n return result;\n }\n}\n","import { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nimport { criterionType, target, add, reference, remove, bid, intentUpdate, nativeTarget } from './targeting-schemas.js';\n\nexport const MICROSOFT_TARGETING_WRITES = new Set(['microsoft_add_campaign_targets', 'microsoft_set_campaign_target_bid', 'microsoft_set_campaign_location_intent', 'microsoft_remove_campaign_targets']);\n\n/** Native REST uses concrete read selectors, Targets mutation selector and percentage bid adjustments. */\nexport class MicrosoftTargetingService extends MicrosoftNativeService {\n private subtype(value: Row) { return criterionType.parse(String(row(value.Criterion).Type).replace(/Criterion$/, '')); }\n\n private key(type: z.infer<typeof criterionType>, criterion: Row) {\n const keys: Record<z.infer<typeof criterionType>, string[]> = { Age: ['AgeRange'], Gender: ['GenderType'], Device: ['DeviceName'], DayTime: ['Day', 'FromHour', 'FromMinute', 'ToHour', 'ToMinute'], Location: ['LocationId'], LocationIntent: [], Radius: ['LatitudeDegrees', 'LongitudeDegrees', 'Radius', 'RadiusUnit'] };\n return JSON.stringify(keys[type].map(key => String(criterion[key] ?? '')));\n }\n\n private async confirm(criterion: string | string[], change: string, check: () => Promise<boolean>) {\n try { if (await check()) return; } catch { /* An accepted mutation is not retried when readback is unavailable. */ }\n throw new AdportError('PROVIDER_ERROR', `microsoft: ${change} was not confirmed; reconcile before retrying`, { resourceIds: Array.isArray(criterion) ? criterion : [criterion] });\n }\n\n private async query(account: string, campaign: string, type: z.infer<typeof criterionType>) {\n const result = await this.request(account, 'CampaignCriterions/QueryByIds', { CampaignId: campaign, CampaignCriterionIds: null, CriterionType: type });\n if (!Object.hasOwn(result, 'CampaignCriterions')) throw new AdportError('PROVIDER_ERROR', 'microsoft: campaign targeting was not returned');\n const values = rows(result.CampaignCriterions);\n if (values.some(value => nativeId(value.CampaignId) !== campaign || this.subtype(value) !== type || !['BiddableCampaignCriterion', 'NegativeCampaignCriterion'].includes(String(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: campaign target identity mismatch');\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate campaign criterion IDs');\n return values;\n }\n\n async list(input: { account_id: string; campaign_id: string; criterion_type: z.infer<typeof criterionType> }) {\n await this.campaign(input.account_id, input.campaign_id);\n return { rows: await this.query(input.account_id, input.campaign_id, input.criterion_type), truncated: false };\n }\n\n private async owned(account: string, input: z.infer<typeof reference>) {\n await this.campaign(account, input.campaign_id);\n const result = (await this.query(account, input.campaign_id, input.criterion_type)).find(value => nativeId(value.Id) === input.criterion_id);\n if (!result) throw new AdportError('INVALID_INPUT', 'microsoft: target was not found with this type in the selected campaign/account');\n return result;\n }\n\n async geoFile(input: { account_id: string; language_locale: string }) {\n const result = await this.request(input.account_id, 'GeoLocationsFileUrl/Query', { Version: '2.0', LanguageLocale: input.language_locale });\n return z.object({ FileUrl: z.string().url(), FileUrlExpiryTimeUtc: z.string(), LastModifiedTimeUtc: z.string() }).parse(result);\n }\n\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_add_campaign_targets' ? 'create' : op.tool === 'microsoft_remove_campaign_targets' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_TARGETING_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: targeting operation kind mismatch');\n if (op.tool === 'microsoft_add_campaign_targets') {\n const input = add.parse(op.payload), campaign = await this.campaign(op.accountId, input.campaign_id), values = input.targets.map(value => nativeTarget({ CampaignId: input.campaign_id }, value));\n if (guard.forcePausedCreation && campaign.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: campaign targets are natively Active and cannot be paused; paused_creation requires a paused campaign');\n const seen = new Map<string, Set<string>>();\n for (const [index, value] of values.entries()) {\n const type = input.targets[index]!.type;\n if (!seen.has(type)) seen.set(type, new Set((await this.query(op.accountId, input.campaign_id, type)).map(value => this.key(type, row(value.Criterion)))));\n const key = this.key(type, row(value.Criterion));\n if (seen.get(type)!.has(key)) throw new AdportError('INVALID_INPUT', 'microsoft: this campaign target already exists; use its explicit bid/intent edit or remove it first');\n seen.get(type)!.add(key);\n }\n return { summary: `Add ${values.length} Microsoft campaign target(s)`, changes: [`+ ${JSON.stringify(values)}`, `Campaign ${input.campaign_id} remains ${campaign.Status}. Targets have native Active status; no parent status changes. Bid adjustments are whole percentages, not multipliers.`, 'Location IDs must be current in the geographical file; Microsoft rejects deprecated targets. Schedule timezone follows the native AdScheduleUseSearcherTimeZone flag: searcher or account time. The deprecated campaign TimeZone is not authoritative.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'CampaignCriterions', { CampaignCriterions: values, CriterionType: 'Targets' });\n const created = Array.isArray(result.CampaignCriterionIds) ? result.CampaignCriterionIds.filter(value => value !== null).map(nativeId) : [];\n if (created.length !== values.length || new Set(created).size !== created.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: target creation receipt mismatch; reconcile before retrying', { resourceIds: created });\n try {\n const byType = new Map<string, Row[]>();\n for (const [index, expected] of values.entries()) {\n const type = input.targets[index]!.type;\n if (!byType.has(type)) byType.set(type, await this.query(op.accountId, input.campaign_id, type));\n const actual = byType.get(type)!.find(value => nativeId(value.Id) === created[index]);\n if (!actual || actual.Type !== expected.Type) throw new Error('Created target missing');\n const actualCriterion = row(actual.Criterion);\n for (const [key, value] of Object.entries(row(expected.Criterion))) if (key !== 'Type' && (key === 'LocationId' ? nativeId(actualCriterion[key]) !== value : actualCriterion[key] !== value)) throw new Error('Created target content mismatch');\n if (expected.CriterionBid && row(actual.CriterionBid).Multiplier !== row(expected.CriterionBid).Multiplier) throw new Error('Created target bid mismatch');\n }\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: targets were accepted but native readback was not confirmed; reconcile before retrying', { resourceIds: created }); }\n return created;\n } };\n }\n if (op.tool === 'microsoft_set_campaign_target_bid') {\n const input = bid.parse(op.payload), current = await this.owned(op.accountId, input);\n if (current.Type !== 'BiddableCampaignCriterion' || row(current.CriterionBid).Type !== 'BidMultiplier') throw new AdportError('INVALID_INPUT', 'microsoft: only biddable campaign targets with BidMultiplier support this edit');\n if (row(current.CriterionBid).Multiplier !== input.expected_current_percent) throw new AdportError('PENDING_MISMATCH', 'microsoft: target bid changed; request a fresh preview');\n const value = { CampaignId: input.campaign_id, Id: input.criterion_id, Type: 'BiddableCampaignCriterion', CriterionBid: { Type: 'BidMultiplier', Multiplier: input.bid_adjustment_percent } };\n return { summary: `Set Microsoft ${input.criterion_type} target bid adjustment`, changes: [`~ ${input.criterion_id}: ${input.expected_current_percent}% → ${input.bid_adjustment_percent}%`, 'Changes the percentage adjustment, preserving the criterion and campaign serving status. Automated bidding may use this as a signal rather than a direct override.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'CampaignCriterions', { CampaignCriterions: [value], CriterionType: 'Targets' }, 'PUT');\n await this.confirm(input.criterion_id, 'target bid update', async () => row((await this.owned(op.accountId, input)).CriterionBid).Multiplier === input.bid_adjustment_percent);\n return [input.criterion_id];\n } };\n }\n if (op.tool === 'microsoft_set_campaign_location_intent') {\n const input = intentUpdate.parse(op.payload), reference = { ...input, criterion_type: 'LocationIntent' as const }, current = await this.owned(op.accountId, reference);\n if (current.Type !== 'BiddableCampaignCriterion' || row(current.Criterion).IntentOption !== input.expected_current_intent) throw new AdportError('PENDING_MISMATCH', 'microsoft: location intent changed; request a fresh preview');\n const value = { CampaignId: input.campaign_id, Id: input.criterion_id, Type: 'BiddableCampaignCriterion', Criterion: { Type: 'LocationIntentCriterion', IntentOption: input.intent_option } };\n return { summary: 'Update Microsoft campaign location intent', changes: [`~ ${input.criterion_id}: ${input.expected_current_intent} → ${input.intent_option}`, 'No bid is sent: Microsoft ignores bid multipliers for location intent. Campaign status is preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'CampaignCriterions', { CampaignCriterions: [value], CriterionType: 'Targets' }, 'PUT');\n await this.confirm(input.criterion_id, 'location intent update', async () => row((await this.owned(op.accountId, reference)).Criterion).IntentOption === input.intent_option);\n return [input.criterion_id];\n } };\n }\n const input = remove.parse(op.payload);\n await this.campaign(op.accountId, input.campaign_id);\n const current = await this.query(op.accountId, input.campaign_id, input.criterion_type), selected = input.criterion_ids.map(id => current.find(value => nativeId(value.Id) === id));\n if (selected.some(value => !value)) throw new AdportError('INVALID_INPUT', 'microsoft: a target was not found with this type in the selected campaign/account');\n // Native code2957 requires the complete set on deletion too, not just creation.\n if (input.criterion_type === 'Device' && (input.criterion_ids.length !== 3 || current.length !== 3 || !['Computers', 'Smartphones', 'Tablets'].every(name => current.some(value => row(value.Criterion).DeviceName === name)))) throw new AdportError('INVALID_INPUT', 'microsoft: remove all three device criterion IDs together (Computers, Smartphones, Tablets)');\n return { summary: `Remove ${input.criterion_ids.length} Microsoft ${input.criterion_type} campaign target(s)`, changes: [`- ${JSON.stringify(selected)}`, 'Removing a target or exclusion can broaden or narrow delivery for this campaign. Other criterion IDs and parent serving status are preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'CampaignCriterions', { CampaignId: input.campaign_id, CampaignCriterionIds: input.criterion_ids, CriterionType: 'Targets' }, 'DELETE');\n await this.confirm(input.criterion_ids, 'target removal', async () => !(await this.query(op.accountId, input.campaign_id, input.criterion_type)).some(value => input.criterion_ids.includes(nativeId(value.Id)) && value.Status !== 'Deleted'));\n return input.criterion_ids;\n } };\n }\n}\n\nexport function microsoftTargetingTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_campaign_targets', namespace: 'microsoft', description: 'Read one concrete campaign targeting subtype with verified campaign/account ownership. Native criterion and percent bid adjustments are preserved. Targets is a mutation selector and cannot be used for reads.', input: z.object({ account_id: id, campaign_id: id, criterion_type: criterionType }), output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() }), annotations: { readOnly: true }, handler: input => provider.targeting.list(input) }),\n defineTool({ name: 'microsoft_geo_locations_file', namespace: 'microsoft', description: 'Get the native geographical-location file URL, server expiration and modification time. Use current non-deprecated location IDs for targeting; returns metadata without downloading or caching the file.', input: z.object({ account_id: id, language_locale: z.enum(['zh-Hant', 'en', 'fr', 'de', 'it', 'ja-JP', 'pt-BR', 'es']).default('en') }), annotations: { readOnly: true }, handler: input => provider.targeting.geoFile(input) }),\n guardedWriteTool({ name: 'microsoft_add_campaign_targets', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Add age, gender, device, day/time, location, location-intent or radius targets; locations can be excluded. Native targets are Active; default paused_creation requires a paused campaign. Device creation requires all three device types together. Bids are integer percent adjustments.', payload: add }),\n guardedWriteTool({ name: 'microsoft_set_campaign_target_bid', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Change a biddable target percentage adjustment with an expected current value. Device range -100..900; other supported targets -90..900. Excluded locations and location-intent criteria do not accept bids.', payload: bid }),\n guardedWriteTool({ name: 'microsoft_set_campaign_location_intent', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Change campaign location intent with an expected current value. PeopleInOrSearchingForOrViewingPages restores the API default; this criterion cannot be deleted. Preserves status and omits the inapplicable bid multiplier.', payload: intentUpdate }),\n guardedWriteTool({ name: 'microsoft_remove_campaign_targets', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove exact owned criterion IDs of one subtype. Devices require all three IDs together. Location intent cannot be deleted; use its edit tool instead. Other targets remain; removing restrictions can broaden delivery. Confirms native disappearance.', payload: remove }),\n ];\n}\n","import { z } from 'zod';\nimport { microsoftId as id, type MicrosoftRow as Row } from './native.js';\n\nexport const criterionType = z.enum(['Age', 'Gender', 'Device', 'DayTime', 'Location', 'LocationIntent', 'Radius']);\nexport const bidType = criterionType.exclude(['LocationIntent']);\nexport const adjustment = z.number().int().min(-90).max(900);\nexport const deviceAdjustment = z.number().int().min(-100).max(900);\nexport const minute = z.enum(['Zero', 'Fifteen', 'Thirty', 'FortyFive']);\nexport const intent = z.enum(['PeopleIn', 'PeopleInOrSearchingForOrViewingPages']);\nexport const target = z.discriminatedUnion('type', [\n z.object({ type: z.literal('Age'), age_range: z.enum(['EighteenToTwentyFour', 'TwentyFiveToThirtyFour', 'ThirtyFiveToFourtyNine', 'FiftyToSixtyFour', 'SixtyFiveAndAbove', 'ThirtyFiveToFiftyFour', 'FiftyFiveAndAbove', 'Unknown']), bid_adjustment_percent: adjustment.default(0) }).strict(),\n z.object({ type: z.literal('Gender'), gender: z.enum(['Male', 'Female']), bid_adjustment_percent: adjustment.default(0) }).strict(),\n z.object({ type: z.literal('Device'), device_name: z.enum(['Computers', 'Smartphones', 'Tablets']), bid_adjustment_percent: deviceAdjustment.default(0) }).strict(),\n z.object({ type: z.literal('DayTime'), day: z.enum(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']), from_hour: z.number().int().min(0).max(23), from_minute: minute, to_hour: z.number().int().min(0).max(24), to_minute: minute, bid_adjustment_percent: adjustment.default(0) }).strict(),\n z.object({ type: z.literal('Location'), location_id: id, exclude: z.boolean().default(false), bid_adjustment_percent: adjustment.optional() }).strict(),\n z.object({ type: z.literal('LocationIntent'), intent_option: intent }).strict(),\n z.object({ type: z.literal('Radius'), latitude: z.number().min(-85).max(85), longitude: z.number().min(-180).max(180), radius: z.number().int().positive().max(800), radius_unit: z.enum(['Miles', 'Kilometers']), name: z.string().max(50).optional(), bid_adjustment_percent: adjustment.default(0) }).strict(),\n]);\nexport const minutes = { Zero: 0, Fifteen: 15, Thirty: 30, FortyFive: 45 };\nexport function validateTargetBatch(value: { targets: Array<z.infer<typeof target>> }, ctx: z.RefinementCtx) {\n const devices = value.targets.filter(value => value.type === 'Device');\n if (devices.length && (devices.length !== 3 || new Set(devices.map(value => value.device_name)).size !== 3 || devices.every(value => value.bid_adjustment_percent === -100))) ctx.addIssue({ code: 'custom', message: 'Add all three distinct device types together, leaving at least one device included' });\n for (const item of value.targets) {\n if (item.type === 'Location' && item.exclude && item.bid_adjustment_percent !== undefined) ctx.addIssue({ code: 'custom', message: 'Excluded locations cannot have a bid adjustment' });\n if (item.type === 'Radius' && item.radius_unit === 'Miles' && item.radius > 500) ctx.addIssue({ code: 'custom', message: 'Radius in miles cannot exceed 500' });\n if (item.type === 'DayTime' && (item.to_hour === 24 && item.to_minute !== 'Zero' || item.from_hour * 60 + minutes[item.from_minute] >= item.to_hour * 60 + minutes[item.to_minute])) ctx.addIssue({ code: 'custom', message: 'DayTime must end after its start within one day; hour 24 requires minute Zero' });\n }\n}\nexport const add = z.object({ campaign_id: id, targets: z.array(target).min(1).max(100) }).superRefine(validateTargetBatch);\nexport const reference = z.object({ campaign_id: id, criterion_id: id, criterion_type: criterionType });\n// Native code2965 forbids deleting LocationIntent; restore its default through the edit tool.\nexport const remove = z.object({ campaign_id: id, criterion_type: criterionType.exclude(['LocationIntent']), criterion_ids: z.array(id).min(1).max(100).refine(value => new Set(value).size === value.length, 'Criterion IDs must be unique') });\nexport const bid = reference.extend({ criterion_type: bidType, bid_adjustment_percent: deviceAdjustment, expected_current_percent: z.number() }).superRefine((value, ctx) => {\n if (value.criterion_type !== 'Device' && value.bid_adjustment_percent < -90) ctx.addIssue({ code: 'custom', message: 'Only devices support a bid adjustment below -90 percent' });\n});\nexport const intentUpdate = z.object({ campaign_id: id, criterion_id: id, intent_option: intent, expected_current_intent: intent });\n\nexport function nativeTarget(parent: Row, input: z.infer<typeof target>): Row {\n const criterion: Row = { Type: `${input.type}Criterion` };\n if (input.type === 'Age') criterion.AgeRange = input.age_range;\n if (input.type === 'Gender') criterion.GenderType = input.gender;\n if (input.type === 'Device') criterion.DeviceName = input.device_name;\n if (input.type === 'DayTime') Object.assign(criterion, { Day: input.day, FromHour: input.from_hour, FromMinute: input.from_minute, ToHour: input.to_hour, ToMinute: input.to_minute });\n if (input.type === 'Location') criterion.LocationId = input.location_id;\n if (input.type === 'LocationIntent') criterion.IntentOption = input.intent_option;\n // REST long values are decimal strings, including Radius (live-verified).\n if (input.type === 'Radius') Object.assign(criterion, { LatitudeDegrees: input.latitude, LongitudeDegrees: input.longitude, Radius: String(input.radius), RadiusUnit: input.radius_unit, ...(input.name !== undefined ? { Name: input.name } : {}) });\n const excluded = input.type === 'Location' && input.exclude;\n return { ...parent, Type: excluded ? `Negative${'AdGroupId' in parent ? 'AdGroup' : 'Campaign'}Criterion` : `Biddable${'AdGroupId' in parent ? 'AdGroup' : 'Campaign'}Criterion`, Criterion: criterion, ...(!excluded && input.type !== 'LocationIntent' ? { CriterionBid: { Type: 'BidMultiplier', Multiplier: input.bid_adjustment_percent ?? 0 } } : {}) };\n }\n","import { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst target = z.discriminatedUnion('type', [z.object({ type: z.literal('Campaign'), campaign_id: id }), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id })]);\nconst keyword = z.object({ text: z.string().min(1).max(100).refine(value => value.trim().length > 0, 'Keyword text cannot be blank'), match_type: z.enum(['Exact', 'Phrase']) });\nconst add = z.object({ target, keywords: z.array(keyword).min(1).max(1000) }).refine(value => new Set(value.keywords.map(value => JSON.stringify([value.text, value.match_type]))).size === value.keywords.length, 'Negative keywords must be unique');\nconst remove = z.object({ target, keyword_ids: z.array(id).min(1).max(1000).refine(value => new Set(value).size === value.length, 'Keyword IDs must be unique') });\ntype Target = z.infer<typeof target>;\ntype Entity = { EntityId: string; EntityType: 'Campaign' | 'AdGroup'; ParentEntityId: string | null };\nexport const MICROSOFT_NEGATIVE_KEYWORD_WRITES = new Set(['microsoft_add_negative_keywords', 'microsoft_remove_negative_keywords']);\n\n/** MicrosoftDocs/Advertising@fdee2fcf; campaign empty-list envelope also live-verified. */\nexport class MicrosoftNegativeKeywordService extends MicrosoftNativeService {\n private async entity(account: string, value: Target): Promise<Entity> {\n await this.campaign(account, value.campaign_id);\n if (value.type === 'Campaign') return { EntityId: value.campaign_id, EntityType: 'Campaign', ParentEntityId: null };\n const result = await this.request(account, 'AdGroups/QueryByIds', { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id] });\n const groups = rows(result.AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== value.ad_group_id) throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n return { EntityId: value.ad_group_id, EntityType: 'AdGroup', ParentEntityId: value.campaign_id };\n }\n\n private async query(account: string, entity: Entity) {\n const result = await this.request(account, 'NegativeKeywords/QueryByEntityIds', { EntityIds: [entity.EntityId], EntityType: entity.EntityType, ParentEntityId: entity.ParentEntityId });\n const collections = rows(result.EntityNegativeKeywords);\n if (collections.length !== 1 || nativeId(collections[0]!.EntityId) !== entity.EntityId || collections[0]!.EntityType !== entity.EntityType || !Object.hasOwn(collections[0]!, 'NegativeKeywords')) throw new AdportError('PROVIDER_ERROR', 'microsoft: negative-keyword entity identity mismatch');\n const values = rows(collections[0]!.NegativeKeywords);\n if (values.length > 20_000 || new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => !keyword.safeParse({ text: value.Text, match_type: value.MatchType }).success)) throw new AdportError('PROVIDER_ERROR', 'microsoft: invalid native negative-keyword list');\n return values;\n }\n\n async list(input: { account_id: string; target: Target; after_keyword_id?: string; limit: number }) {\n const entity = await this.entity(input.account_id, input.target), values = await this.query(input.account_id, entity);\n const remaining = values.filter(value => !input.after_keyword_id || BigInt(nativeId(value.Id)) > BigInt(input.after_keyword_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : BigInt(nativeId(a.Id)) > BigInt(nativeId(b.Id)) ? 1 : 0);\n const page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { rows: page, truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n if (op.provider !== 'microsoft' || !MICROSOFT_NEGATIVE_KEYWORD_WRITES.has(op.tool) || op.kind !== (op.tool === 'microsoft_add_negative_keywords' ? 'create' : 'remove')) throw new AdportError('INVALID_INPUT', 'microsoft: negative-keyword operation kind mismatch');\n const input = op.tool === 'microsoft_add_negative_keywords' ? add.parse(op.payload) : remove.parse(op.payload), entity = await this.entity(op.accountId, input.target), current = await this.query(op.accountId, entity);\n if ('keywords' in input) {\n const existing = new Set(current.map(value => JSON.stringify([value.Text, value.MatchType])));\n if (input.keywords.some(value => existing.has(JSON.stringify([value.text, value.match_type])))) throw new AdportError('INVALID_INPUT', 'microsoft: an exact negative-keyword entry already exists; do not replay the create operation');\n if (current.length + input.keywords.length > 20_000) throw new AdportError('INVALID_INPUT', 'microsoft: this request exceeds the native 20000 direct-negative-keyword limit');\n const values = input.keywords.map(value => ({ Text: value.text, MatchType: value.match_type }));\n return { summary: `Add ${values.length} Microsoft ${entity.EntityType} negative keyword(s)`, changes: [`+ exclusions ${JSON.stringify(values)} in ${entity.EntityType} ${entity.EntityId}`, 'Appends direct exclusions. Native negative keywords have no individual serving status; parent status is preserved. Shared and inherited exclusions are separate.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(op.accountId, 'EntityNegativeKeywords', { EntityNegativeKeywords: [{ EntityId: entity.EntityId, EntityType: entity.EntityType, NegativeKeywords: values }] });\n const groups = rows(result.NegativeKeywordIds), ids = groups.length === 1 && Array.isArray(groups[0]!.Ids) ? groups[0]!.Ids.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== values.length || new Set(ids).size !== ids.length || ids.some(id => current.some(value => nativeId(value.Id) === id))) throw new AdportError('PROVIDER_ERROR', 'microsoft: negative-keyword creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n try {\n const actual = await this.query(op.accountId, entity);\n if (ids.some((id, index) => !actual.some(value => nativeId(value.Id) === id && value.Text === values[index]!.Text && value.MatchType === values[index]!.MatchType))) throw new Error('Created exclusion was not confirmed');\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: negative keywords were accepted but content readback was not confirmed; reconcile before retrying', { resourceIds: ids }); }\n return ids;\n } };\n }\n const selected = input.keyword_ids.map(id => current.find(value => nativeId(value.Id) === id));\n if (selected.some(value => !value)) throw new AdportError('INVALID_INPUT', 'microsoft: a negative keyword was not found in the selected entity/account');\n return { summary: `Remove ${selected.length} Microsoft ${entity.EntityType} negative keyword(s)`, changes: [`- direct exclusions ${JSON.stringify(selected)}`, 'Removing exclusions can broaden delivery. Other direct, inherited and shared-list exclusions and parent serving statuses are preserved.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(op.accountId, 'EntityNegativeKeywords', { EntityNegativeKeywords: [{ EntityId: entity.EntityId, EntityType: entity.EntityType, NegativeKeywords: input.keyword_ids.map(Id => ({ Id })) }] }, 'DELETE');\n try {\n if ((await this.query(op.accountId, entity)).some(value => input.keyword_ids.includes(nativeId(value.Id)))) throw new Error('Deleted exclusion remains');\n } catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: negative-keyword removal was not confirmed; reconcile before retrying', { resourceIds: input.keyword_ids }); }\n return input.keyword_ids;\n } };\n }\n}\n\nexport function microsoftNegativeKeywordTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_negative_keywords', namespace: 'microsoft', description: 'Read direct campaign or ad-group negative keywords after verifying the full account/parent hierarchy. Shared-list and inherited exclusions are separate. Continue with next_cursor as after_keyword_id.', input: z.object({ account_id: id, target, after_keyword_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_keyword_id' }, annotations: { readOnly: true }, handler: input => provider.negativeKeywords.list(input) }),\n guardedWriteTool({ name: 'microsoft_add_negative_keywords', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Append up to 1000 direct Exact/Phrase exclusions to an owned campaign or ad group. Native negative keywords have no pause state and only restrict delivery; parent status is preserved. Verifies every created ID and its text/match type.', payload: add }),\n guardedWriteTool({ name: 'microsoft_remove_negative_keywords', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove exact owned direct exclusion IDs. This can broaden delivery. Text and match type are immutable: add and confirm a replacement before removing its predecessor. Shared and inherited exclusions are separate.', payload: remove }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, type RequestScope } from './client.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst name = z.string().min(1).max(255).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst amount = z.number().positive().refine(value => Number.isSafeInteger(Math.round(value * 1_000_000)) && Math.abs(value * 1_000_000 - Math.round(value * 1_000_000)) < 0.000001, 'Amount must fit safe integer micros with at most six decimal places');\nconst create = z.object({ name, amount });\nconst selected = z.object({ budget_id: id, expected_snapshot_hash: hash });\nconst update = selected.extend({ name: name.optional(), amount: amount.optional() }).refine(value => value.name !== undefined || value.amount !== undefined, 'Supply a name or amount');\nconst assign = z.object({ campaign_id: id, budget_id: id, expected_campaign_hash: hash, expected_budget_hash: hash });\nconst unassign = z.object({ campaign_id: id, daily_budget: amount, expected_campaign_hash: hash });\nconst budgetSchema = z.object({ Id: id, Name: z.string(), Amount: z.number().positive(), BudgetType: z.string(), AssociationCount: z.number().int().nonnegative() });\nconst memberSchema = z.object({ Id: id, Name: z.string(), Status: z.string(), CampaignType: z.string(), SubType: z.string().nullable(), ExperimentId: id.nullable() });\nconst viewSchema = z.object({ budget: budgetSchema, currency: z.string().optional(), members: z.array(memberSchema), membership_complete: z.boolean(), snapshot_hash: hash });\nconst contextSchema = z.object({ campaign: memberSchema, budget_id: id.nullable(), effective_daily_amount: z.number().positive(), budget_type: z.string(), currency: z.string().optional(), shared_budget: viewSchema.optional(), snapshot_hash: hash });\ntype Budget = z.infer<typeof budgetSchema>;\ntype Member = z.infer<typeof memberSchema>;\ntype View = z.infer<typeof viewSchema>;\ntype Context = z.infer<typeof contextSchema>;\ntype Inventory = { budgets: Budget[]; campaigns: Row[]; currency?: string };\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');\nconst micros = (value: number) => { const result = Math.round(value * 1_000_000); if (!Number.isSafeInteger(result) || result <= 0) throw new AdportError('PROVIDER_ERROR', 'microsoft: native budget amount cannot be represented safely in micros'); return result; };\nconst sharedId = (value: unknown) => value === null || value === undefined || value === '0' || value === 0 ? null : nativeId(value);\nconst member = (value: Row): Member => memberSchema.parse({ Id: nativeId(value.Id), Name: value.Name, Status: value.Status, CampaignType: value.CampaignType, SubType: value.SubType ?? null, ExperimentId: sharedId(value.ExperimentId) });\nconst order = (a: { Id: string }, b: { Id: string }) => BigInt(a.Id) < BigInt(b.Id) ? -1 : BigInt(a.Id) > BigInt(b.Id) ? 1 : 0;\nconst notes = ['Snapshot checks detect changed amounts and campaign membership before sending the write. Microsoft has no atomic compare-and-set for these operations; concurrent changes can still occur.', 'Campaign status is preserved. Shared budgets are account-scoped; the amount is one daily pool, not an amount multiplied by its campaign count.'];\n\nexport const MICROSOFT_BUDGET_WRITES = new Set(['microsoft_create_shared_budget', 'microsoft_update_shared_budget', 'microsoft_delete_shared_budget', 'microsoft_assign_shared_budget', 'microsoft_unassign_shared_budget']);\n\n/** MicrosoftDocs/Advertising@fdee2fcf, Budget and Campaign REST v13 contracts. */\nexport class MicrosoftBudgetService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string) => Promise<RequestScope>, lookupCampaign: (account: string, campaign: string) => Promise<unknown>, private readonly campaigns: (account: string) => Promise<unknown>, private readonly currency: (account: string) => Promise<string | undefined>) { super(client, scope, lookupCampaign); }\n\n private async inventory(account: string): Promise<Inventory> {\n const result = await this.request(account, 'Budgets/QueryByIds', { BudgetIds: null });\n const budgets = rows(result.Budgets).map(value => budgetSchema.parse({ ...value, Id: nativeId(value.Id) }));\n if (new Set(budgets.map(value => value.Id)).size !== budgets.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate budget IDs in native inventory');\n budgets.forEach(value => micros(value.Amount));\n const campaigns = rows(await this.campaigns(account));\n if (new Set(campaigns.map(value => nativeId(value.Id))).size !== campaigns.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate campaign IDs in native inventory');\n const currency = await this.currency(account);\n return { budgets, campaigns, ...(currency ? { currency } : {}) };\n }\n\n private view(account: string, budgetId: string, inventory: Inventory): View {\n const budget = inventory.budgets.find(value => value.Id === budgetId);\n if (!budget) throw new AdportError('INVALID_INPUT', 'microsoft: shared budget was not found in the selected account');\n const members = inventory.campaigns.filter(value => sharedId(value.BudgetId) === budgetId).map(member).sort(order);\n const value = { budget, ...(inventory.currency ? { currency: inventory.currency } : {}), members, membership_complete: members.length === budget.AssociationCount };\n return { ...value, snapshot_hash: digest({ account, ...value }) };\n }\n\n private context(account: string, campaignId: string, inventory: Inventory): Context {\n const current = inventory.campaigns.find(value => nativeId(value.Id) === campaignId);\n if (!current) throw new AdportError('INVALID_INPUT', 'microsoft: campaign was not found in the selected account');\n const campaign = member(current), budget_id = sharedId(current.BudgetId), shared_budget = budget_id ? this.view(account, budget_id, inventory) : undefined;\n // The Budget object is authoritative; a campaign's replicated DailyBudget can lag.\n const effective_daily_amount = shared_budget?.budget.Amount ?? amount.parse(current.DailyBudget);\n micros(effective_daily_amount);\n const value = { campaign, budget_id, effective_daily_amount, budget_type: z.string().parse(shared_budget?.budget.BudgetType ?? current.BudgetType), ...(inventory.currency ? { currency: inventory.currency } : {}), ...(shared_budget ? { shared_budget } : {}) };\n return { ...value, snapshot_hash: digest({ account, ...value }) };\n }\n\n async list(input: { account_id: string; after_budget_id?: string; limit: number }) {\n const inventory = await this.inventory(input.account_id), remaining = inventory.budgets.filter(value => !input.after_budget_id || BigInt(value.Id) > BigInt(input.after_budget_id)).sort(order), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { rows: page.map(value => this.view(input.account_id, value.Id, inventory)), truncated, ...(truncated ? { next_cursor: page.at(-1)!.Id } : {}) };\n }\n\n async get(account: string, budgetId: string): Promise<View> { id.parse(budgetId); return this.view(account, budgetId, await this.inventory(account)); }\n async campaignBudget(account: string, campaignId: string): Promise<Context> { id.parse(campaignId); return this.context(account, campaignId, await this.inventory(account)); }\n\n private complete(value: View): void {\n if (!value.membership_complete) throw new AdportError('INVALID_INPUT', 'microsoft: campaign membership does not match native AssociationCount; refresh and reconcile all campaign types before writing');\n if (value.budget.BudgetType !== 'DailyBudgetStandard') throw new AdportError('INVALID_INPUT', 'microsoft: only native DailyBudgetStandard shared budgets can be changed');\n }\n\n private expected(actual: string, expected: string): void {\n if (actual !== expected) throw new AdportError('INVALID_INPUT', 'microsoft: budget or campaign snapshot changed; read fresh context and request a new preview');\n }\n\n private eligible(value: Member): void {\n if (value.CampaignType === 'PerformanceMax' || value.SubType === 'ShoppingSmartAds' || value.ExperimentId) throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max, Smart Shopping and experiment campaigns cannot be assigned or directly detached with shared-budget tools');\n if (!['Active', 'Paused', 'BudgetPaused'].includes(value.Status)) throw new AdportError('INVALID_INPUT', 'microsoft: campaign serving status is not recognized for a budget change');\n }\n\n private async verify(account: string, ids: string[], test: (inventory: Inventory) => boolean): Promise<string[]> {\n try { if (!test(await this.inventory(account))) throw new Error('Native readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: budget write was accepted but readback was not confirmed; reconcile these resource IDs before retrying', { resourceIds: ids }); }\n return ids;\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n const kinds = { microsoft_create_shared_budget: 'create', microsoft_update_shared_budget: 'update', microsoft_delete_shared_budget: 'remove', microsoft_assign_shared_budget: 'update', microsoft_unassign_shared_budget: 'update' } as const;\n if (op.provider !== 'microsoft' || !MICROSOFT_BUDGET_WRITES.has(op.tool) || op.kind !== kinds[op.tool as keyof typeof kinds]) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget operation kind mismatch');\n const input = op.tool === 'microsoft_create_shared_budget' ? create.parse(op.payload) : op.tool === 'microsoft_update_shared_budget' ? update.parse(op.payload) : op.tool === 'microsoft_delete_shared_budget' ? selected.parse(op.payload) : op.tool === 'microsoft_assign_shared_budget' ? assign.parse(op.payload) : unassign.parse(op.payload);\n const account = op.accountId, inventory = await this.inventory(account);\n const delta = (target: string, from: number, to: number) => ({ target, ...(inventory.currency ? { currency: inventory.currency } : {}), fromMicros: from === 0 ? 0 : micros(from), toMicros: micros(to) });\n const unique = (value: string, except?: string) => { if (inventory.budgets.some(budget => budget.Id !== except && budget.Name.toLowerCase() === value.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget name already exists in this account'); };\n if (op.tool === 'microsoft_create_shared_budget' && 'name' in input && 'amount' in input) {\n const value = create.parse(input); unique(value.name);\n return { summary: `Create Microsoft shared daily budget \"${value.name}\"`, changes: [`+ unattached shared budget ${JSON.stringify(value)}`, 'No campaigns are assigned by this operation.'], fieldChanges: [{ field: 'Name', before: '(new)', after: value.name }], notes, coercions: [], budgetDeltas: [delta(`new shared budget \"${value.name}\" daily pool`, 0, value.amount)], execute: async () => {\n const result = await this.request(account, 'Budgets', { Budgets: [{ Name: value.name, Amount: value.amount, BudgetType: 'DailyBudgetStandard' }] });\n const ids = Array.isArray(result.BudgetIds) ? result.BudgetIds.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1 || inventory.budgets.some(value => value.Id === ids[0])) throw new AdportError('PROVIDER_ERROR', 'microsoft: budget creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.verify(account, ids, actual => { const view = this.view(account, ids[0]!, actual); return view.budget.Name === value.name && view.budget.Amount === value.amount && view.budget.BudgetType === 'DailyBudgetStandard' && view.membership_complete && !view.members.length; });\n } };\n }\n if (op.tool === 'microsoft_update_shared_budget' || op.tool === 'microsoft_delete_shared_budget') {\n const value = selected.parse(input), current = this.view(account, value.budget_id, inventory);\n this.complete(current); this.expected(current.snapshot_hash, value.expected_snapshot_hash);\n if (op.tool === 'microsoft_delete_shared_budget') {\n if (current.members.length) throw new AdportError('INVALID_INPUT', 'microsoft: detach all campaigns before deleting a shared budget');\n return { summary: `Delete unused Microsoft shared budget \"${current.budget.Name}\"`, changes: [`- shared budget ${current.budget.Id}; native AssociationCount and discovered membership are both zero`], notes, coercions: [], budgetDeltas: [], execute: async () => { await this.request(account, 'Budgets', { BudgetIds: [current.budget.Id] }, 'DELETE'); return this.verify(account, [current.budget.Id], actual => !actual.budgets.some(value => value.Id === current.budget.Id)); } };\n }\n const edit = update.parse(input); if (edit.name !== undefined) unique(edit.name, current.budget.Id);\n const fields = { ...(edit.name !== undefined && edit.name !== current.budget.Name ? { Name: edit.name } : {}), ...(edit.amount !== undefined && edit.amount !== current.budget.Amount ? { Amount: edit.amount } : {}) };\n if (!Object.keys(fields).length) throw new AdportError('INVALID_INPUT', 'microsoft: shared-budget update has no changes');\n const fieldChanges = Object.entries(fields).map(([field, after]) => ({ field, before: String(current.budget[field as keyof Budget]), after: String(after) }));\n return { summary: `Update Microsoft shared budget \"${current.budget.Name}\" (${current.members.length} campaign(s))`, changes: [`~ shared budget ${current.budget.Id} ${JSON.stringify(fields)}`, `Affected campaigns: ${JSON.stringify(current.members)}`], fieldChanges, notes: [...notes, `Affected campaigns: ${current.members.map(value => `${value.Id} ${value.Name} (${value.Status})`).join('; ') || '(none)'}`], coercions: [], budgetDeltas: fields.Amount !== undefined ? [delta(`shared budget ${current.budget.Id} daily pool`, current.budget.Amount, fields.Amount)] : [], execute: async () => { await this.request(account, 'Budgets', { Budgets: [{ Id: current.budget.Id, ...fields }] }, 'PUT'); return this.verify(account, [current.budget.Id], actual => { const after = this.view(account, current.budget.Id, actual); return after.membership_complete && JSON.stringify(after.members) === JSON.stringify(current.members) && Object.entries(fields).every(([key, value]) => after.budget[key as keyof Budget] === value); }); } };\n }\n if (op.tool === 'microsoft_assign_shared_budget') {\n const value = assign.parse(input), current = this.context(account, value.campaign_id, inventory), destination = this.view(account, value.budget_id, inventory);\n this.eligible(current.campaign); this.complete(destination); if (current.shared_budget) this.complete(current.shared_budget);\n this.expected(current.snapshot_hash, value.expected_campaign_hash); this.expected(destination.snapshot_hash, value.expected_budget_hash);\n if (current.budget_id === value.budget_id) throw new AdportError('INVALID_INPUT', 'microsoft: campaign already uses this shared budget');\n return { summary: `Assign Microsoft campaign \"${current.campaign.Name}\" to shared budget \"${destination.budget.Name}\"`, changes: [`~ campaign ${value.campaign_id} BudgetId ${current.budget_id ?? '(individual)'} → ${value.budget_id}`, `Source members before assignment: ${JSON.stringify(current.shared_budget?.members ?? [current.campaign])}`, `Destination members before assignment: ${JSON.stringify(destination.members)}`, 'Policy compares the campaign’s current effective daily limit with the destination pool amount. Pool membership changes can redistribute spend among its campaigns.'], fieldChanges: [{ field: 'Budget', before: current.budget_id ?? '(individual)', after: value.budget_id }], notes: [...notes, `Source campaigns: ${(current.shared_budget?.members ?? [current.campaign]).map(value => `${value.Id} ${value.Name} (${value.Status})`).join('; ')}`, `Destination campaigns: ${destination.members.map(value => `${value.Id} ${value.Name} (${value.Status})`).join('; ') || '(none)'}`], coercions: [], budgetDeltas: [delta(`campaign ${value.campaign_id} effective daily budget`, current.effective_daily_amount, destination.budget.Amount)], execute: async () => {\n await this.request(account, 'Campaigns', { AccountId: account, Campaigns: [{ Id: value.campaign_id, BudgetId: value.budget_id }] }, 'PUT');\n return this.verify(account, [value.campaign_id, value.budget_id], actual => { const after = this.context(account, value.campaign_id, actual), target = this.view(account, value.budget_id, actual); return after.budget_id === value.budget_id && after.campaign.Status === current.campaign.Status && target.membership_complete && target.budget.Amount === destination.budget.Amount && JSON.stringify(target.members) === JSON.stringify([...destination.members, current.campaign].sort(order)) && (!current.budget_id || this.view(account, current.budget_id, actual).membership_complete); });\n } };\n }\n const value = unassign.parse(input), current = this.context(account, value.campaign_id, inventory);\n this.eligible(current.campaign); this.expected(current.snapshot_hash, value.expected_campaign_hash);\n if (!current.shared_budget) throw new AdportError('INVALID_INPUT', 'microsoft: campaign is not using a shared budget');\n this.complete(current.shared_budget);\n return { summary: `Detach Microsoft campaign \"${current.campaign.Name}\" to its own daily budget`, changes: [`~ campaign ${value.campaign_id} BudgetId ${current.budget_id} → 0; DailyBudget → ${value.daily_budget}; BudgetType → DailyBudgetStandard`, 'The remaining shared pool amount is preserved. Detaching adds an independent daily allocation alongside that pool.'], fieldChanges: [{ field: 'Budget', before: current.budget_id!, after: '(individual DailyBudgetStandard)' }], notes, coercions: [], budgetDeltas: [delta(`campaign ${value.campaign_id} effective daily budget`, current.effective_daily_amount, value.daily_budget)], execute: async () => {\n // Clearing BudgetId starts an individual budget: native REST also requires its type (1121 if omitted).\n await this.request(account, 'Campaigns', { AccountId: account, Campaigns: [{ Id: value.campaign_id, BudgetId: '0', DailyBudget: value.daily_budget, BudgetType: 'DailyBudgetStandard' }] }, 'PUT');\n return this.verify(account, [value.campaign_id, current.budget_id!], actual => { const after = this.context(account, value.campaign_id, actual), previous = this.view(account, current.budget_id!, actual); return after.budget_id === null && after.effective_daily_amount === value.daily_budget && after.campaign.Status === current.campaign.Status && previous.membership_complete && previous.budget.Amount === current.shared_budget!.budget.Amount && JSON.stringify(previous.members) === JSON.stringify(current.shared_budget!.members.filter(value => value.Id !== current.campaign.Id)); });\n } };\n }\n}\n\nexport function microsoftBudgetTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_shared_budgets', namespace: 'microsoft', description: 'List native daily pools with all-type campaign membership, completeness and snapshot hashes. Continue next_cursor as after_budget_id.', input: z.object({ account_id: id, after_budget_id: id.optional(), limit: z.number().int().positive().max(100).default(50) }), output: z.object({ rows: z.array(viewSchema), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_budget_id' }, annotations: { readOnly: true }, handler: input => provider.budgets.list(input) }),\n defineTool({ name: 'microsoft_get_shared_budget', namespace: 'microsoft', description: 'Read an owned daily pool, its campaign members and snapshot_hash for update, assignment or deletion. Writes reject incomplete membership.', input: z.object({ account_id: id, budget_id: id }), output: viewSchema, annotations: { readOnly: true }, handler: input => provider.budgets.get(input.account_id, input.budget_id) }),\n defineTool({ name: 'microsoft_campaign_budget', namespace: 'microsoft', description: 'Read an owned campaign’s effective daily limit, individual/shared budget, members and snapshot_hash. Use this hash as expected_campaign_hash when assigning or detaching.', input: z.object({ account_id: id, campaign_id: id }), output: contextSchema, annotations: { readOnly: true }, handler: input => provider.budgets.campaignBudget(input.account_id, input.campaign_id) }),\n guardedWriteTool({ name: 'microsoft_create_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create an unattached DailyBudgetStandard pool in account currency. Checks its amount in policy micros. Does not assign or activate campaigns.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Rename or change one shared daily pool after binding its amount and all campaign members/statuses with expected_snapshot_hash. Monetary caps apply once to the pool; no atomic native compare-and-set.', payload: update }),\n guardedWriteTool({ name: 'microsoft_delete_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', destructive: true, description: 'Permanently delete an owned unused shared budget. Requires matching snapshot and both native and discovered campaign counts zero; verifies disappearance.', payload: selected }),\n guardedWriteTool({ name: 'microsoft_assign_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Assign a campaign to an owned daily pool using campaign and destination snapshot hashes. Compares current effective limit with the pool amount for policy; preserves status. Excludes Performance Max, Smart Shopping and experiments.', payload: assign }),\n guardedWriteTool({ name: 'microsoft_unassign_shared_budget', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Detach to an explicit individual DailyBudgetStandard budget in account currency. Requires campaign snapshot, preserves status and remaining pool amount, and checks monetary policy. Excludes experiment campaigns.', payload: unassign }),\n ];\n}\n","import { AdportError, defineTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftAdsClient, type RequestScope } from './client.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftRows as rows, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst text = z.string().min(1).max(100).refine(value => value.trim().length > 0, 'Keyword cannot be blank');\nconst keywords = z.array(text).min(1).max(200);\nconst date = z.iso.date();\nconst dateRange = z.object({ start: date, end: date }).refine(value => value.start <= value.end, 'Start date must not follow end date');\nconst targeting = z.object({ account_id: id, language: z.enum(['English', 'French', 'German']), location_ids: z.array(id).min(1).max(2000).refine(value => new Set(value).size === value.length, 'Location IDs must be unique'), network: z.enum(['OwnedAndOperatedAndSyndicatedSearch', 'OwnedAndOperatedOnly']).default('OwnedAndOperatedAndSyndicatedSearch') });\nconst baseIdeas = targeting.extend({ date_range: dateRange.optional(), limit: z.number().int().positive().max(3000).default(100) });\nconst ideas = baseIdeas.extend({ keywords: keywords.optional(), url: z.url().refine(value => { const url = new URL(value); return url.protocol === 'https:' && !url.username && !url.password; }, 'Use an HTTPS URL without credentials').optional(), category_id: id.optional() }).refine(value => value.keywords !== undefined || value.url !== undefined || value.category_id !== undefined, 'Supply keyword, URL or category seeds');\nconst historical = baseIdeas.extend({ keywords });\nconst traffic = targeting.extend({ keywords: z.array(z.object({ text, match_type: z.enum(['Phrase', 'Broad']), max_cpc: z.number().positive().optional() })).min(1).max(1000), max_cpc: z.number().positive(), daily_budget: z.number().positive().optional(), negative_keywords: z.array(z.object({ text, match_type: z.enum(['Exact', 'Phrase']) })).max(1000).optional() });\nconst ideasOutput = z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean(), returned_count: z.number().int().nonnegative(), native_result_count: z.number().int().nonnegative(), currency: z.string().optional(), date_range: dateRange.optional(), notes: z.array(z.string()) });\nconst parts = (value: string) => { const [Year, Month, Day] = value.split('-').map(Number); return { Year, Month, Day }; };\nfunction criteria(input: z.infer<typeof targeting>): Row[] {\n return [{ Type: 'LanguageCriterion', Language: input.language }, { Type: 'NetworkCriterion', Network: input.network }, ...input.location_ids.map(LocationId => ({ Type: 'LocationCriterion', LocationId }))];\n}\n\n/** Ad Insight REST v13 shapes from MicrosoftDocs/Advertising@fdee2fcf. */\nexport class MicrosoftPlanningService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string) => Promise<RequestScope>, lookupCampaign: (account: string, campaign: string) => Promise<unknown>, private readonly currency: (account: string) => string | undefined) { super(client, scope, lookupCampaign); }\n async keywordIdeas(input: z.infer<typeof ideas> | z.infer<typeof historical>, expand: boolean) {\n const value = expand ? ideas.parse(input) : historical.parse(input);\n const parameters: Row[] = [{ Type: 'LanguageSearchParameter', Languages: [{ Type: 'LanguageCriterion', Language: value.language }] }, { Type: 'LocationSearchParameter', Locations: value.location_ids.map(LocationId => ({ Type: 'LocationCriterion', LocationId })) }, { Type: 'NetworkSearchParameter', Network: { Type: 'NetworkCriterion', Network: value.network } }];\n if (value.keywords) parameters.push({ Type: 'QuerySearchParameter', Queries: value.keywords });\n if ('url' in value && value.url) parameters.push({ Type: 'UrlSearchParameter', Url: value.url });\n if ('category_id' in value && value.category_id) parameters.push({ Type: 'CategorySearchParameter', CategoryId: value.category_id });\n if (value.date_range) parameters.push({ Type: 'DateRangeSearchParameter', StartDate: parts(value.date_range.start), EndDate: parts(value.date_range.end) });\n const result = await this.request(value.account_id, 'KeywordIdeas/Query', { ExpandIdeas: expand, IdeaAttributes: ['Keyword', 'Competition', 'MonthlySearchCounts', 'SuggestedBid', 'AdImpressionShare', 'Relevance', 'Source', 'AdGroupId', 'AdGroupName'], SearchParameters: parameters }, 'POST', 'adinsight');\n if (!Object.hasOwn(result, 'KeywordIdeas')) throw new AdportError('PROVIDER_ERROR', 'microsoft: keyword-idea response did not contain the native result envelope');\n const values = rows(result.KeywordIdeas);\n const currency = this.currency(value.account_id);\n const page = values.slice(0, value.limit);\n return { rows: page, truncated: values.length > page.length, returned_count: page.length, native_result_count: values.length, ...(currency ? { currency } : {}), ...(value.date_range ? { date_range: value.date_range } : {}), notes: ['returned_count is the number of rows displayed here. native_result_count is the native response size before the requested limit. Native results are currently capped at 3000 with no continuation cursor; neither count proves the full search universe.', 'MonthlySearchCounts is newest-first. Without an explicit date range, its exact calendar months cannot be identified; the latest month may lag by up to 72 hours.', 'Suggested bids are estimates in account currency, not observed campaign performance. Missing native metrics remain missing; native numeric zero is preserved without inferring availability.', 'Negative AdGroupId values identify suggested planning groups; they are not existing campaign ad-group IDs.'] };\n }\n\n async trafficEstimates(input: z.infer<typeof traffic>) {\n const value = traffic.parse(input);\n const estimator = { AdGroupEstimators: [{ KeywordEstimators: value.keywords.map(value => ({ Keyword: { Text: value.text, MatchType: value.match_type }, ...(value.max_cpc !== undefined ? { MaxCpc: value.max_cpc } : {}) })), MaxCpc: value.max_cpc }], Criteria: criteria(value), ...(value.daily_budget !== undefined ? { DailyBudget: value.daily_budget } : {}), ...(value.negative_keywords !== undefined ? { NegativeKeywords: value.negative_keywords.map(value => ({ Text: value.text, MatchType: value.match_type })) } : {}) };\n const result = await this.request(value.account_id, 'KeywordTrafficEstimates/Query', { CampaignEstimators: [estimator] }, 'POST', 'adinsight');\n if (!Object.hasOwn(result, 'CampaignEstimates')) throw new AdportError('PROVIDER_ERROR', 'microsoft: traffic-estimate response did not contain the native result envelope');\n const currency = this.currency(value.account_id);\n return { rows: rows(result.CampaignEstimates), estimate_period: 'week' as const, deprecated_metrics: ['AveragePosition'], ...(currency ? { currency } : {}), notes: ['Clicks, impressions and total cost are estimated per week. The optional DailyBudget input is a daily filter, not the estimate period.', 'AveragePosition is deprecated and native values have been fixed at zero since 2021-03-31; it is not a valid position estimate.', 'These are hypothetical traffic estimates in account currency, not a forecast guarantee or observed performance. No campaigns, ads or keywords are created or edited.', 'CampaignId and AdGroupId are reserved by this API and are intentionally omitted. Only Phrase and Broad keyword estimates are supported.'] };\n }\n}\n\nexport function microsoftPlanningTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_keyword_ideas', namespace: 'microsoft', description: 'Read Ad Insight keyword ideas from keyword, HTTPS URL or native category seeds. Requires language and location IDs; suggested bids use account currency. Native cap 3000, no pagination; monthly counts newest-first and undated unless date_range supplied.', input: ideas, output: ideasOutput, annotations: { readOnly: true }, handler: input => provider.planning.keywordIdeas(input, true) }),\n defineTool({ name: 'microsoft_keyword_historical_metrics', namespace: 'microsoft', description: 'Read native keyword attributes without expanding seeds: demand history, competition and estimated bids. Monthly counts newest-first; missing values remain unavailable. Exact month labels require explicit date_range.', input: historical, output: ideasOutput, annotations: { readOnly: true }, handler: input => provider.planning.keywordIdeas(input, false) }),\n defineTool({ name: 'microsoft_keyword_traffic_estimates', namespace: 'microsoft', description: 'Estimate hypothetical weekly Phrase/Broad keyword traffic from bids, language, locations and network, optionally daily budget and exclusions. Read-only; no campaign changes. Cost/bids use account currency. AveragePosition is deprecated and always zero.', input: traffic, output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), estimate_period: z.literal('week'), deprecated_metrics: z.array(z.string()), currency: z.string().optional(), notes: z.array(z.string()) }), annotations: { readOnly: true }, handler: input => provider.planning.trafficEstimates(input) }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst goalType = z.enum(['AppDownload', 'AppInstall', 'Duration', 'Event', 'InStoreTransaction', 'OfflineConversion', 'PagesViewedPerVisit', 'Url']);\nconst supportedType = z.enum(['Url', 'Event', 'OfflineConversion']);\nconst standardTypes = ['AppDownload', 'AppInstall', 'Duration', 'Event', 'OfflineConversion', 'PagesViewedPerVisit', 'Url'] as const;\nconst name = z.string().min(1).max(100).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst category = z.enum(['AddToCart', 'BeginCheckout', 'BookAppointment', 'Contact', 'GetDirections', 'Other', 'OutboundClick', 'PageView', 'Purchase', 'RequestQuote', 'Signup', 'SubmitLeadForm', 'Subscribe']);\nconst expression = z.object({ operator: z.enum(['BeginsWith', 'Contains', 'Equals', 'RegularExpression']), text: z.string().min(1).max(100) });\nconst event = z.object({ action: expression.optional(), category: expression.optional(), label: expression.optional(), value: z.object({ operator: z.enum(['Equals', 'GreaterThan', 'LessThan']), amount: z.number() }).optional() }).refine(value => Object.values(value).some(value => value !== undefined), 'At least one complete event condition is required');\nconst url = z.object({ operator: expression.shape.operator, expression: z.string().min(1).max(1000) });\nconst revenue = z.discriminatedUnion('type', [z.object({ type: z.literal('NoValue') }), z.object({ type: z.literal('FixedValue'), value: z.number().nonnegative(), currency: z.string().regex(/^[A-Z]{3}$/).optional() }), z.object({ type: z.literal('VariableValue'), value: z.number().nonnegative().optional(), currency: z.string().regex(/^[A-Z]{3}$/).optional() })]);\nconst common = z.object({ name, goal_category: category, status: z.enum(['Active', 'Paused']).default('Paused'), exclude_from_bidding: z.boolean().default(true), count_type: z.enum(['All', 'Unique']).default('All'), conversion_window_minutes: z.number().int().min(1).max(129600).default(43200), revenue: revenue.default({ type: 'NoValue' }), enhanced_conversions_enabled: z.boolean().optional().describe('IsEnhancedConversionsEnabled; Microsoft accepts true only once one goal in the account has it enabled in the web UI'), expected_auto_tagging_enabled: z.boolean() });\nconst create = z.object({ goal: z.discriminatedUnion('type', [common.extend({ type: z.literal('OfflineConversion'), is_externally_attributed: z.boolean().default(false) }), common.extend({ type: z.literal('Url'), tag_id: id, url_rule: url }), common.extend({ type: z.literal('Event'), tag_id: id, event_conditions: event })]) });\nconst update = z.object({ goal_id: id, goal_type: supportedType, expected_snapshot_hash: z.string().regex(/^[a-f0-9]{64}$/), name: name.optional(), goal_category: category.optional(), status: z.enum(['Active', 'Paused']).optional(), exclude_from_bidding: z.boolean().optional(), count_type: z.enum(['All', 'Unique']).optional(), conversion_window_minutes: z.number().int().min(1).max(129600).optional(), revenue: revenue.optional(), enhanced_conversions_enabled: z.boolean().optional().describe('IsEnhancedConversionsEnabled; Microsoft accepts true only once one goal in the account has it enabled in the web UI'), is_externally_attributed: z.boolean().optional(), url_rule: url.optional(), event_conditions: event.optional() }).refine(value => Object.entries(value).some(([key, value]) => !['goal_id', 'goal_type', 'expected_snapshot_hash'].includes(key) && value !== undefined), 'Supply an editable field');\nconst createTag = z.object({ name, description: z.string().min(1).max(1000).optional(), expected_customer_id: id.describe('native_customer_id from microsoft_linked_uet_tags') });\nconst view = z.object({ account_id: id, goal: z.record(z.string(), z.unknown()), auto_tagging_enabled: z.boolean().describe('MSCLKIDAutoTaggingEnabled on the selected account, separate from the goal Scope'), auto_tagging_scope: z.literal('Account'), snapshot_hash: z.string().regex(/^[a-f0-9]{64}$/) });\nconst additional = 'GoalCategory, IsExternallyAttributed, IsAutoGoal, IsEnhancedConversionsEnabled, ViewThroughConversionWindowInMinutes, AttributionModelType, ApplicationDownloadGoal';\nconst pairs = [['ActionExpression', 'ActionOperator', 'action'], ['CategoryExpression', 'CategoryOperator', 'category'], ['LabelExpression', 'LabelOperator', 'label'], ['Value', 'ValueOperator', 'value']] as const;\nconst notes = ['Microsoft automatically enables MSCLKIDAutoTaggingEnabled when adding or updating this goal, including paused goals. This tool does not install a UET tag or send conversion events.', 'Account scope is fixed. Native Deleted status is internal-only; no permanent goal-deletion operation is exposed. Use Paused to stop tracking.', 'Goal snapshots detect changed configuration before submission; Microsoft provides no atomic compare-and-set. Conversion settings can affect reporting and automated bidding.', 'Enhanced conversions match hashed customer data sent with UET or offline conversions. Microsoft rejects IsEnhancedConversionsEnabled=true until one goal in the account has it enabled in the web UI.'];\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nconst wireRevenue = (value: z.infer<typeof revenue>) => ({ Type: value.type, ...('value' in value && value.value !== undefined ? { Value: value.value } : {}), ...('currency' in value && value.currency ? { CurrencyCode: value.currency } : {}) });\nfunction eventFields(value: z.infer<typeof event>): Row {\n const fields: Row = {};\n for (const [field, operator, key] of pairs) { const condition = value[key]; fields[field] = condition ? 'text' in condition ? condition.text : condition.amount : null; fields[operator] = condition?.operator ?? null; }\n return fields;\n}\nfunction matches(actual: Row, fields: Row): boolean {\n return Object.entries(fields).every(([key, value]) => value === null ? actual[key] === null || actual[key] === undefined : value && typeof value === 'object' && !Array.isArray(value) ? actual[key] && typeof actual[key] === 'object' && matches(actual[key] as Row, value as Row) : String(actual[key]) === String(value));\n}\nexport const MICROSOFT_CONVERSION_WRITES = new Set(['microsoft_create_conversion_goal', 'microsoft_update_conversion_goal', 'microsoft_create_uet_tag']);\n\n/** Campaign Management v13; EventGoal omissions delete criteria, unlike ordinary optional update fields. */\nexport class MicrosoftConversionService extends MicrosoftNativeService {\n private async autoTagging(account: string): Promise<boolean> {\n const result = await this.request(account, 'AccountProperties/Query', { AccountPropertyNames: ['MSCLKIDAutoTaggingEnabled'] });\n const properties = rows(result.AccountProperties).filter(value => value.Name === 'MSCLKIDAutoTaggingEnabled');\n if (properties.length !== 1 || !['true', 'false'].includes(String(properties[0]!.Value))) throw new AdportError('PROVIDER_ERROR', 'microsoft: native click-ID auto-tagging state is unavailable');\n return String(properties[0]!.Value) === 'true';\n }\n\n private async query(account: string, types: z.infer<typeof goalType>[]): Promise<Row[]> {\n const result = await this.request(account, 'ConversionGoals/QueryByIds', { ConversionGoalIds: null, ConversionGoalTypes: types.join(', '), ReturnAdditionalFields: additional });\n if (!Object.hasOwn(result, 'ConversionGoals')) throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion goals response envelope is missing');\n const values = rows(result.ConversionGoals);\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => !types.includes(goalType.parse(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion-goal native identities or types mismatch');\n return values;\n }\n\n private snapshot(account: string, goal: Row, enabled: boolean) {\n const { TrackingStatus: _tracking, ...configuration } = goal;\n return { account_id: account, goal, auto_tagging_enabled: enabled, auto_tagging_scope: 'Account' as const, snapshot_hash: createHash('sha256').update(JSON.stringify(canonical({ account, configuration, enabled }))).digest('hex') };\n }\n\n async list(input: { account_id: string; goal_types: z.infer<typeof goalType>[]; after_goal_id?: string; limit: number }) {\n const values = await this.query(input.account_id, input.goal_types), enabled = await this.autoTagging(input.account_id), remaining = values.filter(value => !input.after_goal_id || BigInt(nativeId(value.Id)) > BigInt(input.after_goal_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { account_id: input.account_id, rows: page.map(value => this.snapshot(input.account_id, value, enabled)), auto_tagging_enabled: enabled, auto_tagging_scope: 'Account' as const, truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n async get(account: string, goalId: string, type: z.infer<typeof goalType>) {\n id.parse(goalId); const values = await this.query(account, [type]), enabled = await this.autoTagging(account), current = values.find(value => nativeId(value.Id) === goalId);\n if (!current) throw new AdportError('INVALID_INPUT', 'microsoft: conversion goal was not found for the selected account/type');\n return this.snapshot(account, current, enabled);\n }\n\n async linkedTags(input: { account_id: string; after_tag_id?: string; limit: number }) {\n const scope = await this.accountScope(input.account_id, true);\n const goals = await this.query(input.account_id, [...standardTypes]), links = new Map<string, string[]>();\n for (const goal of goals) {\n if (goal.TagId === null || goal.TagId === undefined || goal.TagId === '0' || goal.TagId === 0) continue;\n const tag = nativeId(goal.TagId); links.set(tag, [...(links.get(tag) ?? []), nativeId(goal.Id)]);\n }\n const ids = [...links.keys()].filter(value => !input.after_tag_id || BigInt(value) > BigInt(input.after_tag_id)).sort((a, b) => BigInt(a) < BigInt(b) ? -1 : 1), page = ids.slice(0, input.limit), truncated = ids.length > page.length;\n if (!page.length) return { native_customer_id: scope.customerId!, rows: [], truncated: false };\n const result = await this.request(input.account_id, 'UetTags/QueryByIds', { TagIds: page }), tags = rows(result.UetTags);\n if (tags.length !== page.length || new Set(tags.map(value => nativeId(value.Id))).size !== page.length || tags.some(value => !page.includes(nativeId(value.Id)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: linked UET tag readback does not match the selected account’s goal references');\n // CustomerShare is a customer-wide graph; this account-linked view exposes installation metadata only.\n return { native_customer_id: scope.customerId!, rows: tags.sort((a, b) => page.indexOf(nativeId(a.Id)) - page.indexOf(nativeId(b.Id))).map(tag => ({ tag: { ...Object.fromEntries(['Name', 'Description', 'TrackingStatus', 'TrackingScript', 'TrackingNoScript'].filter(key => Object.hasOwn(tag, key)).map(key => [key, tag[key]])), Id: nativeId(tag.Id) }, goal_ids: links.get(nativeId(tag.Id))!, native_scope: 'Customer' as const })), truncated, ...(truncated ? { next_cursor: page.at(-1)! } : {}) };\n }\n\n private async tag(account: string, tagId: string): Promise<void> {\n const result = await this.request(account, 'UetTags/QueryByIds', { TagIds: [tagId] });\n const values = rows(result.UetTags);\n if (values.length !== 1 || nativeId(values[0]!.Id) !== tagId) throw new AdportError('INVALID_INPUT', 'microsoft: UET tag is unavailable in the selected native customer/account context');\n }\n\n private async verify(account: string, goalId: string, type: z.infer<typeof supportedType>, expected: Row): Promise<string[]> {\n try { const current = await this.get(account, goalId, type); if (current.goal.Scope !== 'Account' || !current.auto_tagging_enabled || !matches(current.goal, expected)) throw new Error('Goal readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion-goal write was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: [goalId] }); }\n return [goalId];\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n if (op.provider !== 'microsoft' || !MICROSOFT_CONVERSION_WRITES.has(op.tool) || op.kind !== (op.tool === 'microsoft_update_conversion_goal' ? 'update' : 'create')) throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_create_uet_tag') {\n // AddUetTags is customer-scoped: re-resolve parent ownership, even in a long-lived stdio runtime.\n const value = createTag.parse(op.payload), scope = await this.accountScope(account, true), fields = { Name: value.name, ...(value.description ? { Description: value.description } : {}) };\n if (scope.customerId !== value.expected_customer_id) throw new AdportError('INVALID_INPUT', 'microsoft: parent customer changed; read fresh linked-tag context and request a new preview');\n return { summary: `Create Microsoft UET tag \"${value.name}\"`, changes: [`+ uninstalled UET tag in native customer ${scope.customerId} library ${JSON.stringify(fields)}`], fieldChanges: [{ field: 'Name', before: '(new)', after: value.name }, { field: 'Resource scope', before: '(new)', after: 'Customer' }], notes: [`UET tags belong to native customer ${scope.customerId}'s shared library. The new tag is uninstalled and creates no serving campaign, tracking event or account-share update.`, 'Native tags have no pause state. Associate its ID with a paused account-scoped conversion goal, then use microsoft_linked_uet_tags to read its tracking code. Installation is a separate action.', 'This tool creates a new tag only. Customer-wide tag edits, sharing and permanent deletion are not exposed.'], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(account, 'UetTags', { UetTags: [fields] }), created = rows(result.UetTags), ids = created.map(value => nativeId(value.Id));\n if (created.length !== 1 || !matches(created[0]!, fields)) throw new AdportError('PROVIDER_ERROR', 'microsoft: UET creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n try { const actual = rows((await this.request(account, 'UetTags/QueryByIds', { TagIds: ids })).UetTags); if (actual.length !== 1 || nativeId(actual[0]!.Id) !== ids[0] || !matches(actual[0]!, fields)) throw new Error('UET readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: UET tag was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: ids }); }\n return ids;\n } };\n }\n if (op.tool === 'microsoft_create_conversion_goal') {\n const value = create.parse(op.payload).goal, enabled = await this.autoTagging(account);\n if (value.expected_auto_tagging_enabled !== enabled) throw new AdportError('INVALID_INPUT', 'microsoft: auto-tagging state changed; read fresh conversion context before previewing');\n const existing = await this.query(account, [...standardTypes]);\n if (existing.some(goal => typeof goal.Name === 'string' && goal.Name.toLowerCase() === value.name.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: conversion goal name already exists; do not replay creation');\n if ('tag_id' in value) await this.tag(account, value.tag_id);\n const status = guard.forcePausedCreation ? 'Paused' : value.status;\n const fields: Row = { Type: value.type, Scope: 'Account', Name: value.name, Status: status, GoalCategory: value.goal_category, ExcludeFromBidding: value.exclude_from_bidding, CountType: value.count_type, ConversionWindowInMinutes: value.conversion_window_minutes, Revenue: wireRevenue(value.revenue), ...(value.enhanced_conversions_enabled !== undefined ? { IsEnhancedConversionsEnabled: value.enhanced_conversions_enabled } : {}), ...(value.type === 'OfflineConversion' ? { IsExternallyAttributed: value.is_externally_attributed } : { TagId: value.tag_id }), ...(value.type === 'Url' ? { UrlExpression: value.url_rule.expression, UrlOperator: value.url_rule.operator } : value.type === 'Event' ? eventFields(value.event_conditions) : {}) };\n return { summary: `Create Microsoft ${value.type} goal \"${value.name}\"`, changes: [`+ account-scoped conversion goal ${JSON.stringify(fields)}`, `MSCLKIDAutoTaggingEnabled ${enabled} → true (native side effect)`], fieldChanges: [{ field: 'Name', before: '(new)', after: value.name }, { field: 'Status', before: '(new)', after: status }, ...(value.enhanced_conversions_enabled !== undefined ? [{ field: 'IsEnhancedConversionsEnabled', before: '(new)', after: String(value.enhanced_conversions_enabled) }] : []), { field: 'MSCLKIDAutoTaggingEnabled', before: String(enabled), after: 'true' }], notes, coercions: status !== value.status ? ['Status coerced to Paused by policy (paused_creation)'] : [], budgetDeltas: [], execute: async () => {\n const result = await this.request(account, 'ConversionGoals', { ConversionGoals: [fields] });\n const ids = Array.isArray(result.ConversionGoalIds) ? result.ConversionGoalIds.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1 || existing.some(goal => nativeId(goal.Id) === ids[0])) throw new AdportError('PROVIDER_ERROR', 'microsoft: conversion-goal creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.verify(account, ids[0]!, value.type, fields);\n } };\n }\n const value = update.parse(op.payload), current = await this.get(account, value.goal_id, value.goal_type);\n if (current.goal.Scope !== 'Account') throw new AdportError('INVALID_INPUT', 'microsoft: customer-wide conversion goals require authorization covering every affected account; single-account tools cannot mutate them');\n if (current.snapshot_hash !== value.expected_snapshot_hash) throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal snapshot changed; read fresh context and request a new preview');\n if (value.url_rule && value.goal_type !== 'Url' || value.event_conditions && value.goal_type !== 'Event' || value.is_externally_attributed !== undefined && value.goal_type !== 'OfflineConversion') throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal subtype fields mismatch');\n const fields: Row = {};\n for (const [key, field] of [['name', 'Name'], ['goal_category', 'GoalCategory'], ['status', 'Status'], ['exclude_from_bidding', 'ExcludeFromBidding'], ['count_type', 'CountType'], ['conversion_window_minutes', 'ConversionWindowInMinutes'], ['enhanced_conversions_enabled', 'IsEnhancedConversionsEnabled'], ['is_externally_attributed', 'IsExternallyAttributed']] as const) if (value[key] !== undefined && value[key] !== current.goal[field]) fields[field] = value[key];\n if (value.revenue) fields.Revenue = wireRevenue(value.revenue);\n if (value.url_rule) Object.assign(fields, { UrlExpression: value.url_rule.expression, UrlOperator: value.url_rule.operator });\n if (value.event_conditions) Object.assign(fields, eventFields(value.event_conditions));\n const changed = Object.entries(fields).filter(([key, value]) => !matches(current.goal, { [key]: value }));\n if (!changed.length) throw new AdportError('INVALID_INPUT', 'microsoft: conversion-goal update has no changes');\n // Native EventGoal updates delete any omitted criterion pair, even when only changing name/status.\n if (value.goal_type === 'Event' && !value.event_conditions) for (const [expression, operator] of pairs) {\n const expressionValue = current.goal[expression], operatorValue = current.goal[operator];\n if ((expressionValue === null || expressionValue === undefined) !== (operatorValue === null || operatorValue === undefined)) throw new AdportError('INVALID_INPUT', 'microsoft: existing event condition is incomplete; refusing a partial update');\n fields[expression] = expressionValue ?? null; fields[operator] = operatorValue ?? null;\n }\n const fieldChanges = changed.map(([field, after]) => ({ field, before: JSON.stringify(current.goal[field] ?? null), after: JSON.stringify(after) }));\n return { summary: `Update Microsoft ${value.goal_type} goal \"${String(current.goal.Name)}\"`, changes: [`~ goal ${value.goal_id} ${JSON.stringify(fields)}`, `MSCLKIDAutoTaggingEnabled ${current.auto_tagging_enabled} → true (native side effect)`], fieldChanges: [...fieldChanges, { field: 'MSCLKIDAutoTaggingEnabled', before: String(current.auto_tagging_enabled), after: 'true' }], notes, coercions: [], budgetDeltas: [], execute: async () => { await this.request(account, 'ConversionGoals', { ConversionGoals: [{ Id: value.goal_id, Type: value.goal_type, ...fields }] }, 'PUT'); return this.verify(account, value.goal_id, value.goal_type, { ...fields, Status: fields.Status ?? current.goal.Status }); } };\n }\n}\n\nexport function microsoftConversionTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_linked_uet_tags', namespace: 'microsoft', description: 'Read current native_customer_id plus UET metadata/code only for tags referenced by selected-account goals. Tags are customer-scoped; the entire library and sharing graph are not exposed. Continue next_cursor as after_tag_id.', input: z.object({ account_id: id, after_tag_id: id.optional(), limit: z.number().int().positive().max(100).default(50) }), output: z.object({ native_customer_id: id, rows: z.array(z.object({ tag: z.record(z.string(), z.unknown()), goal_ids: z.array(id), native_scope: z.literal('Customer') })), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_tag_id' }, annotations: { readOnly: true }, handler: input => provider.conversions.linkedTags(input) }),\n guardedWriteTool({ name: 'microsoft_create_uet_tag', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create one uninstalled UET tag in the selected account’s native customer library. Requires expected_customer_id from linked-tag reads; rechecks current parent ownership. Returns its ID for paused goal setup. No installation or event sending; tags have no pause state.', payload: createTag }),\n defineTool({ name: 'microsoft_conversion_goals', namespace: 'microsoft', description: 'Read account-associated native goals, tracking state, configuration hashes and account-level click-ID auto-tagging. Default excludes pilot-only InStoreTransaction, whose inclusion can reject the entire query. Continue next_cursor as after_goal_id.', input: z.object({ account_id: id, goal_types: z.array(goalType).min(1).refine(value => new Set(value).size === value.length, 'Goal types must be unique').default([...standardTypes]), after_goal_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ account_id: id, rows: z.array(view), auto_tagging_enabled: z.boolean(), auto_tagging_scope: z.literal('Account'), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_goal_id' }, annotations: { readOnly: true }, handler: input => provider.conversions.list(input) }),\n defineTool({ name: 'microsoft_get_conversion_goal', namespace: 'microsoft', description: 'Read one account-associated native goal and snapshot_hash. TrackingStatus is system-owned and excluded from the configuration hash. Customer-scoped goals cannot be edited through single-account tools.', input: z.object({ account_id: id, goal_id: id, goal_type: goalType }), output: view, annotations: { readOnly: true }, handler: input => provider.conversions.get(input.account_id, input.goal_id, input.goal_type) }),\n guardedWriteTool({ name: 'microsoft_create_conversion_goal', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create an account-scoped URL, Event or OfflineConversion goal. Defaults Paused and excluded from bidding. Native add automatically enables click-ID auto-tagging; supply its expected state from conversion-goal reads. Does not install tracking or send events. Goals cannot be permanently deleted through this API.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_conversion_goal', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit an Account-scoped URL/Event/Offline goal with expected_snapshot_hash. Preserves omitted event criteria, status and other optional settings. Native update enables click-ID auto-tagging. Event conditions, when supplied, replace the full condition set. Use Paused to stop tracking; Deleted is internal-only.', payload: update }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nexport const microsoftAudienceType = z.enum(['RemarketingList', 'Custom', 'InMarket', 'Product', 'SimilarRemarketingList', 'CombinedList', 'CustomerList', 'ImpressionBasedRemarketingList', 'CustomSegment']);\nconst audienceType = microsoftAudienceType;\nconst standardTypes = audienceType.options.filter(value => value !== 'CustomSegment');\nconst name = z.string().min(1).max(128).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst description = z.string().max(1024);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst stringOperator = z.enum(['Equals', 'Contains', 'BeginsWith', 'EndsWith', 'NotEquals', 'DoesNotContain', 'DoesNotBeginWith', 'DoesNotEndWith']);\nconst numberOperator = z.enum(['Equals', 'GreaterThan', 'LessThan', 'GreaterThanEqualTo', 'LessThanEqualTo', 'NotEquals']);\nconst groups = z.array(z.object({ items: z.array(z.object({ operand: z.enum(['Url', 'ReferrerUrl']), operator: stringOperator, value: z.string().min(1) })).min(1).max(100) })).min(1).max(100);\nconst eventExpression = z.object({ operator: stringOperator, text: z.string().min(1) });\nconst rule = z.discriminatedUnion('type', [\n z.object({ type: z.literal('PageVisitors'), normal_form: z.enum(['Conjunctive', 'Disjunctive']).default('Disjunctive'), groups }),\n z.object({ type: z.literal('PageVisitorsWhoVisitedAnotherPage'), groups, another_groups: groups }),\n z.object({ type: z.literal('PageVisitorsWhoDidNotVisitAnotherPage'), include_groups: groups, exclude_groups: groups }),\n z.object({ type: z.literal('CustomEvents'), action: eventExpression.optional(), category: eventExpression.optional(), label: eventExpression.optional(), value: z.object({ operator: numberOperator, amount: z.number().int().positive() }).optional() }).refine(value => Object.values(value).some(value => value !== undefined && value !== 'CustomEvents'), 'At least one complete event condition is required'),\n]);\nconst create = z.object({ name, description: description.optional(), membership_duration_days: z.number().int().min(1).max(180).default(30), tag_id: id, rule });\nconst reference = z.object({ audience_id: id, expected_snapshot_hash: hash });\nconst update = reference.extend({ name: name.optional(), description: description.optional(), membership_duration_days: z.number().int().min(1).max(180).optional(), tag_id: id.optional(), rule: rule.optional() }).refine(value => Object.entries(value).some(([key, value]) => !['audience_id', 'expected_snapshot_hash'].includes(key) && value !== undefined), 'Supply an editable field');\nconst view = z.object({ account_id: id, audience: z.record(z.string(), z.unknown()), shared: z.boolean(), snapshot_hash: hash });\nconst notes = ['Remarketing lists have no independent pause state. Creation is account-scoped and unattached; it does not install UET, send events or upload customer records.', 'Omitted rules and tag settings are preserved. Supplying a rule replaces its entire condition set. Conjunctive means OR within each group, AND across groups; Disjunctive means AND within each group, OR across groups.', 'Audience changes can affect existing targeting and exclusions in the selected account. Configuration hashes detect drift before submission; Microsoft has no atomic compare-and-set. Customer scope and sharing changes are not exposed.'];\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nfunction matches(actual: unknown, expected: unknown): boolean {\n if (expected === null || expected === undefined) return actual === null || actual === undefined;\n if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => matches(actual[index], value));\n if (typeof expected === 'object') {\n if (actual === null || typeof actual !== 'object') return false;\n if ((expected as Row).Type === 'CustomEvents') {\n for (const field of ['Action', 'Category', 'Label', 'Value']) if (!Object.hasOwn(expected, field) && ![undefined, null, 'None'].includes((actual as Row)[`${field}Operator`] as undefined | null | string)) return false;\n }\n return Object.entries(expected).every(([key, value]) => matches((actual as Row)[key], value));\n }\n return String(actual) === String(expected);\n}\nconst nativeGroups = (value: z.infer<typeof groups>) => value.map(group => ({ Items: group.items.map(item => ({ Type: 'String', Operand: item.operand, Operator: item.operator, Value: item.value })) }));\nfunction nativeRule(value: z.infer<typeof rule>): Row {\n if (value.type === 'PageVisitors') return { Type: value.type, NormalForm: value.normal_form, RuleItemGroups: nativeGroups(value.groups) };\n if (value.type === 'PageVisitorsWhoVisitedAnotherPage') return { Type: value.type, RuleItemGroups: nativeGroups(value.groups), AnotherRuleItemGroups: nativeGroups(value.another_groups) };\n if (value.type === 'PageVisitorsWhoDidNotVisitAnotherPage') return { Type: value.type, IncludeRuleItemGroups: nativeGroups(value.include_groups), ExcludeRuleItemGroups: nativeGroups(value.exclude_groups) };\n const result: Row = { Type: value.type };\n for (const [key, field] of [['action', 'Action'], ['category', 'Category'], ['label', 'Label'], ['value', 'Value']] as const) { const condition = value[key]; if (condition) { result[field] = 'text' in condition ? condition.text : condition.amount; result[`${field}Operator`] = condition.operator; } }\n return result;\n}\nexport const MICROSOFT_AUDIENCE_WRITES = new Set(['microsoft_create_remarketing_list', 'microsoft_update_remarketing_list', 'microsoft_delete_remarketing_list']);\n\n/** Campaign Management v13: explicit Account ownership, replacement-rule semantics and bounded deletion-use checks. */\nexport class MicrosoftAudienceService extends MicrosoftNativeService {\n constructor(...args: [...ConstructorParameters<typeof MicrosoftNativeService>, (account: string) => Promise<unknown[]>]) {\n const [client, scope, campaign, campaigns] = args; super(client, scope, campaign); this.campaigns = campaigns;\n }\n private readonly campaigns: (account: string) => Promise<unknown[]>;\n\n private async query(account: string, types: z.infer<typeof audienceType>[], ids: string[] | null = null): Promise<Row[]> {\n const result = await this.request(account, 'Audiences/QueryByIds', { AudienceIds: ids, Type: types.join(', '), ReturnAdditionalFields: 'NormalForm, NumberRuleItem, ImpressionBasedRemarketingList, CampaignIdsAdGroupIds' });\n if (!Object.hasOwn(result, 'Audiences')) throw new AdportError('PROVIDER_ERROR', 'microsoft: native audience response envelope is missing');\n const values = rows(result.Audiences);\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => !types.includes(audienceType.parse(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: native audience identities or types mismatch');\n return values;\n }\n\n private shared(value: Row): boolean {\n return value.CustomerShare !== null && value.CustomerShare !== undefined && rows(row(value.CustomerShare).CustomerAccountShares).length > 0;\n }\n\n private snapshot(account: string, value: Row) {\n const { SearchSize: _search, AudienceNetworkSize: _network, SupportedCampaignTypes: _supported, ...configuration } = value;\n const { CustomerShare: _sharing, ...audience } = value;\n return { account_id: account, audience, shared: this.shared(value), snapshot_hash: createHash('sha256').update(JSON.stringify(canonical({ account, configuration }))).digest('hex') };\n }\n\n async list(input: { account_id: string; audience_types: z.infer<typeof audienceType>[]; after_audience_id?: string; limit: number }) {\n const values = (await this.query(input.account_id, input.audience_types)).filter(value => !input.after_audience_id || BigInt(nativeId(value.Id)) > BigInt(input.after_audience_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = values.slice(0, input.limit), truncated = values.length > page.length;\n return { rows: page.map(value => this.snapshot(input.account_id, value)), truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n private async find(account: string, audience: string, type: z.infer<typeof audienceType>): Promise<Row> {\n const found = (await this.query(account, [type], [audience])).find(value => nativeId(value.Id) === audience);\n if (!found) throw new AdportError('INVALID_INPUT', 'microsoft: audience was not found for the selected account/type');\n return found;\n }\n\n async get(account: string, audience: string, type: z.infer<typeof audienceType>) { id.parse(audience); return this.snapshot(account, await this.find(account, audience, type)); }\n\n private async owned(account: string, audience: string): Promise<Row> {\n await this.accountScope(account, true);\n const current = await this.find(account, audience, 'RemarketingList');\n if (current.Scope !== 'Account' || nativeId(current.ParentId) !== account || this.shared(current)) throw new AdportError('INVALID_INPUT', 'microsoft: remarketing mutations require an unshared Account-scoped list owned by the selected account');\n return current;\n }\n\n private async tag(account: string, tag: string) {\n const result = await this.request(account, 'UetTags/QueryByIds', { TagIds: [tag] }), values = rows(result.UetTags);\n if (values.length !== 1 || nativeId(values[0]!.Id) !== tag) throw new AdportError('INVALID_INPUT', 'microsoft: UET tag is unavailable in the selected customer/account context');\n }\n\n async usage(account: string, audience: string) {\n await this.owned(account, audience);\n const lists = await this.query(account, ['SimilarRemarketingList', 'CombinedList']), derivedLists = lists.filter(value => value.Type === 'SimilarRemarketingList' && String(value.SourceId) === audience);\n if (derivedLists.some(value => value.Scope !== 'Account' || nativeId(value.ParentId) !== account || this.shared(value))) throw new AdportError('INVALID_INPUT', 'microsoft: a derived similar audience has wider or unverifiable ownership/sharing; single-account deletion use check is incomplete');\n const derived = derivedLists.map(value => nativeId(value.Id)), ids = [audience, ...derived];\n const combined = lists.filter(value => value.Type === 'CombinedList' && rows(value.CombinationRules).some(rule => Array.isArray(rule.AudienceIds) && rule.AudienceIds.some(value => ids.includes(nativeId(value))))).map(value => nativeId(value.Id));\n const groupsResult = await this.request(account, 'AudienceGroups/QueryByIds', { AudienceGroupIds: null });\n if (!Object.hasOwn(groupsResult, 'AudienceGroups')) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience-signal inventory is unavailable; deletion use check is incomplete');\n const signals = rows(groupsResult.AudienceGroups);\n if (signals.length >= 100) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience-signal inventory reached the documented result boundary; deletion use check is incomplete');\n const signalIds = signals.filter(value => rows(value.Dimensions).some(dimension => dimension.Type === 'Audience' && rows(dimension.Audiences).some(value => ids.includes(nativeId(value.Id))))).map(value => nativeId(value.Id));\n const campaigns = rows(await this.campaigns(account)), associations: Row[] = [];\n if (campaigns.length > 200) throw new AdportError('INVALID_INPUT', 'microsoft: audience use check exceeds 200 campaigns; no deletion was submitted');\n let groupCount = 0;\n for (const campaign of campaigns) {\n if (!['Search', 'Audience', 'DynamicSearchAds', 'Shopping', 'PerformanceMax'].includes(String(campaign.CampaignType))) throw new AdportError('INVALID_INPUT', 'microsoft: audience use check encountered an unsupported campaign type; no deletion was submitted');\n const campaignId = nativeId(campaign.Id);\n let groups: Row[] = [];\n // Performance Max uses audience signals and negative campaign criteria, without ordinary ad groups.\n if (campaign.CampaignType !== 'PerformanceMax') {\n const result = await this.request(account, 'AdGroups/QueryByCampaignId', { CampaignId: campaignId });\n if (!Object.hasOwn(result, 'AdGroups')) throw new AdportError('PROVIDER_ERROR', 'microsoft: ad-group inventory is unavailable; audience use check is incomplete');\n groups = rows(result.AdGroups);\n }\n groupCount += groups.length;\n if (groupCount > 2000) throw new AdportError('INVALID_INPUT', 'microsoft: audience use check exceeds 2000 ad groups; no deletion was submitted');\n for (const type of ['RemarketingList', ...(derived.length ? ['SimilarRemarketingList'] : [])]) {\n for (const group of [undefined, ...groups]) {\n const prefix = group ? 'AdGroup' : 'Campaign', parentId = group ? nativeId(group.Id) : campaignId;\n const result = await this.request(account, `${prefix}Criterions/QueryByIds`, { [`${prefix}Id`]: parentId, [`${prefix}CriterionIds`]: null, CriterionType: type });\n if (!Object.hasOwn(result, `${prefix}Criterions`)) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience association response is unavailable; use check is incomplete');\n for (const criterion of rows(result[`${prefix}Criterions`])) {\n // The REST JSON contract says AudienceCriterion; the inherited Type table says Audience.\n if (nativeId(criterion[`${prefix}Id`]) !== parentId || !['AudienceCriterion', 'Audience'].includes(String(row(criterion.Criterion).Type)) || row(criterion.Criterion).AudienceType !== type) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience association ownership/type mismatch');\n if (ids.includes(nativeId(row(criterion.Criterion).AudienceId)) && criterion.Status !== 'Deleted') associations.push({ campaign_id: campaignId, ...(group ? { ad_group_id: parentId } : {}), criterion });\n }\n }\n }\n }\n return { audience_id: audience, derived_audience_ids: derived, associations, combined_list_ids: combined, audience_signal_ids: signalIds, campaigns_scanned: campaigns.length, ad_groups_scanned: groupCount, complete: true as const };\n }\n\n private async confirm(account: string, audience: string, expected: Row) {\n try { const actual = await this.owned(account, audience); if (!matches(actual, expected)) throw new Error('Audience readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: audience write was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: [audience] }); }\n return [audience];\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_create_remarketing_list' ? 'create' : op.tool === 'microsoft_delete_remarketing_list' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_AUDIENCE_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: audience operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_create_remarketing_list') {\n const input = create.parse(op.payload); await this.accountScope(account, true); await this.tag(account, input.tag_id);\n if ((await this.query(account, ['RemarketingList'])).some(value => String(value.Name).toLowerCase() === input.name.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: a remarketing list with this name already exists');\n const fields = { Type: 'RemarketingList', Scope: 'Account', ParentId: account, Name: input.name, MembershipDuration: input.membership_duration_days, TagId: input.tag_id, Rule: nativeRule(input.rule), ...(input.description !== undefined ? { Description: input.description } : {}) };\n return { summary: `Create Microsoft remarketing list \"${input.name}\"`, changes: [`+ ${JSON.stringify(fields)}`], notes, coercions: [], budgetDeltas: [], fieldChanges: [{ field: 'Name', before: '(new)', after: input.name }, { field: 'Scope', before: '(new)', after: 'Account' }, { field: 'Rule', before: '(new)', after: JSON.stringify(fields.Rule) }], execute: async () => {\n const result = await this.request(account, 'Audiences', { Audiences: [fields] }), ids = Array.isArray(result.AudienceIds) ? result.AudienceIds.filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.confirm(account, ids[0]!, fields);\n } };\n }\n const input = (op.kind === 'remove' ? reference : update).parse(op.payload), current = await this.owned(account, input.audience_id);\n if (this.snapshot(account, current).snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience configuration snapshot changed; request a fresh preview');\n if (op.kind === 'remove') {\n const usage = await this.usage(account, input.audience_id);\n if (usage.associations.length || usage.combined_list_ids.length || usage.audience_signal_ids.length) throw new AdportError('INVALID_INPUT', 'microsoft: audience or derived similar audience is referenced; remove its targeting, combined-list and signal references before deleting');\n return { summary: `Delete Microsoft remarketing list ${input.audience_id}`, changes: [`- ${JSON.stringify(this.snapshot(account, current).audience)}`, `Also deletes derived similar lists: ${JSON.stringify(usage.derived_audience_ids)}. No campaign/ad-group, combined-list or audience-signal references were found in the bounded account scan.`], notes: ['Deletion is permanent. Use checks are repeated before submission; native concurrent association changes cannot be locked.'], coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, 'Audiences', { AudienceIds: [input.audience_id] }, 'DELETE');\n try { const remaining = await this.query(account, ['RemarketingList', 'SimilarRemarketingList']); if (remaining.some(value => [input.audience_id, ...usage.derived_audience_ids].includes(nativeId(value.Id)))) throw new Error('Audience still present'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: audience deletion readback was not confirmed; reconcile before retrying', { resourceIds: [input.audience_id, ...usage.derived_audience_ids] }); }\n return [input.audience_id, ...usage.derived_audience_ids];\n } };\n }\n const value = update.parse(input), fields: Row = { Id: value.audience_id, Type: 'RemarketingList' };\n for (const [key, field] of [['name', 'Name'], ['description', 'Description'], ['membership_duration_days', 'MembershipDuration'], ['tag_id', 'TagId']] as const) if (value[key] !== undefined) fields[field] = value[key];\n if (value.tag_id) await this.tag(account, value.tag_id);\n if (value.rule) fields.Rule = nativeRule(value.rule);\n const expected = Object.fromEntries(Object.entries({ ...current, ...fields }).filter(([key]) => !['CustomerShare', 'SearchSize', 'AudienceNetworkSize', 'SupportedCampaignTypes'].includes(key)));\n return { summary: `Update Microsoft remarketing list ${value.audience_id}`, changes: [`~ ${JSON.stringify(fields)}`], fieldChanges: Object.entries(fields).filter(([key]) => !['Id', 'Type'].includes(key)).map(([field, value]) => ({ field, before: typeof current[field] === 'object' ? JSON.stringify(current[field]) : String(current[field] ?? '(unset)'), after: typeof value === 'object' ? JSON.stringify(value) : String(value) })), notes, coercions: [], budgetDeltas: [], execute: async () => { await this.request(account, 'Audiences', { Audiences: [fields] }, 'PUT'); return this.confirm(account, value.audience_id, expected); } };\n }\n}\n\nexport function microsoftAudienceTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_audiences', namespace: 'microsoft', description: 'Read account-associated native audiences with configuration hashes. Preserves unavailable sizes. Sharing graphs are omitted; shared is reported. System-generated visitor/converter/Smart lists are not supported by this API. CustomSegment is opt-in; reserved AIPrompt is excluded. Continue next_cursor as after_audience_id.', input: z.object({ account_id: id, audience_types: z.array(audienceType).min(1).refine(value => new Set(value).size === value.length, 'Audience types must be unique').default(standardTypes), after_audience_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ rows: z.array(view), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_audience_id' }, annotations: { readOnly: true }, handler: input => provider.audiences.list(input) }),\n defineTool({ name: 'microsoft_get_audience', namespace: 'microsoft', description: 'Read one account-associated native audience and snapshot_hash. Customer-scoped or shared lists are readable but cannot be changed by single-account remarketing tools. System-owned sizes are excluded from the hash.', input: z.object({ account_id: id, audience_id: id, audience_type: audienceType }), output: view, annotations: { readOnly: true }, handler: input => provider.audiences.get(input.account_id, input.audience_id, input.audience_type) }),\n defineTool({ name: 'microsoft_audience_usage', namespace: 'microsoft', description: 'Check an owned unshared Account remarketing list and its derived similar lists for campaign/ad-group criteria, combined-list and audience-signal references. Bounded to 200 campaigns, 2000 ad groups and fewer than 100 signals; incomplete/unsupported scans fail closed.', input: z.object({ account_id: id, audience_id: id }), annotations: { readOnly: true }, handler: input => provider.audiences.usage(input.account_id, input.audience_id) }),\n guardedWriteTool({ name: 'microsoft_create_remarketing_list', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create one unattached Account-scoped remarketing list using an available UET tag and PageVisitors, visited-another-page, excluded-page or CustomEvents rule. No pause state, installation, event sending or customer-record upload. Membership is 1..180 days.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_remarketing_list', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit an owned unshared Account remarketing list with expected_snapshot_hash. Preserves omitted rule/tag/settings; supplying rule replaces its entire condition set. Scope/parent/sharing are immutable here. Existing audience targeting and exclusions can be affected.', payload: update }),\n guardedWriteTool({ name: 'microsoft_delete_remarketing_list', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', destructive: true, description: 'Permanently delete an owned unshared Account remarketing list and its derived similar lists. Requires expected_snapshot_hash and a complete bounded scan with no targeting, combined-list or signal references. Confirms disappearance; never retries an uncertain deletion.', payload: reference }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { microsoftAudienceType } from './audiences.js';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst audienceType = microsoftAudienceType.exclude(['CustomSegment']);\nconst selectors = { Custom: 'CustomAudience', InMarket: 'InMarketAudience', Product: 'ProductAudience', RemarketingList: 'RemarketingList', SimilarRemarketingList: 'SimilarRemarketingList', CombinedList: 'CombinedList', CustomerList: 'CustomerList', ImpressionBasedRemarketingList: 'ImpressionBasedRemarketingList' } as const;\nconst target = z.discriminatedUnion('type', [z.object({ type: z.literal('Campaign'), campaign_id: id }), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id })]);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), adjustment = z.number().int().min(-90).max(900);\nconst add = z.object({ target, audience_id: id, audience_type: audienceType, expected_audience_snapshot_hash: hash, exclude: z.boolean().default(false), bid_adjustment_percent: adjustment.optional(), expected_target_and_bid: z.boolean().optional() }).superRefine((value, ctx) => {\n if (value.exclude && (value.bid_adjustment_percent !== undefined || value.expected_target_and_bid !== undefined)) ctx.addIssue({ code: 'custom', message: 'Exclusions have no bid adjustment and are independent of positive target mode' });\n if (!value.exclude && value.expected_target_and_bid === undefined) ctx.addIssue({ code: 'custom', message: 'Positive associations require expected_target_and_bid from microsoft_audience_targets' });\n});\nconst reference = z.object({ target, audience_type: audienceType, criterion_id: id, expected_snapshot_hash: hash });\nconst bid = reference.extend({ bid_adjustment_percent: adjustment });\nconst mode = z.object({ target, expected_context_hash: hash, target_and_bid: z.boolean() });\nconst context = z.object({ account_id: id, target, campaign_status: z.string(), ad_group_status: z.string().optional(), target_and_bid: z.boolean(), audience_target_option: z.enum(['TargetAndBid', 'BidOnly']), context_hash: hash });\ntype Target = z.infer<typeof target>;\ntype AudienceType = z.infer<typeof audienceType>;\ntype Source = { audience: Row; snapshot_hash: string };\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst prefix = (value: Target) => value.type;\nconst entityId = (value: Target) => value.type === 'Campaign' ? value.campaign_id : value.ad_group_id;\nconst isTargetSetting = (value: Row) => ['Target', 'TargetSetting'].includes(String(value.Type));\nconst orderedDetails = (value: Row[]) => [...value].sort((a, b) => String(a.CriterionTypeGroup).localeCompare(String(b.CriterionTypeGroup)));\nconst notices = ['Audience criteria have native Active status, without an independent pause. Default paused_creation requires an effectively paused parent for new associations.', 'Positive audiences can be associated at campaign or ad-group level, but not both within one campaign. Exclusions can exist at both levels and Microsoft applies their union.', 'TargetAndBid restricts positive audience delivery; BidOnly adjusts bids without adding that restriction. Exclusions apply regardless. Automated bidding can treat bid percentages as signals. Snapshots detect changes before submission; Microsoft has no atomic compare-and-set.'];\nexport const MICROSOFT_AUDIENCE_TARGETING_WRITES = new Set(['microsoft_add_audience_target', 'microsoft_set_audience_target_bid', 'microsoft_remove_audience_target', 'microsoft_set_audience_target_mode']);\n\n/** Audience selector on mutations; concrete native selectors on reads. TargetSetting.Details updates replace the complete list. */\nexport class MicrosoftAudienceTargetingService extends MicrosoftNativeService {\n constructor(...args: [...ConstructorParameters<typeof MicrosoftNativeService>, (account: string, audience: string, type: AudienceType) => Promise<Source>]) {\n const [client, scope, campaign, source] = args; super(client, scope, campaign); this.source = source;\n }\n private readonly source: (account: string, audience: string, type: AudienceType) => Promise<Source>;\n\n private async entity(account: string, value: Target, refresh = false) {\n await this.accountScope(account, refresh);\n const known = await this.campaign(account, value.campaign_id);\n const result = await this.request(account, 'Campaigns/QueryByIds', { AccountId: account, CampaignIds: [value.campaign_id], CampaignType: known.CampaignType, ReturnAdditionalFields: 'TargetSetting' }), campaigns = rows(result.Campaigns);\n if (campaigns.length !== 1 || nativeId(campaigns[0]!.Id) !== value.campaign_id || campaigns[0]!.CampaignType !== known.CampaignType || typeof campaigns[0]!.Status !== 'string') throw new AdportError('PROVIDER_ERROR', 'microsoft: audience target campaign context is unavailable or mismatched');\n const campaign = campaigns[0]!;\n let group: Row | undefined;\n if (value.type === 'AdGroup') {\n if (campaign.CampaignType === 'PerformanceMax') throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max audiences use campaign exclusions or asset-group signals, not ordinary ad-group criteria');\n const groups = rows((await this.request(account, 'AdGroups/QueryByIds', { CampaignId: value.campaign_id, AdGroupIds: [value.ad_group_id], ReturnAdditionalFields: 'AdGroupType' })).AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== value.ad_group_id || typeof groups[0]!.Status !== 'string') throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n group = groups[0]!;\n }\n const entity = group ?? campaign, settings = rows(entity.Settings), targetSettings = settings.filter(isTargetSetting);\n if (targetSettings.length > 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate target settings in the selected entity');\n const details = orderedDetails(rows(targetSettings[0]?.Details));\n if (details.some(value => typeof value.CriterionTypeGroup !== 'string' || typeof value.TargetAndBid !== 'boolean') || new Set(details.map(value => value.CriterionTypeGroup)).size !== details.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: target-setting details are incomplete or duplicated');\n const targetAndBid = details.find(value => value.CriterionTypeGroup === 'Audience')?.TargetAndBid === true;\n const visible = { account_id: account, target: value, campaign_status: campaign.Status, ...(group ? { ad_group_status: String(group.Status) } : {}), target_and_bid: targetAndBid, audience_target_option: targetAndBid ? 'TargetAndBid' as const : 'BidOnly' as const };\n return { campaign, group, entity, settings, targetSettings, details, context: { ...visible, context_hash: digest({ ...visible, targetSettings }) } };\n }\n\n private async query(account: string, value: Target, type: AudienceType) {\n const kind = prefix(value), result = await this.request(account, `${kind}Criterions/QueryByIds`, { [`${kind}Id`]: entityId(value), [`${kind}CriterionIds`]: null, CriterionType: selectors[type] });\n if (!Object.hasOwn(result, `${kind}Criterions`)) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience criterion response envelope is missing');\n const values = rows(result[`${kind}Criterions`]);\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(criterion => nativeId(criterion[`${kind}Id`]) !== entityId(value) || ![`Biddable${kind}Criterion`, `Negative${kind}Criterion`].includes(String(criterion.Type)) || !['Audience', 'AudienceCriterion'].includes(String(row(criterion.Criterion).Type)) || row(criterion.Criterion).AudienceType !== type)) throw new AdportError('PROVIDER_ERROR', 'microsoft: native audience criterion ownership or type mismatch');\n return values.filter(value => value.Status !== 'Deleted');\n }\n\n private snapshot(value: Row, contextHash: string) { return digest({ contextHash, value }); }\n\n async list(input: { account_id: string; target: Target; audience_type: AudienceType; after_criterion_id?: string; limit: number }) {\n const current = await this.entity(input.account_id, input.target), values = (await this.query(input.account_id, input.target, input.audience_type)).filter(value => !input.after_criterion_id || BigInt(nativeId(value.Id)) > BigInt(input.after_criterion_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = values.slice(0, input.limit), truncated = values.length > page.length;\n return { context: current.context, rows: page.map(value => ({ criterion: value, snapshot_hash: this.snapshot(value, current.context.context_hash) })), truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}) };\n }\n\n private async all(account: string, value: Target) {\n const results: Row[] = [];\n for (let i = 0; i < audienceType.options.length; i += 4) results.push(...(await Promise.all(audienceType.options.slice(i, i + 4).map(type => this.query(account, value, type)))).flat());\n return results;\n }\n\n private async exclusive(account: string, value: Target) {\n let opposite: Target[];\n if (value.type === 'AdGroup') opposite = [{ type: 'Campaign', campaign_id: value.campaign_id }];\n else {\n const result = await this.request(account, 'AdGroups/QueryByCampaignId', { CampaignId: value.campaign_id });\n if (!Object.hasOwn(result, 'AdGroups')) throw new AdportError('PROVIDER_ERROR', 'microsoft: opposite-level audience check lacks the ad-group inventory');\n const groups = rows(result.AdGroups);\n if (groups.length > 50 || new Set(groups.map(value => nativeId(value.Id))).size !== groups.length) throw new AdportError('INVALID_INPUT', 'microsoft: opposite-level audience check exceeds 50 ad groups or contains duplicate IDs; no association submitted');\n opposite = groups.map(group => ({ type: 'AdGroup', campaign_id: value.campaign_id, ad_group_id: nativeId(group.Id) }));\n }\n for (const entity of opposite) if ((await this.all(account, entity)).some(value => String(value.Type).startsWith('Biddable'))) throw new AdportError('INVALID_INPUT', 'microsoft: positive audience targets already exist at the opposite campaign/ad-group level; remove them before changing levels');\n }\n\n private async confirm(ids: string[], check: () => Promise<boolean>) {\n try { if (await check()) return ids; } catch { /* Accepted writes are never replayed to repair an uncertain readback. */ }\n throw new AdportError('PROVIDER_ERROR', 'microsoft: audience targeting write was accepted but readback was not confirmed; reconcile before retrying', { resourceIds: ids });\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const expectedKind = op.tool === 'microsoft_add_audience_target' ? 'create' : op.tool === 'microsoft_remove_audience_target' ? 'remove' : 'update';\n if (op.provider !== 'microsoft' || !MICROSOFT_AUDIENCE_TARGETING_WRITES.has(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'microsoft: audience targeting operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_set_audience_target_mode') {\n const input = mode.parse(op.payload), current = await this.entity(account, input.target, true);\n if (current.campaign.CampaignType === 'PerformanceMax') throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max does not support TargetSetting; use campaign exclusions or asset-group signals');\n if (current.context.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience parent context changed; request a fresh preview');\n if (current.targetSettings.some(setting => Object.entries(setting).some(([key, value]) => !['Type', 'Details'].includes(key) && value !== null && value !== undefined))) throw new AdportError('INVALID_INPUT', 'microsoft: an unsupported target-setting property prevents a safe replacement');\n const details = orderedDetails([...current.details.filter(value => value.CriterionTypeGroup !== 'Audience'), ...(input.target_and_bid ? [{ CriterionTypeGroup: 'Audience', TargetAndBid: true }] : [])]), fields = { Id: entityId(input.target), Settings: [{ Type: 'TargetSetting', Details: details.length ? details : null }] };\n const body = input.target.type === 'Campaign' ? { AccountId: account, Campaigns: [fields] } : { CampaignId: input.target.campaign_id, AdGroups: [fields] };\n return { summary: `Set Microsoft ${input.target.type} \"${String(current.entity.Name ?? entityId(input.target))}\" audience delivery option`, changes: [`~ ${JSON.stringify(fields)}`, 'Applies to every positive audience on this entity. Other target groups and other settings are preserved; exclusions and serving status are unchanged.'], fieldChanges: [{ field: 'Audience delivery option', before: current.context.audience_target_option, after: input.target_and_bid ? 'TargetAndBid' : 'BidOnly' }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, input.target.type === 'Campaign' ? 'Campaigns' : 'AdGroups', body, 'PUT');\n return this.confirm([entityId(input.target)], async () => { const after = await this.entity(account, input.target); return after.context.target_and_bid === input.target_and_bid && digest(after.details.filter(value => value.CriterionTypeGroup !== 'Audience')) === digest(current.details.filter(value => value.CriterionTypeGroup !== 'Audience')) && digest(after.settings.filter(value => !isTargetSetting(value))) === digest(current.settings.filter(value => !isTargetSetting(value))) && after.context.campaign_status === current.context.campaign_status && after.context.ad_group_status === current.context.ad_group_status; });\n } };\n }\n if (op.tool === 'microsoft_add_audience_target') {\n const input = add.parse(op.payload), current = await this.entity(account, input.target, true), source = await this.source(account, input.audience_id, input.audience_type);\n if (source.snapshot_hash !== input.expected_audience_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience definition changed; read its current snapshot and request a fresh preview');\n if (current.campaign.CampaignType === 'PerformanceMax' && !input.exclude) throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max audience criteria support exclusions only; positive audiences use asset-group signals');\n if (guard.forcePausedCreation && current.campaign.Status !== 'Paused' && current.group?.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: audience criteria are natively Active; paused_creation requires a paused campaign or ad group');\n if (!input.exclude && current.context.target_and_bid !== input.expected_target_and_bid) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience target mode changed; request a fresh preview');\n if ((await this.query(account, input.target, input.audience_type)).some(value => nativeId(row(value.Criterion).AudienceId) === input.audience_id)) throw new AdportError('INVALID_INPUT', 'microsoft: this audience is already associated or excluded at the selected level');\n if (!input.exclude) await this.exclusive(account, input.target);\n const kind = prefix(input.target), percent = input.bid_adjustment_percent ?? 0, fields = { [`${kind}Id`]: entityId(input.target), Type: `${input.exclude ? 'Negative' : 'Biddable'}${kind}Criterion`, Criterion: { Type: 'AudienceCriterion', AudienceId: input.audience_id }, ...(!input.exclude ? { CriterionBid: { Type: 'BidMultiplier', Multiplier: percent } } : {}) };\n return { summary: `${input.exclude ? 'Exclude' : 'Associate'} Microsoft audience \"${String(source.audience.Name ?? input.audience_id)}\"`, changes: [`+ ${JSON.stringify(fields)}`, `Parent audience delivery option remains ${current.context.audience_target_option}. No source-definition, target-mode or parent-status changes.`], fieldChanges: [{ field: 'Audience', before: '(unattached)', after: `${String(source.audience.Name ?? '')} (${input.audience_id})` }, { field: 'Parent', before: '(unattached)', after: `${input.target.type} ${String(current.entity.Name ?? '')} (${entityId(input.target)})` }, { field: 'Association', before: '(none)', after: input.exclude ? 'Exclude' : `${current.context.audience_target_option}, bid adjustment ${percent}%` }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.request(account, `${kind}Criterions`, { [`${kind}Criterions`]: [fields], CriterionType: 'Audience' }), ids = Array.isArray(result[`${kind}CriterionIds`]) ? (result[`${kind}CriterionIds`] as unknown[]).filter(value => value !== null).map(nativeId) : [];\n if (ids.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: audience criterion receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.confirm(ids, async () => { const actual = (await this.query(account, input.target, input.audience_type)).find(value => nativeId(value.Id) === ids[0]); return !!actual && actual.Type === fields.Type && nativeId(row(actual.Criterion).AudienceId) === input.audience_id && (input.exclude || row(actual.CriterionBid).Type === 'BidMultiplier' && row(actual.CriterionBid).Multiplier === percent); });\n } };\n }\n const input = (op.tool === 'microsoft_set_audience_target_bid' ? bid : reference).parse(op.payload), current = await this.entity(account, input.target, true), criterion = (await this.query(account, input.target, input.audience_type)).find(value => nativeId(value.Id) === input.criterion_id);\n if (!criterion) throw new AdportError('INVALID_INPUT', 'microsoft: audience criterion was not found in the selected entity/account/type');\n if (this.snapshot(criterion, current.context.context_hash) !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: audience criterion or parent context changed; request a fresh preview');\n const kind = prefix(input.target);\n if (op.tool === 'microsoft_set_audience_target_bid') {\n const value = bid.parse(input);\n if (criterion.Type !== `Biddable${kind}Criterion` || row(criterion.CriterionBid).Type !== 'BidMultiplier') throw new AdportError('INVALID_INPUT', 'microsoft: only biddable audience criteria with BidMultiplier accept a bid edit');\n const fields = { [`${kind}Id`]: entityId(input.target), Id: input.criterion_id, Type: `Biddable${kind}Criterion`, CriterionBid: { Type: 'BidMultiplier', Multiplier: value.bid_adjustment_percent } };\n return { summary: `Set Microsoft audience ${nativeId(row(criterion.Criterion).AudienceId)} bid adjustment on ${kind} \"${String(current.entity.Name ?? entityId(input.target))}\"`, changes: [`~ ${JSON.stringify(fields)}`], fieldChanges: [{ field: 'Bid adjustment', before: `${row(criterion.CriterionBid).Multiplier}%`, after: `${value.bid_adjustment_percent}%` }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, `${kind}Criterions`, { [`${kind}Criterions`]: [fields], CriterionType: 'Audience' }, 'PUT');\n return this.confirm([input.criterion_id], async () => { const actual = (await this.query(account, input.target, input.audience_type)).find(value => nativeId(value.Id) === input.criterion_id); return !!actual && actual.Type === criterion.Type && digest(actual.Criterion) === digest(criterion.Criterion) && row(actual.CriterionBid).Multiplier === value.bid_adjustment_percent; });\n } };\n }\n return { summary: `Remove Microsoft audience association from ${kind} \"${String(current.entity.Name ?? entityId(input.target))}\"`, changes: [`- ${JSON.stringify(criterion)}`, 'Removing a positive association or an exclusion can change delivery. Parent target mode, status and other criterion IDs are preserved.'], fieldChanges: [{ field: 'Audience association', before: `${String(criterion.Type).startsWith('Negative') ? 'Exclude' : 'Positive'} audience ${nativeId(row(criterion.Criterion).AudienceId)} (criterion ${input.criterion_id})`, after: 'Removed' }], notes: notices, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, `${kind}Criterions`, { [`${kind}Id`]: entityId(input.target), [`${kind}CriterionIds`]: [input.criterion_id], CriterionType: 'Audience' }, 'DELETE');\n return this.confirm([input.criterion_id], async () => !(await this.query(account, input.target, input.audience_type)).some(value => nativeId(value.Id) === input.criterion_id));\n } };\n }\n}\n\nexport function microsoftAudienceTargetingTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_audience_targets', namespace: 'microsoft', description: 'Read campaign or ad-group audience associations/exclusions of one concrete audience type. Returns native criteria, snapshots and verified parent target-mode/status context. Campaign TargetSetting is explicitly requested. Continue next_cursor as after_criterion_id.', input: z.object({ account_id: id, target, audience_type: audienceType, after_criterion_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ context, rows: z.array(z.object({ criterion: z.record(z.string(), z.unknown()), snapshot_hash: hash })), truncated: z.boolean(), next_cursor: id.optional() }), pagination: { cursorInput: 'after_criterion_id' }, annotations: { readOnly: true }, handler: input => provider.audienceTargeting.list(input) }),\n guardedWriteTool({ name: 'microsoft_add_audience_target', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Associate or exclude an account-available audience with expected_audience_snapshot_hash. Positive criteria require expected_target_and_bid from target reads and a complete opposite-level check, bounded to 50 ad groups. Preserves parent mode/status; native Active criteria require an effectively paused parent under paused_creation. Performance Max supports campaign exclusions only.', payload: add }),\n guardedWriteTool({ name: 'microsoft_set_audience_target_bid', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit an owned positive audience criterion percentage adjustment (-90..900, integer) with expected_snapshot_hash. Preserves audience identity, delivery mode and parent status. Exclusions do not accept bids.', payload: bid }),\n guardedWriteTool({ name: 'microsoft_remove_audience_target', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Remove an exact owned audience association/exclusion with expected_snapshot_hash. This can broaden or narrow delivery; preserves target mode and other criteria. Confirms disappearance before reporting success.', payload: reference }),\n guardedWriteTool({ name: 'microsoft_set_audience_target_mode', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Set TargetAndBid (restrict positive audience delivery) or BidOnly (bid adjustment without that restriction) with expected_context_hash from target reads. Preserves all other target-setting details and other settings; affects all positive audiences on that entity. Performance Max uses signals and exclusions instead.', payload: mode }),\n ];\n}\n","import { AdportError, defineTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst range = z.object({ start_utc: z.iso.datetime(), end_utc: z.iso.datetime() }).refine(value => {\n const span = Date.parse(value.end_utc) - Date.parse(value.start_utc);\n return span >= 0 && span <= 7 * 86400000;\n}, 'Use an ordered UTC interval of at most seven days');\nconst accountInput = z.object({ account_id: id, date_range: range });\nconst channels = z.enum(['CampaignManagementAPI', 'BulkAPI', 'WebUpload', 'Unknown']);\nconst goalInput = accountInput.extend({ goal_ids: z.array(id).min(1).max(20).refine(value => new Set(value).size === value.length, 'Goal IDs must be unique'), upload_channels: z.array(channels).min(1).refine(value => new Set(value).size === value.length && (!value.includes('Unknown') || value.length === 1), 'Use unique channels; Unknown cannot be combined with other channels').optional() });\nconst count = z.union([z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), z.string().regex(/^\\d+$/)]);\nconst rate = z.union([z.number().min(0).max(1), z.string().regex(/^(?:0(?:\\.\\d+)?|1(?:\\.0+)?)$/)]);\nconst optionalCount = count.nullable().optional();\nconst alert = z.object({ Count: optionalCount, UnattributedReason: z.string().nullable().optional() });\nconst goalId = z.preprocess(nativeId, id);\nconst day = z.object({ GoalId: goalId, UploadDate: z.string(), SuccessCount: optionalCount, UnattributedCount: optionalCount, SuccessRate: rate.nullable().optional(), Alerts: z.array(alert).nullable().optional() });\nconst summary = z.object({ GoalId: goalId, ConversionName: z.string().nullable().optional(), OverallSuccessCount: optionalCount, OverallUnattributedCount: optionalCount, OverallSuccessRate: rate.nullable().optional(), OverallAlerts: z.array(alert).nullable().optional(), DailySummaries: z.array(day).nullable().optional() });\nconst daily = z.object({ UploadDate: z.string(), SuccessCount: optionalCount, FailureCount: optionalCount, FileUrlExpiryTimeUtc: z.string().nullable().optional(), file_available: z.boolean() });\nconst partialError = z.object({ index: z.number().int().nonnegative().optional(), goal_id: id.optional(), code: z.number().int().optional(), error_code: z.string().optional() });\nconst accountOutput = z.object({ account_id: id, date_range: range, rows: z.array(daily), notes: z.array(z.string()) });\nconst goalOutput = z.object({ account_id: id, date_range: range, rows: z.array(summary), errors: z.array(partialError), not_returned_goal_ids: z.array(id), notes: z.array(z.string()) });\nconst notes = ['Read-only upload diagnostics, not campaign performance or proof of incremental attribution. Counts preserve native strings and missing values; success rates are ratios, not percentages.', 'Input boundaries are UTC. Native UploadDate values are preserved; Microsoft documents DailySummary.UploadDate as local time. No conversion events are submitted.'];\n\n/** Campaign Management v13 report aggregates only; never expose signed report files or pilot event records. */\nexport class MicrosoftOfflineReportService extends MicrosoftNativeService {\n async daily(input: z.infer<typeof accountInput>) {\n const result = await this.request(input.account_id, 'OfflineConversionReports/Query', { StartDateUtc: input.date_range.start_utc, EndDateUtc: input.date_range.end_utc });\n if (!Object.hasOwn(result, 'DailySummaries')) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline upload report envelope is missing');\n const values = rows(result.DailySummaries).map(value => {\n if (!Object.hasOwn(value, 'SuccessCount') && !Object.hasOwn(value, 'FailureCount')) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline report lacks aggregate counts; event-level records are not exposed by this tool');\n return daily.parse({ ...value, file_available: typeof value.FileUrl === 'string' && value.FileUrl.length > 0 });\n });\n return accountOutput.parse({ account_id: input.account_id, date_range: input.date_range, rows: values, notes: [...notes, 'Signed FileUrl values and pilot event/customer fields are omitted. This tool does not download raw conversion files.'] });\n }\n\n async goals(input: z.infer<typeof goalInput>) {\n const available = rows((await this.request(input.account_id, 'ConversionGoals/QueryByIds', { ConversionGoalIds: input.goal_ids, ConversionGoalTypes: 'OfflineConversion' })).ConversionGoals);\n if (available.length !== input.goal_ids.length || new Set(available.map(value => nativeId(value.Id))).size !== available.length || available.some(value => value.Type !== 'OfflineConversion' || !input.goal_ids.includes(nativeId(value.Id)))) throw new AdportError('INVALID_INPUT', 'microsoft: requested offline goals are not all available in the selected account');\n const scope = await this.accountScope(input.account_id);\n // This read can return successful summaries alongside per-goal failures.\n // Preserve those failures explicitly instead of the mutation helper's throw.\n const result = await this.client.request<Record<string, unknown>>('campaign', 'POST', 'OfflineConversionReport/QueryByGoalIds', { StartDateUtc: input.date_range.start_utc, EndDateUtc: input.date_range.end_utc, GoalIds: input.goal_ids, UploadChannelFilter: input.upload_channels?.join(', ') ?? null }, scope);\n if (!Object.hasOwn(result, 'OfflineGoalConversionSummaries') || result.NestedPartialErrors !== undefined && result.NestedPartialErrors !== null && (!Array.isArray(result.NestedPartialErrors) || result.NestedPartialErrors.some(Boolean))) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline goal report envelope is missing or contains unsupported nested errors');\n const values = rows(result.OfflineGoalConversionSummaries).map(value => summary.parse(value));\n if (new Set(values.map(value => value.GoalId)).size !== values.length || values.some(value => !input.goal_ids.includes(value.GoalId) || value.DailySummaries?.some(day => day.GoalId !== value.GoalId))) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline report returned an unexpected or duplicate goal identity');\n const errors = z.array(z.record(z.string(), z.unknown()).nullable()).parse(result.PartialErrors ?? []).filter(value => value !== null).map(value => {\n if (value.Index !== undefined && value.Index !== null && (!Number.isInteger(value.Index) || Number(value.Index) < 0 || Number(value.Index) >= input.goal_ids.length)) throw new AdportError('PROVIDER_ERROR', 'microsoft: offline report error index is outside the requested goals');\n if (typeof value.Code !== 'number' && typeof value.ErrorCode !== 'string') throw new AdportError('PROVIDER_ERROR', 'microsoft: malformed offline report partial error');\n const index = typeof value.Index === 'number' ? value.Index : undefined;\n return partialError.parse({ ...(index !== undefined ? { index, goal_id: input.goal_ids[index] } : {}), ...(value.Code !== undefined ? { code: value.Code } : {}), ...(value.ErrorCode !== undefined ? { error_code: value.ErrorCode } : {}) });\n });\n return goalOutput.parse({ account_id: input.account_id, date_range: input.date_range, rows: values, errors, not_returned_goal_ids: input.goal_ids.filter(goal => !values.some(value => value.GoalId === goal)), notes: [...notes, 'Missing summaries and per-goal errors are explicit; absence does not mean zero conversions. Error messages, details and event/customer fields are omitted.'] });\n }\n}\n\nexport function microsoftOfflineReportTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_offline_conversion_reports', namespace: 'microsoft', description: 'Read daily offline-conversion upload success/failure counts in an explicit UTC interval (tool bound: seven days). Preserves native dates/counts; omits signed file URLs and pilot event/customer records. Downloads and event ingestion are separate workflows.', input: accountInput, output: accountOutput, annotations: { readOnly: true }, handler: input => provider.offlineReports.daily(input) }),\n defineTool({ name: 'microsoft_offline_conversion_goal_report', namespace: 'microsoft', description: 'Read offline conversion attribution diagnostics for up to 20 unique account-available OfflineConversion goals and at most seven days in UTC. Native channel flags are optional CSV filters. Returns aggregate/daily ratios and counts, explicit per-goal errors and missing summaries; never infers zero for missing data.', input: goalInput, output: goalOutput, annotations: { readOnly: true }, handler: input => provider.offlineReports.goals(input) }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, guardedWriteTool, type AnyToolDefinition, type WriteOperation } from '@adport/core';\nimport { offlineAdjustments, offlineTimeTicks, offlineUpload } from './offline-conversion-schemas.js';\nimport { MicrosoftNativeService, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsClient, RequestScope } from './client.js';\nimport type { MicrosoftConversionService } from './conversions.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nexport const MICROSOFT_OFFLINE_CONVERSION_WRITES = new Set(['microsoft_upload_offline_conversions', 'microsoft_upload_offline_conversion_adjustments']);\nconst record = (value: unknown): value is Row => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : record(value) ? Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst wireFields = { microsoft_click_id: 'MicrosoftClickId', hashed_email_address: 'HashedEmailAddress', hashed_phone_number: 'HashedPhoneNumber', conversion_time: 'ConversionTime', conversion_value: 'ConversionValue', conversion_currency_code: 'ConversionCurrencyCode', external_attribution_credit: 'ExternalAttributionCredit', external_attribution_model: 'ExternalAttributionModel', adjustment_time: 'AdjustmentTime', adjustment_type: 'AdjustmentType', adjustment_value: 'AdjustmentValue', adjustment_currency_code: 'AdjustmentCurrencyCode' } as const;\nconst notes = [\n 'This is a local preview. Microsoft has no dry run for offline imports or adjustments; no event is sent until apply.',\n 'Events and adjustments can affect measured revenue, conversion counts and automated bidding. This tool preserves goal configuration, account auto-tagging, campaign status and budgets.',\n 'Wait two hours after creating a goal. Receipt acceptance does not prove matching, attribution or reporting; reporting can take six hours. Click time and conversion-window eligibility cannot be checked from these inputs.',\n 'Native deduplication retains the first original conversion for the same goal/click/time. Use a restatement or retraction to change a prior conversion. No global Adport event ledger or per-event readback is available.',\n 'Approval is single-attempt. Failed or unknown rows are never retried automatically; reconcile batch SHA-256, original row indexes and aggregate upload diagnostics before requesting another preview.',\n 'Private identifiers are omitted from previews, receipts and audit summaries. Full arguments are stored in the private pending approval; the agent applies them without copying them into the widget.',\n];\n\n/** PartialErrors is sparse and indexed into the request, not positional. No native messages/values are exposed. */\nfunction outcome(value: unknown, count: number) {\n const errors: Array<{ index: number; code: number }> = [];\n let unmapped = 0, verified = record(value) && Object.keys(value).every(key => key === 'PartialErrors');\n const partial = record(value) ? value.PartialErrors : undefined;\n if (partial !== undefined && partial !== null && !Array.isArray(partial)) verified = false;\n if (Array.isArray(partial)) {\n if (partial.length > 20_000) { verified = false;unmapped++; }\n for (const item of partial.slice(0, 20_000)) {\n if (item === null) continue;\n if (!record(item) || !Number.isInteger(item.Index) || Number(item.Index) < 0 || Number(item.Index) >= count || !Number.isSafeInteger(item.Code) || Number(item.Code) <= 0) { unmapped++;continue; }\n errors.push({ index: Number(item.Index), code: Number(item.Code) });\n }\n }\n const failed = new Set(errors.map(error => error.index));\n const rows = Array.from({ length: count }, (_, index) => ({ index, status: failed.has(index) ? 'FAILED' : verified && !unmapped ? 'ACCEPTED' : 'UNKNOWN' }));\n return { receipt_verified: verified && !unmapped, accepted_count: rows.filter(row => row.status === 'ACCEPTED').length, failed_count: failed.size, unknown_count: rows.filter(row => row.status === 'UNKNOWN').length, rows, errors, unmapped_error_count: unmapped };\n}\n\n/** Official MicrosoftDocs@5bde65c3 and BingAds Python REST SDK@4b6fb31c, refreshed2026-11-06. */\nexport class MicrosoftOfflineConversionService extends MicrosoftNativeService {\n constructor(client: MicrosoftAdsClient, scope: (account: string, refresh?: boolean) => Promise<RequestScope>, campaign: (account: string, campaign: string) => Promise<unknown>, private readonly conversions: MicrosoftConversionService) {\n super(client, scope, campaign);\n }\n\n async plan(op: WriteOperation): Promise<MicrosoftPlan> {\n const adjusting = op.tool === 'microsoft_upload_offline_conversion_adjustments';\n if (op.provider !== 'microsoft' || !MICROSOFT_OFFLINE_CONVERSION_WRITES.has(op.tool) || op.kind !== (adjusting ? 'update' : 'create')) throw new AdportError('INVALID_INPUT', 'microsoft: offline conversion operation provider/kind mismatch');\n const input = adjusting ? offlineAdjustments.parse(op.payload) : offlineUpload.parse(op.payload);\n const scope = await this.accountScope(op.accountId, true), current = await this.conversions.get(op.accountId, input.goal_id, 'OfflineConversion');\n if (current.snapshot_hash !== input.expected_goal_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: offline goal or auto-tagging configuration changed; read it and preview again');\n const goal = current.goal;\n if (goal.Type !== 'OfflineConversion' || !['Account', 'Customer'].includes(String(goal.Scope)) || !['Active', 'Paused'].includes(String(goal.Status)) || typeof goal.Name !== 'string' || !goal.Name.trim()) throw new AdportError('INVALID_INPUT', 'microsoft: an available Account/Customer offline goal with a concrete name and status is required');\n const source: Row[] = 'conversions' in input ? input.conversions : input.adjustments;\n const now = BigInt(Date.now()) * 10_000n, maxAge = 90n * 86400n * 10_000_000n, identities = new Set<string>();\n for (const row of source) {\n const time = offlineTimeTicks(String(row.conversion_time));\n if (time > now || time < now - maxAge) throw new AdportError('INVALID_INPUT', 'microsoft: original conversion times must be in UTC within the last90days and not in the future');\n if (adjusting && (offlineTimeTicks(String(row.adjustment_time)) < time || offlineTimeTicks(String(row.adjustment_time)) > now)) throw new AdportError('INVALID_INPUT', 'microsoft: adjustment time must be at/after the original conversion and not in the future');\n if ((row.hashed_email_address || row.hashed_phone_number) && goal.IsEnhancedConversionsEnabled !== true) throw new AdportError('INVALID_INPUT', 'microsoft: hashed identifiers require an already enabled enhanced-conversion goal; no setting or terms are changed');\n if ((row.external_attribution_credit !== undefined || row.external_attribution_model !== undefined) && goal.IsExternallyAttributed !== true) throw new AdportError('INVALID_INPUT', 'microsoft: external attribution fields require a verified externally attributed goal');\n const identity = digest({ time: time.toString(), ...(row.microsoft_click_id ? { click: row.microsoft_click_id } : { email: row.hashed_email_address, phone: row.hashed_phone_number }) });\n if (identities.has(identity)) throw new AdportError('INVALID_INPUT', 'microsoft: duplicate original conversion identities in this batch; submit at most one operation per original identity');\n identities.add(identity);\n }\n const bodyRows = source.map(row => ({ ConversionName: goal.Name, ...Object.fromEntries(Object.entries(row).map(([key, value]) => [wireFields[key as keyof typeof wireFields], value])) }));\n const path = adjusting ? 'OfflineConversionAdjustments/Apply' : 'OfflineConversions/Apply';\n const body = { [adjusting ? 'OfflineConversionAdjustments' : 'OfflineConversions']: bodyRows };\n const batchHash = digest({ account: op.accountId, path, body }), count = source.length;\n const valueRanges = new Map<string, { currency: string; records: number; minimum: number; maximum: number }>();\n for (const row of source) {\n const value = adjusting ? row.adjustment_value : row.conversion_value;\n if (typeof value !== 'number') continue;\n const currency = String((adjusting ? row.adjustment_currency_code : row.conversion_currency_code) ?? '(goal default)'), previous = valueRanges.get(currency);\n valueRanges.set(currency, { currency, records: (previous?.records ?? 0) + 1, minimum: Math.min(previous?.minimum ?? value, value), maximum: Math.max(previous?.maximum ?? value, value) });\n }\n const changes = [`${count} ${adjusting ? 'adjustments' : 'conversions'} for offline goal ${input.goal_id}.`, `Approved native batch SHA-256: ${batchHash}.`, adjusting ? 'Restatements replace recorded values; retractions remove previously recorded conversions. Original conversion time identifies the record; adjustment time records the adjustment.' : 'Omitted conversion value and currency use the goal revenue defaults. Values are whole currency units, not budget micros.'];\n const notices = [...notes, ...(goal.Status === 'Paused' ? ['This goal is Paused. It stays paused; receipt acceptance does not imply that these records will be counted.'] : []), ...(record(goal.Revenue) && goal.Revenue.Type === 'NoValue' ? ['Goal revenue is NoValue; supplying monetary values does not change the goal into a revenue-tracking goal.'] : []), ...(!current.auto_tagging_enabled ? ['Click-ID auto-tagging is disabled and remains disabled. An uploaded click ID must already identify a real native click.'] : [])];\n let details: unknown, warnings: string[] = [];\n return { summary: `${adjusting ? 'Adjust' : 'Import'} ${count} Microsoft offline conversion${count === 1 ? '' : 's'} · batch ${batchHash}`, changes, notes: notices, coercions: [], budgetDeltas: [],\n review: { provider: 'microsoft', accountId: op.accountId, kind: op.kind, title: adjusting ? 'Adjust offline conversions' : 'Import offline conversions', fields: [\n { label: 'Goal', after: `${goal.Name} [${input.goal_id}]` }, { label: 'Goal scope', after: goal.Scope }, { label: 'Goal status', after: goal.Status }, { label: 'Records', after: count },\n { label: 'Identifier matching', after: { click_ids: source.filter(row => row.microsoft_click_id).length, hashed_emails: source.filter(row => row.hashed_email_address).length, hashed_phones: source.filter(row => row.hashed_phone_number).length } },\n ...(adjusting ? [{ label: 'Adjustments', after: { restatements: source.filter(row => row.adjustment_type === 'Restate').length, retractions: source.filter(row => row.adjustment_type === 'Retract').length } }] : [{ label: 'Goal revenue defaults', after: goal.Revenue ?? 'Not reported' }]),\n { label: 'Explicit value ranges (whole currency units)', after: [...valueRanges.values()] },\n { label: 'Batch SHA-256', after: batchHash },\n ], notices }, resultDetails: () => details, resultWarnings: () => warnings,\n execute: async () => {\n let result: unknown;\n try { result = await this.client.request<unknown>('campaign', 'POST', path, body, scope, { privatePayload: true }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: offline batch outcome is unknown; private native response details were omitted. Reconcile upload diagnostics before another preview. No request was retried.', { batch_sha256: batchHash, target_goal_id: input.goal_id, record_count: count, ...outcome(null, count), processed: false }); }\n const receipt = outcome(result, count);\n details = { status: receipt.accepted_count ? 'ACCEPTED_FOR_PROCESSING' : 'PARTIAL_OR_UNCONFIRMED', receipt_status: receipt.accepted_count === count ? 'ALL_ACCEPTED' : receipt.unknown_count ? 'UNCONFIRMED' : 'PARTIAL', processed: false, account_id: op.accountId, target_goal_id: input.goal_id, batch_sha256: batchHash, record_count: count, ...receipt, next_tool: 'microsoft_offline_conversion_goal_report' };\n if (!receipt.accepted_count) throw new AdportError('PROVIDER_ERROR', 'microsoft: no offline records were confirmed accepted. Reconcile the returned row outcomes and native upload diagnostics; no automatic retry.', details);\n if (receipt.accepted_count < count) warnings = [`Microsoft accepted ${receipt.accepted_count} of ${count} rows for processing; ${receipt.failed_count} failed and ${receipt.unknown_count} remain unknown. Acceptance is not attribution. Inspect original row indexes before a new upload.`];\n // The API assigns no event IDs. This ID names the existing target goal only.\n return [input.goal_id];\n },\n };\n }\n}\n\nexport function microsoftOfflineConversionTools(_provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'measurement' as const, exposure: 'specialist' as const };\n return [\n guardedWriteTool({ name: 'microsoft_upload_offline_conversions', namespace: 'microsoft', provider: 'microsoft', catalog, kind: 'create', sensitiveInputs: ['conversions'], description: 'Import 1–1,000 offline conversions into an existing goal with expected_goal_hash. Local preview sends no events; apply returns sparse indexed failures and acceptance for processing, not attribution. Uses the current exact goal name, preserves its configuration and never retries. Already hashed identifiers require enhanced conversions to be enabled.', payload: offlineUpload }),\n guardedWriteTool({ name: 'microsoft_upload_offline_conversion_adjustments', namespace: 'microsoft', provider: 'microsoft', catalog, kind: 'update', sensitiveInputs: ['adjustments'], description: 'Restate or retract 1–1,000 previously imported offline conversions with expected_goal_hash. Original conversion_time identifies each record; adjustment_time records the adjustment. Local preview sends nothing. Returns indexed failures and processing acceptance; no automatic retry or per-event readback.', payload: offlineAdjustments }),\n ];\n}\n","import { z } from 'zod';\nimport { microsoftId } from './native.js';\n\n// Preserve Microsoft's dateTime precision (100ns) rather than truncating identities to JS milliseconds.\nexport const offlineTime = z.iso.datetime().regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,7})?Z$/, 'Use a UTC timestamp with seconds and at most seven fractional digits');\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst identifier = z.string().min(1).max(512).regex(/^[^\\s\\x00-\\x1f\\x7f]+$/);\nconst currency = z.string().regex(/^[A-Z]{3}$/);\nconst identity = z.object({\n microsoft_click_id: identifier.optional(),\n hashed_email_address: hash.optional(),\n hashed_phone_number: hash.optional(),\n conversion_time: offlineTime,\n}).strict();\nconst identified = (value: z.infer<typeof identity>) => !!(value.microsoft_click_id || value.hashed_email_address || value.hashed_phone_number);\nexport const offlineConversion = identity.extend({\n conversion_value: z.number().finite().optional(),\n conversion_currency_code: currency.optional(),\n external_attribution_credit: z.number().finite().gt(0).max(1).optional(),\n external_attribution_model: z.string().min(1).max(512).optional(),\n}).strict().refine(identified, 'Supply a Microsoft click ID or an already hashed email/phone identifier');\nconst adjustment = identity.extend({ adjustment_time: offlineTime });\nexport const offlineAdjustment = z.discriminatedUnion('adjustment_type', [\n adjustment.extend({ adjustment_type: z.literal('Restate'), adjustment_value: z.number().finite(), adjustment_currency_code: currency }).strict(),\n adjustment.extend({ adjustment_type: z.literal('Retract') }).strict(),\n]).refine(identified, 'Supply the original Microsoft click ID or already hashed email/phone identifiers');\nconst binding = z.object({\n goal_id: microsoftId,\n expected_goal_hash: hash,\n acknowledge_measurement_effects: z.literal(true),\n}).strict();\nexport const offlineUpload = binding.extend({ conversions: z.array(offlineConversion).min(1).max(1000) }).strict();\nexport const offlineAdjustments = binding.extend({ adjustments: z.array(offlineAdjustment).min(1).max(1000) }).strict();\n\nexport function offlineTimeTicks(value: string): bigint {\n const [whole, fraction = ''] = value.slice(0, -1).split('.');\n return BigInt(Date.parse(`${whole}Z`)) * 10_000n + BigInt(fraction.padEnd(7, '0'));\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type ReviewField, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { MicrosoftNativeService, microsoftNativeId as nativeId, microsoftRow as row, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport { criterionType, minutes, nativeTarget } from './targeting-schemas.js';\nimport { targetSelection, targetingRead, targetingWrite } from './general-targeting-schemas.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\ntype Target = z.infer<typeof targetSelection>;\ntype Kind = z.infer<typeof criterionType>;\nconst BOUND = 20_000;\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value)) ?? 'undefined').digest('hex');\nconst same = (a: unknown, b: unknown) => digest(a) === digest(b);\nconst pick = (value: Row, fields: string[]) => Object.fromEntries(fields.filter(field => Object.hasOwn(value, field)).map(field => [field, value[field]]));\nconst optionalRow = (value: unknown): Row => value === undefined || value === null ? {} : row(value);\nconst kind = (value: Row) => criterionType.parse(String(row(value.Criterion).Type).replace(/Criterion$/, ''));\nconst entityId = (target: Target) => target.type === 'Campaign' ? target.campaign_id : target.ad_group_id;\nconst geo = (value: Row) => ['Location', 'Radius'].includes(kind(value));\nfunction title(value: Row): string {\n const data = row(value.Criterion), type = kind(value), text = (field: string) => data[field] === undefined || data[field] === null ? 'Not reported' : String(data[field]);\n if (type === 'Device') return text('DeviceName');\n if (type === 'Location') return `Location ${text('LocationId')}`;\n if (type === 'Radius') return `${data.Name || 'Radius'} · ${text('Radius')} ${text('RadiusUnit')} · ${text('LatitudeDegrees')}, ${text('LongitudeDegrees')}`;\n if (type === 'Age') return text('AgeRange').replace(/([a-z])([A-Z])/g, '$1 $2');\n if (type === 'Gender') return text('GenderType');\n if (type === 'LocationIntent') return text('IntentOption').replace(/([a-z])([A-Z])/g, '$1 $2');\n const time = (end: boolean) => { const hour = data[end ? 'ToHour' : 'FromHour'], minute = data[end ? 'ToMinute' : 'FromMinute'];return typeof hour === 'number' && typeof minute === 'string' && Object.hasOwn(minutes, minute) ? `${String(hour).padStart(2, '0')}:${String(minutes[minute as keyof typeof minutes]).padStart(2, '0')}` : 'Not reported'; };\n return `${text('Day')} ${time(false)}–${time(true)}`;\n}\nconst identity = (value: Row) => {\n const fields: Record<Kind, string[]> = { Age: ['AgeRange'], Gender: ['GenderType'], Device: ['DeviceName'], DayTime: ['Day', 'FromHour', 'FromMinute', 'ToHour', 'ToMinute'], Location: ['LocationId'], LocationIntent: [], Radius: ['LatitudeDegrees', 'LongitudeDegrees', 'Radius', 'RadiusUnit'] };\n const criterion = row(value.Criterion);return digest({ type: kind(value), fields: fields[kind(value)].map(field => String(criterion[field] ?? '')) });\n};\nconst notices = ['Ad-group criteria override campaign criteria of the same type. Locations, negative locations and radii form one geo family: any ad-group geo criterion disables inheritance of ALL campaign geo criteria. Location intent alone does not change the geo source.', 'Device and schedule criteria override rather than combine with campaign settings. Removing the last ad-group criterion can restore inherited targeting; adding the first can broaden or narrow delivery.', 'BidMultiplier carries whole percentage points, not a ratio or currency micros. Automated bidding can treat it as a signal. Location intent has no bid. Criteria have native Active status without an independent pause.', 'A configuration hash detects observed changes before submission, not concurrent changes during a native request. Reads and preservation checks cover these seven criterion families and selected parent/account configuration, not every native targeting feature.'];\nexport const MICROSOFT_GENERAL_TARGETING_WRITES = new Set(['microsoft_update_targeting']);\n\n/** MicrosoftDocs@5bde65c3, BingAds REST SDK@4b6fb31c; one native mutation per approval. */\nexport class MicrosoftGeneralTargetingService extends MicrosoftNativeService {\n private async query(account: string, target: Target, type: Kind) {\n const prefix = target.type, result = await this.request(account, `${prefix}Criterions/QueryByIds`, { [`${prefix}Id`]: entityId(target), [`${prefix}CriterionIds`]: null, CriterionType: type });\n if (!Object.hasOwn(result, `${prefix}Criterions`)) throw new AdportError('PROVIDER_ERROR', 'microsoft: complete target criteria were not returned');\n const values = rows(result[`${prefix}Criterions`]);\n if (values.length > BOUND || new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => nativeId(value[`${prefix}Id`]) !== entityId(target) || kind(value) !== type || ![`Biddable${prefix}Criterion`, `Negative${prefix}Criterion`].includes(String(value.Type)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: targeting response identity, scope or safety bound mismatch');\n return values.filter(value => value.Status !== 'Deleted');\n }\n private async all(account: string, target: Target) {\n const values: Row[] = [];\n for (let i = 0; i < criterionType.options.length; i += 3) values.push(...(await Promise.all(criterionType.options.slice(i, i + 3).map(type => this.query(account, target, type)))).flat());\n if (values.length > BOUND || new Set(values.map(value => nativeId(value.Id))).size !== values.length) throw new AdportError('PROVIDER_ERROR', 'microsoft: targeting snapshot exceeds its bound or contains duplicate IDs');\n return values.sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1);\n }\n private async context(account: string, target: Target) {\n const scope = await this.accountScope(account, true), known = await this.campaign(account, target.campaign_id);\n const accountResult = await this.request(account, 'Account/Query', { AccountId: account }, 'POST', 'customer'), nativeAccount = row(accountResult.Account);\n if (nativeId(nativeAccount.Id) !== account || nativeId(nativeAccount.ParentCustomerId) !== scope.customerId) throw new AdportError('PROVIDER_ERROR', 'microsoft: account/timezone ownership could not be verified');\n const accountContext = pick(nativeAccount, ['Id', 'ParentCustomerId', 'CurrencyCode', 'TimeZone', 'AccountLifeCycleStatus']);\n const parents = rows((await this.request(account, 'Campaigns/QueryByIds', { AccountId: account, CampaignIds: [target.campaign_id], CampaignType: known.CampaignType, ReturnAdditionalFields: 'TargetSetting, AdScheduleUseSearcherTimeZone' })).Campaigns);\n if (parents.length !== 1 || nativeId(parents[0]!.Id) !== target.campaign_id || parents[0]!.CampaignType !== known.CampaignType || !['Active', 'Paused'].includes(String(parents[0]!.Status))) throw new AdportError('INVALID_INPUT', 'microsoft: campaign context is unavailable or mismatched');\n const campaign = pick(parents[0]!, ['Id', 'Name', 'Status', 'CampaignType', 'SubType', 'DailyBudget', 'BudgetType', 'BudgetId', 'BiddingScheme', 'ExperimentId', 'Settings', 'AdScheduleUseSearcherTimeZone']);\n let group: Row | undefined;\n if (target.type === 'AdGroup') {\n if (campaign.CampaignType === 'PerformanceMax') throw new AdportError('INVALID_INPUT', 'microsoft: Performance Max has asset groups, not ordinary ad-group targeting');\n const groups = rows((await this.request(account, 'AdGroups/QueryByIds', { CampaignId: target.campaign_id, AdGroupIds: [target.ad_group_id], ReturnAdditionalFields: 'AdGroupType, AdScheduleUseSearcherTimeZone' })).AdGroups);\n if (groups.length !== 1 || nativeId(groups[0]!.Id) !== target.ad_group_id || !['Active', 'Paused'].includes(String(groups[0]!.Status))) throw new AdportError('INVALID_INPUT', 'microsoft: ad group was not found in the selected campaign/account');\n group = pick(groups[0]!, ['Id', 'Name', 'Status', 'AdGroupType', 'Language', 'CpcBid', 'CpmBid', 'CpvBid', 'BiddingScheme', 'StartDate', 'EndDate', 'Settings', 'AdScheduleUseSearcherTimeZone']);\n }\n const campaignCriteria = await this.all(account, { type: 'Campaign', campaign_id: target.campaign_id }), ownCriteria = target.type === 'AdGroup' ? await this.all(account, target) : campaignCriteria;\n const data = { account_id: account, target, account: accountContext, campaign, group, campaignCriteria, ownCriteria };\n return { ...data, context_hash: digest(data) };\n }\n private inherited(context: Awaited<ReturnType<MicrosoftGeneralTargetingService['context']>>, own = context.ownCriteria) {\n return Object.fromEntries(criterionType.options.map(type => {\n const useOwn = context.target.type === 'Campaign' || (['Location', 'Radius', 'LocationIntent'].includes(type) ? own.some(geo) : own.some(value => kind(value) === type));\n const source = useOwn ? context.target.type : 'Campaign', selected = useOwn ? own : context.campaignCriteria;\n return [type, { source, criterion_count: selected.filter(value => kind(value) === type).length }];\n }));\n }\n private clock(context: Awaited<ReturnType<MicrosoftGeneralTargetingService['context']>>, own = context.ownCriteria) {\n const source = this.inherited(context, own).DayTime!.source, parent = source === 'AdGroup' ? context.group! : context.campaign, flag = parent.AdScheduleUseSearcherTimeZone;\n return { source, use_searcher_time_zone: typeof flag === 'boolean' ? flag : null, timezone: flag === true ? 'Searcher local time' : flag === false ? context.account.TimeZone ?? 'Account time zone not reported' : 'Schedule clock not reported' };\n }\n private geography(context: Awaited<ReturnType<MicrosoftGeneralTargetingService['context']>>, own = context.ownCriteria) {\n const source = this.inherited(context, own).Location!.source, selected = source === context.target.type ? own : context.campaignCriteria, included = selected.filter(value => kind(value) === 'Location' && String(value.Type).startsWith('Biddable')), excluded = selected.filter(value => kind(value) === 'Location' && String(value.Type).startsWith('Negative')), radii = selected.filter(value => kind(value) === 'Radius');\n return { source, included_location_count: included.length, excluded_location_count: excluded.length, radius_count: radii.length, included_location_ids: included.slice(0, 20).map(value => row(value.Criterion).LocationId), ids_truncated: included.length > 20, ...(!included.length && !radii.length ? { reach: 'No positive location/radius restriction; exclusions and native campaign eligibility still apply.' } : {}) };\n }\n async list(raw: z.input<typeof targetingRead>) {\n const input = targetingRead.parse(raw), context = await this.context(input.account_id, input.target), types = [...input.criterion_types].sort(), visible = [...context.ownCriteria.map(criterion => ({ source: input.target.type, criterion })), ...(input.target.type === 'AdGroup' ? context.campaignCriteria.map(criterion => ({ source: 'Campaign' as const, criterion })) : [])].filter(value => input.criterion_types.includes(kind(value.criterion)));\n let offset = 0;\n if (input.cursor) try {\n const cursor = z.object({ account: z.string(), target: targetSelection, hash: z.string(), types: z.array(z.string()), size: z.number().int().positive(), offset: z.number().int().positive() }).strict().parse(JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8')));\n if (cursor.account !== input.account_id || !same(cursor.target, input.target) || cursor.hash !== context.context_hash || !same(cursor.types, types) || cursor.size !== input.page_size || cursor.offset >= visible.length || cursor.offset % cursor.size) throw new Error('Selection changed');offset = cursor.offset;\n } catch { throw new AdportError('PENDING_MISMATCH', 'microsoft: targeting continuation is stale or belongs to another selection; refresh the first page'); }\n const inheritance = this.inherited(context), page = visible.slice(offset, offset + input.page_size), end = offset + page.length;\n return { account_id: input.account_id, target: input.target, context_hash: context.context_hash, account: context.account, campaign: context.campaign, ad_group: context.group, inheritance, schedule_clock: this.clock(context), total_criteria: visible.length, criteria: page,\n records: page.map(({ source, criterion }) => { const type = kind(criterion), bid = optionalRow(criterion.CriterionBid).Multiplier, selected = inheritance[type]!.source === source, hasGeo = inheritance.Location!.criterion_count + inheritance.Radius!.criterion_count > 0;return { id: `${source}:${nativeId(criterion.Id)}`, criterion_id: nativeId(criterion.Id), kind: type, name: title(criterion), source, effective: selected && (type !== 'LocationIntent' || hasGeo), status: criterion.Status ?? 'Not reported', bid_adjustment: typeof bid === 'number' ? `${bid}%${type === 'Device' && bid === -100 ? ' · device excluded' : ''}` : type === 'LocationIntent' || String(criterion.Type).startsWith('Negative') ? 'Not applicable' : 'Not reported' }; }),\n truncated: end < visible.length, ...(end < visible.length ? { next_cursor: Buffer.from(JSON.stringify({ account: input.account_id, target: input.target, hash: context.context_hash, types, size: input.page_size, offset: end })).toString('base64url') } : {}), notes: [...notices, 'Both owned and campaign criteria are shown. Effective identifies the selected source, not eligibility or delivery; false marks overridden/inapplicable rows. Intent without geographic criteria is inapplicable. Only owned IDs can be edited at the selected scope.'] };\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n if (op.tool !== 'microsoft_update_targeting' || op.provider !== 'microsoft' || op.kind !== 'update') throw new AdportError('INVALID_INPUT', 'microsoft: scoped targeting operation provider/kind mismatch');\n const input = targetingWrite.parse(op.payload), before = await this.context(op.accountId, input.target), change = input.change, prefix = input.target.type, parentKey = `${prefix}Id`, selectedParent = before.group ?? before.campaign;\n if (before.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: targeting, inheritance or parent/account configuration changed; read and preview again');\n let method: 'POST' | 'PUT' | 'DELETE' = 'PUT', path = `${prefix}Criterions`, body: Row = {}, creates: Row[] = [], removed: string[] = [], updated: Row | undefined, clock: boolean | undefined;\n const selected = (id: string) => { const found = before.ownCriteria.find(value => nativeId(value.Id) === id);if (!found) throw new AdportError('INVALID_INPUT', 'microsoft: criterion is not owned by the selected entity; inherited criterion IDs cannot be edited here');return found; };\n if (change.action === 'add') {\n if (guard.forcePausedCreation && before.campaign.Status !== 'Paused' && before.group?.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: new targets are natively Active; paused_creation requires an effectively paused parent');\n creates = change.targets.map(value => nativeTarget({ [parentKey]: entityId(input.target) }, value));\n const seen = new Set(before.ownCriteria.map(identity));\n for (const value of creates) { if (seen.has(identity(value))) throw new AdportError('INVALID_INPUT', 'microsoft: target already exists or is duplicated in this request; use an explicit edit');seen.add(identity(value)); }\n method = 'POST';body = { [`${prefix}Criterions`]: creates, CriterionType: 'Targets' };\n } else if (change.action === 'remove') {\n removed = change.criterion_ids;const values = removed.map(selected);\n if (values.some(value => kind(value) === 'LocationIntent')) throw new AdportError('INVALID_INPUT', 'microsoft: location intent cannot be deleted; restore its default with set_location_intent');\n if (values.some(value => kind(value) === 'Device') && before.ownCriteria.some(value => kind(value) === 'Device' && !removed.includes(nativeId(value.Id)))) throw new AdportError('INVALID_INPUT', 'microsoft: remove the complete device set together');\n method = 'DELETE';body = { [parentKey]: entityId(input.target), [`${prefix}CriterionIds`]: removed, CriterionType: 'Targets' };\n } else if (change.action === 'set_schedule_clock') {\n if (selectedParent.AdScheduleUseSearcherTimeZone === change.use_searcher_time_zone) throw new AdportError('INVALID_INPUT', 'microsoft: schedule clock already has this value');clock = change.use_searcher_time_zone;\n path = prefix === 'Campaign' ? 'Campaigns' : 'AdGroups';body = { [prefix === 'Campaign' ? 'AccountId' : 'CampaignId']: prefix === 'Campaign' ? op.accountId : input.target.campaign_id, [path]: [{ Id: entityId(input.target), AdScheduleUseSearcherTimeZone: clock }] };\n } else {\n const current = selected(change.criterion_id), type = kind(current);\n if (current.Type !== `Biddable${prefix}Criterion`) throw new AdportError('INVALID_INPUT', 'microsoft: excluded targets cannot have a bid or intent edit');\n updated = { ...current };\n if (change.action === 'set_bid') {\n const bid = optionalRow(current.CriterionBid);\n if (type !== change.criterion_type || bid.Type !== 'BidMultiplier' || typeof bid.Multiplier !== 'number' || !Number.isFinite(bid.Multiplier)) throw new AdportError('INVALID_INPUT', 'microsoft: owned biddable criterion with a verified native percentage is required');\n if (bid.Multiplier === change.bid_adjustment_percent) throw new AdportError('INVALID_INPUT', 'microsoft: bid adjustment is unchanged');updated.CriterionBid = { Type: 'BidMultiplier', Multiplier: change.bid_adjustment_percent };\n body = { [`${prefix}Criterions`]: [{ [parentKey]: entityId(input.target), Id: change.criterion_id, Type: current.Type, CriterionBid: updated.CriterionBid }], CriterionType: 'Targets' };\n } else {\n if (type !== 'LocationIntent') throw new AdportError('INVALID_INPUT', 'microsoft: location intent requires its exact criterion ID');if (row(current.Criterion).IntentOption === change.intent_option) throw new AdportError('INVALID_INPUT', 'microsoft: location intent is unchanged');updated.Criterion = { ...row(current.Criterion), IntentOption: change.intent_option };\n body = { [`${prefix}Criterions`]: [{ [parentKey]: entityId(input.target), Id: change.criterion_id, Type: current.Type, Criterion: updated.Criterion }], CriterionType: 'Targets' };\n }\n }\n const afterOwn = [...before.ownCriteria.filter(value => !removed.includes(nativeId(value.Id))).map(value => updated && nativeId(updated.Id) === nativeId(value.Id) ? updated : value), ...creates];\n const touched = new Set<Kind>([...creates.map(kind), ...before.ownCriteria.filter(value => removed.includes(nativeId(value.Id))).map(kind), ...(updated ? [kind(updated)] : [])]);\n this.validateResultingCriteria(afterOwn, touched);\n const touchesSchedule = clock !== undefined || creates.some(value => kind(value) === 'DayTime') || before.ownCriteria.some(value => removed.includes(nativeId(value.Id)) && kind(value) === 'DayTime');\n if (touchesSchedule && (clock ?? selectedParent.AdScheduleUseSearcherTimeZone) !== true && (typeof (clock ?? selectedParent.AdScheduleUseSearcherTimeZone) !== 'boolean' || typeof before.account.TimeZone !== 'string' || !before.account.TimeZone)) throw new AdportError('INVALID_INPUT', 'microsoft: schedule clock/account time zone is not verified; set an explicit clock and read fresh context');\n const projected = { ...before, campaign: { ...before.campaign, ...(prefix === 'Campaign' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) }, group: before.group ? { ...before.group, ...(prefix === 'AdGroup' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) } : undefined };\n const effectiveBefore = this.inherited(before), effectiveAfter = this.inherited(before, afterOwn), fields: ReviewField[] = [{ label: 'Campaign', after: `${before.campaign.Name ?? 'Not reported'} [${input.target.campaign_id}]` }, ...(before.group ? [{ label: 'Ad group', after: `${before.group.Name ?? 'Not reported'} [${entityId(input.target)}]` }] : []), { label: 'Scope', after: input.target }, { label: 'Campaign status', after: before.campaign.Status }, ...(before.group ? [{ label: 'Ad group status', after: before.group.Status }] : []), { label: 'Change', after: change }, { label: 'Effective targeting', before: effectiveBefore, after: effectiveAfter }, { label: 'Geographic reach', before: this.geography(before), after: this.geography(before, afterOwn) }, { label: 'Schedule clock', before: this.clock(before), after: this.clock(projected, afterOwn) }, ...(clock !== undefined ? [{ label: 'Use searcher timezone', before: selectedParent.AdScheduleUseSearcherTimeZone ?? 'Not reported', after: clock }] : [])];\n let details: unknown;const known = new Set<string>([...removed, ...(updated ? [nativeId(updated.Id)] : []), ...(clock !== undefined ? [entityId(input.target)] : [])]);\n return { summary: `Update Microsoft ${prefix} targeting · ${change.action}`, changes: [`${method} ${path}; only approved target fields are submitted.`, `${creates.length} additions, ${removed.length} removals, ${updated ? 1 : 0} criterion updates.`, 'Other returned criteria and parent statuses/budgets/settings are preserved. Immutable schedule intervals require separate reviewed remove/add operations; pause delivery before a multi-step replacement.'], coercions: [], budgetDeltas: [], notes: notices, review: { provider: 'microsoft', accountId: op.accountId, kind: 'update', title: 'Update targeting', fields, notices }, resultDetails: () => details,\n execute: async () => {\n try {\n const result = await this.request(op.accountId, path, body, method), acknowledged = result[`${prefix}CriterionIds`];\n if (Array.isArray(acknowledged)) for (const id of acknowledged) try { known.add(nativeId(id)); } catch { /* Retain the other acknowledged IDs. */ }\n const createdIds = method === 'POST' ? rowsOfIds(acknowledged) : [];\n if (method === 'POST' && (createdIds.length !== creates.length || new Set(createdIds).size !== createdIds.length || createdIds.some(id => before.ownCriteria.some(value => nativeId(value.Id) === id)))) throw new Error('Creation receipt mismatch');\n const after = await this.context(op.accountId, input.target), expectedCampaign = { ...before.campaign, ...(prefix === 'Campaign' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) }, expectedGroup = before.group ? { ...before.group, ...(prefix === 'AdGroup' && clock !== undefined ? { AdScheduleUseSearcherTimeZone: clock } : {}) } : undefined;\n if (!same(after.account, before.account) || !same(after.campaign, expectedCampaign) || !same(after.group, expectedGroup) || prefix === 'AdGroup' && !same(after.campaignCriteria, before.campaignCriteria)) throw new Error('Parent preservation mismatch');\n const expectedIds = new Set([...before.ownCriteria.filter(value => !removed.includes(nativeId(value.Id))).map(value => nativeId(value.Id)), ...createdIds]);\n if (after.ownCriteria.length !== expectedIds.size || after.ownCriteria.some(value => !expectedIds.has(nativeId(value.Id)))) throw new Error('Criterion inventory mismatch');\n for (const previous of before.ownCriteria) {\n if (removed.includes(nativeId(previous.Id))) continue;\n const observed = after.ownCriteria.find(value => nativeId(value.Id) === nativeId(previous.Id)), expected = updated && nativeId(updated.Id) === nativeId(previous.Id) ? updated : previous;\n if (!same(observed, expected)) throw new Error('Criterion preservation mismatch');\n }\n for (let i = 0; i < creates.length; i++) { const observed = after.ownCriteria.find(value => nativeId(value.Id) === createdIds[i]);if (!observed || !contains(observed, creates[i]!)) throw new Error('Created criterion mismatch'); }\n details = { snapshot_hash: after.context_hash, created_criterion_ids: createdIds, removed_criterion_ids: removed, updated_criterion_ids: updated ? [nativeId(updated.Id)] : [], independent_readback_verified: true, inheritance: this.inherited(after), schedule_clock: this.clock(after) };return [...known];\n } catch (error) {\n if (error instanceof AdportError && error.details && typeof error.details === 'object' && Array.isArray((error.details as Row).resourceIds)) for (const id of (error.details as Row).resourceIds as unknown[]) try { known.add(nativeId(id)); } catch { /* Ignore invalid IDs. */ }\n throw new AdportError('PROVIDER_ERROR', 'microsoft: targeting outcome was not confirmed. Reconcile known IDs and current configuration before another mutation; no write was retried.', { resourceIds: [...known] });\n }\n },\n };\n }\n private validateResultingCriteria(values: Row[], touched: Set<Kind>) {\n const devices = values.filter(value => kind(value) === 'Device');\n if (touched.has('Device') && devices.length && (devices.length !== 3 || !['Computers', 'Smartphones', 'Tablets'].every(name => devices.some(value => row(value.Criterion).DeviceName === name)) || devices.some(value => !String(value.Type).startsWith('Biddable') || optionalRow(value.CriterionBid).Type !== 'BidMultiplier' || typeof optionalRow(value.CriterionBid).Multiplier !== 'number') || devices.every(value => optionalRow(value.CriterionBid).Multiplier === -100))) throw new AdportError('INVALID_INPUT', 'microsoft: targeting requires a complete supported three-device set with at least one device included');\n const schedule = values.filter(value => kind(value) === 'DayTime').map(value => row(value.Criterion));\n if (touched.has('DayTime') && schedule.length > 49) throw new AdportError('INVALID_INPUT', 'microsoft: maximum49weekly schedules');\n const number = (value: Row, end: boolean) => { const hour = value[end ? 'ToHour' : 'FromHour'], minute = value[end ? 'ToMinute' : 'FromMinute'];if (typeof hour !== 'number' || !Number.isInteger(hour) || typeof minute !== 'string' || !Object.hasOwn(minutes, minute)) throw new AdportError('PROVIDER_ERROR', 'microsoft: native schedule interval is incomplete');return hour * 60 + minutes[minute as keyof typeof minutes]; };\n if (touched.has('DayTime')) for (const day of new Set(schedule.map(value => value.Day))) { const entries = schedule.filter(value => value.Day === day).sort((a, b) => number(a, false) - number(b, false));if (entries.length > 7 || entries.some((value, index) => number(value, true) <= number(value, false) || index > 0 && number(value, false) < number(entries[index - 1]!, true))) throw new AdportError('INVALID_INPUT', 'microsoft: schedules must not overlap or exceed seven per day'); }\n if (touched.has('Location') && values.filter(value => kind(value) === 'Location').length > 10_000) throw new AdportError('INVALID_INPUT', 'microsoft: combined included/excluded locations exceed10000');\n }\n}\nfunction rowsOfIds(value: unknown): string[] { if (!Array.isArray(value)) return [];return value.map(nativeId); }\nfunction contains(actual: Row, expected: Row): boolean { return Object.entries(expected).every(([key, value]) => value && typeof value === 'object' && !Array.isArray(value) ? actual[key] && typeof actual[key] === 'object' && contains(row(actual[key]), row(value)) : key === 'Type' ? String(actual[key]).replace(/Criterion$/, '') === String(value).replace(/Criterion$/, '') : String(actual[key]) === String(value)); }\nexport function microsoftGeneralTargetingTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'audiences' as const, exposure: 'specialist' as const };\n return [\n defineTool({ name: 'microsoft_targeting_context', namespace: 'microsoft', catalog, description: 'Read owned and inherited campaign/ad-group general targets, effective sources, schedule clock and context_hash. Seven concrete types, complete bounded context and stable paging; bid values are percentages. This is not audience targeting or every native targeting family.', input: targetingRead, presentation: 'records', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: input => provider.generalTargeting.list(input) }),\n guardedWriteTool({ name: 'microsoft_update_targeting', namespace: 'microsoft', provider: 'microsoft', catalog, kind: 'update', description: 'Edit scoped targeting with expected_context_hash and delivery-effects acknowledgement. One native add, remove, bid, location-intent or schedule-clock operation per approval. Preserves unmentioned criteria/status/budgets; checks inheritance, full devices and schedule limits. New criteria require an effectively paused parent under paused_creation.', payload: targetingWrite }),\n ];\n}\n","import { z } from 'zod';\nimport { microsoftId as id } from './native.js';\nimport { bidType, criterionType, deviceAdjustment, intent, target, validateTargetBatch } from './targeting-schemas.js';\n\nexport const targetSelection = z.discriminatedUnion('type', [z.object({ type: z.literal('Campaign'), campaign_id: id }).strict(), z.object({ type: z.literal('AdGroup'), campaign_id: id, ad_group_id: id }).strict()]);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const targetingRead = z.object({ account_id: id, target: targetSelection, criterion_types: z.array(criterionType).min(1).max(7).refine(values => new Set(values).size === values.length, 'Use unique types').default([...criterionType.options]), page_size: z.number().int().min(1).max(200).default(50), cursor: z.string().max(2048).optional() }).strict();\nconst change = z.discriminatedUnion('action', [\n z.object({ action: z.literal('add'), targets: z.array(target).min(1).max(1000) }).strict().superRefine(validateTargetBatch),\n z.object({ action: z.literal('set_bid'), criterion_id: id, criterion_type: bidType, bid_adjustment_percent: deviceAdjustment }).strict().refine(value => value.criterion_type === 'Device' || value.bid_adjustment_percent >= -90, 'Only devices support adjustments below -90 percent'),\n z.object({ action: z.literal('remove'), criterion_ids: z.array(id).min(1).max(1000).refine(values => new Set(values).size === values.length, 'Use unique IDs') }).strict(),\n z.object({ action: z.literal('set_location_intent'), criterion_id: id, intent_option: intent }).strict(),\n z.object({ action: z.literal('set_schedule_clock'), use_searcher_time_zone: z.boolean() }).strict(),\n]);\nexport const targetingWrite = z.object({ target: targetSelection, expected_context_hash: hash, acknowledge_delivery_effects: z.literal(true), change }).strict();\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { MicrosoftNativeService, microsoftId as id, microsoftNativeId as nativeId, microsoftRows as rows, type MicrosoftPlan, type MicrosoftRow as Row } from './native.js';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), name = z.string().min(1).max(128).refine(value => value.trim().length > 0, 'Name cannot be blank');\nconst date = z.iso.date(), split = z.number().int().min(1).max(99);\nconst create = z.object({ base_campaign_id: id, expected_base_context_hash: hash, name, start_date: date, end_date: date.optional(), traffic_split_percent: split, experiment_type: z.enum(['TrafficBased', 'CookieBased']).default('TrafficBased') }).refine(value => !value.end_date || value.start_date <= value.end_date, 'End date must be on or after start date');\nconst reference = z.object({ experiment_id: id, expected_snapshot_hash: hash });\nconst update = reference.extend({ name: name.optional(), start_date: date.optional(), end_date: date.nullable().optional(), traffic_split_percent: split.optional() }).refine(value => ['name', 'start_date', 'end_date', 'traffic_split_percent'].some(key => value[key as keyof typeof value] !== undefined), 'Supply an editable experiment field');\nconst additional = 'ExperimentSubType, ExperimentArms, ExperimentCampaignType';\nconst notes = ['Microsoft copies eligible base-campaign settings and child entities into an experiment campaign. Expired ad groups, legacy ad formats and some legacy keyword/audience settings are not copied; native copy diagnostics can report omissions.', 'The experiment campaign inherits the base budget, BudgetType, status and timezone. TrafficSplitPercent divides the existing base budget/traffic; the branch is not an additional independent daily pool. Pause or change budget through the base campaign.', 'Dates are calendar dates in the base campaign timezone; end dates are inclusive. Setup is asynchronous. A returned experiment ID or Creating status does not prove the campaign copy is ready.', 'Snapshots cover the experiment and parent/branch campaign configuration plus the visible active experiment inventory, not every child entity. Microsoft provides no atomic compare-and-set; external changes can race submission.'];\nconst contextSchema = z.object({ account_id: id, base_campaign: z.record(z.string(), z.unknown()), active_experiments: z.array(z.record(z.string(), z.unknown())), currency: z.string().optional(), snapshot_hash: hash });\nconst viewSchema = z.object({ account_id: id, experiment: z.record(z.string(), z.unknown()), base_context: contextSchema, experiment_campaign: z.record(z.string(), z.unknown()).optional(), snapshot_hash: hash, notes: z.array(z.string()) });\ntype Context = z.infer<typeof contextSchema>;\nfunction canonical(value: unknown): unknown { return Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, canonical(value)])) : value; }\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst optionalId = (value: unknown) => value === null || value === undefined || value === '0' || value === 0 ? undefined : nativeId(value);\nfunction nativeDate(value: string): Row { const [Year, Month, Day] = value.split('-').map(Number); return { Day, Month, Year }; }\nfunction calendarDate(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n const row = z.object({ Year: z.number().int(), Month: z.number().int(), Day: z.number().int() }).parse(value);\n if (row.Year === 0 && row.Month === 0 && row.Day === 0) return undefined;\n return date.parse(`${String(row.Year).padStart(4, '0')}-${String(row.Month).padStart(2, '0')}-${String(row.Day).padStart(2, '0')}`);\n}\nconst micros = (value: unknown) => { if (typeof value !== 'number' || value <= 0 || !Number.isSafeInteger(Math.round(value * 1_000_000)) || Math.abs(value * 1_000_000 - Math.round(value * 1_000_000)) > 0.000001) throw new AdportError('PROVIDER_ERROR', 'microsoft: base campaign daily budget cannot be represented safely in micros'); return Math.round(value * 1_000_000); };\nexport const MICROSOFT_EXPERIMENT_WRITES = new Set(['microsoft_create_experiment', 'microsoft_update_experiment', 'microsoft_end_experiment', 'microsoft_delete_experiment']);\n\n/** Native v13 experiments: Active is the required setup input, not an independently pausable branch status. */\nexport class MicrosoftExperimentService extends MicrosoftNativeService {\n constructor(...args: [...ConstructorParameters<typeof MicrosoftNativeService>, (account: string) => Promise<unknown>, (account: string) => Promise<string | undefined>]) {\n const [client, scope, campaign, campaigns, currency] = args; super(client, scope, campaign); this.campaigns = campaigns; this.currency = currency;\n }\n private readonly campaigns: (account: string) => Promise<unknown>;\n private readonly currency: (account: string) => Promise<string | undefined>;\n\n private async query(account: string, ids: string[] | null): Promise<Row[]> {\n const result = await this.request(account, 'Experiments/QueryByIds', { ExperimentIds: ids, ReturnAdditionalFields: additional });\n if (!Object.hasOwn(result, 'Experiments') || result.Experiments !== null && !Array.isArray(result.Experiments)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment response envelope is missing or malformed');\n const values = rows((result.Experiments as unknown[] | null)?.filter(value => value !== null));\n if (new Set(values.map(value => nativeId(value.Id))).size !== values.length || values.some(value => ids && !ids.includes(nativeId(value.Id)))) throw new AdportError('PROVIDER_ERROR', 'microsoft: duplicate or unexpected experiment identities');\n return values;\n }\n\n private async campaignById(account: string, campaignId: string, type: unknown): Promise<Row | undefined> {\n const result = await this.request(account, 'Campaigns/QueryByIds', { AccountId: account, CampaignIds: [campaignId], CampaignType: type, ReturnAdditionalFields: 'TargetSetting' });\n if (!Object.hasOwn(result, 'Campaigns') || result.Campaigns !== null && !Array.isArray(result.Campaigns)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment campaign response envelope is missing');\n const campaigns = rows((result.Campaigns as unknown[] | null)?.filter(value => value !== null));\n if (campaigns.length > 1 || campaigns.some(value => nativeId(value.Id) !== campaignId || value.CampaignType !== type)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment campaign identity/type mismatch');\n return campaigns[0];\n }\n\n async base(account: string, campaignId: string, refresh = false): Promise<Context> {\n await this.accountScope(account, refresh);\n const known = await this.campaign(account, campaignId), base = await this.campaignById(account, campaignId, known.CampaignType);\n if (!base || typeof base.Name !== 'string' || typeof base.Status !== 'string' || typeof base.TimeZone !== 'string') throw new AdportError('PROVIDER_ERROR', 'microsoft: base campaign configuration is incomplete');\n const active = (await this.query(account, null)).filter(value => nativeId(value.BaseCampaignId) === campaignId).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), currency = await this.currency(account);\n const visible = { account_id: account, base_campaign: base, active_experiments: active, ...(currency ? { currency } : {}) };\n return { ...visible, snapshot_hash: digest(visible) };\n }\n\n async list(input: { account_id: string; after_experiment_id?: string; limit: number }) {\n const remaining = (await this.query(input.account_id, null)).filter(value => !input.after_experiment_id || BigInt(nativeId(value.Id)) > BigInt(input.after_experiment_id)).sort((a, b) => BigInt(nativeId(a.Id)) < BigInt(nativeId(b.Id)) ? -1 : 1), page = remaining.slice(0, input.limit), truncated = remaining.length > page.length;\n return { rows: page, truncated, ...(truncated ? { next_cursor: nativeId(page.at(-1)!.Id) } : {}), visibility: 'Native active inventory only; use microsoft_get_experiment for an exact known historical ID.', notes };\n }\n\n async get(account: string, experimentId: string, refresh = false) {\n await this.accountScope(account, refresh);\n const values = await this.query(account, [experimentId]), experiment = values[0];\n if (!experiment) throw new AdportError('INVALID_INPUT', 'microsoft: experiment was not found in the selected account');\n const context = await this.base(account, nativeId(experiment.BaseCampaignId)), branchId = optionalId(experiment.ExperimentCampaignId), branch = branchId ? await this.campaignById(account, branchId, context.base_campaign.CampaignType) : undefined;\n if (branchId && (!branch || optionalId(branch.ExperimentId) !== experimentId)) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment campaign ownership could not be verified');\n const visible = { account_id: account, experiment, base_context: context, ...(branch ? { experiment_campaign: branch } : {}) };\n return { ...visible, snapshot_hash: digest(visible), notes };\n }\n\n private eligible(context: Context) {\n const base = context.base_campaign;\n if (!['Audience', 'Search', 'Shopping', 'PerformanceMax'].includes(String(base.CampaignType)) || optionalId(base.ExperimentId) || !Object.hasOwn(base, 'ExperimentId') || optionalId(base.BudgetId) || base.SubType !== undefined && base.SubType !== null && base.SubType !== '' || rows(base.Settings).some(value => /dynamicsearch/i.test(String(value.Type)))) throw new AdportError('INVALID_INPUT', 'microsoft: experiments require a verified non-experiment base without shared budgets, Dynamic Search Ads, mixed or other specialized subtypes');\n if (base.BudgetType !== 'DailyBudgetStandard') throw new AdportError('INVALID_INPUT', 'microsoft: experiment base must use DailyBudgetStandard');\n micros(base.DailyBudget);\n }\n\n private budget(context: Context) {\n const value = micros(context.base_campaign.DailyBudget);\n return [{ target: `base campaign ${nativeId(context.base_campaign.Id)} inherited total daily pool (split, not additional)`, ...(context.currency ? { currency: context.currency } : {}), fromMicros: value, toMicros: value }];\n }\n\n private async unique(account: string, value: string, exceptExperiment?: string, exceptCampaign?: string) {\n const campaigns = rows(await this.campaigns(account)), experiments = await this.query(account, null);\n if (campaigns.some(row => nativeId(row.Id) !== exceptCampaign && typeof row.Name === 'string' && row.Name.toLowerCase() === value.toLowerCase()) || experiments.some(row => nativeId(row.Id) !== exceptExperiment && typeof row.Name === 'string' && row.Name.toLowerCase() === value.toLowerCase())) throw new AdportError('INVALID_INPUT', 'microsoft: experiment name conflicts with a visible campaign or experiment');\n }\n\n private interval(context: Context, start: string, end?: string, except?: string) {\n if (context.active_experiments.some(value => {\n if (nativeId(value.Id) === except) return false;\n const from = calendarDate(value.StartDate), to = calendarDate(value.EndDate) ?? '9999-12-31';\n return !from || start <= to && from <= (end ?? '9999-12-31');\n })) throw new AdportError('INVALID_INPUT', 'microsoft: experiment date range overlaps the visible active inventory or an existing range is unverifiable');\n }\n\n private async confirmed(ids: string[], verify: () => Promise<boolean>): Promise<string[]> {\n try { if (!await verify()) throw new Error('Native readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment write was accepted but its readback is unconfirmed; reconcile these IDs before retrying', { resourceIds: ids }); }\n return ids;\n }\n\n private async removedAfterDelete(account: string, kind: 'experiment' | 'campaign', targetId: string, campaignType?: unknown): Promise<boolean> {\n const experiment = kind === 'experiment', collection = experiment ? 'Experiments' : 'Campaigns';\n const result = await this.client.request<Row>('campaign', 'POST', `${collection}/QueryByIds`, experiment\n ? { ExperimentIds: [targetId], ReturnAdditionalFields: additional }\n : { AccountId: account, CampaignIds: [targetId], CampaignType: campaignType, ReturnAdditionalFields: 'TargetSetting' }, await this.accountScope(account));\n const values = result[collection];\n if (!Array.isArray(values) || values.length > 1 || result.NestedPartialErrors !== undefined && result.NestedPartialErrors !== null && (!Array.isArray(result.NestedPartialErrors) || result.NestedPartialErrors.some(Boolean))) return false;\n const errors = z.array(z.record(z.string(), z.unknown()).nullable()).parse(result.PartialErrors ?? []).filter(value => value !== null);\n if (!errors.length) return values.every(value => value === null || nativeId(value.Id) === targetId && value[experiment ? 'ExperimentStatus' : 'Status'] === 'Deleted');\n // Live-confirmed receipts after deleting previously verified owned IDs:\n // 6110/null experiment and 1120/null campaign. Neither error is a general\n // not-found signal: ordinary reads still fail, and independent inventories\n // plus the preserved base are checked before reporting deletion success.\n return values.length === 1 && values[0] === null && errors.length === 1 && errors[0]!.Index === 0\n && errors[0]!.Code === (experiment ? 6110 : 1120)\n && errors[0]!.ErrorCode === (experiment ? 'ExperimentIdInvalid' : 'CampaignServiceInvalidCampaignStatus');\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<MicrosoftPlan> {\n const kinds = { microsoft_create_experiment: 'create', microsoft_update_experiment: 'update', microsoft_end_experiment: 'update', microsoft_delete_experiment: 'remove' } as const;\n if (op.provider !== 'microsoft' || !MICROSOFT_EXPERIMENT_WRITES.has(op.tool) || op.kind !== kinds[op.tool as keyof typeof kinds]) throw new AdportError('INVALID_INPUT', 'microsoft: experiment operation kind mismatch');\n const account = op.accountId;\n if (op.tool === 'microsoft_create_experiment') {\n const input = create.parse(op.payload), context = await this.base(account, input.base_campaign_id, true); this.eligible(context);\n if (context.snapshot_hash !== input.expected_base_context_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: experiment base context changed; read fresh context and request a new preview');\n if (guard.forcePausedCreation && context.base_campaign.Status !== 'Paused') throw new AdportError('POLICY_VIOLATION', 'microsoft: experiment campaign status is inherited; paused_creation requires a currently Paused base campaign');\n await this.unique(account, input.name);\n const start = input.start_date;\n if (context.active_experiments.length >= 10) throw new AdportError('INVALID_INPUT', 'microsoft: visible experiment inventory has reached the native ten-experiment limit for this base');\n this.interval(context, start, input.end_date);\n const fields = { BaseCampaignId: input.base_campaign_id, Name: input.name, StartDate: nativeDate(start), ...(input.end_date ? { EndDate: nativeDate(input.end_date) } : {}), TrafficSplitPercent: input.traffic_split_percent, ExperimentType: input.experiment_type, ExperimentStatus: 'Active' };\n return { summary: `Create Microsoft experiment \"${input.name}\" from \"${String(context.base_campaign.Name)}\"`, changes: [`+ ${JSON.stringify(fields)}`, `Creates an asynchronous campaign copy inheriting base ${context.base_campaign.Status} status, ${context.base_campaign.DailyBudget} daily budget and ${context.base_campaign.TimeZone} timezone. Required native Active setup input transitions to Creating; it is not an independent branch activation.`, 'Existing total base daily allocation is split, not increased. Native name/history and experiment limits remain authoritative.'], fieldChanges: [{ field: 'Experiment', before: '(new)', after: input.name }, { field: 'Base campaign', before: '(none)', after: `${String(context.base_campaign.Name)} (${input.base_campaign_id})` }, { field: 'Experiment traffic/budget share', before: '0%', after: `${input.traffic_split_percent}% of existing base pool` }, { field: 'Inherited serving status', before: String(context.base_campaign.Status), after: String(context.base_campaign.Status) }], notes, coercions: [], budgetDeltas: this.budget(context), execute: async () => {\n const result = await this.request(account, 'Experiments', { Experiments: [fields] }), ids = z.array(z.unknown()).parse(result.ExperimentIds).filter(value => value !== null).map(nativeId);\n if (ids.length !== 1) throw new AdportError('PROVIDER_ERROR', 'microsoft: experiment creation receipt mismatch; reconcile before retrying', { resourceIds: ids });\n return this.confirmed(ids, async () => { const after = await this.get(account, ids[0]!); return nativeId(after.experiment.BaseCampaignId) === input.base_campaign_id && after.experiment.Name === input.name && ['Creating', 'Active', 'Paused', 'Scheduled'].includes(String(after.experiment.ExperimentStatus)) && (!guard.forcePausedCreation || after.base_context.base_campaign.Status === 'Paused' && (!after.experiment_campaign || after.experiment_campaign.Status === 'Paused')); });\n } };\n }\n const input = (op.tool === 'microsoft_update_experiment' ? update : reference).parse(op.payload), current = await this.get(account, input.experiment_id, true), experiment = current.experiment, context = current.base_context, status = String(experiment.ExperimentStatus);\n if (input.expected_snapshot_hash !== current.snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'microsoft: experiment or coupled campaign context changed; request a fresh preview');\n if (['Promoting', 'Graduating'].includes(status)) throw new AdportError('INVALID_INPUT', 'microsoft: reconcile the in-progress experiment transition before another mutation');\n if (op.tool === 'microsoft_delete_experiment') {\n const branchId = optionalId(experiment.ExperimentCampaignId), baseId = nativeId(experiment.BaseCampaignId);\n return { summary: `Delete Microsoft experiment \"${String(experiment.Name)}\" and its campaign copy`, changes: [`- experiment ${input.experiment_id}${branchId ? ` and experiment campaign ${branchId}` : ' (no experiment campaign ID returned yet)'}`, 'Native deletion is coupled to the experiment campaign. The base campaign is preserved.'], fieldChanges: [{ field: 'Experiment and campaign copy', before: `${String(experiment.Name)} (${input.experiment_id})`, after: 'Deleted together' }], notes, coercions: [], budgetDeltas: [], execute: async () => {\n await this.request(account, 'Experiments', { ExperimentIds: [input.experiment_id] }, 'DELETE');\n return this.confirmed([input.experiment_id, ...(branchId ? [branchId] : [])], async () => {\n if (!await this.removedAfterDelete(account, 'experiment', input.experiment_id) || branchId && !await this.removedAfterDelete(account, 'campaign', branchId, context.base_campaign.CampaignType)) return false;\n const base = await this.campaignById(account, baseId, context.base_campaign.CampaignType), active = await this.query(account, null), campaigns = rows(await this.campaigns(account));\n return !!base && base.Status === context.base_campaign.Status && base.DailyBudget === context.base_campaign.DailyBudget && !active.some(value => nativeId(value.Id) === input.experiment_id) && !campaigns.some(value => value.Status !== 'Deleted' && (nativeId(value.Id) === branchId || optionalId(value.ExperimentId) === input.experiment_id));\n });\n } };\n }\n if (!['Active', 'Paused', 'Scheduled', 'Ended'].includes(status)) throw new AdportError('INVALID_INPUT', 'microsoft: experiment is not in a supported settled state for this edit');\n let fields: Row, fieldChanges: Array<{ field: string; before: string; after: string }>;\n if (op.tool === 'microsoft_end_experiment') {\n if (status === 'Ended') throw new AdportError('INVALID_INPUT', 'microsoft: experiment is already ended');\n fields = { Id: input.experiment_id, ExperimentStatus: 'Ended' }; fieldChanges = [{ field: 'Experiment status', before: status, after: 'Ended (cannot restart)' }];\n } else {\n const edit = update.parse(input);\n if (status === 'Ended') throw new AdportError('INVALID_INPUT', 'microsoft: ended experiments cannot be edited; deletion is a separate operation');\n if ((edit.start_date !== undefined || edit.traffic_split_percent !== undefined) && status !== 'Scheduled') throw new AdportError('INVALID_INPUT', 'microsoft: start-date and split edits require native Scheduled status; Paused does not prove the experiment never started');\n const from = edit.start_date ?? calendarDate(experiment.StartDate), to = edit.end_date === null ? undefined : edit.end_date ?? calendarDate(experiment.EndDate);\n if (!from || to && from > to) throw new AdportError('INVALID_INPUT', 'microsoft: experiment date interval is invalid or unavailable');\n if (edit.start_date !== undefined || edit.end_date !== undefined) this.interval(context, from, to, input.experiment_id);\n if (edit.name !== undefined) await this.unique(account, edit.name, input.experiment_id, optionalId(experiment.ExperimentCampaignId));\n fields = { Id: input.experiment_id, ...(edit.name !== undefined ? { Name: edit.name } : {}), ...(edit.start_date !== undefined ? { StartDate: nativeDate(edit.start_date) } : {}), ...(edit.end_date !== undefined ? { EndDate: edit.end_date === null ? { Day: 0, Month: 0, Year: 0 } : nativeDate(edit.end_date) } : {}), ...(edit.traffic_split_percent !== undefined ? { TrafficSplitPercent: edit.traffic_split_percent } : {}) };\n fieldChanges = Object.entries(fields).filter(([key]) => key !== 'Id').map(([field, value]) => ({ field, before: JSON.stringify(experiment[field] ?? null), after: JSON.stringify(value) }));\n }\n return { summary: `${op.tool === 'microsoft_end_experiment' ? 'End' : 'Update'} Microsoft experiment \"${String(experiment.Name)}\"`, changes: [`~ ${JSON.stringify(fields)}`, 'Names are coupled to the experiment campaign; other branch settings, base status and the inherited total budget are preserved. Ending is irreversible and pauses the experiment campaign.'], fieldChanges, notes, coercions: [], budgetDeltas: this.budget(context), execute: async () => {\n await this.request(account, 'Experiments', { Experiments: [fields] }, 'PUT');\n return this.confirmed([input.experiment_id], async () => { const after = await this.get(account, input.experiment_id); return Object.entries(fields).filter(([key]) => key !== 'Id').every(([key, value]) => key === 'EndDate' ? calendarDate(after.experiment.EndDate) === calendarDate(value) : key === 'StartDate' ? calendarDate(after.experiment.StartDate) === calendarDate(value) : after.experiment[key] === value) && after.base_context.base_campaign.Status === context.base_campaign.Status && after.base_context.base_campaign.DailyBudget === context.base_campaign.DailyBudget && (op.tool !== 'microsoft_end_experiment' || !after.experiment_campaign || after.experiment_campaign.Status === 'Paused'); });\n } };\n }\n}\n\nexport function microsoftExperimentTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'microsoft_experiments', namespace: 'microsoft', description: 'Read native active experiments only; this inventory does not establish absence of historical experiments. Use get for an exact known ID. Continue next_cursor as after_experiment_id.', input: z.object({ account_id: id, after_experiment_id: id.optional(), limit: z.number().int().positive().max(1000).default(100) }), output: z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean(), next_cursor: id.optional(), visibility: z.string(), notes: z.array(z.string()) }), pagination: { cursorInput: 'after_experiment_id' }, annotations: { readOnly: true }, handler: input => provider.experiments.list(input) }),\n defineTool({ name: 'microsoft_experiment_base_context', namespace: 'microsoft', description: 'Read an owned base campaign, its native active experiments, currency and snapshot_hash for creation. Budgets/status/timezone are inherited by experiment copies. Snapshot covers campaign configuration and visible active inventory, not every child entity.', input: z.object({ account_id: id, base_campaign_id: id }), output: contextSchema, annotations: { readOnly: true }, handler: input => provider.experiments.base(input.account_id, input.base_campaign_id) }),\n defineTool({ name: 'microsoft_get_experiment', namespace: 'microsoft', description: 'Read an exact known experiment, verified base/experiment campaign ownership, native setup state and coupled snapshot_hash. Creating is asynchronous acceptance, not readiness.', input: z.object({ account_id: id, experiment_id: id }), output: viewSchema, annotations: { readOnly: true }, handler: input => provider.experiments.get(input.account_id, input.experiment_id) }),\n guardedWriteTool({ name: 'microsoft_create_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'create', description: 'Create a native campaign-copy experiment with expected_base_context_hash. Paused creation requires a currently Paused base; native Active setup input becomes Creating. Dates use base timezone. Splits existing daily budget/traffic rather than adding a pool. Shared-budget, DSA, mixed/specialized or experiment bases are rejected. Setup is asynchronous.', payload: create }),\n guardedWriteTool({ name: 'microsoft_update_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'Edit experiment name or calendar schedule with expected_snapshot_hash. Name changes rename the campaign copy. Native Scheduled status is required before changing start/split; Paused alone is insufficient. end_date:null clears expiry with the native zero Date. No promotion or graduation.', payload: update }),\n guardedWriteTool({ name: 'microsoft_end_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'update', description: 'End an owned settled experiment early with expected_snapshot_hash. This cannot be restarted and pauses its campaign copy; the base campaign is preserved. Pausing temporarily is instead coupled to pausing the base campaign.', payload: reference }),\n guardedWriteTool({ name: 'microsoft_delete_experiment', namespace: 'microsoft', provider: 'microsoft', kind: 'remove', description: 'Delete an exact owned experiment and its coupled campaign copy with expected_snapshot_hash; preserve the base. Confirms disappearance before success. Do not retry accepted-but-unconfirmed receipts without reconciling their IDs.', payload: reference }),\n ];\n}\n","import { DATE_PRESETS, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { MicrosoftAdsProvider } from './provider.js';\nimport { microsoftChildTools } from './child-tools.js';\nimport { microsoftImageTools } from './images.js';\nimport { microsoftExtensionTools } from './extensions.js';\nimport { microsoftTargetingTools } from './targeting.js';\nimport { microsoftGeneralTargetingTools } from './general-targeting.js';\nimport { microsoftNegativeKeywordTools } from './negative-keywords.js';\nimport { microsoftBudgetTools } from './budgets.js';\nimport { microsoftPlanningTools } from './planning.js';\nimport { microsoftConversionTools } from './conversions.js';\nimport { microsoftAudienceTools } from './audiences.js';\nimport { microsoftAudienceTargetingTools } from './audience-targeting.js';\nimport { microsoftOfflineReportTools } from './offline-reports.js';\nimport { microsoftOfflineConversionTools } from './offline-conversions.js';\nimport { microsoftExperimentTools } from './experiments.js';\n\nconst statusSchema = z.enum(['Active', 'Paused']);\n\nexport function microsoftTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n ...microsoftChildTools(provider),\n ...microsoftImageTools(provider),\n ...microsoftExtensionTools(provider),\n ...microsoftTargetingTools(provider),\n ...microsoftGeneralTargetingTools(provider),\n ...microsoftNegativeKeywordTools(provider),\n ...microsoftBudgetTools(provider),\n ...microsoftPlanningTools(provider),\n ...microsoftConversionTools(provider),\n ...microsoftAudienceTools(provider),\n ...microsoftAudienceTargetingTools(provider),\n ...microsoftOfflineReportTools(provider),\n ...microsoftOfflineConversionTools(provider),\n ...microsoftExperimentTools(provider),\n ...(['keyword', 'search_term'] as const).map(kind => defineTool({\n name: `microsoft_${kind}_report`, namespace: 'microsoft',\n description: `Read the native Microsoft ${kind.replace('_', ' ')} performance report through Submit/Poll/CSV. Native numeric values remain strings; empty or unavailable values are preserved.`,\n input: z.object({ account_id: z.string().regex(/^\\d+$/), date_range: z.union([z.enum(DATE_PRESETS), z.object({ start: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/), end: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/) })]).default('last_7_days'), limit: z.number().int().positive().max(5000).default(1000) }),\n output: z.object({ rows: z.array(z.record(z.string(), z.string())), truncated: z.boolean(), report_type: z.string() }),\n annotations: { readOnly: true }, handler: input => provider.nativeReport({ ...input, kind }),\n })),\n defineTool({\n name: 'microsoft_api_read',\n namespace: 'microsoft',\n description:\n 'Call any documented Microsoft Advertising v13 query, search, get, or reporting submit/poll operation with selected-account headers.',\n input: z.object({\n account_id: z.string(),\n service: z.enum(['campaign', 'customer', 'reporting', 'adinsight']),\n path: z.string().min(3).describe('REST operation path, e.g. AdGroups/QueryByCampaignId or GenerateReport/Submit'),\n body: z.record(z.string(), z.unknown()).optional(),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n return provider.apiRead(input);\n },\n }),\n defineTool({\n name: 'microsoft_campaigns',\n namespace: 'microsoft',\n description:\n 'List all eight Microsoft Advertising campaign types (Id, Name, Status, DailyBudget in account currency, BudgetId when shared).',\n input: z.object({ account_id: z.string().describe('Ad account id') }),\n annotations: { readOnly: true },\n async handler(input) {\n const campaigns = await provider.listCampaigns(input.account_id);\n return { campaigns };\n },\n }),\n guardedWriteTool({\n name: 'microsoft_create_campaign',\n namespace: 'microsoft',\n description:\n 'Create a Microsoft Advertising Search campaign. daily_budget is a float in account currency. ' +\n \"The API's own default status is Paused. No server dry-run — previews are client-side diffs.\",\n provider: 'microsoft',\n kind: 'create',\n payload: z.object({\n name: z.string().min(1).max(128),\n daily_budget: z.number().positive(),\n time_zone: z.string().optional().describe('Bing Ads time zone name, default PacificTimeUSCanadaTijuana'),\n status: statusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'microsoft_set_campaign_status',\n namespace: 'microsoft',\n description: 'Activate or pause a Microsoft Advertising base campaign; related active/scheduled experiments inherit its serving status. Direct experiment-campaign status edits are refused.',\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), status: statusSchema }),\n }),\n guardedWriteTool({\n name: 'microsoft_set_budget',\n namespace: 'microsoft',\n description:\n \"Change a Microsoft base campaign's DailyBudget (float, account currency). Related campaign-copy experiments split this total pool. Direct experiment-campaign edits and shared budgets are refused.\",\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), daily_budget: z.number().positive() }),\n }),\n guardedWriteTool({\n name: 'microsoft_api_create',\n namespace: 'microsoft',\n description:\n 'Create through Microsoft Campaign Management v13 using its documented API body. Under paused creation, campaigns/ad groups/ads/keywords receive explicit Paused status, including omitted status. Budget fields are policy-checked; shared budgets, conversion goals, UET tags and audiences require typed tools.',\n provider: 'microsoft',\n kind: 'create',\n payload: z.object({ resource: z.string().min(2), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'microsoft_api_update',\n namespace: 'microsoft',\n description: 'Update non-budget fields through any Microsoft Advertising Campaign Management v13 collection.',\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ resource: z.string().min(2), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'microsoft_api_delete',\n namespace: 'microsoft',\n description: 'Permanently delete through any Microsoft Advertising Campaign Management v13 collection.',\n provider: 'microsoft',\n kind: 'remove',\n destructive: true,\n payload: z.object({ resource: z.string().min(2), body: z.record(z.string(), z.unknown()) }),\n }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst id = z.string().regex(/^\\d+$/);\nconst parent = { campaign_id: id, ad_group_id: id };\nconst status = z.enum(['Active', 'Paused']);\nexport const microsoftAdTypes = ['ResponsiveSearch', 'Responsive', 'DynamicSearch', 'ExpandedText', 'AppInstall', 'Product'] as const;\nconst headlines = z.array(z.string().min(1).max(30)).min(3).max(15).refine(value => new Set(value).size === value.length, 'Headlines must be unique');\nconst descriptions = z.array(z.string().min(1).max(90)).min(2).max(4).refine(value => new Set(value).size === value.length, 'Descriptions must be unique');\nconst urls = z.array(z.string().url().refine(value => ['http:', 'https:'].includes(new URL(value).protocol))).min(1).max(10);\nconst copy = { headlines, descriptions, final_urls: urls, path1: z.string().max(15).optional(), path2: z.string().max(15).optional() };\nconst rows = z.object({ rows: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() });\n\nexport function microsoftChildTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n const write = (name: string, description: string, payload: z.ZodObject<z.ZodRawShape>, kind: 'create' | 'update' | 'remove' = 'update') =>\n guardedWriteTool({ name, namespace: 'microsoft', provider: 'microsoft', description, payload, kind });\n return [\n defineTool({ name: 'microsoft_ad_groups', namespace: 'microsoft', description: 'Read ad groups and their bids/statuses after verifying the campaign belongs to the selected account.',\n input: z.object({ account_id: id, campaign_id: id }), output: rows, annotations: { readOnly: true }, handler: input => provider.children.listGroups(input) }),\n defineTool({ name: 'microsoft_ads', namespace: 'microsoft', description: 'Read ad configuration and creative copy with visual edit actions. Verifies the campaign/ad-group hierarchy in the selected account.',\n input: z.object({ account_id: id, ...parent, ad_types: z.array(z.enum(microsoftAdTypes)).min(1).default(['ResponsiveSearch']), limit: z.number().int().positive().max(200).default(50) }),\n output: creativesOutput.extend({ ads: z.array(z.record(z.string(), z.unknown())) }), presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.children.listAds(input) }),\n defineTool({ name: 'microsoft_keywords', namespace: 'microsoft', description: 'Read ad-group keywords, including bids, match types, statuses and URLs, within the selected campaign/account.',\n input: z.object({ account_id: id, ...parent }), output: rows, annotations: { readOnly: true }, handler: input => provider.children.listKeywords(input) }),\n write('microsoft_create_ad_group', 'Create a SearchStandard ad group in an account-owned campaign. CPC bid uses whole account-currency units; policy may force Paused.',\n z.object({ campaign_id: id, name: z.string().min(1).max(256), language: z.string().min(1).describe('Microsoft language name, e.g. English or German; chosen explicitly for ad-group targeting'), cpc_bid: z.number().positive().optional(), status: status.default('Paused') }), 'create'),\n write('microsoft_set_ad_group_status', 'Activate or pause an account-owned ad group; the parent campaign status remains unchanged.', z.object({ ...parent, status })),\n write('microsoft_update_ad_group', 'Rename an ad group or change its CPC bid in whole currency units. Campaign and ad-group status remain unchanged.',\n z.object({ ...parent, name: z.string().min(1).max(256).optional(), cpc_bid: z.number().positive().optional() }).refine(value => value.name !== undefined || value.cpc_bid !== undefined, 'Provide name or cpc_bid')),\n write('microsoft_create_responsive_search_ad', 'Create a responsive search ad using 3–15 unique headlines and 2–4 unique descriptions in a SearchStandard ad group. Policy may force Paused.',\n z.object({ ...parent, ...copy, status: status.default('Paused') }), 'create'),\n write('microsoft_update_responsive_search_ad', 'Edit supplied responsive search ad fields. Omitted fields and serving status are preserved; existing positional pinning is retained.',\n z.object({ ...parent, ad_id: id, headlines: headlines.optional(), descriptions: descriptions.optional(), final_urls: urls.optional(), path1: copy.path1, path2: copy.path2 })\n .refine(value => ['headlines', 'descriptions', 'final_urls', 'path1', 'path2'].some(key => value[key as keyof typeof value] !== undefined), 'Provide a content field')),\n write('microsoft_set_ad_status', 'Activate or pause an ad after verifying its exact parent hierarchy. Parent delivery settings remain unchanged.',\n z.object({ ...parent, ad_id: id, ad_type: z.enum(microsoftAdTypes).default('ResponsiveSearch'), status })),\n write('microsoft_add_keywords', 'Create up to 100 keywords in an account-owned ad group. Bids use whole currency units. Policy may force Paused.',\n z.object({ ...parent, keywords: z.array(z.object({ text: z.string().min(1).max(100), match_type: z.enum(['Broad', 'Phrase', 'Exact']), bid: z.number().positive().optional(), status: status.default('Paused') })).min(1).max(100) }), 'create'),\n write('microsoft_set_keyword_status', 'Activate or pause one verified keyword without replacing its text, match type or bid.', z.object({ ...parent, keyword_id: id, status })),\n write('microsoft_set_keyword_bid', 'Change one verified keyword bid in whole currency units; keyword and parent statuses remain unchanged.', z.object({ ...parent, keyword_id: id, bid: z.number().positive() })),\n write('microsoft_remove_keywords', 'Permanently remove verified keyword IDs from an ad group. This cannot be undone; use microsoft_set_keyword_status to pause instead.',\n z.object({ ...parent, keyword_ids: z.array(id).min(1).max(100).refine(value => new Set(value).size === value.length, 'Keyword IDs must be unique') }), 'remove'),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { MicrosoftAdsClient, type MicrosoftCredentials } from './client.js';\nimport { MicrosoftAdsProvider } from './provider.js';\nimport { microsoftTools } from './tools.js';\n\nexport {\n MicrosoftAdsClient,\n MSADS_SCOPE,\n SANDBOX_DEVELOPER_TOKEN,\n formatMicrosoftError,\n formatPartialErrors,\n type MicrosoftCredentials,\n} from './client.js';\nexport { MicrosoftAdsProvider, UNITS_TO_MICROS } from './provider.js';\nexport { microsoftTools } from './tools.js';\nexport { parseCsv } from './csv.js';\n\nexport async function resolveMicrosoftCredentials(store: CredentialStore): Promise<MicrosoftCredentials | undefined> {\n const record = await store.get('microsoft');\n if (record?.data.developer_token && record.data.client_id && record.data.refresh_token) {\n return {\n developerToken: record.data.developer_token,\n clientId: record.data.client_id,\n refreshToken: record.data.refresh_token,\n clientSecret: record.data.client_secret || undefined,\n sandbox: record.data.sandbox === 'true',\n };\n }\n const env = process.env;\n if (env.MICROSOFT_ADS_DEVELOPER_TOKEN && env.MICROSOFT_ADS_CLIENT_ID && env.MICROSOFT_ADS_REFRESH_TOKEN) {\n return {\n developerToken: env.MICROSOFT_ADS_DEVELOPER_TOKEN,\n clientId: env.MICROSOFT_ADS_CLIENT_ID,\n refreshToken: env.MICROSOFT_ADS_REFRESH_TOKEN,\n clientSecret: env.MICROSOFT_ADS_CLIENT_SECRET || undefined,\n sandbox: env.MICROSOFT_ADS_SANDBOX === 'true',\n };\n }\n return undefined;\n}\n\nexport async function createMicrosoftModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveMicrosoftCredentials(store);\n if (!credentials) return undefined;\n const client = new MicrosoftAdsClient(credentials, async (rotated) => {\n // Public-client refresh tokens rotate; persist the replacement immediately.\n const record = await store.get('microsoft');\n if (record) {\n await store.set({ ...record, data: { ...record.data, refresh_token: rotated } });\n }\n });\n const provider = new MicrosoftAdsProvider(client);\n return { provider, tools: microsoftTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAW5B,IAAM,YAAY;AACX,IAAM,cAAc;AAEpB,IAAM,0BAA0B;AAEvC,SAAS,MAAM,SAAkB;AAC/B,QAAM,QAAQ,UAAU,aAAa;AACrC,SAAO;AAAA,IACL,UAAU,uBAAuB,KAAK;AAAA,IACtC,UAAU,2BAA2B,KAAK;AAAA,IAC1C,WAAW,wBAAwB,KAAK;AAAA,IACxC,WAAW,wBAAwB,KAAK;AAAA,EAC1C;AACF;AAeO,IAAM,qBAAN,MAAyB;AAAA,EAK9B,YAC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B,KAAK;AAC3D,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,SAAS,IAAI,mBAAmB,aAAa,OAAO,YAAY;AAEpE,UAAMA,UAAS,MAAM,MAAM,IAAI,WAAW;AAC1C,QAAIA,SAAQ;AACV,YAAM,MAAM,IAAI,EAAE,GAAGA,SAAQ,MAAM,EAAE,GAAGA,QAAO,MAAM,eAAe,QAAQ,EAAE,CAAC;AAAA,IACjF;AAAA,EACF,CAAC;AACD,QAAM,WAAW,IAAI,qBAAqB,MAAM;AAChD,SAAO,EAAE,UAAU,OAAO,eAAe,QAAQ,EAAE;AACrD;","names":["url","status","AdportError","LocalMediaResolver","text","rows","AdportError","AdportError","id","headlines","descriptions","url","rows","parent","text","fields","keywords","keyword","AdportError","AdportError","url","input","AdportError","creativesOutput","defineTool","guardedWriteTool","z","AdportError","z","id","summary","z","image","creativesOutput","AdportError","text","selected","groups","input","value","change","current","key","defineTool","guardedWriteTool","AdportError","defineTool","guardedWriteTool","z","z","z","target","value","reference","parent","change","AdportError","z","input","value","current","reference","selected","id","name","defineTool","guardedWriteTool","AdportError","defineTool","guardedWriteTool","z","target","z","add","value","remove","groups","AdportError","id","selected","defineTool","guardedWriteTool","AdportError","defineTool","guardedWriteTool","z","z","update","AdportError","currency","value","target","view","current","fields","defineTool","guardedWriteTool","AdportError","defineTool","z","z","url","currency","AdportError","value","defineTool","createHash","AdportError","defineTool","guardedWriteTool","z","z","name","value","url","create","update","notes","fields","AdportError","createHash","goalId","status","expression","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","z","standardTypes","name","hash","value","create","reference","update","view","notes","canonical","matches","AdportError","createHash","rule","groups","prefix","input","fields","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","audienceType","target","z","hash","adjustment","add","reference","bid","canonical","value","digest","createHash","AdportError","groups","kind","input","current","fields","defineTool","guardedWriteTool","AdportError","defineTool","z","z","notes","AdportError","day","defineTool","createHash","AdportError","guardedWriteTool","z","z","hash","adjustment","canonical","digest","createHash","notes","count","rows","AdportError","identity","currency","notices","guardedWriteTool","createHash","z","AdportError","defineTool","guardedWriteTool","z","z","hash","target","canonical","digest","createHash","fields","entityId","target","text","minute","identity","notices","prefix","AdportError","groups","context","selected","parent","z","bid","change","id","name","day","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","hash","z","name","date","create","reference","update","additional","notes","contextSchema","viewSchema","canonical","value","digest","createHash","micros","AdportError","currency","context","kind","input","fields","status","defineTool","guardedWriteTool","LocalMediaResolver","AdportError","range","rows","day","status","url","selected","name","text","identity","key","id","fields","matches","value","amount","defineTool","guardedWriteTool","z","creativesOutput","defineTool","guardedWriteTool","z","id","urls","rows","name","description","kind","z","kind","defineTool","guardedWriteTool","record"]}
|