@code-yeongyu/senpi-ai 2026.8.12 → 2026.8.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -8
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.js +5 -1
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/bedrock-converse-stream.lazy.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +2 -2
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-shared.d.ts +15 -1
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +103 -4
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/google-vertex.d.ts.map +1 -1
- package/dist/api/google-vertex.js +2 -2
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/lazy.d.ts +5 -1
- package/dist/api/lazy.d.ts.map +1 -1
- package/dist/api/lazy.js +19 -7
- package/dist/api/lazy.js.map +1 -1
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts +3 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +47 -7
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +22 -9
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.js +5 -1
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/pi-messages.d.ts.map +1 -1
- package/dist/api/pi-messages.js.map +1 -1
- package/dist/api/simple-options.d.ts +2 -0
- package/dist/api/simple-options.d.ts.map +1 -1
- package/dist/api/simple-options.js +8 -2
- package/dist/api/simple-options.js.map +1 -1
- package/dist/api/transform-messages.js.map +1 -1
- package/dist/api/warm-prompt-cache.js.map +1 -1
- package/dist/auth/credential-store.d.ts +6 -6
- package/dist/auth/credential-store.d.ts.map +1 -1
- package/dist/auth/credential-store.js +22 -11
- package/dist/auth/credential-store.js.map +1 -1
- package/dist/auth/helpers.d.ts +1 -0
- package/dist/auth/helpers.d.ts.map +1 -1
- package/dist/auth/helpers.js +7 -2
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/oauth/anthropic.d.ts.map +1 -1
- package/dist/auth/oauth/anthropic.js +14 -8
- package/dist/auth/oauth/anthropic.js.map +1 -1
- package/dist/auth/oauth/device-code.d.ts +1 -1
- package/dist/auth/oauth/device-code.d.ts.map +1 -1
- package/dist/auth/oauth/device-code.js +4 -4
- package/dist/auth/oauth/device-code.js.map +1 -1
- package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
- package/dist/auth/oauth/github-copilot.js +43 -30
- package/dist/auth/oauth/github-copilot.js.map +1 -1
- package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
- package/dist/auth/oauth/kimi-coding.js +17 -5
- package/dist/auth/oauth/kimi-coding.js.map +1 -1
- package/dist/auth/oauth/load.d.ts.map +1 -1
- package/dist/auth/oauth/load.js.map +1 -1
- package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
- package/dist/auth/oauth/openai-codex.js +12 -5
- package/dist/auth/oauth/openai-codex.js.map +1 -1
- package/dist/auth/oauth/openrouter.d.ts.map +1 -1
- package/dist/auth/oauth/openrouter.js +10 -10
- package/dist/auth/oauth/openrouter.js.map +1 -1
- package/dist/auth/oauth/radius.d.ts.map +1 -1
- package/dist/auth/oauth/radius.js +8 -7
- package/dist/auth/oauth/radius.js.map +1 -1
- package/dist/auth/oauth/xai.d.ts.map +1 -1
- package/dist/auth/oauth/xai.js +3 -2
- package/dist/auth/oauth/xai.js.map +1 -1
- package/dist/auth/resolve.d.ts +1 -0
- package/dist/auth/resolve.d.ts.map +1 -1
- package/dist/auth/resolve.js +24 -13
- package/dist/auth/resolve.js.map +1 -1
- package/dist/auth/types.d.ts +21 -8
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/compat.js.map +1 -1
- package/dist/env-api-keys.d.ts.map +1 -1
- package/dist/env-api-keys.js +3 -0
- package/dist/env-api-keys.js.map +1 -1
- package/dist/image-models.generated.d.ts +69 -54
- package/dist/image-models.generated.d.ts.map +1 -1
- package/dist/image-models.generated.js +15 -0
- package/dist/image-models.generated.js.map +1 -1
- package/dist/images-models.d.ts.map +1 -1
- package/dist/images-models.js +1 -0
- package/dist/images-models.js.map +1 -1
- package/dist/model.d.ts +2 -0
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js.map +1 -1
- package/dist/models-store.d.ts +9 -12
- package/dist/models-store.d.ts.map +1 -1
- package/dist/models-store.js +6 -3
- package/dist/models-store.js.map +1 -1
- package/dist/models.d.ts +40 -18
- package/dist/models.d.ts.map +1 -1
- package/dist/models.generated.d.ts +6 -0
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.generated.js +6 -0
- package/dist/models.generated.js.map +1 -1
- package/dist/models.js +247 -91
- package/dist/models.js.map +1 -1
- package/dist/node/provider-scope.d.ts.map +1 -1
- package/dist/providers/all.d.ts.map +1 -1
- package/dist/providers/all.js +6 -0
- package/dist/providers/all.js.map +1 -1
- package/dist/providers/amazon-bedrock.d.ts.map +1 -1
- package/dist/providers/amazon-bedrock.js +15 -7
- package/dist/providers/amazon-bedrock.js.map +1 -1
- package/dist/providers/anthropic.d.ts.map +1 -1
- package/dist/providers/anthropic.js +15 -6
- package/dist/providers/anthropic.js.map +1 -1
- package/dist/providers/baseten.d.ts +3 -0
- package/dist/providers/baseten.d.ts.map +1 -0
- package/dist/providers/baseten.js +15 -0
- package/dist/providers/baseten.js.map +1 -0
- package/dist/providers/baseten.models.d.ts +4 -0
- package/dist/providers/baseten.models.d.ts.map +1 -0
- package/dist/providers/baseten.models.js +6 -0
- package/dist/providers/baseten.models.js.map +1 -0
- package/dist/providers/cloudflare-auth.d.ts.map +1 -1
- package/dist/providers/cloudflare-auth.js +15 -10
- package/dist/providers/cloudflare-auth.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/baseten.json +1 -0
- package/dist/providers/data/fireworks.json +1 -1
- package/dist/providers/data/github-copilot.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/opengateway.json +1 -0
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/dist/providers/data/qwen-token-plan-individual.json +1 -0
- package/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/xai.json +1 -1
- package/dist/providers/faux.d.ts +18 -13
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +95 -5
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/github-copilot.js +1 -1
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/google-vertex.d.ts.map +1 -1
- package/dist/providers/google-vertex.js +15 -7
- package/dist/providers/google-vertex.js.map +1 -1
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +1 -0
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/ollama.d.ts.map +1 -1
- package/dist/providers/ollama.js +1 -2
- package/dist/providers/ollama.js.map +1 -1
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +5 -1
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/opengateway.d.ts +3 -0
- package/dist/providers/opengateway.d.ts.map +1 -0
- package/dist/providers/opengateway.js +15 -0
- package/dist/providers/opengateway.js.map +1 -0
- package/dist/providers/opengateway.models.d.ts +4 -0
- package/dist/providers/opengateway.models.d.ts.map +1 -0
- package/dist/providers/opengateway.models.js +6 -0
- package/dist/providers/opengateway.models.js.map +1 -0
- package/dist/providers/qwen-token-plan-individual.d.ts +3 -0
- package/dist/providers/qwen-token-plan-individual.d.ts.map +1 -0
- package/dist/providers/qwen-token-plan-individual.js +15 -0
- package/dist/providers/qwen-token-plan-individual.js.map +1 -0
- package/dist/providers/qwen-token-plan-individual.models.d.ts +4 -0
- package/dist/providers/qwen-token-plan-individual.models.d.ts.map +1 -0
- package/dist/providers/qwen-token-plan-individual.models.js +6 -0
- package/dist/providers/qwen-token-plan-individual.models.js.map +1 -0
- package/dist/providers/radius.d.ts.map +1 -1
- package/dist/providers/radius.js +36 -26
- package/dist/providers/radius.js.map +1 -1
- package/dist/providers/xai.d.ts.map +1 -1
- package/dist/providers/xai.js +1 -0
- package/dist/providers/xai.js.map +1 -1
- package/dist/tool-call-middleware/context-transformer.js.map +1 -1
- package/dist/tool-call-middleware/protocols/anthropic-xml/recovery-wrapper-state.d.ts.map +1 -1
- package/dist/tool-call-middleware/protocols/kimi-xtml/parse.js.map +1 -1
- package/dist/tool-call-middleware/recovery-content-lifecycle.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-event-stream.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-native-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-native-projection.js.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-terminal.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-wrapper.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-wrapper.js +5 -0
- package/dist/tool-call-middleware/recovery-stream-wrapper.js.map +1 -1
- package/dist/tool-call-middleware/recovery-text-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-text-projection.js.map +1 -1
- package/dist/tool-call-middleware/stream-thinking-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper-shared.d.ts.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper-shared.js.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper.js.map +1 -1
- package/dist/types.d.ts +94 -87
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/abort.d.ts +8 -0
- package/dist/utils/abort.d.ts.map +1 -0
- package/dist/utils/abort.js +49 -0
- package/dist/utils/abort.js.map +1 -0
- package/dist/utils/deferred-tools.js.map +1 -1
- package/dist/utils/event-stream.d.ts.map +1 -1
- package/dist/utils/overflow.d.ts +14 -1
- package/dist/utils/overflow.d.ts.map +1 -1
- package/dist/utils/overflow.js +18 -1
- package/dist/utils/overflow.js.map +1 -1
- package/dist/utils/prompt-cache-ttl.d.ts +3 -1
- package/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
- package/dist/utils/prompt-cache-ttl.js +2 -0
- package/dist/utils/prompt-cache-ttl.js.map +1 -1
- package/dist/utils/provider-retry.js.map +1 -1
- package/dist/utils/retry.d.ts +25 -0
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +64 -0
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/tool-schema-compat.d.ts.map +1 -1
- package/dist/utils/tool-schema-compat.js +1 -0
- package/dist/utils/tool-schema-compat.js.map +1 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/dist/utils/validation.js +6 -0
- package/dist/utils/validation.js.map +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,MAAM,iCAAiC,GAAG,gDAAgD,CAAC;AAC3F,MAAM,iCAAiC,GAAG,qDAAqD,CAAC;AAChG,MAAM,yBAAyB,GAAG,qDAAqD,CAAC;AACxF,MAAM,yBAAyB,GAAG,0DAA0D,CAAC;AAE7F,SAAS,2BAA2B,CACnC,OAAuC,EACvC,WAAmB,EACnB,OAAyC;IAEzC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,O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CAAC;YAEH,IAAI,aAAa,EAAE,CAAC;gBACnB,aAAa,CAAC,QAAQ,GAAG,IAAI,CAAC;gBAC9B,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;gBACnC,SAAS;YACV,CAAC;YAED,MAAM,CAAC,IAAI,CAAC;gBACX,IAAI,EAAE,YAAY;gBAClB,UAAU,EAAE,KAAK,CAAC,EAAE;gBACpB,QAAQ,EAAE,KAAK,CAAC,IAAI;gBACpB,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oBAAoB,EAAE,CAAC;gBACvD,OAAO,EAAE,IAAI;gBACb,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;aACA,CAAC,CAAC;QACzB,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { isVideoMimeType } from \"../types.ts\";\n\nconst NON_VISION_USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst NON_VISION_TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\nconst NO_VIDEO_USER_PLACEHOLDER = \"(video omitted: model does not support video input)\";\nconst NO_VIDEO_TOOL_PLACEHOLDER = \"(tool video omitted: model does not support video input)\";\n\nfunction replaceMediaWithPlaceholder(\n\tcontent: (TextContent | ImageContent)[],\n\tplaceholder: string,\n\tmatches: (block: ImageContent) => boolean,\n): (TextContent | ImageContent)[] {\n\tif (!content.some((block) => block.type === \"image\" && matches(block))) {\n\t\treturn content;\n\t}\n\tconst result: (TextContent | ImageContent)[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\" && matches(block)) {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult.push(block);\n\t\tpreviousWasPlaceholder = block.type === \"text\" && block.text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction replaceImagesWithPlaceholder(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\") {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult.push(block);\n\t\tpreviousWasPlaceholder = block.text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tconst supportsImages = model.input.includes(\"image\");\n\tconst supportsVideo = model.input.includes(\"video\");\n\tif (supportsImages && supportsVideo) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg) => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\tlet content = msg.content;\n\t\t\t// Video payloads ride ImageContent blocks; strip them first for models\n\t\t\t// without the \"video\" modality so they never hit an incompatible wire.\n\t\t\tif (!supportsVideo) {\n\t\t\t\tcontent = replaceMediaWithPlaceholder(content, NO_VIDEO_USER_PLACEHOLDER, (b) =>\n\t\t\t\t\tisVideoMimeType(b.mimeType),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!supportsImages) {\n\t\t\t\tcontent = replaceImagesWithPlaceholder(content, NON_VISION_USER_IMAGE_PLACEHOLDER);\n\t\t\t}\n\t\t\treturn { ...msg, content };\n\t\t}\n\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tlet content = msg.content;\n\t\t\tif (!supportsVideo) {\n\t\t\t\tcontent = replaceMediaWithPlaceholder(content, NO_VIDEO_TOOL_PLACEHOLDER, (b) =>\n\t\t\t\t\tisVideoMimeType(b.mimeType),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!supportsImages) {\n\t\t\t\tcontent = replaceImagesWithPlaceholder(content, NON_VISION_TOOL_IMAGE_PLACEHOLDER);\n\t\t\t}\n\t\t\treturn { ...msg, content };\n\t\t}\n\n\t\treturn msg;\n\t});\n}\n\nexport interface TransformMessagesOptions {\n\t/**\n\t * Preserve provider-native thinking/reasoning replay state for the current\n\t * model. When false, standalone same-model thinking is omitted, while\n\t * thinking attached to tool calls is preserved for provider validation.\n\t */\n\tpreserveThinking?: boolean;\n\tpreserveTextSignatures?: boolean;\n\t/**\n\t * Preserve same-model thinking blocks that do not carry a usable signature\n\t * so provider adapters can downgrade them to plain text or provider-specific\n\t * compatibility payloads.\n\t */\n\tpreserveUnsignedThinking?: boolean;\n\t/**\n\t * Normalize tool-call IDs even when stored provider/API/model metadata match\n\t * the target. Enable only for target protocols whose wire contract requires it.\n\t */\n\tnormalizeSameModelToolCallIds?: boolean;\n}\n\n/**\n * Normalize tool call ID for cross-provider compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).\n */\nexport function transformMessages<TApi extends Api>(\n\tmessages: Message[],\n\tmodel: Model<TApi>,\n\tnormalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,\n\toptions: TransformMessagesOptions = {},\n): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs\n\tconst toolCallIdMap = new Map<string, string>();\n\t// Normalize null/undefined content from untyped callers (custom tools, hand-built\n\t// histories, old session files) so downstream code can rely on the type contract.\n\tconst normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));\n\tconst imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);\n\tconst preserveThinking = options.preserveThinking ?? true;\n\tconst preserveTextSignatures = options.preserveTextSignatures ?? false;\n\tconst preserveUnsignedThinking = options.preserveUnsignedThinking ?? false;\n\tconst normalizeSameModelToolCallIds = options.normalizeSameModelToolCallIds ?? false;\n\n\t// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)\n\tconst transformed = imageAwareMessages.map((msg) => {\n\t\t// User messages pass through unchanged\n\t\tif (msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tassistantMsg.model === model.id;\n\t\t\tconst hasToolCalls = assistantMsg.content.some((block) => block.type === \"toolCall\");\n\t\t\tconst preserveProviderState = preserveThinking || hasToolCalls;\n\n\t\t\tconst transformedContent = assistantMsg.content.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t// Redacted thinking is opaque encrypted content, only valid for the same model.\n\t\t\t\t\t// Drop it for cross-model to avoid API errors.\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\treturn isSameModel && preserveProviderState ? { ...block } : [];\n\t\t\t\t\t}\n\t\t\t\t\tconst hasUsableSignature =\n\t\t\t\t\t\ttypeof block.thinkingSignature === \"string\" && block.thinkingSignature.trim().length > 0;\n\t\t\t\t\t// For same model: keep signed thinking only while replaying provider state.\n\t\t\t\t\t// Empty signed blocks are opaque compatibility state, not visible reasoning.\n\t\t\t\t\tif (isSameModel && hasUsableSignature && (preserveProviderState || block.thinking.trim() === \"\")) {\n\t\t\t\t\t\treturn { ...block };\n\t\t\t\t\t}\n\t\t\t\t\t// Skip empty thinking blocks, convert others to plain text\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) {\n\t\t\t\t\t\treturn preserveProviderState || (preserveUnsignedThinking && !hasUsableSignature) ? { ...block } : [];\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel && (preserveProviderState || preserveTextSignatures)) return { ...block };\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = { ...toolCall };\n\n\t\t\t\t\tif ((!isSameModel || !preserveProviderState) && toolCall.thoughtSignature) {\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((!isSameModel || normalizeSameModelToolCallIds) && normalizeToolCallId) {\n\t\t\t\t\t\tconst normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Second pass: pair every replayable tool call with the earliest unconsumed\n\t// result after its declaring assistant. Results are emitted adjacent to their\n\t// calls because Anthropic requires that ordering. A reused ID starts a new\n\t// pairing window, so a later result cannot repair an earlier call.\n\tconst result: Message[] = [];\n\tconst toolResultsById = new Map<string, { message: ToolResultMessage; sourceIndex: number; consumed: boolean }[]>();\n\tconst nextToolCallIndexById = new Map<string, number[]>();\n\t// Tool calls declared only by assistants the emit loop drops (errored/aborted).\n\t// Their results must not be emitted either: a strict provider rejects a tool\n\t// message whose tool_call_id no assistant in the request declares.\n\tconst droppedCallIds = new Set<string>();\n\n\tfor (let sourceIndex = 0; sourceIndex < transformed.length; sourceIndex++) {\n\t\tconst message = transformed[sourceIndex];\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst entries = toolResultsById.get(message.toolCallId) ?? [];\n\t\t\tentries.push({ message, sourceIndex, consumed: false });\n\t\t\ttoolResultsById.set(message.toolCallId, entries);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"assistant\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"toolCall\") droppedCallIds.add(block.id);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const block of message.content) {\n\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\tconst indexes = nextToolCallIndexById.get(block.id) ?? [];\n\t\t\tindexes.push(sourceIndex);\n\t\t\tnextToolCallIndexById.set(block.id, indexes);\n\t\t}\n\t}\n\n\tfor (let sourceIndex = 0; sourceIndex < transformed.length; sourceIndex++) {\n\t\tconst message = transformed[sourceIndex];\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst entry = toolResultsById\n\t\t\t\t.get(message.toolCallId)\n\t\t\t\t?.find((candidate) => candidate.sourceIndex === sourceIndex);\n\t\t\tif (!entry?.consumed) {\n\t\t\t\t// Skip results whose call was declared only by a dropped\n\t\t\t\t// (errored/aborted) assistant. An id re-declared by a kept assistant\n\t\t\t\t// still pairs through the normal windows, so keep those results.\n\t\t\t\tif (!droppedCallIds.has(message.toolCallId) || nextToolCallIndexById.has(message.toolCallId)) {\n\t\t\t\t\tresult.push(message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"assistant\") {\n\t\t\tresult.push(message);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Skip errored/aborted assistant messages entirely. These incomplete turns\n\t\t// must not be revived merely because a matching result appears later.\n\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") continue;\n\n\t\tresult.push(message);\n\t\tfor (const block of message.content) {\n\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\tconst laterDeclarations = nextToolCallIndexById.get(block.id) ?? [];\n\t\t\tconst nextDeclarationIndex = laterDeclarations.find((index) => index > sourceIndex) ?? Infinity;\n\t\t\tconst matchedResult = toolResultsById\n\t\t\t\t.get(block.id)\n\t\t\t\t?.find(\n\t\t\t\t\t(candidate) =>\n\t\t\t\t\t\t!candidate.consumed &&\n\t\t\t\t\t\tcandidate.sourceIndex > sourceIndex &&\n\t\t\t\t\t\tcandidate.sourceIndex < nextDeclarationIndex,\n\t\t\t\t);\n\n\t\t\tif (matchedResult) {\n\t\t\t\tmatchedResult.consumed = true;\n\t\t\t\tresult.push(matchedResult.message);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tresult.push({\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: block.id,\n\t\t\t\ttoolName: block.name,\n\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as ToolResultMessage);\n\t\t}\n\t}\n\n\treturn result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,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AG,iBAAiB,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,WAAW,CAAC,IAAI,QAAQ,CAAC;YAChG,MAAM,aAAa,GAAG,eAAe;iBACnC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;gBACd,EAAE,IAAI,CACL,CAAC,SAAS,EAAE,EAAE,CACb,CAAC,SAAS,CAAC,QAAQ;gBACnB,SAAS,CAAC,WAAW,GAAG,WAAW;gBACnC,SAAS,CAAC,WAAW,GAAG,oBAAoB,CAC7C,CAAC;YAEH,IAAI,aAAa,EAAE,CAAC;gBACnB,aAAa,CAAC,QAAQ,GAAG,IAAI,CAAC;gBAC9B,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;gBACnC,SAAS;YACV,CAAC;YAED,MAAM,CAAC,IAAI,CAAC;gBACX,IAAI,EAAE,YAAY;gBAClB,UAAU,EAAE,KAAK,CAAC,EAAE;gBACpB,QAAQ,EAAE,KAAK,CAAC,IAAI;gBACpB,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oBAAoB,EAAE,CAAC;gBACvD,OAAO,EAAE,IAAI;gBACb,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;aACA,CAAC,CAAC;QACzB,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { isVideoMimeType } from \"../types.ts\";\n\nconst NON_VISION_USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst NON_VISION_TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\nconst NO_VIDEO_USER_PLACEHOLDER = \"(video omitted: model does not support video input)\";\nconst NO_VIDEO_TOOL_PLACEHOLDER = \"(tool video omitted: model does not support video input)\";\n\nfunction replaceMediaWithPlaceholder(\n\tcontent: (TextContent | ImageContent)[],\n\tplaceholder: string,\n\tmatches: (block: ImageContent) => boolean,\n): (TextContent | ImageContent)[] {\n\tif (!content.some((block) => block.type === \"image\" && matches(block))) {\n\t\treturn content;\n\t}\n\tconst result: (TextContent | ImageContent)[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\" && matches(block)) {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult.push(block);\n\t\tpreviousWasPlaceholder = block.type === \"text\" && block.text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction replaceImagesWithPlaceholder(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\") {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult.push(block);\n\t\tpreviousWasPlaceholder = block.text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tconst supportsImages = model.input.includes(\"image\");\n\tconst supportsVideo = model.input.includes(\"video\");\n\tif (supportsImages && supportsVideo) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg) => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\tlet content = msg.content;\n\t\t\t// Video payloads ride ImageContent blocks; strip them first for models\n\t\t\t// without the \"video\" modality so they never hit an incompatible wire.\n\t\t\tif (!supportsVideo) {\n\t\t\t\tcontent = replaceMediaWithPlaceholder(content, NO_VIDEO_USER_PLACEHOLDER, (b) =>\n\t\t\t\t\tisVideoMimeType(b.mimeType),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!supportsImages) {\n\t\t\t\tcontent = replaceImagesWithPlaceholder(content, NON_VISION_USER_IMAGE_PLACEHOLDER);\n\t\t\t}\n\t\t\treturn { ...msg, content };\n\t\t}\n\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tlet content = msg.content;\n\t\t\tif (!supportsVideo) {\n\t\t\t\tcontent = replaceMediaWithPlaceholder(content, NO_VIDEO_TOOL_PLACEHOLDER, (b) =>\n\t\t\t\t\tisVideoMimeType(b.mimeType),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!supportsImages) {\n\t\t\t\tcontent = replaceImagesWithPlaceholder(content, NON_VISION_TOOL_IMAGE_PLACEHOLDER);\n\t\t\t}\n\t\t\treturn { ...msg, content };\n\t\t}\n\n\t\treturn msg;\n\t});\n}\n\nexport interface TransformMessagesOptions {\n\t/**\n\t * Preserve provider-native thinking/reasoning replay state for the current\n\t * model. When false, standalone same-model thinking is omitted, while\n\t * thinking attached to tool calls is preserved for provider validation.\n\t */\n\tpreserveThinking?: boolean;\n\tpreserveTextSignatures?: boolean;\n\t/**\n\t * Preserve same-model thinking blocks that do not carry a usable signature\n\t * so provider adapters can downgrade them to plain text or provider-specific\n\t * compatibility payloads.\n\t */\n\tpreserveUnsignedThinking?: boolean;\n\t/**\n\t * Normalize tool-call IDs even when stored provider/API/model metadata match\n\t * the target. Enable only for target protocols whose wire contract requires it.\n\t */\n\tnormalizeSameModelToolCallIds?: boolean;\n}\n\n/**\n * Normalize tool call ID for cross-provider compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).\n */\nexport function transformMessages<TApi extends Api>(\n\tmessages: Message[],\n\tmodel: Model<TApi>,\n\tnormalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,\n\toptions: TransformMessagesOptions = {},\n): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs\n\tconst toolCallIdMap = new Map<string, string>();\n\t// Normalize null/undefined content from untyped callers (custom tools, hand-built\n\t// histories, old session files) so downstream code can rely on the type contract.\n\tconst normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));\n\tconst imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);\n\tconst preserveThinking = options.preserveThinking ?? true;\n\tconst preserveTextSignatures = options.preserveTextSignatures ?? false;\n\tconst preserveUnsignedThinking = options.preserveUnsignedThinking ?? false;\n\tconst normalizeSameModelToolCallIds = options.normalizeSameModelToolCallIds ?? false;\n\n\t// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)\n\tconst transformed = imageAwareMessages.map((msg) => {\n\t\t// User messages pass through unchanged\n\t\tif (msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tassistantMsg.model === model.id;\n\t\t\tconst hasToolCalls = assistantMsg.content.some((block) => block.type === \"toolCall\");\n\t\t\tconst preserveProviderState = preserveThinking || hasToolCalls;\n\n\t\t\tconst transformedContent = assistantMsg.content.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t// Redacted thinking is opaque encrypted content, only valid for the same model.\n\t\t\t\t\t// Drop it for cross-model to avoid API errors.\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\treturn isSameModel && preserveProviderState ? { ...block } : [];\n\t\t\t\t\t}\n\t\t\t\t\tconst hasUsableSignature =\n\t\t\t\t\t\ttypeof block.thinkingSignature === \"string\" && block.thinkingSignature.trim().length > 0;\n\t\t\t\t\t// For same model: keep signed thinking only while replaying provider state.\n\t\t\t\t\t// Empty signed blocks are opaque compatibility state, not visible reasoning.\n\t\t\t\t\tif (isSameModel && hasUsableSignature && (preserveProviderState || block.thinking.trim() === \"\")) {\n\t\t\t\t\t\treturn { ...block };\n\t\t\t\t\t}\n\t\t\t\t\t// Skip empty thinking blocks, convert others to plain text\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) {\n\t\t\t\t\t\treturn preserveProviderState || (preserveUnsignedThinking && !hasUsableSignature) ? { ...block } : [];\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel && (preserveProviderState || preserveTextSignatures)) return { ...block };\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = { ...toolCall };\n\n\t\t\t\t\tif ((!isSameModel || !preserveProviderState) && toolCall.thoughtSignature) {\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((!isSameModel || normalizeSameModelToolCallIds) && normalizeToolCallId) {\n\t\t\t\t\t\tconst normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Second pass: pair every replayable tool call with the earliest unconsumed\n\t// result after its declaring assistant. Results are emitted adjacent to their\n\t// calls because Anthropic requires that ordering. A reused ID starts a new\n\t// pairing window, so a later result cannot repair an earlier call.\n\tconst result: Message[] = [];\n\tconst toolResultsById = new Map<string, { message: ToolResultMessage; sourceIndex: number; consumed: boolean }[]>();\n\tconst nextToolCallIndexById = new Map<string, number[]>();\n\t// Tool calls declared only by assistants the emit loop drops (errored/aborted).\n\t// Their results must not be emitted either: a strict provider rejects a tool\n\t// message whose tool_call_id no assistant in the request declares.\n\tconst droppedCallIds = new Set<string>();\n\n\tfor (let sourceIndex = 0; sourceIndex < transformed.length; sourceIndex++) {\n\t\tconst message = transformed[sourceIndex];\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst entries = toolResultsById.get(message.toolCallId) ?? [];\n\t\t\tentries.push({ message, sourceIndex, consumed: false });\n\t\t\ttoolResultsById.set(message.toolCallId, entries);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"assistant\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"toolCall\") droppedCallIds.add(block.id);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const block of message.content) {\n\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\tconst indexes = nextToolCallIndexById.get(block.id) ?? [];\n\t\t\tindexes.push(sourceIndex);\n\t\t\tnextToolCallIndexById.set(block.id, indexes);\n\t\t}\n\t}\n\n\tfor (let sourceIndex = 0; sourceIndex < transformed.length; sourceIndex++) {\n\t\tconst message = transformed[sourceIndex];\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst entry = toolResultsById\n\t\t\t\t.get(message.toolCallId)\n\t\t\t\t?.find((candidate) => candidate.sourceIndex === sourceIndex);\n\t\t\tif (!entry?.consumed) {\n\t\t\t\t// Skip results whose call was declared only by a dropped\n\t\t\t\t// (errored/aborted) assistant. An id re-declared by a kept assistant\n\t\t\t\t// still pairs through the normal windows, so keep those results.\n\t\t\t\tif (!droppedCallIds.has(message.toolCallId) || nextToolCallIndexById.has(message.toolCallId)) {\n\t\t\t\t\tresult.push(message);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role !== \"assistant\") {\n\t\t\tresult.push(message);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Skip errored/aborted assistant messages entirely. These incomplete turns\n\t\t// must not be revived merely because a matching result appears later.\n\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") continue;\n\n\t\tresult.push(message);\n\t\tfor (const block of message.content) {\n\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\tconst laterDeclarations = nextToolCallIndexById.get(block.id) ?? [];\n\t\t\tconst nextDeclarationIndex = laterDeclarations.find((index) => index > sourceIndex) ?? Infinity;\n\t\t\tconst matchedResult = toolResultsById\n\t\t\t\t.get(block.id)\n\t\t\t\t?.find(\n\t\t\t\t\t(candidate) =>\n\t\t\t\t\t\t!candidate.consumed &&\n\t\t\t\t\t\tcandidate.sourceIndex > sourceIndex &&\n\t\t\t\t\t\tcandidate.sourceIndex < nextDeclarationIndex,\n\t\t\t\t);\n\n\t\t\tif (matchedResult) {\n\t\t\t\tmatchedResult.consumed = true;\n\t\t\t\tresult.push(matchedResult.message);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tresult.push({\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: block.id,\n\t\t\t\ttoolName: block.name,\n\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t} as ToolResultMessage);\n\t\t}\n\t}\n\n\treturn result;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"warm-prompt-cache.js","sourceRoot":"","sources":["../../src/api/warm-prompt-cache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAmBrE,MAAM,CAAC,KAAK,UAAU,eAAe,CACpC,KAAiB,EACjB,OAAgB,EAChB,
|
|
1
|
+
{"version":3,"file":"warm-prompt-cache.js","sourceRoot":"","sources":["../../src/api/warm-prompt-cache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAmBrE,MAAM,CAAC,KAAK,UAAU,eAAe,CACpC,KAAiB,EACjB,OAAgB,EAChB,UAAkC,EAAE;IAEpC,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QACjF,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,MAAM,cAAc,GAAG,KAAoC,CAAC;IAC5D,4EAA4E;IAC5E,kFAAkF;IAClF,MAAM,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,EAAE,mCAAmC,EAAE,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QAC3F,MAAM,CAAC,mBAAmB,CAAC;QAC3B,MAAM,CAAC,yBAAyB,CAAC;KACjC,CAAC,CAAC;IACH,M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CAAC,CAAC,EAAE,CAAC;KAC1E,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC;IAChC,OAAO;QACN,SAAS,EAAE,IAAI;QACf,KAAK,EAAE;YACN,KAAK,EAAE,QAAQ,CAAC,YAAY;YAC5B,MAAM,EAAE,QAAQ,CAAC,aAAa;YAC9B,SAAS,EAAE,QAAQ,CAAC,uBAAuB,IAAI,CAAC;YAChD,UAAU,EAAE,QAAQ,CAAC,2BAA2B,IAAI,CAAC;SACrD;QACD,QAAQ;KACR,CAAC;AACH,CAAC","sourcesContent":["import type { Context, Model, ProviderHeaders, StreamOptions } from \"../types.ts\";\nimport { providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { isAnthropicApiBaseUrl } from \"../utils/prompt-cache-ttl.ts\";\nimport type { AnthropicOptions } from \"./anthropic-messages.ts\";\n\nexport interface WarmPromptCacheUsage {\n\treadonly input: number;\n\treadonly output: number;\n\treadonly cacheRead: number;\n\treadonly cacheWrite: number;\n}\n\nexport type WarmPromptCacheResult =\n\t| { readonly supported: false }\n\t| { readonly supported: true; readonly usage: WarmPromptCacheUsage; readonly usageRaw: unknown };\n\nexport type WarmPromptCacheOptions = Pick<\n\tStreamOptions,\n\t\"apiKey\" | \"cacheRetention\" | \"env\" | \"fetch\" | \"headers\" | \"onPayload\" | \"sessionId\" | \"signal\" | \"timeoutMs\"\n>;\n\nexport async function warmPromptCache(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: WarmPromptCacheOptions = {},\n): Promise<WarmPromptCacheResult> {\n\tif (model.api !== \"anthropic-messages\" || !isAnthropicApiBaseUrl(model.baseUrl)) {\n\t\treturn { supported: false };\n\t}\n\n\tconst anthropicModel = model as Model<\"anthropic-messages\">;\n\t// Loaded lazily: a static import would pull the Anthropic SDK into the root\n\t// barrel and break the lazy provider-loading contract (lazy-module-load.test.ts).\n\tconst [{ default: Anthropic }, { buildAnthropicWarmPromptCacheParams }] = await Promise.all([\n\t\timport(\"@anthropic-ai/sdk\"),\n\t\timport(\"./anthropic-messages.ts\"),\n\t]);\n\tconst headers = providerHeadersToRecord(options.headers);\n\tconst client = new Anthropic({\n\t\tapiKey: options.apiKey ?? null,\n\t\tbaseURL: anthropicModel.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tfetch: options.fetch,\n\t\tdefaultHeaders: { ...anthropicModel.headers, ...headers },\n\t});\n\tlet params = buildAnthropicWarmPromptCacheParams(anthropicModel, context, options as AnthropicOptions);\n\tconst transformed = await options.onPayload?.(params, anthropicModel, {\n\t\tmodel: anthropicModel,\n\t\theaders: headers as ProviderHeaders,\n\t});\n\tif (transformed !== undefined) params = transformed as typeof params;\n\tconst sanitized = { ...params } as Record<string, unknown>;\n\tdelete sanitized.stream;\n\tdelete sanitized.thinking;\n\tdelete sanitized.output_config;\n\tdelete sanitized.tool_choice;\n\tsanitized.max_tokens = 0;\n\n\tconst response = await client.messages.create(sanitized as unknown as typeof params, {\n\t\tmaxRetries: 0,\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t\t...(options.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t});\n\tconst usageRaw = response.usage;\n\treturn {\n\t\tsupported: true,\n\t\tusage: {\n\t\t\tinput: usageRaw.input_tokens,\n\t\t\toutput: usageRaw.output_tokens,\n\t\t\tcacheRead: usageRaw.cache_read_input_tokens ?? 0,\n\t\t\tcacheWrite: usageRaw.cache_creation_input_tokens ?? 0,\n\t\t},\n\t\tusageRaw,\n\t};\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Credential, CredentialInfo, CredentialStore } from "./types.ts";
|
|
1
|
+
import type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from "./types.ts";
|
|
2
2
|
/**
|
|
3
3
|
* Default in-memory credential store. Apps inject persistent stores.
|
|
4
4
|
* Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.
|
|
@@ -7,11 +7,11 @@ import type { Credential, CredentialInfo, CredentialStore } from "./types.ts";
|
|
|
7
7
|
export declare class InMemoryCredentialStore implements CredentialStore {
|
|
8
8
|
private credentials;
|
|
9
9
|
private chains;
|
|
10
|
-
/** Serialize tasks per provider id. */
|
|
10
|
+
/** Serialize tasks per provider id without releasing the chain before active work settles. */
|
|
11
11
|
private enqueue;
|
|
12
|
-
read(providerId: string): Promise<Credential | undefined>;
|
|
13
|
-
list(): Promise<readonly CredentialInfo[]>;
|
|
14
|
-
modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined
|
|
15
|
-
delete(providerId: string): Promise<void>;
|
|
12
|
+
read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;
|
|
13
|
+
list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;
|
|
14
|
+
modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>, options?: AuthOperationOptions): Promise<Credential | undefined>;
|
|
15
|
+
delete(providerId: string, options?: AuthOperationOptions): Promise<void>;
|
|
16
16
|
}
|
|
17
17
|
//# sourceMappingURL=credential-store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-store.d.ts","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"credential-store.d.ts","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,UAAU,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEpG;;;;GAIG;AACH,qBAAa,uBAAwB,YAAW,eAAe;IAC9D,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,MAAM,CAAuC;IAErD,8FAA8F;IAC9F,OAAO,CAAC,OAAO;IAgBT,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAKzF,IAAI,CAAC,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC;IAK9E,MAAM,CACL,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,EACxE,OAAO,CAAC,EAAE,oBAAoB,GAC5B,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAclC,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC;CASzE"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { operationSignal, raceWithAbortSignal } from "../utils/abort.js";
|
|
1
2
|
/**
|
|
2
3
|
* Default in-memory credential store. Apps inject persistent stores.
|
|
3
4
|
* Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.
|
|
@@ -8,35 +9,45 @@ export class InMemoryCredentialStore {
|
|
|
8
9
|
this.credentials = new Map();
|
|
9
10
|
this.chains = new Map();
|
|
10
11
|
}
|
|
11
|
-
/** Serialize tasks per provider id. */
|
|
12
|
-
enqueue(providerId, task) {
|
|
12
|
+
/** Serialize tasks per provider id without releasing the chain before active work settles. */
|
|
13
|
+
enqueue(providerId, task, options) {
|
|
14
|
+
const signal = operationSignal(options?.signal);
|
|
13
15
|
const previous = this.chains.get(providerId) ?? Promise.resolve();
|
|
14
|
-
const
|
|
16
|
+
const queued = (async () => {
|
|
15
17
|
await previous.catch(() => { });
|
|
18
|
+
signal.throwIfAborted();
|
|
16
19
|
return task();
|
|
17
20
|
})();
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
const tail = queued.catch(() => { });
|
|
22
|
+
this.chains.set(providerId, tail);
|
|
23
|
+
void tail.then(() => {
|
|
24
|
+
if (this.chains.get(providerId) === tail)
|
|
25
|
+
this.chains.delete(providerId);
|
|
26
|
+
});
|
|
27
|
+
return raceWithAbortSignal(queued, signal);
|
|
20
28
|
}
|
|
21
|
-
async read(providerId) {
|
|
29
|
+
async read(providerId, options) {
|
|
30
|
+
options?.signal?.throwIfAborted();
|
|
22
31
|
return this.credentials.get(providerId);
|
|
23
32
|
}
|
|
24
|
-
async list() {
|
|
33
|
+
async list(options) {
|
|
34
|
+
options?.signal?.throwIfAborted();
|
|
25
35
|
return [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));
|
|
26
36
|
}
|
|
27
|
-
modify(providerId, fn) {
|
|
37
|
+
modify(providerId, fn, options) {
|
|
28
38
|
return this.enqueue(providerId, async () => {
|
|
29
39
|
const current = this.credentials.get(providerId);
|
|
30
40
|
const next = await fn(current);
|
|
41
|
+
options?.signal?.throwIfAborted();
|
|
31
42
|
if (next !== undefined)
|
|
32
43
|
this.credentials.set(providerId, next);
|
|
33
44
|
return next ?? current;
|
|
34
|
-
});
|
|
45
|
+
}, options);
|
|
35
46
|
}
|
|
36
|
-
delete(providerId) {
|
|
47
|
+
delete(providerId, options) {
|
|
37
48
|
return this.enqueue(providerId, async () => {
|
|
38
49
|
this.credentials.delete(providerId);
|
|
39
|
-
});
|
|
50
|
+
}, options);
|
|
40
51
|
}
|
|
41
52
|
}
|
|
42
53
|
//# sourceMappingURL=credential-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-store.js","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"credential-store.js","sourceRoot":"","sources":["../../src/auth/credential-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAGzE;;;;GAIG;AACH,MAAM,OAAO,uBAAuB;IAApC;QACS,gBAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;QAC5C,WAAM,GAAG,IAAI,GAAG,EAA4B,CAAC;IAwDtD,CAAC;IAtDA,8FAA8F;IACtF,OAAO,CAAI,UAAkB,EAAE,IAAsB,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,UAAU,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACzG,CAAC;IAED,MAAM,CACL,UAAkB,EAClB,EAAwE,EACxE,OAA8B;QAE9B,OAAO,IAAI,CAAC,OAAO,CAClB,UAAU,EACV,KAAK,IAAI,EAAE;YACV,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACjD,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC;YAC/B,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC;YAClC,IAAI,IAAI,KAAK,SAAS;gBAAE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;YAC/D,OAAO,IAAI,IAAI,OAAO,CAAC;QACxB,CAAC,EACD,OAAO,CACP,CAAC;IACH,CAAC;IAED,MAAM,CAAC,UAAkB,EAAE,OAA8B;QACxD,OAAO,IAAI,CAAC,OAAO,CAClB,UAAU,EACV,KAAK,IAAI,EAAE;YACV,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACrC,CAAC,EACD,OAAO,CACP,CAAC;IACH,CAAC;CACD","sourcesContent":["import { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from \"./types.ts\";\n\n/**\n * Default in-memory credential store. Apps inject persistent stores.\n * Keyed by `Provider.id`, one credential per provider; see `CredentialStore`.\n * Writes are serialized per provider through a promise chain.\n */\nexport class InMemoryCredentialStore implements CredentialStore {\n\tprivate credentials = new Map<string, Credential>();\n\tprivate chains = new Map<string, Promise<unknown>>();\n\n\t/** Serialize tasks per provider id without releasing the chain before active work settles. */\n\tprivate enqueue<T>(providerId: string, task: () => Promise<T>, options?: AuthOperationOptions): Promise<T> {\n\t\tconst signal = operationSignal(options?.signal);\n\t\tconst previous = this.chains.get(providerId) ?? Promise.resolve();\n\t\tconst queued = (async () => {\n\t\t\tawait previous.catch(() => {});\n\t\t\tsignal.throwIfAborted();\n\t\t\treturn task();\n\t\t})();\n\t\tconst tail = queued.catch(() => {});\n\t\tthis.chains.set(providerId, tail);\n\t\tvoid tail.then(() => {\n\t\t\tif (this.chains.get(providerId) === tail) this.chains.delete(providerId);\n\t\t});\n\t\treturn raceWithAbortSignal(queued, signal);\n\t}\n\n\tasync read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn this.credentials.get(providerId);\n\t}\n\n\tasync list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]> {\n\t\toptions?.signal?.throwIfAborted();\n\t\treturn [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tconst current = this.credentials.get(providerId);\n\t\t\t\tconst next = await fn(current);\n\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\tif (next !== undefined) this.credentials.set(providerId, next);\n\t\t\t\treturn next ?? current;\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void> {\n\t\treturn this.enqueue(\n\t\t\tproviderId,\n\t\t\tasync () => {\n\t\t\t\tthis.credentials.delete(providerId);\n\t\t\t},\n\t\t\toptions,\n\t\t);\n\t}\n}\n"]}
|
package/dist/auth/helpers.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAExD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,UAAU,
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAExD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,UAAU,CAsBlF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;CAC/B,GAAG,SAAS,CAcZ"}
|
package/dist/auth/helpers.js
CHANGED
|
@@ -8,15 +8,19 @@ export function envApiKeyAuth(name, envVars) {
|
|
|
8
8
|
return {
|
|
9
9
|
name,
|
|
10
10
|
login: async (interaction) => {
|
|
11
|
+
interaction.signal.throwIfAborted();
|
|
11
12
|
const key = await interaction.prompt({ type: "secret", message: `Enter ${name}` });
|
|
13
|
+
interaction.signal.throwIfAborted();
|
|
12
14
|
return { type: "api_key", key };
|
|
13
15
|
},
|
|
14
|
-
resolve: async ({ ctx, credential }) => {
|
|
16
|
+
resolve: async ({ ctx, credential, signal }) => {
|
|
17
|
+
signal.throwIfAborted();
|
|
15
18
|
if (credential?.key) {
|
|
16
19
|
return { auth: { apiKey: credential.key }, env: credential.env, source: "stored credential" };
|
|
17
20
|
}
|
|
18
21
|
for (const envVar of envVars) {
|
|
19
22
|
const value = await ctx.env(envVar);
|
|
23
|
+
signal.throwIfAborted();
|
|
20
24
|
if (value)
|
|
21
25
|
return { auth: { apiKey: value }, source: envVar };
|
|
22
26
|
}
|
|
@@ -39,9 +43,10 @@ export function lazyOAuth(input) {
|
|
|
39
43
|
};
|
|
40
44
|
return {
|
|
41
45
|
name: input.name,
|
|
46
|
+
isSubscription: input.isSubscription,
|
|
42
47
|
loginLabel: input.loginLabel,
|
|
43
48
|
login: async (interaction) => (await loaded()).login(interaction),
|
|
44
|
-
refresh: async (credential) => (await loaded()).refresh(credential),
|
|
49
|
+
refresh: async (credential, signal) => (await loaded()).refresh(credential, signal),
|
|
45
50
|
toAuth: async (credential) => (await loaded()).toAuth(credential),
|
|
46
51
|
};
|
|
47
52
|
}
|
package/dist/auth/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAA0B;IACrE,OAAO;QACN,IAAI;QACJ,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE;YAC5B,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE,EAAE,CAAC,CAAC;YACnF,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;QACjC,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE;
|
|
1
|
+
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAA0B;IACrE,OAAO;QACN,IAAI;QACJ,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE;YAC5B,WAAW,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YACpC,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAA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AAC,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC;QACjE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC;QACnF,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC;KACjE,CAAC;AACH,CAAC","sourcesContent":["import type { ApiKeyAuth, OAuthAuth } from \"./types.ts\";\n\n/**\n * Standard api-key auth: a stored credential key wins, otherwise the first\n * set env var resolves. Includes a `login` that prompts for the key.\n * Providers with non-standard resolution (provider env, ambient files, IAM)\n * write their own `ApiKeyAuth`.\n */\nexport function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth {\n\treturn {\n\t\tname,\n\t\tlogin: async (interaction) => {\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: `Enter ${name}` });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\t\t\tfor (const envVar of envVars) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (value) return { auth: { apiKey: value }, source: envVar };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/**\n * Wraps a dynamically imported `OAuthAuth` so provider definitions can\n * advertise OAuth without importing the implementation. The flow loads on\n * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out\n * of bundles by loading through a bundler-opaque dynamic import (variable\n * specifier, see the bedrock lazy wrapper).\n */\nexport function lazyOAuth(input: {\n\tname: string;\n\tisSubscription?: boolean;\n\tloginLabel?: string;\n\tload: () => Promise<OAuthAuth>;\n}): OAuthAuth {\n\tlet promise: Promise<OAuthAuth> | undefined;\n\tconst loaded = () => {\n\t\tpromise ??= input.load();\n\t\treturn promise;\n\t};\n\treturn {\n\t\tname: input.name,\n\t\tisSubscription: input.isSubscription,\n\t\tloginLabel: input.loginLabel,\n\t\tlogin: async (interaction) => (await loaded()).login(interaction),\n\t\trefresh: async (credential, signal) => (await loaded()).refresh(credential, signal),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAyVvF,eAAO,MAAM,cAAc,EAAE,SAS5B,CAAC"}
|
|
@@ -140,7 +140,7 @@ async function startCallbackServer(expectedState) {
|
|
|
140
140
|
});
|
|
141
141
|
});
|
|
142
142
|
}
|
|
143
|
-
async function postJson(url, body) {
|
|
143
|
+
async function postJson(url, body, signal) {
|
|
144
144
|
const response = await fetch(url, {
|
|
145
145
|
method: "POST",
|
|
146
146
|
headers: {
|
|
@@ -148,7 +148,7 @@ async function postJson(url, body) {
|
|
|
148
148
|
Accept: "application/json",
|
|
149
149
|
},
|
|
150
150
|
body: JSON.stringify(body),
|
|
151
|
-
signal: AbortSignal.timeout(30_000),
|
|
151
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
|
|
152
152
|
});
|
|
153
153
|
const responseBody = await response.text();
|
|
154
154
|
if (!response.ok) {
|
|
@@ -156,7 +156,7 @@ async function postJson(url, body) {
|
|
|
156
156
|
}
|
|
157
157
|
return responseBody;
|
|
158
158
|
}
|
|
159
|
-
async function exchangeAuthorizationCode(code, state, verifier, redirectUri) {
|
|
159
|
+
async function exchangeAuthorizationCode(code, state, verifier, redirectUri, signal) {
|
|
160
160
|
let responseBody;
|
|
161
161
|
try {
|
|
162
162
|
responseBody = await postJson(TOKEN_URL, {
|
|
@@ -166,7 +166,7 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri) {
|
|
|
166
166
|
state,
|
|
167
167
|
redirect_uri: redirectUri,
|
|
168
168
|
code_verifier: verifier,
|
|
169
|
-
});
|
|
169
|
+
}, signal);
|
|
170
170
|
}
|
|
171
171
|
catch (error) {
|
|
172
172
|
throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`);
|
|
@@ -189,6 +189,10 @@ async function loginAnthropic(interaction) {
|
|
|
189
189
|
const { verifier, challenge } = await generatePKCE();
|
|
190
190
|
const server = await startCallbackServer(verifier);
|
|
191
191
|
const manualAbort = new AbortController();
|
|
192
|
+
const onAbort = () => server.cancelWait();
|
|
193
|
+
interaction.signal.addEventListener("abort", onAbort, { once: true });
|
|
194
|
+
if (interaction.signal.aborted)
|
|
195
|
+
onAbort();
|
|
192
196
|
let code;
|
|
193
197
|
let state;
|
|
194
198
|
let manualInput;
|
|
@@ -255,9 +259,10 @@ async function loginAnthropic(interaction) {
|
|
|
255
259
|
if (!state)
|
|
256
260
|
throw new Error("Missing OAuth state");
|
|
257
261
|
interaction.notify({ type: "progress", message: "Exchanging authorization code for tokens..." });
|
|
258
|
-
return exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI);
|
|
262
|
+
return exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);
|
|
259
263
|
}
|
|
260
264
|
finally {
|
|
265
|
+
interaction.signal.removeEventListener("abort", onAbort);
|
|
261
266
|
manualAbort.abort();
|
|
262
267
|
server.server.close();
|
|
263
268
|
}
|
|
@@ -265,14 +270,14 @@ async function loginAnthropic(interaction) {
|
|
|
265
270
|
/**
|
|
266
271
|
* Refresh Anthropic OAuth token
|
|
267
272
|
*/
|
|
268
|
-
async function refreshAnthropicToken(refreshToken) {
|
|
273
|
+
async function refreshAnthropicToken(refreshToken, signal) {
|
|
269
274
|
let responseBody;
|
|
270
275
|
try {
|
|
271
276
|
responseBody = await postJson(TOKEN_URL, {
|
|
272
277
|
grant_type: "refresh_token",
|
|
273
278
|
client_id: CLIENT_ID,
|
|
274
279
|
refresh_token: refreshToken,
|
|
275
|
-
});
|
|
280
|
+
}, signal);
|
|
276
281
|
}
|
|
277
282
|
catch (error) {
|
|
278
283
|
throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);
|
|
@@ -293,8 +298,9 @@ async function refreshAnthropicToken(refreshToken) {
|
|
|
293
298
|
}
|
|
294
299
|
export const anthropicOAuth = {
|
|
295
300
|
name: "Anthropic (Claude Pro/Max)",
|
|
301
|
+
isSubscription: true,
|
|
296
302
|
login: loginAnthropic,
|
|
297
|
-
refresh: (credential) => refreshAnthropicToken(credential.refresh),
|
|
303
|
+
refresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),
|
|
298
304
|
async toAuth(credential) {
|
|
299
305
|
return { apiKey: credential.access };
|
|
300
306
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAazC,IAAI,QAAQ,GAAoB,IAAI,CAAC;AACrC,IAAI,eAAe,GAA6B,IAAI,CAAC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AM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport type { Server } from \"node:http\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { AuthInteraction, OAuthAuth, OAuthCredential } from \"../types.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\ntype CallbackServerInfo = {\n\tserver: Server;\n\tredirectUri: string;\n\tcancelWait: () => void;\n\twaitForCode: () => Promise<{ code: string; state: string } | null>;\n};\n\ntype NodeApis = {\n\tcreateServer: typeof import(\"node:http\").createServer;\n};\n\nlet nodeApis: NodeApis | null = null;\nlet nodeApisPromise: Promise<NodeApis> | null = null;\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode(\"OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl\");\nconst AUTHORIZE_URL = \"https://claude.ai/oauth/authorize\";\nconst TOKEN_URL = \"https://platform.claude.com/v1/oauth/token\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 53692;\nconst CALLBACK_PATH = \"/callback\";\nconst REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst SCOPES =\n\t\"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\nasync function getNodeApis(): Promise<NodeApis> {\n\tif (nodeApis) return nodeApis;\n\tif (!nodeApisPromise) {\n\t\tif (typeof process === \"undefined\" || (!process.versions?.node && !process.versions?.bun)) {\n\t\t\tthrow new Error(\"Anthropic OAuth is only available in Node.js environments\");\n\t\t}\n\t\tnodeApisPromise = import(\"node:http\").then((httpModule) => ({\n\t\t\tcreateServer: httpModule.createServer,\n\t\t}));\n\t}\n\tnodeApis = await nodeApisPromise;\n\treturn nodeApis;\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\n\t}\n\n\treturn { code: value };\n}\n\nfunction formatErrorDetails(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst details: string[] = [`${error.name}: ${error.message}`];\n\t\tconst errorWithCode = error as Error & { code?: string; errno?: number | string; cause?: unknown };\n\t\tif (errorWithCode.code) details.push(`code=${errorWithCode.code}`);\n\t\tif (typeof errorWithCode.errno !== \"undefined\") details.push(`errno=${String(errorWithCode.errno)}`);\n\t\tif (typeof error.cause !== \"undefined\") {\n\t\t\tdetails.push(`cause=${formatErrorDetails(error.cause)}`);\n\t\t}\n\t\tif (error.stack) {\n\t\t\tdetails.push(`stack=${error.stack}`);\n\t\t}\n\t\treturn details.join(\"; \");\n\t}\n\treturn String(error);\n}\n\nasync function startCallbackServer(expectedState: string): Promise<CallbackServerInfo> {\n\tconst { createServer } = await getNodeApis();\n\n\treturn new Promise((resolve, reject) => {\n\t\tlet settleWait: ((value: { code: string; state: string } | null) => void) | undefined;\n\t\tconst waitForCodePromise = new Promise<{ code: string; state: string } | null>((resolveWait) => {\n\t\t\tlet settled = false;\n\t\t\tsettleWait = (value) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolveWait(value);\n\t\t\t};\n\t\t});\n\n\t\tconst server = createServer((req, res) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tres.writeHead(404, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst code = url.searchParams.get(\"code\");\n\t\t\t\tconst state = url.searchParams.get(\"state\");\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Anthropic authentication did not complete.\", `Error: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!code || !state) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Missing code or state parameter.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (state !== expectedState) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"State mismatch.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(oauthSuccessHtml(\"Anthropic authentication completed. You can close this window.\"));\n\t\t\t\tsettleWait?.({ code, state });\n\t\t\t} catch {\n\t\t\t\tres.writeHead(500, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n\t\t\t\tres.end(\"Internal error\");\n\t\t\t}\n\t\t});\n\n\t\tserver.on(\"error\", (err) => {\n\t\t\treject(err);\n\t\t});\n\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tresolve({\n\t\t\t\tserver,\n\t\t\t\tredirectUri: REDIRECT_URI,\n\t\t\t\tcancelWait: () => {\n\t\t\t\t\tsettleWait?.(null);\n\t\t\t\t},\n\t\t\t\twaitForCode: () => waitForCodePromise,\n\t\t\t});\n\t\t});\n\t});\n}\n\nasync function postJson(url: string, body: Record<string, string | number>): Promise<string> {\n\tconst response = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: AbortSignal.timeout(30_000),\n\t});\n\n\tconst responseBody = await response.text();\n\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);\n\t}\n\n\treturn responseBody;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tstate: string,\n\tverifier: string,\n\tredirectUri: string,\n): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(TOKEN_URL, {\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tcode,\n\t\t\tstate,\n\t\t\tredirect_uri: redirectUri,\n\t\t\tcode_verifier: verifier,\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\tlet tokenData: { access_token: string; refresh_token: string; expires_in: number };\n\ttry {\n\t\ttokenData = JSON.parse(responseBody) as { access_token: string; refresh_token: string; expires_in: number };\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: tokenData.refresh_token,\n\t\taccess: tokenData.access_token,\n\t\texpires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nasync function loginAnthropic(interaction: AuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst server = await startCallbackServer(verifier);\n\tconst manualAbort = new AbortController();\n\tlet code: string | undefined;\n\tlet state: string | undefined;\n\tlet manualInput: string | undefined;\n\tlet manualError: Error | undefined;\n\n\ttry {\n\t\tconst authParams = new URLSearchParams({\n\t\t\tcode: \"true\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tresponse_type: \"code\",\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tscope: SCOPES,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tstate: verifier,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\t\tinstructions:\n\t\t\t\t\"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst manualPromise = interaction\n\t\t\t.prompt({\n\t\t\t\ttype: \"manual_code\",\n\t\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\t\tplaceholder: REDIRECT_URI,\n\t\t\t\tsignal: manualAbort.signal,\n\t\t\t})\n\t\t\t.then((input) => {\n\t\t\t\tmanualInput = input;\n\t\t\t\tserver.cancelWait();\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tmanualError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tserver.cancelWait();\n\t\t\t});\n\n\t\tconst result = await server.waitForCode();\n\t\tif (manualError) throw manualError;\n\t\tif (result?.code) {\n\t\t\tcode = result.code;\n\t\t\tstate = result.state;\n\t\t} else if (manualInput) {\n\t\t\tconst parsed = parseAuthorizationInput(manualInput);\n\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\tcode = parsed.code;\n\t\t\tstate = parsed.state ?? verifier;\n\t\t}\n\n\t\tif (!code) {\n\t\t\tawait manualPromise;\n\t\t\tif (manualError) throw manualError;\n\t\t\tif (manualInput) {\n\t\t\t\tconst parsed = parseAuthorizationInput(manualInput);\n\t\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\t\tcode = parsed.code;\n\t\t\t\tstate = parsed.state ?? verifier;\n\t\t\t}\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tif (!state) throw new Error(\"Missing OAuth state\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI);\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tserver.server.close();\n\t}\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken: string): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(TOKEN_URL, {\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\trefresh_token: refreshToken,\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);\n\t}\n\n\tlet data: { access_token: string; refresh_token: string; expires_in: number; scope?: string };\n\ttry {\n\t\tdata = JSON.parse(responseBody) as {\n\t\t\taccess_token: string;\n\t\t\trefresh_token: string;\n\t\t\texpires_in: number;\n\t\t\tscope?: string;\n\t\t};\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: data.refresh_token,\n\t\taccess: data.access_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nexport const anthropicOAuth: OAuthAuth = {\n\tname: \"Anthropic (Claude Pro/Max)\",\n\tlogin: loginAnthropic,\n\trefresh: (credential) => refreshAnthropicToken(credential.refresh),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
|
|
1
|
+
{"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAazC,IAAI,QAAQ,GAAoB,IAAI,CAAC;AACrC,IAAI,eAAe,GAA6B,IAAI,CAAC;AAErD,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,SAAS,GAAG,MAAM,CAAC,kDAAkD,CAAC,CAAC;AAC7E,MAAM,aAAa,GAAG,mCAAmC,CAAC;AAC1D,MAAM,SAAS,GAAG,4CAA4C,CAAC;AAC/D,MAAM,aAAa,GAAG,mBAAmB,CAAC,wBAAwB,CAAC,IAAI,WAAW,CAAC;AACnF,MAAM,aAAa,GAAG,KAAK,CAAC;AAC5B,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,YAAY,GAAG,oBAAoB,aAAa,GAAG,aAAa,EAAE,CAAC;AACzE,MAAM,MAAM,GACX,4GAA4G,CAAC;AAC9G,KAAK,UAAU,WAAW;IACzB,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC9B,IAAI,CAAC,eAAe,EAAE,CAAC;QACtB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,QAAQ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Q,CAC5B,SAAS,EACT;YACC,UAAU,EAAE,eAAe;YAC3B,SAAS,EAAE,SAAS;YACpB,aAAa,EAAE,YAAY;SAC3B,EACD,MAAM,CACN,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,+CAA+C,SAAS,aAAa,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACnH,CAAC;IAED,IAAI,IAAyF,CAAC;IAC9F,IAAI,CAAC;QACJ,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAK7B,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CACd,sDAAsD,SAAS,UAAU,YAAY,aAAa,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAC7H,CAAC;IACH,CAAC;IAED,OAAO;QACN,IAAI,EAAE,OAAO;QACb,OAAO,EAAE,IAAI,CAAC,aAAa;QAC3B,MAAM,EAAE,IAAI,CAAC,YAAY;QACzB,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI;KAC5D,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAc;IACxC,IAAI,EAAE,4BAA4B;IAClC,cAAc,EAAE,IAAI;IACpB,KAAK,EAAE,cAAc;IACrB,OAAO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,qBAAqB,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IAElF,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport type { Server } from \"node:http\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\ntype CallbackServerInfo = {\n\tserver: Server;\n\tredirectUri: string;\n\tcancelWait: () => void;\n\twaitForCode: () => Promise<{ code: string; state: string } | null>;\n};\n\ntype NodeApis = {\n\tcreateServer: typeof import(\"node:http\").createServer;\n};\n\nlet nodeApis: NodeApis | null = null;\nlet nodeApisPromise: Promise<NodeApis> | null = null;\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode(\"OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl\");\nconst AUTHORIZE_URL = \"https://claude.ai/oauth/authorize\";\nconst TOKEN_URL = \"https://platform.claude.com/v1/oauth/token\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 53692;\nconst CALLBACK_PATH = \"/callback\";\nconst REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst SCOPES =\n\t\"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\nasync function getNodeApis(): Promise<NodeApis> {\n\tif (nodeApis) return nodeApis;\n\tif (!nodeApisPromise) {\n\t\tif (typeof process === \"undefined\" || (!process.versions?.node && !process.versions?.bun)) {\n\t\t\tthrow new Error(\"Anthropic OAuth is only available in Node.js environments\");\n\t\t}\n\t\tnodeApisPromise = import(\"node:http\").then((httpModule) => ({\n\t\t\tcreateServer: httpModule.createServer,\n\t\t}));\n\t}\n\tnodeApis = await nodeApisPromise;\n\treturn nodeApis;\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\n\t}\n\n\treturn { code: value };\n}\n\nfunction formatErrorDetails(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst details: string[] = [`${error.name}: ${error.message}`];\n\t\tconst errorWithCode = error as Error & { code?: string; errno?: number | string; cause?: unknown };\n\t\tif (errorWithCode.code) details.push(`code=${errorWithCode.code}`);\n\t\tif (typeof errorWithCode.errno !== \"undefined\") details.push(`errno=${String(errorWithCode.errno)}`);\n\t\tif (typeof error.cause !== \"undefined\") {\n\t\t\tdetails.push(`cause=${formatErrorDetails(error.cause)}`);\n\t\t}\n\t\tif (error.stack) {\n\t\t\tdetails.push(`stack=${error.stack}`);\n\t\t}\n\t\treturn details.join(\"; \");\n\t}\n\treturn String(error);\n}\n\nasync function startCallbackServer(expectedState: string): Promise<CallbackServerInfo> {\n\tconst { createServer } = await getNodeApis();\n\n\treturn new Promise((resolve, reject) => {\n\t\tlet settleWait: ((value: { code: string; state: string } | null) => void) | undefined;\n\t\tconst waitForCodePromise = new Promise<{ code: string; state: string } | null>((resolveWait) => {\n\t\t\tlet settled = false;\n\t\t\tsettleWait = (value) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolveWait(value);\n\t\t\t};\n\t\t});\n\n\t\tconst server = createServer((req, res) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tres.writeHead(404, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst code = url.searchParams.get(\"code\");\n\t\t\t\tconst state = url.searchParams.get(\"state\");\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\n\t\t\t\tif (error) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Anthropic authentication did not complete.\", `Error: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!code || !state) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"Missing code or state parameter.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (state !== expectedState) {\n\t\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\t\tres.end(oauthErrorHtml(\"State mismatch.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(oauthSuccessHtml(\"Anthropic authentication completed. You can close this window.\"));\n\t\t\t\tsettleWait?.({ code, state });\n\t\t\t} catch {\n\t\t\t\tres.writeHead(500, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n\t\t\t\tres.end(\"Internal error\");\n\t\t\t}\n\t\t});\n\n\t\tserver.on(\"error\", (err) => {\n\t\t\treject(err);\n\t\t});\n\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tresolve({\n\t\t\t\tserver,\n\t\t\t\tredirectUri: REDIRECT_URI,\n\t\t\t\tcancelWait: () => {\n\t\t\t\t\tsettleWait?.(null);\n\t\t\t\t},\n\t\t\t\twaitForCode: () => waitForCodePromise,\n\t\t\t});\n\t\t});\n\t});\n}\n\nasync function postJson(url: string, body: Record<string, string | number>, signal: AbortSignal): Promise<string> {\n\tconst response = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),\n\t});\n\n\tconst responseBody = await response.text();\n\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);\n\t}\n\n\treturn responseBody;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tstate: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\tcode,\n\t\t\t\tstate,\n\t\t\t\tredirect_uri: redirectUri,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\tlet tokenData: { access_token: string; refresh_token: string; expires_in: number };\n\ttry {\n\t\ttokenData = JSON.parse(responseBody) as { access_token: string; refresh_token: string; expires_in: number };\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: tokenData.refresh_token,\n\t\taccess: tokenData.access_token,\n\t\texpires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nasync function loginAnthropic(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst server = await startCallbackServer(verifier);\n\tconst manualAbort = new AbortController();\n\tconst onAbort = () => server.cancelWait();\n\tinteraction.signal.addEventListener(\"abort\", onAbort, { once: true });\n\tif (interaction.signal.aborted) onAbort();\n\tlet code: string | undefined;\n\tlet state: string | undefined;\n\tlet manualInput: string | undefined;\n\tlet manualError: Error | undefined;\n\n\ttry {\n\t\tconst authParams = new URLSearchParams({\n\t\t\tcode: \"true\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tresponse_type: \"code\",\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tscope: SCOPES,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tstate: verifier,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\t\tinstructions:\n\t\t\t\t\"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst manualPromise = interaction\n\t\t\t.prompt({\n\t\t\t\ttype: \"manual_code\",\n\t\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\t\tplaceholder: REDIRECT_URI,\n\t\t\t\tsignal: manualAbort.signal,\n\t\t\t})\n\t\t\t.then((input) => {\n\t\t\t\tmanualInput = input;\n\t\t\t\tserver.cancelWait();\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tmanualError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tserver.cancelWait();\n\t\t\t});\n\n\t\tconst result = await server.waitForCode();\n\t\tif (manualError) throw manualError;\n\t\tif (result?.code) {\n\t\t\tcode = result.code;\n\t\t\tstate = result.state;\n\t\t} else if (manualInput) {\n\t\t\tconst parsed = parseAuthorizationInput(manualInput);\n\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\tcode = parsed.code;\n\t\t\tstate = parsed.state ?? verifier;\n\t\t}\n\n\t\tif (!code) {\n\t\t\tawait manualPromise;\n\t\t\tif (manualError) throw manualError;\n\t\t\tif (manualInput) {\n\t\t\t\tconst parsed = parseAuthorizationInput(manualInput);\n\t\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\t\tcode = parsed.code;\n\t\t\t\tstate = parsed.state ?? verifier;\n\t\t\t}\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tif (!state) throw new Error(\"Missing OAuth state\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tinteraction.signal.removeEventListener(\"abort\", onAbort);\n\t\tmanualAbort.abort();\n\t\tserver.server.close();\n\t}\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);\n\t}\n\n\tlet data: { access_token: string; refresh_token: string; expires_in: number; scope?: string };\n\ttry {\n\t\tdata = JSON.parse(responseBody) as {\n\t\t\taccess_token: string;\n\t\t\trefresh_token: string;\n\t\t\texpires_in: number;\n\t\t\tscope?: string;\n\t\t};\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: data.refresh_token,\n\t\taccess: data.access_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nexport const anthropicOAuth: OAuthAuth = {\n\tname: \"Anthropic (Claude Pro/Max)\",\n\tisSubscription: true,\n\tlogin: loginAnthropic,\n\trefresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
|
|
@@ -16,7 +16,7 @@ export type OAuthDeviceCodePollOptions<T> = {
|
|
|
16
16
|
expiresInSeconds?: number;
|
|
17
17
|
waitBeforeFirstPoll?: boolean;
|
|
18
18
|
poll: () => Promise<OAuthDeviceCodePollResult<T>>;
|
|
19
|
-
signal
|
|
19
|
+
signal: AbortSignal;
|
|
20
20
|
};
|
|
21
21
|
export declare function pollOAuthDeviceCodeFlow<T>(options: OAuthDeviceCodePollOptions<T>): Promise<T>;
|
|
22
22
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"device-code.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/device-code.ts"],"names":[],"mappings":"AAUA,KAAK,mCAAmC,GACrC;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,MAAM,EAAE,QAAQ,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzC,MAAM,MAAM,yBAAyB,CAAC,CAAC,IAAI,mCAAmC,GAAG;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAC;AAElH,MAAM,MAAM,0BAA0B,CAAC,CAAC,IAAI;IAC3C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,IAAI,EAAE,MAAM,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,MAAM,
|
|
1
|
+
{"version":3,"file":"device-code.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/device-code.ts"],"names":[],"mappings":"AAUA,KAAK,mCAAmC,GACrC;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,MAAM,EAAE,QAAQ,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzC,MAAM,MAAM,yBAAyB,CAAC,CAAC,IAAI,mCAAmC,GAAG;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAC;AAElH,MAAM,MAAM,0BAA0B,CAAC,CAAC,IAAI;IAC3C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,IAAI,EAAE,MAAM,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,MAAM,EAAE,WAAW,CAAC;CACpB,CAAC;AAsBF,wBAAsB,uBAAuB,CAAC,CAAC,EAAE,OAAO,EAAE,0BAA0B,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAoDnG"}
|
|
@@ -8,7 +8,7 @@ const DEFAULT_POLL_INTERVAL_SECONDS = 5;
|
|
|
8
8
|
const SLOW_DOWN_INTERVAL_INCREMENT_MS = 5000;
|
|
9
9
|
function abortableSleep(ms, signal, cancelMessage) {
|
|
10
10
|
return new Promise((resolve, reject) => {
|
|
11
|
-
if (signal
|
|
11
|
+
if (signal.aborted) {
|
|
12
12
|
reject(new Error(cancelMessage));
|
|
13
13
|
return;
|
|
14
14
|
}
|
|
@@ -17,10 +17,10 @@ function abortableSleep(ms, signal, cancelMessage) {
|
|
|
17
17
|
reject(new Error(cancelMessage));
|
|
18
18
|
};
|
|
19
19
|
const timeout = setTimeout(() => {
|
|
20
|
-
signal
|
|
20
|
+
signal.removeEventListener("abort", onAbort);
|
|
21
21
|
resolve();
|
|
22
22
|
}, ms);
|
|
23
|
-
signal
|
|
23
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
24
24
|
});
|
|
25
25
|
}
|
|
26
26
|
export async function pollOAuthDeviceCodeFlow(options) {
|
|
@@ -36,7 +36,7 @@ export async function pollOAuthDeviceCodeFlow(options) {
|
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
while (Date.now() < deadline) {
|
|
39
|
-
if (options.signal
|
|
39
|
+
if (options.signal.aborted) {
|
|
40
40
|
throw new Error(CANCEL_MESSAGE);
|
|
41
41
|
}
|
|
42
42
|
const result = await options.poll();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"device-code.js","sourceRoot":"","sources":["../../../src/auth/oauth/device-code.ts"],"names":[],"mappings":"AAAA,MAAM,cAAc,GAAG,iBAAiB,CAAC;AACzC,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAChD,MAAM,yBAAyB,GAC9B,gLAAgL,CAAC;AAClL,MAAM,mBAAmB,GAAG,IAAI,CAAC;AACjC,qGAAqG;AACrG,MAAM,6BAA6B,GAAG,CAAC,CAAC;AACxC,2FAA2F;AAC3F,MAAM,+BAA+B,GAAG,IAAI,CAAC;AAiB7C,SAAS,cAAc,CAAC,EAAU,EAAE,
|
|
1
|
+
{"version":3,"file":"device-code.js","sourceRoot":"","sources":["../../../src/auth/oauth/device-code.ts"],"names":[],"mappings":"AAAA,MAAM,cAAc,GAAG,iBAAiB,CAAC;AACzC,MAAM,eAAe,GAAG,uBAAuB,CAAC;AAChD,MAAM,yBAAyB,GAC9B,gLAAg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C,CAAC;oBAC1E,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,mBAAmB,EAAE,UAAU,GAAG,+BAA+B,CAAC,CAAC;QACjF,CAAC;QAED,MAAM,WAAW,GAAG,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC1C,IAAI,WAAW,IAAI,CAAC,EAAE,CAAC;YACtB,MAAM;QACP,CAAC;QAED,MAAM,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACzF,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,iBAAiB,GAAG,CAAC,CAAC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC;AACtF,CAAC","sourcesContent":["const CANCEL_MESSAGE = \"Login cancelled\";\nconst TIMEOUT_MESSAGE = \"Device flow timed out\";\nconst SLOW_DOWN_TIMEOUT_MESSAGE =\n\t\"Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.\";\nconst MINIMUM_INTERVAL_MS = 1000;\n// RFC 8628 section 3.2: if the authorization server omits `interval`, the client must use 5 seconds.\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\n// RFC 8628 section 3.5: `slow_down` means the polling interval must increase by 5 seconds.\nconst SLOW_DOWN_INTERVAL_INCREMENT_MS = 5000;\n\ntype OAuthDeviceCodeIncompletePollResult =\n\t| { status: \"pending\" }\n\t| { status: \"slow_down\"; intervalSeconds?: number }\n\t| { status: \"failed\"; message: string };\n\nexport type OAuthDeviceCodePollResult<T> = OAuthDeviceCodeIncompletePollResult | { status: \"complete\"; value: T };\n\nexport type OAuthDeviceCodePollOptions<T> = {\n\tintervalSeconds?: number;\n\texpiresInSeconds?: number;\n\twaitBeforeFirstPoll?: boolean;\n\tpoll: () => Promise<OAuthDeviceCodePollResult<T>>;\n\tsignal: AbortSignal;\n};\n\nfunction abortableSleep(ms: number, signal: AbortSignal, cancelMessage: string): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal.aborted) {\n\t\t\treject(new Error(cancelMessage));\n\t\t\treturn;\n\t\t}\n\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(cancelMessage));\n\t\t};\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nexport async function pollOAuthDeviceCodeFlow<T>(options: OAuthDeviceCodePollOptions<T>): Promise<T> {\n\tconst deadline =\n\t\ttypeof options.expiresInSeconds === \"number\"\n\t\t\t? Date.now() + options.expiresInSeconds * 1000\n\t\t\t: Number.POSITIVE_INFINITY;\n\tlet intervalMs = Math.max(\n\t\tMINIMUM_INTERVAL_MS,\n\t\tMath.floor((options.intervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS) * 1000),\n\t);\n\n\tlet slowDownResponses = 0;\n\tif (options.waitBeforeFirstPoll) {\n\t\tconst remainingMs = deadline - Date.now();\n\t\tif (remainingMs > 0) {\n\t\t\tawait abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);\n\t\t}\n\t}\n\n\twhile (Date.now() < deadline) {\n\t\tif (options.signal.aborted) {\n\t\t\tthrow new Error(CANCEL_MESSAGE);\n\t\t}\n\n\t\tconst result = await options.poll();\n\t\tif (result.status === \"complete\") {\n\t\t\treturn result.value;\n\t\t}\n\t\tif (result.status === \"failed\") {\n\t\t\tthrow new Error(result.message);\n\t\t}\n\t\tif (result.status === \"slow_down\") {\n\t\t\tslowDownResponses += 1;\n\t\t\t// Use the server-provided interval when given (GitHub reports the new required minimum\n\t\t\t// in `interval`); trusting only a client-tracked value risks polling early forever under\n\t\t\t// WSL/VM clock drift. Otherwise apply RFC 8628 section 3.5: increase by 5 seconds.\n\t\t\tintervalMs =\n\t\t\t\ttypeof result.intervalSeconds === \"number\" &&\n\t\t\t\tNumber.isFinite(result.intervalSeconds) &&\n\t\t\t\tresult.intervalSeconds > 0\n\t\t\t\t\t? Math.max(MINIMUM_INTERVAL_MS, Math.floor(result.intervalSeconds * 1000))\n\t\t\t\t\t: Math.max(MINIMUM_INTERVAL_MS, intervalMs + SLOW_DOWN_INTERVAL_INCREMENT_MS);\n\t\t}\n\n\t\tconst remainingMs = deadline - Date.now();\n\t\tif (remainingMs <= 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tawait abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);\n\t}\n\n\tthrow new Error(slowDownResponses > 0 ? SLOW_DOWN_TIMEOUT_MESSAGE : TIMEOUT_MESSAGE);\n}\n"]}
|