@cortexkit/common-auth 0.11.8 → 0.13.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 (43) hide show
  1. package/README.md +2 -2
  2. package/dist/auth-menu/accounts.d.ts +11 -2
  3. package/dist/auth-menu/accounts.js +12 -26
  4. package/dist/claustrum/enrollment.d.ts +26 -0
  5. package/dist/claustrum/enrollment.js +108 -0
  6. package/dist/claustrum/index.d.ts +1 -1
  7. package/dist/claustrum/index.js +1 -1
  8. package/dist/commands/builtins.js +123 -102
  9. package/dist/commands/model.d.ts +42 -1
  10. package/dist/commands/pi.d.ts +2 -1
  11. package/dist/commands/pi.js +40 -12
  12. package/dist/commands/seam.js +3 -0
  13. package/dist/fs/atomic-write.d.ts +13 -0
  14. package/dist/fs/atomic-write.js +52 -0
  15. package/dist/opencode2/index.d.ts +2 -2
  16. package/dist/opencode2/index.js +1 -1
  17. package/dist/opencode2/integration.d.ts +45 -11
  18. package/dist/opencode2/integration.js +58 -9
  19. package/dist/quota/format.d.ts +46 -0
  20. package/dist/quota/format.js +138 -0
  21. package/dist/quota/index.d.ts +2 -0
  22. package/dist/quota/index.js +1 -0
  23. package/dist/store/attribution.js +1 -0
  24. package/dist/store/errors.d.ts +2 -2
  25. package/dist/store/identity.js +2 -0
  26. package/dist/store/index.d.ts +2 -1
  27. package/dist/store/mutate.d.ts +22 -2
  28. package/dist/store/mutate.js +140 -34
  29. package/dist/store/pool.d.ts +9 -2
  30. package/dist/store/pool.js +4 -0
  31. package/dist/store/publication.d.ts +47 -0
  32. package/dist/store/publication.js +304 -0
  33. package/dist/store/pull.js +6 -1
  34. package/dist/store/refresh.js +2 -0
  35. package/dist/store/reserved.d.ts +3 -0
  36. package/dist/store/reserved.js +13 -0
  37. package/dist/store/rows.d.ts +62 -13
  38. package/dist/store/rows.js +331 -42
  39. package/dist/store/runtime.js +13 -1
  40. package/dist/store/schema.d.ts +18 -0
  41. package/dist/store/schema.js +58 -2
  42. package/dist/store/torn.js +1 -1
  43. package/package.json +1 -1
@@ -51,6 +51,11 @@ export interface MenuAction {
51
51
  id: string;
52
52
  label: string;
53
53
  description?: string;
54
+ /**
55
+ * The header a section-level action is listed under (`Actions`). See
56
+ * `MenuSection` for how renderers draw groups.
57
+ */
58
+ group?: string;
54
59
  knobs: MenuKnob[];
55
60
  /** Present when the action must be confirmed before it is applied. */
56
61
  confirm?: MenuConfirmation;
@@ -72,6 +77,13 @@ export interface MenuItem {
72
77
  id: string;
73
78
  label: string;
74
79
  detail?: string;
80
+ /** The header the item is listed under (`Accounts`); see `MenuSection`. */
81
+ group?: string;
82
+ /**
83
+ * A short value shown right-aligned beside the label (`enabled`,
84
+ * `5h 58% left`): an OpenCode dialog option's `footer`.
85
+ */
86
+ status?: string;
75
87
  account?: MenuAccount;
76
88
  /**
77
89
  * Extra name/value pairs a drawer may list under the item. Plugin data
@@ -80,11 +92,33 @@ export interface MenuItem {
80
92
  facts?: Record<string, unknown>;
81
93
  actions: MenuAction[];
82
94
  }
95
+ /**
96
+ * One section of the menu. How every renderer draws it:
97
+ *
98
+ * - Every option a renderer shows can be selected and does something: it is
99
+ * an item with at least one action, or a section-level action. Text that
100
+ * does nothing is never an option; it is a group header or a line.
101
+ * - `lines` are read-only text. On OpenCode they are drawn as header text
102
+ * (a `category`) above the first group; on Pi they are part of the select
103
+ * title.
104
+ * - The options are the items, then the section-level actions, in that
105
+ * order. When an option's `group` differs from the previous one's, a
106
+ * header naming the group is drawn first. A header is never selectable
107
+ * (on OpenCode it is the option's `category`).
108
+ * - An item's `status` is drawn right-aligned beside its label (on
109
+ * OpenCode, `footer`); its `detail` and an action's `description` are
110
+ * the secondary text (`description`).
111
+ *
112
+ * The built-in sections never emit an item without actions, and a plugin
113
+ * section should not either. A renderer that meets one must not offer it as
114
+ * an option: on OpenCode a `disabled` option is hidden altogether, so the
115
+ * item is written as header text instead, and Pi writes it into the title.
116
+ */
83
117
  export interface MenuSection {
84
118
  id: string;
85
119
  slot: SectionSlot;
86
120
  title: string;
87
- /** Read-only lines shown above the items. */
121
+ /** Read-only text shown above the rows; never a selectable option. */
88
122
  lines: string[];
89
123
  items: MenuItem[];
90
124
  actions: MenuAction[];
@@ -158,6 +192,8 @@ type ActionBase = {
158
192
  id: string;
159
193
  label: string;
160
194
  description?: string;
195
+ /** The header a section-level action is listed under; see `MenuSection`. */
196
+ group?: string;
161
197
  knobs?: MenuKnob[];
162
198
  run(input: ActionInput): Promise<string | ActionOutcome>;
163
199
  };
@@ -176,10 +212,15 @@ export interface ItemDefinition {
176
212
  id: string;
177
213
  label: string;
178
214
  detail?: string;
215
+ /** The header the item is listed under; see `MenuSection`. */
216
+ group?: string;
217
+ /** A short value shown right-aligned beside the label. */
218
+ status?: string;
179
219
  facts?: Record<string, unknown>;
180
220
  actions?: ActionDefinition[];
181
221
  }
182
222
  export interface SectionContent {
223
+ /** Read-only text; renderers never make a line selectable. */
183
224
  lines?: string[];
184
225
  items?: ItemDefinition[];
185
226
  actions?: ActionDefinition[];
@@ -16,7 +16,8 @@ export interface PiMenuOptions {
16
16
  /**
17
17
  * Runs one invocation of the slash command on Pi: sections, then an item or
18
18
  * a section action, then the action's inputs and confirmation; after each
19
- * apply the user is back in the same section with the refreshed menu. Backing
19
+ * apply the user is back in the same section with the refreshed menu. Each
20
+ * section's list ends with Back, which returns to the section list; backing
20
21
  * out of the section list ends the invocation.
21
22
  */
22
23
  export declare function runPiCommandMenu(menu: CommandMenu, ui: PiMenuUi, options?: PiMenuOptions): Promise<void>;
@@ -22,11 +22,35 @@ async function pick(ui, title, entries) {
22
22
  function withLines(title, lines) {
23
23
  return lines.length > 0 ? `${title}\n${lines.join('\n')}` : title;
24
24
  }
25
+ /** A row as one line of text: its label, then its status when it has one. */
26
+ function rowText(item) {
27
+ return item.status ? `${item.label} · ${item.status}` : item.label;
28
+ }
29
+ /**
30
+ * The read-only part of a section's select title: its lines, then each item
31
+ * that has no actions, under its group's header. Such an item does nothing
32
+ * when chosen, so it is shown as text rather than offered as an option. Pi's
33
+ * `select` cannot put text between options, so the headers of groups whose
34
+ * rows are all selectable are not shown.
35
+ */
36
+ function sectionText(section) {
37
+ const text = [...section.lines];
38
+ let header;
39
+ for (const item of section.items) {
40
+ if (item.actions.length > 0)
41
+ continue;
42
+ if (item.group !== undefined && item.group !== header)
43
+ text.push(item.group);
44
+ header = item.group;
45
+ text.push(item.group !== undefined ? ` ${rowText(item)}` : rowText(item));
46
+ }
47
+ return text;
48
+ }
25
49
  function itemTitle(item) {
26
50
  const lines = item.detail ? [item.detail] : [];
27
51
  for (const [name, value] of Object.entries(item.facts ?? {}))
28
52
  lines.push(`${name}: ${String(value)}`);
29
- return withLines(item.label, lines);
53
+ return withLines(rowText(item), lines);
30
54
  }
31
55
  /** One knob's value, or undefined when the user backed out or typed nonsense. */
32
56
  async function askKnob(ui, knob) {
@@ -94,7 +118,8 @@ async function askValues(ui, action) {
94
118
  /**
95
119
  * Runs one invocation of the slash command on Pi: sections, then an item or
96
120
  * a section action, then the action's inputs and confirmation; after each
97
- * apply the user is back in the same section with the refreshed menu. Backing
121
+ * apply the user is back in the same section with the refreshed menu. Each
122
+ * section's list ends with Back, which returns to the section list; backing
98
123
  * out of the section list ends the invocation.
99
124
  */
100
125
  export async function runPiCommandMenu(menu, ui, options = {}) {
@@ -118,9 +143,12 @@ export async function runPiCommandMenu(menu, ui, options = {}) {
118
143
  const section = model.sections.find((entry) => entry.id === chosen);
119
144
  if (!section)
120
145
  break;
146
+ // Only rows that do something are options; the rest is title text.
121
147
  const entries = [
122
- ...section.items.map((item) => ({
123
- label: item.detail ? `${item.label}: ${item.detail}` : item.label,
148
+ ...section.items
149
+ .filter((item) => item.actions.length > 0)
150
+ .map((item) => ({
151
+ label: rowText(item),
124
152
  value: { kind: 'item', item },
125
153
  })),
126
154
  ...section.actions.map((action) => ({
@@ -128,21 +156,21 @@ export async function runPiCommandMenu(menu, ui, options = {}) {
128
156
  value: { kind: 'action', action },
129
157
  })),
130
158
  ];
131
- if (entries.length === 0) {
132
- ui.notify(section.lines.join('\n') || 'Nothing to do here.');
159
+ const text = sectionText(section);
160
+ if (entries.length === 0 && text.length === 0) {
161
+ ui.notify('Nothing to do here.');
133
162
  break;
134
163
  }
135
- const choice = await pick(ui, withLines(section.title, section.lines), entries);
136
- if (!choice)
164
+ const choice = await pick(ui, withLines(section.title, text), [
165
+ ...entries,
166
+ { label: 'Back', value: { kind: 'back' } },
167
+ ]);
168
+ if (!choice || choice.kind === 'back')
137
169
  break;
138
170
  let action;
139
171
  let item;
140
172
  if (choice.kind === 'item') {
141
173
  item = choice.item;
142
- if (item.actions.length === 0) {
143
- ui.notify(itemTitle(item));
144
- continue;
145
- }
146
174
  action = await pick(ui, itemTitle(item), item.actions.map((entry) => ({ label: entry.label, value: entry })));
147
175
  if (!action)
148
176
  continue;
@@ -240,6 +240,7 @@ function projectAction(action) {
240
240
  ...(action.description !== undefined
241
241
  ? { description: action.description }
242
242
  : {}),
243
+ ...(action.group !== undefined ? { group: String(action.group) } : {}),
243
244
  knobs: (action.knobs ?? []).map(projectKnob),
244
245
  ...(confirm ? { confirm } : {}),
245
246
  };
@@ -259,6 +260,8 @@ function projectItem(item) {
259
260
  id: item.id,
260
261
  label: item.label,
261
262
  ...(item.detail !== undefined ? { detail: item.detail } : {}),
263
+ ...(item.group !== undefined ? { group: String(item.group) } : {}),
264
+ ...(item.status !== undefined ? { status: String(item.status) } : {}),
262
265
  ...(item.account ? { account: projectAccount(item.account) } : {}),
263
266
  ...(item.facts !== undefined ? { facts: item.facts } : {}),
264
267
  actions: (item.actions ?? []).map(projectAction),
@@ -3,5 +3,18 @@ export interface AtomicWriteOptions {
3
3
  beforeRename?: () => Promise<void>;
4
4
  /** Test seam for forcing staging-name collisions; defaults to randomUUID. */
5
5
  stageName?: () => string;
6
+ /** Sync the staged file and, after rename, its parent directory. Opt-in. */
7
+ durable?: boolean;
8
+ }
9
+ /** Internal classification of fsync failures, including a failure after rename. */
10
+ export declare class AtomicSyncError extends Error {
11
+ constructor(cause: unknown);
6
12
  }
7
13
  export declare function writeJsonAtomic(path: string, value: unknown, options?: AtomicWriteOptions): Promise<void>;
14
+ /**
15
+ * Notify internal callers at the rename. The store records committed writes
16
+ * and removed ids here, because a later directory sync cannot undo the rename.
17
+ */
18
+ export declare function writeJsonAtomicTracked(path: string, value: unknown, options: AtomicWriteOptions, onRenamed?: () => void): Promise<void>;
19
+ /** Make an already renamed file and its directory durable without rewriting bytes. */
20
+ export declare function syncJsonFile(path: string): Promise<void>;
@@ -1,7 +1,21 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { mkdir, open, rename, rm } from 'node:fs/promises';
3
3
  import { dirname } from 'node:path';
4
+ /** Internal classification of fsync failures, including a failure after rename. */
5
+ export class AtomicSyncError extends Error {
6
+ constructor(cause) {
7
+ super('file or directory sync failed', { cause });
8
+ this.name = 'AtomicSyncError';
9
+ }
10
+ }
4
11
  export async function writeJsonAtomic(path, value, options = {}) {
12
+ await writeJsonAtomicTracked(path, value, options);
13
+ }
14
+ /**
15
+ * Notify internal callers at the rename. The store records committed writes
16
+ * and removed ids here, because a later directory sync cannot undo the rename.
17
+ */
18
+ export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
5
19
  await mkdir(dirname(path), { recursive: true });
6
20
  const tempPath = `${path}.${(options.stageName ?? randomUUID)()}.tmp`;
7
21
  let handle;
@@ -13,11 +27,32 @@ export async function writeJsonAtomic(path, value, options = {}) {
13
27
  ? options.serialize(value)
14
28
  : `${JSON.stringify(value, null, 2)}\n`, 'utf8');
15
29
  await handle.chmod(0o600);
30
+ if (options.durable) {
31
+ try {
32
+ await handle.sync();
33
+ }
34
+ catch (cause) {
35
+ throw new AtomicSyncError(cause);
36
+ }
37
+ }
16
38
  await handle.close();
17
39
  handle = undefined;
18
40
  await options.beforeRename?.();
19
41
  await rename(tempPath, path);
20
42
  created = false;
43
+ onRenamed?.();
44
+ if (options.durable) {
45
+ const directory = await open(dirname(path), 'r');
46
+ try {
47
+ await directory.sync();
48
+ }
49
+ catch (cause) {
50
+ throw new AtomicSyncError(cause);
51
+ }
52
+ finally {
53
+ await directory.close();
54
+ }
55
+ }
21
56
  }
22
57
  finally {
23
58
  await handle?.close().catch(() => { });
@@ -26,3 +61,20 @@ export async function writeJsonAtomic(path, value, options = {}) {
26
61
  await rm(tempPath, { force: true }).catch(() => { });
27
62
  }
28
63
  }
64
+ /** Make an already renamed file and its directory durable without rewriting bytes. */
65
+ export async function syncJsonFile(path) {
66
+ const file = await open(path, 'r');
67
+ try {
68
+ await file.sync();
69
+ }
70
+ finally {
71
+ await file.close();
72
+ }
73
+ const directory = await open(dirname(path), 'r');
74
+ try {
75
+ await directory.sync();
76
+ }
77
+ finally {
78
+ await directory.close();
79
+ }
80
+ }
@@ -1,8 +1,8 @@
1
1
  export type { OpenCode2AuthFailureKind } from './errors.js';
2
2
  export { OpenCode2AuthError } from './errors.js';
3
3
  export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
4
- export type { FormAnswer, PoolAuthorization, PoolLoginMethod, RegisterOpenCode2AuthMethodsOptions, } from './integration.js';
5
- export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, } from './integration.js';
4
+ export type { FormAnswer, LoginContext, PoolAuthorization, PoolLoginMethod, RegisterOpenCode2AuthMethodsOptions, VaultActivationMethod, } from './integration.js';
5
+ export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
6
6
  export type { ServerSentEvent } from './sse.js';
7
7
  export { watchServerSentEvents } from './sse.js';
8
8
  export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryReason, SelectingHook, Transport, } from './types.js';
@@ -1,4 +1,4 @@
1
1
  export { OpenCode2AuthError } from './errors.js';
2
2
  export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
3
- export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, } from './integration.js';
3
+ export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
4
4
  export { watchServerSentEvents } from './sse.js';
@@ -47,31 +47,65 @@ export interface PoolLoginMethod<T> {
47
47
  readonly method: IntegrationOAuthMethod;
48
48
  authorize(answer: FormAnswer): Promise<PoolAuthorization<T>>;
49
49
  }
50
+ /** What `activate` and `onLogin` are told about the login they serve. */
51
+ export interface LoginContext {
52
+ readonly integrationID: string;
53
+ readonly methodID: string;
54
+ }
55
+ /**
56
+ * Shown by `opencode auth login` when the vault method starts. The host has no
57
+ * page to open for this method, so the text only says what happens instead.
58
+ */
59
+ export declare const VAULT_ACTIVATION_INSTRUCTIONS = "No browser sign-in: this connects the plugin to the accounts in its vault.";
60
+ /**
61
+ * A login method for a host whose accounts all come from a vault. Choosing it
62
+ * signs in to nothing and writes nothing to the plugin's pool: once
63
+ * `activate` resolves, the host only receives this integration's placeholder,
64
+ * which marks later requests as the plugin's to serve from the vault.
65
+ */
66
+ export interface VaultActivationMethod {
67
+ /** Must not share an ID with any of the pool login methods. */
68
+ readonly method: IntegrationOAuthMethod;
69
+ /**
70
+ * Confirms the host may use this method, normally by checking that
71
+ * `enrollmentAuthority` reports `'vault'`. Throw to refuse: the host shows
72
+ * the error's message and stores nothing, so it must be a fixed text that
73
+ * carries no credential.
74
+ */
75
+ activate(context: LoginContext): Promise<void> | void;
76
+ /** Replaces `VAULT_ACTIVATION_INSTRUCTIONS`. */
77
+ readonly instructions?: string;
78
+ }
50
79
  export interface RegisterOpenCode2AuthMethodsOptions<T> {
51
80
  readonly integrationID: string;
52
81
  readonly methods: readonly PoolLoginMethod<T>[];
82
+ /**
83
+ * Adds a login method that activates the plugin for vault accounts without
84
+ * creating a local account. Leave it out when the plugin has no vault.
85
+ */
86
+ readonly vault?: VaultActivationMethod;
53
87
  /**
54
88
  * Writes a completed login into the plugin's pool. The host only receives
55
89
  * a placeholder once this resolves; if it throws, the login fails in the
56
90
  * host and nothing is stored there.
57
91
  */
58
- onLogin(result: T, context: {
59
- readonly integrationID: string;
60
- readonly methodID: string;
61
- }): Promise<void> | void;
92
+ onLogin(result: T, context: LoginContext): Promise<void> | void;
62
93
  /** Label the host shows for its (placeholder) connection. */
63
94
  readonly label?: string;
64
95
  readonly now?: () => number;
65
96
  }
66
97
  /**
67
- * Registers the plugin's login methods with the host so that a login lands in
68
- * the plugin's pool and the host keeps only a placeholder credential.
98
+ * Registers the plugin's own login methods with the host so that a login lands
99
+ * in the plugin's pool and the host keeps only a placeholder credential.
100
+ *
101
+ * With `vault`, one more method lets a host whose accounts all live in a vault
102
+ * activate the plugin: it calls `activate`, writes nothing to the pool and
103
+ * hands the host the same placeholder under its own method ID.
69
104
  *
70
- * Host-driven refresh never reaches the pool: it hands back a fresh
71
- * placeholder whatever it is given. A real credential stored by an earlier
72
- * login under one of these method IDs is therefore replaced by a placeholder
73
- * at its first refresh; a plugin that wants to import such a login must read
74
- * it (`ctx.integration.connection`) before that happens.
105
+ * Host-driven refresh never reaches the pool: it renews only this integration's
106
+ * placeholder and refuses every other credential without replacing it. Plugins
107
+ * must register under their own method IDs; a plugin importing an existing
108
+ * host login should read it through `ctx.integration.connection` instead.
75
109
  */
76
110
  export declare function registerOpenCode2AuthMethods<T>(ctx: {
77
111
  readonly integration: Pick<Plugin.Context['integration'], 'transform'>;
@@ -39,14 +39,22 @@ export function isPlaceholderCredential(value, integrationID) {
39
39
  return matches(value.access) && matches(value.refresh);
40
40
  }
41
41
  /**
42
- * Registers the plugin's login methods with the host so that a login lands in
43
- * the plugin's pool and the host keeps only a placeholder credential.
42
+ * Shown by `opencode auth login` when the vault method starts. The host has no
43
+ * page to open for this method, so the text only says what happens instead.
44
+ */
45
+ export const VAULT_ACTIVATION_INSTRUCTIONS = 'No browser sign-in: this connects the plugin to the accounts in its vault.';
46
+ /**
47
+ * Registers the plugin's own login methods with the host so that a login lands
48
+ * in the plugin's pool and the host keeps only a placeholder credential.
44
49
  *
45
- * Host-driven refresh never reaches the pool: it hands back a fresh
46
- * placeholder whatever it is given. A real credential stored by an earlier
47
- * login under one of these method IDs is therefore replaced by a placeholder
48
- * at its first refresh; a plugin that wants to import such a login must read
49
- * it (`ctx.integration.connection`) before that happens.
50
+ * With `vault`, one more method lets a host whose accounts all live in a vault
51
+ * activate the plugin: it calls `activate`, writes nothing to the pool and
52
+ * hands the host the same placeholder under its own method ID.
53
+ *
54
+ * Host-driven refresh never reaches the pool: it renews only this integration's
55
+ * placeholder and refuses every other credential without replacing it. Plugins
56
+ * must register under their own method IDs; a plugin importing an existing
57
+ * host login should read it through `ctx.integration.connection` instead.
50
58
  */
51
59
  export async function registerOpenCode2AuthMethods(ctx, options) {
52
60
  const now = options.now ?? Date.now;
@@ -81,14 +89,55 @@ export async function registerOpenCode2AuthMethods(ctx, options) {
81
89
  };
82
90
  };
83
91
  return ctx.integration.transform((editor) => {
92
+ const label = options.label === undefined ? {} : { label: () => options.label };
84
93
  for (const login of options.methods) {
85
94
  editor.method.update({
86
95
  integrationID,
87
96
  method: login.method,
88
97
  authorize: authorizeWith(login),
89
- refresh: async (credential) => placeholderFor(credential.methodID),
90
- ...(options.label === undefined ? {} : { label: () => options.label }),
98
+ refresh: async (credential) => {
99
+ if (!isPlaceholderCredential(credential, integrationID)) {
100
+ throw new Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");
101
+ }
102
+ return placeholderFor(credential.methodID);
103
+ },
104
+ ...label,
91
105
  });
92
106
  }
107
+ const vault = options.vault;
108
+ if (vault === undefined)
109
+ return;
110
+ const methodID = vault.method.id;
111
+ editor.method.update({
112
+ integrationID,
113
+ method: vault.method,
114
+ // OpenCode 2 has no login method kind that needs no user step: OAuth
115
+ // expects a page, a key method a typed secret, a command method a
116
+ // program. An automatic OAuth authorization with an empty `url` fits:
117
+ // on 2.0.22 the CLI's and the TUI's browser openers refuse anything but
118
+ // an http(s) URL, and the host stores what `callback` resolves to as
119
+ // soon as it settles, so the login completes with no browser.
120
+ authorize: async () => ({
121
+ url: '',
122
+ instructions: vault.instructions ?? VAULT_ACTIVATION_INSTRUCTIONS,
123
+ mode: 'auto',
124
+ // Activation runs in the callback, not before returning, so a refusal
125
+ // marks the host's login attempt failed with the plugin's own message,
126
+ // which the host shows as is.
127
+ callback: Promise.resolve()
128
+ .then(() => vault.activate({ integrationID, methodID }))
129
+ .then(() => placeholderFor(methodID)),
130
+ }),
131
+ // Nothing to renew in the vault: only this method's own placeholder is
132
+ // reissued, and anything else must be signed in again.
133
+ refresh: async (credential) => {
134
+ if (!isPlaceholderCredential(credential, integrationID) ||
135
+ credential.methodID !== methodID) {
136
+ throw new Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");
137
+ }
138
+ return placeholderFor(methodID);
139
+ },
140
+ ...label,
141
+ });
93
142
  });
94
143
  }
@@ -0,0 +1,46 @@
1
+ import type { ProjectedLimit, ProjectedQuota } from './projection.js';
2
+ /** A reading older than this is marked with its age. */
3
+ export declare const QUOTA_STALE_AFTER_MS: number;
4
+ /** What `formatQuota` returns when there is no reading at all. */
5
+ export declare const NO_QUOTA_READING = "no quota reading yet";
6
+ /**
7
+ * What `formatQuota` returns when the provider answered but reported no
8
+ * limit for any window (every window is an absence record or a tombstone).
9
+ */
10
+ export declare const NO_LIMITS_REPORTED = "no limits reported";
11
+ /**
12
+ * `compact` fits a footer or a sidebar row: each window's figure, the credit
13
+ * budget and the stale marker, without reset times. `full` adds each reset.
14
+ */
15
+ export type QuotaTextForm = 'compact' | 'full';
16
+ export interface QuotaTextOptions {
17
+ /** The current time in ms, for reset countdowns and the stale marker. */
18
+ now: number;
19
+ /** Defaults to `full`. */
20
+ form?: QuotaTextForm;
21
+ /** Defaults to `QUOTA_STALE_AFTER_MS`. */
22
+ staleAfterMs?: number;
23
+ }
24
+ /**
25
+ * The name a window is shown under. A general window (scope `all`) is named
26
+ * by its stored length; a model-scoped window keeps the label the plugin
27
+ * stored it under, which already names the model (`seven_day_opus`). A
28
+ * general window stored without a length (a snapshot from before lengths
29
+ * were recorded) falls back to its label.
30
+ */
31
+ export declare function quotaWindowName(limit: Pick<ProjectedLimit, 'scope' | 'label' | 'windowMinutes'>): string;
32
+ /**
33
+ * The pieces of a quota text, in order: one per reported window
34
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
35
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
36
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
37
+ * one line per window (the terminal auth menu) uses these directly.
38
+ */
39
+ export declare function quotaTextParts(quota: ProjectedQuota | undefined, options: QuotaTextOptions): string[];
40
+ /**
41
+ * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
42
+ * form, with `, resets 2h` after each window in the full form. With nothing
43
+ * reported it is `NO_QUOTA_READING`, or `NO_LIMITS_REPORTED` when the
44
+ * provider answered without a limit for any window.
45
+ */
46
+ export declare function formatQuota(quota: ProjectedQuota | undefined, options: QuotaTextOptions): string;