pi-agy-acp 0.1.2 → 0.1.4
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/CHANGELOG.md +17 -0
- package/README.md +9 -4
- package/docs/development.md +69 -20
- package/docs/reference.md +60 -37
- package/index.ts +178 -47
- package/package.json +7 -4
- package/src/acp-process.ts +8 -2
- package/src/config.ts +75 -0
- package/src/conversation.ts +327 -71
- package/src/format.ts +332 -19
- package/src/history.ts +75 -24
- package/src/jsonrpc.ts +16 -0
- package/src/mcp-bridge.ts +121 -43
- package/src/pi-stream.ts +43 -2
- package/src/preflight.ts +1 -14
- package/src/runtime.ts +330 -138
- package/src/util.ts +12 -5
package/index.ts
CHANGED
|
@@ -4,11 +4,19 @@ import {
|
|
|
4
4
|
type ProviderModelConfig,
|
|
5
5
|
type ExtensionContext,
|
|
6
6
|
} from '@earendil-works/pi-coding-agent'
|
|
7
|
-
import { AntigravityRuntime } from './src/runtime.ts'
|
|
8
|
-
import {
|
|
7
|
+
import { AntigravityRuntime, type RuntimeHost } from './src/runtime.ts'
|
|
8
|
+
import {
|
|
9
|
+
asQuotaDisplay,
|
|
10
|
+
DEFAULT_QUOTA_DISPLAY,
|
|
11
|
+
defaults,
|
|
12
|
+
readQuotaDisplayPreference,
|
|
13
|
+
writeQuotaDisplayPreference,
|
|
14
|
+
type QuotaDisplay,
|
|
15
|
+
} from './src/config.ts'
|
|
9
16
|
import { spawnAcp, runCommand } from './src/host.ts'
|
|
10
17
|
import { streamPi } from './src/pi-stream.ts'
|
|
11
18
|
import {
|
|
19
|
+
displayFraction,
|
|
12
20
|
formatQuota,
|
|
13
21
|
formatStatus,
|
|
14
22
|
formatQuotaStatus,
|
|
@@ -16,7 +24,11 @@ import {
|
|
|
16
24
|
} from './src/format.ts'
|
|
17
25
|
import type { QuotaSnapshot } from './src/quota.ts'
|
|
18
26
|
|
|
19
|
-
export default function (
|
|
27
|
+
export default function (
|
|
28
|
+
pi: ExtensionAPI,
|
|
29
|
+
host: Partial<Pick<RuntimeHost, 'runCommand'>> = {},
|
|
30
|
+
) {
|
|
31
|
+
const envQuotaDisplay = asQuotaDisplay(process.env.PI_AGY_QUOTA_DISPLAY)
|
|
20
32
|
const config = {
|
|
21
33
|
...defaults,
|
|
22
34
|
command: process.env.PI_AGY_COMMAND || '',
|
|
@@ -27,13 +39,18 @@ export default function (pi: ExtensionAPI) {
|
|
|
27
39
|
new AntigravityRuntime({
|
|
28
40
|
config,
|
|
29
41
|
spawnAcp,
|
|
30
|
-
runCommand,
|
|
42
|
+
runCommand: host.runCommand ?? runCommand,
|
|
31
43
|
log: { info: () => {}, warn: () => {} },
|
|
32
44
|
onModelsChanged: () => {
|
|
33
45
|
if (refreshDepth === 0) register()
|
|
34
46
|
},
|
|
35
47
|
})
|
|
36
48
|
let runtime = createRuntime()
|
|
49
|
+
const home = runtime.status().home
|
|
50
|
+
let quotaDisplay: QuotaDisplay =
|
|
51
|
+
envQuotaDisplay ??
|
|
52
|
+
readQuotaDisplayPreference(home) ??
|
|
53
|
+
DEFAULT_QUOTA_DISPLAY
|
|
37
54
|
const models = (): ProviderModelConfig[] =>
|
|
38
55
|
runtime.catalog.list().map((m) => {
|
|
39
56
|
const efforts = runtime.catalog.effortsFor(m.id)
|
|
@@ -85,104 +102,216 @@ export default function (pi: ExtensionAPI) {
|
|
|
85
102
|
})
|
|
86
103
|
register()
|
|
87
104
|
let uiEpoch = 0
|
|
88
|
-
let
|
|
105
|
+
let shutDown = false
|
|
106
|
+
let activeRuntime: AntigravityRuntime | undefined = runtime
|
|
107
|
+
let resetting: Promise<void> | undefined
|
|
108
|
+
interface PendingSettle {
|
|
109
|
+
runtime: AntigravityRuntime
|
|
110
|
+
epoch: number
|
|
111
|
+
ctx: ExtensionContext
|
|
112
|
+
model: ExtensionContext['model']
|
|
113
|
+
}
|
|
114
|
+
let pendingSettle: PendingSettle | undefined
|
|
89
115
|
const warned = new Set<string>()
|
|
90
116
|
const clearStatus = (ctx?: ExtensionContext) => {
|
|
91
117
|
uiEpoch++
|
|
92
|
-
|
|
118
|
+
pendingSettle = undefined
|
|
119
|
+
if (!shutDown && ctx?.hasUI) ctx.ui.setStatus(config.provider, undefined)
|
|
93
120
|
}
|
|
94
121
|
const updateStatus = (
|
|
95
122
|
ctx: ExtensionContext,
|
|
96
123
|
snapshot?: QuotaSnapshot,
|
|
97
|
-
explicit = false,
|
|
98
124
|
model = ctx.model,
|
|
99
125
|
) => {
|
|
100
|
-
if (ctx.hasUI &&
|
|
126
|
+
if (!shutDown && activeRuntime && ctx.hasUI && model?.provider === config.provider)
|
|
101
127
|
ctx.ui.setStatus(
|
|
102
128
|
config.provider,
|
|
103
|
-
snapshot
|
|
129
|
+
snapshot
|
|
130
|
+
? formatQuotaStatus(snapshot, model, quotaDisplay)
|
|
131
|
+
: undefined,
|
|
104
132
|
)
|
|
105
133
|
}
|
|
106
|
-
const reset =
|
|
134
|
+
const reset = () => {
|
|
107
135
|
uiEpoch++
|
|
108
136
|
warned.clear()
|
|
109
|
-
|
|
110
|
-
|
|
137
|
+
pendingSettle = undefined
|
|
138
|
+
activeRuntime = undefined
|
|
139
|
+
if (resetting) return resetting
|
|
140
|
+
const previous = runtime
|
|
141
|
+
resetting = (async () => {
|
|
142
|
+
try {
|
|
143
|
+
await previous.dispose()
|
|
144
|
+
if (shutDown) return
|
|
145
|
+
runtime = activeRuntime = createRuntime()
|
|
146
|
+
} finally {
|
|
147
|
+
resetting = undefined
|
|
148
|
+
}
|
|
149
|
+
})()
|
|
150
|
+
return resetting
|
|
111
151
|
}
|
|
112
|
-
pi.on('session_tree', () =>
|
|
113
|
-
pi.on('session_compact', () =>
|
|
152
|
+
pi.on('session_tree', () => activeRuntime?.resetConversations())
|
|
153
|
+
pi.on('session_compact', () => activeRuntime?.resetConversations())
|
|
114
154
|
pi.on('session_start', async (event, ctx) => {
|
|
115
155
|
clearStatus(ctx)
|
|
156
|
+
const epoch = uiEpoch
|
|
157
|
+
if (resetting) await resetting.catch(() => {})
|
|
158
|
+
if (shutDown) return
|
|
116
159
|
if (['new', 'resume', 'fork'].includes(event.reason))
|
|
117
|
-
await
|
|
118
|
-
|
|
160
|
+
await activeRuntime?.resetConversations()
|
|
161
|
+
if (!shutDown && epoch === uiEpoch)
|
|
162
|
+
updateStatus(ctx, activeRuntime?.quota.peek())
|
|
119
163
|
})
|
|
120
164
|
pi.on('session_shutdown', async (_event, ctx) => {
|
|
121
165
|
clearStatus(ctx)
|
|
166
|
+
shutDown = true
|
|
167
|
+
activeRuntime = undefined
|
|
168
|
+
pendingSettle = undefined
|
|
169
|
+
if (resetting) await resetting.catch(() => {})
|
|
122
170
|
await runtime.dispose()
|
|
123
171
|
})
|
|
124
|
-
pi.on('cache_warming_decision', () =>
|
|
172
|
+
pi.on('cache_warming_decision', (_event, ctx) =>
|
|
173
|
+
ctx.model?.provider === config.provider ? { action: 'stop' } : undefined,
|
|
174
|
+
)
|
|
125
175
|
pi.on('model_select', (event, ctx) => {
|
|
176
|
+
const retarget =
|
|
177
|
+
pendingSettle &&
|
|
178
|
+
pendingSettle.runtime === activeRuntime &&
|
|
179
|
+
pendingSettle.epoch === uiEpoch &&
|
|
180
|
+
event.model?.provider === config.provider
|
|
181
|
+
? pendingSettle
|
|
182
|
+
: undefined
|
|
126
183
|
clearStatus(ctx)
|
|
127
|
-
|
|
184
|
+
if (retarget) {
|
|
185
|
+
retarget.epoch = uiEpoch
|
|
186
|
+
retarget.ctx = ctx
|
|
187
|
+
retarget.model = event.model
|
|
188
|
+
pendingSettle = retarget
|
|
189
|
+
}
|
|
190
|
+
updateStatus(ctx, activeRuntime?.quota.peek(), event.model)
|
|
128
191
|
})
|
|
129
192
|
pi.on('agent_settled', (_event, ctx) => {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
)
|
|
193
|
+
// Pi 1.5.2 AgentSession._emitAgentSettled runs after tools and the run finish.
|
|
194
|
+
runtime.settleSession(ctx.sessionManager.getSessionId())
|
|
195
|
+
const current = activeRuntime
|
|
196
|
+
if (!current || !ctx.hasUI || ctx.model?.provider !== config.provider) return
|
|
197
|
+
if (pendingSettle?.runtime === current) {
|
|
198
|
+
pendingSettle.epoch = uiEpoch
|
|
199
|
+
pendingSettle.ctx = ctx
|
|
200
|
+
pendingSettle.model = ctx.model
|
|
135
201
|
return
|
|
136
|
-
|
|
137
|
-
const
|
|
138
|
-
|
|
202
|
+
}
|
|
203
|
+
const state: PendingSettle = {
|
|
204
|
+
runtime: current,
|
|
205
|
+
epoch: uiEpoch,
|
|
206
|
+
ctx,
|
|
207
|
+
model: ctx.model,
|
|
208
|
+
}
|
|
209
|
+
pendingSettle = state
|
|
139
210
|
void current.quota
|
|
140
211
|
.read(false)
|
|
141
212
|
.then((snapshot) => {
|
|
142
213
|
if (
|
|
143
|
-
|
|
144
|
-
|
|
214
|
+
shutDown ||
|
|
215
|
+
pendingSettle !== state ||
|
|
216
|
+
state.runtime !== activeRuntime ||
|
|
217
|
+
state.epoch !== uiEpoch ||
|
|
145
218
|
snapshot.status !== 'ok'
|
|
146
219
|
)
|
|
147
220
|
return
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
221
|
+
const targetCtx = state.ctx
|
|
222
|
+
const model = state.model
|
|
223
|
+
if (!targetCtx.hasUI || model?.provider !== config.provider) return
|
|
224
|
+
updateStatus(targetCtx, snapshot, model)
|
|
225
|
+
const quota = quotaForModel(snapshot, model)
|
|
151
226
|
if (!quota || quota.fraction > 0.2) return
|
|
152
227
|
const threshold = quota.fraction <= 0.05 ? 5 : 20
|
|
153
|
-
const
|
|
228
|
+
const groupName = quota.group.name || 'Unnamed model group'
|
|
229
|
+
const windowLabel =
|
|
230
|
+
quota.bucket.window ||
|
|
231
|
+
quota.bucket.name ||
|
|
232
|
+
quota.bucket.id ||
|
|
233
|
+
'quota'
|
|
234
|
+
const key = `${groupName}:${quota.bucket.id}:${windowLabel}:${quota.bucket.resetTime || 'none'}:${threshold}`
|
|
154
235
|
if (warned.has(key)) return
|
|
155
236
|
warned.add(key)
|
|
156
|
-
|
|
157
|
-
|
|
237
|
+
const percent = Math.round(
|
|
238
|
+
displayFraction(quota.fraction, quotaDisplay) * 100,
|
|
239
|
+
)
|
|
240
|
+
const metric = `${percent}% ${quotaDisplay}`
|
|
241
|
+
targetCtx.ui.notify(
|
|
242
|
+
`Antigravity quota low: ${metric} (${groupName}, ${windowLabel}).`,
|
|
158
243
|
'warning',
|
|
159
244
|
)
|
|
160
245
|
})
|
|
161
246
|
.catch(() => {})
|
|
162
247
|
.finally(() => {
|
|
163
|
-
|
|
248
|
+
if (pendingSettle === state) pendingSettle = undefined
|
|
164
249
|
})
|
|
165
250
|
})
|
|
251
|
+
const readQuotaSafe = async (): Promise<QuotaSnapshot> => {
|
|
252
|
+
if (!activeRuntime)
|
|
253
|
+
return {
|
|
254
|
+
status: 'error',
|
|
255
|
+
updatedAt: new Date().toISOString(),
|
|
256
|
+
groups: [],
|
|
257
|
+
error: 'Antigravity ACP runtime is disposed.',
|
|
258
|
+
}
|
|
259
|
+
try {
|
|
260
|
+
return await activeRuntime.readQuota(true)
|
|
261
|
+
} catch (err) {
|
|
262
|
+
return {
|
|
263
|
+
status: 'error',
|
|
264
|
+
updatedAt: new Date().toISOString(),
|
|
265
|
+
groups: [],
|
|
266
|
+
error: err instanceof Error ? err.message : String(err),
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
166
270
|
pi.registerCommand('agy-acp', {
|
|
167
271
|
description: 'Antigravity ACP status, quota, or reset',
|
|
168
272
|
getArgumentCompletions: (prefix) => {
|
|
169
|
-
const
|
|
170
|
-
|
|
273
|
+
const normalized = prefix.trimStart()
|
|
274
|
+
const items = [
|
|
275
|
+
'status',
|
|
276
|
+
'quota',
|
|
277
|
+
'quota used',
|
|
278
|
+
'quota remaining',
|
|
279
|
+
'reset',
|
|
280
|
+
]
|
|
281
|
+
.filter((command) => command.startsWith(normalized))
|
|
171
282
|
.map((value) => ({ value, label: value }))
|
|
172
283
|
return items.length > 0 ? items : null
|
|
173
284
|
},
|
|
174
285
|
handler: async (args, ctx) => {
|
|
175
|
-
|
|
176
|
-
|
|
286
|
+
if (shutDown) return
|
|
287
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean)
|
|
288
|
+
const command = tokens[0] ?? ''
|
|
289
|
+
const requestedDisplay =
|
|
290
|
+
command === 'quota' && tokens.length === 2
|
|
291
|
+
? asQuotaDisplay(tokens[1])
|
|
292
|
+
: undefined
|
|
293
|
+
if (command === 'reset' && tokens.length === 1) {
|
|
177
294
|
clearStatus(ctx)
|
|
178
295
|
await reset()
|
|
179
|
-
ctx.ui.notify('Antigravity ACP sessions reset', 'info')
|
|
296
|
+
if (!shutDown) ctx.ui.notify('Antigravity ACP sessions reset', 'info')
|
|
180
297
|
return
|
|
181
298
|
}
|
|
182
|
-
|
|
183
|
-
|
|
299
|
+
const isStatus =
|
|
300
|
+
(command === '' || command === 'status') && tokens.length <= 1
|
|
301
|
+
const isQuota =
|
|
302
|
+
command === 'quota' &&
|
|
303
|
+
(tokens.length === 1 || requestedDisplay !== undefined)
|
|
304
|
+
if (!isStatus && !isQuota) {
|
|
305
|
+
ctx.ui.notify(
|
|
306
|
+
'Usage: /agy-acp [status|quota [used|remaining]|reset]',
|
|
307
|
+
'warning',
|
|
308
|
+
)
|
|
184
309
|
return
|
|
185
310
|
}
|
|
311
|
+
if (requestedDisplay !== undefined) {
|
|
312
|
+
quotaDisplay = requestedDisplay
|
|
313
|
+
writeQuotaDisplayPreference(home, quotaDisplay)
|
|
314
|
+
}
|
|
186
315
|
let snapshot: QuotaSnapshot | null = null
|
|
187
316
|
const epoch = uiEpoch
|
|
188
317
|
if (command === 'quota') {
|
|
@@ -196,24 +325,26 @@ export default function (pi: ExtensionAPI) {
|
|
|
196
325
|
'Fetching Antigravity quota...',
|
|
197
326
|
)
|
|
198
327
|
loader.onAbort = () => done(null)
|
|
199
|
-
//
|
|
200
|
-
void
|
|
328
|
+
// readQuotaSafe converts runtime errors into snapshots so loaders always close cleanly.
|
|
329
|
+
void readQuotaSafe().then((result) => {
|
|
201
330
|
if (!loader.signal.aborted) done(result)
|
|
202
331
|
})
|
|
203
332
|
return loader
|
|
204
333
|
},
|
|
205
334
|
)
|
|
206
|
-
: await
|
|
335
|
+
: await readQuotaSafe()
|
|
336
|
+
if (shutDown) return
|
|
207
337
|
if (snapshot === null) {
|
|
338
|
+
if (epoch === uiEpoch) updateStatus(ctx, activeRuntime?.quota.peek())
|
|
208
339
|
ctx.ui.notify('Quota check cancelled', 'info')
|
|
209
340
|
return
|
|
210
341
|
}
|
|
211
342
|
}
|
|
212
343
|
const notice = snapshot
|
|
213
|
-
? formatQuota(snapshot)
|
|
344
|
+
? formatQuota(snapshot, undefined, quotaDisplay)
|
|
214
345
|
: formatStatus(runtime.status())
|
|
215
346
|
if (epoch === uiEpoch)
|
|
216
|
-
updateStatus(ctx, snapshot ??
|
|
347
|
+
updateStatus(ctx, snapshot ?? activeRuntime?.quota.peek())
|
|
217
348
|
ctx.ui.notify(notice.text, notice.level)
|
|
218
349
|
},
|
|
219
350
|
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-agy-acp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Google Antigravity ACP provider extension for Pi Coding Agent",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"NOTICE"
|
|
28
28
|
],
|
|
29
29
|
"engines": {
|
|
30
|
-
"node": ">=22.
|
|
30
|
+
"node": ">=22.19.0"
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
33
33
|
"@earendil-works/pi-ai": "*",
|
|
@@ -39,8 +39,11 @@
|
|
|
39
39
|
"check": "tsc --noEmit"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"typescript": "
|
|
43
|
-
"@types/node": "
|
|
42
|
+
"typescript": "7.0.2",
|
|
43
|
+
"@types/node": "22.20.5",
|
|
44
|
+
"@earendil-works/pi-ai": "1.5.2",
|
|
45
|
+
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
46
|
+
"@earendil-works/pi-tui": "1.5.2"
|
|
44
47
|
},
|
|
45
48
|
"keywords": [
|
|
46
49
|
"pi-package",
|
package/src/acp-process.ts
CHANGED
|
@@ -36,6 +36,7 @@ export interface AcpSessionUpdate {
|
|
|
36
36
|
sessionUpdate: string
|
|
37
37
|
content?: { type: string; text?: string }
|
|
38
38
|
toolCallId?: string
|
|
39
|
+
name?: string
|
|
39
40
|
title?: string
|
|
40
41
|
status?: string
|
|
41
42
|
kind?: string
|
|
@@ -74,6 +75,7 @@ export interface AcpPermissionRequest {
|
|
|
74
75
|
sessionId: string
|
|
75
76
|
toolCall?: {
|
|
76
77
|
toolCallId?: string
|
|
78
|
+
name?: string
|
|
77
79
|
title?: string
|
|
78
80
|
kind?: string
|
|
79
81
|
rawInput?: unknown
|
|
@@ -202,7 +204,9 @@ export class AcpProcess {
|
|
|
202
204
|
|
|
203
205
|
/** Terminate the process. */
|
|
204
206
|
stop(): void {
|
|
205
|
-
|
|
207
|
+
const error = new Error('ACP process stopped')
|
|
208
|
+
this.fail(error)
|
|
209
|
+
this.peer?.close(error)
|
|
206
210
|
this.child?.terminate()
|
|
207
211
|
}
|
|
208
212
|
|
|
@@ -223,7 +227,8 @@ export class AcpProcess {
|
|
|
223
227
|
params,
|
|
224
228
|
{ timeoutMs },
|
|
225
229
|
)
|
|
226
|
-
|
|
230
|
+
// JsonRpcPeer can resolve a buffered reply before stop; leave its rollback to the owner.
|
|
231
|
+
if (this.alive) this.listeners.set(result.sessionId, listener)
|
|
227
232
|
return result
|
|
228
233
|
}
|
|
229
234
|
|
|
@@ -307,6 +312,7 @@ export class AcpProcess {
|
|
|
307
312
|
private fail(error: Error): void {
|
|
308
313
|
if (this.exitError !== undefined) return
|
|
309
314
|
this.exitError = error
|
|
315
|
+
this.listeners.clear()
|
|
310
316
|
for (const listener of this.exitListeners) listener(error)
|
|
311
317
|
}
|
|
312
318
|
|
package/src/config.ts
CHANGED
|
@@ -1,8 +1,24 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mkdirSync,
|
|
3
|
+
readFileSync,
|
|
4
|
+
renameSync,
|
|
5
|
+
unlinkSync,
|
|
6
|
+
writeFileSync,
|
|
7
|
+
} from 'node:fs'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
|
|
1
10
|
/** Reasoning effort ids accepted by the Antigravity ACP `thought_level` option. */
|
|
2
11
|
export const EFFORTS = ['low', 'medium', 'high'] as const
|
|
3
12
|
/** One Antigravity reasoning effort. */
|
|
4
13
|
export type Effort = (typeof EFFORTS)[number]
|
|
5
14
|
|
|
15
|
+
/** Supported quota percentage display conventions. */
|
|
16
|
+
export const QUOTA_DISPLAY_MODES = ['used', 'remaining'] as const
|
|
17
|
+
/** Quota percentage display convention (`used` counts up from 0%, `remaining` counts down from 100%). */
|
|
18
|
+
export type QuotaDisplay = (typeof QUOTA_DISPLAY_MODES)[number]
|
|
19
|
+
/** Default quota percentage display convention when no env var or saved preference is set. */
|
|
20
|
+
export const DEFAULT_QUOTA_DISPLAY: QuotaDisplay = 'used'
|
|
21
|
+
|
|
6
22
|
/** Validated plugin configuration. */
|
|
7
23
|
export interface Config {
|
|
8
24
|
/** Provider route id shown in the model picker. */
|
|
@@ -45,6 +61,65 @@ export const defaults: Config = {
|
|
|
45
61
|
longDecodeContinuations: 3,
|
|
46
62
|
quotaTtlMs: 120000,
|
|
47
63
|
}
|
|
64
|
+
|
|
48
65
|
export function asEffort(value: string | undefined): Effort | undefined {
|
|
49
66
|
return EFFORTS.includes(value as Effort) ? (value as Effort) : undefined
|
|
50
67
|
}
|
|
68
|
+
|
|
69
|
+
export function asQuotaDisplay(
|
|
70
|
+
value: string | undefined,
|
|
71
|
+
): QuotaDisplay | undefined {
|
|
72
|
+
const normalized = value?.trim().toLowerCase()
|
|
73
|
+
return QUOTA_DISPLAY_MODES.includes(normalized as QuotaDisplay)
|
|
74
|
+
? (normalized as QuotaDisplay)
|
|
75
|
+
: undefined
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const SETTINGS_FILE = 'settings.json'
|
|
79
|
+
|
|
80
|
+
/** Read a JSON file as a plain object, returning `{}` when missing or invalid. */
|
|
81
|
+
export function readJson(path: string): Record<string, unknown> {
|
|
82
|
+
try {
|
|
83
|
+
const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
|
|
84
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
85
|
+
? (parsed as Record<string, unknown>)
|
|
86
|
+
: {}
|
|
87
|
+
} catch {
|
|
88
|
+
return {}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Read the last remembered quota display preference from `home/settings.json`. */
|
|
93
|
+
export function readQuotaDisplayPreference(
|
|
94
|
+
home: string,
|
|
95
|
+
): QuotaDisplay | undefined {
|
|
96
|
+
const settings = readJson(join(home, SETTINGS_FILE))
|
|
97
|
+
return typeof settings.quotaDisplay === 'string'
|
|
98
|
+
? asQuotaDisplay(settings.quotaDisplay)
|
|
99
|
+
: undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Persist the user's quota display preference in `home/settings.json`. */
|
|
103
|
+
export function writeQuotaDisplayPreference(
|
|
104
|
+
home: string,
|
|
105
|
+
quotaDisplay: QuotaDisplay,
|
|
106
|
+
): void {
|
|
107
|
+
const path = join(home, SETTINGS_FILE)
|
|
108
|
+
const tempPath = join(
|
|
109
|
+
home,
|
|
110
|
+
`.${SETTINGS_FILE}.${process.pid}.${Date.now()}.tmp`,
|
|
111
|
+
)
|
|
112
|
+
try {
|
|
113
|
+
mkdirSync(home, { recursive: true })
|
|
114
|
+
const existing = readJson(path)
|
|
115
|
+
const content = `${JSON.stringify({ ...existing, quotaDisplay }, null, 2)}\n`
|
|
116
|
+
writeFileSync(tempPath, content)
|
|
117
|
+
renameSync(tempPath, path)
|
|
118
|
+
} catch {
|
|
119
|
+
try {
|
|
120
|
+
unlinkSync(tempPath)
|
|
121
|
+
} catch {
|
|
122
|
+
// Best-effort cleanup.
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|