@dirgha/code 1.2.0
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 +101 -0
- package/README.md +674 -0
- package/dist/dirgha.mjs +2185 -0
- package/dist_v2/acp/index.d.ts +1 -0
- package/dist_v2/acp/index.js +2 -0
- package/dist_v2/acp/server.d.ts +31 -0
- package/dist_v2/acp/server.js +137 -0
- package/dist_v2/cli/auth-cmd.d.ts +10 -0
- package/dist_v2/cli/auth-cmd.js +69 -0
- package/dist_v2/cli/config.d.ts +46 -0
- package/dist_v2/cli/config.js +70 -0
- package/dist_v2/cli/flags.d.ts +10 -0
- package/dist_v2/cli/flags.js +49 -0
- package/dist_v2/cli/flows/full-cycle.d.ts +30 -0
- package/dist_v2/cli/flows/full-cycle.js +39 -0
- package/dist_v2/cli/flows/index.d.ts +2 -0
- package/dist_v2/cli/flows/index.js +3 -0
- package/dist_v2/cli/flows/tarball.d.ts +10 -0
- package/dist_v2/cli/flows/tarball.js +47 -0
- package/dist_v2/cli/index.d.ts +4 -0
- package/dist_v2/cli/index.js +5 -0
- package/dist_v2/cli/interactive.d.ts +21 -0
- package/dist_v2/cli/interactive.js +207 -0
- package/dist_v2/cli/main.d.ts +10 -0
- package/dist_v2/cli/main.js +173 -0
- package/dist_v2/cli/models-cmd.d.ts +6 -0
- package/dist_v2/cli/models-cmd.js +50 -0
- package/dist_v2/cli/setup.d.ts +13 -0
- package/dist_v2/cli/setup.js +128 -0
- package/dist_v2/cli/slash/account.d.ts +10 -0
- package/dist_v2/cli/slash/account.js +59 -0
- package/dist_v2/cli/slash/clear.d.ts +8 -0
- package/dist_v2/cli/slash/clear.js +15 -0
- package/dist_v2/cli/slash/compact.d.ts +7 -0
- package/dist_v2/cli/slash/compact.js +13 -0
- package/dist_v2/cli/slash/config.d.ts +8 -0
- package/dist_v2/cli/slash/config.js +49 -0
- package/dist_v2/cli/slash/exit.d.ts +7 -0
- package/dist_v2/cli/slash/exit.js +16 -0
- package/dist_v2/cli/slash/fleet.d.ts +7 -0
- package/dist_v2/cli/slash/fleet.js +22 -0
- package/dist_v2/cli/slash/help.d.ts +9 -0
- package/dist_v2/cli/slash/help.js +31 -0
- package/dist_v2/cli/slash/history.d.ts +7 -0
- package/dist_v2/cli/slash/history.js +42 -0
- package/dist_v2/cli/slash/index.d.ts +30 -0
- package/dist_v2/cli/slash/index.js +52 -0
- package/dist_v2/cli/slash/init.d.ts +8 -0
- package/dist_v2/cli/slash/init.js +57 -0
- package/dist_v2/cli/slash/keys.d.ts +8 -0
- package/dist_v2/cli/slash/keys.js +101 -0
- package/dist_v2/cli/slash/login.d.ts +10 -0
- package/dist_v2/cli/slash/login.js +47 -0
- package/dist_v2/cli/slash/memory.d.ts +8 -0
- package/dist_v2/cli/slash/memory.js +101 -0
- package/dist_v2/cli/slash/mode.d.ts +8 -0
- package/dist_v2/cli/slash/mode.js +30 -0
- package/dist_v2/cli/slash/models.d.ts +8 -0
- package/dist_v2/cli/slash/models.js +73 -0
- package/dist_v2/cli/slash/resume.d.ts +8 -0
- package/dist_v2/cli/slash/resume.js +24 -0
- package/dist_v2/cli/slash/session.d.ts +8 -0
- package/dist_v2/cli/slash/session.js +74 -0
- package/dist_v2/cli/slash/setup.d.ts +8 -0
- package/dist_v2/cli/slash/setup.js +50 -0
- package/dist_v2/cli/slash/status.d.ts +7 -0
- package/dist_v2/cli/slash/status.js +37 -0
- package/dist_v2/cli/slash/theme.d.ts +9 -0
- package/dist_v2/cli/slash/theme.js +53 -0
- package/dist_v2/cli/slash/types.d.ts +14 -0
- package/dist_v2/cli/slash/types.js +9 -0
- package/dist_v2/cli/slash/upgrade.d.ts +9 -0
- package/dist_v2/cli/slash/upgrade.js +66 -0
- package/dist_v2/cli/slash.d.ts +72 -0
- package/dist_v2/cli/slash.js +77 -0
- package/dist_v2/cli/subcommands/ask.d.ts +17 -0
- package/dist_v2/cli/subcommands/ask.js +76 -0
- package/dist_v2/cli/subcommands/audit.d.ts +15 -0
- package/dist_v2/cli/subcommands/audit.js +128 -0
- package/dist_v2/cli/subcommands/chat.d.ts +13 -0
- package/dist_v2/cli/subcommands/chat.js +72 -0
- package/dist_v2/cli/subcommands/compact.d.ts +14 -0
- package/dist_v2/cli/subcommands/compact.js +114 -0
- package/dist_v2/cli/subcommands/doctor.d.ts +11 -0
- package/dist_v2/cli/subcommands/doctor.js +103 -0
- package/dist_v2/cli/subcommands/export-session.d.ts +10 -0
- package/dist_v2/cli/subcommands/export-session.js +60 -0
- package/dist_v2/cli/subcommands/import-session.d.ts +11 -0
- package/dist_v2/cli/subcommands/import-session.js +77 -0
- package/dist_v2/cli/subcommands/index.d.ts +40 -0
- package/dist_v2/cli/subcommands/index.js +38 -0
- package/dist_v2/cli/subcommands/init.d.ts +10 -0
- package/dist_v2/cli/subcommands/init.js +74 -0
- package/dist_v2/cli/subcommands/keys.d.ts +12 -0
- package/dist_v2/cli/subcommands/keys.js +136 -0
- package/dist_v2/cli/subcommands/login.d.ts +10 -0
- package/dist_v2/cli/subcommands/login.js +60 -0
- package/dist_v2/cli/subcommands/logout.d.ts +10 -0
- package/dist_v2/cli/subcommands/logout.js +21 -0
- package/dist_v2/cli/subcommands/models.d.ts +14 -0
- package/dist_v2/cli/subcommands/models.js +144 -0
- package/dist_v2/cli/subcommands/setup.d.ts +11 -0
- package/dist_v2/cli/subcommands/setup.js +107 -0
- package/dist_v2/cli/subcommands/stats.d.ts +13 -0
- package/dist_v2/cli/subcommands/stats.js +148 -0
- package/dist_v2/cli/subcommands/status.d.ts +14 -0
- package/dist_v2/cli/subcommands/status.js +91 -0
- package/dist_v2/cli/submit-paper.d.ts +15 -0
- package/dist_v2/cli/submit-paper.js +68 -0
- package/dist_v2/context/_fts.d.ts +62 -0
- package/dist_v2/context/_fts.js +195 -0
- package/dist_v2/context/branch.d.ts +18 -0
- package/dist_v2/context/branch.js +66 -0
- package/dist_v2/context/compaction.d.ts +26 -0
- package/dist_v2/context/compaction.js +120 -0
- package/dist_v2/context/index.d.ts +5 -0
- package/dist_v2/context/index.js +6 -0
- package/dist_v2/context/knowledge.d.ts +38 -0
- package/dist_v2/context/knowledge.js +146 -0
- package/dist_v2/context/memory.d.ts +80 -0
- package/dist_v2/context/memory.js +276 -0
- package/dist_v2/context/mode.d.ts +25 -0
- package/dist_v2/context/mode.js +81 -0
- package/dist_v2/context/session.d.ts +56 -0
- package/dist_v2/context/session.js +108 -0
- package/dist_v2/daemon/index.d.ts +2 -0
- package/dist_v2/daemon/index.js +3 -0
- package/dist_v2/daemon/protocol.d.ts +73 -0
- package/dist_v2/daemon/protocol.js +6 -0
- package/dist_v2/daemon/server.d.ts +35 -0
- package/dist_v2/daemon/server.js +191 -0
- package/dist_v2/eval/index.d.ts +5 -0
- package/dist_v2/eval/index.js +6 -0
- package/dist_v2/eval/regression.d.ts +14 -0
- package/dist_v2/eval/regression.js +106 -0
- package/dist_v2/eval/reporter.d.ts +7 -0
- package/dist_v2/eval/reporter.js +34 -0
- package/dist_v2/eval/swe-bench.d.ts +18 -0
- package/dist_v2/eval/swe-bench.js +23 -0
- package/dist_v2/eval/terminal-bench.d.ts +13 -0
- package/dist_v2/eval/terminal-bench.js +19 -0
- package/dist_v2/eval/types.d.ts +36 -0
- package/dist_v2/eval/types.js +5 -0
- package/dist_v2/fleet/apply-back.d.ts +27 -0
- package/dist_v2/fleet/apply-back.js +191 -0
- package/dist_v2/fleet/cli-command.d.ts +61 -0
- package/dist_v2/fleet/cli-command.js +329 -0
- package/dist_v2/fleet/index.d.ts +21 -0
- package/dist_v2/fleet/index.js +21 -0
- package/dist_v2/fleet/runner.d.ts +28 -0
- package/dist_v2/fleet/runner.js +347 -0
- package/dist_v2/fleet/tripleshot.d.ts +21 -0
- package/dist_v2/fleet/tripleshot.js +222 -0
- package/dist_v2/fleet/types.d.ts +193 -0
- package/dist_v2/fleet/types.js +24 -0
- package/dist_v2/fleet/worktree.d.ts +51 -0
- package/dist_v2/fleet/worktree.js +176 -0
- package/dist_v2/hooks/index.d.ts +1 -0
- package/dist_v2/hooks/index.js +2 -0
- package/dist_v2/hooks/registry.d.ts +21 -0
- package/dist_v2/hooks/registry.js +40 -0
- package/dist_v2/index.d.ts +12 -0
- package/dist_v2/index.js +11 -0
- package/dist_v2/integrations/arniko-client.d.ts +42 -0
- package/dist_v2/integrations/arniko-client.js +86 -0
- package/dist_v2/integrations/auth.d.ts +45 -0
- package/dist_v2/integrations/auth.js +54 -0
- package/dist_v2/integrations/billing.d.ts +71 -0
- package/dist_v2/integrations/billing.js +107 -0
- package/dist_v2/integrations/bucky-client.d.ts +105 -0
- package/dist_v2/integrations/bucky-client.js +76 -0
- package/dist_v2/integrations/deploy-client.d.ts +60 -0
- package/dist_v2/integrations/deploy-client.js +87 -0
- package/dist_v2/integrations/device-auth.d.ts +48 -0
- package/dist_v2/integrations/device-auth.js +192 -0
- package/dist_v2/integrations/entitlements.d.ts +34 -0
- package/dist_v2/integrations/entitlements.js +43 -0
- package/dist_v2/integrations/http.d.ts +22 -0
- package/dist_v2/integrations/http.js +114 -0
- package/dist_v2/integrations/index.d.ts +8 -0
- package/dist_v2/integrations/index.js +15 -0
- package/dist_v2/intelligence/cost.d.ts +28 -0
- package/dist_v2/intelligence/cost.js +58 -0
- package/dist_v2/intelligence/error-classifier.d.ts +8 -0
- package/dist_v2/intelligence/error-classifier.js +71 -0
- package/dist_v2/intelligence/index.d.ts +5 -0
- package/dist_v2/intelligence/index.js +6 -0
- package/dist_v2/intelligence/prices.d.ts +13 -0
- package/dist_v2/intelligence/prices.js +26 -0
- package/dist_v2/intelligence/smart-router.d.ts +21 -0
- package/dist_v2/intelligence/smart-router.js +59 -0
- package/dist_v2/intelligence/telemetry.d.ts +22 -0
- package/dist_v2/intelligence/telemetry.js +31 -0
- package/dist_v2/kernel/agent-loop.d.ts +32 -0
- package/dist_v2/kernel/agent-loop.js +151 -0
- package/dist_v2/kernel/event-stream.d.ts +18 -0
- package/dist_v2/kernel/event-stream.js +102 -0
- package/dist_v2/kernel/index.d.ts +4 -0
- package/dist_v2/kernel/index.js +5 -0
- package/dist_v2/kernel/message.d.ts +29 -0
- package/dist_v2/kernel/message.js +118 -0
- package/dist_v2/kernel/types.d.ts +206 -0
- package/dist_v2/kernel/types.js +9 -0
- package/dist_v2/mcp/client.d.ts +44 -0
- package/dist_v2/mcp/client.js +63 -0
- package/dist_v2/mcp/index.d.ts +3 -0
- package/dist_v2/mcp/index.js +4 -0
- package/dist_v2/mcp/tool-bridge.d.ts +11 -0
- package/dist_v2/mcp/tool-bridge.js +33 -0
- package/dist_v2/mcp/transport.d.ts +29 -0
- package/dist_v2/mcp/transport.js +73 -0
- package/dist_v2/parity/index.d.ts +3 -0
- package/dist_v2/parity/index.js +4 -0
- package/dist_v2/parity/mock-openai-compat.d.ts +15 -0
- package/dist_v2/parity/mock-openai-compat.js +35 -0
- package/dist_v2/parity/runner.d.ts +21 -0
- package/dist_v2/parity/runner.js +76 -0
- package/dist_v2/parity/scenarios.d.ts +20 -0
- package/dist_v2/parity/scenarios.js +70 -0
- package/dist_v2/providers/anthropic.d.ts +21 -0
- package/dist_v2/providers/anthropic.js +191 -0
- package/dist_v2/providers/dispatch.d.ts +11 -0
- package/dist_v2/providers/dispatch.js +45 -0
- package/dist_v2/providers/fireworks.d.ts +18 -0
- package/dist_v2/providers/fireworks.js +44 -0
- package/dist_v2/providers/gemini.d.ts +19 -0
- package/dist_v2/providers/gemini.js +188 -0
- package/dist_v2/providers/http.d.ts +41 -0
- package/dist_v2/providers/http.js +188 -0
- package/dist_v2/providers/iface.d.ts +18 -0
- package/dist_v2/providers/iface.js +18 -0
- package/dist_v2/providers/index.d.ts +39 -0
- package/dist_v2/providers/index.js +51 -0
- package/dist_v2/providers/nvidia.d.ts +27 -0
- package/dist_v2/providers/nvidia.js +142 -0
- package/dist_v2/providers/ollama.d.ts +15 -0
- package/dist_v2/providers/ollama.js +37 -0
- package/dist_v2/providers/openai-compat.d.ts +29 -0
- package/dist_v2/providers/openai-compat.js +239 -0
- package/dist_v2/providers/openai.d.ts +20 -0
- package/dist_v2/providers/openai.js +107 -0
- package/dist_v2/providers/openrouter.d.ts +24 -0
- package/dist_v2/providers/openrouter.js +69 -0
- package/dist_v2/safety/approval-bus.d.ts +26 -0
- package/dist_v2/safety/approval-bus.js +48 -0
- package/dist_v2/safety/audit-log.d.ts +27 -0
- package/dist_v2/safety/audit-log.js +71 -0
- package/dist_v2/safety/index.d.ts +4 -0
- package/dist_v2/safety/index.js +5 -0
- package/dist_v2/safety/policy.d.ts +32 -0
- package/dist_v2/safety/policy.js +131 -0
- package/dist_v2/safety/sandbox/bwrap.d.ts +11 -0
- package/dist_v2/safety/sandbox/bwrap.js +52 -0
- package/dist_v2/safety/sandbox/iface.d.ts +29 -0
- package/dist_v2/safety/sandbox/iface.js +8 -0
- package/dist_v2/safety/sandbox/index.d.ts +7 -0
- package/dist_v2/safety/sandbox/index.js +8 -0
- package/dist_v2/safety/sandbox/landlock.d.ts +17 -0
- package/dist_v2/safety/sandbox/landlock.js +26 -0
- package/dist_v2/safety/sandbox/noop.d.ts +12 -0
- package/dist_v2/safety/sandbox/noop.js +52 -0
- package/dist_v2/safety/sandbox/seatbelt.d.ts +11 -0
- package/dist_v2/safety/sandbox/seatbelt.js +49 -0
- package/dist_v2/safety/sandbox/select.d.ts +6 -0
- package/dist_v2/safety/sandbox/select.js +42 -0
- package/dist_v2/safety/sandbox/windows.d.ts +13 -0
- package/dist_v2/safety/sandbox/windows.js +22 -0
- package/dist_v2/skills/index.d.ts +3 -0
- package/dist_v2/skills/index.js +4 -0
- package/dist_v2/skills/loader.d.ts +38 -0
- package/dist_v2/skills/loader.js +102 -0
- package/dist_v2/skills/matcher.d.ts +14 -0
- package/dist_v2/skills/matcher.js +72 -0
- package/dist_v2/skills/runtime.d.ts +13 -0
- package/dist_v2/skills/runtime.js +40 -0
- package/dist_v2/subagents/delegator.d.ts +36 -0
- package/dist_v2/subagents/delegator.js +82 -0
- package/dist_v2/subagents/index.d.ts +2 -0
- package/dist_v2/subagents/index.js +3 -0
- package/dist_v2/subagents/pool.d.ts +18 -0
- package/dist_v2/subagents/pool.js +31 -0
- package/dist_v2/tools/browser.d.ts +27 -0
- package/dist_v2/tools/browser.js +179 -0
- package/dist_v2/tools/checkpoint.d.ts +25 -0
- package/dist_v2/tools/checkpoint.js +222 -0
- package/dist_v2/tools/cron.d.ts +32 -0
- package/dist_v2/tools/cron.js +160 -0
- package/dist_v2/tools/diff.d.ts +18 -0
- package/dist_v2/tools/diff.js +117 -0
- package/dist_v2/tools/exec.d.ts +19 -0
- package/dist_v2/tools/exec.js +49 -0
- package/dist_v2/tools/fs-edit.d.ts +11 -0
- package/dist_v2/tools/fs-edit.js +81 -0
- package/dist_v2/tools/fs-ls.d.ts +7 -0
- package/dist_v2/tools/fs-ls.js +57 -0
- package/dist_v2/tools/fs-read.d.ts +7 -0
- package/dist_v2/tools/fs-read.js +60 -0
- package/dist_v2/tools/fs-write.d.ts +8 -0
- package/dist_v2/tools/fs-write.js +46 -0
- package/dist_v2/tools/git.d.ts +8 -0
- package/dist_v2/tools/git.js +57 -0
- package/dist_v2/tools/index.d.ts +25 -0
- package/dist_v2/tools/index.js +39 -0
- package/dist_v2/tools/multimodal.d.ts +41 -0
- package/dist_v2/tools/multimodal.js +381 -0
- package/dist_v2/tools/permission.d.ts +27 -0
- package/dist_v2/tools/permission.js +43 -0
- package/dist_v2/tools/registry.d.ts +44 -0
- package/dist_v2/tools/registry.js +62 -0
- package/dist_v2/tools/search-glob.d.ts +7 -0
- package/dist_v2/tools/search-glob.js +98 -0
- package/dist_v2/tools/search-grep.d.ts +7 -0
- package/dist_v2/tools/search-grep.js +109 -0
- package/dist_v2/tools/shell.d.ts +10 -0
- package/dist_v2/tools/shell.js +76 -0
- package/dist_v2/tools/task.d.ts +8 -0
- package/dist_v2/tools/task.js +37 -0
- package/dist_v2/tui/approval.d.ts +7 -0
- package/dist_v2/tui/approval.js +55 -0
- package/dist_v2/tui/index.d.ts +4 -0
- package/dist_v2/tui/index.js +5 -0
- package/dist_v2/tui/ink/App.d.ts +39 -0
- package/dist_v2/tui/ink/App.js +206 -0
- package/dist_v2/tui/ink/components/AtFileComplete.d.ts +25 -0
- package/dist_v2/tui/ink/components/AtFileComplete.js +158 -0
- package/dist_v2/tui/ink/components/HelpOverlay.d.ts +24 -0
- package/dist_v2/tui/ink/components/HelpOverlay.js +130 -0
- package/dist_v2/tui/ink/components/InputBox.d.ts +35 -0
- package/dist_v2/tui/ink/components/InputBox.js +153 -0
- package/dist_v2/tui/ink/components/Logo.d.ts +12 -0
- package/dist_v2/tui/ink/components/Logo.js +27 -0
- package/dist_v2/tui/ink/components/ModelPicker.d.ts +26 -0
- package/dist_v2/tui/ink/components/ModelPicker.js +80 -0
- package/dist_v2/tui/ink/components/PasteCollapse.d.ts +36 -0
- package/dist_v2/tui/ink/components/PasteCollapse.js +59 -0
- package/dist_v2/tui/ink/components/StatusBar.d.ts +18 -0
- package/dist_v2/tui/ink/components/StatusBar.js +41 -0
- package/dist_v2/tui/ink/components/StreamingText.d.ts +14 -0
- package/dist_v2/tui/ink/components/StreamingText.js +11 -0
- package/dist_v2/tui/ink/components/ThinkingBlock.d.ts +13 -0
- package/dist_v2/tui/ink/components/ThinkingBlock.js +13 -0
- package/dist_v2/tui/ink/components/ToolBox.d.ts +20 -0
- package/dist_v2/tui/ink/components/ToolBox.js +63 -0
- package/dist_v2/tui/ink/components/vim-bindings.d.ts +43 -0
- package/dist_v2/tui/ink/components/vim-bindings.js +135 -0
- package/dist_v2/tui/ink/index.d.ts +39 -0
- package/dist_v2/tui/ink/index.js +47 -0
- package/dist_v2/tui/ink/use-event-projection.d.ts +51 -0
- package/dist_v2/tui/ink/use-event-projection.js +126 -0
- package/dist_v2/tui/ink/use-overlays.d.ts +24 -0
- package/dist_v2/tui/ink/use-overlays.js +50 -0
- package/dist_v2/tui/renderer.d.ts +19 -0
- package/dist_v2/tui/renderer.js +64 -0
- package/dist_v2/tui/status-bar.d.ts +12 -0
- package/dist_v2/tui/status-bar.js +16 -0
- package/dist_v2/tui/theme.d.ts +27 -0
- package/dist_v2/tui/theme.js +56 -0
- package/dist_v2/utils/json-repair.d.ts +7 -0
- package/dist_v2/utils/json-repair.js +45 -0
- package/package.json +113 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device-code OAuth flow for the Dirgha gateway.
|
|
3
|
+
*
|
|
4
|
+
* Canonical auth module. Stores tokens at `~/.dirgha/credentials.json`
|
|
5
|
+
* (0600) and drives the `/api/auth/device/*` endpoints. The older
|
|
6
|
+
* `integrations/auth.ts` is now a compatibility shim that delegates
|
|
7
|
+
* here so the billing + entitlements stack has exactly one source of
|
|
8
|
+
* truth for the active token.
|
|
9
|
+
*
|
|
10
|
+
* Callers:
|
|
11
|
+
* - Slash commands (`/login`, `/account`, `/upgrade`) via `loadToken()`.
|
|
12
|
+
* - CLI subcommands (`dirgha login`, `dirgha logout`).
|
|
13
|
+
* - Billing preflight (`preRequestCheck` reads the bearer).
|
|
14
|
+
*/
|
|
15
|
+
import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { homedir } from 'node:os';
|
|
17
|
+
import { dirname, join } from 'node:path';
|
|
18
|
+
const DEFAULT_API_BASE = 'https://api.dirgha.ai';
|
|
19
|
+
const POLL_INTERVAL_MS = 2_000;
|
|
20
|
+
const POLL_TIMEOUT_MS = 15 * 60 * 1_000;
|
|
21
|
+
const TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
|
|
22
|
+
function resolveApiBase(apiBase) {
|
|
23
|
+
const raw = apiBase ?? process.env.DIRGHA_API_BASE ?? DEFAULT_API_BASE;
|
|
24
|
+
return raw.replace(/\/+$/, '');
|
|
25
|
+
}
|
|
26
|
+
function credentialsPath() {
|
|
27
|
+
return join(homedir(), '.dirgha', 'credentials.json');
|
|
28
|
+
}
|
|
29
|
+
function redact(err) {
|
|
30
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
31
|
+
return message.replace(/Bearer\s+[\w.\-]+/gi, 'Bearer [REDACTED]');
|
|
32
|
+
}
|
|
33
|
+
export async function startDeviceAuth(apiBase) {
|
|
34
|
+
const base = resolveApiBase(apiBase);
|
|
35
|
+
let response;
|
|
36
|
+
try {
|
|
37
|
+
response = await fetch(`${base}/api/auth/device/start`, {
|
|
38
|
+
method: 'POST',
|
|
39
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
40
|
+
body: JSON.stringify({ client_id: 'dirgha-cli' }),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
throw new Error(`device/start request failed: ${redact(err)}`);
|
|
45
|
+
}
|
|
46
|
+
if (!response.ok) {
|
|
47
|
+
throw new Error(`device/start failed: HTTP ${response.status}`);
|
|
48
|
+
}
|
|
49
|
+
const data = (await response.json());
|
|
50
|
+
const deviceCode = data.device_code;
|
|
51
|
+
const userCode = data.user_code;
|
|
52
|
+
const verifyUri = data.verification_uri ?? data.verification_url;
|
|
53
|
+
if (!deviceCode || !userCode || !verifyUri) {
|
|
54
|
+
throw new Error('device/start returned malformed payload');
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
deviceCode,
|
|
58
|
+
userCode,
|
|
59
|
+
verifyUri,
|
|
60
|
+
interval: (data.interval ?? 5) * 1_000,
|
|
61
|
+
expiresIn: (data.expires_in ?? 900) * 1_000,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export async function pollDeviceAuth(deviceCode, apiBase, opts = {}) {
|
|
65
|
+
const base = resolveApiBase(apiBase);
|
|
66
|
+
const intervalMs = opts.intervalMs ?? POLL_INTERVAL_MS;
|
|
67
|
+
const deadline = Date.now() + (opts.timeoutMs ?? POLL_TIMEOUT_MS);
|
|
68
|
+
while (Date.now() < deadline) {
|
|
69
|
+
let response;
|
|
70
|
+
try {
|
|
71
|
+
response = await fetch(`${base}/api/auth/device/poll`, {
|
|
72
|
+
method: 'POST',
|
|
73
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
74
|
+
body: JSON.stringify({ device_code: deviceCode }),
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
// Network blip — keep polling
|
|
79
|
+
await sleep(intervalMs);
|
|
80
|
+
if (Date.now() >= deadline)
|
|
81
|
+
throw new Error(`device/poll network error: ${redact(err)}`);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (response.status === 410)
|
|
85
|
+
throw new Error('device code expired');
|
|
86
|
+
if (response.status === 403)
|
|
87
|
+
throw new Error('device code denied');
|
|
88
|
+
if (response.ok) {
|
|
89
|
+
const data = (await response.json());
|
|
90
|
+
if (data.status === 'authorized' && data.token) {
|
|
91
|
+
return {
|
|
92
|
+
token: data.token,
|
|
93
|
+
userId: data.user?.id ?? 'unknown',
|
|
94
|
+
email: data.user?.email ?? 'unknown',
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
if (data.status === 'denied')
|
|
98
|
+
throw new Error('device code denied');
|
|
99
|
+
if (data.status === 'expired')
|
|
100
|
+
throw new Error('device code expired');
|
|
101
|
+
}
|
|
102
|
+
else if (response.status !== 202 && response.status !== 425 && response.status !== 428) {
|
|
103
|
+
throw new Error(`device/poll failed: HTTP ${response.status}`);
|
|
104
|
+
}
|
|
105
|
+
await sleep(intervalMs);
|
|
106
|
+
}
|
|
107
|
+
throw new Error('device/poll timed out');
|
|
108
|
+
}
|
|
109
|
+
export async function saveToken(token, userId, email) {
|
|
110
|
+
const path = credentialsPath();
|
|
111
|
+
await mkdir(dirname(path), { recursive: true });
|
|
112
|
+
const payload = {
|
|
113
|
+
token,
|
|
114
|
+
userId,
|
|
115
|
+
email,
|
|
116
|
+
expiresAt: new Date(Date.now() + TOKEN_TTL_MS).toISOString(),
|
|
117
|
+
};
|
|
118
|
+
await writeFile(path, JSON.stringify(payload, null, 2), 'utf8');
|
|
119
|
+
try {
|
|
120
|
+
await chmod(path, 0o600);
|
|
121
|
+
}
|
|
122
|
+
catch { /* chmod may fail on Windows */ }
|
|
123
|
+
}
|
|
124
|
+
export async function loadToken() {
|
|
125
|
+
const path = credentialsPath();
|
|
126
|
+
const text = await readFile(path, 'utf8').catch(() => undefined);
|
|
127
|
+
if (!text)
|
|
128
|
+
return null;
|
|
129
|
+
try {
|
|
130
|
+
const parsed = JSON.parse(text);
|
|
131
|
+
if (!parsed.token || !parsed.expiresAt)
|
|
132
|
+
return null;
|
|
133
|
+
if (Date.parse(parsed.expiresAt) <= Date.now())
|
|
134
|
+
return null;
|
|
135
|
+
return parsed;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export async function clearToken() {
|
|
142
|
+
const path = credentialsPath();
|
|
143
|
+
await unlink(path).catch(() => undefined);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* One-shot migration from the legacy `~/.dirgha/auth.json` format
|
|
147
|
+
* (`integrations/auth.ts`) to the canonical `credentials.json`. Safe to
|
|
148
|
+
* call on every CLI start — returns `false` fast when nothing to do.
|
|
149
|
+
*
|
|
150
|
+
* Logs a single line to stderr on a successful move. Silent on no-op.
|
|
151
|
+
*/
|
|
152
|
+
export async function migrateLegacyAuth() {
|
|
153
|
+
const legacyPath = join(homedir(), '.dirgha', 'auth.json');
|
|
154
|
+
const targetPath = credentialsPath();
|
|
155
|
+
const legacyInfo = await stat(legacyPath).catch(() => undefined);
|
|
156
|
+
if (!legacyInfo || !legacyInfo.isFile() || legacyInfo.size === 0)
|
|
157
|
+
return false;
|
|
158
|
+
const targetInfo = await stat(targetPath).catch(() => undefined);
|
|
159
|
+
if (targetInfo && targetInfo.size > 0)
|
|
160
|
+
return false;
|
|
161
|
+
const text = await readFile(legacyPath, 'utf8').catch(() => undefined);
|
|
162
|
+
if (!text)
|
|
163
|
+
return false;
|
|
164
|
+
let parsed;
|
|
165
|
+
try {
|
|
166
|
+
parsed = JSON.parse(text);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
if (!parsed || !parsed.jwt)
|
|
172
|
+
return false;
|
|
173
|
+
await mkdir(dirname(targetPath), { recursive: true });
|
|
174
|
+
const payload = {
|
|
175
|
+
token: parsed.jwt,
|
|
176
|
+
userId: parsed.userId ?? 'unknown',
|
|
177
|
+
email: 'unknown',
|
|
178
|
+
expiresAt: parsed.expiresAt ?? new Date(Date.now() + TOKEN_TTL_MS).toISOString(),
|
|
179
|
+
};
|
|
180
|
+
await writeFile(targetPath, JSON.stringify(payload, null, 2), 'utf8');
|
|
181
|
+
try {
|
|
182
|
+
await chmod(targetPath, 0o600);
|
|
183
|
+
}
|
|
184
|
+
catch { /* non-POSIX */ }
|
|
185
|
+
await rename(legacyPath, `${legacyPath}.migrated`).catch(() => undefined);
|
|
186
|
+
process.stderr.write('[auth] migrated legacy credentials\n');
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
function sleep(ms) {
|
|
190
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=device-auth.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entitlements check. Pulls the user's tier + feature flags from the
|
|
3
|
+
* gateway. When a gated feature is requested, the caller invokes
|
|
4
|
+
* requireFeature() which throws a clean error that the CLI turns into
|
|
5
|
+
* an upgrade prompt.
|
|
6
|
+
*/
|
|
7
|
+
export type Tier = 'free' | 'pro' | 'team' | 'enterprise';
|
|
8
|
+
export type Feature = 'deploy' | 'codeRegister' | 'privateSkills' | 'teamsBucky' | 'customSandbox' | 'fleet' | 'tripleshot';
|
|
9
|
+
export interface Entitlements {
|
|
10
|
+
tier: Tier;
|
|
11
|
+
features: Record<Feature, boolean>;
|
|
12
|
+
limits: {
|
|
13
|
+
dailyDeploys: number;
|
|
14
|
+
monthlyBuckyHours: number;
|
|
15
|
+
maxSubagents: number;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export interface EntitlementsClient {
|
|
19
|
+
get(token: string): Promise<Entitlements>;
|
|
20
|
+
requireFeature(token: string, feature: Feature): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Low-level feature check: returns true/false without throwing. Used by
|
|
24
|
+
* slash commands that want to show/hide capability (e.g. `/fleet`,
|
|
25
|
+
* `/tripleshot`) rather than hard-block.
|
|
26
|
+
*/
|
|
27
|
+
export declare function checkEntitlement(token: string, feature: Feature, opts?: {
|
|
28
|
+
baseUrl?: string;
|
|
29
|
+
}): Promise<boolean>;
|
|
30
|
+
export interface EntitlementsClientOptions {
|
|
31
|
+
baseUrl?: string;
|
|
32
|
+
upgradeUrl?: string;
|
|
33
|
+
}
|
|
34
|
+
export declare function createEntitlementsClient(opts?: EntitlementsClientOptions): EntitlementsClient;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entitlements check. Pulls the user's tier + feature flags from the
|
|
3
|
+
* gateway. When a gated feature is requested, the caller invokes
|
|
4
|
+
* requireFeature() which throws a clean error that the CLI turns into
|
|
5
|
+
* an upgrade prompt.
|
|
6
|
+
*/
|
|
7
|
+
import { jsonRequest } from './http.js';
|
|
8
|
+
/**
|
|
9
|
+
* Low-level feature check: returns true/false without throwing. Used by
|
|
10
|
+
* slash commands that want to show/hide capability (e.g. `/fleet`,
|
|
11
|
+
* `/tripleshot`) rather than hard-block.
|
|
12
|
+
*/
|
|
13
|
+
export async function checkEntitlement(token, feature, opts = {}) {
|
|
14
|
+
const baseUrl = opts.baseUrl ?? process.env.DIRGHA_API_BASE ?? process.env.DIRGHA_GATEWAY_URL ?? 'https://api.dirgha.ai';
|
|
15
|
+
try {
|
|
16
|
+
const entitlements = await jsonRequest({
|
|
17
|
+
baseUrl,
|
|
18
|
+
path: '/api/billing/entitlements',
|
|
19
|
+
token,
|
|
20
|
+
timeoutMs: 5_000,
|
|
21
|
+
});
|
|
22
|
+
return entitlements.features[feature] === true;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function createEntitlementsClient(opts = {}) {
|
|
29
|
+
const baseUrl = opts.baseUrl ?? process.env.DIRGHA_GATEWAY_URL ?? 'https://api.dirgha.ai';
|
|
30
|
+
const upgradeUrl = opts.upgradeUrl ?? 'https://dirgha.ai/upgrade';
|
|
31
|
+
return {
|
|
32
|
+
async get(token) {
|
|
33
|
+
return jsonRequest({ baseUrl, path: '/api/billing/entitlements', token });
|
|
34
|
+
},
|
|
35
|
+
async requireFeature(token, feature) {
|
|
36
|
+
const entitlements = await this.get(token);
|
|
37
|
+
if (!entitlements.features[feature]) {
|
|
38
|
+
throw new Error(`Feature "${feature}" requires an upgrade. Visit ${upgradeUrl} to unlock it on tier: ${entitlements.tier}.`);
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
//# sourceMappingURL=entitlements.js.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared HTTP helper for integration clients. Adds Bearer auth, typed
|
|
3
|
+
* JSON parsing, and consistent error surfaces.
|
|
4
|
+
*/
|
|
5
|
+
export declare class IntegrationError extends Error {
|
|
6
|
+
readonly status?: number | undefined;
|
|
7
|
+
readonly body?: unknown | undefined;
|
|
8
|
+
constructor(message: string, status?: number | undefined, body?: unknown | undefined);
|
|
9
|
+
}
|
|
10
|
+
export interface RequestOptions {
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
path: string;
|
|
13
|
+
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';
|
|
14
|
+
token?: string;
|
|
15
|
+
body?: unknown;
|
|
16
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
17
|
+
headers?: Record<string, string>;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
export declare function jsonRequest<T>(opts: RequestOptions): Promise<T>;
|
|
22
|
+
export declare function sseRequest(opts: RequestOptions): Promise<AsyncIterable<string>>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared HTTP helper for integration clients. Adds Bearer auth, typed
|
|
3
|
+
* JSON parsing, and consistent error surfaces.
|
|
4
|
+
*/
|
|
5
|
+
export class IntegrationError extends Error {
|
|
6
|
+
status;
|
|
7
|
+
body;
|
|
8
|
+
constructor(message, status, body) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.body = body;
|
|
12
|
+
this.name = 'IntegrationError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export async function jsonRequest(opts) {
|
|
16
|
+
const url = buildUrl(opts.baseUrl, opts.path, opts.query);
|
|
17
|
+
const controller = new AbortController();
|
|
18
|
+
const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 30_000);
|
|
19
|
+
if (opts.signal)
|
|
20
|
+
opts.signal.addEventListener('abort', () => controller.abort(), { once: true });
|
|
21
|
+
const headers = {
|
|
22
|
+
Accept: 'application/json',
|
|
23
|
+
...opts.headers,
|
|
24
|
+
};
|
|
25
|
+
if (opts.token)
|
|
26
|
+
headers.Authorization = `Bearer ${opts.token}`;
|
|
27
|
+
if (opts.body !== undefined)
|
|
28
|
+
headers['Content-Type'] = 'application/json';
|
|
29
|
+
let response;
|
|
30
|
+
try {
|
|
31
|
+
response = await fetch(url, {
|
|
32
|
+
method: opts.method ?? 'GET',
|
|
33
|
+
headers,
|
|
34
|
+
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
|
|
35
|
+
signal: controller.signal,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
throw new IntegrationError(`Request failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
41
|
+
}
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
if (!response.ok) {
|
|
44
|
+
const body = await safeJson(response);
|
|
45
|
+
throw new IntegrationError(`HTTP ${response.status} ${response.statusText}`, response.status, body);
|
|
46
|
+
}
|
|
47
|
+
return (await response.json());
|
|
48
|
+
}
|
|
49
|
+
export async function sseRequest(opts) {
|
|
50
|
+
const url = buildUrl(opts.baseUrl, opts.path, opts.query);
|
|
51
|
+
const headers = {
|
|
52
|
+
Accept: 'text/event-stream',
|
|
53
|
+
...opts.headers,
|
|
54
|
+
};
|
|
55
|
+
if (opts.token)
|
|
56
|
+
headers.Authorization = `Bearer ${opts.token}`;
|
|
57
|
+
if (opts.body !== undefined)
|
|
58
|
+
headers['Content-Type'] = 'application/json';
|
|
59
|
+
const response = await fetch(url, {
|
|
60
|
+
method: opts.method ?? 'GET',
|
|
61
|
+
headers,
|
|
62
|
+
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
|
|
63
|
+
signal: opts.signal,
|
|
64
|
+
});
|
|
65
|
+
if (!response.ok) {
|
|
66
|
+
throw new IntegrationError(`HTTP ${response.status} ${response.statusText}`, response.status);
|
|
67
|
+
}
|
|
68
|
+
if (!response.body)
|
|
69
|
+
throw new IntegrationError('No response body on SSE');
|
|
70
|
+
return (async function* sseIterator() {
|
|
71
|
+
const reader = response.body.getReader();
|
|
72
|
+
const decoder = new TextDecoder('utf-8');
|
|
73
|
+
let buffer = '';
|
|
74
|
+
for (;;) {
|
|
75
|
+
const { value, done } = await reader.read();
|
|
76
|
+
if (done)
|
|
77
|
+
break;
|
|
78
|
+
buffer += decoder.decode(value, { stream: true });
|
|
79
|
+
let nl;
|
|
80
|
+
while ((nl = buffer.indexOf('\n')) >= 0) {
|
|
81
|
+
const raw = buffer.slice(0, nl);
|
|
82
|
+
buffer = buffer.slice(nl + 1);
|
|
83
|
+
const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
|
|
84
|
+
if (line.startsWith('data:'))
|
|
85
|
+
yield line.slice(5).trim();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
})();
|
|
89
|
+
}
|
|
90
|
+
function buildUrl(base, path, query) {
|
|
91
|
+
const url = new URL(path.startsWith('http') ? path : `${base.replace(/\/+$/, '')}${path.startsWith('/') ? path : `/${path}`}`);
|
|
92
|
+
if (query) {
|
|
93
|
+
for (const [k, v] of Object.entries(query)) {
|
|
94
|
+
if (v === undefined)
|
|
95
|
+
continue;
|
|
96
|
+
url.searchParams.set(k, String(v));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return url.toString();
|
|
100
|
+
}
|
|
101
|
+
async function safeJson(r) {
|
|
102
|
+
try {
|
|
103
|
+
return await r.json();
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
try {
|
|
107
|
+
return await r.text();
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=http.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './device-auth.js';
|
|
2
|
+
export * from './billing.js';
|
|
3
|
+
export * from './entitlements.js';
|
|
4
|
+
export * from './http.js';
|
|
5
|
+
export * from './bucky-client.js';
|
|
6
|
+
export * from './arniko-client.js';
|
|
7
|
+
export * from './deploy-client.js';
|
|
8
|
+
export * from './auth.js';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Canonical auth (device-code flow) comes first.
|
|
2
|
+
export * from './device-auth.js';
|
|
3
|
+
// Billing + entitlements consume the canonical token.
|
|
4
|
+
export * from './billing.js';
|
|
5
|
+
export * from './entitlements.js';
|
|
6
|
+
// HTTP helpers + service clients.
|
|
7
|
+
export * from './http.js';
|
|
8
|
+
export * from './bucky-client.js';
|
|
9
|
+
export * from './arniko-client.js';
|
|
10
|
+
export * from './deploy-client.js';
|
|
11
|
+
// @deprecated — compatibility shim delegating to device-auth.
|
|
12
|
+
// Re-exported last so name collisions resolve in favour of the
|
|
13
|
+
// canonical implementations above.
|
|
14
|
+
export * from './auth.js';
|
|
15
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost tracker. Accumulates token usage by session and translates it to
|
|
3
|
+
* USD via the price catalogue. Supports per-session budgets that
|
|
4
|
+
* report when the budget is close or exceeded; enforcement is the
|
|
5
|
+
* caller's responsibility (typically the agent loop).
|
|
6
|
+
*/
|
|
7
|
+
import type { UsageTotal } from '../kernel/types.js';
|
|
8
|
+
export interface CostRecord {
|
|
9
|
+
sessionId: string;
|
|
10
|
+
provider: string;
|
|
11
|
+
model: string;
|
|
12
|
+
inputTokens: number;
|
|
13
|
+
outputTokens: number;
|
|
14
|
+
cachedTokens: number;
|
|
15
|
+
costUsd: number;
|
|
16
|
+
ts: string;
|
|
17
|
+
}
|
|
18
|
+
export interface CostTracker {
|
|
19
|
+
record(provider: string, model: string, usage: UsageTotal, sessionId: string): CostRecord;
|
|
20
|
+
sessionTotal(sessionId: string): UsageTotal;
|
|
21
|
+
dailyTotal(date?: string): UsageTotal;
|
|
22
|
+
budget(sessionId: string, budgetUsd: number): {
|
|
23
|
+
withinBudget: boolean;
|
|
24
|
+
used: number;
|
|
25
|
+
remaining: number;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export declare function createCostTracker(): CostTracker;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost tracker. Accumulates token usage by session and translates it to
|
|
3
|
+
* USD via the price catalogue. Supports per-session budgets that
|
|
4
|
+
* report when the budget is close or exceeded; enforcement is the
|
|
5
|
+
* caller's responsibility (typically the agent loop).
|
|
6
|
+
*/
|
|
7
|
+
import { findPrice } from './prices.js';
|
|
8
|
+
export function createCostTracker() {
|
|
9
|
+
const records = [];
|
|
10
|
+
return {
|
|
11
|
+
record(provider, model, usage, sessionId) {
|
|
12
|
+
const price = findPrice(provider, model);
|
|
13
|
+
const costUsd = price
|
|
14
|
+
? (usage.inputTokens / 1_000_000) * price.inputPerM
|
|
15
|
+
+ (usage.outputTokens / 1_000_000) * price.outputPerM
|
|
16
|
+
+ (usage.cachedTokens / 1_000_000) * (price.cachedInputPerM ?? 0)
|
|
17
|
+
: 0;
|
|
18
|
+
const rec = {
|
|
19
|
+
sessionId,
|
|
20
|
+
provider,
|
|
21
|
+
model,
|
|
22
|
+
inputTokens: usage.inputTokens,
|
|
23
|
+
outputTokens: usage.outputTokens,
|
|
24
|
+
cachedTokens: usage.cachedTokens,
|
|
25
|
+
costUsd,
|
|
26
|
+
ts: new Date().toISOString(),
|
|
27
|
+
};
|
|
28
|
+
records.push(rec);
|
|
29
|
+
return rec;
|
|
30
|
+
},
|
|
31
|
+
sessionTotal(sessionId) {
|
|
32
|
+
return accumulate(records.filter(r => r.sessionId === sessionId));
|
|
33
|
+
},
|
|
34
|
+
dailyTotal(date) {
|
|
35
|
+
const prefix = date ?? new Date().toISOString().slice(0, 10);
|
|
36
|
+
return accumulate(records.filter(r => r.ts.startsWith(prefix)));
|
|
37
|
+
},
|
|
38
|
+
budget(sessionId, budgetUsd) {
|
|
39
|
+
const total = this.sessionTotal(sessionId);
|
|
40
|
+
return {
|
|
41
|
+
used: total.costUsd,
|
|
42
|
+
remaining: Math.max(0, budgetUsd - total.costUsd),
|
|
43
|
+
withinBudget: total.costUsd <= budgetUsd,
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function accumulate(records) {
|
|
49
|
+
const totals = { inputTokens: 0, outputTokens: 0, cachedTokens: 0, costUsd: 0 };
|
|
50
|
+
for (const r of records) {
|
|
51
|
+
totals.inputTokens += r.inputTokens;
|
|
52
|
+
totals.outputTokens += r.outputTokens;
|
|
53
|
+
totals.cachedTokens += r.cachedTokens;
|
|
54
|
+
totals.costUsd += r.costUsd;
|
|
55
|
+
}
|
|
56
|
+
return totals;
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=cost.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error classifier. Maps any provider error into a structured
|
|
3
|
+
* ClassifiedError with actionable recovery hints. The agent loop and
|
|
4
|
+
* retry policy consult this — no string matching anywhere else.
|
|
5
|
+
*/
|
|
6
|
+
import type { ErrorClassifier } from '../kernel/types.js';
|
|
7
|
+
export type ErrorReason = 'auth' | 'billing' | 'rate_limit' | 'overloaded' | 'timeout' | 'network' | 'context_overflow' | 'model_not_found' | 'format_error' | 'tool_schema' | 'content_filter' | 'unknown';
|
|
8
|
+
export declare function createErrorClassifier(): ErrorClassifier;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error classifier. Maps any provider error into a structured
|
|
3
|
+
* ClassifiedError with actionable recovery hints. The agent loop and
|
|
4
|
+
* retry policy consult this — no string matching anywhere else.
|
|
5
|
+
*/
|
|
6
|
+
import { ProviderError } from '../providers/iface.js';
|
|
7
|
+
export function createErrorClassifier() {
|
|
8
|
+
return {
|
|
9
|
+
classify(err, provider, model) {
|
|
10
|
+
const { reason, backoffMs } = diagnose(err);
|
|
11
|
+
void provider;
|
|
12
|
+
void model;
|
|
13
|
+
return {
|
|
14
|
+
reason,
|
|
15
|
+
retryable: isRetryable(reason),
|
|
16
|
+
backoffMs,
|
|
17
|
+
shouldFallback: shouldFallback(reason),
|
|
18
|
+
};
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function diagnose(err) {
|
|
23
|
+
if (err instanceof ProviderError) {
|
|
24
|
+
const status = err.status ?? 0;
|
|
25
|
+
if (status === 401 || status === 403)
|
|
26
|
+
return { reason: 'auth' };
|
|
27
|
+
if (status === 402)
|
|
28
|
+
return { reason: 'billing' };
|
|
29
|
+
if (status === 404)
|
|
30
|
+
return { reason: 'model_not_found' };
|
|
31
|
+
if (status === 408)
|
|
32
|
+
return { reason: 'timeout', backoffMs: 1000 };
|
|
33
|
+
if (status === 413)
|
|
34
|
+
return { reason: 'context_overflow' };
|
|
35
|
+
if (status === 415 || status === 422)
|
|
36
|
+
return { reason: 'format_error' };
|
|
37
|
+
if (status === 429)
|
|
38
|
+
return { reason: 'rate_limit', backoffMs: 4000 };
|
|
39
|
+
if (status === 503 || status === 529)
|
|
40
|
+
return { reason: 'overloaded', backoffMs: 3000 };
|
|
41
|
+
if (status >= 500)
|
|
42
|
+
return { reason: 'overloaded', backoffMs: 2000 };
|
|
43
|
+
const msg = err.message.toLowerCase();
|
|
44
|
+
if (msg.includes('content filter') || msg.includes('content policy'))
|
|
45
|
+
return { reason: 'content_filter' };
|
|
46
|
+
if (msg.includes('tool') && msg.includes('schema'))
|
|
47
|
+
return { reason: 'tool_schema' };
|
|
48
|
+
if (msg.includes('context length'))
|
|
49
|
+
return { reason: 'context_overflow' };
|
|
50
|
+
return { reason: 'unknown' };
|
|
51
|
+
}
|
|
52
|
+
const message = err instanceof Error ? err.message.toLowerCase() : String(err).toLowerCase();
|
|
53
|
+
if (message.includes('timed out') || message.includes('abort'))
|
|
54
|
+
return { reason: 'timeout', backoffMs: 1000 };
|
|
55
|
+
if (message.includes('econnrefused') || message.includes('enotfound') || message.includes('network'))
|
|
56
|
+
return { reason: 'network', backoffMs: 1000 };
|
|
57
|
+
return { reason: 'unknown' };
|
|
58
|
+
}
|
|
59
|
+
function isRetryable(reason) {
|
|
60
|
+
return reason === 'rate_limit'
|
|
61
|
+
|| reason === 'overloaded'
|
|
62
|
+
|| reason === 'timeout'
|
|
63
|
+
|| reason === 'network';
|
|
64
|
+
}
|
|
65
|
+
function shouldFallback(reason) {
|
|
66
|
+
return reason === 'rate_limit'
|
|
67
|
+
|| reason === 'overloaded'
|
|
68
|
+
|| reason === 'model_not_found'
|
|
69
|
+
|| reason === 'billing';
|
|
70
|
+
}
|
|
71
|
+
//# sourceMappingURL=error-classifier.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Price catalogue. USD per million tokens. Update quarterly.
|
|
3
|
+
* When a model is not listed, the cost tracker falls back to 0.
|
|
4
|
+
*/
|
|
5
|
+
export interface PricePoint {
|
|
6
|
+
provider: string;
|
|
7
|
+
model: string;
|
|
8
|
+
inputPerM: number;
|
|
9
|
+
outputPerM: number;
|
|
10
|
+
cachedInputPerM?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare const PRICES: PricePoint[];
|
|
13
|
+
export declare function findPrice(provider: string, model: string): PricePoint | undefined;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Price catalogue. USD per million tokens. Update quarterly.
|
|
3
|
+
* When a model is not listed, the cost tracker falls back to 0.
|
|
4
|
+
*/
|
|
5
|
+
// Kept in sync with apps/agent-os/src/lib/models.ts (2026-04-24 refresh).
|
|
6
|
+
// Only lists models verified live on prod. Removed Kimi K2.5 Turbo, Qwen Coder/235B,
|
|
7
|
+
// MiniMax M2/M2.7, DeepSeek V3.1/R1, GLM 5.1 — NIM returns 404/410 for these.
|
|
8
|
+
export const PRICES = [
|
|
9
|
+
{ provider: 'anthropic', model: 'claude-opus-4-7', inputPerM: 15, outputPerM: 75, cachedInputPerM: 1.5 },
|
|
10
|
+
{ provider: 'anthropic', model: 'claude-sonnet-4-6', inputPerM: 3, outputPerM: 15, cachedInputPerM: 0.3 },
|
|
11
|
+
{ provider: 'anthropic', model: 'claude-haiku-4-5', inputPerM: 0.8, outputPerM: 4, cachedInputPerM: 0.08 },
|
|
12
|
+
{ provider: 'openai', model: 'gpt-5', inputPerM: 10, outputPerM: 30 },
|
|
13
|
+
{ provider: 'openai', model: 'gpt-5-mini', inputPerM: 0.5, outputPerM: 2 },
|
|
14
|
+
{ provider: 'openai', model: 'gpt-4o-mini', inputPerM: 0.15, outputPerM: 0.6 },
|
|
15
|
+
{ provider: 'openai', model: 'o1', inputPerM: 15, outputPerM: 60 },
|
|
16
|
+
{ provider: 'gemini', model: 'gemini-2.5-pro', inputPerM: 1.25, outputPerM: 5 },
|
|
17
|
+
{ provider: 'gemini', model: 'gemini-2.5-flash', inputPerM: 0.075, outputPerM: 0.3 },
|
|
18
|
+
{ provider: 'nvidia', model: 'moonshotai/kimi-k2-instruct', inputPerM: 0.15, outputPerM: 0.60 },
|
|
19
|
+
{ provider: 'nvidia', model: 'qwen/qwen3-next-80b-a3b-instruct', inputPerM: 0.08, outputPerM: 0.30 },
|
|
20
|
+
{ provider: 'nvidia', model: 'meta/llama-3.3-70b-instruct', inputPerM: 0.20, outputPerM: 0.80 },
|
|
21
|
+
{ provider: 'openrouter', model: 'inclusionai/ling-2.6-1t:free', inputPerM: 0, outputPerM: 0 },
|
|
22
|
+
];
|
|
23
|
+
export function findPrice(provider, model) {
|
|
24
|
+
return PRICES.find(p => p.provider === provider && p.model === model);
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=prices.js.map
|