opencode-acp-provider 1.1.0 → 1.1.2
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.md +56 -23
- package/package.json +3 -2
- package/src/acp-client.ts +67 -4
- package/src/acp-tools/antigravity.ts +117 -0
- package/src/acp-tools/claude.ts +105 -0
- package/src/acp-tools/codex.ts +204 -0
- package/src/acp-tools/command-code.ts +135 -0
- package/src/acp-tools/fallback.ts +92 -0
- package/src/acp-tools/shared.ts +436 -0
- package/src/acp-tools.ts +119 -241
- package/src/agent-command.ts +1 -1
- package/src/agent-pool.ts +5 -1
- package/src/agents/README.md +4 -2
- package/src/agents/cmd/index.ts +1 -1
- package/src/agents/cmd/mods/no-native-orchestration.ts +33 -11
- package/src/index.ts +139 -47
- package/src/inventory.ts +14 -0
- package/src/language-model.ts +27 -13
- package/src/mcp-bridge.mjs +34 -4
- package/src/mcp-server.ts +87 -61
- package/src/prompt.ts +68 -14
- package/src/server-manager.ts +517 -74
- package/src/shim.ts +75 -35
- package/src/unsolicited.ts +388 -0
- package/src/util.ts +60 -2
- package/src/mcp-config.ts +0 -198
package/src/mcp-server.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
|
|
|
4
4
|
import { posix, win32 } from "node:path"
|
|
5
5
|
import { fileURLToPath } from "node:url"
|
|
6
6
|
import type { Plugin } from "@opencode/plugin"
|
|
7
|
+
import { Schema } from "effect"
|
|
7
8
|
import packageJson from "../package.json" with { type: "json" }
|
|
8
9
|
import type { AcpMcpServer } from "./acp-client.ts"
|
|
9
10
|
import type { LogFn, McpLease } from "./server-manager.ts"
|
|
@@ -20,14 +21,6 @@ const MAX_CONTEXT_CHARS = 60_000
|
|
|
20
21
|
/** Live tokens above this suggest leases are not being released. */
|
|
21
22
|
const TOKEN_WARN_THRESHOLD = 256
|
|
22
23
|
|
|
23
|
-
const SUBAGENT_DESCRIPTION = [
|
|
24
|
-
"Spawns an agent in a child session to work on the specified task.",
|
|
25
|
-
"Subagents always run in the background: the call returns immediately with a sessionID, and you receive a `<subagent>` message each time the child goes idle, including after later work.",
|
|
26
|
-
"Keep working on non-overlapping tasks, or briefly tell the user what you launched and end your response. Do not sleep, poll, or proactively check on the child's progress.",
|
|
27
|
-
"New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.",
|
|
28
|
-
"Pass the returned sessionID to continue that specific child conversation. A follow-up to a running child joins its current run.",
|
|
29
|
-
].join("\n")
|
|
30
|
-
|
|
31
24
|
/**
|
|
32
25
|
* Order used by the initialize instructions. Clients that defer MCP tools (Codex
|
|
33
26
|
* shows only the server's `instructions` until a namespace is loaded, and appends
|
|
@@ -37,6 +30,7 @@ const SUBAGENT_DESCRIPTION = [
|
|
|
37
30
|
const TOOL_ORDER = [
|
|
38
31
|
"question",
|
|
39
32
|
"subagent",
|
|
33
|
+
"subagent_list",
|
|
40
34
|
"models",
|
|
41
35
|
"todowrite",
|
|
42
36
|
"session_create",
|
|
@@ -73,6 +67,7 @@ interface McpTool {
|
|
|
73
67
|
name: string
|
|
74
68
|
description: string
|
|
75
69
|
inputSchema: Record<string, unknown>
|
|
70
|
+
nativeInput?: unknown
|
|
76
71
|
call: (args: any, signal: AbortSignal) => Promise<any>
|
|
77
72
|
}
|
|
78
73
|
|
|
@@ -96,6 +91,47 @@ const objectSchema = (properties: Record<string, unknown>, required: string[] =
|
|
|
96
91
|
|
|
97
92
|
const stringSchema = (description?: string) => ({ type: "string", ...(description ? { description } : {}) })
|
|
98
93
|
|
|
94
|
+
function schemaRecord(value: unknown): Record<string, unknown> | undefined {
|
|
95
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function nativeSchema(input: unknown) {
|
|
99
|
+
try {
|
|
100
|
+
if (Schema.isSchema(input)) {
|
|
101
|
+
return Schema.toJsonSchemaDocument(input, {
|
|
102
|
+
referencePolicy: () => undefined,
|
|
103
|
+
generateDescriptions: false,
|
|
104
|
+
}).schema
|
|
105
|
+
}
|
|
106
|
+
const schema = schemaRecord(input)
|
|
107
|
+
const jsonSchema = schemaRecord(schemaRecord(schema?.["~standard"])?.jsonSchema)
|
|
108
|
+
if (typeof jsonSchema?.input === "function") return jsonSchema.input({ target: "draft-2020-12" }) as unknown
|
|
109
|
+
return schema
|
|
110
|
+
} catch {
|
|
111
|
+
// Not every registry schema supports JSON Schema export.
|
|
112
|
+
return undefined
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Only copy annotations at existing field paths; the bridge owns the wire shape and constraints.
|
|
117
|
+
function withNativeDescriptions(input: Record<string, unknown>, source: unknown): Record<string, unknown> {
|
|
118
|
+
const native = schemaRecord(source)
|
|
119
|
+
if (!native) return input
|
|
120
|
+
const result = { ...input }
|
|
121
|
+
if (typeof native.description === "string") result.description = native.description
|
|
122
|
+
const properties = schemaRecord(input.properties)
|
|
123
|
+
const nativeProperties = schemaRecord(native.properties)
|
|
124
|
+
if (properties && nativeProperties) {
|
|
125
|
+
result.properties = Object.fromEntries(Object.entries(properties).map(([key, value]) => {
|
|
126
|
+
const field = schemaRecord(value)
|
|
127
|
+
return [key, field ? withNativeDescriptions(field, nativeProperties[key]) : value]
|
|
128
|
+
}))
|
|
129
|
+
}
|
|
130
|
+
const items = schemaRecord(input.items)
|
|
131
|
+
if (items) result.items = withNativeDescriptions(items, native.items)
|
|
132
|
+
return result
|
|
133
|
+
}
|
|
134
|
+
|
|
99
135
|
/**
|
|
100
136
|
* How to launch the stdio bridge. An absolute runtime runs directly; a bare
|
|
101
137
|
* name (default `node`) is looked up on PATH, through `/usr/bin/env` on POSIX
|
|
@@ -328,16 +364,14 @@ export async function createMcpServer(options: McpServerOptions): Promise<McpSer
|
|
|
328
364
|
tools: tools.map((tool) => ({
|
|
329
365
|
name: tool.name,
|
|
330
366
|
description: tool.description,
|
|
331
|
-
inputSchema: tool.inputSchema,
|
|
367
|
+
inputSchema: withNativeDescriptions(tool.inputSchema, nativeSchema(tool.nativeInput)),
|
|
332
368
|
})),
|
|
333
369
|
})
|
|
334
370
|
}
|
|
335
371
|
case "tools/call": {
|
|
336
372
|
const name = String(message.params?.name ?? "")
|
|
337
373
|
const args = message.params?.arguments ?? {}
|
|
338
|
-
|
|
339
|
-
// lookup that only feeds the subagent description.
|
|
340
|
-
const tools = await buildTools(ctx, sessionKey, options.localService, log, { describe: false })
|
|
374
|
+
const tools = await buildTools(ctx, sessionKey, options.localService, log)
|
|
341
375
|
const tool = tools.find((candidate) => candidate.name === name)
|
|
342
376
|
if (!tool) return fail(-32602, `Unknown tool: ${name}`)
|
|
343
377
|
const startedAt = Date.now()
|
|
@@ -488,7 +522,7 @@ async function buildInstructions(
|
|
|
488
522
|
log?: LogFn,
|
|
489
523
|
) {
|
|
490
524
|
// Only the names are used here.
|
|
491
|
-
const tools = await buildTools(ctx, sessionKey, service, log
|
|
525
|
+
const tools = await buildTools(ctx, sessionKey, service, log)
|
|
492
526
|
if (!tools.length) return undefined
|
|
493
527
|
const names = new Set(tools.map((tool) => tool.name))
|
|
494
528
|
// Tools the model is most likely to need come first; some clients append this
|
|
@@ -511,7 +545,7 @@ async function buildInstructions(
|
|
|
511
545
|
}
|
|
512
546
|
if (names.has("subagent")) {
|
|
513
547
|
lines.push(
|
|
514
|
-
"Use `
|
|
548
|
+
"Use `subagent_list` to discover agent IDs and descriptions, then delegate with `subagent` ({ agent, description, prompt }).",
|
|
515
549
|
"It returns at once and reports back with a <subagent> message when the child goes idle; do not poll it.",
|
|
516
550
|
)
|
|
517
551
|
}
|
|
@@ -526,7 +560,6 @@ async function buildTools(
|
|
|
526
560
|
sessionKey: string,
|
|
527
561
|
localService?: LocalServiceSource,
|
|
528
562
|
log?: LogFn,
|
|
529
|
-
{ describe = true }: { describe?: boolean } = {},
|
|
530
563
|
): Promise<McpTool[]> {
|
|
531
564
|
const tools: McpTool[] = []
|
|
532
565
|
const available = await ctx.tool.list().catch(() => [])
|
|
@@ -563,7 +596,8 @@ async function buildTools(
|
|
|
563
596
|
if (models) {
|
|
564
597
|
tools.push({
|
|
565
598
|
name: "models",
|
|
566
|
-
description:
|
|
599
|
+
description: models.description,
|
|
600
|
+
nativeInput: models.input,
|
|
567
601
|
inputSchema: objectSchema({
|
|
568
602
|
query: stringSchema("Text to search for in model names and IDs."),
|
|
569
603
|
provider: stringSchema("Provider ID or name to filter by. Try your own provider first."),
|
|
@@ -588,7 +622,8 @@ async function buildTools(
|
|
|
588
622
|
if (subagent) {
|
|
589
623
|
tools.push({
|
|
590
624
|
name: "subagent",
|
|
591
|
-
description:
|
|
625
|
+
description: subagent.description,
|
|
626
|
+
nativeInput: subagent.input,
|
|
592
627
|
inputSchema: objectSchema(
|
|
593
628
|
{
|
|
594
629
|
agent: stringSchema(
|
|
@@ -610,28 +645,35 @@ async function buildTools(
|
|
|
610
645
|
return toMcpResult(await invoke(subagent, input, signal))
|
|
611
646
|
},
|
|
612
647
|
})
|
|
648
|
+
tools.push({
|
|
649
|
+
name: "subagent_list",
|
|
650
|
+
description: "List available OpenCode subagents and their descriptions. Call before delegating with `subagent` to pick a valid `agent` ID.",
|
|
651
|
+
inputSchema: objectSchema({}),
|
|
652
|
+
call: async () => {
|
|
653
|
+
const { data } = await ctx.agent.list()
|
|
654
|
+
const agents = data
|
|
655
|
+
.filter((agent) => agent.mode !== "primary" && !agent.hidden)
|
|
656
|
+
.sort((left, right) => left.id.localeCompare(right.id))
|
|
657
|
+
.map(({ id, description }) => ({
|
|
658
|
+
id,
|
|
659
|
+
description,
|
|
660
|
+
}))
|
|
661
|
+
return toMcpResult({ agents })
|
|
662
|
+
},
|
|
663
|
+
})
|
|
613
664
|
}
|
|
614
665
|
|
|
615
666
|
const question = find("question")
|
|
616
667
|
if (question) {
|
|
617
668
|
tools.push({
|
|
618
669
|
name: "question",
|
|
619
|
-
description:
|
|
620
|
-
|
|
621
|
-
"1. Gather user preferences or requirements",
|
|
622
|
-
"2. Clarify ambiguous instructions",
|
|
623
|
-
"3. Get decisions on implementation choices as you work",
|
|
624
|
-
"4. Offer choices to the user about what direction to take.",
|
|
625
|
-
"",
|
|
626
|
-
"Usage notes:",
|
|
627
|
-
"- A \"Type your own answer\" option is added automatically; don't include a separate option for free form answers",
|
|
628
|
-
"- Set `multiple: true` to allow selecting more than one option",
|
|
629
|
-
"- If you recommend a specific option, make that the first option in the list and add \"(Recommended)\" at the end of the label",
|
|
630
|
-
].join("\n"),
|
|
670
|
+
description: question.description,
|
|
671
|
+
nativeInput: question.input,
|
|
631
672
|
inputSchema: objectSchema({
|
|
632
673
|
questions: {
|
|
633
674
|
type: "array",
|
|
634
675
|
description: "Questions to ask",
|
|
676
|
+
minItems: 1,
|
|
635
677
|
items: objectSchema(
|
|
636
678
|
{
|
|
637
679
|
header: stringSchema("Very short label (max 30 chars)"),
|
|
@@ -669,15 +711,8 @@ async function buildTools(
|
|
|
669
711
|
if (todowrite) {
|
|
670
712
|
tools.push({
|
|
671
713
|
name: "todowrite",
|
|
672
|
-
description:
|
|
673
|
-
|
|
674
|
-
"",
|
|
675
|
-
"Use it proactively when a task has 3 or more distinct steps, or when the user gives several tasks or asks for a todo list. Skip it for a single simple task or a purely conversational request. When in doubt, use it.",
|
|
676
|
-
"",
|
|
677
|
-
"- Send the full list on every call; it replaces the previous one.",
|
|
678
|
-
"- Mark items `in_progress` when you start them and `completed` as soon as they're actually done.",
|
|
679
|
-
"- Only call it when the list changes.",
|
|
680
|
-
].join("\n"),
|
|
714
|
+
description: todowrite.description,
|
|
715
|
+
nativeInput: todowrite.input,
|
|
681
716
|
inputSchema: objectSchema({
|
|
682
717
|
todos: {
|
|
683
718
|
type: "array",
|
|
@@ -831,12 +866,19 @@ async function buildTools(
|
|
|
831
866
|
},
|
|
832
867
|
{
|
|
833
868
|
name: "worktree_create",
|
|
834
|
-
description:
|
|
869
|
+
description:
|
|
870
|
+
"Create a detached git worktree for the calling session's project and return its directory. Defaults to the project's canonical checkout HEAD; pass `from` for another existing checkout/worktree directory or `branch` for an existing starting ref (commit, branch, or tag). Mirrors worktree.create.",
|
|
835
871
|
inputSchema: objectSchema({
|
|
836
|
-
from: stringSchema(
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
872
|
+
from: stringSchema(
|
|
873
|
+
"Absolute path of an existing checkout or worktree directory to start from. Defaults to the project's canonical checkout. Do not pass a commit SHA or ref here; use `branch` for refs.",
|
|
874
|
+
),
|
|
875
|
+
branch: stringSchema(
|
|
876
|
+
"Existing git ref (commit SHA, branch, or tag) to start the detached worktree at, not the name of a new branch to create.",
|
|
877
|
+
),
|
|
878
|
+
name: stringSchema("Name for the worktree; used to pick its directory name."),
|
|
879
|
+
directory: stringSchema(
|
|
880
|
+
"Parent directory for the new worktree. Uses the project's configured worktree directory or OpenCode's default if omitted; the strategy may choose another, so use the returned directory.",
|
|
881
|
+
),
|
|
840
882
|
}),
|
|
841
883
|
call: async (args, signal) => {
|
|
842
884
|
await assertPermission(ctx, sessionKey, "worktree", "*", "create", signal)
|
|
@@ -876,22 +918,6 @@ async function buildTools(
|
|
|
876
918
|
return tools
|
|
877
919
|
}
|
|
878
920
|
|
|
879
|
-
async function subagentDescription(ctx: Ctx) {
|
|
880
|
-
const parts = [SUBAGENT_DESCRIPTION]
|
|
881
|
-
try {
|
|
882
|
-
const agents = (await ctx.agent.list()).data
|
|
883
|
-
const available = agents
|
|
884
|
-
.filter((agent) => agent.mode !== "primary" && !agent.hidden)
|
|
885
|
-
.sort((left, right) => left.id.localeCompare(right.id))
|
|
886
|
-
if (available.length) {
|
|
887
|
-
parts.push("", "Available subagents:", ...available.map((agent) => `- ${agent.id}: ${agent.description ?? "This subagent should only be called when explicitly requested."}`))
|
|
888
|
-
}
|
|
889
|
-
} catch {
|
|
890
|
-
// agent discovery is best effort
|
|
891
|
-
}
|
|
892
|
-
return parts.join("\n")
|
|
893
|
-
}
|
|
894
|
-
|
|
895
921
|
/**
|
|
896
922
|
* Ask for a `session` or `worktree` permission on a target. Listing spans
|
|
897
923
|
* targets, so it is asserted against `"*"` and needs an explicit permission of
|
|
@@ -915,7 +941,8 @@ async function assertPermission(
|
|
|
915
941
|
} as any)
|
|
916
942
|
} catch (error) {
|
|
917
943
|
if (signal.aborted) throw error
|
|
918
|
-
const
|
|
944
|
+
const detail = errorMessage(error)
|
|
945
|
+
const message = detail !== "Error" && detail !== "Unknown error" ? `: ${detail}` : ""
|
|
919
946
|
const scope = target === "*" ? "" : ` on ${target}`
|
|
920
947
|
throw new Error(`Permission denied: ${action} ${operation}${scope}${message}`)
|
|
921
948
|
}
|
|
@@ -998,4 +1025,3 @@ function boundContext(messages: any[]) {
|
|
|
998
1025
|
}
|
|
999
1026
|
return { messages: messages.slice(start), truncated: true, omittedMessages: start }
|
|
1000
1027
|
}
|
|
1001
|
-
|
package/src/prompt.ts
CHANGED
|
@@ -18,12 +18,29 @@ export function isAuxiliaryRequest(kind: unknown) {
|
|
|
18
18
|
return kind === "title" || kind === "generate" || kind === "compaction"
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* OpenCode injects harness blocks such as `<system-reminder>` (plan mode,
|
|
23
|
+
* opened-file notes) and `<system-update>` into user text. ACP agents run on
|
|
24
|
+
* their own instructions, so drop them. Only whole blocks that start and end
|
|
25
|
+
* on their own lines match, so a user mentioning a tag inline is untouched.
|
|
26
|
+
*/
|
|
27
|
+
const SYSTEM_BLOCK = /(^|\n)[ \t]*<(system(?:[-_][a-z]+)*)(?:\s[^>]*)?>[\s\S]*?<\/\2>[ \t]*(?=\n|$)/gi
|
|
28
|
+
|
|
29
|
+
export function stripSystemBlocks(text: string): string {
|
|
30
|
+
if (!text.includes("<system")) return text
|
|
31
|
+
const stripped = text.replace(SYSTEM_BLOCK, "$1")
|
|
32
|
+
return stripped === text ? text : stripped.replace(/\n{3,}/g, "\n\n").trim()
|
|
33
|
+
}
|
|
34
|
+
|
|
21
35
|
export function textOf(message: ChatMessage): string {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
36
|
+
const text = typeof message.content === "string"
|
|
37
|
+
? message.content
|
|
38
|
+
: Array.isArray(message.content)
|
|
39
|
+
? message.content
|
|
40
|
+
.flatMap((part) => part?.type === "text" && typeof part.text === "string" && part.text ? [part.text] : [])
|
|
41
|
+
.join("\n")
|
|
42
|
+
: ""
|
|
43
|
+
return message.role === "user" ? stripSystemBlocks(text) : text
|
|
27
44
|
}
|
|
28
45
|
|
|
29
46
|
const conversational = (message: ChatMessage) => message.role === "user" || message.role === "assistant"
|
|
@@ -33,6 +50,10 @@ const speaker = (message: ChatMessage) => message.role === "assistant" ? "Assist
|
|
|
33
50
|
* Keep the current turn intact, plus the suffix needed to reconstruct bounded
|
|
34
51
|
* replay. One extra history character lets the shim detect truncation without
|
|
35
52
|
* losing the original clipping or sending the whole oldest retained message.
|
|
53
|
+
*
|
|
54
|
+
* OpenCode drains every message queued while it was busy after the last
|
|
55
|
+
* assistant reply, so a turn can be several consecutive user messages. All of
|
|
56
|
+
* them are the current turn and none of them may be clipped or dropped.
|
|
36
57
|
*/
|
|
37
58
|
export function boundedMessages<T extends ChatMessage>(
|
|
38
59
|
messages: readonly T[],
|
|
@@ -40,14 +61,16 @@ export function boundedMessages<T extends ChatMessage>(
|
|
|
40
61
|
includeSystem: boolean,
|
|
41
62
|
): Array<{ message: T; text: string }> {
|
|
42
63
|
const kept: Array<{ message: T; text: string }> = []
|
|
43
|
-
let
|
|
64
|
+
let phase: "tail" | "current-user" | "history" = "tail"
|
|
65
|
+
// A tool-only assistant turn has no text to replay, but it still separates
|
|
66
|
+
// trailing user messages from older history. Hold it back until some older
|
|
67
|
+
// history is kept, so no dangling blank assistant message is emitted.
|
|
68
|
+
let boundary: T | undefined
|
|
44
69
|
let turns = 0
|
|
45
70
|
let budget = limits.chars > 0 ? limits.chars + 1 : 0
|
|
46
71
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
47
72
|
const message = messages[i]
|
|
48
73
|
if (!message) continue
|
|
49
|
-
const historyFull = turns >= limits.turns || budget <= 0
|
|
50
|
-
if (latest && historyFull && !includeSystem) break
|
|
51
74
|
if (message.role === "system") {
|
|
52
75
|
if (includeSystem) {
|
|
53
76
|
const text = textOf(message)
|
|
@@ -55,14 +78,39 @@ export function boundedMessages<T extends ChatMessage>(
|
|
|
55
78
|
}
|
|
56
79
|
continue
|
|
57
80
|
}
|
|
58
|
-
if (
|
|
81
|
+
if (phase === "history" && (turns >= limits.turns || budget <= 0) && !includeSystem) break
|
|
82
|
+
if (!conversational(message)) {
|
|
83
|
+
// A tool result ends the assistant turn that follows the current user.
|
|
84
|
+
if (phase === "current-user") phase = "history"
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
59
87
|
const text = textOf(message)
|
|
60
|
-
if (
|
|
61
|
-
|
|
88
|
+
if (phase === "tail") {
|
|
89
|
+
if (!text.trim()) continue
|
|
62
90
|
kept.push({ message, text })
|
|
63
|
-
|
|
91
|
+
phase = message.role === "user" ? "current-user" : "history"
|
|
64
92
|
continue
|
|
65
93
|
}
|
|
94
|
+
if (phase === "current-user") {
|
|
95
|
+
if (message.role === "user") {
|
|
96
|
+
if (text.trim()) kept.push({ message, text })
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
phase = "history"
|
|
100
|
+
}
|
|
101
|
+
const historyFull = turns >= limits.turns || budget <= 0
|
|
102
|
+
if (historyFull) {
|
|
103
|
+
if (!includeSystem) break
|
|
104
|
+
continue
|
|
105
|
+
}
|
|
106
|
+
if (!text.trim()) {
|
|
107
|
+
if (message.role === "assistant" && turns === 0 && !boundary) boundary = message
|
|
108
|
+
continue
|
|
109
|
+
}
|
|
110
|
+
if (boundary) {
|
|
111
|
+
kept.push({ message: boundary, text: "" })
|
|
112
|
+
boundary = undefined
|
|
113
|
+
}
|
|
66
114
|
const tail = text.length > budget ? text.slice(-budget) : text
|
|
67
115
|
// The visible prefix is clipped away; it keeps a whitespace-only tail
|
|
68
116
|
// from being mistaken for an originally empty turn by the shim.
|
|
@@ -74,7 +122,10 @@ export function boundedMessages<T extends ChatMessage>(
|
|
|
74
122
|
}
|
|
75
123
|
|
|
76
124
|
function historyText(turns: Array<{ message: ChatMessage; text: string }>, chars: number) {
|
|
77
|
-
const text = turns
|
|
125
|
+
const text = turns
|
|
126
|
+
.filter(({ text }) => text.trim())
|
|
127
|
+
.map(({ message, text }) => `${speaker(message)}${text}`)
|
|
128
|
+
.join("\n\n")
|
|
78
129
|
return text.length > chars ? `[...earlier history omitted...]\n\n${text.slice(-chars)}` : text
|
|
79
130
|
}
|
|
80
131
|
|
|
@@ -89,7 +140,10 @@ export function recentConversation(messages: ChatMessage[], limits: HistoryLimit
|
|
|
89
140
|
export function buildPrompts(messages: ChatMessage[], limits: HistoryLimits, includeSystem: boolean) {
|
|
90
141
|
const turns = boundedMessages(messages, limits, includeSystem)
|
|
91
142
|
const conversation = turns.filter(({ message }) => conversational(message))
|
|
92
|
-
|
|
143
|
+
// Every trailing user message is part of the same turn; send them together.
|
|
144
|
+
const pending: string[] = []
|
|
145
|
+
while (conversation.at(-1)?.message.role === "user") pending.unshift(conversation.pop()!.text)
|
|
146
|
+
const latest = pending.length ? pending.join("\n\n") : conversation.pop()?.text ?? ""
|
|
93
147
|
const history = historyText(conversation, limits.chars)
|
|
94
148
|
const system = turns.filter(({ message }) => message.role === "system").map(({ text }) => text).join("\n\n")
|
|
95
149
|
return {
|