@agentprojectcontext/apx 1.17.0 → 1.18.0
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentprojectcontext/apx",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.18.0",
|
|
4
4
|
"description": "APX — unified CLI + daemon for the Agent Project Context (APC) standard.",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -35,10 +35,6 @@
|
|
|
35
35
|
},
|
|
36
36
|
"packageManager": "pnpm@10.25.0",
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@langchain/anthropic": "^0.3.34",
|
|
39
|
-
"@langchain/community": "^0.3.59",
|
|
40
|
-
"@langchain/core": "^0.3.80",
|
|
41
|
-
"@langchain/ollama": "^0.2.4",
|
|
42
38
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
43
39
|
"@opentui/core": "^0.2.8",
|
|
44
40
|
"@opentui/keymap": "^0.2.8",
|
|
@@ -56,7 +52,6 @@
|
|
|
56
52
|
"express": "^4.21.0",
|
|
57
53
|
"fuzzysort": "^3.1.0",
|
|
58
54
|
"jsonc-parser": "^3.3.1",
|
|
59
|
-
"langchain": "^0.3.37",
|
|
60
55
|
"node-fetch": "^3.3.2",
|
|
61
56
|
"open": "^11.0.0",
|
|
62
57
|
"opentui-spinner": "^0.0.6",
|
|
@@ -226,19 +226,6 @@ export async function runSuperAgent({
|
|
|
226
226
|
const sa = globalConfig.super_agent;
|
|
227
227
|
const activeModel = overrideModel || sa.model;
|
|
228
228
|
|
|
229
|
-
// Engine toggle: if config.super_agent.engine === "langchain", delegate to
|
|
230
|
-
// the LangChain AgentExecutor adapter. Default stays "native" (this loop).
|
|
231
|
-
// The toggle exists so we can A/B the two paths on the user's actual chat
|
|
232
|
-
// without committing to a full migration. See super-agent-langchain.js.
|
|
233
|
-
if (sa.engine === "langchain") {
|
|
234
|
-
const { runSuperAgentLangChain } = await import("./super-agent-langchain.js");
|
|
235
|
-
return runSuperAgentLangChain({
|
|
236
|
-
globalConfig, projects, plugins, registries,
|
|
237
|
-
prompt, previousMessages, contextNote,
|
|
238
|
-
onEvent, onToken, signal,
|
|
239
|
-
});
|
|
240
|
-
}
|
|
241
|
-
|
|
242
229
|
// Tiny project hint — JUST names + ids, no detail. The model is expected to
|
|
243
230
|
// call list_agents / list_mcps / read_agent_memory / etc. for everything
|
|
244
231
|
// else. Keeping this short forces actual tool use instead of letting the
|
|
@@ -4,6 +4,7 @@ import { onCleanup } from "solid-js"
|
|
|
4
4
|
import fs from "node:fs"
|
|
5
5
|
import os from "node:os"
|
|
6
6
|
import path from "node:path"
|
|
7
|
+
import { spawn } from "node:child_process"
|
|
7
8
|
|
|
8
9
|
const TOKEN_PATH = path.join(os.homedir(), ".apx", "daemon.token")
|
|
9
10
|
|
|
@@ -20,6 +21,9 @@ export type ApxEvent =
|
|
|
20
21
|
| { type: "chunk"; sessionID: string; chunk: string }
|
|
21
22
|
| { type: "final"; sessionID: string; text: string; usage?: { input_tokens: number; output_tokens: number } }
|
|
22
23
|
| { type: "error"; sessionID: string; error: string }
|
|
24
|
+
| { type: "shell.start"; sessionID: string; shellID: string; command: string; cwd: string }
|
|
25
|
+
| { type: "shell.output"; sessionID: string; shellID: string; stream: "stdout" | "stderr"; chunk: string }
|
|
26
|
+
| { type: "shell.done"; sessionID: string; shellID: string; exitCode: number | null; signal: NodeJS.Signals | null }
|
|
23
27
|
|
|
24
28
|
export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
|
|
25
29
|
name: "SDK",
|
|
@@ -102,6 +106,27 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
|
|
|
102
106
|
return (data as any).id as string
|
|
103
107
|
}
|
|
104
108
|
|
|
109
|
+
function runShell(sessionID: string, command: string, cwd: string = process.cwd()): Promise<{ shellID: string; exitCode: number | null }> {
|
|
110
|
+
const shellID = `sh-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`
|
|
111
|
+
emitter.emit("event", { type: "shell.start", sessionID, shellID, command, cwd })
|
|
112
|
+
return new Promise((resolve) => {
|
|
113
|
+
const child = spawn(command, { shell: true, cwd, env: process.env })
|
|
114
|
+
child.stdout?.on("data", (buf) => {
|
|
115
|
+
emitter.emit("event", { type: "shell.output", sessionID, shellID, stream: "stdout", chunk: buf.toString() })
|
|
116
|
+
})
|
|
117
|
+
child.stderr?.on("data", (buf) => {
|
|
118
|
+
emitter.emit("event", { type: "shell.output", sessionID, shellID, stream: "stderr", chunk: buf.toString() })
|
|
119
|
+
})
|
|
120
|
+
child.on("error", (err) => {
|
|
121
|
+
emitter.emit("event", { type: "shell.output", sessionID, shellID, stream: "stderr", chunk: `[spawn error] ${err.message}\n` })
|
|
122
|
+
})
|
|
123
|
+
child.on("close", (code, signal) => {
|
|
124
|
+
emitter.emit("event", { type: "shell.done", sessionID, shellID, exitCode: code, signal })
|
|
125
|
+
resolve({ shellID, exitCode: code })
|
|
126
|
+
})
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
|
|
105
130
|
async function listSessions(): Promise<Array<{ id: string; title: string; updatedAt?: number }>> {
|
|
106
131
|
try {
|
|
107
132
|
const token = readToken()
|
|
@@ -146,7 +171,12 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
|
|
|
146
171
|
fork: async (_opts: any) => ({ data: undefined, error: new Error("not supported") }),
|
|
147
172
|
abort: async (_opts: any) => {},
|
|
148
173
|
prompt: async (_opts: any) => {},
|
|
149
|
-
shell: async (
|
|
174
|
+
shell: async (opts: { sessionID?: string; command?: string; cwd?: string }) => {
|
|
175
|
+
if (!opts?.command) return { data: undefined }
|
|
176
|
+
const sid = opts.sessionID || (await createSession())
|
|
177
|
+
const r = await runShell(sid, opts.command, opts.cwd)
|
|
178
|
+
return { data: r }
|
|
179
|
+
},
|
|
150
180
|
command: async (_opts: any) => {},
|
|
151
181
|
refresh: async () => {},
|
|
152
182
|
update: async (_opts: any) => ({ data: undefined }),
|
|
@@ -180,6 +210,7 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
|
|
|
180
210
|
streamChat,
|
|
181
211
|
createSession,
|
|
182
212
|
listSessions,
|
|
213
|
+
runShell,
|
|
183
214
|
}
|
|
184
215
|
},
|
|
185
216
|
})
|
|
@@ -13,10 +13,15 @@ export type ApxSession = {
|
|
|
13
13
|
export type ApxMessage = {
|
|
14
14
|
id: string
|
|
15
15
|
sessionID: string
|
|
16
|
-
role: "user" | "assistant"
|
|
16
|
+
role: "user" | "assistant" | "shell"
|
|
17
17
|
text: string
|
|
18
18
|
streaming?: boolean
|
|
19
19
|
error?: boolean
|
|
20
|
+
// Shell-specific
|
|
21
|
+
shellID?: string
|
|
22
|
+
command?: string
|
|
23
|
+
cwd?: string
|
|
24
|
+
exitCode?: number | null
|
|
20
25
|
}
|
|
21
26
|
|
|
22
27
|
export const { use: useApxSync, provider: ApxSyncProvider } = createSimpleContext({
|
|
@@ -78,6 +83,55 @@ export const { use: useApxSync, provider: ApxSyncProvider } = createSimpleContex
|
|
|
78
83
|
setStore("previousMessages", (prev) => [...prev, { role: "assistant", content: e.text }])
|
|
79
84
|
}
|
|
80
85
|
|
|
86
|
+
if (ev.type === "shell.start") {
|
|
87
|
+
const e = ev
|
|
88
|
+
setStore(
|
|
89
|
+
"messages",
|
|
90
|
+
produce((draft) => {
|
|
91
|
+
;(draft[e.sessionID] ??= []).push({
|
|
92
|
+
id: e.shellID,
|
|
93
|
+
sessionID: e.sessionID,
|
|
94
|
+
role: "shell",
|
|
95
|
+
text: "",
|
|
96
|
+
streaming: true,
|
|
97
|
+
shellID: e.shellID,
|
|
98
|
+
command: e.command,
|
|
99
|
+
cwd: e.cwd,
|
|
100
|
+
})
|
|
101
|
+
}),
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (ev.type === "shell.output") {
|
|
106
|
+
const e = ev
|
|
107
|
+
setStore(
|
|
108
|
+
"messages",
|
|
109
|
+
produce((draft) => {
|
|
110
|
+
const msgs = draft[e.sessionID]
|
|
111
|
+
if (!msgs) return
|
|
112
|
+
const target = msgs.find((m) => m.role === "shell" && m.shellID === e.shellID)
|
|
113
|
+
if (target) target.text += e.chunk
|
|
114
|
+
}),
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (ev.type === "shell.done") {
|
|
119
|
+
const e = ev
|
|
120
|
+
setStore(
|
|
121
|
+
"messages",
|
|
122
|
+
produce((draft) => {
|
|
123
|
+
const msgs = draft[e.sessionID]
|
|
124
|
+
if (!msgs) return
|
|
125
|
+
const target = msgs.find((m) => m.role === "shell" && m.shellID === e.shellID)
|
|
126
|
+
if (target) {
|
|
127
|
+
target.streaming = false
|
|
128
|
+
target.exitCode = e.exitCode
|
|
129
|
+
if (e.signal) target.text += `\n[killed by signal ${e.signal}]`
|
|
130
|
+
}
|
|
131
|
+
}),
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
|
|
81
135
|
if (ev.type === "error") {
|
|
82
136
|
const e = ev
|
|
83
137
|
setStore(
|
|
@@ -121,6 +175,11 @@ export const { use: useApxSync, provider: ApxSyncProvider } = createSimpleContex
|
|
|
121
175
|
return id
|
|
122
176
|
}
|
|
123
177
|
|
|
178
|
+
async function runShell(command: string, cwd?: string) {
|
|
179
|
+
const sessionID = await ensureSession()
|
|
180
|
+
await sdk.runShell(sessionID, command, cwd ?? process.cwd())
|
|
181
|
+
}
|
|
182
|
+
|
|
124
183
|
async function sendMessage(text: string) {
|
|
125
184
|
const sessionID = await ensureSession()
|
|
126
185
|
const userMsg: ApxMessage = {
|
|
@@ -172,6 +231,7 @@ export const { use: useApxSync, provider: ApxSyncProvider } = createSimpleContex
|
|
|
172
231
|
async refresh() {},
|
|
173
232
|
},
|
|
174
233
|
sendMessage,
|
|
234
|
+
runShell,
|
|
175
235
|
ensureSession,
|
|
176
236
|
}
|
|
177
237
|
},
|
|
@@ -47,6 +47,35 @@ function AssistantBubble(props: { msg: ApxMessage }) {
|
|
|
47
47
|
)
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
function ShellBubble(props: { msg: ApxMessage }) {
|
|
51
|
+
const { theme } = useTheme()
|
|
52
|
+
const header = () => {
|
|
53
|
+
const code = props.msg.exitCode
|
|
54
|
+
const status = props.msg.streaming
|
|
55
|
+
? "running"
|
|
56
|
+
: code === 0
|
|
57
|
+
? "exit 0"
|
|
58
|
+
: code == null
|
|
59
|
+
? "ended"
|
|
60
|
+
: `exit ${code}`
|
|
61
|
+
return `$ ${props.msg.command ?? ""} · ${status}`
|
|
62
|
+
}
|
|
63
|
+
const body = () => props.msg.text || (props.msg.streaming ? "…" : "(no output)")
|
|
64
|
+
return (
|
|
65
|
+
<box flexDirection="column" marginBottom={1} paddingLeft={2} paddingRight={2}>
|
|
66
|
+
<text color={theme.warning ?? theme.primary} bold>
|
|
67
|
+
{header()}
|
|
68
|
+
</text>
|
|
69
|
+
<text
|
|
70
|
+
color={props.msg.exitCode && props.msg.exitCode !== 0 ? theme.error : theme.text}
|
|
71
|
+
wrap
|
|
72
|
+
>
|
|
73
|
+
{body()}
|
|
74
|
+
</text>
|
|
75
|
+
</box>
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
|
|
50
79
|
export function Session() {
|
|
51
80
|
const dims = useTerminalDimensions()
|
|
52
81
|
const { theme } = useTheme()
|
|
@@ -109,7 +138,11 @@ export function Session() {
|
|
|
109
138
|
inputEl.clear()
|
|
110
139
|
setSending(true)
|
|
111
140
|
try {
|
|
112
|
-
|
|
141
|
+
if (text.startsWith("!") && text.length > 1) {
|
|
142
|
+
await sync.runShell(text.slice(1).trim())
|
|
143
|
+
} else {
|
|
144
|
+
await sync.sendMessage(text)
|
|
145
|
+
}
|
|
113
146
|
} catch (e) {
|
|
114
147
|
toast.error(e instanceof Error ? e : new Error(String(e)))
|
|
115
148
|
} finally {
|
|
@@ -132,17 +165,17 @@ export function Session() {
|
|
|
132
165
|
fallback={
|
|
133
166
|
<box paddingLeft={2} paddingTop={2}>
|
|
134
167
|
<text color={theme.textMuted} italic>
|
|
135
|
-
Type a message
|
|
168
|
+
Type a message to chat, or prefix with ! to run a shell command (e.g. !ls).
|
|
136
169
|
</text>
|
|
137
170
|
</box>
|
|
138
171
|
}
|
|
139
172
|
>
|
|
140
173
|
<For each={messages()}>
|
|
141
|
-
{(msg) =>
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
174
|
+
{(msg) => {
|
|
175
|
+
if (msg.role === "user") return <UserBubble msg={msg} />
|
|
176
|
+
if (msg.role === "shell") return <ShellBubble msg={msg} />
|
|
177
|
+
return <AssistantBubble msg={msg} />
|
|
178
|
+
}}
|
|
146
179
|
</For>
|
|
147
180
|
</Show>
|
|
148
181
|
<box height={1} />
|
|
@@ -163,7 +196,7 @@ export function Session() {
|
|
|
163
196
|
inputEl = r
|
|
164
197
|
promptRef.set(makeRef(r))
|
|
165
198
|
}}
|
|
166
|
-
placeholder={sending() ? "Waiting for response…" : "Ask anything... (
|
|
199
|
+
placeholder={sending() ? "Waiting for response…" : "Ask anything... (prefix ! to run shell, e.g. !ls)"}
|
|
167
200
|
placeholderColor={theme.textMuted}
|
|
168
201
|
textColor={theme.text}
|
|
169
202
|
focusedTextColor={theme.text}
|
|
@@ -1,296 +0,0 @@
|
|
|
1
|
-
// LangChain adapter for the APX super-agent.
|
|
2
|
-
//
|
|
3
|
-
// Lives alongside the native loop in super-agent.js. Selected via
|
|
4
|
-
// config.super_agent.engine === "langchain" (default: "native"). The two
|
|
5
|
-
// implementations expose the same shape:
|
|
6
|
-
//
|
|
7
|
-
// { text, usage, name, trace } ← return value
|
|
8
|
-
// { globalConfig, projects, plugins, registries, prompt,
|
|
9
|
-
// previousMessages, contextNote, onEvent, onToken, signal } ← input
|
|
10
|
-
//
|
|
11
|
-
// Why a toggle and not a replacement: the native loop carries APX-specific
|
|
12
|
-
// features (pseudo-tool fallback for Ollama 500, ghost-response detection,
|
|
13
|
-
// permission_mode gates wired through tool handlers, identity-block injection,
|
|
14
|
-
// ACK_ONLY_TOOLS streak guard). Re-implementing all of those inside LangChain
|
|
15
|
-
// is a large refactor; meanwhile the toggle lets us A/B both paths and pick
|
|
16
|
-
// the one that actually behaves better with gemma4-class models on the
|
|
17
|
-
// user's hardware.
|
|
18
|
-
//
|
|
19
|
-
// LangChain version compat: written against @langchain/core ^0.3 +
|
|
20
|
-
// langchain ^0.3 + @langchain/anthropic ^0.3 + @langchain/ollama ^0.2.
|
|
21
|
-
//
|
|
22
|
-
// Limitations vs native loop (acknowledged in v1):
|
|
23
|
-
// - permission_mode confirmations are still enforced inside each tool
|
|
24
|
-
// handler (they return {error: "requires_confirmation: ..."}), but
|
|
25
|
-
// the loop has no UI to ask the user mid-run, so confirmable tools
|
|
26
|
-
// just fail-fast as they do today.
|
|
27
|
-
// - Pseudo-tool fallback (for Ollama 500 on structured tools) is NOT
|
|
28
|
-
// implemented here — if the underlying engine fails, the call
|
|
29
|
-
// propagates. Use engine === "native" for that case.
|
|
30
|
-
|
|
31
|
-
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
|
|
32
|
-
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";
|
|
33
|
-
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
34
|
-
import { HumanMessage, AIMessage, ToolMessage } from "@langchain/core/messages";
|
|
35
|
-
import { z } from "zod";
|
|
36
|
-
|
|
37
|
-
import { TOOL_SCHEMAS, makeToolHandlers } from "./super-agent-tools.js";
|
|
38
|
-
import { readIdentity } from "../core/identity.js";
|
|
39
|
-
import { logInfo, logWarn, logError } from "../core/logging.js";
|
|
40
|
-
|
|
41
|
-
const MAX_ITER_DEFAULT = 15;
|
|
42
|
-
|
|
43
|
-
// ---------------------------------------------------------------------------
|
|
44
|
-
// JSON-Schema → Zod converter
|
|
45
|
-
// ---------------------------------------------------------------------------
|
|
46
|
-
// LangChain's DynamicStructuredTool wants a Zod schema. APX's tools ship JSON
|
|
47
|
-
// Schema (in the OpenAI function-calling shape). We translate just enough for
|
|
48
|
-
// the parameter types APX actually uses: string, number, boolean, object,
|
|
49
|
-
// array, enum, optional/required. Anything more exotic falls back to z.any().
|
|
50
|
-
function jsonSchemaToZod(schema) {
|
|
51
|
-
if (!schema || typeof schema !== "object") return z.any();
|
|
52
|
-
// OpenAI function shape: { type: "function", function: { parameters: {...} } }
|
|
53
|
-
const root = schema.function?.parameters || schema.parameters || schema;
|
|
54
|
-
return objectToZod(root);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function objectToZod(obj) {
|
|
58
|
-
if (!obj || obj.type !== "object" || !obj.properties) {
|
|
59
|
-
return z.object({}).passthrough();
|
|
60
|
-
}
|
|
61
|
-
const required = new Set(obj.required || []);
|
|
62
|
-
const shape = {};
|
|
63
|
-
for (const [key, prop] of Object.entries(obj.properties)) {
|
|
64
|
-
let s = propToZod(prop);
|
|
65
|
-
if (!required.has(key)) s = s.optional();
|
|
66
|
-
if (prop?.description) s = s.describe(prop.description);
|
|
67
|
-
shape[key] = s;
|
|
68
|
-
}
|
|
69
|
-
return z.object(shape);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function propToZod(prop) {
|
|
73
|
-
if (!prop || typeof prop !== "object") return z.any();
|
|
74
|
-
if (Array.isArray(prop.enum) && prop.enum.length > 0) {
|
|
75
|
-
return z.enum(prop.enum);
|
|
76
|
-
}
|
|
77
|
-
switch (prop.type) {
|
|
78
|
-
case "string": return z.string();
|
|
79
|
-
case "number": return z.number();
|
|
80
|
-
case "integer": return z.number().int();
|
|
81
|
-
case "boolean": return z.boolean();
|
|
82
|
-
case "array": return z.array(prop.items ? propToZod(prop.items) : z.any());
|
|
83
|
-
case "object": return objectToZod(prop);
|
|
84
|
-
default: return z.any();
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// ---------------------------------------------------------------------------
|
|
89
|
-
// APX tool → LangChain DynamicStructuredTool
|
|
90
|
-
// ---------------------------------------------------------------------------
|
|
91
|
-
function buildLangChainTools(handlers, schemas, { trace, onEvent }) {
|
|
92
|
-
return schemas.map((s) => {
|
|
93
|
-
const name = s.function.name;
|
|
94
|
-
const handler = handlers[name];
|
|
95
|
-
if (!handler) {
|
|
96
|
-
logWarn("super-agent-lc", `no handler for tool ${name} — skipping`);
|
|
97
|
-
return null;
|
|
98
|
-
}
|
|
99
|
-
return new DynamicStructuredTool({
|
|
100
|
-
name,
|
|
101
|
-
description: s.function.description || "",
|
|
102
|
-
schema: jsonSchemaToZod(s),
|
|
103
|
-
func: async (args) => {
|
|
104
|
-
const traceId = `lc:${trace.length + 1}`;
|
|
105
|
-
if (typeof onEvent === "function") {
|
|
106
|
-
try {
|
|
107
|
-
await onEvent({
|
|
108
|
-
type: "tool_start",
|
|
109
|
-
trace: { id: traceId, tool: name, args, pending: true },
|
|
110
|
-
});
|
|
111
|
-
} catch {}
|
|
112
|
-
}
|
|
113
|
-
try {
|
|
114
|
-
const result = await handler(args || {});
|
|
115
|
-
trace.push({ id: traceId, tool: name, args, result });
|
|
116
|
-
if (typeof onEvent === "function") {
|
|
117
|
-
try { await onEvent({ type: "tool_result", trace: { id: traceId, tool: name, args, result } }); } catch {}
|
|
118
|
-
}
|
|
119
|
-
return typeof result === "string" ? result : JSON.stringify(result);
|
|
120
|
-
} catch (e) {
|
|
121
|
-
const errObj = { error: e.message };
|
|
122
|
-
trace.push({ id: traceId, tool: name, args, result: errObj });
|
|
123
|
-
if (typeof onEvent === "function") {
|
|
124
|
-
try { await onEvent({ type: "tool_result", trace: { id: traceId, tool: name, args, result: errObj } }); } catch {}
|
|
125
|
-
}
|
|
126
|
-
return JSON.stringify(errObj);
|
|
127
|
-
}
|
|
128
|
-
},
|
|
129
|
-
});
|
|
130
|
-
}).filter(Boolean);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// ---------------------------------------------------------------------------
|
|
134
|
-
// Engine factory — picks an @langchain ChatModel based on modelId
|
|
135
|
-
// ---------------------------------------------------------------------------
|
|
136
|
-
async function makeLangChainModel(modelId, config) {
|
|
137
|
-
// modelId grammar matches engines/index.js: "<provider>:<model>" or
|
|
138
|
-
// an inferable bare model id ("claude-…" → anthropic, etc).
|
|
139
|
-
const [providerRaw, ...rest] = String(modelId || "").split(":");
|
|
140
|
-
let provider = providerRaw.toLowerCase();
|
|
141
|
-
let model = rest.join(":");
|
|
142
|
-
if (!model) {
|
|
143
|
-
// bare id — infer like engines/index.js
|
|
144
|
-
if (/^claude/i.test(providerRaw)) { provider = "anthropic"; model = providerRaw; }
|
|
145
|
-
else if (/^gpt|^o[134]/i.test(providerRaw)) { provider = "openai"; model = providerRaw; }
|
|
146
|
-
else if (/^gemini/i.test(providerRaw)) { provider = "gemini"; model = providerRaw; }
|
|
147
|
-
else { provider = "ollama"; model = providerRaw; }
|
|
148
|
-
}
|
|
149
|
-
const providerCfg = (config && config.engines && config.engines[provider]) || {};
|
|
150
|
-
|
|
151
|
-
if (provider === "anthropic") {
|
|
152
|
-
const { ChatAnthropic } = await import("@langchain/anthropic");
|
|
153
|
-
const apiKey = providerCfg.api_key || process.env.ANTHROPIC_API_KEY;
|
|
154
|
-
if (!apiKey) throw new Error("anthropic: no api_key set");
|
|
155
|
-
return new ChatAnthropic({ apiKey, model, temperature: 1.0, maxTokens: 1024 });
|
|
156
|
-
}
|
|
157
|
-
if (provider === "ollama") {
|
|
158
|
-
const { ChatOllama } = await import("@langchain/ollama");
|
|
159
|
-
const baseUrl = providerCfg.base_url || process.env.OLLAMA_HOST || "http://localhost:11434";
|
|
160
|
-
return new ChatOllama({ baseUrl, model, temperature: 0.7 });
|
|
161
|
-
}
|
|
162
|
-
if (provider === "openai") {
|
|
163
|
-
// Lazy import — only required if the user picks openai.
|
|
164
|
-
const { ChatOpenAI } = await import("@langchain/openai").catch(() => ({}));
|
|
165
|
-
if (!ChatOpenAI) throw new Error("openai: install @langchain/openai to use this provider with the langchain engine");
|
|
166
|
-
const apiKey = providerCfg.api_key || process.env.OPENAI_API_KEY;
|
|
167
|
-
if (!apiKey) throw new Error("openai: no api_key set");
|
|
168
|
-
return new ChatOpenAI({ apiKey, model, temperature: 1.0 });
|
|
169
|
-
}
|
|
170
|
-
throw new Error(`langchain engine: unknown provider "${provider}" (modelId="${modelId}")`);
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// ---------------------------------------------------------------------------
|
|
174
|
-
// Convert APX "previousMessages" rows ({role, content}) → LangChain messages
|
|
175
|
-
// ---------------------------------------------------------------------------
|
|
176
|
-
function toLangChainHistory(previousMessages) {
|
|
177
|
-
return (previousMessages || []).map((m) => {
|
|
178
|
-
if (m.role === "user") return new HumanMessage(m.content || "");
|
|
179
|
-
if (m.role === "assistant") return new AIMessage(m.content || "");
|
|
180
|
-
if (m.role === "tool") {
|
|
181
|
-
// LangChain ToolMessage requires a tool_call_id; APX doesn't track ids
|
|
182
|
-
// in the FS history, so we use a synthetic one. The agent only sees
|
|
183
|
-
// the content anyway.
|
|
184
|
-
return new ToolMessage({ content: m.content || "", tool_call_id: m.tool_name || "tool" });
|
|
185
|
-
}
|
|
186
|
-
return new HumanMessage(m.content || "");
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// ---------------------------------------------------------------------------
|
|
191
|
-
// Public entry — same contract as runSuperAgent in super-agent.js
|
|
192
|
-
// ---------------------------------------------------------------------------
|
|
193
|
-
export async function runSuperAgentLangChain({
|
|
194
|
-
globalConfig,
|
|
195
|
-
projects,
|
|
196
|
-
plugins,
|
|
197
|
-
registries,
|
|
198
|
-
prompt,
|
|
199
|
-
previousMessages = [],
|
|
200
|
-
contextNote = "",
|
|
201
|
-
systemOverride = null,
|
|
202
|
-
onEvent,
|
|
203
|
-
onToken,
|
|
204
|
-
signal,
|
|
205
|
-
}) {
|
|
206
|
-
const sa = globalConfig?.super_agent || {};
|
|
207
|
-
if (!sa.model) throw new Error("super-agent (langchain): no model configured");
|
|
208
|
-
|
|
209
|
-
const identity = (() => { try { return readIdentity(); } catch { return null; } })();
|
|
210
|
-
const userLang = globalConfig?.user?.language || "en";
|
|
211
|
-
|
|
212
|
-
// System prompt — we reuse the native module's DEFAULT_SYSTEM unless the
|
|
213
|
-
// caller passes systemOverride. This keeps the personality / language /
|
|
214
|
-
// hard-rules consistent across both engines.
|
|
215
|
-
const { DEFAULT_SYSTEM, buildIdentityBlock } = await import("./super-agent.js");
|
|
216
|
-
const identityBlock = buildIdentityBlock(identity, userLang);
|
|
217
|
-
const systemPieces = [
|
|
218
|
-
systemOverride || sa.system || DEFAULT_SYSTEM,
|
|
219
|
-
identityBlock,
|
|
220
|
-
contextNote,
|
|
221
|
-
].filter(Boolean);
|
|
222
|
-
// LangChain ChatPromptTemplate uses f-string formatting and will try to
|
|
223
|
-
// resolve any `{name}` it finds in the system text as an input variable.
|
|
224
|
-
// The APX prompt naturally contains literal `{path: <CWD>}` examples and
|
|
225
|
-
// JSON-like snippets, so we double every `{` and `}` to escape them.
|
|
226
|
-
const systemText = systemPieces.join("\n\n").replace(/[{}]/g, (c) => c + c);
|
|
227
|
-
|
|
228
|
-
const trace = [];
|
|
229
|
-
const handlers = makeToolHandlers({
|
|
230
|
-
projects, plugins, registries, globalConfig,
|
|
231
|
-
implicitConfirmation: false,
|
|
232
|
-
});
|
|
233
|
-
const tools = buildLangChainTools(handlers, TOOL_SCHEMAS, { trace, onEvent });
|
|
234
|
-
|
|
235
|
-
logInfo("super-agent-lc", "starting AgentExecutor", {
|
|
236
|
-
model: sa.model, tools: tools.length, prev: previousMessages.length,
|
|
237
|
-
});
|
|
238
|
-
|
|
239
|
-
const llm = await makeLangChainModel(sa.model, globalConfig);
|
|
240
|
-
|
|
241
|
-
const promptTemplate = ChatPromptTemplate.fromMessages([
|
|
242
|
-
["system", systemText],
|
|
243
|
-
new MessagesPlaceholder("chat_history"),
|
|
244
|
-
["human", "{input}"],
|
|
245
|
-
new MessagesPlaceholder("agent_scratchpad"),
|
|
246
|
-
]);
|
|
247
|
-
|
|
248
|
-
const agent = await createToolCallingAgent({ llm, tools, prompt: promptTemplate });
|
|
249
|
-
|
|
250
|
-
const executor = new AgentExecutor({
|
|
251
|
-
agent,
|
|
252
|
-
tools,
|
|
253
|
-
maxIterations: Number(sa.max_iterations) > 0 ? Number(sa.max_iterations) : MAX_ITER_DEFAULT,
|
|
254
|
-
returnIntermediateSteps: true,
|
|
255
|
-
handleParsingErrors: true,
|
|
256
|
-
// verbose is noisy; we already log via core/logging.js
|
|
257
|
-
});
|
|
258
|
-
|
|
259
|
-
const t0 = Date.now();
|
|
260
|
-
let result;
|
|
261
|
-
try {
|
|
262
|
-
if (typeof onEvent === "function") {
|
|
263
|
-
try { await onEvent({ type: "model_start", iteration: 1 }); } catch {}
|
|
264
|
-
}
|
|
265
|
-
result = await executor.invoke({
|
|
266
|
-
input: prompt,
|
|
267
|
-
chat_history: toLangChainHistory(previousMessages),
|
|
268
|
-
}, { signal });
|
|
269
|
-
} catch (e) {
|
|
270
|
-
logError("super-agent-lc", `executor failed in ${Date.now() - t0}ms`, { error: e.message });
|
|
271
|
-
throw e;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// result.output is the final text. result.intermediateSteps is an array
|
|
275
|
-
// of { action, observation }; we already pushed each into `trace` from the
|
|
276
|
-
// DynamicStructuredTool wrappers, so we don't double-record them here.
|
|
277
|
-
const text = String(result.output || "");
|
|
278
|
-
logInfo("super-agent-lc", `done in ${Date.now() - t0}ms`, {
|
|
279
|
-
text_len: text.length,
|
|
280
|
-
tool_calls: trace.length,
|
|
281
|
-
});
|
|
282
|
-
|
|
283
|
-
return {
|
|
284
|
-
text,
|
|
285
|
-
// LangChain doesn't surface token counts uniformly across providers;
|
|
286
|
-
// leave 0/0 so the caller's bookkeeping doesn't break. Real values
|
|
287
|
-
// would require provider-specific callback handlers.
|
|
288
|
-
usage: { input_tokens: 0, output_tokens: 0 },
|
|
289
|
-
name: sa.name || "apx",
|
|
290
|
-
trace,
|
|
291
|
-
};
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
export function isLangChainEngineSelected(cfg) {
|
|
295
|
-
return cfg?.super_agent?.engine === "langchain";
|
|
296
|
-
}
|