carthagent 0.0.0-stage → 1.0.7
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/LICENSE +21 -0
- package/README.md +219 -2
- package/bin/ctg.mjs +736 -0
- package/docs/budgets.md +72 -0
- package/docs/compaction.md +34 -0
- package/docs/context-efficiency-plan.md +24 -0
- package/docs/context-efficiency-review.md +27 -0
- package/docs/context-efficiency.md +49 -0
- package/docs/deepseek-jev-benchmark-plan.md +70 -0
- package/docs/deepseek-jev-benchmark-repair-plan.md +20 -0
- package/docs/deepseek-jev-benchmark-restart.md +9 -0
- package/docs/deepseek-jev-benchmark-results.md +77 -0
- package/docs/deepseek-jev-benchmark-running.md +60 -0
- package/docs/deepseek-jev-benchmark-v3-results.md +41 -0
- package/docs/deepseek-jev-benchmark-v4-protocol.md +15 -0
- package/docs/deepseek-jev-benchmark-v4-results.md +119 -0
- package/docs/deepseek-jev-http400-diagnosis.md +45 -0
- package/docs/delivery-review-evidence.md +53 -0
- package/docs/delivery-timeout-repair-plan.md +51 -0
- package/docs/evaluation-readiness.md +31 -0
- package/docs/evaluation.md +70 -0
- package/docs/extending.md +354 -0
- package/docs/glm-pilot-execution.md +9 -0
- package/docs/glm-pilot-plan.md +15 -0
- package/docs/glm-pilot-results.md +71 -0
- package/docs/graph-context-optimization.md +15 -0
- package/docs/jev-repository-pilot-plan.md +25 -0
- package/docs/jev-repository-pilot-protocol.md +39 -0
- package/docs/jev-repository-pilot-restart.md +7 -0
- package/docs/jev-repository-pilot-results.md +79 -0
- package/docs/jev.md +32 -0
- package/docs/model-registry.md +25 -0
- package/docs/native-compatibility.md +117 -0
- package/docs/opencode-archive.md +9 -0
- package/docs/opencode-migration.md +115 -0
- package/docs/opencode-runtime.md +94 -0
- package/docs/opencode-workspace.md +31 -0
- package/docs/owned-runtime-workflow-registration.md +17 -0
- package/docs/plan-advisor-evaluation.md +38 -0
- package/docs/planning-startup-fix-plan.md +23 -0
- package/docs/planning-startup-fix-review.md +24 -0
- package/docs/planning.md +118 -0
- package/docs/production-merge-review.md +23 -0
- package/docs/quality.md +35 -0
- package/docs/repository-benchmark-design.md +111 -0
- package/docs/review-assurance.md +9 -0
- package/docs/review-experiment-results.md +59 -0
- package/docs/tested-planning-roadmap.md +58 -0
- package/docs/tested-planning.md +58 -0
- package/docs/tui-pickers.md +9 -0
- package/docs/webdriver.md +83 -0
- package/docs/workflow-modes.md +26 -0
- package/docs/workflow.d2 +17 -0
- package/docs/workflow.svg +149 -0
- package/docs/workspace-coordination.md +9 -0
- package/evaluate.mjs +249 -0
- package/extensions/codegraph.ts +36 -0
- package/extensions/delivery.ts +819 -0
- package/extensions/experiential.ts +21 -0
- package/extensions/subscriptions.ts +21 -0
- package/guidance/profiles/authenticated-web.json +24 -0
- package/guidance/profiles/data-visualization.json +25 -0
- package/guidance/profiles/database-change.json +24 -0
- package/guidance/profiles/external-api.json +24 -0
- package/guidance/profiles/transactional-data.json +25 -0
- package/guidance/profiles/web-application.json +26 -0
- package/lib/acceptance-review.mjs +4 -0
- package/lib/browser-bin.mjs +160 -0
- package/lib/browser-errors.mjs +54 -0
- package/lib/browser.mjs +219 -0
- package/lib/budget.mjs +37 -0
- package/lib/cdp.mjs +221 -0
- package/lib/cloud/client.mjs +275 -0
- package/lib/cloud/control-plane.mjs +350 -0
- package/lib/cloud/gateway.mjs +380 -0
- package/lib/cloud/http.mjs +135 -0
- package/lib/cloud/ledger.mjs +215 -0
- package/lib/codegraph-query.mjs +60 -0
- package/lib/codegraph.mjs +378 -0
- package/lib/context-archive.mjs +18 -0
- package/lib/delivery-context.mjs +132 -0
- package/lib/delivery-guidance.mjs +9 -0
- package/lib/delivery-review.mjs +94 -0
- package/lib/delivery.mjs +610 -0
- package/lib/engine.mjs +137 -0
- package/lib/guidance.mjs +71 -0
- package/lib/jev-advisor.mjs +47 -0
- package/lib/opencode/archive.mjs +122 -0
- package/lib/opencode/compatibility.mjs +19 -0
- package/lib/opencode/credentials.mjs +205 -0
- package/lib/opencode/evaluation-budget-plugin/index.ts +147 -0
- package/lib/opencode/evaluation.mjs +242 -0
- package/lib/opencode/file-lock.mjs +86 -0
- package/lib/opencode/headless.mjs +200 -0
- package/lib/opencode/review.mjs +213 -0
- package/lib/opencode/runtime.mjs +246 -0
- package/lib/opencode/service.mjs +249 -0
- package/lib/opencode/session-options.mjs +60 -0
- package/lib/opencode/workspace.mjs +133 -0
- package/lib/openrouter-jev.mjs +37 -0
- package/lib/outcome-contract.mjs +21 -0
- package/lib/plan-advisor.mjs +38 -0
- package/lib/planning-access.mjs +7 -0
- package/lib/planning-advice.mjs +28 -0
- package/lib/planning-discovery.mjs +14 -0
- package/lib/planning-guide.mjs +34 -0
- package/lib/planning-view.mjs +57 -0
- package/lib/planning.mjs +155 -0
- package/lib/probe-diagnostics.mjs +13 -0
- package/lib/providers/experiential.mjs +292 -0
- package/lib/providers/model-catalog.json +700 -0
- package/lib/providers/model-catalog.mjs +7 -0
- package/lib/providers/names.mjs +13 -0
- package/lib/providers/subscription-models.mjs +483 -0
- package/lib/reports.mjs +80 -0
- package/lib/review-state.mjs +49 -0
- package/lib/review.mjs +114 -0
- package/lib/scenarios.mjs +99 -0
- package/lib/ship-auth.mjs +44 -0
- package/lib/ship-jev.mjs +59 -0
- package/lib/ship-telemetry.mjs +183 -0
- package/lib/tui/ansi.mjs +255 -0
- package/lib/tui/app.mjs +2445 -0
- package/lib/tui/auth.mjs +249 -0
- package/lib/tui/carthage.mjs +109 -0
- package/lib/tui/clipboard.mjs +122 -0
- package/lib/tui/d2.mjs +431 -0
- package/lib/tui/feed.mjs +467 -0
- package/lib/tui/framing.mjs +80 -0
- package/lib/tui/glyphs.mjs +172 -0
- package/lib/tui/hash-worker.mjs +11 -0
- package/lib/tui/mock-engine.mjs +222 -0
- package/lib/tui/models.mjs +73 -0
- package/lib/tui/picker.mjs +18 -0
- package/lib/tui/theme.mjs +663 -0
- package/lib/tui/title.mjs +7 -0
- package/lib/update-channel.mjs +62 -0
- package/lib/update.mjs +230 -0
- package/lib/webdriver.mjs +82 -0
- package/lib/workflow.mjs +88 -0
- package/lib/workspace.mjs +39 -0
- package/metadata.json +8 -0
- package/package.json +94 -4
- package/plugins/carthagent/index.ts +3 -0
- package/plugins/carthagent/package.json +28 -0
- package/plugins/carthagent/src/archive-rpc.ts +46 -0
- package/plugins/carthagent/src/bootstrap.ts +38 -0
- package/plugins/carthagent/src/index.ts +62 -0
- package/plugins/carthagent/src/pull-request-rpc.ts +54 -0
- package/plugins/carthagent/src/rpc.ts +76 -0
- package/plugins/carthagent/src/server/archive-rpc.ts +327 -0
- package/plugins/carthagent/src/server/budgets.ts +21 -0
- package/plugins/carthagent/src/server/codegraph.ts +46 -0
- package/plugins/carthagent/src/server/delivery.ts +488 -0
- package/plugins/carthagent/src/server/device-auth.ts +91 -0
- package/plugins/carthagent/src/server/native-delivery.ts +26 -0
- package/plugins/carthagent/src/server/orchestration.ts +56 -0
- package/plugins/carthagent/src/server/policy.ts +24 -0
- package/plugins/carthagent/src/server/providers.ts +424 -0
- package/plugins/carthagent/src/server/pull-request-rpc.ts +387 -0
- package/plugins/carthagent/src/server/session-controls.ts +82 -0
- package/plugins/carthagent/src/server/telemetry.ts +92 -0
- package/plugins/carthagent/src/server/workspace-rpc.ts +349 -0
- package/plugins/carthagent/src/session-rpc.ts +31 -0
- package/plugins/carthagent/src/testing.ts +85 -0
- package/plugins/carthagent/src/workspace-rpc.ts +133 -0
- package/plugins/carthagent/test-plugin/index.ts +4 -0
- package/plugins/carthagent/test-plugin/package.json +1 -0
- package/plugins/carthagent/tsconfig.json +19 -0
- package/plugins/carthagent/tui.ts +1 -0
- package/prompts/delivery.md +7 -0
- package/public/index.html +983 -0
- package/scenarios/cli/grade_cli.py +69 -0
- package/scenarios/cli/scenario.json +21 -0
- package/scenarios/game/baseline/minecraft.py +193 -0
- package/scenarios/game/context.md +1 -0
- package/scenarios/game/grade_minecraft_clone.py +603 -0
- package/scenarios/game/requirements.txt +2 -0
- package/scenarios/game/scenario.json +33 -0
- package/server.mjs +341 -0
- package/skills/game-development/SKILL.md +36 -0
- package/skills/game-development/assets/ursina_starter.py +98 -0
- package/skills/game-development/scripts/verify_ursina.py +80 -0
- package/skills/software-delivery/SKILL.md +50 -0
- package/skills/typescript-delivery/SKILL.md +69 -0
- package/tests/acceptance-review.test.mjs +13 -0
- package/tests/auth.test.mjs +234 -0
- package/tests/bounded-summary.test.mjs +68 -0
- package/tests/browser-bin.test.mjs +91 -0
- package/tests/browser.test.mjs +96 -0
- package/tests/budget-engine.test.mjs +110 -0
- package/tests/budget.test.mjs +23 -0
- package/tests/cli.test.mjs +245 -0
- package/tests/clipboard.test.mjs +79 -0
- package/tests/cloud-client.test.mjs +129 -0
- package/tests/cloud-control-plane.test.mjs +144 -0
- package/tests/cloud-gateway.test.mjs +147 -0
- package/tests/cloud-http.test.mjs +102 -0
- package/tests/cloud-ledger.test.mjs +75 -0
- package/tests/codegraph-query.test.mjs +66 -0
- package/tests/codegraph.test.mjs +142 -0
- package/tests/delivery-context.test.mjs +66 -0
- package/tests/delivery-review.test.mjs +139 -0
- package/tests/delivery.test.mjs +343 -0
- package/tests/engine-api.mjs +24 -0
- package/tests/experiential-extension.test.mjs +37 -0
- package/tests/experiential.test.mjs +300 -0
- package/tests/extension.test.mjs +921 -0
- package/tests/fixtures/archive-plugin/index.ts +10 -0
- package/tests/guidance.test.mjs +78 -0
- package/tests/model-registry.test.mjs +68 -0
- package/tests/models.test.mjs +70 -0
- package/tests/openai-idempotency.test.mjs +99 -0
- package/tests/opencode-archive-rpc.test.mjs +82 -0
- package/tests/opencode-delivery.test.mjs +231 -0
- package/tests/opencode-providers.test.mjs +414 -0
- package/tests/opencode-runtime.test.mjs +455 -0
- package/tests/opencode-session-controls.test.mjs +115 -0
- package/tests/opencode-session-options.test.mjs +26 -0
- package/tests/opencode-workspace.test.mjs +339 -0
- package/tests/outcome-contract.test.mjs +17 -0
- package/tests/picker.test.mjs +34 -0
- package/tests/plan-advisor.test.mjs +88 -0
- package/tests/plan-review-loop.test.mjs +53 -0
- package/tests/planning-advice.test.mjs +27 -0
- package/tests/planning-contract.test.mjs +65 -0
- package/tests/planning-startup.test.mjs +38 -0
- package/tests/planning-view.test.mjs +33 -0
- package/tests/planning.test.mjs +223 -0
- package/tests/probe-diagnostics.test.mjs +21 -0
- package/tests/pull-request-rpc.test.mjs +366 -0
- package/tests/review-state.test.mjs +32 -0
- package/tests/review.test.mjs +127 -0
- package/tests/server.test.mjs +252 -0
- package/tests/ship-jev.test.mjs +77 -0
- package/tests/ship-telemetry.test.mjs +333 -0
- package/tests/standard-workflow.test.mjs +28 -0
- package/tests/subscription-models.test.mjs +416 -0
- package/tests/subscriptions-extension.test.mjs +27 -0
- package/tests/terminal-title.test.mjs +13 -0
- package/tests/test_grade_minecraft_clone.py +199 -0
- package/tests/test_starter.py +78 -0
- package/tests/theme.test.mjs +175 -0
- package/tests/tui-copy-paste.test.mjs +54 -0
- package/tests/tui.test.mjs +808 -0
- package/tests/update-channels.test.mjs +129 -0
- package/tests/update.test.mjs +175 -0
- package/tests/webdriver.test.mjs +31 -0
- package/tests/workflow.test.mjs +47 -0
- package/tests/workspace-rpc.test.mjs +236 -0
- package/tests/workspace.test.mjs +24 -0
- package/tools/benchmark/advisor.test.mjs +7 -0
- package/tools/benchmark/advisor.ts +27 -0
- package/tools/benchmark/campaign.mjs +45 -0
- package/tools/benchmark/diagnose-request.mjs +40 -0
- package/tools/benchmark/eval-common.mjs +32 -0
- package/tools/benchmark/eval-ledger.mjs +22 -0
- package/tools/benchmark/eval-shop.mjs +26 -0
- package/tools/benchmark/eval-voxel.mjs +20 -0
- package/tools/benchmark/evaluate.mjs +24 -0
- package/tools/benchmark/evaluators.test.mjs +13 -0
- package/tools/benchmark/fixtures/shop/server.mjs +18 -0
- package/tools/benchmark/fixtures/shop/ui.html +8 -0
- package/tools/benchmark/freeze.mjs +30 -0
- package/tools/benchmark/gateway.mjs +91 -0
- package/tools/benchmark/gateway.test.mjs +38 -0
- package/tools/benchmark/generator.mjs +11 -0
- package/tools/benchmark/generator.test.mjs +26 -0
- package/tools/benchmark/guard.test.mjs +133 -0
- package/tools/benchmark/guard.ts +136 -0
- package/tools/benchmark/native-plugin/index.ts +24 -0
- package/tools/benchmark/planning-startup.test.mjs +47 -0
- package/tools/benchmark/preflight-live.mjs +31 -0
- package/tools/benchmark/preflight.mjs +22 -0
- package/tools/benchmark/replay-diagnostic.mjs +23 -0
- package/tools/benchmark/runner.mjs +141 -0
- package/tools/benchmark/runner.test.mjs +93 -0
- package/tools/benchmark/runtime.mjs +23 -0
- package/tools/benchmark/selftest.mjs +47 -0
- package/tools/benchmark/smoke-jev.mjs +5 -0
- package/tools/benchmark/tasks.mjs +20 -0
- package/tools/benchmark/transport.mjs +65 -0
- package/tools/benchmark/transport.test.mjs +44 -0
- package/tools/benchmark/upstream-error.mjs +18 -0
- package/tools/benchmark/upstream-error.test.mjs +10 -0
- package/tools/browser-check.mjs +109 -0
- package/tools/check-syntax.mjs +27 -0
- package/tools/evaluate-plan-advisor.mjs +20 -0
- package/tools/native-fixture.mjs +194 -0
- package/tools/native-pty-smoke.py +108 -0
- package/tools/native-report-plugin/index.ts +50 -0
- package/tools/native-report-plugin/package.json +7 -0
- package/tools/patch-compaction.mjs +24 -0
- package/tools/patch-model-catalog.mjs +12 -0
- package/tools/patch-print-shutdown.mjs +39 -0
- package/tools/repo-pilot/evaluator.cjs +32 -0
- package/tools/repo-pilot/reference.mjs +43 -0
- package/tools/repo-pilot/runner.mjs +85 -0
- package/tools/repo-pilot/sandbox-entry.mjs +12 -0
- package/tools/repo-pilot/tasks.mjs +20 -0
- package/tools/repo-pilot/type-evaluator.cjs +6 -0
- package/tools/test-native-controls.mjs +84 -0
- package/tools/test-native-delivery-host.mjs +307 -0
- package/tools/test-native-evaluation.mjs +46 -0
- package/tools/test-native-host.mjs +385 -0
- package/tools/test-native-outcomes.mjs +73 -0
- package/tools/test-native-package.mjs +70 -0
- package/tools/test-native-pty.mjs +20 -0
- package/tools/test-native-report.mjs +88 -0
- package/tools/test-native-swe-host.mjs +132 -0
- package/tools/test-native-swe.mjs +122 -0
- package/tools/test-picker-pty.py +45 -0
- package/tools/test-python.mjs +29 -0
- package/tools/test-webdriver.mjs +54 -0
- package/tools/verify-release-version.mjs +37 -0
- package/tools/webdriver-check.mjs +52 -0
- package/vendor/agent/bounded-summary.mjs +88 -0
- package/vendor/agent/chunks/anthropic-messages-VWZZOSJQ.js +6 -0
- package/vendor/agent/chunks/anthropic.js +75 -0
- package/vendor/agent/chunks/azure-openai-responses-BJLAM6CD.js +2 -0
- package/vendor/agent/chunks/bedrock-converse-stream.js +74 -0
- package/vendor/agent/chunks/chord-context.js +96 -0
- package/vendor/agent/chunks/chunk-4L3WN2XY.js +2 -0
- package/vendor/agent/chunks/chunk-6CYCI3EJ.js +12 -0
- package/vendor/agent/chunks/chunk-6R7UI4IY.js +2 -0
- package/vendor/agent/chunks/chunk-7ZC4UXSL.js +2 -0
- package/vendor/agent/chunks/chunk-AXIIZGTV.js +2 -0
- package/vendor/agent/chunks/chunk-CLNPYIDP.js +42 -0
- package/vendor/agent/chunks/chunk-DRQDKNXA.js +2 -0
- package/vendor/agent/chunks/chunk-GMWCTUPB.js +2 -0
- package/vendor/agent/chunks/chunk-IDDQWTHI.js +2 -0
- package/vendor/agent/chunks/chunk-JVUZSMYM.js +1548 -0
- package/vendor/agent/chunks/chunk-L2ZPNLYD.js +2 -0
- package/vendor/agent/chunks/chunk-NUHFSC37.js +25 -0
- package/vendor/agent/chunks/chunk-OUXLLA64.js +11 -0
- package/vendor/agent/chunks/chunk-PGXDEOVV.js +2 -0
- package/vendor/agent/chunks/chunk-PJACZCIR.js +2 -0
- package/vendor/agent/chunks/chunk-PRRNXB7S.js +2 -0
- package/vendor/agent/chunks/chunk-TEPMHNKQ.js +2 -0
- package/vendor/agent/chunks/chunk-TRDNDS6A.js +4 -0
- package/vendor/agent/chunks/chunk-U6ZMQKGD.js +50 -0
- package/vendor/agent/chunks/chunk-UAQELI3K.js +2 -0
- package/vendor/agent/chunks/chunk-USJZMAIR.js +2 -0
- package/vendor/agent/chunks/chunk-XDUWOHPL.js +6 -0
- package/vendor/agent/chunks/chunk-XNGRGP62.js +2 -0
- package/vendor/agent/chunks/github-copilot.js +2 -0
- package/vendor/agent/chunks/google-generative-ai-Q2K7FBDI.js +2 -0
- package/vendor/agent/chunks/google-vertex-7UJBF4S7.js +2 -0
- package/vendor/agent/chunks/https-proxy-agent-2VXB7436.js +13 -0
- package/vendor/agent/chunks/image-resize-worker.js +2 -0
- package/vendor/agent/chunks/kimi-coding.js +2 -0
- package/vendor/agent/chunks/lib-HGQMNYVT.js +9 -0
- package/vendor/agent/chunks/mistral-conversations-4M6BZBX6.js +5 -0
- package/vendor/agent/chunks/multipart-parser-SQ6GDJL7.js +3 -0
- package/vendor/agent/chunks/node-KG362ECQ.js +16 -0
- package/vendor/agent/chunks/node-TWVVAGPO.js +2 -0
- package/vendor/agent/chunks/openai-codex-responses-R6VYZTVY.js +10 -0
- package/vendor/agent/chunks/openai-codex.js +75 -0
- package/vendor/agent/chunks/openai-completions-EKZT2IH2.js +7 -0
- package/vendor/agent/chunks/openai-responses-TFDINO6W.js +2 -0
- package/vendor/agent/chunks/openrouter-images-N4XVVFSD.js +2 -0
- package/vendor/agent/chunks/openrouter.js +75 -0
- package/vendor/agent/chunks/pi-messages-PML4SPVJ.js +8 -0
- package/vendor/agent/chunks/radius.js +75 -0
- package/vendor/agent/chunks/src-UK77SYZE.js +4 -0
- package/vendor/agent/chunks/xai.js +2 -0
- package/vendor/agent/cli.js +3 -0
- package/vendor/agent/dist/modes/interactive/theme/dark.json +91 -0
- package/vendor/agent/dist/modes/interactive/theme/light.json +90 -0
- package/vendor/agent/dist/modes/interactive/theme/theme-schema.json +356 -0
- package/vendor/agent/index.js +2 -0
- package/vendor/agent/modes/interactive/theme/dark.json +91 -0
- package/vendor/agent/modes/interactive/theme/light.json +90 -0
- package/vendor/agent/modes/interactive/theme/theme-schema.json +356 -0
- package/vendor/agent/package.json +14 -0
- package/vendor/agent/rpc-entry.js +3 -0
- package/vendor/agent/theme/dark.json +91 -0
- package/vendor/agent/theme/light.json +90 -0
- package/vendor/agent/theme/theme-schema.json +356 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { readLegacyCarthagentCredential, refreshSingleFlight, refreshNativeCredential, credentialStorageKey, nativeCredentialFile } from '../lib/opencode/credentials.mjs';
|
|
4
|
+
import { createSessionIdentity, managedRequestIdentity, shipTelemetryHeaders } from '../plugins/carthagent/src/server/telemetry.ts';
|
|
5
|
+
import { registerProviders, providerConstants } from '../plugins/carthagent/src/server/providers.ts';
|
|
6
|
+
import { createDeviceAuthController } from '../plugins/carthagent/src/server/device-auth.ts';
|
|
7
|
+
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
|
|
13
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
14
|
+
|
|
15
|
+
function fakeContext({ integrations = ['experiential-labs', 'anthropic', 'openai-codex'], connections = {}, failAt, disposeFailure } = {}) {
|
|
16
|
+
const hooks = [];
|
|
17
|
+
const events = [];
|
|
18
|
+
const providerTransforms = [];
|
|
19
|
+
const integrationTransforms = [];
|
|
20
|
+
const activeRegistrations = new Set();
|
|
21
|
+
const disposeCalls = [];
|
|
22
|
+
const storage = new Map();
|
|
23
|
+
const registrations = name => {
|
|
24
|
+
activeRegistrations.add(name);
|
|
25
|
+
return { async dispose() {
|
|
26
|
+
disposeCalls.push(name);
|
|
27
|
+
activeRegistrations.delete(name);
|
|
28
|
+
if (name.startsWith('hook:')) {
|
|
29
|
+
const hookName = name.slice('hook:'.length);
|
|
30
|
+
const index = hooks.findIndex(hook => hook.name === hookName);
|
|
31
|
+
if (index >= 0) hooks.splice(index, 1);
|
|
32
|
+
}
|
|
33
|
+
this.disposed = true;
|
|
34
|
+
if (disposeFailure === name) throw new Error(`dispose failed: ${name}`);
|
|
35
|
+
} };
|
|
36
|
+
};
|
|
37
|
+
const ctx = {
|
|
38
|
+
provider: {
|
|
39
|
+
async transform(callback) {
|
|
40
|
+
const models = new Map();
|
|
41
|
+
const editor = {
|
|
42
|
+
add(record) { providerTransforms.push(record); },
|
|
43
|
+
get(id) { return integrations.includes(id) ? { provider: { id }, models: new Map() } : undefined; },
|
|
44
|
+
models: { set(id, value) { models.set(id, value); } },
|
|
45
|
+
};
|
|
46
|
+
callback(editor);
|
|
47
|
+
if (failAt === 'provider.transform') throw new Error('injected provider transform failure');
|
|
48
|
+
providerTransforms.push({ models });
|
|
49
|
+
return registrations('provider.transform');
|
|
50
|
+
},
|
|
51
|
+
async reload() {},
|
|
52
|
+
},
|
|
53
|
+
integration: {
|
|
54
|
+
async transform(callback) {
|
|
55
|
+
const methods = [];
|
|
56
|
+
const editor = {
|
|
57
|
+
list: () => integrations.map(id => ({ id, name: id })),
|
|
58
|
+
get: id => integrations.includes(id) ? ({ id, name: id }) : undefined,
|
|
59
|
+
update() {}, remove() {},
|
|
60
|
+
method: { update(value) { methods.push(value); }, list: () => [], remove() {} },
|
|
61
|
+
};
|
|
62
|
+
callback(editor);
|
|
63
|
+
if (failAt === 'integration.transform') throw new Error('injected integration transform failure');
|
|
64
|
+
integrationTransforms.push(methods);
|
|
65
|
+
return registrations('integration.transform');
|
|
66
|
+
},
|
|
67
|
+
connection: {
|
|
68
|
+
async active(id) { return connections[id]?.connection; },
|
|
69
|
+
async resolve(connection) { return connection.credential; },
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
session: { async hook(name, callback, options) {
|
|
73
|
+
if (failAt === `hook:${name}`) throw new Error(`injected hook failure: ${name}`);
|
|
74
|
+
hooks.push({ name, callback, options });
|
|
75
|
+
return registrations(`hook:${name}`);
|
|
76
|
+
} },
|
|
77
|
+
storage: {
|
|
78
|
+
async get(key) { return storage.get(key); },
|
|
79
|
+
async set(key, value) { storage.set(key, value); },
|
|
80
|
+
},
|
|
81
|
+
event: { async *subscribe({ signal } = {}) { events.push('subscribed'); if (!signal?.aborted) await new Promise(resolve => signal?.addEventListener('abort', resolve, { once: true })); } },
|
|
82
|
+
};
|
|
83
|
+
return { ctx, hooks, events, providerTransforms, integrationTransforms, storage, activeRegistrations, disposeCalls };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
test('session telemetry uses stable session-derived thread IDs and request-kind identities', () => {
|
|
87
|
+
const identities = createSessionIdentity({ secret: 'fixture' });
|
|
88
|
+
const alpha = identities.thread('ses_native_non_uuid');
|
|
89
|
+
assert.equal(alpha, identities.thread('ses_native_non_uuid'));
|
|
90
|
+
assert.notEqual(alpha, identities.thread('ses_other'));
|
|
91
|
+
assert.match(alpha, /^[0-9a-f-]{36}$/);
|
|
92
|
+
assert.equal(managedRequestIdentity({ sessionID: 's', kind: 'primary', body: '{}', secret: 'x' }),
|
|
93
|
+
managedRequestIdentity({ sessionID: 's', kind: 'primary', body: '{}', secret: 'x' }));
|
|
94
|
+
assert.notEqual(managedRequestIdentity({ sessionID: 's', kind: 'primary', body: '{}', secret: 'x' }),
|
|
95
|
+
managedRequestIdentity({ sessionID: 's', kind: 'title', body: '{}', secret: 'x' }));
|
|
96
|
+
assert.notEqual(identities.request('same-session', 'primary'), identities.request('same-session', 'primary'));
|
|
97
|
+
const headers = shipTelemetryHeaders({ sessionID: 'ses_native_non_uuid', kind: 'generate', body: '{}', env: {}, agentDir: '/missing' , identity: identities, requestSecret: 'x', version: 'test' });
|
|
98
|
+
assert.equal(headers['x-carthagent-thread-id'], alpha);
|
|
99
|
+
assert.equal(headers['x-carthagent-turn'], '1');
|
|
100
|
+
assert.ok(headers['x-carthagent-request-id']);
|
|
101
|
+
assert.equal(headers['x-carthagent-version'], 'test');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('parallel token refresh callers share one rotation result and failures can retry', async () => {
|
|
105
|
+
let calls = 0;
|
|
106
|
+
let release;
|
|
107
|
+
const work = refreshSingleFlight('credential-1:refresh-A', async () => {
|
|
108
|
+
calls++;
|
|
109
|
+
await new Promise(resolve => { release = resolve; });
|
|
110
|
+
return { access: 'next', refresh: 'rotated' };
|
|
111
|
+
});
|
|
112
|
+
const concurrent = refreshSingleFlight('credential-1:refresh-A', async () => { calls++; return null; });
|
|
113
|
+
await Promise.resolve();
|
|
114
|
+
assert.equal(calls, 1);
|
|
115
|
+
release();
|
|
116
|
+
assert.deepEqual(await Promise.all([work, concurrent]), [
|
|
117
|
+
{ access: 'next', refresh: 'rotated' }, { access: 'next', refresh: 'rotated' },
|
|
118
|
+
]);
|
|
119
|
+
await assert.rejects(refreshSingleFlight('credential-2', async () => { throw new Error('failed'); }), /failed/);
|
|
120
|
+
assert.equal(await refreshSingleFlight('credential-2', async () => 'recovered'), 'recovered');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('native-vault refresh rereads after cross-process lease acquisition and rotates once', async t => {
|
|
124
|
+
const directory = await mkdtemp(join(os.tmpdir(), 'ctg-refresh-vault-'));
|
|
125
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
126
|
+
const vault = join(directory, 'auth.json');
|
|
127
|
+
const profile = join(directory, 'profile');
|
|
128
|
+
await writeFile(vault, JSON.stringify({ refresh: 'issued-old-token', access: 'old-access' }), { mode: 0o600 });
|
|
129
|
+
const moduleUrl = new URL('../lib/opencode/credentials.mjs', import.meta.url).href;
|
|
130
|
+
const worker = join(directory, 'worker.mjs');
|
|
131
|
+
await writeFile(worker, `
|
|
132
|
+
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
133
|
+
import { refreshNativeCredential } from ${JSON.stringify(moduleUrl)};
|
|
134
|
+
const [vault, profile, name, gate, rotating, resultFile] = process.argv.slice(2);
|
|
135
|
+
while (true) { try { await readFile(gate); break; } catch { await new Promise(resolve => setTimeout(resolve, 5)); } }
|
|
136
|
+
let rotatedByThisWorker = false;
|
|
137
|
+
const result = await refreshNativeCredential({
|
|
138
|
+
credential: { type: 'oauth', methodID: 'carthagent-device', refresh: 'issued-old-token', access: 'old-access' },
|
|
139
|
+
credentialFile: profile,
|
|
140
|
+
reread: async () => ({ type: 'oauth', methodID: 'carthagent-device', ...JSON.parse(await readFile(vault, 'utf8')) }),
|
|
141
|
+
refresh: async current => {
|
|
142
|
+
if (current.refresh !== 'issued-old-token') throw new Error('unexpected stale vault read');
|
|
143
|
+
await writeFile(rotating, name, { flag: 'wx' });
|
|
144
|
+
const rotated = { refresh: 'rotated-token', access: 'new-access' };
|
|
145
|
+
rotatedByThisWorker = true;
|
|
146
|
+
return { type: 'oauth', methodID: 'carthagent-device', ...rotated };
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
// Model the native host: the same process that owns the refresh callback
|
|
150
|
+
// persists its result atomically before exiting. Do not let the parent
|
|
151
|
+
// mutate the vault after observing this worker's exit.
|
|
152
|
+
if (rotatedByThisWorker) {
|
|
153
|
+
const temporary = vault + '.' + name + '.tmp';
|
|
154
|
+
await writeFile(temporary, JSON.stringify({ refresh: result.refresh, access: result.access }), { mode: 0o600 });
|
|
155
|
+
await rename(temporary, vault);
|
|
156
|
+
}
|
|
157
|
+
await writeFile(resultFile, JSON.stringify({ refresh: result.refresh, access: result.access }));
|
|
158
|
+
console.log(JSON.stringify({ name, refreshed: true }));
|
|
159
|
+
`);
|
|
160
|
+
const rotating = join(directory, 'rotating');
|
|
161
|
+
const resultFiles = ['one', 'two'].map(name => join(directory, `${name}.result`));
|
|
162
|
+
const children = ['one', 'two'].map((name, index) => spawn(process.execPath, [worker, vault, profile, name, join(directory, 'go'), rotating, resultFiles[index]], { stdio: ['ignore', 'pipe', 'pipe'] }));
|
|
163
|
+
const outputsPromise = Promise.all(children.map(child => new Promise((resolve, reject) => {
|
|
164
|
+
let stdout = '';
|
|
165
|
+
let stderr = '';
|
|
166
|
+
child.stdout.on('data', chunk => { stdout += chunk; });
|
|
167
|
+
child.stderr.on('data', chunk => { stderr += chunk; });
|
|
168
|
+
child.once('error', reject);
|
|
169
|
+
child.once('close', code => code === 0 ? resolve(JSON.parse(stdout.trim())) : reject(new Error(stderr)));
|
|
170
|
+
})));
|
|
171
|
+
await writeFile(join(directory, 'go'), 'start');
|
|
172
|
+
const waitForFile = async file => {
|
|
173
|
+
const deadline = Date.now() + 5_000;
|
|
174
|
+
while (Date.now() < deadline) {
|
|
175
|
+
try { return await readFile(file, 'utf8'); } catch { await new Promise(resolve => setTimeout(resolve, 10)); }
|
|
176
|
+
}
|
|
177
|
+
throw new Error('Timed out waiting for cross-process refresh fixture state.');
|
|
178
|
+
};
|
|
179
|
+
await waitForFile(rotating);
|
|
180
|
+
const outputs = await outputsPromise;
|
|
181
|
+
assert.deepEqual(outputs.map(output => output.refreshed), [true, true]);
|
|
182
|
+
for (const resultFile of resultFiles) {
|
|
183
|
+
assert.deepEqual(JSON.parse(await readFile(resultFile, 'utf8')), { refresh: 'rotated-token', access: 'new-access' });
|
|
184
|
+
}
|
|
185
|
+
assert.deepEqual(JSON.parse(await readFile(vault, 'utf8')), { refresh: 'rotated-token', access: 'new-access' });
|
|
186
|
+
const lockFiles = await (await import('node:fs/promises')).readdir(directory);
|
|
187
|
+
assert.equal(lockFiles.some(entry => entry.startsWith('profile.ctg-refresh-') && entry.endsWith('.lock')), false, 'completed lease should be released');
|
|
188
|
+
assert.equal(lockFiles.filter(entry => entry.endsWith('.lock.pending')).length, 0, 'the pending receipt is removed after the native vault shows the matching rotation');
|
|
189
|
+
for (const entry of lockFiles) {
|
|
190
|
+
if (!entry.includes('ctg-refresh-')) continue;
|
|
191
|
+
const contents = await readFile(join(directory, entry), 'utf8').catch(() => '');
|
|
192
|
+
assert.doesNotMatch(contents, /issued-old-token|rotated-token|old-access|new-access/);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test('native refresh waits are bounded and never retry an uncertain rotation', async t => {
|
|
197
|
+
const directory = await mkdtemp(join(os.tmpdir(), 'ctg-refresh-timeout-'));
|
|
198
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
199
|
+
const profile = join(directory, 'auth.json');
|
|
200
|
+
const credential = { type: 'oauth', methodID: 'carthagent-device', refresh: 'issued-old-token', access: 'old-access' };
|
|
201
|
+
const digest = createHash('sha256').update(`${credential.methodID}\0${credential.refresh}`).digest('hex').slice(0, 32);
|
|
202
|
+
const lock = `${profile}.ctg-refresh-${digest}.lock`;
|
|
203
|
+
const pending = `${lock}.pending`;
|
|
204
|
+
await writeFile(pending, JSON.stringify({ pid: process.pid, owner: 'test-owner', from: digest, stage: 'complete', to: 'not-the-old-digest', createdAt: Date.now() }), { mode: 0o600 });
|
|
205
|
+
let refreshCalls = 0;
|
|
206
|
+
await assert.rejects(refreshNativeCredential({
|
|
207
|
+
credential,
|
|
208
|
+
credentialFile: profile,
|
|
209
|
+
timeout: 80,
|
|
210
|
+
reread: async () => credential,
|
|
211
|
+
refresh: async () => { refreshCalls++; return credential; },
|
|
212
|
+
}), /Timed out waiting for OpenCode to persist/);
|
|
213
|
+
assert.equal(refreshCalls, 0, 'a contender must not submit the old single-use token again');
|
|
214
|
+
const receipt = await readFile(pending, 'utf8');
|
|
215
|
+
assert.doesNotMatch(receipt, /issued-old-token|old-access/);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test('native refresh fails closed when its owner crashes before vault persistence', async t => {
|
|
219
|
+
const directory = await mkdtemp(join(os.tmpdir(), 'ctg-refresh-owner-crash-'));
|
|
220
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
221
|
+
const profile = join(directory, 'auth.json');
|
|
222
|
+
const credential = { type: 'oauth', methodID: 'carthagent-device', refresh: 'issued-old-token', access: 'old-access' };
|
|
223
|
+
const digest = createHash('sha256').update(`${credential.methodID}\0${credential.refresh}`).digest('hex').slice(0, 32);
|
|
224
|
+
const pending = `${profile}.ctg-refresh-${digest}.lock.pending`;
|
|
225
|
+
await writeFile(pending, JSON.stringify({
|
|
226
|
+
pid: Number.MAX_SAFE_INTEGER,
|
|
227
|
+
owner: 'crashed-owner',
|
|
228
|
+
from: digest,
|
|
229
|
+
stage: 'refreshing',
|
|
230
|
+
createdAt: Date.now(),
|
|
231
|
+
}), { mode: 0o600 });
|
|
232
|
+
|
|
233
|
+
let refreshCalls = 0;
|
|
234
|
+
await assert.rejects(refreshNativeCredential({
|
|
235
|
+
credential,
|
|
236
|
+
credentialFile: profile,
|
|
237
|
+
processAliveImpl: () => false,
|
|
238
|
+
reread: async () => credential,
|
|
239
|
+
refresh: async () => { refreshCalls++; return credential; },
|
|
240
|
+
}), /ended before its vault write could be confirmed/);
|
|
241
|
+
assert.equal(refreshCalls, 0, 'do not replay a potentially consumed refresh token');
|
|
242
|
+
assert.equal(await readFile(pending, 'utf8').then(Boolean), true, 'preserve the receipt for recovery diagnostics');
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
test('native refresh accepts a vault rotation persisted just before its owner exits', async t => {
|
|
246
|
+
const directory = await mkdtemp(join(os.tmpdir(), 'ctg-refresh-owner-exit-'));
|
|
247
|
+
t.after(() => rm(directory, { recursive: true, force: true }));
|
|
248
|
+
const profile = join(directory, 'auth.json');
|
|
249
|
+
const credential = { type: 'oauth', methodID: 'carthagent-device', refresh: 'issued-old-token', access: 'old-access' };
|
|
250
|
+
const rotated = { type: 'oauth', methodID: 'carthagent-device', refresh: 'rotated-token', access: 'new-access' };
|
|
251
|
+
const digest = createHash('sha256').update(`${credential.methodID}\0${credential.refresh}`).digest('hex').slice(0, 32);
|
|
252
|
+
const rotatedDigest = createHash('sha256').update(`${rotated.methodID}\0${rotated.refresh}`).digest('hex').slice(0, 32);
|
|
253
|
+
const pending = `${profile}.ctg-refresh-${digest}.lock.pending`;
|
|
254
|
+
await writeFile(pending, JSON.stringify({
|
|
255
|
+
pid: Number.MAX_SAFE_INTEGER,
|
|
256
|
+
owner: 'exited-owner',
|
|
257
|
+
from: digest,
|
|
258
|
+
to: rotatedDigest,
|
|
259
|
+
stage: 'complete',
|
|
260
|
+
createdAt: Date.now(),
|
|
261
|
+
}), { mode: 0o600 });
|
|
262
|
+
|
|
263
|
+
let reads = 0;
|
|
264
|
+
let refreshCalls = 0;
|
|
265
|
+
const result = await refreshNativeCredential({
|
|
266
|
+
credential,
|
|
267
|
+
credentialFile: profile,
|
|
268
|
+
timeout: 500,
|
|
269
|
+
processAliveImpl: () => false,
|
|
270
|
+
reread: async () => ++reads >= 3 ? rotated : credential,
|
|
271
|
+
refresh: async () => { refreshCalls++; throw new Error('must not rotate again'); },
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
assert.deepEqual(result, rotated);
|
|
275
|
+
assert.equal(reads, 3, 'perform a final native-vault read after detecting owner exit');
|
|
276
|
+
assert.equal(refreshCalls, 0, 'never submit the previous single-use refresh token again');
|
|
277
|
+
await assert.rejects(readFile(pending), { code: 'ENOENT' }, 'remove only the matching persisted-rotation receipt');
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
test('provider registration rolls back every completed stage in reverse order after failures', async t => {
|
|
281
|
+
for (const [failAt, expected] of [
|
|
282
|
+
['integration.transform', []],
|
|
283
|
+
['provider.transform', ['integration.transform']],
|
|
284
|
+
['hook:http.request', ['provider.transform', 'integration.transform']],
|
|
285
|
+
['hook:model.request', ['hook:http.request', 'provider.transform', 'integration.transform']],
|
|
286
|
+
['hook:retry', ['hook:model.request', 'hook:http.request', 'provider.transform', 'integration.transform']],
|
|
287
|
+
['hook:http.response', ['hook:retry', 'hook:model.request', 'hook:http.request', 'provider.transform', 'integration.transform']],
|
|
288
|
+
]) {
|
|
289
|
+
const fake = fakeContext({ failAt });
|
|
290
|
+
await assert.rejects(registerProviders(fake.ctx, { env: { CARTHAGENT_CODING_AGENT_DIR: '/missing' } }), /injected/);
|
|
291
|
+
assert.deepEqual(fake.disposeCalls, expected, `rollback ordering for ${failAt}`);
|
|
292
|
+
assert.equal(fake.activeRegistrations.size, 0, `all handles released after ${failAt}`);
|
|
293
|
+
assert.deepEqual(fake.hooks, [], `no hook remains after ${failAt}`);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const failingCleanup = fakeContext({ failAt: 'hook:model.request', disposeFailure: 'provider.transform' });
|
|
297
|
+
await assert.rejects(registerProviders(failingCleanup.ctx, { env: { CARTHAGENT_CODING_AGENT_DIR: '/missing' } }), error => {
|
|
298
|
+
assert.ok(error instanceof AggregateError);
|
|
299
|
+
assert.match(error.message, /rollback was incomplete/);
|
|
300
|
+
assert.match(error.errors[0].message, /injected hook failure/);
|
|
301
|
+
assert.match(error.errors[1].message, /dispose failed/);
|
|
302
|
+
return true;
|
|
303
|
+
});
|
|
304
|
+
assert.deepEqual(failingCleanup.disposeCalls, ['hook:http.request', 'provider.transform', 'integration.transform'],
|
|
305
|
+
'cleanup proceeds after an individual dispose failure');
|
|
306
|
+
assert.equal(failingCleanup.activeRegistrations.size, 0);
|
|
307
|
+
assert.deepEqual(failingCleanup.hooks, []);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
test('CTG device-auth generations cancel polling, expire, and clean up on unload', async () => {
|
|
311
|
+
const requests = [];
|
|
312
|
+
const controller = createDeviceAuthController({
|
|
313
|
+
env: { CARTHAGENT_CLOUD_URL: 'https://cloud.test' }, agentDir: '/tmp/device-auth-test',
|
|
314
|
+
fetchImpl: async (url, options) => {
|
|
315
|
+
requests.push({ url: String(url), options });
|
|
316
|
+
if (String(url).endsWith('/v1/device/authorizations')) return new Response(JSON.stringify({
|
|
317
|
+
deviceCode: 'device', userCode: 'ABCD', verificationUri: 'https://verify.test', expiresIn: 30, interval: 1,
|
|
318
|
+
}), { status: 201 });
|
|
319
|
+
return new Promise((resolve, reject) => {
|
|
320
|
+
options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });
|
|
321
|
+
});
|
|
322
|
+
},
|
|
323
|
+
sleep: async (_ms, signal) => {
|
|
324
|
+
if (signal?.aborted) throw signal.reason;
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
const flow = await controller.start();
|
|
328
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
329
|
+
assert.match(JSON.parse(requests[0].options.body).installId, UUID);
|
|
330
|
+
assert.equal(requests[1].url, 'https://cloud.test/v1/device/token');
|
|
331
|
+
assert.equal(controller.cancel(flow.flowId), true);
|
|
332
|
+
await assert.rejects(flow.callback, /cancelled/);
|
|
333
|
+
assert.equal(controller.cancel(flow.flowId), false);
|
|
334
|
+
|
|
335
|
+
const next = await controller.start();
|
|
336
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
337
|
+
await controller.cleanup();
|
|
338
|
+
await assert.rejects(next.callback, /plugin_unloaded/);
|
|
339
|
+
assert.equal(controller.cancel(next.flowId), false);
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
test('legacy credential migration reads Ship OAuth and BYOK without writing Pi store', async () => {
|
|
343
|
+
const source = JSON.stringify({
|
|
344
|
+
'experiential-labs': { type: 'oauth', access: 'a', refresh: 'r', expires: 123 },
|
|
345
|
+
});
|
|
346
|
+
assert.deepEqual(await readLegacyCarthagentCredential({ agentDir: '/unused', readFileImpl: async () => source }),
|
|
347
|
+
{ type: 'oauth', access: 'a', refresh: 'r', expires: 123 });
|
|
348
|
+
assert.equal(credentialStorageKey('experiential-labs'), 'ctg.credentials/experiential-labs');
|
|
349
|
+
assert.equal(nativeCredentialFile({ XDG_DATA_HOME: '/profile/data' }), join('/profile/data', 'opencode', 'auth.json'));
|
|
350
|
+
assert.equal(nativeCredentialFile({}, 'darwin', '/home/test'), join('/home/test', 'Library', 'Application Support', 'opencode', 'auth.json'));
|
|
351
|
+
assert.throws(() => credentialStorageKey('../auth'), /Invalid/);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
test('provider registration uses native provider transforms and cleanup; refresh discovers subscriptions through injected APIs', async () => {
|
|
355
|
+
const token = `x.${Buffer.from(JSON.stringify({ sub: 'acct', sid: 'sid', scope: 'gateway:invoke' })).toString('base64url')}.x`;
|
|
356
|
+
const connections = {
|
|
357
|
+
'experiential-labs': { connection: { id: 'ship', credential: { type: 'oauth', access: token, refresh: 'refresh', expires: Date.now() + 100000 } } },
|
|
358
|
+
anthropic: { connection: { id: 'claude', credential: { type: 'oauth', access: 'claude-token' } } },
|
|
359
|
+
'openai-codex': { connection: { id: 'codex', credential: { type: 'oauth', access: 'codex-token' } } },
|
|
360
|
+
};
|
|
361
|
+
const fake = fakeContext({ integrations: ['experiential-labs', 'anthropic', 'openai-codex'], connections });
|
|
362
|
+
const fetchCalls = [];
|
|
363
|
+
const fetchImpl = async (url, init) => {
|
|
364
|
+
fetchCalls.push([String(url), init]);
|
|
365
|
+
if (String(url).endsWith('/models') && String(url).includes('experientiallabs')) {
|
|
366
|
+
return new Response(JSON.stringify({ data: [{ id: 'gpt-6-luna' }, { id: 'unknown-model', name: 'Unknown' }] }), { status: 200 });
|
|
367
|
+
}
|
|
368
|
+
if (String(url).includes('api.anthropic.com')) return new Response(JSON.stringify({ data: [{ id: 'claude-test', type: 'model' }] }), { status: 200 });
|
|
369
|
+
if (String(url).includes('chatgpt.com')) return new Response(JSON.stringify({ models: [{ slug: 'codex-test', supported_reasoning_levels: ['low', 'high'] }] }), { status: 200 });
|
|
370
|
+
throw new Error(`unexpected URL ${url}`);
|
|
371
|
+
};
|
|
372
|
+
const cleanup = await registerProviders(fake.ctx, {
|
|
373
|
+
env: { CARTHAGENT_CODING_AGENT_DIR: '/missing' }, fetchImpl,
|
|
374
|
+
openBrowser: () => false, requestSecret: 'test-secret',
|
|
375
|
+
});
|
|
376
|
+
assert.equal(typeof cleanup, 'function');
|
|
377
|
+
assert.deepEqual(fake.integrationTransforms[0].map(item => item.integrationID), ['experiential-labs', 'experiential-labs', 'experiential-labs']);
|
|
378
|
+
assert.equal(fake.integrationTransforms[0][0].method.id, 'carthagent-device');
|
|
379
|
+
assert.equal(fake.integrationTransforms[0][1].method.type, 'key');
|
|
380
|
+
assert.equal(fake.providerTransforms.find(item => item.info?.id === providerConstants.SHIP_PROVIDER_ID).info.package,
|
|
381
|
+
'@opencode/ai/providers/openai-compatible');
|
|
382
|
+
assert.ok(fake.hooks.some(item => item.name === 'http.request' && item.options.providerID === 'experiential-labs'));
|
|
383
|
+
assert.ok(fake.hooks.some(item => item.name === 'http.response'));
|
|
384
|
+
const hooksByName = Object.fromEntries(fake.hooks.map(item => [item.name, item]));
|
|
385
|
+
const nativeSession = { sessionID: 'ses_non_uuid_123', kind: 'primary', model: { providerID: 'experiential-labs' } };
|
|
386
|
+
const modelRequest = { ...nativeSession, headers: {} };
|
|
387
|
+
await hooksByName['model.request'].callback(modelRequest);
|
|
388
|
+
const nextModelRequest = { ...nativeSession, headers: {} };
|
|
389
|
+
await hooksByName['model.request'].callback(nextModelRequest);
|
|
390
|
+
assert.ok(modelRequest.headers['x-carthagent-request-id']);
|
|
391
|
+
assert.notEqual(modelRequest.headers['x-carthagent-request-id'], nextModelRequest.headers['x-carthagent-request-id'],
|
|
392
|
+
'separate native requests in one session must have distinct idempotency identities');
|
|
393
|
+
const auxiliaryRequest = { ...nativeSession, kind: 'title', headers: {} };
|
|
394
|
+
await hooksByName['model.request'].callback(auxiliaryRequest);
|
|
395
|
+
assert.notEqual(modelRequest.headers['x-carthagent-request-id'], auxiliaryRequest.headers['x-carthagent-request-id'],
|
|
396
|
+
'auxiliary request kinds must have independent identities');
|
|
397
|
+
const request = new Request('https://gateway.example/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: 'gpt-6-luna', messages: [] }) });
|
|
398
|
+
const hookedRequestEvent = { ...nativeSession, request: new Request(request, { headers: { 'x-carthagent-request-id': modelRequest.headers['x-carthagent-request-id'] } }) };
|
|
399
|
+
await hooksByName['http.request'].callback(hookedRequestEvent);
|
|
400
|
+
assert.equal(hookedRequestEvent.request.headers.get('x-carthagent-thread-id')?.length, 36);
|
|
401
|
+
assert.equal(hookedRequestEvent.request.headers.get('Idempotency-Key'), modelRequest.headers['x-carthagent-request-id']);
|
|
402
|
+
const retry = new Request('https://gateway.example/v1/chat/completions', { method: 'POST', headers: { 'x-carthagent-request-id': modelRequest.headers['x-carthagent-request-id'] }, body: JSON.stringify({ model: 'gpt-6-luna', messages: [] }) });
|
|
403
|
+
const retryRequestEvent = { ...nativeSession, request: retry };
|
|
404
|
+
await hooksByName['http.request'].callback(retryRequestEvent);
|
|
405
|
+
assert.equal(retryRequestEvent.request.headers.get('Idempotency-Key'), hookedRequestEvent.request.headers.get('Idempotency-Key'),
|
|
406
|
+
'transport retry identity must remain stable');
|
|
407
|
+
const retryEvent = { ...nativeSession, attempt: 1, decision: { retry: true, delay: 0 }, error: {} };
|
|
408
|
+
await hooksByName.retry.callback(retryEvent);
|
|
409
|
+
assert.deepEqual(retryEvent.decision, { retry: false });
|
|
410
|
+
await new Promise(resolve => setTimeout(resolve, 30));
|
|
411
|
+
assert.ok(fetchCalls.some(([url]) => url.includes('/models')));
|
|
412
|
+
await cleanup();
|
|
413
|
+
assert.ok(fake.events.includes('subscribed'));
|
|
414
|
+
});
|