@magpie-community/opencode-agy-tui-auth 0.1.4 → 0.1.6

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/index.mjs CHANGED
@@ -6,7 +6,8 @@ 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
+ import { mcpToolsOf } from "./tools.mjs"
10
11
 
11
12
  // agy-tui: Antigravity's models through agy's own interactive mode. Each
12
13
  // request starts the real `agy` TUI in a terminal magpie gives it (`magpie
@@ -20,8 +21,12 @@ import { liveText } from "./live.mjs"
20
21
  // user's own ~/.gemini, skills and MCP servers are never used. agy runs
21
22
  // on its default agent (default-agent.mjs; a custom agent's session costs
22
23
  // about four times the quota from agy 1.5.17, plugins#1684), told to answer
23
- // in text, with a tool gate that turns every one of agy's tools down: it
24
- // answers in text; the caller's tools are not offered to the model. A
24
+ // in text, with a tool gate that turns every one of agy's tools down. The
25
+ // caller's tools (a request's `tools`) are given to agy through magpie's
26
+ // tool server (`magpie mcp-helper`, started by tui-helper): a call the
27
+ // model makes ends the response with that tool call, and agy waits, its
28
+ // turn parked, until the request with the call's result answers it and
29
+ // the reply goes on (startTurn, park). A
25
30
  // request's images and videos are written to the turn's folder and their
26
31
  // paths pasted into the prompt before its text, which agy attaches as it
27
32
  // does a file dragged onto its terminal; a file agy can't attach (a PDF,
@@ -33,8 +38,26 @@ const NPM = "@ai-sdk/openai-compatible"
33
38
  // what the session's AGENTS.md says; its tool gate allows nothing
34
39
  const INSTRUCTIONS = "Answer in text. Every tool is turned off in this session."
35
40
  const AGY_MANUAL = "https://antigravity.google/docs/cli"
41
+ // with the caller's tools: agy's own stay off, and the caller's come as
42
+ // functions agy names mcp_magpie_<name> (its MCP server's name and the
43
+ // tool's), each the tool the conversation calls <name>
44
+ const MCP_SERVER = "magpie"
45
+ const MCP_FUNCTIONS = `mcp_${MCP_SERVER}_*`
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.`
36
47
 
37
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
57
+ export async function settled() {
58
+ while (going.size) await Promise.allSettled([...going])
59
+ }
60
+
38
61
  export const READY = "? for shortcuts"
39
62
  export const BUSY = "esc to cancel"
40
63
 
@@ -53,6 +76,19 @@ const PASTE_SETTLE_MS = 300
53
76
  const IDLE_MS = 5_000
54
77
  // how often a running turn's reply is read from agy's store (live.mjs)
55
78
  const LIVE_POLL_MS = 100
79
+ // how long agy waits for a call of the caller's tool, which the client
80
+ // runs: as long as a turn waits for its result (parkTimeout) and more
81
+ const MCP_CALL_SECONDS = 3600
82
+ // agy lists the tools as it starts, before its prompt shows
83
+ const LISTED_MS = 20_000
84
+ // how many turns may wait on a call's result at once
85
+ const MAX_PARKED = 8
86
+
87
+ // how long a turn waits for the request with a call's result
88
+ function parkTimeout() {
89
+ const n = Number(process.env.AGY_TUI_PARK_TIMEOUT_MS)
90
+ return Number.isFinite(n) && n > 0 ? n : 10 * 60_000
91
+ }
56
92
 
57
93
  function attachTimeout() {
58
94
  const n = Number(process.env.AGY_TUI_ATTACH_TIMEOUT_MS)
@@ -330,6 +366,9 @@ function partsOf(content, media) {
330
366
  // turnOf is what goes into agy's prompt: the images and videos, attached in
331
367
  // the order they came, and the text pasted after them, the last user
332
368
  // message alone, or with the instructions and the conversation before it.
369
+ // The conversation's tool calls and results are written in, as what was
370
+ // done: a turn that carries on after a call is typed in whole when no agy
371
+ // waits on that call any more (parked).
333
372
  // A file magpie could only name in words (ATTACHMENT_NOTE) in the last
334
373
  // user message is refused: the model would be told of a file it can't
335
374
  // see. One in an earlier turn stays, as what was said then.
@@ -343,21 +382,26 @@ export function turnOf(messages) {
343
382
  const text = partsOf(m?.content, media).trim()
344
383
  if (text) system.push(text)
345
384
  } else if (m?.role === "user" || m?.role === "assistant") {
346
- const text = partsOf(m?.content, media).trim()
385
+ const said = [partsOf(m?.content, media).trim()]
386
+ if (m.role === "assistant" && Array.isArray(m.tool_calls)) {
387
+ for (const c of m.tool_calls) said.push(`[called ${c?.function?.name ?? "a tool"} ${c?.function?.arguments || "{}"} as ${c?.id ?? "a call"}]`)
388
+ }
389
+ const text = said.filter(Boolean).join("\n")
347
390
  if (text) turns.push({ role: m.role, text })
348
391
  } else if (m?.role === "tool") {
349
- throw refuse("agy-tui runs no tools: the conversation has a tool result")
392
+ turns.push({ role: "tool", text: `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}` })
350
393
  }
351
394
  }
352
- if (!turns.length || turns.at(-1).role !== "user") throw refuse("the last message is not the user's")
395
+ if (!turns.length || turns.at(-1).role === "assistant") throw refuse("the last message is not the user's or a tool's result")
353
396
  const note = ATTACHMENT_NOTE.exec(turns.at(-1).text)
354
397
  if (note) throw refuse(`${TAKES}; the message has ${named(note[1])}`)
355
- if (!system.length && turns.length === 1) return { prompt: turns[0].text, media }
398
+ if (!system.length && turns.length === 1 && turns[0].role === "user") return { prompt: turns[0].text, media }
356
399
  const parts = []
400
+ const said = (t) => `${{ user: "User", assistant: "Assistant", tool: "Tool" }[t.role]}: ${t.text}`
357
401
  if (system.length) parts.push(system.join("\n\n"))
358
- if (turns.length > 1) {
359
- parts.push(turns.slice(0, -1).map((t) => `${t.role === "user" ? "User" : "Assistant"}: ${t.text}`).join("\n\n"))
360
- parts.push(`User: ${turns.at(-1).text}`)
402
+ if (turns.length > 1 || turns[0].role !== "user") {
403
+ parts.push(turns.slice(0, -1).map(said).join("\n\n"))
404
+ parts.push(said(turns.at(-1)))
361
405
  } else {
362
406
  parts.push(turns[0].text)
363
407
  }
@@ -461,45 +505,146 @@ class Failure extends Error {
461
505
  }
462
506
  }
463
507
 
508
+ // sessionHome makes dir the HOME of one turn that has the caller's tools:
509
+ // the account's home linked in, entry by entry, but for .gemini/config,
510
+ // which is the turn's own, so the MCP server in its mcp_config.json (which
511
+ // agy reads again when the file changes) is this turn's alone while other
512
+ // turns of the account run beside it. agy's sign-in, conversations and
513
+ // caches stay the account's, through the links. On Windows a folder is a
514
+ // junction and a file a copy (a symbolic link to a file needs a privilege).
515
+ // The links are made before the turn's terminal starts, the tool server's
516
+ // config (mcp_config.json, from mcpConfig) once it is known.
517
+ export function sessionHome(home, dir, platform = process.platform) {
518
+ const link = (from, to) => {
519
+ if (fs.existsSync(to)) return
520
+ let folder
521
+ try { folder = fs.statSync(from).isDirectory() } catch { return }
522
+ if (platform === "win32" && !folder) return fs.copyFileSync(from, to)
523
+ fs.symlinkSync(from, to, folder ? "junction" : "file")
524
+ }
525
+ const each = (from, to, skip) => {
526
+ let names = []
527
+ try { names = fs.readdirSync(from) } catch {}
528
+ for (const name of names) if (name !== skip) link(path.join(from, name), path.join(to, name))
529
+ }
530
+ fs.mkdirSync(path.join(dir, ".gemini", "config"), { recursive: true, mode: 0o700 })
531
+ each(home, dir, ".gemini")
532
+ each(path.join(home, ".gemini"), path.join(dir, ".gemini"), "config")
533
+ each(path.join(home, ".gemini", "config"), path.join(dir, ".gemini", "config"), "mcp_config.json")
534
+ }
535
+
536
+ // mcpConfig is agy's mcp_config.json for the tool server magpie started
537
+ // (`mcp`, from tui-helper): every tool eager, so the model has it as a
538
+ // function from the first message (a lazy one would have to be looked up
539
+ // through agy's own tools, which are off), and a call may wait as long as
540
+ // the client takes to run it.
541
+ export function mcpConfig(mcp, tools) {
542
+ return {
543
+ mcpServers: {
544
+ [MCP_SERVER]: {
545
+ command: mcp.command,
546
+ args: mcp.args,
547
+ disabled: false,
548
+ env: {},
549
+ timeoutSeconds: MCP_CALL_SECONDS,
550
+ tools: Object.fromEntries(tools.map((t) => [t.name, { eager: true }])),
551
+ },
552
+ },
553
+ }
554
+ }
555
+
464
556
  // startTurn starts agy in its terminal and types the prompt; it resolves
465
- // once agy has the message, with `answer`, a promise of its reply.
466
- export async function startTurn({ agy, home, model, prompt, media = [], signal, helper = process.env.MAGPIE_EXE }) {
557
+ // once agy has the message, with the turn: `next()` is what it comes to
558
+ // next, a call of one of the caller's tools ({call}), the end ({text}) or
559
+ // a failure ({error}); `live` is the reply as agy's model writes it, and
560
+ // `sent` what of it the client has had. A call is answered with
561
+ // `reply(id, content)`, and the turn goes on to its next stop. With tools
562
+ // (MCP tools: name, description, inputSchema), agy is given them through
563
+ // magpie's tool server, in a HOME of the turn's own (sessionHome), and its
564
+ // own tools stay off.
565
+ export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE }) {
467
566
  if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
468
567
  settleHome(home)
568
+ const withTools = tools.length > 0
469
569
  const ws = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-")))
470
570
  // agy's default agent, never --agent: the instructions in AGENTS.md, agy's
471
- // bundled skills left out, and a PreToolUse hook that denies every tool
472
- // call (what the old agent's `tools: []` did)
571
+ // bundled skills left out, and a PreToolUse hook that denies every call of
572
+ // agy's own tools (what the old agent's `tools: []` did); with tools, the
573
+ // caller's are let through
473
574
  let hookEnv
474
575
  let files
576
+ let ownHome = null
475
577
  try {
476
- hookEnv = await writeDefaultAgentFiles(ws, { instructions: INSTRUCTIONS, allowed: [], geminiDir: path.join(home, ".gemini") })
578
+ hookEnv = await writeDefaultAgentFiles(ws, {
579
+ instructions: withTools ? TOOL_INSTRUCTIONS : INSTRUCTIONS,
580
+ allowed: withTools ? [MCP_FUNCTIONS] : [],
581
+ geminiDir: path.join(home, ".gemini"),
582
+ })
477
583
  // the images and videos, in the turn's folder: agy copies each one it
478
584
  // attaches into the conversation's own (forget removes it), and the
479
585
  // folder goes with the turn
480
586
  files = writeMedia(path.join(ws, "attachments"), media)
587
+ if (withTools) {
588
+ ownHome = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-home-")))
589
+ sessionHome(home, ownHome)
590
+ }
481
591
  } catch (error) {
482
592
  fs.rmSync(ws, { recursive: true, force: true })
593
+ if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
483
594
  throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
484
595
  }
485
596
  const brain = path.join(home, ".gemini", "antigravity-cli", "brain")
486
597
  let before
487
598
  try { before = new Set(fs.readdirSync(brain)) } catch { before = new Set() }
488
599
 
489
- // the folder is trusted for this session only (never saved)
600
+ // the folder is trusted for this session only (never saved); the
601
+ // caller's tools run without agy asking at its prompt
490
602
  const settings = { trustedWorkspaces: [ws] }
603
+ if (withTools) settings.permissions = { allow: [`mcp(${MCP_SERVER}/*)`] }
491
604
  const args = ["--settings", JSON.stringify(settings)]
492
605
  // agy's own default customizations stay out, as the old agent's
493
606
  // inheritCustomizations: false kept them
494
607
  if ((await agyHelp(agy)).includes("--include-default-customizations")) args.push("--include-default-customizations=false")
495
608
  if (model) args.push("--model", model)
496
- const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
609
+ const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
497
610
  let screen = ""
498
611
  let ended = null
499
612
  let errorLine = ""
500
613
  let stderr = ""
614
+ let mcp = null
615
+ let listed = false
501
616
  const waiters = new Set()
502
617
  const poke = () => { for (const w of waiters) w() }
618
+
619
+ // the turn's stops, in order, for next()
620
+ const stops = []
621
+ let wake = null
622
+ const stop = (s) => {
623
+ stops.push(s)
624
+ const w = wake
625
+ wake = null
626
+ w?.()
627
+ }
628
+ // the calls agy waits on, by id; one it stopped waiting for can't be
629
+ // answered
630
+ const pending = new Set()
631
+ let found = null
632
+ const look = () => {
633
+ found = answerOf(brain, before, prompt, found?.id)
634
+ if (found?.id) claimed.add(found.id)
635
+ }
636
+ // what the model has said so far, its text and its thinking, from agy's
637
+ // conversation store (live.mjs), for a stream to send as it comes
638
+ const live = { text: "", thinking: "", listeners: new Set() }
639
+ const publish = (reply) => {
640
+ let grew = false
641
+ for (const k of ["text", "thinking"]) {
642
+ const v = reply?.[k]
643
+ if (typeof v === "string" && v.length > live[k].length) { live[k] = v; grew = true }
644
+ }
645
+ if (grew) for (const fn of live.listeners) fn()
646
+ }
647
+
503
648
  let buf = ""
504
649
  child.stdout.setEncoding("utf8").on("data", (d) => {
505
650
  buf += d
@@ -512,6 +657,16 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
512
657
  if (typeof o.screen === "string") screen = o.screen
513
658
  if (o.error) errorLine = o.error
514
659
  if (o.exit) ended = o.exit
660
+ if (o.mcp) mcp = o.mcp
661
+ if (o.listed) listed = true
662
+ if (o.call?.id) {
663
+ // what the model wrote before the call goes first
664
+ pending.add(o.call.id)
665
+ if (!found?.id) look()
666
+ if (found?.id) publish(liveReply(home, found.id))
667
+ stop({ call: o.call })
668
+ }
669
+ if (o.dropped) pending.delete(o.dropped)
515
670
  }
516
671
  poke()
517
672
  })
@@ -529,29 +684,56 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
529
684
  const late = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 5000)
530
685
  await closed
531
686
  clearTimeout(late)
687
+ // the links in it go, never what they point to
688
+ if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
532
689
  if (process.env.AGY_TUI_KEEP) return
533
690
  fs.rmSync(ws, { recursive: true, force: true })
534
691
  }
692
+ // the request the turn answers now: its end, before the turn's, ends it
693
+ let sig = null
535
694
  const onAbort = () => { cleanup() }
536
- signal?.addEventListener?.("abort", onAbort, { once: true })
695
+ const watch = (s) => {
696
+ sig?.removeEventListener?.("abort", onAbort)
697
+ sig = s ?? null
698
+ sig?.addEventListener?.("abort", onAbort, { once: true })
699
+ if (sig?.aborted) onAbort()
700
+ }
701
+ watch(signal)
537
702
 
703
+ // waitFor resolves once ok() holds; ms is how long it may take, or a
704
+ // function giving the time it must hold by
538
705
  const waitFor = (what, ok, ms) => new Promise((resolve, reject) => {
706
+ const end = typeof ms === "function" ? ms : ((at) => () => at)(Date.now() + ms)
707
+ const secs = Math.round((typeof ms === "function" ? turnTimeout() : ms) / 1000)
539
708
  const check = () => {
540
709
  if (ok()) return done(resolve)
541
- if (signal?.aborted) return done(() => reject(new Failure(499, "the request was cancelled")))
710
+ if (sig?.aborted) return done(() => reject(new Failure(499, "the request was cancelled")))
542
711
  if (ended) return done(() => reject(new Failure(502, `agy ended ${what}: ${errorLine || ended.error || `exit ${ended.code}`}${screenTail(screen) ? `\n${screenTail(screen)}` : ""}`)))
712
+ if (Date.now() > end()) return done(() => reject(new Failure(504, `agy: no ${what} in ${secs}s${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)))
543
713
  }
544
- const timer = setTimeout(() => done(() => reject(new Failure(504, `agy: no ${what} in ${Math.round(ms / 1000)}s${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`))), ms)
545
714
  const tick = setInterval(check, 250)
546
- const done = (f) => { clearTimeout(timer); clearInterval(tick); waiters.delete(check); f() }
715
+ const done = (f) => { clearInterval(tick); waiters.delete(check); f() }
547
716
  waiters.add(check)
548
717
  check()
549
718
  })
550
719
  const ready = () => screen.includes(READY) && !screen.includes(BUSY)
551
720
 
552
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`)
730
+ }
731
+ fs.writeFileSync(path.join(ownHome, ".gemini", "config", "mcp_config.json"), JSON.stringify(mcpConfig(mcp, tools)), { mode: 0o600 })
732
+ }
553
733
  send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
554
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)
555
737
  if (files.length) {
556
738
  // pasted alone, the paths are attached, as files dragged onto the
557
739
  // terminal are; the turn waits until agy shows every one attached,
@@ -575,32 +757,49 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
575
757
  throw error
576
758
  }
577
759
 
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)
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(),
585
779
  }
586
- const answer = (async () => {
587
- let found = null
780
+
781
+ ;(async () => {
782
+ let last
588
783
  let polled = 0
589
- const look = () => {
590
- found = answerOf(brain, before, prompt, found?.id)
591
- if (found?.id) claimed.add(found.id)
592
- }
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()
593
787
  try {
594
788
  // back at its prompt with nothing in the transcript for a while:
595
789
  // the turn failed, and what agy drew says why (a quota, a refusal)
596
790
  let idleSince = 0
597
791
  await waitFor("answer", () => {
792
+ if (pending.size) {
793
+ until = Date.now() + turnTimeout()
794
+ idleSince = 0
795
+ return false
796
+ }
598
797
  if (!ready()) {
599
798
  idleSince = 0
600
799
  if (Date.now() - polled >= LIVE_POLL_MS) {
601
800
  polled = Date.now()
602
801
  if (!found?.id) look()
603
- if (found?.id) publish(liveText(home, found.id))
802
+ if (found?.id) publish(liveReply(home, found.id))
604
803
  }
605
804
  return false
606
805
  }
@@ -608,17 +807,75 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
608
807
  if (found?.answer) return true
609
808
  idleSince ||= Date.now()
610
809
  return Date.now() - idleSince > IDLE_MS
611
- }, turnTimeout())
810
+ }, () => until)
612
811
  if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
613
812
  // the whole of it, read before the conversation goes
614
- publish(liveText(home, found.id))
615
- return found.answer
813
+ publish(liveReply(home, found.id))
814
+ last = { text: found.answer }
815
+ } catch (error) {
816
+ last = { error }
616
817
  } finally {
617
- await cleanup()
618
- forget(brain, found?.id)
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)))
619
825
  }
620
826
  })()
621
- return { answer, live }
827
+ return turn
828
+ }
829
+
830
+ // ---- turns waiting on the client's tool
831
+
832
+ // A turn that stopped at a call waits, its agy running, for the request
833
+ // that brings the call's result (by the call's id). One left waiting past
834
+ // parkTimeout, or pushed out by newer ones past MAX_PARKED, ends; its
835
+ // result, when it comes, starts a turn of its own, with the conversation
836
+ // typed in as text.
837
+ const parked = new Map()
838
+
839
+ function park(id, turn) {
840
+ const timer = setTimeout(() => {
841
+ if (parked.get(id)?.turn !== turn) return
842
+ parked.delete(id)
843
+ turn.close()
844
+ }, parkTimeout())
845
+ timer.unref?.()
846
+ parked.set(id, { turn, timer })
847
+ while (parked.size > MAX_PARKED) {
848
+ const [oldest, p] = parked.entries().next().value
849
+ parked.delete(oldest)
850
+ clearTimeout(p.timer)
851
+ p.turn.close()
852
+ }
853
+ }
854
+
855
+ function unpark(id) {
856
+ const p = typeof id === "string" ? parked.get(id) : null
857
+ if (!p) return null
858
+ parked.delete(id)
859
+ clearTimeout(p.timer)
860
+ return p.turn
861
+ }
862
+
863
+ // toolContent is a tool message's content as the tool server answers it: a
864
+ // string, or MCP content blocks (text, and an image given as data).
865
+ export function toolContent(content) {
866
+ if (typeof content === "string") return content
867
+ if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content)
868
+ const blocks = []
869
+ for (const part of content) {
870
+ if (part?.type === "text" || part?.type === "input_text") blocks.push({ type: "text", text: part.text ?? "" })
871
+ else if (part?.type === "image_url" || part?.type === "input_image") {
872
+ const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url
873
+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(String(url ?? ""))
874
+ if (!m) throw refuse("a tool result's image goes to agy as data, not a link")
875
+ blocks.push({ type: "image", data: m[2], mimeType: m[1] })
876
+ } else if (part?.type) throw refuse(`a tool result's ${part.type} part can't go to agy`)
877
+ }
878
+ return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
622
879
  }
623
880
 
624
881
  // forget removes the conversation agy kept for a turn from the account's
@@ -643,49 +900,89 @@ function jsonError(status, message, headers = {}) {
643
900
  })
644
901
  }
645
902
 
646
- function completion(id, model, text) {
903
+ const toolCallOf = (call, index) => ({ ...(index === undefined ? {} : { index }), id: call.id, type: "function", function: { name: call.name, arguments: JSON.stringify(call.arguments ?? {}) } })
904
+
905
+ // since is what of text is new to this response: past what the turn's
906
+ // earlier responses had (`had`, the text's by default), without the break
907
+ // before it
908
+ function since(turn, text, had = turn.sent) {
909
+ return text.startsWith(had) ? text.slice(had.length).replace(/^\n+/, "") : ""
910
+ }
911
+
912
+ // stopped ends a response at a call: the turn waits for its result
913
+ function stopped(turn, call) {
914
+ turn.watch(null)
915
+ turn.sent = turn.live.text
916
+ turn.thought = turn.live.thinking
917
+ park(call.id, turn)
918
+ }
919
+
920
+ function completion(id, model, message, finish) {
647
921
  return {
648
922
  id,
649
923
  object: "chat.completion",
650
924
  created: Math.floor(Date.now() / 1000),
651
925
  model,
652
- choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }],
926
+ choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }],
927
+ }
928
+ }
929
+
930
+ // answered is the turn's next stop as one completion.
931
+ async function answered(id, model, turn) {
932
+ const s = await turn.next()
933
+ if (s.error) throw s.error
934
+ const thinking = since(turn, turn.live.thinking, turn.thought)
935
+ const reasoning = thinking ? { reasoning_content: thinking } : {}
936
+ if (s.call) {
937
+ const text = since(turn, turn.live.text)
938
+ stopped(turn, s.call)
939
+ return completion(id, model, { content: text || null, ...reasoning, tool_calls: [toolCallOf(s.call)] }, "tool_calls")
653
940
  }
941
+ return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop")
654
942
  }
655
943
 
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.
944
+ // streamOf sends the turn's reply up to its next stop as agy's model
945
+ // writes it (turn.live), each piece once; at the end, what the store has
946
+ // whole, or, with nothing read from it, the transcript's answer; at a call,
947
+ // the call.
659
948
  export function streamOf(id, model, turn) {
660
- const { answer, live } = turn
949
+ const { live } = turn
661
950
  const enc = new TextEncoder()
662
951
  const created = Math.floor(Date.now() / 1000)
663
952
  const chunk = (delta, finish = null) => `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`
664
953
  let keep
665
954
  let listen
666
955
  let quiet = 0
667
- const stop = () => {
956
+ const halt = () => {
668
957
  clearInterval(keep)
669
- if (listen) live?.listeners.delete(listen)
958
+ if (listen) live.listeners.delete(listen)
670
959
  }
671
960
  return new ReadableStream({
672
961
  async start(c) {
673
962
  let sent = ""
963
+ let thought = ""
674
964
  // 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
965
+ // left to the end. The thinking goes as it comes, as
966
+ // reasoning_content, so a model that thinks a while before its first
967
+ // word shows it from the first thought
968
+ const send = () => {
969
+ const think = since(turn, live.thinking, turn.thought)
970
+ if (think.length > thought.length && think.startsWith(thought)) {
971
+ try { c.enqueue(enc.encode(chunk({ reasoning_content: think.slice(thought.length) }))) } catch { return }
972
+ thought = think
973
+ quiet = Date.now()
974
+ }
975
+ const full = since(turn, live.text)
976
+ if (full.length <= sent.length || !full.startsWith(sent)) return
977
+ try { c.enqueue(enc.encode(chunk({ content: full.slice(sent.length) }))) } catch { return }
978
+ sent = full
680
979
  quiet = Date.now()
681
980
  }
682
981
  c.enqueue(enc.encode(chunk({ role: "assistant", content: "" })))
683
982
  quiet = Date.now()
684
- if (live) {
685
- listen = send
686
- live.listeners.add(listen)
687
- send(live.text)
688
- }
983
+ listen = send
984
+ live.listeners.add(listen)
985
+ send()
689
986
  // the turn may take minutes before its first word: a comment now
690
987
  // and then keeps the connection from looking dead
691
988
  keep = setInterval(() => {
@@ -694,22 +991,38 @@ export function streamOf(id, model, turn) {
694
991
  quiet = Date.now()
695
992
  }, 5_000)
696
993
  try {
697
- const text = await answer
698
- stop()
699
- send(live?.text || text)
700
- c.enqueue(enc.encode(chunk({}, "stop")))
994
+ const s = await turn.next()
995
+ halt()
996
+ if (s.error) throw s.error
997
+ send()
998
+ if (s.call) {
999
+ stopped(turn, s.call)
1000
+ c.enqueue(enc.encode(chunk({ tool_calls: [toolCallOf(s.call, 0)] })))
1001
+ c.enqueue(enc.encode(chunk({}, "tool_calls")))
1002
+ } else {
1003
+ if (!sent && s.text) c.enqueue(enc.encode(chunk({ content: s.text })))
1004
+ c.enqueue(enc.encode(chunk({}, "stop")))
1005
+ }
701
1006
  } catch (error) {
702
1007
  c.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: error.message, type: "agy_tui_error" } })}\n\n`))
703
1008
  } finally {
704
- stop()
1009
+ halt()
705
1010
  }
706
1011
  c.enqueue(enc.encode("data: [DONE]\n\n"))
707
1012
  c.close()
708
1013
  },
709
- cancel() { stop() },
1014
+ cancel() { halt() },
710
1015
  })
711
1016
  }
712
1017
 
1018
+ function respond(id, model, turn, stream) {
1019
+ if (stream) return new Response(streamOf(id, model, turn), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
1020
+ return answered(id, model, turn).then(
1021
+ (body) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }),
1022
+ (error) => jsonError(error.status ?? 502, error.message),
1023
+ )
1024
+ }
1025
+
713
1026
  export async function handle(home, input, init = {}) {
714
1027
  const url = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url || ""
715
1028
  if (!/\/chat\/completions(?:$|[?#])/.test(url)) return jsonError(404, `agy-tui serves chat completions, not ${url}`)
@@ -720,32 +1033,45 @@ export async function handle(home, input, init = {}) {
720
1033
  } catch {
721
1034
  return jsonError(400, "the request is not JSON")
722
1035
  }
1036
+ const signal = init.signal ?? input?.signal
1037
+ const id = `chatcmpl-${randomBytes(12).toString("hex")}`
1038
+ const model = String(body.model ?? "")
1039
+ // the result of a call a turn waits on goes on with that turn
1040
+ const last = Array.isArray(body.messages) ? body.messages.at(-1) : null
1041
+ if (last?.role === "tool") {
1042
+ const waiting = unpark(last.tool_call_id)
1043
+ if (waiting && !waiting.ended) {
1044
+ let content
1045
+ try { content = toolContent(last.content) } catch (error) {
1046
+ waiting.close()
1047
+ return jsonError(error.status ?? 400, error.message)
1048
+ }
1049
+ if (waiting.reply(last.tool_call_id, content)) {
1050
+ waiting.watch(signal)
1051
+ return respond(id, model, waiting, body.stream)
1052
+ }
1053
+ }
1054
+ // agy no longer waits on it: a turn of its own, the conversation
1055
+ // typed in as text
1056
+ waiting?.close()
1057
+ }
723
1058
  if (!home) return jsonError(401, "agy-tui: no account; sign in again", { "X-Magpie-Sign-In": "expired" })
724
1059
  if (!fs.existsSync(tokenFile(home))) return jsonError(401, "agy-tui: the account's agy is signed out; sign in again", { "X-Magpie-Sign-In": "expired" })
725
1060
  const agy = findAgy()
726
1061
  if (!agy) return jsonError(503, `agy CLI not found on this machine: ${AGY_MANUAL}`)
727
1062
  const refusal = await agyRefusal(agy)
728
1063
  if (refusal) return jsonError(503, refusal)
729
- const signal = init.signal ?? input?.signal
730
- const id = `chatcmpl-${randomBytes(12).toString("hex")}`
731
- const model = String(body.model ?? "")
732
1064
  let turn
733
1065
  try {
1066
+ const tools = mcpToolsOf(body)
734
1067
  const { prompt, media } = turnOf(body.messages)
735
1068
  // agy attaches a video for any model, but only Gemini's see one
736
1069
  if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
737
- turn = await startTurn({ agy, home, model, prompt, media, signal })
1070
+ turn = await startTurn({ agy, home, model, prompt, media, tools, signal })
738
1071
  } catch (error) {
739
1072
  return jsonError(error.status ?? 502, error.message, error.headers)
740
1073
  }
741
- if (body.stream) {
742
- return new Response(streamOf(id, model, turn), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
743
- }
744
- try {
745
- return new Response(JSON.stringify(completion(id, model, await turn.answer)), { status: 200, headers: { "Content-Type": "application/json" } })
746
- } catch (error) {
747
- return jsonError(error.status ?? 502, error.message)
748
- }
1074
+ return respond(id, model, turn, body.stream)
749
1075
  }
750
1076
 
751
1077
  // ---- the plugin