@magpie-community/opencode-agy-tui-auth 0.1.17 → 0.1.18

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.
Files changed (2) hide show
  1. package/index.mjs +94 -27
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -793,8 +793,8 @@ export function mcpConfig(mcp, tools) {
793
793
  // own tools stay off. With a conversation (an id agy kept, carried), agy
794
794
  // starts with it and the prompt carries it on; `messages` is the request's
795
795
  // 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 }) {
797
- const opts = { agy, home, model, tools, helper, conversation }
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 }
798
798
  const key = spareKey(opts)
799
799
  let turn = null
800
800
  const spare = await takeSpare(key)
@@ -810,7 +810,7 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
810
810
  if (!turn) turn = await (await launch(opts)).begin({ prompt, media, signal, messages })
811
811
  // agy has the message: the next request's agy starts now (a chat carried
812
812
  // on has its own, left as its turn ends)
813
- if (!conversation) leaveSpare(key, { ...opts, conversation: null })
813
+ if (!conversation) leaveSpare(key, { ...opts, conversation: null, place: null })
814
814
  return turn
815
815
  }
816
816
 
@@ -872,15 +872,36 @@ export async function closeSpares() {
872
872
  }))
873
873
  }
874
874
 
875
+ // folderAt is a new, empty folder for a turn: at `want`, the path the
876
+ // conversation it carries on ran in before, when that is one of ours (in
877
+ // the temp folder, named as ours are) and nothing has it now; else one of
878
+ // its own. agy writes the folder's path into the model's instructions
879
+ // (the workspace's AGENTS.md rule, its active workspaces, the command
880
+ // folder, with tools the HOME's app data folder), and a conversation
881
+ // started again in another adds it beside the last ones: the instructions
882
+ // would change every turn, and every token after them miss the model's
883
+ // cache (plugins#1963).
884
+ function folderAt(want, prefix) {
885
+ const tmp = fs.realpathSync(os.tmpdir())
886
+ if (typeof want === "string" && path.dirname(want) === tmp && new RegExp(`^${prefix}[A-Za-z0-9]{6}$`).test(path.basename(want))) {
887
+ try {
888
+ fs.mkdirSync(want, { mode: 0o700 })
889
+ return fs.realpathSync(want)
890
+ } catch {}
891
+ }
892
+ return fs.realpathSync(fs.mkdtempSync(path.join(tmp, prefix)))
893
+ }
894
+
875
895
  // launch starts agy for a turn, in a folder of its own (with the
876
- // conversation it carries on, if any), and resolves at once: begin({
877
- // prompt, media, signal, messages }) waits until it is at its prompt,
878
- // types the request in and resolves with the turn
879
- async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null }) {
896
+ // conversation it carries on, if any, in the folders it ran in before,
897
+ // `place`), and resolves at once: begin({ prompt, media, signal, messages
898
+ // }) waits until it is at its prompt, types the request in and resolves
899
+ // with the turn
900
+ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null, place = null }) {
880
901
  if (!helper) throw new Failure(501, oldMagpie(TUI_HELPER_MAGPIE, "has a terminal for agy"))
881
902
  settleHome(home)
882
903
  const withTools = tools.length > 0
883
- const ws = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-")))
904
+ const ws = folderAt(place?.ws, "agy-tui-")
884
905
  // agy's default agent, never --agent: the instructions in AGENTS.md, agy's
885
906
  // bundled skills left out, and a PreToolUse hook that denies every call of
886
907
  // agy's own tools (what the old agent's `tools: []` did); with tools, the
@@ -894,7 +915,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
894
915
  geminiDir: path.join(home, ".gemini"),
895
916
  })
896
917
  if (withTools) {
897
- ownHome = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-home-")))
918
+ ownHome = folderAt(place?.ownHome, "agy-tui-home-")
898
919
  sessionHome(home, ownHome)
899
920
  }
900
921
  } catch (error) {
@@ -1225,7 +1246,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1225
1246
  const id = found?.id
1226
1247
  const answered = Boolean(resumable && last.text && id && turn.messages)
1227
1248
  const out = cleanup()
1228
- if (answered) keep(home, turn.messages, id, [found.answer, since(turn, live.text)], { agy, home, model, tools, helper }, out)
1249
+ if (answered) keep(home, turn.messages, id, [found.answer, since(turn, live.text)], { agy, home, model, tools, helper, place: { ws, ownHome } }, out)
1229
1250
  await leaving(out.then(() => {
1230
1251
  if (!answered) forget(brain, id)
1231
1252
  }))
@@ -1287,6 +1308,43 @@ export function toolContent(content) {
1287
1308
  return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
1288
1309
  }
1289
1310
 
1311
+ // NOTE_ROLES are the messages a client sends after a tool's result that
1312
+ // aren't the user's next turn: Claude Code's reminders beside a
1313
+ // tool_result, a system note Claude Desktop puts after every one, and the
1314
+ // images a tool returned, which magpie gives in a user message after the
1315
+ // tool message (a tool message holds text only)
1316
+ const NOTE_ROLES = new Set(["user", "system", "developer"])
1317
+
1318
+ // resultOf is the tool message a request ends with that answers a call,
1319
+ // and the notes the client sent after it ({ tool, notes }), or null: what
1320
+ // came after the request's last assistant message is tool messages, then
1321
+ // notes alone.
1322
+ export function resultOf(messages) {
1323
+ if (!Array.isArray(messages)) return null
1324
+ const tail = messages.slice(messages.findLastIndex((m) => m?.role === "assistant") + 1)
1325
+ const k = tail.findLastIndex((m) => m?.role === "tool")
1326
+ if (k < 0 || !tail.slice(0, k).every((m) => m?.role === "tool")) return null
1327
+ const notes = tail.slice(k + 1)
1328
+ if (!notes.every((m) => NOTE_ROLES.has(m?.role))) return null
1329
+ return { tool: tail[k], notes }
1330
+ }
1331
+
1332
+ // resultContent is what agy gets as a call's result: the tool's content,
1333
+ // and the notes' text and images after it, so a parked turn goes on with
1334
+ // them (a note it didn't get would make the chat look new, typed in whole
1335
+ // into a new agy: a whole new prompt for the model's cache, every call,
1336
+ // plugins#1963). A note's part a result can't carry throws.
1337
+ export function resultContent(tool, notes = []) {
1338
+ const own = toolContent(tool.content)
1339
+ if (!notes.length) return own
1340
+ const blocks = typeof own === "string" ? (own ? [{ type: "text", text: own }] : []) : [...own]
1341
+ for (const n of notes) {
1342
+ const c = toolContent(n.content)
1343
+ if (typeof c === "string") { if (c.trim()) blocks.push({ type: "text", text: c }) } else blocks.push(...c)
1344
+ }
1345
+ return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
1346
+ }
1347
+
1290
1348
  // forget removes the conversation agy kept for a turn from the account's
1291
1349
  // home.
1292
1350
  function forget(brain, id) {
@@ -1312,10 +1370,12 @@ function forget(brain, id) {
1312
1370
  // (a new chat, one the client compacted or edited, an answer the client
1313
1371
  // changed) starts a conversation of its own, the chat typed in as before.
1314
1372
  // One carried on is taken off the list while its turn runs, so two
1315
- // requests never share it; a fork of the chat starts its own. Each is kept
1373
+ // requests never share it; a fork of the chat starts its own. Its agy
1374
+ // runs in the folders the turn before ran in (folderAt), so the model's
1375
+ // instructions are the same each turn and its cache holds. Each is kept
1316
1376
  // KEEP_MS from its last answer, MAX_KEPT an account (the oldest go first),
1317
- // and the list, hashes and ids alone, is in the account's home, so a
1318
- // restart finds them.
1377
+ // and the list, hashes, ids and folder paths alone, is in the account's
1378
+ // home, so a restart finds them.
1319
1379
  const KEEP_MS = 24 * 3600_000
1320
1380
  const MAX_KEPT = 32
1321
1381
  const KEPT_FILE = "agy-tui-conversations.json"
@@ -1362,7 +1422,7 @@ function saveKept(home, list) {
1362
1422
  const file = path.join(home, KEPT_FILE)
1363
1423
  const tmp = `${file}.${process.pid}.tmp`
1364
1424
  try {
1365
- fs.writeFileSync(tmp, JSON.stringify({ kept: [...list].map(([key, e]) => ({ key, id: e.id, replies: e.replies, at: e.at })) }), { mode: 0o600 })
1425
+ fs.writeFileSync(tmp, JSON.stringify({ kept: [...list].map(([key, e]) => ({ key, id: e.id, replies: e.replies, at: e.at, place: e.place })) }), { mode: 0o600 })
1366
1426
  fs.renameSync(tmp, file)
1367
1427
  } catch {
1368
1428
  try { fs.rmSync(tmp, { force: true }) } catch {}
@@ -1389,7 +1449,8 @@ function keptOf(home) {
1389
1449
  try { saved = JSON.parse(fs.readFileSync(path.join(home, KEPT_FILE), "utf8")) } catch {}
1390
1450
  for (const e of Array.isArray(saved?.kept) ? saved.kept : []) {
1391
1451
  if (typeof e?.key !== "string" || !CONVERSATION_ID.test(String(e?.id ?? "")) || !Array.isArray(e.replies) || !Number.isFinite(e.at)) continue
1392
- list.set(e.key, { id: e.id, replies: e.replies.filter((r) => typeof r === "string"), at: e.at })
1452
+ const place = { ws: typeof e.place?.ws === "string" ? e.place.ws : null, ownHome: typeof e.place?.ownHome === "string" ? e.place.ownHome : null }
1453
+ list.set(e.key, { id: e.id, replies: e.replies.filter((r) => typeof r === "string"), at: e.at, place })
1393
1454
  // never another turn's answer
1394
1455
  claimed.add(e.id)
1395
1456
  }
@@ -1437,7 +1498,7 @@ function keep(home, messages, id, replies, opts, gone) {
1437
1498
  list.delete(key)
1438
1499
  if (old.id !== id) dropKept(home, old)
1439
1500
  }
1440
- const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), ready: Promise.resolve(gone).catch(() => {}) }
1501
+ const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), place: opts.place ?? null, ready: Promise.resolve(gone).catch(() => {}) }
1441
1502
  list.set(key, e)
1442
1503
  prune(home, list)
1443
1504
  saveKept(home, list)
@@ -1484,7 +1545,7 @@ export async function carriedOn(home, messages, { agy, model, tools }) {
1484
1545
  forget(brainOf(home), e.id)
1485
1546
  return null
1486
1547
  }
1487
- return { id: e.id, prompt, media }
1548
+ return { id: e.id, prompt, media, place: e.place ?? null }
1488
1549
  }
1489
1550
 
1490
1551
  // ---- OpenAI chat completions
@@ -1637,20 +1698,26 @@ export async function handle(home, input, init = {}) {
1637
1698
  // agent asked (efforts.mjs); a level's own id is run as it is
1638
1699
  const said = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined) ?? {}).get("x-magpie-effort") ?? ""
1639
1700
  const agyModel = home ? agyModelOf(model, (modelLists.get(home) ?? readModelList(home))?.list, body, said) : model
1640
- // the result of a call a turn waits on goes on with that turn
1641
- const last = Array.isArray(body.messages) ? body.messages.at(-1) : null
1642
- if (last?.role === "tool") {
1643
- const waiting = unpark(last.tool_call_id)
1701
+ // the result of a call a turn waits on goes on with that turn, with the
1702
+ // notes the client sent after it
1703
+ const result = resultOf(body.messages)
1704
+ if (result) {
1705
+ const { tool, notes } = result
1706
+ const waiting = unpark(tool.tool_call_id)
1644
1707
  if (waiting && !waiting.ended) {
1645
- waiting.messages = body.messages
1646
1708
  let content
1647
- try { content = toolContent(last.content) } catch (error) {
1709
+ try { content = toolContent(tool.content) } catch (error) {
1648
1710
  waiting.close()
1649
1711
  return jsonError(error.status ?? 400, error.message)
1650
1712
  }
1651
- if (waiting.reply(last.tool_call_id, content)) {
1652
- waiting.watch(signal)
1653
- return respond(id, model, waiting, body.stream)
1713
+ // a note a result can't carry: the chat typed in, as before
1714
+ try { content = resultContent(tool, notes) } catch { content = null }
1715
+ if (content !== null) {
1716
+ waiting.messages = body.messages
1717
+ if (waiting.reply(tool.tool_call_id, content)) {
1718
+ waiting.watch(signal)
1719
+ return respond(id, model, waiting, body.stream)
1720
+ }
1654
1721
  }
1655
1722
  }
1656
1723
  // agy no longer waits on it: a turn of its own, the conversation
@@ -1687,7 +1754,7 @@ export async function handle(home, input, init = {}) {
1687
1754
  const { prompt, media } = c ?? paste
1688
1755
  // agy attaches a video for any model, but only Gemini's see one
1689
1756
  if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
1690
- return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, messages: body.messages })
1757
+ return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages: body.messages })
1691
1758
  }
1692
1759
  try {
1693
1760
  turn = await start(carried)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
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",