ap-mcp-server
Version:
Model Context Protocol (MCP) server for the Associated Press Media API
81 lines (64 loc) • 112 kB
JavaScript
#!/usr/bin/env node
import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {z}from'zod';var ue="1.2.6";var _=class c extends Error{code;statusCode;details;suggested_action;can_retry;alternative_tool;constructor(e,t,n,r){super(e),this.name="APError",this.code=t,this.statusCode=n,this.details=r,this.setRecoveryHints(),Error.captureStackTrace&&Error.captureStackTrace(this,c);}setRecoveryHints(){this.can_retry=false,this.suggested_action="Review error details and adjust request";}toJSON(){let e={name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,suggested_action:this.suggested_action,can_retry:this.can_retry,alternative_tool:this.alternative_tool};return (process.env.NODE_ENV==="development"||process.env.AP_DEBUG==="true")&&(e.stack=this.stack),e}},$=class extends _{constructor(e,t){super(e,"CONFIGURATION_ERROR",void 0,t),this.name="APConfigurationError";}setRecoveryHints(){this.can_retry=false,this.suggested_action="Check AP_API_KEY environment variable and other configuration settings";}},j=class c extends _{originalError;constructor(e,t,n,r,i){super(e,n,t,r),this.name="APAPIError",this.originalError=i;}setRecoveryHints(){switch(this.statusCode){case 400:this.can_retry=false,this.suggested_action="Review request parameters and correct invalid values";break;case 401:this.can_retry=false,this.suggested_action="Verify API key is valid and properly configured";break;case 403:this.can_retry=false,this.suggested_action="Check if content is included in your AP plan",this.alternative_tool="search_content with in_my_plan=true";break;case 404:this.can_retry=false,this.suggested_action="Verify item ID or try searching for content",this.alternative_tool="search_content";break;case 429:this.can_retry=true,this.suggested_action="Wait for rate limit reset before retrying (check retry_after header)";break;case 500:case 502:case 503:case 504:this.can_retry=true,this.suggested_action="AP service issue - retry after a short delay (30-60 seconds)";break;default:this.can_retry=false,this.suggested_action="Review API documentation for this error code";}}static fromAPResponse(e,t){let n=e?.error||{};return new c(n.message||"AP API Error",t,n.code?.toString()||"UNKNOWN_API_ERROR",{timestamp:n.timestamp,item:n.item,response:e})}},O=class extends _{originalError;constructor(e,t){super(e,"NETWORK_ERROR",void 0,{originalMessage:t.message,originalName:t.name}),this.name="APNetworkError",this.originalError=t;}setRecoveryHints(){this.can_retry=true,this.message.includes("timeout")?this.suggested_action="Request timed out - retry with longer timeout or smaller page_size":this.message.includes("cancelled")?(this.suggested_action="Request was cancelled - retry if needed",this.can_retry=false):this.suggested_action="Network issue - check connection and retry";}},d=class extends _{constructor(e,t,n){super(e,"VALIDATION_ERROR",400,{field:t,...n}),this.name="APValidationError";}setRecoveryHints(){this.can_retry=false,this.suggested_action=`Fix validation error in field '${this.details?.field}' and retry`,this.details?.field==="page_size"?this.suggested_action="Adjust page_size to be between 1 and 100":this.details?.field==="item_ids"&&(this.suggested_action="Ensure item_ids array has 1-50 valid IDs");}},se=class extends _{constructor(e="Authentication failed"){super(e,"AUTHENTICATION_ERROR",401),this.name="APAuthenticationError";}setRecoveryHints(){this.can_retry=false,this.suggested_action="Verify AP_API_KEY is valid and has not expired";}},H=class extends _{retryAfter;constructor(e,t){super(e,"RATE_LIMIT_ERROR",429,{retryAfter:t}),this.name="APRateLimitError",this.retryAfter=t;}setRecoveryHints(){this.can_retry=true,this.retryAfter?this.suggested_action=`Rate limit exceeded - wait ${this.retryAfter} seconds before retrying`:this.suggested_action="Rate limit exceeded - wait before retrying or reduce request frequency";}},oe=class extends _{constructor(e,t){super(e,"NOT_FOUND_ERROR",404,{resource:t}),this.name="APNotFoundError";}setRecoveryHints(){this.can_retry=false,this.suggested_action=`Resource '${this.details?.resource}' not found - verify ID or use search_content`,this.alternative_tool="search_content";}};function ae(c){return c instanceof _}var I=class{static handleError(e){if(ae(e))return e;if(e instanceof Error){let t=false;try{let a=e.message||"",o=e.name||"";t=a.includes("timeout")||a.includes("ECONNREFUSED")||a.includes("ENOTFOUND")||a.includes("fetch")||a.includes("Network error")||a.includes("Failed to fetch")||o==="AbortError";}catch{t=false;}if(t){let a;try{a=`Network error: ${e.message}`;}catch{a="Network error occurred";}return new O(a,e)}let n,r,i;try{if(e&&typeof e=="object"&&"message"in e){let a=e.message;typeof a=="string"?n=a:a!=null?n=String(a):n="Error with no message";}else n=String(e);}catch{n="Error occurred but message could not be retrieved";}try{r=e?.name;}catch{r=void 0;}try{i=e?.stack;}catch{i=void 0;}return !n||n.length===0?n="Error occurred with empty message":(n.includes("Cannot read properties of undefined")||n.includes("Cannot read property"))&&(process.env.NODE_ENV==="test"||(n="Error occurred (details unavailable due to error object corruption)")),new _(n,"UNKNOWN_ERROR",void 0,{originalName:r,originalStack:i})}return new _(`Unknown error: ${String(e)}`,"UNKNOWN_ERROR",void 0,{originalError:e})}static handleHttpError(e,t){if(!e)return new _("HTTP error with invalid response","HTTP_ERROR",void 0,{body:t});let n=e.status,r=e.statusText;switch(n){case 400:{let i=t?.error?.message,a=t?.error?.code,o=i&&(i.includes("Malformed JSON response")||i.includes("invalid json")||i.includes("JSON")||i.includes("unexpected token")||i.includes("Unexpected token")),l=i||`Bad Request: ${r}`;if(o)return new j(l,n,"MALFORMED_RESPONSE",{response:t});if(a==="INVALID_PARAMETER"||a==="VALIDATION_ERROR"||i?.includes("parameter")||i?.includes("required")||i?.includes("invalid")||i?.includes("missing")){let m=t?.error?.details?.parameter||t?.error?.details?.field||void 0;return new d(l,m,{response:t})}return new j(l,n,a||"BAD_REQUEST",{response:t})}case 401:return new se(t?.error?.message||`Authentication failed: ${r}`);case 403:return new _(t?.error?.message||`Forbidden: ${r}`,"FORBIDDEN_ERROR",403,{response:t});case 404:return new oe(t?.error?.message||`Not found: ${r}`);case 429:{let i=null;try{e&&e.headers&&e.headers.get&&(i=e.headers.get("retry-after"));}catch{}return new H(t?.error?.message||`Rate limit exceeded: ${r}`,i?parseInt(i,10):void 0)}case 500:case 502:case 503:case 504:return new j(t?.error?.message||`Server error: ${r}`,n,t?.error?.code?.toString()||"SERVER_ERROR",{response:t});default:return new j(t?.error?.message||`HTTP ${n}: ${r}`,n,t?.error?.code?.toString()||"HTTP_ERROR",{response:t})}}};var K={baseUrl:"https://api.ap.org/media/v",timeout:3e4,retries:3,enforcePlan:true},L=class c{config;constructor(e={}){this.config=this.loadConfiguration(e),this.validateConfiguration();}loadConfiguration(e){let t=e.apiKey||process.env.AP_API_KEY;if(!t)throw new $("AP API key is required. Set AP_API_KEY environment variable or provide apiKey in configuration.",{envVar:"AP_API_KEY",providedOverrides:Object.keys(e)});return {apiKey:t,baseUrl:e.baseUrl||process.env.AP_BASE_URL||K.baseUrl,timeout:e.timeout||(process.env.AP_TIMEOUT?parseInt(process.env.AP_TIMEOUT,10):K.timeout),retries:e.retries||(process.env.AP_RETRIES?parseInt(process.env.AP_RETRIES,10):K.retries),enforcePlan:e.enforcePlan!==void 0?e.enforcePlan:process.env.AP_ENFORCE_PLAN!==void 0?process.env.AP_ENFORCE_PLAN!=="false":K.enforcePlan}}validateConfiguration(){let{apiKey:e,baseUrl:t,timeout:n,retries:r}=this.config;if(!e.trim())throw new $("API key cannot be empty");if(!t||!this.isValidUrl(t))throw new $(`Invalid base URL: ${t}. Must be a valid HTTP/HTTPS URL.`,{baseUrl:t});if(n!==void 0&&(n<1e3||n>3e5))throw new $(`Timeout must be between 1000ms and 300000ms (5 minutes). Got: ${n}ms`,{timeout:n});if(r!==void 0&&(r<0||r>10))throw new $(`Retries must be between 0 and 10. Got: ${r}`,{retries:r})}isValidUrl(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}}getConfig(){return Object.freeze({...this.config})}get(e){return this.config[e]}updateConfig(e){return new c({...this.config,...e})}getHttpHeaders(){return {"x-api-key":this.config.apiKey,"Content-Type":"application/json",Accept:"application/json","User-Agent":"AP-MCP-Server/1.0.0"}}buildUrl(e){let t=e.startsWith("/")?e.slice(1):e;return `${this.config.baseUrl.replace(/\/$/,"")}/${t}`}static fromEnvironment(){return new c}static create(e){return new c(e)}getSummary(){return {baseUrl:this.config.baseUrl,timeout:this.config.timeout,retries:this.config.retries,enforcePlan:this.config.enforcePlan,hasApiKey:!!this.config.apiKey,apiKeyLength:this.config.apiKey?.length||0}}};var W=class{config;options;activeRequests=new Set;constructor(e,t={}){this.config=e,this.options={timeout:t.timeout??e.get("timeout"),retries:t.retries??e.get("retries"),retryDelay:t.retryDelay??1e3};}async get(e,t,n){let r=this.buildUrlWithParams(e,t);return this.executeWithRetry(()=>this.executeRequest("GET",r,void 0,n?.signal))}async post(e,t,n,r){let i=this.buildUrlWithParams(e,n);return this.executeWithRetry(()=>this.executeRequest("POST",i,t,r?.signal))}async put(e,t,n,r){let i=this.buildUrlWithParams(e,n);return this.executeWithRetry(()=>this.executeRequest("PUT",i,t,r?.signal))}async delete(e,t,n){let r=this.buildUrlWithParams(e,t);return this.executeWithRetry(()=>this.executeRequest("DELETE",r,void 0,n?.signal))}extractRateLimitInfo(e){let t=e["x-ratelimit-remaining"]||e["X-RateLimit-Remaining"],n=e["x-ratelimit-reset"]||e["X-RateLimit-Reset"],r=e["x-ratelimit-limit"]||e["X-RateLimit-Limit"],i=e["retry-after"]||e["Retry-After"];if(!t&&!n&&!r)return;let a={remaining:parseInt(t||"100",10),reset:parseInt(n||"0",10),limit:parseInt(r||"100",10)};return i&&(a.retry_after=parseInt(i,10)),a}combineSignals(e,t){if(!t)return e;let n=new AbortController,r=()=>{n.signal.aborted||n.abort();},i=()=>{n.signal.aborted||n.abort();};return e.addEventListener("abort",r,{once:true}),t.addEventListener("abort",i,{once:true}),(e.aborted||t.aborted)&&n.abort(),n.signal}buildUrlWithParams(e,t){let n=this.config.buildUrl(e);if(!t||Object.keys(t).length===0)return n;let r=new URLSearchParams;return Object.entries(t).forEach(([i,a])=>{a!=null&&(Array.isArray(a)?r.append(i,a.join(",")):r.append(i,String(a)));}),`${n}?${r.toString()}`}async executeRequest(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),this.options.timeout);this.activeRequests.add(i);let o=this.combineSignals(i.signal,r);try{let l={method:e,headers:this.config.getHttpHeaders(),signal:o};n&&(e==="POST"||e==="PUT")&&(l.body=typeof n=="string"?n:JSON.stringify(n));let u=await fetch(t,l);return clearTimeout(a),this.activeRequests.delete(i),await this.processResponse(u)}catch(l){if(clearTimeout(a),this.activeRequests.delete(i),l instanceof Error&&l.name==="AbortError")throw r?.aborted?new O("Request cancelled by client",l):new O(`Request timeout after ${this.options.timeout}ms`,l);if(l instanceof _)throw l;if(l instanceof Error)try{let u=String(l.message||l);if(u.includes("fetch")||u.includes("Failed to fetch")||u.includes("Network error"))throw new O(`Network request failed: ${u}`,l)}catch{throw new O("Network request failed",l)}throw I.handleError(l)}}async processResponse(e){if(!e)throw new _("Invalid response object","HTTP_ERROR",void 0,{});let t={};try{e.headers&&e.headers.forEach&&e.headers.forEach((o,l)=>{t[l]=o;});}catch{}let n,r="";try{r=e&&e.headers&&e.headers.get&&e.headers.get("content-type")||"";}catch{r="";}if(r.includes("application/json"))try{let o=await e.text();try{n=JSON.parse(o);}catch{if(!(e&&e.ok!==!1)){let m={error:{message:o||"Malformed JSON response"}};throw I.handleHttpError(e,m)}n=o;}}catch(o){if(o instanceof _)throw o;if(!(e&&e.ok!==false))throw I.handleHttpError(e);n="Unable to read response";}else try{n=await e.text();}catch{n="Unable to read response";}if(!e||e.ok===false)throw e?I.handleHttpError(e,n):new _("Invalid response object","HTTP_ERROR",void 0,{data:n});let i=this.extractRateLimitInfo(t),a={data:n,status:e.status,statusText:e.statusText,headers:t};return i&&(a.rateLimit=i),a}async executeWithRetry(e){let t;for(let n=0;n<=this.options.retries;n++)try{return await e()}catch(r){if(t=I.handleError(r),this.shouldNotRetry(t)||n===this.options.retries)throw t;let i=this.calculateRetryDelay(n);await this.sleep(i);}throw t}shouldNotRetry(e){return e.statusCode===401||e.statusCode===400||e.statusCode===403||e.statusCode===404?true:e instanceof H?false:!!(e instanceof O&&e.message.includes("timeout"))}calculateRetryDelay(e){let t=this.options.retryDelay*Math.pow(2,e),n=Math.random()*1e3;return Math.min(t+n,3e4)}sleep(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return {...this.options,baseUrl:this.config.get("baseUrl")}}async testConnection(){try{return await this.get("account"),!0}catch(e){if(ae(e)&&e.statusCode===401)return false;throw e}}cleanup(){for(let e of this.activeRequests)try{e.abort();}catch{}this.activeRequests.clear();}};var J=class{pool=new Map;maxConnections=5;connectionTimestamps=new Map;connectionUsage=new Map;cleanupTimer;maxIdleTime=300*1e3;constructor(e){e&&e>0&&(this.maxConnections=e),this.startCleanupTimer();}getConnectionKey(e){let t=e.get("apiKey"),n=e.get("baseUrl");return `${t.substring(0,12)}:${n}`}acquire(e){let t=this.getConnectionKey(e);if(this.pool.has(t)){let r=this.pool.get(t);return this.connectionTimestamps.set(t,Date.now()),this.connectionUsage.set(t,(this.connectionUsage.get(t)||0)+1),r}this.pool.size>=this.maxConnections&&this.evictLeastUsed();let n=new W(e);return this.pool.set(t,n),this.connectionTimestamps.set(t,Date.now()),this.connectionUsage.set(t,1),n}release(e){let t=this.getConnectionKey(e);this.connectionTimestamps.set(t,Date.now());}evictLeastUsed(){let e=null,t=Date.now(),n=1/0;for(let[r,i]of this.connectionTimestamps.entries()){let a=this.connectionUsage.get(r)||0;(i<t||i===t&&a<n)&&(t=i,e=r,n=a);}e&&this.remove(e);}remove(e){let t=this.pool.get(e);t&&(t.cleanup(),this.pool.delete(e),this.connectionTimestamps.delete(e),this.connectionUsage.delete(e));}startCleanupTimer(){this.cleanupTimer=setInterval(()=>{this.cleanupIdleConnections();},6e4);}cleanupIdleConnections(){let e=Date.now(),t=[];for(let[n,r]of this.connectionTimestamps.entries())e-r>this.maxIdleTime&&t.push(n);for(let n of t)this.remove(n);}getStats(){let e=Date.now(),t=Array.from(this.pool.keys()).map(n=>({key:n,usage:this.connectionUsage.get(n)||0,lastUsed:this.connectionTimestamps.get(n)||0,idleTime:e-(this.connectionTimestamps.get(n)||0)}));return {size:this.pool.size,maxConnections:this.maxConnections,connections:t}}clear(){for(let e of this.pool.values())e.cleanup();this.pool.clear(),this.connectionTimestamps.clear(),this.connectionUsage.clear();}cleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear();}};function N(c,e){let t=new Date,n={};if(c){let r=new Date(t.getTime()-c*60*60*1e3);n.min_date=r.toISOString();}else if(e){let r=new Date(t.getTime()-e*24*60*60*1e3);n.min_date=r.toISOString();}return n.max_date=t.toISOString(),n}function G(c){let e=[];if(c.topic&&e.push(c.topic),c.keywords&&c.keywords.length>0&&e.push(c.keywords.join(" AND ")),c.locations&&c.locations.length>0){let t=c.locations.map(n=>`location:"${n}"`).join(" OR ");e.push(`(${t})`);}if(c.exclude&&c.exclude.length>0){let t=c.exclude.map(n=>`-"${n}"`).join(" ");e.push(t);}return e.join(" ")}function V(c,e=10){let t=[];return (c==="idle"||c==="both")&&t.push({type:"idleFeed",enabled:true,criteria:{idleTime:`PT${e}M`}}),(c==="quality"||c==="both")&&t.push({type:"quality",enabled:true,criteria:{}}),t}var Z=["politics","business","technology","sports","entertainment","health","science","world","national","local"],Q={PHOTO:"picture",VIDEO:"video",GRAPHIC:"graphic",AUDIO:"audio"};function ce(c){return c.includes(",")?c.trim():`${c}*`}function F(c){let e={minimal:["item_id","headline","published","uri"],standard:["item_id","headline","published","uri","subject","summary","byline"],detailed:[]},t={minimal:["renditions","associations","edit_history"],standard:["renditions","edit_history"],detailed:[]};return {include:e[c],exclude:t[c]}}function x(c,e){let t=c?.data?.items||[],n=e?.maxItems?t.slice(0,e.maxItems):t,r=n.map((i,a)=>{let o=[`${a+1}. ${i.headline||"No headline"}`];if(i.published&&o.push(` Published: ${new Date(i.published).toLocaleString()}`),i.summary&&o.push(` Summary: ${i.summary.substring(0,200)}...`),i.byline&&o.push(` By: ${i.byline}`),i.subject&&i.subject.length>0){let l=i.subject.map(u=>u.name).join(", ");o.push(` Topics: ${l}`);}return i.uri&&o.push(` ID: ${i.item_id||i.uri}`),o.join(`
`)}).join(`
`);if(e?.includeMetadata&&c?.data){let i=[`
--- Search Metadata ---`,`Total Results: ${c.data.total||"Unknown"}`,`Page: ${c.data.page||1}`,`Items Shown: ${n.length}`].join(`
`);return r+`
`+i}return r}function B(c){return !c||c.length===0?"No trending topics found.":`=== Trending Topics ===
`+c.map((t,n)=>{let r=[`${n+1}. ${t.name||t.subject||"Unknown topic"}`];return t.frequency&&r.push(` Mentions: ${t.frequency}`),t.trend&&r.push(` Trend: ${t.trend}`),t.category&&r.push(` Category: ${t.category}`),r.join(`
`)}).join(`
`)}function le(c){return !c||c.length===0?"No recommendations available.":`=== Content Recommendations ===
`+c.map((t,n)=>{let r=[`${n+1}. ${t.headline||t.title||"Untitled"}`];return t.relevance_score&&r.push(` Relevance: ${(t.relevance_score*100).toFixed(1)}%`),t.reason&&r.push(` Why: ${t.reason}`),t.summary&&r.push(` Summary: ${t.summary.substring(0,150)}...`),r.join(`
`)}).join(`
`)}function X(c){let e=["=== Monitor Created Successfully ==="];if(c.name&&e.push(`Name: ${c.name}`),c.id&&e.push(`ID: ${c.id}`),c.description&&e.push(`Description: ${c.description}`),c.conditions&&c.conditions.length>0){let t=c.conditions.map(n=>` - ${n.type}: ${n.enabled?"Enabled":"Disabled"}`).join(`
`);e.push(`Conditions:
${t}`);}if(c.notify&&c.notify.length>0){let t=c.notify.map(n=>` - ${n.channelType}: ${n.channelDestinations.join(", ")}`).join(`
`);e.push(`Notifications:
${t}`);}return e.join(`
`)}function me(c){let e=[];return c.topStories&&c.topStories.length>0&&(e.push("=== Top Stories ==="),e.push(x({data:{items:c.topStories}}))),c.trends&&c.trends.length>0&&e.push(`
`+B(c.trends)),c.coverage&&(e.push(`
=== Coverage Analysis ===`),Object.entries(c.coverage).forEach(([t,n])=>{e.push(`${t}: ${n}`);})),c.sentiment&&(e.push(`
=== Sentiment Analysis ===`),Object.entries(c.sentiment).forEach(([t,n])=>{e.push(`${t}: ${n}`);})),e.join(`
`)}function he(c){let e=c.date||new Date,t=["=== Daily News Briefing ===",`Date: ${e.toLocaleDateString()}`,`Time: ${e.toLocaleTimeString()}`,""];return c.breakingNews&&c.breakingNews.length>0&&(t.push("\u{1F4F0} BREAKING NEWS"),t.push(x({data:{items:c.breakingNews}},{maxItems:5})),t.push("")),c.trending&&c.trending.length>0&&(t.push("\u{1F4C8} TRENDING TOPICS"),t.push(B(c.trending.slice(0,10))),t.push("")),c.recommendations&&c.recommendations.length>0&&(t.push("\u{1F4A1} RECOMMENDED READING"),t.push(le(c.recommendations.slice(0,5)))),t.join(`
`)}function pe(c,e){c.registerPrompt("breaking-news-search",{title:"Breaking News Search",description:"Search for the latest breaking news on a specific topic or globally",argsSchema:{topic:z.string().optional().describe("Topic to search for (optional, defaults to all breaking news)"),hours_ago:z.number().min(1).max(24).default(2).describe("How many hours back to search (1-24)"),location:z.string().optional().describe('Location filter (e.g., "Washington", "London", "Asia")'),max_results:z.number().min(5).max(50).default(10).describe("Maximum number of results to return")}},async({topic:t,hours_ago:n,location:r,max_results:i})=>{let a=G({topic:t,keywords:["breaking","urgent","latest"],locations:r?[ce(r)]:void 0}),o=N(n),l=F("standard");try{let u=await e.searchContent({q:a,...o,page_size:i,sort:"newest",...l}),m=x(u,{includeMetadata:!0,maxItems:i});return {messages:[{role:"assistant",content:{type:"text",text:`Breaking News Search Results (Last ${n} hours):
${m}`}}]}}catch(u){return {messages:[{role:"assistant",content:{type:"text",text:`Error searching for breaking news: ${u instanceof Error?u.message:"Unknown error"}`}}]}}}),c.registerPrompt("topic-deep-dive",{title:"Topic Deep Dive",description:"Comprehensive search for in-depth coverage of a specific topic",argsSchema:{topic:z.string().describe("Topic to research in depth"),days_back:z.number().min(1).max(30).default(7).describe("Number of days to search back (1-30)"),min_word_count:z.number().min(100).default(500).describe("Minimum word count for articles"),include_analysis:z.boolean().default(true).describe("Include analysis and opinion pieces"),max_results:z.number().min(10).max(100).default(25).describe("Maximum results to return")}},async({topic:t,days_back:n,min_word_count:r,include_analysis:i,max_results:a})=>{let l=G({keywords:i?[t,"(analysis OR opinion OR editorial OR investigation)"]:[t]}),u=N(void 0,n),m=F("detailed");try{let h=await e.searchContent({q:l,...u,page_size:a,sort:"relevance",...m});h?.data?.items&&(h.data.items=h.data.items.filter(p=>(p.word_count||p.body_text?.split(" ").length||0)>=r));let g=x(h,{includeMetadata:!0});return {messages:[{role:"assistant",content:{type:"text",text:`Deep Dive: "${t}" (Last ${n} days, ${r}+ words):
${g}`}}]}}catch(h){return {messages:[{role:"assistant",content:{type:"text",text:`Error performing deep dive search: ${h instanceof Error?h.message:"Unknown error"}`}}]}}}),c.registerPrompt("multimedia-search",{title:"Multimedia Content Search",description:"Search specifically for photos, videos, graphics, and audio content",argsSchema:{topic:z.string().describe("Topic or keywords to search"),media_type:z.enum(["photo","video","graphic","audio","all"]).default("all").describe("Type of media to search for"),days_back:z.number().min(1).max(90).default(7).describe("Days to search back"),high_quality_only:z.boolean().default(true).describe("Filter for high-quality/professional content only"),max_results:z.number().min(10).max(100).default(30).describe("Maximum results")}},async({topic:t,media_type:n,days_back:r,high_quality_only:i,max_results:a})=>{let o=G({topic:t,keywords:i?["professional","high-resolution"]:void 0}),l=N(void 0,r),u=F("standard"),m=n==="all"?void 0:{type:n==="photo"?Q.PHOTO:n==="video"?Q.VIDEO:n==="graphic"?Q.GRAPHIC:Q.AUDIO};try{let h=await e.searchContent({q:o,...l,...m,page_size:a,sort:"newest",...u}),g=x(h,{includeMetadata:!0}),p=n==="all"?"All Media Types":n.toUpperCase();return {messages:[{role:"assistant",content:{type:"text",text:`Multimedia Search: "${t}" (${p}, Last ${r} days):
${g}`}}]}}catch(h){return {messages:[{role:"assistant",content:{type:"text",text:`Error searching multimedia content: ${h instanceof Error?h.message:"Unknown error"}`}}]}}}),c.registerPrompt("regional-coverage",{title:"Regional News Coverage",description:"Get comprehensive news coverage for a specific region or location",argsSchema:{location:z.string().describe('Location/region (e.g., "California", "Europe", "Tokyo")'),include_national:z.boolean().default(true).describe("Include national news affecting the region"),include_local:z.boolean().default(true).describe("Include local news from the region"),days_back:z.number().min(1).max(7).default(3).describe("Days to search back"),max_results:z.number().min(10).max(50).default(20).describe("Maximum results")}},async({location:t,include_national:n,include_local:r,days_back:i,max_results:a})=>{let o=[];n&&o.push("national"),r&&o.push("local");let l=G({locations:[ce(t)],keywords:o.length>0?o:void 0}),u=N(void 0,i),m=F("standard");try{let h=await e.searchContent({q:l,...u,page_size:a,sort:"newest",...m}),g=x(h,{includeMetadata:!0});return {messages:[{role:"assistant",content:{type:"text",text:`Regional Coverage for ${t} (Last ${i} days):
${g}`}}]}}catch(h){return {messages:[{role:"assistant",content:{type:"text",text:`Error searching regional coverage: ${h instanceof Error?h.message:"Unknown error"}`}}]}}}),c.registerPrompt("smart-search",{title:"Smart Search Assistant",description:"Intelligently search AP content with natural language queries",argsSchema:{query:z.string().describe("Natural language search query"),search_mode:z.enum(["fast","comprehensive","archive"]).default("fast").describe("Search mode"),auto_expand:z.boolean().default(true).describe("Automatically expand search if few results found")}},async({query:t,search_mode:n,auto_expand:r})=>{let i={fast:{page_size:10,days_back:3,sort:"newest"},comprehensive:{page_size:50,days_back:30,sort:"relevance"},archive:{page_size:100,days_back:365,sort:"relevance"}}[n],a=N(void 0,i.days_back),o=F(n==="fast"?"minimal":"standard");try{let l=await e.searchContent({q:t,...a,page_size:i.page_size,sort:i.sort,...o});if(r&&l?.data?.total<5&&n!=="archive"){let m=t.split(" ").slice(0,2).join(" ");l=await e.searchContent({q:m,...a,page_size:i.page_size*2,sort:i.sort,...o});}let u=x(l,{includeMetadata:!0});return {messages:[{role:"assistant",content:{type:"text",text:`Smart Search Results (Mode: ${n}):
Query: "${t}"
${u}`}}]}}catch(l){return {messages:[{role:"assistant",content:{type:"text",text:`Error performing smart search: ${l instanceof Error?l.message:"Unknown error"}`}}]}}});}function ge(c,e){c.registerPrompt("create-news-monitor",{title:"Create News Monitor",description:"Set up automated monitoring for specific news topics with email alerts",argsSchema:{topic:z.string().describe("Topic or keywords to monitor"),monitor_name:z.string().min(1).max(20).describe("Short name for the monitor (1-20 chars)"),email:z.string().email().describe("Email address for notifications"),alert_frequency:z.enum(["immediate","10min","30min","1hour","2hours"]).default("30min").describe("How often to check for updates"),description:z.string().optional().describe("Optional description of what this monitor tracks")}},async({topic:t,monitor_name:n,email:r,alert_frequency:i,description:a})=>{let l={immediate:2,"10min":10,"30min":30,"1hour":60,"2hours":120}[i],u=V("idle",l),m={name:n.replace(/[^a-zA-Z0-9_.-]/g,"_"),description:a||`Monitoring news about: ${t}`,notify:[{channelType:"email",channelDestinations:[r]}],conditions:u,playbook:`Monitor for news about "${t}". Alert when new content is detected.`,repeatAlerts:i==="immediate"?"0":`PT${l}M`};try{let h=await e.createMonitor(m);return {messages:[{role:"assistant",content:{type:"text",text:`${X(h)}
The monitor is now active and will alert you about "${t}" every ${i}.`}}]}}catch(h){return {messages:[{role:"assistant",content:{type:"text",text:`Error creating monitor: ${h instanceof Error?h.message:"Unknown error"}`}}]}}}),c.registerPrompt("breaking-alert-setup",{title:"Breaking News Alert Setup",description:"Quick setup for urgent breaking news alerts on critical topics",argsSchema:{topics:z.array(z.string()).min(1).max(5).describe("Topics to monitor (1-5 topics)"),email:z.string().email().describe("Email for urgent notifications"),sensitivity:z.enum(["high","medium","low"]).default("high").describe("Alert sensitivity level")}},async({topics:t,email:n,sensitivity:r})=>{let a={high:{interval:2,repeat:"0"},medium:{interval:5,repeat:"PT10M"},low:{interval:10,repeat:"PT30M"}}[r],o=`breaking_${t[0].substring(0,10).replace(/\s/g,"_")}`,l=V("both",a.interval),u={name:o,description:`URGENT: Breaking news monitor for ${t.join(", ")}`,notify:[{channelType:"email",channelDestinations:[n]}],conditions:l,playbook:`IMMEDIATE ALERT: Check for breaking news on: ${t.join(", ")}. This is a high-priority monitor.`,repeatAlerts:a.repeat};try{let m=await e.createMonitor(u);return {messages:[{role:"assistant",content:{type:"text",text:`\u{1F6A8} BREAKING NEWS ALERT CONFIGURED \u{1F6A8}
${X(m)}
Monitoring: ${t.join(", ")}
Sensitivity: ${r.toUpperCase()}
You will receive immediate alerts for breaking news on these topics.`}}]}}catch(m){return {messages:[{role:"assistant",content:{type:"text",text:`Error setting up breaking news alert: ${m instanceof Error?m.message:"Unknown error"}`}}]}}}),c.registerPrompt("list-monitors",{title:"List Active Monitors",description:"View all active content monitors and their status",argsSchema:{include_status:z.boolean().default(true).describe("Include current status information"),include_history:z.boolean().default(false).describe("Include recent alert history")}},async({include_status:t,include_history:n})=>{try{let r=await e.listMonitors();if(!r||r.length===0)return {messages:[{role:"assistant",content:{type:"text",text:'No active monitors found. Use "create-news-monitor" or "breaking-alert-setup" to create one.'}}]};let i=await Promise.all(r.map(async l=>{let u=[`\u{1F4CD} ${l.name}`];if(l.description&&u.push(` Description: ${l.description}`),l.conditions){let m=l.conditions.map(h=>h.type).join(", ");u.push(` Monitoring Type: ${m}`);}if(l.notify&&l.notify[0]){let m=l.notify[0].channelDestinations.join(", ");u.push(` Alerts To: ${m}`);}if(t&&l.id)try{let m=await e.getMonitorStatus(l.id,{show_detail:!1});m?.status&&u.push(` Status: ${m.status}`),m?.last_alert&&u.push(` Last Alert: ${new Date(m.last_alert).toLocaleString()}`);}catch{}if(n&&l.id)try{let m=await e.getMonitorHistory(l.id,{page_size:3,show_detail:!1});m?.alerts&&m.alerts.length>0&&u.push(` Recent Alerts: ${m.alerts.length} in last 24 hours`);}catch{}return u.join(`
`)})),a=`=== Active Monitors (${r.length} total) ===
`,o=i.join(`
`);return {messages:[{role:"assistant",content:{type:"text",text:a+o}}]}}catch(r){return {messages:[{role:"assistant",content:{type:"text",text:`Error listing monitors: ${r instanceof Error?r.message:"Unknown error"}`}}]}}}),c.registerPrompt("manage-monitor",{title:"Manage Monitor",description:"Update or delete an existing monitor",argsSchema:{monitor_id:z.string().describe("Monitor ID or name"),action:z.enum(["update","delete","status"]).describe("Action to perform"),new_email:z.string().email().optional().describe("New email for notifications (update only)"),new_frequency:z.enum(["immediate","10min","30min","1hour"]).optional().describe("New check frequency (update only)")}},async({monitor_id:t,action:n,new_email:r,new_frequency:i})=>{try{if(n==="delete")return await e.deleteMonitor(t),{messages:[{role:"assistant",content:{type:"text",text:`\u2705 Monitor "${t}" has been deleted successfully.`}}]};if(n==="status"){let a=await e.getMonitorStatus(t,{show_detail:!0}),o=JSON.stringify(a,null,2);return {messages:[{role:"assistant",content:{type:"text",text:`Monitor Status for "${t}":
${o}`}}]}}if(n==="update"){let a=await e.getMonitor(t),o={monitor_id:t,name:a.name,notify:a.notify,conditions:a.conditions};if(r&&(o.notify=[{channelType:"email",channelDestinations:[r]}]),i){let h={immediate:2,"10min":10,"30min":30,"1hour":60}[i];o.conditions=V("idle",h),o.repeatAlerts=i==="immediate"?"0":`PT${h}M`;}let l=await e.updateMonitor(o);return {messages:[{role:"assistant",content:{type:"text",text:`\u2705 Monitor Updated:
${X(l)}`}}]}}}catch(a){return {messages:[{role:"assistant",content:{type:"text",text:`Error managing monitor: ${a instanceof Error?a.message:"Unknown error"}`}}]}}});}function fe(c,e){c.registerPrompt("trend-analysis",{title:"Trend Analysis",description:"Analyze trending topics and patterns in news coverage",argsSchema:{category:z.enum(["all",...Z]).default("all").describe("Category to analyze"),timeframe:z.enum(["hour","day","week"]).default("day").describe("Time period for trend analysis"),location_filter:z.string().optional().describe("Filter trends by location"),include_sentiment:z.boolean().default(false).describe("Include sentiment analysis"),max_topics:z.number().min(5).max(50).default(20).describe("Maximum trending topics to return")}},async({category:t,timeframe:n,location_filter:r,include_sentiment:i,max_topics:a})=>{try{let o={timeframe:n,max_topics:a};t!=="all"&&(o.subject_filter=t),r&&(o.location_filter=r),i&&(o.include_metrics=!0);let l=await e.analyzeTrends(o),u=B(l);return {messages:[{role:"assistant",content:{type:"text",text:`=== Trend Analysis ===
Category: ${t}
Timeframe: ${n}
${r?`Location: ${r}
`:""}
`+u}}]}}catch(o){return {messages:[{role:"assistant",content:{type:"text",text:`Error analyzing trends: ${o instanceof Error?o.message:"Unknown error"}`}}]}}}),c.registerPrompt("content-recommendations",{title:"Content Recommendations",description:"Get AI-powered content recommendations based on topics or past content",argsSchema:{based_on:z.string().optional().describe("Topic or content ID to base recommendations on"),subjects:z.array(z.string()).optional().describe("Subject preferences"),content_types:z.array(z.enum(["text","photo","video","graphic","audio"])).optional().describe("Preferred content types"),location_preference:z.string().optional().describe("Preferred location for content"),max_recommendations:z.number().min(5).max(25).default(10).describe("Number of recommendations")}},async({based_on:t,subjects:n,content_types:r,location_preference:i,max_recommendations:a})=>{try{let o={max_recommendations:a};t&&(t.includes(":")||t.length>20?o.seed_content=[t]:o.subjects=[t]),n&&n.length>0&&(o.subjects=n),r&&r.length>0&&(o.content_types=r),i&&(o.location_preference=i);let l=await e.getRecommendations(o);return {messages:[{role:"assistant",content:{type:"text",text:le(l)}}]}}catch(o){return {messages:[{role:"assistant",content:{type:"text",text:`Error getting recommendations: ${o instanceof Error?o.message:"Unknown error"}`}}]}}}),c.registerPrompt("coverage-comparison",{title:"Coverage Comparison",description:"Compare news coverage across different time periods or topics",argsSchema:{topic:z.string().describe("Topic to analyze"),period1_days_ago:z.number().min(1).max(30).describe("Start of first period (days ago)"),period2_days_ago:z.number().min(1).max(30).describe("Start of second period (days ago)"),period_length_days:z.number().min(1).max(7).default(3).describe("Length of each period in days"),metrics:z.array(z.enum(["volume","sentiment","sources","locations"])).default(["volume","sources"]).describe("Metrics to compare")}},async({topic:t,period1_days_ago:n,period2_days_ago:r,period_length_days:i,metrics:a})=>{try{let o=new Date;o.setDate(o.getDate()-n);let l=new Date(o);l.setDate(l.getDate()+i);let u=await e.searchContent({q:t,min_date:o.toISOString(),max_date:l.toISOString(),page_size:100}),m=new Date;m.setDate(m.getDate()-r);let h=new Date(m);h.setDate(h.getDate()+i);let g=await e.searchContent({q:t,min_date:m.toISOString(),max_date:h.toISOString(),page_size:100}),p={coverage:{[`Period 1 (${n} days ago)`]:u?.data?.total||0,[`Period 2 (${r} days ago)`]:g?.data?.total||0,Change:`${(g?.data?.total||0)-(u?.data?.total||0)} articles`}};if(a.includes("sources")){let y=new Set(u?.data?.items?.map(v=>v.source)||[]),b=new Set(g?.data?.items?.map(v=>v.source)||[]);p.coverage["Unique Sources Period 1"]=y.size,p.coverage["Unique Sources Period 2"]=b.size;}if(a.includes("locations")){let y=new Set(u?.data?.items?.flatMap(v=>v.locations||[])||[]),b=new Set(g?.data?.items?.flatMap(v=>v.locations||[])||[]);p.coverage["Locations Covered Period 1"]=y.size,p.coverage["Locations Covered Period 2"]=b.size;}let f=me(p);return {messages:[{role:"assistant",content:{type:"text",text:`Coverage Comparison: "${t}"
${f}`}}]}}catch(o){return {messages:[{role:"assistant",content:{type:"text",text:`Error comparing coverage: ${o instanceof Error?o.message:"Unknown error"}`}}]}}}),c.registerPrompt("quick-trending",{title:"Quick Trending Topics",description:"Get a quick snapshot of what's trending right now",argsSchema:{max_topics:z.number().min(5).max(20).default(10).describe("Number of topics to show")}},async({max_topics:t})=>{try{let n=await e.getTrendingSubjects({timeframe:"hour",max_subjects:t,min_frequency:2});return {messages:[{role:"assistant",content:{type:"text",text:`\u{1F525} Trending Right Now:
${B(n)}`}}]}}catch(n){return {messages:[{role:"assistant",content:{type:"text",text:`Error fetching trending topics: ${n instanceof Error?n.message:"Unknown error"}`}}]}}});}function ye(c,e){c.registerPrompt("daily-news-briefing",{title:"Daily News Briefing",description:"Generate a comprehensive daily news briefing with breaking news, trending topics, and recommendations",argsSchema:{categories:z.array(z.enum(["all",...Z])).default(["all"]).describe("Categories to include"),location:z.string().optional().describe("Location focus for the briefing"),include_breaking:z.boolean().default(true).describe("Include breaking news section"),include_trending:z.boolean().default(true).describe("Include trending topics"),include_recommendations:z.boolean().default(true).describe("Include content recommendations")}},async({categories:t,location:n,include_breaking:r,include_trending:i,include_recommendations:a})=>{try{let o={date:new Date};if(r){let u=N(4),m=await e.searchContent({q:n?`breaking news ${n}`:"breaking news",...u,page_size:10,sort:"newest"});o.breakingNews=m?.data?.items||[];}if(i){let u={timeframe:"day",max_subjects:15,min_frequency:3};t.length>0&&!t.includes("all")&&(u.subject_types=t),n&&(u.location_filter=n),o.trending=await e.getTrendingSubjects(u);}if(a){let u={max_recommendations:8,recency_preference:"recent"};t.length>0&&!t.includes("all")&&(u.subjects=t),n&&(u.location_preference=n),o.recommendations=await e.getRecommendations(u);}return {messages:[{role:"assistant",content:{type:"text",text:he(o)}}]}}catch(o){return {messages:[{role:"assistant",content:{type:"text",text:`Error generating briefing: ${o instanceof Error?o.message:"Unknown error"}`}}]}}}),c.registerPrompt("research-workflow",{title:"Research Assistant Workflow",description:"Comprehensive research workflow for investigating a topic",argsSchema:{topic:z.string().describe("Topic to research"),depth:z.enum(["quick","standard","deep"]).default("standard").describe("Research depth"),time_range_days:z.number().min(1).max(90).default(30).describe("Days to search back"),include_multimedia:z.boolean().default(false).describe("Include photos and videos"),include_analysis:z.boolean().default(true).describe("Include analysis pieces")}},async({topic:t,depth:n,time_range_days:r,include_multimedia:i,include_analysis:a})=>{try{let o=[],l=N(void 0,r),m={quick:{articles:10,analysis:5,multimedia:5},standard:{articles:25,analysis:10,multimedia:10},deep:{articles:50,analysis:20,multimedia:20}}[n];o.push("=== RECENT COVERAGE ===");let h=await e.searchContent({q:t,...l,page_size:m.articles,sort:"newest"});if(o.push(x(h,{maxItems:m.articles})),a){o.push(`
=== ANALYSIS & OPINION ===`);let f=await e.searchContent({q:`${t} AND (analysis OR opinion OR editorial OR investigation)`,...l,page_size:m.analysis,sort:"relevance"});o.push(x(f,{maxItems:m.analysis}));}if(i){o.push(`
=== MULTIMEDIA CONTENT ===`);let f=await e.searchContent({q:t,...l,page_size:m.multimedia,sort:"newest",type:"picture"});o.push(x(f,{maxItems:m.multimedia}));}o.push(`
=== RELATED TRENDING TOPICS ===`);let g=await e.getTrendingSubjects({timeframe:"week",max_subjects:10,subject_types:[t]});if(g&&g.length>0){let f=g.map((y,b)=>`${b+1}. ${y.name||y.subject} (${y.frequency||0} mentions)`).join(`
`);o.push(f);}else o.push("No specific trending subtopics found.");let p=h?.data?.total||0;return o.push(`
=== RESEARCH SUMMARY ===`),o.push(`Topic: "${t}"`),o.push(`Time Range: Last ${r} days`),o.push(`Total Articles Found: ${p}`),o.push(`Research Depth: ${n}`),{messages:[{role:"assistant",content:{type:"text",text:o.join(`
`)}}]}}catch(o){return {messages:[{role:"assistant",content:{type:"text",text:`Error in research workflow: ${o instanceof Error?o.message:"Unknown error"}`}}]}}}),c.registerPrompt("content-curation",{title:"Content Curation Workflow",description:"Curate content for specific audiences or purposes",argsSchema:{audience:z.enum(["general","business","academic","youth","professional"]).describe("Target audience"),topics:z.array(z.string()).min(1).max(5).describe("Topics to curate (1-5)"),content_mix:z.object({news:z.number().min(0).max(100).default(40),analysis:z.number().min(0).max(100).default(30),features:z.number().min(0).max(100).default(20),multimedia:z.number().min(0).max(100).default(10)}).describe("Content mix percentages (should total 100)"),total_items:z.number().min(10).max(50).default(20).describe("Total items to curate")}},async({audience:t,topics:n,content_mix:r,total_items:i})=>{try{let a=r.news+r.analysis+r.features+r.multimedia,o=Math.round(r.news/a*i),l=Math.round(r.analysis/a*i),u=Math.round(r.features/a*i),m=Math.round(r.multimedia/a*i),h=[],g=n.join(" OR "),p=N(void 0,7),y={general:"",business:" AND (business OR economy OR market OR finance)",academic:" AND (research OR study OR university OR education)",youth:" AND (youth OR generation OR student OR teen)",professional:" AND (industry OR professional OR career OR executive)"}[t];if(h.push(`=== CURATED CONTENT FOR ${t.toUpperCase()} AUDIENCE ===`),h.push(`Topics: ${n.join(", ")}`),h.push(`Content Mix: News ${r.news}% | Analysis ${r.analysis}% | Features ${r.features}% | Multimedia ${r.multimedia}%
`),o>0){h.push("\u{1F4F0} NEWS");let b=await e.searchContent({q:`(${g})${y}`,...p,page_size:o,sort:"newest"});h.push(x(b,{maxItems:o}));}if(l>0){h.push(`
\u{1F4CA} ANALYSIS & INSIGHTS`);let b=await e.searchContent({q:`(${g}) AND (analysis OR opinion OR commentary)${y}`,...p,page_size:l,sort:"relevance"});h.push(x(b,{maxItems:l}));}if(u>0){h.push(`
\u2728 FEATURE STORIES`);let b=await e.searchContent({q:`(${g}) AND (feature OR profile OR investigation)${y}`,...p,page_size:u,sort:"relevance"});h.push(x(b,{maxItems:u}));}if(m>0){h.push(`
\u{1F3AC} MULTIMEDIA`);let b=await e.searchContent({q:`(${g})${y}`,...p,page_size:m,sort:"newest",type:"picture"});h.push(x(b,{maxItems:m}));}return {messages:[{role:"assistant",content:{type:"text",text:h.join(`
`)}}]}}catch(a){return {messages:[{role:"assistant",content:{type:"text",text:`Error in content curation: ${a instanceof Error?a.message:"Unknown error"}`}}]}}}),c.registerPrompt("story-development",{title:"Story Development Helper",description:"Assist in developing a story by finding background, context, and related coverage",argsSchema:{story_topic:z.string().describe("Main story topic or angle"),story_type:z.enum(["news","feature","investigation","profile"]).describe("Type of story being developed"),needs:z.array(z.enum(["background","timeline","experts","similar_stories","data","visuals"])).describe("What you need for the story")}},async({story_topic:t,story_type:n,needs:r})=>{try{let i=[];if(i.push("=== STORY DEVELOPMENT ASSISTANT ==="),i.push(`Topic: "${t}"`),i.push(`Story Type: ${n}
`),r.includes("background")){i.push("\u{1F4DA} BACKGROUND & CONTEXT");let a=await e.searchContent({q:`${t} AND (background OR context OR history OR explainer)`,page_size:10,sort:"relevance"});i.push(x(a,{maxItems:5}));}if(r.includes("timeline")){i.push(`
\u23F1\uFE0F TIMELINE OF EVENTS`);let a=await e.searchContent({q:t,page_size:15,sort:"oldest"});i.push(x(a,{maxItems:10}));}if(r.includes("experts")){i.push(`
\u{1F465} EXPERT SOURCES & QUOTES`);let a=await e.searchContent({q:`${t} AND (expert OR professor OR analyst OR researcher OR "according to")`,page_size:10,sort:"relevance"});i.push(x(a,{maxItems:8}));}if(r.includes("similar_stories")){i.push(`
\u{1F4D1} SIMILAR STORIES & APPROACHES`);let a=await e.searchContent({q:`${t} AND ${n}`,page_size:10,sort:"relevance"});i.push(x(a,{maxItems:8}));}if(r.includes("data")){i.push(`
\u{1F4CA} DATA & STATISTICS`);let a=await e.searchContent({q:`${t} AND (data OR statistics OR survey OR poll OR study OR report)`,page_size:10,sort:"relevance"});i.push(x(a,{maxItems:8}));}if(r.includes("visuals")){i.push(`
\u{1F4F7} VISUAL CONTENT AVAILABLE`);let a=await e.searchContent({q:t,page_size:10,sort:"newest",type:"picture"});i.push(x(a,{maxItems:8}));}return {messages:[{role:"assistant",content:{type:"text",text:i.join(`
`)}}]}}catch(i){return {messages:[{role:"assistant",content:{type:"text",text:`Error in story development: ${i instanceof Error?i.message:"Unknown error"}`}}]}}});}function be(c,e,t){pe(c,e),ge(c,t),fe(c,e),ye(c,e),console.log("\u2705 AP Media API Prompts registered successfully"),console.log(" - Search prompts: breaking-news-search, topic-deep-dive, multimedia-search, regional-coverage, smart-search"),console.log(" - Monitoring prompts: create-news-monitor, breaking-alert-setup, list-monitors, manage-monitor"),console.log(" - Analysis prompts: trend-analysis, content-recommendations, coverage-comparison, quick-trending"),console.log(" - Workflow prompts: daily-news-briefing, research-workflow, content-curation, story-development");}var ee=class{constructor(e){this.httpClient=e;}async getAccountInfo(){try{return (await this.httpClient.get("account")).data}catch(e){throw this.handleServiceError("getAccountInfo",e)}}async getAccountPlans(e={}){this.validatePlanParams(e);try{return (await this.httpClient.get("account/plans",e)).data}catch(t){throw this.handleServiceError("getAccountPlans",t,e)}}async getAccountDownloads(e={}){this.validateDownloadParams(e);try{return (await this.httpClient.get("account/downloads",e)).data}catch(t){throw this.handleServiceError("getAccountDownloads",t,e)}}async getAccountQuotas(){try{return (await this.httpClient.get("account/quotas")).data}catch(e){throw this.handleServiceError("getAccountQuotas",e)}}async getFollowedTopics(e={}){this.validateFollowedTopicsParams(e);try{return (await this.httpClient.get("account/followedtopics",e)).data}catch(t){throw this.handleServiceError("getFollowedTopics",t,e)}}validatePlanParams(e){if(e.include&&!Array.isArray(e.include))throw new d("Include must be an array of strings","include",{include:e.include});if(e.exclude&&!Array.isArray(e.exclude))throw new d("Exclude must be an array of strings","exclude",{exclude:e.exclude});if(e.format&&!["json","csv"].includes(e.format))throw new d('Format must be "json" or "csv"',"format",{format:e.format})}validateDownloadParams(e){if(e.include&&!Array.isArray(e.include))throw new d("Include must be an array of strings","include",{include:e.include});if(e.exclude&&!Array.isArray(e.exclude))throw new d("Exclude must be an array of strings","exclude",{exclude:e.exclude});if(e.format&&!["json","csv"].includes(e.format))throw new d('Format must be "json" or "csv"',"format",{format:e.format});if(e.min_date&&!this.isValidDateString(e.min_date))throw new d("min_date must be in format YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss","min_date",{min_date:e.min_date});if(e.max_date&&!this.isValidDateString(e.max_date))throw new d("max_date must be in format YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss","max_date",{max_date:e.max_date});if(e.order!==void 0&&(!Number.isInteger(e.order)||e.order<=0))throw new d("Order must be a positive integer","order",{order:e.order});if(e.min_date&&e.max_date){let t=new Date(e.min_date),r=(new Date(e.max_date).getTime()-t.getTime())/(1e3*60*60*24);if(r>60)throw new d("Date range cannot exceed 60 days","date_range",{min_date:e.min_date,max_date:e.max_date,days:r});if(r<0)throw new d("min_date must be before max_date","date_range",{min_date:e.min_date,max_date:e.max_date})}}validateFollowedTopicsParams(e){if(e.format&&!["json","csv"].includes(e.format))throw new d('Format must be "json" or "csv"',"format",{format:e.format});if(e.include&&!Array.isArray(e.include))throw new d("Include must be an array of strings","include",{include:e.include})}isValidDateString(e){if(/^\d{4}-\d{2}-\d{2}$/.test(e)){let t=new Date(e+"T00:00:00.000Z");return !isNaN(t.getTime())&&t.toISOString().startsWith(e)}return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(e)?!isNaN(Date.parse(e)):!!(/^P\d+[YMWD]$/.test(e)||/^PT\d+[HMS]$/.test(e))}handleServiceError(e,t,n){if(t instanceof _){let r={...t.details,operation:e,context:n};return new _(t.message,t.code,t.statusCode,r)}return new _(`AccountService.${e} failed: ${t}`,"ACCOUNT_SERVICE_ERROR",void 0,{operation:e,context:n,originalError:t})}static extractPlanSummary(e){let t=e.data.plans||[];return {totalPlans:t.length,activePlans:t.map(n=>({id:n.id,name:n.name,used:n.used,limit:n.usage_limit,usagePercent:n.usage_limit>0?Math.round(n.used/n.usage_limit*100):0,nextCycle:n.next_cycle_begins})),totalEntitlements:t.reduce((n,r)=>n+(r.entitlements?.length||0),0)}}static extractDownloadSummary(e){let t=e.data,n=t.downloads||[],r={},i=0,a;return n.forEach(o=>{let l=o.item.type;r[l]=(r[l]||0)+1,i+=o.charge||0,!a&&o.currency&&(a=o.currency);}),{totalDownloads:t.total_items,currentItems:t.current_item_count,dateRange:{min:t.min_date,max:t.max_date},mediaTypes:r,totalCost:i,currency:a}}static extractQuotaSummary(e){let t=e.data;return {account:t.account,updated:t.updated,quotas:t.quotas||[]}}};var U=class{cache=new Map;maxSize;defaultTTL;cleanupInterval;cleanupTimer=null;stats={hits:0,misses:0,evictions:0};constructor(e={}){this.maxSize=e.maxSize||1e3,this.defaultTTL=e.defaultTTL||300*1e3,this.cleanupInterval=e.cleanupInterval||60*1e3,e.autoCleanup;}set(e,t,n){let r=Date.now(),i=n||this.defaultTTL;this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictOldest(),this.cache.set(e,{value:t,expires:r+i,createdAt:r}),this.manageCleanupTimer();}get(e){let t=this.cache.get(e);return t?Date.now()>t.expires?(this.cache.delete(e),this.stats.misses++,null):(this.stats.hits++,t.value):(this.stats.misses++,null)}has(e){let t=this.cache.get(e);return t?Date.now()>t.expires?(this.cache.delete(e),false):true:false}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.stats.hits=0,this.stats.misses=0,this.stats.evictions=0,this.manageCleanupTimer();}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return {size:this.cache.size,hits:this.stats.hits,misses:this.stats.misses,hitRate:Math.round(t*1e3)/1e3,evictions:this.stats.evictions,