@magpie-community/opencode-agy-tui-auth 0.1.20 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -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 longest a turn may take, 15 minutes by default.
38
- - `AGY_TUI_PARK_TIMEOUT_MS`: how long a turn waits for a tool call's result, 10 minutes by default.
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`:一轮的最长时间,默认 15 分钟。
38
- - `AGY_TUI_PARK_TIMEOUT_MS`:一轮等待工具调用结果的最长时间,默认 10 分钟。
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
- // how many turns may wait on a call's result at once
93
- const MAX_PARKED = 8
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 : 10 * 60_000
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 : 15 * 60_000
113
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_TIMEOUT_MS
112
114
  }
113
115
 
114
116
  // ---- accounts
@@ -446,6 +448,11 @@ 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
+
449
456
  // turnOf is what goes into agy's prompt: the images and videos, attached in
450
457
  // the order they came, and the text pasted after them, the last user
451
458
  // message alone, or with the instructions and the conversation before it.
@@ -479,7 +486,7 @@ export function turnOf(messages, budget = INPUT_BUDGET) {
479
486
  const text = said.filter(Boolean).join("\n")
480
487
  if (text) turns.push({ role: m.role, text, m })
481
488
  } else if (m?.role === "tool") {
482
- turns.push({ role: "tool", text: `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}`, m })
489
+ turns.push({ role: "tool", text: toolResultText(m, media), m })
483
490
  }
484
491
  }
485
492
  return { system, turns }
@@ -576,7 +583,7 @@ export function seedSteps(messages, budget = INPUT_BUDGET) {
576
583
  const text = said.filter(Boolean).join("\n")
577
584
  if (text) add("model", text)
578
585
  } else if (m?.role === "tool") {
579
- add("user", `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}`)
586
+ add("user", toolResultText(m, media))
580
587
  }
581
588
  }
582
589
  if (groups.at(-1)?.role !== "user") throw refuse("the last message is not the user's or a tool's result")
@@ -632,6 +639,19 @@ export function pastedPaths(files, platform = process.platform) {
632
639
  }).join("\n")
633
640
  }
634
641
 
642
+ export function attachmentPaste(files, platform = process.platform) {
643
+ const paste = `\x1b[200~${pastedPaths(files, platform)}\x1b[201~`
644
+ if (platform !== "win32") return paste
645
+ // ConPTY drops the paste markers from ordinary VT input. Win32 input
646
+ // mode carries the whole paste as Unicode key-down events, markers and all.
647
+ // Each record is CSI Vk;Sc;Uc;Kd;Cs;Rc_, with Uc one UTF-16 code unit.
648
+ let input = ""
649
+ for (let i = 0; i < paste.length; i++) {
650
+ input += `\x1b[0;0;${paste.charCodeAt(i)};1;0;1_`
651
+ }
652
+ return input
653
+ }
654
+
635
655
  // attached is how many files agy's prompt shows attached ("📎 2 media
636
656
  // attached"), 0 for none.
637
657
  export function attached(screen) {
@@ -649,7 +669,7 @@ const claimed = new Set()
649
669
  // call there too. A turn that carries a conversation on (`from`: its id
650
670
  // and the transcript's length in lines before the turn) looks in that
651
671
  // one alone, past those lines.
652
- export function answerOf(brain, before, prompt, own = null, from = null) {
672
+ export function answerOf(brain, before, prompt, own = null, from = null, owns = null) {
653
673
  // its own words, not an image's or a video's mark, which other turns have too
654
674
  const lines = prompt.split("\n").map((l) => l.trim())
655
675
  const snip = (lines.find((l) => l.replace(MEDIA_MARK, "").trim()) ?? lines.find(Boolean))?.slice(0, 60) ?? ""
@@ -676,13 +696,39 @@ export function answerOf(brain, before, prompt, own = null, from = null) {
676
696
  mine = true
677
697
  }
678
698
  }
679
- if (mine) return { id, answer }
699
+ if (mine && (from || !owns || id === own || owns(id))) return { id, answer }
680
700
  }
681
701
  return null
682
702
  }
683
703
 
684
704
  const transcriptOf = (brain, id) => path.join(brain, id, ".system_generated", "logs", "transcript_full.jsonl")
685
705
 
706
+ // A completed planner row declares the full batch. The helper's callbacks
707
+ // alone cannot tell us if another call belongs to the same generation.
708
+ function toolBatchOf(brain, id, after) {
709
+ if (!id) return null
710
+ let lines
711
+ try { lines = fs.readFileSync(transcriptOf(brain, id), "utf8").trimEnd().split("\n") } catch { return null }
712
+ for (const line of lines.reverse()) {
713
+ let row
714
+ try { row = JSON.parse(line) } catch { continue }
715
+ if (row.type !== "PLANNER_RESPONSE") continue
716
+ if (row.status !== "DONE" || !Number.isInteger(row.step_index) || row.step_index <= after || !row.tool_calls?.length) return null
717
+ return { step: row.step_index, calls: row.tool_calls.map((call) => toolIdentity(call.name, call.args)) }
718
+ }
719
+ return null
720
+ }
721
+
722
+ function toolIdentity(name, args) {
723
+ const sorted = (value) => {
724
+ if (Array.isArray(value)) return value.map(sorted)
725
+ if (!value || typeof value !== "object") return value
726
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sorted(value[key])]))
727
+ }
728
+ const { toolSummary, ...parameters } = args ?? {}
729
+ return JSON.stringify([String(name ?? "").replace(/^mcp_magpie_/, ""), sorted(parameters)])
730
+ }
731
+
686
732
  // transcriptLines is how many lines the conversation's transcript has
687
733
  function transcriptLines(brain, id) {
688
734
  try { return fs.readFileSync(transcriptOf(brain, id), "utf8").split("\n").length - 1 } catch { return 0 }
@@ -793,8 +839,8 @@ export function mcpConfig(mcp, tools) {
793
839
  // own tools stay off. With a conversation (an id agy kept, carried), agy
794
840
  // starts with it and the prompt carries it on; `messages` is the request's
795
841
  // 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 }
842
+ export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE, conversation = null, messages = null, place = null, scope = "" }) {
843
+ const opts = { agy, home, model, tools, helper, conversation, place, scope }
798
844
  const key = spareKey(opts)
799
845
  let turn = null
800
846
  const spare = await takeSpare(key)
@@ -820,56 +866,59 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
820
866
  // the account, its plan and its models before it takes a message (a median
821
867
  // of 3.8s a start on a real account, 11s at worst). So each turn leaves an
822
868
  // agy started for the next request with the same account, model and tools,
823
- // which only types its message into it. One waits per kind, for
824
- // SPARE_IDLE_MS at most.
825
- const SPARE_IDLE_MS = 10 * 60_000
869
+ // which only types its message into it. A finished chat can also keep the
870
+ // terminal it just used. Both kinds share the same idle limit and pool.
871
+ const SPARE_IDLE_MS = DEFAULT_TIMEOUT_MS
826
872
  const MAX_SPARES = 3
827
873
  const spares = new Map()
874
+ const closingSpares = new Map()
828
875
 
829
- function spareKey({ agy, home, model, tools, helper, conversation }) {
830
- return createHash("sha256").update(JSON.stringify([agy, home, model ?? "", tools, helper ?? "", conversation ?? ""])).digest("hex")
876
+ function spareKey({ agy, home, model, tools, helper, conversation, scope = "" }) {
877
+ return sha(JSON.stringify([agy, home, model ?? "", tools, helper ?? "", conversation ?? "", scope]))
831
878
  }
832
879
 
833
880
  async function takeSpare(key) {
834
881
  const s = spares.get(key)
835
- if (!s) return null
882
+ if (!s) {
883
+ await closingSpares.get(key)
884
+ return null
885
+ }
836
886
  spares.delete(key)
837
887
  clearTimeout(s.timer)
838
888
  const a = await s.started.catch(() => null)
839
889
  if (a?.alive()) return a
840
- a?.close()
890
+ await a?.close()
841
891
  return null
842
892
  }
843
893
 
844
- // dropSpare ends the spare of key, if one waits; it resolves once its agy
845
- // has gone
894
+ // Track shutdown after removing the spare so a resumed chat can wait for
895
+ // the old terminal to finish with its conversation store.
846
896
  function dropSpare(key) {
847
897
  const s = spares.get(key)
848
- if (!s) return Promise.resolve()
898
+ if (!s) return closingSpares.get(key) ?? Promise.resolve()
849
899
  spares.delete(key)
850
900
  clearTimeout(s.timer)
851
- return s.started.then((a) => a.close(), () => {})
901
+ const closed = s.started.then((a) => a.close(), () => {})
902
+ closingSpares.set(key, closed)
903
+ const forget = () => { if (closingSpares.get(key) === closed) closingSpares.delete(key) }
904
+ closed.then(forget, forget)
905
+ return closed
852
906
  }
853
907
 
854
- function leaveSpare(key, opts) {
908
+ function leaveSpare(key, opts, terminal) {
855
909
  if (process.env.AGY_TUI_SPARES === "0" || spares.has(key)) return
856
910
  while (spares.size >= MAX_SPARES) dropSpare(spares.keys().next().value)
857
- const started = launch(opts)
911
+ const started = terminal ? Promise.resolve(terminal) : launch(opts)
858
912
  started.catch(() => {})
859
913
  const timer = setTimeout(() => dropSpare(key), SPARE_IDLE_MS)
860
914
  timer.unref?.()
861
915
  spares.set(key, { started, timer })
916
+ return true
862
917
  }
863
918
 
864
919
  // closeSpares ends every agy that waits for a request
865
920
  export async function closeSpares() {
866
- const all = [...spares.values()]
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
- }))
921
+ await Promise.all([...closingSpares.values(), ...[...spares.keys()].map(dropSpare)])
873
922
  }
874
923
 
875
924
  // folderAt is a new, empty folder for a turn: at `want`, the path the
@@ -897,7 +946,7 @@ function folderAt(want, prefix) {
897
946
  // `place`), and resolves at once: begin({ prompt, media, signal, messages
898
947
  // }) waits until it is at its prompt, types the request in and resolves
899
948
  // with the turn
900
- async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null, place = null }) {
949
+ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null, place = null, scope = "" }) {
901
950
  if (!helper) throw new Failure(501, oldMagpie(TUI_HELPER_MAGPIE, "has a terminal for agy"))
902
951
  settleHome(home)
903
952
  const withTools = tools.length > 0
@@ -971,13 +1020,25 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
971
1020
  // transcript (from) and its store (stepBase)
972
1021
  let from = null
973
1022
  let stepBase = -1
1023
+ // A scoped terminal may run beside another one typing the same prompt.
1024
+ // The workspace in agy's store ties a new conversation to its terminal.
1025
+ const owns = scope ? (id) => {
1026
+ try {
1027
+ const dir = path.normalize(fileURLToPath(conversationWorkspace(home, id)))
1028
+ return process.platform === "win32" ? dir.toLowerCase() === ws.toLowerCase() : dir === ws
1029
+ } catch {
1030
+ return false
1031
+ }
1032
+ } : null
974
1033
  const look = () => {
975
- found = answerOf(brain, before, prompt, found?.id, from) ?? (from ? { id: from.id, answer: "" } : null)
1034
+ found = answerOf(brain, before, prompt, found?.id, from, owns) ?? (from ? { id: from.id, answer: "" } : null)
976
1035
  if (found?.id) claimed.add(found.id)
977
1036
  }
978
1037
  // what the model has said so far, its text and its thinking, from agy's
979
1038
  // conversation store (live.mjs), for a stream to send as it comes
980
- const live = { text: "", thinking: "", listeners: new Set() }
1039
+ let live
1040
+ let activeConversation = conversation
1041
+ let checkedResume = false
981
1042
  const publish = (reply) => {
982
1043
  let grew = false
983
1044
  for (const k of ["text", "thinking"]) {
@@ -991,16 +1052,25 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
991
1052
  // none): agy writes a call's counts as the call ends, so a moment is
992
1053
  // given for them
993
1054
  let usageAt = null
994
- const spent = async () => {
995
- for (let i = 0; i < USAGE_TRIES; i++) {
1055
+ let usageBaselineKnown = true
1056
+ const spent = async (tries = USAGE_TRIES, deferred = false) => {
1057
+ if (!usageBaselineKnown) return null
1058
+ for (let i = 0; i < tries; i++) {
996
1059
  if (!found?.id) look()
997
1060
  const got = found?.id ? callsAfter(home, found.id, usageAt) : null
998
- if (!got) return null
999
- if (got.calls.length) {
1061
+ if (got?.calls.length) {
1000
1062
  usageAt = got.cursor
1063
+ if (deferred) {
1064
+ return got.calls.reduce((total, call) => ({
1065
+ prompt_tokens: total.prompt_tokens + call.input + call.read + call.write,
1066
+ completion_tokens: total.completion_tokens + call.output,
1067
+ cached_tokens: total.cached_tokens + call.read,
1068
+ cache_write_tokens: total.cache_write_tokens + call.write,
1069
+ }), { prompt_tokens: 0, completion_tokens: 0, cached_tokens: 0, cache_write_tokens: 0 })
1070
+ }
1001
1071
  return usageOf(got.calls)
1002
1072
  }
1003
- await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
1073
+ if (i + 1 < tries) await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
1004
1074
  }
1005
1075
  return null
1006
1076
  }
@@ -1024,9 +1094,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1024
1094
  pending.add(o.call.id)
1025
1095
  if (!found?.id) look()
1026
1096
  if (found?.id) publish(liveReply(home, found.id, stepBase))
1027
- // a tool agy has under a short name goes back under the client's
1028
- const call = { ...o.call, name: clients.get(o.call.name) ?? o.call.name }
1029
- spent().then((usage) => stop({ call, usage }))
1097
+ stop({ call: o.call })
1030
1098
  }
1031
1099
  if (o.dropped) pending.delete(o.dropped)
1032
1100
  }
@@ -1037,10 +1105,8 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1037
1105
  const closed = new Promise((resolve) => child.on("close", () => { ended ??= { code: -1, error: errorLine || lastLine(stderr) || "the terminal ended" }; poke(); resolve() }))
1038
1106
  child.on("error", (e) => { errorLine = e.message })
1039
1107
  const send = (v) => { try { child.stdin.write(JSON.stringify(v) + "\n") } catch {} }
1040
- let cleaned = false
1041
- const cleanup = async () => {
1042
- if (cleaned) return
1043
- cleaned = true
1108
+ let cleaning
1109
+ const cleanup = () => cleaning ??= (async () => {
1044
1110
  send({ stop: true })
1045
1111
  try { child.stdin.end() } catch {}
1046
1112
  const late = setTimeout(() => { try { child.kill("SIGKILL") } catch {} }, 5000)
@@ -1050,7 +1116,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1050
1116
  if (ownHome) fs.rmSync(ownHome, { recursive: true, force: true })
1051
1117
  if (process.env.AGY_TUI_KEEP) return
1052
1118
  fs.rmSync(ws, { recursive: true, force: true })
1053
- }
1119
+ })()
1054
1120
  // the request the turn answers now: its end, before the turn's, ends it
1055
1121
  let sig = null
1056
1122
  const onAbort = () => { cleanup() }
@@ -1114,14 +1180,16 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1114
1180
  const begin = async (req) => {
1115
1181
  prompt = req.prompt
1116
1182
  const media = req.media ?? []
1183
+ live = { text: "", thinking: "", listeners: new Set() }
1117
1184
  watch(req.signal)
1118
1185
  try {
1119
1186
  await booted
1187
+ if (ended || cleaning) throw new Failure(502, "agy's waiting terminal has ended")
1120
1188
  } catch (error) {
1121
1189
  error.boot = true
1122
1190
  throw error
1123
1191
  }
1124
- if (conversation) {
1192
+ if (conversation && !checkedResume) {
1125
1193
  // agy that ignored the conversation (its log says it found none) has
1126
1194
  // started one of its own, which the message would go to without the
1127
1195
  // chat: the request goes without it (handle). Its log says one or
@@ -1135,12 +1203,21 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1135
1203
  await cleanup()
1136
1204
  throw Object.assign(new Failure(502, `agy didn't start with conversation ${conversation}`), { ignored: true })
1137
1205
  }
1206
+ checkedResume = true
1207
+ }
1208
+ if (activeConversation) {
1138
1209
  // what the conversation has already, before this turn's message
1139
- from = { id: conversation, line: transcriptLines(brain, conversation) }
1140
- stepBase = lastStep(home, conversation) ?? -1
1141
- usageAt = callsAfter(home, conversation)?.cursor ?? null
1142
- found = { id: conversation, answer: "" }
1143
- claimed.add(conversation)
1210
+ from = { id: activeConversation, line: transcriptLines(brain, activeConversation) }
1211
+ stepBase = lastStep(home, activeConversation) ?? -1
1212
+ let baseline = callsAfter(home, activeConversation)
1213
+ for (let i = 0; baseline === null && i < 3; i++) {
1214
+ await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
1215
+ baseline = callsAfter(home, activeConversation)
1216
+ }
1217
+ usageAt = baseline?.cursor ?? null
1218
+ usageBaselineKnown = baseline !== null
1219
+ found = { id: activeConversation, answer: "" }
1220
+ claimed.add(activeConversation)
1144
1221
  }
1145
1222
  try {
1146
1223
  let files
@@ -1156,7 +1233,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1156
1233
  // pasted alone, the paths are attached, as files dragged onto the
1157
1234
  // terminal are; the turn waits until agy shows every one attached,
1158
1235
  // so a path agy took for text is never sent as the message
1159
- send({ write: `\x1b[200~${pastedPaths(files)}\x1b[201~` })
1236
+ send({ write: attachmentPaste(files) })
1160
1237
  try {
1161
1238
  await waitFor("attachment", () => attached(screen) >= files.length, attachTimeout())
1162
1239
  } catch (error) {
@@ -1169,14 +1246,51 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1169
1246
  send({ write: "\r" })
1170
1247
  // agy has the message once it is in a turn, or its transcript has it
1171
1248
  // (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)
1249
+ await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt, null, from, owns)), SUBMIT_MS)
1173
1250
  } catch (error) {
1174
1251
  await cleanup()
1175
1252
  throw error
1176
1253
  }
1177
1254
 
1255
+ let until = Date.now() + turnTimeout()
1256
+ let batchStep = stepBase
1257
+ let previousCalls = []
1258
+ let usageMissing = false
1259
+ const clientCall = (call) => ({ ...call, name: clients.get(call.name) ?? call.name })
1260
+ const toolStop = async (first, parallel) => {
1261
+ let batch
1262
+ let size = 1
1263
+ const identity = (call) => toolIdentity(call.name, call.arguments)
1264
+ // Give the transcript and the remaining callbacks a short chance
1265
+ // to arrive. The timeout itself is never evidence of a batch.
1266
+ for (let i = 0; i < 7; i++) {
1267
+ if (!found?.id) look()
1268
+ batch = toolBatchOf(brain, found?.id, batchStep)
1269
+ if (batch && batch.calls.includes(identity(first))) {
1270
+ if (!parallel || batch.calls.length > MAX_PARKED || batch.calls.length === 1) break
1271
+ const queued = [first, ...stops.slice(0, batch.calls.length - 1).map((s) => s.call)]
1272
+ if (queued.length === batch.calls.length && queued.every(Boolean) &&
1273
+ JSON.stringify(queued.map(identity).sort()) === JSON.stringify([...batch.calls].sort())) {
1274
+ size = queued.length
1275
+ break
1276
+ }
1277
+ }
1278
+ if (i < 6) await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
1279
+ }
1280
+ const calls = [first, ...stops.splice(0, size - 1).map((s) => s.call)]
1281
+ if (batch?.calls.includes(identity(first))) {
1282
+ batchStep = batch.step
1283
+ previousCalls = [...batch.calls]
1284
+ for (const call of calls) previousCalls.splice(previousCalls.indexOf(identity(call)), 1)
1285
+ }
1286
+ const usage = await spent()
1287
+ usageMissing = !usage
1288
+ return { calls: calls.map(clientCall), usage: usage ?? { magpie_usage_state: "unavailable" } }
1289
+ }
1178
1290
  const turn = {
1179
1291
  live,
1292
+ home,
1293
+ scope,
1180
1294
  // the request's chat, which the conversation is kept under once the
1181
1295
  // turn answers (handle gives each request's that goes on with it)
1182
1296
  messages: req.messages ?? null,
@@ -1185,17 +1299,33 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1185
1299
  sent: "",
1186
1300
  thought: "",
1187
1301
  ended: false,
1188
- next: async () => {
1302
+ next: async (parallel) => {
1189
1303
  while (!stops.length) await new Promise((r) => { wake = r })
1190
- return stops.shift()
1304
+ const next = stops.shift()
1305
+ if (!next.call) return next
1306
+ const position = previousCalls.indexOf(toolIdentity(next.call.name, next.call.arguments))
1307
+ const latest = position < 0 ? null : toolBatchOf(brain, found?.id, batchStep - 1)
1308
+ if (latest?.step !== batchStep) {
1309
+ previousCalls = []
1310
+ return toolStop(next.call, parallel)
1311
+ }
1312
+ previousCalls.splice(position, 1)
1313
+ const late = usageMissing ? await spent(1, true) : null
1314
+ if (late) usageMissing = false
1315
+ return { calls: [clientCall(next.call)], usage: { magpie_usage_state: "tool_handoff", ...(late ? { magpie_deferred: late } : {}) } }
1191
1316
  },
1192
- // reply answers a call agy waits on; false when it waits no more
1193
- reply: (id, content, isError = false) => {
1194
- if (!pending.delete(id)) return false
1195
- send({ result: { id, content, isError } })
1317
+ // Validate the full batch before replying to any call.
1318
+ replyAll: (replies) => {
1319
+ if (!replies.every(({ id }) => pending.has(id))) return false
1320
+ until = Date.now() + turnTimeout()
1321
+ for (const result of replies) {
1322
+ pending.delete(result.id)
1323
+ send({ result })
1324
+ }
1196
1325
  return true
1197
1326
  },
1198
1327
  watch,
1328
+ conversation: () => found?.id,
1199
1329
  close: () => cleanup(),
1200
1330
  }
1201
1331
 
@@ -1204,7 +1334,6 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1204
1334
  let polled = 0
1205
1335
  // a turn waiting on the client's tool has no clock: the time is the
1206
1336
  // client's (a parked turn has its own, parkTimeout)
1207
- let until = Date.now() + turnTimeout()
1208
1337
  try {
1209
1338
  // back at its prompt with nothing in the transcript for a while:
1210
1339
  // the turn failed, and what agy drew says why (a quota, a refusal)
@@ -1232,64 +1361,90 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1232
1361
  if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
1233
1362
  // the whole of it, read before the conversation goes
1234
1363
  publish(liveReply(home, found.id, stepBase))
1235
- last = { text: found.answer, usage: await spent() }
1364
+ last = { text: found.answer, usage: await spent() ?? { magpie_usage_state: "unavailable" } }
1236
1365
  } catch (error) {
1237
1366
  last = { error }
1238
1367
  } finally {
1239
- // the end is told at once: agy's exit can wait on its own network
1240
- // (a telemetry flush on the way out), and the client needn't. The
1241
- // turn's files go after, once agy has.
1368
+ // The client can finish while agy waits for another message or
1369
+ // shuts down. Keep the live terminal only for this conversation.
1242
1370
  turn.ended = true
1371
+ if (parked.get(turn.parkedKey)?.turn === turn) takeParked(turn.parkedKey)
1243
1372
  watch(null)
1244
1373
  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
1374
  const id = found?.id
1249
- const answered = Boolean(resumable && last.text && id && turn.messages)
1250
- const out = cleanup()
1251
- if (answered) keep(home, turn.messages, id, [found.answer, since(turn, live.text)], { agy, home, model, tools, helper, place: { ws, ownHome } }, out)
1252
- await leaving(out.then(() => {
1253
- if (!answered) forget(brain, id)
1254
- }))
1375
+ const answered = Boolean(resumable && last.text && CONVERSATION_ID.test(id ?? "") && turn.messages && carrying())
1376
+ if (answered) {
1377
+ activeConversation = id
1378
+ const next = { agy, home, model, tools, helper, conversation: id, scope }
1379
+ const key = spareKey(next)
1380
+ const reused = !ended && !cleaning && leaveSpare(key, next, terminal)
1381
+ keep(home, scope, turn.messages, id, [found.answer, since(turn, live.text)], { ws, ownHome }, reused ? key : null, reused ? null : leaving(cleanup()))
1382
+ } else {
1383
+ await leaving(cleanup().then(() => forget(brain, id)))
1384
+ }
1255
1385
  }
1256
1386
  })()
1257
1387
  return turn
1258
1388
  }
1259
- return { begin, alive: () => !ended && !cleaned, close: () => cleanup() }
1389
+ const terminal = { begin, alive: () => !ended && !cleaning, close: cleanup }
1390
+ return terminal
1260
1391
  }
1261
1392
 
1262
1393
  // ---- turns waiting on the client's tool
1263
1394
 
1264
1395
  // A turn that stopped at a call waits, its agy running, for the request
1265
- // that brings the call's result (by the call's id). One left waiting past
1266
- // parkTimeout, or pushed out by newer ones past MAX_PARKED, ends; its
1267
- // result, when it comes, starts a turn of its own, with the conversation
1268
- // typed in as text.
1396
+ // that brings the call's result. A late result can still start a new turn
1397
+ // using the supplied history.
1269
1398
  const parked = new Map()
1270
1399
 
1271
- function park(id, turn) {
1400
+ function parkedKey(home, scope, id) {
1401
+ return JSON.stringify([home, scope, id])
1402
+ }
1403
+
1404
+ function park(calls, turn) {
1405
+ const ids = calls.map((call) => call.id)
1406
+ const key = parkedKey(turn.home, turn.scope, ids[0])
1407
+ if (parked.size >= MAX_PARKED || parked.has(key)) {
1408
+ turn.close()
1409
+ throw new Failure(503, "agy-tui cannot accept another waiting tool call")
1410
+ }
1272
1411
  const timer = setTimeout(() => {
1273
- if (parked.get(id)?.turn !== turn) return
1274
- parked.delete(id)
1412
+ if (parked.get(key)?.turn !== turn) return
1413
+ takeParked(key)
1275
1414
  turn.close()
1276
1415
  }, parkTimeout())
1277
1416
  timer.unref?.()
1278
- parked.set(id, { turn, timer })
1279
- while (parked.size > MAX_PARKED) {
1280
- const [oldest, p] = parked.entries().next().value
1281
- parked.delete(oldest)
1282
- clearTimeout(p.timer)
1283
- p.turn.close()
1417
+ parked.set(key, { turn, timer, ids })
1418
+ turn.parkedKey = key
1419
+ }
1420
+
1421
+ // The gateway can append reminders or tool images as user messages.
1422
+ const NOTE_ROLES = new Set(["user", "system", "developer"])
1423
+
1424
+ export function resultOf(messages) {
1425
+ if (!Array.isArray(messages)) return null
1426
+ const assistant = messages.findLastIndex((m) => m?.role === "assistant")
1427
+ const start = assistant < 0 ? messages.findLastIndex((m) => m?.role !== "tool") : assistant
1428
+ const [tool, ...notes] = messages.slice(start + 1)
1429
+ if (tool?.role !== "tool") return null
1430
+ const calls = messages[assistant]?.tool_calls
1431
+ if (Array.isArray(calls) && !calls.some((call) => call?.id === tool.tool_call_id)) return null
1432
+ return { tool, notes }
1433
+ }
1434
+
1435
+ function traceToolContinuation(request, outcome, reason, conversation) {
1436
+ if (process.env.AGY_TUI_TRACE_RESUME === "1") {
1437
+ console.error(JSON.stringify({ plugin: PROVIDER_ID, request, event: "tool_continuation", outcome, reason, conversation }))
1284
1438
  }
1285
1439
  }
1286
1440
 
1287
- function unpark(id) {
1288
- const p = typeof id === "string" ? parked.get(id) : null
1441
+ function takeParked(key) {
1442
+ const p = parked.get(key)
1289
1443
  if (!p) return null
1290
- parked.delete(id)
1444
+ parked.delete(key)
1291
1445
  clearTimeout(p.timer)
1292
- return p.turn
1446
+ delete p.turn.parkedKey
1447
+ return p
1293
1448
  }
1294
1449
 
1295
1450
  // toolContent is a tool message's content as the tool server answers it: a
@@ -1310,41 +1465,24 @@ export function toolContent(content) {
1310
1465
  return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
1311
1466
  }
1312
1467
 
1313
- // NOTE_ROLES are the messages a client sends after a tool's result that
1314
- // aren't the user's next turn: Claude Code's reminders beside a
1315
- // tool_result, a system note Claude Desktop puts after every one, and the
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"])
1468
+ function contentBlocks(content) {
1469
+ return typeof content === "string" ? [{ type: "text", text: content }] : content
1470
+ }
1319
1471
 
1320
- // resultOf is the tool message a request ends with that answers a call,
1321
- // and the notes the client sent after it ({ tool, notes }), or null: what
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.
1472
+ // The CLI helper replies to agy through MCP. Keep the tool's own output
1473
+ // first and label the later user content as such in separate MCP blocks.
1339
1474
  export function resultContent(tool, notes = []) {
1340
- const own = toolContent(tool.content)
1341
- if (!notes.length) return own
1342
- const blocks = typeof own === "string" ? (own ? [{ type: "text", text: own }] : []) : [...own]
1343
- for (const n of notes) {
1344
- const c = toolContent(n.content)
1345
- if (typeof c === "string") { if (c.trim()) blocks.push({ type: "text", text: c }) } else blocks.push(...c)
1475
+ const content = toolContent(tool.content)
1476
+ if (!notes.length) return content
1477
+ const blocks = [...contentBlocks(content)]
1478
+ for (const message of notes) {
1479
+ if (!NOTE_ROLES.has(message?.role) || (typeof message.content !== "string" && !Array.isArray(message.content))) {
1480
+ throw new Failure(400, "the tool result is followed by messages that need a new turn")
1481
+ }
1482
+ const role = message.role[0].toUpperCase() + message.role.slice(1)
1483
+ blocks.push({ type: "text", text: `[${role} message after the tool result]` }, ...contentBlocks(toolContent(message.content)))
1346
1484
  }
1347
- return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
1485
+ return blocks
1348
1486
  }
1349
1487
 
1350
1488
  // forget removes the conversation agy kept for a turn from the account's
@@ -1488,30 +1626,25 @@ function prune(home, list) {
1488
1626
  }
1489
1627
 
1490
1628
  // keep puts an answered turn's conversation on the account's list, under
1491
- // the request's chat, with the words of the answer (as the client may have
1492
- // had it, `replies`), and, once the turn's agy has gone (`gone`), starts an
1493
- // agy with it for the chat's next request (`opts`: the turn's own)
1494
- function keep(home, messages, id, replies, opts, gone) {
1495
- if (!CONVERSATION_ID.test(String(id ?? "")) || !carrying()) return forget(brainOf(home), id)
1629
+ // the request's chat, with the words of the answer as the client may have
1630
+ // had it, and its live terminal if there is one.
1631
+ function keptKey(scope, messages) {
1632
+ const history = chatKey(messages)
1633
+ return scope ? sha(JSON.stringify([scope, history])) : history
1634
+ }
1635
+
1636
+ function keep(home, scope, messages, id, replies, place, spare, gone) {
1496
1637
  const list = keptOf(home)
1497
- const key = chatKey(messages)
1638
+ const key = keptKey(scope, messages)
1498
1639
  const old = list.get(key)
1499
1640
  if (old) {
1500
1641
  list.delete(key)
1501
1642
  if (old.id !== id) dropKept(home, old)
1502
1643
  }
1503
- const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), place: opts.place ?? null, ready: Promise.resolve(gone).catch(() => {}) }
1644
+ const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), place, spare, ready: Promise.resolve(gone).catch(() => {}) }
1504
1645
  list.set(key, e)
1505
1646
  prune(home, list)
1506
1647
  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
1648
  }
1516
1649
 
1517
1650
  function carrying() {
@@ -1523,7 +1656,7 @@ function carrying() {
1523
1656
  // or null: the chat, up to its last answer, is one a turn answered, the
1524
1657
  // answer is the one that turn gave, and what comes after it is the user's
1525
1658
  // alone and fits in one message.
1526
- export async function carriedOn(home, messages, { agy, model, tools }) {
1659
+ export async function carriedOn(home, messages, { agy, model, tools, scope = "" }) {
1527
1660
  if (!carrying() || !Array.isArray(messages)) return null
1528
1661
  const j = messages.findLastIndex((m) => m?.role === "assistant")
1529
1662
  if (j < 0) return null
@@ -1532,7 +1665,7 @@ export async function carriedOn(home, messages, { agy, model, tools }) {
1532
1665
  if (!tail.length || !tail.every((m) => m?.role === "user")) return null
1533
1666
  if (Array.isArray(answer.tool_calls) && answer.tool_calls.length) return null
1534
1667
  const list = keptOf(home)
1535
- const key = chatKey(messages.slice(0, j))
1668
+ const key = keptKey(scope, messages.slice(0, j))
1536
1669
  const e = list.get(key)
1537
1670
  if (!e || !e.replies.includes(replyKey(answer.content))) return null
1538
1671
  const { prompt, media } = turnOf(tail, Infinity)
@@ -1542,7 +1675,7 @@ export async function carriedOn(home, messages, { agy, model, tools }) {
1542
1675
  // the agy of the turn that kept it gone, and its spare, when it isn't
1543
1676
  // one this request takes, before another agy opens the conversation
1544
1677
  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)
1678
+ if (e.spare && e.spare !== spareKey({ agy, home, model, tools, helper: process.env.MAGPIE_EXE, conversation: e.id, scope })) await dropSpare(e.spare)
1546
1679
  if (!fs.existsSync(path.join(brainOf(home), e.id))) {
1547
1680
  forget(brainOf(home), e.id)
1548
1681
  return null
@@ -1569,11 +1702,11 @@ function since(turn, text, had = turn.sent) {
1569
1702
  }
1570
1703
 
1571
1704
  // stopped ends a response at a call: the turn waits for its result
1572
- function stopped(turn, call) {
1705
+ function stopped(turn, calls) {
1573
1706
  turn.watch(null)
1574
1707
  turn.sent = turn.live.text
1575
1708
  turn.thought = turn.live.thinking
1576
- park(call.id, turn)
1709
+ park(calls, turn)
1577
1710
  }
1578
1711
 
1579
1712
  function completion(id, model, message, finish, usage = null) {
@@ -1588,15 +1721,15 @@ function completion(id, model, message, finish, usage = null) {
1588
1721
  }
1589
1722
 
1590
1723
  // answered is the turn's next stop as one completion.
1591
- async function answered(id, model, turn) {
1592
- const s = await turn.next()
1724
+ async function answered(id, model, turn, parallel) {
1725
+ const s = await turn.next(parallel)
1593
1726
  if (s.error) throw s.error
1594
1727
  const thinking = since(turn, turn.live.thinking, turn.thought)
1595
1728
  const reasoning = thinking ? { reasoning_content: thinking } : {}
1596
- if (s.call) {
1729
+ if (s.calls) {
1597
1730
  const text = since(turn, turn.live.text)
1598
- stopped(turn, s.call)
1599
- return completion(id, model, { content: text || null, ...reasoning, tool_calls: [toolCallOf(s.call)] }, "tool_calls", s.usage)
1731
+ stopped(turn, s.calls)
1732
+ return completion(id, model, { content: text || null, ...reasoning, tool_calls: s.calls.map((call) => toolCallOf(call)) }, "tool_calls", s.usage)
1600
1733
  }
1601
1734
  return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop", s.usage)
1602
1735
  }
@@ -1605,7 +1738,7 @@ async function answered(id, model, turn) {
1605
1738
  // writes it (turn.live), each piece once; at the end, what the store has
1606
1739
  // whole, or, with nothing read from it, the transcript's answer; at a call,
1607
1740
  // the call.
1608
- export function streamOf(id, model, turn) {
1741
+ export function streamOf(id, model, turn, parallel = true) {
1609
1742
  const { live } = turn
1610
1743
  const enc = new TextEncoder()
1611
1744
  const created = Math.floor(Date.now() / 1000)
@@ -1651,13 +1784,13 @@ export function streamOf(id, model, turn) {
1651
1784
  quiet = Date.now()
1652
1785
  }, 5_000)
1653
1786
  try {
1654
- const s = await turn.next()
1787
+ const s = await turn.next(parallel)
1655
1788
  halt()
1656
1789
  if (s.error) throw s.error
1657
1790
  send()
1658
- if (s.call) {
1659
- stopped(turn, s.call)
1660
- c.enqueue(enc.encode(chunk({ tool_calls: [toolCallOf(s.call, 0)] })))
1791
+ if (s.calls) {
1792
+ stopped(turn, s.calls)
1793
+ c.enqueue(enc.encode(chunk({ tool_calls: s.calls.map(toolCallOf) })))
1661
1794
  c.enqueue(enc.encode(chunk({}, "tool_calls", s.usage)))
1662
1795
  } else {
1663
1796
  if (!sent && s.text) c.enqueue(enc.encode(chunk({ content: s.text })))
@@ -1675,9 +1808,10 @@ export function streamOf(id, model, turn) {
1675
1808
  })
1676
1809
  }
1677
1810
 
1678
- function respond(id, model, turn, stream) {
1679
- if (stream) return new Response(streamOf(id, model, turn), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
1680
- return answered(id, model, turn).then(
1811
+ function respond(id, model, turn, body) {
1812
+ const parallel = body.parallel_tool_calls !== false
1813
+ if (body.stream) return new Response(streamOf(id, model, turn, parallel), { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
1814
+ return answered(id, model, turn, parallel).then(
1681
1815
  (body) => new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }),
1682
1816
  (error) => jsonError(error.status ?? 502, error.message),
1683
1817
  )
@@ -1695,39 +1829,58 @@ export async function handle(home, input, init = {}) {
1695
1829
  }
1696
1830
  const signal = init.signal ?? input?.signal
1697
1831
  const id = `chatcmpl-${randomBytes(12).toString("hex")}`
1832
+ const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined) ?? {})
1833
+ const caller = headers.get("x-magpie-caller-id") ?? ""
1834
+ const session = headers.get("x-magpie-session") || headers.get("x-magpie-conversation") || ""
1835
+ const subagent = headers.get("x-magpie-subagent") ?? ""
1836
+ if (process.env.AGY_TUI_REQUIRE_CALLER === "1" && !caller) {
1837
+ return jsonError(403, "agy-tui shared mode requires an authenticated Magpie gateway caller key")
1838
+ }
1839
+ const scope = caller || session || subagent ? sha(JSON.stringify([caller, session, subagent])) : ""
1840
+ if (!home) return jsonError(401, "agy-tui: no account; sign in again", { "X-Magpie-Sign-In": "expired" })
1841
+ 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
1842
  const model = String(body.model ?? "")
1699
1843
  // the level of a model listed with its levels as variants, as the
1700
1844
  // agent asked (efforts.mjs); a level's own id is run as it is
1701
- const said = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined) ?? {}).get("x-magpie-effort") ?? ""
1702
- const agyModel = home ? agyModelOf(model, (modelLists.get(home) ?? readModelList(home))?.list, body, said) : model
1703
- // the result of a call a turn waits on goes on with that turn, with the
1704
- // notes the client sent after it
1705
- const result = resultOf(body.messages)
1706
- if (result) {
1707
- const { tool, notes } = result
1708
- const waiting = unpark(tool.tool_call_id)
1845
+ const said = headers.get("x-magpie-effort") ?? ""
1846
+ const agyModel = agyModelOf(model, (modelLists.get(home) ?? readModelList(home))?.list, body, said)
1847
+ // Chat translation can put a user message immediately after a tool result.
1848
+ const continuation = resultOf(body.messages)
1849
+ if (continuation) {
1850
+ const { tool: result, notes } = continuation
1851
+ const noteAt = notes.findIndex((message) => message?.role !== "tool")
1852
+ const results = [result, ...(noteAt < 0 ? notes : notes.slice(0, noteAt))]
1853
+ const keys = results.map((message) => parkedKey(home, scope, message.tool_call_id))
1854
+ const key = keys.find((candidate) => parked.has(candidate))
1855
+ const entry = key && parked.get(key)
1856
+ const waiting = entry?.turn
1709
1857
  if (waiting && !waiting.ended) {
1710
- let content
1711
- try { content = toolContent(tool.content) } catch (error) {
1712
- waiting.close()
1713
- return jsonError(error.status ?? 400, error.message, error.headers)
1858
+ let replies
1859
+ try {
1860
+ if (results.length === entry.ids.length && entry.ids.every((id) => results.some((message) => message.tool_call_id === id))) {
1861
+ const trailing = notes.slice(results.length - 1)
1862
+ replies = results.map((message, i) => ({
1863
+ id: message.tool_call_id,
1864
+ content: resultContent(message, i === results.length - 1 ? trailing : []),
1865
+ isError: message.is_error === true,
1866
+ }))
1867
+ }
1868
+ } catch {
1869
+ // A fresh prompt can carry content the MCP reply cannot, such as video.
1714
1870
  }
1715
- // a note a result can't carry: the chat typed in, as before
1716
- try { content = resultContent(tool, notes) } catch { content = null }
1717
- if (content !== null) {
1871
+ takeParked(key)
1872
+ if (replies && waiting.replyAll(replies)) {
1718
1873
  waiting.messages = body.messages
1719
- if (waiting.reply(tool.tool_call_id, content)) {
1720
- waiting.watch(signal)
1721
- return respond(id, model, waiting, body.stream)
1722
- }
1874
+ waiting.watch(signal)
1875
+ traceToolContinuation(id, "resumed", undefined, waiting.conversation())
1876
+ return respond(id, model, waiting, body)
1723
1877
  }
1878
+ traceToolContinuation(id, "replay", replies ? "tool_call_no_longer_pending" : "unsupported_or_incomplete_tool_results")
1879
+ } else {
1880
+ traceToolContinuation(id, "replay", "no_matching_parked_turn")
1724
1881
  }
1725
- // agy no longer waits on it: a turn of its own, the conversation
1726
- // typed in as text
1727
1882
  waiting?.close()
1728
1883
  }
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
1884
  const agy = findAgy()
1732
1885
  if (!agy) return jsonError(503, `agy CLI not found on this machine: ${AGY_MANUAL}`)
1733
1886
  const refusal = await agyRefusal(agy)
@@ -1737,37 +1890,44 @@ export async function handle(home, input, init = {}) {
1737
1890
  try {
1738
1891
  const tools = mcpToolsOf(body)
1739
1892
  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
1893
  let paste = null
1746
- if (!carried) {
1894
+ const rebuild = () => {
1747
1895
  try {
1748
1896
  paste = turnOf(body.messages)
1749
1897
  } catch (error) {
1750
- if (!error.long || !resumable) throw error
1898
+ if (!error.long || !resumable || process.env.AGY_TUI_SEED === "0") throw error
1751
1899
  }
1752
- if (resumable && (!paste || paste.cut) && process.env.AGY_TUI_SEED !== "0") carried = seedOf(home, body.messages)
1753
- if (!carried && !paste) paste = turnOf(body.messages)
1900
+ if (resumable && (!paste || paste.cut) && process.env.AGY_TUI_SEED !== "0") {
1901
+ const seeded = seedOf(home, body.messages)
1902
+ if (seeded) return seeded
1903
+ }
1904
+ paste ??= turnOf(body.messages)
1905
+ return null
1754
1906
  }
1755
1907
  const start = async (c) => {
1756
1908
  const { prompt, media } = c ?? paste
1757
1909
  // agy attaches a video for any model, but only Gemini's see one
1758
1910
  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: body.messages })
1911
+ return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages: body.messages, scope })
1760
1912
  }
1761
- try {
1762
- turn = await start(carried)
1763
- } catch (error) {
1764
- if (!error.ignored) throw error
1765
- // an agy that wouldn't start with the conversation: the chat typed
1766
- // in, as much of it as one message takes
1767
- forget(brainOf(home), carried.id)
1768
- carried = null
1769
- paste ??= turnOf(body.messages)
1770
- turn = await start(null)
1913
+ // Local state is an optimization. A different worker can start from
1914
+ // the request history alone, even if agy has lost a retained session.
1915
+ carried = resumable ? await carriedOn(home, body.messages, { agy, model: agyModel, tools, scope }) : null
1916
+ carried ??= rebuild()
1917
+ for (;;) {
1918
+ try {
1919
+ turn = await start(carried)
1920
+ break
1921
+ } catch (error) {
1922
+ if (!carried || !error.ignored) throw error
1923
+ const previous = carried
1924
+ carried = null
1925
+ forget(brainOf(home), previous.id)
1926
+ // Rebuild once from the full request if the old session vanished.
1927
+ // If agy also ignores a newly seeded store, use the prompt it takes.
1928
+ if (!previous.seeded) carried = rebuild()
1929
+ else paste ??= turnOf(body.messages)
1930
+ }
1771
1931
  }
1772
1932
  } catch (error) {
1773
1933
  // a conversation taken for a turn that never began is in a state
@@ -1775,7 +1935,7 @@ export async function handle(home, input, init = {}) {
1775
1935
  if (carried) forget(brainOf(home), carried.id)
1776
1936
  return jsonError(error.status ?? 502, error.message, error.headers)
1777
1937
  }
1778
- return respond(id, model, turn, body.stream)
1938
+ return respond(id, model, turn, body)
1779
1939
  }
1780
1940
 
1781
1941
  // ---- 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.20",
3
+ "version": "0.1.21",
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",