@neuralnomads/codenomad-dev 0.20.1-dev-20261008-027f5094 → 0.20.1-dev-20261009-43165435

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +3 -1
  2. package/dist/api-types.js +1 -0
  3. package/dist/api-types.js.map +1 -1
  4. package/dist/server/routes/pending-requests.js +2 -1
  5. package/dist/server/routes/pending-requests.js.map +1 -1
  6. package/dist/server/routes/usage.js +21 -1
  7. package/dist/server/routes/usage.js.map +1 -1
  8. package/dist/server/routes/usage.test.js +61 -3
  9. package/dist/server/routes/usage.test.js.map +1 -1
  10. package/dist/usage/claude-credential.js +82 -0
  11. package/dist/usage/claude-credential.js.map +1 -0
  12. package/dist/usage/claude-credential.test.js +63 -0
  13. package/dist/usage/claude-credential.test.js.map +1 -0
  14. package/dist/usage/native-codex.js +2 -5
  15. package/dist/usage/native-codex.js.map +1 -1
  16. package/dist/usage/native-credentials.js +38 -0
  17. package/dist/usage/native-credentials.js.map +1 -0
  18. package/dist/usage/native-credentials.test.js +58 -0
  19. package/dist/usage/native-credentials.test.js.map +1 -0
  20. package/dist/usage/providers/api-key.js +10 -10
  21. package/dist/usage/providers/api-key.js.map +1 -1
  22. package/dist/usage/providers/api-key.test.js +5 -4
  23. package/dist/usage/providers/api-key.test.js.map +1 -1
  24. package/dist/usage/providers/credits.js +148 -0
  25. package/dist/usage/providers/credits.js.map +1 -0
  26. package/dist/usage/providers/credits.test.js +88 -0
  27. package/dist/usage/providers/credits.test.js.map +1 -0
  28. package/dist/usage/providers/extra.js +76 -70
  29. package/dist/usage/providers/extra.js.map +1 -1
  30. package/dist/usage/providers/extra.test.js +10 -2
  31. package/dist/usage/providers/extra.test.js.map +1 -1
  32. package/dist/usage/providers/minimax.js +2 -2
  33. package/dist/usage/providers/minimax.js.map +1 -1
  34. package/dist/usage/providers/oauth.js +12 -5
  35. package/dist/usage/providers/oauth.js.map +1 -1
  36. package/dist/usage/providers/oauth.test.js +5 -2
  37. package/dist/usage/providers/oauth.test.js.map +1 -1
  38. package/dist/usage/providers/special.test.js +2 -1
  39. package/dist/usage/providers/special.test.js.map +1 -1
  40. package/dist/usage/providers/xai.js +2 -2
  41. package/dist/usage/providers/xai.js.map +1 -1
  42. package/dist/usage/providers/xai.test.js +3 -2
  43. package/dist/usage/providers/xai.test.js.map +1 -1
  44. package/dist/usage/service.js +28 -15
  45. package/dist/usage/service.js.map +1 -1
  46. package/dist/usage/service.test.js +79 -7
  47. package/dist/usage/service.test.js.map +1 -1
  48. package/dist/usage/shared.js +5 -6
  49. package/dist/usage/shared.js.map +1 -1
  50. package/dist/usage/shared.test.js +4 -4
  51. package/dist/usage/shared.test.js.map +1 -1
  52. package/dist/usage/types.js.map +1 -1
  53. package/package.json +1 -1
  54. package/public/assets/App-CUreRG6q.js +107 -0
  55. package/public/assets/App-CUreRG6q.js.map +1 -0
  56. package/public/assets/{FilesPanel-DdwOUMB-.js → FilesPanel-DEwHSqQm.js} +2 -2
  57. package/public/assets/{FilesPanel-DdwOUMB-.js.map → FilesPanel-DEwHSqQm.js.map} +1 -1
  58. package/public/assets/StatusTab-Di-riiuX.js +2 -0
  59. package/public/assets/StatusTab-Di-riiuX.js.map +1 -0
  60. package/public/assets/{bundle-full-B6llhXbi.js → bundle-full-_-MEJY-w.js} +2 -2
  61. package/public/assets/{bundle-full-B6llhXbi.js.map → bundle-full-_-MEJY-w.js.map} +1 -1
  62. package/public/assets/{client-state-FIEAaaVx.js → client-state-CPEkpB2r.js} +2 -2
  63. package/public/assets/{client-state-FIEAaaVx.js.map → client-state-CPEkpB2r.js.map} +1 -1
  64. package/public/assets/{diff-viewer-CUpTjTeD.js → diff-viewer-CRaaZqVl.js} +2 -2
  65. package/public/assets/{diff-viewer-CUpTjTeD.js.map → diff-viewer-CRaaZqVl.js.map} +1 -1
  66. package/public/assets/{index-COifbS0Z.js → index-BMkxSdGX.js} +2 -2
  67. package/public/assets/index-BMkxSdGX.js.map +1 -0
  68. package/public/assets/{index-CWEGmOqN.js → index-BOug-GtB.js} +2 -2
  69. package/public/assets/index-BOug-GtB.js.map +1 -0
  70. package/public/assets/{index-DFlVpZho.js → index-BUOehX2p.js} +2 -2
  71. package/public/assets/{index-DFlVpZho.js.map → index-BUOehX2p.js.map} +1 -1
  72. package/public/assets/{index-BvEbvmim.js → index-C5s1G5fZ.js} +2 -2
  73. package/public/assets/index-C5s1G5fZ.js.map +1 -0
  74. package/public/assets/{index-D-6KUEZq.js → index-CRyXGv_I.js} +2 -2
  75. package/public/assets/index-CRyXGv_I.js.map +1 -0
  76. package/public/assets/{index-DhhLKUaB.js → index-DKCJsUXW.js} +2 -2
  77. package/public/assets/index-DKCJsUXW.js.map +1 -0
  78. package/public/assets/{index-Di1ASRtw.js → index-DKxNaxHd.js} +3 -3
  79. package/public/assets/index-DKxNaxHd.js.map +1 -0
  80. package/public/assets/{index-CjgCyxpO.js → index-DcSSbI-e.js} +2 -2
  81. package/public/assets/index-DcSSbI-e.js.map +1 -0
  82. package/public/assets/{index-hsSbaGZ2.js → index-DeYxSVKf.js} +2 -2
  83. package/public/assets/index-DeYxSVKf.js.map +1 -0
  84. package/public/assets/{index-DUMhzcnf.js → index-DyZCX8RD.js} +2 -2
  85. package/public/assets/{index-DUMhzcnf.js.map → index-DyZCX8RD.js.map} +1 -1
  86. package/public/assets/{index-Dq6dKGRs.js → index-hGc5h-HY.js} +2 -2
  87. package/public/assets/{index-Dq6dKGRs.js.map → index-hGc5h-HY.js.map} +1 -1
  88. package/public/assets/{index-4cJ939YX.js → index-yrNn4LeR.js} +2 -2
  89. package/public/assets/index-yrNn4LeR.js.map +1 -0
  90. package/public/assets/{loading-CiXS3zDp.js → loading-AYTswBvd.js} +2 -2
  91. package/public/assets/{loading-CiXS3zDp.js.map → loading-AYTswBvd.js.map} +1 -1
  92. package/public/assets/{main-mPloHnyu.js → main-CtdNkoGE.js} +22 -22
  93. package/public/assets/main-CtdNkoGE.js.map +1 -0
  94. package/public/assets/{markdown-CaIB2onp.js → markdown-CG-E8WYP.js} +4 -4
  95. package/public/assets/{markdown-CaIB2onp.js.map → markdown-CG-E8WYP.js.map} +1 -1
  96. package/public/assets/{startup-state-settings-card-BrRiV_nS.js → startup-state-settings-card-CqK_xq42.js} +2 -2
  97. package/public/assets/{startup-state-settings-card-BrRiV_nS.js.map → startup-state-settings-card-CqK_xq42.js.map} +1 -1
  98. package/public/assets/{terminal-square-uGLAMZeY.js → terminal-square-C7asuyRM.js} +2 -2
  99. package/public/assets/{terminal-square-uGLAMZeY.js.map → terminal-square-C7asuyRM.js.map} +1 -1
  100. package/public/assets/{tool-call-B0ZUhQFB.js → tool-call-BVwYrEtd.js} +4 -4
  101. package/public/assets/{tool-call-B0ZUhQFB.js.map → tool-call-BVwYrEtd.js.map} +1 -1
  102. package/public/assets/{unified-picker-CVF2hvM4.js → unified-picker-e7xIK0Ta.js} +2 -2
  103. package/public/assets/{unified-picker-CVF2hvM4.js.map → unified-picker-e7xIK0Ta.js.map} +1 -1
  104. package/public/index.html +2 -2
  105. package/public/loading.html +2 -2
  106. package/public/sw.js +1 -1
  107. package/public/sw.js.map +1 -1
  108. package/public/assets/App-D3z0UG97.js +0 -107
  109. package/public/assets/App-D3z0UG97.js.map +0 -1
  110. package/public/assets/StatusTab-DurrtnDF.js +0 -2
  111. package/public/assets/StatusTab-DurrtnDF.js.map +0 -1
  112. package/public/assets/index-4cJ939YX.js.map +0 -1
  113. package/public/assets/index-BvEbvmim.js.map +0 -1
  114. package/public/assets/index-COifbS0Z.js.map +0 -1
  115. package/public/assets/index-CWEGmOqN.js.map +0 -1
  116. package/public/assets/index-CjgCyxpO.js.map +0 -1
  117. package/public/assets/index-D-6KUEZq.js.map +0 -1
  118. package/public/assets/index-DhhLKUaB.js.map +0 -1
  119. package/public/assets/index-Di1ASRtw.js.map +0 -1
  120. package/public/assets/index-hsSbaGZ2.js.map +0 -1
  121. package/public/assets/main-mPloHnyu.js.map +0 -1
package/README.md CHANGED
@@ -246,10 +246,12 @@ The stream is volatile and has no replay guarantee. After reconnecting, clients
246
246
 
247
247
  ### Provider Plan Usage
248
248
 
249
- The Status panel automatically displays quota information for the provider used by the active session. CodeNomad reads existing OpenCode and Codex CLI credential files but never modifies them or returns provider secrets through its API. Expired externally owned OAuth sessions must be refreshed by OpenCode or Codex CLI; CodeNomad does not exchange their refresh tokens, so refresh-token rotation cannot be lost.
249
+ The Status panel automatically displays quota information for the provider used by the active session. CodeNomad reads the credential each integration currently selects through OpenCode's native credential API; only daemons without that API (before 2.0.20) fall back to the legacy `auth.json`. Claude usage follows the login the session uses: `anthropic` sessions use OpenCode's Anthropic OAuth login, while the `claude-code` provider registered by opencode-claude uses the Claude Code login on the OpenCode daemon's host (including WSL distros), resolved with that host's environment and CodeNomad profile variables in Claude Code's own order: `CLAUDE_CODE_OAUTH_TOKEN`, then the stored login (macOS Keychain for a local daemon, otherwise `.credentials.json` under `CLAUDE_SECURESTORAGE_CONFIG_DIR`, `CLAUDE_CONFIG_DIR` or `~/.claude`). CodeNomad never modifies these credentials or returns provider secrets through its API. Expired externally owned OAuth sessions must be refreshed by their owner (OpenCode, Claude Code or Codex CLI); CodeNomad does not exchange their refresh tokens, so refresh-token rotation cannot be lost.
250
250
 
251
251
  Some optional usage integrations require credentials that OpenCode does not expose. They can be enabled without UI configuration through these environment variables:
252
252
 
253
253
  - Cursor access token: `CURSOR_ACCESS_TOKEN` or `CURSOR_TOKEN`
254
254
  - Ollama Cloud: `OLLAMA_CLOUD_COOKIE`
255
255
  - OpenCode Go: `OPENCODE_GO_WORKSPACE_ID` and `OPENCODE_GO_AUTH_COOKIE`
256
+ - ZenMux platform API key (distinct from its inference key): `ZENMUX_PLATFORM_API_KEY`
257
+ - exe.dev usage token: `EXE_DEV_USAGE_TOKEN`
package/dist/api-types.js CHANGED
@@ -13,4 +13,5 @@ export const WINDOWS_DRIVES_ROOT = "__drives__";
13
13
  export const OPENCODE_V2_REQUIRED_ERROR_CODE = "opencode_v2_required";
14
14
  export const SESSION_ENVIRONMENT_FAILED_ERROR_CODE = "session_environment_failed";
15
15
  export const PENDING_RECONCILIATION_HEADER = "x-codenomad-pending-reconciliation";
16
+ export const PENDING_REQUEST_SNAPSHOT_TIMEOUT_MS = 30_000;
16
17
  //# sourceMappingURL=api-types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-types.js","sourceRoot":"","sources":["../src/api-types.ts"],"names":[],"mappings":"AAYA;;;GAGG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,YAAY,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;IAC7B,QAAQ,EAAE,EAAE;IACZ,aAAa,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;IAC/B,kFAAkF;IAClF,mBAAmB,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;CAC7B,CAAA;AA8YV,MAAM,CAAC,MAAM,mBAAmB,GAAG,YAAY,CAAA;AA8E/C,MAAM,CAAC,MAAM,+BAA+B,GAAG,sBAA+B,CAAA;AAC9E,MAAM,CAAC,MAAM,qCAAqC,GAAG,4BAAqC,CAAA;AAC1F,MAAM,CAAC,MAAM,6BAA6B,GAAG,oCAA6C,CAAA","sourcesContent":["import type {\n AgentModelSelection,\n AgentModelSelections,\n ModelPreference,\n OpenCodeBinary,\n Preferences,\n RecentFolder,\n} from \"./config/schema\"\nimport type { FormInfo, OpenCodeEvent, PermissionRequest } from \"@opencode/client\"\nexport type { PanelExtensionManifest, PanelExtensionSummary, PanelExtensionContext, PanelExtensionCatalog, PanelExtensionCatalogEntry } from \"./panel-extensions/contract\"\nexport type { GitHistoryCommit, GitHistoryPage, GitCommitFile, GitCommitDetails, GitCommitDiff } from \"./git-history-types\"\n\n/**\n * Canonical HTTP/SSE contract for the CLI server.\n * These types are consumed by both the CLI implementation and any UI clients.\n */\n\nexport const PROMPT_INLINE_FILE_LIMITS = {\n maxFileBytes: 5 * 1024 * 1024,\n maxFiles: 10,\n maxTotalBytes: 20 * 1024 * 1024,\n // Covers the aggregate raw-byte budget after base64 expansion plus JSON metadata.\n maxRequestBodyBytes: 32 * 1024 * 1024,\n} as const\n\nexport type WorkspaceStatus = \"starting\" | \"ready\" | \"stopped\" | \"error\"\n\nexport interface WorkspaceDescriptor {\n id: string\n /** Correlates creation events with the client request that initiated them. */\n requestId?: string\n /** Absolute path on the server host. */\n path: string\n name?: string\n status: WorkspaceStatus\n /** PID/port are populated when the workspace is running. */\n pid?: number\n port?: number\n /** Canonical proxy path the CLI exposes for this instance. */\n proxyPath: string\n /** Identifier of the binary resolved from config. */\n binaryId: string\n binaryLabel: string\n binaryVersion?: string\n createdAt: string\n updatedAt: string\n /** Present when `status` is \"error\". */\n error?: string\n}\n\nexport interface WorkspaceCreateRequest {\n path: string\n name?: string\n requestId?: string\n}\n\nexport interface WorkspaceCloneRequest {\n repositoryUrl: string\n destinationPath: string\n cleanup?: boolean\n}\n\nexport interface WorkspaceCloneResponse {\n path: string\n}\n\nexport type WorkspaceCreateResponse = WorkspaceDescriptor & {\n /** True when this request did not own creation of the returned workspace. */\n reused?: true\n}\nexport type WorkspaceListResponse = WorkspaceDescriptor[]\nexport type WorkspaceDetailResponse = WorkspaceDescriptor\n\n/** Only successful exact-directory coverage may remove local interruptions. */\nexport interface WorkspacePendingRequestLocation {\n location: { directory: string }\n permissions: PermissionRequest[]\n forms: FormInfo[]\n}\n\nexport type WorkspacePendingRequestsResponse = { supported: false } | {\n supported: true\n directories: Array<{\n directory: string\n status: \"ok\"\n locations: WorkspacePendingRequestLocation[]\n } | { directory: string; status: \"error\"; locations?: WorkspacePendingRequestLocation[] }\n // An optional historical hint is outside current ownership; never empty queue authority.\n | { directory: string; status: \"excluded\"; locations?: never }>\n}\n\nexport interface WorkspaceDeleteResponse {\n id: string\n status: WorkspaceStatus\n}\n\nexport interface ProviderAccountsSnapshot {\n supported: boolean\n enabled: boolean\n logins: Record<string, string>\n}\n\nexport interface ProviderUsageWindow {\n usedPercent: number | null\n remainingPercent: number | null\n windowSeconds: number | null\n resetAt: number | null\n valueLabel?: string\n}\n\nexport interface ProviderUsageResponse {\n requestedProviderId: string\n providerId: string | null\n providerName: string\n modelId?: string\n supported: boolean\n configured: boolean\n ok: boolean\n windows: Record<string, ProviderUsageWindow>\n fetchedAt: number\n unavailableReason?: \"native-credential-api-unavailable\"\n}\n\nexport type WorktreeKind = \"root\" | \"worktree\"\n\nexport interface WorktreeDescriptor {\n /** Stable identifier used by CodeNomad + clients (\"root\" for the selected workspace folder). */\n slug: string\n /** Presentation only; the worktree identifier does not change with its branch. */\n label?: string\n /** Absolute directory path on the server host. */\n directory: string\n /** Equivalent path in the OpenCode service namespace (notably WSL). */\n serviceDirectory?: string\n /** Native checkout root (before mirroring a nested workspace folder). */\n serviceRoot?: string\n /** Exact path registered in Git's worktree inventory. */\n registeredDirectory?: string\n /** Degraded mode: only this exact physical directory authorizes sessions. */\n directoryOnly?: boolean\n kind: WorktreeKind\n /** False for the opened folder and Git's main checkout. */\n removable?: boolean\n /** Optional VCS branch name when available. */\n branch?: string\n /** Commit recorded by the Git worktree inventory. */\n head?: string\n}\n\nexport interface WorktreeListResponse {\n /** False means directory-only degraded mode; repository membership is unknown. */\n gitAvailable?: boolean\n worktrees: WorktreeDescriptor[]\n /** Default creation parent in the OpenCode service namespace. */\n defaultDirectory?: string\n /** True when the workspace folder resolves to a Git repository. */\n isGitRepo?: boolean\n}\n\nexport interface WorktreeCreateRequest {\n slug: string\n fromSlug?: string\n /** Optional branch name (defaults to slug). */\n branch?: string\n}\n\nexport interface WorktreeSessionMoveRequest {\n worktreeSlug: string\n}\n\nexport interface WorktreeSessionMoveResponse {\n rootSessionId: string\n sessionIds: string[]\n worktreeSlug: string\n}\n\nexport type GitChangeKind = \"added\" | \"modified\" | \"deleted\" | \"renamed\" | \"copied\" | \"untracked\" | \"unmerged\"\n\nexport interface WorktreeGitStatusEntry {\n path: string\n originalPath?: string | null\n stagedStatus: GitChangeKind | null\n stagedAdditions: number\n stagedDeletions: number\n unstagedStatus: GitChangeKind | null\n unstagedAdditions: number\n unstagedDeletions: number\n}\n\nexport type WorktreeGitStatusResponse = WorktreeGitStatusEntry[]\n\nexport type WorktreeGitDiffScope = \"staged\" | \"unstaged\"\n\nexport interface WorktreeGitPathsRequest {\n paths: string[]\n}\n\nexport interface WorktreeGitMutationResponse {\n ok: true\n}\n\nexport interface WorktreeGitCommitRequest {\n message: string\n}\n\nexport interface WorktreeGitCommitResponse {\n ok: true\n commitSha?: string\n}\n\nexport interface WorktreeGitDiffResponse {\n path: string\n originalPath?: string | null\n scope: WorktreeGitDiffScope\n before: string\n after: string\n isBinary?: boolean\n image?: import(\"./git-history-types\").GitImageDiff\n}\n\nexport interface WorktreeGitDiffRequest {\n path: string\n originalPath?: string | null\n scope: WorktreeGitDiffScope\n}\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\"\n\nexport interface WorkspaceLogEntry {\n workspaceId: string\n timestamp: string\n level: LogLevel\n message: string\n}\n\nexport interface FileSystemEntry {\n name: string\n /**\n * Path identifier for the entry. Relative to the server root in restricted\n * single-root listings (\".\" represents the root itself); absolute in\n * unrestricted, drives, and multi-root top-level listings.\n */\n path: string\n /** Absolute path when available (unrestricted and multi-root listings). */\n absolutePath?: string\n type: \"file\" | \"directory\"\n size?: number\n /** ISO timestamp of last modification when available. */\n modifiedAt?: string\n}\n\nexport type FileSystemScope = \"restricted\" | \"unrestricted\"\nexport type FileSystemPathKind = \"relative\" | \"absolute\" | \"drives\"\n\nexport interface FileSystemListingMetadata {\n scope: FileSystemScope\n /**\n * Canonical identifier of the current view:\n * - \".\" for restricted single-root listings\n * - WINDOWS_DRIVES_ROOT for the Windows drives pseudo-root\n * - absolute path otherwise\n */\n currentPath: string\n /** Optional parent path if navigation upward is allowed. */\n parentPath?: string\n /** Absolute path representing the root or origin point for this listing. */\n rootPath: string\n /** Absolute home directory of the CLI host (useful defaults for unrestricted mode). */\n homePath: string\n /** Human-friendly label for the current path. */\n displayPath: string\n /** Indicates whether entry paths are relative, absolute, or represent the drive pseudo-view. */\n pathKind: FileSystemPathKind\n}\n\nexport interface FileSystemListResponse {\n entries: FileSystemEntry[]\n metadata: FileSystemListingMetadata\n}\n\nexport interface FileSystemCreateFolderRequest {\n /**\n * Path identifier for the currently browsed directory.\n * Matches the `path` parameter used for `/api/filesystem`.\n */\n parentPath?: string\n /** Single folder name (no separators). */\n name: string\n}\n\nexport interface FileSystemCreateFolderResponse {\n /**\n * Path identifier that can be passed back to `/api/filesystem` to browse the new folder.\n * Relative for restricted listings and absolute for unrestricted listings.\n */\n path: string\n /** Absolute folder path on the server host. */\n absolutePath: string\n}\n\nexport interface FileSystemFileContentResponse {\n path: string\n contents: string\n encoding: \"utf-8\" | \"base64\"\n}\n\nexport interface ConfigFileDescriptor {\n id: string\n label: string\n path: string\n language: string\n}\n\nexport type ConfigFileListResponse = ConfigFileDescriptor[]\n\nexport interface ConfigFileContentResponse {\n id: string\n path: string\n contents: string\n exists: boolean\n}\n\nexport interface ConfigFileContentRequest {\n contents: string\n}\n\nexport type PluginControlScope = \"global\" | \"project\"\nexport type WebSearchSelection = string | false | null\nexport interface WebSearchSettingsSnapshot {\n location: PluginControlLocation\n effective: WebSearchSelection\n scopes: Array<{ scope: PluginControlScope; path: string; selection: WebSearchSelection }>\n}\nexport interface WebSearchSettingsMutation {\n location: PluginControlLocation\n scope: PluginControlScope\n provider: WebSearchSelection\n}\nexport type PluginConfigScope = PluginControlScope | \"other\" | \"virtual\"\n\nexport interface PluginControlLocation {\n directory: string\n workspaceID?: string\n}\n\nexport type PluginRuntimeSource =\n | { type: \"builtin\" }\n | { type: \"package\"; target: string; version?: string; outdated?: true; updating?: true }\n | { type: \"local\"; path: string }\n | { type: \"sdk\" }\n\nexport interface PluginRuntimeInventoryEntry {\n key: string\n id?: string\n source: PluginRuntimeSource\n features: { server?: true; tui?: true; rpc?: true }\n state: { status: \"active\" } | { status: \"failed\"; error: string; ref?: string }\n}\n\nexport interface PluginConfiguredRule {\n selector: string\n enabled: boolean\n scope: PluginConfigScope\n path?: string\n order: number\n entryIndex: number\n}\n\nexport interface PluginConfiguredSource {\n target: string\n scope: PluginConfigScope\n path?: string\n entryIndex: number\n hasOptions: boolean\n}\n\nexport type PluginScopeRuleState = \"default\" | \"enabled\" | \"disabled\"\n\nexport interface PluginActivationControl {\n id: string\n runtime?: PluginRuntimeInventoryEntry\n /** True for OpenCode-owned plugins, including disabled builtins absent from runtime inventory. */\n builtin: boolean\n effective: PluginScopeRuleState\n global: PluginScopeRuleState\n project: PluginScopeRuleState\n controllingRule?: PluginConfiguredRule\n}\n\nexport interface PluginControlTarget {\n scope: PluginControlScope\n path: string\n exists: boolean\n}\n\nexport interface PluginControlsSnapshot {\n location: PluginControlLocation\n runtime: PluginRuntimeInventoryEntry[]\n configured: {\n rules: PluginConfiguredRule[]\n sources: PluginConfiguredSource[]\n }\n controls: PluginActivationControl[]\n targets: PluginControlTarget[]\n}\n\nexport interface PluginActivationMutationRequest {\n location: PluginControlLocation\n pluginId: string\n scope: PluginControlScope\n enabled: boolean\n}\n\nexport interface PluginActivationMutationResponse {\n snapshot: PluginControlsSnapshot\n rule: string\n target: PluginControlTarget\n changed: boolean\n reloadPending: boolean\n}\n\nexport const WINDOWS_DRIVES_ROOT = \"__drives__\"\n\nexport interface WorkspaceFileResponse {\n workspaceId: string\n relativePath: string\n /** UTF-8 file contents; binary files should be base64 encoded by the caller. */\n contents: string\n encoding?: \"utf-8\" | \"base64\"\n}\n\nexport type WorkspaceFileSearchResponse = FileSystemEntry[]\n\nexport interface InstanceData {\n messageHistory: string[]\n agentModelSelections: AgentModelSelection\n}\n\nexport type InstanceStreamStatus = \"connecting\" | \"connected\" | \"error\" | \"disconnected\"\n\nexport type InstanceStreamEvent = OpenCodeEvent\n\nexport type SideCarKind = \"port\"\n\nexport type SideCarPrefixMode = \"strip\" | \"preserve\"\n\nexport type SideCarStatus = \"running\" | \"stopped\"\n\nexport interface SideCar {\n id: string\n kind: SideCarKind\n name: string\n port: number\n insecure: boolean\n prefixMode: SideCarPrefixMode\n status: SideCarStatus\n createdAt: string\n updatedAt: string\n}\n\nexport interface PreviewSession {\n token: string\n sessionId: string\n targetUrl: string\n proxyUrl: string\n createdAt: string\n}\n\nexport interface BinaryRecord {\n id: string\n path: string\n label: string\n version?: string\n\n /** Indicates that this binary will be picked when workspaces omit an explicit choice. */\n isDefault: boolean\n lastValidatedAt?: string\n validationError?: string\n}\n\nexport type SettingsOwner = string\nexport type SettingsBucket = Record<string, unknown>\nexport type SettingsDoc = Record<string, unknown>\n\nexport interface BinaryListResponse {\n binaries: BinaryRecord[]\n}\n\nexport interface BinaryCreateRequest {\n path: string\n label?: string\n makeDefault?: boolean\n}\n\nexport interface BinaryUpdateRequest {\n label?: string\n makeDefault?: boolean\n}\n\nexport const OPENCODE_V2_REQUIRED_ERROR_CODE = \"opencode_v2_required\" as const\nexport const SESSION_ENVIRONMENT_FAILED_ERROR_CODE = \"session_environment_failed\" as const\nexport const PENDING_RECONCILIATION_HEADER = \"x-codenomad-pending-reconciliation\" as const\n\nexport interface BinaryValidationResult {\n valid: boolean\n version?: string\n error?: string\n errorCode?: typeof OPENCODE_V2_REQUIRED_ERROR_CODE\n}\n\nexport interface OpenCodeUpdateStatus {\n currentVersion: string | null\n latestVersion: string | null\n updateAvailable: boolean | null\n canUpgrade: boolean\n checkError?: \"update_check_failed\"\n minimumVersion: string\n recommendedVersion: string\n versionAssessment: \"tested\" | \"untested\" | \"incompatible\"\n incompatibilityReason?: \"step_timestamp\" | \"canonical_api\" | \"session_environment\"\n state: \"missing\" | \"update_required\" | \"ready\" | \"error\"\n binaryPath: string\n installationSource?: \"path\" | \"user\"\n needsSharedInstallation?: boolean\n daemonVersion?: string\n serviceState?: \"stopped\" | \"ready\" | \"restart_required\" | \"restart_available\" | \"incompatible\" | \"error\"\n canReload?: boolean\n serviceError?: string\n target: \"host\" | \"wsl\"\n canRestart: boolean\n}\n\nexport interface OpenCodeUpdateResponse {\n success: boolean\n version: string\n}\n\nexport interface SpeechSegment {\n startMs: number\n endMs: number\n text: string\n}\n\nexport interface SpeechCapabilitiesResponse {\n available: boolean\n configured: boolean\n provider: string\n supportsStt: boolean\n supportsTts: boolean\n supportsStreamingTts: boolean\n baseUrl?: string\n sttModel: string\n ttsModel: string\n ttsVoice: string\n ttsFormats: string[]\n streamingTtsFormats: string[]\n separateProviders?: boolean\n sttConfigured?: boolean\n ttsConfigured?: boolean\n sttBaseUrl?: string\n ttsBaseUrl?: string\n}\n\nexport interface SpeechTranscriptionResponse {\n text: string\n language?: string\n durationMs?: number\n segments?: SpeechSegment[]\n}\n\nexport interface SpeechSynthesisResponse {\n audioBase64: string\n mimeType: string\n}\n\nexport interface YoloStateResponse {\n enabled: boolean\n}\n\nexport interface RemoteServerProfile {\n id: string\n name: string\n baseUrl: string\n skipTlsVerify: boolean\n createdAt: string\n updatedAt: string\n lastConnectedAt?: string\n}\n\nexport interface RemoteServerProbeRequest {\n baseUrl: string\n skipTlsVerify?: boolean\n}\n\nexport interface RemoteServerProbeResponse {\n ok: boolean\n reachable: boolean\n normalizedUrl: string\n skipTlsVerify: boolean\n requiresAuth: boolean\n authenticated: boolean\n error?: string\n errorCode?: string\n}\n\nexport interface RemoteProxySessionCreateRequest {\n baseUrl: string\n skipTlsVerify?: boolean\n}\n\nexport interface RemoteProxySessionCreateResponse {\n sessionId: string\n windowUrl: string\n}\n\nexport type WorkspaceEventType =\n | \"workspace.created\"\n | \"workspace.started\"\n | \"workspace.error\"\n | \"workspace.stopped\"\n | \"workspace.log\"\n | \"workspace.worktreesChanged\"\n | \"sidecar.updated\"\n | \"sidecar.removed\"\n | \"storage.configChanged\"\n | \"storage.stateChanged\"\n | \"instance.dataChanged\"\n | \"instance.event\"\n | \"instance.eventStatus\"\n | \"yolo.stateChanged\"\n | \"yolo.autoAccepted\"\n | \"permission.receiptsChanged\"\n\nexport interface PermissionReceipt {\n requestId: string\n sessionId: string\n action?: string\n resources: string[]\n requestMessage?: string\n source?: { messageId: string; callId: string }\n decision: \"once\" | \"always\" | \"reject\"\n reason?: string\n origin: \"codenomad\" | \"yolo\" | \"native\"\n resolvedAt: number\n}\n\nexport interface PermissionReceiptPage {\n receipts: PermissionReceipt[]\n next?: string\n}\n\nexport type WorkspaceEventPayload =\n | { type: \"workspace.created\"; workspace: WorkspaceDescriptor }\n | { type: \"workspace.started\"; workspace: WorkspaceDescriptor }\n | { type: \"workspace.error\"; workspace: WorkspaceDescriptor }\n | { type: \"workspace.stopped\"; workspaceId: string; reason?: \"deleted\" | \"stopped\" }\n | { type: \"workspace.log\"; entry: WorkspaceLogEntry }\n | { type: \"workspace.worktreesChanged\"; workspaceId: string }\n | { type: \"sidecar.updated\"; sidecar: SideCar }\n | { type: \"sidecar.removed\"; sidecarId: string }\n | { type: \"storage.configChanged\"; owner: SettingsOwner; value: SettingsBucket }\n | { type: \"storage.stateChanged\"; owner: SettingsOwner; value: SettingsBucket }\n | { type: \"instance.dataChanged\"; instanceId: string; data: InstanceData }\n | { type: \"instance.event\"; instanceId: string; event: InstanceStreamEvent }\n | { type: \"instance.eventStatus\"; instanceId: string; status: InstanceStreamStatus; generation: number; reason?: string }\n | { type: \"yolo.stateChanged\"; instanceId: string; sessionId: string; enabled: boolean }\n | { type: \"yolo.autoAccepted\"; instanceId: string; sessionId: string; permissionId: string }\n | { type: \"permission.receiptsChanged\"; instanceId: string; sessionId: string; messageId?: string }\n\nexport interface NetworkAddress {\n ip: string\n family: \"ipv4\" | \"ipv6\"\n scope: \"external\" | \"internal\" | \"loopback\"\n /** Remote URL using the server's remote protocol/port for this IP. */\n remoteUrl: string\n}\n\nexport interface LatestReleaseInfo {\n version: string\n tag: string\n url: string\n channel: \"stable\" | \"dev\"\n publishedAt?: string\n notes?: string\n}\n\nexport interface UiMeta {\n version?: string\n source: \"bundled\" | \"downloaded\" | \"previous\" | \"override\" | \"dev-proxy\" | \"missing\"\n}\n\nexport interface SupportMeta {\n supported: boolean\n message?: string\n minServerVersion?: string\n latestServerVersion?: string\n latestServerUrl?: string\n}\n\nexport interface ServerMeta {\n /** URL desktop apps should use to connect (prefers loopback HTTP when enabled). */\n localUrl: string\n /** URL remote clients should use (prefers HTTPS when enabled). */\n remoteUrl?: string\n /** SSE endpoint advertised to clients (`/api/events` by default). */\n eventsUrl: string\n /** Host the server is bound to (e.g., 127.0.0.1 or 0.0.0.0). */\n host: string\n /** Listening mode derived from host binding. */\n listeningMode: \"local\" | \"all\"\n /** Actual local port in use after binding. */\n localPort: number\n /** Actual remote port in use after binding (when remoteUrl is set). */\n remotePort?: number\n /** Display label for the host (e.g., hostname or friendly name). */\n hostLabel: string\n /** Absolute path of the filesystem root exposed to clients. */\n workspaceRoot: string\n /** Reachable addresses for this server, external first. */\n addresses: NetworkAddress[]\n serverVersion?: string\n /** CodeNomad backend OS and Node runtime architecture, never the UI or OpenCode host. */\n system?: { platform: string; arch: string }\n ui?: UiMeta\n support?: SupportMeta\n /** Optional update info (dev channel only). */\n update?: LatestReleaseInfo | null\n}\n\nexport type {\n Preferences,\n ModelPreference,\n AgentModelSelections,\n RecentFolder,\n OpenCodeBinary,\n}\nexport type { PruneRequest, PruneResult } from \"./opencode/session-pruning/contract\"\n"]}
1
+ {"version":3,"file":"api-types.js","sourceRoot":"","sources":["../src/api-types.ts"],"names":[],"mappings":"AAYA;;;GAGG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACvC,YAAY,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;IAC7B,QAAQ,EAAE,EAAE;IACZ,aAAa,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;IAC/B,kFAAkF;IAClF,mBAAmB,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;CAC7B,CAAA;AA8YV,MAAM,CAAC,MAAM,mBAAmB,GAAG,YAAY,CAAA;AA8E/C,MAAM,CAAC,MAAM,+BAA+B,GAAG,sBAA+B,CAAA;AAC9E,MAAM,CAAC,MAAM,qCAAqC,GAAG,4BAAqC,CAAA;AAC1F,MAAM,CAAC,MAAM,6BAA6B,GAAG,oCAA6C,CAAA;AAC1F,MAAM,CAAC,MAAM,mCAAmC,GAAG,MAAM,CAAA","sourcesContent":["import type {\n AgentModelSelection,\n AgentModelSelections,\n ModelPreference,\n OpenCodeBinary,\n Preferences,\n RecentFolder,\n} from \"./config/schema\"\nimport type { FormInfo, OpenCodeEvent, PermissionRequest } from \"@opencode/client\"\nexport type { PanelExtensionManifest, PanelExtensionSummary, PanelExtensionContext, PanelExtensionCatalog, PanelExtensionCatalogEntry } from \"./panel-extensions/contract\"\nexport type { GitHistoryCommit, GitHistoryPage, GitCommitFile, GitCommitDetails, GitCommitDiff } from \"./git-history-types\"\n\n/**\n * Canonical HTTP/SSE contract for the CLI server.\n * These types are consumed by both the CLI implementation and any UI clients.\n */\n\nexport const PROMPT_INLINE_FILE_LIMITS = {\n maxFileBytes: 5 * 1024 * 1024,\n maxFiles: 10,\n maxTotalBytes: 20 * 1024 * 1024,\n // Covers the aggregate raw-byte budget after base64 expansion plus JSON metadata.\n maxRequestBodyBytes: 32 * 1024 * 1024,\n} as const\n\nexport type WorkspaceStatus = \"starting\" | \"ready\" | \"stopped\" | \"error\"\n\nexport interface WorkspaceDescriptor {\n id: string\n /** Correlates creation events with the client request that initiated them. */\n requestId?: string\n /** Absolute path on the server host. */\n path: string\n name?: string\n status: WorkspaceStatus\n /** PID/port are populated when the workspace is running. */\n pid?: number\n port?: number\n /** Canonical proxy path the CLI exposes for this instance. */\n proxyPath: string\n /** Identifier of the binary resolved from config. */\n binaryId: string\n binaryLabel: string\n binaryVersion?: string\n createdAt: string\n updatedAt: string\n /** Present when `status` is \"error\". */\n error?: string\n}\n\nexport interface WorkspaceCreateRequest {\n path: string\n name?: string\n requestId?: string\n}\n\nexport interface WorkspaceCloneRequest {\n repositoryUrl: string\n destinationPath: string\n cleanup?: boolean\n}\n\nexport interface WorkspaceCloneResponse {\n path: string\n}\n\nexport type WorkspaceCreateResponse = WorkspaceDescriptor & {\n /** True when this request did not own creation of the returned workspace. */\n reused?: true\n}\nexport type WorkspaceListResponse = WorkspaceDescriptor[]\nexport type WorkspaceDetailResponse = WorkspaceDescriptor\n\n/** Only successful exact-directory coverage may remove local interruptions. */\nexport interface WorkspacePendingRequestLocation {\n location: { directory: string }\n permissions: PermissionRequest[]\n forms: FormInfo[]\n}\n\nexport type WorkspacePendingRequestsResponse = { supported: false } | {\n supported: true\n directories: Array<{\n directory: string\n status: \"ok\"\n locations: WorkspacePendingRequestLocation[]\n } | { directory: string; status: \"error\"; locations?: WorkspacePendingRequestLocation[] }\n // An optional historical hint is outside current ownership; never empty queue authority.\n | { directory: string; status: \"excluded\"; locations?: never }>\n}\n\nexport interface WorkspaceDeleteResponse {\n id: string\n status: WorkspaceStatus\n}\n\nexport interface ProviderAccountsSnapshot {\n supported: boolean\n enabled: boolean\n logins: Record<string, string>\n}\n\nexport interface ProviderUsageWindow {\n usedPercent: number | null\n remainingPercent: number | null\n windowSeconds: number | null\n resetAt: number | null\n valueLabel?: string\n}\n\nexport interface ProviderUsageResponse {\n requestedProviderId: string\n providerId: string | null\n providerName: string\n modelId?: string\n supported: boolean\n configured: boolean\n ok: boolean\n windows: Record<string, ProviderUsageWindow>\n fetchedAt: number\n unavailableReason?: \"native-credential-api-unavailable\"\n}\n\nexport type WorktreeKind = \"root\" | \"worktree\"\n\nexport interface WorktreeDescriptor {\n /** Stable identifier used by CodeNomad + clients (\"root\" for the selected workspace folder). */\n slug: string\n /** Presentation only; the worktree identifier does not change with its branch. */\n label?: string\n /** Absolute directory path on the server host. */\n directory: string\n /** Equivalent path in the OpenCode service namespace (notably WSL). */\n serviceDirectory?: string\n /** Native checkout root (before mirroring a nested workspace folder). */\n serviceRoot?: string\n /** Exact path registered in Git's worktree inventory. */\n registeredDirectory?: string\n /** Degraded mode: only this exact physical directory authorizes sessions. */\n directoryOnly?: boolean\n kind: WorktreeKind\n /** False for the opened folder and Git's main checkout. */\n removable?: boolean\n /** Optional VCS branch name when available. */\n branch?: string\n /** Commit recorded by the Git worktree inventory. */\n head?: string\n}\n\nexport interface WorktreeListResponse {\n /** False means directory-only degraded mode; repository membership is unknown. */\n gitAvailable?: boolean\n worktrees: WorktreeDescriptor[]\n /** Default creation parent in the OpenCode service namespace. */\n defaultDirectory?: string\n /** True when the workspace folder resolves to a Git repository. */\n isGitRepo?: boolean\n}\n\nexport interface WorktreeCreateRequest {\n slug: string\n fromSlug?: string\n /** Optional branch name (defaults to slug). */\n branch?: string\n}\n\nexport interface WorktreeSessionMoveRequest {\n worktreeSlug: string\n}\n\nexport interface WorktreeSessionMoveResponse {\n rootSessionId: string\n sessionIds: string[]\n worktreeSlug: string\n}\n\nexport type GitChangeKind = \"added\" | \"modified\" | \"deleted\" | \"renamed\" | \"copied\" | \"untracked\" | \"unmerged\"\n\nexport interface WorktreeGitStatusEntry {\n path: string\n originalPath?: string | null\n stagedStatus: GitChangeKind | null\n stagedAdditions: number\n stagedDeletions: number\n unstagedStatus: GitChangeKind | null\n unstagedAdditions: number\n unstagedDeletions: number\n}\n\nexport type WorktreeGitStatusResponse = WorktreeGitStatusEntry[]\n\nexport type WorktreeGitDiffScope = \"staged\" | \"unstaged\"\n\nexport interface WorktreeGitPathsRequest {\n paths: string[]\n}\n\nexport interface WorktreeGitMutationResponse {\n ok: true\n}\n\nexport interface WorktreeGitCommitRequest {\n message: string\n}\n\nexport interface WorktreeGitCommitResponse {\n ok: true\n commitSha?: string\n}\n\nexport interface WorktreeGitDiffResponse {\n path: string\n originalPath?: string | null\n scope: WorktreeGitDiffScope\n before: string\n after: string\n isBinary?: boolean\n image?: import(\"./git-history-types\").GitImageDiff\n}\n\nexport interface WorktreeGitDiffRequest {\n path: string\n originalPath?: string | null\n scope: WorktreeGitDiffScope\n}\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\"\n\nexport interface WorkspaceLogEntry {\n workspaceId: string\n timestamp: string\n level: LogLevel\n message: string\n}\n\nexport interface FileSystemEntry {\n name: string\n /**\n * Path identifier for the entry. Relative to the server root in restricted\n * single-root listings (\".\" represents the root itself); absolute in\n * unrestricted, drives, and multi-root top-level listings.\n */\n path: string\n /** Absolute path when available (unrestricted and multi-root listings). */\n absolutePath?: string\n type: \"file\" | \"directory\"\n size?: number\n /** ISO timestamp of last modification when available. */\n modifiedAt?: string\n}\n\nexport type FileSystemScope = \"restricted\" | \"unrestricted\"\nexport type FileSystemPathKind = \"relative\" | \"absolute\" | \"drives\"\n\nexport interface FileSystemListingMetadata {\n scope: FileSystemScope\n /**\n * Canonical identifier of the current view:\n * - \".\" for restricted single-root listings\n * - WINDOWS_DRIVES_ROOT for the Windows drives pseudo-root\n * - absolute path otherwise\n */\n currentPath: string\n /** Optional parent path if navigation upward is allowed. */\n parentPath?: string\n /** Absolute path representing the root or origin point for this listing. */\n rootPath: string\n /** Absolute home directory of the CLI host (useful defaults for unrestricted mode). */\n homePath: string\n /** Human-friendly label for the current path. */\n displayPath: string\n /** Indicates whether entry paths are relative, absolute, or represent the drive pseudo-view. */\n pathKind: FileSystemPathKind\n}\n\nexport interface FileSystemListResponse {\n entries: FileSystemEntry[]\n metadata: FileSystemListingMetadata\n}\n\nexport interface FileSystemCreateFolderRequest {\n /**\n * Path identifier for the currently browsed directory.\n * Matches the `path` parameter used for `/api/filesystem`.\n */\n parentPath?: string\n /** Single folder name (no separators). */\n name: string\n}\n\nexport interface FileSystemCreateFolderResponse {\n /**\n * Path identifier that can be passed back to `/api/filesystem` to browse the new folder.\n * Relative for restricted listings and absolute for unrestricted listings.\n */\n path: string\n /** Absolute folder path on the server host. */\n absolutePath: string\n}\n\nexport interface FileSystemFileContentResponse {\n path: string\n contents: string\n encoding: \"utf-8\" | \"base64\"\n}\n\nexport interface ConfigFileDescriptor {\n id: string\n label: string\n path: string\n language: string\n}\n\nexport type ConfigFileListResponse = ConfigFileDescriptor[]\n\nexport interface ConfigFileContentResponse {\n id: string\n path: string\n contents: string\n exists: boolean\n}\n\nexport interface ConfigFileContentRequest {\n contents: string\n}\n\nexport type PluginControlScope = \"global\" | \"project\"\nexport type WebSearchSelection = string | false | null\nexport interface WebSearchSettingsSnapshot {\n location: PluginControlLocation\n effective: WebSearchSelection\n scopes: Array<{ scope: PluginControlScope; path: string; selection: WebSearchSelection }>\n}\nexport interface WebSearchSettingsMutation {\n location: PluginControlLocation\n scope: PluginControlScope\n provider: WebSearchSelection\n}\nexport type PluginConfigScope = PluginControlScope | \"other\" | \"virtual\"\n\nexport interface PluginControlLocation {\n directory: string\n workspaceID?: string\n}\n\nexport type PluginRuntimeSource =\n | { type: \"builtin\" }\n | { type: \"package\"; target: string; version?: string; outdated?: true; updating?: true }\n | { type: \"local\"; path: string }\n | { type: \"sdk\" }\n\nexport interface PluginRuntimeInventoryEntry {\n key: string\n id?: string\n source: PluginRuntimeSource\n features: { server?: true; tui?: true; rpc?: true }\n state: { status: \"active\" } | { status: \"failed\"; error: string; ref?: string }\n}\n\nexport interface PluginConfiguredRule {\n selector: string\n enabled: boolean\n scope: PluginConfigScope\n path?: string\n order: number\n entryIndex: number\n}\n\nexport interface PluginConfiguredSource {\n target: string\n scope: PluginConfigScope\n path?: string\n entryIndex: number\n hasOptions: boolean\n}\n\nexport type PluginScopeRuleState = \"default\" | \"enabled\" | \"disabled\"\n\nexport interface PluginActivationControl {\n id: string\n runtime?: PluginRuntimeInventoryEntry\n /** True for OpenCode-owned plugins, including disabled builtins absent from runtime inventory. */\n builtin: boolean\n effective: PluginScopeRuleState\n global: PluginScopeRuleState\n project: PluginScopeRuleState\n controllingRule?: PluginConfiguredRule\n}\n\nexport interface PluginControlTarget {\n scope: PluginControlScope\n path: string\n exists: boolean\n}\n\nexport interface PluginControlsSnapshot {\n location: PluginControlLocation\n runtime: PluginRuntimeInventoryEntry[]\n configured: {\n rules: PluginConfiguredRule[]\n sources: PluginConfiguredSource[]\n }\n controls: PluginActivationControl[]\n targets: PluginControlTarget[]\n}\n\nexport interface PluginActivationMutationRequest {\n location: PluginControlLocation\n pluginId: string\n scope: PluginControlScope\n enabled: boolean\n}\n\nexport interface PluginActivationMutationResponse {\n snapshot: PluginControlsSnapshot\n rule: string\n target: PluginControlTarget\n changed: boolean\n reloadPending: boolean\n}\n\nexport const WINDOWS_DRIVES_ROOT = \"__drives__\"\n\nexport interface WorkspaceFileResponse {\n workspaceId: string\n relativePath: string\n /** UTF-8 file contents; binary files should be base64 encoded by the caller. */\n contents: string\n encoding?: \"utf-8\" | \"base64\"\n}\n\nexport type WorkspaceFileSearchResponse = FileSystemEntry[]\n\nexport interface InstanceData {\n messageHistory: string[]\n agentModelSelections: AgentModelSelection\n}\n\nexport type InstanceStreamStatus = \"connecting\" | \"connected\" | \"error\" | \"disconnected\"\n\nexport type InstanceStreamEvent = OpenCodeEvent\n\nexport type SideCarKind = \"port\"\n\nexport type SideCarPrefixMode = \"strip\" | \"preserve\"\n\nexport type SideCarStatus = \"running\" | \"stopped\"\n\nexport interface SideCar {\n id: string\n kind: SideCarKind\n name: string\n port: number\n insecure: boolean\n prefixMode: SideCarPrefixMode\n status: SideCarStatus\n createdAt: string\n updatedAt: string\n}\n\nexport interface PreviewSession {\n token: string\n sessionId: string\n targetUrl: string\n proxyUrl: string\n createdAt: string\n}\n\nexport interface BinaryRecord {\n id: string\n path: string\n label: string\n version?: string\n\n /** Indicates that this binary will be picked when workspaces omit an explicit choice. */\n isDefault: boolean\n lastValidatedAt?: string\n validationError?: string\n}\n\nexport type SettingsOwner = string\nexport type SettingsBucket = Record<string, unknown>\nexport type SettingsDoc = Record<string, unknown>\n\nexport interface BinaryListResponse {\n binaries: BinaryRecord[]\n}\n\nexport interface BinaryCreateRequest {\n path: string\n label?: string\n makeDefault?: boolean\n}\n\nexport interface BinaryUpdateRequest {\n label?: string\n makeDefault?: boolean\n}\n\nexport const OPENCODE_V2_REQUIRED_ERROR_CODE = \"opencode_v2_required\" as const\nexport const SESSION_ENVIRONMENT_FAILED_ERROR_CODE = \"session_environment_failed\" as const\nexport const PENDING_RECONCILIATION_HEADER = \"x-codenomad-pending-reconciliation\" as const\nexport const PENDING_REQUEST_SNAPSHOT_TIMEOUT_MS = 30_000\n\nexport interface BinaryValidationResult {\n valid: boolean\n version?: string\n error?: string\n errorCode?: typeof OPENCODE_V2_REQUIRED_ERROR_CODE\n}\n\nexport interface OpenCodeUpdateStatus {\n currentVersion: string | null\n latestVersion: string | null\n updateAvailable: boolean | null\n canUpgrade: boolean\n checkError?: \"update_check_failed\"\n minimumVersion: string\n recommendedVersion: string\n versionAssessment: \"tested\" | \"untested\" | \"incompatible\"\n incompatibilityReason?: \"step_timestamp\" | \"canonical_api\" | \"session_environment\"\n state: \"missing\" | \"update_required\" | \"ready\" | \"error\"\n binaryPath: string\n installationSource?: \"path\" | \"user\"\n needsSharedInstallation?: boolean\n daemonVersion?: string\n serviceState?: \"stopped\" | \"ready\" | \"restart_required\" | \"restart_available\" | \"incompatible\" | \"error\"\n canReload?: boolean\n serviceError?: string\n target: \"host\" | \"wsl\"\n canRestart: boolean\n}\n\nexport interface OpenCodeUpdateResponse {\n success: boolean\n version: string\n}\n\nexport interface SpeechSegment {\n startMs: number\n endMs: number\n text: string\n}\n\nexport interface SpeechCapabilitiesResponse {\n available: boolean\n configured: boolean\n provider: string\n supportsStt: boolean\n supportsTts: boolean\n supportsStreamingTts: boolean\n baseUrl?: string\n sttModel: string\n ttsModel: string\n ttsVoice: string\n ttsFormats: string[]\n streamingTtsFormats: string[]\n separateProviders?: boolean\n sttConfigured?: boolean\n ttsConfigured?: boolean\n sttBaseUrl?: string\n ttsBaseUrl?: string\n}\n\nexport interface SpeechTranscriptionResponse {\n text: string\n language?: string\n durationMs?: number\n segments?: SpeechSegment[]\n}\n\nexport interface SpeechSynthesisResponse {\n audioBase64: string\n mimeType: string\n}\n\nexport interface YoloStateResponse {\n enabled: boolean\n}\n\nexport interface RemoteServerProfile {\n id: string\n name: string\n baseUrl: string\n skipTlsVerify: boolean\n createdAt: string\n updatedAt: string\n lastConnectedAt?: string\n}\n\nexport interface RemoteServerProbeRequest {\n baseUrl: string\n skipTlsVerify?: boolean\n}\n\nexport interface RemoteServerProbeResponse {\n ok: boolean\n reachable: boolean\n normalizedUrl: string\n skipTlsVerify: boolean\n requiresAuth: boolean\n authenticated: boolean\n error?: string\n errorCode?: string\n}\n\nexport interface RemoteProxySessionCreateRequest {\n baseUrl: string\n skipTlsVerify?: boolean\n}\n\nexport interface RemoteProxySessionCreateResponse {\n sessionId: string\n windowUrl: string\n}\n\nexport type WorkspaceEventType =\n | \"workspace.created\"\n | \"workspace.started\"\n | \"workspace.error\"\n | \"workspace.stopped\"\n | \"workspace.log\"\n | \"workspace.worktreesChanged\"\n | \"sidecar.updated\"\n | \"sidecar.removed\"\n | \"storage.configChanged\"\n | \"storage.stateChanged\"\n | \"instance.dataChanged\"\n | \"instance.event\"\n | \"instance.eventStatus\"\n | \"yolo.stateChanged\"\n | \"yolo.autoAccepted\"\n | \"permission.receiptsChanged\"\n\nexport interface PermissionReceipt {\n requestId: string\n sessionId: string\n action?: string\n resources: string[]\n requestMessage?: string\n source?: { messageId: string; callId: string }\n decision: \"once\" | \"always\" | \"reject\"\n reason?: string\n origin: \"codenomad\" | \"yolo\" | \"native\"\n resolvedAt: number\n}\n\nexport interface PermissionReceiptPage {\n receipts: PermissionReceipt[]\n next?: string\n}\n\nexport type WorkspaceEventPayload =\n | { type: \"workspace.created\"; workspace: WorkspaceDescriptor }\n | { type: \"workspace.started\"; workspace: WorkspaceDescriptor }\n | { type: \"workspace.error\"; workspace: WorkspaceDescriptor }\n | { type: \"workspace.stopped\"; workspaceId: string; reason?: \"deleted\" | \"stopped\" }\n | { type: \"workspace.log\"; entry: WorkspaceLogEntry }\n | { type: \"workspace.worktreesChanged\"; workspaceId: string }\n | { type: \"sidecar.updated\"; sidecar: SideCar }\n | { type: \"sidecar.removed\"; sidecarId: string }\n | { type: \"storage.configChanged\"; owner: SettingsOwner; value: SettingsBucket }\n | { type: \"storage.stateChanged\"; owner: SettingsOwner; value: SettingsBucket }\n | { type: \"instance.dataChanged\"; instanceId: string; data: InstanceData }\n | { type: \"instance.event\"; instanceId: string; event: InstanceStreamEvent }\n | { type: \"instance.eventStatus\"; instanceId: string; status: InstanceStreamStatus; generation: number; reason?: string }\n | { type: \"yolo.stateChanged\"; instanceId: string; sessionId: string; enabled: boolean }\n | { type: \"yolo.autoAccepted\"; instanceId: string; sessionId: string; permissionId: string }\n | { type: \"permission.receiptsChanged\"; instanceId: string; sessionId: string; messageId?: string }\n\nexport interface NetworkAddress {\n ip: string\n family: \"ipv4\" | \"ipv6\"\n scope: \"external\" | \"internal\" | \"loopback\"\n /** Remote URL using the server's remote protocol/port for this IP. */\n remoteUrl: string\n}\n\nexport interface LatestReleaseInfo {\n version: string\n tag: string\n url: string\n channel: \"stable\" | \"dev\"\n publishedAt?: string\n notes?: string\n}\n\nexport interface UiMeta {\n version?: string\n source: \"bundled\" | \"downloaded\" | \"previous\" | \"override\" | \"dev-proxy\" | \"missing\"\n}\n\nexport interface SupportMeta {\n supported: boolean\n message?: string\n minServerVersion?: string\n latestServerVersion?: string\n latestServerUrl?: string\n}\n\nexport interface ServerMeta {\n /** URL desktop apps should use to connect (prefers loopback HTTP when enabled). */\n localUrl: string\n /** URL remote clients should use (prefers HTTPS when enabled). */\n remoteUrl?: string\n /** SSE endpoint advertised to clients (`/api/events` by default). */\n eventsUrl: string\n /** Host the server is bound to (e.g., 127.0.0.1 or 0.0.0.0). */\n host: string\n /** Listening mode derived from host binding. */\n listeningMode: \"local\" | \"all\"\n /** Actual local port in use after binding. */\n localPort: number\n /** Actual remote port in use after binding (when remoteUrl is set). */\n remotePort?: number\n /** Display label for the host (e.g., hostname or friendly name). */\n hostLabel: string\n /** Absolute path of the filesystem root exposed to clients. */\n workspaceRoot: string\n /** Reachable addresses for this server, external first. */\n addresses: NetworkAddress[]\n serverVersion?: string\n /** CodeNomad backend OS and Node runtime architecture, never the UI or OpenCode host. */\n system?: { platform: string; arch: string }\n ui?: UiMeta\n support?: SupportMeta\n /** Optional update info (dev channel only). */\n update?: LatestReleaseInfo | null\n}\n\nexport type {\n Preferences,\n ModelPreference,\n AgentModelSelections,\n RecentFolder,\n OpenCodeBinary,\n}\nexport type { PruneRequest, PruneResult } from \"./opencode/session-pruning/contract\"\n"]}
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { z } from "zod";
3
+ import { PENDING_REQUEST_SNAPSHOT_TIMEOUT_MS } from "../../api-types";
3
4
  import { readGitCommonDirectory } from "../../workspaces/git-common-directory";
4
5
  import { deferPendingDiscovery, markLoadedPendingSupported, PENDING_DISCOVERY_DEFERRED } from "../../workspaces/pending-discovery";
5
6
  const directorySchema = z.string().min(1).max(4096);
@@ -54,7 +55,7 @@ export function registerPendingRequestRoutes(app, deps) {
54
55
  if (!workspace)
55
56
  return reply.code(404).send({ error: "Workspace not found" });
56
57
  // Includes bounded Git ownership reads before/after the native reader's independent two-second deadline.
57
- const signal = AbortSignal.timeout(30_000);
58
+ const signal = AbortSignal.timeout(PENDING_REQUEST_SNAPSHOT_TIMEOUT_MS);
58
59
  try {
59
60
  const connection = await manager.getSharedServiceConnection(id);
60
61
  if (!connection)
@@ -1 +1 @@
1
- {"version":3,"file":"pending-requests.js","sourceRoot":"","sources":["../../../src/server/routes/pending-requests.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAKvB,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAA;AAC9E,OAAO,EAAE,qBAAqB,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAA;AAElI,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;AACnD,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC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OAAO,KAAK,CAAA;gBACd,CAAC,CAAC,CAAA;YACF,IAAI,IAAI,KAAK,CAAC,UAAU,CAAA;YACxB,IAAI,IAAI,GAAG,kBAAkB;gBAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;YACjF,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACpB,CAAC;IACH,CAAC;YAAS,CAAC;QAAC,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAAC,MAAM,CAAC,WAAW,EAAE,CAAA;IAAC,CAAC;AAC3E,CAAC","sourcesContent":["import type { FastifyInstance } from \"fastify\"\nimport path from \"node:path\"\nimport { z } from \"zod\"\nimport type { FormInfo, PermissionRequest } from \"@opencode/client\"\nimport type { WorkspacePendingRequestLocation, WorkspacePendingRequestsResponse } from \"../../api-types\"\nimport type { WorkspaceManager } from \"../../workspaces/manager\"\nimport type { WorktreeDeletionFence } from \"../../workspaces/worktree-session-evacuation\"\nimport { readGitCommonDirectory } from \"../../workspaces/git-common-directory\"\nimport { deferPendingDiscovery, markLoadedPendingSupported, PENDING_DISCOVERY_DEFERRED } from \"../../workspaces/pending-discovery\"\n\nconst directorySchema = z.string().min(1).max(4096)\nconst directoryListSchema = z.union([directorySchema, z.array(directorySchema).min(1).max(64)])\nconst querySchema = z.object({ directories: directoryListSchema, optionalDirectories: directoryListSchema.optional() }).strict()\nconst permissionSchema = z.object({\n id: z.string(), sessionID: z.string(), action: z.string(), resources: z.array(z.string()),\n save: z.array(z.string()).optional(), metadata: z.record(z.unknown()).optional(), message: z.string().optional(),\n source: z.object({ type: z.literal(\"tool\"), messageID: z.string(), id: z.string() }).optional(),\n})\nconst numeric = z.union([z.number(), z.enum([\"Infinity\", \"-Infinity\", \"NaN\"])])\nconst option = z.object({ value: z.string(), label: z.string(), description: z.string().optional() })\nconst field = z.object({\n key: z.string(), title: z.string().optional(), description: z.string().optional(),\n required: z.boolean().optional(), hidden: z.boolean().optional(),\n when: z.array(z.object({ key: z.string(), op: z.enum([\"eq\", \"neq\"]), value: z.union([z.string(), numeric, z.boolean()]) })).optional(),\n})\nconst fieldSchema = z.discriminatedUnion(\"type\", [\n field.extend({ type: z.literal(\"string\"), format: z.enum([\"email\", \"uri\", \"date\", \"date-time\"]).optional(),\n minLength: z.number().optional(), maxLength: z.number().optional(), pattern: z.string().optional(),\n placeholder: z.string().optional(), default: z.string().optional(), options: z.array(option).optional(), custom: z.boolean().optional() }),\n field.extend({ type: z.literal(\"number\"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }),\n field.extend({ type: z.literal(\"integer\"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }),\n field.extend({ type: z.literal(\"boolean\"), default: z.boolean().optional() }),\n field.extend({ type: z.literal(\"multiselect\"), options: z.array(option), minItems: z.number().optional(),\n maxItems: z.number().optional(), custom: z.boolean().optional(), default: z.array(z.string()).optional() }),\n field.extend({ type: z.literal(\"external\"), url: z.string() }),\n])\nconst formSchema = z.object({\n id: z.string(), sessionID: z.string(), title: z.string(), metadata: z.record(z.unknown()).optional(),\n fields: z.array(fieldSchema).min(1),\n})\n// One backend-owned RPC; never exposed by the generic instance proxy.\nconst snapshotSchema = z.object({ originDirectory: directorySchema, data: z.array(\n z.object({ directory: directorySchema, status: z.literal(\"complete\"), locations: z.array(z.object({\n location: z.object({ directory: directorySchema, workspaceID: z.string().optional() }).strict(),\n permissions: z.array(permissionSchema).max(1024), forms: z.array(formSchema).max(1024),\n })).max(64) }),\n).max(64) }).strict()\nconst nativeSchema = z.object({ output: snapshotSchema }).strict()\nconst unavailableSchema = z.object({\n _tag: z.literal(\"RpcError\"), type: z.enum([\"rpc.unavailable\", \"rpc.method_not_found\"]),\n message: z.string().min(1).max(4096),\n}).strict()\nconst MAX_RESPONSE_BYTES = 4 * 1024 * 1024\n\nexport interface PendingRequestsRouteDeps {\n workspaceManager: Pick<WorkspaceManager, \"get\" | \"getSharedServiceConnection\" | \"getServiceLocation\" | \"getServicePathStyle\" | \"getServiceDirectoryForPath\" | \"getWorktreeIdentityForPath\" | \"getHostPathForServicePath\" | \"ownsLocation\">\n worktreeDeletionFence: Pick<WorktreeDeletionFence, \"isBlocked\">\n}\n\nexport function registerPendingRequestRoutes(app: FastifyInstance, deps: PendingRequestsRouteDeps): void {\n app.get<{ Params: { id: string } }>(\"/api/workspaces/:id/pending-requests\", async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\")\n const query = querySchema.safeParse(request.query)\n if (!query.success) return reply.code(400).send({ error: \"Invalid pending request directories\" })\n const manager = deps.workspaceManager, id = request.params.id\n const workspace = manager.get(id)\n if (!workspace) return reply.code(404).send({ error: \"Workspace not found\" })\n // Includes bounded Git ownership reads before/after the native reader's independent two-second deadline.\n const signal = AbortSignal.timeout(30_000)\n try {\n const connection = await manager.getSharedServiceConnection(id)\n if (!connection) return reply.code(503).send({ error: \"Pending requests unavailable\" })\n if (deferPendingDiscovery(connection, { loadedOnly: true })) return reply.header(\"Retry-After\", \"30\").code(503).send({ error: PENDING_DISCOVERY_DEFERRED })\n const submitted = [...new Set(typeof query.data.directories === \"string\" ? [query.data.directories] : query.data.directories)]\n const optional = new Set(typeof query.data.optionalDirectories === \"string\" ? [query.data.optionalDirectories] : query.data.optionalDirectories ?? [])\n if ([...optional].some((directory) => !submitted.includes(directory))) return reply.code(400).send({ error: \"Invalid optional pending request directories\" })\n const result: Extract<WorkspacePendingRequestsResponse, { supported: true }> = { supported: true, directories: [] }\n const resolved: Array<{ submitted: string; directory: string; identity: string }> = []\n const bootstrap = manager.getServiceLocation(id)\n const style = manager.getServicePathStyle(id)\n const nativePath = style === \"win32\" ? path.win32 : style === \"posix\" ? path.posix : undefined\n const root = await manager.getServiceDirectoryForPath(id, workspace.path)\n const rootIdentity = bootstrap && await manager.getWorktreeIdentityForPath(id, bootstrap.directory)\n if (!bootstrap || bootstrap.workspaceID !== undefined || !root || !rootIdentity || !nativePath?.isAbsolute(bootstrap.directory)\n || await manager.getServiceDirectoryForPath(id, bootstrap.directory) !== root) throw new Error(\"Pending bootstrap unavailable\")\n const bootstrapDirectory = bootstrap.directory\n let common: Promise<string> | undefined\n // ponytail: eight ownership checks at a time keep bounded Windows Git reads inside the request deadline.\n for (let offset = 0; offset < submitted.length; offset += 8) {\n const candidates = await Promise.all(submitted.slice(offset, offset + 8).map(async (candidate) => {\n signal.throwIfAborted()\n const directory = await manager.getServiceDirectoryForPath(id, candidate)\n if (!directory && optional.has(candidate)) {\n result.directories.push({ directory: candidate, status: \"excluded\" })\n return\n }\n const identity = directory && await manager.getWorktreeIdentityForPath(id, directory)\n const host = directory && await manager.getHostPathForServicePath(id, directory)\n // Containment alone cannot authorize a nested independent clone.\n const sameRepository = directory === root || Boolean(host && await Promise.all([\n common ??= readGitCommonDirectory(workspace.path), readGitCommonDirectory(host),\n ]).then(([left, right]) => left === right, () => false))\n if (!directory || !identity || !host || !sameRepository) {\n result.directories.push({ directory: candidate, status: \"error\" })\n return\n }\n return { submitted: candidate, directory, identity }\n }))\n resolved.push(...candidates.filter((candidate) => candidate !== undefined))\n }\n if (!resolved.length && result.directories.some((entry) => entry.status !== \"excluded\")) return reply.code(403).send({ error: \"Directory does not belong to workspace\" })\n const assertCurrent = () => {\n signal.throwIfAborted()\n connection.assertCurrent()\n const currentRoot = manager.getServiceLocation(id)\n if (manager.get(id) !== workspace || currentRoot?.directory !== bootstrapDirectory || currentRoot.workspaceID !== undefined\n || deps.worktreeDeletionFence.isBlocked(rootIdentity) || resolved.some(({ identity }) => deps.worktreeDeletionFence.isBlocked(identity))) {\n throw new Error(\"Pending request ownership changed\")\n }\n }\n const assertOrigin = async (directory: string) => {\n // Resolve spelling/realpath aliases through existing ownership, but never accept a host alias as WSL-native provenance.\n if (!nativePath.isAbsolute(directory) || await manager.getServiceDirectoryForPath(id, directory) !== root\n || await manager.getServiceDirectoryForPath(id, workspace.path) !== root\n || await manager.getWorktreeIdentityForPath(id, bootstrapDirectory) !== rootIdentity) throw new Error(\"Invalid pending origin\")\n assertCurrent()\n }\n const assertCandidates = async () => {\n const currentCommon = resolved.some((candidate) => candidate.directory !== root) ? await readGitCommonDirectory(workspace.path) : undefined\n for (let offset = 0; offset < resolved.length; offset += 8) {\n await Promise.all(resolved.slice(offset, offset + 8).map(async (candidate) => {\n if (await manager.getServiceDirectoryForPath(id, candidate.submitted) !== candidate.directory\n || await manager.getWorktreeIdentityForPath(id, candidate.directory) !== candidate.identity) throw new Error(\"Pending directory ownership changed\")\n if (candidate.directory !== root) {\n const host = await manager.getHostPathForServicePath(id, candidate.directory)\n if (!host || await readGitCommonDirectory(host) !== currentCommon) throw new Error(\"Pending repository ownership changed\")\n }\n assertCurrent()\n }))\n }\n }\n assertCurrent()\n await assertOrigin(bootstrapDirectory)\n await assertCandidates()\n if (deferPendingDiscovery(connection, { loadedOnly: true })) return reply.header(\"Retry-After\", \"30\").code(503).send({ error: PENDING_DISCOVERY_DEFERRED })\n // Even an all-excluded historical batch must negotiate real RPC capability.\n // The established root is the only bootstrap, never an inactive candidate.\n const expected = new Set(resolved.length ? resolved.map((entry) => entry.directory) : [root])\n const url = new URL(\"/api/rpc/codenomad.pending-requests/snapshot\", connection.endpoint.url)\n url.searchParams.set(\"location[directory]\", bootstrapDirectory)\n const response = await connection.fetch(url, { method: \"POST\", signal, redirect: \"error\",\n headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ input: { directories: [...expected] } }) })\n assertCurrent()\n if (response.status === 400 && unavailableSchema.safeParse(await readBoundedJson(response)).success) {\n await assertOrigin(bootstrapDirectory)\n await assertCandidates()\n markLoadedPendingSupported(connection, false)\n return { supported: false } satisfies WorkspacePendingRequestsResponse\n }\n if (!response.ok) { await response.body?.cancel(); throw new Error(\"Native pending requests unavailable\") }\n const native = nativeSchema.parse(await readBoundedJson(response)).output\n await assertOrigin(native.originDirectory)\n if (native.data.length !== expected.size || new Set(native.data.map((entry) => entry.directory)).size !== expected.size\n || native.data.some((entry) => !expected.has(entry.directory))\n || native.data.reduce((count, entry) => count + entry.locations.length, 0) > 64) throw new Error(\"Invalid pending coverage\")\n for (const entry of native.data) {\n const locations: WorkspacePendingRequestLocation[] = []\n if (new Set(entry.locations.map((snapshot) => snapshot.location.directory)).size !== entry.locations.length) throw new Error(\"Duplicate pending placement\")\n if (entry.locations.reduce((count, snapshot) => count + snapshot.permissions.length, 0) > 1024\n || entry.locations.reduce((count, snapshot) => count + snapshot.forms.length, 0) > 1024) {\n throw new Error(\"Invalid pending request count\")\n }\n for (const snapshot of entry.locations) {\n const owned = snapshot.location.workspaceID === undefined && nativePath.isAbsolute(snapshot.location.directory)\n && await manager.getServiceDirectoryForPath(id, snapshot.location.directory) === entry.directory\n && await manager.ownsLocation(id, snapshot.location, connection.client, signal)\n if (!owned) throw new Error(\"Invalid pending placement\")\n locations.push({ location: { directory: snapshot.location.directory },\n permissions: snapshot.permissions as PermissionRequest[], forms: snapshot.forms as FormInfo[] })\n }\n // Even empty/cold coverage needs current directory ownership; no location.get.\n const stillOwned = await manager.getServiceDirectoryForPath(id, entry.directory) === entry.directory\n assertCurrent()\n if (!stillOwned) throw new Error(\"Pending directory ownership changed\")\n if (!locations.length) {\n locations.push({ location: { directory: entry.directory }, permissions: [], forms: [] })\n }\n for (const original of resolved.filter((candidate) => candidate.directory === entry.directory)) {\n result.directories.push({ directory: original.submitted, status: \"ok\", locations })\n }\n }\n await assertOrigin(native.originDirectory)\n await assertCandidates()\n markLoadedPendingSupported(connection, true)\n return result\n } catch {\n // Never convert transport, malformed coverage or ownership errors to empty.\n return reply.code(503).send({ error: \"Pending requests unavailable; retain existing queues\" })\n }\n })\n}\n\nasync function readBoundedJson(response: Response): Promise<unknown> {\n if (!response.body || !response.headers.get(\"content-type\")?.includes(\"application/json\")) throw new Error(\"Invalid pending response\")\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n try {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) return JSON.parse(Buffer.concat(chunks).toString(\"utf8\"), (_key, value) => {\n if (typeof value === \"number\" && !Number.isFinite(value)) throw new Error(\"Invalid pending JSON number\")\n return value\n })\n size += value.byteLength\n if (size > MAX_RESPONSE_BYTES) throw new Error(\"Pending response exceeded bound\")\n chunks.push(value)\n }\n } finally { await reader.cancel().catch(() => {}); reader.releaseLock() }\n}\n"]}
1
+ {"version":3,"file":"pending-requests.js","sourceRoot":"","sources":["../../../src/server/routes/pending-requests.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAGvB,OAAO,EAAE,mCAAmC,EAAE,MAAM,iBAAiB,CAAA;AAGrE,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAA;AAC9E,OAAO,EAAE,qBAAqB,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAA;AAElI,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;AACnD,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;AAC/F,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,mBAAmB,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAA;AAChI,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,SAAS,EAA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ify\"\nimport path from \"node:path\"\nimport { z } from \"zod\"\nimport type { FormInfo, PermissionRequest } from \"@opencode/client\"\nimport type { WorkspacePendingRequestLocation, WorkspacePendingRequestsResponse } from \"../../api-types\"\nimport { PENDING_REQUEST_SNAPSHOT_TIMEOUT_MS } from \"../../api-types\"\nimport type { WorkspaceManager } from \"../../workspaces/manager\"\nimport type { WorktreeDeletionFence } from \"../../workspaces/worktree-session-evacuation\"\nimport { readGitCommonDirectory } from \"../../workspaces/git-common-directory\"\nimport { deferPendingDiscovery, markLoadedPendingSupported, PENDING_DISCOVERY_DEFERRED } from \"../../workspaces/pending-discovery\"\n\nconst directorySchema = z.string().min(1).max(4096)\nconst directoryListSchema = z.union([directorySchema, z.array(directorySchema).min(1).max(64)])\nconst querySchema = z.object({ directories: directoryListSchema, optionalDirectories: directoryListSchema.optional() }).strict()\nconst permissionSchema = z.object({\n id: z.string(), sessionID: z.string(), action: z.string(), resources: z.array(z.string()),\n save: z.array(z.string()).optional(), metadata: z.record(z.unknown()).optional(), message: z.string().optional(),\n source: z.object({ type: z.literal(\"tool\"), messageID: z.string(), id: z.string() }).optional(),\n})\nconst numeric = z.union([z.number(), z.enum([\"Infinity\", \"-Infinity\", \"NaN\"])])\nconst option = z.object({ value: z.string(), label: z.string(), description: z.string().optional() })\nconst field = z.object({\n key: z.string(), title: z.string().optional(), description: z.string().optional(),\n required: z.boolean().optional(), hidden: z.boolean().optional(),\n when: z.array(z.object({ key: z.string(), op: z.enum([\"eq\", \"neq\"]), value: z.union([z.string(), numeric, z.boolean()]) })).optional(),\n})\nconst fieldSchema = z.discriminatedUnion(\"type\", [\n field.extend({ type: z.literal(\"string\"), format: z.enum([\"email\", \"uri\", \"date\", \"date-time\"]).optional(),\n minLength: z.number().optional(), maxLength: z.number().optional(), pattern: z.string().optional(),\n placeholder: z.string().optional(), default: z.string().optional(), options: z.array(option).optional(), custom: z.boolean().optional() }),\n field.extend({ type: z.literal(\"number\"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }),\n field.extend({ type: z.literal(\"integer\"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }),\n field.extend({ type: z.literal(\"boolean\"), default: z.boolean().optional() }),\n field.extend({ type: z.literal(\"multiselect\"), options: z.array(option), minItems: z.number().optional(),\n maxItems: z.number().optional(), custom: z.boolean().optional(), default: z.array(z.string()).optional() }),\n field.extend({ type: z.literal(\"external\"), url: z.string() }),\n])\nconst formSchema = z.object({\n id: z.string(), sessionID: z.string(), title: z.string(), metadata: z.record(z.unknown()).optional(),\n fields: z.array(fieldSchema).min(1),\n})\n// One backend-owned RPC; never exposed by the generic instance proxy.\nconst snapshotSchema = z.object({ originDirectory: directorySchema, data: z.array(\n z.object({ directory: directorySchema, status: z.literal(\"complete\"), locations: z.array(z.object({\n location: z.object({ directory: directorySchema, workspaceID: z.string().optional() }).strict(),\n permissions: z.array(permissionSchema).max(1024), forms: z.array(formSchema).max(1024),\n })).max(64) }),\n).max(64) }).strict()\nconst nativeSchema = z.object({ output: snapshotSchema }).strict()\nconst unavailableSchema = z.object({\n _tag: z.literal(\"RpcError\"), type: z.enum([\"rpc.unavailable\", \"rpc.method_not_found\"]),\n message: z.string().min(1).max(4096),\n}).strict()\nconst MAX_RESPONSE_BYTES = 4 * 1024 * 1024\n\nexport interface PendingRequestsRouteDeps {\n workspaceManager: Pick<WorkspaceManager, \"get\" | \"getSharedServiceConnection\" | \"getServiceLocation\" | \"getServicePathStyle\" | \"getServiceDirectoryForPath\" | \"getWorktreeIdentityForPath\" | \"getHostPathForServicePath\" | \"ownsLocation\">\n worktreeDeletionFence: Pick<WorktreeDeletionFence, \"isBlocked\">\n}\n\nexport function registerPendingRequestRoutes(app: FastifyInstance, deps: PendingRequestsRouteDeps): void {\n app.get<{ Params: { id: string } }>(\"/api/workspaces/:id/pending-requests\", async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\")\n const query = querySchema.safeParse(request.query)\n if (!query.success) return reply.code(400).send({ error: \"Invalid pending request directories\" })\n const manager = deps.workspaceManager, id = request.params.id\n const workspace = manager.get(id)\n if (!workspace) return reply.code(404).send({ error: \"Workspace not found\" })\n // Includes bounded Git ownership reads before/after the native reader's independent two-second deadline.\n const signal = AbortSignal.timeout(PENDING_REQUEST_SNAPSHOT_TIMEOUT_MS)\n try {\n const connection = await manager.getSharedServiceConnection(id)\n if (!connection) return reply.code(503).send({ error: \"Pending requests unavailable\" })\n if (deferPendingDiscovery(connection, { loadedOnly: true })) return reply.header(\"Retry-After\", \"30\").code(503).send({ error: PENDING_DISCOVERY_DEFERRED })\n const submitted = [...new Set(typeof query.data.directories === \"string\" ? [query.data.directories] : query.data.directories)]\n const optional = new Set(typeof query.data.optionalDirectories === \"string\" ? [query.data.optionalDirectories] : query.data.optionalDirectories ?? [])\n if ([...optional].some((directory) => !submitted.includes(directory))) return reply.code(400).send({ error: \"Invalid optional pending request directories\" })\n const result: Extract<WorkspacePendingRequestsResponse, { supported: true }> = { supported: true, directories: [] }\n const resolved: Array<{ submitted: string; directory: string; identity: string }> = []\n const bootstrap = manager.getServiceLocation(id)\n const style = manager.getServicePathStyle(id)\n const nativePath = style === \"win32\" ? path.win32 : style === \"posix\" ? path.posix : undefined\n const root = await manager.getServiceDirectoryForPath(id, workspace.path)\n const rootIdentity = bootstrap && await manager.getWorktreeIdentityForPath(id, bootstrap.directory)\n if (!bootstrap || bootstrap.workspaceID !== undefined || !root || !rootIdentity || !nativePath?.isAbsolute(bootstrap.directory)\n || await manager.getServiceDirectoryForPath(id, bootstrap.directory) !== root) throw new Error(\"Pending bootstrap unavailable\")\n const bootstrapDirectory = bootstrap.directory\n let common: Promise<string> | undefined\n // ponytail: eight ownership checks at a time keep bounded Windows Git reads inside the request deadline.\n for (let offset = 0; offset < submitted.length; offset += 8) {\n const candidates = await Promise.all(submitted.slice(offset, offset + 8).map(async (candidate) => {\n signal.throwIfAborted()\n const directory = await manager.getServiceDirectoryForPath(id, candidate)\n if (!directory && optional.has(candidate)) {\n result.directories.push({ directory: candidate, status: \"excluded\" })\n return\n }\n const identity = directory && await manager.getWorktreeIdentityForPath(id, directory)\n const host = directory && await manager.getHostPathForServicePath(id, directory)\n // Containment alone cannot authorize a nested independent clone.\n const sameRepository = directory === root || Boolean(host && await Promise.all([\n common ??= readGitCommonDirectory(workspace.path), readGitCommonDirectory(host),\n ]).then(([left, right]) => left === right, () => false))\n if (!directory || !identity || !host || !sameRepository) {\n result.directories.push({ directory: candidate, status: \"error\" })\n return\n }\n return { submitted: candidate, directory, identity }\n }))\n resolved.push(...candidates.filter((candidate) => candidate !== undefined))\n }\n if (!resolved.length && result.directories.some((entry) => entry.status !== \"excluded\")) return reply.code(403).send({ error: \"Directory does not belong to workspace\" })\n const assertCurrent = () => {\n signal.throwIfAborted()\n connection.assertCurrent()\n const currentRoot = manager.getServiceLocation(id)\n if (manager.get(id) !== workspace || currentRoot?.directory !== bootstrapDirectory || currentRoot.workspaceID !== undefined\n || deps.worktreeDeletionFence.isBlocked(rootIdentity) || resolved.some(({ identity }) => deps.worktreeDeletionFence.isBlocked(identity))) {\n throw new Error(\"Pending request ownership changed\")\n }\n }\n const assertOrigin = async (directory: string) => {\n // Resolve spelling/realpath aliases through existing ownership, but never accept a host alias as WSL-native provenance.\n if (!nativePath.isAbsolute(directory) || await manager.getServiceDirectoryForPath(id, directory) !== root\n || await manager.getServiceDirectoryForPath(id, workspace.path) !== root\n || await manager.getWorktreeIdentityForPath(id, bootstrapDirectory) !== rootIdentity) throw new Error(\"Invalid pending origin\")\n assertCurrent()\n }\n const assertCandidates = async () => {\n const currentCommon = resolved.some((candidate) => candidate.directory !== root) ? await readGitCommonDirectory(workspace.path) : undefined\n for (let offset = 0; offset < resolved.length; offset += 8) {\n await Promise.all(resolved.slice(offset, offset + 8).map(async (candidate) => {\n if (await manager.getServiceDirectoryForPath(id, candidate.submitted) !== candidate.directory\n || await manager.getWorktreeIdentityForPath(id, candidate.directory) !== candidate.identity) throw new Error(\"Pending directory ownership changed\")\n if (candidate.directory !== root) {\n const host = await manager.getHostPathForServicePath(id, candidate.directory)\n if (!host || await readGitCommonDirectory(host) !== currentCommon) throw new Error(\"Pending repository ownership changed\")\n }\n assertCurrent()\n }))\n }\n }\n assertCurrent()\n await assertOrigin(bootstrapDirectory)\n await assertCandidates()\n if (deferPendingDiscovery(connection, { loadedOnly: true })) return reply.header(\"Retry-After\", \"30\").code(503).send({ error: PENDING_DISCOVERY_DEFERRED })\n // Even an all-excluded historical batch must negotiate real RPC capability.\n // The established root is the only bootstrap, never an inactive candidate.\n const expected = new Set(resolved.length ? resolved.map((entry) => entry.directory) : [root])\n const url = new URL(\"/api/rpc/codenomad.pending-requests/snapshot\", connection.endpoint.url)\n url.searchParams.set(\"location[directory]\", bootstrapDirectory)\n const response = await connection.fetch(url, { method: \"POST\", signal, redirect: \"error\",\n headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ input: { directories: [...expected] } }) })\n assertCurrent()\n if (response.status === 400 && unavailableSchema.safeParse(await readBoundedJson(response)).success) {\n await assertOrigin(bootstrapDirectory)\n await assertCandidates()\n markLoadedPendingSupported(connection, false)\n return { supported: false } satisfies WorkspacePendingRequestsResponse\n }\n if (!response.ok) { await response.body?.cancel(); throw new Error(\"Native pending requests unavailable\") }\n const native = nativeSchema.parse(await readBoundedJson(response)).output\n await assertOrigin(native.originDirectory)\n if (native.data.length !== expected.size || new Set(native.data.map((entry) => entry.directory)).size !== expected.size\n || native.data.some((entry) => !expected.has(entry.directory))\n || native.data.reduce((count, entry) => count + entry.locations.length, 0) > 64) throw new Error(\"Invalid pending coverage\")\n for (const entry of native.data) {\n const locations: WorkspacePendingRequestLocation[] = []\n if (new Set(entry.locations.map((snapshot) => snapshot.location.directory)).size !== entry.locations.length) throw new Error(\"Duplicate pending placement\")\n if (entry.locations.reduce((count, snapshot) => count + snapshot.permissions.length, 0) > 1024\n || entry.locations.reduce((count, snapshot) => count + snapshot.forms.length, 0) > 1024) {\n throw new Error(\"Invalid pending request count\")\n }\n for (const snapshot of entry.locations) {\n const owned = snapshot.location.workspaceID === undefined && nativePath.isAbsolute(snapshot.location.directory)\n && await manager.getServiceDirectoryForPath(id, snapshot.location.directory) === entry.directory\n && await manager.ownsLocation(id, snapshot.location, connection.client, signal)\n if (!owned) throw new Error(\"Invalid pending placement\")\n locations.push({ location: { directory: snapshot.location.directory },\n permissions: snapshot.permissions as PermissionRequest[], forms: snapshot.forms as FormInfo[] })\n }\n // Even empty/cold coverage needs current directory ownership; no location.get.\n const stillOwned = await manager.getServiceDirectoryForPath(id, entry.directory) === entry.directory\n assertCurrent()\n if (!stillOwned) throw new Error(\"Pending directory ownership changed\")\n if (!locations.length) {\n locations.push({ location: { directory: entry.directory }, permissions: [], forms: [] })\n }\n for (const original of resolved.filter((candidate) => candidate.directory === entry.directory)) {\n result.directories.push({ directory: original.submitted, status: \"ok\", locations })\n }\n }\n await assertOrigin(native.originDirectory)\n await assertCandidates()\n markLoadedPendingSupported(connection, true)\n return result\n } catch {\n // Never convert transport, malformed coverage or ownership errors to empty.\n return reply.code(503).send({ error: \"Pending requests unavailable; retain existing queues\" })\n }\n })\n}\n\nasync function readBoundedJson(response: Response): Promise<unknown> {\n if (!response.body || !response.headers.get(\"content-type\")?.includes(\"application/json\")) throw new Error(\"Invalid pending response\")\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n try {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) return JSON.parse(Buffer.concat(chunks).toString(\"utf8\"), (_key, value) => {\n if (typeof value === \"number\" && !Number.isFinite(value)) throw new Error(\"Invalid pending JSON number\")\n return value\n })\n size += value.byteLength\n if (size > MAX_RESPONSE_BYTES) throw new Error(\"Pending response exceeded bound\")\n chunks.push(value)\n }\n } finally { await reader.cancel().catch(() => {}); reader.releaseLock() }\n}\n"]}
@@ -1,12 +1,26 @@
1
1
  import { z } from "zod";
2
2
  import { readLocationRef } from "../../opencode/compatibility/location";
3
3
  import { createNativeCodexUsage } from "../../usage/native-codex";
4
+ import { claudeCodeAuthEntry, claudeCodeCredential } from "../../usage/claude-credential";
5
+ import { readUsageCredentials } from "../../usage/native-credentials";
4
6
  import { getProviderUsage, resolveUsageProvider } from "../../usage/service";
5
7
  const UsageParamsSchema = z.object({ providerId: z.string().trim().min(1) });
6
8
  const UsageQuerySchema = z.object({
7
9
  instanceId: z.string().trim().min(1).max(256), sessionId: z.string().trim().min(1).max(256),
8
10
  modelId: z.string().trim().max(256).optional(),
9
11
  }).strict();
12
+ // opencode-claude runs Claude Code inside the daemon, so its login lives on the
13
+ // daemon host (possibly a WSL distro) under that host's environment.
14
+ async function claudeCodeHost(manager, instanceId, signal) {
15
+ const environment = await manager.getSessionEnvironment(instanceId, signal);
16
+ const wsl = Boolean(manager.getServiceWslDistro(instanceId));
17
+ return {
18
+ environment,
19
+ pathStyle: wsl || process.platform !== "win32" ? "posix" : "win32",
20
+ keychain: !wsl && process.platform === "darwin",
21
+ toHostPath: servicePath => manager.getHostPathForServicePath(instanceId, servicePath),
22
+ };
23
+ }
10
24
  export function registerUsageRoutes(app, deps) {
11
25
  const nativeCodexUsage = createNativeCodexUsage();
12
26
  app.get("/api/usage/:providerId", async (request, reply) => {
@@ -45,7 +59,13 @@ export function registerUsageRoutes(app, deps) {
45
59
  ? await nativeCodexUsage(connection, { instanceId, sessionId, directory: location.directory,
46
60
  providerId: params.data.providerId, modelId }, signal)
47
61
  : null;
48
- const usage = native ?? await getProviderUsage(params.data.providerId, { modelId });
62
+ const auth = !native && provider ? await readUsageCredentials(connection, signal) : {};
63
+ signal.throwIfAborted();
64
+ if (provider?.id === "claude-code") {
65
+ auth["claude-code"] = claudeCodeAuthEntry(await claudeCodeCredential(await claudeCodeHost(manager, instanceId, signal), signal));
66
+ signal.throwIfAborted();
67
+ }
68
+ const usage = native ?? await getProviderUsage(params.data.providerId, { modelId, auth });
49
69
  // Session movement, workspace eviction and reconnect fence publication too.
50
70
  const current = await connection.client.session.get({ sessionID: sessionId }, { signal });
51
71
  const currentLocation = readLoc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Y,CAAC,OAAO,CAAC,CAAA;QACvB,CAAC;IACH,CAAC,CACF,CAAA;AACH,CAAC;AAED,KAAK,UAAU,WAAW,CAAI,SAA2B,EAAE,MAAmB;IAC5E,IAAI,KAAkB,CAAA;IACtB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE;QACtD,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC,CAAA;QAC3D,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;IACzD,CAAC,CAAC,CAAA;IACF,IAAI,CAAC;QAAC,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,OAAO,CAAC,CAAC,CAAA;IAAC,CAAC;YACjD,CAAC;QAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IAAC,CAAC;AACxD,CAAC","sourcesContent":["import type { FastifyInstance } from \"fastify\"\nimport { z } from \"zod\"\nimport type { WorkspaceManager } from \"../../workspaces/manager\"\nimport { readLocationRef } from \"../../opencode/compatibility/location\"\nimport { createNativeCodexUsage } from \"../../usage/native-codex\"\nimport { getProviderUsage, resolveUsageProvider } from \"../../usage/service\"\n\nconst UsageParamsSchema = z.object({ providerId: z.string().trim().min(1) })\nconst UsageQuerySchema = z.object({\n instanceId: z.string().trim().min(1).max(256), sessionId: z.string().trim().min(1).max(256),\n modelId: z.string().trim().max(256).optional(),\n}).strict()\n\nexport interface UsageRouteDeps {\n workspaceManager: Pick<WorkspaceManager, \"get\" | \"getSharedServiceConnection\" | \"ownsLocation\">\n}\n\nexport function registerUsageRoutes(app: FastifyInstance, deps: UsageRouteDeps) {\n const nativeCodexUsage = createNativeCodexUsage()\n app.get<{ Params: { providerId: string }; Querystring: z.infer<typeof UsageQuerySchema> }>(\n \"/api/usage/:providerId\",\n async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\")\n const params = UsageParamsSchema.safeParse(request.params)\n const query = UsageQuerySchema.safeParse(request.query ?? {})\n if (!params.success || !query.success) return reply.code(400).send({ error: \"Invalid usage request\" })\n const { instanceId, sessionId, modelId } = query.data\n const manager = deps.workspaceManager\n const workspace = manager.get(instanceId)\n if (!workspace) return reply.code(404).send({ error: \"Workspace not found\" })\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 15_000)\n const signal = controller.signal\n try {\n return await boundedRead(async () => {\n const connection = await manager.getSharedServiceConnection(instanceId)\n signal.throwIfAborted()\n if (!connection) return reply.code(503).send({ error: \"Provider usage unavailable\" })\n connection.assertCurrent()\n signal.throwIfAborted()\n const session = await connection.client.session.get({ sessionID: sessionId }, { signal })\n const location = readLocationRef(session.location)\n const owned = location.workspaceID === undefined && await manager.ownsLocation(instanceId, location, connection.client)\n signal.throwIfAborted()\n if (!owned) {\n return reply.code(403).send({ error: \"Session does not belong to workspace\" })\n }\n signal.throwIfAborted()\n connection.assertCurrent()\n const provider = resolveUsageProvider(params.data.providerId)\n const native = !provider || provider.id === \"codex\"\n ? await nativeCodexUsage(connection, { instanceId, sessionId, directory: location.directory,\n providerId: params.data.providerId, modelId }, signal)\n : null\n const usage = native ?? await getProviderUsage(params.data.providerId, { modelId })\n // Session movement, workspace eviction and reconnect fence publication too.\n const current = await connection.client.session.get({ sessionID: sessionId }, { signal })\n const currentLocation = readLocationRef(current.location)\n connection.assertCurrent()\n signal.throwIfAborted()\n const stillOwned = manager.get(instanceId) === workspace && currentLocation.directory === location.directory\n && currentLocation.workspaceID === undefined && await manager.ownsLocation(instanceId, currentLocation, connection.client)\n signal.throwIfAborted()\n if (!stillOwned) {\n return reply.code(403).send({ error: \"Session does not belong to workspace\" })\n }\n signal.throwIfAborted()\n connection.assertCurrent()\n return usage\n }, signal)\n } catch (error) {\n // Do not serialize/log SDK errors: credential exports and request bodies\n // are server-only, and arbitrary upstream errors can contain secrets.\n const missing = error && typeof error === \"object\" && \"_tag\" in error && error._tag === \"SessionNotFoundError\"\n return reply.code(missing ? 404 : 503).send({ error: missing ? \"Session not found\" : \"Provider usage unavailable\" })\n } finally {\n clearTimeout(timeout)\n }\n },\n )\n}\n\nasync function boundedRead<T>(operation: () => Promise<T>, signal: AbortSignal): Promise<T> {\n let abort!: () => void\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => reject(new Error(\"Provider usage timed out\"))\n signal.addEventListener(\"abort\", abort, { once: true })\n })\n try { return await Promise.race([operation(), aborted]) }\n finally { signal.removeEventListener(\"abort\", abort) }\n}\n"]}
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/server/routes/usage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAA;AACvE,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAuB,MAAM,+BAA+B,CAAA;AAC9G,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAA;AACrE,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAE5E,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC5E,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CA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AAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,sBAAsB,CAAA;YAC9G,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,4BAA4B,EAAE,CAAC,CAAA;QACtH,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,OAAO,CAAC,CAAA;QACvB,CAAC;IACH,CAAC,CACF,CAAA;AACH,CAAC;AAED,KAAK,UAAU,WAAW,CAAI,SAA2B,EAAE,MAAmB;IAC5E,IAAI,KAAkB,CAAA;IACtB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE;QACtD,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC,CAAA;QAC3D,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;IACzD,CAAC,CAAC,CAAA;IACF,IAAI,CAAC;QAAC,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,OAAO,CAAC,CAAC,CAAA;IAAC,CAAC;YACjD,CAAC;QAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IAAC,CAAC;AACxD,CAAC","sourcesContent":["import type { FastifyInstance } from \"fastify\"\nimport { z } from \"zod\"\nimport type { WorkspaceManager } from \"../../workspaces/manager\"\nimport { readLocationRef } from \"../../opencode/compatibility/location\"\nimport { createNativeCodexUsage } from \"../../usage/native-codex\"\nimport { claudeCodeAuthEntry, claudeCodeCredential, type ClaudeCodeHost } from \"../../usage/claude-credential\"\nimport { readUsageCredentials } from \"../../usage/native-credentials\"\nimport { getProviderUsage, resolveUsageProvider } from \"../../usage/service\"\n\nconst UsageParamsSchema = z.object({ providerId: z.string().trim().min(1) })\nconst UsageQuerySchema = z.object({\n instanceId: z.string().trim().min(1).max(256), sessionId: z.string().trim().min(1).max(256),\n modelId: z.string().trim().max(256).optional(),\n}).strict()\n\nexport interface UsageRouteDeps {\n workspaceManager: Pick<WorkspaceManager, \"get\" | \"getSharedServiceConnection\" | \"ownsLocation\"\n | \"getSessionEnvironment\" | \"getServiceWslDistro\" | \"getHostPathForServicePath\">\n}\n\n// opencode-claude runs Claude Code inside the daemon, so its login lives on the\n// daemon host (possibly a WSL distro) under that host's environment.\nasync function claudeCodeHost(manager: UsageRouteDeps[\"workspaceManager\"], instanceId: string, signal: AbortSignal): Promise<ClaudeCodeHost> {\n const environment = await manager.getSessionEnvironment(instanceId, signal)\n const wsl = Boolean(manager.getServiceWslDistro(instanceId))\n return {\n environment,\n pathStyle: wsl || process.platform !== \"win32\" ? \"posix\" : \"win32\",\n keychain: !wsl && process.platform === \"darwin\",\n toHostPath: servicePath => manager.getHostPathForServicePath(instanceId, servicePath),\n }\n}\n\nexport function registerUsageRoutes(app: FastifyInstance, deps: UsageRouteDeps) {\n const nativeCodexUsage = createNativeCodexUsage()\n app.get<{ Params: { providerId: string }; Querystring: z.infer<typeof UsageQuerySchema> }>(\n \"/api/usage/:providerId\",\n async (request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\")\n const params = UsageParamsSchema.safeParse(request.params)\n const query = UsageQuerySchema.safeParse(request.query ?? {})\n if (!params.success || !query.success) return reply.code(400).send({ error: \"Invalid usage request\" })\n const { instanceId, sessionId, modelId } = query.data\n const manager = deps.workspaceManager\n const workspace = manager.get(instanceId)\n if (!workspace) return reply.code(404).send({ error: \"Workspace not found\" })\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 15_000)\n const signal = controller.signal\n try {\n return await boundedRead(async () => {\n const connection = await manager.getSharedServiceConnection(instanceId)\n signal.throwIfAborted()\n if (!connection) return reply.code(503).send({ error: \"Provider usage unavailable\" })\n connection.assertCurrent()\n signal.throwIfAborted()\n const session = await connection.client.session.get({ sessionID: sessionId }, { signal })\n const location = readLocationRef(session.location)\n const owned = location.workspaceID === undefined && await manager.ownsLocation(instanceId, location, connection.client)\n signal.throwIfAborted()\n if (!owned) {\n return reply.code(403).send({ error: \"Session does not belong to workspace\" })\n }\n signal.throwIfAborted()\n connection.assertCurrent()\n const provider = resolveUsageProvider(params.data.providerId)\n const native = !provider || provider.id === \"codex\"\n ? await nativeCodexUsage(connection, { instanceId, sessionId, directory: location.directory,\n providerId: params.data.providerId, modelId }, signal)\n : null\n const auth = !native && provider ? await readUsageCredentials(connection, signal) : {}\n signal.throwIfAborted()\n if (provider?.id === \"claude-code\") {\n auth[\"claude-code\"] = claudeCodeAuthEntry(await claudeCodeCredential(await claudeCodeHost(manager, instanceId, signal), signal))\n signal.throwIfAborted()\n }\n const usage = native ?? await getProviderUsage(params.data.providerId, { modelId, auth })\n // Session movement, workspace eviction and reconnect fence publication too.\n const current = await connection.client.session.get({ sessionID: sessionId }, { signal })\n const currentLocation = readLocationRef(current.location)\n connection.assertCurrent()\n signal.throwIfAborted()\n const stillOwned = manager.get(instanceId) === workspace && currentLocation.directory === location.directory\n && currentLocation.workspaceID === undefined && await manager.ownsLocation(instanceId, currentLocation, connection.client)\n signal.throwIfAborted()\n if (!stillOwned) {\n return reply.code(403).send({ error: \"Session does not belong to workspace\" })\n }\n signal.throwIfAborted()\n connection.assertCurrent()\n return usage\n }, signal)\n } catch (error) {\n // Do not serialize/log SDK errors: credential exports and request bodies\n // are server-only, and arbitrary upstream errors can contain secrets.\n const missing = error && typeof error === \"object\" && \"_tag\" in error && error._tag === \"SessionNotFoundError\"\n return reply.code(missing ? 404 : 503).send({ error: missing ? \"Session not found\" : \"Provider usage unavailable\" })\n } finally {\n clearTimeout(timeout)\n }\n },\n )\n}\n\nasync function boundedRead<T>(operation: () => Promise<T>, signal: AbortSignal): Promise<T> {\n let abort!: () => void\n const aborted = new Promise<never>((_resolve, reject) => {\n abort = () => reject(new Error(\"Provider usage timed out\"))\n signal.addEventListener(\"abort\", abort, { once: true })\n })\n try { return await Promise.race([operation(), aborted]) }\n finally { signal.removeEventListener(\"abort\", abort) }\n}\n"]}
@@ -1,11 +1,15 @@
1
1
  import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
2
5
  import test from "node:test";
3
6
  import Fastify from "fastify";
4
7
  import { OpenCode } from "@opencode/client";
5
8
  import { registerUsageRoutes } from "./usage";
6
9
  function harness() {
7
10
  const expires = Date.now() + 3600000;
8
- const state = { nativeCalls: [], quotaCalls: 0, directory: "/wsl/repo", switched: false, oldEndpoint: false, fail: false };
11
+ const state = { nativeCalls: [], quotaCalls: 0, directory: "/wsl/repo", switched: false, oldEndpoint: false, fail: false,
12
+ daemonEnvironment: { HOME: "/home/dev" }, hostFiles: new Map() };
9
13
  const logs = [];
10
14
  const app = Fastify({ logger: { stream: { write: (text) => { logs.push(text); } } } });
11
15
  const workspace = {};
@@ -30,7 +34,7 @@ function harness() {
30
34
  return Response.json({ data: [{ id: "selected", integrationID: "openai", active: true, label: "Secret account",
31
35
  value: { type: "oauth", methodID: "chatgpt-headless", access: "secret-token", refresh: "secret-refresh", expires,
32
36
  metadata: { accountID: "secret-account" } },
33
- }] }, { status: state.oldEndpoint ? 404 : 200 });
37
+ }, { id: "key", integrationID: "deepinfra", active: true, label: "Key", value: { type: "key", key: "secret-deepinfra" } }] }, { status: state.oldEndpoint ? 404 : 200 });
34
38
  return Response.json({}, { status: 404 });
35
39
  } });
36
40
  const connection = { client, assertCurrent: () => { } };
@@ -38,6 +42,9 @@ function harness() {
38
42
  get: id => id === "instance" ? workspace : undefined,
39
43
  getSharedServiceConnection: async () => connection,
40
44
  ownsLocation: async (_id, location) => location.directory === "/wsl/repo",
45
+ getSessionEnvironment: async () => ({ ...state.daemonEnvironment }),
46
+ getServiceWslDistro: () => "Ubuntu",
47
+ getHostPathForServicePath: async (_id, servicePath) => state.hostFiles.get(servicePath)?.path,
41
48
  };
42
49
  registerUsageRoutes(app, { workspaceManager: manager });
43
50
  return { app, state, logs };
@@ -121,16 +128,67 @@ test("session movement during quota fetch fences publication", async () => {
121
128
  }
122
129
  });
123
130
  test("owned unknown provider retains a typed unsupported result without a quota request", async () => {
124
- const { app } = harness();
131
+ const { app, state } = harness();
125
132
  try {
126
133
  const response = await app.inject({ url: url.replace("/usage/openai", "/usage/unknown-provider") });
127
134
  assert.equal(response.statusCode, 200);
128
135
  assert.equal(response.json().providerId, null);
129
136
  assert.equal(response.json().supported, false);
130
137
  assert.deepEqual(response.json().windows, {});
138
+ assert.equal(state.nativeCalls.includes("/api/credential"), false);
131
139
  }
132
140
  finally {
133
141
  await app.close();
134
142
  }
135
143
  });
144
+ test("other providers use the daemon's selected native credential, never returning it", async () => {
145
+ const { app, logs } = harness();
146
+ const previousFetch = globalThis.fetch;
147
+ globalThis.fetch = async (input, init) => {
148
+ assert.equal(String(input), "https://api.deepinfra.com/v1/me?checklist=true");
149
+ assert.equal(new Headers(init?.headers).get("authorization"), "Bearer secret-deepinfra");
150
+ return Response.json({ checklist: { stripe_balance: -4 } });
151
+ };
152
+ try {
153
+ const response = await app.inject({ url: url.replace("/usage/openai", "/usage/deepinfra") });
154
+ assert.equal(response.statusCode, 200);
155
+ assert.equal(response.json().ok, true);
156
+ assert.equal(response.json().windows.credits_balance.valueLabel, "$4.00");
157
+ assert.equal([response.body, ...logs].join("").includes("secret-"), false);
158
+ }
159
+ finally {
160
+ globalThis.fetch = previousFetch;
161
+ await app.close();
162
+ }
163
+ });
164
+ test("claude-code sessions read Claude Code's login on the daemon host, never returning it", async () => {
165
+ const { app, state, logs } = harness();
166
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-usage-route-claude-"));
167
+ const file = path.join(directory, "credentials.json");
168
+ fs.writeFileSync(file, JSON.stringify({ claudeAiOauth: { accessToken: "secret-distro-login", expiresAt: Date.now() + 3_600_000 } }));
169
+ state.hostFiles.set("/home/dev/.claude/.credentials.json", { path: file });
170
+ const authorizations = [];
171
+ const previousFetch = globalThis.fetch;
172
+ globalThis.fetch = async (input, init) => {
173
+ assert.equal(String(input), "https://api.anthropic.com/api/oauth/usage");
174
+ authorizations.push(new Headers(init?.headers).get("authorization") ?? "");
175
+ return Response.json({ limits: [{ kind: "session", percent: 7 }] });
176
+ };
177
+ const claudeUrl = url.replace("/usage/openai", "/usage/claude-code");
178
+ try {
179
+ const response = await app.inject({ url: claudeUrl });
180
+ assert.equal(response.json().providerId, "claude-code");
181
+ assert.equal(response.json().windows["5h"].usedPercent, 7);
182
+ // A profile token outranks the stored login and fences the cached snapshot.
183
+ state.daemonEnvironment.CLAUDE_CODE_OAUTH_TOKEN = "secret-profile-token";
184
+ assert.equal((await app.inject({ url: claudeUrl })).json().ok, true);
185
+ assert.deepEqual(authorizations, ["Bearer secret-distro-login", "Bearer secret-profile-token"]);
186
+ assert.equal([response.body, ...logs].join("").includes("secret-"), false);
187
+ }
188
+ finally {
189
+ globalThis.fetch = previousFetch;
190
+ await app.close();
191
+ fs.rmSync(directory, { recursive: true, force: true });
192
+ }
193
+ });
136
194
  //# sourceMappingURL=usage.test.js.map