@remnic/core 1.0.0 → 1.0.2

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.
Files changed (41) hide show
  1. package/README.md +47 -0
  2. package/dist/access-cli.js +10 -9
  3. package/dist/access-cli.js.map +1 -1
  4. package/dist/access-schema.d.ts +6 -6
  5. package/dist/calibration.js +3 -2
  6. package/dist/calibration.js.map +1 -1
  7. package/dist/causal-consolidation.js +3 -2
  8. package/dist/causal-consolidation.js.map +1 -1
  9. package/dist/{chunk-QFQVZOGA.js → chunk-6UJQNRIO.js} +2 -2
  10. package/dist/{chunk-CDW777AI.js → chunk-LP47L3ZX.js} +2 -2
  11. package/dist/{chunk-LU3GQNDQ.js → chunk-M5ZBBBJI.js} +12 -1
  12. package/dist/chunk-M5ZBBBJI.js.map +1 -0
  13. package/dist/chunk-OOSWAUYB.js +47 -0
  14. package/dist/chunk-OOSWAUYB.js.map +1 -0
  15. package/dist/{chunk-YAPUAHAY.js → chunk-OTFNI3OO.js} +32 -32
  16. package/dist/{chunk-TKO4HZCK.js → chunk-UYSKNO6E.js} +1 -1
  17. package/dist/{chunk-KT4NEUNF.js → chunk-XUHI52HK.js} +80 -22
  18. package/dist/chunk-XUHI52HK.js.map +1 -0
  19. package/dist/cli.js +1 -1
  20. package/dist/{engine-P26JFSVY.js → engine-2A6J4XEX.js} +2 -2
  21. package/dist/extraction.js +4 -3
  22. package/dist/fallback-llm.d.ts +22 -3
  23. package/dist/fallback-llm.js +3 -2
  24. package/dist/index.js +10 -9
  25. package/dist/index.js.map +1 -1
  26. package/dist/models-json.d.ts +17 -0
  27. package/dist/models-json.js +12 -0
  28. package/dist/models-json.js.map +1 -0
  29. package/dist/orchestrator.js +10 -9
  30. package/dist/resolve-provider-secret.d.ts +29 -1
  31. package/dist/resolve-provider-secret.js +3 -1
  32. package/dist/schemas.d.ts +18 -18
  33. package/dist/summarizer.js +4 -3
  34. package/package.json +2 -1
  35. package/dist/chunk-KT4NEUNF.js.map +0 -1
  36. package/dist/chunk-LU3GQNDQ.js.map +0 -1
  37. /package/dist/{chunk-QFQVZOGA.js.map → chunk-6UJQNRIO.js.map} +0 -0
  38. /package/dist/{chunk-CDW777AI.js.map → chunk-LP47L3ZX.js.map} +0 -0
  39. /package/dist/{chunk-YAPUAHAY.js.map → chunk-OTFNI3OO.js.map} +0 -0
  40. /package/dist/{chunk-TKO4HZCK.js.map → chunk-UYSKNO6E.js.map} +0 -0
  41. /package/dist/{engine-P26JFSVY.js.map → engine-2A6J4XEX.js.map} +0 -0
@@ -0,0 +1,17 @@
1
+ import { ModelProviderConfig } from './types.js';
2
+
3
+ /**
4
+ * Load the full providers map from the gateway's models.json.
5
+ * Returns an empty object if the file doesn't exist or can't be parsed.
6
+ */
7
+ declare function loadModelsJsonProviders(): Record<string, ModelProviderConfig>;
8
+ /**
9
+ * Clear the cached providers (useful for testing).
10
+ */
11
+ declare function clearModelsJsonCache(): void;
12
+ /**
13
+ * Inject a providers map for testing, bypassing file I/O.
14
+ */
15
+ declare function __setModelsJsonForTest(providers: Record<string, ModelProviderConfig>): void;
16
+
17
+ export { __setModelsJsonForTest, clearModelsJsonCache, loadModelsJsonProviders };
@@ -0,0 +1,12 @@
1
+ import {
2
+ __setModelsJsonForTest,
3
+ clearModelsJsonCache,
4
+ loadModelsJsonProviders
5
+ } from "./chunk-OOSWAUYB.js";
6
+ import "./chunk-KWBU5S5U.js";
7
+ export {
8
+ __setModelsJsonForTest,
9
+ clearModelsJsonCache,
10
+ loadModelsJsonProviders
11
+ };
12
+ //# sourceMappingURL=models-json.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -25,30 +25,30 @@ import {
25
25
  sanitizeSessionKeyForFilename,
26
26
  shouldFilterLifecycleRecallCandidate,
27
27
  summarizeGraphShadowComparison
28
- } from "./chunk-YAPUAHAY.js";
28
+ } from "./chunk-OTFNI3OO.js";
29
+ import "./chunk-UYSKNO6E.js";
29
30
  import "./chunk-IFFFR3MR.js";
30
- import "./chunk-TKO4HZCK.js";
31
31
  import "./chunk-Z5AAYHUC.js";
32
32
  import "./chunk-4A24LIM2.js";
33
33
  import "./chunk-TPB3I2AC.js";
34
34
  import "./chunk-UHGBNIOS.js";
35
35
  import "./chunk-ZKYI7UVO.js";
36
- import "./chunk-CDW777AI.js";
36
+ import "./chunk-LP47L3ZX.js";
37
37
  import "./chunk-ETOW6ACV.js";
38
+ import "./chunk-GPGBSNKM.js";
39
+ import "./chunk-V3RXWQIE.js";
38
40
  import "./chunk-G3AG3KZN.js";
39
41
  import "./chunk-2CJCWDMR.js";
42
+ import "./chunk-HG2NKWR2.js";
40
43
  import "./chunk-X7XN6YU4.js";
41
44
  import "./chunk-BRK4ODMI.js";
42
45
  import "./chunk-C7VW7C3F.js";
43
- import "./chunk-GPGBSNKM.js";
44
- import "./chunk-V3RXWQIE.js";
45
46
  import "./chunk-YCN4BVDK.js";
46
47
  import "./chunk-L5RPWGFK.js";
47
- import "./chunk-HG2NKWR2.js";
48
48
  import "./chunk-GJR6D6KC.js";
49
49
  import "./chunk-H63EDPFJ.js";
50
50
  import "./chunk-WWIQTB2Y.js";
51
- import "./chunk-QFQVZOGA.js";
51
+ import "./chunk-6UJQNRIO.js";
52
52
  import "./chunk-MWGVGUIS.js";
53
53
  import "./chunk-763GUIOU.js";
54
54
  import "./chunk-ONRU4L2N.js";
@@ -87,8 +87,9 @@ import "./chunk-JWPLJLDU.js";
87
87
  import "./chunk-YNI4S5WT.js";
88
88
  import "./chunk-DORBM6OB.js";
89
89
  import "./chunk-XYIK4LF6.js";
90
- import "./chunk-KT4NEUNF.js";
91
- import "./chunk-LU3GQNDQ.js";
90
+ import "./chunk-XUHI52HK.js";
91
+ import "./chunk-M5ZBBBJI.js";
92
+ import "./chunk-OOSWAUYB.js";
92
93
  import "./chunk-Y27UJK6V.js";
93
94
  import "./chunk-UZB5KHKX.js";
94
95
  import "./chunk-M5KEYE5E.js";
@@ -1,3 +1,23 @@
1
+ /**
2
+ * Resolve request-ready auth for a model, including provider-owned transforms
3
+ * (e.g., OAuth token exchange, base URL override for openai-codex).
4
+ */
5
+ type GetRuntimeAuthForModelFn = (params: {
6
+ model: {
7
+ provider: string;
8
+ id: string;
9
+ api?: string;
10
+ baseUrl?: string;
11
+ };
12
+ cfg?: unknown;
13
+ workspaceDir?: string;
14
+ }) => Promise<{
15
+ apiKey?: string;
16
+ baseUrl?: string;
17
+ source?: string;
18
+ mode?: string;
19
+ profileId?: string;
20
+ } | null>;
1
21
  /**
2
22
  * Resolve a provider API key from various OpenClaw formats.
3
23
  *
@@ -8,9 +28,17 @@
8
28
  * 4. undefined → provider is skipped in the fallback chain
9
29
  */
10
30
  declare function resolveProviderApiKey(providerId: string, apiKeyValue: unknown, gatewayConfig?: unknown, agentDir?: string): Promise<string | undefined>;
31
+ /**
32
+ * Get the gateway's getRuntimeAuthForModel function, if available.
33
+ * This resolves request-ready auth including provider-owned transforms
34
+ * (OAuth token exchange, base URL override for codex/copilot/etc.).
35
+ * Must be called after at least one resolveProviderApiKey() call to
36
+ * trigger the lazy module load.
37
+ */
38
+ declare function getGatewayRuntimeAuthForModel(): Promise<GetRuntimeAuthForModelFn | null>;
11
39
  /**
12
40
  * Clear the resolution cache (useful for testing or key rotation).
13
41
  */
14
42
  declare function clearSecretCache(): void;
15
43
 
16
- export { clearSecretCache, resolveProviderApiKey };
44
+ export { type GetRuntimeAuthForModelFn, clearSecretCache, getGatewayRuntimeAuthForModel, resolveProviderApiKey };
@@ -1,11 +1,13 @@
1
1
  import {
2
2
  clearSecretCache,
3
+ getGatewayRuntimeAuthForModel,
3
4
  resolveProviderApiKey
4
- } from "./chunk-LU3GQNDQ.js";
5
+ } from "./chunk-M5ZBBBJI.js";
5
6
  import "./chunk-MARWOCVP.js";
6
7
  import "./chunk-KWBU5S5U.js";
7
8
  export {
8
9
  clearSecretCache,
10
+ getGatewayRuntimeAuthForModel,
9
11
  resolveProviderApiKey
10
12
  };
11
13
  //# sourceMappingURL=resolve-provider-secret.js.map
package/dist/schemas.d.ts CHANGED
@@ -7,13 +7,13 @@ declare const MemoryActionEligibilityContextSchema: z.ZodObject<{
7
7
  importance: z.ZodNumber;
8
8
  source: z.ZodEnum<["extraction", "consolidation", "replay", "manual", "unknown"]>;
9
9
  }, "strict", z.ZodTypeAny, {
10
+ source: "extraction" | "consolidation" | "replay" | "manual" | "unknown";
10
11
  confidence: number;
11
- source: "unknown" | "extraction" | "consolidation" | "replay" | "manual";
12
12
  lifecycleState: "active" | "archived" | "candidate" | "validated" | "stale";
13
13
  importance: number;
14
14
  }, {
15
+ source: "extraction" | "consolidation" | "replay" | "manual" | "unknown";
15
16
  confidence: number;
16
- source: "unknown" | "extraction" | "consolidation" | "replay" | "manual";
17
17
  lifecycleState: "active" | "archived" | "candidate" | "validated" | "stale";
18
18
  importance: number;
19
19
  }>;
@@ -28,16 +28,16 @@ declare const ExtractedFactSchema: z.ZodObject<{
28
28
  promptedByQuestion: z.ZodNullable<z.ZodOptional<z.ZodString>>;
29
29
  structuredAttributes: z.ZodNullable<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
30
30
  }, "strip", z.ZodTypeAny, {
31
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
32
31
  content: string;
32
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
33
33
  confidence: number;
34
34
  tags: string[];
35
35
  entityRef?: string | null | undefined;
36
36
  structuredAttributes?: Record<string, string> | null | undefined;
37
37
  promptedByQuestion?: string | null | undefined;
38
38
  }, {
39
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
40
39
  content: string;
40
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
41
41
  confidence: number;
42
42
  tags: string[];
43
43
  entityRef?: string | null | undefined;
@@ -126,16 +126,16 @@ declare const ProactiveExtractionResultSchema: z.ZodObject<{
126
126
  promptedByQuestion: z.ZodNullable<z.ZodOptional<z.ZodString>>;
127
127
  structuredAttributes: z.ZodNullable<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
128
128
  }, "strip", z.ZodTypeAny, {
129
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
130
129
  content: string;
130
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
131
131
  confidence: number;
132
132
  tags: string[];
133
133
  entityRef?: string | null | undefined;
134
134
  structuredAttributes?: Record<string, string> | null | undefined;
135
135
  promptedByQuestion?: string | null | undefined;
136
136
  }, {
137
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
138
137
  content: string;
138
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
139
139
  confidence: number;
140
140
  tags: string[];
141
141
  entityRef?: string | null | undefined;
@@ -177,8 +177,8 @@ declare const ProactiveExtractionResultSchema: z.ZodObject<{
177
177
  }>, "many">>>;
178
178
  }, "strip", z.ZodTypeAny, {
179
179
  facts: {
180
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
181
180
  content: string;
181
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
182
182
  confidence: number;
183
183
  tags: string[];
184
184
  entityRef?: string | null | undefined;
@@ -200,8 +200,8 @@ declare const ProactiveExtractionResultSchema: z.ZodObject<{
200
200
  }[] | null | undefined;
201
201
  }, {
202
202
  facts: {
203
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
204
203
  content: string;
204
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
205
205
  confidence: number;
206
206
  tags: string[];
207
207
  entityRef?: string | null | undefined;
@@ -232,16 +232,16 @@ declare const ExtractionResultSchema: z.ZodObject<{
232
232
  promptedByQuestion: z.ZodNullable<z.ZodOptional<z.ZodString>>;
233
233
  structuredAttributes: z.ZodNullable<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
234
234
  }, "strip", z.ZodTypeAny, {
235
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
236
235
  content: string;
236
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
237
237
  confidence: number;
238
238
  tags: string[];
239
239
  entityRef?: string | null | undefined;
240
240
  structuredAttributes?: Record<string, string> | null | undefined;
241
241
  promptedByQuestion?: string | null | undefined;
242
242
  }, {
243
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
244
243
  content: string;
244
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
245
245
  confidence: number;
246
246
  tags: string[];
247
247
  entityRef?: string | null | undefined;
@@ -302,8 +302,8 @@ declare const ExtractionResultSchema: z.ZodObject<{
302
302
  context: string;
303
303
  }[];
304
304
  facts: {
305
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
306
305
  content: string;
306
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
307
307
  confidence: number;
308
308
  tags: string[];
309
309
  entityRef?: string | null | undefined;
@@ -331,8 +331,8 @@ declare const ExtractionResultSchema: z.ZodObject<{
331
331
  context: string;
332
332
  }[];
333
333
  facts: {
334
- category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
335
334
  content: string;
335
+ category: "fact" | "preference" | "correction" | "entity" | "decision" | "relationship" | "principle" | "commitment" | "moment" | "skill" | "rule";
336
336
  confidence: number;
337
337
  tags: string[];
338
338
  entityRef?: string | null | undefined;
@@ -585,8 +585,8 @@ declare const BehaviorLoopAdjustmentSchema: z.ZodObject<{
585
585
  reason: z.ZodString;
586
586
  appliedAt: z.ZodString;
587
587
  }, "strip", z.ZodTypeAny, {
588
- confidence: number;
589
588
  reason: string;
589
+ confidence: number;
590
590
  parameter: string;
591
591
  previousValue: number;
592
592
  nextValue: number;
@@ -594,8 +594,8 @@ declare const BehaviorLoopAdjustmentSchema: z.ZodObject<{
594
594
  evidenceCount: number;
595
595
  appliedAt: string;
596
596
  }, {
597
- confidence: number;
598
597
  reason: string;
598
+ confidence: number;
599
599
  parameter: string;
600
600
  previousValue: number;
601
601
  nextValue: number;
@@ -619,8 +619,8 @@ declare const BehaviorLoopPolicyStateSchema: z.ZodObject<{
619
619
  reason: z.ZodString;
620
620
  appliedAt: z.ZodString;
621
621
  }, "strip", z.ZodTypeAny, {
622
- confidence: number;
623
622
  reason: string;
623
+ confidence: number;
624
624
  parameter: string;
625
625
  previousValue: number;
626
626
  nextValue: number;
@@ -628,8 +628,8 @@ declare const BehaviorLoopPolicyStateSchema: z.ZodObject<{
628
628
  evidenceCount: number;
629
629
  appliedAt: string;
630
630
  }, {
631
- confidence: number;
632
631
  reason: string;
632
+ confidence: number;
633
633
  parameter: string;
634
634
  previousValue: number;
635
635
  nextValue: number;
@@ -646,8 +646,8 @@ declare const BehaviorLoopPolicyStateSchema: z.ZodObject<{
646
646
  maxDeltaPerCycle: number;
647
647
  protectedParams: string[];
648
648
  adjustments: {
649
- confidence: number;
650
649
  reason: string;
650
+ confidence: number;
651
651
  parameter: string;
652
652
  previousValue: number;
653
653
  nextValue: number;
@@ -663,8 +663,8 @@ declare const BehaviorLoopPolicyStateSchema: z.ZodObject<{
663
663
  maxDeltaPerCycle: number;
664
664
  protectedParams: string[];
665
665
  adjustments: {
666
- confidence: number;
667
666
  reason: string;
667
+ confidence: number;
668
668
  parameter: string;
669
669
  previousValue: number;
670
670
  nextValue: number;
@@ -1,12 +1,13 @@
1
1
  import {
2
2
  HourlySummarizer
3
- } from "./chunk-CDW777AI.js";
3
+ } from "./chunk-LP47L3ZX.js";
4
4
  import "./chunk-ETOW6ACV.js";
5
5
  import "./chunk-ONRU4L2N.js";
6
6
  import "./chunk-MDDAA2AO.js";
7
7
  import "./chunk-LK6SGL53.js";
8
- import "./chunk-KT4NEUNF.js";
9
- import "./chunk-LU3GQNDQ.js";
8
+ import "./chunk-XUHI52HK.js";
9
+ import "./chunk-M5ZBBBJI.js";
10
+ import "./chunk-OOSWAUYB.js";
10
11
  import "./chunk-Y27UJK6V.js";
11
12
  import "./chunk-UZB5KHKX.js";
12
13
  import "./chunk-MARWOCVP.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remnic/core",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Framework-agnostic Remnic memory engine — orchestrator, storage, extraction, search, trust zones",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -33,6 +33,7 @@
33
33
  "@orama/orama": "^3.0.0",
34
34
  "@orama/plugin-data-persistence": "^3.0.0",
35
35
  "@sinclair/typebox": "^0.34.0",
36
+ "apache-arrow": "^18.1.0",
36
37
  "better-sqlite3": "^12.6.2",
37
38
  "meilisearch": "^0.46.0",
38
39
  "openai": "^6.0.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/fallback-llm.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport type { GatewayConfig, ModelProviderConfig, AgentPersona } from \"./types.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport {\n buildChatCompletionTokenLimit,\n shouldAssumeOpenAiChatCompletions,\n} from \"./openai-chat-compat.js\";\nimport { resolveProviderApiKey } from \"./resolve-provider-secret.js\";\n\nexport interface FallbackLlmOptions {\n temperature?: number;\n maxTokens?: number;\n timeoutMs?: number;\n /** Override which agent persona's model chain to use (by ID from agents.list[]). */\n agentId?: string;\n}\n\nexport interface FallbackLlmResponse {\n content: string;\n modelUsed: string;\n usage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n };\n}\n\ninterface ModelRef {\n providerId: string;\n modelId: string;\n providerConfig: ModelProviderConfig;\n modelString: string;\n}\n\n/**\n * Generic fallback LLM client that uses the gateway's default AI configuration\n * and walks through the full fallback chain (primary + fallbacks).\n * Supports OpenAI and Anthropic API formats.\n */\nexport class FallbackLlmClient {\n private gatewayConfig: GatewayConfig | undefined;\n\n constructor(gatewayConfig?: GatewayConfig) {\n this.gatewayConfig = gatewayConfig;\n }\n\n /**\n * Check if fallback is available (gateway config has at least one model).\n */\n isAvailable(agentId?: string): boolean {\n const models = this.getModelChain(agentId);\n return models.length > 0;\n }\n\n /**\n * Make a chat completion request using the gateway's default AI chain.\n * Tries primary first, then each fallback in order.\n * When agentId is provided, uses that agent persona's model chain instead of defaults.\n */\n async chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions = {},\n ): Promise<FallbackLlmResponse | null> {\n const models = this.getModelChain(options.agentId);\n if (models.length === 0) {\n log.warn(\"fallback LLM: no models configured in gateway\");\n return null;\n }\n\n const runChain = async (): Promise<FallbackLlmResponse | null> => {\n // Try each model in the chain\n for (let i = 0; i < models.length; i++) {\n const model = models[i];\n const isFallback = i > 0;\n\n try {\n const result = await this.tryModel(model, messages, options);\n if (result) {\n if (isFallback) {\n log.debug(`fallback LLM: succeeded using ${model.modelString} (fallback ${i})`);\n }\n return {\n content: result.content,\n modelUsed: model.modelString,\n usage: result.usage,\n };\n }\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n log.debug(`fallback LLM: ${model.modelString} failed (${errorMsg}), trying next...`);\n // Continue to next model in chain\n }\n }\n\n log.warn(`fallback LLM: all ${models.length} models in chain failed`);\n return null;\n };\n\n if (typeof options.timeoutMs === \"number\") {\n if (options.timeoutMs <= 0) {\n log.warn(\"fallback LLM: timed out before request started\");\n return null;\n }\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n runChain(),\n new Promise<null>((resolve) => {\n timeoutHandle = setTimeout(() => {\n log.warn(`fallback LLM: timed out after ${options.timeoutMs}ms`);\n resolve(null);\n }, options.timeoutMs);\n }),\n ]);\n } finally {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n }\n }\n\n return await runChain();\n }\n\n /**\n * Make a request with structured output (Zod schema).\n * Returns parsed JSON or null on failure.\n */\n async parseWithSchema<T>(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n schema: { parse: (data: unknown) => T },\n options: FallbackLlmOptions = {},\n ): Promise<T | null> {\n const detailed = await this.parseWithSchemaDetailed(messages, schema, options);\n return detailed?.result ?? null;\n }\n\n /**\n * Like parseWithSchema but also returns the model that was used,\n * so callers can emit accurate trace events.\n */\n async parseWithSchemaDetailed<T>(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n schema: { parse: (data: unknown) => T },\n options: FallbackLlmOptions = {},\n ): Promise<{ result: T; modelUsed: string } | null> {\n const response = await this.chatCompletion(messages, options);\n if (!response?.content) return null;\n\n try {\n const candidates = extractJsonCandidates(response.content);\n for (const c of candidates) {\n try {\n const parsed = JSON.parse(c);\n return { result: schema.parse(parsed), modelUsed: response.modelUsed };\n } catch {\n // keep trying other candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"fallback LLM: failed to parse structured output:\", err);\n return null;\n }\n }\n\n /**\n * Get the full model chain from gateway config.\n * Returns array of models in order: [primary, fallback1, fallback2, ...]\n *\n * When agentId is provided, looks up the matching entry in agents.list[]\n * and uses that persona's model chain. Falls back to agents.defaults.model\n * if agentId is not found or not provided.\n */\n private getModelChain(agentId?: string): ModelRef[] {\n const chain: ModelRef[] = [];\n const providers = this.gatewayConfig?.models?.providers;\n\n if (!providers) return chain;\n\n // Resolve the model config: agent persona chain or global defaults\n let modelConfig: { primary?: string; fallbacks?: string[] } | undefined;\n\n if (agentId) {\n const persona = this.gatewayConfig?.agents?.list?.find(\n (a) => a.id === agentId,\n );\n if (persona?.model) {\n modelConfig = persona.model;\n log.debug(`fallback LLM: using agent persona \"${agentId}\" model chain`);\n } else {\n log.warn(\n `fallback LLM: agent persona \"${agentId}\" not found or has no model config, falling back to defaults`,\n );\n }\n }\n\n if (!modelConfig) {\n modelConfig = this.gatewayConfig?.agents?.defaults?.model;\n }\n\n // Build list of model strings: primary + fallbacks\n const modelStrings: string[] = [];\n\n if (modelConfig?.primary) {\n modelStrings.push(modelConfig.primary);\n }\n\n if (Array.isArray(modelConfig?.fallbacks)) {\n for (const fb of modelConfig.fallbacks) {\n if (typeof fb === \"string\" && !modelStrings.includes(fb)) {\n modelStrings.push(fb);\n }\n }\n }\n\n // Parse each model string and look up provider config\n for (const modelString of modelStrings) {\n const modelRef = this.parseModelString(modelString, providers);\n if (modelRef) {\n chain.push(modelRef);\n }\n }\n\n return chain;\n }\n\n /**\n * Parse a \"provider/model\" string and look up its config.\n */\n private parseModelString(\n modelString: string,\n providers: Record<string, ModelProviderConfig>,\n ): ModelRef | null {\n // Parse \"provider/model\" format (e.g., \"openai/gpt-5.2\", \"anthropic/claude-opus-4-6\")\n const parts = modelString.split(\"/\");\n if (parts.length < 2) {\n log.warn(`fallback LLM: invalid model format: ${modelString}`);\n return null;\n }\n\n const providerId = parts[0];\n const modelId = parts.slice(1).join(\"/\"); // Handle cases like \"openai/gpt-5.2-turbo\"\n\n const providerConfig = providers[providerId];\n if (!providerConfig) {\n log.warn(`fallback LLM: provider not found: ${providerId}`);\n return null;\n }\n\n return { providerId, modelId, providerConfig, modelString };\n }\n\n /**\n * Resolve the API key for a provider, handling OpenClaw secret ref formats.\n * Results are cached per provider so exec calls only happen once.\n */\n private async resolveApiKey(\n providerId: string,\n providerConfig: ModelProviderConfig,\n ): Promise<string | undefined> {\n return resolveProviderApiKey(providerId, providerConfig.apiKey, this.gatewayConfig);\n }\n\n /**\n * Try to call a single model.\n */\n private async tryModel(\n model: ModelRef,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n // Resolve the API key from secret refs before making the call.\n // If the raw key looks like an unresolved secret ref and resolution fails,\n // skip this provider entirely so the chain falls through to the next.\n const rawKey = model.providerConfig.apiKey;\n const needsResolution = rawKey === \"secretref-managed\"\n || (typeof rawKey === \"object\" && rawKey !== null);\n const resolvedApiKey = await this.resolveApiKey(model.providerId, model.providerConfig);\n\n if (needsResolution && !resolvedApiKey) {\n throw new Error(`API key for provider \"${model.providerId}\" could not be resolved from secret ref`);\n }\n\n const configWithResolvedKey = resolvedApiKey\n ? { ...model.providerConfig, apiKey: resolvedApiKey }\n : model.providerConfig;\n\n switch (model.providerConfig.api) {\n case \"anthropic-messages\":\n return await this.callAnthropic(configWithResolvedKey, model.modelId, messages, options);\n case \"openai-completions\":\n default:\n return await this.callOpenAI(\n configWithResolvedKey,\n model.modelId,\n messages,\n options,\n shouldAssumeOpenAiChatCompletions(model.providerConfig.baseUrl),\n );\n }\n }\n\n /**\n * Call OpenAI-compatible API.\n */\n private async callOpenAI(\n config: ModelProviderConfig,\n modelId: string,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n assumeOpenAI: boolean,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n const base = config.baseUrl.replace(/\\/$/, \"\");\n const url = base.endsWith(\"/v1\")\n ? `${base}/chat/completions`\n : `${base}/v1/chat/completions`;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n\n // Handle auth — apiKey is already resolved to a string by tryModel()\n if (config.apiKey && typeof config.apiKey === \"string\") {\n if (config.authHeader !== false) {\n headers[\"Authorization\"] = `Bearer ${config.apiKey}`;\n }\n }\n\n const body = {\n model: modelId,\n messages,\n temperature: options.temperature ?? 0.3,\n ...buildChatCompletionTokenLimit(modelId, options.maxTokens ?? 4096, {\n assumeOpenAI,\n }),\n };\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${response.status} ${error}`);\n }\n\n const data = (await response.json()) as {\n choices: Array<{\n message: {\n content: string;\n };\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n };\n };\n\n const content = data.choices?.[0]?.message?.content;\n if (!content) {\n throw new Error(\"Empty response from OpenAI API\");\n }\n\n return {\n content,\n usage: data.usage\n ? {\n inputTokens: data.usage.prompt_tokens,\n outputTokens: data.usage.completion_tokens,\n totalTokens: data.usage.total_tokens,\n }\n : undefined,\n };\n }\n\n /**\n * Call Anthropic Messages API.\n */\n private async callAnthropic(\n config: ModelProviderConfig,\n modelId: string,\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: FallbackLlmOptions,\n ): Promise<{ content: string; usage?: FallbackLlmResponse[\"usage\"] } | null> {\n const url = `${config.baseUrl.replace(/\\/$/, \"\")}/messages`;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n ...config.headers,\n };\n\n // Handle auth - Anthropic uses x-api-key header (apiKey resolved by tryModel)\n if (config.apiKey && typeof config.apiKey === \"string\") {\n headers[\"x-api-key\"] = config.apiKey;\n }\n\n // Extract system message (Anthropic handles it separately)\n const systemMessage = messages.find((m) => m.role === \"system\")?.content;\n const nonSystemMessages = messages.filter((m) => m.role !== \"system\");\n\n // Convert messages to Anthropic format\n const anthropicMessages = nonSystemMessages.map((m) => ({\n role: m.role,\n content: m.content,\n }));\n\n const body: Record<string, unknown> = {\n model: modelId,\n messages: anthropicMessages,\n max_tokens: options.maxTokens ?? 4096,\n temperature: options.temperature ?? 0.3,\n };\n\n if (systemMessage) {\n body.system = systemMessage;\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${response.status} ${error}`);\n }\n\n const data = (await response.json()) as {\n content: Array<{\n type: string;\n text: string;\n }>;\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n };\n };\n\n const content = data.content?.[0]?.text;\n if (!content) {\n throw new Error(\"Empty response from Anthropic API\");\n }\n\n return {\n content,\n usage: data.usage\n ? {\n inputTokens: data.usage.input_tokens,\n outputTokens: data.usage.output_tokens,\n totalTokens: (data.usage.input_tokens ?? 0) + (data.usage.output_tokens ?? 0),\n }\n : undefined,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuCO,IAAM,oBAAN,MAAwB;AAAA,EACrB;AAAA,EAER,YAAY,eAA+B;AACzC,SAAK,gBAAgB;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY,SAA2B;AACrC,UAAM,SAAS,KAAK,cAAc,OAAO;AACzC,WAAO,OAAO,SAAS;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,eACJ,UACA,UAA8B,CAAC,GACM;AACrC,UAAM,SAAS,KAAK,cAAc,QAAQ,OAAO;AACjD,QAAI,OAAO,WAAW,GAAG;AACvB,UAAI,KAAK,+CAA+C;AACxD,aAAO;AAAA,IACT;AAEA,UAAM,WAAW,YAAiD;AAEhE,eAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,cAAM,QAAQ,OAAO,CAAC;AACtB,cAAM,aAAa,IAAI;AAEvB,YAAI;AACF,gBAAM,SAAS,MAAM,KAAK,SAAS,OAAO,UAAU,OAAO;AAC3D,cAAI,QA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AAEA,WAAO;AAAA,MACL;AAAA,MACA,OAAO,KAAK,QACR;AAAA,QACE,aAAa,KAAK,MAAM;AAAA,QACxB,cAAc,KAAK,MAAM;AAAA,QACzB,cAAc,KAAK,MAAM,gBAAgB,MAAM,KAAK,MAAM,iBAAiB;AAAA,MAC7E,IACA;AAAA,IACN;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/resolve-provider-secret.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport { readEnvVar } from \"./runtime/env.js\";\nimport path from \"node:path\";\nimport os from \"node:os\";\n\n/**\n * Resolve a provider API key using OpenClaw's own auth resolution system.\n *\n * This module delegates to the gateway's `resolveApiKeyForProvider()` function,\n * which handles all secret reference formats (SecretRef objects, auth profiles,\n * \"secretref-managed\" markers, environment variables, etc.) using the same\n * codepath the gateway uses for its own agent sessions.\n *\n * For plain-text API keys, a fast path returns them directly without\n * involving the gateway auth system.\n *\n * Results are cached per provider for the gateway process lifetime.\n */\n\ntype ResolveApiKeyFn = (params: {\n provider: string;\n cfg?: unknown;\n agentDir?: string;\n}) => Promise<{ apiKey?: string; source?: string; mode?: string } | null>;\n\nlet _resolveApiKeyForProvider: ResolveApiKeyFn | null = null;\nlet _resolverLoaded = false;\nlet _resolverNextRetryAt = 0;\nconst RESOLVER_RETRY_BACKOFF_MS = 60_000; // 1 minute between retries after first failure\nconst resolvedCache = new Map<string, string | undefined>();\n\n/**\n * Lazily load the gateway's resolveApiKeyForProvider function.\n * Returns null if not available (e.g., running outside the gateway process).\n */\nasync function getGatewayResolver(): Promise<ResolveApiKeyFn | null> {\n if (_resolverLoaded) {\n return _resolveApiKeyForProvider;\n }\n // Backoff: don't re-scan filesystem on every call when module wasn't found.\n // After a failure, wait RESOLVER_RETRY_BACKOFF_MS before trying again.\n if (_resolverNextRetryAt > 0 && Date.now() < _resolverNextRetryAt) {\n return null;\n }\n\n try {\n // The gateway bundles this in a runtime chunk — import it dynamically.\n // This import path is stable across gateway versions since it's a named runtime export.\n const candidates = [\n // Try glob-matching the runtime module name (hash varies per build)\n ...await findRuntimeModules(),\n ];\n\n const { pathToFileURL } = await import(\"node:url\");\n for (const candidate of candidates) {\n try {\n // Convert native path to file:// URL for cross-platform ESM import compatibility\n const importUrl = pathToFileURL(candidate).href;\n const mod = await import(importUrl);\n if (typeof mod.resolveApiKeyForProvider === \"function\") {\n _resolveApiKeyForProvider = mod.resolveApiKeyForProvider;\n _resolverLoaded = true;\n log.debug(\"loaded gateway resolveApiKeyForProvider from runtime module\");\n return _resolveApiKeyForProvider;\n }\n } catch {\n // Try next candidate\n }\n }\n } catch {\n // Silent\n }\n\n // Backoff before retrying — avoid repeated fs scanning.\n // Retries after RESOLVER_RETRY_BACKOFF_MS so the resolver can\n // recover if the gateway restarts or the module becomes available.\n _resolverNextRetryAt = Date.now() + RESOLVER_RETRY_BACKOFF_MS;\n log.debug(`gateway resolveApiKeyForProvider not available — will retry after ${RESOLVER_RETRY_BACKOFF_MS / 1000}s`);\n return null;\n}\n\n/**\n * Find the gateway's model-auth runtime module by scanning the dist directory.\n * Uses require.resolve to find the openclaw package regardless of install method.\n */\nasync function findRuntimeModules(): Promise<string[]> {\n const { readdirSync } = await import(\"node:fs\");\n const { createRequire } = await import(\"node:module\");\n const candidates: string[] = [];\n\n // Discover the openclaw dist directory from the installed package,\n // regardless of how it was installed (Homebrew, npm global, local, etc.)\n const distDirs: string[] = [];\n\n try {\n // require.resolve finds the package from the current process context\n const req = createRequire(import.meta.url);\n const openclawMain = req.resolve(\"openclaw\");\n const openclawDist = path.join(path.dirname(openclawMain), \"..\", \"dist\");\n if (openclawDist) distDirs.push(path.resolve(openclawDist));\n } catch {\n // openclaw not resolvable from plugin context — try alternate paths\n }\n\n // Fallback: infer from the running process (gateway runs from its own dist/)\n // Use fs.realpathSync to resolve symlinks (e.g., /usr/local/bin/openclaw → actual path)\n try {\n const { realpathSync } = await import(\"node:fs\");\n const mainScript = process.argv[1];\n if (mainScript) {\n const realScript = realpathSync(mainScript);\n if (realScript.includes(\"openclaw\")) {\n const distDir = path.dirname(realScript);\n if (!distDirs.includes(distDir)) distDirs.push(distDir);\n }\n }\n } catch {\n // Silent\n }\n\n for (const dir of distDirs) {\n try {\n const files = readdirSync(dir);\n for (const f of files) {\n if (f.startsWith(\"runtime-model-auth.runtime-\") && f.endsWith(\".js\")) {\n candidates.push(path.join(dir, f));\n }\n }\n } catch {\n // Directory doesn't exist — skip\n }\n }\n\n return candidates;\n}\n\n/**\n * Resolve a provider API key from various OpenClaw formats.\n *\n * Resolution order:\n * 1. Plain-text string → returned immediately\n * 2. Gateway's resolveApiKeyForProvider → handles all secret ref formats\n * 3. Environment variable fallback (PROVIDER_NAME_API_KEY)\n * 4. undefined → provider is skipped in the fallback chain\n */\nexport async function resolveProviderApiKey(\n providerId: string,\n apiKeyValue: unknown,\n gatewayConfig?: unknown,\n agentDir?: string,\n): Promise<string | undefined> {\n // Check cache first\n const cacheKey = `provider:${providerId}`;\n if (resolvedCache.has(cacheKey)) {\n return resolvedCache.get(cacheKey);\n }\n\n let resolved: string | undefined;\n\n // Fast path: plain-text string that looks like an actual API key\n if (typeof apiKeyValue === \"string\" && apiKeyValue.trim().length > 0) {\n // Skip known non-API-key markers used by the gateway for auth modes\n // that don't use bearer tokens (OAuth, local endpoints, GCP credentials)\n if (\n apiKeyValue === \"secretref-managed\" ||\n apiKeyValue.endsWith(\"-oauth\") ||\n apiKeyValue.endsWith(\"-local\") ||\n apiKeyValue === \"lm-studio\" ||\n apiKeyValue.startsWith(\"gcp-\")\n ) {\n // Fall through to gateway resolver / env var fallback\n } else {\n resolved = apiKeyValue;\n resolvedCache.set(cacheKey, resolved);\n return resolved;\n }\n }\n\n // The API key is either a SecretRef object, \"secretref-managed\", or empty.\n // Try the gateway's own auth resolution system first.\n const resolver = await getGatewayResolver();\n if (resolver) {\n try {\n const resolvedAgentDir = agentDir ?? path.join(os.homedir(), \".openclaw\", \"agents\", \"main\", \"agent\");\n const auth = await resolver({ provider: providerId, cfg: gatewayConfig, agentDir: resolvedAgentDir });\n if (auth?.apiKey) {\n resolved = auth.apiKey;\n log.debug(`resolved API key for provider \"${providerId}\" via gateway auth (source: ${auth.source ?? \"unknown\"}, mode: ${auth.mode ?? \"unknown\"})`);\n resolvedCache.set(cacheKey, resolved);\n return resolved;\n }\n } catch (err) {\n log.debug(\n `gateway auth resolution failed for provider \"${providerId}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n // Environment variable fallback\n resolved = resolveFromEnv(providerId);\n if (resolved) {\n log.debug(`resolved API key for provider \"${providerId}\" from environment variable`);\n } else {\n log.debug(`could not resolve API key for provider \"${providerId}\" — skipping`);\n }\n\n // Only cache successful resolutions — failures are retried on next call\n // so providers can recover after transient issues (e.g., 1Password agent restart)\n if (resolved) {\n resolvedCache.set(cacheKey, resolved);\n }\n return resolved;\n}\n\n/**\n * Try to resolve an API key from environment variables.\n */\nfunction resolveFromEnv(providerId: string): string | undefined {\n const normalized = providerId.toUpperCase().replace(/[^A-Z0-9]/g, \"_\");\n const candidates = [\n `${normalized}_API_KEY`,\n `${normalized}_TOKEN`,\n ];\n for (const envVar of candidates) {\n const value = readEnvVar(envVar);\n if (value && value.trim().length > 0) {\n return value.trim();\n }\n }\n return undefined;\n}\n\n/**\n * Clear the resolution cache (useful for testing or key rotation).\n */\nexport function clearSecretCache(): void {\n resolvedCache.clear();\n _resolveApiKeyForProvider = null;\n _resolverLoaded = false;\n _resolverNextRetryAt = 0;\n}\n"],"mappings":";;;;;;;;AAEA,OAAO,UAAU;AACjB,OAAO,QAAQ;AAsBf,IAAI,4BAAoD;AACxD,IAAI,kBAAkB;AACtB,IAAI,uBAAuB;AAC3B,IAAM,4BAA4B;AAClC,IAAM,gBAAgB,oBAAI,IAAgC;AAM1D,eAAe,qBAAsD;AACnE,MAAI,iBAAiB;AACnB,WAAO;AAAA,EACT;AAGA,MAAI,uBAAuB,KAAK,KAAK,IAAI,IAAI,sBAAsB;AACjE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