pi-agy-acp 0.2.1 → 0.2.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/CHANGELOG.md +9 -0
- package/docs/development.md +15 -6
- package/docs/reference.md +15 -8
- package/index.ts +11 -2
- package/package.json +1 -1
- package/src/acp-process.ts +15 -1
- package/src/catalog.ts +29 -19
- package/src/conversation.ts +66 -16
- package/src/format.ts +68 -23
- package/src/host.ts +148 -13
- package/src/jsonrpc.ts +38 -4
- package/src/mcp-bridge.ts +26 -2
- package/src/preflight.ts +296 -371
- package/src/quota.ts +39 -20
- package/src/runtime.ts +305 -104
- package/src/session-db.ts +670 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.2](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.1...v0.2.2) (2026-11-22)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Bug Fixes
|
|
7
|
+
|
|
8
|
+
* **host:** harden process lifecycle, OAuth/settings atomic writes, and JSON-RPC framing ([#40](https://github.com/fdkevin0/pi-agy-acp/issues/40)) ([c468085](https://github.com/fdkevin0/pi-agy-acp/commit/c4680859c9b407f6729382484c26dea2340423fe))
|
|
9
|
+
* **quota:** filter disabled buckets, suppress untouched rolling resets, and use monotonic TTL ([#38](https://github.com/fdkevin0/pi-agy-acp/issues/38)) ([707eb80](https://github.com/fdkevin0/pi-agy-acp/commit/707eb80bfec3505b1634ee51f1f55ab9b9636000))
|
|
10
|
+
* **runtime:** atomic MCP relay delivery, re-entry guard, and catalog/sweep hardening ([#42](https://github.com/fdkevin0/pi-agy-acp/issues/42)) ([4016234](https://github.com/fdkevin0/pi-agy-acp/commit/40162349b432746646ed4adfc0d084cac5f390dd))
|
|
11
|
+
|
|
3
12
|
## [0.2.1](https://github.com/fdkevin0/pi-agy-acp/compare/v0.2.0...v0.2.1) (2026-11-22)
|
|
4
13
|
|
|
5
14
|
|
package/docs/development.md
CHANGED
|
@@ -53,8 +53,16 @@ pi -e ./index.ts
|
|
|
53
53
|
credentials, and validates structured tool identity before granting permissions.
|
|
54
54
|
On Unix, `agy acp` and helper commands run in detached process groups so
|
|
55
55
|
termination and timeouts signal `-pid` (`SIGTERM`, then `SIGKILL`) without
|
|
56
|
-
orphaning `--process-per-session` workers. Session SQLite reads
|
|
57
|
-
symlinked or non-regular `.db`, `.db-wal`,
|
|
56
|
+
orphaning `--process-per-session` workers. Session SQLite reads
|
|
57
|
+
(`src/session-db.ts`) reject symlinked or non-regular `.db`, `.db-wal`,
|
|
58
|
+
`.db-shm`, and `.db-journal` files, gate streaming reads by cached context
|
|
59
|
+
window / positive `usage_update` and `(mtimeNs, size)` stamps, bound
|
|
60
|
+
`gen_metadata` scans with `LIMIT`, and inspect terminal `steps` (`step_type = 17`)
|
|
61
|
+
on `end_turn` and `refusal` to surface hidden API errors (`QUOTA_EXHAUSTED`,
|
|
62
|
+
`INVALID_THINKING_SIGNATURE`, `429`/`RESOURCE_EXHAUSTED`, and `404`/`NOT_FOUND`)
|
|
63
|
+
while preserving pure safety refusals and resetting poisoned sessions.
|
|
64
|
+
Startup and session cleanup also remove `.db-journal` sidecars and
|
|
65
|
+
`annotations/` files without traversing symlinks.
|
|
58
66
|
Live `agy 1.5.10+` sessions issue `session/request_permission` only inside an
|
|
59
67
|
active `session/prompt` turn (never during `session/new` or
|
|
60
68
|
`session/set_config_option`), so session creation and idle pre-/post-turn
|
|
@@ -80,8 +88,9 @@ pi -e ./index.ts
|
|
|
80
88
|
runtime, persisting the tier in `catalog.json`. Email lookup scans `cli.log`
|
|
81
89
|
and the newest 10 contained `log/cli-*.log` and `log/acp-server-*.log` files
|
|
82
90
|
(newest first, deduplicated), checking the tail 64 KiB first and falling back
|
|
83
|
-
to the head 64 KiB when larger. Runtime warnings stay off stderr to
|
|
84
|
-
TUI rendering
|
|
91
|
+
to the head 64 KiB when larger. Runtime warnings stay off stderr by default to
|
|
92
|
+
preserve TUI rendering (diagnostics use status and agy's logs); set
|
|
93
|
+
`PI_AGY_DEBUG=1` to print runtime warnings on stderr.
|
|
85
94
|
- **Pi stream and error contracts:** `onPayload` can replace the request, and
|
|
86
95
|
`onProviderStreamEvent` observes events before conversion. At the first stream
|
|
87
96
|
event, `onResponse` receives synthetic status `200` and empty headers before
|
|
@@ -93,7 +102,7 @@ pi -e ./index.ts
|
|
|
93
102
|
## MCP HTTP boundary
|
|
94
103
|
|
|
95
104
|
The loopback bridge returns 400 for invalid URLs and 413 for authenticated POST
|
|
96
|
-
bodies exceeding
|
|
105
|
+
bodies exceeding 8 MiB (8,388,608 bytes), including chunked uploads. Rejected
|
|
97
106
|
oversized uploads close their connection after the error response. JSON parse
|
|
98
107
|
errors retain the MCP parse-error response. Unexpected handler failures return
|
|
99
108
|
500 before headers or destroy an already-started response; listener errors go to
|
|
@@ -112,7 +121,7 @@ connections and destroys all tracked sockets without waiting for tool promises.
|
|
|
112
121
|
| `src/pi-stream.ts`, `src/protocol.ts` | Pi message conversion and bridge event contracts. |
|
|
113
122
|
| `src/runtime.ts`, `src/conversation.ts`, `src/history.ts` | Session orchestration, pending calls, tool identity metadata, streaming, and history replay. |
|
|
114
123
|
| `src/acp-process.ts`, `src/jsonrpc.ts`, `src/mcp-bridge.ts` | ACP transport, local MCP server, tool schema compression, and tool deltas. |
|
|
115
|
-
| `src/host.ts`, `src/preflight.ts`, `src/config.ts` | Process execution, executable discovery,
|
|
124
|
+
| `src/host.ts`, `src/preflight.ts`, `src/session-db.ts`, `src/config.ts` | Process execution, executable discovery, isolated home setup, and read-only session SQLite telemetry/error inspection. |
|
|
116
125
|
| `src/catalog.ts`, `src/quota.ts`, `src/format.ts`, `src/util.ts` | Model catalog, quota queries, TUI notice formatting, and shared utilities. |
|
|
117
126
|
| `src/version.ts` | ACP/MCP version read from `package.json`. |
|
|
118
127
|
| `tests/` | Scripted agy fixture, runtime tests, and Pi integration tests. |
|
package/docs/reference.md
CHANGED
|
@@ -36,9 +36,11 @@ will not appear after cancellation. Non-TUI modes query directly without a loade
|
|
|
36
36
|
|
|
37
37
|
Quota is read through `agy -p /usage --output-format json`. Each model group has
|
|
38
38
|
one row per quota window, with a 12-cell bar, a rounded percentage, and a relative
|
|
39
|
-
reset time
|
|
40
|
-
|
|
41
|
-
|
|
39
|
+
reset time (omitted for untouched rolling windows at `0%` used / `100%` remaining
|
|
40
|
+
whose reset time is still a full window away). By default (`used` mode), bars and
|
|
41
|
+
percentages count up from `0%`; pass `remaining` (`/agy-acp quota remaining`) to
|
|
42
|
+
count down from `100%`. The last selected mode is saved in `settings.json` inside
|
|
43
|
+
`PI_AGY_HOME`. For example:
|
|
42
44
|
|
|
43
45
|
```text
|
|
44
46
|
Antigravity Quota
|
|
@@ -46,7 +48,7 @@ Antigravity Quota
|
|
|
46
48
|
|
|
47
49
|
Gemini Models
|
|
48
50
|
Gemini Flash, Gemini Pro
|
|
49
|
-
5h [░░░░░░░░░░░░] 0%
|
|
51
|
+
5h [░░░░░░░░░░░░] 0%
|
|
50
52
|
weekly [█░░░░░░░░░░░] 9% · resets in 6d 7h
|
|
51
53
|
```
|
|
52
54
|
|
|
@@ -109,6 +111,7 @@ Set these environment variables before starting Pi:
|
|
|
109
111
|
| `PI_AGY_COMMAND` | Absolute path to the `agy` executable. | Automatic discovery. |
|
|
110
112
|
| `PI_AGY_HOME` | Dedicated directory for this extension's agy state. | `~/.pi/agent/cache/antigravity-acp` |
|
|
111
113
|
| `PI_AGY_QUOTA_DISPLAY` | Startup quota display mode (`used` or `remaining`), overriding `settings.json` for startup. Invalid values are ignored; `/agy-acp quota <mode>` overrides it for the active session. | `settings.json`, then `used` |
|
|
114
|
+
| `PI_AGY_DEBUG` | Set to `1` to emit runtime warnings on `stderr` (silent by default to protect the TUI). | Unset (silent) |
|
|
112
115
|
|
|
113
116
|
For example:
|
|
114
117
|
|
|
@@ -127,10 +130,14 @@ are retained; sessions rebuild from Pi's history. Cleanup is best-effort if file
|
|
|
127
130
|
for each concurrently running Pi instance, since startup cleanup assumes exclusive
|
|
128
131
|
use of the directory.
|
|
129
132
|
|
|
130
|
-
With file-backed authentication
|
|
131
|
-
from your normal agy directory
|
|
132
|
-
`~/.gemini/antigravity-cli`)
|
|
133
|
-
|
|
133
|
+
With file-backed authentication and the default `PI_AGY_HOME`, the extension
|
|
134
|
+
atomically syncs the existing OAuth token from your normal agy directory
|
|
135
|
+
(`ANTIGRAVITY_CLI_HOME`, `AGY_HOME`, or `~/.gemini/antigravity-cli`) with `0600`
|
|
136
|
+
permissions while refusing symlinked paths. A custom `PI_AGY_HOME` stays
|
|
137
|
+
isolated and does not copy tokens from default agy directories. Note that quota
|
|
138
|
+
queries (`agy -p /usage`) always query the global `agy` CLI account because
|
|
139
|
+
`agy` does not accept `--gemini-dir` on `/usage`. Do not commit or share this
|
|
140
|
+
directory. Authentication and token refresh remain agy's responsibility.
|
|
134
141
|
|
|
135
142
|
## Models and context
|
|
136
143
|
|
package/index.ts
CHANGED
|
@@ -26,9 +26,10 @@ import type { QuotaSnapshot } from './src/quota.ts'
|
|
|
26
26
|
|
|
27
27
|
export default function (
|
|
28
28
|
pi: ExtensionAPI,
|
|
29
|
-
host: Partial<Pick<RuntimeHost, 'runCommand' | 'spawnAcp'>> = {},
|
|
29
|
+
host: Partial<Pick<RuntimeHost, 'runCommand' | 'spawnAcp' | 'quotaNow'>> = {},
|
|
30
30
|
) {
|
|
31
31
|
const envQuotaDisplay = asQuotaDisplay(process.env.PI_AGY_QUOTA_DISPLAY)
|
|
32
|
+
const debug = process.env.PI_AGY_DEBUG === '1'
|
|
32
33
|
const config = {
|
|
33
34
|
...defaults,
|
|
34
35
|
command: process.env.PI_AGY_COMMAND || '',
|
|
@@ -40,7 +41,15 @@ export default function (
|
|
|
40
41
|
config,
|
|
41
42
|
spawnAcp: host.spawnAcp ?? spawnAcp,
|
|
42
43
|
runCommand: host.runCommand ?? runCommand,
|
|
43
|
-
|
|
44
|
+
quotaNow: host.quotaNow,
|
|
45
|
+
log: {
|
|
46
|
+
info: () => {},
|
|
47
|
+
warn: debug
|
|
48
|
+
? (message) => {
|
|
49
|
+
process.stderr.write(`[pi-agy-acp] ${message}\n`)
|
|
50
|
+
}
|
|
51
|
+
: () => {},
|
|
52
|
+
},
|
|
44
53
|
onModelsChanged: () => {
|
|
45
54
|
if (refreshDepth === 0) register()
|
|
46
55
|
},
|
package/package.json
CHANGED
package/src/acp-process.ts
CHANGED
|
@@ -167,6 +167,8 @@ export class AcpProcess {
|
|
|
167
167
|
private readonly listeners = new Map<string, AcpSessionListener>()
|
|
168
168
|
private child: AcpChild | undefined
|
|
169
169
|
private peer: JsonRpcPeer | undefined
|
|
170
|
+
private childExited = false
|
|
171
|
+
private childTerminated = false
|
|
170
172
|
private exitError: Error | undefined
|
|
171
173
|
private readonly exitListeners = new Set<(error: Error) => void>()
|
|
172
174
|
private readonly options: AcpProcessOptions
|
|
@@ -202,15 +204,21 @@ export class AcpProcess {
|
|
|
202
204
|
async start(timeoutMs: number): Promise<AcpInitializeResult | undefined> {
|
|
203
205
|
const child = this.options.spawn(this.options.argv, this.options.cwd)
|
|
204
206
|
this.child = child
|
|
207
|
+
this.childExited = false
|
|
208
|
+
this.childTerminated = false
|
|
205
209
|
const peer = new JsonRpcPeer(child.stdout, child.stdin, {
|
|
206
210
|
onRequest: (method, params) => this.onRequest(method, params),
|
|
207
211
|
onNotification: (method, params) => this.onNotification(method, params),
|
|
208
|
-
onClose: (error) =>
|
|
212
|
+
onClose: (error) => {
|
|
213
|
+
if (!this.childExited) this.terminateChild()
|
|
214
|
+
this.fail(error)
|
|
215
|
+
},
|
|
209
216
|
onProtocolError: (detail) =>
|
|
210
217
|
this.options.log?.(`acp: dropped frame: ${detail}`),
|
|
211
218
|
})
|
|
212
219
|
this.peer = peer
|
|
213
220
|
void child.exited.then(({ code, signal }) => {
|
|
221
|
+
this.childExited = true
|
|
214
222
|
const tail = child.stderrTail().trim().split('\n').slice(-5).join(' | ')
|
|
215
223
|
const error = new Error(
|
|
216
224
|
`agy acp exited (code=${code ?? 'null'} signal=${signal ?? 'null'})${tail ? `: ${tail}` : ''}`,
|
|
@@ -237,6 +245,12 @@ export class AcpProcess {
|
|
|
237
245
|
const error = new Error('ACP process stopped')
|
|
238
246
|
this.fail(error)
|
|
239
247
|
this.peer?.close(error)
|
|
248
|
+
this.terminateChild()
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private terminateChild(): void {
|
|
252
|
+
if (this.childTerminated || this.childExited) return
|
|
253
|
+
this.childTerminated = true
|
|
240
254
|
this.child?.terminate()
|
|
241
255
|
}
|
|
242
256
|
|
package/src/catalog.ts
CHANGED
|
@@ -285,13 +285,14 @@ export class ModelCatalog {
|
|
|
285
285
|
(o) => o.id === 'thought_level' || o.category === 'thought_level',
|
|
286
286
|
)
|
|
287
287
|
const beforeEfforts = JSON.stringify(this.efforts)
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
288
|
+
const levelEfforts =
|
|
289
|
+
levelOption?.options !== undefined
|
|
290
|
+
? flattenConfigOptions(levelOption.options)
|
|
291
|
+
.map((o) => o.value)
|
|
292
|
+
.filter((v): v is Effort =>
|
|
293
|
+
(EFFORTS as readonly string[]).includes(v),
|
|
294
|
+
)
|
|
295
|
+
: []
|
|
295
296
|
const modelEntries = flattenConfigOptions(modelOption?.options)
|
|
296
297
|
const next =
|
|
297
298
|
modelEntries.length > 0
|
|
@@ -303,18 +304,31 @@ export class ModelCatalog {
|
|
|
303
304
|
this.observed = true
|
|
304
305
|
const changed = JSON.stringify(next) !== JSON.stringify(this.models)
|
|
305
306
|
if (changed) this.models = next
|
|
307
|
+
let prunedChanged = false
|
|
308
|
+
if (modelEntries.length > 0) {
|
|
309
|
+
const activeIds = new Set(this.models.map((m) => m.id))
|
|
310
|
+
for (const id of [...this.byModel.keys()]) {
|
|
311
|
+
if (!activeIds.has(id)) {
|
|
312
|
+
this.byModel.delete(id)
|
|
313
|
+
prunedChanged = true
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
306
317
|
const derivedChanged = this.deriveEfforts()
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
318
|
+
const union = new Set<Effort>(levelEfforts)
|
|
319
|
+
for (const model of this.models) {
|
|
320
|
+
const values = this.byModel.get(model.id)
|
|
321
|
+
if (values !== undefined) {
|
|
310
322
|
for (const effort of values) union.add(effort)
|
|
311
323
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
324
|
+
}
|
|
325
|
+
if (union.size > 0) {
|
|
326
|
+
this.efforts = EFFORTS.filter((e) => union.has(e))
|
|
315
327
|
}
|
|
316
328
|
const effortsChanged =
|
|
317
|
-
|
|
329
|
+
prunedChanged ||
|
|
330
|
+
derivedChanged ||
|
|
331
|
+
beforeEfforts !== JSON.stringify(this.efforts)
|
|
318
332
|
if (changed || effortsChanged || tierChanged || this.fingerprintDirty)
|
|
319
333
|
this.save()
|
|
320
334
|
return changed || effortsChanged
|
|
@@ -350,11 +364,7 @@ export class ModelCatalog {
|
|
|
350
364
|
}
|
|
351
365
|
continue
|
|
352
366
|
}
|
|
353
|
-
const present = this.available.some(
|
|
354
|
-
(entry) =>
|
|
355
|
-
entry.modelId === model.id ||
|
|
356
|
-
entry.modelId.startsWith(`${model.id}-`),
|
|
357
|
-
)
|
|
367
|
+
const present = this.available.some((entry) => entry.modelId === model.id)
|
|
358
368
|
if (!present) continue
|
|
359
369
|
const prevEfforts = this.effortsFor(model.id)
|
|
360
370
|
if (this.byModel.get(model.id)?.length !== 0) {
|
package/src/conversation.ts
CHANGED
|
@@ -19,7 +19,11 @@ import type {
|
|
|
19
19
|
AcpPermissionRequest,
|
|
20
20
|
AcpToolCallMeta,
|
|
21
21
|
} from './acp-process.ts'
|
|
22
|
-
import type {
|
|
22
|
+
import type {
|
|
23
|
+
BridgeCallRequest,
|
|
24
|
+
BridgeTool,
|
|
25
|
+
BridgeToolResult,
|
|
26
|
+
} from './mcp-bridge.ts'
|
|
23
27
|
import {
|
|
24
28
|
AGENT_TOOL_PREFIX,
|
|
25
29
|
CALL_TOOL_NAME,
|
|
@@ -67,8 +71,10 @@ export function classifyOutputLimitNotice(
|
|
|
67
71
|
): 'drop' | 'hold' | 'emit' {
|
|
68
72
|
const text = noticeText(raw)
|
|
69
73
|
if (text.length === 0) return raw.includes('⚠') ? 'hold' : 'emit'
|
|
74
|
+
// Terminal exhaustion (`Retries remaining: 0`) must surface immediately instead of being dropped or held.
|
|
75
|
+
if (/\bretries remaining:\s*0+$/i.test(text)) return 'emit'
|
|
70
76
|
if (/^there was a problem\b/.test(text)) {
|
|
71
|
-
if (/\bretries remaining:\s
|
|
77
|
+
if (/\bretries remaining:\s*[1-9]\d*$/.test(text)) return 'drop'
|
|
72
78
|
return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
|
|
73
79
|
}
|
|
74
80
|
if (PROBLEM_RETRY_PREFIX.startsWith(text) && text.startsWith('there was'))
|
|
@@ -78,7 +84,7 @@ export function classifyOutputLimitNotice(
|
|
|
78
84
|
if (retry.length > 0 && !/^retries remaining:\s*\d*$/i.test(retry))
|
|
79
85
|
return 'emit'
|
|
80
86
|
if (stripped.length === 0) {
|
|
81
|
-
if (/^retries remaining:\s
|
|
87
|
+
if (/^retries remaining:\s*[1-9]\d*$/i.test(text)) return 'drop'
|
|
82
88
|
return /^retries remaining:\s*$/i.test(text) ? 'hold' : 'emit'
|
|
83
89
|
}
|
|
84
90
|
const full = `${OUTPUT_LIMIT_HEAD} ${OUTPUT_LIMIT_TAIL}`
|
|
@@ -89,8 +95,11 @@ export function classifyOutputLimitNotice(
|
|
|
89
95
|
stripped === STREAM_INTERRUPTED ||
|
|
90
96
|
stripped === EMPTY_MODEL_OUTPUT ||
|
|
91
97
|
stripped === EMPTY_MODEL_OUTPUT_BODY
|
|
92
|
-
)
|
|
93
|
-
|
|
98
|
+
) {
|
|
99
|
+
if (retry.length === 0 || /^retries remaining:\s*[1-9]\d*$/i.test(retry))
|
|
100
|
+
return 'drop'
|
|
101
|
+
return /^retries remaining:\s*$/i.test(retry) ? 'hold' : 'emit'
|
|
102
|
+
}
|
|
94
103
|
if (full.startsWith(stripped) && stripped.startsWith('your previous'))
|
|
95
104
|
return 'hold'
|
|
96
105
|
if (
|
|
@@ -212,8 +221,12 @@ export class AcpTurn {
|
|
|
212
221
|
estimatedContextUsed?: number
|
|
213
222
|
/** Lower `gen_metadata.idx` bound owned by the active turn segment, or `null` when unobservable. */
|
|
214
223
|
metaFloorIdx: number | null = 0
|
|
224
|
+
/** Highest `steps.idx` already persisted before the active prompt segment started, or `null` when unobservable. */
|
|
225
|
+
lastStepIdx: number | null = -1
|
|
215
226
|
/** Per-call relay lifecycle: waiting (gating `relayBuffer`) -> unawaited -> notified. */
|
|
216
227
|
private readonly relays = new Map<string, RelayEntry>()
|
|
228
|
+
/** Per-call MCP delivery ownership: absent (idle), waiting (active MCP handler), or delivered (committed). */
|
|
229
|
+
private readonly callDelivery = new Map<string, 'waiting' | 'delivered'>()
|
|
217
230
|
/** Tool deltas and steering text deferred until an active MCP call returns a real result. */
|
|
218
231
|
private readonly pendingSuffix: string[] = []
|
|
219
232
|
/** Bounded output buffered while one or more calls are relayed. */
|
|
@@ -246,7 +259,6 @@ export class AcpTurn {
|
|
|
246
259
|
bindPrompt(
|
|
247
260
|
promise: Promise<AcpPromptResult>,
|
|
248
261
|
options?: {
|
|
249
|
-
onSettled?: () => void
|
|
250
262
|
mapError?: (error: unknown) => Error
|
|
251
263
|
},
|
|
252
264
|
): void {
|
|
@@ -254,12 +266,10 @@ export class AcpTurn {
|
|
|
254
266
|
this.promptSettled = promise.then(
|
|
255
267
|
(result) => {
|
|
256
268
|
this.promptActive = false
|
|
257
|
-
options?.onSettled?.()
|
|
258
269
|
this.events.push({ kind: 'done', result })
|
|
259
270
|
},
|
|
260
271
|
(error: unknown) => {
|
|
261
272
|
this.promptActive = false
|
|
262
|
-
options?.onSettled?.()
|
|
263
273
|
this.fail(
|
|
264
274
|
options?.mapError !== undefined
|
|
265
275
|
? options.mapError(error)
|
|
@@ -299,8 +309,9 @@ export class AcpTurn {
|
|
|
299
309
|
args: Record<string, unknown>,
|
|
300
310
|
relayAfterMs: number,
|
|
301
311
|
signal: AbortSignal,
|
|
312
|
+
commit?: BridgeCallRequest['commit'],
|
|
302
313
|
): Promise<BridgeToolResult> {
|
|
303
|
-
return this.awaitCall(this.park(name, args), relayAfterMs, signal)
|
|
314
|
+
return this.awaitCall(this.park(name, args), relayAfterMs, signal, commit)
|
|
304
315
|
}
|
|
305
316
|
|
|
306
317
|
/** Resume waiting on a previously parked call via `pi_await_result`, or return undefined if unknown. */
|
|
@@ -308,11 +319,40 @@ export class AcpTurn {
|
|
|
308
319
|
callId: string,
|
|
309
320
|
relayAfterMs: number,
|
|
310
321
|
signal: AbortSignal,
|
|
322
|
+
commit?: BridgeCallRequest['commit'],
|
|
311
323
|
): Promise<BridgeToolResult> | undefined {
|
|
312
324
|
const call = this.calls.get(callId)
|
|
313
325
|
if (call === undefined) return undefined
|
|
326
|
+
const status = this.callDelivery.get(callId)
|
|
327
|
+
if (status === 'delivered') {
|
|
328
|
+
return Promise.resolve({
|
|
329
|
+
content: [
|
|
330
|
+
{
|
|
331
|
+
type: 'text',
|
|
332
|
+
text: `Tool call ${callId} result was already delivered.`,
|
|
333
|
+
},
|
|
334
|
+
],
|
|
335
|
+
})
|
|
336
|
+
}
|
|
337
|
+
if (status === 'waiting') {
|
|
338
|
+
return Promise.resolve({
|
|
339
|
+
content: [
|
|
340
|
+
{
|
|
341
|
+
type: 'text',
|
|
342
|
+
text: `Tool call ${callId} is already being awaited.`,
|
|
343
|
+
},
|
|
344
|
+
],
|
|
345
|
+
isError: true,
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
if (signal.aborted) {
|
|
349
|
+
return Promise.resolve({
|
|
350
|
+
content: [{ type: 'text', text: 'The tool call was cancelled.' }],
|
|
351
|
+
isError: true,
|
|
352
|
+
})
|
|
353
|
+
}
|
|
314
354
|
this.resumeRelay(callId)
|
|
315
|
-
return this.awaitCall(call, relayAfterMs, signal)
|
|
355
|
+
return this.awaitCall(call, relayAfterMs, signal, commit)
|
|
316
356
|
}
|
|
317
357
|
|
|
318
358
|
get isRelaying(): boolean {
|
|
@@ -400,7 +440,9 @@ export class AcpTurn {
|
|
|
400
440
|
call: ParkedCall,
|
|
401
441
|
relayAfterMs: number,
|
|
402
442
|
signal: AbortSignal,
|
|
443
|
+
commit?: BridgeCallRequest['commit'],
|
|
403
444
|
): Promise<BridgeToolResult> {
|
|
445
|
+
this.callDelivery.set(call.id, 'waiting')
|
|
404
446
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
405
447
|
const relay = new Promise<'relay'>((resolve) => {
|
|
406
448
|
timer = setTimeout(() => resolve('relay'), relayAfterMs)
|
|
@@ -415,18 +457,24 @@ export class AcpTurn {
|
|
|
415
457
|
})
|
|
416
458
|
try {
|
|
417
459
|
const outcome = await Promise.race([call.result.promise, relay, aborted])
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
}
|
|
422
|
-
if (outcome === 'aborted') {
|
|
460
|
+
// Check signal.aborted first to close the same-tick Promise.race tie where
|
|
461
|
+
// call.result.promise precedes aborted.
|
|
462
|
+
if (signal.aborted || outcome === 'aborted') {
|
|
423
463
|
return {
|
|
424
464
|
content: [{ type: 'text', text: 'The tool call was cancelled.' }],
|
|
425
465
|
isError: true,
|
|
426
466
|
}
|
|
427
467
|
}
|
|
428
|
-
|
|
468
|
+
if (outcome === 'relay') {
|
|
469
|
+
this.markRelayed(call.id)
|
|
470
|
+
return relayNotice(call)
|
|
471
|
+
}
|
|
472
|
+
return commit !== undefined
|
|
473
|
+
? commit(() => this.deliverCallResult(call.id, outcome))
|
|
474
|
+
: this.deliverCallResult(call.id, outcome)
|
|
429
475
|
} finally {
|
|
476
|
+
if (this.callDelivery.get(call.id) === 'waiting')
|
|
477
|
+
this.callDelivery.delete(call.id)
|
|
430
478
|
if (timer !== undefined) clearTimeout(timer)
|
|
431
479
|
if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
|
|
432
480
|
}
|
|
@@ -448,6 +496,7 @@ export class AcpTurn {
|
|
|
448
496
|
callId: string,
|
|
449
497
|
result: BridgeToolResult,
|
|
450
498
|
): BridgeToolResult {
|
|
499
|
+
this.callDelivery.set(callId, 'delivered')
|
|
451
500
|
this.relays.delete(callId)
|
|
452
501
|
this.releaseRelayWait()
|
|
453
502
|
const notes: string[] = []
|
|
@@ -905,6 +954,7 @@ async function* stepChunks(
|
|
|
905
954
|
const stop = event.result.stopReason
|
|
906
955
|
if (
|
|
907
956
|
stop === 'max_tokens' &&
|
|
957
|
+
!turn.isRelaying &&
|
|
908
958
|
turn.continuations < host.maxContinuations
|
|
909
959
|
) {
|
|
910
960
|
turn.continuations++
|
package/src/format.ts
CHANGED
|
@@ -33,16 +33,28 @@ export interface QuotaModelRef {
|
|
|
33
33
|
const EXPLICIT_MEMBERS_PREFIX = /^\s*models within this group:\s*/i
|
|
34
34
|
const CLAUSE_SPLIT = /[,;\n/|&+]+|\b(?:and|or)\b/i
|
|
35
35
|
const ID_DATE_SUFFIX = /[-_](?:20\d{2}[-_]\d{2}[-_]\d{2}|20\d{6})$/i
|
|
36
|
-
|
|
36
|
+
type EffortQualifier = Effort | 'extra-low'
|
|
37
|
+
|
|
38
|
+
// Keep longest qualifiers first (`extra[-_]low` before `low`) so compound suffixes match whole.
|
|
39
|
+
const EFFORT_QUALIFIER_PATTERN = [
|
|
40
|
+
'extra[-_]low',
|
|
41
|
+
...[...EFFORTS].sort((a, b) => b.length - a.length),
|
|
42
|
+
].join('|')
|
|
37
43
|
// Effort or thinking-mode suffixes in model IDs (`-thinking`) and `/usage` labels (`(Thinking)`).
|
|
38
44
|
const ID_QUALIFIER_SUFFIX = new RegExp(
|
|
39
|
-
`[-_](?:(${
|
|
45
|
+
`[-_](?:(${EFFORT_QUALIFIER_PATTERN})(?:[-_]effort)?|(thinking))$`,
|
|
40
46
|
'i',
|
|
41
47
|
)
|
|
42
48
|
const GROUP_QUALIFIER_SUFFIX = new RegExp(
|
|
43
|
-
`\\s*\\((${
|
|
49
|
+
`\\s*\\((${EFFORT_QUALIFIER_PATTERN}|thinking)\\)(?=\\s*(?:models?|groups?)?[\\s.!?)]*$)`,
|
|
44
50
|
'i',
|
|
45
51
|
)
|
|
52
|
+
|
|
53
|
+
function parseEffortQualifier(raw: string): EffortQualifier | undefined {
|
|
54
|
+
const normalized = raw.toLowerCase().replace(/_/g, '-')
|
|
55
|
+
if (normalized === 'extra-low') return 'extra-low'
|
|
56
|
+
return asEffort(normalized)
|
|
57
|
+
}
|
|
46
58
|
const SPECIFIER = /^\d+(?:\.\d+)*b?$/
|
|
47
59
|
const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
|
|
48
60
|
const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
|
|
@@ -75,7 +87,7 @@ interface ParsedPhrase {
|
|
|
75
87
|
readonly head: string | undefined
|
|
76
88
|
readonly words: readonly string[]
|
|
77
89
|
readonly specs: readonly string[]
|
|
78
|
-
readonly effort:
|
|
90
|
+
readonly effort: EffortQualifier | undefined
|
|
79
91
|
readonly thinking: boolean
|
|
80
92
|
readonly effortConflict: boolean
|
|
81
93
|
readonly tokenCount: number
|
|
@@ -84,7 +96,7 @@ interface ParsedPhrase {
|
|
|
84
96
|
|
|
85
97
|
function buildPhrase(
|
|
86
98
|
tokens: readonly string[],
|
|
87
|
-
effort?:
|
|
99
|
+
effort?: EffortQualifier,
|
|
88
100
|
thinking = false,
|
|
89
101
|
effortConflict = false,
|
|
90
102
|
): ParsedPhrase {
|
|
@@ -108,9 +120,21 @@ function buildPhrase(
|
|
|
108
120
|
|
|
109
121
|
function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
110
122
|
let text = raw.trim().replace(/[.!?]+$/, '')
|
|
111
|
-
let effort:
|
|
123
|
+
let effort: EffortQualifier | undefined
|
|
112
124
|
let thinking = false
|
|
113
125
|
let effortConflict = false
|
|
126
|
+
const applyQualifier = (rawQualifier: string) => {
|
|
127
|
+
const token = rawQualifier.toLowerCase()
|
|
128
|
+
if (token === 'thinking') {
|
|
129
|
+
thinking = true
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
const nextEffort = parseEffortQualifier(token)
|
|
133
|
+
if (nextEffort) {
|
|
134
|
+
if (effort && effort !== nextEffort) effortConflict = true
|
|
135
|
+
effort = nextEffort
|
|
136
|
+
}
|
|
137
|
+
}
|
|
114
138
|
while (text.length > 0) {
|
|
115
139
|
const withoutDate = text.replace(ID_DATE_SUFFIX, '')
|
|
116
140
|
if (withoutDate !== text) {
|
|
@@ -119,13 +143,7 @@ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
|
119
143
|
}
|
|
120
144
|
const groupQual = GROUP_QUALIFIER_SUFFIX.exec(text)
|
|
121
145
|
if (groupQual) {
|
|
122
|
-
|
|
123
|
-
if (nextEffort) {
|
|
124
|
-
if (effort && effort !== nextEffort) effortConflict = true
|
|
125
|
-
effort = nextEffort
|
|
126
|
-
} else {
|
|
127
|
-
thinking = true
|
|
128
|
-
}
|
|
146
|
+
applyQualifier(groupQual[1]!)
|
|
129
147
|
text =
|
|
130
148
|
text.slice(0, groupQual.index) +
|
|
131
149
|
text.slice(groupQual.index + groupQual[0].length)
|
|
@@ -133,13 +151,7 @@ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
|
133
151
|
}
|
|
134
152
|
const idQual = ID_QUALIFIER_SUFFIX.exec(text)
|
|
135
153
|
if (idQual) {
|
|
136
|
-
|
|
137
|
-
if (nextEffort) {
|
|
138
|
-
if (effort && effort !== nextEffort) effortConflict = true
|
|
139
|
-
effort = nextEffort
|
|
140
|
-
} else {
|
|
141
|
-
thinking = true
|
|
142
|
-
}
|
|
154
|
+
applyQualifier((idQual[1] ?? idQual[2])!)
|
|
143
155
|
text = text.slice(0, idQual.index)
|
|
144
156
|
continue
|
|
145
157
|
}
|
|
@@ -371,6 +383,38 @@ export function formatQuotaStatus(
|
|
|
371
383
|
return `AGY ${Math.round(displayFraction(quota.fraction, display) * 100)}%`
|
|
372
384
|
}
|
|
373
385
|
|
|
386
|
+
const WINDOW_DURATION = /^(\d+)([mhdw])$/
|
|
387
|
+
const WINDOW_UNIT_SECONDS: Record<string, number> = {
|
|
388
|
+
m: 60,
|
|
389
|
+
h: 3600,
|
|
390
|
+
d: 86400,
|
|
391
|
+
w: 7 * 86400,
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function windowSeconds(window: string): number | undefined {
|
|
395
|
+
const normalized = window.trim().toLowerCase()
|
|
396
|
+
if (normalized === 'weekly') return 7 * 86400
|
|
397
|
+
if (normalized === 'daily') return 86400
|
|
398
|
+
const match = WINDOW_DURATION.exec(normalized)
|
|
399
|
+
if (!match) return undefined
|
|
400
|
+
const count = Number(match[1])
|
|
401
|
+
const unit = WINDOW_UNIT_SECONDS[match[2]!]
|
|
402
|
+
return count > 0 && unit !== undefined ? count * unit : undefined
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function isUntouchedRollingReset(
|
|
406
|
+
bucket: QuotaBucket,
|
|
407
|
+
fraction: number | undefined,
|
|
408
|
+
now: number,
|
|
409
|
+
): boolean {
|
|
410
|
+
if (fraction === undefined || fraction < 1) return false
|
|
411
|
+
const resetMs = Date.parse(bucket.resetTime)
|
|
412
|
+
if (!Number.isFinite(resetMs)) return false
|
|
413
|
+
const windowSecs = windowSeconds(bucket.window)
|
|
414
|
+
if (windowSecs === undefined) return false
|
|
415
|
+
return Math.abs((resetMs - now) / 1000 - windowSecs) <= 60
|
|
416
|
+
}
|
|
417
|
+
|
|
374
418
|
function resetCountdown(resetTime: string, now: number): string {
|
|
375
419
|
const reset = Date.parse(resetTime)
|
|
376
420
|
if (!Number.isFinite(reset)) return 'reset time unavailable'
|
|
@@ -423,9 +467,10 @@ export function formatQuota(
|
|
|
423
467
|
bucket.id ||
|
|
424
468
|
'quota'
|
|
425
469
|
).padEnd(7)
|
|
426
|
-
const reset =
|
|
427
|
-
|
|
428
|
-
|
|
470
|
+
const reset =
|
|
471
|
+
bucket.resetTime && !isUntouchedRollingReset(bucket, fraction, now)
|
|
472
|
+
? ` · ${resetCountdown(bucket.resetTime, now)}`
|
|
473
|
+
: ''
|
|
429
474
|
lines.push(` ${label} [${bar}] ${percent.padStart(4)}${reset}`)
|
|
430
475
|
if (fraction !== undefined) {
|
|
431
476
|
if (fraction <= 0.05) level = 'error'
|