@tduyng/pi-session 0.0.0-stage → 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,178 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ Use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 tduyng
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @tduyng/pi-session
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
+ Session lifecycle: sessions name themselves and resume once a provider quota resets. No more `untitled` rows in the picker, no more waiting out a usage limit by hand.
4
+
5
+ ## Auto-name
6
+
7
+ A new session starts unnamed. On `agent_end`, the extension reads the first user message and uses it as the name. It takes the first line, strips a leading `/` or `#`, collapses whitespace, and limits the result to 60 characters, cutting at a word boundary.
8
+
9
+ An expanded skill uses its argument when one is present, or the skill name when it has no argument. The extension ignores the expanded instructions and the skill's filesystem path. A `/skill:name task` command follows the same rule and uses `task` when present. A `Skill invocation protocol` message without a skill block is skipped because an extension injected it. A name you set with `/name` always wins. Naming runs last and swallows its own errors. It is cosmetic and never blocks the turn.
10
+
11
+ The extension finds the first user-role message in the `event.messages` array. If the message content is a block array, it extracts text blocks and joins them with spaces. When no user message exists, naming is skipped silently.
12
+
13
+ Before: a week of `2026-09-01 14:22`, `2026-09-01 14:47`, `2026-09-02 09:03`. After: `fix retry backoff`, `review auth diff`, `migrate schema`.
14
+
15
+ ## Autoresume
16
+
17
+ When a provider quota exhaustion kills a turn, the extension parses a reset time from the error text. Formats it accepts:
18
+
19
+ - Epoch timestamps: `limit reached|1757193000`
20
+ - ISO timestamps: `resets at 2026-09-06T23:30:00+02:00`
21
+ - Relative times: `try again in 2h 15m`, `retry after 3600 seconds`
22
+ - Clock times: `resets 11:30pm (Europe/Paris)`, `reset at 23:30`
23
+ - Retry-after headers: `retry-after: 3600`
24
+
25
+ For claude-bridge sessions where the error carries no reset time, autoresume queries the Anthropic OAuth usage endpoint and picks the latest reset among all exhausted windows, with the credential from the macOS keychain (`Claude Code-credentials`) or `~/.claude/.credentials.json`.
26
+
27
+ A 5-second safety delay is added past the reset time. The timer caps at 24 hours. A parsed reset further than 24 hours out schedules nothing and posts a warning: Usage limit resets in over 24h, auto-resume not scheduled. Any user turn or session shutdown cancels it. The resume sends a real user message: "The usage limit has reset. Continue the previous task from where it stopped."
28
+
29
+ Commands: `/autoresume`, `/autoresume status`, `/autoresume on`, `/autoresume off`, `/autoresume cancel`.
30
+
31
+ ## Design
32
+
33
+ Auto-naming reads at `agent_end`, when real conversation content exists. Autoresume touches no session storage and adds no tools beyond the one command. Session creation, storage, and selection stay with pi.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pi install npm:@tduyng/pi-session
39
+ ```
40
+
41
+ Local checkout: `pi install /path/to/dotfiles/pi/agent/extensions/pi-session`
42
+
43
+ ## Configure
44
+
45
+ None. It works out of the box.
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@tduyng/pi-session",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Session lifecycle: name an unnamed session after its first message, and resume once a provider quota resets.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "session",
11
+ "naming",
12
+ "resume"
13
+ ],
14
+ "homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-session#readme",
15
+ "bugs": "https://gitlab.com/tduyng/pi-agent/-/issues",
16
+ "license": "Apache-2.0",
17
+ "author": "tduyng",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://gitlab.com/tduyng/pi-agent.git",
21
+ "directory": "extensions/pi-session"
22
+ },
23
+ "type": "module",
24
+ "files": [
25
+ "src",
26
+ "!src/**/*.test.ts",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "peerDependencies": {
31
+ "@earendil-works/pi-ai": "*",
32
+ "@earendil-works/pi-coding-agent": "*"
33
+ },
34
+ "dependencies": {
35
+ "ata-validator": "^1.62.1"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "pi": {
41
+ "extensions": [
42
+ "./src/auto-name.ts",
43
+ "./src/autoresume.ts"
44
+ ]
45
+ }
46
+ }
@@ -0,0 +1,58 @@
1
+ import type { UserMessage } from '@earendil-works/pi-ai'
2
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
3
+
4
+ const MAX_NAME_CHARS = 60
5
+
6
+ function skillTask(text: string): string | undefined {
7
+ const trimmed = text.trim()
8
+ if (trimmed.startsWith('Skill invocation protocol')) return undefined
9
+
10
+ const block = /^<skill\s+name="([^"]+)"[^>]*>[\s\S]*?<\/skill>(?:\s*([\s\S]*))?$/i.exec(trimmed)
11
+ if (block) {
12
+ const trailing = block[2]?.replace(/^Skill input:\s*/i, '').trim()
13
+ return trailing || block[1]
14
+ }
15
+
16
+ const command = /^\/skill:([^\s]+)(?:\s+([\s\S]*))?$/.exec(trimmed)
17
+ if (command) {
18
+ const args = command[2]?.trim()
19
+ return args || command[1]
20
+ }
21
+
22
+ return undefined
23
+ }
24
+
25
+ function textOf(message: { role: string; content: UserMessage['content'] }): string {
26
+ const content = message.content
27
+ if (!Array.isArray(content)) return content
28
+ return content
29
+ .filter((block): block is Extract<UserMessage['content'][number], { type: 'text' }> => block.type === 'text')
30
+ .map((block) => block.text)
31
+ .join(' ')
32
+ }
33
+
34
+ export function candidateName(text: string): string {
35
+ const expandedSkill = skillTask(text)
36
+ const line = (expandedSkill ?? text).split('\n', 1)[0]?.trim() ?? ''
37
+ if (!expandedSkill && line.startsWith('Skill invocation protocol')) return ''
38
+ const cleaned = line
39
+ .replace(/^[/#]+\s*/, '')
40
+ .replace(/\s+/g, ' ')
41
+ .trim()
42
+ if (cleaned.length <= MAX_NAME_CHARS) return cleaned
43
+ const cut = cleaned.slice(0, MAX_NAME_CHARS)
44
+ const lastSpace = cut.lastIndexOf(' ')
45
+ return (lastSpace > MAX_NAME_CHARS / 2 ? cut.slice(0, lastSpace) : cut).trim()
46
+ }
47
+
48
+ export default function autoNameExtension(pi: ExtensionAPI): void {
49
+ pi.on('agent_end', (event) => {
50
+ try {
51
+ if (pi.getSessionName()) return
52
+ const user = event.messages.find((message) => message.role === 'user')
53
+ if (!user) return
54
+ const name = candidateName(textOf(user as { role: string; content: UserMessage['content'] }))
55
+ if (name) pi.setSessionName(name)
56
+ } catch {}
57
+ })
58
+ }
@@ -0,0 +1,349 @@
1
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent'
2
+ import { claudeToken, exhaustedResetAt, fetchAnthropicUsage } from './usage.js'
3
+
4
+ const SAFETY_DELAY_MS = 5_000
5
+ const MAX_DELAY_MS = 24 * 60 * 60 * 1000
6
+ const TICK_MS = 10_000
7
+ const RESUME_PROMPT = 'The usage limit has reset. Continue the previous task from where it stopped.'
8
+
9
+ function isStale(error: unknown): error is Error {
10
+ return error instanceof Error && error.message.includes('stale after session')
11
+ }
12
+
13
+ let enabled = true
14
+ let ticker: ReturnType<typeof setInterval> | undefined
15
+ let resumeAt: number | undefined
16
+ let lastStatus = ''
17
+ let pendingError: string | undefined
18
+
19
+ export default function autoResume(pi: ExtensionAPI) {
20
+ pi.on('agent_end', async (event) => {
21
+ pendingError = undefined
22
+
23
+ const assistant = event.messages.findLast((message) => message.role === 'assistant')
24
+
25
+ if (assistant?.stopReason !== 'error') return
26
+
27
+ pendingError = assistant.errorMessage
28
+ })
29
+
30
+ pi.on('agent_settled', async (_event, ctx) => {
31
+ const error = pendingError
32
+ pendingError = undefined
33
+
34
+ if (!enabled || !error || resumeAt) return
35
+ if (!isQuotaError(error)) return
36
+
37
+ const reportedTarget = parseReset(error)
38
+ const providerTarget = ctx.model?.provider === 'claude-bridge' ? await usageResetAt(pi, ctx) : undefined
39
+ const target = preferResetTarget(reportedTarget, providerTarget)
40
+
41
+ if (!target) return
42
+
43
+ schedule(pi, ctx, target)
44
+ })
45
+
46
+ pi.on('turn_start', async (_event, ctx) => cancel(ctx))
47
+
48
+ pi.registerCommand('autoresume', {
49
+ description: "Auto-resume when the provider's usage limit resets",
50
+
51
+ handler: async (args, ctx) => {
52
+ switch (args.trim().toLowerCase()) {
53
+ case '':
54
+ case 'status':
55
+ ctx.ui.notify(statusLine(ctx), 'info')
56
+ return
57
+
58
+ case 'on':
59
+ enabled = true
60
+ ctx.ui.notify('Auto-resume enabled.', 'info')
61
+ return
62
+
63
+ case 'off':
64
+ enabled = false
65
+ cancel(ctx)
66
+ ctx.ui.notify('Auto-resume disabled.', 'info')
67
+ return
68
+
69
+ case 'cancel':
70
+ ctx.ui.notify(resumeAt ? 'Scheduled resume cancelled.' : 'Nothing scheduled.', 'info')
71
+ cancel(ctx)
72
+ return
73
+
74
+ default:
75
+ ctx.ui.notify('Usage: /autoresume [status|on|off|cancel]', 'warning')
76
+ }
77
+ }
78
+ })
79
+
80
+ pi.on('session_shutdown', async (_event, ctx) => cancel(ctx))
81
+ pi.on('session_start', (_event, ctx) => {
82
+ pendingError = undefined
83
+ cancel(ctx)
84
+ })
85
+ }
86
+
87
+ export function preferResetTarget(reported: number | undefined, authoritative: number | undefined): number | undefined {
88
+ return authoritative ?? reported
89
+ }
90
+
91
+ async function usageResetAt(pi: ExtensionAPI, ctx: ExtensionContext): Promise<number | undefined> {
92
+ if (ctx.model?.provider !== 'claude-bridge') return
93
+
94
+ const token = await claudeToken(pi).catch(() => undefined)
95
+ const payload = token ? await fetchAnthropicUsage(token).catch(() => undefined) : undefined
96
+ const resetAt = payload ? exhaustedResetAt(payload) : undefined
97
+
98
+ return resetAt !== undefined && resetAt > Date.now() ? resetAt : undefined
99
+ }
100
+
101
+ function schedule(pi: ExtensionAPI, ctx: ExtensionContext, target: number) {
102
+ const delay = target - Date.now()
103
+
104
+ if (delay > MAX_DELAY_MS) {
105
+ ctx.ui.notify('Usage limit resets in over 24h · auto-resume not scheduled.', 'warning')
106
+ return
107
+ }
108
+
109
+ resumeAt = target + SAFETY_DELAY_MS
110
+ lastStatus = ''
111
+
112
+ ctx.ui.notify(`Usage limit reached · continuing automatically at ${formatTime(resumeAt)}`, 'warning')
113
+ tick(pi, ctx)
114
+
115
+ ticker = setInterval(() => {
116
+ try {
117
+ tick(pi, ctx)
118
+ } catch (error) {
119
+ stopTicker()
120
+ if (!isStale(error)) {
121
+ try {
122
+ ctx.ui.notify(
123
+ `auto-resume stopped: ${error instanceof Error ? error.message : String(error)}`,
124
+ 'warning'
125
+ )
126
+ } catch {}
127
+ }
128
+ }
129
+ }, TICK_MS)
130
+ }
131
+
132
+ function tick(pi: ExtensionAPI, ctx: ExtensionContext) {
133
+ if (!resumeAt) return
134
+
135
+ const remaining = resumeAt - Date.now()
136
+
137
+ if (remaining > 0) {
138
+ const status = `⏳ resumes ${formatTime(resumeAt)} · ${formatRemaining(remaining)}`
139
+
140
+ if (status !== lastStatus) {
141
+ lastStatus = status
142
+ ctx.ui.setStatus('autoresume', status)
143
+ }
144
+
145
+ return
146
+ }
147
+
148
+ if (!ctx.isIdle()) return
149
+
150
+ cancel(ctx)
151
+
152
+ ctx.ui.notify(`Usage limit reset · continuing with ${describeModel(ctx)}`, 'info')
153
+ pi.sendUserMessage(RESUME_PROMPT)
154
+ }
155
+
156
+ function stopTicker(): void {
157
+ if (ticker) clearInterval(ticker)
158
+
159
+ ticker = undefined
160
+ resumeAt = undefined
161
+ lastStatus = ''
162
+ }
163
+
164
+ function cancel(ctx?: ExtensionContext) {
165
+ stopTicker()
166
+
167
+ ctx?.ui.setStatus('autoresume', undefined)
168
+ }
169
+
170
+ function statusLine(ctx: ExtensionContext): string {
171
+ if (!enabled) return 'Auto-resume is disabled.'
172
+ if (!resumeAt) return 'Auto-resume enabled · nothing scheduled.'
173
+
174
+ return `Auto-resume at ${formatTime(resumeAt)} · ${formatRemaining(resumeAt - Date.now())} · ${describeModel(ctx)}`
175
+ }
176
+
177
+ function describeModel(ctx: ExtensionContext): string {
178
+ const provider = ctx.model?.provider
179
+ const model = ctx.model?.id
180
+
181
+ if (provider && model) return `${provider}/${model}`
182
+
183
+ return model ?? provider ?? 'the active model'
184
+ }
185
+
186
+ export function parseReset(input: string, now = Date.now()): number | undefined {
187
+ const target =
188
+ parseEpoch(input) ??
189
+ parseTimestamp(input) ??
190
+ parseRelative(input, now) ??
191
+ parseClock(input, now) ??
192
+ parseRetryAfter(input, now)
193
+
194
+ return target !== undefined && target > now ? target : undefined
195
+ }
196
+
197
+ function parseEpoch(input: string): number | undefined {
198
+ const match = input.match(/\b(?:limit\s+reached|reset(?:s|_at)?|retry(?:_at)?)\W{0,3}(\d{10}|\d{13})\b/i)
199
+
200
+ if (!match) return
201
+
202
+ const digits = match[1] ?? ''
203
+
204
+ return digits.length === 10 ? Number(digits) * 1000 : Number(digits)
205
+ }
206
+
207
+ function parseTimestamp(input: string): number | undefined {
208
+ const match = input.match(
209
+ /\b(?:reset(?:s)?(?:\s+at)?|retry(?:\s+at)?)[:\s]+(\d{4}-\d{2}-\d{2}T[0-9:.]+(?:Z|[+-]\d{2}:?\d{2}))/i
210
+ )
211
+
212
+ if (!match) return
213
+
214
+ const value = Date.parse(match[1] ?? '')
215
+
216
+ return Number.isFinite(value) ? value : undefined
217
+ }
218
+
219
+ function parseRelative(input: string, now: number): number | undefined {
220
+ const prefix = input.match(/(?:try\s+again|retry|reset(?:s)?)\s+(?:after|in)\s+([^.,;\n]+)/i)
221
+
222
+ if (!prefix) return
223
+
224
+ const units = /(\d+(?:\.\d+)?)\s*(days?|d|hours?|hrs?|hr|h|minutes?|mins?|min|m|seconds?|secs?|sec|s)\b/gi
225
+
226
+ let milliseconds = 0
227
+
228
+ for (const match of (prefix[1] ?? '').matchAll(units)) {
229
+ const amount = Number(match[1])
230
+ const unit = (match[2] ?? '').toLowerCase()
231
+
232
+ if (unit.startsWith('d')) milliseconds += amount * 86_400_000
233
+ else if (unit.startsWith('h')) milliseconds += amount * 3_600_000
234
+ else if (unit.startsWith('m')) milliseconds += amount * 60_000
235
+ else milliseconds += amount * 1_000
236
+ }
237
+
238
+ return milliseconds > 0 ? now + milliseconds : undefined
239
+ }
240
+
241
+ function parseRetryAfter(input: string, now: number): number | undefined {
242
+ const match = input.match(/\bretry[-_\s]?after["'\s:]+(\d+)\b/i)
243
+
244
+ return match ? now + Number(match[1]) * 1000 : undefined
245
+ }
246
+
247
+ function isQuotaError(input: string): boolean {
248
+ return /\b(?:usage|quota|limit|rate[- ]?limit|too many requests|429)\b/i.test(input)
249
+ }
250
+
251
+ function parseClock(input: string, now: number): number | undefined {
252
+ const match = input.match(/\breset(?:s)?(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?/i)
253
+
254
+ if (!match || (match[2] === undefined && match[3] === undefined)) return
255
+
256
+ let hour = Number(match[1])
257
+ const minute = Number(match[2] ?? '0')
258
+ const meridiem = match[3]?.toLowerCase()
259
+ const timeZone = match[4]?.trim()
260
+
261
+ if (minute > 59) return
262
+
263
+ if (meridiem) {
264
+ if (hour < 1 || hour > 12) return
265
+
266
+ if (meridiem === 'am') hour = hour === 12 ? 0 : hour
267
+ else hour = hour === 12 ? 12 : hour + 12
268
+ } else if (hour > 23) {
269
+ return
270
+ }
271
+
272
+ if (timeZone) return nextTimeInZone(hour, minute, timeZone, now)
273
+
274
+ const target = new Date(now)
275
+ target.setHours(hour, minute, 0, 0)
276
+
277
+ if (target.getTime() <= now) target.setDate(target.getDate() + 1)
278
+
279
+ return target.getTime()
280
+ }
281
+
282
+ function nextTimeInZone(hour: number, minute: number, timeZone: string, now: number): number | undefined {
283
+ try {
284
+ const today = zonedParts(now, timeZone)
285
+
286
+ let target = zonedEpoch(today.year, today.month, today.day, hour, minute, timeZone)
287
+
288
+ if (target <= now) {
289
+ const tomorrow = zonedParts(target + 86_400_000, timeZone)
290
+
291
+ target = zonedEpoch(tomorrow.year, tomorrow.month, tomorrow.day, hour, minute, timeZone)
292
+ }
293
+
294
+ return target
295
+ } catch {
296
+ return
297
+ }
298
+ }
299
+
300
+ function zonedEpoch(year: number, month: number, day: number, hour: number, minute: number, timeZone: string): number {
301
+ const wanted = Date.UTC(year, month - 1, day, hour, minute)
302
+
303
+ let value = wanted
304
+
305
+ for (let i = 0; i < 2; i++) {
306
+ const actual = zonedParts(value, timeZone)
307
+
308
+ value += wanted - Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour, actual.minute)
309
+ }
310
+
311
+ return value
312
+ }
313
+
314
+ function zonedParts(epoch: number, timeZone: string) {
315
+ const formatter = new Intl.DateTimeFormat('en-CA', {
316
+ timeZone,
317
+ year: 'numeric',
318
+ month: '2-digit',
319
+ day: '2-digit',
320
+ hour: '2-digit',
321
+ minute: '2-digit',
322
+ hourCycle: 'h23'
323
+ })
324
+
325
+ const parts = new Map(formatter.formatToParts(epoch).map((part) => [part.type, part.value]))
326
+ const value = (type: Intl.DateTimeFormatPartTypes) => Number(parts.get(type))
327
+
328
+ return {
329
+ year: value('year'),
330
+ month: value('month'),
331
+ day: value('day'),
332
+ hour: value('hour'),
333
+ minute: value('minute')
334
+ }
335
+ }
336
+
337
+ export function formatRemaining(milliseconds: number): string {
338
+ const minutes = Math.max(1, Math.round(milliseconds / 60_000))
339
+
340
+ if (minutes < 60) return `${minutes}m`
341
+
342
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
343
+ }
344
+
345
+ function formatTime(epoch: number): string {
346
+ return new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit', timeZoneName: 'short' }).format(
347
+ epoch
348
+ )
349
+ }
package/src/usage.ts ADDED
@@ -0,0 +1,109 @@
1
+ import fs from 'node:fs/promises'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
5
+ import { Validator } from 'ata-validator'
6
+ import { t } from 'ata-validator/t'
7
+
8
+ const REQUEST_TIMEOUT_MS = 10_000
9
+ const KEYCHAIN_TIMEOUT_MS = 5_000
10
+
11
+ const WindowSchema = t.object({
12
+ utilization: t.optional(t.union([t.number(), t.null()])),
13
+ resets_at: t.optional(t.union([t.string(), t.number(), t.null()]))
14
+ })
15
+ const UsageSchema = t.object({
16
+ five_hour: t.optional(t.union([WindowSchema, t.null()])),
17
+ seven_day: t.optional(t.union([WindowSchema, t.null()])),
18
+ seven_day_opus: t.optional(t.union([WindowSchema, t.null()])),
19
+ seven_day_sonnet: t.optional(t.union([WindowSchema, t.null()]))
20
+ })
21
+ const CredentialsSchema = t.object(
22
+ {
23
+ claudeAiOauth: t.optional(t.object({ accessToken: t.optional(t.string()) }, { additionalProperties: true }))
24
+ },
25
+ { additionalProperties: true }
26
+ )
27
+
28
+ const isUsage = new Validator(UsageSchema).isValidObject
29
+ const isCredentials = new Validator(CredentialsSchema).isValidObject
30
+
31
+ export type AnthropicWindow = { utilization?: number | null; resets_at?: string | number | null }
32
+
33
+ export type AnthropicUsagePayload = {
34
+ five_hour?: AnthropicWindow | null
35
+ seven_day?: AnthropicWindow | null
36
+ seven_day_opus?: AnthropicWindow | null
37
+ seven_day_sonnet?: AnthropicWindow | null
38
+ }
39
+
40
+ function finite(value: number | null | undefined): number | undefined {
41
+ const numeric = value ?? Number.NaN
42
+ return Number.isFinite(numeric) ? numeric : undefined
43
+ }
44
+
45
+ export function resetAtMs(value: string | number | null | undefined): number | undefined {
46
+ if (value === null || value === undefined) return undefined
47
+ const numeric = Number(value)
48
+ const parsed = Number.isFinite(numeric) ? numeric : Date.parse(String(value))
49
+ if (!Number.isFinite(parsed) || parsed <= 0) return undefined
50
+ return parsed < 1e12 ? parsed * 1000 : parsed
51
+ }
52
+
53
+ export function exhaustedResetAt(payload: AnthropicUsagePayload): number | undefined {
54
+ const windows = [payload.five_hour, payload.seven_day, payload.seven_day_opus, payload.seven_day_sonnet]
55
+ let latest: number | undefined
56
+ for (const window of windows) {
57
+ const utilization = finite(window?.utilization)
58
+ const resetAt = resetAtMs(window?.resets_at)
59
+ if (utilization === undefined || utilization < 100 || resetAt === undefined) continue
60
+ latest = latest === undefined ? resetAt : Math.max(latest, resetAt)
61
+ }
62
+ return latest
63
+ }
64
+
65
+ export function claudeAccessToken(raw: string | undefined): string | undefined {
66
+ if (!raw) return undefined
67
+ try {
68
+ const parsed: unknown = JSON.parse(raw)
69
+ if (!isCredentials(parsed)) return undefined
70
+ const token = parsed.claudeAiOauth?.accessToken?.trim()
71
+ return token || undefined
72
+ } catch {
73
+ return undefined
74
+ }
75
+ }
76
+
77
+ export async function claudeToken(
78
+ pi: ExtensionAPI,
79
+ platform: NodeJS.Platform = process.platform
80
+ ): Promise<string | undefined> {
81
+ let raw: string | undefined
82
+ if (platform === 'darwin') {
83
+ const result = await pi.exec('security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], {
84
+ cwd: os.homedir(),
85
+ timeout: KEYCHAIN_TIMEOUT_MS
86
+ })
87
+ if (result.code && result.code !== 44) throw new Error(`keychain lookup failed (exit ${result.code})`)
88
+ raw = result.stdout
89
+ }
90
+ if (!raw) {
91
+ raw = await fs.readFile(path.join(os.homedir(), '.claude', '.credentials.json'), 'utf8').catch(() => undefined)
92
+ }
93
+ return claudeAccessToken(raw)
94
+ }
95
+
96
+ export async function fetchAnthropicUsage(token: string): Promise<AnthropicUsagePayload> {
97
+ const response = await fetch('https://api.anthropic.com/api/oauth/usage', {
98
+ headers: {
99
+ authorization: `Bearer ${token}`,
100
+ 'anthropic-beta': 'oauth-2025-04-20',
101
+ accept: 'application/json'
102
+ },
103
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
104
+ })
105
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
106
+ const payload: unknown = await response.json()
107
+ if (!isUsage(payload)) throw new Error('usage response did not match the Anthropic schema')
108
+ return payload
109
+ }