@magpie-community/opencode-agy-tui-auth 0.1.6 → 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
@@ -24,6 +24,7 @@ A request's tools (`tools`, function tools) are given to the model through magpi
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
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
@@ -24,6 +24,7 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
24
24
  - 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。
25
25
  - 每个请求都是一次新的 agy 会话(工具调用的结果除外,它会回到发起调用的那个 agy 里继续),之前的对话会整理成文字一起粘贴进去。
26
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,5 +1,5 @@
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"
@@ -53,8 +53,10 @@ const leaving = (p) => {
53
53
  return p.finally(() => going.delete(p))
54
54
  }
55
55
 
56
- // settled is when every turn's agy has gone and its files with it
56
+ // settled is when every turn's agy has gone and its files with it, the
57
+ // spares' too
57
58
  export async function settled() {
59
+ await closeSpares()
58
60
  while (going.size) await Promise.allSettled([...going])
59
61
  }
60
62
 
@@ -563,6 +565,85 @@ export function mcpConfig(mcp, tools) {
563
565
  // magpie's tool server, in a HOME of the turn's own (sessionHome), and its
564
566
  // own tools stay off.
565
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 }) {
566
647
  if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
567
648
  settleHome(home)
568
649
  const withTools = tools.length > 0
@@ -572,7 +653,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
572
653
  // agy's own tools (what the old agent's `tools: []` did); with tools, the
573
654
  // caller's are let through
574
655
  let hookEnv
575
- let files
576
656
  let ownHome = null
577
657
  try {
578
658
  hookEnv = await writeDefaultAgentFiles(ws, {
@@ -580,10 +660,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
580
660
  allowed: withTools ? [MCP_FUNCTIONS] : [],
581
661
  geminiDir: path.join(home, ".gemini"),
582
662
  })
583
- // the images and videos, in the turn's folder: agy copies each one it
584
- // attaches into the conversation's own (forget removes it), and the
585
- // folder goes with the turn
586
- files = writeMedia(path.join(ws, "attachments"), media)
587
663
  if (withTools) {
588
664
  ownHome = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-home-")))
589
665
  sessionHome(home, ownHome)
@@ -594,6 +670,8 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
594
670
  throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
595
671
  }
596
672
  const brain = path.join(home, ".gemini", "antigravity-cli", "brain")
673
+ // the message, once a request gives it (begin)
674
+ let prompt = ""
597
675
  let before
598
676
  try { before = new Set(fs.readdirSync(brain)) } catch { before = new Set() }
599
677
 
@@ -698,7 +776,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
698
776
  sig?.addEventListener?.("abort", onAbort, { once: true })
699
777
  if (sig?.aborted) onAbort()
700
778
  }
701
- watch(signal)
702
779
 
703
780
  // waitFor resolves once ok() holds; ms is how long it may take, or a
704
781
  // function giving the time it must hold by
@@ -718,113 +795,148 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
718
795
  })
719
796
  const ready = () => screen.includes(READY) && !screen.includes(BUSY)
720
797
 
721
- try {
722
- if (withTools) {
723
- // the tool server first: agy reads its config as it starts
724
- send({ tools })
725
- try {
726
- await waitFor("tool server", () => mcp, START_MS)
727
- } catch (error) {
728
- if (error.status === 499) throw error
729
- 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 })
730
812
  }
731
- 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
820
+ }
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
732
836
  }
733
- send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
734
- await waitFor("prompt", ready, START_MS)
735
- // a message sent before agy listed the tools may find none of them
736
- if (withTools) await waitFor("tools listed", () => listed, LISTED_MS)
737
- if (files.length) {
738
- // pasted alone, the paths are attached, as files dragged onto the
739
- // terminal are; the turn waits until agy shows every one attached,
740
- // so a path agy took for text is never sent as the message
741
- send({ write: `\x1b[200~${pastedPaths(files)}\x1b[201~` })
837
+ try {
838
+ let files
742
839
  try {
743
- 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)
744
844
  } catch (error) {
745
- if (error.status !== 504) throw error
746
- 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}`)
846
+ }
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)}` : ""}`)
857
+ }
747
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)
865
+ } catch (error) {
866
+ await cleanup()
867
+ throw error
748
868
  }
749
- send({ write: `\x1b[200~${prompt}\x1b[201~` })
750
- await new Promise((r) => setTimeout(r, PASTE_SETTLE_MS))
751
- send({ write: "\r" })
752
- // agy has the message once it is in a turn, or its transcript has it
753
- // (a turn that failed at once may never draw "esc to cancel")
754
- await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt)), SUBMIT_MS)
755
- } catch (error) {
756
- await cleanup()
757
- throw error
758
- }
759
869
 
760
- const turn = {
761
- live,
762
- // the reply's text and thinking the client has had, in the responses
763
- // before this one
764
- sent: "",
765
- thought: "",
766
- ended: false,
767
- next: async () => {
768
- while (!stops.length) await new Promise((r) => { wake = r })
769
- return stops.shift()
770
- },
771
- // reply answers a call agy waits on; false when it waits no more
772
- reply: (id, content, isError = false) => {
773
- if (!pending.delete(id)) return false
774
- send({ result: { id, content, isError } })
775
- return true
776
- },
777
- watch,
778
- close: () => cleanup(),
779
- }
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
+ }
780
890
 
781
- ;(async () => {
782
- let last
783
- let polled = 0
784
- // a turn waiting on the client's tool has no clock: the time is the
785
- // client's (a parked turn has its own, parkTimeout)
786
- let until = Date.now() + turnTimeout()
787
- try {
788
- // back at its prompt with nothing in the transcript for a while:
789
- // the turn failed, and what agy drew says why (a quota, a refusal)
790
- let idleSince = 0
791
- await waitFor("answer", () => {
792
- if (pending.size) {
793
- until = Date.now() + turnTimeout()
794
- idleSince = 0
795
- return false
796
- }
797
- if (!ready()) {
798
- idleSince = 0
799
- if (Date.now() - polled >= LIVE_POLL_MS) {
800
- polled = Date.now()
801
- if (!found?.id) look()
802
- if (found?.id) publish(liveReply(home, found.id))
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
803
906
  }
804
- return false
805
- }
806
- look()
807
- if (found?.answer) return true
808
- idleSince ||= Date.now()
809
- return Date.now() - idleSince > IDLE_MS
810
- }, () => until)
811
- if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
812
- // the whole of it, read before the conversation goes
813
- publish(liveReply(home, found.id))
814
- last = { text: found.answer }
815
- } catch (error) {
816
- last = { error }
817
- } finally {
818
- // the end is told at once: agy's exit can wait on its own network
819
- // (a telemetry flush on the way out), and the client needn't. The
820
- // turn's files go after, once agy has.
821
- turn.ended = true
822
- watch(null)
823
- stop(last)
824
- await leaving(cleanup().then(() => forget(brain, found?.id)))
825
- }
826
- })()
827
- return turn
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() }
828
940
  }
829
941
 
830
942
  // ---- turns waiting on the client's tool
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.6",
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",