opencode-acp-provider 1.1.1 → 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 +29 -4
- package/package.json +1 -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 +12 -5
- package/src/mcp-bridge.mjs +34 -4
- package/src/mcp-server.ts +14 -6
- package/src/prompt.ts +46 -9
- package/src/util.ts +60 -2
package/README.md
CHANGED
|
@@ -102,10 +102,29 @@ delegation and questions through the MCP bridge instead of a second hidden agent
|
|
|
102
102
|
{
|
|
103
103
|
"id": "claude",
|
|
104
104
|
"command": ["claude-agent-acp"],
|
|
105
|
-
"meta": {
|
|
105
|
+
"meta": {
|
|
106
|
+
"claudeCode": {
|
|
107
|
+
"options": {
|
|
108
|
+
"disallowedTools": [
|
|
109
|
+
"Task", "AskUserQuestion",
|
|
110
|
+
"EnterPlanMode", "ExitPlanMode", "EnterWorktree", "ExitWorktree",
|
|
111
|
+
"ListAgents", "SendMessage",
|
|
112
|
+
"CronCreate", "CronDelete", "CronList", "ScheduleWakeup",
|
|
113
|
+
"PushNotification", "RemoteTrigger", "SendToProject", "SendToProjectContext", "DesignSync"
|
|
114
|
+
]
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
106
118
|
}
|
|
107
119
|
```
|
|
108
120
|
|
|
121
|
+
Beyond subagents and questions, this list drops tools that do nothing useful under an ACP host:
|
|
122
|
+
plan mode (approval turns into an auto-approved permission request; use OpenCode's plan agent),
|
|
123
|
+
native worktrees (edits move out of OpenCode's snapshots; use `worktree_create`), peer-session
|
|
124
|
+
messaging, scheduling (idle sessions and processes close, so schedules die silently, and a firing
|
|
125
|
+
one starts a turn nobody sent), and Claude app features (push notifications, remote triggers,
|
|
126
|
+
projects, design sync). claude.ai connectors stay available.
|
|
127
|
+
|
|
109
128
|
The adapter accepts injected HTTP MCP servers, so `mcpTransport: "http"` works.
|
|
110
129
|
|
|
111
130
|
### Codex (`codex`)
|
|
@@ -115,11 +134,16 @@ The adapter accepts injected HTTP MCP servers, so `mcpTransport: "http"` works.
|
|
|
115
134
|
"id": "codex",
|
|
116
135
|
"command": ["codex-acp"],
|
|
117
136
|
"env": {
|
|
118
|
-
"CODEX_CONFIG": "{\"agents\":{\"enabled\":false},\"tools\":{\"experimental_request_user_input\":{\"enabled\":false}}}"
|
|
137
|
+
"CODEX_CONFIG": "{\"agents\":{\"enabled\":false},\"tools\":{\"experimental_request_user_input\":{\"enabled\":false}},\"features\":{\"goals\":false,\"tool_suggest\":false,\"image_generation\":false}}"
|
|
119
138
|
}
|
|
120
139
|
}
|
|
121
140
|
```
|
|
122
141
|
|
|
142
|
+
`features` turns off Codex goals (use OpenCode's goal loop), plugin-install suggestions, and image
|
|
143
|
+
generation (the plugin forwards text only). To drop individual ChatGPT apps, add
|
|
144
|
+
`"apps":{"<connector_id>":{"enabled":false}}`; the ids are in
|
|
145
|
+
`~/.codex/cache/codex_apps_tools/*.json` (`connector_id`).
|
|
146
|
+
|
|
123
147
|
Codex drops injected HTTP MCP servers, so keep the stdio transport. It does not advertise `/compact`,
|
|
124
148
|
so a manual `/compact` reports that it cannot compact on request.
|
|
125
149
|
|
|
@@ -148,7 +172,8 @@ Ships its own ACP stdio server, so it needs no adapter package:
|
|
|
148
172
|
with the server's `mode` option. Permission requests in `default` mode go through `autoApprove`.
|
|
149
173
|
- **Native tools.** `agy` keeps `ask_question` plus its own subagent family (`invoke_subagent`,
|
|
150
174
|
`define_subagent`, `manage_subagents`, `swarm`, `run_workflow`). ACP has no question method, so
|
|
151
|
-
`ask_question` prints the question into the turn and ends, which looks like a stalled prompt.
|
|
175
|
+
`ask_question` prints the question into the turn and ends, which looks like a stalled prompt.
|
|
176
|
+
`send_message` only talks to its native subagents, and `schedule` timers die with idle sessions. Its
|
|
152
177
|
`permissions` block cannot gate these (it covers only `read_file`, `write_file`, `read_url`,
|
|
153
178
|
`execute_url`, `command`, and `mcp`), so deny them by tool name in `~/.gemini/config/hooks.json`
|
|
154
179
|
(every workspace) or `<workspace>/.agents/hooks.json`:
|
|
@@ -158,7 +183,7 @@ Ships its own ACP stdio server, so it needs no adapter package:
|
|
|
158
183
|
"opencode-orchestration": {
|
|
159
184
|
"PreToolUse": [
|
|
160
185
|
{
|
|
161
|
-
"matcher": "ask_question|invoke_subagent|define_subagent|manage_subagents|swarm|run_workflow",
|
|
186
|
+
"matcher": "ask_question|invoke_subagent|define_subagent|manage_subagents|swarm|run_workflow|send_message|schedule",
|
|
162
187
|
"hooks": [
|
|
163
188
|
{
|
|
164
189
|
"command": "echo '{\"decision\":\"deny\",\"reason\":\"Use the OpenCode question and subagent tools instead.\"}'"
|
package/package.json
CHANGED
package/src/agents/README.md
CHANGED
|
@@ -33,8 +33,10 @@ src/agents/
|
|
|
33
33
|
|
|
34
34
|
### `no-native-orchestration.ts`
|
|
35
35
|
|
|
36
|
-
Removes the native `agent`, `agent_output`, and `ask_user_question`
|
|
37
|
-
tools
|
|
36
|
+
Removes the native `agent`, `agent_output`, and `ask_user_question` tools from the main loop, along
|
|
37
|
+
with tools an ACP host cannot use: plan mode (`enter_plan_mode`, `exit_plan_mode`, `plan_review`),
|
|
38
|
+
worktrees (`enter_worktree`, `exit_worktree`), scheduling (`cron_create`, `cron_delete`,
|
|
39
|
+
`cron_list`, `schedule_wakeup`), and artifact publishing (`artifact_publish`, `artifact_manage`). Command Code's permission rules cannot block the `agent` tool (its docs
|
|
38
40
|
mark it as always allowed), so the mod uses `cmd.setActiveTools` to remove it from the model's schema
|
|
39
41
|
and `beforeToolCall` to refuse any call that still arrives.
|
|
40
42
|
|
package/src/agents/cmd/index.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { isCmdCommand } from "../../agent-command.ts"
|
|
|
3
3
|
|
|
4
4
|
const mod = (name: string) => fileURLToPath(new URL(`./mods/${name}`, import.meta.url))
|
|
5
5
|
|
|
6
|
-
/** Hides cmd's native
|
|
6
|
+
/** Hides cmd's native orchestration, question, plan, worktree, scheduling, and artifact tools inside ACP. */
|
|
7
7
|
export const CMD_ORCHESTRATION_MOD = mod("no-native-orchestration.ts")
|
|
8
8
|
/** Registers OPENCODE_ACP_PROVIDER_SKILL_DIR with cmd, because `cmd acp` ignores `--skill`. */
|
|
9
9
|
export const CMD_SKILL_MOD = mod("opencode-skills.ts")
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Disable Command Code's native
|
|
2
|
+
* Disable Command Code's native tools that OpenCode replaces or cannot host inside `cmd acp`.
|
|
3
3
|
*
|
|
4
4
|
* Command Code exposes `agent` and `agent_output` to the main loop. Inside an
|
|
5
5
|
* ACP host such as OpenCode those duplicate the orchestrator, which already
|
|
@@ -12,19 +12,47 @@
|
|
|
12
12
|
* showing OpenCode's question UI. The agent should call the host's MCP
|
|
13
13
|
* `question` tool instead.
|
|
14
14
|
*
|
|
15
|
+
* The rest have no place under an ACP host:
|
|
16
|
+
* - Plan mode (`enter_plan_mode`, `exit_plan_mode`, `plan_review`): approval
|
|
17
|
+
* becomes an auto-approved permission request and the review panel lives in
|
|
18
|
+
* cmd's own TUI. OpenCode has its own plan agent.
|
|
19
|
+
* - Worktrees (`enter_worktree`, `exit_worktree`): moving the session out of
|
|
20
|
+
* the OpenCode location hides its edits from OpenCode's snapshots. The host
|
|
21
|
+
* exposes `worktree_create` instead.
|
|
22
|
+
* - Scheduling (`cron_*`, `schedule_wakeup`): pooled ACP sessions and agent
|
|
23
|
+
* processes close when idle, so schedules die silently, and a firing one
|
|
24
|
+
* starts a turn the user never sent.
|
|
25
|
+
* - Artifacts (`artifact_publish`, `artifact_manage`): publish to Command
|
|
26
|
+
* Code's hosting, unrelated to OpenCode.
|
|
27
|
+
*
|
|
15
28
|
* Loaded automatically by the plugin (src/agents/cmd/index.ts) on any `cmd ... acp`
|
|
16
29
|
* command while the MCP bridge is enabled. `--safe-mode` disables it.
|
|
17
30
|
*/
|
|
18
31
|
import type { ModApi } from "@commandcode/harness"
|
|
19
32
|
|
|
20
|
-
const
|
|
33
|
+
const REASONS: Record<string, string> = {
|
|
34
|
+
agent: "Native subagents are disabled. Use the host's own subagent tool instead.",
|
|
35
|
+
agent_output: "Native subagents are disabled. Use the host's own subagent tool instead.",
|
|
36
|
+
ask_user_question: "Native questions are disabled. Use the host's MCP `question` tool instead.",
|
|
37
|
+
enter_plan_mode: "Plan mode is disabled inside OpenCode. Plan in the conversation instead.",
|
|
38
|
+
exit_plan_mode: "Plan mode is disabled inside OpenCode. Plan in the conversation instead.",
|
|
39
|
+
plan_review: "Plan mode is disabled inside OpenCode. Plan in the conversation instead.",
|
|
40
|
+
enter_worktree: "Native worktrees are disabled. Use the host's MCP `worktree_create` tool instead.",
|
|
41
|
+
exit_worktree: "Native worktrees are disabled. Use the host's MCP `worktree_create` tool instead.",
|
|
42
|
+
cron_create: "Scheduling is disabled inside OpenCode.",
|
|
43
|
+
cron_delete: "Scheduling is disabled inside OpenCode.",
|
|
44
|
+
cron_list: "Scheduling is disabled inside OpenCode.",
|
|
45
|
+
schedule_wakeup: "Scheduling is disabled inside OpenCode.",
|
|
46
|
+
artifact_publish: "Artifact publishing is disabled inside OpenCode.",
|
|
47
|
+
artifact_manage: "Artifact publishing is disabled inside OpenCode.",
|
|
48
|
+
}
|
|
21
49
|
|
|
22
50
|
export default function (cmd: ModApi) {
|
|
23
51
|
const hide = () => {
|
|
24
52
|
// Base the filter on the *active* tools, not every registered tool: another
|
|
25
53
|
// mod may already have disabled something, and getAllTools would re-enable it.
|
|
26
54
|
const active = cmd.getActiveTools()
|
|
27
|
-
const next = active.filter((name) => !
|
|
55
|
+
const next = active.filter((name) => !Object.hasOwn(REASONS, name))
|
|
28
56
|
if (next.length !== active.length) cmd.setActiveTools(next)
|
|
29
57
|
}
|
|
30
58
|
|
|
@@ -41,14 +69,8 @@ export default function (cmd: ModApi) {
|
|
|
41
69
|
},
|
|
42
70
|
// Fail closed if a call slips through the schema filter.
|
|
43
71
|
beforeToolCall({ toolName }) {
|
|
44
|
-
if (!
|
|
45
|
-
return {
|
|
46
|
-
block: true,
|
|
47
|
-
additionalContext:
|
|
48
|
-
toolName === "ask_user_question"
|
|
49
|
-
? "Native questions are disabled. Use the host's MCP `question` tool instead."
|
|
50
|
-
: "Native subagents are disabled. Use the host's own subagent tool instead.",
|
|
51
|
-
}
|
|
72
|
+
if (!Object.hasOwn(REASONS, toolName)) return undefined
|
|
73
|
+
return { block: true, additionalContext: REASONS[toolName] }
|
|
52
74
|
},
|
|
53
75
|
})
|
|
54
76
|
}
|
package/src/index.ts
CHANGED
|
@@ -92,6 +92,8 @@ function storedSessionKey(poolKey: string) {
|
|
|
92
92
|
/**
|
|
93
93
|
* Resolve an ACP continuation token when OpenCode is running a turn prompted by
|
|
94
94
|
* a background-completion synthetic message rather than a new user prompt.
|
|
95
|
+
* A wake queued behind another pending message is left for a normal prompt, so
|
|
96
|
+
* only a lone user message at the turn boundary can attach a continuation.
|
|
95
97
|
*/
|
|
96
98
|
function continuationTokenOf(
|
|
97
99
|
messages: ReadonlyArray<{
|
|
@@ -102,16 +104,21 @@ function continuationTokenOf(
|
|
|
102
104
|
sessionID: string,
|
|
103
105
|
manager: Pick<AcpServerManager, "findContinuationByText">,
|
|
104
106
|
): string | undefined {
|
|
107
|
+
let pending: (typeof messages)[number] | undefined
|
|
105
108
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
106
109
|
const message = messages[i]
|
|
107
110
|
if (!message) continue
|
|
108
|
-
if (message.role === "assistant")
|
|
111
|
+
if (message.role === "assistant" || message.role === "tool") break
|
|
109
112
|
if (message.role !== "user") continue
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
+
if (!textOf(message).trim()) continue
|
|
114
|
+
// More than one pending message means the turn is not only the wake.
|
|
115
|
+
if (pending) return undefined
|
|
116
|
+
pending = message
|
|
113
117
|
}
|
|
114
|
-
return undefined
|
|
118
|
+
if (!pending) return undefined
|
|
119
|
+
const token = pending.metadata?.source === "acp-background" ? pending.metadata.acpContinuation : undefined
|
|
120
|
+
if (typeof token === "string" && token) return token
|
|
121
|
+
return sessionID ? manager.findContinuationByText(sessionID, textOf(pending)) : undefined
|
|
115
122
|
}
|
|
116
123
|
|
|
117
124
|
|
package/src/mcp-bridge.mjs
CHANGED
|
@@ -16,8 +16,38 @@ let protocolVersion = null
|
|
|
16
16
|
let buffer = ""
|
|
17
17
|
const aborters = new Map()
|
|
18
18
|
|
|
19
|
+
function extractErrorMessage(error, seen) {
|
|
20
|
+
if (error === null || error === undefined) return undefined
|
|
21
|
+
if (typeof error === "string") return error.trim() ? error : undefined
|
|
22
|
+
if (typeof error !== "object") {
|
|
23
|
+
try {
|
|
24
|
+
return String(error)
|
|
25
|
+
} catch {
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (seen.has(error)) return undefined
|
|
30
|
+
seen.add(error)
|
|
31
|
+
if (typeof error.message === "string" && error.message.trim()) return error.message
|
|
32
|
+
if (error.cause !== undefined) {
|
|
33
|
+
const caused = extractErrorMessage(error.cause, seen)
|
|
34
|
+
if (caused) return caused
|
|
35
|
+
}
|
|
36
|
+
if (typeof error.name === "string" && error.name.trim()) return error.name
|
|
37
|
+
try {
|
|
38
|
+
const text = String(error).trim()
|
|
39
|
+
return text && text !== "[object Object]" ? text : undefined
|
|
40
|
+
} catch {
|
|
41
|
+
return undefined
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function errorMessage(error) {
|
|
46
|
+
return extractErrorMessage(error, new Set()) ?? "Unknown error"
|
|
47
|
+
}
|
|
48
|
+
|
|
19
49
|
process.stdout.on("error", (error) => {
|
|
20
|
-
process.stderr.write(`mcp-bridge: stdout failed: ${error
|
|
50
|
+
process.stderr.write(`mcp-bridge: stdout failed: ${errorMessage(error)}\n`)
|
|
21
51
|
process.exit(1)
|
|
22
52
|
})
|
|
23
53
|
process.stderr.on("error", () => process.exit(1))
|
|
@@ -95,7 +125,7 @@ async function handle(message) {
|
|
|
95
125
|
try {
|
|
96
126
|
await post(message)
|
|
97
127
|
} catch (error) {
|
|
98
|
-
log(
|
|
128
|
+
log(errorMessage(error))
|
|
99
129
|
}
|
|
100
130
|
return
|
|
101
131
|
}
|
|
@@ -117,7 +147,7 @@ async function handle(message) {
|
|
|
117
147
|
write({
|
|
118
148
|
jsonrpc: "2.0",
|
|
119
149
|
id: message.id,
|
|
120
|
-
error: { code: -32000, message:
|
|
150
|
+
error: { code: -32000, message: errorMessage(error) },
|
|
121
151
|
})
|
|
122
152
|
} finally {
|
|
123
153
|
aborters.delete(message.id)
|
|
@@ -145,6 +175,6 @@ process.stdin.on("data", (chunk) => {
|
|
|
145
175
|
process.stdin.on("end", () => process.exit(0))
|
|
146
176
|
process.stdin.on("close", () => process.exit(0))
|
|
147
177
|
process.stdin.on("error", (error) => {
|
|
148
|
-
log(error
|
|
178
|
+
log(errorMessage(error))
|
|
149
179
|
process.exit(1)
|
|
150
180
|
})
|
package/src/mcp-server.ts
CHANGED
|
@@ -866,12 +866,19 @@ async function buildTools(
|
|
|
866
866
|
},
|
|
867
867
|
{
|
|
868
868
|
name: "worktree_create",
|
|
869
|
-
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.",
|
|
870
871
|
inputSchema: objectSchema({
|
|
871
|
-
from: stringSchema(
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
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
|
+
),
|
|
875
882
|
}),
|
|
876
883
|
call: async (args, signal) => {
|
|
877
884
|
await assertPermission(ctx, sessionKey, "worktree", "*", "create", signal)
|
|
@@ -934,7 +941,8 @@ async function assertPermission(
|
|
|
934
941
|
} as any)
|
|
935
942
|
} catch (error) {
|
|
936
943
|
if (signal.aborted) throw error
|
|
937
|
-
const
|
|
944
|
+
const detail = errorMessage(error)
|
|
945
|
+
const message = detail !== "Error" && detail !== "Unknown error" ? `: ${detail}` : ""
|
|
938
946
|
const scope = target === "*" ? "" : ` on ${target}`
|
|
939
947
|
throw new Error(`Permission denied: ${action} ${operation}${scope}${message}`)
|
|
940
948
|
}
|
package/src/prompt.ts
CHANGED
|
@@ -50,6 +50,10 @@ const speaker = (message: ChatMessage) => message.role === "assistant" ? "Assist
|
|
|
50
50
|
* Keep the current turn intact, plus the suffix needed to reconstruct bounded
|
|
51
51
|
* replay. One extra history character lets the shim detect truncation without
|
|
52
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.
|
|
53
57
|
*/
|
|
54
58
|
export function boundedMessages<T extends ChatMessage>(
|
|
55
59
|
messages: readonly T[],
|
|
@@ -57,14 +61,16 @@ export function boundedMessages<T extends ChatMessage>(
|
|
|
57
61
|
includeSystem: boolean,
|
|
58
62
|
): Array<{ message: T; text: string }> {
|
|
59
63
|
const kept: Array<{ message: T; text: string }> = []
|
|
60
|
-
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
|
|
61
69
|
let turns = 0
|
|
62
70
|
let budget = limits.chars > 0 ? limits.chars + 1 : 0
|
|
63
71
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
64
72
|
const message = messages[i]
|
|
65
73
|
if (!message) continue
|
|
66
|
-
const historyFull = turns >= limits.turns || budget <= 0
|
|
67
|
-
if (latest && historyFull && !includeSystem) break
|
|
68
74
|
if (message.role === "system") {
|
|
69
75
|
if (includeSystem) {
|
|
70
76
|
const text = textOf(message)
|
|
@@ -72,14 +78,39 @@ export function boundedMessages<T extends ChatMessage>(
|
|
|
72
78
|
}
|
|
73
79
|
continue
|
|
74
80
|
}
|
|
75
|
-
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
|
+
}
|
|
76
87
|
const text = textOf(message)
|
|
77
|
-
if (
|
|
78
|
-
|
|
88
|
+
if (phase === "tail") {
|
|
89
|
+
if (!text.trim()) continue
|
|
79
90
|
kept.push({ message, text })
|
|
80
|
-
|
|
91
|
+
phase = message.role === "user" ? "current-user" : "history"
|
|
92
|
+
continue
|
|
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
|
|
81
104
|
continue
|
|
82
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
|
+
}
|
|
83
114
|
const tail = text.length > budget ? text.slice(-budget) : text
|
|
84
115
|
// The visible prefix is clipped away; it keeps a whitespace-only tail
|
|
85
116
|
// from being mistaken for an originally empty turn by the shim.
|
|
@@ -91,7 +122,10 @@ export function boundedMessages<T extends ChatMessage>(
|
|
|
91
122
|
}
|
|
92
123
|
|
|
93
124
|
function historyText(turns: Array<{ message: ChatMessage; text: string }>, chars: number) {
|
|
94
|
-
const text = turns
|
|
125
|
+
const text = turns
|
|
126
|
+
.filter(({ text }) => text.trim())
|
|
127
|
+
.map(({ message, text }) => `${speaker(message)}${text}`)
|
|
128
|
+
.join("\n\n")
|
|
95
129
|
return text.length > chars ? `[...earlier history omitted...]\n\n${text.slice(-chars)}` : text
|
|
96
130
|
}
|
|
97
131
|
|
|
@@ -106,7 +140,10 @@ export function recentConversation(messages: ChatMessage[], limits: HistoryLimit
|
|
|
106
140
|
export function buildPrompts(messages: ChatMessage[], limits: HistoryLimits, includeSystem: boolean) {
|
|
107
141
|
const turns = boundedMessages(messages, limits, includeSystem)
|
|
108
142
|
const conversation = turns.filter(({ message }) => conversational(message))
|
|
109
|
-
|
|
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 ?? ""
|
|
110
147
|
const history = historyText(conversation, limits.chars)
|
|
111
148
|
const system = turns.filter(({ message }) => message.role === "system").map(({ text }) => text).join("\n\n")
|
|
112
149
|
return {
|
package/src/util.ts
CHANGED
|
@@ -62,9 +62,67 @@ export function agentName(config: { name?: string; id: string }) {
|
|
|
62
62
|
return (config.name ?? config.id).replace(/\s*\(ACP\)$/, "")
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
function nonEmptyString(value: unknown): string | undefined {
|
|
66
|
+
return typeof value === "string" && value.trim().length > 0 ? value : undefined
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function extractErrorMessage(error: unknown, seen: Set<unknown>): string | undefined {
|
|
70
|
+
if (error === null || error === undefined) return undefined
|
|
71
|
+
if (typeof error === "string") return nonEmptyString(error)
|
|
72
|
+
if (typeof error !== "object") return String(error)
|
|
73
|
+
if (seen.has(error)) return undefined
|
|
74
|
+
seen.add(error)
|
|
75
|
+
|
|
76
|
+
const record = error as Record<string, unknown>
|
|
77
|
+
const direct = nonEmptyString(record.message)
|
|
78
|
+
if (direct) return direct
|
|
79
|
+
|
|
80
|
+
const data = record.data
|
|
81
|
+
if (data && typeof data === "object") {
|
|
82
|
+
const nested = nonEmptyString((data as Record<string, unknown>).message)
|
|
83
|
+
if (nested) return nested
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if ("cause" in record && record.cause !== undefined) {
|
|
87
|
+
const caused = extractErrorMessage(record.cause, seen)
|
|
88
|
+
if (caused) return caused
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if ("error" in record && record.error !== undefined) {
|
|
92
|
+
const inner = extractErrorMessage(record.error, seen)
|
|
93
|
+
if (inner) return inner
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (Array.isArray(record.errors)) {
|
|
97
|
+
const parts = record.errors
|
|
98
|
+
.map((item) => extractErrorMessage(item, seen))
|
|
99
|
+
.filter((item): item is string => Boolean(item))
|
|
100
|
+
if (parts.length) return parts.join("; ")
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const tag = nonEmptyString(record._tag) ?? nonEmptyString(record.name)
|
|
104
|
+
if (tag) return tag
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
const text = String(error).trim()
|
|
108
|
+
if (text && text !== "[object Object]") return text
|
|
109
|
+
} catch {
|
|
110
|
+
// null-prototype or otherwise unconvertible
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
const json = JSON.stringify(error)
|
|
115
|
+
if (json && json !== "{}") return json
|
|
116
|
+
} catch {
|
|
117
|
+
// circular or otherwise unserializable
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return undefined
|
|
121
|
+
}
|
|
122
|
+
|
|
65
123
|
/** The message of a thrown value, whatever was thrown. */
|
|
66
|
-
export function errorMessage(error: unknown) {
|
|
67
|
-
return error
|
|
124
|
+
export function errorMessage(error: unknown): string {
|
|
125
|
+
return extractErrorMessage(error, new Set()) ?? "Unknown error"
|
|
68
126
|
}
|
|
69
127
|
|
|
70
128
|
/** Listen on an ephemeral loopback port and return it. */
|