@ashx-j/lunr 0.1.3 → 0.1.5

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 (93) hide show
  1. package/dist/builtin-extensions/lunr-local-providers/index.d.ts.map +1 -1
  2. package/dist/builtin-extensions/lunr-local-providers/index.js +25 -3
  3. package/dist/builtin-extensions/lunr-local-providers/index.js.map +1 -1
  4. package/dist/builtin-extensions/lunr-local-providers/local-servers.d.ts.map +1 -1
  5. package/dist/builtin-extensions/lunr-local-providers/local-servers.js +4 -2
  6. package/dist/builtin-extensions/lunr-local-providers/local-servers.js.map +1 -1
  7. package/dist/builtin-extensions/pi-ollama-cloud/index.d.ts +2 -3
  8. package/dist/builtin-extensions/pi-ollama-cloud/index.d.ts.map +1 -1
  9. package/dist/builtin-extensions/pi-ollama-cloud/index.js +4 -25
  10. package/dist/builtin-extensions/pi-ollama-cloud/index.js.map +1 -1
  11. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
  12. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +3 -0
  13. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
  14. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
  15. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +4 -1
  16. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
  17. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
  18. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +4 -1
  19. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
  20. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  21. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +20 -0
  22. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  23. package/dist/builtin-extensions/pi-subagents/src/runs/shared/dynamic-fanout.d.ts.map +1 -1
  24. package/dist/builtin-extensions/pi-subagents/src/runs/shared/dynamic-fanout.js +1 -1
  25. package/dist/builtin-extensions/pi-subagents/src/runs/shared/dynamic-fanout.js.map +1 -1
  26. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts +2 -0
  27. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts.map +1 -1
  28. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.js.map +1 -1
  29. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts +2 -0
  30. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts.map +1 -1
  31. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js +2 -0
  32. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js.map +1 -1
  33. package/dist/catalog/models.json +1 -1
  34. package/dist/catalog/providers/amazon-bedrock.json +1 -1
  35. package/dist/catalog/providers/huggingface.json +1 -1
  36. package/dist/catalog/providers/opencode-go.json +1 -1
  37. package/dist/catalog/providers/openrouter.json +1 -1
  38. package/dist/catalog/providers/together.json +1 -1
  39. package/dist/catalog/providers/vercel-ai-gateway.json +1 -1
  40. package/dist/catalog/publication.json +3 -3
  41. package/dist/cli.d.ts.map +1 -1
  42. package/dist/cli.js +19 -4
  43. package/dist/cli.js.map +1 -1
  44. package/dist/core/agent-session-services.d.ts.map +1 -1
  45. package/dist/core/agent-session-services.js +4 -0
  46. package/dist/core/agent-session-services.js.map +1 -1
  47. package/dist/core/auth-storage.d.ts.map +1 -1
  48. package/dist/core/auth-storage.js +39 -7
  49. package/dist/core/auth-storage.js.map +1 -1
  50. package/dist/core/catalog-merge.d.ts.map +1 -1
  51. package/dist/core/catalog-merge.js +4 -1
  52. package/dist/core/catalog-merge.js.map +1 -1
  53. package/dist/core/grok-cli-auth.d.ts +13 -3
  54. package/dist/core/grok-cli-auth.d.ts.map +1 -1
  55. package/dist/core/grok-cli-auth.js +130 -21
  56. package/dist/core/grok-cli-auth.js.map +1 -1
  57. package/dist/core/model-runtime.d.ts +6 -0
  58. package/dist/core/model-runtime.d.ts.map +1 -1
  59. package/dist/core/model-runtime.js +38 -10
  60. package/dist/core/model-runtime.js.map +1 -1
  61. package/dist/core/official-catalog.d.ts +8 -1
  62. package/dist/core/official-catalog.d.ts.map +1 -1
  63. package/dist/core/official-catalog.js +38 -11
  64. package/dist/core/official-catalog.js.map +1 -1
  65. package/dist/core/plan-mode.d.ts +2 -0
  66. package/dist/core/plan-mode.d.ts.map +1 -1
  67. package/dist/core/plan-mode.js +7 -0
  68. package/dist/core/plan-mode.js.map +1 -1
  69. package/dist/core/subagent-permission-inherit.d.ts +38 -0
  70. package/dist/core/subagent-permission-inherit.d.ts.map +1 -0
  71. package/dist/core/subagent-permission-inherit.js +110 -0
  72. package/dist/core/subagent-permission-inherit.js.map +1 -0
  73. package/dist/core/usage-service.d.ts.map +1 -1
  74. package/dist/core/usage-service.js +5 -5
  75. package/dist/core/usage-service.js.map +1 -1
  76. package/dist/gateway/command.d.ts.map +1 -1
  77. package/dist/gateway/command.js +2 -1
  78. package/dist/gateway/command.js.map +1 -1
  79. package/dist/main.d.ts.map +1 -1
  80. package/dist/main.js +4 -0
  81. package/dist/main.js.map +1 -1
  82. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  83. package/dist/modes/interactive/interactive-mode.js +19 -8
  84. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  85. package/docs/keybindings.md +1 -0
  86. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  87. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  88. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  89. package/examples/extensions/gondolin/package-lock.json +2 -2
  90. package/examples/extensions/gondolin/package.json +1 -1
  91. package/examples/extensions/with-deps/package-lock.json +2 -2
  92. package/examples/extensions/with-deps/package.json +1 -1
  93. package/package.json +4 -4
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,CAAC,KAAK,GAAG,QAAQ,CAAC;AACzB,OAAO,CAAC,GAAG,CAAC,eAAe,GAAG,MAAM,CAAC;AACrC,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAA+B,CAAC;AAE/D,4EAA4E;AAC5E,wFAAwF;AACxF,uBAAuB,EAAE,CAAC;AAE1B,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * CLI entry point for the refactored coding agent.\n * Uses main.ts with AgentSession and new mode modules.\n *\n * Test with: npx tsx src/cli-new.ts [args...]\n */\nimport { APP_NAME } from \"./config.ts\";\nimport { configureHttpDispatcher } from \"./core/http-dispatcher.ts\";\nimport { main } from \"./main.ts\";\n\nprocess.title = APP_NAME;\nprocess.env.PI_CODING_AGENT = \"true\";\nprocess.emitWarning = (() => {}) as typeof process.emitWarning;\n\n// Configure undici's global dispatcher before provider SDKs issue requests.\n// Runtime settings are applied once SettingsManager has loaded global/project settings.\nconfigureHttpDispatcher();\n\nmain(process.argv.slice(2));\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;GAKG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,4EAA4E;AAC5E,6EAA6E;AAC7E,4EAA4E;AAC5E,IAAI,CAAC;IACJ,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9F,kBAAkB,CAAC,IAAI,CAAC,QAAQ,EAAE,eAAe,CAAC,CAAC,CAAC;AACrD,CAAC;AAAC,MAAM,CAAC;IACR,uCAAuC;AACxC,CAAC;AAED,MAAM,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,uBAAuB,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;IAC/E,MAAM,CAAC,aAAa,CAAC;IACrB,MAAM,CAAC,2BAA2B,CAAC;IACnC,MAAM,CAAC,WAAW,CAAC;CACnB,CAAC,CAAC;AAEH,OAAO,CAAC,KAAK,GAAG,QAAQ,CAAC;AACzB,OAAO,CAAC,GAAG,CAAC,eAAe,GAAG,MAAM,CAAC;AACrC,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAA+B,CAAC;AAE/D,4EAA4E;AAC5E,wFAAwF;AACxF,uBAAuB,EAAE,CAAC;AAE1B,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * CLI entry point for the refactored coding agent.\n * Uses main.ts with AgentSession and new mode modules.\n *\n * Test with: npx tsx src/cli-new.ts [args...]\n */\nimport { enableCompileCache } from \"node:module\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n// Enable before importing the rest of the graph so subsequent processes can\n// reuse V8 code cache. Helps the first start after a reboot when the OS page\n// cache is cold. Static imports are hoisted, so main is loaded dynamically.\ntry {\n\tconst agentDir = process.env.PI_CODING_AGENT_DIR?.trim() || join(homedir(), \".lunr\", \"agent\");\n\tenableCompileCache(join(agentDir, \"compile-cache\"));\n} catch {\n\t// Node < 22.8 or unwritable cache dir.\n}\n\nconst [{ APP_NAME }, { configureHttpDispatcher }, { main }] = await Promise.all([\n\timport(\"./config.ts\"),\n\timport(\"./core/http-dispatcher.ts\"),\n\timport(\"./main.ts\"),\n]);\n\nprocess.title = APP_NAME;\nprocess.env.PI_CODING_AGENT = \"true\";\nprocess.emitWarning = (() => {}) as typeof process.emitWarning;\n\n// Configure undici's global dispatcher before provider SDKs issue requests.\n// Runtime settings are applied once SettingsManager has loaded global/project settings.\nconfigureHttpDispatcher();\n\nawait main(process.argv.slice(2));\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-services.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAGnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAEN,KAAK,4BAA4B,EACjC,KAAK,cAAc,EACnB,KAAK,2BAA2B,EAChC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,KAAK,yBAAyB,EAAE,KAAK,wBAAwB,EAAsB,MAAM,UAAU,CAAC;AAC7G,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD;;;;;;GAMG;AACH,MAAM,WAAW,6BAA6B;IAC7C,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC;IACnC,OAAO,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,iCAAiC;IACjD,GAA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O,EAAE,iCAAiC,GACxC,OAAO,CAAC,oBAAoB,CAAC,CA2C/B;AAED;;;;;;GAMG;AACH,wBAAsB,8BAA8B,CACnD,OAAO,EAAE,qCAAqC,GAC5C,OAAO,CAAC,wBAAwB,CAAC,CAiBnC","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t}));\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
1
+ {"version":3,"file":"agent-session-services.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAGnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAEN,KAAK,4BAA4B,EACjC,KAAK,cAAc,EACnB,KAAK,2BAA2B,EAChC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,KAAK,yBAAyB,EAAE,KAAK,wBAAwB,EAAsB,MAA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c,EAAE,CAAC;CAC/B;AAED;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,YAAY,CAAC;IAC3B,eAAe,EAAE,eAAe,CAAC;IACjC,cAAc,EAAE,cAAc,CAAC;IAC/B,WAAW,EAAE,6BAA6B,EAAE,CAAC;CAC7C;AAkDD;;;;GAIG;AACH,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,iCAAiC,GACxC,OAAO,CAAC,oBAAoB,CAAC,CA8C/B;AAED;;;;;;GAMG;AACH,wBAAsB,8BAA8B,CACnD,OAAO,EAAE,qCAAqC,GAC5C,OAAO,CAAC,wBAAwB,CAAC,CAiBnC","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t}));\n\ttime(\"ModelRuntime.create\");\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\ttime(\"resourceLoader.reload\");\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\ttime(\"modelRuntime.refresh(cache-only)\");\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
@@ -5,6 +5,7 @@ import { ModelRuntime } from "./model-runtime.js";
5
5
  import { DefaultResourceLoader, } from "./resource-loader.js";
6
6
  import { createAgentSession } from "./sdk.js";
7
7
  import { SettingsManager } from "./settings-manager.js";
8
+ import { time } from "./timings.js";
8
9
  function applyExtensionFlagValues(resourceLoader, extensionFlagValues) {
9
10
  if (!extensionFlagValues) {
10
11
  return [];
@@ -58,6 +59,7 @@ export async function createAgentSessionServices(options) {
58
59
  authPath: join(agentDir, "auth.json"),
59
60
  modelsPath: join(agentDir, "models.json"),
60
61
  }));
62
+ time("ModelRuntime.create");
61
63
  const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);
62
64
  const resourceLoader = new DefaultResourceLoader({
63
65
  ...(options.resourceLoaderOptions ?? {}),
@@ -66,6 +68,7 @@ export async function createAgentSessionServices(options) {
66
68
  settingsManager,
67
69
  });
68
70
  await resourceLoader.reload(options.resourceLoaderReloadOptions);
71
+ time("resourceLoader.reload");
69
72
  const diagnostics = [];
70
73
  const extensionsResult = resourceLoader.getExtensions();
71
74
  for (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {
@@ -82,6 +85,7 @@ export async function createAgentSessionServices(options) {
82
85
  }
83
86
  extensionsResult.runtime.pendingProviderRegistrations = [];
84
87
  await modelRuntime.refresh({ allowNetwork: false });
88
+ time("modelRuntime.refresh(cache-only)");
85
89
  diagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));
86
90
  return {
87
91
  cwd,
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EACN,qBAAqB,GAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAiE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,CAAC,QAAQ;QACnC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY;QAC3C,eAAe,EAAE,OAAO,CAAC,QAAQ,CAAC,eAAe;QACjD,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,cAAc;QAC/C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t}));\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
1
+ {"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW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AAC,CAAC;IACzC,WAAW,CAAC,IAAI,CAAC,GAAG,wBAAwB,CAAC,cAAc,EAAE,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC;IAE3F,OAAO;QACN,GAAG;QACH,QAAQ;QACR,YAAY;QACZ,eAAe;QACf,cAAc;QACd,WAAW;KACX,CAAC;AAAA,CACF;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CACnD,OAA8C,EACV;IACpC,OAAO,kBAAkB,CAAC;QACzB,GAAG,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG;QACzB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,QAAQ;QACnC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY;QAC3C,eAAe,EAAE,OAAO,CAAC,QAAQ,CAAC,eAAe;QACjD,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,cAAc;QAC/C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@ashx-j/lunr-agent\";\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t}));\n\ttime(\"ModelRuntime.create\");\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\ttime(\"resourceLoader.reload\");\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\ttime(\"modelRuntime.refresh(cache-only)\");\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage.d.ts","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAQzF,KAAK,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAElD,KAAK,UAAU,CAAC,CAAC,IAAI;IACpB,MAAM,EAAE,CAAC,CAAC;IACV,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAIF,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACnE,aAAa,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC1F;AAED,qBAAa,sBAAuB,YAAW,kBAAkB;IAChE,OAAO,CAAC,QAAQ,CAAS;IAEzB,YAAY,QAAQ,GAAE,MAAyC,EAE9D;IAED,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,gBAAgB;IA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E,CAAC,OAAO,EAAE,UAAU,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,GACtE,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAajC;IAEK,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAO5C;IAED,wEAAwE;IAClE,IAAI,IAAI,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC,CAE/C;CACD;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CACnC,UAAU,EAAE,MAAM,EAClB,QAAQ,GAAE,MAAyC,GACjD,UAAU,GAAG,SAAS,CAOxB","sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { Credential, CredentialInfo, CredentialStore } from \"@ashx-j/lunr-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate data: AuthStorageData = {};\n\tprivate storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tasync read(provider: string): Promise<Credential | undefined> {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tthis.data = currentData;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tthis.data = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(provider: string): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tthis.data = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t});\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\treturn Object.entries(this.data).map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(\n\tproviderId: string,\n\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"auth-storage.d.ts","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAQzF,KAAK,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAElD,KAAK,UAAU,CAAC,CAAC,IAAI;IACpB,MAAM,EAAE,CAAC,CAAC;IAC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ACH,qBAAa,WAAY,YAAW,eAAe;IAClD,OAAO,CAAC,IAAI,CAAuB;IACnC,OAAO,CAAC,OAAO,CAAqB;IAEpC,OAAO,eAGN;IAED,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,WAAW,CAE5C;IAED,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CAE3D;IAED,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAE,eAAoB,GAAG,WAAW,CAIvD;IAED,OAAO,CAAC,gBAAgB;IAOxB;;OAEG;IACH,MAAM,IAAI,IAAI,CAWb;IAEK,IAAI,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAK5D;IAEK,MAAM,CACX,QAAQ,EAAE,MAAM,EAChB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,GACtE,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAajC;IAEK,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAO5C;IAED,wEAAwE;IAClE,IAAI,IAAI,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC,CAE/C;CACD;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CACnC,UAAU,EAAE,MAAM,EAClB,QAAQ,GAAE,MAAyC,GACjD,UAAU,GAAG,SAAS,CAOxB","sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { Credential, CredentialInfo, CredentialStore } from \"@ashx-j/lunr-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n/** OAuth refresh holds this lock for the IdP round-trip. 30s made a sleepy refresh look stale and let a second process spend the same token. */\nconst AUTH_LOCK_STALE_MS = 120_000;\n\nfunction writeAuthFileAtomic(authPath: string, contents: string): void {\n\tconst tmp = `${authPath}.${process.pid}.${Date.now()}.tmp`;\n\twriteFileSync(tmp, contents, AUTH_FILE_WRITE_OPTIONS);\n\ttry {\n\t\tchmodSync(tmp, 0o600);\n\t} catch {\n\t\t// mode bits are best-effort on Windows.\n\t}\n\ttry {\n\t\tif (process.platform === \"win32\" && existsSync(authPath)) {\n\t\t\twriteFileSync(authPath, contents, AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(authPath, 0o600);\n\t\t\treturn;\n\t\t}\n\t\trenameSync(tmp, authPath);\n\t\ttry {\n\t\t\tchmodSync(authPath, 0o600);\n\t\t} catch {\n\t\t\t// mode bits are best-effort on Windows.\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmp);\n\t\t} catch {\n\t\t\t// tmp already renamed, or never created.\n\t\t}\n\t}\n}\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false, stale: AUTH_LOCK_STALE_MS });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteAuthFileAtomic(this.authPath, next);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: AUTH_LOCK_STALE_MS,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteAuthFileAtomic(this.authPath, next);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate data: AuthStorageData = {};\n\tprivate storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tasync read(provider: string): Promise<Credential | undefined> {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tthis.data = currentData;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tthis.data = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(provider: string): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tthis.data = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t});\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\treturn Object.entries(this.data).map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(\n\tproviderId: string,\n\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -2,13 +2,47 @@
2
2
  * CredentialStore implementation backed by auth.json.
3
3
  * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.
4
4
  */
5
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
6
6
  import { dirname, join } from "path";
7
7
  import lockfile from "proper-lockfile";
8
8
  import { getAgentDir } from "../config.js";
9
9
  import { normalizePath } from "../utils/paths.js";
10
10
  import { resolveConfigValue } from "./resolve-config-value.js";
11
11
  const AUTH_FILE_WRITE_OPTIONS = { encoding: "utf-8", mode: 0o600 };
12
+ /** OAuth refresh holds this lock for the IdP round-trip. 30s made a sleepy refresh look stale and let a second process spend the same token. */
13
+ const AUTH_LOCK_STALE_MS = 120_000;
14
+ function writeAuthFileAtomic(authPath, contents) {
15
+ const tmp = `${authPath}.${process.pid}.${Date.now()}.tmp`;
16
+ writeFileSync(tmp, contents, AUTH_FILE_WRITE_OPTIONS);
17
+ try {
18
+ chmodSync(tmp, 0o600);
19
+ }
20
+ catch {
21
+ // mode bits are best-effort on Windows.
22
+ }
23
+ try {
24
+ if (process.platform === "win32" && existsSync(authPath)) {
25
+ writeFileSync(authPath, contents, AUTH_FILE_WRITE_OPTIONS);
26
+ chmodSync(authPath, 0o600);
27
+ return;
28
+ }
29
+ renameSync(tmp, authPath);
30
+ try {
31
+ chmodSync(authPath, 0o600);
32
+ }
33
+ catch {
34
+ // mode bits are best-effort on Windows.
35
+ }
36
+ }
37
+ finally {
38
+ try {
39
+ unlinkSync(tmp);
40
+ }
41
+ catch {
42
+ // tmp already renamed, or never created.
43
+ }
44
+ }
45
+ }
12
46
  export class FileAuthStorageBackend {
13
47
  authPath;
14
48
  constructor(authPath = join(getAgentDir(), "auth.json")) {
@@ -32,7 +66,7 @@ export class FileAuthStorageBackend {
32
66
  let lastError;
33
67
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
34
68
  try {
35
- return lockfile.lockSync(path, { realpath: false });
69
+ return lockfile.lockSync(path, { realpath: false, stale: AUTH_LOCK_STALE_MS });
36
70
  }
37
71
  catch (error) {
38
72
  const code = typeof error === "object" && error !== null && "code" in error
@@ -59,8 +93,7 @@ export class FileAuthStorageBackend {
59
93
  const current = existsSync(this.authPath) ? readFileSync(this.authPath, "utf-8") : undefined;
60
94
  const { result, next } = fn(current);
61
95
  if (next !== undefined) {
62
- writeFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);
63
- chmodSync(this.authPath, 0o600);
96
+ writeAuthFileAtomic(this.authPath, next);
64
97
  }
65
98
  return result;
66
99
  }
@@ -90,7 +123,7 @@ export class FileAuthStorageBackend {
90
123
  maxTimeout: 10000,
91
124
  randomize: true,
92
125
  },
93
- stale: 30000,
126
+ stale: AUTH_LOCK_STALE_MS,
94
127
  onCompromised: (err) => {
95
128
  lockCompromised = true;
96
129
  lockCompromisedError = err;
@@ -101,8 +134,7 @@ export class FileAuthStorageBackend {
101
134
  const { result, next } = await fn(current);
102
135
  throwIfCompromised();
103
136
  if (next !== undefined) {
104
- writeFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);
105
- chmodSync(this.authPath, 0o600);
137
+ writeAuthFileAtomic(this.authPath, next);
106
138
  }
107
139
  throwIfCompromised();
108
140
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"auth-storage.js","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAS/D,MAAM,uBAAuB,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAW,CAAC;AAO5E,MAAM,OAAO,sBAAsB;IAC1B,QAAQ,CAAS;IAEzB,YAAY,QAAQ,GAAW,IAAI,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,EAAE;QAChE,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;IAAA,CACxC;IAEO,eAAe,GAAS;QAC/B,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAA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AC,UAAU,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAAA,CAC5G;CACD;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CACnC,UAAkB,EAClB,QAAQ,GAAW,IAAI,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,EAC1B;IACzB,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAoB,CAAC;QAC3F,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { Credential, CredentialInfo, CredentialStore } from \"@ashx-j/lunr-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: 30000,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteFileSync(this.authPath, next, AUTH_FILE_WRITE_OPTIONS);\n\t\t\t\tchmodSync(this.authPath, 0o600);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate data: AuthStorageData = {};\n\tprivate storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tasync read(provider: string): Promise<Credential | undefined> {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tthis.data = currentData;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tthis.data = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(provider: string): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tthis.data = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t});\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\treturn Object.entries(this.data).map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(\n\tproviderId: string,\n\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"auth-storage.js","sourceRoot":"","sources":["../../src/core/auth-storage.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,M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AAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QAAA,CACzE,CAAC,CAAC;IAAA,CACH;IAED,wEAAwE;IACxE,KAAK,CAAC,IAAI,GAAuC;QAChD,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAAA,CAC5G;CACD;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CACnC,UAAkB,EAClB,QAAQ,GAAW,IAAI,CAAC,WAAW,EAAE,EAAE,WAAW,CAAC,EAC1B;IACzB,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAoB,CAAC;QAC3F,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC;IACzB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["/**\n * CredentialStore implementation backed by auth.json.\n * Provider auth orchestration belongs to ModelRuntime and pi-ai Models.\n */\n\nimport type { Credential, CredentialInfo, CredentialStore } from \"@ashx-j/lunr-ai\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir } from \"../config.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\nimport { resolveConfigValue } from \"./resolve-config-value.ts\";\n\ntype AuthStorageData = Record<string, Credential>;\n\ntype LockResult<T> = {\n\tresult: T;\n\tnext?: string;\n};\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n/** OAuth refresh holds this lock for the IdP round-trip. 30s made a sleepy refresh look stale and let a second process spend the same token. */\nconst AUTH_LOCK_STALE_MS = 120_000;\n\nfunction writeAuthFileAtomic(authPath: string, contents: string): void {\n\tconst tmp = `${authPath}.${process.pid}.${Date.now()}.tmp`;\n\twriteFileSync(tmp, contents, AUTH_FILE_WRITE_OPTIONS);\n\ttry {\n\t\tchmodSync(tmp, 0o600);\n\t} catch {\n\t\t// mode bits are best-effort on Windows.\n\t}\n\ttry {\n\t\tif (process.platform === \"win32\" && existsSync(authPath)) {\n\t\t\twriteFileSync(authPath, contents, AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(authPath, 0o600);\n\t\t\treturn;\n\t\t}\n\t\trenameSync(tmp, authPath);\n\t\ttry {\n\t\t\tchmodSync(authPath, 0o600);\n\t\t} catch {\n\t\t\t// mode bits are best-effort on Windows.\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmp);\n\t\t} catch {\n\t\t\t// tmp already renamed, or never created.\n\t\t}\n\t}\n}\n\nexport interface AuthStorageBackend {\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T;\n\twithLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T>;\n}\n\nexport class FileAuthStorageBackend implements AuthStorageBackend {\n\tprivate authPath: string;\n\n\tconstructor(authPath: string = join(getAgentDir(), \"auth.json\")) {\n\t\tthis.authPath = normalizePath(authPath);\n\t}\n\n\tprivate ensureParentDir(): void {\n\t\tconst dir = dirname(this.authPath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\t}\n\t}\n\n\tprivate ensureFileExists(): void {\n\t\tif (!existsSync(this.authPath)) {\n\t\t\twriteFileSync(this.authPath, \"{}\", AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(this.authPath, 0o600);\n\t\t}\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false, stale: AUTH_LOCK_STALE_MS });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire auth storage lock\");\n\t}\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\trelease = this.acquireLockSyncWithRetry(this.authPath);\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteAuthFileAtomic(this.authPath, next);\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tthis.ensureParentDir();\n\t\tthis.ensureFileExists();\n\n\t\tlet release: (() => Promise<void>) | undefined;\n\t\tlet lockCompromised = false;\n\t\tlet lockCompromisedError: Error | undefined;\n\t\tconst throwIfCompromised = () => {\n\t\t\tif (lockCompromised) {\n\t\t\t\tthrow lockCompromisedError ?? new Error(\"Auth storage lock was compromised\");\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\trelease = await lockfile.lock(this.authPath, {\n\t\t\t\tretries: {\n\t\t\t\t\tretries: 10,\n\t\t\t\t\tfactor: 2,\n\t\t\t\t\tminTimeout: 100,\n\t\t\t\t\tmaxTimeout: 10000,\n\t\t\t\t\trandomize: true,\n\t\t\t\t},\n\t\t\t\tstale: AUTH_LOCK_STALE_MS,\n\t\t\t\tonCompromised: (err) => {\n\t\t\t\t\tlockCompromised = true;\n\t\t\t\t\tlockCompromisedError = err;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthrowIfCompromised();\n\t\t\tconst current = existsSync(this.authPath) ? readFileSync(this.authPath, \"utf-8\") : undefined;\n\t\t\tconst { result, next } = await fn(current);\n\t\t\tthrowIfCompromised();\n\t\t\tif (next !== undefined) {\n\t\t\t\twriteAuthFileAtomic(this.authPath, next);\n\t\t\t}\n\t\t\tthrowIfCompromised();\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\ttry {\n\t\t\t\t\tawait release();\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore unlock errors when lock is compromised.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemoryAuthStorageBackend implements AuthStorageBackend {\n\tprivate value: string | undefined;\n\n\twithLock<T>(fn: (current: string | undefined) => LockResult<T>): T {\n\t\tconst { result, next } = fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync withLockAsync<T>(fn: (current: string | undefined) => Promise<LockResult<T>>): Promise<T> {\n\t\tconst { result, next } = await fn(this.value);\n\t\tif (next !== undefined) {\n\t\t\tthis.value = next;\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage implements CredentialStore {\n\tprivate data: AuthStorageData = {};\n\tprivate storage: AuthStorageBackend;\n\n\tprivate constructor(storage: AuthStorageBackend) {\n\t\tthis.storage = storage;\n\t\tthis.reload();\n\t}\n\n\tstatic create(authPath?: string): AuthStorage {\n\t\treturn new AuthStorage(new FileAuthStorageBackend(authPath ?? join(getAgentDir(), \"auth.json\")));\n\t}\n\n\tstatic fromStorage(storage: AuthStorageBackend): AuthStorage {\n\t\treturn new AuthStorage(storage);\n\t}\n\n\tstatic inMemory(data: AuthStorageData = {}): AuthStorage {\n\t\tconst storage = new InMemoryAuthStorageBackend();\n\t\tstorage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));\n\t\treturn AuthStorage.fromStorage(storage);\n\t}\n\n\tprivate parseStorageData(content: string | undefined): AuthStorageData {\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\treturn JSON.parse(content) as AuthStorageData;\n\t}\n\n\t/**\n\t * Reload credentials from storage.\n\t */\n\treload(): void {\n\t\tlet content: string | undefined;\n\t\ttry {\n\t\t\tthis.storage.withLock((current) => {\n\t\t\t\tcontent = current;\n\t\t\t\treturn { result: undefined };\n\t\t\t});\n\t\t\tthis.data = this.parseStorageData(content);\n\t\t} catch {\n\t\t\t// Preserve the last valid in-memory snapshot.\n\t\t}\n\t}\n\n\tasync read(provider: string): Promise<Credential | undefined> {\n\t\tconst credential = this.data[provider];\n\t\tif (credential?.type !== \"api_key\") return credential;\n\t\tif (credential.key === undefined) return credential;\n\t\treturn { ...credential, key: resolveConfigValue(credential.key, credential.env) };\n\t}\n\n\tasync modify(\n\t\tprovider: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined> {\n\t\treturn this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tconst next = await fn(currentData[provider]);\n\t\t\tif (next === undefined) {\n\t\t\t\tthis.data = currentData;\n\t\t\t\treturn { result: currentData[provider] };\n\t\t\t}\n\n\t\t\tconst merged: AuthStorageData = { ...currentData, [provider]: next };\n\t\t\tthis.data = merged;\n\t\t\treturn { result: next, next: JSON.stringify(merged, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(provider: string): Promise<void> {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst currentData = this.parseStorageData(content);\n\t\t\tdelete currentData[provider];\n\t\t\tthis.data = currentData;\n\t\t\treturn { result: undefined, next: JSON.stringify(currentData, null, 2) };\n\t\t});\n\t}\n\n\t/** List credential metadata without resolving configured key values. */\n\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\treturn Object.entries(this.data).map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n}\n\n/**\n * One-off synchronous read of a stored credential from an auth.json file,\n * without instantiating a store or resolving configured key values.\n */\nexport function readStoredCredential(\n\tproviderId: string,\n\tauthPath: string = join(getAgentDir(), \"auth.json\"),\n): Credential | undefined {\n\ttry {\n\t\tconst data = JSON.parse(readFileSync(normalizePath(authPath), \"utf-8\")) as AuthStorageData;\n\t\treturn data[providerId];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"catalog-merge.d.ts","sourceRoot":"","sources":["../../src/core/catalog-merge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAY,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAE7E,MAAM,MAAM,4BAA4B,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,QAAQ,CAAC;AAE7F,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IACxC,OAAO,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAC/B,IAAI,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAC7B,IAAI,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAC7B,QAA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AC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,eAAe,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1F,SAAS,EAAE,SAAS,6BAA6B,EAAE,CAAC;IACpD,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,yFAAyF;AACzF,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,0BAA0B,GAAG,MAAM,CA2CrF;AASD,wBAAgB,cAAc,CAC7B,OAAO,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,EAC9B,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,EAC1B,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,GACpB,GAAG,CAAC,MAAM,CAAC,CAKb","sourcesContent":["import type { Api, Model } from \"@ashx-j/lunr-ai\";\nimport { modelKey, type OfficialCatalogSource } from \"./official-catalog.ts\";\n\nexport type CatalogProviderRefreshStatus = \"ok\" | \"timeout\" | \"error\" | \"skipped\" | \"static\";\n\nexport function mergeCatalogLayers(args: {\n\tbakedIn: readonly Model<Api>[];\n\tlive?: readonly Model<Api>[];\n\tuser?: readonly Model<Api>[];\n\tofficial?: readonly Model<Api>[];\n}): Model<Api>[] {\n\tconst byId = new Map<string, Model<Api>>();\n\tfor (const model of args.bakedIn) byId.set(model.id, model);\n\tfor (const model of args.live ?? []) byId.set(model.id, model);\n\tfor (const model of args.user ?? []) byId.set(model.id, model);\n\tfor (const model of args.official ?? []) byId.set(model.id, model);\n\n\tconst seen = new Set<string>();\n\tconst result: Model<Api>[] = [];\n\tfor (const baked of args.bakedIn) {\n\t\tconst merged = byId.get(baked.id);\n\t\tif (!merged) continue;\n\t\tresult.push(merged);\n\t\tseen.add(baked.id);\n\t}\n\tfor (const model of [...(args.live ?? []), ...(args.user ?? []), ...(args.official ?? [])]) {\n\t\tif (seen.has(model.id)) continue;\n\t\tconst winner = byId.get(model.id);\n\t\tif (!winner) continue;\n\t\tresult.push(winner);\n\t\tseen.add(model.id);\n\t}\n\treturn result;\n}\n\nexport class CatalogOverlaySource {\n\tprivate official = new Map<string, Model<Api>[]>();\n\tprivate user = new Map<string, Model<Api>[]>();\n\tprivate live = new Map<string, Model<Api>[]>();\n\n\tsetOfficial(models: readonly Model<Api>[]): void {\n\t\tthis.official = groupByProvider(models);\n\t}\n\n\tsetUser(models: readonly Model<Api>[]): void {\n\t\tthis.user = groupByProvider(models);\n\t}\n\n\tsetLive(providerId: string, models: readonly Model<Api>[]): void {\n\t\tthis.live.set(providerId, [...models]);\n\t}\n\n\tofficialFor(providerId: string): Model<Api>[] {\n\t\treturn this.official.get(providerId) ?? [];\n\t}\n\n\tuserFor(providerId: string): Model<Api>[] {\n\t\treturn this.user.get(providerId) ?? [];\n\t}\n\n\tliveFor(providerId: string): Model<Api>[] {\n\t\treturn this.live.get(providerId) ?? [];\n\t}\n}\n\nfunction groupByProvider(models: readonly Model<Api>[]): Map<string, Model<Api>[]> {\n\tconst byProvider = new Map<string, Model<Api>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\treturn byProvider;\n}\n\nexport function withCatalogOverlay<T extends { id: string; getModels: () => readonly Model<Api>[] }>(\n\tprovider: T,\n\toverlay: CatalogOverlaySource,\n): T {\n\tconst bakedIn = () => provider.getModels();\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeCatalogLayers({\n\t\t\t\tbakedIn: bakedIn(),\n\t\t\t\tlive: overlay.liveFor(provider.id),\n\t\t\t\tuser: overlay.userFor(provider.id),\n\t\t\t\tofficial: overlay.officialFor(provider.id),\n\t\t\t}),\n\t};\n}\n\nexport interface CatalogRefreshProviderSummary {\n\tid: string;\n\tstatus: CatalogProviderRefreshStatus;\n\tadded?: number;\n\ttotal?: number;\n\terror?: string;\n}\n\nexport interface CatalogRefreshSummaryInput {\n\tofficial?: { source: OfficialCatalogSource; modelCount: number; evictedUserRows: number };\n\tproviders: readonly CatalogRefreshProviderSummary[];\n\tasked?: readonly string[];\n\textraDefaults?: number;\n\tollama?: string;\n}\n\n/** Build the /refresh toast. One hung provider must not become a global timeout line. */\nexport function formatCatalogRefreshSummary(input: CatalogRefreshSummaryInput): string {\n\tconst parts: string[] = [];\n\tif (input.official?.source === \"github\") {\n\t\tconst evicted =\n\t\t\tinput.official.evictedUserRows > 0 ? `; replaced ${input.official.evictedUserRows} user-filled row` : \"\";\n\t\tconst plural = input.official.evictedUserRows === 1 ? \"\" : input.official.evictedUserRows > 0 ? \"s\" : \"\";\n\t\tparts.push(`Official catalog updated (${input.official.modelCount} models)${evicted}${plural}.`);\n\t}\n\n\tconst refreshed: string[] = [];\n\tconst failed: string[] = [];\n\tfor (const provider of input.providers) {\n\t\tif (provider.status === \"ok\") {\n\t\t\tconst added = provider.added ?? 0;\n\t\t\tconst total = provider.total ?? 0;\n\t\t\trefreshed.push(added > 0 ? `${provider.id} (+${added})` : `${provider.id} (${total})`);\n\t\t} else if (provider.status === \"timeout\") {\n\t\t\tfailed.push(`${provider.id} timed out (cached)`);\n\t\t} else if (provider.status === \"error\") {\n\t\t\tfailed.push(formatLiveProviderError(provider));\n\t\t}\n\t}\n\n\tif (refreshed.length > 0) {\n\t\tparts.push(`Refreshed ${refreshed.join(\", \")}.`);\n\t} else if (input.providers.some((provider) => provider.status === \"ok\")) {\n\t\tparts.push(\"Refreshed model catalogs.\");\n\t}\n\n\tif (failed.length > 0) {\n\t\tparts.push(`${failed.join(\"; \")}.`);\n\t}\n\n\tif (input.asked && input.asked.length > 0) {\n\t\tparts.push(`Asked for missing metadata on ${input.asked.join(\", \")}.`);\n\t}\n\tif (input.extraDefaults && input.extraDefaults > 0) {\n\t\tparts.push(`+${input.extraDefaults} more using defaults.`);\n\t}\n\tif (input.ollama) parts.push(input.ollama);\n\n\tif (parts.length === 0) return \"Model catalogs refreshed.\";\n\treturn parts.join(\" \");\n}\n\nfunction formatLiveProviderError(provider: CatalogRefreshProviderSummary): string {\n\tif (provider.id === \"xai\" && provider.error && /invalid_grant|oauth refresh failed/i.test(provider.error)) {\n\t\treturn \"xai login expired (run /login xai)\";\n\t}\n\treturn provider.error ? `${provider.id} failed (${provider.error})` : `${provider.id} failed`;\n}\n\nexport function knownModelKeys(\n\tbakedIn: readonly Model<Api>[],\n\tofficial: Iterable<string>,\n\tuser: Iterable<string>,\n): Set<string> {\n\tconst keys = new Set<string>(official);\n\tfor (const key of user) keys.add(key);\n\tfor (const model of bakedIn) keys.add(modelKey(model.provider, model.id));\n\treturn keys;\n}\n"]}
1
+ {"version":3,"file":"catalog-merge.d.ts","sourceRoot":"","sources":["../../src/core/catalog-merge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAY,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAE7E,MAAM,MAAM,4BAA4B,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,QAAQ,CAAC;AAE7F,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IACxC,OAAO,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAC/B,IAAI,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAC7B,IAAI,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAC7B,QAAQ,CAAC,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;CACjC,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAuBf;AAED,qBAAa,oBAAoB;IAChC,OAAO,CAAC,QAAQ,CAAmC;IACnD,OAAO,CAAC,IAAI,CAAmC;IAC/C,OAAO,CAAC,IAAI,CAAmC;IAE/C,WAAW,CAAC,MAAM,EA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ED,yFAAyF;AACzF,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,0BAA0B,GAAG,MAAM,CA2CrF;AAcD,wBAAgB,cAAc,CAC7B,OAAO,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,EAC9B,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,EAC1B,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,GACpB,GAAG,CAAC,MAAM,CAAC,CAKb","sourcesContent":["import type { Api, Model } from \"@ashx-j/lunr-ai\";\nimport { modelKey, type OfficialCatalogSource } from \"./official-catalog.ts\";\n\nexport type CatalogProviderRefreshStatus = \"ok\" | \"timeout\" | \"error\" | \"skipped\" | \"static\";\n\nexport function mergeCatalogLayers(args: {\n\tbakedIn: readonly Model<Api>[];\n\tlive?: readonly Model<Api>[];\n\tuser?: readonly Model<Api>[];\n\tofficial?: readonly Model<Api>[];\n}): Model<Api>[] {\n\tconst byId = new Map<string, Model<Api>>();\n\tfor (const model of args.bakedIn) byId.set(model.id, model);\n\tfor (const model of args.live ?? []) byId.set(model.id, model);\n\tfor (const model of args.user ?? []) byId.set(model.id, model);\n\tfor (const model of args.official ?? []) byId.set(model.id, model);\n\n\tconst seen = new Set<string>();\n\tconst result: Model<Api>[] = [];\n\tfor (const baked of args.bakedIn) {\n\t\tconst merged = byId.get(baked.id);\n\t\tif (!merged) continue;\n\t\tresult.push(merged);\n\t\tseen.add(baked.id);\n\t}\n\tfor (const model of [...(args.live ?? []), ...(args.user ?? []), ...(args.official ?? [])]) {\n\t\tif (seen.has(model.id)) continue;\n\t\tconst winner = byId.get(model.id);\n\t\tif (!winner) continue;\n\t\tresult.push(winner);\n\t\tseen.add(model.id);\n\t}\n\treturn result;\n}\n\nexport class CatalogOverlaySource {\n\tprivate official = new Map<string, Model<Api>[]>();\n\tprivate user = new Map<string, Model<Api>[]>();\n\tprivate live = new Map<string, Model<Api>[]>();\n\n\tsetOfficial(models: readonly Model<Api>[]): void {\n\t\tthis.official = groupByProvider(models);\n\t}\n\n\tsetUser(models: readonly Model<Api>[]): void {\n\t\tthis.user = groupByProvider(models);\n\t}\n\n\tsetLive(providerId: string, models: readonly Model<Api>[]): void {\n\t\tthis.live.set(providerId, [...models]);\n\t}\n\n\tofficialFor(providerId: string): Model<Api>[] {\n\t\treturn this.official.get(providerId) ?? [];\n\t}\n\n\tuserFor(providerId: string): Model<Api>[] {\n\t\treturn this.user.get(providerId) ?? [];\n\t}\n\n\tliveFor(providerId: string): Model<Api>[] {\n\t\treturn this.live.get(providerId) ?? [];\n\t}\n}\n\nfunction groupByProvider(models: readonly Model<Api>[]): Map<string, Model<Api>[]> {\n\tconst byProvider = new Map<string, Model<Api>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\treturn byProvider;\n}\n\nexport function withCatalogOverlay<T extends { id: string; getModels: () => readonly Model<Api>[] }>(\n\tprovider: T,\n\toverlay: CatalogOverlaySource,\n): T {\n\tconst bakedIn = () => provider.getModels();\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeCatalogLayers({\n\t\t\t\tbakedIn: bakedIn(),\n\t\t\t\tlive: overlay.liveFor(provider.id),\n\t\t\t\tuser: overlay.userFor(provider.id),\n\t\t\t\tofficial: overlay.officialFor(provider.id),\n\t\t\t}),\n\t};\n}\n\nexport interface CatalogRefreshProviderSummary {\n\tid: string;\n\tstatus: CatalogProviderRefreshStatus;\n\tadded?: number;\n\ttotal?: number;\n\terror?: string;\n}\n\nexport interface CatalogRefreshSummaryInput {\n\tofficial?: { source: OfficialCatalogSource; modelCount: number; evictedUserRows: number };\n\tproviders: readonly CatalogRefreshProviderSummary[];\n\tasked?: readonly string[];\n\textraDefaults?: number;\n\tollama?: string;\n}\n\n/** Build the /refresh toast. One hung provider must not become a global timeout line. */\nexport function formatCatalogRefreshSummary(input: CatalogRefreshSummaryInput): string {\n\tconst parts: string[] = [];\n\tif (input.official?.source === \"github\") {\n\t\tconst evicted =\n\t\t\tinput.official.evictedUserRows > 0 ? `; replaced ${input.official.evictedUserRows} user-filled row` : \"\";\n\t\tconst plural = input.official.evictedUserRows === 1 ? \"\" : input.official.evictedUserRows > 0 ? \"s\" : \"\";\n\t\tparts.push(`Official catalog updated (${input.official.modelCount} models)${evicted}${plural}.`);\n\t}\n\n\tconst refreshed: string[] = [];\n\tconst failed: string[] = [];\n\tfor (const provider of input.providers) {\n\t\tif (provider.status === \"ok\") {\n\t\t\tconst added = provider.added ?? 0;\n\t\t\tconst total = provider.total ?? 0;\n\t\t\trefreshed.push(added > 0 ? `${provider.id} (+${added})` : `${provider.id} (${total})`);\n\t\t} else if (provider.status === \"timeout\") {\n\t\t\tfailed.push(`${provider.id} timed out (cached)`);\n\t\t} else if (provider.status === \"error\") {\n\t\t\tfailed.push(formatLiveProviderError(provider));\n\t\t}\n\t}\n\n\tif (refreshed.length > 0) {\n\t\tparts.push(`Refreshed ${refreshed.join(\", \")}.`);\n\t} else if (input.providers.some((provider) => provider.status === \"ok\")) {\n\t\tparts.push(\"Refreshed model catalogs.\");\n\t}\n\n\tif (failed.length > 0) {\n\t\tparts.push(`${failed.join(\"; \")}.`);\n\t}\n\n\tif (input.asked && input.asked.length > 0) {\n\t\tparts.push(`Asked for missing metadata on ${input.asked.join(\", \")}.`);\n\t}\n\tif (input.extraDefaults && input.extraDefaults > 0) {\n\t\tparts.push(`+${input.extraDefaults} more using defaults.`);\n\t}\n\tif (input.ollama) parts.push(input.ollama);\n\n\tif (parts.length === 0) return \"Model catalogs refreshed.\";\n\treturn parts.join(\" \");\n}\n\nfunction formatLiveProviderError(provider: CatalogRefreshProviderSummary): string {\n\tif (\n\t\tprovider.id === \"xai\" &&\n\t\tprovider.error &&\n\t\t/invalid_grant|refresh token revoked/i.test(provider.error) &&\n\t\t!/timed out|aborted|cancelled|ECONN|ENOTFOUND|network/i.test(provider.error)\n\t) {\n\t\treturn \"xai login expired (run /login xai)\";\n\t}\n\treturn provider.error ? `${provider.id} failed (${provider.error})` : `${provider.id} failed`;\n}\n\nexport function knownModelKeys(\n\tbakedIn: readonly Model<Api>[],\n\tofficial: Iterable<string>,\n\tuser: Iterable<string>,\n): Set<string> {\n\tconst keys = new Set<string>(official);\n\tfor (const key of user) keys.add(key);\n\tfor (const model of bakedIn) keys.add(modelKey(model.provider, model.id));\n\treturn keys;\n}\n"]}
@@ -118,7 +118,10 @@ export function formatCatalogRefreshSummary(input) {
118
118
  return parts.join(" ");
119
119
  }
120
120
  function formatLiveProviderError(provider) {
121
- if (provider.id === "xai" && provider.error && /invalid_grant|oauth refresh failed/i.test(provider.error)) {
121
+ if (provider.id === "xai" &&
122
+ provider.error &&
123
+ /invalid_grant|refresh token revoked/i.test(provider.error) &&
124
+ !/timed out|aborted|cancelled|ECONN|ENOTFOUND|network/i.test(provider.error)) {
122
125
  return "xai login expired (run /login xai)";
123
126
  }
124
127
  return provider.error ? `${provider.id} failed (${provider.error})` : `${provider.id} failed`;
@@ -1 +1 @@
1
- {"version":3,"file":"catalog-merge.js","sourceRoot":"","sources":["../../src/core/catalog-merge.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAA8B,MAAM,uBAAuB,CAAC;AAI7E,MAAM,UAAU,kBAAkB,CAAC,IAKlC,EAAgB;IAChB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAsB,CAAC;IAC3C,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO;QAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,IAAI,IAAI,EAAE;QAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC/D,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,IAAI,IAAI,EAAE;QAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC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CAAC,CAAC;IAC1E,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import type { Api, Model } from \"@ashx-j/lunr-ai\";\nimport { modelKey, type OfficialCatalogSource } from \"./official-catalog.ts\";\n\nexport type CatalogProviderRefreshStatus = \"ok\" | \"timeout\" | \"error\" | \"skipped\" | \"static\";\n\nexport function mergeCatalogLayers(args: {\n\tbakedIn: readonly Model<Api>[];\n\tlive?: readonly Model<Api>[];\n\tuser?: readonly Model<Api>[];\n\tofficial?: readonly Model<Api>[];\n}): Model<Api>[] {\n\tconst byId = new Map<string, Model<Api>>();\n\tfor (const model of args.bakedIn) byId.set(model.id, model);\n\tfor (const model of args.live ?? []) byId.set(model.id, model);\n\tfor (const model of args.user ?? []) byId.set(model.id, model);\n\tfor (const model of args.official ?? []) byId.set(model.id, model);\n\n\tconst seen = new Set<string>();\n\tconst result: Model<Api>[] = [];\n\tfor (const baked of args.bakedIn) {\n\t\tconst merged = byId.get(baked.id);\n\t\tif (!merged) continue;\n\t\tresult.push(merged);\n\t\tseen.add(baked.id);\n\t}\n\tfor (const model of [...(args.live ?? []), ...(args.user ?? []), ...(args.official ?? [])]) {\n\t\tif (seen.has(model.id)) continue;\n\t\tconst winner = byId.get(model.id);\n\t\tif (!winner) continue;\n\t\tresult.push(winner);\n\t\tseen.add(model.id);\n\t}\n\treturn result;\n}\n\nexport class CatalogOverlaySource {\n\tprivate official = new Map<string, Model<Api>[]>();\n\tprivate user = new Map<string, Model<Api>[]>();\n\tprivate live = new Map<string, Model<Api>[]>();\n\n\tsetOfficial(models: readonly Model<Api>[]): void {\n\t\tthis.official = groupByProvider(models);\n\t}\n\n\tsetUser(models: readonly Model<Api>[]): void {\n\t\tthis.user = groupByProvider(models);\n\t}\n\n\tsetLive(providerId: string, models: readonly Model<Api>[]): void {\n\t\tthis.live.set(providerId, [...models]);\n\t}\n\n\tofficialFor(providerId: string): Model<Api>[] {\n\t\treturn this.official.get(providerId) ?? [];\n\t}\n\n\tuserFor(providerId: string): Model<Api>[] {\n\t\treturn this.user.get(providerId) ?? [];\n\t}\n\n\tliveFor(providerId: string): Model<Api>[] {\n\t\treturn this.live.get(providerId) ?? [];\n\t}\n}\n\nfunction groupByProvider(models: readonly Model<Api>[]): Map<string, Model<Api>[]> {\n\tconst byProvider = new Map<string, Model<Api>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\treturn byProvider;\n}\n\nexport function withCatalogOverlay<T extends { id: string; getModels: () => readonly Model<Api>[] }>(\n\tprovider: T,\n\toverlay: CatalogOverlaySource,\n): T {\n\tconst bakedIn = () => provider.getModels();\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeCatalogLayers({\n\t\t\t\tbakedIn: bakedIn(),\n\t\t\t\tlive: overlay.liveFor(provider.id),\n\t\t\t\tuser: overlay.userFor(provider.id),\n\t\t\t\tofficial: overlay.officialFor(provider.id),\n\t\t\t}),\n\t};\n}\n\nexport interface CatalogRefreshProviderSummary {\n\tid: string;\n\tstatus: CatalogProviderRefreshStatus;\n\tadded?: number;\n\ttotal?: number;\n\terror?: string;\n}\n\nexport interface CatalogRefreshSummaryInput {\n\tofficial?: { source: OfficialCatalogSource; modelCount: number; evictedUserRows: number };\n\tproviders: readonly CatalogRefreshProviderSummary[];\n\tasked?: readonly string[];\n\textraDefaults?: number;\n\tollama?: string;\n}\n\n/** Build the /refresh toast. One hung provider must not become a global timeout line. */\nexport function formatCatalogRefreshSummary(input: CatalogRefreshSummaryInput): string {\n\tconst parts: string[] = [];\n\tif (input.official?.source === \"github\") {\n\t\tconst evicted =\n\t\t\tinput.official.evictedUserRows > 0 ? `; replaced ${input.official.evictedUserRows} user-filled row` : \"\";\n\t\tconst plural = input.official.evictedUserRows === 1 ? \"\" : input.official.evictedUserRows > 0 ? \"s\" : \"\";\n\t\tparts.push(`Official catalog updated (${input.official.modelCount} models)${evicted}${plural}.`);\n\t}\n\n\tconst refreshed: string[] = [];\n\tconst failed: string[] = [];\n\tfor (const provider of input.providers) {\n\t\tif (provider.status === \"ok\") {\n\t\t\tconst added = provider.added ?? 0;\n\t\t\tconst total = provider.total ?? 0;\n\t\t\trefreshed.push(added > 0 ? `${provider.id} (+${added})` : `${provider.id} (${total})`);\n\t\t} else if (provider.status === \"timeout\") {\n\t\t\tfailed.push(`${provider.id} timed out (cached)`);\n\t\t} else if (provider.status === \"error\") {\n\t\t\tfailed.push(formatLiveProviderError(provider));\n\t\t}\n\t}\n\n\tif (refreshed.length > 0) {\n\t\tparts.push(`Refreshed ${refreshed.join(\", \")}.`);\n\t} else if (input.providers.some((provider) => provider.status === \"ok\")) {\n\t\tparts.push(\"Refreshed model catalogs.\");\n\t}\n\n\tif (failed.length > 0) {\n\t\tparts.push(`${failed.join(\"; \")}.`);\n\t}\n\n\tif (input.asked && input.asked.length > 0) {\n\t\tparts.push(`Asked for missing metadata on ${input.asked.join(\", \")}.`);\n\t}\n\tif (input.extraDefaults && input.extraDefaults > 0) {\n\t\tparts.push(`+${input.extraDefaults} more using defaults.`);\n\t}\n\tif (input.ollama) parts.push(input.ollama);\n\n\tif (parts.length === 0) return \"Model catalogs refreshed.\";\n\treturn parts.join(\" \");\n}\n\nfunction formatLiveProviderError(provider: CatalogRefreshProviderSummary): string {\n\tif (provider.id === \"xai\" && provider.error && /invalid_grant|oauth refresh failed/i.test(provider.error)) {\n\t\treturn \"xai login expired (run /login xai)\";\n\t}\n\treturn provider.error ? `${provider.id} failed (${provider.error})` : `${provider.id} failed`;\n}\n\nexport function knownModelKeys(\n\tbakedIn: readonly Model<Api>[],\n\tofficial: Iterable<string>,\n\tuser: Iterable<string>,\n): Set<string> {\n\tconst keys = new Set<string>(official);\n\tfor (const key of user) keys.add(key);\n\tfor (const model of bakedIn) keys.add(modelKey(model.provider, model.id));\n\treturn keys;\n}\n"]}
1
+ {"version":3,"file":"catalog-merge.js","sourceRoot":"","sources":["../../src/core/catalog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Q,CAAC,KAAK,CAAC,EAC3E,CAAC;QACF,OAAO,oCAAoC,CAAC;IAC7C,CAAC;IACD,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,EAAE,YAAY,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,EAAE,SAAS,CAAC;AAAA,CAC9F;AAED,MAAM,UAAU,cAAc,CAC7B,OAA8B,EAC9B,QAA0B,EAC1B,IAAsB,EACR;IACd,MAAM,IAAI,GAAG,IAAI,GAAG,CAAS,QAAQ,CAAC,CAAC;IACvC,KAAK,MAAM,GAAG,IAAI,IAAI;QAAE,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACtC,KAAK,MAAM,KAAK,IAAI,OAAO;QAAE,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1E,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import type { Api, Model } from \"@ashx-j/lunr-ai\";\nimport { modelKey, type OfficialCatalogSource } from \"./official-catalog.ts\";\n\nexport type CatalogProviderRefreshStatus = \"ok\" | \"timeout\" | \"error\" | \"skipped\" | \"static\";\n\nexport function mergeCatalogLayers(args: {\n\tbakedIn: readonly Model<Api>[];\n\tlive?: readonly Model<Api>[];\n\tuser?: readonly Model<Api>[];\n\tofficial?: readonly Model<Api>[];\n}): Model<Api>[] {\n\tconst byId = new Map<string, Model<Api>>();\n\tfor (const model of args.bakedIn) byId.set(model.id, model);\n\tfor (const model of args.live ?? []) byId.set(model.id, model);\n\tfor (const model of args.user ?? []) byId.set(model.id, model);\n\tfor (const model of args.official ?? []) byId.set(model.id, model);\n\n\tconst seen = new Set<string>();\n\tconst result: Model<Api>[] = [];\n\tfor (const baked of args.bakedIn) {\n\t\tconst merged = byId.get(baked.id);\n\t\tif (!merged) continue;\n\t\tresult.push(merged);\n\t\tseen.add(baked.id);\n\t}\n\tfor (const model of [...(args.live ?? []), ...(args.user ?? []), ...(args.official ?? [])]) {\n\t\tif (seen.has(model.id)) continue;\n\t\tconst winner = byId.get(model.id);\n\t\tif (!winner) continue;\n\t\tresult.push(winner);\n\t\tseen.add(model.id);\n\t}\n\treturn result;\n}\n\nexport class CatalogOverlaySource {\n\tprivate official = new Map<string, Model<Api>[]>();\n\tprivate user = new Map<string, Model<Api>[]>();\n\tprivate live = new Map<string, Model<Api>[]>();\n\n\tsetOfficial(models: readonly Model<Api>[]): void {\n\t\tthis.official = groupByProvider(models);\n\t}\n\n\tsetUser(models: readonly Model<Api>[]): void {\n\t\tthis.user = groupByProvider(models);\n\t}\n\n\tsetLive(providerId: string, models: readonly Model<Api>[]): void {\n\t\tthis.live.set(providerId, [...models]);\n\t}\n\n\tofficialFor(providerId: string): Model<Api>[] {\n\t\treturn this.official.get(providerId) ?? [];\n\t}\n\n\tuserFor(providerId: string): Model<Api>[] {\n\t\treturn this.user.get(providerId) ?? [];\n\t}\n\n\tliveFor(providerId: string): Model<Api>[] {\n\t\treturn this.live.get(providerId) ?? [];\n\t}\n}\n\nfunction groupByProvider(models: readonly Model<Api>[]): Map<string, Model<Api>[]> {\n\tconst byProvider = new Map<string, Model<Api>[]>();\n\tfor (const model of models) {\n\t\tconst list = byProvider.get(model.provider) ?? [];\n\t\tlist.push(model);\n\t\tbyProvider.set(model.provider, list);\n\t}\n\treturn byProvider;\n}\n\nexport function withCatalogOverlay<T extends { id: string; getModels: () => readonly Model<Api>[] }>(\n\tprovider: T,\n\toverlay: CatalogOverlaySource,\n): T {\n\tconst bakedIn = () => provider.getModels();\n\treturn {\n\t\t...provider,\n\t\tgetModels: () =>\n\t\t\tmergeCatalogLayers({\n\t\t\t\tbakedIn: bakedIn(),\n\t\t\t\tlive: overlay.liveFor(provider.id),\n\t\t\t\tuser: overlay.userFor(provider.id),\n\t\t\t\tofficial: overlay.officialFor(provider.id),\n\t\t\t}),\n\t};\n}\n\nexport interface CatalogRefreshProviderSummary {\n\tid: string;\n\tstatus: CatalogProviderRefreshStatus;\n\tadded?: number;\n\ttotal?: number;\n\terror?: string;\n}\n\nexport interface CatalogRefreshSummaryInput {\n\tofficial?: { source: OfficialCatalogSource; modelCount: number; evictedUserRows: number };\n\tproviders: readonly CatalogRefreshProviderSummary[];\n\tasked?: readonly string[];\n\textraDefaults?: number;\n\tollama?: string;\n}\n\n/** Build the /refresh toast. One hung provider must not become a global timeout line. */\nexport function formatCatalogRefreshSummary(input: CatalogRefreshSummaryInput): string {\n\tconst parts: string[] = [];\n\tif (input.official?.source === \"github\") {\n\t\tconst evicted =\n\t\t\tinput.official.evictedUserRows > 0 ? `; replaced ${input.official.evictedUserRows} user-filled row` : \"\";\n\t\tconst plural = input.official.evictedUserRows === 1 ? \"\" : input.official.evictedUserRows > 0 ? \"s\" : \"\";\n\t\tparts.push(`Official catalog updated (${input.official.modelCount} models)${evicted}${plural}.`);\n\t}\n\n\tconst refreshed: string[] = [];\n\tconst failed: string[] = [];\n\tfor (const provider of input.providers) {\n\t\tif (provider.status === \"ok\") {\n\t\t\tconst added = provider.added ?? 0;\n\t\t\tconst total = provider.total ?? 0;\n\t\t\trefreshed.push(added > 0 ? `${provider.id} (+${added})` : `${provider.id} (${total})`);\n\t\t} else if (provider.status === \"timeout\") {\n\t\t\tfailed.push(`${provider.id} timed out (cached)`);\n\t\t} else if (provider.status === \"error\") {\n\t\t\tfailed.push(formatLiveProviderError(provider));\n\t\t}\n\t}\n\n\tif (refreshed.length > 0) {\n\t\tparts.push(`Refreshed ${refreshed.join(\", \")}.`);\n\t} else if (input.providers.some((provider) => provider.status === \"ok\")) {\n\t\tparts.push(\"Refreshed model catalogs.\");\n\t}\n\n\tif (failed.length > 0) {\n\t\tparts.push(`${failed.join(\"; \")}.`);\n\t}\n\n\tif (input.asked && input.asked.length > 0) {\n\t\tparts.push(`Asked for missing metadata on ${input.asked.join(\", \")}.`);\n\t}\n\tif (input.extraDefaults && input.extraDefaults > 0) {\n\t\tparts.push(`+${input.extraDefaults} more using defaults.`);\n\t}\n\tif (input.ollama) parts.push(input.ollama);\n\n\tif (parts.length === 0) return \"Model catalogs refreshed.\";\n\treturn parts.join(\" \");\n}\n\nfunction formatLiveProviderError(provider: CatalogRefreshProviderSummary): string {\n\tif (\n\t\tprovider.id === \"xai\" &&\n\t\tprovider.error &&\n\t\t/invalid_grant|refresh token revoked/i.test(provider.error) &&\n\t\t!/timed out|aborted|cancelled|ECONN|ENOTFOUND|network/i.test(provider.error)\n\t) {\n\t\treturn \"xai login expired (run /login xai)\";\n\t}\n\treturn provider.error ? `${provider.id} failed (${provider.error})` : `${provider.id} failed`;\n}\n\nexport function knownModelKeys(\n\tbakedIn: readonly Model<Api>[],\n\tofficial: Iterable<string>,\n\tuser: Iterable<string>,\n): Set<string> {\n\tconst keys = new Set<string>(official);\n\tfor (const key of user) keys.add(key);\n\tfor (const model of bakedIn) keys.add(modelKey(model.provider, model.id));\n\treturn keys;\n}\n"]}
@@ -2,9 +2,8 @@
2
2
  * Official Grok CLI SuperGrok session (`~/.grok/auth.json`).
3
3
  *
4
4
  * lunR and Grok CLI share xAI client `b1a00492-073a-47ea-816f-4c329264a828`.
5
- * A later `grok login` revokes lunR's refresh token; this module reads the
6
- * still-live Grok CLI entry and write-throughs rotated tokens so the two
7
- * CLIs do not fight.
5
+ * xAI rotates refresh tokens and revokes the family on reuse, so this module
6
+ * must never write a rotated-out refresh back over a newer one.
8
7
  */
9
8
  import type { Credential, CredentialStore, OAuthCredential } from "@ashx-j/lunr-ai";
10
9
  export declare const XAI_PROVIDER_ID = "xai";
@@ -14,6 +13,8 @@ export declare function grokHomeDir(grokHome?: string): string;
14
13
  export declare function grokAuthPath(grokHome?: string): string;
15
14
  export declare function grokOidcEntryKey(clientId?: string): string;
16
15
  export declare function parseGrokExpiresAt(value: unknown): number | undefined;
16
+ /** Grok CLI deserializes `expires_at` as RFC3339, not epoch ms. */
17
+ export declare function formatGrokExpiresAt(expires: number): string;
17
18
  export declare function grokEntryToOAuth(entry: unknown): OAuthCredential | undefined;
18
19
  export declare function readGrokCliXaiOAuth(options?: {
19
20
  grokHome?: string;
@@ -21,6 +22,15 @@ export declare function readGrokCliXaiOAuth(options?: {
21
22
  export declare function hasGrokCliXaiAuth(options?: {
22
23
  grokHome?: string;
23
24
  }): boolean;
25
+ /**
26
+ * Pick the live SuperGrok session.
27
+ *
28
+ * lunR stores `expires` 5 minutes early. Grok CLI stores the server expiry.
29
+ * A raw `>=` compare therefore treats a just-rotated lunR token as older than
30
+ * the still-unrotated Grok file and writes the dead refresh back. When both
31
+ * look live and the refresh tokens differ, keep lunR; `modify` retries Grok
32
+ * only after `invalid_grant`.
33
+ */
24
34
  export declare function chooseXaiOAuth(lunr: Credential | undefined, grok: OAuthCredential | undefined): Credential | undefined;
25
35
  export declare function writeGrokCliXaiOAuth(credential: OAuthCredential, options?: {
26
36
  grokHome?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"grok-cli-auth.d.ts","sourceRoot":"","sources":["../../src/core/grok-cli-auth.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,KAAK,EAAE,UAAU,EAAkB,eAAe,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAG1G,eAAO,MAAM,eAAe,QAAQ,CAAC;AACrC,wEAAwE;AACxE,eAAO,MAAM,sBAAsB,yCAAyC,CAAC;AAI7E,wBAAgB,WAAW,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAKrD;AAED,wBAAgB,YAAY,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,GAAE,MAA+B,GAAG,MAAM,CAElF;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAarE;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,eAAe,GAAG,SAAS,CAQ5E;AAED,wBAAgB,mBAAmB,CAAC,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,eAAe,GAAG,SAAS,CASpG;AAED,wBAAgB,iBAAiB,CAAC,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,OAAO,CAE9E;AAED,wBAAgB,cAAc,CAC7B,IAAI,EAAE,UAAU,GAAG,SAAS,EAC5B,IAAI,EAAE,eAAe,GAAG,SAAS,GAC/B,UAAU,GAAG,SAAS,CAKxB;AAwBD,wBAAgB,oBAAoB,CACnC,UAAU,EAAE,eAAe,EAC3B,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC7D,OAAO,CA8CT;AAED,wBAAgB,yBAAyB,CACxC,KAAK,EAAE,eAAe,EACtB,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GACjC,eAAe,CAyDjB","sourcesContent":["/**\n * Official Grok CLI SuperGrok session (`~/.grok/auth.json`).\n *\n * lunR and Grok CLI share xAI client `b1a00492-073a-47ea-816f-4c329264a828`.\n * A later `grok login` revokes lunR's refresh token; this module reads the\n * still-live Grok CLI entry and write-throughs rotated tokens so the two\n * CLIs do not fight.\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Credential, CredentialInfo, CredentialStore, OAuthCredential } from \"@ashx-j/lunr-ai\";\nimport lockfile from \"proper-lockfile\";\n\nexport const XAI_PROVIDER_ID = \"xai\";\n/** Same client as packages/ai/src/auth/oauth/xai.ts `XAI_CLIENT_ID`. */\nexport const XAI_GROK_CLI_CLIENT_ID = \"b1a00492-073a-47ea-816f-4c329264a828\";\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport function grokHomeDir(grokHome?: string): string {\n\tif (grokHome) return grokHome;\n\tconst fromEnv = process.env.GROK_HOME?.trim();\n\tif (fromEnv) return fromEnv;\n\treturn join(homedir(), \".grok\");\n}\n\nexport function grokAuthPath(grokHome?: string): string {\n\treturn join(grokHomeDir(grokHome), \"auth.json\");\n}\n\nexport function grokOidcEntryKey(clientId: string = XAI_GROK_CLI_CLIENT_ID): string {\n\treturn `https://auth.x.ai::${clientId}`;\n}\n\nexport function parseGrokExpiresAt(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value) && value > 0) {\n\t\treturn value < 1e12 ? Math.round(value * 1000) : Math.round(value);\n\t}\n\tif (typeof value === \"string\" && value.trim()) {\n\t\tconst numeric = Number(value);\n\t\tif (Number.isFinite(numeric) && numeric > 0) {\n\t\t\treturn numeric < 1e12 ? Math.round(numeric * 1000) : Math.round(numeric);\n\t\t}\n\t\tconst parsed = Date.parse(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn undefined;\n}\n\nexport function grokEntryToOAuth(entry: unknown): OAuthCredential | undefined {\n\tif (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return undefined;\n\tconst record = entry as Record<string, unknown>;\n\tconst access = typeof record.key === \"string\" ? record.key : undefined;\n\tconst refresh = typeof record.refresh_token === \"string\" ? record.refresh_token : undefined;\n\tconst expires = parseGrokExpiresAt(record.expires_at);\n\tif (!access || !refresh || expires === undefined) return undefined;\n\treturn { type: \"oauth\", access, refresh, expires };\n}\n\nexport function readGrokCliXaiOAuth(options: { grokHome?: string } = {}): OAuthCredential | undefined {\n\ttry {\n\t\tconst raw = readFileSync(grokAuthPath(options.grokHome), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return undefined;\n\t\treturn grokEntryToOAuth((parsed as Record<string, unknown>)[grokOidcEntryKey()]);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function hasGrokCliXaiAuth(options: { grokHome?: string } = {}): boolean {\n\treturn readGrokCliXaiOAuth(options) !== undefined;\n}\n\nexport function chooseXaiOAuth(\n\tlunr: Credential | undefined,\n\tgrok: OAuthCredential | undefined,\n): Credential | undefined {\n\tif (lunr?.type === \"api_key\") return lunr;\n\tconst lunrOAuth = lunr?.type === \"oauth\" ? lunr : undefined;\n\tif (lunrOAuth && grok) return grok.expires >= lunrOAuth.expires ? grok : lunrOAuth;\n\treturn grok ?? lunrOAuth ?? lunr;\n}\n\nfunction oauthRefreshFailed(error: unknown): boolean {\n\tconst parts: string[] = [];\n\tlet current: unknown = error;\n\tconst seen = new Set<unknown>();\n\twhile (current && typeof current === \"object\" && !seen.has(current)) {\n\t\tseen.add(current);\n\t\tif (current instanceof Error) {\n\t\t\tparts.push(current.message);\n\t\t\tcurrent = current.cause;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn /invalid_grant|oauth refresh failed/i.test(parts.join(\" \"));\n}\n\nfunction shouldAdopt(lunr: Credential | undefined, chosen: Credential | undefined): boolean {\n\tif (!chosen || chosen.type !== \"oauth\") return false;\n\tif (!lunr || lunr.type !== \"oauth\") return true;\n\treturn lunr.access !== chosen.access || lunr.refresh !== chosen.refresh;\n}\n\nexport function writeGrokCliXaiOAuth(\n\tcredential: OAuthCredential,\n\toptions: { grokHome?: string; onlyIfFileExists?: boolean } = {},\n): boolean {\n\tconst authPath = grokAuthPath(options.grokHome);\n\tif (options.onlyIfFileExists !== false && !existsSync(authPath)) return false;\n\n\tconst dir = dirname(authPath);\n\tif (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });\n\tif (!existsSync(authPath)) {\n\t\twriteFileSync(authPath, \"{}\\n\", AUTH_FILE_WRITE_OPTIONS);\n\t\tchmodSync(authPath, 0o600);\n\t}\n\n\tlet release: (() => void) | undefined;\n\ttry {\n\t\trelease = lockfile.lockSync(authPath, { realpath: false });\n\t\tlet data: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(authPath, \"utf-8\")) as unknown;\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\t\tdata = parsed as Record<string, unknown>;\n\t\t\t}\n\t\t} catch {\n\t\t\tdata = {};\n\t\t}\n\t\tconst key = grokOidcEntryKey();\n\t\tconst previous =\n\t\t\tdata[key] && typeof data[key] === \"object\" && !Array.isArray(data[key])\n\t\t\t\t? (data[key] as Record<string, unknown>)\n\t\t\t\t: {};\n\t\tdata[key] = {\n\t\t\t...previous,\n\t\t\tkey: credential.access,\n\t\t\trefresh_token: credential.refresh,\n\t\t\texpires_at: credential.expires,\n\t\t};\n\t\twriteFileSync(authPath, `${JSON.stringify(data, null, 2)}\\n`, AUTH_FILE_WRITE_OPTIONS);\n\t\tchmodSync(authPath, 0o600);\n\t\treturn true;\n\t} finally {\n\t\tif (release) {\n\t\t\ttry {\n\t\t\t\trelease();\n\t\t\t} catch {\n\t\t\t\t// Unlock is best-effort.\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function wrapXaiGrokCliCredentials(\n\tstore: CredentialStore,\n\toptions: { grokHome?: string } = {},\n): CredentialStore {\n\tconst grokHome = options.grokHome;\n\treturn {\n\t\tasync read(providerId: string): Promise<Credential | undefined> {\n\t\t\tconst stored = await store.read(providerId);\n\t\t\tif (providerId !== XAI_PROVIDER_ID) return stored;\n\t\t\tif (stored?.type === \"api_key\") return stored;\n\t\t\tconst grok = readGrokCliXaiOAuth({ grokHome });\n\t\t\tconst chosen = chooseXaiOAuth(stored, grok);\n\t\t\tif (shouldAdopt(stored, chosen) && chosen?.type === \"oauth\") {\n\t\t\t\ttry {\n\t\t\t\t\tawait store.modify(providerId, async () => chosen);\n\t\t\t\t} catch {\n\t\t\t\t\t// Read still returns the live Grok token if persist fails.\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn chosen;\n\t\t},\n\t\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\t\tconst entries = new Map((await store.list()).map((entry) => [entry.providerId, entry]));\n\t\t\tif (!entries.has(XAI_PROVIDER_ID) && hasGrokCliXaiAuth({ grokHome })) {\n\t\t\t\tentries.set(XAI_PROVIDER_ID, { providerId: XAI_PROVIDER_ID, type: \"oauth\" });\n\t\t\t}\n\t\t\treturn [...entries.values()];\n\t\t},\n\t\tmodify(providerId, fn) {\n\t\t\tif (providerId !== XAI_PROVIDER_ID) return store.modify(providerId, fn);\n\t\t\treturn store.modify(providerId, async (lunrCurrent) => {\n\t\t\t\tif (lunrCurrent?.type === \"api_key\") return fn(lunrCurrent);\n\t\t\t\tconst grok = readGrokCliXaiOAuth({ grokHome });\n\t\t\t\tconst chosen = chooseXaiOAuth(lunrCurrent, grok);\n\t\t\t\tlet next: Credential | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tnext = await fn(chosen);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!oauthRefreshFailed(error) || !grok || chosen === grok) throw error;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnext = await fn(grok);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst persist = next ?? (shouldAdopt(lunrCurrent, chosen) ? chosen : undefined);\n\t\t\t\tif (persist?.type === \"oauth\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\twriteGrokCliXaiOAuth(persist, { grokHome, onlyIfFileExists: true });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// lunR persist still happens; Grok file update is best-effort.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn persist;\n\t\t\t});\n\t\t},\n\t\tdelete(providerId: string): Promise<void> {\n\t\t\treturn store.delete(providerId);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"grok-cli-auth.d.ts","sourceRoot":"","sources":["../../src/core/grok-cli-auth.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,KAAK,EAAE,UAAU,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eAAe,CAuEjB","sourcesContent":["/**\n * Official Grok CLI SuperGrok session (`~/.grok/auth.json`).\n *\n * lunR and Grok CLI share xAI client `b1a00492-073a-47ea-816f-4c329264a828`.\n * xAI rotates refresh tokens and revokes the family on reuse, so this module\n * must never write a rotated-out refresh back over a newer one.\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Credential, CredentialInfo, CredentialStore, OAuthCredential } from \"@ashx-j/lunr-ai\";\nimport lockfile from \"proper-lockfile\";\n\nexport const XAI_PROVIDER_ID = \"xai\";\n/** Same client as packages/ai/src/auth/oauth/xai.ts `XAI_CLIENT_ID`. */\nexport const XAI_GROK_CLI_CLIENT_ID = \"b1a00492-073a-47ea-816f-4c329264a828\";\n/** Matches packages/ai/src/auth/oauth/xai.ts `REFRESH_SKEW_MS`. */\nconst REFRESH_SKEW_MS = 5 * 60 * 1000;\n\nconst AUTH_FILE_WRITE_OPTIONS = { encoding: \"utf-8\", mode: 0o600 } as const;\n\nexport function grokHomeDir(grokHome?: string): string {\n\tif (grokHome) return grokHome;\n\tconst fromEnv = process.env.GROK_HOME?.trim();\n\tif (fromEnv) return fromEnv;\n\treturn join(homedir(), \".grok\");\n}\n\nexport function grokAuthPath(grokHome?: string): string {\n\treturn join(grokHomeDir(grokHome), \"auth.json\");\n}\n\nexport function grokOidcEntryKey(clientId: string = XAI_GROK_CLI_CLIENT_ID): string {\n\treturn `https://auth.x.ai::${clientId}`;\n}\n\nexport function parseGrokExpiresAt(value: unknown): number | undefined {\n\tif (typeof value === \"number\" && Number.isFinite(value) && value > 0) {\n\t\treturn value < 1e12 ? Math.round(value * 1000) : Math.round(value);\n\t}\n\tif (typeof value === \"string\" && value.trim()) {\n\t\tconst numeric = Number(value);\n\t\tif (Number.isFinite(numeric) && numeric > 0) {\n\t\t\treturn numeric < 1e12 ? Math.round(numeric * 1000) : Math.round(numeric);\n\t\t}\n\t\tconst parsed = Date.parse(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn undefined;\n}\n\n/** Grok CLI deserializes `expires_at` as RFC3339, not epoch ms. */\nexport function formatGrokExpiresAt(expires: number): string {\n\treturn new Date(expires).toISOString();\n}\n\nexport function grokEntryToOAuth(entry: unknown): OAuthCredential | undefined {\n\tif (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return undefined;\n\tconst record = entry as Record<string, unknown>;\n\tconst access = typeof record.key === \"string\" ? record.key : undefined;\n\tconst refresh = typeof record.refresh_token === \"string\" ? record.refresh_token : undefined;\n\tconst expires = parseGrokExpiresAt(record.expires_at);\n\tif (!access || !refresh || expires === undefined) return undefined;\n\treturn { type: \"oauth\", access, refresh, expires };\n}\n\nexport function readGrokCliXaiOAuth(options: { grokHome?: string } = {}): OAuthCredential | undefined {\n\ttry {\n\t\tconst raw = readFileSync(grokAuthPath(options.grokHome), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return undefined;\n\t\treturn grokEntryToOAuth((parsed as Record<string, unknown>)[grokOidcEntryKey()]);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function hasGrokCliXaiAuth(options: { grokHome?: string } = {}): boolean {\n\treturn readGrokCliXaiOAuth(options) !== undefined;\n}\n\n/**\n * Pick the live SuperGrok session.\n *\n * lunR stores `expires` 5 minutes early. Grok CLI stores the server expiry.\n * A raw `>=` compare therefore treats a just-rotated lunR token as older than\n * the still-unrotated Grok file and writes the dead refresh back. When both\n * look live and the refresh tokens differ, keep lunR; `modify` retries Grok\n * only after `invalid_grant`.\n */\nexport function chooseXaiOAuth(\n\tlunr: Credential | undefined,\n\tgrok: OAuthCredential | undefined,\n): Credential | undefined {\n\tif (lunr?.type === \"api_key\") return lunr;\n\tconst lunrOAuth = lunr?.type === \"oauth\" ? lunr : undefined;\n\tif (lunrOAuth && grok) {\n\t\tif (lunrOAuth.refresh === grok.refresh) {\n\t\t\treturn grok.expires >= lunrOAuth.expires ? grok : lunrOAuth;\n\t\t}\n\t\tconst now = Date.now();\n\t\tconst lunrLive = now < lunrOAuth.expires;\n\t\tconst grokLive = now < grok.expires;\n\t\tif (grokLive && !lunrLive) return grok;\n\t\tif (lunrLive && !grokLive) return lunrOAuth;\n\t\tif (!lunrLive && !grokLive) return grok.expires >= lunrOAuth.expires ? grok : lunrOAuth;\n\t\treturn lunrOAuth;\n\t}\n\treturn grok ?? lunrOAuth ?? lunr;\n}\n\nfunction oauthRefreshFailed(error: unknown): boolean {\n\tconst parts: string[] = [];\n\tlet current: unknown = error;\n\tconst seen = new Set<unknown>();\n\twhile (current && typeof current === \"object\" && !seen.has(current)) {\n\t\tseen.add(current);\n\t\tif (current instanceof Error) {\n\t\t\tparts.push(current.message);\n\t\t\tcurrent = current.cause;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\tconst chain = parts.join(\" \");\n\tif (/timed out|aborted|cancelled|ECONN|ENOTFOUND|network/i.test(chain)) return false;\n\treturn /invalid_grant|refresh token revoked/i.test(chain);\n}\n\nfunction shouldAdopt(lunr: Credential | undefined, chosen: Credential | undefined): boolean {\n\tif (!chosen || chosen.type !== \"oauth\") return false;\n\tif (!lunr || lunr.type !== \"oauth\") return true;\n\treturn lunr.access !== chosen.access || lunr.refresh !== chosen.refresh;\n}\n\nfunction writeAuthFileAtomic(authPath: string, contents: string): void {\n\tconst tmp = `${authPath}.${process.pid}.${Date.now()}.tmp`;\n\twriteFileSync(tmp, contents, AUTH_FILE_WRITE_OPTIONS);\n\ttry {\n\t\tchmodSync(tmp, 0o600);\n\t} catch {\n\t\t// mode bits are best-effort on Windows.\n\t}\n\ttry {\n\t\tif (process.platform === \"win32\" && existsSync(authPath)) {\n\t\t\twriteFileSync(authPath, contents, AUTH_FILE_WRITE_OPTIONS);\n\t\t\tchmodSync(authPath, 0o600);\n\t\t\treturn;\n\t\t}\n\t\trenameSync(tmp, authPath);\n\t\ttry {\n\t\t\tchmodSync(authPath, 0o600);\n\t\t} catch {\n\t\t\t// mode bits are best-effort on Windows.\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmp);\n\t\t} catch {\n\t\t\t// tmp already renamed, or never created.\n\t\t}\n\t}\n}\n\nfunction acquireGrokLock(authPath: string): () => void {\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(authPath, { realpath: false, stale: 120_000 });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to match AuthStorage.\n\t\t\t}\n\t\t}\n\t}\n\tthrow (lastError as Error) ?? new Error(\"Failed to acquire Grok CLI auth lock\");\n}\n\nexport function writeGrokCliXaiOAuth(\n\tcredential: OAuthCredential,\n\toptions: { grokHome?: string; onlyIfFileExists?: boolean } = {},\n): boolean {\n\tconst authPath = grokAuthPath(options.grokHome);\n\tif (options.onlyIfFileExists !== false && !existsSync(authPath)) return false;\n\n\tconst dir = dirname(authPath);\n\tif (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });\n\tif (!existsSync(authPath)) {\n\t\twriteAuthFileAtomic(authPath, \"{}\\n\");\n\t}\n\n\tlet release: (() => void) | undefined;\n\ttry {\n\t\trelease = acquireGrokLock(authPath);\n\t\tlet data: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(authPath, \"utf-8\")) as unknown;\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\t\tdata = parsed as Record<string, unknown>;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Never replace a corrupt Grok file with a single-entry stub.\n\t\t\treturn false;\n\t\t}\n\t\tconst key = grokOidcEntryKey();\n\t\tconst previous =\n\t\t\tdata[key] && typeof data[key] === \"object\" && !Array.isArray(data[key])\n\t\t\t\t? (data[key] as Record<string, unknown>)\n\t\t\t\t: {};\n\t\tconst existing = grokEntryToOAuth(previous);\n\t\tif (\n\t\t\texisting &&\n\t\t\texisting.refresh !== credential.refresh &&\n\t\t\texisting.expires > credential.expires + REFRESH_SKEW_MS\n\t\t) {\n\t\t\t// Disk already has a newer family (usually a later `grok login`).\n\t\t\treturn false;\n\t\t}\n\t\tdata[key] = {\n\t\t\t...previous,\n\t\t\tkey: credential.access,\n\t\t\trefresh_token: credential.refresh,\n\t\t\texpires_at: formatGrokExpiresAt(credential.expires),\n\t\t};\n\t\twriteAuthFileAtomic(authPath, `${JSON.stringify(data, null, 2)}\\n`);\n\t\treturn true;\n\t} finally {\n\t\tif (release) {\n\t\t\ttry {\n\t\t\t\trelease();\n\t\t\t} catch {\n\t\t\t\t// Unlock is best-effort.\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function wrapXaiGrokCliCredentials(\n\tstore: CredentialStore,\n\toptions: { grokHome?: string } = {},\n): CredentialStore {\n\tconst grokHome = options.grokHome;\n\treturn {\n\t\tasync read(providerId: string): Promise<Credential | undefined> {\n\t\t\tconst stored = await store.read(providerId);\n\t\t\tif (providerId !== XAI_PROVIDER_ID) return stored;\n\t\t\tif (stored?.type === \"api_key\") return stored;\n\t\t\tconst grok = readGrokCliXaiOAuth({ grokHome });\n\t\t\tconst chosen = chooseXaiOAuth(stored, grok);\n\t\t\tif (shouldAdopt(stored, chosen) && chosen?.type === \"oauth\") {\n\t\t\t\ttry {\n\t\t\t\t\tawait store.modify(providerId, async (current) => {\n\t\t\t\t\t\tif (current?.type === \"api_key\") return undefined;\n\t\t\t\t\t\tconst latestGrok = readGrokCliXaiOAuth({ grokHome });\n\t\t\t\t\t\tconst latestChosen = chooseXaiOAuth(current, latestGrok);\n\t\t\t\t\t\tif (shouldAdopt(current, latestChosen) && latestChosen?.type === \"oauth\") {\n\t\t\t\t\t\t\treturn latestChosen;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// Read still returns the live Grok token if persist fails.\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn chosen;\n\t\t},\n\t\tasync list(): Promise<readonly CredentialInfo[]> {\n\t\t\tconst entries = new Map((await store.list()).map((entry) => [entry.providerId, entry]));\n\t\t\tif (!entries.has(XAI_PROVIDER_ID) && hasGrokCliXaiAuth({ grokHome })) {\n\t\t\t\tentries.set(XAI_PROVIDER_ID, { providerId: XAI_PROVIDER_ID, type: \"oauth\" });\n\t\t\t}\n\t\t\treturn [...entries.values()];\n\t\t},\n\t\tmodify(providerId, fn) {\n\t\t\tif (providerId !== XAI_PROVIDER_ID) return store.modify(providerId, fn);\n\t\t\treturn store.modify(providerId, async (lunrCurrent) => {\n\t\t\t\tif (lunrCurrent?.type === \"api_key\") return fn(lunrCurrent);\n\t\t\t\tconst grok = readGrokCliXaiOAuth({ grokHome });\n\t\t\t\tconst chosen = chooseXaiOAuth(lunrCurrent, grok);\n\t\t\t\tlet next: Credential | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tnext = await fn(chosen);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst retryGrok = readGrokCliXaiOAuth({ grokHome });\n\t\t\t\t\tconst canRetry =\n\t\t\t\t\t\toauthRefreshFailed(error) &&\n\t\t\t\t\t\tretryGrok &&\n\t\t\t\t\t\t!(chosen?.type === \"oauth\" && retryGrok.refresh === chosen.refresh);\n\t\t\t\t\tif (!canRetry) throw error;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnext = await fn(retryGrok);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// `undefined` means \"leave the lunR row unchanged\". Adopting `chosen`\n\t\t\t\t// here wrote a rotated-out Grok refresh over a just-rotated lunR token.\n\t\t\t\tif (next?.type === \"oauth\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\twriteGrokCliXaiOAuth(next, { grokHome, onlyIfFileExists: true });\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// lunR persist still happens; Grok file update is best-effort.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn next;\n\t\t\t});\n\t\t},\n\t\tdelete(providerId: string): Promise<void> {\n\t\t\treturn store.delete(providerId);\n\t\t},\n\t};\n}\n"]}