pi-agy-acp 0.2.3 → 0.2.5

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/src/runtime.ts CHANGED
@@ -23,12 +23,15 @@ import {
23
23
  type AcpPermissionOutcome,
24
24
  type AcpPermissionRequest,
25
25
  type AcpPromptResult,
26
+ type AcpSessionUpdate,
26
27
  type AcpSpawner,
27
28
  } from './acp-process.ts'
28
29
  import {
30
+ findConfigOption,
29
31
  flattenConfigOptions,
30
32
  ModelCatalog,
31
33
  nearestEffort,
34
+ offeredEffortsFrom,
32
35
  } from './catalog.ts'
33
36
  import { asEffort, defaults, type Config, type Effort } from './config.ts'
34
37
  import {
@@ -48,6 +51,7 @@ import {
48
51
  bridgeSystemPrompt,
49
52
  inputPrompt,
50
53
  MCP_SERVER_NAME,
54
+ renderSessionInstructions,
51
55
  renderTranscript,
52
56
  replayPrompt,
53
57
  splitSystem,
@@ -177,6 +181,13 @@ interface Conversation {
177
181
  effort: Effort | undefined
178
182
  }
179
183
 
184
+ interface ResumableSession {
185
+ readonly sessionId: string
186
+ readonly systemHash: string
187
+ readonly knownIds: readonly string[]
188
+ readonly issuedIds: ReadonlySet<string>
189
+ }
190
+
180
191
  interface PromptPlan {
181
192
  rebuild: boolean
182
193
  history: readonly RequestMessage[]
@@ -200,6 +211,8 @@ export class AntigravityRuntime {
200
211
  private tierDiscovery: Promise<void> | undefined
201
212
  private warmupPromise: Promise<void> | undefined
202
213
  private readonly conversations = new Map<string, Conversation>()
214
+ /** Dormant idle-swept sessions eligible for `session/resume` on next request. */
215
+ private readonly resumableSessions = new Map<string, ResumableSession>()
203
216
  private readonly tenants = new Map<string, Conversation>()
204
217
  private readonly mutex = new KeyedMutex()
205
218
  /** Serializes capacity checks and session creation so concurrent requests cannot overshoot maxLiveSessions. */
@@ -274,6 +287,7 @@ export class AntigravityRuntime {
274
287
  ) {
275
288
  this.preflight = undefined
276
289
  this.preflightFingerprint = undefined
290
+ this.clearResumableSessions()
277
291
  }
278
292
  if (
279
293
  this.process?.alive &&
@@ -297,6 +311,7 @@ export class AntigravityRuntime {
297
311
  .map((conv) => ({ conv, sessionId: conv.sessionId }))
298
312
  this.detachProcess(stale)
299
313
  void this.bridge.close()
314
+ this.clearResumableSessions()
300
315
  for (const { conv, sessionId } of staleSessions) {
301
316
  if (sessionId !== undefined) {
302
317
  removeSessionArtifacts(this.home, sessionId)
@@ -586,16 +601,29 @@ export class AntigravityRuntime {
586
601
 
587
602
  /** Close conversation sessions while retaining the process and discovery/quota caches. */
588
603
  async resetConversations(): Promise<void> {
589
- this.assertActive()
604
+ if (this.lifecycle !== 'active' || this.shutdown.signal.aborted) return
590
605
  this.processIdleMs = 0
606
+ this.clearResumableSessions()
591
607
  const conversations = [...this.conversations.values()]
592
608
  for (const conv of conversations)
593
609
  this.dropTurn(conv, 'The Pi session changed.')
594
610
  await Promise.all(
595
611
  conversations.map(async (conv) => {
596
- const release = await this.mutex.acquire(conv.key, this.shutdown.signal)
612
+ let release: () => void
613
+ try {
614
+ release = await this.mutex.acquire(conv.key, this.shutdown.signal)
615
+ } catch (error) {
616
+ if (this.lifecycle !== 'active' || this.shutdown.signal.aborted)
617
+ return
618
+ throw error
619
+ }
597
620
  try {
598
- if (this.conversations.get(conv.key) !== conv) return
621
+ if (
622
+ this.lifecycle !== 'active' ||
623
+ this.shutdown.signal.aborted ||
624
+ this.conversations.get(conv.key) !== conv
625
+ )
626
+ return
599
627
  await this.resetSession(conv)
600
628
  this.conversations.delete(conv.key)
601
629
  } finally {
@@ -613,6 +641,7 @@ export class AntigravityRuntime {
613
641
  new LlmError('Antigravity provider was disposed', 'TRANSPORT'),
614
642
  )
615
643
  this.stopSweeper()
644
+ this.clearResumableSessions()
616
645
  for (const conv of this.conversations.values()) {
617
646
  conv.turn?.abandon('The harness provider was unloaded.')
618
647
  this.clearSession(conv)
@@ -739,14 +768,45 @@ export class AntigravityRuntime {
739
768
  this.dropTurn(conv, 'Superseded by a newer request.')
740
769
  }
741
770
 
742
- const plan = this.plan(conv, split.system, split.messages)
743
- if (plan.rebuild) await this.resetSession(conv)
744
- this.assertOwner(proc, conv)
771
+ let plan = this.plan(conv, split.system, split.messages)
745
772
  let supplementalTools: readonly BridgeTool[] = []
773
+ let resumed = false
746
774
  if (conv.sessionId === undefined) {
747
- conv.systemHash = digest(split.system)
748
- supplementalTools = await this.openSession(conv, tools, proc)
749
- effort = this.effectiveEffort(options.model, requestedEffort)
775
+ const resumable = this.resumableSessions.get(conv.key)
776
+ if (resumable !== undefined) {
777
+ this.resumableSessions.delete(conv.key)
778
+ const resumeInput = this.deltaInput(
779
+ resumable,
780
+ split.system,
781
+ split.messages,
782
+ )
783
+ if (resumeInput === undefined) {
784
+ // History or system prompt diverged while dormant: discard persisted session DB.
785
+ removeSessionArtifacts(this.home, resumable.sessionId)
786
+ } else {
787
+ const resumedTools = await this.resumeSession(
788
+ conv,
789
+ resumable,
790
+ tools,
791
+ proc,
792
+ )
793
+ if (resumedTools !== undefined) {
794
+ supplementalTools = resumedTools
795
+ plan = { rebuild: false, history: [], input: resumeInput }
796
+ resumed = true
797
+ effort = this.effectiveEffort(options.model, requestedEffort)
798
+ }
799
+ }
800
+ }
801
+ }
802
+ if (!resumed) {
803
+ if (plan.rebuild) await this.resetSession(conv)
804
+ this.assertOwner(proc, conv)
805
+ if (conv.sessionId === undefined) {
806
+ conv.systemHash = digest(split.system)
807
+ supplementalTools = await this.openSession(conv, tools, proc)
808
+ effort = this.effectiveEffort(options.model, requestedEffort)
809
+ }
750
810
  }
751
811
  this.assertOwner(proc, conv, conv.sessionId)
752
812
  effort = await this.select(conv, proc, options.model, effort)
@@ -759,6 +819,14 @@ export class AntigravityRuntime {
759
819
  })
760
820
  } else {
761
821
  blocks = inputPrompt(plan.input)
822
+ if (supplementalTools.length > 0) {
823
+ const toolInstructions = renderSessionInstructions(
824
+ '',
825
+ supplementalTools,
826
+ )
827
+ if (toolInstructions.length > 0)
828
+ blocks.unshift({ type: 'text', text: toolInstructions })
829
+ }
762
830
  const toolDelta = consumeToolDelta(conv, tools)
763
831
  if (toolDelta.length > 0)
764
832
  blocks.unshift({ type: 'text', text: `${toolDelta}\n\n` })
@@ -951,7 +1019,10 @@ export class AntigravityRuntime {
951
1019
  this.reconcileBinaryFingerprint()
952
1020
  const warn = (message: string) => this.host.log.warn(message)
953
1021
  if (this.preflight !== undefined) {
954
- prepareHome(this.home, undefined, undefined, warn)
1022
+ // Preserve retained session DBs across idle front restarts when dormant sessions exist.
1023
+ prepareHome(this.home, undefined, undefined, warn, {
1024
+ cleanArtifacts: this.resumableSessions.size === 0,
1025
+ })
955
1026
  return Promise.resolve(this.preflight)
956
1027
  }
957
1028
  this.preflightPromise ??= (async () => {
@@ -961,7 +1032,9 @@ export class AntigravityRuntime {
961
1032
  const version = await readVersion(binary, this.host.runCommand)
962
1033
  this.assertActive()
963
1034
  assertSupportedAgyVersion(version, binary)
964
- const workspace = prepareHome(this.home, undefined, undefined, warn)
1035
+ const workspace = prepareHome(this.home, undefined, undefined, warn, {
1036
+ cleanArtifacts: true,
1037
+ })
965
1038
  const result: PreflightResult = {
966
1039
  binary,
967
1040
  version,
@@ -1004,10 +1077,40 @@ export class AntigravityRuntime {
1004
1077
  }
1005
1078
  }
1006
1079
 
1007
- private async openSession(
1080
+ private openSession(
1081
+ conv: Conversation,
1082
+ tools: readonly BridgeTool[],
1083
+ proc: AcpProcess,
1084
+ ): Promise<readonly BridgeTool[]> {
1085
+ return this.establishSession(conv, tools, proc)
1086
+ }
1087
+
1088
+ private async resumeSession(
1089
+ conv: Conversation,
1090
+ resumable: ResumableSession,
1091
+ tools: readonly BridgeTool[],
1092
+ proc: AcpProcess,
1093
+ ): Promise<readonly BridgeTool[] | undefined> {
1094
+ try {
1095
+ return await this.establishSession(conv, tools, proc, resumable)
1096
+ } catch (error) {
1097
+ if (error instanceof JsonRpcRemoteError && this.owns(proc, conv)) {
1098
+ this.host.log.warn(
1099
+ `antigravity-acp: session/resume failed for ${resumable.sessionId} (${error.message}); falling back to session/new`,
1100
+ )
1101
+ this.clearSession(conv)
1102
+ removeSessionArtifacts(this.home, resumable.sessionId)
1103
+ return undefined
1104
+ }
1105
+ throw mapError(error)
1106
+ }
1107
+ }
1108
+
1109
+ private async establishSession(
1008
1110
  conv: Conversation,
1009
1111
  tools: readonly BridgeTool[],
1010
1112
  proc: AcpProcess,
1113
+ resumable?: ResumableSession,
1011
1114
  ): Promise<readonly BridgeTool[]> {
1012
1115
  this.assertOwner(proc, conv)
1013
1116
  try {
@@ -1038,68 +1141,68 @@ export class AntigravityRuntime {
1038
1141
  conv.tenantKey = tenantKey
1039
1142
  conv.tenantSecret = tenantSecret
1040
1143
  this.tenants.set(tenantKey, conv)
1041
- try {
1042
- const result = await proc.newSession(
1043
- {
1044
- cwd: this.preflight?.workspace ?? this.home,
1045
- mcpServers,
1046
- _meta: {
1047
- antigravity: {
1048
- systemPrompt: {
1049
- append: bridgeSystemPrompt(),
1050
- },
1051
- },
1144
+ const params: Record<string, unknown> = {
1145
+ ...(resumable !== undefined ? { sessionId: resumable.sessionId } : {}),
1146
+ cwd: this.preflight?.workspace ?? this.home,
1147
+ mcpServers,
1148
+ _meta: {
1149
+ antigravity: {
1150
+ systemPrompt: {
1151
+ append: bridgeSystemPrompt(),
1052
1152
  },
1053
1153
  },
1054
- {
1055
- onUpdate: (update) => {
1056
- if (
1057
- !this.owns(proc, conv) ||
1058
- conv.tenantKey !== tenantKey
1059
- ) return
1060
- if (
1061
- update.sessionUpdate === 'config_option_update' &&
1062
- Array.isArray(update.configOptions)
1063
- ) {
1064
- conv.configOptions = update.configOptions
1065
- if (this.catalog.observe(update.configOptions))
1066
- this.host.onModelsChanged()
1067
- }
1068
- if (recordReportedToolCall(conv, update) === 'conflict') {
1069
- this.host.log.warn(
1070
- `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
1071
- )
1072
- }
1073
- conv.turn?.onUpdate(update)
1074
- if (update.sessionUpdate === 'usage_update') {
1075
- const hasCachedContextWindow =
1076
- conv.model !== undefined &&
1077
- this.catalog.contextWindowFor(conv.model) !== undefined
1078
- const hasPositiveUsed =
1079
- typeof update.used === 'number' &&
1080
- Number.isFinite(update.used) &&
1081
- update.used > 0
1082
- if (!(hasCachedContextWindow && hasPositiveUsed)) {
1083
- this.harvestSessionTurnData(
1084
- conv,
1085
- conv.sessionId,
1086
- conv.model,
1087
- conv.metaFloorIdx,
1088
- {
1089
- turn: conv.turn,
1090
- ifChangedSince: conv.lastDbStamp,
1091
- },
1092
- )
1093
- }
1094
- }
1095
- },
1096
- onPermission: (request) => this.owns(proc, conv) && conv.tenantKey === tenantKey
1097
- ? this.answerPermission(conv, request)
1098
- : { outcome: 'cancelled' },
1099
- },
1100
- 120_000,
1101
- )
1102
- // A buffered session/new reply can resolve after its process has exited.
1154
+ },
1155
+ }
1156
+ const listener = {
1157
+ onUpdate: (update: AcpSessionUpdate) => {
1158
+ if (!this.owns(proc, conv) || conv.tenantKey !== tenantKey) return
1159
+ if (
1160
+ update.sessionUpdate === 'config_option_update' &&
1161
+ Array.isArray(update.configOptions)
1162
+ ) {
1163
+ conv.configOptions = update.configOptions
1164
+ if (this.catalog.observe(update.configOptions))
1165
+ this.host.onModelsChanged()
1166
+ }
1167
+ if (recordReportedToolCall(conv, update) === 'conflict') {
1168
+ this.host.log.warn(
1169
+ `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
1170
+ )
1171
+ }
1172
+ conv.turn?.onUpdate(update)
1173
+ if (update.sessionUpdate === 'usage_update') {
1174
+ const hasCachedContextWindow =
1175
+ conv.model !== undefined &&
1176
+ this.catalog.contextWindowFor(conv.model) !== undefined
1177
+ const hasPositiveUsed =
1178
+ typeof update.used === 'number' &&
1179
+ Number.isFinite(update.used) &&
1180
+ update.used > 0
1181
+ if (!(hasCachedContextWindow && hasPositiveUsed)) {
1182
+ this.harvestSessionTurnData(
1183
+ conv,
1184
+ conv.sessionId,
1185
+ conv.model,
1186
+ conv.metaFloorIdx,
1187
+ {
1188
+ turn: conv.turn,
1189
+ ifChangedSince: conv.lastDbStamp,
1190
+ },
1191
+ )
1192
+ }
1193
+ }
1194
+ },
1195
+ onPermission: (request: AcpPermissionRequest) =>
1196
+ this.owns(proc, conv) && conv.tenantKey === tenantKey
1197
+ ? this.answerPermission(conv, request)
1198
+ : ({ outcome: 'cancelled' } as const),
1199
+ }
1200
+ try {
1201
+ const result =
1202
+ resumable !== undefined
1203
+ ? await proc.resumeSession(params, listener, 120_000)
1204
+ : await proc.newSession(params, listener, 120_000)
1205
+ // A buffered session reply can resolve after its process has exited.
1103
1206
  if (!this.owns(proc, conv)) {
1104
1207
  await this.closeAndCleanSession(proc, result.sessionId)
1105
1208
  this.assertActive()
@@ -1112,9 +1215,14 @@ export class AntigravityRuntime {
1112
1215
  conv.metaFloorIdx = 0
1113
1216
  conv.lastDbStamp = undefined
1114
1217
  conv.effort = undefined
1115
-
1116
1218
  conv.dirty = false
1117
- conv.issuedIds.clear()
1219
+ if (resumable !== undefined) {
1220
+ conv.systemHash = resumable.systemHash
1221
+ conv.knownIds = [...resumable.knownIds]
1222
+ conv.issuedIds = new Set(resumable.issuedIds)
1223
+ } else {
1224
+ conv.issuedIds.clear()
1225
+ }
1118
1226
  if (
1119
1227
  this.catalog.observe(
1120
1228
  result.configOptions,
@@ -1126,6 +1234,7 @@ export class AntigravityRuntime {
1126
1234
  return supplementalTools
1127
1235
  } catch (error) {
1128
1236
  this.clearSession(conv)
1237
+ if (resumable !== undefined) throw error
1129
1238
  throw mapError(error)
1130
1239
  }
1131
1240
  }
@@ -1165,7 +1274,14 @@ export class AntigravityRuntime {
1165
1274
  request: AcpPermissionRequest,
1166
1275
  ): AcpPermissionOutcome {
1167
1276
  const pick = (kind: string): AcpPermissionOutcome | undefined => {
1168
- const option = request.options.find((o) => o.kind === kind)
1277
+ if (!Array.isArray(request.options)) return undefined
1278
+ const option = request.options.find(
1279
+ (o) =>
1280
+ o !== null &&
1281
+ typeof o === 'object' &&
1282
+ o.kind === kind &&
1283
+ typeof o.optionId === 'string',
1284
+ )
1169
1285
  return option === undefined
1170
1286
  ? undefined
1171
1287
  : { outcome: 'selected', optionId: option.optionId }
@@ -1249,9 +1365,7 @@ export class AntigravityRuntime {
1249
1365
  ): Promise<Effort> {
1250
1366
  const sessionId = conv.sessionId as string
1251
1367
  this.assertOwner(proc, conv, sessionId)
1252
- const modelOption = conv.configOptions.find(
1253
- (o) => o.id === 'model' || o.category === 'model',
1254
- )
1368
+ const modelOption = findConfigOption(conv.configOptions, 'model')
1255
1369
  const modelValues =
1256
1370
  modelOption?.options !== undefined
1257
1371
  ? flattenConfigOptions(modelOption.options)
@@ -1290,15 +1404,8 @@ export class AntigravityRuntime {
1290
1404
  conv.lastDbStamp = undefined
1291
1405
  }
1292
1406
  conv.model = model
1293
- const levelOption = conv.configOptions.find(
1294
- (o) => o.id === 'thought_level' || o.category === 'thought_level',
1295
- )
1296
- const offeredEfforts =
1297
- levelOption?.options !== undefined
1298
- ? flattenConfigOptions(levelOption.options)
1299
- .map((o) => asEffort(o.value))
1300
- .filter((v): v is Effort => v !== undefined)
1301
- : undefined
1407
+ const levelOption = findConfigOption(conv.configOptions, 'thought_level')
1408
+ const offeredEfforts = offeredEffortsFrom(levelOption)
1302
1409
  const targetEffort =
1303
1410
  offeredEfforts !== undefined && offeredEfforts.length > 0
1304
1411
  ? offeredEfforts.includes(effort)
@@ -1350,25 +1457,10 @@ export class AntigravityRuntime {
1350
1457
  system: string,
1351
1458
  messages: readonly RequestMessage[],
1352
1459
  ): PromptPlan {
1353
- const reusable =
1354
- conv.sessionId !== undefined &&
1355
- !conv.dirty &&
1356
- this.historyPrefixIntact(conv, system, messages)
1357
- if (reusable) {
1358
- const known = conv.knownIds as string[]
1359
- let rest = messages.slice(known.length)
1360
- let skip = 0
1361
- while (
1362
- skip < rest.length &&
1363
- this.isOwn(conv, rest[skip] as RequestMessage)
1364
- )
1365
- skip++
1366
- rest = rest.slice(skip)
1367
- if (
1368
- rest.length > 0 &&
1369
- rest.every((m) => m.role === 'user' || m.role === 'system')
1370
- ) {
1371
- return { rebuild: false, history: [], input: rest }
1460
+ if (conv.sessionId !== undefined && !conv.dirty) {
1461
+ const input = this.deltaInput(conv, system, messages)
1462
+ if (input !== undefined) {
1463
+ return { rebuild: false, history: [], input }
1372
1464
  }
1373
1465
  }
1374
1466
  let cut = messages.length
@@ -1384,43 +1476,106 @@ export class AntigravityRuntime {
1384
1476
  }
1385
1477
  }
1386
1478
 
1479
+ /**
1480
+ * Compute incremental user/system input after a session's known prefix and
1481
+ * own assistant/tool messages, or `undefined` if the history diverged.
1482
+ */
1483
+ private deltaInput(
1484
+ state: {
1485
+ systemHash: string | undefined
1486
+ knownIds: readonly string[] | undefined
1487
+ issuedIds: ReadonlySet<string>
1488
+ },
1489
+ system: string,
1490
+ messages: readonly RequestMessage[],
1491
+ ): readonly RequestMessage[] | undefined {
1492
+ if (!this.historyPrefixIntact(state, system, messages)) return undefined
1493
+ const known = state.knownIds as readonly string[]
1494
+ let rest = messages.slice(known.length)
1495
+ let skip = 0
1496
+ while (
1497
+ skip < rest.length &&
1498
+ this.isOwn(state.issuedIds, rest[skip] as RequestMessage)
1499
+ )
1500
+ skip++
1501
+ rest = rest.slice(skip)
1502
+ if (
1503
+ rest.length > 0 &&
1504
+ rest.every((m) => m.role === 'user' || m.role === 'system')
1505
+ ) {
1506
+ return rest
1507
+ }
1508
+ return undefined
1509
+ }
1510
+
1387
1511
  /**
1388
1512
  * Whether the live ACP session's context is still an exact prefix of the
1389
1513
  * request: the same system prompt and the same message ids in the same order.
1390
1514
  * A compaction checkpoint, a pruned/rewritten prefix, or a replaced system
1391
1515
  * prompt all make the session stale and force a rebuild.
1392
- * @param conv - conversation owning the ACP session.
1516
+ * @param state - conversation or dormant session owning the prefix metadata.
1393
1517
  * @param system - current Pi system prompt.
1394
1518
  * @param messages - full request history after leading system messages.
1395
1519
  * @returns true when only new messages were appended.
1396
1520
  */
1397
1521
  private historyPrefixIntact(
1398
- conv: Conversation,
1522
+ state: {
1523
+ systemHash: string | undefined
1524
+ knownIds: readonly string[] | undefined
1525
+ },
1399
1526
  system: string,
1400
1527
  messages: readonly RequestMessage[],
1401
1528
  ): boolean {
1402
1529
  // plan() has always required the same system digest for reuse; a changed
1403
1530
  // digest is a genuinely new prompt, while mid-conversation updates travel
1404
1531
  // as `system` messages inside `messages` (systemPromptUpdate: 'in-history').
1405
- if (conv.knownIds === undefined || conv.systemHash !== digest(system))
1532
+ if (state.knownIds === undefined || state.systemHash !== digest(system))
1406
1533
  return false
1407
- const known = conv.knownIds
1534
+ const known = state.knownIds
1408
1535
  return (
1409
1536
  known.length <= messages.length &&
1410
1537
  known.every((id, index) => messages[index]?.id === id)
1411
1538
  )
1412
1539
  }
1413
1540
 
1414
- private isOwn(conv: Conversation, message: RequestMessage): boolean {
1541
+ private isOwn(
1542
+ issuedIds: ReadonlySet<string>,
1543
+ message: RequestMessage,
1544
+ ): boolean {
1415
1545
  if (message.role === 'assistant')
1416
1546
  return (
1417
1547
  message.source.kind === 'model' &&
1418
1548
  message.source.provider === this.host.config.provider
1419
1549
  )
1420
- if (message.role === 'tool') return conv.issuedIds.has(message.toolCallId)
1550
+ if (message.role === 'tool') return issuedIds.has(message.toolCallId)
1421
1551
  return false
1422
1552
  }
1423
1553
 
1554
+ private parkResumableSession(key: string, entry: ResumableSession): void {
1555
+ this.dropResumableSession(key)
1556
+ this.resumableSessions.set(key, entry)
1557
+ const maxResumable = Math.max(1, this.host.config.maxLiveSessions) * 2
1558
+ while (this.resumableSessions.size > maxResumable) {
1559
+ const oldestKey = this.resumableSessions.keys().next().value
1560
+ if (oldestKey === undefined) break
1561
+ this.dropResumableSession(oldestKey)
1562
+ }
1563
+ }
1564
+
1565
+ private dropResumableSession(key: string): void {
1566
+ const existing = this.resumableSessions.get(key)
1567
+ if (existing === undefined) return
1568
+ this.resumableSessions.delete(key)
1569
+ removeSessionArtifacts(this.home, existing.sessionId)
1570
+ }
1571
+
1572
+ private clearResumableSessions(): void {
1573
+ for (const entry of this.resumableSessions.values()) {
1574
+ removeSessionArtifacts(this.home, entry.sessionId)
1575
+ }
1576
+ this.resumableSessions.clear()
1577
+ }
1578
+
1424
1579
  private async closeAndCleanSession(
1425
1580
  proc: AcpProcess,
1426
1581
  sessionId: string,
@@ -1432,7 +1587,38 @@ export class AntigravityRuntime {
1432
1587
  }
1433
1588
  }
1434
1589
 
1590
+ private async evictIdleSession(conv: Conversation): Promise<void> {
1591
+ this.harvestSessionTurnData(conv, conv.sessionId, conv.model, conv.metaFloorIdx, {
1592
+ ifChangedSince: conv.lastDbStamp,
1593
+ })
1594
+ const canPark =
1595
+ conv.sessionId !== undefined &&
1596
+ conv.systemHash !== undefined &&
1597
+ !conv.dirty &&
1598
+ conv.knownIds !== undefined &&
1599
+ !conv.key.startsWith('anon-')
1600
+ if (!canPark) {
1601
+ await this.resetSession(conv)
1602
+ return
1603
+ }
1604
+ const sessionId = conv.sessionId as string
1605
+ const proc = conv.process
1606
+ this.parkResumableSession(conv.key, {
1607
+ sessionId,
1608
+ systemHash: conv.systemHash as string,
1609
+ knownIds: [...(conv.knownIds as string[])],
1610
+ issuedIds: new Set(conv.issuedIds),
1611
+ })
1612
+ this.clearSession(conv)
1613
+ conv.knownIds = undefined
1614
+ conv.dirty = false
1615
+ if (proc !== undefined) {
1616
+ await proc.closeSession(sessionId)
1617
+ }
1618
+ }
1619
+
1435
1620
  private async resetSession(conv: Conversation): Promise<void> {
1621
+ this.dropResumableSession(conv.key)
1436
1622
  this.harvestSessionTurnData(conv, conv.sessionId, conv.model, conv.metaFloorIdx, {
1437
1623
  ifChangedSince: conv.lastDbStamp,
1438
1624
  })
@@ -1691,9 +1877,6 @@ export class AntigravityRuntime {
1691
1877
  data: block.data,
1692
1878
  mimeType: block.mimeType,
1693
1879
  })
1694
- } else {
1695
- const rendered = renderTranscript([{ role: 'user', content: [block] }])
1696
- if (rendered.length > 0) items.push({ type: 'text', text: rendered })
1697
1880
  }
1698
1881
  }
1699
1882
  if (items.length === 0) items.push({ type: 'text', text: '(no output)' })
@@ -1877,7 +2060,7 @@ export class AntigravityRuntime {
1877
2060
  conv.idleMs += slice
1878
2061
  if (conv.idleMs > ttl) {
1879
2062
  evictions.push(
1880
- this.resetSession(conv).catch((error: unknown) => {
2063
+ this.evictIdleSession(conv).catch((error: unknown) => {
1881
2064
  this.host.log.warn(
1882
2065
  `session sweep cleanup failed: ${error instanceof Error ? error.message : String(error)}`,
1883
2066
  )
@@ -1908,14 +2091,11 @@ function clampEffortToOptions(
1908
2091
  configOptions: readonly AcpConfigOption[],
1909
2092
  effort: Effort,
1910
2093
  ): Effort {
1911
- const levelOption = configOptions.find(
1912
- (o) => o.id === 'thought_level' || o.category === 'thought_level',
2094
+ const offered = offeredEffortsFrom(
2095
+ findConfigOption(configOptions, 'thought_level'),
1913
2096
  )
1914
- if (levelOption?.options === undefined) return effort
1915
- const offered = flattenConfigOptions(levelOption.options)
1916
- .map((o) => asEffort(o.value))
1917
- .filter((v): v is Effort => v !== undefined)
1918
- if (offered.length === 0 || offered.includes(effort)) return effort
2097
+ if (offered === undefined || offered.length === 0 || offered.includes(effort))
2098
+ return effort
1919
2099
  return nearestEffort(effort, offered)
1920
2100
  }
1921
2101
 
@@ -1969,7 +2149,7 @@ export function mapError(error: unknown): Error {
1969
2149
  )
1970
2150
  ) {
1971
2151
  return new LlmError(
1972
- `Antigravity requires sign-in: run \`agy\` once in a terminal (${message})`,
2152
+ `Antigravity requires sign-in: run \`agy\` once in a terminal or \`agy acp --login\` for headless/SSH setups (${message})`,
1973
2153
  'AUTH',
1974
2154
  { cause: error },
1975
2155
  )
@@ -1984,8 +2164,18 @@ export function mapError(error: unknown): Error {
1984
2164
  return new LlmError(message, 'CONTEXT_WINDOW_EXCEEDED', { cause: error })
1985
2165
  if (/rate.?limit|429|too many requests|overloaded|capacity/i.test(message))
1986
2166
  return new LlmError(message, 'RATE_LIMIT', { cause: error })
1987
- if (/quota|resource.?exhausted|limit reached|exceeded your/i.test(message))
2167
+ if (
2168
+ /quota|resource.?exhausted|limit reached|exceeded your|prepaid\s+balance|spend\s+cap|insufficient\s+(?:funds|credits?|balance)|billing\s+(?:limit|exhausted|disabled|required)/i.test(
2169
+ message,
2170
+ )
2171
+ )
1988
2172
  return new LlmError(message, 'QUOTA', { cause: error })
2173
+ if (
2174
+ /\binvalid_argument\b|unable to process input image|http\s+400|\(code\s+400\)|invalid\s+(?:image|request|argument)/i.test(
2175
+ message,
2176
+ )
2177
+ )
2178
+ return new LlmError(message, 'INVALID_REQUEST', { cause: error })
1989
2179
  if (error instanceof JsonRpcRemoteError)
1990
2180
  return new LlmError(`Antigravity: ${message}`, 'SERVER', { cause: error })
1991
2181
  return new LlmError(message, 'TRANSPORT', { cause: error })