@cortexkit/opencode-anthropic-auth 1.23.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +239 -195
  2. package/dist/cli-failure.d.ts +69 -0
  3. package/dist/cli.d.ts +14 -9
  4. package/dist/cli.js +98 -76
  5. package/dist/custody-dimensions.d.ts +7 -24
  6. package/dist/custody-mode.d.ts +29 -169
  7. package/dist/effort-history.d.ts +6 -1
  8. package/dist/index-1jkyhgyr.js +2 -0
  9. package/dist/{index-8y2t4mwz.js → index-2arfb1y3.js} +1 -1
  10. package/dist/{index-0jfsxyn9.js → index-4ya27n12.js} +1 -1
  11. package/dist/index-aaajxwzd.js +2 -0
  12. package/dist/index-ae3fq4n6.js +42 -0
  13. package/dist/{index-xzbhzz0a.js → index-fds0s2j4.js} +2 -2
  14. package/dist/index-nngmvczq.js +450 -0
  15. package/dist/index-pn597b6f.js +2 -0
  16. package/dist/{index-1gr8v4fn.js → index-rqync0pc.js} +1 -1
  17. package/dist/index.js +1 -38
  18. package/dist/native-command.d.ts +19 -0
  19. package/dist/rpc/notifications.d.ts +2 -1
  20. package/dist/rpc/port-file.js +1 -1
  21. package/dist/rpc/protocol.d.ts +8 -4
  22. package/dist/rpc/protocol.js +1 -1
  23. package/dist/rpc/rpc-client.d.ts +2 -0
  24. package/dist/rpc/rpc-client.js +1 -1
  25. package/dist/rpc/rpc-dir.js +1 -1
  26. package/dist/rpc/rpc-server.d.ts +5 -1
  27. package/dist/setup/command.d.ts +12 -0
  28. package/dist/setup/command.test.d.ts +1 -0
  29. package/dist/setup/native-activation.d.ts +29 -0
  30. package/dist/setup/native-enrollment.d.ts +26 -0
  31. package/dist/setup/native-enrollment.test.d.ts +1 -0
  32. package/dist/setup/native-local.d.ts +20 -0
  33. package/dist/setup/native-login.d.ts +3 -0
  34. package/dist/setup/native-paths.d.ts +15 -0
  35. package/dist/setup/native-paths.test.d.ts +1 -0
  36. package/dist/setup/pi.d.ts +13 -3
  37. package/dist/setup/process-fence.d.ts +7 -1
  38. package/dist/setup/process-fence.test.d.ts +1 -0
  39. package/dist/sidebar-state.js +1 -1
  40. package/dist/tui/command-dialogs.d.ts +5 -0
  41. package/dist/tui-preferences.js +2 -2
  42. package/dist/v2/activation.d.ts +7 -0
  43. package/dist/v2/adapter.d.ts +276 -0
  44. package/dist/v2/install.d.ts +13 -0
  45. package/dist/v2/lifecycle.d.ts +8 -0
  46. package/dist/v2/menu-contract.d.ts +8 -0
  47. package/dist/v2/menu.d.ts +10 -0
  48. package/dist/v2/models.d.ts +6 -0
  49. package/dist/v2/ownership.d.ts +11 -0
  50. package/dist/v2/prime.d.ts +12 -0
  51. package/dist/v2/rpc.d.ts +50 -0
  52. package/dist/v2/server.d.ts +8 -0
  53. package/dist/v2/server.js +4 -0
  54. package/dist/v2/setup.d.ts +58 -0
  55. package/dist/v2/source.d.ts +41 -0
  56. package/dist/v2/tui.d.ts +13 -0
  57. package/dist/v2/tui.js +2 -0
  58. package/dist/v2/wire.d.ts +36 -0
  59. package/package.json +20 -5
  60. package/src/rpc/notifications.ts +9 -2
  61. package/src/rpc/protocol.ts +8 -7
  62. package/src/rpc/rpc-client.ts +17 -0
  63. package/src/rpc/rpc-server.ts +20 -3
  64. package/src/tui/command-dialogs.tsx +264 -0
  65. package/src/tui/entry.mjs +44 -18
  66. package/src/tui-compiled/rpc/protocol.ts +8 -7
  67. package/src/tui-compiled/rpc/rpc-client.ts +17 -0
  68. package/src/tui-compiled/tui/command-dialogs.tsx +315 -76
  69. package/src/tui-compiled/tui.tsx +24 -7
  70. package/src/tui.tsx +37 -9
  71. package/dist/claustrum-enrollment-registry.d.ts +0 -4
  72. package/dist/custody-enrollment.d.ts +0 -14
  73. package/dist/custody-live.d.ts +0 -111
  74. package/dist/custody-manifest-watcher.d.ts +0 -16
  75. package/dist/index-1fq7h6yd.js +0 -430
  76. package/dist/index-797pmamn.js +0 -2
  77. package/dist/index-a5d6v3ba.js +0 -5
  78. package/dist/index-n96q8pks.js +0 -2
  79. package/dist/index-xxhyhp98.js +0 -2
  80. package/dist/index-z7gfdyv3.js +0 -1
  81. package/dist/local-login.d.ts +0 -64
  82. package/dist/logger-kk9vyem9.js +0 -1
@@ -1,6 +1,8 @@
1
+ import type { CommandApplyRequest, CommandApplyResult } from '@cortexkit/anthropic-auth-core';
1
2
  import type { ApplyRequest, ApplyResult, RpcNotification } from './protocol';
2
3
  export interface RpcClient {
3
4
  pending: (lastReceivedId: number, sessionId: string) => Promise<RpcNotification[]>;
4
5
  apply: (request: ApplyRequest) => Promise<ApplyResult>;
6
+ applyMenu: (request: CommandApplyRequest) => Promise<CommandApplyResult>;
5
7
  }
6
8
  export declare function createRpcClient(dir: string, expectedPid?: number): RpcClient;
@@ -1 +1 @@
1
- import{ph as l}from"../index-0jfsxyn9.js";import"../index-n96q8pks.js";async function a(n,e,t,o){let r=await l(n,o);if(!r)return null;let i=new AbortController,p=setTimeout(()=>i.abort(),2000);try{let s=await fetch(`http://127.0.0.1:${r.port}/rpc/${e}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.token}`},body:JSON.stringify(t),signal:i.signal});if(!s.ok)return null;return await s.json()}catch{return null}finally{clearTimeout(p)}}function u(n,e){return{async pending(t,o){return(await a(n,"pending-notifications",{lastReceivedId:t,sessionId:o},e))?.messages??[]},async apply(t){return await a(n,"apply",{...t},e)??{text:"apply failed",knobs:{}}}}}export{u as createRpcClient};
1
+ import{qe as s}from"../index-4ya27n12.js";import"../index-aaajxwzd.js";async function i(e,o,t,n){let r=await s(e,n);if(!r)return null;let a=new AbortController,l=setTimeout(()=>a.abort(),2000);try{let p=await fetch(`http://127.0.0.1:${r.port}/rpc/${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.token}`},body:JSON.stringify(t),signal:a.signal});if(!p.ok)return null;return await p.json()}catch{return null}finally{clearTimeout(l)}}function c(e,o){return{async pending(t,n){return(await i(e,"pending-notifications",{lastReceivedId:t,sessionId:n},o))?.messages??[]},async apply(t){return await i(e,"apply",{...t},o)??{text:"apply failed",knobs:{}}},async applyMenu(t){if(t.command!=="claude"||!t.sessionId?.trim())throw TypeError("A claude menu sessionId is required");let n=await i(e,"apply-menu",{...t},o);if(!n)throw Error("Menu apply unavailable; outcome unknown");return n}}}export{c as createRpcClient};
@@ -1 +1 @@
1
- import{rh as a,sh as b}from"../index-1gr8v4fn.js";import"../index-n96q8pks.js";export{a as tmpdir,b as getRpcDir};
1
+ import{q as a,r as b}from"../index-rqync0pc.js";import"../index-aaajxwzd.js";export{a as tmpdir,b as getRpcDir};
@@ -1,3 +1,4 @@
1
+ import { type CommandApplyRequest, type CommandApplyResult } from '@cortexkit/anthropic-auth-core';
1
2
  import type { drainNotifications } from './notifications';
2
3
  import type { ApplyRequest, ApplyResult } from './protocol';
3
4
  export interface RpcServerHandle {
@@ -8,6 +9,9 @@ export interface RpcServerHandle {
8
9
  export interface RpcServerOptions {
9
10
  dir: string;
10
11
  drain: typeof drainNotifications;
11
- apply: (request: ApplyRequest) => Promise<ApplyResult>;
12
+ /** Structured-menu hosts need no text parser; internal text consumers may still supply one. */
13
+ apply?: (request: ApplyRequest) => Promise<ApplyResult>;
14
+ /** Run menu actions through the host's credential service, not legacy account-file writes. */
15
+ applyMenu?: (request: CommandApplyRequest) => Promise<CommandApplyResult>;
12
16
  }
13
17
  export declare function startRpcServer(options: RpcServerOptions): Promise<RpcServerHandle>;
@@ -1,8 +1,20 @@
1
+ import type { Writable } from 'node:stream';
2
+ import { detectAll } from './detect.ts';
3
+ import { activateNativeVaultForHost } from './native-activation.ts';
4
+ import { migrateNativeLocalForHost } from './native-local.ts';
5
+ import { loginNativeOffline } from './native-login.ts';
1
6
  import type { CommandRunner, ProcessFence } from './types.ts';
2
7
  export interface SetupCommandOptions {
3
8
  runner?: CommandRunner;
4
9
  fence?: ProcessFence;
5
10
  env?: NodeJS.ProcessEnv;
6
11
  isInteractive?: boolean;
12
+ /** Let tests substitute host detection and per-host vault activation. */
13
+ detect?: typeof detectAll;
14
+ activate?: typeof activateNativeVaultForHost;
15
+ migrateLocal?: typeof migrateNativeLocalForHost;
16
+ localLogin?: typeof loginNativeOffline;
17
+ /** Where setup prints its progress and errors; defaults to stdout. */
18
+ output?: Writable;
7
19
  }
8
20
  export declare function runSetupCommand(argv?: string[], options?: SetupCommandOptions): Promise<number>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ import { type NativeCustodyActivationHooks, type NativeCustodyInventory } from '@cortexkit/anthropic-auth-core';
2
+ import { type NativeVaultEnrollmentOptions } from './native-enrollment.ts';
3
+ import { type NativeSetupPaths } from './native-paths.ts';
4
+ import type { CommandRunner, HarnessKind, ProcessFence } from './types.ts';
5
+ export declare class NativeVaultActivationError extends Error {
6
+ readonly code: 'auth-content-refused' | 'host-auth-invalid' | 'primary-conflict' | 'consent-required' | 'primary-unverified';
7
+ constructor(code: 'auth-content-refused' | 'host-auth-invalid' | 'primary-conflict' | 'consent-required' | 'primary-unverified');
8
+ }
9
+ export interface NativeVaultActivationOptions {
10
+ env: NodeJS.ProcessEnv;
11
+ runner: CommandRunner;
12
+ fence: ProcessFence;
13
+ /** Consent to move Pi's stored authentication aside; never consent to delete it. */
14
+ removePiAnthropicAuth: boolean;
15
+ /**
16
+ * Tests override the host paths, enrollment client and vault listing;
17
+ * production resolves them from the host's environment.
18
+ */
19
+ paths?: NativeSetupPaths;
20
+ enrollment?: Pick<NativeVaultEnrollmentOptions, 'paths' | 'client' | 'ckBinary' | 'connectionFile'>;
21
+ discover?: () => Promise<NativeCustodyInventory>;
22
+ hooks?: NativeCustodyActivationHooks;
23
+ }
24
+ /**
25
+ * Enroll this stopped host, discover its verified default vault account and
26
+ * leave the host auth slot untouched. Local credentials, migration journal,
27
+ * account metadata and routing assignments are not inputs to this operation.
28
+ */
29
+ export declare function activateNativeVaultForHost(host: HarnessKind, options: NativeVaultActivationOptions): Promise<'committed' | 'already-vault'>;
@@ -0,0 +1,26 @@
1
+ import { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentPaths } from '@cortexkit/common-auth/claustrum';
2
+ import type { CommandRunner, HarnessKind } from './types.ts';
3
+ export interface NativeVaultEnrollmentOptions {
4
+ env: NodeJS.ProcessEnv;
5
+ runner: CommandRunner;
6
+ /**
7
+ * Check that selected host processes are stopped and their inspection succeeded,
8
+ * and reject an inherited OPENCODE_AUTH_CONTENT snapshot. These checks run
9
+ * before each enrollment request, token write and permission change.
10
+ */
11
+ processFence: () => Promise<void>;
12
+ paths?: ClaustrumEnrollmentPaths;
13
+ client?: ClaustrumEnrollmentClient;
14
+ ckBinary?: string;
15
+ connectionFile?: string;
16
+ }
17
+ export declare class NativeVaultEnrollmentError extends Error {
18
+ readonly code: 'enrollment-refused' | 'enrollment-reset' | 'approval-refused' | 'permission-refused';
19
+ constructor(code: 'enrollment-refused' | 'enrollment-reset' | 'approval-refused' | 'permission-refused');
20
+ }
21
+ /**
22
+ * Enroll this stopped host and grant permission to list native Claude accounts.
23
+ * This function does not fetch OAuth tokens or change which store serves requests;
24
+ * account discovery and the credential-store switch are separate setup steps.
25
+ */
26
+ export declare function enrollNativeVaultForHost(host: HarnessKind, options: NativeVaultEnrollmentOptions): Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ import { type NativeSetupPaths } from './native-paths';
2
+ import type { HarnessKind, ProcessFence } from './types';
3
+ export interface NativeOfflineLogin {
4
+ credential: {
5
+ type: 'oauth';
6
+ access: string;
7
+ refresh: string;
8
+ expires: number;
9
+ };
10
+ accountIdentity: string;
11
+ }
12
+ export interface NativeLocalSetupOptions {
13
+ env: NodeJS.ProcessEnv;
14
+ fence: ProcessFence;
15
+ paths?: NativeSetupPaths;
16
+ removePiAnthropicAuth: boolean;
17
+ login?: (host: HarnessKind) => Promise<NativeOfflineLogin>;
18
+ }
19
+ /** Transfer local credentials while hosts are stopped, before telling the user to restart. */
20
+ export declare function migrateNativeLocalForHost(host: HarnessKind, options: NativeLocalSetupOptions): Promise<void>;
@@ -0,0 +1,3 @@
1
+ import type { NativeOfflineLogin } from './native-local';
2
+ import type { HarnessKind } from './types';
3
+ export declare function loginNativeOffline(host: HarnessKind): Promise<NativeOfflineLogin>;
@@ -0,0 +1,15 @@
1
+ import { type NativePoolPaths } from '@cortexkit/anthropic-auth-core';
2
+ import type { HarnessKind } from './types.ts';
3
+ export interface NativeSetupPaths {
4
+ host: HarnessKind;
5
+ paths: NativePoolPaths;
6
+ legacyConfigPath: string;
7
+ legacyStatePath: string;
8
+ hostAuthPath: string;
9
+ routingSourcePath: string;
10
+ routingDestinationPath: string;
11
+ }
12
+ /** Resolve actor-supplied environment without changing ambient process variables. */
13
+ export declare function resolveNativeSetupPaths(host: HarnessKind, env: NodeJS.ProcessEnv): Promise<NativeSetupPaths>;
14
+ /** Reject plans where OpenCode and Pi share credential, journal or routing files. */
15
+ export declare function requireDisjointNativeSetupPaths(plans: readonly NativeSetupPaths[]): Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -2,7 +2,17 @@ import type { CommandRunner } from './types.ts';
2
2
  export declare function isPiPackageInstalled(env?: NodeJS.ProcessEnv): boolean;
3
3
  export declare function hasPiLocalAnthropicAuth(env?: NodeJS.ProcessEnv): Promise<boolean>;
4
4
  export declare function cleanPiLocalAnthropicAuth(env?: NodeJS.ProcessEnv): Promise<boolean>;
5
- export declare function installPiExtension(version: string, runner?: CommandRunner, env?: NodeJS.ProcessEnv): Promise<{
6
- ok: boolean;
5
+ /**
6
+ * A failed install carries the child's raw exit code and stderr for the
7
+ * diagnostic log only; stderr can echo credentials from the environment, so it
8
+ * is never meant for the screen.
9
+ */
10
+ export type PiInstallResult = {
11
+ ok: true;
7
12
  message: string;
8
- }>;
13
+ } | {
14
+ ok: false;
15
+ exitCode: number;
16
+ stderr: string;
17
+ };
18
+ export declare function installPiExtension(version: string, runner?: CommandRunner, env?: NodeJS.ProcessEnv): Promise<PiInstallResult>;
@@ -1,4 +1,8 @@
1
1
  import type { CommandRunner, ProcessFence } from './types.ts';
2
+ export declare class ProcessInspectionError extends Error {
3
+ readonly code = "process-inspection-failed";
4
+ constructor();
5
+ }
2
6
  export declare class ProcessFenceViolationError extends Error {
3
7
  readonly activeHosts: Array<{
4
8
  pid: number;
@@ -9,6 +13,8 @@ export declare class ProcessFenceViolationError extends Error {
9
13
  command: string;
10
14
  }>);
11
15
  }
12
- export declare function createProcessFence(runner?: CommandRunner): ProcessFence;
16
+ export declare function createProcessFence(runner?: CommandRunner, options?: {
17
+ platform?: NodeJS.Platform;
18
+ }): ProcessFence;
13
19
  export declare const defaultProcessFence: ProcessFence;
14
20
  export declare function assertHostsStopped(fence?: ProcessFence): Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -1 +1 @@
1
- import{A as t,B as u,h as a,i as b,j as c,k as d,l as e,m as f,n as g,o as h,p as i,q as j,r as k,s as l,t as m,u as n,v as o,w as p,x as q,y as r,z as s}from"./index-xzbhzz0a.js";import"./index-1fq7h6yd.js";import"./index-a5d6v3ba.js";import"./index-n96q8pks.js";export{i as setSidebarState,k as resolveActiveAccount,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,q as getFableRecoverySummary,r as getCollapsedQuotaSummary,l as formatScopedQuotaLabel,n as formatPrimeTime,o as formatPrimeCost,p as formatPrimeAccountValue,m as formatFallbackModelLabel,j as drainSidebarWrites,u as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,t as SEVEN_DAY_MS,s as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
1
+ import{E as a,F as b,G as c,H as d,I as e,J as f,K as g,L as h,M as i,N as j,O as k,P as l,Q as m,R as n,S as o,T as p,U as q,V as r,W as s,X as t,Y as u}from"./index-fds0s2j4.js";import"./index-nngmvczq.js";import"./index-aaajxwzd.js";export{i as setSidebarState,k as resolveActiveAccount,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,q as getFableRecoverySummary,r as getCollapsedQuotaSummary,l as formatScopedQuotaLabel,n as formatPrimeTime,o as formatPrimeCost,p as formatPrimeAccountValue,m as formatFallbackModelLabel,j as drainSidebarWrites,u as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,t as SEVEN_DAY_MS,s as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
@@ -1,8 +1,13 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
+ import type { CommandApplyRequest, CommandApplyResult, CommandDialogPayload } from '@cortexkit/anthropic-auth-core';
2
3
  import { type PrimeAccountStatus } from '@cortexkit/anthropic-auth-core';
3
4
  import type { TuiPluginApi } from '@opencode-ai/plugin/tui';
4
5
  import type { AccountDialogAccount } from '../rpc/protocol';
5
6
  import type { OpenDialogPayload } from '../rpc/protocol.js';
7
+ /** Render menu sections, accounts and action inputs; send changes to the host instead of writing credentials here. */
8
+ export declare function openNativeMenuDialog(api: {
9
+ readonly ui: Pick<TuiPluginApi['ui'], 'dialog' | 'DialogSelect' | 'DialogPrompt' | 'DialogConfirm' | 'toast'>;
10
+ }, payload: CommandDialogPayload, apply: (request: CommandApplyRequest) => Promise<CommandApplyResult>, isCurrentSession: () => boolean): void;
6
11
  type ApplyFn = (command: OpenDialogPayload['command'], args: string) => Promise<{
7
12
  text: string;
8
13
  knobs: Record<string, unknown>;
@@ -1,6 +1,6 @@
1
- import{nh as _}from"./index-xxhyhp98.js";import{th as C}from"./index-n96q8pks.js";var W=C(_(),1);import{readFileSync as E,watch as b}from"node:fs";import{mkdir as g,readFile as A,rename as F,writeFile as T}from"node:fs/promises";import{homedir as y}from"node:os";import{basename as f,dirname as x,join as D}from"node:path";import{clearTimeout as U,setTimeout as R}from"node:timers";var v="OPENCODE_TUI_PREFERENCES_FILE",h="tui-preferences.jsonc";function K(){let J=process.env[v];if(J)return J;let z=process.env.OPENCODE_CONFIG_DIR||D(process.env.XDG_CONFIG_HOME||D(y(),".config"),"opencode");return D(z,h)}function H(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}async function e(){try{let J=await A(K(),"utf8"),z=[],q=W.parse(J,z,{allowTrailingComma:!0});if(z.length>0)return{};return H(q)?q:{}}catch{return{}}}var m="anthropic-auth",p=160,w={forceToTop:!1,order:p,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function $(J,z){return typeof J==="boolean"?J:z}function Y(J,z,q,X){if(typeof J!=="number"||!Number.isFinite(J))return z;return Math.min(Math.max(Math.round(J),q),X)}function c(J,z,q){if(typeof J!=="string"||J.length===0)return z;return J.slice(0,q)}function P(J,z){if(typeof J!=="string")return z;return[...J][0]??z}function qq(J){let z=J[m];if(!H(z))return structuredClone(w);let q=w,X=H(z.header)?z.header:{},Q=H(z.sections)?z.sections:{},Z=H(z.appearance)?z.appearance:{},G=Y(Z.warnThreshold,q.appearance.warnThreshold,0,99),V=Math.max(Y(Z.errorThreshold,q.appearance.errorThreshold,0,100),Math.min(G+1,100));return{forceToTop:$(z.forceToTop,q.forceToTop),order:Y(z.order,q.order,-1e4,1e4),startCollapsed:$(z.startCollapsed,q.startCollapsed),rememberCollapsed:$(z.rememberCollapsed,q.rememberCollapsed),collapsed:typeof z.collapsed==="boolean"?z.collapsed:null,pollMs:Y(z.pollMs,q.pollMs,500,30000),refreshDebounceMs:Y(z.refreshDebounceMs,q.refreshDebounceMs,50,5000),header:{label:c(X.label,q.header.label,20),showVersion:$(X.showVersion,q.header.showVersion)},sections:{quota:$(Q.quota,q.sections.quota),fallbackAccounts:$(Q.fallbackAccounts,q.sections.fallbackAccounts),routing:$(Q.routing,q.sections.routing),cache:$(Q.cache,q.sections.cache),health:$(Q.health,q.sections.health),pacing:$(Q.pacing,q.sections.pacing)},appearance:{barWidth:Y(Z.barWidth,q.appearance.barWidth,4,40),barFilledChar:P(Z.barFilledChar,q.appearance.barFilledChar),barEmptyChar:P(Z.barEmptyChar,q.appearance.barEmptyChar),warnThreshold:G,errorThreshold:V}}}var u=-1e5;function zq(J,z,q){let X=J[z];if(!H(X))return q;if(X.forceToTop===!0)return u+Object.keys(J).indexOf(z);return Y(X.order,q,-1e4,1e4)}var s=`// Shared preferences for opencode TUI plugins.
1
+ import"./index-aaajxwzd.js";import{readFileSync as k,watch as C}from"node:fs";import{mkdir as _,readFile as I,rename as E,writeFile as b}from"node:fs/promises";import{homedir as g}from"node:os";import{basename as F,dirname as P,join as N}from"node:path";import{clearTimeout as D,setTimeout as L}from"node:timers";import{applyEdits as T,modify as y,parse as f}from"jsonc-parser";var v="OPENCODE_TUI_PREFERENCES_FILE",h="tui-preferences.jsonc";function A(){let J=process.env[v];if(J)return J;let z=process.env.OPENCODE_CONFIG_DIR||N(process.env.XDG_CONFIG_HOME||N(g(),".config"),"opencode");return N(z,h)}function H(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}async function qq(){try{let J=await I(A(),"utf8"),z=[],q=f(J,z,{allowTrailingComma:!0});if(z.length>0)return{};return H(q)?q:{}}catch{return{}}}var m="anthropic-auth",p=160,R={forceToTop:!1,order:p,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function $(J,z){return typeof J==="boolean"?J:z}function Y(J,z,q,X){if(typeof J!=="number"||!Number.isFinite(J))return z;return Math.min(Math.max(Math.round(J),q),X)}function c(J,z,q){if(typeof J!=="string"||J.length===0)return z;return J.slice(0,q)}function w(J,z){if(typeof J!=="string")return z;return[...J][0]??z}function zq(J){let z=J[m];if(!H(z))return structuredClone(R);let q=R,X=H(z.header)?z.header:{},Q=H(z.sections)?z.sections:{},Z=H(z.appearance)?z.appearance:{},G=Y(Z.warnThreshold,q.appearance.warnThreshold,0,99),V=Math.max(Y(Z.errorThreshold,q.appearance.errorThreshold,0,100),Math.min(G+1,100));return{forceToTop:$(z.forceToTop,q.forceToTop),order:Y(z.order,q.order,-1e4,1e4),startCollapsed:$(z.startCollapsed,q.startCollapsed),rememberCollapsed:$(z.rememberCollapsed,q.rememberCollapsed),collapsed:typeof z.collapsed==="boolean"?z.collapsed:null,pollMs:Y(z.pollMs,q.pollMs,500,30000),refreshDebounceMs:Y(z.refreshDebounceMs,q.refreshDebounceMs,50,5000),header:{label:c(X.label,q.header.label,20),showVersion:$(X.showVersion,q.header.showVersion)},sections:{quota:$(Q.quota,q.sections.quota),fallbackAccounts:$(Q.fallbackAccounts,q.sections.fallbackAccounts),routing:$(Q.routing,q.sections.routing),cache:$(Q.cache,q.sections.cache),health:$(Q.health,q.sections.health),pacing:$(Q.pacing,q.sections.pacing)},appearance:{barWidth:Y(Z.barWidth,q.appearance.barWidth,4,40),barFilledChar:w(Z.barFilledChar,q.appearance.barFilledChar),barEmptyChar:w(Z.barEmptyChar,q.appearance.barEmptyChar),warnThreshold:G,errorThreshold:V}}}var u=-1e5;function Jq(J,z,q){let X=J[z];if(!H(X))return q;if(X.forceToTop===!0)return u+Object.keys(J).indexOf(z);return Y(X.order,q,-1e4,1e4)}var s=`// Shared preferences for opencode TUI plugins.
2
2
  // One top-level key per plugin (short name). See each plugin's README for
3
3
  // its supported settings. This file is safe to hand-edit; plugins update
4
4
  // individual keys in place and preserve comments.
5
5
  {}
6
- `;async function d(J,z,q){let X=K();await g(x(X),{recursive:!0});let Q;try{Q=await A(X,"utf8")}catch{Q=""}if(Q.trim()==="")Q=s;let Z=W.modify(Q,[J,...z],q,{formattingOptions:{insertSpaces:!0,tabSize:2}}),G=W.applyEdits(Q,Z),V=`${X}.${process.pid}.tmp`;await T(V,G,"utf8"),await F(V,X)}var I=Promise.resolve();function Jq(J,z,q){return I=I.then(()=>d(J,z,q)).catch(()=>{}),I}var o=150,n=100;function Qq(J,z={}){let q=K(),X=f(q),Q=null,Z=null;try{Z=E(q,"utf8")}catch{}let G=!1,V=async()=>{let j=await A(q,"utf8").catch(()=>null);if(G||j===null)return;if(j===Z)return;Z=j,J()},S=()=>{if(Q)U(Q);Q=R(()=>{Q=null,V()},o)},O=null;try{O=(z.watchDirectory??b)(x(q),(j,M)=>{let k=M===X||M?.startsWith(`${X}.`)&&M.endsWith(".tmp");if(M!=null&&!k)return;S()})}catch{if(Z===null)return()=>{}}let B=null,N=!1,L=()=>{if(G||B)return;B=R(()=>{if(B=null,G||N)return;N=!0,V().finally(()=>{N=!1,L()})},n),B.unref?.()};return L(),()=>{if(G=!0,Q)U(Q);if(B)U(B);O?.close()}}export{Qq as watchTuiPreferences,qq as resolveAnthropicAuthPrefs,e as readTuiPreferencesFile,Jq as queueTuiPreferenceUpdate,K as getTuiPreferencesFile,zq as computeEffectiveOrder,v as TUI_PREFS_FILE_ENV,m as PLUGIN_KEY,p as DEFAULT_SLOT_ORDER,w as DEFAULT_PREFS};
6
+ `;async function d(J,z,q){let X=A();await _(P(X),{recursive:!0});let Q;try{Q=await I(X,"utf8")}catch{Q=""}if(Q.trim()==="")Q=s;let Z=y(Q,[J,...z],q,{formattingOptions:{insertSpaces:!0,tabSize:2}}),G=T(Q,Z),V=`${X}.${process.pid}.tmp`;await b(V,G,"utf8"),await E(V,X)}var U=Promise.resolve();function Qq(J,z,q){return U=U.then(()=>d(J,z,q)).catch(()=>{}),U}var o=150,n=100;function Xq(J,z={}){let q=A(),X=F(q),Q=null,Z=null;try{Z=k(q,"utf8")}catch{}let G=!1,V=async()=>{let W=await I(q,"utf8").catch(()=>null);if(G||W===null)return;if(W===Z)return;Z=W,J()},x=()=>{if(Q)D(Q);Q=L(()=>{Q=null,V()},o)},K=null;try{K=(z.watchDirectory??C)(P(q),(W,j)=>{let S=j===X||j?.startsWith(`${X}.`)&&j.endsWith(".tmp");if(j!=null&&!S)return;x()})}catch{if(Z===null)return()=>{}}let B=null,M=!1,O=()=>{if(G||B)return;B=L(()=>{if(B=null,G||M)return;M=!0,V().finally(()=>{M=!1,O()})},n),B.unref?.()};return O(),()=>{if(G=!0,Q)D(Q);if(B)D(B);K?.close()}}export{Xq as watchTuiPreferences,zq as resolveAnthropicAuthPrefs,qq as readTuiPreferencesFile,Qq as queueTuiPreferenceUpdate,A as getTuiPreferencesFile,Jq as computeEffectiveOrder,v as TUI_PREFS_FILE_ENV,m as PLUGIN_KEY,p as DEFAULT_SLOT_ORDER,R as DEFAULT_PREFS};
@@ -0,0 +1,7 @@
1
+ /** Explicit sign-in to the native Claude account pool creates this OAuth connection. Startup leaves existing OpenCode connections unchanged. */
2
+ export declare const CLAUDE_POOL_LOGIN_METHOD_ID = "native-claude-oauth";
3
+ /**
4
+ * Connects OpenCode to the Claude accounts held in the vault. It signs in to
5
+ * nothing and stores no local account; only the host's placeholder is written.
6
+ */
7
+ export declare const CLAUDE_VAULT_ACTIVATION_METHOD_ID = "native-claude-vault";
@@ -0,0 +1,276 @@
1
+ import { type ClaudeCodeIdentity, TrailingAssistantHistoryError } from '@cortexkit/anthropic-auth-core';
2
+ import type { AccountRequest, AttemptOutcome, ChooseAccountInput, HeaderEdits, HostError, LimitSignal, OpenCode2AuthAdapter, RequestScope, Transport } from '@cortexkit/common-auth/opencode2';
3
+ import { EffortMarkerCorrelationError } from '../effort-history';
4
+ import { createStrippedStream, rewriteRequestBody } from '../transform';
5
+ /** The provider OpenCode 2 serves Claude under. */
6
+ export declare const ANTHROPIC_PROVIDER_ID = "anthropic";
7
+ /**
8
+ * Plugin-internal request headers that correlate a request with this
9
+ * plugin's own state. They are meaningful only inside the plugin and are
10
+ * removed before the request goes upstream, on both routes.
11
+ */
12
+ export declare const INTERNAL_REQUEST_HEADERS: readonly string[];
13
+ /**
14
+ * Fixed text of the refusal raised when the source has no credential for a
15
+ * send. It names no account, route or vault, because the host shows and logs
16
+ * it.
17
+ */
18
+ export declare const NO_ACCOUNT_REFUSAL = "Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.";
19
+ /**
20
+ * Most sends whose credential may wait between `accountHeaders` and
21
+ * `rewriteRequest` at once. Matches the installer's own default record bound;
22
+ * the oldest is dropped first, and a send whose entry was dropped is refused
23
+ * rather than sent without it.
24
+ */
25
+ export declare const DEFAULT_MAX_PENDING_SENDS = 512;
26
+ /**
27
+ * How long `onAttemptEnd` waits for the source to finish recording how a send
28
+ * ended. After that the adapter returns and logs a warning; the source's own
29
+ * work is not cancelled.
30
+ */
31
+ export declare const DEFAULT_ATTEMPT_END_TIMEOUT_MS = 5000;
32
+ /** Which kind of credential one send goes out with. */
33
+ export type NativeAnthropicRoute = 'oauth' | 'api';
34
+ /**
35
+ * Where one send goes: directly to Anthropic, or through the selected HTTP
36
+ * relay. A selected WebSocket relay appears here only so the adapter can
37
+ * refuse it before anything is sent. No local proxy transport is used.
38
+ */
39
+ export type NativeAnthropicDispatch = {
40
+ readonly kind: 'direct';
41
+ } | {
42
+ readonly kind: 'http-relay';
43
+ readonly url: string;
44
+ readonly token: string;
45
+ } | {
46
+ readonly kind: 'websocket-relay';
47
+ };
48
+ /**
49
+ * What the source authorizes for one send. `provenance` is the source's own
50
+ * record of the account and credential version that serve it (a local slot,
51
+ * a vault receipt with its version, an API key row). The adapter hands it back
52
+ * unchanged with every response, error and end of that send, so the source
53
+ * can tie a 401 or a quota reading to the exact account and version served.
54
+ */
55
+ export type NativeAnthropicAuthorization<P> = {
56
+ readonly route: 'oauth';
57
+ readonly accessToken: string;
58
+ /** The Claude Code identity of the account, when the source knows it. */
59
+ readonly identity?: ClaudeCodeIdentity;
60
+ /** Additional OAuth request headers; authorization and x-api-key edits are ignored so they cannot replace the authorized bearer. */
61
+ readonly headers?: HeaderEdits;
62
+ readonly provenance: P;
63
+ readonly dispatch?: NativeAnthropicDispatch;
64
+ } | {
65
+ readonly route: 'api';
66
+ /**
67
+ * API-route authentication headers must set authorization or x-api-key.
68
+ */
69
+ readonly headers: HeaderEdits;
70
+ /** The URL the send goes to instead of the host's, for this account. */
71
+ readonly baseURL?: string;
72
+ readonly provenance: P;
73
+ readonly dispatch?: NativeAnthropicDispatch;
74
+ };
75
+ /**
76
+ * Correlation metadata carried by common-auth's request hooks for one send.
77
+ * It contains neither credentials nor request body content.
78
+ */
79
+ export interface NativeAnthropicAttemptData<P> {
80
+ readonly route: NativeAnthropicRoute;
81
+ readonly provenance: P;
82
+ readonly dispatch: 'direct' | 'http-relay';
83
+ }
84
+ /**
85
+ * One send, as the source's response, error and end callbacks receive it:
86
+ * the host's request scope, the attempt, and what the source authorized.
87
+ */
88
+ export interface NativeAnthropicAttemptContext<P> extends AccountRequest {
89
+ readonly attemptId: string;
90
+ readonly transport: Transport | undefined;
91
+ readonly route: NativeAnthropicRoute;
92
+ readonly provenance: P;
93
+ readonly dispatch: 'direct' | 'http-relay';
94
+ }
95
+ /** Non-nullable options accepted by rewriteRequestBody. */
96
+ type RewriteBodyOptions = NonNullable<Parameters<typeof rewriteRequestBody>[1]>;
97
+ /**
98
+ * The body rewrite options a source supplies for an OAuth send: billing
99
+ * lineage, effort plan, cache, fast mode, safety and diagnostics inputs. Two
100
+ * options are left out because the adapter sets them: the Claude Code
101
+ * identity, which the source returns with the credential, and the session id,
102
+ * which is the host's own session id for the request.
103
+ */
104
+ export type NativeAnthropicBodyOptions = Omit<RewriteBodyOptions, 'identity' | 'sessionId'>;
105
+ type StrippedStreamOptions = NonNullable<Parameters<typeof createStrippedStream>[1]>;
106
+ /**
107
+ * The response observers a source may attach to an OAuth response. Content
108
+ * filter recovery and relay error hooks are left out on purpose: they exist
109
+ * to send the request again, and this adapter never sends.
110
+ */
111
+ export type NativeAnthropicResponseOptions = Pick<StrippedStreamOptions, 'perf' | 'onComplete' | 'serverSideFallbackModel' | 'onServerSideFallbackOutcome' | 'onMessageStart' | 'onMessageDelta' | 'onMessageResponse' | 'onStreamEnd' | 'laneStart'>;
112
+ /** What `requestOptions` receives for an OAuth send, before its body is rewritten. */
113
+ export interface NativeAnthropicRequestContext<P> extends NativeAnthropicAttemptContext<P> {
114
+ readonly route: 'oauth';
115
+ /**
116
+ * This plugin's own correlation headers found on the request (lower-case
117
+ * names, such as the effort plan or billing lineage id), already removed
118
+ * from it. The adapter does not interpret them; the source looks them up
119
+ * in its own trackers.
120
+ */
121
+ readonly correlation: Readonly<Record<string, string>>;
122
+ }
123
+ /**
124
+ * What the source's response callbacks receive: the send, plus the HTTP
125
+ * status of its response, before the body is read.
126
+ */
127
+ export interface NativeAnthropicResponseContext<P> extends NativeAnthropicAttemptContext<P> {
128
+ readonly status: number;
129
+ }
130
+ /** An `error` event inside a streamed response. */
131
+ export interface NativeAnthropicStreamErrorContext<P> extends NativeAnthropicAttemptContext<P> {
132
+ /** The provider's `error.type`, such as `overloaded_error`. */
133
+ readonly errorType: string | undefined;
134
+ readonly message: string | undefined;
135
+ }
136
+ /**
137
+ * How a send ended. `localRefusal` is set when the adapter refused the
138
+ * request itself before anything was sent (a malformed history, say); a
139
+ * provider 400 never carries it.
140
+ */
141
+ export interface NativeAnthropicAttemptOutcome extends AttemptOutcome {
142
+ readonly localRefusal?: {
143
+ readonly check: string;
144
+ };
145
+ }
146
+ /**
147
+ * The Core-owned source of accounts and policy. Every member is a function
148
+ * property, so under `strictFunctionTypes` a callback that accepts less than
149
+ * the adapter passes it is rejected at compile time.
150
+ */
151
+ export interface NativeAnthropicSource<Q, P> {
152
+ /** Picks the account for one request; `undefined` refuses it. */
153
+ readonly chooseAccount: (input: ChooseAccountInput) => Promise<string | undefined> | string | undefined;
154
+ /**
155
+ * The credential for one send with the chosen account; `undefined` refuses
156
+ * the request before anything is sent.
157
+ */
158
+ readonly authorizeAccount: (scope: RequestScope, accountId: string) => Promise<NativeAnthropicAuthorization<P> | undefined> | NativeAnthropicAuthorization<P> | undefined;
159
+ /** Body rewrite options for an OAuth send. */
160
+ readonly requestOptions?: (input: NativeAnthropicRequestContext<P>) => Promise<NativeAnthropicBodyOptions> | NativeAnthropicBodyOptions;
161
+ /** Rechecks policy after asynchronous rewriting, immediately before dispatch. */
162
+ readonly admitRequest?: (input: NativeAnthropicAttemptContext<P>) => Promise<void> | void;
163
+ /** Response observers for an OAuth response. */
164
+ readonly responseOptions?: (input: NativeAnthropicResponseContext<P>) => NativeAnthropicResponseOptions | undefined;
165
+ /** Quota carried by the upstream response headers, read once per response. */
166
+ readonly quotaFromHeaders?: (headers: Headers, input: NativeAnthropicResponseContext<P>) => Q | undefined;
167
+ /**
168
+ * Classifies an error response before its body streams. `body()` reads a
169
+ * copy, so the host still receives the body.
170
+ */
171
+ readonly limitFromResponse?: (input: NativeAnthropicResponseContext<P> & {
172
+ readonly headers: Headers;
173
+ readonly body: () => Promise<string>;
174
+ }) => Promise<LimitSignal | undefined> | LimitSignal | undefined;
175
+ /** Classifies a relay-local failure, never an Anthropic credential failure. */
176
+ readonly limitFromRelayFailure?: (input: NativeAnthropicResponseContext<P>) => Promise<LimitSignal | undefined> | LimitSignal | undefined;
177
+ /** Classifies an `error` event inside a streamed response. */
178
+ readonly limitFromStreamError?: (input: NativeAnthropicStreamErrorContext<P>) => LimitSignal | undefined;
179
+ /**
180
+ * Classifies the error the host hands the retry hook. Never asked about a
181
+ * send the adapter refused locally.
182
+ */
183
+ readonly limitFromHostError?: (error: HostError, input: NativeAnthropicAttemptContext<P>) => LimitSignal | undefined;
184
+ /**
185
+ * How a send ended, with the provenance of the credential it used, so a
186
+ * 401 can be reported against the exact vault receipt version served.
187
+ */
188
+ readonly onAttemptEnd?: (input: NativeAnthropicAttemptContext<P>, outcome: NativeAnthropicAttemptOutcome) => Promise<void> | void;
189
+ /**
190
+ * Called by the adapter's `forgetSession`; drops whatever the source keeps
191
+ * for the session.
192
+ */
193
+ readonly forgetSession?: (sessionID: string) => void;
194
+ }
195
+ export interface NativeAnthropicAdapterLogger {
196
+ warn(message: string, data?: Record<string, unknown>): void;
197
+ }
198
+ export interface NativeAnthropicAdapterDeps<Q, P> {
199
+ readonly source: NativeAnthropicSource<Q, P>;
200
+ readonly log?: NativeAnthropicAdapterLogger;
201
+ /** Maximum number of authorized sends waiting for their request rewrite. */
202
+ readonly maxPendingSends?: number;
203
+ /**
204
+ * How long `onAttemptEnd` waits for the source to record how a send
205
+ * ended; the source's work is not cancelled.
206
+ */
207
+ readonly attemptEndTimeoutMs?: number;
208
+ }
209
+ export interface NativeAnthropicAdapter<Q, P> {
210
+ readonly adapter: OpenCode2AuthAdapter<Q, NativeAnthropicAttemptData<P>>;
211
+ /**
212
+ * Drops the session's authorized sends that have not been rewritten yet,
213
+ * revokes its choices, authorizations and rewrites still in progress so
214
+ * none of them can return, and calls the source's `forgetSession`.
215
+ */
216
+ forgetSession(sessionID: string): void;
217
+ /** Revokes all pending work. Later calls refuse without invoking the source. */
218
+ dispose(): void;
219
+ /** Number of sends authorized and not yet rewritten or ended. */
220
+ readonly pendingSendCount: number;
221
+ /** Number of OAuth access tokens held for sends not yet rewritten. */
222
+ readonly heldCredentialCount: number;
223
+ /**
224
+ * Number of sends whose credentials are still held to scrub their errors:
225
+ * kept until the send ends cleanly, the retry hook has classified its
226
+ * failure, its session is forgotten, or maxPendingSends evicts the oldest.
227
+ */
228
+ readonly heldRedactorCount: number;
229
+ /** Number of choices, authorizations and rewrites still in progress. */
230
+ readonly operationsInProgress: number;
231
+ }
232
+ /**
233
+ * The request was refused before anything was sent because the source had
234
+ * no credential for it. Never retried on the host's own credential.
235
+ */
236
+ export declare class NativeAnthropicNoAccountError extends Error {
237
+ readonly sessionID: string;
238
+ readonly requestKind: string;
239
+ readonly kind = "no-account";
240
+ readonly providerID = "anthropic";
241
+ constructor(sessionID: string, requestKind: string);
242
+ }
243
+ /**
244
+ * The request was refused because its session was forgotten while the
245
+ * account choice, authorization or request rewrite for it was still in
246
+ * progress. Nothing from that work is returned or kept, and nothing is sent.
247
+ */
248
+ export declare class NativeAnthropicRevokedError extends Error {
249
+ readonly sessionID: string;
250
+ readonly requestKind: string;
251
+ readonly kind = "session-forgotten";
252
+ readonly providerID = "anthropic";
253
+ constructor(sessionID: string, requestKind: string);
254
+ }
255
+ /** OpenCode 2's HTTP model driver cannot speak the relay's binary WebSocket protocol. */
256
+ export declare class NativeAnthropicTransportRefusal extends Error {
257
+ readonly kind = "unsupported-transport";
258
+ readonly providerID = "anthropic";
259
+ constructor();
260
+ }
261
+ /**
262
+ * The request was refused with a local 400 because it can never succeed as
263
+ * written: its history ends on a meaningful assistant turn, or an effort
264
+ * marker in it cannot be matched to the session's effort plan. Nothing was
265
+ * sent, and another account cannot help, so the adapter never reports it as
266
+ * an account limit. The message and `check` describe only the shape of the
267
+ * problem, never conversation content.
268
+ */
269
+ export declare class NativeAnthropicLocalRefusal extends Error {
270
+ readonly kind = "local-invalid-request";
271
+ readonly status = 400;
272
+ readonly check: string;
273
+ constructor(cause: TrailingAssistantHistoryError | EffortMarkerCorrelationError);
274
+ }
275
+ export declare function createNativeAnthropicAdapter<Q, P>(deps: NativeAnthropicAdapterDeps<Q, P>): NativeAnthropicAdapter<Q, P>;
276
+ export {};
@@ -0,0 +1,13 @@
1
+ import { type InstallOpenCode2AuthOptions, type OpenCode2AuthInstallation, type OpenCode2HookContext } from '@cortexkit/common-auth/opencode2';
2
+ import { type NativeAnthropicAdapterDeps, type NativeAnthropicAttemptData } from './adapter';
3
+ export interface NativeAnthropicInstallation<Q, P> {
4
+ readonly installation: OpenCode2AuthInstallation<Q, NativeAnthropicAttemptData<P>>;
5
+ readonly forgetSession: (sessionID: string) => void;
6
+ readonly dispose: () => Promise<void>;
7
+ }
8
+ /**
9
+ * The shared installer removes request records on session deletion. Also cancel
10
+ * the adapter's pending credential lookup and body preparation: removing a
11
+ * record alone cannot stop an asynchronous callback from returning a token.
12
+ */
13
+ export declare function installNativeAnthropic<Q, P>(ctx: OpenCode2HookContext, deps: NativeAnthropicAdapterDeps<Q, P>, ownership: NonNullable<InstallOpenCode2AuthOptions['gateOnPlaceholder']>): Promise<NativeAnthropicInstallation<Q, P>>;
@@ -0,0 +1,8 @@
1
+ import { type NativeAccountRuntime } from '@cortexkit/anthropic-auth-core';
2
+ /**
3
+ * Background quota and profile reads obtain their own account credentials.
4
+ * They must not inherit the model policy of the latest user request.
5
+ */
6
+ export declare function startNativeAnthropicLifecycle(runtime: NativeAccountRuntime, fetchImpl?: typeof fetch): {
7
+ dispose(): Promise<void>;
8
+ };
@@ -0,0 +1,8 @@
1
+ import type { NativeMenuCommandId, NativeMenuDispatch } from '@cortexkit/anthropic-auth-core';
2
+ /** Account, setting and session actions exposed through the server's menu RPC. */
3
+ export interface NativeMenuCapabilities {
4
+ readonly dispatch: NativeMenuDispatch;
5
+ readonly readStatus: (command: Exclude<NativeMenuCommandId, 'start'>) => Promise<string>;
6
+ readonly forgetSession: (sessionID: string) => void;
7
+ readonly close: () => void;
8
+ }
@@ -0,0 +1,10 @@
1
+ import { type NativeAccountRuntime } from '@cortexkit/anthropic-auth-core';
2
+ import type { NativeMenuCapabilities } from './menu-contract';
3
+ import type { NativeSource } from './source';
4
+ export type { NativeMenuCapabilities } from './menu-contract';
5
+ /** Account and setting changes use the same Core runtime as model requests. */
6
+ export declare function createNativeMenuCapabilities(options: {
7
+ readonly runtime: NativeAccountRuntime;
8
+ readonly source: NativeSource;
9
+ readonly start: (sessionID: string, text: string) => Promise<void>;
10
+ }): NativeMenuCapabilities;
@@ -0,0 +1,6 @@
1
+ import type { Plugin } from '@opencode/plugin';
2
+ /** Each model variant supplies request settings for adaptive thinking and its selected reasoning effort. */
3
+ export declare function createNativeClaudeModelRules(): {
4
+ install: (ctx: Pick<Plugin.Context, 'model'>) => Promise<import("@opencode/plugin/promise/registration").Registration>;
5
+ modelId: (id: string) => string;
6
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Read the credential OpenCode attached to this request: the bearer token, or
3
+ * else the API key. When a user signs in through this plugin (Claude pool
4
+ * login or vault activation), OpenCode stores a fixed, non-secret placeholder
5
+ * string instead of a real token: placeholderSecret('anthropic') from
6
+ * @cortexkit/common-auth. The request hooks that installOpenCode2Auth installs
7
+ * serve a request from the plugin's own accounts only when this value equals
8
+ * that placeholder exactly. Any real token or key, whether from OpenCode's own
9
+ * login, a configured API key or an environment variable, is left untouched.
10
+ */
11
+ export declare function preparedAnthropicCredential(headers: Headers): string | undefined;
@@ -0,0 +1,12 @@
1
+ import { type NativeAccountRuntime, type NativePoolPaths, PrimeManager } from '@cortexkit/anthropic-auth-core';
2
+ import type { NativeSource } from './source';
3
+ /** After the five-hour quota resets, send one minimal authenticated request to start its next window and record that request's token usage. */
4
+ export declare function createNativePrime(options: {
5
+ runtime: NativeAccountRuntime;
6
+ paths: NativePoolPaths;
7
+ source: NativeSource;
8
+ fetch?: typeof fetch;
9
+ }): {
10
+ manager: PrimeManager;
11
+ dispose(): Promise<void>;
12
+ };