@magpie-community/opencode-agy-tui-auth 0.1.3 → 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/README.en.md CHANGED
@@ -20,7 +20,7 @@ agy runs on its default agent, never a custom one (`--agent`), which agy 1.5.17
20
20
  - Images (PNG, JPEG, GIF, WebP, BMP, TIFF, SVG; up to 10 MB each) and videos (MP4, MOV, WebM, AVI; up to 50 MB each), sent inline as a data: URL, go to agy as attachments, the way a file dragged into its prompt does: what agy 1.5.19's prompt attaches, at its own size limits. Images work with Gemini and Claude models, videos with Gemini models. Each file is written to the turn's folder and deleted with it.
21
21
  - Anything else agy's prompt doesn't attach, so it is refused (400) with what it was, never dropped: a PDF, audio, a text or code file, a HEIC, a link to a file instead of the file itself, and a video for a Claude model.
22
22
  - Each request is a new agy conversation; the conversation before it is pasted with it as text.
23
- - The answer comes whole when the turn ends (a streamed request gets keep-alives first, then the answer).
23
+ - A streamed request gets the answer as the model writes it: agy commits each piece of the reply to its own conversation store (`conversations/<id>.db`), and the plugin reads what is new, read-only. When the store can't be read, the answer comes whole when the turn ends.
24
24
  - It needs magpie v0.1.5027 or newer (with `tui-helper`). Not yet tried on Windows.
25
25
 
26
26
  ## Options (environment)
package/README.md CHANGED
@@ -20,7 +20,7 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
20
20
  - 图片(PNG、JPEG、GIF、WebP、BMP、TIFF、SVG,每张不超过 10 MB)和视频(MP4、MOV、WebM、AVI,每个不超过 50 MB)以 data: URL 内联发送,会像拖进 agy 输入框的文件一样作为附件交给 agy:正是 agy 1.5.19 输入框能附加的类型,大小限制也和 agy 自己的一样。图片适用于 Gemini 和 Claude 模型,视频只适用于 Gemini 模型。每个文件写进本轮的临时目录,随目录一起删除。
21
21
  - 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。
22
22
  - 每个请求都是一次新的 agy 会话,之前的对话会整理成文字一起粘贴进去。
23
- - 回答在一轮结束后一次性返回(流式请求会先收到心跳,再收到完整回答)。
23
+ - 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。
24
24
  - 需要 magpie v0.1.5027 或更新(带 `tui-helper`)。Windows 尚未测试。
25
25
 
26
26
  ## 选项(环境变量)
package/index.mjs CHANGED
@@ -6,6 +6,7 @@ import path from "node:path"
6
6
  import { startLogin } from "./login.mjs"
7
7
  import { writeDefaultAgentFiles } from "./default-agent.mjs"
8
8
  import { agyTooOld, MIN_AGY_VERSION } from "./agy-version.mjs"
9
+ import { liveText } from "./live.mjs"
9
10
 
10
11
  // agy-tui: Antigravity's models through agy's own interactive mode. Each
11
12
  // request starts the real `agy` TUI in a terminal magpie gives it (`magpie
@@ -50,6 +51,8 @@ const PASTE_SETTLE_MS = 300
50
51
  // how long agy may sit at its prompt after a turn before the transcript has
51
52
  // its answer
52
53
  const IDLE_MS = 5_000
54
+ // how often a running turn's reply is read from agy's store (live.mjs)
55
+ const LIVE_POLL_MS = 100
53
56
 
54
57
  function attachTimeout() {
55
58
  const n = Number(process.env.AGY_TUI_ATTACH_TIMEOUT_MS)
@@ -100,12 +103,22 @@ export function agyEnv(home, parent = process.env, platform = process.platform)
100
103
  }
101
104
 
102
105
  // agy's first-run screens are the account home's own business: they were
103
- // passed once its sign-in took. Written only where nothing is.
104
- function settleHome(home) {
106
+ // passed once its sign-in took. `agy models`, run to list the models before
107
+ // any turn, writes the file with every step not done, so a file that is
108
+ // there is brought up too; its other keys are kept.
109
+ export function settleHome(home) {
105
110
  const file = path.join(home, ".gemini", "antigravity-cli", "cache", "onboarding.json")
106
- if (fs.existsSync(file)) return
111
+ let state = {}
112
+ try {
113
+ const read = JSON.parse(fs.readFileSync(file, "utf8"))
114
+ if (read && typeof read === "object" && !Array.isArray(read)) state = read
115
+ } catch {}
116
+ if (state.consumerOnboardingComplete === true && state.onboardingComplete === true) return
117
+ state = { ...state, consumerOnboardingComplete: true, onboardingComplete: true }
107
118
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
108
- fs.writeFileSync(file, JSON.stringify({ consumerOnboardingComplete: true, onboardingComplete: true }), { mode: 0o600 })
119
+ const tmp = `${file}.${process.pid}.tmp`
120
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 })
121
+ fs.renameSync(tmp, file)
109
122
  }
110
123
 
111
124
  // ---- agy
@@ -562,8 +575,21 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
562
575
  throw error
563
576
  }
564
577
 
578
+ // what the model has said so far, from agy's conversation store
579
+ // (live.mjs), for a stream to send as it comes
580
+ const live = { text: "", listeners: new Set() }
581
+ const publish = (text) => {
582
+ if (typeof text !== "string" || text.length <= live.text.length) return
583
+ live.text = text
584
+ for (const fn of live.listeners) fn(text)
585
+ }
565
586
  const answer = (async () => {
566
587
  let found = null
588
+ let polled = 0
589
+ const look = () => {
590
+ found = answerOf(brain, before, prompt, found?.id)
591
+ if (found?.id) claimed.add(found.id)
592
+ }
567
593
  try {
568
594
  // back at its prompt with nothing in the transcript for a while:
569
595
  // the turn failed, and what agy drew says why (a quota, a refusal)
@@ -571,22 +597,28 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
571
597
  await waitFor("answer", () => {
572
598
  if (!ready()) {
573
599
  idleSince = 0
600
+ if (Date.now() - polled >= LIVE_POLL_MS) {
601
+ polled = Date.now()
602
+ if (!found?.id) look()
603
+ if (found?.id) publish(liveText(home, found.id))
604
+ }
574
605
  return false
575
606
  }
576
- found = answerOf(brain, before, prompt, found?.id)
577
- if (found?.id) claimed.add(found.id)
607
+ look()
578
608
  if (found?.answer) return true
579
609
  idleSince ||= Date.now()
580
610
  return Date.now() - idleSince > IDLE_MS
581
611
  }, turnTimeout())
582
612
  if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
613
+ // the whole of it, read before the conversation goes
614
+ publish(liveText(home, found.id))
583
615
  return found.answer
584
616
  } finally {
585
617
  await cleanup()
586
618
  forget(brain, found?.id)
587
619
  }
588
620
  })()
589
- return { answer }
621
+ return { answer, live }
590
622
  }
591
623
 
592
624
  // forget removes the conversation agy kept for a turn from the account's
@@ -621,30 +653,60 @@ function completion(id, model, text) {
621
653
  }
622
654
  }
623
655
 
624
- function streamOf(id, model, answer) {
656
+ // streamOf sends the reply as agy's model writes it (turn.live), each
657
+ // piece once; at the end, what the store has whole, or, with nothing read
658
+ // from it, the transcript's answer.
659
+ export function streamOf(id, model, turn) {
660
+ const { answer, live } = turn
625
661
  const enc = new TextEncoder()
626
662
  const created = Math.floor(Date.now() / 1000)
627
663
  const chunk = (delta, finish = null) => `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`
628
664
  let keep
665
+ let listen
666
+ let quiet = 0
667
+ const stop = () => {
668
+ clearInterval(keep)
669
+ if (listen) live?.listeners.delete(listen)
670
+ }
629
671
  return new ReadableStream({
630
672
  async start(c) {
673
+ let sent = ""
674
+ // only what continues what was sent: agy writing a reply over is
675
+ // left to the end
676
+ const send = (text) => {
677
+ if (text.length <= sent.length || !text.startsWith(sent)) return
678
+ try { c.enqueue(enc.encode(chunk({ content: text.slice(sent.length) }))) } catch { return }
679
+ sent = text
680
+ quiet = Date.now()
681
+ }
631
682
  c.enqueue(enc.encode(chunk({ role: "assistant", content: "" })))
632
- // the turn may take minutes: a comment now and then keeps the
633
- // connection from looking dead
634
- keep = setInterval(() => { try { c.enqueue(enc.encode(": working\n\n")) } catch {} }, 15_000)
683
+ quiet = Date.now()
684
+ if (live) {
685
+ listen = send
686
+ live.listeners.add(listen)
687
+ send(live.text)
688
+ }
689
+ // the turn may take minutes before its first word: a comment now
690
+ // and then keeps the connection from looking dead
691
+ keep = setInterval(() => {
692
+ if (Date.now() - quiet < 15_000) return
693
+ try { c.enqueue(enc.encode(": working\n\n")) } catch {}
694
+ quiet = Date.now()
695
+ }, 5_000)
635
696
  try {
636
697
  const text = await answer
637
- c.enqueue(enc.encode(chunk({ content: text })))
698
+ stop()
699
+ send(live?.text || text)
638
700
  c.enqueue(enc.encode(chunk({}, "stop")))
639
701
  } catch (error) {
640
702
  c.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: error.message, type: "agy_tui_error" } })}\n\n`))
641
703
  } finally {
642
- clearInterval(keep)
704
+ stop()
643
705
  }
644
706
  c.enqueue(enc.encode("data: [DONE]\n\n"))
645
707
  c.close()
646
708
  },
647
- cancel() { clearInterval(keep) },
709
+ cancel() { stop() },
648
710
  })
649
711
  }
650
712
 
@@ -677,7 +739,7 @@ export async function handle(home, input, init = {}) {
677
739
  return jsonError(error.status ?? 502, error.message, error.headers)
678
740
  }
679
741
  if (body.stream) {
680
- return new Response(streamOf(id, model, turn.answer), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
742
+ return new Response(streamOf(id, model, turn), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
681
743
  }
682
744
  try {
683
745
  return new Response(JSON.stringify(completion(id, model, await turn.answer)), { status: 200, headers: { "Content-Type": "application/json" } })
package/live.mjs ADDED
@@ -0,0 +1,143 @@
1
+ // The answer as agy writes it, while it writes it. agy keeps each
2
+ // conversation in its home's antigravity-cli/conversations/<id>.db (SQLite,
3
+ // in WAL mode, <id> the conversation's brain folder), and commits its
4
+ // model's reply there as each piece of it arrives: a row of `steps` with
5
+ // step_type 15 (the PLANNER_RESPONSE the transcript gets at the end),
6
+ // status 8 while it comes and 3 once whole, its text, as the model wrote
7
+ // it, in field 20.1 of step_payload. The transcript is written only when
8
+ // the reply is whole, and the screen shows it drawn (markup taken out,
9
+ // lines wrapped), so this is the one place the reply can be read as it
10
+ // comes. Read-only, never waiting on a lock; anything unreadable is null,
11
+ // and the turn's transcript gives the answer at its end as before.
12
+ // (The layout was read from agy 1.5.20's store; agy-cli's step-usage.mjs
13
+ // reads the same table.)
14
+ import { createRequire } from "node:module"
15
+ import fs from "node:fs"
16
+ import path from "node:path"
17
+
18
+ const MODEL_STEP = 15
19
+ const require = createRequire(import.meta.url)
20
+
21
+ let opener
22
+
23
+ // bun:sqlite under Bun (magpie's plugin host), node:sqlite on Node 22.5+;
24
+ // read-only, and a busy store is not waited for.
25
+ function loadOpener() {
26
+ if (opener !== undefined) return opener
27
+ opener = null
28
+ try {
29
+ const { Database, constants } = require("bun:sqlite")
30
+ if (typeof Database === "function") {
31
+ opener = (file) => {
32
+ const db = new Database(file, constants.SQLITE_OPEN_READONLY)
33
+ return {
34
+ all(sql) {
35
+ const stmt = db.prepare(sql)
36
+ try { return stmt.all() } finally { stmt.finalize() }
37
+ },
38
+ close: () => db.close(),
39
+ }
40
+ }
41
+ return opener
42
+ }
43
+ } catch {}
44
+ try {
45
+ const { DatabaseSync } = require("node:sqlite")
46
+ if (typeof DatabaseSync === "function") {
47
+ opener = (file) => {
48
+ const db = new DatabaseSync(file, { readOnly: true, timeout: 0 })
49
+ return { all: (sql) => db.prepare(sql).all(), close: () => db.close() }
50
+ }
51
+ return opener
52
+ }
53
+ } catch {}
54
+ return opener
55
+ }
56
+
57
+ export function conversationDb(home, id) {
58
+ if (typeof id !== "string" || !/^[A-Za-z0-9._-]+$/.test(id)) return null
59
+ return path.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`)
60
+ }
61
+
62
+ function varint(buf, at) {
63
+ let value = 0
64
+ let scale = 1
65
+ for (let i = 0; i < 10; i++) {
66
+ const byte = buf[at + i]
67
+ if (byte === undefined) return null
68
+ value += (byte & 0x7f) * scale
69
+ if ((byte & 0x80) === 0) return { value, next: at + i + 1 }
70
+ scale *= 128
71
+ }
72
+ return null
73
+ }
74
+
75
+ // fields calls fn(field, wire, value) for each of buf's fields, the bytes
76
+ // of a length-delimited one; false when buf isn't a message.
77
+ function fields(buf, fn) {
78
+ let at = 0
79
+ while (at < buf.length) {
80
+ const tag = varint(buf, at)
81
+ if (!tag || tag.value < 8) return false
82
+ at = tag.next
83
+ const field = Math.floor(tag.value / 8)
84
+ const wire = tag.value % 8
85
+ if (wire === 0) {
86
+ const v = varint(buf, at)
87
+ if (!v) return false
88
+ at = v.next
89
+ fn(field, wire, v.value)
90
+ } else if (wire === 2) {
91
+ const len = varint(buf, at)
92
+ if (!len || len.next + len.value > buf.length) return false
93
+ fn(field, wire, buf.subarray(len.next, len.next + len.value))
94
+ at = len.next + len.value
95
+ } else if (wire === 1 || wire === 5) {
96
+ at += wire === 1 ? 8 : 4
97
+ if (at > buf.length) return false
98
+ } else {
99
+ return false
100
+ }
101
+ }
102
+ return true
103
+ }
104
+
105
+ const bytesOf = (v) => v instanceof Uint8Array ? v : ArrayBuffer.isView(v) ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : v instanceof ArrayBuffer ? new Uint8Array(v) : null
106
+
107
+ // replyOf is a PLANNER_RESPONSE step's text (field 20.1 of its payload),
108
+ // "" when it has none yet, null when the payload isn't one.
109
+ export function replyOf(payload) {
110
+ const buf = bytesOf(payload)
111
+ if (!buf) return null
112
+ let response = null
113
+ if (!fields(buf, (f, w, v) => { if (f === 20 && w === 2) response = v })) return null
114
+ if (!response) return ""
115
+ let text = ""
116
+ if (!fields(response, (f, w, v) => { if (f === 1 && w === 2) text = new TextDecoder().decode(v) })) return null
117
+ return text
118
+ }
119
+
120
+ // liveText is what agy's model has said so far in the conversation id of
121
+ // the account at home: each reply's text, in order, a blank line between
122
+ // two; null when the store can't be read.
123
+ export function liveText(home, id) {
124
+ const file = conversationDb(home, id)
125
+ if (!file || !fs.existsSync(file)) return null
126
+ const open = loadOpener()
127
+ if (!open) return null
128
+ let db
129
+ try {
130
+ db = open(file)
131
+ const rows = db.all(`SELECT idx, step_payload FROM steps WHERE step_type = ${MODEL_STEP} ORDER BY idx`)
132
+ const texts = []
133
+ for (const row of rows) {
134
+ const text = replyOf(row.step_payload)
135
+ if (text) texts.push(text)
136
+ }
137
+ return texts.join("\n\n")
138
+ } catch {
139
+ return null
140
+ } finally {
141
+ try { db?.close() } catch {}
142
+ }
143
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.3",
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 read from agy's transcript",
3
+ "version": "0.1.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",
7
7
  "exports": {
@@ -9,6 +9,7 @@
9
9
  },
10
10
  "files": [
11
11
  "index.mjs",
12
+ "live.mjs",
12
13
  "login.mjs",
13
14
  "default-agent.mjs",
14
15
  "agy-version.mjs",