@magpie-community/opencode-agy-tui-auth 0.1.4 → 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/README.en.md +8 -4
- package/README.md +8 -4
- package/array-items.mjs +209 -0
- package/index.mjs +365 -70
- package/package.json +7 -2
- package/re2-pattern.mjs +606 -0
- package/tool-budget.mjs +157 -0
- package/tool-schema.mjs +672 -0
- package/tools.mjs +204 -0
package/index.mjs
CHANGED
|
@@ -7,6 +7,7 @@ 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
9
|
import { liveText } 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
|
|
24
|
-
//
|
|
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,6 +38,12 @@ 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.
|
|
38
49
|
export const READY = "? for shortcuts"
|
|
@@ -53,6 +64,19 @@ const PASTE_SETTLE_MS = 300
|
|
|
53
64
|
const IDLE_MS = 5_000
|
|
54
65
|
// how often a running turn's reply is read from agy's store (live.mjs)
|
|
55
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
|
+
}
|
|
56
80
|
|
|
57
81
|
function attachTimeout() {
|
|
58
82
|
const n = Number(process.env.AGY_TUI_ATTACH_TIMEOUT_MS)
|
|
@@ -330,6 +354,9 @@ function partsOf(content, media) {
|
|
|
330
354
|
// turnOf is what goes into agy's prompt: the images and videos, attached in
|
|
331
355
|
// the order they came, and the text pasted after them, the last user
|
|
332
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).
|
|
333
360
|
// A file magpie could only name in words (ATTACHMENT_NOTE) in the last
|
|
334
361
|
// user message is refused: the model would be told of a file it can't
|
|
335
362
|
// see. One in an earlier turn stays, as what was said then.
|
|
@@ -343,21 +370,26 @@ export function turnOf(messages) {
|
|
|
343
370
|
const text = partsOf(m?.content, media).trim()
|
|
344
371
|
if (text) system.push(text)
|
|
345
372
|
} else if (m?.role === "user" || m?.role === "assistant") {
|
|
346
|
-
const
|
|
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")
|
|
347
378
|
if (text) turns.push({ role: m.role, text })
|
|
348
379
|
} else if (m?.role === "tool") {
|
|
349
|
-
|
|
380
|
+
turns.push({ role: "tool", text: `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}` })
|
|
350
381
|
}
|
|
351
382
|
}
|
|
352
|
-
if (!turns.length || turns.at(-1).role
|
|
383
|
+
if (!turns.length || turns.at(-1).role === "assistant") throw refuse("the last message is not the user's or a tool's result")
|
|
353
384
|
const note = ATTACHMENT_NOTE.exec(turns.at(-1).text)
|
|
354
385
|
if (note) throw refuse(`${TAKES}; the message has ${named(note[1])}`)
|
|
355
|
-
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 }
|
|
356
387
|
const parts = []
|
|
388
|
+
const said = (t) => `${{ user: "User", assistant: "Assistant", tool: "Tool" }[t.role]}: ${t.text}`
|
|
357
389
|
if (system.length) parts.push(system.join("\n\n"))
|
|
358
|
-
if (turns.length > 1) {
|
|
359
|
-
parts.push(turns.slice(0, -1).map(
|
|
360
|
-
parts.push(
|
|
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)))
|
|
361
393
|
} else {
|
|
362
394
|
parts.push(turns[0].text)
|
|
363
395
|
}
|
|
@@ -461,45 +493,143 @@ class Failure extends Error {
|
|
|
461
493
|
}
|
|
462
494
|
}
|
|
463
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
|
+
|
|
464
544
|
// startTurn starts agy in its terminal and types the prompt; it resolves
|
|
465
|
-
// once agy has the message, with `
|
|
466
|
-
|
|
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 }) {
|
|
467
554
|
if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
|
|
468
555
|
settleHome(home)
|
|
556
|
+
const withTools = tools.length > 0
|
|
469
557
|
const ws = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-")))
|
|
470
558
|
// 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
|
|
472
|
-
//
|
|
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
|
|
473
562
|
let hookEnv
|
|
474
563
|
let files
|
|
564
|
+
let ownHome = null
|
|
475
565
|
try {
|
|
476
|
-
hookEnv = await writeDefaultAgentFiles(ws, {
|
|
566
|
+
hookEnv = await writeDefaultAgentFiles(ws, {
|
|
567
|
+
instructions: withTools ? TOOL_INSTRUCTIONS : INSTRUCTIONS,
|
|
568
|
+
allowed: withTools ? [MCP_FUNCTIONS] : [],
|
|
569
|
+
geminiDir: path.join(home, ".gemini"),
|
|
570
|
+
})
|
|
477
571
|
// the images and videos, in the turn's folder: agy copies each one it
|
|
478
572
|
// attaches into the conversation's own (forget removes it), and the
|
|
479
573
|
// folder goes with the turn
|
|
480
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
|
+
}
|
|
481
579
|
} catch (error) {
|
|
482
580
|
fs.rmSync(ws, { recursive: true, force: true })
|
|
581
|
+
if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
|
|
483
582
|
throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
|
|
484
583
|
}
|
|
485
584
|
const brain = path.join(home, ".gemini", "antigravity-cli", "brain")
|
|
486
585
|
let before
|
|
487
586
|
try { before = new Set(fs.readdirSync(brain)) } catch { before = new Set() }
|
|
488
587
|
|
|
489
|
-
// 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
|
|
490
590
|
const settings = { trustedWorkspaces: [ws] }
|
|
591
|
+
if (withTools) settings.permissions = { allow: [`mcp(${MCP_SERVER}/*)`] }
|
|
491
592
|
const args = ["--settings", JSON.stringify(settings)]
|
|
492
593
|
// agy's own default customizations stay out, as the old agent's
|
|
493
594
|
// inheritCustomizations: false kept them
|
|
494
595
|
if ((await agyHelp(agy)).includes("--include-default-customizations")) args.push("--include-default-customizations=false")
|
|
495
596
|
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 })
|
|
597
|
+
const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
|
|
497
598
|
let screen = ""
|
|
498
599
|
let ended = null
|
|
499
600
|
let errorLine = ""
|
|
500
601
|
let stderr = ""
|
|
602
|
+
let mcp = null
|
|
603
|
+
let listed = false
|
|
501
604
|
const waiters = new Set()
|
|
502
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
|
+
|
|
503
633
|
let buf = ""
|
|
504
634
|
child.stdout.setEncoding("utf8").on("data", (d) => {
|
|
505
635
|
buf += d
|
|
@@ -512,6 +642,16 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
|
|
|
512
642
|
if (typeof o.screen === "string") screen = o.screen
|
|
513
643
|
if (o.error) errorLine = o.error
|
|
514
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)
|
|
515
655
|
}
|
|
516
656
|
poke()
|
|
517
657
|
})
|
|
@@ -529,29 +669,56 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
|
|
|
529
669
|
const late = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 5000)
|
|
530
670
|
await closed
|
|
531
671
|
clearTimeout(late)
|
|
672
|
+
// the links in it go, never what they point to
|
|
673
|
+
if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
|
|
532
674
|
if (process.env.AGY_TUI_KEEP) return
|
|
533
675
|
fs.rmSync(ws, { recursive: true, force: true })
|
|
534
676
|
}
|
|
677
|
+
// the request the turn answers now: its end, before the turn's, ends it
|
|
678
|
+
let sig = null
|
|
535
679
|
const onAbort = () => { cleanup() }
|
|
536
|
-
|
|
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)
|
|
537
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
|
|
538
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)
|
|
539
693
|
const check = () => {
|
|
540
694
|
if (ok()) return done(resolve)
|
|
541
|
-
if (
|
|
695
|
+
if (sig?.aborted) return done(() => reject(new Failure(499, "the request was cancelled")))
|
|
542
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)}` : ""}`)))
|
|
543
698
|
}
|
|
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
699
|
const tick = setInterval(check, 250)
|
|
546
|
-
const done = (f) => {
|
|
700
|
+
const done = (f) => { clearInterval(tick); waiters.delete(check); f() }
|
|
547
701
|
waiters.add(check)
|
|
548
702
|
check()
|
|
549
703
|
})
|
|
550
704
|
const ready = () => screen.includes(READY) && !screen.includes(BUSY)
|
|
551
705
|
|
|
552
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
|
+
}
|
|
553
718
|
send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
|
|
554
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)
|
|
555
722
|
if (files.length) {
|
|
556
723
|
// pasted alone, the paths are attached, as files dragged onto the
|
|
557
724
|
// terminal are; the turn waits until agy shows every one attached,
|
|
@@ -575,26 +742,41 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
|
|
|
575
742
|
throw error
|
|
576
743
|
}
|
|
577
744
|
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
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(),
|
|
585
762
|
}
|
|
586
|
-
|
|
587
|
-
|
|
763
|
+
|
|
764
|
+
;(async () => {
|
|
765
|
+
let last
|
|
588
766
|
let polled = 0
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
}
|
|
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()
|
|
593
770
|
try {
|
|
594
771
|
// back at its prompt with nothing in the transcript for a while:
|
|
595
772
|
// the turn failed, and what agy drew says why (a quota, a refusal)
|
|
596
773
|
let idleSince = 0
|
|
597
774
|
await waitFor("answer", () => {
|
|
775
|
+
if (pending.size) {
|
|
776
|
+
until = Date.now() + turnTimeout()
|
|
777
|
+
idleSince = 0
|
|
778
|
+
return false
|
|
779
|
+
}
|
|
598
780
|
if (!ready()) {
|
|
599
781
|
idleSince = 0
|
|
600
782
|
if (Date.now() - polled >= LIVE_POLL_MS) {
|
|
@@ -608,17 +790,74 @@ export async function startTurn({ agy, home, model, prompt, media = [], signal,
|
|
|
608
790
|
if (found?.answer) return true
|
|
609
791
|
idleSince ||= Date.now()
|
|
610
792
|
return Date.now() - idleSince > IDLE_MS
|
|
611
|
-
},
|
|
793
|
+
}, () => until)
|
|
612
794
|
if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
|
|
613
795
|
// the whole of it, read before the conversation goes
|
|
614
796
|
publish(liveText(home, found.id))
|
|
615
|
-
|
|
797
|
+
last = { text: found.answer }
|
|
798
|
+
} catch (error) {
|
|
799
|
+
last = { error }
|
|
616
800
|
} finally {
|
|
801
|
+
// the end is told once the turn's files are gone
|
|
802
|
+
turn.ended = true
|
|
803
|
+
watch(null)
|
|
617
804
|
await cleanup()
|
|
618
805
|
forget(brain, found?.id)
|
|
806
|
+
stop(last)
|
|
619
807
|
}
|
|
620
808
|
})()
|
|
621
|
-
return
|
|
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
|
|
622
861
|
}
|
|
623
862
|
|
|
624
863
|
// forget removes the conversation agy kept for a turn from the account's
|
|
@@ -643,30 +882,58 @@ function jsonError(status, message, headers = {}) {
|
|
|
643
882
|
})
|
|
644
883
|
}
|
|
645
884
|
|
|
646
|
-
|
|
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) {
|
|
647
901
|
return {
|
|
648
902
|
id,
|
|
649
903
|
object: "chat.completion",
|
|
650
904
|
created: Math.floor(Date.now() / 1000),
|
|
651
905
|
model,
|
|
652
|
-
choices: [{ index: 0, message: { role: "assistant",
|
|
906
|
+
choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }],
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
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")
|
|
653
918
|
}
|
|
919
|
+
return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text }, "stop")
|
|
654
920
|
}
|
|
655
921
|
|
|
656
|
-
// streamOf sends the reply as agy's model
|
|
657
|
-
// piece once; at the end, what the store has
|
|
658
|
-
// from it, the transcript's answer
|
|
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.
|
|
659
926
|
export function streamOf(id, model, turn) {
|
|
660
|
-
const {
|
|
927
|
+
const { live } = turn
|
|
661
928
|
const enc = new TextEncoder()
|
|
662
929
|
const created = Math.floor(Date.now() / 1000)
|
|
663
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`
|
|
664
931
|
let keep
|
|
665
932
|
let listen
|
|
666
933
|
let quiet = 0
|
|
667
|
-
const
|
|
934
|
+
const halt = () => {
|
|
668
935
|
clearInterval(keep)
|
|
669
|
-
if (listen) live
|
|
936
|
+
if (listen) live.listeners.delete(listen)
|
|
670
937
|
}
|
|
671
938
|
return new ReadableStream({
|
|
672
939
|
async start(c) {
|
|
@@ -674,18 +941,17 @@ export function streamOf(id, model, turn) {
|
|
|
674
941
|
// only what continues what was sent: agy writing a reply over is
|
|
675
942
|
// left to the end
|
|
676
943
|
const send = (text) => {
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
sent
|
|
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
|
|
680
948
|
quiet = Date.now()
|
|
681
949
|
}
|
|
682
950
|
c.enqueue(enc.encode(chunk({ role: "assistant", content: "" })))
|
|
683
951
|
quiet = Date.now()
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
send(live.text)
|
|
688
|
-
}
|
|
952
|
+
listen = send
|
|
953
|
+
live.listeners.add(listen)
|
|
954
|
+
send(live.text)
|
|
689
955
|
// the turn may take minutes before its first word: a comment now
|
|
690
956
|
// and then keeps the connection from looking dead
|
|
691
957
|
keep = setInterval(() => {
|
|
@@ -694,22 +960,38 @@ export function streamOf(id, model, turn) {
|
|
|
694
960
|
quiet = Date.now()
|
|
695
961
|
}, 5_000)
|
|
696
962
|
try {
|
|
697
|
-
const
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
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
|
+
}
|
|
701
975
|
} catch (error) {
|
|
702
976
|
c.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: error.message, type: "agy_tui_error" } })}\n\n`))
|
|
703
977
|
} finally {
|
|
704
|
-
|
|
978
|
+
halt()
|
|
705
979
|
}
|
|
706
980
|
c.enqueue(enc.encode("data: [DONE]\n\n"))
|
|
707
981
|
c.close()
|
|
708
982
|
},
|
|
709
|
-
cancel() {
|
|
983
|
+
cancel() { halt() },
|
|
710
984
|
})
|
|
711
985
|
}
|
|
712
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
|
+
|
|
713
995
|
export async function handle(home, input, init = {}) {
|
|
714
996
|
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url || ""
|
|
715
997
|
if (!/\/chat\/completions(?:$|[?#])/.test(url)) return jsonError(404, `agy-tui serves chat completions, not ${url}`)
|
|
@@ -720,32 +1002,45 @@ export async function handle(home, input, init = {}) {
|
|
|
720
1002
|
} catch {
|
|
721
1003
|
return jsonError(400, "the request is not JSON")
|
|
722
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
|
+
}
|
|
723
1027
|
if (!home) return jsonError(401, "agy-tui: no account; sign in again", { "X-Magpie-Sign-In": "expired" })
|
|
724
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" })
|
|
725
1029
|
const agy = findAgy()
|
|
726
1030
|
if (!agy) return jsonError(503, `agy CLI not found on this machine: ${AGY_MANUAL}`)
|
|
727
1031
|
const refusal = await agyRefusal(agy)
|
|
728
1032
|
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
1033
|
let turn
|
|
733
1034
|
try {
|
|
1035
|
+
const tools = mcpToolsOf(body)
|
|
734
1036
|
const { prompt, media } = turnOf(body.messages)
|
|
735
1037
|
// agy attaches a video for any model, but only Gemini's see one
|
|
736
1038
|
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 })
|
|
1039
|
+
turn = await startTurn({ agy, home, model, prompt, media, tools, signal })
|
|
738
1040
|
} catch (error) {
|
|
739
1041
|
return jsonError(error.status ?? 502, error.message, error.headers)
|
|
740
1042
|
}
|
|
741
|
-
|
|
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
|
-
}
|
|
1043
|
+
return respond(id, model, turn, body.stream)
|
|
749
1044
|
}
|
|
750
1045
|
|
|
751
1046
|
// ---- the plugin
|