@magpie-community/opencode-agy-tui-auth 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.mjs +52 -7
  2. package/package.json +1 -1
  3. package/seed.mjs +72 -0
package/index.mjs CHANGED
@@ -8,7 +8,7 @@ import { startLogin } from "./login.mjs"
8
8
  import { writeDefaultAgentFiles } from "./default-agent.mjs"
9
9
  import { agyHasUsageSubcommand, agyTooOld, MIN_AGY_VERSION, oldAgyError, USAGE_SUBCOMMAND_AGY_VERSION } from "./agy-version.mjs"
10
10
  import { conversationWorkspace, liveReply, callsAfter, usageOf, lastStep } from "./live.mjs"
11
- import { canSeed, chunks, resumed, writeConversation } from "./seed.mjs"
11
+ import { canSeed, chunks, mendStores, resumed, writeConversation } from "./seed.mjs"
12
12
  import { mcpToolsOf, unfit } from "./tools.mjs"
13
13
  import { clientNames, MCP_SERVER, offered } from "./tool-names.mjs"
14
14
  import { agyModelOf, foldModels } from "./efforts.mjs"
@@ -263,6 +263,7 @@ export async function agyRefusal(agy) {
263
263
  async function listModels(agy, home) {
264
264
  // the account's provider, not a modelProvider a settings file names
265
265
  const args = (await agyHelp(agy)).includes("--settings") ? ["--settings", '{"modelProvider":""}', "models"] : ["models"]
266
+ mendHome(home)
266
267
  const r = await run(agy, args, { env: agyEnv(home) })
267
268
  const models = r.code === 0 ? parseModels(r.stdout) : []
268
269
  if (!models.length) throw new Error(`agy lists no models for this account${lastLine(r.stderr || r.stdout) ? `: ${lastLine(r.stderr || r.stdout)}` : ""}`)
@@ -453,6 +454,24 @@ function toolResultText(message, media) {
453
454
  return `[${status} of ${message.tool_call_id ?? "a call"}]\n${partsOf(message.content, media).trim()}`
454
455
  }
455
456
 
457
+ // what a chat that ends on the assistant's own words (a client going on
458
+ // from a cut or finished reply) is typed with, as opencode-agy-cli-auth's
459
+ // continuation carrier says it
460
+ const CONTINUE_NOTE = "(system note: the last message above is part of your own reply; continue exactly from where it stops, and do not repeat it.)"
461
+
462
+ // continued is the chat with the user's note after a last message of the
463
+ // assistant's that is words alone, so it ends on a message agy can answer.
464
+ // A last message with calls nobody answered, or with no words, or a chat
465
+ // in which the user never spoke, is left as it is, for the caller to
466
+ // refuse.
467
+ export function continued(messages) {
468
+ const last = Array.isArray(messages) ? messages.at(-1) : null
469
+ if (last?.role !== "assistant" || (Array.isArray(last.tool_calls) && last.tool_calls.length)) return messages
470
+ if (!partsOf(last.content, []).trim()) return messages
471
+ if (!messages.some((m) => m?.role === "user")) return messages
472
+ return [...messages, { role: "user", content: CONTINUE_NOTE }]
473
+ }
474
+
456
475
  // turnOf is what goes into agy's prompt: the images and videos, attached in
457
476
  // the order they came, and the text pasted after them, the last user
458
477
  // message alone, or with the instructions and the conversation before it.
@@ -469,6 +488,7 @@ function toolResultText(message, media) {
469
488
  // see. One in an earlier turn stays, as what was said then.
470
489
  export function turnOf(messages, budget = INPUT_BUDGET) {
471
490
  if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
491
+ messages = continued(messages)
472
492
  // read once to weigh the turns, then again with only the kept ones, so
473
493
  // the images are numbered as they are attached
474
494
  const read = (list, media) => {
@@ -560,6 +580,7 @@ const GOES_ON = "\n\n[continued in the next message]"
560
580
  // came, as their marks in the steps say.
561
581
  export function seedSteps(messages, budget = INPUT_BUDGET) {
562
582
  if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
583
+ messages = continued(messages)
563
584
  const media = []
564
585
  const system = []
565
586
  const groups = []
@@ -949,6 +970,7 @@ function folderAt(want, prefix) {
949
970
  async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null, place = null, scope = "" }) {
950
971
  if (!helper) throw new Failure(501, oldMagpie(TUI_HELPER_MAGPIE, "has a terminal for agy"))
951
972
  settleHome(home)
973
+ mendHome(home)
952
974
  const withTools = tools.length > 0
953
975
  const clients = clientNames(tools)
954
976
  const ws = folderAt(place?.ws, "agy-tui-")
@@ -1498,6 +1520,28 @@ function forget(brain, id) {
1498
1520
  } catch {}
1499
1521
  }
1500
1522
 
1523
+ // mendHome takes out of the account's home, once a run before its first
1524
+ // agy, the conversations an older seed wrote with a workspace agy can't
1525
+ // parse (mendStores): from agy's lists, from the kept ones, and their
1526
+ // files.
1527
+ const mended = new Set()
1528
+ function mendHome(home) {
1529
+ if (mended.has(home)) return
1530
+ mended.add(home)
1531
+ let ids = []
1532
+ try { ids = mendStores(home) } catch {}
1533
+ if (!ids.length) return
1534
+ const list = keptOf(home)
1535
+ let changed = false
1536
+ for (const [key, e] of list) {
1537
+ if (!ids.includes(e.id)) continue
1538
+ list.delete(key)
1539
+ changed = true
1540
+ }
1541
+ if (changed) saveKept(home, list)
1542
+ for (const id of ids) forget(brainOf(home), id)
1543
+ }
1544
+
1501
1545
  // ---- conversations carried on
1502
1546
  //
1503
1547
  // agy keeps each conversation, and starts with one again given its id
@@ -1889,30 +1933,31 @@ export async function handle(home, input, init = {}) {
1889
1933
  let carried = null
1890
1934
  try {
1891
1935
  const tools = mcpToolsOf(body)
1936
+ const messages = continued(body.messages)
1892
1937
  const resumable = (await agyHelp(agy)).includes("--conversation")
1893
1938
  let paste = null
1894
1939
  const rebuild = () => {
1895
1940
  try {
1896
- paste = turnOf(body.messages)
1941
+ paste = turnOf(messages)
1897
1942
  } catch (error) {
1898
1943
  if (!error.long || !resumable || process.env.AGY_TUI_SEED === "0") throw error
1899
1944
  }
1900
1945
  if (resumable && (!paste || paste.cut) && process.env.AGY_TUI_SEED !== "0") {
1901
- const seeded = seedOf(home, body.messages)
1946
+ const seeded = seedOf(home, messages)
1902
1947
  if (seeded) return seeded
1903
1948
  }
1904
- paste ??= turnOf(body.messages)
1949
+ paste ??= turnOf(messages)
1905
1950
  return null
1906
1951
  }
1907
1952
  const start = async (c) => {
1908
1953
  const { prompt, media } = c ?? paste
1909
1954
  // agy attaches a video for any model, but only Gemini's see one
1910
1955
  if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw unfit(`${model || "this model"} takes no video; a Gemini model does`)
1911
- return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages: body.messages, scope })
1956
+ return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages, scope })
1912
1957
  }
1913
1958
  // Local state is an optimization. A different worker can start from
1914
1959
  // the request history alone, even if agy has lost a retained session.
1915
- carried = resumable ? await carriedOn(home, body.messages, { agy, model: agyModel, tools, scope }) : null
1960
+ carried = resumable ? await carriedOn(home, messages, { agy, model: agyModel, tools, scope }) : null
1916
1961
  carried ??= rebuild()
1917
1962
  for (;;) {
1918
1963
  try {
@@ -1926,7 +1971,7 @@ export async function handle(home, input, init = {}) {
1926
1971
  // Rebuild once from the full request if the old session vanished.
1927
1972
  // If agy also ignores a newly seeded store, use the prompt it takes.
1928
1973
  if (!previous.seeded) carried = rebuild()
1929
- else paste ??= turnOf(body.messages)
1974
+ else paste ??= turnOf(messages)
1930
1975
  }
1931
1976
  }
1932
1977
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.21",
3
+ "version": "0.1.23",
4
4
  "description": "Magpie/OpenCode model provider that runs Antigravity's models through agy's own interactive mode: each request is typed into the real agy TUI and its answer streamed from agy's own conversation store as the model writes it",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",
package/seed.mjs CHANGED
@@ -67,6 +67,7 @@ function loadOpener() {
67
67
  return {
68
68
  exec: (sql) => db.exec(sql),
69
69
  run: (sql, ...args) => db.prepare(sql).run(...args),
70
+ all: (sql, ...args) => db.prepare(sql).all(...args),
70
71
  close: () => db.close(),
71
72
  }
72
73
  }
@@ -81,6 +82,7 @@ function loadOpener() {
81
82
  return {
82
83
  exec: (sql) => db.exec(sql),
83
84
  run: (sql, ...args) => db.prepare(sql).run(...args),
85
+ all: (sql, ...args) => db.prepare(sql).all(...args),
84
86
  close: () => db.close(),
85
87
  }
86
88
  }
@@ -167,6 +169,76 @@ export function writeConversation(home, steps, { ws = home, now = Date.now(), wi
167
169
  }
168
170
  }
169
171
 
172
+ // A workspace URI with a drive letter where a file URL's host goes
173
+ // (file://C:\Users\…), as this plugin's seeds wrote it on Windows before
174
+ // workspaceUri (0.1.16 to 0.1.19; plugins#1967). agy fails such a
175
+ // conversation with "failed to resolve workspace infos: … invalid port",
176
+ // and keeps it in its two lists of conversations,
177
+ // cache/conversation_metadata.json and conversation_summaries.db, which it
178
+ // reconciles with each other.
179
+ const brokenURI = (uri) => typeof uri === "string" && /^file:\/\/[A-Za-z]:/.test(uri)
180
+
181
+ // mendStores takes every conversation with such a workspace out of both of
182
+ // agy's lists, and gives their ids, for the caller to remove their files.
183
+ // A list that can't be read is left as it is.
184
+ export function mendStores(home) {
185
+ const ac = path.join(home, ".gemini", "antigravity-cli")
186
+ const ids = new Set()
187
+ const metaFile = path.join(ac, "cache", "conversation_metadata.json")
188
+ let meta = null
189
+ try { meta = JSON.parse(fs.readFileSync(metaFile, "utf8")) } catch {}
190
+ const listed = meta?.conversations && typeof meta.conversations === "object" ? meta.conversations : {}
191
+ for (const [id, c] of Object.entries(listed)) {
192
+ const uris = c?.summary?.WorkspaceURIs
193
+ if (Array.isArray(uris) && uris.some(brokenURI)) ids.add(id)
194
+ }
195
+ const dbFile = path.join(ac, "conversation_summaries.db")
196
+ const open = loadOpener()
197
+ if (open && fs.existsSync(dbFile)) {
198
+ let db
199
+ try {
200
+ db = open(dbFile)
201
+ db.exec("PRAGMA busy_timeout = 2000")
202
+ for (const row of db.all("SELECT conversation_id, workspace_uris FROM conversation_summaries")) {
203
+ let uris = null
204
+ try { uris = JSON.parse(row.workspace_uris) } catch {}
205
+ if (Array.isArray(uris) && uris.some(brokenURI)) ids.add(String(row.conversation_id))
206
+ }
207
+ for (const id of ids) {
208
+ db.run("DELETE FROM conversation_summaries WHERE conversation_id = ?", id)
209
+ // agy's own tables beside it; its search index is FTS5, which a
210
+ // SQLite without it can't open
211
+ try { db.run("DELETE FROM conversation_parents WHERE conversation_id = ? OR parent_id = ?", id, id) } catch {}
212
+ try { db.run("DELETE FROM conversations_fts WHERE conversation_id = ?", id) } catch {}
213
+ }
214
+ } catch {} finally {
215
+ try { db?.close() } catch {}
216
+ }
217
+ }
218
+ const gone = (id) => ids.has(id)
219
+ if (Object.keys(listed).some(gone)) {
220
+ for (const id of ids) delete listed[id]
221
+ writeJSON(metaFile, meta)
222
+ }
223
+ const lastFile = path.join(ac, "cache", "last_conversations.json")
224
+ let last = null
225
+ try { last = JSON.parse(fs.readFileSync(lastFile, "utf8")) } catch {}
226
+ if (last && typeof last === "object" && Object.values(last).some(gone)) {
227
+ writeJSON(lastFile, Object.fromEntries(Object.entries(last).filter(([, id]) => !gone(id))))
228
+ }
229
+ return [...ids]
230
+ }
231
+
232
+ function writeJSON(file, value) {
233
+ const tmp = `${file}.${process.pid}.tmp`
234
+ try {
235
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 })
236
+ fs.renameSync(tmp, file)
237
+ } catch {
238
+ try { fs.rmSync(tmp, { force: true }) } catch {}
239
+ }
240
+ }
241
+
170
242
  // resumed is whether agy, started at `since` (ms) with the conversation
171
243
  // id, says in its log that it took it: true when it is resuming it, false
172
244
  // when it ignored it (and started one of its own), null while its log