@magpie-community/opencode-agy-tui-auth 0.1.5 → 0.1.7

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
@@ -23,7 +23,8 @@ A request's tools (`tools`, function tools) are given to the model through magpi
23
23
  - 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.
24
24
  - 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.
25
25
  - Each request is a new agy conversation, but for a tool call's result, which goes on in the agy that made the call; the conversation before it is pasted with it as text.
26
- - 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.
26
+ - 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. The model's thinking (agy asks Gemini for it) comes the same way, as `reasoning_content`, before the answer; not streamed, it is the message's `reasoning_content`. The response ends when the answer is whole, without waiting for agy to exit (it sends its own telemetry on the way out).
27
+ - agy takes seconds to start (signed in with Google, it asks Google for the account, its plan and its models before it takes a message), so each request leaves an agy started, at its prompt, for the next request with the same account, model and tools, which only types its message into it. One waits for each such kind (three at most), for 10 minutes at most; `AGY_TUI_SPARES=0` starts each request's agy when it comes instead.
27
28
  - It needs magpie 0.1.5217 or newer (with `tui-helper` and its tool server); an older magpie is told to update when a request has tools. Not yet tried on Windows.
28
29
 
29
30
  ## Options (environment)
@@ -32,4 +33,5 @@ A request's tools (`tools`, function tools) are given to the model through magpi
32
33
  - `AGY_TUI_TURN_TIMEOUT_MS`: the longest a turn may take, 15 minutes by default.
33
34
  - `AGY_TUI_PARK_TIMEOUT_MS`: how long a turn waits for a tool call's result, 10 minutes by default.
34
35
  - `AGY_TUI_ATTACH_TIMEOUT_MS`: how long agy may take to attach a turn's images and videos, 15 seconds by default.
36
+ - `AGY_TUI_SPARES=0`: no agy started ahead for the next request.
35
37
  - `AGY_TUI_KEEP=1`: keep each turn's folder (its images and videos too) and agy's conversation, to look into a problem.
package/README.md CHANGED
@@ -23,7 +23,8 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
23
23
  - 图片(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 模型。每个文件写进本轮的临时目录,随目录一起删除。
24
24
  - 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。
25
25
  - 每个请求都是一次新的 agy 会话(工具调用的结果除外,它会回到发起调用的那个 agy 里继续),之前的对话会整理成文字一起粘贴进去。
26
- - 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。
26
+ - 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。模型的思考(agy 向 Gemini 要了思考内容)同样边生成边作为 `reasoning_content` 返回,在回答之前;非流式时放在消息的 `reasoning_content` 里。回答写完就结束响应,不等 agy 退出(它退出前会先发完自己的遥测)。
27
+ - agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
27
28
  - 需要 magpie 0.1.5217 或更新(带 `tui-helper` 及其工具服务器);magpie 太旧时,带工具的请求会提示更新 magpie。Windows 尚未测试。
28
29
 
29
30
  ## 选项(环境变量)
@@ -32,4 +33,5 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
32
33
  - `AGY_TUI_TURN_TIMEOUT_MS`:一轮的最长时间,默认 15 分钟。
33
34
  - `AGY_TUI_PARK_TIMEOUT_MS`:一轮等待工具调用结果的最长时间,默认 10 分钟。
34
35
  - `AGY_TUI_ATTACH_TIMEOUT_MS`:agy 附加本轮图片和视频的最长等待时间,默认 15 秒。
36
+ - `AGY_TUI_SPARES=0`:不为下一个请求预先启动 agy。
35
37
  - `AGY_TUI_KEEP=1`:保留每轮的临时目录(包括图片和视频)和 agy 的对话记录,方便排查。
package/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
1
  import { spawn } from "node:child_process"
2
- import { randomBytes } from "node:crypto"
2
+ import { createHash, randomBytes } from "node:crypto"
3
3
  import fs from "node:fs"
4
4
  import os from "node:os"
5
5
  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
+ import { liveReply } from "./live.mjs"
10
10
  import { mcpToolsOf } from "./tools.mjs"
11
11
 
12
12
  // agy-tui: Antigravity's models through agy's own interactive mode. Each
@@ -46,6 +46,20 @@ const MCP_FUNCTIONS = `mcp_${MCP_SERVER}_*`
46
46
  const TOOL_INSTRUCTIONS = `agy's own tools are turned off in this session. The user's tools are given to you as ${MCP_FUNCTIONS.slice(0, -1)}<name>: each is the tool the conversation calls <name>, run on the user's computer. Call them when the task needs one.`
47
47
 
48
48
  // What agy 1.5's footer says: waiting for a message, and in a turn.
49
+ // the turns whose agy is on its way out, after their client had the end
50
+ const going = new Set()
51
+ const leaving = (p) => {
52
+ going.add(p)
53
+ return p.finally(() => going.delete(p))
54
+ }
55
+
56
+ // settled is when every turn's agy has gone and its files with it, the
57
+ // spares' too
58
+ export async function settled() {
59
+ await closeSpares()
60
+ while (going.size) await Promise.allSettled([...going])
61
+ }
62
+
49
63
  export const READY = "? for shortcuts"
50
64
  export const BUSY = "esc to cancel"
51
65
 
@@ -551,6 +565,85 @@ export function mcpConfig(mcp, tools) {
551
565
  // magpie's tool server, in a HOME of the turn's own (sessionHome), and its
552
566
  // own tools stay off.
553
567
  export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE }) {
568
+ const opts = { agy, home, model, tools, helper }
569
+ const key = spareKey(opts)
570
+ let turn = null
571
+ const spare = await takeSpare(key)
572
+ if (spare) {
573
+ try {
574
+ turn = await spare.begin({ prompt, media, signal })
575
+ } catch (error) {
576
+ // a spare that died while it waited is started again; the
577
+ // request's own failures are its own
578
+ if (!error.boot || signal?.aborted) throw error
579
+ }
580
+ }
581
+ if (!turn) turn = await (await launch(opts)).begin({ prompt, media, signal })
582
+ // agy has the message: the next request's agy starts now
583
+ leaveSpare(key, opts)
584
+ return turn
585
+ }
586
+
587
+ // ---- spares
588
+ //
589
+ // agy takes seconds to start: signed in with Google, it asks Cloud Code for
590
+ // the account, its plan and its models before it takes a message (a median
591
+ // of 3.8s a start on a real account, 11s at worst). So each turn leaves an
592
+ // agy started for the next request with the same account, model and tools,
593
+ // which only types its message into it. One waits per kind, for
594
+ // SPARE_IDLE_MS at most.
595
+ const SPARE_IDLE_MS = 10 * 60_000
596
+ const MAX_SPARES = 3
597
+ const spares = new Map()
598
+
599
+ function spareKey({ agy, home, model, tools, helper }) {
600
+ return createHash("sha256").update(JSON.stringify([agy, home, model ?? "", tools, helper ?? ""])).digest("hex")
601
+ }
602
+
603
+ async function takeSpare(key) {
604
+ const s = spares.get(key)
605
+ if (!s) return null
606
+ spares.delete(key)
607
+ clearTimeout(s.timer)
608
+ const a = await s.started.catch(() => null)
609
+ if (a?.alive()) return a
610
+ a?.close()
611
+ return null
612
+ }
613
+
614
+ function dropSpare(key) {
615
+ const s = spares.get(key)
616
+ if (!s) return
617
+ spares.delete(key)
618
+ clearTimeout(s.timer)
619
+ s.started.then((a) => a.close(), () => {})
620
+ }
621
+
622
+ function leaveSpare(key, opts) {
623
+ if (process.env.AGY_TUI_SPARES === "0" || spares.has(key)) return
624
+ while (spares.size >= MAX_SPARES) dropSpare(spares.keys().next().value)
625
+ const started = launch(opts)
626
+ started.catch(() => {})
627
+ const timer = setTimeout(() => dropSpare(key), SPARE_IDLE_MS)
628
+ timer.unref?.()
629
+ spares.set(key, { started, timer })
630
+ }
631
+
632
+ // closeSpares ends every agy that waits for a request
633
+ export async function closeSpares() {
634
+ const all = [...spares.values()]
635
+ spares.clear()
636
+ await Promise.all(all.map(async (s) => {
637
+ clearTimeout(s.timer)
638
+ const a = await s.started.catch(() => null)
639
+ await a?.close()
640
+ }))
641
+ }
642
+
643
+ // launch starts agy for a turn, in a folder of its own, and resolves at
644
+ // once: begin({ prompt, media, signal }) waits until it is at its prompt,
645
+ // types the request in and resolves with the turn
646
+ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE }) {
554
647
  if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
555
648
  settleHome(home)
556
649
  const withTools = tools.length > 0
@@ -560,7 +653,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
560
653
  // agy's own tools (what the old agent's `tools: []` did); with tools, the
561
654
  // caller's are let through
562
655
  let hookEnv
563
- let files
564
656
  let ownHome = null
565
657
  try {
566
658
  hookEnv = await writeDefaultAgentFiles(ws, {
@@ -568,10 +660,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
568
660
  allowed: withTools ? [MCP_FUNCTIONS] : [],
569
661
  geminiDir: path.join(home, ".gemini"),
570
662
  })
571
- // the images and videos, in the turn's folder: agy copies each one it
572
- // attaches into the conversation's own (forget removes it), and the
573
- // folder goes with the turn
574
- files = writeMedia(path.join(ws, "attachments"), media)
575
663
  if (withTools) {
576
664
  ownHome = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-home-")))
577
665
  sessionHome(home, ownHome)
@@ -582,6 +670,8 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
582
670
  throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
583
671
  }
584
672
  const brain = path.join(home, ".gemini", "antigravity-cli", "brain")
673
+ // the message, once a request gives it (begin)
674
+ let prompt = ""
585
675
  let before
586
676
  try { before = new Set(fs.readdirSync(brain)) } catch { before = new Set() }
587
677
 
@@ -621,13 +711,16 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
621
711
  found = answerOf(brain, before, prompt, found?.id)
622
712
  if (found?.id) claimed.add(found.id)
623
713
  }
624
- // what the model has said so far, from agy's conversation store
625
- // (live.mjs), for a stream to send as it comes
626
- const live = { text: "", listeners: new Set() }
627
- const publish = (text) => {
628
- if (typeof text !== "string" || text.length <= live.text.length) return
629
- live.text = text
630
- for (const fn of live.listeners) fn(text)
714
+ // what the model has said so far, its text and its thinking, from agy's
715
+ // conversation store (live.mjs), for a stream to send as it comes
716
+ const live = { text: "", thinking: "", listeners: new Set() }
717
+ const publish = (reply) => {
718
+ let grew = false
719
+ for (const k of ["text", "thinking"]) {
720
+ const v = reply?.[k]
721
+ if (typeof v === "string" && v.length > live[k].length) { live[k] = v; grew = true }
722
+ }
723
+ if (grew) for (const fn of live.listeners) fn()
631
724
  }
632
725
 
633
726
  let buf = ""
@@ -648,7 +741,7 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
648
741
  // what the model wrote before the call goes first
649
742
  pending.add(o.call.id)
650
743
  if (!found?.id) look()
651
- if (found?.id) publish(liveText(home, found.id))
744
+ if (found?.id) publish(liveReply(home, found.id))
652
745
  stop({ call: o.call })
653
746
  }
654
747
  if (o.dropped) pending.delete(o.dropped)
@@ -683,7 +776,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
683
776
  sig?.addEventListener?.("abort", onAbort, { once: true })
684
777
  if (sig?.aborted) onAbort()
685
778
  }
686
- watch(signal)
687
779
 
688
780
  // waitFor resolves once ok() holds; ms is how long it may take, or a
689
781
  // function giving the time it must hold by
@@ -703,110 +795,148 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
703
795
  })
704
796
  const ready = () => screen.includes(READY) && !screen.includes(BUSY)
705
797
 
706
- try {
707
- if (withTools) {
708
- // the tool server first: agy reads its config as it starts
709
- send({ tools })
710
- try {
711
- await waitFor("tool server", () => mcp, START_MS)
712
- } catch (error) {
713
- if (error.status === 499) throw error
714
- throw new Failure(501, `this magpie's terminal can't give agy tools (${errorLine || error.message}): update magpie`)
798
+ // agy started, at its prompt, with the tools listed: what a request
799
+ // waits on before its message is typed (begin)
800
+ const booted = (async () => {
801
+ try {
802
+ if (withTools) {
803
+ // the tool server first: agy reads its config as it starts
804
+ send({ tools })
805
+ try {
806
+ await waitFor("tool server", () => mcp, START_MS)
807
+ } catch (error) {
808
+ if (error.status === 499) throw error
809
+ throw new Failure(501, `this magpie's terminal can't give agy tools (${errorLine || error.message}): update magpie`)
810
+ }
811
+ fs.writeFileSync(path.join(ownHome, ".gemini", "config", "mcp_config.json"), JSON.stringify(mcpConfig(mcp, tools)), { mode: 0o600 })
715
812
  }
716
- fs.writeFileSync(path.join(ownHome, ".gemini", "config", "mcp_config.json"), JSON.stringify(mcpConfig(mcp, tools)), { mode: 0o600 })
813
+ send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
814
+ await waitFor("prompt", ready, START_MS)
815
+ // a message sent before agy listed the tools may find none of them
816
+ if (withTools) await waitFor("tools listed", () => listed, LISTED_MS)
817
+ } catch (error) {
818
+ await cleanup()
819
+ throw error
717
820
  }
718
- send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
719
- await waitFor("prompt", ready, START_MS)
720
- // a message sent before agy listed the tools may find none of them
721
- if (withTools) await waitFor("tools listed", () => listed, LISTED_MS)
722
- if (files.length) {
723
- // pasted alone, the paths are attached, as files dragged onto the
724
- // terminal are; the turn waits until agy shows every one attached,
725
- // so a path agy took for text is never sent as the message
726
- send({ write: `\x1b[200~${pastedPaths(files)}\x1b[201~` })
821
+ })()
822
+ // told to the request that begins, not before
823
+ booted.catch(() => {})
824
+
825
+ // begin types a request into this agy, its files and then its message,
826
+ // and resolves with the turn once agy has it
827
+ const begin = async (req) => {
828
+ prompt = req.prompt
829
+ const media = req.media ?? []
830
+ watch(req.signal)
831
+ try {
832
+ await booted
833
+ } catch (error) {
834
+ error.boot = true
835
+ throw error
836
+ }
837
+ try {
838
+ let files
727
839
  try {
728
- await waitFor("attachment", () => attached(screen) >= files.length, attachTimeout())
840
+ // the images and videos, in the turn's folder: agy copies each one
841
+ // it attaches into the conversation's own (forget removes it), and
842
+ // the folder goes with the turn
843
+ files = writeMedia(path.join(ws, "attachments"), media)
729
844
  } catch (error) {
730
- if (error.status !== 504) throw error
731
- throw new Failure(502, `agy didn't attach the ${files.length === 1 ? kindOf(media[0].type) : `${files.length} files`} (it shows ${attached(screen)})${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
845
+ throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
732
846
  }
733
- }
734
- send({ write: `\x1b[200~${prompt}\x1b[201~` })
735
- await new Promise((r) => setTimeout(r, PASTE_SETTLE_MS))
736
- send({ write: "\r" })
737
- // agy has the message once it is in a turn, or its transcript has it
738
- // (a turn that failed at once may never draw "esc to cancel")
739
- await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt)), SUBMIT_MS)
740
- } catch (error) {
741
- await cleanup()
742
- throw error
743
- }
744
-
745
- const turn = {
746
- live,
747
- // the reply's text the client has had, in the responses before this one
748
- sent: "",
749
- ended: false,
750
- next: async () => {
751
- while (!stops.length) await new Promise((r) => { wake = r })
752
- return stops.shift()
753
- },
754
- // reply answers a call agy waits on; false when it waits no more
755
- reply: (id, content, isError = false) => {
756
- if (!pending.delete(id)) return false
757
- send({ result: { id, content, isError } })
758
- return true
759
- },
760
- watch,
761
- close: () => cleanup(),
762
- }
763
-
764
- ;(async () => {
765
- let last
766
- let polled = 0
767
- // a turn waiting on the client's tool has no clock: the time is the
768
- // client's (a parked turn has its own, parkTimeout)
769
- let until = Date.now() + turnTimeout()
770
- try {
771
- // back at its prompt with nothing in the transcript for a while:
772
- // the turn failed, and what agy drew says why (a quota, a refusal)
773
- let idleSince = 0
774
- await waitFor("answer", () => {
775
- if (pending.size) {
776
- until = Date.now() + turnTimeout()
777
- idleSince = 0
778
- return false
779
- }
780
- if (!ready()) {
781
- idleSince = 0
782
- if (Date.now() - polled >= LIVE_POLL_MS) {
783
- polled = Date.now()
784
- if (!found?.id) look()
785
- if (found?.id) publish(liveText(home, found.id))
786
- }
787
- return false
847
+ if (files.length) {
848
+ // pasted alone, the paths are attached, as files dragged onto the
849
+ // terminal are; the turn waits until agy shows every one attached,
850
+ // so a path agy took for text is never sent as the message
851
+ send({ write: `\x1b[200~${pastedPaths(files)}\x1b[201~` })
852
+ try {
853
+ await waitFor("attachment", () => attached(screen) >= files.length, attachTimeout())
854
+ } catch (error) {
855
+ if (error.status !== 504) throw error
856
+ throw new Failure(502, `agy didn't attach the ${files.length === 1 ? kindOf(media[0].type) : `${files.length} files`} (it shows ${attached(screen)})${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
788
857
  }
789
- look()
790
- if (found?.answer) return true
791
- idleSince ||= Date.now()
792
- return Date.now() - idleSince > IDLE_MS
793
- }, () => until)
794
- if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
795
- // the whole of it, read before the conversation goes
796
- publish(liveText(home, found.id))
797
- last = { text: found.answer }
858
+ }
859
+ send({ write: `\x1b[200~${prompt}\x1b[201~` })
860
+ await new Promise((r) => setTimeout(r, PASTE_SETTLE_MS))
861
+ send({ write: "\r" })
862
+ // agy has the message once it is in a turn, or its transcript has it
863
+ // (a turn that failed at once may never draw "esc to cancel")
864
+ await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt)), SUBMIT_MS)
798
865
  } catch (error) {
799
- last = { error }
800
- } finally {
801
- // the end is told once the turn's files are gone
802
- turn.ended = true
803
- watch(null)
804
866
  await cleanup()
805
- forget(brain, found?.id)
806
- stop(last)
867
+ throw error
807
868
  }
808
- })()
809
- return turn
869
+
870
+ const turn = {
871
+ live,
872
+ // the reply's text and thinking the client has had, in the responses
873
+ // before this one
874
+ sent: "",
875
+ thought: "",
876
+ ended: false,
877
+ next: async () => {
878
+ while (!stops.length) await new Promise((r) => { wake = r })
879
+ return stops.shift()
880
+ },
881
+ // reply answers a call agy waits on; false when it waits no more
882
+ reply: (id, content, isError = false) => {
883
+ if (!pending.delete(id)) return false
884
+ send({ result: { id, content, isError } })
885
+ return true
886
+ },
887
+ watch,
888
+ close: () => cleanup(),
889
+ }
890
+
891
+ ;(async () => {
892
+ let last
893
+ let polled = 0
894
+ // a turn waiting on the client's tool has no clock: the time is the
895
+ // client's (a parked turn has its own, parkTimeout)
896
+ let until = Date.now() + turnTimeout()
897
+ try {
898
+ // back at its prompt with nothing in the transcript for a while:
899
+ // the turn failed, and what agy drew says why (a quota, a refusal)
900
+ let idleSince = 0
901
+ await waitFor("answer", () => {
902
+ if (pending.size) {
903
+ until = Date.now() + turnTimeout()
904
+ idleSince = 0
905
+ return false
906
+ }
907
+ if (!ready()) {
908
+ idleSince = 0
909
+ if (Date.now() - polled >= LIVE_POLL_MS) {
910
+ polled = Date.now()
911
+ if (!found?.id) look()
912
+ if (found?.id) publish(liveReply(home, found.id))
913
+ }
914
+ return false
915
+ }
916
+ look()
917
+ if (found?.answer) return true
918
+ idleSince ||= Date.now()
919
+ return Date.now() - idleSince > IDLE_MS
920
+ }, () => until)
921
+ if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
922
+ // the whole of it, read before the conversation goes
923
+ publish(liveReply(home, found.id))
924
+ last = { text: found.answer }
925
+ } catch (error) {
926
+ last = { error }
927
+ } finally {
928
+ // the end is told at once: agy's exit can wait on its own network
929
+ // (a telemetry flush on the way out), and the client needn't. The
930
+ // turn's files go after, once agy has.
931
+ turn.ended = true
932
+ watch(null)
933
+ stop(last)
934
+ await leaving(cleanup().then(() => forget(brain, found?.id)))
935
+ }
936
+ })()
937
+ return turn
938
+ }
939
+ return { begin, alive: () => !ended && !cleaned, close: () => cleanup() }
810
940
  }
811
941
 
812
942
  // ---- turns waiting on the client's tool
@@ -885,15 +1015,17 @@ function jsonError(status, message, headers = {}) {
885
1015
  const toolCallOf = (call, index) => ({ ...(index === undefined ? {} : { index }), id: call.id, type: "function", function: { name: call.name, arguments: JSON.stringify(call.arguments ?? {}) } })
886
1016
 
887
1017
  // since is what of text is new to this response: past what the turn's
888
- // earlier responses had, without the break before it
889
- function since(turn, text) {
890
- return text.startsWith(turn.sent) ? text.slice(turn.sent.length).replace(/^\n+/, "") : ""
1018
+ // earlier responses had (`had`, the text's by default), without the break
1019
+ // before it
1020
+ function since(turn, text, had = turn.sent) {
1021
+ return text.startsWith(had) ? text.slice(had.length).replace(/^\n+/, "") : ""
891
1022
  }
892
1023
 
893
1024
  // stopped ends a response at a call: the turn waits for its result
894
1025
  function stopped(turn, call) {
895
1026
  turn.watch(null)
896
1027
  turn.sent = turn.live.text
1028
+ turn.thought = turn.live.thinking
897
1029
  park(call.id, turn)
898
1030
  }
899
1031
 
@@ -911,12 +1043,14 @@ function completion(id, model, message, finish) {
911
1043
  async function answered(id, model, turn) {
912
1044
  const s = await turn.next()
913
1045
  if (s.error) throw s.error
1046
+ const thinking = since(turn, turn.live.thinking, turn.thought)
1047
+ const reasoning = thinking ? { reasoning_content: thinking } : {}
914
1048
  if (s.call) {
915
1049
  const text = since(turn, turn.live.text)
916
1050
  stopped(turn, s.call)
917
- return completion(id, model, { content: text || null, tool_calls: [toolCallOf(s.call)] }, "tool_calls")
1051
+ return completion(id, model, { content: text || null, ...reasoning, tool_calls: [toolCallOf(s.call)] }, "tool_calls")
918
1052
  }
919
- return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text }, "stop")
1053
+ return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop")
920
1054
  }
921
1055
 
922
1056
  // streamOf sends the turn's reply up to its next stop as agy's model
@@ -938,10 +1072,19 @@ export function streamOf(id, model, turn) {
938
1072
  return new ReadableStream({
939
1073
  async start(c) {
940
1074
  let sent = ""
1075
+ let thought = ""
941
1076
  // only what continues what was sent: agy writing a reply over is
942
- // left to the end
943
- const send = (text) => {
944
- const full = since(turn, text)
1077
+ // left to the end. The thinking goes as it comes, as
1078
+ // reasoning_content, so a model that thinks a while before its first
1079
+ // word shows it from the first thought
1080
+ const send = () => {
1081
+ const think = since(turn, live.thinking, turn.thought)
1082
+ if (think.length > thought.length && think.startsWith(thought)) {
1083
+ try { c.enqueue(enc.encode(chunk({ reasoning_content: think.slice(thought.length) }))) } catch { return }
1084
+ thought = think
1085
+ quiet = Date.now()
1086
+ }
1087
+ const full = since(turn, live.text)
945
1088
  if (full.length <= sent.length || !full.startsWith(sent)) return
946
1089
  try { c.enqueue(enc.encode(chunk({ content: full.slice(sent.length) }))) } catch { return }
947
1090
  sent = full
@@ -951,7 +1094,7 @@ export function streamOf(id, model, turn) {
951
1094
  quiet = Date.now()
952
1095
  listen = send
953
1096
  live.listeners.add(listen)
954
- send(live.text)
1097
+ send()
955
1098
  // the turn may take minutes before its first word: a comment now
956
1099
  // and then keeps the connection from looking dead
957
1100
  keep = setInterval(() => {
@@ -963,7 +1106,7 @@ export function streamOf(id, model, turn) {
963
1106
  const s = await turn.next()
964
1107
  halt()
965
1108
  if (s.error) throw s.error
966
- send(live.text)
1109
+ send()
967
1110
  if (s.call) {
968
1111
  stopped(turn, s.call)
969
1112
  c.enqueue(enc.encode(chunk({ tool_calls: [toolCallOf(s.call, 0)] })))
package/live.mjs CHANGED
@@ -4,7 +4,9 @@
4
4
  // model's reply there as each piece of it arrives: a row of `steps` with
5
5
  // step_type 15 (the PLANNER_RESPONSE the transcript gets at the end),
6
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
7
+ // it, in field 20.1 of step_payload, and its thinking (the thought parts
8
+ // Gemini streams before the text, which agy asks for with includeThoughts)
9
+ // in field 20.3, filled in first. The transcript is written only when
8
10
  // the reply is whole, and the screen shows it drawn (markup taken out,
9
11
  // lines wrapped), so this is the one place the reply can be read as it
10
12
  // comes. Read-only, never waiting on a lock; anything unreadable is null,
@@ -104,23 +106,35 @@ function fields(buf, fn) {
104
106
 
105
107
  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
108
 
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) {
109
+ // stepOf is a PLANNER_RESPONSE step's text (field 20.1 of its payload)
110
+ // and thinking (field 20.3), each "" when it has none yet; null when the
111
+ // payload isn't one.
112
+ export function stepOf(payload) {
110
113
  const buf = bytesOf(payload)
111
114
  if (!buf) return null
112
115
  let response = null
113
116
  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
117
+ const step = { text: "", thinking: "" }
118
+ if (!response) return step
119
+ const dec = new TextDecoder()
120
+ if (!fields(response, (f, w, v) => {
121
+ if (w !== 2) return
122
+ if (f === 1) step.text = dec.decode(v)
123
+ else if (f === 3) step.thinking = dec.decode(v)
124
+ })) return null
125
+ return step
118
126
  }
119
127
 
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) {
128
+ // replyOf is a PLANNER_RESPONSE step's text, "" when it has none yet, null
129
+ // when the payload isn't one.
130
+ export function replyOf(payload) {
131
+ return stepOf(payload)?.text ?? null
132
+ }
133
+
134
+ // liveReply is what agy's model has said so far in the conversation id of
135
+ // the account at home: { text, thinking }, each the replies' own, in
136
+ // order, a blank line between two; null when the store can't be read.
137
+ export function liveReply(home, id) {
124
138
  const file = conversationDb(home, id)
125
139
  if (!file || !fs.existsSync(file)) return null
126
140
  const open = loadOpener()
@@ -130,14 +144,21 @@ export function liveText(home, id) {
130
144
  db = open(file)
131
145
  const rows = db.all(`SELECT idx, step_payload FROM steps WHERE step_type = ${MODEL_STEP} ORDER BY idx`)
132
146
  const texts = []
147
+ const thoughts = []
133
148
  for (const row of rows) {
134
- const text = replyOf(row.step_payload)
135
- if (text) texts.push(text)
149
+ const step = stepOf(row.step_payload)
150
+ if (step?.text) texts.push(step.text)
151
+ if (step?.thinking) thoughts.push(step.thinking)
136
152
  }
137
- return texts.join("\n\n")
153
+ return { text: texts.join("\n\n"), thinking: thoughts.join("\n\n") }
138
154
  } catch {
139
155
  return null
140
156
  } finally {
141
157
  try { db?.close() } catch {}
142
158
  }
143
159
  }
160
+
161
+ // liveText is liveReply's text alone.
162
+ export function liveText(home, id) {
163
+ return liveReply(home, id)?.text ?? null
164
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
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",