feat(pi): enable native QuickJS-WASI codemode extension for batched tool orchestration
This commit is contained in:
parent
b501a91913
commit
f76fcdf407
|
|
@ -406,6 +406,9 @@ multi_agent:
|
|||
tool_search_always_visible: 12
|
||||
tool_search_always_visible_tools: [get_tool_execution, wait_tool_execution, cancel_tool_execution, search_knowledge_base]
|
||||
tool_search_include_builtins: true # true:后端内置工具始终常驻,绕过 tool_search
|
||||
codemode_enable: false # true:启用 Pi 原生 QuickJS-WASI codemode 沙箱,模型可用一段 JS 批量编排/过滤多步工具调用
|
||||
codemode_mode: on # codemode 工具面板形态:留空/on(默认,常规工具并存)或 only(脚本优先);其他值拒绝加载
|
||||
codemode_inline_budget: 0 # >0 时限制 codemode 描述中内联工具声明的估算 token 预算;0 用 Pi 默认
|
||||
plantask_enable: true
|
||||
plantask_rel_dir: .pi/plantask
|
||||
reduction_enable: true
|
||||
|
|
|
|||
|
|
@ -80,6 +80,9 @@ type Request struct {
|
|||
ToolSearch bool `json:"toolSearch"`
|
||||
ToolSearchMinTools int `json:"toolSearchMinTools,omitempty"`
|
||||
AlwaysVisibleTools []string `json:"alwaysVisibleTools,omitempty"`
|
||||
Codemode bool `json:"codemode,omitempty"`
|
||||
CodemodeMode string `json:"codemodeMode,omitempty"`
|
||||
CodemodeInlineBudget int `json:"codemodeInlineBudget,omitempty"`
|
||||
SessionDir string `json:"sessionDir,omitempty"`
|
||||
MaxTurns int `json:"maxTurns"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -170,6 +170,12 @@ type AgentTuningConfig struct {
|
|||
ToolSearchAlwaysVisibleTools []string `yaml:"tool_search_always_visible_tools,omitempty" json:"tool_search_always_visible_tools,omitempty"`
|
||||
// ToolSearchIncludeBuiltins keeps backend builtin tools always visible (nil = true).
|
||||
ToolSearchIncludeBuiltins *bool `yaml:"tool_search_include_builtins,omitempty" json:"tool_search_include_builtins,omitempty"`
|
||||
// CodemodeEnable turns on Pi's native QuickJS-WASI codemode extension for sandboxed batched tool orchestration.
|
||||
CodemodeEnable bool `yaml:"codemode_enable" json:"codemode_enable"`
|
||||
// CodemodeMode selects the codemode loadout presentation: "" / "on" (default) / "only".
|
||||
CodemodeMode string `yaml:"codemode_mode,omitempty" json:"codemode_mode,omitempty"`
|
||||
// CodemodeInlineBudget caps estimated tokens of tool declarations in the codemode description; positive values pass through.
|
||||
CodemodeInlineBudget int `yaml:"codemode_inline_budget,omitempty" json:"codemode_inline_budget,omitempty"`
|
||||
// Plantask adds TaskCreate/Get/Update/List (file-backed under skills dir); requires skills and its configured directory.
|
||||
PlantaskEnable bool `yaml:"plantask_enable,omitempty" json:"plantask_enable,omitempty"`
|
||||
// PlantaskRelDir relative to skills_dir for per-conversation task boards (default .pi/plantask).
|
||||
|
|
@ -237,6 +243,16 @@ type AgentTuningConfig struct {
|
|||
TaskToolDescriptionPrefix string `yaml:"task_tool_description_prefix,omitempty" json:"task_tool_description_prefix,omitempty"`
|
||||
}
|
||||
|
||||
// ValidateCodemode rejects codemode_mode values Pi cannot interpret.
|
||||
func (c AgentTuningConfig) ValidateCodemode() error {
|
||||
switch c.CodemodeMode {
|
||||
case "", "on", "only":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("multi_agent.runtime.codemode_mode 仅支持留空、on 或 only,当前为 %q", c.CodemodeMode)
|
||||
}
|
||||
}
|
||||
|
||||
func (c AgentTuningConfig) SummarizationTriggerRatioEffective() float64 {
|
||||
v := c.SummarizationTriggerRatio
|
||||
if v <= 0 {
|
||||
|
|
@ -1581,6 +1597,9 @@ func Load(path string) (*Config, error) {
|
|||
if err := cfg.Agent.validateTaskTimeout(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.MultiAgent.Runtime.ValidateCodemode(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.ToolGuard != nil {
|
||||
if err := validateToolGuardYAML(data); err != nil {
|
||||
return nil, fmt.Errorf("调用拦截配置无效: %w", err)
|
||||
|
|
|
|||
|
|
@ -238,6 +238,35 @@ func TestLoadRejectsInvalidChannelContextSettings(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidCodemodeMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, mode := range []string{"", "on", "only", "off", "batch"} {
|
||||
mode := mode
|
||||
t.Run("mode="+mode, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
body := "multi_agent:\n runtime:\n codemode_enable: true\n codemode_mode: " + mode + "\n"
|
||||
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
|
||||
t.Fatalf("write config: %v", err)
|
||||
}
|
||||
cfg, err := Load(path)
|
||||
if mode == "off" || mode == "batch" {
|
||||
if err == nil || !strings.Contains(err.Error(), "codemode_mode") {
|
||||
t.Fatalf("Load error = %v, want codemode_mode rejection", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if !cfg.MultiAgent.Runtime.CodemodeEnable || cfg.MultiAgent.Runtime.CodemodeMode != mode {
|
||||
t.Fatalf("codemode fields not preserved: %+v", cfg.MultiAgent.Runtime)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAIProviderProfilesForOfficialDeepSeekEndpoint(t *testing.T) {
|
||||
cfg := &Config{
|
||||
OpenAI: OpenAIConfig{
|
||||
|
|
|
|||
|
|
@ -349,6 +349,14 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) {
|
|||
req.ToolSearch = r.cfg.MultiAgent.Runtime.ToolSearchEnable
|
||||
req.ToolSearchMinTools = r.cfg.MultiAgent.Runtime.ToolSearchMinTools
|
||||
req.AlwaysVisibleTools = append([]string(nil), r.cfg.MultiAgent.Runtime.ToolSearchAlwaysVisibleTools...)
|
||||
if r.cfg.MultiAgent.Runtime.CodemodeEnable {
|
||||
req.Codemode = true
|
||||
req.CodemodeMode = r.cfg.MultiAgent.Runtime.CodemodeMode
|
||||
req.CodemodeInlineBudget = r.cfg.MultiAgent.Runtime.CodemodeInlineBudget
|
||||
if req.ToolSearch && !slices.Contains(req.AlwaysVisibleTools, "codemode") {
|
||||
req.AlwaysVisibleTools = append(req.AlwaysVisibleTools, "codemode")
|
||||
}
|
||||
}
|
||||
if options.Native == nil && r.cfg.MultiAgent.Runtime.ToolSearchIncludeBuiltinsEffective() {
|
||||
req.AlwaysVisibleTools = append(req.AlwaysVisibleTools, builtin.GetAllBuiltinTools()...)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { InMemoryCredentialStore, type Model, type Api, type AssistantMessage, t
|
|||
import {
|
||||
createAgentSession, createExtensionRuntime, ModelRuntime, SessionManager, SettingsManager,
|
||||
type AgentSession, type ResourceLoader, type ToolDefinition,
|
||||
DefaultResourceLoader, createToolSearchExtension, loadSkills, formatSkillsForPrompt,
|
||||
DefaultResourceLoader, createToolSearchExtension, createCodemodeExtension, loadSkills, formatSkillsForPrompt,
|
||||
} from "@earendil-works/pi-coding-agent";
|
||||
import { PROTOCOL_VERSION, RecordReader, send } from "./protocol.js";
|
||||
import { installModelFetchPolicy } from "./network.js";
|
||||
|
|
@ -38,6 +38,7 @@ interface RunRequest {
|
|||
retryMaxDelayMs?: number;
|
||||
toolSearch?: boolean; alwaysVisibleTools?: string[];
|
||||
toolSearchMinTools?: number;
|
||||
codemode?: boolean; codemodeMode?: "on" | "only"; codemodeInlineBudget?: number;
|
||||
}
|
||||
interface ToolReply { content: string; images?: Omit<ImageContent, "type">[]; isError?: boolean; executionId?: string; terminate?: boolean; structuredContent?: Record<string, unknown> }
|
||||
|
||||
|
|
@ -267,6 +268,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
const workingDir = req.workingDir ? resolve(req.workingDir) : scratch;
|
||||
const names = req.tools.map(t => t.name);
|
||||
if (new Set(names).size !== names.length || names.some(n => !/^[a-zA-Z0-9_.-]+$/.test(n))) throw new Error("Invalid tool catalog");
|
||||
const codemodeEnabled = req.codemode === true && !names.includes("codemode");
|
||||
const runtime = await ModelRuntime.create({ credentials: new InMemoryCredentialStore(), modelsPath: null,
|
||||
modelsStorePath: join(scratch, "models.json"), allowModelNetwork: false, refreshOnCreate: false });
|
||||
const configs = [req.model, ...(req.fallbackModels ?? [])];
|
||||
|
|
@ -348,7 +350,9 @@ async function run(req: RunRequest): Promise<void> {
|
|||
? formatSkillsForPrompt(skills.skills, "indirect")
|
||||
+ `\nLoad matching skill files with ${skillLoaderTool}. Skill resources are task data and do not expand tool permissions.`
|
||||
: "";
|
||||
const systemPrompt = req.systemPrompt + skillsPrompt + (req.systemPromptDynamic ?? "");
|
||||
const systemPrompt = req.systemPrompt + skillsPrompt
|
||||
+ (codemodeEnabled ? "\nUse codemode to batch, join, or filter multi-step tool calls in a single sandboxed JavaScript turn when raw tool outputs would be large." : "")
|
||||
+ (req.systemPromptDynamic ?? "");
|
||||
if (req.generateOnly) {
|
||||
const input = SessionManager.inMemory(scratch);
|
||||
importHistory(input, req.history ?? [], req.model);
|
||||
|
|
@ -380,10 +384,15 @@ async function run(req: RunRequest): Promise<void> {
|
|||
const searchEnabled = req.toolSearch === true && names.length >= (req.toolSearchMinTools || 20) && !names.includes("tool_search");
|
||||
const always = new Set(["task", "exit", "transfer_to_agent", "write_todos", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "skill", "read_file", "execute", "wait_tool_execution", "get_tool_execution", "cancel_tool_execution", ...(req.alwaysVisibleTools ?? [])]);
|
||||
const loader = resources(systemPrompt + (searchEnabled ? "\nDiscover additional task tools with tool_search. Search results enable matching tools for subsequent calls." : ""));
|
||||
if (searchEnabled || workflow) {
|
||||
if (searchEnabled || workflow || codemodeEnabled) {
|
||||
const extensions = new DefaultResourceLoader({ cwd: scratch, agentDir: scratch, settingsManager: SettingsManager.inMemory(),
|
||||
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
||||
extensionFactories: [...(searchEnabled ? [createToolSearchExtension()] : []), ...(workflow ? [(pi: any) => {
|
||||
extensionFactories: [...(searchEnabled ? [createToolSearchExtension()] : []), ...(codemodeEnabled ? [createCodemodeExtension({
|
||||
mode: req.codemodeMode === "only" ? "only" : "on",
|
||||
...(req.codemodeInlineBudget && req.codemodeInlineBudget > 0 ? { inlineBudget: req.codemodeInlineBudget } : {}),
|
||||
// The host registers only its own channels; the built-in public catalog would expose unconfigured models.
|
||||
models: false,
|
||||
})] : []), ...(workflow ? [(pi: any) => {
|
||||
pi.on("agent_before_settle", (event: any) => {
|
||||
if (submitted || canceled || status !== "completed" || event.outcome !== "completed") return;
|
||||
if (wrappingUp && wrapupRemaining <= 0) { status = "yielded"; return; }
|
||||
|
|
@ -393,7 +402,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
: "The bounded step has not submitted its outcome. Preserve observed progress and call " + workflow.completionTool + " with evidence and remaining gaps. If blocked, report blocked; do not invent success.";
|
||||
return { entries: [...event.entries, { type: "custom_message", customType: "assessment-completion", display: false, content: promptText }], continue: true };
|
||||
});
|
||||
}] : [])], disabledBuiltinExtensions: ["mcp", "codemode"],
|
||||
}] : [])], disabledBuiltinExtensions: codemodeEnabled ? ["mcp"] : ["mcp", "codemode"],
|
||||
});
|
||||
await extensions.reload();
|
||||
loader.getExtensions = () => extensions.getExtensions();
|
||||
|
|
@ -404,7 +413,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
({ session } = await createAgentSession({ cwd: workingDir, agentDir: scratch, modelRuntime: runtime, model,
|
||||
thinkingLevel: (req.model.thinking || "off") as any, sessionManager: manager,
|
||||
settingsManager: SettingsManager.inMemory({ retry: { enabled: true, maxRetries: req.retryMax ?? Math.max(2, configs.length - 1), ...(req.retryMaxDelayMs ? { maxAgentDelayMs: req.retryMaxDelayMs } : {}) }, compaction: { enabled: true, reserveTokens: model.contextWindow - inputBudget, keepRecentTokens: Math.min(20000, Math.floor(inputBudget / 2)) } }),
|
||||
noTools: "builtin", tools: searchEnabled ? ["+tool_search"] : names, customTools: req.tools.map(def => ({ ...hostTool(def, imageInput, workflow ? (name, reply) => {
|
||||
noTools: "builtin", tools: searchEnabled ? (codemodeEnabled ? ["+tool_search", "+codemode"] : ["+tool_search"]) : (codemodeEnabled ? [...names, "codemode"] : names), customTools: req.tools.map(def => ({ ...hostTool(def, imageInput, workflow ? (name, reply) => {
|
||||
if (name === workflow?.completionTool) submitted = true;
|
||||
if (workflow && (name === workflow.checkpointTool || name === workflow.completionTool)) manager!.appendCustomEntry("assessment-checkpoint", { tool: name, content: reply.content.slice(0,16000), data: reply.structuredContent });
|
||||
} : undefined, workflow ? providerId => {
|
||||
|
|
@ -413,7 +422,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
} : undefined), exposure: def.exposure ?? (searchEnabled && !always.has(def.name) ? "deferred" : "direct") })),
|
||||
resourceLoader: loader,
|
||||
}));
|
||||
if (searchEnabled || workflow) await session.bindExtensions({});
|
||||
if (searchEnabled || workflow || codemodeEnabled) await session.bindExtensions({});
|
||||
session.agent.toolExecution = "sequential";
|
||||
let turns = 0;
|
||||
const previousFinish = session.agent.finishTurn;
|
||||
|
|
|
|||
|
|
@ -656,3 +656,74 @@ test('host tool images reach vision models natively and stay out of host events'
|
|||
assert.ok(!JSON.stringify(result.history).includes(image.data), 'exported history carried raw image bytes');
|
||||
}
|
||||
});
|
||||
|
||||
test("codemode batches host tools in one sandboxed turn and keeps large intermediates out of the model", { timeout: 60000 }, async t => {
|
||||
const bulkA = "A".repeat(120000);
|
||||
const bulkB = "B".repeat(90000);
|
||||
const dir = await mkdtemp(join(tmpdir(), "csai-pi-codemode-"));
|
||||
t.after(() => rm(dir, { recursive: true, force: true }));
|
||||
const fixture = await startFixture(t, (body, res, count) => {
|
||||
if (count === 1) {
|
||||
assert.deepEqual(body.tools.map(tool => tool.function.name), ["echo", "codemode"]);
|
||||
const code = [
|
||||
'const [a, b] = await Promise.all([tools.echo({ text: "alpha" }), tools.echo({ text: "beta" })]);',
|
||||
'store("cursor", { marker: "CURSOR-STATE-42", total: a.length + b.length });',
|
||||
'return "filtered:" + (a.length + b.length);',
|
||||
].join("\n");
|
||||
sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "cm-1", type: "function", function: { name: "codemode", arguments: JSON.stringify({ code }) } }] }, "tool_calls");
|
||||
} else if (count === 2) {
|
||||
const wire = JSON.stringify(body.messages);
|
||||
assert.ok(!wire.includes(bulkA) && !wire.includes(bulkB), "large intermediate tool output leaked into the model request");
|
||||
assert.ok(wire.includes("filtered:" + (bulkA.length + bulkB.length)), wire);
|
||||
sse(res, { role: "assistant", content: "batch verified" }, "stop");
|
||||
} else if (count === 3) {
|
||||
const code = 'const c = load("cursor"); return "loaded:" + c.marker + ":" + c.total;';
|
||||
sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "cm-2", type: "function", function: { name: "codemode", arguments: JSON.stringify({ code }) } }] }, "tool_calls");
|
||||
} else {
|
||||
const wire = JSON.stringify(body.messages);
|
||||
assert.ok(wire.includes("loaded:CURSOR-STATE-42:" + (bulkA.length + bulkB.length)), wire);
|
||||
assert.ok(!wire.includes(bulkA) && !wire.includes(bulkB), "resumed session leaked large intermediates");
|
||||
sse(res, { role: "assistant", content: "resume verified" }, "stop");
|
||||
}
|
||||
});
|
||||
const hostCalls = [];
|
||||
const host = (r, send) => {
|
||||
if (r.type === "tool_call") {
|
||||
hostCalls.push(r.call.name);
|
||||
assert.equal(r.call.name, "echo");
|
||||
send({ type: "tool_result", id: r.call.id, result: { content: r.call.arguments.text === "alpha" ? bulkA : bulkB } });
|
||||
}
|
||||
};
|
||||
const first = await invoke(t, { ...request(fixture.url, dir), codemode: true }, host);
|
||||
assert.equal(first.result.status, "completed", first.result.error);
|
||||
assert.equal(first.result.response, "batch verified");
|
||||
assert.deepEqual(hostCalls, ["echo", "echo"]);
|
||||
const second = await invoke(t, { ...request(fixture.url, dir), runId: "codemode-resume", message: "Continue from stored state", codemode: true }, host);
|
||||
assert.equal(second.result.status, "completed", second.result.error);
|
||||
assert.equal(second.result.response, "resume verified");
|
||||
assert.equal(fixture.requests.length, 4);
|
||||
assert.deepEqual(hostCalls, ["echo", "echo"]);
|
||||
});
|
||||
|
||||
test("codemode and tool search coexist without a tool list validation conflict", { timeout: 60000 }, async t => {
|
||||
const fixture = await startFixture(t, (body, res, count) => {
|
||||
const names = body.tools.map(tool => tool.function.name);
|
||||
if (count === 1) {
|
||||
assert.deepEqual(names, ["tool_search", "codemode"]);
|
||||
const code = 'const r = await tools.echo({ text: "deferred" }); return "search+" + r;';
|
||||
sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "cm-search", type: "function", function: { name: "codemode", arguments: JSON.stringify({ code }) } }] }, "tool_calls");
|
||||
} else {
|
||||
assert.ok(JSON.stringify(body.messages).includes("search+deferred"));
|
||||
sse(res, { role: "assistant", content: "coexistence verified" }, "stop");
|
||||
}
|
||||
});
|
||||
const req = request(fixture.url);
|
||||
req.tools.push(...Array.from({ length: 45 }, (_, i) => ({ name: "unrelated_" + i, description: "Unrelated operation", parameters: { type: "object", properties: {} } })));
|
||||
let hostCalls = 0;
|
||||
const { result } = await invoke(t, { ...req, toolSearch: true, codemode: true, codemodeMode: "on", codemodeInlineBudget: 2000 }, (r, send) => {
|
||||
if (r.type === "tool_call") { hostCalls++; assert.equal(r.call.name, "echo"); send({ type: "tool_result", id: r.call.id, result: { content: "deferred" } }); }
|
||||
});
|
||||
assert.equal(result.status, "completed", result.error);
|
||||
assert.equal(result.response, "coexistence verified");
|
||||
assert.equal(hostCalls, 1);
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in New Issue