@hiper2d/ai-agents 0.3.1 → 0.4.1

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.mjs CHANGED
@@ -758,7 +758,8 @@ var API_KEY_CONSTANTS = {
758
758
  Z_AI: "Z_AI_API_KEY",
759
759
  FUGU: "FUGU_API_KEY",
760
760
  QWEN: "QWEN_API_KEY",
761
- MINIMAX: "MINIMAX_API_KEY"
761
+ MINIMAX: "MINIMAX_API_KEY",
762
+ META: "META_API_KEY"
762
763
  };
763
764
  var SupportedAiKeyNames = {
764
765
  [API_KEY_CONSTANTS.OPENAI]: "OpenAI",
@@ -771,7 +772,8 @@ var SupportedAiKeyNames = {
771
772
  [API_KEY_CONSTANTS.Z_AI]: "Z.AI",
772
773
  [API_KEY_CONSTANTS.FUGU]: "Sakana Fugu",
773
774
  [API_KEY_CONSTANTS.QWEN]: "Qwen",
774
- [API_KEY_CONSTANTS.MINIMAX]: "MiniMax"
775
+ [API_KEY_CONSTANTS.MINIMAX]: "MiniMax",
776
+ [API_KEY_CONSTANTS.META]: "Meta"
775
777
  };
776
778
  var LLM_CONSTANTS = {
777
779
  // Thinking-only catalog since 2026-08-05: models whose API offers a thinking toggle used to
@@ -808,7 +810,9 @@ var LLM_CONSTANTS = {
808
810
  QWEN_MAX: "qwen-max",
809
811
  QWEN_FLASH: "qwen-flash",
810
812
  // MiniMax. Single M3 entry; stable id without the version for the same repoint reason.
811
- MINIMAX: "minimax"
813
+ MINIMAX: "minimax",
814
+ // Meta Model API (api.meta.ai). Muse Spark; version-free id so a 1.3 → 1.4 repoint is entry-only.
815
+ MUSE_SPARK: "muse-spark"
812
816
  };
813
817
  var DEFAULT_MAX_OUTPUT_TOKENS = 8192;
814
818
  var SupportedAiModels = {
@@ -1093,6 +1097,26 @@ var SupportedAiModels = {
1093
1097
  hasThinking: true,
1094
1098
  temperature: 1,
1095
1099
  tags: ["very-slow", "cheap"]
1100
+ },
1101
+ // Meta Muse Spark 1.3 (added 2026-09-12) on Meta's own Model API — Standard tier, i.e.
1102
+ // the private model id (the `-contributor` id is a quarter of the price but Meta trains
1103
+ // on the prompts). Always-on reasoning with an effort dial (minimal … max, "none" is
1104
+ // rejected); the chain of thought is never returned, only an optional summary, plus
1105
+ // encrypted reasoning items replayed across turns like Grok. 'medium' is pinned as the
1106
+ // game default: turns are short and every reasoning token bills as output.
1107
+ // Temperature: Meta documents the model as tuned to its 1.0 default.
1108
+ // Speed: measured 2026-09-12 at medium effort — 9.6s on a full-context day-2 vote, 4-8s on
1109
+ // short turns (reasoning ≈ 90% of output tokens). That is the untagged middle band by the
1110
+ // grading above; tagged 'slow' anyway by decision so players expect a wait. Price-wise it
1111
+ // is neither cheap nor expensive.
1112
+ [LLM_CONSTANTS.MUSE_SPARK]: {
1113
+ displayName: "Muse Spark 1.3",
1114
+ modelApiName: "muse-spark-1.3",
1115
+ apiKeyName: API_KEY_CONSTANTS.META,
1116
+ hasThinking: true,
1117
+ temperature: 1,
1118
+ reasoningEffort: "medium",
1119
+ tags: ["slow"]
1096
1120
  }
1097
1121
  };
1098
1122
  function createCatalog(overrides = {}) {
@@ -1360,6 +1384,14 @@ var MODEL_PRICING = {
1360
1384
  extendedContextOutputPrice: 2.4,
1361
1385
  extendedContextCacheHitPrice: 0.12,
1362
1386
  extendedContextThresholdTokens: 512e3
1387
+ },
1388
+ // Meta Muse Spark 1.3, Standard tier. Rates from ai.developer.meta.com/docs/pricing-rate-limits
1389
+ // (2026-09-12): no long-context premium at any point of the 1M window; reasoning tokens bill
1390
+ // as output; caching is automatic, hits reported in input_tokens_details.cached_tokens.
1391
+ [SupportedAiModels[LLM_CONSTANTS.MUSE_SPARK].modelApiName]: {
1392
+ inputPrice: 1.25,
1393
+ outputPrice: 4.25,
1394
+ cacheHitPrice: 0.15
1363
1395
  }
1364
1396
  };
1365
1397
  var HYBRID_THINKING_API_NAMES = /* @__PURE__ */ new Set([
@@ -1423,6 +1455,9 @@ function getProviderSignatureFields(aiType, signature) {
1423
1455
  if (aiType.startsWith("grok")) {
1424
1456
  return { grokEncryptedReasoning: signature };
1425
1457
  }
1458
+ if (aiType.startsWith("muse-")) {
1459
+ return { metaEncryptedReasoning: signature };
1460
+ }
1426
1461
  return {};
1427
1462
  }
1428
1463
 
@@ -1434,6 +1469,7 @@ var GEMINI_REASONING_EFFORTS = ["minimal", "low", "medium", "high"];
1434
1469
  var GLM_REASONING_EFFORTS = ["low", "high", "max"];
1435
1470
  var DEEPSEEK_REASONING_EFFORTS = ["low", "high", "max"];
1436
1471
  var FUGU_REASONING_EFFORTS = ["high", "xhigh"];
1472
+ var META_REASONING_EFFORTS = ["minimal", "low", "medium", "high", "xhigh", "max"];
1437
1473
  function clampReasoningEffort(effort, allowed) {
1438
1474
  const rank = REASONING_EFFORT_SCALE.indexOf(effort);
1439
1475
  let best = allowed[0];
@@ -1452,6 +1488,7 @@ var toAnthropicEffort = (effort) => clampReasoningEffort(effort, ANTHROPIC_REASO
1452
1488
  var toGeminiEffort = (effort) => clampReasoningEffort(effort, GEMINI_REASONING_EFFORTS);
1453
1489
  var toGlmEffort = (effort) => clampReasoningEffort(effort, GLM_REASONING_EFFORTS);
1454
1490
  var toDeepSeekEffort = (effort) => clampReasoningEffort(effort, DEEPSEEK_REASONING_EFFORTS);
1491
+ var toMetaEffort = (effort) => clampReasoningEffort(effort, META_REASONING_EFFORTS);
1455
1492
  var toFuguEffort = (effort) => clampReasoningEffort(effort, FUGU_REASONING_EFFORTS);
1456
1493
 
1457
1494
  // src/pricing/token-usage-utils.ts
@@ -1506,6 +1543,9 @@ function extractKimiTokenUsage(response) {
1506
1543
  function extractGrokTokenUsage(response) {
1507
1544
  return extractTokenUsage(response);
1508
1545
  }
1546
+ function extractMetaTokenUsage(response) {
1547
+ return extractTokenUsage(response);
1548
+ }
1509
1549
  function extractAnthropicTokenUsage(response) {
1510
1550
  if (!response?.usage) {
1511
1551
  return null;
@@ -1594,11 +1634,19 @@ function extractTokenUsageFromResponse4(response) {
1594
1634
  return extractGrokTokenUsage(response);
1595
1635
  }
1596
1636
 
1637
+ // src/pricing/meta-pricing.ts
1638
+ function calculateMetaCost(model, inputTokens, outputTokens, cacheHitTokens = 0) {
1639
+ return calculateCost(model, inputTokens, outputTokens, { cacheHitTokens });
1640
+ }
1641
+ function extractTokenUsageFromResponse5(response) {
1642
+ return extractMetaTokenUsage(response);
1643
+ }
1644
+
1597
1645
  // src/pricing/anthropic-pricing.ts
1598
1646
  function calculateAnthropicCost(model, inputTokens, outputTokens, cacheHitTokens = 0) {
1599
1647
  return calculateCost(model, inputTokens, outputTokens, { cacheHitTokens });
1600
1648
  }
1601
- function extractTokenUsageFromResponse5(response) {
1649
+ function extractTokenUsageFromResponse6(response) {
1602
1650
  return extractAnthropicTokenUsage(response);
1603
1651
  }
1604
1652
 
@@ -1606,7 +1654,7 @@ function extractTokenUsageFromResponse5(response) {
1606
1654
  function calculateGoogleCost(model, inputTokens, outputTokens, options = {}) {
1607
1655
  return calculateCost(model, inputTokens, outputTokens, options);
1608
1656
  }
1609
- function extractTokenUsageFromResponse6(response) {
1657
+ function extractTokenUsageFromResponse7(response) {
1610
1658
  return extractGoogleTokenUsage(response);
1611
1659
  }
1612
1660
 
@@ -1614,7 +1662,7 @@ function extractTokenUsageFromResponse6(response) {
1614
1662
  function calculateMistralCost(model, inputTokens, outputTokens, cacheHitTokens = 0) {
1615
1663
  return calculateCost(model, inputTokens, outputTokens, { cacheHitTokens });
1616
1664
  }
1617
- function extractTokenUsageFromResponse7(response) {
1665
+ function extractTokenUsageFromResponse8(response) {
1618
1666
  return extractMistralTokenUsage(response);
1619
1667
  }
1620
1668
 
@@ -4684,6 +4732,221 @@ ${openAIMessages[0].content}`;
4684
4732
  }
4685
4733
  };
4686
4734
 
4735
+ // src/agents/meta-agent.ts
4736
+ import { OpenAI as OpenAI11 } from "openai";
4737
+ var MetaAgent = class extends AbstractAgent {
4738
+ client;
4739
+ promptCacheKey;
4740
+ // Log message templates
4741
+ logTemplates = {
4742
+ error: (name, error) => `Error in ${name} agent: ${error}`
4743
+ };
4744
+ // Error message templates
4745
+ errorMessages = {
4746
+ emptyResponse: "Empty or undefined response from Meta API",
4747
+ invalidFormat: "Invalid response format from Meta API",
4748
+ apiError: (error) => `Failed to get response from Meta API: ${error instanceof Error ? error.message : String(error)}`
4749
+ };
4750
+ constructor(name, instruction, model, apiKey, temperature, enableThinking = false, agentLoggingConfig = DEFAULT_LOGGING_CONFIG.agents) {
4751
+ super(name, instruction, model, temperature, enableThinking, agentLoggingConfig);
4752
+ this.promptCacheKey = stableHashHex(`${name}
4753
+ ${instruction}`);
4754
+ this.client = new OpenAI11({
4755
+ apiKey,
4756
+ baseURL: "https://api.meta.ai/v1",
4757
+ timeout: 12e5
4758
+ });
4759
+ }
4760
+ /**
4761
+ * Structured output: json_schema format on the Responses API plus the schema described
4762
+ * in the prompt, parsed leniently and validated with Zod.
4763
+ */
4764
+ async doAskWithZodSchema(zodSchema, messages) {
4765
+ try {
4766
+ const schemaDescription = ZodSchemaConverter.toPromptDescription(zodSchema);
4767
+ const input = this.buildResponsesInput(this.prepareMessages(messages));
4768
+ const lastMessage = input[input.length - 1];
4769
+ if (lastMessage && typeof lastMessage.content === "string") {
4770
+ lastMessage.content += `
4771
+
4772
+ Your response must be a valid JSON object matching this schema:
4773
+ ${schemaDescription}`;
4774
+ }
4775
+ this.logAsking(messages);
4776
+ this.logMessages(messages);
4777
+ const response = await this.createResponse(input, zodSchema);
4778
+ const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4779
+ if (!text) {
4780
+ throw new Error(this.errorMessages.emptyResponse);
4781
+ }
4782
+ this.logger(`Meta Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
4783
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
4784
+ this.logger(`\u2705 Response validated successfully with Zod schema`);
4785
+ const tokenUsage = this.extractTokenUsage(response);
4786
+ if (parsedData) {
4787
+ this.logReply(parsedData, reasoningSummary, tokenUsage);
4788
+ }
4789
+ return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
4790
+ } catch (error) {
4791
+ this.logger(this.logTemplates.error(this.name, error));
4792
+ throw new Error(this.errorMessages.apiError(error));
4793
+ }
4794
+ }
4795
+ /**
4796
+ * Plain-text ask: no JSON mode and no schema appended to the prompt.
4797
+ * Reasoning extraction and token accounting are identical to askWithZodSchema.
4798
+ */
4799
+ async doAskText(messages) {
4800
+ try {
4801
+ const input = this.buildResponsesInput(this.prepareMessages(messages));
4802
+ this.logAsking(messages);
4803
+ this.logMessages(messages);
4804
+ const response = await this.createResponse(input);
4805
+ const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4806
+ if (!text) {
4807
+ throw new Error(this.errorMessages.emptyResponse);
4808
+ }
4809
+ const tokenUsage = this.extractTokenUsage(response);
4810
+ this.logReply(text, reasoningSummary, tokenUsage);
4811
+ return [text, reasoningSummary, tokenUsage, encryptedReasoning];
4812
+ } catch (error) {
4813
+ this.logger(this.logTemplates.error(this.name, error));
4814
+ throw new Error(this.errorMessages.apiError(error));
4815
+ }
4816
+ }
4817
+ createResponse(input, zodSchema) {
4818
+ return this.client.responses.create({
4819
+ model: this.model,
4820
+ temperature: this.temperature,
4821
+ input,
4822
+ // Reasoning bills against the output budget on top of the visible answer, so this
4823
+ // has to cover both. Raise it with a catalog `maxOutputTokens` override if Muse
4824
+ // ever starts truncating.
4825
+ max_output_tokens: this.maxOutputTokens,
4826
+ // Effort read at request time so a per-instance override (story generation runs
4827
+ // deeper) is honored; omitted entirely when nothing is pinned, leaving Meta's default.
4828
+ reasoning: {
4829
+ ...this.reasoningEffort ? { effort: toMetaEffort(this.reasoningEffort) } : {},
4830
+ summary: "auto"
4831
+ },
4832
+ // We manage conversation state ourselves; encrypted reasoning is only
4833
+ // returned for unstored responses.
4834
+ store: false,
4835
+ include: ["reasoning.encrypted_content"],
4836
+ prompt_cache_key: this.promptCacheKey,
4837
+ ...zodSchema ? {
4838
+ text: {
4839
+ format: {
4840
+ type: "json_schema",
4841
+ name: "response_schema",
4842
+ schema: ZodSchemaConverter.toJsonSchema(zodSchema),
4843
+ strict: false
4844
+ }
4845
+ }
4846
+ } : {}
4847
+ });
4848
+ }
4849
+ /**
4850
+ * Converts history to Responses API input items. The system instruction is merged into
4851
+ * the leading system message; assistant messages carrying stored encrypted reasoning get
4852
+ * their reasoning items replayed right before them.
4853
+ */
4854
+ buildResponsesInput(messages) {
4855
+ const input = [];
4856
+ for (const msg of messages) {
4857
+ if (msg.role === "assistant" && msg.metaEncryptedReasoning) {
4858
+ try {
4859
+ const reasoningItems = JSON.parse(msg.metaEncryptedReasoning);
4860
+ if (Array.isArray(reasoningItems)) {
4861
+ for (const item of reasoningItems) {
4862
+ if (item?.encrypted_content) {
4863
+ input.push({
4864
+ type: "reasoning",
4865
+ ...item.id ? { id: item.id } : {},
4866
+ summary: Array.isArray(item.summary) ? item.summary : [],
4867
+ encrypted_content: item.encrypted_content
4868
+ });
4869
+ }
4870
+ }
4871
+ }
4872
+ } catch {
4873
+ this.logger(`Failed to parse stored encrypted reasoning, replaying message without it`);
4874
+ }
4875
+ }
4876
+ input.push({ role: msg.role, content: msg.content });
4877
+ }
4878
+ if (input.length > 0 && input[0].role !== "system") {
4879
+ input.unshift({ role: "system", content: this.instruction });
4880
+ } else if (input.length > 0 && input[0].role === "system") {
4881
+ input[0].content = `${this.instruction}
4882
+
4883
+ ${input[0].content}`;
4884
+ }
4885
+ return input;
4886
+ }
4887
+ /**
4888
+ * Walks the response output items: reasoning items yield the human-readable summary
4889
+ * plus the encrypted items (serialized for storage/replay); message items yield text.
4890
+ */
4891
+ extractResponseParts(response) {
4892
+ const textParts = [];
4893
+ const summaryParts = [];
4894
+ const encryptedItems = [];
4895
+ for (const item of response?.output ?? []) {
4896
+ if (!item) {
4897
+ continue;
4898
+ }
4899
+ if (item.type === "reasoning") {
4900
+ for (const summary of item.summary ?? []) {
4901
+ if (typeof summary?.text === "string" && summary.text) {
4902
+ summaryParts.push(summary.text);
4903
+ }
4904
+ }
4905
+ if (item.encrypted_content) {
4906
+ encryptedItems.push(item);
4907
+ }
4908
+ } else if (item.type === "message") {
4909
+ for (const part of item.content ?? []) {
4910
+ if (part?.type === "output_text" && typeof part.text === "string") {
4911
+ textParts.push(part.text);
4912
+ }
4913
+ }
4914
+ }
4915
+ }
4916
+ return {
4917
+ text: textParts.join("\n").trim(),
4918
+ reasoningSummary: summaryParts.join("\n").trim(),
4919
+ encryptedReasoning: encryptedItems.length > 0 ? JSON.stringify(encryptedItems) : void 0
4920
+ };
4921
+ }
4922
+ extractTokenUsage(response) {
4923
+ const usage = response?.usage;
4924
+ if (!usage) {
4925
+ return void 0;
4926
+ }
4927
+ const inputTokens = usage.input_tokens || 0;
4928
+ const outputTokens = usage.output_tokens || 0;
4929
+ const reasoningTokens = usage.output_tokens_details?.reasoning_tokens || 0;
4930
+ const cachedTokens = usage.input_tokens_details?.cached_tokens || 0;
4931
+ const cost = calculateMetaCost(this.model, inputTokens, outputTokens, cachedTokens);
4932
+ if (reasoningTokens > 0) {
4933
+ this.logger(`Output breakdown: ${reasoningTokens} reasoning tokens, ${outputTokens - reasoningTokens} final answer tokens, ${outputTokens} total output tokens`);
4934
+ }
4935
+ if (cachedTokens > 0) {
4936
+ this.logger(`Input breakdown: ${cachedTokens} cached tokens of ${inputTokens} input tokens`);
4937
+ }
4938
+ return {
4939
+ inputTokens,
4940
+ outputTokens,
4941
+ totalTokens: inputTokens + outputTokens,
4942
+ costUSD: cost,
4943
+ // Omitted when zero so we never hand Firestore an undefined value.
4944
+ ...reasoningTokens > 0 ? { reasoningTokens } : {},
4945
+ ...cachedTokens > 0 ? { cachedInputTokens: cachedTokens } : {}
4946
+ };
4947
+ }
4948
+ };
4949
+
4687
4950
  // src/agents/agent-factory.ts
4688
4951
  var AgentFactory = class {
4689
4952
  static createAgent(name, instruction, llmType, apiKeys, enableThinking = false) {
@@ -4737,6 +5000,9 @@ var AgentFactory = class {
4737
5000
  // MiniMax M3 — adaptive thinking (the model decides per-request)
4738
5001
  case LLM_CONSTANTS.MINIMAX:
4739
5002
  return new MiniMaxAgent(name, instruction, model.modelApiName, key, model.temperature, shouldEnableThinking);
5003
+ // Meta Muse Spark — Responses API with encrypted reasoning replay, effort from the catalog
5004
+ case LLM_CONSTANTS.MUSE_SPARK:
5005
+ return new MetaAgent(name, instruction, model.modelApiName, key, model.temperature, shouldEnableThinking);
4740
5006
  default:
4741
5007
  throw new Error(`Unknown Key: ${modelName}`);
4742
5008
  }
@@ -4778,7 +5044,9 @@ export {
4778
5044
  KimiAgent,
4779
5045
  LLM_CONSTANTS,
4780
5046
  MESSAGE_ROLE,
5047
+ META_REASONING_EFFORTS,
4781
5048
  MODEL_PRICING,
5049
+ MetaAgent,
4782
5050
  MiniMaxAgent,
4783
5051
  MistralAgent,
4784
5052
  ModelAuthenticationError,
@@ -4811,6 +5079,7 @@ export {
4811
5079
  calculateGoogleCost,
4812
5080
  calculateGrokCost,
4813
5081
  calculateKimiCost,
5082
+ calculateMetaCost,
4814
5083
  calculateMistralCost,
4815
5084
  calculateModelCost,
4816
5085
  calculateOpenAICost,
@@ -4822,18 +5091,20 @@ export {
4822
5091
  createVoiceAgent,
4823
5092
  evaluateBudget,
4824
5093
  extractAnthropicTokenUsage,
4825
- extractTokenUsageFromResponse5 as extractAnthropicTokenUsageFromResponse,
5094
+ extractTokenUsageFromResponse6 as extractAnthropicTokenUsageFromResponse,
4826
5095
  extractDeepSeekTokenUsage,
4827
5096
  extractTokenUsageFromResponse2 as extractDeepSeekTokenUsageFromResponse,
4828
5097
  extractFirstJsonObject,
4829
5098
  extractGoogleTokenUsage,
4830
- extractTokenUsageFromResponse6 as extractGoogleTokenUsageFromResponse,
5099
+ extractTokenUsageFromResponse7 as extractGoogleTokenUsageFromResponse,
4831
5100
  extractGrokTokenUsage,
4832
5101
  extractTokenUsageFromResponse4 as extractGrokTokenUsageFromResponse,
4833
5102
  extractKimiTokenUsage,
4834
5103
  extractTokenUsageFromResponse3 as extractKimiTokenUsageFromResponse,
5104
+ extractMetaTokenUsage,
5105
+ extractTokenUsageFromResponse5 as extractMetaTokenUsageFromResponse,
4835
5106
  extractMistralTokenUsage,
4836
- extractTokenUsageFromResponse7 as extractMistralTokenUsageFromResponse,
5107
+ extractTokenUsageFromResponse8 as extractMistralTokenUsageFromResponse,
4837
5108
  extractOpenAITokenUsage,
4838
5109
  extractTokenUsageFromResponse as extractOpenAITokenUsageFromResponse,
4839
5110
  extractTokenUsage,
@@ -4873,6 +5144,7 @@ export {
4873
5144
  toFuguEffort,
4874
5145
  toGeminiEffort,
4875
5146
  toGlmEffort,
5147
+ toMetaEffort,
4876
5148
  toOpenAIEffort,
4877
5149
  transcribeWithGemini,
4878
5150
  transcribeWithOpenAi,