@bastani/atomic 0.9.5-alpha.7 → 0.9.5-alpha.8
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/CHANGELOG.md +17 -2
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +17 -0
- package/dist/builtin/intercom/README.md +27 -21
- package/dist/builtin/intercom/broker/broker.ts +3 -6
- package/dist/builtin/intercom/broker/paths.ts +42 -5
- package/dist/builtin/intercom/broker/spawn.ts +78 -10
- package/dist/builtin/intercom/config.ts +6 -3
- package/dist/builtin/intercom/contact-supervisor-tool.ts +6 -4
- package/dist/builtin/intercom/index-heavy.ts +1 -1
- package/dist/builtin/intercom/index.ts +162 -130
- package/dist/builtin/intercom/intercom-tool.ts +9 -3
- package/dist/builtin/intercom/package.json +10 -1
- package/dist/builtin/intercom/result-renderers.ts +1 -1
- package/dist/builtin/intercom/ui/compose.ts +2 -2
- package/dist/builtin/intercom/ui/inline-message.ts +2 -2
- package/dist/builtin/intercom/ui/session-list.ts +2 -2
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/tui/render-event-formatting.ts +15 -48
- package/dist/builtin/subagents/src/tui/render-layout.ts +9 -0
- package/dist/builtin/subagents/src/tui/render-widget-graph.ts +27 -25
- package/dist/builtin/subagents/src/tui/render-widget.ts +46 -69
- package/dist/builtin/subagents/src/tui/render.ts +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +11 -0
- package/dist/builtin/workflows/README.md +3 -1
- package/dist/builtin/workflows/builtin/goal-artifacts.ts +3 -1
- package/dist/builtin/workflows/builtin/goal-prompts.ts +23 -2
- package/dist/builtin/workflows/builtin/goal-reducer.ts +21 -0
- package/dist/builtin/workflows/builtin/goal-review.ts +60 -6
- package/dist/builtin/workflows/builtin/goal-runner.ts +32 -21
- package/dist/builtin/workflows/builtin/goal-types.ts +7 -1
- package/dist/builtin/workflows/builtin/ralph-core.ts +52 -4
- package/dist/builtin/workflows/builtin/ralph-review-gate.ts +10 -3
- package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +23 -2
- package/dist/builtin/workflows/builtin/ralph-runner.ts +38 -16
- package/dist/builtin/workflows/builtin/review-convergence.ts +111 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/skills/create-spec/SKILL.md +2 -0
- package/dist/builtin/workflows/src/durable/child-primitive.ts +12 -8
- package/dist/builtin/workflows/src/durable/dbos-backend.ts +47 -2
- package/dist/builtin/workflows/src/durable/dbos-envelope.ts +28 -0
- package/dist/builtin/workflows/src/durable/stage-primitive.ts +165 -27
- package/dist/builtin/workflows/src/durable/types.ts +14 -1
- package/dist/builtin/workflows/src/engine/run.ts +12 -13
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +2 -0
- package/dist/builtin/workflows/src/runs/foreground/executor-continuation.ts +13 -3
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +18 -19
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-unresolved-overflow.ts +38 -0
- package/dist/builtin/workflows/src/shared/persistence-restore-helpers.ts +18 -1
- package/dist/builtin/workflows/src/shared/persistence-restore.ts +23 -5
- package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +4 -0
- package/dist/bun/internal-intercom-broker.d.ts +6 -0
- package/dist/bun/internal-intercom-broker.d.ts.map +1 -0
- package/dist/bun/internal-intercom-broker.js +39 -0
- package/dist/bun/internal-intercom-broker.js.map +1 -0
- package/dist/bun/split-loader.d.ts.map +1 -1
- package/dist/bun/split-loader.js +21 -8
- package/dist/bun/split-loader.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts +4 -5
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +49 -9
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +3 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +9 -3
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-models.d.ts +2 -2
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +1 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts +2 -0
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +152 -4
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +15 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +4 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +4 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/context-compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-runner.js +36 -20
- package/dist/core/compaction/context-compaction-runner.js.map +1 -1
- package/dist/core/copilot-anthropic-sse-repair.d.ts +23 -0
- package/dist/core/copilot-anthropic-sse-repair.d.ts.map +1 -0
- package/dist/core/copilot-anthropic-sse-repair.js +340 -0
- package/dist/core/copilot-anthropic-sse-repair.js.map +1 -0
- package/dist/core/copilot-gemini-reasoning.d.ts +16 -8
- package/dist/core/copilot-gemini-reasoning.d.ts.map +1 -1
- package/dist/core/copilot-gemini-reasoning.js +27 -22
- package/dist/core/copilot-gemini-reasoning.js.map +1 -1
- package/dist/core/copilot-hosts.d.ts +12 -0
- package/dist/core/copilot-hosts.d.ts.map +1 -0
- package/dist/core/copilot-hosts.js +33 -0
- package/dist/core/copilot-hosts.js.map +1 -0
- package/dist/core/extensions/agent-events.d.ts +1 -1
- package/dist/core/extensions/agent-events.d.ts.map +1 -1
- package/dist/core/extensions/agent-events.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +5 -5
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/sdk-types.d.ts +2 -0
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +6 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-types.d.ts +1 -0
- package/dist/core/settings-types.d.ts.map +1 -1
- package/dist/core/settings-types.js.map +1 -1
- package/dist/index-extensions.d.ts +1 -1
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index-extensions.js.map +1 -1
- package/dist/main-deferred-startup.d.ts +12 -0
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-deferred-startup.js +21 -0
- package/dist/main-deferred-startup.js.map +1 -1
- package/dist/main-early-input.d.ts +41 -0
- package/dist/main-early-input.d.ts.map +1 -0
- package/dist/main-early-input.js +147 -0
- package/dist/main-early-input.js.map +1 -0
- package/dist/main.d.ts +0 -6
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +19 -13
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.js +15 -0
- package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +24 -0
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +279 -181
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +9 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +36 -0
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +4 -0
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-types.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-types.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +21 -9
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +6 -1
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/docs/compaction.md +4 -0
- package/docs/json.md +3 -1
- package/docs/providers.md +1 -0
- package/docs/rpc.md +3 -1
- package/docs/settings.md +26 -0
- package/docs/terminal-setup.md +4 -0
- package/docs/usage.md +2 -2
- package/docs/workflows.md +13 -3
- package/npm-shrinkwrap.json +513 -23
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/context-compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAyC,MAAM,+BAA+B,CAAC;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OAAO,+BAA+B,CAAC,UAAU,EAAE,MAAM,CAAC,2BAA2B,CAAC,CAAC;IACxF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;QACnF,MAAM,IAAI,KAAK,CAAC,GAAG,2CAA2C,CAAC,QAAQ,EAAE,UAAU,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;IACrG,CAAC;AACF,CAAC","sourcesContent":["import { Agent, type AgentMessage, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { createAssistantMessageEventStream, isContextOverflow, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { formatCopilotProviderError } from \"../copilot-errors.ts\";\nimport type {\n\tCompactableTranscript,\n\tContextCompactionParameters,\n\tContextCompactionPreparation,\n\tValidatedContextDeletionResult,\n} from \"./context-compaction-types.ts\";\nimport { CONTEXT_COMPACTION_AUTO_QUERY } from \"./context-compaction-types.ts\";\nimport {\n\tcreateContextCompactionBudgetDetails,\n\tcontextCompactionProgressKey,\n\tcontextCompactionProgressPercent,\n\tcontextCompactionTargetLabel,\n\tcontextCompactionTargetMet,\n\tformatErrorMessage,\n} from \"./context-compaction-metrics.ts\";\nimport { getTranscriptCompactionParameters, normalizeContextCompactionParameters } from \"./context-compaction-strategy.ts\";\nimport {\n\tCONTEXT_COMPACTION_BUDGET_TOOL_NAME,\n\tCONTEXT_DELETE_TOOL_NAME,\n\tCONTEXT_GREP_DELETE_TOOL_NAME,\n\tCONTEXT_READ_ENTRY_TOOL_NAME,\n\tCONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME,\n} from \"./context-deletion-tool-definitions.ts\";\nimport { createContextDeletionTool } from \"./context-deletion-tools.ts\";\nimport {\n\tbuildContextCompactionPrompt,\n\tCONTEXT_COMPACTION_SYSTEM_PROMPT,\n\twriteContextCompactionTranscriptFile,\n} from \"./context-compaction-prompt.ts\";\nimport {\n\tCONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\tcriticalCompactionParameters,\n\trelaxTranscriptForCriticalEviction,\n} from \"./context-compaction-critical.ts\";\nimport { runDeterministicContextEviction } from \"./context-compaction-eviction.ts\";\n\nexport const CONTEXT_COMPACTION_MAX_TURNS = 50;\nexport const CONTEXT_COMPACTION_MAX_PLANNER_NUDGES = 50;\n\nexport interface ContextCompactionLadderOptions {\n\tacceptanceTokenBudget?: number;\n\tcriticalEvictionTokenBudget?: number;\n}\n\ninterface ContextDeletionAssistantOptions {\n\tpromptSuffix?: string;\n\tacceptanceTokenBudget?: number;\n}\n\nfunction createContextCompactionTargetNudgeMessage(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n): AgentMessage {\n\tconst currentReductionPercent = contextCompactionProgressPercent(result);\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tconst tokensToDelete = result\n\t\t? createContextCompactionBudgetDetails(result.stats, 0, undefined, parameters, 0, 0).tokensToDeleteForTarget\n\t\t: undefined;\n\tconst remainingText = tokensToDelete !== undefined ? ` Delete about ${tokensToDelete} more token(s) if safe candidates exist.` : \"\";\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `The strict ${targetLabel} context-reduction requirement is not met yet; current validated reduction is ${currentReductionPercent}%.${remainingText} Continue removing low-value message entries or message content blocks using ${CONTEXT_DELETE_TOOL_NAME} or ${CONTEXT_GREP_DELETE_TOOL_NAME}. Use the focus query ${JSON.stringify(parameters.query)} to preserve relevant context. Call ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME} to verify progress, and do not provide a final answer until the validated reduction is at least ${targetLabel}.`,\n\t\t\t},\n\t\t],\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionAssistantMessage(\n\tmodel: Model<Api>,\n\tcontent: AssistantMessage[\"content\"],\n\tstopReason: AssistantMessage[\"stopReason\"],\n\terrorMessage?: string,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent,\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason,\n\t\t...(errorMessage !== undefined ? { errorMessage } : {}),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionStopStream(model: Model<Api>, text: string) {\n\tconst stream = createAssistantMessageEventStream();\n\tqueueMicrotask(() => {\n\t\tconst message = createContextCompactionAssistantMessage(model, [{ type: \"text\", text }], \"stop\");\n\t\tstream.push({ type: \"done\", reason: \"stop\", message });\n\t\tstream.end(message);\n\t});\n\treturn stream;\n}\n\nfunction isContextCompactionOverflowError(model: Model<Api>, errorMessage: string): boolean {\n\treturn isContextOverflow(createContextCompactionAssistantMessage(model, [], \"error\", errorMessage), model.contextWindow);\n}\n\nfunction feasibleAccepted(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\treturn (\n\t\tacceptanceTokenBudget !== undefined &&\n\t\tresult !== undefined &&\n\t\tresult.deletedTargets.length > 0 &&\n\t\tresult.stats.tokensAfter <= acceptanceTokenBudget\n\t);\n}\n\nfunction acceptedWithinRun(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\tif (acceptanceTokenBudget !== undefined) return feasibleAccepted(result, acceptanceTokenBudget);\n\treturn contextCompactionTargetMet(result, parameters);\n}\n\nfunction targetMetAcceptedForLadder(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n\tladder: ContextCompactionLadderOptions | undefined,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\tif (!hasMetContextCompactionTarget(run, parameters)) return false;\n\tconst overflowBudget = ladder?.criticalEvictionTokenBudget;\n\treturn overflowBudget === undefined || run.validatedResult.stats.tokensAfter <= overflowBudget;\n}\n\ninterface ContextDeletionRun {\n\tvalidatedResult: ValidatedContextDeletionResult | undefined;\n\tlastToolError: string | undefined;\n\tproviderError: string | undefined;\n}\n\nasync function runContextDeletionAssistant(\n\tinputTranscript: CompactableTranscript,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tparameters: ContextCompactionParameters = getTranscriptCompactionParameters(inputTranscript),\n\toptions: ContextDeletionAssistantOptions = {},\n): Promise<ContextDeletionRun> {\n\tconst transcript: CompactableTranscript = { ...inputTranscript, parameters };\n\tconst maxTokens = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tconst transcriptFile = writeContextCompactionTranscriptFile(transcript);\n\tconst promptText = buildContextCompactionPrompt(transcript, transcriptFile.path, parameters) + (options.promptSuffix ?? \"\");\n\tconst promptMessage: AgentMessage = {\n\t\trole: \"user\",\n\t\tcontent: [{ type: \"text\", text: promptText }],\n\t\ttimestamp: Date.now(),\n\t};\n\tconst deletionTool = createContextDeletionTool(transcript, { contextWindow: model.contextWindow, ...parameters });\n\tlet providerTurnCount = 0;\n\tconst agent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: CONTEXT_COMPACTION_SYSTEM_PROMPT,\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: deletionTool.tools,\n\t\t},\n\t\ttoolExecution: \"parallel\",\n\t\tstreamFn: async (requestModel, context, streamOptions) => {\n\t\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached an acceptable context-reduction result (${currentResult.stats.percentReduction}%, ${currentResult.stats.tokensAfter} token(s) after deletion); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (providerTurnCount >= CONTEXT_COMPACTION_MAX_TURNS) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached the context compaction turn cap (${CONTEXT_COMPACTION_MAX_TURNS}); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tproviderTurnCount += 1;\n\t\t\treturn streamSimple(requestModel, context, {\n\t\t\t\t...streamOptions,\n\t\t\t\tmaxTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders: headers ?? streamOptions?.headers,\n\t\t\t});\n\t\t},\n\t});\n\n\tlet lastNudgedProgressKey: string | undefined;\n\tlet nudgeCount = 0;\n\tconst unsubscribeNudge = agent.subscribe((event, eventSignal) => {\n\t\tif (event.type !== \"turn_end\" || signal?.aborted || eventSignal.aborted) return;\n\t\tif (event.message.role !== \"assistant\") return;\n\t\tif (event.message.stopReason === \"error\" || event.message.stopReason === \"aborted\") return;\n\t\tif (event.message.content.some((content) => content.type === \"toolCall\")) return;\n\t\tif (nudgeCount >= CONTEXT_COMPACTION_MAX_PLANNER_NUDGES) return;\n\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) return;\n\t\tconst progressKey = contextCompactionProgressKey(currentResult);\n\t\tif (progressKey === lastNudgedProgressKey) return;\n\t\tlastNudgedProgressKey = progressKey;\n\t\tnudgeCount += 1;\n\t\tagent.followUp(createContextCompactionTargetNudgeMessage(currentResult, parameters));\n\t});\n\n\tconst abortOnSignal = () => agent.abort();\n\tsignal?.addEventListener(\"abort\", abortOnSignal, { once: true });\n\ttry {\n\t\tawait agent.prompt(promptMessage);\n\t} catch (error) {\n\t\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\t\tthrow new Error(`Context compaction failed: ${formatCopilotProviderError(model.provider, formatErrorMessage(error))}`);\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", abortOnSignal);\n\t\tunsubscribeNudge();\n\t\ttranscriptFile.cleanup();\n\t}\n\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tif (agent.state.errorMessage) {\n\t\tconst formattedErrorMessage = formatCopilotProviderError(model.provider, agent.state.errorMessage);\n\t\tif (isContextCompactionOverflowError(model, agent.state.errorMessage)) {\n\t\t\treturn {\n\t\t\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\t\t\tlastToolError: deletionTool.getLastError(),\n\t\t\t\tproviderError: formattedErrorMessage === agent.state.errorMessage ? undefined : formattedErrorMessage,\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Context compaction failed: ${formattedErrorMessage}`);\n\t}\n\tif (deletionTool.getCallCount() === 0) {\n\t\tthrow new Error(\n\t\t\t`Context compaction did not call any transcript inspection, budget, or deletion tools (${CONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME}, ${CONTEXT_READ_ENTRY_TOOL_NAME}, ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME}, ${CONTEXT_DELETE_TOOL_NAME}, or ${CONTEXT_GREP_DELETE_TOOL_NAME})`,\n\t\t);\n\t}\n\treturn {\n\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\tlastToolError: deletionTool.getLastError(),\n\t\tproviderError: undefined,\n\t};\n}\n\nfunction hasMetContextCompactionTarget(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\treturn contextCompactionTargetMet(run.validatedResult, parameters);\n}\n\nfunction formatContextCompactionTargetFailureMessage(\n\tattempts: readonly ContextDeletionRunAttempt[],\n\tparameters: ContextCompactionParameters,\n): string {\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tif (attempts.length === 0) return `Context compaction did not meet the strict ${targetLabel} reduction requirement`;\n\tconst attemptDetails = attempts\n\t\t.map((attempt) => {\n\t\t\tconst reduction = contextCompactionProgressPercent(attempt.validatedResult);\n\t\t\tconst deletionCount = attempt.validatedResult?.deletedTargets.length ?? 0;\n\t\t\tconst tokensAfterText = attempt.validatedResult ? `; tokens after: ${attempt.validatedResult.stats.tokensAfter}` : \"\";\n\t\t\tconst toolErrorText = attempt.lastToolError ? `; last deletion tool error: ${attempt.lastToolError}` : \"\";\n\t\t\tconst providerErrorText = attempt.providerError ? `; provider error: ${attempt.providerError}` : \"\";\n\t\t\treturn `attempt reached ${reduction}% with ${deletionCount} validated deletion target(s)${tokensAfterText}${toolErrorText}${providerErrorText}`;\n\t\t})\n\t\t.join(\"; \");\n\treturn `Context compaction did not meet the strict ${targetLabel} reduction requirement; ${attemptDetails}`;\n}\n\nfunction runFailedAttempt(error: Error): ContextDeletionRunAttempt {\n\treturn { validatedResult: undefined, lastToolError: undefined, providerError: error.message };\n}\n\nfunction shouldRethrowPlannerError(error: Error, signal: AbortSignal | undefined, ladder: ContextCompactionLadderOptions | undefined): boolean {\n\tif (signal?.aborted) return true;\n\tif (error.message === \"Context compaction failed: Request was aborted\") return true;\n\treturn ladder?.criticalEvictionTokenBudget === undefined;\n}\n\ninterface ContextDeletionRunAttempt extends ContextDeletionRun {}\n\nexport async function contextCompact(\n\tpreparation: ContextCompactionPreparation,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tladder?: ContextCompactionLadderOptions,\n): Promise<ValidatedContextDeletionResult> {\n\tconst parameters = normalizeContextCompactionParameters(\n\t\tpreparation.parameters ?? preparation.transcript.parameters,\n\t\tpreparation.parameters?.query ?? preparation.transcript.parameters?.query ?? CONTEXT_COMPACTION_AUTO_QUERY,\n\t);\n\tconst transcript: CompactableTranscript = { ...preparation.transcript, parameters };\n\tconst attempts: ContextDeletionRunAttempt[] = [];\n\ttry {\n\t\tconst standardRun = await runContextDeletionAssistant(transcript, model, apiKey, headers, signal, thinkingLevel, parameters);\n\t\tif (targetMetAcceptedForLadder(standardRun, parameters, ladder)) return standardRun.validatedResult;\n\t\tif (feasibleAccepted(standardRun.validatedResult, ladder?.acceptanceTokenBudget)) return standardRun.validatedResult;\n\t\tattempts.push({ ...standardRun });\n\t} catch (error) {\n\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\tif (shouldRethrowPlannerError(formattedError, signal, ladder)) throw formattedError;\n\t\tattempts.push(runFailedAttempt(formattedError));\n\t}\n\n\tif (ladder?.criticalEvictionTokenBudget === undefined) {\n\t\tthrow new Error(formatContextCompactionTargetFailureMessage(attempts, parameters));\n\t}\n\n\ttry {\n\t\tconst criticalParameters = criticalCompactionParameters(parameters);\n\t\tconst criticalTranscript = relaxTranscriptForCriticalEviction(transcript);\n\t\tconst criticalRun = await runContextDeletionAssistant(\n\t\t\tcriticalTranscript,\n\t\t\tmodel,\n\t\t\tapiKey,\n\t\t\theaders,\n\t\t\tsignal,\n\t\t\tthinkingLevel,\n\t\t\tcriticalParameters,\n\t\t\t{\n\t\t\t\tpromptSuffix: CONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\t\t\t\tacceptanceTokenBudget: ladder.criticalEvictionTokenBudget,\n\t\t\t},\n\t\t);\n\t\tif (targetMetAcceptedForLadder(criticalRun, parameters, ladder)) return criticalRun.validatedResult;\n\t\tif (feasibleAccepted(criticalRun.validatedResult, ladder.criticalEvictionTokenBudget)) return criticalRun.validatedResult;\n\t\tattempts.push({ ...criticalRun });\n\t} catch (error) {\n\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\tif (signal?.aborted || formattedError.message === \"Context compaction failed: Request was aborted\") throw formattedError;\n\t\tattempts.push(runFailedAttempt(formattedError));\n\t}\n\n\ttry {\n\t\treturn runDeterministicContextEviction(transcript, ladder.criticalEvictionTokenBudget);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : formatErrorMessage(error);\n\t\tthrow new Error(`${formatContextCompactionTargetFailureMessage(attempts, parameters)}; ${message}`);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-compaction-runner.js","sourceRoot":"","sources":["../../../src/core/compaction/context-compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAyC,MAAM,+BAA+B,CAAC;AAE7F,OAAO,EAAE,iCAAiC,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAClH,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAOlE,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EACN,oCAAoC,EACpC,4BAA4B,EAC5B,gCAAgC,EAChC,4BAA4B,EAC5B,0BAA0B,EAC1B,kBAAkB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iCAAiC,EAAE,oCAAoC,EAAE,MAAM,kCAAkC,CAAC;AAC3H,OAAO,EACN,mCAAmC,EACnC,wBAAwB,EACxB,6BAA6B,EAC7B,4BAA4B,EAC5B,mCAAmC,GACnC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EACN,4BAA4B,EAC5B,gCAAgC,EAChC,oCAAoC,GACpC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACN,2CAA2C,EAC3C,4BAA4B,EAC5B,kCAAkC,GAClC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AAEnF,MAAM,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MAAM,IAAI,KAAK,CAAC,GAAG,2CAA2C,CAAC,QAAQ,EAAE,UAAU,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;IACrG,CAAC;AACF,CAAC","sourcesContent":["import { Agent, type AgentMessage, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { createAssistantMessageEventStream, isContextOverflow, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { formatCopilotProviderError } from \"../copilot-errors.ts\";\nimport type {\n\tCompactableTranscript,\n\tContextCompactionParameters,\n\tContextCompactionPreparation,\n\tValidatedContextDeletionResult,\n} from \"./context-compaction-types.ts\";\nimport { CONTEXT_COMPACTION_AUTO_QUERY } from \"./context-compaction-types.ts\";\nimport {\n\tcreateContextCompactionBudgetDetails,\n\tcontextCompactionProgressKey,\n\tcontextCompactionProgressPercent,\n\tcontextCompactionTargetLabel,\n\tcontextCompactionTargetMet,\n\tformatErrorMessage,\n} from \"./context-compaction-metrics.ts\";\nimport { getTranscriptCompactionParameters, normalizeContextCompactionParameters } from \"./context-compaction-strategy.ts\";\nimport {\n\tCONTEXT_COMPACTION_BUDGET_TOOL_NAME,\n\tCONTEXT_DELETE_TOOL_NAME,\n\tCONTEXT_GREP_DELETE_TOOL_NAME,\n\tCONTEXT_READ_ENTRY_TOOL_NAME,\n\tCONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME,\n} from \"./context-deletion-tool-definitions.ts\";\nimport { createContextDeletionTool } from \"./context-deletion-tools.ts\";\nimport {\n\tbuildContextCompactionPrompt,\n\tCONTEXT_COMPACTION_SYSTEM_PROMPT,\n\twriteContextCompactionTranscriptFile,\n} from \"./context-compaction-prompt.ts\";\nimport {\n\tCONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\tcriticalCompactionParameters,\n\trelaxTranscriptForCriticalEviction,\n} from \"./context-compaction-critical.ts\";\nimport { runDeterministicContextEviction } from \"./context-compaction-eviction.ts\";\n\nexport const CONTEXT_COMPACTION_MAX_TURNS = 50;\nexport const CONTEXT_COMPACTION_MAX_PLANNER_NUDGES = 50;\n\nexport interface ContextCompactionLadderOptions {\n\tacceptanceTokenBudget?: number;\n\tcriticalEvictionTokenBudget?: number;\n}\n\ninterface ContextDeletionAssistantOptions {\n\tpromptSuffix?: string;\n\tacceptanceTokenBudget?: number;\n}\n\nfunction createContextCompactionTargetNudgeMessage(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n): AgentMessage {\n\tconst currentReductionPercent = contextCompactionProgressPercent(result);\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tconst tokensToDelete = result\n\t\t? createContextCompactionBudgetDetails(result.stats, 0, undefined, parameters, 0, 0).tokensToDeleteForTarget\n\t\t: undefined;\n\tconst remainingText = tokensToDelete !== undefined ? ` Delete about ${tokensToDelete} more token(s) if safe candidates exist.` : \"\";\n\treturn {\n\t\trole: \"user\",\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `The strict ${targetLabel} context-reduction requirement is not met yet; current validated reduction is ${currentReductionPercent}%.${remainingText} Continue removing low-value message entries or message content blocks using ${CONTEXT_DELETE_TOOL_NAME} or ${CONTEXT_GREP_DELETE_TOOL_NAME}. Use the focus query ${JSON.stringify(parameters.query)} to preserve relevant context. Call ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME} to verify progress, and do not provide a final answer until the validated reduction is at least ${targetLabel}.`,\n\t\t\t},\n\t\t],\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionAssistantMessage(\n\tmodel: Model<Api>,\n\tcontent: AssistantMessage[\"content\"],\n\tstopReason: AssistantMessage[\"stopReason\"],\n\terrorMessage?: string,\n): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent,\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason,\n\t\t...(errorMessage !== undefined ? { errorMessage } : {}),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction createContextCompactionStopStream(model: Model<Api>, text: string) {\n\tconst stream = createAssistantMessageEventStream();\n\tqueueMicrotask(() => {\n\t\tconst message = createContextCompactionAssistantMessage(model, [{ type: \"text\", text }], \"stop\");\n\t\tstream.push({ type: \"done\", reason: \"stop\", message });\n\t\tstream.end(message);\n\t});\n\treturn stream;\n}\n\nfunction isContextCompactionOverflowError(model: Model<Api>, errorMessage: string): boolean {\n\treturn isContextOverflow(createContextCompactionAssistantMessage(model, [], \"error\", errorMessage), model.contextWindow);\n}\n\nfunction feasibleAccepted(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\treturn (\n\t\tacceptanceTokenBudget !== undefined &&\n\t\tresult !== undefined &&\n\t\tresult.deletedTargets.length > 0 &&\n\t\tresult.stats.tokensAfter <= acceptanceTokenBudget\n\t);\n}\n\nfunction acceptedWithinRun(\n\tresult: ValidatedContextDeletionResult | undefined,\n\tparameters: ContextCompactionParameters,\n\tacceptanceTokenBudget: number | undefined,\n): result is ValidatedContextDeletionResult {\n\tif (acceptanceTokenBudget !== undefined) return feasibleAccepted(result, acceptanceTokenBudget);\n\treturn contextCompactionTargetMet(result, parameters);\n}\n\nfunction targetMetAcceptedForLadder(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n\tladder: ContextCompactionLadderOptions | undefined,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\tif (!hasMetContextCompactionTarget(run, parameters)) return false;\n\tconst overflowBudget = ladder?.criticalEvictionTokenBudget;\n\treturn overflowBudget === undefined || run.validatedResult.stats.tokensAfter <= overflowBudget;\n}\n\ninterface ContextDeletionRun {\n\tvalidatedResult: ValidatedContextDeletionResult | undefined;\n\tlastToolError: string | undefined;\n\tproviderError: string | undefined;\n\tproviderOverflow: boolean;\n}\n\nasync function runContextDeletionAssistant(\n\tinputTranscript: CompactableTranscript,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tparameters: ContextCompactionParameters = getTranscriptCompactionParameters(inputTranscript),\n\toptions: ContextDeletionAssistantOptions = {},\n): Promise<ContextDeletionRun> {\n\tconst transcript: CompactableTranscript = { ...inputTranscript, parameters };\n\tconst maxTokens = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tconst transcriptFile = writeContextCompactionTranscriptFile(transcript);\n\tconst promptText = buildContextCompactionPrompt(transcript, transcriptFile.path, parameters) + (options.promptSuffix ?? \"\");\n\tconst promptMessage: AgentMessage = {\n\t\trole: \"user\",\n\t\tcontent: [{ type: \"text\", text: promptText }],\n\t\ttimestamp: Date.now(),\n\t};\n\tconst deletionTool = createContextDeletionTool(transcript, { contextWindow: model.contextWindow, ...parameters });\n\tlet providerTurnCount = 0;\n\tconst agent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: CONTEXT_COMPACTION_SYSTEM_PROMPT,\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: deletionTool.tools,\n\t\t},\n\t\ttoolExecution: \"parallel\",\n\t\tstreamFn: async (requestModel, context, streamOptions) => {\n\t\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached an acceptable context-reduction result (${currentResult.stats.percentReduction}%, ${currentResult.stats.tokensAfter} token(s) after deletion); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (providerTurnCount >= CONTEXT_COMPACTION_MAX_TURNS) {\n\t\t\t\treturn createContextCompactionStopStream(\n\t\t\t\t\trequestModel,\n\t\t\t\t\t`Reached the context compaction turn cap (${CONTEXT_COMPACTION_MAX_TURNS}); using the validated deletions recorded so far.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tproviderTurnCount += 1;\n\t\t\treturn streamSimple(requestModel, context, {\n\t\t\t\t...streamOptions,\n\t\t\t\tmaxTokens,\n\t\t\t\tapiKey,\n\t\t\t\theaders: headers ?? streamOptions?.headers,\n\t\t\t});\n\t\t},\n\t});\n\n\tlet lastNudgedProgressKey: string | undefined;\n\tlet nudgeCount = 0;\n\tconst unsubscribeNudge = agent.subscribe((event, eventSignal) => {\n\t\tif (event.type !== \"turn_end\" || signal?.aborted || eventSignal.aborted) return;\n\t\tif (event.message.role !== \"assistant\") return;\n\t\tif (event.message.stopReason === \"error\" || event.message.stopReason === \"aborted\") return;\n\t\tif (event.message.content.some((content) => content.type === \"toolCall\")) return;\n\t\tif (nudgeCount >= CONTEXT_COMPACTION_MAX_PLANNER_NUDGES) return;\n\t\tconst currentResult = deletionTool.getValidatedResult();\n\t\tif (acceptedWithinRun(currentResult, parameters, options.acceptanceTokenBudget)) return;\n\t\tconst progressKey = contextCompactionProgressKey(currentResult);\n\t\tif (progressKey === lastNudgedProgressKey) return;\n\t\tlastNudgedProgressKey = progressKey;\n\t\tnudgeCount += 1;\n\t\tagent.followUp(createContextCompactionTargetNudgeMessage(currentResult, parameters));\n\t});\n\n\tconst abortOnSignal = () => agent.abort();\n\tsignal?.addEventListener(\"abort\", abortOnSignal, { once: true });\n\ttry {\n\t\tawait agent.prompt(promptMessage);\n\t} catch (error) {\n\t\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\t\tconst errorMessage = formatErrorMessage(error);\n\t\tconst formattedErrorMessage = formatCopilotProviderError(model.provider, errorMessage);\n\t\tif (isContextCompactionOverflowError(model, errorMessage)) {\n\t\t\treturn {\n\t\t\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\t\t\tlastToolError: deletionTool.getLastError(),\n\t\t\t\tproviderError: formattedErrorMessage,\n\t\t\t\tproviderOverflow: true,\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Context compaction failed: ${formattedErrorMessage}`);\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", abortOnSignal);\n\t\tunsubscribeNudge();\n\t\ttranscriptFile.cleanup();\n\t}\n\n\tif (signal?.aborted) throw new Error(\"Context compaction failed: Request was aborted\");\n\tif (agent.state.errorMessage) {\n\t\tconst formattedErrorMessage = formatCopilotProviderError(model.provider, agent.state.errorMessage);\n\t\tif (isContextCompactionOverflowError(model, agent.state.errorMessage)) {\n\t\t\treturn {\n\t\t\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\t\t\tlastToolError: deletionTool.getLastError(),\n\t\t\t\tproviderError: formattedErrorMessage === agent.state.errorMessage ? undefined : formattedErrorMessage,\n\t\t\t\tproviderOverflow: true,\n\t\t\t};\n\t\t}\n\t\tthrow new Error(`Context compaction failed: ${formattedErrorMessage}`);\n\t}\n\tif (deletionTool.getCallCount() === 0) {\n\t\tthrow new Error(\n\t\t\t`Context compaction did not call any transcript inspection, budget, or deletion tools (${CONTEXT_SEARCH_TRANSCRIPT_TOOL_NAME}, ${CONTEXT_READ_ENTRY_TOOL_NAME}, ${CONTEXT_COMPACTION_BUDGET_TOOL_NAME}, ${CONTEXT_DELETE_TOOL_NAME}, or ${CONTEXT_GREP_DELETE_TOOL_NAME})`,\n\t\t);\n\t}\n\treturn {\n\t\tvalidatedResult: deletionTool.getValidatedResult(),\n\t\tlastToolError: deletionTool.getLastError(),\n\t\tproviderError: undefined,\n\t\tproviderOverflow: false,\n\t};\n}\n\nfunction hasMetContextCompactionTarget(\n\trun: ContextDeletionRun,\n\tparameters: ContextCompactionParameters,\n): run is ContextDeletionRun & { validatedResult: ValidatedContextDeletionResult } {\n\treturn contextCompactionTargetMet(run.validatedResult, parameters);\n}\n\nfunction formatContextCompactionTargetFailureMessage(\n\tattempts: readonly ContextDeletionRunAttempt[],\n\tparameters: ContextCompactionParameters,\n): string {\n\tconst targetLabel = contextCompactionTargetLabel(parameters);\n\tif (attempts.length === 0) return `Context compaction did not meet the strict ${targetLabel} reduction requirement`;\n\tconst attemptDetails = attempts\n\t\t.map((attempt) => {\n\t\t\tconst reduction = contextCompactionProgressPercent(attempt.validatedResult);\n\t\t\tconst deletionCount = attempt.validatedResult?.deletedTargets.length ?? 0;\n\t\t\tconst tokensAfterText = attempt.validatedResult ? `; tokens after: ${attempt.validatedResult.stats.tokensAfter}` : \"\";\n\t\t\tconst toolErrorText = attempt.lastToolError ? `; last deletion tool error: ${attempt.lastToolError}` : \"\";\n\t\t\tconst providerErrorText = attempt.providerError ? `; provider error: ${attempt.providerError}` : \"\";\n\t\t\treturn `attempt reached ${reduction}% with ${deletionCount} validated deletion target(s)${tokensAfterText}${toolErrorText}${providerErrorText}`;\n\t\t})\n\t\t.join(\"; \");\n\treturn `Context compaction did not meet the strict ${targetLabel} reduction requirement; ${attemptDetails}`;\n}\n\nfunction runFailedAttempt(error: Error): ContextDeletionRunAttempt {\n\treturn { validatedResult: undefined, lastToolError: undefined, providerError: error.message, providerOverflow: false };\n}\n\nfunction shouldRethrowPlannerError(error: Error, signal: AbortSignal | undefined, ladder: ContextCompactionLadderOptions | undefined): boolean {\n\tif (signal?.aborted) return true;\n\tif (error.message === \"Context compaction failed: Request was aborted\") return true;\n\treturn ladder?.criticalEvictionTokenBudget === undefined;\n}\n\ninterface ContextDeletionRunAttempt extends ContextDeletionRun {}\n\nexport async function contextCompact(\n\tpreparation: ContextCompactionPreparation,\n\tmodel: Model<Api>,\n\tapiKey: string,\n\theaders?: Record<string, string>,\n\tsignal?: AbortSignal,\n\tthinkingLevel: ThinkingLevel = \"off\",\n\tladder?: ContextCompactionLadderOptions,\n): Promise<ValidatedContextDeletionResult> {\n\tconst parameters = normalizeContextCompactionParameters(\n\t\tpreparation.parameters ?? preparation.transcript.parameters,\n\t\tpreparation.parameters?.query ?? preparation.transcript.parameters?.query ?? CONTEXT_COMPACTION_AUTO_QUERY,\n\t);\n\tconst transcript: CompactableTranscript = { ...preparation.transcript, parameters };\n\tconst attempts: ContextDeletionRunAttempt[] = [];\n\tlet skipCriticalPlanner = false;\n\ttry {\n\t\tconst standardRun = await runContextDeletionAssistant(transcript, model, apiKey, headers, signal, thinkingLevel, parameters);\n\t\tif (targetMetAcceptedForLadder(standardRun, parameters, ladder)) return standardRun.validatedResult;\n\t\tif (feasibleAccepted(standardRun.validatedResult, ladder?.acceptanceTokenBudget)) return standardRun.validatedResult;\n\t\tskipCriticalPlanner = standardRun.providerOverflow;\n\t\tattempts.push({ ...standardRun });\n\t} catch (error) {\n\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\tif (shouldRethrowPlannerError(formattedError, signal, ladder)) throw formattedError;\n\t\tattempts.push(runFailedAttempt(formattedError));\n\t}\n\n\tif (ladder?.criticalEvictionTokenBudget === undefined) {\n\t\tthrow new Error(formatContextCompactionTargetFailureMessage(attempts, parameters));\n\t}\n\n\tif (!skipCriticalPlanner) {\n\t\ttry {\n\t\t\tconst criticalParameters = criticalCompactionParameters(parameters);\n\t\t\tconst criticalTranscript = relaxTranscriptForCriticalEviction(transcript);\n\t\t\tconst criticalRun = await runContextDeletionAssistant(\n\t\t\t\tcriticalTranscript,\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tsignal,\n\t\t\t\tthinkingLevel,\n\t\t\t\tcriticalParameters,\n\t\t\t\t{\n\t\t\t\t\tpromptSuffix: CONTEXT_COMPACTION_CRITICAL_OVERFLOW_PROMPT,\n\t\t\t\t\tacceptanceTokenBudget: ladder.criticalEvictionTokenBudget,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (targetMetAcceptedForLadder(criticalRun, parameters, ladder)) return criticalRun.validatedResult;\n\t\t\tif (feasibleAccepted(criticalRun.validatedResult, ladder.criticalEvictionTokenBudget)) return criticalRun.validatedResult;\n\t\t\tattempts.push({ ...criticalRun });\n\t\t} catch (error) {\n\t\t\tconst formattedError = error instanceof Error ? error : new Error(formatErrorMessage(error));\n\t\t\tif (signal?.aborted || formattedError.message === \"Context compaction failed: Request was aborted\") throw formattedError;\n\t\t\tattempts.push(runFailedAttempt(formattedError));\n\t\t}\n\t}\n\n\ttry {\n\t\treturn runDeterministicContextEviction(transcript, ladder.criticalEvictionTokenBudget);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : formatErrorMessage(error);\n\t\tthrow new Error(`${formatContextCompactionTargetFailureMessage(attempts, parameters)}; ${message}`);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Narrow repair for GitHub Copilot Anthropic Messages SSE streams that carry a
|
|
3
|
+
* complete Anthropic turn but omit the required terminal `message_stop` event.
|
|
4
|
+
*
|
|
5
|
+
* The wrapper is deliberately conservative: it is only installed for Copilot
|
|
6
|
+
* `/v1/messages` event streams, passes original SSE frames through unchanged,
|
|
7
|
+
* and appends/inserts a single synthetic `message_stop` only after observing the
|
|
8
|
+
* same terminal evidence Anthropic's parser requires for a complete message.
|
|
9
|
+
*/
|
|
10
|
+
export declare const COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT = "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n";
|
|
11
|
+
/**
|
|
12
|
+
* Wrap a Copilot Anthropic Messages SSE byte stream and repair one narrow class
|
|
13
|
+
* of provider truncation: missing `message_stop` after a fully closed message.
|
|
14
|
+
* Original SSE frames are emitted unchanged; the only possible mutation is one
|
|
15
|
+
* synthetic terminal event at clean EOF or immediately before `[DONE]`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createCopilotAnthropicMessagesSseRepairStream(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
|
|
18
|
+
/**
|
|
19
|
+
* Scope the Anthropic SSE repair to GitHub Copilot `/v1/messages` event streams
|
|
20
|
+
* with a body. All other responses are returned as the original instance.
|
|
21
|
+
*/
|
|
22
|
+
export declare function maybeRepairCopilotAnthropicMessagesResponse(url: string | undefined, response: Response): Response;
|
|
23
|
+
//# sourceMappingURL=copilot-anthropic-sse-repair.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-anthropic-sse-repair.d.ts","sourceRoot":"","sources":["../../src/core/copilot-anthropic-sse-repair.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAoBH,eAAO,MAAM,8CAA8C,+DACD,CAAC;AAsP3D;;;;;GAKG;AACH,wBAAgB,6CAA6C,CAC3D,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GACjC,cAAc,CAAC,UAAU,CAAC,CA6D5B;AAgBD;;;GAGG;AACH,wBAAgB,2CAA2C,CACzD,GAAG,EAAE,MAAM,GAAG,SAAS,EACvB,QAAQ,EAAE,QAAQ,GACjB,QAAQ,CAWV","sourcesContent":["/**\n * Narrow repair for GitHub Copilot Anthropic Messages SSE streams that carry a\n * complete Anthropic turn but omit the required terminal `message_stop` event.\n *\n * The wrapper is deliberately conservative: it is only installed for Copilot\n * `/v1/messages` event streams, passes original SSE frames through unchanged,\n * and appends/inserts a single synthetic `message_stop` only after observing the\n * same terminal evidence Anthropic's parser requires for a complete message.\n */\n\nimport { isCopilotApiHost } from \"./copilot-hosts.ts\";\n\ntype JsonObject = { [key: string]: JsonValue };\ntype JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;\n\ntype SseObservation = \"data\" | \"done\" | \"empty\";\n\ninterface RepairState {\n sawMessageStart: boolean;\n sawMessageStop: boolean;\n sawTerminalStopReason: boolean;\n sawErrorEvent: boolean;\n malformedOrUncertain: boolean;\n sawDoneSentinel: boolean;\n insertedSyntheticStop: boolean;\n openContentBlockIndexes: Set<number>;\n}\n\nexport const COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT =\n 'event: message_stop\\ndata: {\"type\":\"message_stop\"}\\n\\n';\n\nconst COPILOT_ANTHROPIC_MESSAGES_PATH = \"/v1/messages\";\nconst KNOWN_ANTHROPIC_SSE_EVENT_NAMES = new Set([\n \"message_start\",\n \"content_block_start\",\n \"content_block_delta\",\n \"content_block_stop\",\n \"message_delta\",\n \"message_stop\",\n \"ping\",\n \"error\",\n]);\n\nfunction createRepairState(): RepairState {\n return {\n sawMessageStart: false,\n sawMessageStop: false,\n sawTerminalStopReason: false,\n sawErrorEvent: false,\n malformedOrUncertain: false,\n sawDoneSentinel: false,\n insertedSyntheticStop: false,\n openContentBlockIndexes: new Set<number>(),\n };\n}\n\nfunction isPlainObject(value: JsonValue): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonNegativeInteger(value: JsonValue | undefined): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\nfunction markMalformed(state: RepairState): void {\n state.malformedOrUncertain = true;\n}\n\nfunction shouldSynthesizeMessageStop(state: RepairState): boolean {\n return (\n state.sawMessageStart &&\n !state.sawMessageStop &&\n state.sawTerminalStopReason &&\n !state.sawErrorEvent &&\n !state.malformedOrUncertain &&\n !state.sawDoneSentinel &&\n !state.insertedSyntheticStop &&\n state.openContentBlockIndexes.size === 0\n );\n}\n\nfunction findSseEventBoundary(buffer: string): number {\n const candidates = [\"\\r\\n\\r\\n\", \"\\n\\n\", \"\\r\\r\"];\n let bestIndex = -1;\n let bestLength = 0;\n for (const candidate of candidates) {\n const index = buffer.indexOf(candidate);\n if (index === -1) continue;\n if (bestIndex === -1 || index < bestIndex) {\n bestIndex = index;\n bestLength = candidate.length;\n }\n }\n return bestIndex === -1 ? -1 : bestIndex + bestLength;\n}\n\nfunction stripEventSeparator(frame: string): string {\n if (frame.endsWith(\"\\r\\n\\r\\n\")) return frame.slice(0, -4);\n if (frame.endsWith(\"\\n\\n\")) return frame.slice(0, -2);\n if (frame.endsWith(\"\\r\\r\")) return frame.slice(0, -2);\n return frame;\n}\n\nfunction missingFinalFrameSeparator(frame: string): string {\n if (frame.endsWith(\"\\r\\n\")) return \"\\r\\n\";\n if (frame.endsWith(\"\\n\")) return \"\\n\";\n if (frame.endsWith(\"\\r\")) return \"\\r\";\n return \"\\n\\n\";\n}\n\nfunction hasKnownAnthropicEventName(eventName: string | undefined): eventName is string {\n return eventName !== undefined && KNOWN_ANTHROPIC_SSE_EVENT_NAMES.has(eventName);\n}\n\nfunction canObserveOpenMessageLifecycle(state: RepairState): boolean {\n if (!state.sawMessageStart || state.sawMessageStop || state.sawTerminalStopReason) {\n markMalformed(state);\n return false;\n }\n return true;\n}\n\nfunction observeContentBlockStart(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const index = payload.index;\n if (!isNonNegativeInteger(index) || state.openContentBlockIndexes.has(index)) {\n markMalformed(state);\n return;\n }\n state.openContentBlockIndexes.add(index);\n}\n\nfunction observeContentBlockDelta(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const index = payload.index;\n if (!isNonNegativeInteger(index) || !state.openContentBlockIndexes.has(index)) {\n markMalformed(state);\n }\n}\n\nfunction observeContentBlockStop(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const index = payload.index;\n if (!isNonNegativeInteger(index) || !state.openContentBlockIndexes.delete(index)) {\n markMalformed(state);\n }\n}\n\nfunction observeMessageDelta(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const delta = payload.delta;\n if (!isPlainObject(delta)) return;\n const stopReason = delta.stop_reason;\n if (typeof stopReason === \"string\" && stopReason.length > 0) {\n state.sawTerminalStopReason = true;\n }\n}\n\nfunction observeAnthropicPayload(eventName: string | undefined, payload: JsonObject, state: RepairState): void {\n if (!hasKnownAnthropicEventName(eventName)) {\n markMalformed(state);\n return;\n }\n\n const type = payload.type;\n if (typeof type !== \"string\" || eventName !== type) {\n markMalformed(state);\n return;\n }\n\n switch (type) {\n case \"message_start\":\n if (state.sawMessageStart || state.sawMessageStop || state.sawTerminalStopReason) markMalformed(state);\n state.sawMessageStart = true;\n break;\n case \"content_block_start\":\n observeContentBlockStart(payload, state);\n break;\n case \"content_block_delta\":\n observeContentBlockDelta(payload, state);\n break;\n case \"content_block_stop\":\n observeContentBlockStop(payload, state);\n break;\n case \"message_delta\":\n observeMessageDelta(payload, state);\n break;\n case \"message_stop\":\n if (!state.sawMessageStart || state.sawMessageStop || state.openContentBlockIndexes.size > 0) {\n markMalformed(state);\n }\n state.sawMessageStop = true;\n break;\n case \"ping\":\n break;\n case \"error\":\n state.sawErrorEvent = true;\n break;\n }\n}\n\nfunction observeSseFrame(frame: string, state: RepairState): SseObservation {\n if (state.sawDoneSentinel) {\n markMalformed(state);\n }\n\n const core = stripEventSeparator(frame);\n if (core.length === 0) return \"empty\";\n\n let eventName: string | undefined;\n const dataLines: string[] = [];\n for (const line of core.split(/\\r\\n|\\n|\\r/)) {\n if (line.length === 0 || line.startsWith(\":\")) continue;\n const separatorIndex = line.indexOf(\":\");\n const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);\n let value = separatorIndex === -1 ? \"\" : line.slice(separatorIndex + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n if (field === \"event\") {\n eventName = value;\n } else if (field === \"data\") {\n dataLines.push(value);\n }\n }\n\n if (dataLines.length === 0) {\n if (eventName === \"error\") state.sawErrorEvent = true;\n return \"empty\";\n }\n\n const dataPayload = dataLines.join(\"\\n\");\n if (dataPayload.trim() === \"[DONE]\") {\n return \"done\";\n }\n\n let parsed: JsonValue;\n try {\n parsed = JSON.parse(dataPayload) as JsonValue;\n } catch {\n markMalformed(state);\n return \"data\";\n }\n\n if (!isPlainObject(parsed)) {\n markMalformed(state);\n return \"data\";\n }\n\n observeAnthropicPayload(eventName, parsed, state);\n return \"data\";\n}\n\nfunction drainCompleteFrames(buffer: string, state: RepairState): { output: string; rest: string } {\n let rest = buffer;\n let output = \"\";\n for (;;) {\n const boundaryEnd = findSseEventBoundary(rest);\n if (boundaryEnd === -1) break;\n\n const frame = rest.slice(0, boundaryEnd);\n rest = rest.slice(boundaryEnd);\n const observation = observeSseFrame(frame, state);\n if (observation === \"done\") {\n if (shouldSynthesizeMessageStop(state)) {\n output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;\n state.insertedSyntheticStop = true;\n state.sawMessageStop = true;\n }\n state.sawDoneSentinel = true;\n }\n output += frame;\n }\n return { output, rest };\n}\n\n/**\n * Wrap a Copilot Anthropic Messages SSE byte stream and repair one narrow class\n * of provider truncation: missing `message_stop` after a fully closed message.\n * Original SSE frames are emitted unchanged; the only possible mutation is one\n * synthetic terminal event at clean EOF or immediately before `[DONE]`.\n */\nexport function createCopilotAnthropicMessagesSseRepairStream(\n source: ReadableStream<Uint8Array>,\n): ReadableStream<Uint8Array> {\n const reader = source.getReader();\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n const state = createRepairState();\n let buffer = \"\";\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n buffer += decoder.decode();\n const drained = drainCompleteFrames(buffer, state);\n buffer = drained.rest;\n let output = drained.output;\n\n if (buffer.length > 0) {\n const trailingFrame = buffer;\n const observation = observeSseFrame(trailingFrame, state);\n buffer = \"\";\n if (observation === \"done\") {\n if (shouldSynthesizeMessageStop(state)) {\n output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;\n state.insertedSyntheticStop = true;\n state.sawMessageStop = true;\n }\n state.sawDoneSentinel = true;\n }\n output += trailingFrame;\n if (observation === \"data\" && shouldSynthesizeMessageStop(state)) {\n output += missingFinalFrameSeparator(trailingFrame);\n }\n }\n\n if (shouldSynthesizeMessageStop(state)) {\n output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;\n state.insertedSyntheticStop = true;\n state.sawMessageStop = true;\n }\n\n if (output.length > 0) {\n controller.enqueue(encoder.encode(output));\n }\n controller.close();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const drained = drainCompleteFrames(buffer, state);\n buffer = drained.rest;\n if (drained.output.length > 0) {\n controller.enqueue(encoder.encode(drained.output));\n return;\n }\n }\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n}\n\nfunction isCopilotAnthropicMessagesUrl(url: string | undefined): boolean {\n if (!url) return false;\n try {\n const parsed = new URL(url);\n return isCopilotApiHost(parsed) && parsed.pathname === COPILOT_ANTHROPIC_MESSAGES_PATH;\n } catch {\n return false;\n }\n}\n\nfunction isEventStreamResponse(response: Response): boolean {\n return (response.headers.get(\"content-type\") ?? \"\").toLowerCase().includes(\"text/event-stream\");\n}\n\n/**\n * Scope the Anthropic SSE repair to GitHub Copilot `/v1/messages` event streams\n * with a body. All other responses are returned as the original instance.\n */\nexport function maybeRepairCopilotAnthropicMessagesResponse(\n url: string | undefined,\n response: Response,\n): Response {\n if (!isCopilotAnthropicMessagesUrl(url)) return response;\n if (!isEventStreamResponse(response)) return response;\n if (!response.body) return response;\n\n const transformed = createCopilotAnthropicMessagesSseRepairStream(response.body);\n return new Response(transformed, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n"]}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Narrow repair for GitHub Copilot Anthropic Messages SSE streams that carry a
|
|
3
|
+
* complete Anthropic turn but omit the required terminal `message_stop` event.
|
|
4
|
+
*
|
|
5
|
+
* The wrapper is deliberately conservative: it is only installed for Copilot
|
|
6
|
+
* `/v1/messages` event streams, passes original SSE frames through unchanged,
|
|
7
|
+
* and appends/inserts a single synthetic `message_stop` only after observing the
|
|
8
|
+
* same terminal evidence Anthropic's parser requires for a complete message.
|
|
9
|
+
*/
|
|
10
|
+
import { isCopilotApiHost } from "./copilot-hosts.js";
|
|
11
|
+
export const COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT = 'event: message_stop\ndata: {"type":"message_stop"}\n\n';
|
|
12
|
+
const COPILOT_ANTHROPIC_MESSAGES_PATH = "/v1/messages";
|
|
13
|
+
const KNOWN_ANTHROPIC_SSE_EVENT_NAMES = new Set([
|
|
14
|
+
"message_start",
|
|
15
|
+
"content_block_start",
|
|
16
|
+
"content_block_delta",
|
|
17
|
+
"content_block_stop",
|
|
18
|
+
"message_delta",
|
|
19
|
+
"message_stop",
|
|
20
|
+
"ping",
|
|
21
|
+
"error",
|
|
22
|
+
]);
|
|
23
|
+
function createRepairState() {
|
|
24
|
+
return {
|
|
25
|
+
sawMessageStart: false,
|
|
26
|
+
sawMessageStop: false,
|
|
27
|
+
sawTerminalStopReason: false,
|
|
28
|
+
sawErrorEvent: false,
|
|
29
|
+
malformedOrUncertain: false,
|
|
30
|
+
sawDoneSentinel: false,
|
|
31
|
+
insertedSyntheticStop: false,
|
|
32
|
+
openContentBlockIndexes: new Set(),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function isPlainObject(value) {
|
|
36
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
37
|
+
}
|
|
38
|
+
function isNonNegativeInteger(value) {
|
|
39
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
40
|
+
}
|
|
41
|
+
function markMalformed(state) {
|
|
42
|
+
state.malformedOrUncertain = true;
|
|
43
|
+
}
|
|
44
|
+
function shouldSynthesizeMessageStop(state) {
|
|
45
|
+
return (state.sawMessageStart &&
|
|
46
|
+
!state.sawMessageStop &&
|
|
47
|
+
state.sawTerminalStopReason &&
|
|
48
|
+
!state.sawErrorEvent &&
|
|
49
|
+
!state.malformedOrUncertain &&
|
|
50
|
+
!state.sawDoneSentinel &&
|
|
51
|
+
!state.insertedSyntheticStop &&
|
|
52
|
+
state.openContentBlockIndexes.size === 0);
|
|
53
|
+
}
|
|
54
|
+
function findSseEventBoundary(buffer) {
|
|
55
|
+
const candidates = ["\r\n\r\n", "\n\n", "\r\r"];
|
|
56
|
+
let bestIndex = -1;
|
|
57
|
+
let bestLength = 0;
|
|
58
|
+
for (const candidate of candidates) {
|
|
59
|
+
const index = buffer.indexOf(candidate);
|
|
60
|
+
if (index === -1)
|
|
61
|
+
continue;
|
|
62
|
+
if (bestIndex === -1 || index < bestIndex) {
|
|
63
|
+
bestIndex = index;
|
|
64
|
+
bestLength = candidate.length;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return bestIndex === -1 ? -1 : bestIndex + bestLength;
|
|
68
|
+
}
|
|
69
|
+
function stripEventSeparator(frame) {
|
|
70
|
+
if (frame.endsWith("\r\n\r\n"))
|
|
71
|
+
return frame.slice(0, -4);
|
|
72
|
+
if (frame.endsWith("\n\n"))
|
|
73
|
+
return frame.slice(0, -2);
|
|
74
|
+
if (frame.endsWith("\r\r"))
|
|
75
|
+
return frame.slice(0, -2);
|
|
76
|
+
return frame;
|
|
77
|
+
}
|
|
78
|
+
function missingFinalFrameSeparator(frame) {
|
|
79
|
+
if (frame.endsWith("\r\n"))
|
|
80
|
+
return "\r\n";
|
|
81
|
+
if (frame.endsWith("\n"))
|
|
82
|
+
return "\n";
|
|
83
|
+
if (frame.endsWith("\r"))
|
|
84
|
+
return "\r";
|
|
85
|
+
return "\n\n";
|
|
86
|
+
}
|
|
87
|
+
function hasKnownAnthropicEventName(eventName) {
|
|
88
|
+
return eventName !== undefined && KNOWN_ANTHROPIC_SSE_EVENT_NAMES.has(eventName);
|
|
89
|
+
}
|
|
90
|
+
function canObserveOpenMessageLifecycle(state) {
|
|
91
|
+
if (!state.sawMessageStart || state.sawMessageStop || state.sawTerminalStopReason) {
|
|
92
|
+
markMalformed(state);
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
function observeContentBlockStart(payload, state) {
|
|
98
|
+
if (!canObserveOpenMessageLifecycle(state))
|
|
99
|
+
return;
|
|
100
|
+
const index = payload.index;
|
|
101
|
+
if (!isNonNegativeInteger(index) || state.openContentBlockIndexes.has(index)) {
|
|
102
|
+
markMalformed(state);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
state.openContentBlockIndexes.add(index);
|
|
106
|
+
}
|
|
107
|
+
function observeContentBlockDelta(payload, state) {
|
|
108
|
+
if (!canObserveOpenMessageLifecycle(state))
|
|
109
|
+
return;
|
|
110
|
+
const index = payload.index;
|
|
111
|
+
if (!isNonNegativeInteger(index) || !state.openContentBlockIndexes.has(index)) {
|
|
112
|
+
markMalformed(state);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function observeContentBlockStop(payload, state) {
|
|
116
|
+
if (!canObserveOpenMessageLifecycle(state))
|
|
117
|
+
return;
|
|
118
|
+
const index = payload.index;
|
|
119
|
+
if (!isNonNegativeInteger(index) || !state.openContentBlockIndexes.delete(index)) {
|
|
120
|
+
markMalformed(state);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function observeMessageDelta(payload, state) {
|
|
124
|
+
if (!canObserveOpenMessageLifecycle(state))
|
|
125
|
+
return;
|
|
126
|
+
const delta = payload.delta;
|
|
127
|
+
if (!isPlainObject(delta))
|
|
128
|
+
return;
|
|
129
|
+
const stopReason = delta.stop_reason;
|
|
130
|
+
if (typeof stopReason === "string" && stopReason.length > 0) {
|
|
131
|
+
state.sawTerminalStopReason = true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function observeAnthropicPayload(eventName, payload, state) {
|
|
135
|
+
if (!hasKnownAnthropicEventName(eventName)) {
|
|
136
|
+
markMalformed(state);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const type = payload.type;
|
|
140
|
+
if (typeof type !== "string" || eventName !== type) {
|
|
141
|
+
markMalformed(state);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
switch (type) {
|
|
145
|
+
case "message_start":
|
|
146
|
+
if (state.sawMessageStart || state.sawMessageStop || state.sawTerminalStopReason)
|
|
147
|
+
markMalformed(state);
|
|
148
|
+
state.sawMessageStart = true;
|
|
149
|
+
break;
|
|
150
|
+
case "content_block_start":
|
|
151
|
+
observeContentBlockStart(payload, state);
|
|
152
|
+
break;
|
|
153
|
+
case "content_block_delta":
|
|
154
|
+
observeContentBlockDelta(payload, state);
|
|
155
|
+
break;
|
|
156
|
+
case "content_block_stop":
|
|
157
|
+
observeContentBlockStop(payload, state);
|
|
158
|
+
break;
|
|
159
|
+
case "message_delta":
|
|
160
|
+
observeMessageDelta(payload, state);
|
|
161
|
+
break;
|
|
162
|
+
case "message_stop":
|
|
163
|
+
if (!state.sawMessageStart || state.sawMessageStop || state.openContentBlockIndexes.size > 0) {
|
|
164
|
+
markMalformed(state);
|
|
165
|
+
}
|
|
166
|
+
state.sawMessageStop = true;
|
|
167
|
+
break;
|
|
168
|
+
case "ping":
|
|
169
|
+
break;
|
|
170
|
+
case "error":
|
|
171
|
+
state.sawErrorEvent = true;
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function observeSseFrame(frame, state) {
|
|
176
|
+
if (state.sawDoneSentinel) {
|
|
177
|
+
markMalformed(state);
|
|
178
|
+
}
|
|
179
|
+
const core = stripEventSeparator(frame);
|
|
180
|
+
if (core.length === 0)
|
|
181
|
+
return "empty";
|
|
182
|
+
let eventName;
|
|
183
|
+
const dataLines = [];
|
|
184
|
+
for (const line of core.split(/\r\n|\n|\r/)) {
|
|
185
|
+
if (line.length === 0 || line.startsWith(":"))
|
|
186
|
+
continue;
|
|
187
|
+
const separatorIndex = line.indexOf(":");
|
|
188
|
+
const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);
|
|
189
|
+
let value = separatorIndex === -1 ? "" : line.slice(separatorIndex + 1);
|
|
190
|
+
if (value.startsWith(" "))
|
|
191
|
+
value = value.slice(1);
|
|
192
|
+
if (field === "event") {
|
|
193
|
+
eventName = value;
|
|
194
|
+
}
|
|
195
|
+
else if (field === "data") {
|
|
196
|
+
dataLines.push(value);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (dataLines.length === 0) {
|
|
200
|
+
if (eventName === "error")
|
|
201
|
+
state.sawErrorEvent = true;
|
|
202
|
+
return "empty";
|
|
203
|
+
}
|
|
204
|
+
const dataPayload = dataLines.join("\n");
|
|
205
|
+
if (dataPayload.trim() === "[DONE]") {
|
|
206
|
+
return "done";
|
|
207
|
+
}
|
|
208
|
+
let parsed;
|
|
209
|
+
try {
|
|
210
|
+
parsed = JSON.parse(dataPayload);
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
markMalformed(state);
|
|
214
|
+
return "data";
|
|
215
|
+
}
|
|
216
|
+
if (!isPlainObject(parsed)) {
|
|
217
|
+
markMalformed(state);
|
|
218
|
+
return "data";
|
|
219
|
+
}
|
|
220
|
+
observeAnthropicPayload(eventName, parsed, state);
|
|
221
|
+
return "data";
|
|
222
|
+
}
|
|
223
|
+
function drainCompleteFrames(buffer, state) {
|
|
224
|
+
let rest = buffer;
|
|
225
|
+
let output = "";
|
|
226
|
+
for (;;) {
|
|
227
|
+
const boundaryEnd = findSseEventBoundary(rest);
|
|
228
|
+
if (boundaryEnd === -1)
|
|
229
|
+
break;
|
|
230
|
+
const frame = rest.slice(0, boundaryEnd);
|
|
231
|
+
rest = rest.slice(boundaryEnd);
|
|
232
|
+
const observation = observeSseFrame(frame, state);
|
|
233
|
+
if (observation === "done") {
|
|
234
|
+
if (shouldSynthesizeMessageStop(state)) {
|
|
235
|
+
output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;
|
|
236
|
+
state.insertedSyntheticStop = true;
|
|
237
|
+
state.sawMessageStop = true;
|
|
238
|
+
}
|
|
239
|
+
state.sawDoneSentinel = true;
|
|
240
|
+
}
|
|
241
|
+
output += frame;
|
|
242
|
+
}
|
|
243
|
+
return { output, rest };
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Wrap a Copilot Anthropic Messages SSE byte stream and repair one narrow class
|
|
247
|
+
* of provider truncation: missing `message_stop` after a fully closed message.
|
|
248
|
+
* Original SSE frames are emitted unchanged; the only possible mutation is one
|
|
249
|
+
* synthetic terminal event at clean EOF or immediately before `[DONE]`.
|
|
250
|
+
*/
|
|
251
|
+
export function createCopilotAnthropicMessagesSseRepairStream(source) {
|
|
252
|
+
const reader = source.getReader();
|
|
253
|
+
const decoder = new TextDecoder();
|
|
254
|
+
const encoder = new TextEncoder();
|
|
255
|
+
const state = createRepairState();
|
|
256
|
+
let buffer = "";
|
|
257
|
+
return new ReadableStream({
|
|
258
|
+
async pull(controller) {
|
|
259
|
+
for (;;) {
|
|
260
|
+
const { done, value } = await reader.read();
|
|
261
|
+
if (done) {
|
|
262
|
+
buffer += decoder.decode();
|
|
263
|
+
const drained = drainCompleteFrames(buffer, state);
|
|
264
|
+
buffer = drained.rest;
|
|
265
|
+
let output = drained.output;
|
|
266
|
+
if (buffer.length > 0) {
|
|
267
|
+
const trailingFrame = buffer;
|
|
268
|
+
const observation = observeSseFrame(trailingFrame, state);
|
|
269
|
+
buffer = "";
|
|
270
|
+
if (observation === "done") {
|
|
271
|
+
if (shouldSynthesizeMessageStop(state)) {
|
|
272
|
+
output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;
|
|
273
|
+
state.insertedSyntheticStop = true;
|
|
274
|
+
state.sawMessageStop = true;
|
|
275
|
+
}
|
|
276
|
+
state.sawDoneSentinel = true;
|
|
277
|
+
}
|
|
278
|
+
output += trailingFrame;
|
|
279
|
+
if (observation === "data" && shouldSynthesizeMessageStop(state)) {
|
|
280
|
+
output += missingFinalFrameSeparator(trailingFrame);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (shouldSynthesizeMessageStop(state)) {
|
|
284
|
+
output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;
|
|
285
|
+
state.insertedSyntheticStop = true;
|
|
286
|
+
state.sawMessageStop = true;
|
|
287
|
+
}
|
|
288
|
+
if (output.length > 0) {
|
|
289
|
+
controller.enqueue(encoder.encode(output));
|
|
290
|
+
}
|
|
291
|
+
controller.close();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
buffer += decoder.decode(value, { stream: true });
|
|
295
|
+
const drained = drainCompleteFrames(buffer, state);
|
|
296
|
+
buffer = drained.rest;
|
|
297
|
+
if (drained.output.length > 0) {
|
|
298
|
+
controller.enqueue(encoder.encode(drained.output));
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
cancel(reason) {
|
|
304
|
+
return reader.cancel(reason);
|
|
305
|
+
},
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
function isCopilotAnthropicMessagesUrl(url) {
|
|
309
|
+
if (!url)
|
|
310
|
+
return false;
|
|
311
|
+
try {
|
|
312
|
+
const parsed = new URL(url);
|
|
313
|
+
return isCopilotApiHost(parsed) && parsed.pathname === COPILOT_ANTHROPIC_MESSAGES_PATH;
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
function isEventStreamResponse(response) {
|
|
320
|
+
return (response.headers.get("content-type") ?? "").toLowerCase().includes("text/event-stream");
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Scope the Anthropic SSE repair to GitHub Copilot `/v1/messages` event streams
|
|
324
|
+
* with a body. All other responses are returned as the original instance.
|
|
325
|
+
*/
|
|
326
|
+
export function maybeRepairCopilotAnthropicMessagesResponse(url, response) {
|
|
327
|
+
if (!isCopilotAnthropicMessagesUrl(url))
|
|
328
|
+
return response;
|
|
329
|
+
if (!isEventStreamResponse(response))
|
|
330
|
+
return response;
|
|
331
|
+
if (!response.body)
|
|
332
|
+
return response;
|
|
333
|
+
const transformed = createCopilotAnthropicMessagesSseRepairStream(response.body);
|
|
334
|
+
return new Response(transformed, {
|
|
335
|
+
status: response.status,
|
|
336
|
+
statusText: response.statusText,
|
|
337
|
+
headers: response.headers,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
//# sourceMappingURL=copilot-anthropic-sse-repair.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-anthropic-sse-repair.js","sourceRoot":"","sources":["../../src/core/copilot-anthropic-sse-repair.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAkBtD,MAAM,CAAC,MAAM,8CAA8C,GACzD,wDAAwD,CAAC;AAE3D,MAAM,+BAA+B,GAAG,cAAc,CAAC;AACvD,MAAM,+BAA+B,GAAG,IAAI,GAAG,CAAC;IAC9C,eAAe;IACf,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;IACpB,eAAe;IACf,cAAc;IACd,MAAM;IACN,OAAO;CACR,CAAC,CAAC;AAEH,SAAS,iBAAiB;IACxB,OAAO;QACL,eAAe,EAAE,KAAK;QACtB,cAAc,EAAE,KAAK;QACrB,qBAAqB,EAAE,KAAK;QAC5B,aAAa,EAAE,KAAK;QACpB,oBAAoB,EAAE,KAAK;QAC3B,eAAe,EAAE,KAAK;QACtB,qBAAqB,EAAE,KAAK;QAC5B,uBAAuB,EAAE,IAAI,GAAG,EAAU;KAC3C,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CAAC,KAAgB;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,oBAAoB,CAAC,KAA4B;IACxD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK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AM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC/B,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,SAAS,6BAA6B,CAAC,GAAuB;IAC5D,IAAI,CAAC,GAAG;QAAE,OAAO,KAAK,CAAC;IACvB,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QAC5B,OAAO,gBAAgB,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,QAAQ,KAAK,+BAA+B,CAAC;IACzF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB,CAAC,QAAkB;IAC/C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAC;AAClG,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,2CAA2C,CACzD,GAAuB,EACvB,QAAkB;IAElB,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC;QAAE,OAAO,QAAQ,CAAC;IACzD,IAAI,CAAC,qBAAqB,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC;IACtD,IAAI,CAAC,QAAQ,CAAC,IAAI;QAAE,OAAO,QAAQ,CAAC;IAEpC,MAAM,WAAW,GAAG,6CAA6C,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACjF,OAAO,IAAI,QAAQ,CAAC,WAAW,EAAE;QAC/B,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,OAAO,EAAE,QAAQ,CAAC,OAAO;KAC1B,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Narrow repair for GitHub Copilot Anthropic Messages SSE streams that carry a\n * complete Anthropic turn but omit the required terminal `message_stop` event.\n *\n * The wrapper is deliberately conservative: it is only installed for Copilot\n * `/v1/messages` event streams, passes original SSE frames through unchanged,\n * and appends/inserts a single synthetic `message_stop` only after observing the\n * same terminal evidence Anthropic's parser requires for a complete message.\n */\n\nimport { isCopilotApiHost } from \"./copilot-hosts.ts\";\n\ntype JsonObject = { [key: string]: JsonValue };\ntype JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;\n\ntype SseObservation = \"data\" | \"done\" | \"empty\";\n\ninterface RepairState {\n sawMessageStart: boolean;\n sawMessageStop: boolean;\n sawTerminalStopReason: boolean;\n sawErrorEvent: boolean;\n malformedOrUncertain: boolean;\n sawDoneSentinel: boolean;\n insertedSyntheticStop: boolean;\n openContentBlockIndexes: Set<number>;\n}\n\nexport const COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT =\n 'event: message_stop\\ndata: {\"type\":\"message_stop\"}\\n\\n';\n\nconst COPILOT_ANTHROPIC_MESSAGES_PATH = \"/v1/messages\";\nconst KNOWN_ANTHROPIC_SSE_EVENT_NAMES = new Set([\n \"message_start\",\n \"content_block_start\",\n \"content_block_delta\",\n \"content_block_stop\",\n \"message_delta\",\n \"message_stop\",\n \"ping\",\n \"error\",\n]);\n\nfunction createRepairState(): RepairState {\n return {\n sawMessageStart: false,\n sawMessageStop: false,\n sawTerminalStopReason: false,\n sawErrorEvent: false,\n malformedOrUncertain: false,\n sawDoneSentinel: false,\n insertedSyntheticStop: false,\n openContentBlockIndexes: new Set<number>(),\n };\n}\n\nfunction isPlainObject(value: JsonValue): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonNegativeInteger(value: JsonValue | undefined): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n}\n\nfunction markMalformed(state: RepairState): void {\n state.malformedOrUncertain = true;\n}\n\nfunction shouldSynthesizeMessageStop(state: RepairState): boolean {\n return (\n state.sawMessageStart &&\n !state.sawMessageStop &&\n state.sawTerminalStopReason &&\n !state.sawErrorEvent &&\n !state.malformedOrUncertain &&\n !state.sawDoneSentinel &&\n !state.insertedSyntheticStop &&\n state.openContentBlockIndexes.size === 0\n );\n}\n\nfunction findSseEventBoundary(buffer: string): number {\n const candidates = [\"\\r\\n\\r\\n\", \"\\n\\n\", \"\\r\\r\"];\n let bestIndex = -1;\n let bestLength = 0;\n for (const candidate of candidates) {\n const index = buffer.indexOf(candidate);\n if (index === -1) continue;\n if (bestIndex === -1 || index < bestIndex) {\n bestIndex = index;\n bestLength = candidate.length;\n }\n }\n return bestIndex === -1 ? -1 : bestIndex + bestLength;\n}\n\nfunction stripEventSeparator(frame: string): string {\n if (frame.endsWith(\"\\r\\n\\r\\n\")) return frame.slice(0, -4);\n if (frame.endsWith(\"\\n\\n\")) return frame.slice(0, -2);\n if (frame.endsWith(\"\\r\\r\")) return frame.slice(0, -2);\n return frame;\n}\n\nfunction missingFinalFrameSeparator(frame: string): string {\n if (frame.endsWith(\"\\r\\n\")) return \"\\r\\n\";\n if (frame.endsWith(\"\\n\")) return \"\\n\";\n if (frame.endsWith(\"\\r\")) return \"\\r\";\n return \"\\n\\n\";\n}\n\nfunction hasKnownAnthropicEventName(eventName: string | undefined): eventName is string {\n return eventName !== undefined && KNOWN_ANTHROPIC_SSE_EVENT_NAMES.has(eventName);\n}\n\nfunction canObserveOpenMessageLifecycle(state: RepairState): boolean {\n if (!state.sawMessageStart || state.sawMessageStop || state.sawTerminalStopReason) {\n markMalformed(state);\n return false;\n }\n return true;\n}\n\nfunction observeContentBlockStart(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const index = payload.index;\n if (!isNonNegativeInteger(index) || state.openContentBlockIndexes.has(index)) {\n markMalformed(state);\n return;\n }\n state.openContentBlockIndexes.add(index);\n}\n\nfunction observeContentBlockDelta(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const index = payload.index;\n if (!isNonNegativeInteger(index) || !state.openContentBlockIndexes.has(index)) {\n markMalformed(state);\n }\n}\n\nfunction observeContentBlockStop(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const index = payload.index;\n if (!isNonNegativeInteger(index) || !state.openContentBlockIndexes.delete(index)) {\n markMalformed(state);\n }\n}\n\nfunction observeMessageDelta(payload: JsonObject, state: RepairState): void {\n if (!canObserveOpenMessageLifecycle(state)) return;\n const delta = payload.delta;\n if (!isPlainObject(delta)) return;\n const stopReason = delta.stop_reason;\n if (typeof stopReason === \"string\" && stopReason.length > 0) {\n state.sawTerminalStopReason = true;\n }\n}\n\nfunction observeAnthropicPayload(eventName: string | undefined, payload: JsonObject, state: RepairState): void {\n if (!hasKnownAnthropicEventName(eventName)) {\n markMalformed(state);\n return;\n }\n\n const type = payload.type;\n if (typeof type !== \"string\" || eventName !== type) {\n markMalformed(state);\n return;\n }\n\n switch (type) {\n case \"message_start\":\n if (state.sawMessageStart || state.sawMessageStop || state.sawTerminalStopReason) markMalformed(state);\n state.sawMessageStart = true;\n break;\n case \"content_block_start\":\n observeContentBlockStart(payload, state);\n break;\n case \"content_block_delta\":\n observeContentBlockDelta(payload, state);\n break;\n case \"content_block_stop\":\n observeContentBlockStop(payload, state);\n break;\n case \"message_delta\":\n observeMessageDelta(payload, state);\n break;\n case \"message_stop\":\n if (!state.sawMessageStart || state.sawMessageStop || state.openContentBlockIndexes.size > 0) {\n markMalformed(state);\n }\n state.sawMessageStop = true;\n break;\n case \"ping\":\n break;\n case \"error\":\n state.sawErrorEvent = true;\n break;\n }\n}\n\nfunction observeSseFrame(frame: string, state: RepairState): SseObservation {\n if (state.sawDoneSentinel) {\n markMalformed(state);\n }\n\n const core = stripEventSeparator(frame);\n if (core.length === 0) return \"empty\";\n\n let eventName: string | undefined;\n const dataLines: string[] = [];\n for (const line of core.split(/\\r\\n|\\n|\\r/)) {\n if (line.length === 0 || line.startsWith(\":\")) continue;\n const separatorIndex = line.indexOf(\":\");\n const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);\n let value = separatorIndex === -1 ? \"\" : line.slice(separatorIndex + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n if (field === \"event\") {\n eventName = value;\n } else if (field === \"data\") {\n dataLines.push(value);\n }\n }\n\n if (dataLines.length === 0) {\n if (eventName === \"error\") state.sawErrorEvent = true;\n return \"empty\";\n }\n\n const dataPayload = dataLines.join(\"\\n\");\n if (dataPayload.trim() === \"[DONE]\") {\n return \"done\";\n }\n\n let parsed: JsonValue;\n try {\n parsed = JSON.parse(dataPayload) as JsonValue;\n } catch {\n markMalformed(state);\n return \"data\";\n }\n\n if (!isPlainObject(parsed)) {\n markMalformed(state);\n return \"data\";\n }\n\n observeAnthropicPayload(eventName, parsed, state);\n return \"data\";\n}\n\nfunction drainCompleteFrames(buffer: string, state: RepairState): { output: string; rest: string } {\n let rest = buffer;\n let output = \"\";\n for (;;) {\n const boundaryEnd = findSseEventBoundary(rest);\n if (boundaryEnd === -1) break;\n\n const frame = rest.slice(0, boundaryEnd);\n rest = rest.slice(boundaryEnd);\n const observation = observeSseFrame(frame, state);\n if (observation === \"done\") {\n if (shouldSynthesizeMessageStop(state)) {\n output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;\n state.insertedSyntheticStop = true;\n state.sawMessageStop = true;\n }\n state.sawDoneSentinel = true;\n }\n output += frame;\n }\n return { output, rest };\n}\n\n/**\n * Wrap a Copilot Anthropic Messages SSE byte stream and repair one narrow class\n * of provider truncation: missing `message_stop` after a fully closed message.\n * Original SSE frames are emitted unchanged; the only possible mutation is one\n * synthetic terminal event at clean EOF or immediately before `[DONE]`.\n */\nexport function createCopilotAnthropicMessagesSseRepairStream(\n source: ReadableStream<Uint8Array>,\n): ReadableStream<Uint8Array> {\n const reader = source.getReader();\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n const state = createRepairState();\n let buffer = \"\";\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n buffer += decoder.decode();\n const drained = drainCompleteFrames(buffer, state);\n buffer = drained.rest;\n let output = drained.output;\n\n if (buffer.length > 0) {\n const trailingFrame = buffer;\n const observation = observeSseFrame(trailingFrame, state);\n buffer = \"\";\n if (observation === \"done\") {\n if (shouldSynthesizeMessageStop(state)) {\n output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;\n state.insertedSyntheticStop = true;\n state.sawMessageStop = true;\n }\n state.sawDoneSentinel = true;\n }\n output += trailingFrame;\n if (observation === \"data\" && shouldSynthesizeMessageStop(state)) {\n output += missingFinalFrameSeparator(trailingFrame);\n }\n }\n\n if (shouldSynthesizeMessageStop(state)) {\n output += COPILOT_ANTHROPIC_SYNTHETIC_MESSAGE_STOP_EVENT;\n state.insertedSyntheticStop = true;\n state.sawMessageStop = true;\n }\n\n if (output.length > 0) {\n controller.enqueue(encoder.encode(output));\n }\n controller.close();\n return;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const drained = drainCompleteFrames(buffer, state);\n buffer = drained.rest;\n if (drained.output.length > 0) {\n controller.enqueue(encoder.encode(drained.output));\n return;\n }\n }\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n}\n\nfunction isCopilotAnthropicMessagesUrl(url: string | undefined): boolean {\n if (!url) return false;\n try {\n const parsed = new URL(url);\n return isCopilotApiHost(parsed) && parsed.pathname === COPILOT_ANTHROPIC_MESSAGES_PATH;\n } catch {\n return false;\n }\n}\n\nfunction isEventStreamResponse(response: Response): boolean {\n return (response.headers.get(\"content-type\") ?? \"\").toLowerCase().includes(\"text/event-stream\");\n}\n\n/**\n * Scope the Anthropic SSE repair to GitHub Copilot `/v1/messages` event streams\n * with a body. All other responses are returned as the original instance.\n */\nexport function maybeRepairCopilotAnthropicMessagesResponse(\n url: string | undefined,\n response: Response,\n): Response {\n if (!isCopilotAnthropicMessagesUrl(url)) return response;\n if (!isEventStreamResponse(response)) return response;\n if (!response.body) return response;\n\n const transformed = createCopilotAnthropicMessagesSseRepairStream(response.body);\n return new Response(transformed, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n"]}
|
|
@@ -103,16 +103,24 @@ export declare function restoreCopilotGeminiReasoningOpaque(payload: unknown, mo
|
|
|
103
103
|
*/
|
|
104
104
|
export declare function maybeRewriteCopilotGeminiResponse(url: string | undefined, response: Response): Response;
|
|
105
105
|
/**
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
106
|
+
* Apply Copilot response-body transforms before pi-ai parses streamed provider
|
|
107
|
+
* output. Anthropic Messages repair gets first refusal for `/v1/messages`
|
|
108
|
+
* streams; other Copilot event streams keep the existing Gemini reasoning bridge.
|
|
109
|
+
*/
|
|
110
|
+
export declare function maybeRewriteCopilotProviderResponse(url: string | undefined, response: Response): Response;
|
|
111
|
+
/**
|
|
112
|
+
* Install a `globalThis.fetch` wrapper that applies Copilot-only stream
|
|
113
|
+
* compatibility shims before pi-ai parses provider output. Currently this
|
|
114
|
+
* includes the Gemini `reasoning_opaque` bridge and the Anthropic Messages
|
|
115
|
+
* terminal `message_stop` repair. Idempotent.
|
|
109
116
|
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
* keeping the blast radius to streaming CAPI Gemini turns only.
|
|
117
|
+
* SDK clients resolve `globalThis.fetch` at client-construction time, and a new
|
|
118
|
+
* client is built per request, so wrapping the global before the first request
|
|
119
|
+
* is reliably picked up. Non-Copilot hosts and non-event-stream responses are
|
|
120
|
+
* returned untouched by the underlying shims.
|
|
115
121
|
*/
|
|
122
|
+
export declare function installCopilotResponseInterceptor(): void;
|
|
123
|
+
/** Backward-compatible name for the original Gemini-only interceptor export. */
|
|
116
124
|
export declare function installCopilotGeminiReasoningInterceptor(): void;
|
|
117
125
|
export {};
|
|
118
126
|
//# sourceMappingURL=copilot-gemini-reasoning.d.ts.map
|