diff --git a/internal/multiagent/pi_background.go b/internal/multiagent/pi_background.go new file mode 100644 index 00000000..82909207 --- /dev/null +++ b/internal/multiagent/pi_background.go @@ -0,0 +1,64 @@ +package multiagent + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "cyberstrike-ai/internal/agent" + "cyberstrike-ai/internal/agentruntime" + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/openai" + "github.com/google/uuid" + "go.uber.org/zap" +) + +func CompleteBackgroundStep(ctx context.Context, oa config.OpenAIConfig, msgs []agent.ChatMessage, tools []agent.Tool, maxTokens int, logger *zap.Logger) (*agent.ChatMessage, int, error) { + return CompleteBackgroundStepWithRuntime(ctx, config.AgentRuntimeConfig{}, oa, msgs, tools, maxTokens, logger) +} + +// Generate one proposal only. The caller owns tool execution, +// approvals, retries, budgets and transcript persistence; the SDK cannot execute here. +func CompleteBackgroundStepWithRuntime(ctx context.Context, runtime config.AgentRuntimeConfig, oa config.OpenAIConfig, msgs []agent.ChatMessage, tools []agent.Tool, maxTokens int, logger *zap.Logger) (*agent.ChatMessage, int, error) { + if err := runtime.Validate(); err != nil { + return nil, 0, err + } + + if maxTokens <= 0 { + return nil, 0, fmt.Errorf("background generation budget is exhausted") + } + if oa.MaxCompletionTokensEffective() > maxTokens { + oa.MaxCompletionTokens = maxTokens + } + var system []string + var history []agent.ChatMessage + for _, m := range msgs { + if m.Role == "system" { + system = append(system, m.Content) + } else { + history = append(history, m) + } + } + raw, err := piHistoryJSON(history) + if err != nil { + return nil, 0, err + } + defs := make([]agentruntime.Tool, 0, len(tools)) + for _, t := range tools { + defs = append(defs, agentruntime.Tool{Name: t.Function.Name, Description: t.Function.Description, Parameters: t.Function.Parameters}) + } + req := agentruntime.Request{RunID: uuid.NewString(), GenerateOnly: true, SystemPrompt: strings.Join(system, "\n\n"), History: raw, Model: piModelConfig(oa, nil, openai.SessionIDFromContext(ctx)), Tools: defs, MaxTurns: 1} + result, err := (agentruntime.Pi{NodePath: runtime.NodePath, WorkerPath: runtime.WorkerPath}).Run(ctx, req, nil, nil, nil) + if err != nil { + return nil, 0, err + } + var messages []agent.ChatMessage + if err = json.Unmarshal(result.History, &messages); err != nil { + return nil, 0, err + } + if len(messages) != 1 { + return nil, 0, fmt.Errorf("Pi returned no background proposal") + } + return &messages[0], result.TotalTokens, nil +} diff --git a/runtime/pi/src/protocol.ts b/runtime/pi/src/protocol.ts index 4fc1d7eb..95b030bd 100644 --- a/runtime/pi/src/protocol.ts +++ b/runtime/pi/src/protocol.ts @@ -1,5 +1,3 @@ -import { once } from "node:events"; - export const PROTOCOL_VERSION = 1; export const MAX_RECORD_BYTES = 32 * 1024 * 1024; @@ -29,8 +27,10 @@ let writes = Promise.resolve(); export function send(value: unknown): Promise { const line = JSON.stringify(value) + "\n"; if (Buffer.byteLength(line) > MAX_RECORD_BYTES) return Promise.reject(new Error("Protocol output exceeds limit")); - writes = writes.then(async () => { - if (!process.stdout.write(line)) await once(process.stdout, "drain"); - }); + // A true return value only means the stream accepted the data. The worker + // exits after its final record, so wait until the underlying write completes. + writes = writes.then(() => new Promise((resolve, reject) => { + process.stdout.write(line, error => error ? reject(error) : resolve()); + })); return writes; } diff --git a/runtime/pi/src/worker.ts b/runtime/pi/src/worker.ts index dfc919b7..35b01364 100644 --- a/runtime/pi/src/worker.ts +++ b/runtime/pi/src/worker.ts @@ -373,7 +373,16 @@ const reader = new RecordReader(); process.stdin.on("data", (chunk: Buffer) => { try { for (const record of reader.push(chunk)) void command(record).catch(fatal); } catch (e) { void fatal(e); } }); -process.stdin.on("end", () => { if (started) void command({ type: "cancel" }); else process.exit(0); }); +process.stdin.on("end", () => { + try { + reader.finish(); + } catch (error) { + void fatal(error); + return; + } + if (started) void command({ type: "cancel" }); + else process.exit(0); +}); async function fatal(error: unknown): Promise { await send({ type: "fatal", error: error instanceof Error ? error.message : String(error) }); session?.dispose(); diff --git a/runtime/pi/test/protocol.test.mjs b/runtime/pi/test/protocol.test.mjs new file mode 100644 index 00000000..aaf0c107 --- /dev/null +++ b/runtime/pi/test/protocol.test.mjs @@ -0,0 +1,65 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; + +test("the worker flushes a fatal record for a truncated input at EOF", { timeout: 10000 }, async t => { + const child = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "pipe"] }); + t.after(() => child.kill()); + const closed = once(child, "close"); + const chunks = []; + child.stdout.on("data", chunk => chunks.push(chunk)); + await once(child.stdout, "data"); + child.stdin.end('{"type":'); + const [code] = await closed; + const output = Buffer.concat(chunks).toString(); + assert.equal(code, 1); + assert.ok(output.endsWith("\n")); + const records = output.trimEnd().split("\n").map(line => JSON.parse(line)); + assert.deepEqual(records.at(-1), { type: "fatal", error: "Truncated protocol record" }); +}); + +test("send waits for the write callback even below the stream high water mark", async () => { + const child = spawn(process.execPath, ["--input-type=module", "-e", ` + import { send } from './dist/protocol.js'; + const pending = []; + process.stdout.write = (line, callback) => { pending.push({line, callback}); return true; }; + let settled = false; + const first = send({type:'event',text:'中文'.repeat(10000)}).then(() => { settled = true; }); + const second = send({type:'result',text:'last'}); + await new Promise(resolve => setImmediate(resolve)); + if (settled || pending.length !== 1 || typeof pending[0].callback !== 'function') process.exit(2); + pending[0].callback(); + await first; + await new Promise(resolve => setImmediate(resolve)); + if (pending.length !== 2 || !pending[1].line.endsWith('\\n')) process.exit(3); + pending[1].callback(); + await second; + process.exit(0); + `], { stdio: ["ignore", "pipe", "pipe"] }); + let stderr = ""; + child.stderr.on("data", chunk => stderr += chunk); + const [code] = await once(child, "close"); + assert.equal(code, 0, stderr || "send resolved before buffered output was flushed"); +}); + +test("a slow reader receives the complete final JSON before an immediate exit", async () => { + const child = spawn(process.execPath, ["--input-type=module", "-e", ` + import { send } from './dist/protocol.js'; + process.stdout._writableState.highWaterMark = 8 * 1024 * 1024; + await send({type:'result',text:'x'.repeat(4 * 1024 * 1024)}); + process.exit(0); + `], { stdio: ["ignore", "pipe", "pipe"] }); + let stderr = ""; + child.stderr.on("data", chunk => stderr += chunk); + const chunks = []; + child.stdout.on("data", chunk => chunks.push(chunk)); + child.stdout.pause(); + const resume = setTimeout(() => child.stdout.resume(), 100); + const [code] = await once(child, "close"); + clearTimeout(resume); + assert.equal(code, 0, stderr); + const body = Buffer.concat(chunks).toString(); + assert.ok(body.endsWith("\n"), "final JSON record was truncated"); + assert.equal(JSON.parse(body).text.length, 4 * 1024 * 1024); +});