pi-requesty-discover 2.0.0 β†’ 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONTRIBUTING.adoc CHANGED
@@ -32,4 +32,5 @@ Notes:
32
32
  * Keep implementation in `src/`; root `index.ts` is just the package entrypoint.
33
33
  * Edit `README.adoc` if necessary.
34
34
  * See `AGENTS.md` for detailed repository conventions.
35
+ * See `docs/DECISIONS.adoc` for deliberate design decisions.
35
36
  * I am pretty good at identifying AI slop 😁.
package/README.adoc CHANGED
@@ -18,6 +18,7 @@ This is a fork of https://github.com/requestyai/pi-requesty[pi-requesty] with ad
18
18
  * Health-check available models and write a log about them
19
19
  * Brief information about what was found, including added/removed models, health summary
20
20
  * Confirm before writing `models.json`, with a dry-run mode that only previews
21
+ * A footer status line showing your monthly Requesty spend against your monthly limit
21
22
 
22
23
  == When and why use it
23
24
 
@@ -27,6 +28,7 @@ Use this extension if
27
28
  - you are limited to certain models by a company policy (for instance, for data residency/protection reasons)
28
29
  - you don't want to handcraft your own curated list of models constantly
29
30
  - you want to health-check models and preview the diff before writing
31
+ - you want to keep in touch with your usage without having to constantly visit the Requesty dashboard
30
32
 
31
33
  == Installation
32
34
 
@@ -142,3 +144,23 @@ After a successful write, run `/reload`.
142
144
  ----
143
145
 
144
146
  Same discovery and health checks, but never prompts to write and leaves `models.json` unchanged.
147
+
148
+ == Usage status
149
+
150
+ The extension shows your current Requesty monthly spend as a persistent line in Pi's footer, e.g.:
151
+
152
+ [source,text]
153
+ ----
154
+ Requesty Usage (<API Key Name>): $63.55/$150.00 (42%)
155
+ ----
156
+
157
+ When your API key has no monthly limit (`monthly_limit` is `0`), the limit is treated as unlimited:
158
+
159
+ [source,text]
160
+ ----
161
+ Requesty Usage (<API Key Name>): $63.55 (unlimited)
162
+ ----
163
+
164
+ When you select a model from a provider other than `REQUESTY_PROVIDER_ID`, the status is cleared β€” there is no Requesty usage to show for it. If `REQUESTY_API_KEY` is not configured, the status is left untouched.
165
+
166
+ NOTE: The footer update is best-effort and never blocks a turn. If it fails (network error, stale context after `/reload`), it fails silently without spamming notifications.
package/README.md CHANGED
@@ -10,6 +10,7 @@ This is a fork of [pi-requesty](https://github.com/requestyai/pi-requesty) with
10
10
  * Health-check available models and write a log about them
11
11
  * Brief information about what was found, including added/removed models, health summary
12
12
  * Confirm before writing `models.json`, with a dry-run mode that only previews
13
+ * A footer status line showing your monthly Requesty spend against your monthly limit
13
14
 
14
15
  ## When and why use it
15
16
 
@@ -19,6 +20,7 @@ Use this extension if
19
20
  * you are limited to certain models by a company policy (for instance, for data residency/protection reasons)
20
21
  * you don’t want to handcraft your own curated list of models constantly
21
22
  * you want to health-check models and preview the diff before writing
23
+ * you want to keep in touch with your usage without having to constantly visit the Requesty dashboard
22
24
 
23
25
  ## Installation
24
26
 
@@ -108,3 +110,22 @@ After a successful write, run `/reload`.
108
110
  ```
109
111
 
110
112
  Same discovery and health checks, but never prompts to write and leaves `models.json` unchanged.
113
+
114
+ ## Usage status
115
+
116
+ The extension shows your current Requesty monthly spend as a persistent line in Pi’s footer, e.g.:
117
+
118
+ ```text
119
+ Requesty Usage (<API Key Name>): $63.55/$150.00 (42%)
120
+ ```
121
+
122
+ When your API key has no monthly limit (`monthly_limit` is `0`), the limit is treated as unlimited:
123
+
124
+ ```text
125
+ Requesty Usage (<API Key Name>): $63.55 (unlimited)
126
+ ```
127
+
128
+ When you select a model from a provider other than `REQUESTY_PROVIDER_ID`, the status is cleared β€” there is no Requesty usage to show for it. If `REQUESTY_API_KEY` is not configured, the status is left untouched.
129
+
130
+ **πŸ“Œ NOTE**\
131
+ The footer update is best-effort and never blocks a turn. If it fails (network error, stale context after `/reload`), it fails silently without spamming notifications.
@@ -0,0 +1,36 @@
1
+ = Decision records
2
+
3
+ Short notes for non-obvious decisions: context, decision, why not the obvious alternative.
4
+
5
+ == Usage status stays on `setStatus` (shared, truncated footer line)
6
+
7
+ Pi's `FooterComponent` joins all extensions' `setStatus` entries on one line and
8
+ ellipsis-truncates the joined line to terminal width. No per-key layout, no wrap.
9
+
10
+ `ctx.ui.setFooter(factory)` is replacement-only β€” it swaps the whole footer (pwd,
11
+ tokens, context %, model, statuses), and the factory gets `footerData` but not
12
+ token/model state. No "extra footer" API exists.
13
+
14
+ Decision: keep `setStatus`. Revisit when the line overflows visibly with other
15
+ extensions' statuses, or if the usage string grows past a typical width.
16
+
17
+ == Not a provider β€” a models.json-writing extension
18
+
19
+ Context: Requesty already works as a Pi provider via `models.json`. The temptation
20
+ is to make this extension *be* the provider: read the model list from the Requesty
21
+ API, hold it in memory, surface usage stats, let Pi manage the API key.
22
+
23
+ Why not:
24
+
25
+ - Health-checking is the core value and has no home in a provider. A provider serves
26
+ models; it doesn't vet them. The health check plus the diff/confirm/write flow is a
27
+ discovery-and-selection step, not serving.
28
+ - A provider keeps its model list in-memory and refreshes occasionally. Here the
29
+ list is a persistent on-disk snapshot (`models.json`) β€” constant until you re-run
30
+ `/requesty-discover`. That matches the intent: an explicit, reviewed, user-confirmed write,
31
+ after which Pi's normal provider machinery serves the models.
32
+
33
+ The provider-like parts (API model fetch, usage footer, wanting Pi-managed auth) are
34
+ real, but the health check and the snapshot model break the provider fit.
35
+
36
+ Decision: stay a `/requesty-discover` command that writes `models.json`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-requesty-discover",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Discover available Requesty models for the Pi Coding Agent",
5
5
  "repository": {
6
6
  "type": "git",
package/src/env.ts CHANGED
@@ -5,6 +5,8 @@ import { getAgentDir } from '@earendil-works/pi-coding-agent'
5
5
 
6
6
  const HealthCheckModeSchema = z.enum(['off', 'basic', 'full']).default('full')
7
7
 
8
+ export const DEFAULT_PROVIDER_ID = 'requesty-export'
9
+
8
10
  export type Env = {
9
11
  models_json_path: string
10
12
  health_check_log_path: string
@@ -28,7 +30,7 @@ export function getEnv(): Env {
28
30
  return {
29
31
  models_json_path: path.join(agentPath, 'models.json'),
30
32
  health_check_log_path: path.join(agentPath, 'requesty-health-check.log'),
31
- provider_id: envVars.REQUESTY_PROVIDER_ID ?? 'requesty-export',
33
+ provider_id: envVars.REQUESTY_PROVIDER_ID ?? DEFAULT_PROVIDER_ID,
32
34
  requesty_api_key: apiKey,
33
35
  health_check_mode: result.data,
34
36
  }
package/src/index.ts CHANGED
@@ -1,4 +1,9 @@
1
- import { ExtensionAPI, ExtensionCommandContext, ProviderModelConfig } from '@earendil-works/pi-coding-agent'
1
+ import {
2
+ ExtensionAPI,
3
+ ExtensionCommandContext,
4
+ ExtensionContext,
5
+ ProviderModelConfig,
6
+ } from '@earendil-works/pi-coding-agent'
2
7
  import { type Env, getEnv } from './env'
3
8
  import {
4
9
  diffModels,
@@ -7,12 +12,13 @@ import {
7
12
  type ModelsDiff,
8
13
  updateModelsJson,
9
14
  } from './models-json'
10
- import { discoverModels } from './requesty-api'
15
+ import { type ApiKeyInfo, discoverModels, fetchApiUsage } from './requesty-api'
11
16
  import { checkModels, formatHealthSummary, writeHealthCheckLog } from './health-check'
12
17
  import { RequestyStatusLoader } from './ui/requesty-status-loader.ts'
13
18
 
14
19
  const COMMAND_NAME = 'requesty-discover'
15
20
  const DRY_RUN_ARG = '--dry-run'
21
+ export const USAGE_STATUS_KEY = 'requesty-usage'
16
22
 
17
23
  interface AutocompleteItem {
18
24
  value: string
@@ -55,6 +61,9 @@ type EvaluationResult =
55
61
  }
56
62
  | { ok: false; error: unknown }
57
63
 
64
+ // A per-instance token suppresses stale writes when turns overlap
65
+ let latestToken: object = {}
66
+
58
67
  // noinspection JSUnusedGlobalSymbols
59
68
  export default function (pi: ExtensionAPI) {
60
69
  pi.registerCommand(COMMAND_NAME, {
@@ -64,6 +73,18 @@ export default function (pi: ExtensionAPI) {
64
73
  await runDiscoveryWorkflow(ctx, args)
65
74
  },
66
75
  })
76
+
77
+ pi.on('turn_end', (_event, ctx) => {
78
+ void updateUsageStatus(ctx)
79
+ })
80
+
81
+ pi.on('session_start', (_event, ctx) => {
82
+ void updateUsageStatus(ctx)
83
+ })
84
+
85
+ pi.on('model_select', (_event, ctx) => {
86
+ void updateUsageStatus(ctx)
87
+ })
67
88
  }
68
89
 
69
90
  export async function runDiscoveryWorkflow(ctx: ExtensionCommandContext, args: string) {
@@ -272,3 +293,48 @@ function createLoaderStatusReporter(loader: RequestyStatusLoader): StatusReporte
272
293
  },
273
294
  }
274
295
  }
296
+
297
+ export async function updateUsageStatus(ctx: ExtensionContext): Promise<void> {
298
+ if (!ctx.hasUI) return // no footer to write to (print/json mode): skip the wasted fetch
299
+ const token: object = {}
300
+ latestToken = token
301
+ const providerId = getRequestyProviderId()
302
+ if (providerId === undefined) return // not configured for Requesty: nothing to do
303
+ const shouldClear = ctx.model?.provider !== providerId
304
+ try {
305
+ if (shouldClear) {
306
+ ctx.ui.setStatus(USAGE_STATUS_KEY, undefined)
307
+ return
308
+ }
309
+ const info = await fetchUsageStatus()
310
+ if (latestToken !== token) return
311
+ ctx.ui.setStatus(USAGE_STATUS_KEY, formatUsageStatus(info))
312
+ } catch {
313
+ // best-effort footer update: swallow fetch errors and stale-ctx throws (e.g. after /reload)
314
+ }
315
+ }
316
+
317
+ /** Returns the configured Requesty provider id, or undefined when Requesty is not configured. */
318
+ function getRequestyProviderId(): string | undefined {
319
+ try {
320
+ return getEnv().provider_id
321
+ } catch {
322
+ return undefined
323
+ }
324
+ }
325
+
326
+ export function formatUsageStatus(info: ApiKeyInfo): string {
327
+ const spend = `$${info.monthlySpend.toFixed(2)}`
328
+ if (info.monthlyLimit <= 0) {
329
+ return `Requesty Usage (${info.name}): ${spend} (unlimited)`
330
+ }
331
+ const limit = `$${info.monthlyLimit.toFixed(2)}`
332
+ const percent = Math.floor((info.monthlySpend / info.monthlyLimit) * 100)
333
+ return `Requesty Usage (${info.name}): ${spend}/${limit} (${percent}%)`
334
+ }
335
+
336
+ async function fetchUsageStatus(): Promise<ApiKeyInfo> {
337
+ const env = getEnv()
338
+ const { provider } = getRequestyConfig(env)
339
+ return await fetchApiUsage(provider)
340
+ }
@@ -3,6 +3,7 @@ import { z } from 'zod'
3
3
 
4
4
  const DEFAULT_CONTEXT_WINDOW = 128000
5
5
  const DEFAULT_MAX_TOKENS = 4096
6
+ const REQUESTY_MANAGE_URL = 'https://api-v2.requesty.ai/v1/manage'
6
7
 
7
8
  const RequestyModelSchema = z
8
9
  .object({
@@ -66,3 +67,31 @@ function pricePerMillionTokens(value: number | null | undefined): number {
66
67
  const raw = (value ?? 0) * 1_000_000
67
68
  return Number(raw.toFixed(3))
68
69
  }
70
+
71
+ const ApiKeyInfoSchema = z
72
+ .object({
73
+ name: z.string().min(1),
74
+ monthly_spend: z.coerce.number(),
75
+ monthly_limit: z.coerce.number(),
76
+ })
77
+ .transform(value => ({
78
+ name: value.name,
79
+ monthlySpend: value.monthly_spend,
80
+ monthlyLimit: value.monthly_limit,
81
+ }))
82
+
83
+ export type ApiKeyInfo = z.infer<typeof ApiKeyInfoSchema>
84
+
85
+ export async function fetchApiUsage(provider: Provider): Promise<ApiKeyInfo> {
86
+ const url = `${REQUESTY_MANAGE_URL}/apikey/self`
87
+ const response = await fetch(url, {
88
+ headers: { Authorization: `Bearer ${provider.apiKey}` },
89
+ })
90
+
91
+ if (!response.ok) {
92
+ throw new Error(`HTTP ${response.status} ${response.statusText}`)
93
+ }
94
+
95
+ const rawData = await response.json()
96
+ return ApiKeyInfoSchema.parse(rawData)
97
+ }