@midpath/gptmitra-pi 0.0.0-stage → 1.4.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/index.ts +85 -0
  4. package/package.json +27 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Midpath Software Pvt Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # GPT Mitra for Pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use GPT Mitra's OpenAI-compatible API in Pi with per-call supplier pricing and persisted session costs.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:@midpath/gptmitra-pi
9
+ export GPTMITRA_API_KEY='your-consumer-key'
10
+ ```
11
+
12
+ Restart Pi or run `/reload`. Add your model to `~/.pi/agent/models.json`:
13
+
14
+ ```json
15
+ {
16
+ "providers": {
17
+ "gptmitra": {
18
+ "api": "gptmitra",
19
+ "baseUrl": "https://app.gptmitra.in/v1",
20
+ "models": [{
21
+ "id": "your-model-id",
22
+ "name": "Your model",
23
+ "input": ["text"],
24
+ "reasoning": false,
25
+ "contextWindow": 32768,
26
+ "maxTokens": 4096
27
+ }]
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ Select the model under the `gptmitra` provider. Replace the example ID and capabilities with those supported by your supplier. A consumer key needs an enabled owned or shared supplier serving that model. See [GPT Mitra setup](https://gptmitra.in/docs.html).
34
+
35
+ Keep `api: gptmitra`; using `openai-completions` bypasses cost handling. For another deployment, change `baseUrl`, retaining `/v1`.
36
+
37
+ ## Costs
38
+
39
+ Uses the server's final cost, or complete token usage with the response's supplier rates. Missing usage is marked unavailable, not treated as free; Pi's numeric total excludes unavailable costs and the extension warns that the total is incomplete. Costs persist in Pi sessions. No local prices or additional requests are needed.
40
+
41
+ Targets Pi's `@earendil-works` provider API; tested with Pi 1.4.0. This is not a budget or payment system.
42
+
43
+ ## Publish
44
+
45
+ From the repository, after `npm login`:
46
+
47
+ ```sh
48
+ ./pi-extension/scripts/publish.sh
49
+ ```
50
+
51
+ Runs tests and publishes publicly. The npm prepack hook syncs the version from root `VERSION.txt`; no Go build is required. Bump that file before subsequent releases. To preview without publishing, pass `--dry-run`.
package/index.ts ADDED
@@ -0,0 +1,85 @@
1
+ import { createAssistantMessageEventStream, openAICompletionsApi, type Api, type Model, type SimpleStreamOptions, type TranscriptContext } from '@earendil-works/pi-ai/compat';
2
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
3
+
4
+ const decimal = /^(0|[1-9]\d*)(\.\d{1,12})?$/;
5
+ function money(value: unknown): number | undefined {
6
+ if (typeof value !== 'string' || !decimal.test(value)) return;
7
+ const n = Number(value);
8
+ return Number.isFinite(n) && n >= 0 ? n : undefined;
9
+ }
10
+ function tokens(n: unknown): n is number { return Number.isSafeInteger(n) && (n as number) >= 0; }
11
+
12
+ // Every invocation owns its metadata. Never mutate model-wide prices or fetch.
13
+ export function streamGPTMitra(model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) {
14
+ const stream = createAssistantMessageEventStream();
15
+ let inputRate: number | undefined, outputRate: number | undefined;
16
+ let counts: {input: number; output: number} | undefined;
17
+ let reported: {input: number; output: number; cacheRead: number; cacheWrite: number; total: number} | undefined;
18
+ const innerModel = {...model, api: 'openai-completions' as const, cost: {input: 0, output: 0, cacheRead: 0, cacheWrite: 0}};
19
+ const inner = openAICompletionsApi().streamSimple(innerModel, context, {
20
+ ...options,
21
+ onResponse: async (response, m) => {
22
+ const headers = new Headers(response.headers);
23
+ if (headers.get('X-GPTMitra-Currency') === 'USD') {
24
+ inputRate = money(headers.get('X-GPTMitra-Input-Per-Million'));
25
+ outputRate = money(headers.get('X-GPTMitra-Output-Per-Million'));
26
+ }
27
+ await options?.onResponse?.(response, m);
28
+ },
29
+ onProviderStreamEvent: async (event, m) => {
30
+ const u = (event as any)?.usage;
31
+ if (u) { counts = undefined; reported = undefined; }
32
+ if (tokens(u?.prompt_tokens) && tokens(u?.completion_tokens)) {
33
+ counts = {input: u.prompt_tokens, output: u.completion_tokens};
34
+ const c = u.gptmitra_cost;
35
+ if (c?.currency === 'USD') {
36
+ const input = money(c.input_cost), output = money(c.output_cost), total = money(c.total);
37
+ const close = (a: number, b: number) => Math.abs(a - b) <= Math.max(1e-12, Math.abs(b) * Number.EPSILON * 4);
38
+ if (input !== undefined && output !== undefined && total !== undefined && inputRate !== undefined && outputRate !== undefined
39
+ && close(input, counts.input * inputRate / 1e6) && close(output, counts.output * outputRate / 1e6) && close(input + output, total)) {
40
+ reported = {input, output, cacheRead: 0, cacheWrite: 0, total};
41
+ }
42
+ }
43
+ }
44
+ await options?.onProviderStreamEvent?.(event, m);
45
+ },
46
+ });
47
+ void (async () => {
48
+ for await (const event of inner) {
49
+ if (event.type === 'done' || event.type === 'error') {
50
+ const message = event.type === 'done' ? event.message : event.error;
51
+ const fallback = counts && inputRate !== undefined && outputRate !== undefined
52
+ ? {input: counts.input * inputRate / 1e6, output: counts.output * outputRate / 1e6, cacheRead: 0, cacheWrite: 0, total: (counts.input * inputRate + counts.output * outputRate) / 1e6}
53
+ : undefined;
54
+ message.usage.cost = reported ?? fallback ?? {input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0};
55
+ // NOTE: Pi requires numeric costs. Unknown calls are excluded, with a
56
+ // persisted status and explicit warning rather than claiming a free call.
57
+ (message.usage as any).gptmitraCostStatus = reported ? 'reported' : fallback ? 'calculated' : 'unavailable';
58
+ message.api = model.api;
59
+ }
60
+ stream.push(event);
61
+ }
62
+ stream.end();
63
+ })();
64
+ return stream;
65
+ }
66
+
67
+ export default function (pi: ExtensionAPI) {
68
+ pi.registerProvider('gptmitra', {
69
+ baseUrl: 'https://app.gptmitra.in/v1',
70
+ apiKey: '$GPTMITRA_API_KEY',
71
+ api: 'gptmitra',
72
+ streamSimple: streamGPTMitra,
73
+ });
74
+ // NOTE: O(n) scan per message keeps warnings consistent with native session
75
+ // totals across branches; use an incremental counter if huge sessions need it.
76
+ const update = (event: any, ctx: any) => {
77
+ const messages = ctx.sessionManager.getEntries().filter((e: any) => e.type === 'message').map((e: any) => e.message);
78
+ // message_end runs before the new message is appended to session storage.
79
+ if (event.message && !messages.includes(event.message)) messages.push(event.message);
80
+ const missing = messages.filter((m: any) => m.role === 'assistant' && m.usage?.gptmitraCostStatus === 'unavailable').length;
81
+ ctx.ui.setStatus('gptmitra', missing ? `GPT Mitra: ${missing} call(s) have unavailable cost; USD total is incomplete` : undefined);
82
+ };
83
+ pi.on('session_start', update);
84
+ pi.on('message_end', update);
85
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@midpath/gptmitra-pi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.4.0",
4
+ "description": "GPT Mitra provider for Pi with per-call supplier pricing and persisted session costs",
5
+ "license": "MIT",
6
+ "author": "Midpath Software Pvt Ltd",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "files": [
11
+ "index.ts"
12
+ ],
13
+ "scripts": {
14
+ "test": "node test.cjs",
15
+ "prepack": "node sync-version.cjs"
16
+ },
17
+ "keywords": [
18
+ "pi-package"
19
+ ],
20
+ "pi": {
21
+ "extensions": [
22
+ "./index.ts"
23
+ ]
24
+ },
25
+ "peerDependencies": {
26
+ "@earendil-works/pi-ai": "*",
27
+ "@earendil-works/pi-coding-agent": "*"
28
+ }
29
+ }