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

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,6 +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"
10
+ import { mcpToolsOf } from "./tools.mjs"
9
11
 
10
12
  // agy-tui: Antigravity's models through agy's own interactive mode. Each
11
13
  // request starts the real `agy` TUI in a terminal magpie gives it (`magpie
@@ -19,8 +21,12 @@ import { agyTooOld, MIN_AGY_VERSION } from "./agy-version.mjs"
19
21
  // user's own ~/.gemini, skills and MCP servers are never used. agy runs
20
22
  // on its default agent (default-agent.mjs; a custom agent's session costs
21
23
  // about four times the quota from agy 1.5.17, plugins#1684), told to answer
22
- // in text, with a tool gate that turns every one of agy's tools down: it
23
- // 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
24
30
  // request's images and videos are written to the turn's folder and their
25
31
  // paths pasted into the prompt before its text, which agy attaches as it
26
32
  // does a file dragged onto its terminal; a file agy can't attach (a PDF,
@@ -32,6 +38,12 @@ const NPM = "@ai-sdk/openai-compatible"
32
38
  // what the session's AGENTS.md says; its tool gate allows nothing
33
39
  const INSTRUCTIONS = "Answer in text. Every tool is turned off in this session."
34
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.`
35
47
 
36
48
  // What agy 1.5's footer says: waiting for a message, and in a turn.
37
49
  export const READY = "? for shortcuts"
@@ -50,6 +62,21 @@ const PASTE_SETTLE_MS = 300
50
62
  // how long agy may sit at its prompt after a turn before the transcript has
51
63
  // its answer
52
64
  const IDLE_MS = 5_000
65
+ // how often a running turn's reply is read from agy's store (live.mjs)
66
+ const LIVE_POLL_MS = 100
67
+ // how long agy waits for a call of the caller's tool, which the client
68
+ // runs: as long as a turn waits for its result (parkTimeout) and more
69
+ const MCP_CALL_SECONDS = 3600
70
+ // agy lists the tools as it starts, before its prompt shows
71
+ const LISTED_MS = 20_000
72
+ // how many turns may wait on a call's result at once
73
+ const MAX_PARKED = 8
74
+
75
+ // how long a turn waits for the request with a call's result
76
+ function parkTimeout() {
77
+ const n = Number(process.env.AGY_TUI_PARK_TIMEOUT_MS)
78
+ return Number.isFinite(n) && n > 0 ? n : 10 * 60_000
79
+ }
53
80
 
54
81
  function attachTimeout() {
55
82
  const n = Number(process.env.AGY_TUI_ATTACH_TIMEOUT_MS)
@@ -100,12 +127,22 @@ export function agyEnv(home, parent = process.env, platform = process.platform)
100
127
  }
101
128
 
102
129
  // 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) {
130
+ // passed once its sign-in took. `agy models`, run to list the models before
131
+ // any turn, writes the file with every step not done, so a file that is
132
+ // there is brought up too; its other keys are kept.
133
+ export function settleHome(home) {
105
134
  const file = path.join(home, ".gemini", "antigravity-cli", "cache", "onboarding.json")
106
- if (fs.existsSync(file)) return
135
+ let state = {}
136
+ try {
137
+ const read = JSON.parse(fs.readFileSync(file, "utf8"))
138
+ if (read && typeof read === "object" && !Array.isArray(read)) state = read
139
+ } catch {}
140
+ if (state.consumerOnboardingComplete === true && state.onboardingComplete === true) return
141
+ state = { ...state, consumerOnboardingComplete: true, onboardingComplete: true }
107
142
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
108
- fs.writeFileSync(file, JSON.stringify({ consumerOnboardingComplete: true, onboardingComplete: true }), { mode: 0o600 })
143
+ const tmp = `${file}.${process.pid}.tmp`
144
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 })
145
+ fs.renameSync(tmp, file)
109
146
  }
110
147
 
111
148
  // ---- agy
@@ -317,6 +354,9 @@ function partsOf(content, media) {
317
354
  // turnOf is what goes into agy's prompt: the images and videos, attached in
318
355
  // the order they came, and the text pasted after them, the last user
319
356
  // message alone, or with the instructions and the conversation before it.
357
+ // The conversation's tool calls and results are written in, as what was
358
+ // done: a turn that carries on after a call is typed in whole when no agy
359
+ // waits on that call any more (parked).
320
360
  // A file magpie could only name in words (ATTACHMENT_NOTE) in the last
321
361
  // user message is refused: the model would be told of a file it can't
322
362
  // see. One in an earlier turn stays, as what was said then.
@@ -330,21 +370,26 @@ export function turnOf(messages) {
330
370
  const text = partsOf(m?.content, media).trim()
331
371
  if (text) system.push(text)
332
372
  } else if (m?.role === "user" || m?.role === "assistant") {
333
- const text = partsOf(m?.content, media).trim()
373
+ const said = [partsOf(m?.content, media).trim()]
374
+ if (m.role === "assistant" && Array.isArray(m.tool_calls)) {
375
+ for (const c of m.tool_calls) said.push(`[called ${c?.function?.name ?? "a tool"} ${c?.function?.arguments || "{}"} as ${c?.id ?? "a call"}]`)
376
+ }
377
+ const text = said.filter(Boolean).join("\n")
334
378
  if (text) turns.push({ role: m.role, text })
335
379
  } else if (m?.role === "tool") {
336
- throw refuse("agy-tui runs no tools: the conversation has a tool result")
380
+ turns.push({ role: "tool", text: `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}` })
337
381
  }
338
382
  }
339
- if (!turns.length || turns.at(-1).role !== "user") throw refuse("the last message is not the user's")
383
+ if (!turns.length || turns.at(-1).role === "assistant") throw refuse("the last message is not the user's or a tool's result")
340
384
  const note = ATTACHMENT_NOTE.exec(turns.at(-1).text)
341
385
  if (note) throw refuse(`${TAKES}; the message has ${named(note[1])}`)
342
- if (!system.length && turns.length === 1) return { prompt: turns[0].text, media }
386
+ if (!system.length && turns.length === 1 && turns[0].role === "user") return { prompt: turns[0].text, media }
343
387
  const parts = []
388
+ const said = (t) => `${{ user: "User", assistant: "Assistant", tool: "Tool" }[t.role]}: ${t.text}`
344
389
  if (system.length) parts.push(system.join("\n\n"))
345
- if (turns.length > 1) {
346
- parts.push(turns.slice(0, -1).map((t) => `${t.role === "user" ? "User" : "Assistant"}: ${t.text}`).join("\n\n"))
347
- parts.push(`User: ${turns.at(-1).text}`)
390
+ if (turns.length > 1 || turns[0].role !== "user") {
391
+ parts.push(turns.slice(0, -1).map(said).join("\n\n"))
392
+ parts.push(said(turns.at(-1)))
348
393
  } else {
349
394
  parts.push(turns[0].text)
350
395
  }
@@ -448,45 +493,143 @@ class Failure extends Error {
448
493
  }
449
494
  }
450
495
 
496
+ // sessionHome makes dir the HOME of one turn that has the caller's tools:
497
+ // the account's home linked in, entry by entry, but for .gemini/config,
498
+ // which is the turn's own, so the MCP server in its mcp_config.json (which
499
+ // agy reads again when the file changes) is this turn's alone while other
500
+ // turns of the account run beside it. agy's sign-in, conversations and
501
+ // caches stay the account's, through the links. On Windows a folder is a
502
+ // junction and a file a copy (a symbolic link to a file needs a privilege).
503
+ // The links are made before the turn's terminal starts, the tool server's
504
+ // config (mcp_config.json, from mcpConfig) once it is known.
505
+ export function sessionHome(home, dir, platform = process.platform) {
506
+ const link = (from, to) => {
507
+ if (fs.existsSync(to)) return
508
+ let folder
509
+ try { folder = fs.statSync(from).isDirectory() } catch { return }
510
+ if (platform === "win32" && !folder) return fs.copyFileSync(from, to)
511
+ fs.symlinkSync(from, to, folder ? "junction" : "file")
512
+ }
513
+ const each = (from, to, skip) => {
514
+ let names = []
515
+ try { names = fs.readdirSync(from) } catch {}
516
+ for (const name of names) if (name !== skip) link(path.join(from, name), path.join(to, name))
517
+ }
518
+ fs.mkdirSync(path.join(dir, ".gemini", "config"), { recursive: true, mode: 0o700 })
519
+ each(home, dir, ".gemini")
520
+ each(path.join(home, ".gemini"), path.join(dir, ".gemini"), "config")
521
+ each(path.join(home, ".gemini", "config"), path.join(dir, ".gemini", "config"), "mcp_config.json")
522
+ }
523
+
524
+ // mcpConfig is agy's mcp_config.json for the tool server magpie started
525
+ // (`mcp`, from tui-helper): every tool eager, so the model has it as a
526
+ // function from the first message (a lazy one would have to be looked up
527
+ // through agy's own tools, which are off), and a call may wait as long as
528
+ // the client takes to run it.
529
+ export function mcpConfig(mcp, tools) {
530
+ return {
531
+ mcpServers: {
532
+ [MCP_SERVER]: {
533
+ command: mcp.command,
534
+ args: mcp.args,
535
+ disabled: false,
536
+ env: {},
537
+ timeoutSeconds: MCP_CALL_SECONDS,
538
+ tools: Object.fromEntries(tools.map((t) => [t.name, { eager: true }])),
539
+ },
540
+ },
541
+ }
542
+ }
543
+
451
544
  // startTurn starts agy in its terminal and types the prompt; it resolves
452
- // once agy has the message, with `answer`, a promise of its reply.
453
- export async function startTurn({ agy, home, model, prompt, media = [], signal, helper = process.env.MAGPIE_EXE }) {
545
+ // once agy has the message, with the turn: `next()` is what it comes to
546
+ // next, a call of one of the caller's tools ({call}), the end ({text}) or
547
+ // a failure ({error}); `live` is the reply as agy's model writes it, and
548
+ // `sent` what of it the client has had. A call is answered with
549
+ // `reply(id, content)`, and the turn goes on to its next stop. With tools
550
+ // (MCP tools: name, description, inputSchema), agy is given them through
551
+ // magpie's tool server, in a HOME of the turn's own (sessionHome), and its
552
+ // own tools stay off.
553
+ export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE }) {
454
554
  if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
455
555
  settleHome(home)
556
+ const withTools = tools.length > 0
456
557
  const ws = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-")))
457
558
  // agy's default agent, never --agent: the instructions in AGENTS.md, agy's
458
- // bundled skills left out, and a PreToolUse hook that denies every tool
459
- // call (what the old agent's `tools: []` did)
559
+ // bundled skills left out, and a PreToolUse hook that denies every call of
560
+ // agy's own tools (what the old agent's `tools: []` did); with tools, the
561
+ // caller's are let through
460
562
  let hookEnv
461
563
  let files
564
+ let ownHome = null
462
565
  try {
463
- hookEnv = await writeDefaultAgentFiles(ws, { instructions: INSTRUCTIONS, allowed: [], geminiDir: path.join(home, ".gemini") })
566
+ hookEnv = await writeDefaultAgentFiles(ws, {
567
+ instructions: withTools ? TOOL_INSTRUCTIONS : INSTRUCTIONS,
568
+ allowed: withTools ? [MCP_FUNCTIONS] : [],
569
+ geminiDir: path.join(home, ".gemini"),
570
+ })
464
571
  // the images and videos, in the turn's folder: agy copies each one it
465
572
  // attaches into the conversation's own (forget removes it), and the
466
573
  // folder goes with the turn
467
574
  files = writeMedia(path.join(ws, "attachments"), media)
575
+ if (withTools) {
576
+ ownHome = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-home-")))
577
+ sessionHome(home, ownHome)
578
+ }
468
579
  } catch (error) {
469
580
  fs.rmSync(ws, { recursive: true, force: true })
581
+ if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
470
582
  throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
471
583
  }
472
584
  const brain = path.join(home, ".gemini", "antigravity-cli", "brain")
473
585
  let before
474
586
  try { before = new Set(fs.readdirSync(brain)) } catch { before = new Set() }
475
587
 
476
- // the folder is trusted for this session only (never saved)
588
+ // the folder is trusted for this session only (never saved); the
589
+ // caller's tools run without agy asking at its prompt
477
590
  const settings = { trustedWorkspaces: [ws] }
591
+ if (withTools) settings.permissions = { allow: [`mcp(${MCP_SERVER}/*)`] }
478
592
  const args = ["--settings", JSON.stringify(settings)]
479
593
  // agy's own default customizations stay out, as the old agent's
480
594
  // inheritCustomizations: false kept them
481
595
  if ((await agyHelp(agy)).includes("--include-default-customizations")) args.push("--include-default-customizations=false")
482
596
  if (model) args.push("--model", model)
483
- const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
597
+ const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
484
598
  let screen = ""
485
599
  let ended = null
486
600
  let errorLine = ""
487
601
  let stderr = ""
602
+ let mcp = null
603
+ let listed = false
488
604
  const waiters = new Set()
489
605
  const poke = () => { for (const w of waiters) w() }
606
+
607
+ // the turn's stops, in order, for next()
608
+ const stops = []
609
+ let wake = null
610
+ const stop = (s) => {
611
+ stops.push(s)
612
+ const w = wake
613
+ wake = null
614
+ w?.()
615
+ }
616
+ // the calls agy waits on, by id; one it stopped waiting for can't be
617
+ // answered
618
+ const pending = new Set()
619
+ let found = null
620
+ const look = () => {
621
+ found = answerOf(brain, before, prompt, found?.id)
622
+ if (found?.id) claimed.add(found.id)
623
+ }
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)
631
+ }
632
+
490
633
  let buf = ""
491
634
  child.stdout.setEncoding("utf8").on("data", (d) => {
492
635
  buf += d
@@ -499,6 +642,16 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
499
642
  if (typeof o.screen === "string") screen = o.screen
500
643
  if (o.error) errorLine = o.error
501
644
  if (o.exit) ended = o.exit
645
+ if (o.mcp) mcp = o.mcp
646
+ if (o.listed) listed = true
647
+ if (o.call?.id) {
648
+ // what the model wrote before the call goes first
649
+ pending.add(o.call.id)
650
+ if (!found?.id) look()
651
+ if (found?.id) publish(liveText(home, found.id))
652
+ stop({ call: o.call })
653
+ }
654
+ if (o.dropped) pending.delete(o.dropped)
502
655
  }
503
656
  poke()
504
657
  })
@@ -516,29 +669,56 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
516
669
  const late = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 5000)
517
670
  await closed
518
671
  clearTimeout(late)
672
+ // the links in it go, never what they point to
673
+ if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
519
674
  if (process.env.AGY_TUI_KEEP) return
520
675
  fs.rmSync(ws, { recursive: true, force: true })
521
676
  }
677
+ // the request the turn answers now: its end, before the turn's, ends it
678
+ let sig = null
522
679
  const onAbort = () => { cleanup() }
523
- signal?.addEventListener?.("abort", onAbort, { once: true })
680
+ const watch = (s) => {
681
+ sig?.removeEventListener?.("abort", onAbort)
682
+ sig = s ?? null
683
+ sig?.addEventListener?.("abort", onAbort, { once: true })
684
+ if (sig?.aborted) onAbort()
685
+ }
686
+ watch(signal)
524
687
 
688
+ // waitFor resolves once ok() holds; ms is how long it may take, or a
689
+ // function giving the time it must hold by
525
690
  const waitFor = (what, ok, ms) => new Promise((resolve, reject) => {
691
+ const end = typeof ms === "function" ? ms : ((at) => () => at)(Date.now() + ms)
692
+ const secs = Math.round((typeof ms === "function" ? turnTimeout() : ms) / 1000)
526
693
  const check = () => {
527
694
  if (ok()) return done(resolve)
528
- if (signal?.aborted) return done(() => reject(new Failure(499, "the request was cancelled")))
695
+ if (sig?.aborted) return done(() => reject(new Failure(499, "the request was cancelled")))
529
696
  if (ended) return done(() => reject(new Failure(502, `agy ended ${what}: ${errorLine || ended.error || `exit ${ended.code}`}${screenTail(screen) ? `\n${screenTail(screen)}` : ""}`)))
697
+ if (Date.now() > end()) return done(() => reject(new Failure(504, `agy: no ${what} in ${secs}s${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)))
530
698
  }
531
- const timer = setTimeout(() => done(() => reject(new Failure(504, `agy: no ${what} in ${Math.round(ms / 1000)}s${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`))), ms)
532
699
  const tick = setInterval(check, 250)
533
- const done = (f) => { clearTimeout(timer); clearInterval(tick); waiters.delete(check); f() }
700
+ const done = (f) => { clearInterval(tick); waiters.delete(check); f() }
534
701
  waiters.add(check)
535
702
  check()
536
703
  })
537
704
  const ready = () => screen.includes(READY) && !screen.includes(BUSY)
538
705
 
539
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`)
715
+ }
716
+ fs.writeFileSync(path.join(ownHome, ".gemini", "config", "mcp_config.json"), JSON.stringify(mcpConfig(mcp, tools)), { mode: 0o600 })
717
+ }
540
718
  send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
541
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)
542
722
  if (files.length) {
543
723
  // pasted alone, the paths are attached, as files dragged onto the
544
724
  // terminal are; the turn waits until agy shows every one attached,
@@ -562,31 +742,122 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
562
742
  throw error
563
743
  }
564
744
 
565
- const answer = (async () => {
566
- let found = null
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()
567
770
  try {
568
771
  // back at its prompt with nothing in the transcript for a while:
569
772
  // the turn failed, and what agy drew says why (a quota, a refusal)
570
773
  let idleSince = 0
571
774
  await waitFor("answer", () => {
775
+ if (pending.size) {
776
+ until = Date.now() + turnTimeout()
777
+ idleSince = 0
778
+ return false
779
+ }
572
780
  if (!ready()) {
573
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
+ }
574
787
  return false
575
788
  }
576
- found = answerOf(brain, before, prompt, found?.id)
577
- if (found?.id) claimed.add(found.id)
789
+ look()
578
790
  if (found?.answer) return true
579
791
  idleSince ||= Date.now()
580
792
  return Date.now() - idleSince > IDLE_MS
581
- }, turnTimeout())
793
+ }, () => until)
582
794
  if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
583
- return found.answer
795
+ // the whole of it, read before the conversation goes
796
+ publish(liveText(home, found.id))
797
+ last = { text: found.answer }
798
+ } catch (error) {
799
+ last = { error }
584
800
  } finally {
801
+ // the end is told once the turn's files are gone
802
+ turn.ended = true
803
+ watch(null)
585
804
  await cleanup()
586
805
  forget(brain, found?.id)
806
+ stop(last)
587
807
  }
588
808
  })()
589
- return { answer }
809
+ return turn
810
+ }
811
+
812
+ // ---- turns waiting on the client's tool
813
+
814
+ // A turn that stopped at a call waits, its agy running, for the request
815
+ // that brings the call's result (by the call's id). One left waiting past
816
+ // parkTimeout, or pushed out by newer ones past MAX_PARKED, ends; its
817
+ // result, when it comes, starts a turn of its own, with the conversation
818
+ // typed in as text.
819
+ const parked = new Map()
820
+
821
+ function park(id, turn) {
822
+ const timer = setTimeout(() => {
823
+ if (parked.get(id)?.turn !== turn) return
824
+ parked.delete(id)
825
+ turn.close()
826
+ }, parkTimeout())
827
+ timer.unref?.()
828
+ parked.set(id, { turn, timer })
829
+ while (parked.size > MAX_PARKED) {
830
+ const [oldest, p] = parked.entries().next().value
831
+ parked.delete(oldest)
832
+ clearTimeout(p.timer)
833
+ p.turn.close()
834
+ }
835
+ }
836
+
837
+ function unpark(id) {
838
+ const p = typeof id === "string" ? parked.get(id) : null
839
+ if (!p) return null
840
+ parked.delete(id)
841
+ clearTimeout(p.timer)
842
+ return p.turn
843
+ }
844
+
845
+ // toolContent is a tool message's content as the tool server answers it: a
846
+ // string, or MCP content blocks (text, and an image given as data).
847
+ export function toolContent(content) {
848
+ if (typeof content === "string") return content
849
+ if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content)
850
+ const blocks = []
851
+ for (const part of content) {
852
+ if (part?.type === "text" || part?.type === "input_text") blocks.push({ type: "text", text: part.text ?? "" })
853
+ else if (part?.type === "image_url" || part?.type === "input_image") {
854
+ const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url
855
+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(String(url ?? ""))
856
+ if (!m) throw refuse("a tool result's image goes to agy as data, not a link")
857
+ blocks.push({ type: "image", data: m[2], mimeType: m[1] })
858
+ } else if (part?.type) throw refuse(`a tool result's ${part.type} part can't go to agy`)
859
+ }
860
+ return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
590
861
  }
591
862
 
592
863
  // forget removes the conversation agy kept for a turn from the account's
@@ -611,43 +882,116 @@ function jsonError(status, message, headers = {}) {
611
882
  })
612
883
  }
613
884
 
614
- function completion(id, model, text) {
885
+ const toolCallOf = (call, index) => ({ ...(index === undefined ? {} : { index }), id: call.id, type: "function", function: { name: call.name, arguments: JSON.stringify(call.arguments ?? {}) } })
886
+
887
+ // 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+/, "") : ""
891
+ }
892
+
893
+ // stopped ends a response at a call: the turn waits for its result
894
+ function stopped(turn, call) {
895
+ turn.watch(null)
896
+ turn.sent = turn.live.text
897
+ park(call.id, turn)
898
+ }
899
+
900
+ function completion(id, model, message, finish) {
615
901
  return {
616
902
  id,
617
903
  object: "chat.completion",
618
904
  created: Math.floor(Date.now() / 1000),
619
905
  model,
620
- choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }],
906
+ choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }],
621
907
  }
622
908
  }
623
909
 
624
- function streamOf(id, model, answer) {
910
+ // answered is the turn's next stop as one completion.
911
+ async function answered(id, model, turn) {
912
+ const s = await turn.next()
913
+ if (s.error) throw s.error
914
+ if (s.call) {
915
+ const text = since(turn, turn.live.text)
916
+ stopped(turn, s.call)
917
+ return completion(id, model, { content: text || null, tool_calls: [toolCallOf(s.call)] }, "tool_calls")
918
+ }
919
+ return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text }, "stop")
920
+ }
921
+
922
+ // streamOf sends the turn's reply up to its next stop as agy's model
923
+ // writes it (turn.live), each piece once; at the end, what the store has
924
+ // whole, or, with nothing read from it, the transcript's answer; at a call,
925
+ // the call.
926
+ export function streamOf(id, model, turn) {
927
+ const { live } = turn
625
928
  const enc = new TextEncoder()
626
929
  const created = Math.floor(Date.now() / 1000)
627
930
  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
931
  let keep
932
+ let listen
933
+ let quiet = 0
934
+ const halt = () => {
935
+ clearInterval(keep)
936
+ if (listen) live.listeners.delete(listen)
937
+ }
629
938
  return new ReadableStream({
630
939
  async start(c) {
940
+ let sent = ""
941
+ // 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)
945
+ if (full.length <= sent.length || !full.startsWith(sent)) return
946
+ try { c.enqueue(enc.encode(chunk({ content: full.slice(sent.length) }))) } catch { return }
947
+ sent = full
948
+ quiet = Date.now()
949
+ }
631
950
  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)
951
+ quiet = Date.now()
952
+ listen = send
953
+ live.listeners.add(listen)
954
+ send(live.text)
955
+ // the turn may take minutes before its first word: a comment now
956
+ // and then keeps the connection from looking dead
957
+ keep = setInterval(() => {
958
+ if (Date.now() - quiet < 15_000) return
959
+ try { c.enqueue(enc.encode(": working\n\n")) } catch {}
960
+ quiet = Date.now()
961
+ }, 5_000)
635
962
  try {
636
- const text = await answer
637
- c.enqueue(enc.encode(chunk({ content: text })))
638
- c.enqueue(enc.encode(chunk({}, "stop")))
963
+ const s = await turn.next()
964
+ halt()
965
+ if (s.error) throw s.error
966
+ send(live.text)
967
+ if (s.call) {
968
+ stopped(turn, s.call)
969
+ c.enqueue(enc.encode(chunk({ tool_calls: [toolCallOf(s.call, 0)] })))
970
+ c.enqueue(enc.encode(chunk({}, "tool_calls")))
971
+ } else {
972
+ if (!sent && s.text) c.enqueue(enc.encode(chunk({ content: s.text })))
973
+ c.enqueue(enc.encode(chunk({}, "stop")))
974
+ }
639
975
  } catch (error) {
640
976
  c.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: error.message, type: "agy_tui_error" } })}\n\n`))
641
977
  } finally {
642
- clearInterval(keep)
978
+ halt()
643
979
  }
644
980
  c.enqueue(enc.encode("data: [DONE]\n\n"))
645
981
  c.close()
646
982
  },
647
- cancel() { clearInterval(keep) },
983
+ cancel() { halt() },
648
984
  })
649
985
  }
650
986
 
987
+ function respond(id, model, turn, stream) {
988
+ if (stream) return new Response(streamOf(id, model, turn), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
989
+ return answered(id, model, turn).then(
990
+ (body) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }),
991
+ (error) => jsonError(error.status ?? 502, error.message),
992
+ )
993
+ }
994
+
651
995
  export async function handle(home, input, init = {}) {
652
996
  const url = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url || ""
653
997
  if (!/\/chat\/completions(?:$|[?#])/.test(url)) return jsonError(404, `agy-tui serves chat completions, not ${url}`)
@@ -658,32 +1002,45 @@ export async function handle(home, input, init = {}) {
658
1002
  } catch {
659
1003
  return jsonError(400, "the request is not JSON")
660
1004
  }
1005
+ const signal = init.signal ?? input?.signal
1006
+ const id = `chatcmpl-${randomBytes(12).toString("hex")}`
1007
+ const model = String(body.model ?? "")
1008
+ // the result of a call a turn waits on goes on with that turn
1009
+ const last = Array.isArray(body.messages) ? body.messages.at(-1) : null
1010
+ if (last?.role === "tool") {
1011
+ const waiting = unpark(last.tool_call_id)
1012
+ if (waiting && !waiting.ended) {
1013
+ let content
1014
+ try { content = toolContent(last.content) } catch (error) {
1015
+ waiting.close()
1016
+ return jsonError(error.status ?? 400, error.message)
1017
+ }
1018
+ if (waiting.reply(last.tool_call_id, content)) {
1019
+ waiting.watch(signal)
1020
+ return respond(id, model, waiting, body.stream)
1021
+ }
1022
+ }
1023
+ // agy no longer waits on it: a turn of its own, the conversation
1024
+ // typed in as text
1025
+ waiting?.close()
1026
+ }
661
1027
  if (!home) return jsonError(401, "agy-tui: no account; sign in again", { "X-Magpie-Sign-In": "expired" })
662
1028
  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" })
663
1029
  const agy = findAgy()
664
1030
  if (!agy) return jsonError(503, `agy CLI not found on this machine: ${AGY_MANUAL}`)
665
1031
  const refusal = await agyRefusal(agy)
666
1032
  if (refusal) return jsonError(503, refusal)
667
- const signal = init.signal ?? input?.signal
668
- const id = `chatcmpl-${randomBytes(12).toString("hex")}`
669
- const model = String(body.model ?? "")
670
1033
  let turn
671
1034
  try {
1035
+ const tools = mcpToolsOf(body)
672
1036
  const { prompt, media } = turnOf(body.messages)
673
1037
  // agy attaches a video for any model, but only Gemini's see one
674
1038
  if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
675
- turn = await startTurn({ agy, home, model, prompt, media, signal })
1039
+ turn = await startTurn({ agy, home, model, prompt, media, tools, signal })
676
1040
  } catch (error) {
677
1041
  return jsonError(error.status ?? 502, error.message, error.headers)
678
1042
  }
679
- if (body.stream) {
680
- return new Response(streamOf(id, model, turn.answer), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
681
- }
682
- try {
683
- return new Response(JSON.stringify(completion(id, model, await turn.answer)), { status: 200, headers: { "Content-Type": "application/json" } })
684
- } catch (error) {
685
- return jsonError(error.status ?? 502, error.message)
686
- }
1043
+ return respond(id, model, turn, body.stream)
687
1044
  }
688
1045
 
689
1046
  // ---- the plugin