@magpie-community/opencode-agy-tui-auth 0.1.20 → 0.1.22
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 -2
- package/README.md +8 -2
- package/index.mjs +386 -205
- package/live.mjs +21 -0
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -33,9 +33,15 @@ A request's tools (`tools`, function tools) are given to the model through magpi
|
|
|
33
33
|
|
|
34
34
|
## Options (environment)
|
|
35
35
|
|
|
36
|
+
Behind a load balancer, send the conversation history in each request. A worker without a matching terminal or saved conversation rebuilds from the supplied messages, including tool results. Long requests use agy's conversation store when available. The first generation on that worker may need to read the context again.
|
|
37
|
+
|
|
38
|
+
When agy's transcript identifies a complete tool batch and all callbacks are available, the plugin can deliver them together and accept the results in any order. If the client sets `parallel_tool_calls: false` or agy exposes callbacks one at a time, the plugin continues to deliver them one at a time.
|
|
39
|
+
|
|
36
40
|
- `AGY_PATH`: where agy is.
|
|
37
|
-
- `AGY_TUI_TURN_TIMEOUT_MS`: the
|
|
38
|
-
- `AGY_TUI_PARK_TIMEOUT_MS`: how long a turn waits for a tool
|
|
41
|
+
- `AGY_TUI_TURN_TIMEOUT_MS`: the generation deadline per model step, 15 minutes by default.
|
|
42
|
+
- `AGY_TUI_PARK_TIMEOUT_MS`: how long a turn waits for a tool result, 15 minutes by default.
|
|
43
|
+
- `AGY_TUI_TRACE_RESUME=1`: log the request ID, continuation outcome, and the agy conversation ID or replay reason.
|
|
44
|
+
- `AGY_TUI_REQUIRE_CALLER=1`: require the authenticated caller ID supplied by the Magpie gateway for shared service. Give each user a separate gateway key and send a stable, distinct `X-Magpie-Session` for each conversation. Keyed requests without a session use the gateway's conversation ID derived from the opening messages. Use a gateway build that forwards `X-Magpie-Caller-ID` from its authenticated key identity. No Magpie release sends that header yet, so with this set every request is refused.
|
|
39
45
|
- `AGY_TUI_ATTACH_TIMEOUT_MS`: how long agy may take to attach a turn's images and videos, 15 seconds by default.
|
|
40
46
|
- `AGY_TUI_SPARES=0`: no agy started ahead for the next request.
|
|
41
47
|
- `AGY_TUI_CARRY=0`: every request in a new agy conversation, the chat pasted in whole, and no conversation kept.
|
package/README.md
CHANGED
|
@@ -33,9 +33,15 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
|
|
|
33
33
|
|
|
34
34
|
## 选项(环境变量)
|
|
35
35
|
|
|
36
|
+
通过负载均衡使用时,每个请求都应携带对话历史。接单实例如果找不到对应的终端或已保存会话,会用请求携带的消息和工具结果重建。长对话会在支持时写入 agy 的会话存储。切换实例后的首次生成可能需要重新读取上下文。
|
|
37
|
+
|
|
38
|
+
agy 日志确认同一批工具调用、且所有回调均已到达时,插件可以一次交付整批调用,并接受乱序返回的结果。客户端设置 `parallel_tool_calls: false` 或 agy 逐个提供回调时,插件继续逐个交付。
|
|
39
|
+
|
|
36
40
|
- `AGY_PATH`:agy 的路径。
|
|
37
|
-
- `AGY_TUI_TURN_TIMEOUT_MS
|
|
38
|
-
- `AGY_TUI_PARK_TIMEOUT_MS
|
|
41
|
+
- `AGY_TUI_TURN_TIMEOUT_MS`:每次模型生成的时间上限,默认 15 分钟。
|
|
42
|
+
- `AGY_TUI_PARK_TIMEOUT_MS`:等待工具调用结果的时间上限,默认 15 分钟。
|
|
43
|
+
- `AGY_TUI_TRACE_RESUME=1`:记录请求 ID、续接结果,以及 agy 会话 ID 或回放原因。
|
|
44
|
+
- `AGY_TUI_REQUIRE_CALLER=1`:共享服务要求 Magpie 网关提供已认证的调用者 ID。每个用户使用独立的网关密钥,每个会话使用独立且稳定的 `X-Magpie-Session`。已认证请求未提供会话标识时,使用网关根据开场消息生成的对话 ID。网关版本须支持从认证身份生成 `X-Magpie-Caller-ID`;目前还没有 Magpie 版本发送这个请求头,开启后每个请求都会被拒绝。
|
|
39
45
|
- `AGY_TUI_ATTACH_TIMEOUT_MS`:agy 附加本轮图片和视频的最长等待时间,默认 15 秒。
|
|
40
46
|
- `AGY_TUI_SPARES=0`:不为下一个请求预先启动 agy。
|
|
41
47
|
- `AGY_TUI_CARRY=0`:每个请求都开新的 agy 会话、整段粘贴对话,不保留会话。
|
package/index.mjs
CHANGED
|
@@ -3,10 +3,11 @@ import { createHash, randomBytes } from "node:crypto"
|
|
|
3
3
|
import fs from "node:fs"
|
|
4
4
|
import os from "node:os"
|
|
5
5
|
import path from "node:path"
|
|
6
|
+
import { fileURLToPath } from "node:url"
|
|
6
7
|
import { startLogin } from "./login.mjs"
|
|
7
8
|
import { writeDefaultAgentFiles } from "./default-agent.mjs"
|
|
8
9
|
import { agyHasUsageSubcommand, agyTooOld, MIN_AGY_VERSION, oldAgyError, USAGE_SUBCOMMAND_AGY_VERSION } from "./agy-version.mjs"
|
|
9
|
-
import { liveReply, callsAfter, usageOf, lastStep } from "./live.mjs"
|
|
10
|
+
import { conversationWorkspace, liveReply, callsAfter, usageOf, lastStep } from "./live.mjs"
|
|
10
11
|
import { canSeed, chunks, resumed, writeConversation } from "./seed.mjs"
|
|
11
12
|
import { mcpToolsOf, unfit } from "./tools.mjs"
|
|
12
13
|
import { clientNames, MCP_SERVER, offered } from "./tool-names.mjs"
|
|
@@ -89,16 +90,17 @@ const RESUME_TRIES = 20
|
|
|
89
90
|
const MCP_CALL_SECONDS = 3600
|
|
90
91
|
// agy lists the tools as it starts, before its prompt shows
|
|
91
92
|
const LISTED_MS = 20_000
|
|
92
|
-
|
|
93
|
-
|
|
93
|
+
const DEFAULT_TIMEOUT_MS = 15 * 60_000
|
|
94
|
+
// Reject new tool waits at capacity without evicting someone else's turn.
|
|
95
|
+
const MAX_PARKED = 32
|
|
94
96
|
// how long a response's end waits for agy to write its calls' token counts
|
|
95
97
|
const USAGE_POLL_MS = 100
|
|
96
98
|
const USAGE_TRIES = 15
|
|
97
99
|
|
|
98
100
|
// how long a turn waits for the request with a call's result
|
|
99
|
-
function parkTimeout() {
|
|
101
|
+
export function parkTimeout() {
|
|
100
102
|
const n = Number(process.env.AGY_TUI_PARK_TIMEOUT_MS)
|
|
101
|
-
return Number.isFinite(n) && n > 0 ? n :
|
|
103
|
+
return Number.isFinite(n) && n > 0 ? n : DEFAULT_TIMEOUT_MS
|
|
102
104
|
}
|
|
103
105
|
|
|
104
106
|
function attachTimeout() {
|
|
@@ -106,9 +108,9 @@ function attachTimeout() {
|
|
|
106
108
|
return Number.isFinite(n) && n > 0 ? n : 15_000
|
|
107
109
|
}
|
|
108
110
|
|
|
109
|
-
function turnTimeout() {
|
|
111
|
+
export function turnTimeout() {
|
|
110
112
|
const n = Number(process.env.AGY_TUI_TURN_TIMEOUT_MS)
|
|
111
|
-
return Number.isFinite(n) && n > 0 ? n :
|
|
113
|
+
return Number.isFinite(n) && n > 0 ? n : DEFAULT_TIMEOUT_MS
|
|
112
114
|
}
|
|
113
115
|
|
|
114
116
|
// ---- accounts
|
|
@@ -446,6 +448,29 @@ export function contextOf(id) {
|
|
|
446
448
|
}
|
|
447
449
|
const bytes = (s) => Buffer.byteLength(s)
|
|
448
450
|
|
|
451
|
+
function toolResultText(message, media) {
|
|
452
|
+
const status = message.is_error === true ? "error result" : "result"
|
|
453
|
+
return `[${status} of ${message.tool_call_id ?? "a call"}]\n${partsOf(message.content, media).trim()}`
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// what a chat that ends on the assistant's own words (a client going on
|
|
457
|
+
// from a cut or finished reply) is typed with, as opencode-agy-cli-auth's
|
|
458
|
+
// continuation carrier says it
|
|
459
|
+
const CONTINUE_NOTE = "(system note: the last message above is part of your own reply; continue exactly from where it stops, and do not repeat it.)"
|
|
460
|
+
|
|
461
|
+
// continued is the chat with the user's note after a last message of the
|
|
462
|
+
// assistant's that is words alone, so it ends on a message agy can answer.
|
|
463
|
+
// A last message with calls nobody answered, or with no words, or a chat
|
|
464
|
+
// in which the user never spoke, is left as it is, for the caller to
|
|
465
|
+
// refuse.
|
|
466
|
+
export function continued(messages) {
|
|
467
|
+
const last = Array.isArray(messages) ? messages.at(-1) : null
|
|
468
|
+
if (last?.role !== "assistant" || (Array.isArray(last.tool_calls) && last.tool_calls.length)) return messages
|
|
469
|
+
if (!partsOf(last.content, []).trim()) return messages
|
|
470
|
+
if (!messages.some((m) => m?.role === "user")) return messages
|
|
471
|
+
return [...messages, { role: "user", content: CONTINUE_NOTE }]
|
|
472
|
+
}
|
|
473
|
+
|
|
449
474
|
// turnOf is what goes into agy's prompt: the images and videos, attached in
|
|
450
475
|
// the order they came, and the text pasted after them, the last user
|
|
451
476
|
// message alone, or with the instructions and the conversation before it.
|
|
@@ -462,6 +487,7 @@ const bytes = (s) => Buffer.byteLength(s)
|
|
|
462
487
|
// see. One in an earlier turn stays, as what was said then.
|
|
463
488
|
export function turnOf(messages, budget = INPUT_BUDGET) {
|
|
464
489
|
if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
|
|
490
|
+
messages = continued(messages)
|
|
465
491
|
// read once to weigh the turns, then again with only the kept ones, so
|
|
466
492
|
// the images are numbered as they are attached
|
|
467
493
|
const read = (list, media) => {
|
|
@@ -479,7 +505,7 @@ export function turnOf(messages, budget = INPUT_BUDGET) {
|
|
|
479
505
|
const text = said.filter(Boolean).join("\n")
|
|
480
506
|
if (text) turns.push({ role: m.role, text, m })
|
|
481
507
|
} else if (m?.role === "tool") {
|
|
482
|
-
turns.push({ role: "tool", text:
|
|
508
|
+
turns.push({ role: "tool", text: toolResultText(m, media), m })
|
|
483
509
|
}
|
|
484
510
|
}
|
|
485
511
|
return { system, turns }
|
|
@@ -553,6 +579,7 @@ const GOES_ON = "\n\n[continued in the next message]"
|
|
|
553
579
|
// came, as their marks in the steps say.
|
|
554
580
|
export function seedSteps(messages, budget = INPUT_BUDGET) {
|
|
555
581
|
if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
|
|
582
|
+
messages = continued(messages)
|
|
556
583
|
const media = []
|
|
557
584
|
const system = []
|
|
558
585
|
const groups = []
|
|
@@ -576,7 +603,7 @@ export function seedSteps(messages, budget = INPUT_BUDGET) {
|
|
|
576
603
|
const text = said.filter(Boolean).join("\n")
|
|
577
604
|
if (text) add("model", text)
|
|
578
605
|
} else if (m?.role === "tool") {
|
|
579
|
-
add("user",
|
|
606
|
+
add("user", toolResultText(m, media))
|
|
580
607
|
}
|
|
581
608
|
}
|
|
582
609
|
if (groups.at(-1)?.role !== "user") throw refuse("the last message is not the user's or a tool's result")
|
|
@@ -632,6 +659,19 @@ export function pastedPaths(files, platform = process.platform) {
|
|
|
632
659
|
}).join("\n")
|
|
633
660
|
}
|
|
634
661
|
|
|
662
|
+
export function attachmentPaste(files, platform = process.platform) {
|
|
663
|
+
const paste = `\x1b[200~${pastedPaths(files, platform)}\x1b[201~`
|
|
664
|
+
if (platform !== "win32") return paste
|
|
665
|
+
// ConPTY drops the paste markers from ordinary VT input. Win32 input
|
|
666
|
+
// mode carries the whole paste as Unicode key-down events, markers and all.
|
|
667
|
+
// Each record is CSI Vk;Sc;Uc;Kd;Cs;Rc_, with Uc one UTF-16 code unit.
|
|
668
|
+
let input = ""
|
|
669
|
+
for (let i = 0; i < paste.length; i++) {
|
|
670
|
+
input += `\x1b[0;0;${paste.charCodeAt(i)};1;0;1_`
|
|
671
|
+
}
|
|
672
|
+
return input
|
|
673
|
+
}
|
|
674
|
+
|
|
635
675
|
// attached is how many files agy's prompt shows attached ("📎 2 media
|
|
636
676
|
// attached"), 0 for none.
|
|
637
677
|
export function attached(screen) {
|
|
@@ -649,7 +689,7 @@ const claimed = new Set()
|
|
|
649
689
|
// call there too. A turn that carries a conversation on (`from`: its id
|
|
650
690
|
// and the transcript's length in lines before the turn) looks in that
|
|
651
691
|
// one alone, past those lines.
|
|
652
|
-
export function answerOf(brain, before, prompt, own = null, from = null) {
|
|
692
|
+
export function answerOf(brain, before, prompt, own = null, from = null, owns = null) {
|
|
653
693
|
// its own words, not an image's or a video's mark, which other turns have too
|
|
654
694
|
const lines = prompt.split("\n").map((l) => l.trim())
|
|
655
695
|
const snip = (lines.find((l) => l.replace(MEDIA_MARK, "").trim()) ?? lines.find(Boolean))?.slice(0, 60) ?? ""
|
|
@@ -676,13 +716,39 @@ export function answerOf(brain, before, prompt, own = null, from = null) {
|
|
|
676
716
|
mine = true
|
|
677
717
|
}
|
|
678
718
|
}
|
|
679
|
-
if (mine) return { id, answer }
|
|
719
|
+
if (mine && (from || !owns || id === own || owns(id))) return { id, answer }
|
|
680
720
|
}
|
|
681
721
|
return null
|
|
682
722
|
}
|
|
683
723
|
|
|
684
724
|
const transcriptOf = (brain, id) => path.join(brain, id, ".system_generated", "logs", "transcript_full.jsonl")
|
|
685
725
|
|
|
726
|
+
// A completed planner row declares the full batch. The helper's callbacks
|
|
727
|
+
// alone cannot tell us if another call belongs to the same generation.
|
|
728
|
+
function toolBatchOf(brain, id, after) {
|
|
729
|
+
if (!id) return null
|
|
730
|
+
let lines
|
|
731
|
+
try { lines = fs.readFileSync(transcriptOf(brain, id), "utf8").trimEnd().split("\n") } catch { return null }
|
|
732
|
+
for (const line of lines.reverse()) {
|
|
733
|
+
let row
|
|
734
|
+
try { row = JSON.parse(line) } catch { continue }
|
|
735
|
+
if (row.type !== "PLANNER_RESPONSE") continue
|
|
736
|
+
if (row.status !== "DONE" || !Number.isInteger(row.step_index) || row.step_index <= after || !row.tool_calls?.length) return null
|
|
737
|
+
return { step: row.step_index, calls: row.tool_calls.map((call) => toolIdentity(call.name, call.args)) }
|
|
738
|
+
}
|
|
739
|
+
return null
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function toolIdentity(name, args) {
|
|
743
|
+
const sorted = (value) => {
|
|
744
|
+
if (Array.isArray(value)) return value.map(sorted)
|
|
745
|
+
if (!value || typeof value !== "object") return value
|
|
746
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sorted(value[key])]))
|
|
747
|
+
}
|
|
748
|
+
const { toolSummary, ...parameters } = args ?? {}
|
|
749
|
+
return JSON.stringify([String(name ?? "").replace(/^mcp_magpie_/, ""), sorted(parameters)])
|
|
750
|
+
}
|
|
751
|
+
|
|
686
752
|
// transcriptLines is how many lines the conversation's transcript has
|
|
687
753
|
function transcriptLines(brain, id) {
|
|
688
754
|
try { return fs.readFileSync(transcriptOf(brain, id), "utf8").split("\n").length - 1 } catch { return 0 }
|
|
@@ -793,8 +859,8 @@ export function mcpConfig(mcp, tools) {
|
|
|
793
859
|
// own tools stay off. With a conversation (an id agy kept, carried), agy
|
|
794
860
|
// starts with it and the prompt carries it on; `messages` is the request's
|
|
795
861
|
// whole chat, which the conversation is kept under when the turn answers.
|
|
796
|
-
export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE, conversation = null, messages = null, place = null }) {
|
|
797
|
-
const opts = { agy, home, model, tools, helper, conversation, place }
|
|
862
|
+
export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE, conversation = null, messages = null, place = null, scope = "" }) {
|
|
863
|
+
const opts = { agy, home, model, tools, helper, conversation, place, scope }
|
|
798
864
|
const key = spareKey(opts)
|
|
799
865
|
let turn = null
|
|
800
866
|
const spare = await takeSpare(key)
|
|
@@ -820,56 +886,59 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
820
886
|
// the account, its plan and its models before it takes a message (a median
|
|
821
887
|
// of 3.8s a start on a real account, 11s at worst). So each turn leaves an
|
|
822
888
|
// agy started for the next request with the same account, model and tools,
|
|
823
|
-
// which only types its message into it.
|
|
824
|
-
//
|
|
825
|
-
const SPARE_IDLE_MS =
|
|
889
|
+
// which only types its message into it. A finished chat can also keep the
|
|
890
|
+
// terminal it just used. Both kinds share the same idle limit and pool.
|
|
891
|
+
const SPARE_IDLE_MS = DEFAULT_TIMEOUT_MS
|
|
826
892
|
const MAX_SPARES = 3
|
|
827
893
|
const spares = new Map()
|
|
894
|
+
const closingSpares = new Map()
|
|
828
895
|
|
|
829
|
-
function spareKey({ agy, home, model, tools, helper, conversation }) {
|
|
830
|
-
return
|
|
896
|
+
function spareKey({ agy, home, model, tools, helper, conversation, scope = "" }) {
|
|
897
|
+
return sha(JSON.stringify([agy, home, model ?? "", tools, helper ?? "", conversation ?? "", scope]))
|
|
831
898
|
}
|
|
832
899
|
|
|
833
900
|
async function takeSpare(key) {
|
|
834
901
|
const s = spares.get(key)
|
|
835
|
-
if (!s)
|
|
902
|
+
if (!s) {
|
|
903
|
+
await closingSpares.get(key)
|
|
904
|
+
return null
|
|
905
|
+
}
|
|
836
906
|
spares.delete(key)
|
|
837
907
|
clearTimeout(s.timer)
|
|
838
908
|
const a = await s.started.catch(() => null)
|
|
839
909
|
if (a?.alive()) return a
|
|
840
|
-
a?.close()
|
|
910
|
+
await a?.close()
|
|
841
911
|
return null
|
|
842
912
|
}
|
|
843
913
|
|
|
844
|
-
//
|
|
845
|
-
//
|
|
914
|
+
// Track shutdown after removing the spare so a resumed chat can wait for
|
|
915
|
+
// the old terminal to finish with its conversation store.
|
|
846
916
|
function dropSpare(key) {
|
|
847
917
|
const s = spares.get(key)
|
|
848
|
-
if (!s) return Promise.resolve()
|
|
918
|
+
if (!s) return closingSpares.get(key) ?? Promise.resolve()
|
|
849
919
|
spares.delete(key)
|
|
850
920
|
clearTimeout(s.timer)
|
|
851
|
-
|
|
921
|
+
const closed = s.started.then((a) => a.close(), () => {})
|
|
922
|
+
closingSpares.set(key, closed)
|
|
923
|
+
const forget = () => { if (closingSpares.get(key) === closed) closingSpares.delete(key) }
|
|
924
|
+
closed.then(forget, forget)
|
|
925
|
+
return closed
|
|
852
926
|
}
|
|
853
927
|
|
|
854
|
-
function leaveSpare(key, opts) {
|
|
928
|
+
function leaveSpare(key, opts, terminal) {
|
|
855
929
|
if (process.env.AGY_TUI_SPARES === "0" || spares.has(key)) return
|
|
856
930
|
while (spares.size >= MAX_SPARES) dropSpare(spares.keys().next().value)
|
|
857
|
-
const started = launch(opts)
|
|
931
|
+
const started = terminal ? Promise.resolve(terminal) : launch(opts)
|
|
858
932
|
started.catch(() => {})
|
|
859
933
|
const timer = setTimeout(() => dropSpare(key), SPARE_IDLE_MS)
|
|
860
934
|
timer.unref?.()
|
|
861
935
|
spares.set(key, { started, timer })
|
|
936
|
+
return true
|
|
862
937
|
}
|
|
863
938
|
|
|
864
939
|
// closeSpares ends every agy that waits for a request
|
|
865
940
|
export async function closeSpares() {
|
|
866
|
-
|
|
867
|
-
spares.clear()
|
|
868
|
-
await Promise.all(all.map(async (s) => {
|
|
869
|
-
clearTimeout(s.timer)
|
|
870
|
-
const a = await s.started.catch(() => null)
|
|
871
|
-
await a?.close()
|
|
872
|
-
}))
|
|
941
|
+
await Promise.all([...closingSpares.values(), ...[...spares.keys()].map(dropSpare)])
|
|
873
942
|
}
|
|
874
943
|
|
|
875
944
|
// folderAt is a new, empty folder for a turn: at `want`, the path the
|
|
@@ -897,7 +966,7 @@ function folderAt(want, prefix) {
|
|
|
897
966
|
// `place`), and resolves at once: begin({ prompt, media, signal, messages
|
|
898
967
|
// }) waits until it is at its prompt, types the request in and resolves
|
|
899
968
|
// with the turn
|
|
900
|
-
async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null, place = null }) {
|
|
969
|
+
async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null, place = null, scope = "" }) {
|
|
901
970
|
if (!helper) throw new Failure(501, oldMagpie(TUI_HELPER_MAGPIE, "has a terminal for agy"))
|
|
902
971
|
settleHome(home)
|
|
903
972
|
const withTools = tools.length > 0
|
|
@@ -971,13 +1040,25 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
971
1040
|
// transcript (from) and its store (stepBase)
|
|
972
1041
|
let from = null
|
|
973
1042
|
let stepBase = -1
|
|
1043
|
+
// A scoped terminal may run beside another one typing the same prompt.
|
|
1044
|
+
// The workspace in agy's store ties a new conversation to its terminal.
|
|
1045
|
+
const owns = scope ? (id) => {
|
|
1046
|
+
try {
|
|
1047
|
+
const dir = path.normalize(fileURLToPath(conversationWorkspace(home, id)))
|
|
1048
|
+
return process.platform === "win32" ? dir.toLowerCase() === ws.toLowerCase() : dir === ws
|
|
1049
|
+
} catch {
|
|
1050
|
+
return false
|
|
1051
|
+
}
|
|
1052
|
+
} : null
|
|
974
1053
|
const look = () => {
|
|
975
|
-
found = answerOf(brain, before, prompt, found?.id, from) ?? (from ? { id: from.id, answer: "" } : null)
|
|
1054
|
+
found = answerOf(brain, before, prompt, found?.id, from, owns) ?? (from ? { id: from.id, answer: "" } : null)
|
|
976
1055
|
if (found?.id) claimed.add(found.id)
|
|
977
1056
|
}
|
|
978
1057
|
// what the model has said so far, its text and its thinking, from agy's
|
|
979
1058
|
// conversation store (live.mjs), for a stream to send as it comes
|
|
980
|
-
|
|
1059
|
+
let live
|
|
1060
|
+
let activeConversation = conversation
|
|
1061
|
+
let checkedResume = false
|
|
981
1062
|
const publish = (reply) => {
|
|
982
1063
|
let grew = false
|
|
983
1064
|
for (const k of ["text", "thinking"]) {
|
|
@@ -991,16 +1072,25 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
991
1072
|
// none): agy writes a call's counts as the call ends, so a moment is
|
|
992
1073
|
// given for them
|
|
993
1074
|
let usageAt = null
|
|
994
|
-
|
|
995
|
-
|
|
1075
|
+
let usageBaselineKnown = true
|
|
1076
|
+
const spent = async (tries = USAGE_TRIES, deferred = false) => {
|
|
1077
|
+
if (!usageBaselineKnown) return null
|
|
1078
|
+
for (let i = 0; i < tries; i++) {
|
|
996
1079
|
if (!found?.id) look()
|
|
997
1080
|
const got = found?.id ? callsAfter(home, found.id, usageAt) : null
|
|
998
|
-
if (
|
|
999
|
-
if (got.calls.length) {
|
|
1081
|
+
if (got?.calls.length) {
|
|
1000
1082
|
usageAt = got.cursor
|
|
1083
|
+
if (deferred) {
|
|
1084
|
+
return got.calls.reduce((total, call) => ({
|
|
1085
|
+
prompt_tokens: total.prompt_tokens + call.input + call.read + call.write,
|
|
1086
|
+
completion_tokens: total.completion_tokens + call.output,
|
|
1087
|
+
cached_tokens: total.cached_tokens + call.read,
|
|
1088
|
+
cache_write_tokens: total.cache_write_tokens + call.write,
|
|
1089
|
+
}), { prompt_tokens: 0, completion_tokens: 0, cached_tokens: 0, cache_write_tokens: 0 })
|
|
1090
|
+
}
|
|
1001
1091
|
return usageOf(got.calls)
|
|
1002
1092
|
}
|
|
1003
|
-
await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
|
|
1093
|
+
if (i + 1 < tries) await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
|
|
1004
1094
|
}
|
|
1005
1095
|
return null
|
|
1006
1096
|
}
|
|
@@ -1024,9 +1114,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1024
1114
|
pending.add(o.call.id)
|
|
1025
1115
|
if (!found?.id) look()
|
|
1026
1116
|
if (found?.id) publish(liveReply(home, found.id, stepBase))
|
|
1027
|
-
|
|
1028
|
-
const call = { ...o.call, name: clients.get(o.call.name) ?? o.call.name }
|
|
1029
|
-
spent().then((usage) => stop({ call, usage }))
|
|
1117
|
+
stop({ call: o.call })
|
|
1030
1118
|
}
|
|
1031
1119
|
if (o.dropped) pending.delete(o.dropped)
|
|
1032
1120
|
}
|
|
@@ -1037,10 +1125,8 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1037
1125
|
const closed = new Promise((resolve) => child.on("close", () => { ended ??= { code: -1, error: errorLine || lastLine(stderr) || "the terminal ended" }; poke(); resolve() }))
|
|
1038
1126
|
child.on("error", (e) => { errorLine = e.message })
|
|
1039
1127
|
const send = (v) => { try { child.stdin.write(JSON.stringify(v) + "\n") } catch {} }
|
|
1040
|
-
let
|
|
1041
|
-
const cleanup = async () => {
|
|
1042
|
-
if (cleaned) return
|
|
1043
|
-
cleaned = true
|
|
1128
|
+
let cleaning
|
|
1129
|
+
const cleanup = () => cleaning ??= (async () => {
|
|
1044
1130
|
send({ stop: true })
|
|
1045
1131
|
try { child.stdin.end() } catch {}
|
|
1046
1132
|
const late = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 5000)
|
|
@@ -1050,7 +1136,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1050
1136
|
if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
|
|
1051
1137
|
if (process.env.AGY_TUI_KEEP) return
|
|
1052
1138
|
fs.rmSync(ws, { recursive: true, force: true })
|
|
1053
|
-
}
|
|
1139
|
+
})()
|
|
1054
1140
|
// the request the turn answers now: its end, before the turn's, ends it
|
|
1055
1141
|
let sig = null
|
|
1056
1142
|
const onAbort = () => { cleanup() }
|
|
@@ -1114,14 +1200,16 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1114
1200
|
const begin = async (req) => {
|
|
1115
1201
|
prompt = req.prompt
|
|
1116
1202
|
const media = req.media ?? []
|
|
1203
|
+
live = { text: "", thinking: "", listeners: new Set() }
|
|
1117
1204
|
watch(req.signal)
|
|
1118
1205
|
try {
|
|
1119
1206
|
await booted
|
|
1207
|
+
if (ended || cleaning) throw new Failure(502, "agy's waiting terminal has ended")
|
|
1120
1208
|
} catch (error) {
|
|
1121
1209
|
error.boot = true
|
|
1122
1210
|
throw error
|
|
1123
1211
|
}
|
|
1124
|
-
if (conversation) {
|
|
1212
|
+
if (conversation && !checkedResume) {
|
|
1125
1213
|
// agy that ignored the conversation (its log says it found none) has
|
|
1126
1214
|
// started one of its own, which the message would go to without the
|
|
1127
1215
|
// chat: the request goes without it (handle). Its log says one or
|
|
@@ -1135,12 +1223,21 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1135
1223
|
await cleanup()
|
|
1136
1224
|
throw Object.assign(new Failure(502, `agy didn't start with conversation ${conversation}`), { ignored: true })
|
|
1137
1225
|
}
|
|
1226
|
+
checkedResume = true
|
|
1227
|
+
}
|
|
1228
|
+
if (activeConversation) {
|
|
1138
1229
|
// what the conversation has already, before this turn's message
|
|
1139
|
-
from = { id:
|
|
1140
|
-
stepBase = lastStep(home,
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1230
|
+
from = { id: activeConversation, line: transcriptLines(brain, activeConversation) }
|
|
1231
|
+
stepBase = lastStep(home, activeConversation) ?? -1
|
|
1232
|
+
let baseline = callsAfter(home, activeConversation)
|
|
1233
|
+
for (let i = 0; baseline === null && i < 3; i++) {
|
|
1234
|
+
await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
|
|
1235
|
+
baseline = callsAfter(home, activeConversation)
|
|
1236
|
+
}
|
|
1237
|
+
usageAt = baseline?.cursor ?? null
|
|
1238
|
+
usageBaselineKnown = baseline !== null
|
|
1239
|
+
found = { id: activeConversation, answer: "" }
|
|
1240
|
+
claimed.add(activeConversation)
|
|
1144
1241
|
}
|
|
1145
1242
|
try {
|
|
1146
1243
|
let files
|
|
@@ -1156,7 +1253,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1156
1253
|
// pasted alone, the paths are attached, as files dragged onto the
|
|
1157
1254
|
// terminal are; the turn waits until agy shows every one attached,
|
|
1158
1255
|
// so a path agy took for text is never sent as the message
|
|
1159
|
-
send({ write:
|
|
1256
|
+
send({ write: attachmentPaste(files) })
|
|
1160
1257
|
try {
|
|
1161
1258
|
await waitFor("attachment", () => attached(screen) >= files.length, attachTimeout())
|
|
1162
1259
|
} catch (error) {
|
|
@@ -1169,14 +1266,51 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1169
1266
|
send({ write: "\r" })
|
|
1170
1267
|
// agy has the message once it is in a turn, or its transcript has it
|
|
1171
1268
|
// (a turn that failed at once may never draw "esc to cancel")
|
|
1172
|
-
await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt, null, from)), SUBMIT_MS)
|
|
1269
|
+
await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt, null, from, owns)), SUBMIT_MS)
|
|
1173
1270
|
} catch (error) {
|
|
1174
1271
|
await cleanup()
|
|
1175
1272
|
throw error
|
|
1176
1273
|
}
|
|
1177
1274
|
|
|
1275
|
+
let until = Date.now() + turnTimeout()
|
|
1276
|
+
let batchStep = stepBase
|
|
1277
|
+
let previousCalls = []
|
|
1278
|
+
let usageMissing = false
|
|
1279
|
+
const clientCall = (call) => ({ ...call, name: clients.get(call.name) ?? call.name })
|
|
1280
|
+
const toolStop = async (first, parallel) => {
|
|
1281
|
+
let batch
|
|
1282
|
+
let size = 1
|
|
1283
|
+
const identity = (call) => toolIdentity(call.name, call.arguments)
|
|
1284
|
+
// Give the transcript and the remaining callbacks a short chance
|
|
1285
|
+
// to arrive. The timeout itself is never evidence of a batch.
|
|
1286
|
+
for (let i = 0; i < 7; i++) {
|
|
1287
|
+
if (!found?.id) look()
|
|
1288
|
+
batch = toolBatchOf(brain, found?.id, batchStep)
|
|
1289
|
+
if (batch && batch.calls.includes(identity(first))) {
|
|
1290
|
+
if (!parallel || batch.calls.length > MAX_PARKED || batch.calls.length === 1) break
|
|
1291
|
+
const queued = [first, ...stops.slice(0, batch.calls.length - 1).map((s) => s.call)]
|
|
1292
|
+
if (queued.length === batch.calls.length && queued.every(Boolean) &&
|
|
1293
|
+
JSON.stringify(queued.map(identity).sort()) === JSON.stringify([...batch.calls].sort())) {
|
|
1294
|
+
size = queued.length
|
|
1295
|
+
break
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
if (i < 6) await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
|
|
1299
|
+
}
|
|
1300
|
+
const calls = [first, ...stops.splice(0, size - 1).map((s) => s.call)]
|
|
1301
|
+
if (batch?.calls.includes(identity(first))) {
|
|
1302
|
+
batchStep = batch.step
|
|
1303
|
+
previousCalls = [...batch.calls]
|
|
1304
|
+
for (const call of calls) previousCalls.splice(previousCalls.indexOf(identity(call)), 1)
|
|
1305
|
+
}
|
|
1306
|
+
const usage = await spent()
|
|
1307
|
+
usageMissing = !usage
|
|
1308
|
+
return { calls: calls.map(clientCall), usage: usage ?? { magpie_usage_state: "unavailable" } }
|
|
1309
|
+
}
|
|
1178
1310
|
const turn = {
|
|
1179
1311
|
live,
|
|
1312
|
+
home,
|
|
1313
|
+
scope,
|
|
1180
1314
|
// the request's chat, which the conversation is kept under once the
|
|
1181
1315
|
// turn answers (handle gives each request's that goes on with it)
|
|
1182
1316
|
messages: req.messages ?? null,
|
|
@@ -1185,17 +1319,33 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1185
1319
|
sent: "",
|
|
1186
1320
|
thought: "",
|
|
1187
1321
|
ended: false,
|
|
1188
|
-
next: async () => {
|
|
1322
|
+
next: async (parallel) => {
|
|
1189
1323
|
while (!stops.length) await new Promise((r) => { wake = r })
|
|
1190
|
-
|
|
1324
|
+
const next = stops.shift()
|
|
1325
|
+
if (!next.call) return next
|
|
1326
|
+
const position = previousCalls.indexOf(toolIdentity(next.call.name, next.call.arguments))
|
|
1327
|
+
const latest = position < 0 ? null : toolBatchOf(brain, found?.id, batchStep - 1)
|
|
1328
|
+
if (latest?.step !== batchStep) {
|
|
1329
|
+
previousCalls = []
|
|
1330
|
+
return toolStop(next.call, parallel)
|
|
1331
|
+
}
|
|
1332
|
+
previousCalls.splice(position, 1)
|
|
1333
|
+
const late = usageMissing ? await spent(1, true) : null
|
|
1334
|
+
if (late) usageMissing = false
|
|
1335
|
+
return { calls: [clientCall(next.call)], usage: { magpie_usage_state: "tool_handoff", ...(late ? { magpie_deferred: late } : {}) } }
|
|
1191
1336
|
},
|
|
1192
|
-
//
|
|
1193
|
-
|
|
1194
|
-
if (!pending.
|
|
1195
|
-
|
|
1337
|
+
// Validate the full batch before replying to any call.
|
|
1338
|
+
replyAll: (replies) => {
|
|
1339
|
+
if (!replies.every(({ id }) => pending.has(id))) return false
|
|
1340
|
+
until = Date.now() + turnTimeout()
|
|
1341
|
+
for (const result of replies) {
|
|
1342
|
+
pending.delete(result.id)
|
|
1343
|
+
send({ result })
|
|
1344
|
+
}
|
|
1196
1345
|
return true
|
|
1197
1346
|
},
|
|
1198
1347
|
watch,
|
|
1348
|
+
conversation: () => found?.id,
|
|
1199
1349
|
close: () => cleanup(),
|
|
1200
1350
|
}
|
|
1201
1351
|
|
|
@@ -1204,7 +1354,6 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1204
1354
|
let polled = 0
|
|
1205
1355
|
// a turn waiting on the client's tool has no clock: the time is the
|
|
1206
1356
|
// client's (a parked turn has its own, parkTimeout)
|
|
1207
|
-
let until = Date.now() + turnTimeout()
|
|
1208
1357
|
try {
|
|
1209
1358
|
// back at its prompt with nothing in the transcript for a while:
|
|
1210
1359
|
// the turn failed, and what agy drew says why (a quota, a refusal)
|
|
@@ -1232,64 +1381,90 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1232
1381
|
if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
|
|
1233
1382
|
// the whole of it, read before the conversation goes
|
|
1234
1383
|
publish(liveReply(home, found.id, stepBase))
|
|
1235
|
-
last = { text: found.answer, usage: await spent() }
|
|
1384
|
+
last = { text: found.answer, usage: await spent() ?? { magpie_usage_state: "unavailable" } }
|
|
1236
1385
|
} catch (error) {
|
|
1237
1386
|
last = { error }
|
|
1238
1387
|
} finally {
|
|
1239
|
-
//
|
|
1240
|
-
//
|
|
1241
|
-
// turn's files go after, once agy has.
|
|
1388
|
+
// The client can finish while agy waits for another message or
|
|
1389
|
+
// shuts down. Keep the live terminal only for this conversation.
|
|
1242
1390
|
turn.ended = true
|
|
1391
|
+
if (parked.get(turn.parkedKey)?.turn === turn) takeParked(turn.parkedKey)
|
|
1243
1392
|
watch(null)
|
|
1244
1393
|
stop(last)
|
|
1245
|
-
// an answered turn's conversation is kept for the chat's next
|
|
1246
|
-
// request, from now (that request can come before agy has gone,
|
|
1247
|
-
// and waits for it); any other goes
|
|
1248
1394
|
const id = found?.id
|
|
1249
|
-
const answered = Boolean(resumable && last.text && id && turn.messages)
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1395
|
+
const answered = Boolean(resumable && last.text && CONVERSATION_ID.test(id ?? "") && turn.messages && carrying())
|
|
1396
|
+
if (answered) {
|
|
1397
|
+
activeConversation = id
|
|
1398
|
+
const next = { agy, home, model, tools, helper, conversation: id, scope }
|
|
1399
|
+
const key = spareKey(next)
|
|
1400
|
+
const reused = !ended && !cleaning && leaveSpare(key, next, terminal)
|
|
1401
|
+
keep(home, scope, turn.messages, id, [found.answer, since(turn, live.text)], { ws, ownHome }, reused ? key : null, reused ? null : leaving(cleanup()))
|
|
1402
|
+
} else {
|
|
1403
|
+
await leaving(cleanup().then(() => forget(brain, id)))
|
|
1404
|
+
}
|
|
1255
1405
|
}
|
|
1256
1406
|
})()
|
|
1257
1407
|
return turn
|
|
1258
1408
|
}
|
|
1259
|
-
|
|
1409
|
+
const terminal = { begin, alive: () => !ended && !cleaning, close: cleanup }
|
|
1410
|
+
return terminal
|
|
1260
1411
|
}
|
|
1261
1412
|
|
|
1262
1413
|
// ---- turns waiting on the client's tool
|
|
1263
1414
|
|
|
1264
1415
|
// A turn that stopped at a call waits, its agy running, for the request
|
|
1265
|
-
// that brings the call's result
|
|
1266
|
-
//
|
|
1267
|
-
// result, when it comes, starts a turn of its own, with the conversation
|
|
1268
|
-
// typed in as text.
|
|
1416
|
+
// that brings the call's result. A late result can still start a new turn
|
|
1417
|
+
// using the supplied history.
|
|
1269
1418
|
const parked = new Map()
|
|
1270
1419
|
|
|
1271
|
-
function
|
|
1420
|
+
function parkedKey(home, scope, id) {
|
|
1421
|
+
return JSON.stringify([home, scope, id])
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
function park(calls, turn) {
|
|
1425
|
+
const ids = calls.map((call) => call.id)
|
|
1426
|
+
const key = parkedKey(turn.home, turn.scope, ids[0])
|
|
1427
|
+
if (parked.size >= MAX_PARKED || parked.has(key)) {
|
|
1428
|
+
turn.close()
|
|
1429
|
+
throw new Failure(503, "agy-tui cannot accept another waiting tool call")
|
|
1430
|
+
}
|
|
1272
1431
|
const timer = setTimeout(() => {
|
|
1273
|
-
if (parked.get(
|
|
1274
|
-
|
|
1432
|
+
if (parked.get(key)?.turn !== turn) return
|
|
1433
|
+
takeParked(key)
|
|
1275
1434
|
turn.close()
|
|
1276
1435
|
}, parkTimeout())
|
|
1277
1436
|
timer.unref?.()
|
|
1278
|
-
parked.set(
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1437
|
+
parked.set(key, { turn, timer, ids })
|
|
1438
|
+
turn.parkedKey = key
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
// The gateway can append reminders or tool images as user messages.
|
|
1442
|
+
const NOTE_ROLES = new Set(["user", "system", "developer"])
|
|
1443
|
+
|
|
1444
|
+
export function resultOf(messages) {
|
|
1445
|
+
if (!Array.isArray(messages)) return null
|
|
1446
|
+
const assistant = messages.findLastIndex((m) => m?.role === "assistant")
|
|
1447
|
+
const start = assistant < 0 ? messages.findLastIndex((m) => m?.role !== "tool") : assistant
|
|
1448
|
+
const [tool, ...notes] = messages.slice(start + 1)
|
|
1449
|
+
if (tool?.role !== "tool") return null
|
|
1450
|
+
const calls = messages[assistant]?.tool_calls
|
|
1451
|
+
if (Array.isArray(calls) && !calls.some((call) => call?.id === tool.tool_call_id)) return null
|
|
1452
|
+
return { tool, notes }
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
function traceToolContinuation(request, outcome, reason, conversation) {
|
|
1456
|
+
if (process.env.AGY_TUI_TRACE_RESUME === "1") {
|
|
1457
|
+
console.error(JSON.stringify({ plugin: PROVIDER_ID, request, event: "tool_continuation", outcome, reason, conversation }))
|
|
1284
1458
|
}
|
|
1285
1459
|
}
|
|
1286
1460
|
|
|
1287
|
-
function
|
|
1288
|
-
const p =
|
|
1461
|
+
function takeParked(key) {
|
|
1462
|
+
const p = parked.get(key)
|
|
1289
1463
|
if (!p) return null
|
|
1290
|
-
parked.delete(
|
|
1464
|
+
parked.delete(key)
|
|
1291
1465
|
clearTimeout(p.timer)
|
|
1292
|
-
|
|
1466
|
+
delete p.turn.parkedKey
|
|
1467
|
+
return p
|
|
1293
1468
|
}
|
|
1294
1469
|
|
|
1295
1470
|
// toolContent is a tool message's content as the tool server answers it: a
|
|
@@ -1310,41 +1485,24 @@ export function toolContent(content) {
|
|
|
1310
1485
|
return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
|
|
1311
1486
|
}
|
|
1312
1487
|
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
// images a tool returned, which magpie gives in a user message after the
|
|
1317
|
-
// tool message (a tool message holds text only)
|
|
1318
|
-
const NOTE_ROLES = new Set(["user", "system", "developer"])
|
|
1488
|
+
function contentBlocks(content) {
|
|
1489
|
+
return typeof content === "string" ? [{ type: "text", text: content }] : content
|
|
1490
|
+
}
|
|
1319
1491
|
|
|
1320
|
-
//
|
|
1321
|
-
// and
|
|
1322
|
-
// came after the request's last assistant message is tool messages, then
|
|
1323
|
-
// notes alone.
|
|
1324
|
-
export function resultOf(messages) {
|
|
1325
|
-
if (!Array.isArray(messages)) return null
|
|
1326
|
-
const tail = messages.slice(messages.findLastIndex((m) => m?.role === "assistant") + 1)
|
|
1327
|
-
const k = tail.findLastIndex((m) => m?.role === "tool")
|
|
1328
|
-
if (k < 0 || !tail.slice(0, k).every((m) => m?.role === "tool")) return null
|
|
1329
|
-
const notes = tail.slice(k + 1)
|
|
1330
|
-
if (!notes.every((m) => NOTE_ROLES.has(m?.role))) return null
|
|
1331
|
-
return { tool: tail[k], notes }
|
|
1332
|
-
}
|
|
1333
|
-
|
|
1334
|
-
// resultContent is what agy gets as a call's result: the tool's content,
|
|
1335
|
-
// and the notes' text and images after it, so a parked turn goes on with
|
|
1336
|
-
// them (a note it didn't get would make the chat look new, typed in whole
|
|
1337
|
-
// into a new agy: a whole new prompt for the model's cache, every call,
|
|
1338
|
-
// plugins#1963). A note's part a result can't carry throws.
|
|
1492
|
+
// The CLI helper replies to agy through MCP. Keep the tool's own output
|
|
1493
|
+
// first and label the later user content as such in separate MCP blocks.
|
|
1339
1494
|
export function resultContent(tool, notes = []) {
|
|
1340
|
-
const
|
|
1341
|
-
if (!notes.length) return
|
|
1342
|
-
const blocks =
|
|
1343
|
-
for (const
|
|
1344
|
-
|
|
1345
|
-
|
|
1495
|
+
const content = toolContent(tool.content)
|
|
1496
|
+
if (!notes.length) return content
|
|
1497
|
+
const blocks = [...contentBlocks(content)]
|
|
1498
|
+
for (const message of notes) {
|
|
1499
|
+
if (!NOTE_ROLES.has(message?.role) || (typeof message.content !== "string" && !Array.isArray(message.content))) {
|
|
1500
|
+
throw new Failure(400, "the tool result is followed by messages that need a new turn")
|
|
1501
|
+
}
|
|
1502
|
+
const role = message.role[0].toUpperCase() + message.role.slice(1)
|
|
1503
|
+
blocks.push({ type: "text", text: `[${role} message after the tool result]` }, ...contentBlocks(toolContent(message.content)))
|
|
1346
1504
|
}
|
|
1347
|
-
return blocks
|
|
1505
|
+
return blocks
|
|
1348
1506
|
}
|
|
1349
1507
|
|
|
1350
1508
|
// forget removes the conversation agy kept for a turn from the account's
|
|
@@ -1488,30 +1646,25 @@ function prune(home, list) {
|
|
|
1488
1646
|
}
|
|
1489
1647
|
|
|
1490
1648
|
// keep puts an answered turn's conversation on the account's list, under
|
|
1491
|
-
// the request's chat, with the words of the answer
|
|
1492
|
-
// had it,
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1649
|
+
// the request's chat, with the words of the answer as the client may have
|
|
1650
|
+
// had it, and its live terminal if there is one.
|
|
1651
|
+
function keptKey(scope, messages) {
|
|
1652
|
+
const history = chatKey(messages)
|
|
1653
|
+
return scope ? sha(JSON.stringify([scope, history])) : history
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
function keep(home, scope, messages, id, replies, place, spare, gone) {
|
|
1496
1657
|
const list = keptOf(home)
|
|
1497
|
-
const key =
|
|
1658
|
+
const key = keptKey(scope, messages)
|
|
1498
1659
|
const old = list.get(key)
|
|
1499
1660
|
if (old) {
|
|
1500
1661
|
list.delete(key)
|
|
1501
1662
|
if (old.id !== id) dropKept(home, old)
|
|
1502
1663
|
}
|
|
1503
|
-
const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), place
|
|
1664
|
+
const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), place, spare, ready: Promise.resolve(gone).catch(() => {}) }
|
|
1504
1665
|
list.set(key, e)
|
|
1505
1666
|
prune(home, list)
|
|
1506
1667
|
saveKept(home, list)
|
|
1507
|
-
if (process.env.AGY_TUI_SPARES === "0") return
|
|
1508
|
-
e.ready.then(() => {
|
|
1509
|
-
// not when the chat went on, or the conversation went, first
|
|
1510
|
-
if (list.get(key) !== e) return
|
|
1511
|
-
const next = { ...opts, conversation: id }
|
|
1512
|
-
e.spare = spareKey(next)
|
|
1513
|
-
leaveSpare(e.spare, next)
|
|
1514
|
-
})
|
|
1515
1668
|
}
|
|
1516
1669
|
|
|
1517
1670
|
function carrying() {
|
|
@@ -1523,7 +1676,7 @@ function carrying() {
|
|
|
1523
1676
|
// or null: the chat, up to its last answer, is one a turn answered, the
|
|
1524
1677
|
// answer is the one that turn gave, and what comes after it is the user's
|
|
1525
1678
|
// alone and fits in one message.
|
|
1526
|
-
export async function carriedOn(home, messages, { agy, model, tools }) {
|
|
1679
|
+
export async function carriedOn(home, messages, { agy, model, tools, scope = "" }) {
|
|
1527
1680
|
if (!carrying() || !Array.isArray(messages)) return null
|
|
1528
1681
|
const j = messages.findLastIndex((m) => m?.role === "assistant")
|
|
1529
1682
|
if (j < 0) return null
|
|
@@ -1532,7 +1685,7 @@ export async function carriedOn(home, messages, { agy, model, tools }) {
|
|
|
1532
1685
|
if (!tail.length || !tail.every((m) => m?.role === "user")) return null
|
|
1533
1686
|
if (Array.isArray(answer.tool_calls) && answer.tool_calls.length) return null
|
|
1534
1687
|
const list = keptOf(home)
|
|
1535
|
-
const key =
|
|
1688
|
+
const key = keptKey(scope, messages.slice(0, j))
|
|
1536
1689
|
const e = list.get(key)
|
|
1537
1690
|
if (!e || !e.replies.includes(replyKey(answer.content))) return null
|
|
1538
1691
|
const { prompt, media } = turnOf(tail, Infinity)
|
|
@@ -1542,7 +1695,7 @@ export async function carriedOn(home, messages, { agy, model, tools }) {
|
|
|
1542
1695
|
// the agy of the turn that kept it gone, and its spare, when it isn't
|
|
1543
1696
|
// one this request takes, before another agy opens the conversation
|
|
1544
1697
|
await e.ready
|
|
1545
|
-
if (e.spare && e.spare !== spareKey({ agy, home, model, tools, helper: process.env.MAGPIE_EXE, conversation: e.id })) await dropSpare(e.spare)
|
|
1698
|
+
if (e.spare && e.spare !== spareKey({ agy, home, model, tools, helper: process.env.MAGPIE_EXE, conversation: e.id, scope })) await dropSpare(e.spare)
|
|
1546
1699
|
if (!fs.existsSync(path.join(brainOf(home), e.id))) {
|
|
1547
1700
|
forget(brainOf(home), e.id)
|
|
1548
1701
|
return null
|
|
@@ -1569,11 +1722,11 @@ function since(turn, text, had = turn.sent) {
|
|
|
1569
1722
|
}
|
|
1570
1723
|
|
|
1571
1724
|
// stopped ends a response at a call: the turn waits for its result
|
|
1572
|
-
function stopped(turn,
|
|
1725
|
+
function stopped(turn, calls) {
|
|
1573
1726
|
turn.watch(null)
|
|
1574
1727
|
turn.sent = turn.live.text
|
|
1575
1728
|
turn.thought = turn.live.thinking
|
|
1576
|
-
park(
|
|
1729
|
+
park(calls, turn)
|
|
1577
1730
|
}
|
|
1578
1731
|
|
|
1579
1732
|
function completion(id, model, message, finish, usage = null) {
|
|
@@ -1588,15 +1741,15 @@ function completion(id, model, message, finish, usage = null) {
|
|
|
1588
1741
|
}
|
|
1589
1742
|
|
|
1590
1743
|
// answered is the turn's next stop as one completion.
|
|
1591
|
-
async function answered(id, model, turn) {
|
|
1592
|
-
const s = await turn.next()
|
|
1744
|
+
async function answered(id, model, turn, parallel) {
|
|
1745
|
+
const s = await turn.next(parallel)
|
|
1593
1746
|
if (s.error) throw s.error
|
|
1594
1747
|
const thinking = since(turn, turn.live.thinking, turn.thought)
|
|
1595
1748
|
const reasoning = thinking ? { reasoning_content: thinking } : {}
|
|
1596
|
-
if (s.
|
|
1749
|
+
if (s.calls) {
|
|
1597
1750
|
const text = since(turn, turn.live.text)
|
|
1598
|
-
stopped(turn, s.
|
|
1599
|
-
return completion(id, model, { content: text || null, ...reasoning, tool_calls:
|
|
1751
|
+
stopped(turn, s.calls)
|
|
1752
|
+
return completion(id, model, { content: text || null, ...reasoning, tool_calls: s.calls.map((call) => toolCallOf(call)) }, "tool_calls", s.usage)
|
|
1600
1753
|
}
|
|
1601
1754
|
return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop", s.usage)
|
|
1602
1755
|
}
|
|
@@ -1605,7 +1758,7 @@ async function answered(id, model, turn) {
|
|
|
1605
1758
|
// writes it (turn.live), each piece once; at the end, what the store has
|
|
1606
1759
|
// whole, or, with nothing read from it, the transcript's answer; at a call,
|
|
1607
1760
|
// the call.
|
|
1608
|
-
export function streamOf(id, model, turn) {
|
|
1761
|
+
export function streamOf(id, model, turn, parallel = true) {
|
|
1609
1762
|
const { live } = turn
|
|
1610
1763
|
const enc = new TextEncoder()
|
|
1611
1764
|
const created = Math.floor(Date.now() / 1000)
|
|
@@ -1651,13 +1804,13 @@ export function streamOf(id, model, turn) {
|
|
|
1651
1804
|
quiet = Date.now()
|
|
1652
1805
|
}, 5_000)
|
|
1653
1806
|
try {
|
|
1654
|
-
const s = await turn.next()
|
|
1807
|
+
const s = await turn.next(parallel)
|
|
1655
1808
|
halt()
|
|
1656
1809
|
if (s.error) throw s.error
|
|
1657
1810
|
send()
|
|
1658
|
-
if (s.
|
|
1659
|
-
stopped(turn, s.
|
|
1660
|
-
c.enqueue(enc.encode(chunk({ tool_calls:
|
|
1811
|
+
if (s.calls) {
|
|
1812
|
+
stopped(turn, s.calls)
|
|
1813
|
+
c.enqueue(enc.encode(chunk({ tool_calls: s.calls.map(toolCallOf) })))
|
|
1661
1814
|
c.enqueue(enc.encode(chunk({}, "tool_calls", s.usage)))
|
|
1662
1815
|
} else {
|
|
1663
1816
|
if (!sent && s.text) c.enqueue(enc.encode(chunk({ content: s.text })))
|
|
@@ -1675,9 +1828,10 @@ export function streamOf(id, model, turn) {
|
|
|
1675
1828
|
})
|
|
1676
1829
|
}
|
|
1677
1830
|
|
|
1678
|
-
function respond(id, model, turn,
|
|
1679
|
-
|
|
1680
|
-
return
|
|
1831
|
+
function respond(id, model, turn, body) {
|
|
1832
|
+
const parallel = body.parallel_tool_calls !== false
|
|
1833
|
+
if (body.stream) return new Response(streamOf(id, model, turn, parallel), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
|
|
1834
|
+
return answered(id, model, turn, parallel).then(
|
|
1681
1835
|
(body) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }),
|
|
1682
1836
|
(error) => jsonError(error.status ?? 502, error.message),
|
|
1683
1837
|
)
|
|
@@ -1695,39 +1849,58 @@ export async function handle(home, input, init = {}) {
|
|
|
1695
1849
|
}
|
|
1696
1850
|
const signal = init.signal ?? input?.signal
|
|
1697
1851
|
const id = `chatcmpl-${randomBytes(12).toString("hex")}`
|
|
1852
|
+
const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined) ?? {})
|
|
1853
|
+
const caller = headers.get("x-magpie-caller-id") ?? ""
|
|
1854
|
+
const session = headers.get("x-magpie-session") || headers.get("x-magpie-conversation") || ""
|
|
1855
|
+
const subagent = headers.get("x-magpie-subagent") ?? ""
|
|
1856
|
+
if (process.env.AGY_TUI_REQUIRE_CALLER === "1" && !caller) {
|
|
1857
|
+
return jsonError(403, "agy-tui shared mode requires an authenticated Magpie gateway caller key")
|
|
1858
|
+
}
|
|
1859
|
+
const scope = caller || session || subagent ? sha(JSON.stringify([caller, session, subagent])) : ""
|
|
1860
|
+
if (!home) return jsonError(401, "agy-tui: no account; sign in again", { "X-Magpie-Sign-In": "expired" })
|
|
1861
|
+
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" })
|
|
1698
1862
|
const model = String(body.model ?? "")
|
|
1699
1863
|
// the level of a model listed with its levels as variants, as the
|
|
1700
1864
|
// agent asked (efforts.mjs); a level's own id is run as it is
|
|
1701
|
-
const said =
|
|
1702
|
-
const agyModel =
|
|
1703
|
-
//
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
const
|
|
1708
|
-
const
|
|
1865
|
+
const said = headers.get("x-magpie-effort") ?? ""
|
|
1866
|
+
const agyModel = agyModelOf(model, (modelLists.get(home) ?? readModelList(home))?.list, body, said)
|
|
1867
|
+
// Chat translation can put a user message immediately after a tool result.
|
|
1868
|
+
const continuation = resultOf(body.messages)
|
|
1869
|
+
if (continuation) {
|
|
1870
|
+
const { tool: result, notes } = continuation
|
|
1871
|
+
const noteAt = notes.findIndex((message) => message?.role !== "tool")
|
|
1872
|
+
const results = [result, ...(noteAt < 0 ? notes : notes.slice(0, noteAt))]
|
|
1873
|
+
const keys = results.map((message) => parkedKey(home, scope, message.tool_call_id))
|
|
1874
|
+
const key = keys.find((candidate) => parked.has(candidate))
|
|
1875
|
+
const entry = key && parked.get(key)
|
|
1876
|
+
const waiting = entry?.turn
|
|
1709
1877
|
if (waiting && !waiting.ended) {
|
|
1710
|
-
let
|
|
1711
|
-
try {
|
|
1712
|
-
|
|
1713
|
-
|
|
1878
|
+
let replies
|
|
1879
|
+
try {
|
|
1880
|
+
if (results.length === entry.ids.length && entry.ids.every((id) => results.some((message) => message.tool_call_id === id))) {
|
|
1881
|
+
const trailing = notes.slice(results.length - 1)
|
|
1882
|
+
replies = results.map((message, i) => ({
|
|
1883
|
+
id: message.tool_call_id,
|
|
1884
|
+
content: resultContent(message, i === results.length - 1 ? trailing : []),
|
|
1885
|
+
isError: message.is_error === true,
|
|
1886
|
+
}))
|
|
1887
|
+
}
|
|
1888
|
+
} catch {
|
|
1889
|
+
// A fresh prompt can carry content the MCP reply cannot, such as video.
|
|
1714
1890
|
}
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
if (content !== null) {
|
|
1891
|
+
takeParked(key)
|
|
1892
|
+
if (replies && waiting.replyAll(replies)) {
|
|
1718
1893
|
waiting.messages = body.messages
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
}
|
|
1894
|
+
waiting.watch(signal)
|
|
1895
|
+
traceToolContinuation(id, "resumed", undefined, waiting.conversation())
|
|
1896
|
+
return respond(id, model, waiting, body)
|
|
1723
1897
|
}
|
|
1898
|
+
traceToolContinuation(id, "replay", replies ? "tool_call_no_longer_pending" : "unsupported_or_incomplete_tool_results")
|
|
1899
|
+
} else {
|
|
1900
|
+
traceToolContinuation(id, "replay", "no_matching_parked_turn")
|
|
1724
1901
|
}
|
|
1725
|
-
// agy no longer waits on it: a turn of its own, the conversation
|
|
1726
|
-
// typed in as text
|
|
1727
1902
|
waiting?.close()
|
|
1728
1903
|
}
|
|
1729
|
-
if (!home) return jsonError(401, "agy-tui: no account; sign in again", { "X-Magpie-Sign-In": "expired" })
|
|
1730
|
-
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" })
|
|
1731
1904
|
const agy = findAgy()
|
|
1732
1905
|
if (!agy) return jsonError(503, `agy CLI not found on this machine: ${AGY_MANUAL}`)
|
|
1733
1906
|
const refusal = await agyRefusal(agy)
|
|
@@ -1736,38 +1909,46 @@ export async function handle(home, input, init = {}) {
|
|
|
1736
1909
|
let carried = null
|
|
1737
1910
|
try {
|
|
1738
1911
|
const tools = mcpToolsOf(body)
|
|
1912
|
+
const messages = continued(body.messages)
|
|
1739
1913
|
const resumable = (await agyHelp(agy)).includes("--conversation")
|
|
1740
|
-
// the chat's conversation, kept from its last answer, goes on with the
|
|
1741
|
-
// new messages alone; any other is typed in whole, and one too long
|
|
1742
|
-
// for one message is written into agy's store as a conversation
|
|
1743
|
-
// (seedOf) that the turn starts with, its newest message typed
|
|
1744
|
-
carried = resumable ? await carriedOn(home, body.messages, { agy, model: agyModel, tools }) : null
|
|
1745
1914
|
let paste = null
|
|
1746
|
-
|
|
1915
|
+
const rebuild = () => {
|
|
1747
1916
|
try {
|
|
1748
|
-
paste = turnOf(
|
|
1917
|
+
paste = turnOf(messages)
|
|
1749
1918
|
} catch (error) {
|
|
1750
|
-
if (!error.long || !resumable) throw error
|
|
1919
|
+
if (!error.long || !resumable || process.env.AGY_TUI_SEED === "0") throw error
|
|
1751
1920
|
}
|
|
1752
|
-
if (resumable && (!paste || paste.cut) && process.env.AGY_TUI_SEED !== "0")
|
|
1753
|
-
|
|
1921
|
+
if (resumable && (!paste || paste.cut) && process.env.AGY_TUI_SEED !== "0") {
|
|
1922
|
+
const seeded = seedOf(home, messages)
|
|
1923
|
+
if (seeded) return seeded
|
|
1924
|
+
}
|
|
1925
|
+
paste ??= turnOf(messages)
|
|
1926
|
+
return null
|
|
1754
1927
|
}
|
|
1755
1928
|
const start = async (c) => {
|
|
1756
1929
|
const { prompt, media } = c ?? paste
|
|
1757
1930
|
// agy attaches a video for any model, but only Gemini's see one
|
|
1758
1931
|
if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw unfit(`${model || "this model"} takes no video; a Gemini model does`)
|
|
1759
|
-
return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages
|
|
1932
|
+
return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages, scope })
|
|
1760
1933
|
}
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1934
|
+
// Local state is an optimization. A different worker can start from
|
|
1935
|
+
// the request history alone, even if agy has lost a retained session.
|
|
1936
|
+
carried = resumable ? await carriedOn(home, messages, { agy, model: agyModel, tools, scope }) : null
|
|
1937
|
+
carried ??= rebuild()
|
|
1938
|
+
for (;;) {
|
|
1939
|
+
try {
|
|
1940
|
+
turn = await start(carried)
|
|
1941
|
+
break
|
|
1942
|
+
} catch (error) {
|
|
1943
|
+
if (!carried || !error.ignored) throw error
|
|
1944
|
+
const previous = carried
|
|
1945
|
+
carried = null
|
|
1946
|
+
forget(brainOf(home), previous.id)
|
|
1947
|
+
// Rebuild once from the full request if the old session vanished.
|
|
1948
|
+
// If agy also ignores a newly seeded store, use the prompt it takes.
|
|
1949
|
+
if (!previous.seeded) carried = rebuild()
|
|
1950
|
+
else paste ??= turnOf(messages)
|
|
1951
|
+
}
|
|
1771
1952
|
}
|
|
1772
1953
|
} catch (error) {
|
|
1773
1954
|
// a conversation taken for a turn that never began is in a state
|
|
@@ -1775,7 +1956,7 @@ export async function handle(home, input, init = {}) {
|
|
|
1775
1956
|
if (carried) forget(brainOf(home), carried.id)
|
|
1776
1957
|
return jsonError(error.status ?? 502, error.message, error.headers)
|
|
1777
1958
|
}
|
|
1778
|
-
return respond(id, model, turn, body
|
|
1959
|
+
return respond(id, model, turn, body)
|
|
1779
1960
|
}
|
|
1780
1961
|
|
|
1781
1962
|
// ---- the plugin
|
package/live.mjs
CHANGED
|
@@ -106,6 +106,27 @@ function fields(buf, fn) {
|
|
|
106
106
|
|
|
107
107
|
const bytesOf = (v) => v instanceof Uint8Array ? v : ArrayBuffer.isView(v) ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : v instanceof ArrayBuffer ? new Uint8Array(v) : null
|
|
108
108
|
|
|
109
|
+
// The workspace URI in a new conversation's trajectory metadata.
|
|
110
|
+
export function conversationWorkspace(home, id) {
|
|
111
|
+
const file = conversationDb(home, id)
|
|
112
|
+
const open = loadOpener()
|
|
113
|
+
if (!file || !open || !fs.existsSync(file)) return null
|
|
114
|
+
let db
|
|
115
|
+
try {
|
|
116
|
+
db = open(file)
|
|
117
|
+
const metadata = bytesOf(db.all("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'")[0]?.data)
|
|
118
|
+
let uri = null
|
|
119
|
+
if (metadata && fields(metadata, (field, wire, value) => {
|
|
120
|
+
if (field === 7 && wire === 2) uri = new TextDecoder().decode(value)
|
|
121
|
+
})) return uri
|
|
122
|
+
} catch {
|
|
123
|
+
// agy may still be writing the store.
|
|
124
|
+
} finally {
|
|
125
|
+
db?.close()
|
|
126
|
+
}
|
|
127
|
+
return null
|
|
128
|
+
}
|
|
129
|
+
|
|
109
130
|
// stepOf is a PLANNER_RESPONSE step's text (field 20.1 of its payload)
|
|
110
131
|
// and thinking (field 20.3), each "" when it has none yet; null when the
|
|
111
132
|
// payload isn't one.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-agy-tui-auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.22",
|
|
4
4
|
"description": "Magpie/OpenCode model provider that runs Antigravity's models through agy's own interactive mode: each request is typed into the real agy TUI and its answer streamed from agy's own conversation store as the model writes it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./opencode.mjs",
|