@a5c-ai/babysitter-sdk 0.0.182 → 0.0.183-staging.2dca8387
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/dist/cli/commands/harnessInstall.d.ts +8 -0
- package/dist/cli/commands/harnessInstall.d.ts.map +1 -0
- package/dist/cli/commands/harnessInstall.js +94 -0
- package/dist/cli/commands/hookRun.d.ts +1 -1
- package/dist/cli/commands/hookRun.d.ts.map +1 -1
- package/dist/cli/commands/hookRun.js +16 -0
- package/dist/cli/commands/processLibrary.d.ts +16 -0
- package/dist/cli/commands/processLibrary.d.ts.map +1 -0
- package/dist/cli/commands/processLibrary.js +152 -0
- package/dist/cli/commands/sessionCreate.d.ts +27 -0
- package/dist/cli/commands/sessionCreate.d.ts.map +1 -0
- package/dist/cli/commands/sessionCreate.js +1288 -0
- package/dist/cli/commands/sessionCreatePrompts.d.ts +39 -0
- package/dist/cli/commands/sessionCreatePrompts.d.ts.map +1 -0
- package/dist/cli/commands/sessionCreatePrompts.js +183 -0
- package/dist/cli/commands/skill.d.ts +3 -3
- package/dist/cli/commands/skill.d.ts.map +1 -1
- package/dist/cli/commands/skill.js +63 -12
- package/dist/cli/commands/templates/process-generation-prompt.md +101 -0
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +260 -15
- package/dist/harness/claudeCode.d.ts.map +1 -1
- package/dist/harness/claudeCode.js +158 -21
- package/dist/harness/codex.d.ts +4 -3
- package/dist/harness/codex.d.ts.map +1 -1
- package/dist/harness/codex.js +310 -35
- package/dist/harness/customAdapter.d.ts +14 -0
- package/dist/harness/customAdapter.d.ts.map +1 -0
- package/dist/harness/customAdapter.js +108 -0
- package/dist/harness/discovery.d.ts +78 -0
- package/dist/harness/discovery.d.ts.map +1 -0
- package/dist/harness/discovery.js +301 -0
- package/dist/harness/geminiCli.d.ts.map +1 -1
- package/dist/harness/geminiCli.js +33 -0
- package/dist/harness/index.d.ts +7 -1
- package/dist/harness/index.d.ts.map +1 -1
- package/dist/harness/index.js +19 -1
- package/dist/harness/installSupport.d.ts +34 -0
- package/dist/harness/installSupport.d.ts.map +1 -0
- package/dist/harness/installSupport.js +194 -0
- package/dist/harness/invoker.d.ts +47 -0
- package/dist/harness/invoker.d.ts.map +1 -0
- package/dist/harness/invoker.js +143 -0
- package/dist/harness/ohMyPi.d.ts +17 -0
- package/dist/harness/ohMyPi.d.ts.map +1 -0
- package/dist/harness/ohMyPi.js +46 -0
- package/dist/harness/pi.d.ts +5 -1
- package/dist/harness/pi.d.ts.map +1 -1
- package/dist/harness/pi.js +64 -0
- package/dist/harness/piSecureSandbox.d.ts +21 -0
- package/dist/harness/piSecureSandbox.d.ts.map +1 -0
- package/dist/harness/piSecureSandbox.js +373 -0
- package/dist/harness/piWrapper.d.ts +87 -0
- package/dist/harness/piWrapper.d.ts.map +1 -0
- package/dist/harness/piWrapper.js +479 -0
- package/dist/harness/registry.d.ts +1 -1
- package/dist/harness/registry.d.ts.map +1 -1
- package/dist/harness/registry.js +6 -3
- package/dist/harness/types.d.ts +168 -0
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js +18 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/interaction/askUserQuestion.d.ts +25 -0
- package/dist/interaction/askUserQuestion.d.ts.map +1 -0
- package/dist/interaction/askUserQuestion.js +163 -0
- package/dist/interaction/index.d.ts +2 -0
- package/dist/interaction/index.d.ts.map +1 -0
- package/dist/interaction/index.js +17 -0
- package/dist/processLibrary/active.d.ts +65 -0
- package/dist/processLibrary/active.d.ts.map +1 -0
- package/dist/processLibrary/active.js +205 -0
- package/dist/tasks/serializer.d.ts.map +1 -1
- package/dist/tasks/serializer.js +2 -0
- package/package.json +5 -2
|
@@ -0,0 +1,1288 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* session:create command handler.
|
|
4
|
+
*
|
|
5
|
+
* Drives a full babysitter session lifecycle through two agentic phases:
|
|
6
|
+
* Phase 1 - Unbound interview / intent / process-definition
|
|
7
|
+
* Phase 2 - Bound orchestration loop with hook-style continuation semantics
|
|
8
|
+
*
|
|
9
|
+
* Both phases are driven through a Pi agent session and LLM-callable tools.
|
|
10
|
+
* Interactive user input is exposed through an AskUserQuestion tool instead of
|
|
11
|
+
* direct imperative prompts inside the host loop.
|
|
12
|
+
*/
|
|
13
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
14
|
+
if (k2 === undefined) k2 = k;
|
|
15
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
16
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
17
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
18
|
+
}
|
|
19
|
+
Object.defineProperty(o, k2, desc);
|
|
20
|
+
}) : (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
o[k2] = m[k];
|
|
23
|
+
}));
|
|
24
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
25
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
26
|
+
}) : function(o, v) {
|
|
27
|
+
o["default"] = v;
|
|
28
|
+
});
|
|
29
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
30
|
+
var ownKeys = function(o) {
|
|
31
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
32
|
+
var ar = [];
|
|
33
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
34
|
+
return ar;
|
|
35
|
+
};
|
|
36
|
+
return ownKeys(o);
|
|
37
|
+
};
|
|
38
|
+
return function (mod) {
|
|
39
|
+
if (mod && mod.__esModule) return mod;
|
|
40
|
+
var result = {};
|
|
41
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
42
|
+
__setModuleDefault(result, mod);
|
|
43
|
+
return result;
|
|
44
|
+
};
|
|
45
|
+
})();
|
|
46
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
47
|
+
exports.selectHarness = selectHarness;
|
|
48
|
+
exports.handleSessionCreate = handleSessionCreate;
|
|
49
|
+
const path = __importStar(require("node:path"));
|
|
50
|
+
const readline = __importStar(require("node:readline"));
|
|
51
|
+
const node_child_process_1 = require("node:child_process");
|
|
52
|
+
const node_fs_1 = require("node:fs");
|
|
53
|
+
const node_url_1 = require("node:url");
|
|
54
|
+
const typebox_1 = require("@sinclair/typebox");
|
|
55
|
+
const discovery_1 = require("../../harness/discovery");
|
|
56
|
+
const invoker_1 = require("../../harness/invoker");
|
|
57
|
+
const piWrapper_1 = require("../../harness/piWrapper");
|
|
58
|
+
const config_loader_1 = require("../../compression/config-loader");
|
|
59
|
+
const density_filter_1 = require("../../compression/density-filter");
|
|
60
|
+
const harness_1 = require("../../harness");
|
|
61
|
+
const interaction_1 = require("../../interaction");
|
|
62
|
+
const createRun_1 = require("../../runtime/createRun");
|
|
63
|
+
const orchestrateIteration_1 = require("../../runtime/orchestrateIteration");
|
|
64
|
+
const commitEffectResult_1 = require("../../runtime/commitEffectResult");
|
|
65
|
+
const exceptions_1 = require("../../runtime/exceptions");
|
|
66
|
+
const sessionCreatePrompts_1 = require("./sessionCreatePrompts");
|
|
67
|
+
const DIM = "\x1b[2m";
|
|
68
|
+
const RESET = "\x1b[0m";
|
|
69
|
+
const BOLD = "\x1b[1m";
|
|
70
|
+
const CYAN = "\x1b[36m";
|
|
71
|
+
const GREEN = "\x1b[32m";
|
|
72
|
+
const YELLOW = "\x1b[33m";
|
|
73
|
+
const RED = "\x1b[31m";
|
|
74
|
+
const MAGENTA = "\x1b[35m";
|
|
75
|
+
function loadSessionCompressionConfig(workspace) {
|
|
76
|
+
try {
|
|
77
|
+
return (0, config_loader_1.loadCompressionConfig)(workspace ?? process.cwd());
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function compressInternalHarnessPrompt(text, compressionConfig, taskKind = "agent") {
|
|
84
|
+
if (!compressionConfig?.enabled || !compressionConfig.layers.sdkContextHook.enabled) {
|
|
85
|
+
return text;
|
|
86
|
+
}
|
|
87
|
+
const layer = compressionConfig.layers.sdkContextHook;
|
|
88
|
+
if ((0, density_filter_1.estimateTokens)(text) <= layer.minCompressionTokens) {
|
|
89
|
+
return text;
|
|
90
|
+
}
|
|
91
|
+
const targetReduction = layer.perTaskKind?.[taskKind] ?? layer.targetReduction;
|
|
92
|
+
return (0, density_filter_1.densityFilterText)(text, targetReduction);
|
|
93
|
+
}
|
|
94
|
+
function buildPromptContext(args) {
|
|
95
|
+
const envNames = [
|
|
96
|
+
"CI",
|
|
97
|
+
"BABYSITTER_COMPRESSION_ENABLED",
|
|
98
|
+
"BABYSITTER_PI_SANDBOX_IMAGE",
|
|
99
|
+
"AZURE_OPENAI_API_KEY",
|
|
100
|
+
"AZURE_OPENAI_PROJECT_NAME",
|
|
101
|
+
"AZURE_OPENAI_DEPLOYMENT",
|
|
102
|
+
"OPENAI_API_KEY",
|
|
103
|
+
"ANTHROPIC_API_KEY",
|
|
104
|
+
];
|
|
105
|
+
return {
|
|
106
|
+
platform: process.platform,
|
|
107
|
+
arch: process.arch,
|
|
108
|
+
nodeVersion: process.version,
|
|
109
|
+
cwd: process.cwd(),
|
|
110
|
+
workspace: path.resolve(args.workspace ?? process.cwd()),
|
|
111
|
+
selectedHarnessName: args.selectedHarnessName,
|
|
112
|
+
discoveredHarnesses: args.discovered,
|
|
113
|
+
compressionEnabled: Boolean(args.compressionConfig?.enabled &&
|
|
114
|
+
args.compressionConfig.layers.sdkContextHook.enabled),
|
|
115
|
+
secureSandboxImage: process.env.BABYSITTER_PI_SANDBOX_IMAGE || "node:22-bookworm",
|
|
116
|
+
piDefaultBashSandbox: "local",
|
|
117
|
+
piIsolationDefault: false,
|
|
118
|
+
envFlags: envNames.map((name) => ({
|
|
119
|
+
name,
|
|
120
|
+
value: process.env[name]
|
|
121
|
+
? (name.endsWith("_API_KEY") ? "set" : process.env[name])
|
|
122
|
+
: "unset",
|
|
123
|
+
})),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const HARNESS_PRIORITY = [
|
|
127
|
+
"pi",
|
|
128
|
+
"oh-my-pi",
|
|
129
|
+
"claude-code",
|
|
130
|
+
"codex",
|
|
131
|
+
"gemini-cli",
|
|
132
|
+
"opencode",
|
|
133
|
+
];
|
|
134
|
+
function selectHarness(discovered, preferred) {
|
|
135
|
+
if (preferred) {
|
|
136
|
+
const match = discovered.find((h) => h.name === preferred && h.installed);
|
|
137
|
+
if (match)
|
|
138
|
+
return match;
|
|
139
|
+
}
|
|
140
|
+
for (const name of HARNESS_PRIORITY) {
|
|
141
|
+
const match = discovered.find((h) => h.name === name && h.installed);
|
|
142
|
+
if (match)
|
|
143
|
+
return match;
|
|
144
|
+
}
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
function createReadlineInterface() {
|
|
148
|
+
return readline.createInterface({
|
|
149
|
+
input: process.stdin,
|
|
150
|
+
output: process.stderr,
|
|
151
|
+
terminal: true,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
const PROCESS_GENERATION_TEMPLATE_PATH = path.join(__dirname, "templates", "process-generation-prompt.md");
|
|
155
|
+
let cachedTemplate;
|
|
156
|
+
function loadProcessGenerationTemplate() {
|
|
157
|
+
if (cachedTemplate === undefined) {
|
|
158
|
+
cachedTemplate = (0, node_fs_1.readFileSync)(PROCESS_GENERATION_TEMPLATE_PATH, "utf8");
|
|
159
|
+
}
|
|
160
|
+
return cachedTemplate;
|
|
161
|
+
}
|
|
162
|
+
function buildMetaPrompt(userPrompt, workDir) {
|
|
163
|
+
let template = loadProcessGenerationTemplate();
|
|
164
|
+
template = template.replace("{{USER_PROMPT}}", userPrompt);
|
|
165
|
+
template = template.replace("{{OUTPUT_PATH}}", path.join(workDir, "generated-process.js"));
|
|
166
|
+
template = template.replace("{{INTERVIEW_CONTEXT}}", "");
|
|
167
|
+
return template;
|
|
168
|
+
}
|
|
169
|
+
const POLL_INTERVAL_MS = 1_000;
|
|
170
|
+
const POLL_TIMEOUT_MS = 60_000;
|
|
171
|
+
async function waitForProcessFile(filePath, timeoutMs = POLL_TIMEOUT_MS) {
|
|
172
|
+
const deadline = Date.now() + timeoutMs;
|
|
173
|
+
while (Date.now() < deadline) {
|
|
174
|
+
try {
|
|
175
|
+
await node_fs_1.promises.access(filePath);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
// keep polling
|
|
180
|
+
}
|
|
181
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
182
|
+
}
|
|
183
|
+
throw new exceptions_1.BabysitterRuntimeError("ProcessFileTimeoutError", `Process file was not created within ${timeoutMs / 1_000}s: ${filePath}`, {
|
|
184
|
+
category: exceptions_1.ErrorCategory.External,
|
|
185
|
+
nextSteps: [
|
|
186
|
+
"Check harness output for errors",
|
|
187
|
+
"Ensure the harness can write to the workspace directory",
|
|
188
|
+
],
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const dynamicImportModule = (() => {
|
|
192
|
+
if (process.env.VITEST) {
|
|
193
|
+
return (specifier) => Promise.resolve(`${specifier}`).then(s => __importStar(require(s)));
|
|
194
|
+
}
|
|
195
|
+
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
|
196
|
+
return new Function("specifier", "return import(specifier);");
|
|
197
|
+
})();
|
|
198
|
+
async function ensureSdkResolvable(workspaceDir) {
|
|
199
|
+
const sdkPkg = path.resolve(__dirname, "..", "..", "..");
|
|
200
|
+
const targetNodeModules = path.join(workspaceDir, "node_modules");
|
|
201
|
+
const targetSdkDir = path.join(targetNodeModules, "@a5c-ai", "babysitter-sdk");
|
|
202
|
+
try {
|
|
203
|
+
await node_fs_1.promises.access(targetSdkDir);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
// create below
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
await node_fs_1.promises.mkdir(path.join(targetNodeModules, "@a5c-ai"), { recursive: true });
|
|
211
|
+
const linkType = process.platform === "win32" ? "junction" : "dir";
|
|
212
|
+
await node_fs_1.promises.symlink(sdkPkg, targetSdkDir, linkType);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
// best effort
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async function validateProcessExport(filePath) {
|
|
219
|
+
await ensureSdkResolvable(path.dirname(path.resolve(filePath)));
|
|
220
|
+
const moduleUrl = (0, node_url_1.pathToFileURL)(path.resolve(filePath)).href;
|
|
221
|
+
const mod = await dynamicImportModule(moduleUrl);
|
|
222
|
+
const fn = mod.process ?? mod.default;
|
|
223
|
+
if (typeof fn !== "function") {
|
|
224
|
+
throw new exceptions_1.BabysitterRuntimeError("InvalidProcessExportError", `Process file at ${filePath} does not export a function named 'process' or 'default'`, {
|
|
225
|
+
category: exceptions_1.ErrorCategory.Validation,
|
|
226
|
+
nextSteps: [
|
|
227
|
+
"Ensure the file exports: async function process(inputs, ctx) { ... }",
|
|
228
|
+
],
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function execShellEffect(command, args, cwd) {
|
|
233
|
+
return new Promise((resolve) => {
|
|
234
|
+
(0, node_child_process_1.execFile)(command, args, {
|
|
235
|
+
cwd,
|
|
236
|
+
timeout: 300_000,
|
|
237
|
+
windowsHide: true,
|
|
238
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
239
|
+
}, (error, stdout, stderr) => {
|
|
240
|
+
let exitCode = 0;
|
|
241
|
+
if (error) {
|
|
242
|
+
const execError = error;
|
|
243
|
+
exitCode = typeof execError.status === "number" ? execError.status : 1;
|
|
244
|
+
}
|
|
245
|
+
resolve({
|
|
246
|
+
stdout: String(stdout),
|
|
247
|
+
stderr: String(stderr),
|
|
248
|
+
exitCode,
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
function buildAgentPrompt(taskDef) {
|
|
254
|
+
const agent = taskDef.agent;
|
|
255
|
+
if (!agent)
|
|
256
|
+
return taskDef.title ?? "Execute task";
|
|
257
|
+
const prompt = agent.prompt;
|
|
258
|
+
if (!prompt)
|
|
259
|
+
return taskDef.title ?? "Execute task";
|
|
260
|
+
const parts = [];
|
|
261
|
+
parts.push("You are an autonomous agent. PERFORM the task below using your available tools.", "Do not just describe what you would do. Execute the work and then summarize what you changed.", "");
|
|
262
|
+
if (typeof prompt.role === "string")
|
|
263
|
+
parts.push(`Role: ${prompt.role}`);
|
|
264
|
+
if (typeof prompt.task === "string")
|
|
265
|
+
parts.push(`\nTask:\n${prompt.task}`);
|
|
266
|
+
if (prompt.context)
|
|
267
|
+
parts.push(`\nContext:\n${JSON.stringify(prompt.context, null, 2)}`);
|
|
268
|
+
if (Array.isArray(prompt.instructions)) {
|
|
269
|
+
parts.push(`\nInstructions:\n${prompt.instructions.map((item, index) => `${index + 1}. ${item}`).join("\n")}`);
|
|
270
|
+
}
|
|
271
|
+
if (typeof prompt.outputFormat === "string")
|
|
272
|
+
parts.push(`\nOutput format: ${prompt.outputFormat}`);
|
|
273
|
+
return parts.join("\n");
|
|
274
|
+
}
|
|
275
|
+
function shellQuoteArg(value) {
|
|
276
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
277
|
+
}
|
|
278
|
+
function resolveTaskHarness(action, defaultHarness, discovered) {
|
|
279
|
+
const meta = action.taskDef?.metadata;
|
|
280
|
+
if (typeof meta?.harness === "string") {
|
|
281
|
+
const match = discovered.find((h) => h.name === meta.harness && h.installed);
|
|
282
|
+
if (match)
|
|
283
|
+
return match.name;
|
|
284
|
+
}
|
|
285
|
+
const agent = action.taskDef?.agent;
|
|
286
|
+
if (typeof agent?.name === "string") {
|
|
287
|
+
const match = discovered.find((h) => h.name === agent.name && h.installed);
|
|
288
|
+
if (match)
|
|
289
|
+
return match.name;
|
|
290
|
+
}
|
|
291
|
+
return defaultHarness;
|
|
292
|
+
}
|
|
293
|
+
function isPiHarness(harnessName) {
|
|
294
|
+
return harnessName === "pi" || harnessName === "oh-my-pi";
|
|
295
|
+
}
|
|
296
|
+
function readBooleanMetadata(metadata, key) {
|
|
297
|
+
const value = metadata?.[key];
|
|
298
|
+
if (typeof value === "boolean") {
|
|
299
|
+
return value;
|
|
300
|
+
}
|
|
301
|
+
if (value === "true") {
|
|
302
|
+
return true;
|
|
303
|
+
}
|
|
304
|
+
if (value === "false") {
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
function readBashSandboxMetadata(metadata) {
|
|
310
|
+
const value = metadata?.bashSandbox;
|
|
311
|
+
return value === "auto" || value === "secure" || value === "local"
|
|
312
|
+
? value
|
|
313
|
+
: undefined;
|
|
314
|
+
}
|
|
315
|
+
function buildPiWorkerSessionOptions(args) {
|
|
316
|
+
const metadata = args.action.taskDef?.metadata;
|
|
317
|
+
const isolated = readBooleanMetadata(metadata, "isolated");
|
|
318
|
+
const enableCompaction = readBooleanMetadata(metadata, "enableCompaction");
|
|
319
|
+
const bashSandbox = readBashSandboxMetadata(metadata);
|
|
320
|
+
return {
|
|
321
|
+
workspace: args.workspace,
|
|
322
|
+
model: args.model,
|
|
323
|
+
toolsMode: "coding",
|
|
324
|
+
ephemeral: true,
|
|
325
|
+
...(isolated !== undefined ? { isolated } : {}),
|
|
326
|
+
...(enableCompaction !== undefined ? { enableCompaction } : {}),
|
|
327
|
+
...(bashSandbox ? { bashSandbox } : {}),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
async function resolveEffect(action, harnessName, options, piSession, discovered, rl, json) {
|
|
331
|
+
const kind = action.kind;
|
|
332
|
+
if (kind === "node" || kind === "orchestrator_task") {
|
|
333
|
+
const meta = action.taskDef?.metadata;
|
|
334
|
+
const metaPrompt = typeof meta?.prompt === "string" ? meta.prompt : undefined;
|
|
335
|
+
const prompt = metaPrompt ??
|
|
336
|
+
action.taskDef?.title ??
|
|
337
|
+
`Execute task ${action.taskId ?? action.effectId}`;
|
|
338
|
+
const effectivePrompt = compressInternalHarnessPrompt(prompt, options.compressionConfig, "skill");
|
|
339
|
+
const taskHarness = discovered
|
|
340
|
+
? resolveTaskHarness(action, harnessName, discovered)
|
|
341
|
+
: harnessName;
|
|
342
|
+
if ((taskHarness === "pi" || taskHarness === "oh-my-pi") && piSession) {
|
|
343
|
+
const piResult = await piSession.prompt(effectivePrompt);
|
|
344
|
+
return {
|
|
345
|
+
status: piResult.success ? "ok" : "error",
|
|
346
|
+
value: piResult.success ? piResult.output : undefined,
|
|
347
|
+
error: piResult.success ? undefined : new Error(piResult.output),
|
|
348
|
+
stdout: piResult.output,
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
const result = await (0, invoker_1.invokeHarness)(taskHarness, {
|
|
352
|
+
prompt: effectivePrompt,
|
|
353
|
+
workspace: options.workspace,
|
|
354
|
+
model: options.model,
|
|
355
|
+
});
|
|
356
|
+
return {
|
|
357
|
+
status: result.success ? "ok" : "error",
|
|
358
|
+
value: result.success ? result.output : undefined,
|
|
359
|
+
error: result.success ? undefined : new Error(result.output),
|
|
360
|
+
stdout: result.output,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
if (kind === "shell") {
|
|
364
|
+
const shellMeta = action.taskDef?.metadata;
|
|
365
|
+
const command = typeof shellMeta?.command === "string" ? shellMeta.command : "echo";
|
|
366
|
+
const shellArgs = Array.isArray(shellMeta?.args)
|
|
367
|
+
? shellMeta.args.filter((arg) => typeof arg === "string")
|
|
368
|
+
: [];
|
|
369
|
+
const cwd = typeof shellMeta?.cwd === "string" ? shellMeta.cwd : options.workspace;
|
|
370
|
+
if (piSession) {
|
|
371
|
+
const bashCommand = [command, ...shellArgs.map(shellQuoteArg)].join(" ");
|
|
372
|
+
const bashResult = await piSession.executeBash(bashCommand);
|
|
373
|
+
return {
|
|
374
|
+
status: bashResult.exitCode === 0 ? "ok" : "error",
|
|
375
|
+
value: bashResult.exitCode === 0 ? bashResult.output : undefined,
|
|
376
|
+
error: bashResult.exitCode === 0
|
|
377
|
+
? undefined
|
|
378
|
+
: new Error(`Shell command exited with code ${bashResult.exitCode ?? "null"}: ${bashResult.output}`),
|
|
379
|
+
stdout: bashResult.output,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
const shellResult = await execShellEffect(command, shellArgs, cwd);
|
|
383
|
+
return {
|
|
384
|
+
status: shellResult.exitCode === 0 ? "ok" : "error",
|
|
385
|
+
value: shellResult.exitCode === 0 ? shellResult.stdout : undefined,
|
|
386
|
+
error: shellResult.exitCode === 0
|
|
387
|
+
? undefined
|
|
388
|
+
: new Error(`Shell command exited with code ${shellResult.exitCode}: ${shellResult.stderr}`),
|
|
389
|
+
stdout: shellResult.stdout,
|
|
390
|
+
stderr: shellResult.stderr,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
if (kind === "breakpoint") {
|
|
394
|
+
const bpQuestion = action.taskDef?.question ??
|
|
395
|
+
action.taskDef?.title ??
|
|
396
|
+
"Breakpoint reached. Continue?";
|
|
397
|
+
const approvalPrompt = (0, interaction_1.createApprovalAskUserQuestion)(bpQuestion);
|
|
398
|
+
const approvalKey = approvalPrompt.questions[0]?.header ?? "Decision";
|
|
399
|
+
if (options.interactive && rl) {
|
|
400
|
+
if (!json) {
|
|
401
|
+
process.stderr.write(`\n${YELLOW}${BOLD}BREAKPOINT${RESET} ${bpQuestion}\n`);
|
|
402
|
+
}
|
|
403
|
+
const response = await (0, interaction_1.promptAskUserQuestionWithReadline)(rl, approvalPrompt);
|
|
404
|
+
const option = response.answers[approvalKey] ?? "Reject";
|
|
405
|
+
return {
|
|
406
|
+
status: "ok",
|
|
407
|
+
value: {
|
|
408
|
+
approved: option === "Approve",
|
|
409
|
+
option,
|
|
410
|
+
askUserQuestion: response,
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
const response = (0, interaction_1.createAskUserQuestionResponse)(approvalPrompt, {
|
|
415
|
+
[approvalKey]: "Approve",
|
|
416
|
+
});
|
|
417
|
+
return {
|
|
418
|
+
status: "ok",
|
|
419
|
+
value: {
|
|
420
|
+
approved: true,
|
|
421
|
+
option: "Approve",
|
|
422
|
+
askUserQuestion: response,
|
|
423
|
+
},
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
if (kind === "sleep") {
|
|
427
|
+
const targetMs = action.taskDef?.sleep?.targetEpochMs;
|
|
428
|
+
if (typeof targetMs === "number") {
|
|
429
|
+
const delay = Math.max(0, targetMs - Date.now());
|
|
430
|
+
if (delay > 0) {
|
|
431
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return { status: "ok", value: { sleptUntil: new Date().toISOString() } };
|
|
435
|
+
}
|
|
436
|
+
if (kind === "agent") {
|
|
437
|
+
const textPrompt = compressInternalHarnessPrompt(buildAgentPrompt(action.taskDef), options.compressionConfig, "agent");
|
|
438
|
+
const taskHarness = discovered
|
|
439
|
+
? resolveTaskHarness(action, harnessName, discovered)
|
|
440
|
+
: harnessName;
|
|
441
|
+
const explicitCliRequested = taskHarness !== harnessName && taskHarness !== "pi" && taskHarness !== "oh-my-pi";
|
|
442
|
+
if (explicitCliRequested) {
|
|
443
|
+
const result = await (0, invoker_1.invokeHarness)(taskHarness, {
|
|
444
|
+
prompt: textPrompt,
|
|
445
|
+
workspace: options.workspace,
|
|
446
|
+
model: options.model,
|
|
447
|
+
});
|
|
448
|
+
return {
|
|
449
|
+
status: result.success ? "ok" : "error",
|
|
450
|
+
value: result.success ? result.output : undefined,
|
|
451
|
+
error: result.success ? undefined : new Error(result.output),
|
|
452
|
+
stdout: result.output,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
if (piSession) {
|
|
456
|
+
const piResult = await piSession.prompt(textPrompt);
|
|
457
|
+
return {
|
|
458
|
+
status: piResult.success ? "ok" : "error",
|
|
459
|
+
value: piResult.success ? piResult.output : undefined,
|
|
460
|
+
error: piResult.success ? undefined : new Error(piResult.output),
|
|
461
|
+
stdout: piResult.output,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
const result = await (0, invoker_1.invokeHarness)(taskHarness, {
|
|
465
|
+
prompt: textPrompt,
|
|
466
|
+
workspace: options.workspace,
|
|
467
|
+
model: options.model,
|
|
468
|
+
});
|
|
469
|
+
return {
|
|
470
|
+
status: result.success ? "ok" : "error",
|
|
471
|
+
value: result.success ? result.output : undefined,
|
|
472
|
+
error: result.success ? undefined : new Error(result.output),
|
|
473
|
+
stdout: result.output,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
const fallbackPrompt = action.taskDef?.title ?? `Handle effect ${action.effectId} (kind: ${kind})`;
|
|
477
|
+
const effectiveFallbackPrompt = compressInternalHarnessPrompt(fallbackPrompt, options.compressionConfig, "skill");
|
|
478
|
+
const result = await (0, invoker_1.invokeHarness)(harnessName, {
|
|
479
|
+
prompt: effectiveFallbackPrompt,
|
|
480
|
+
workspace: options.workspace,
|
|
481
|
+
model: options.model,
|
|
482
|
+
});
|
|
483
|
+
return {
|
|
484
|
+
status: result.success ? "ok" : "error",
|
|
485
|
+
value: result.success ? result.output : undefined,
|
|
486
|
+
error: result.success ? undefined : new Error(result.output),
|
|
487
|
+
stdout: result.output,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
const ASK_OPTION_SCHEMA = typebox_1.Type.Object({
|
|
491
|
+
label: typebox_1.Type.String(),
|
|
492
|
+
description: typebox_1.Type.Optional(typebox_1.Type.String()),
|
|
493
|
+
preview: typebox_1.Type.Optional(typebox_1.Type.String()),
|
|
494
|
+
});
|
|
495
|
+
const ASK_QUESTION_SCHEMA = typebox_1.Type.Object({
|
|
496
|
+
question: typebox_1.Type.String(),
|
|
497
|
+
header: typebox_1.Type.Optional(typebox_1.Type.String()),
|
|
498
|
+
options: typebox_1.Type.Optional(typebox_1.Type.Array(ASK_OPTION_SCHEMA)),
|
|
499
|
+
multiSelect: typebox_1.Type.Optional(typebox_1.Type.Boolean()),
|
|
500
|
+
allowOther: typebox_1.Type.Optional(typebox_1.Type.Boolean()),
|
|
501
|
+
required: typebox_1.Type.Optional(typebox_1.Type.Boolean()),
|
|
502
|
+
});
|
|
503
|
+
const ASK_USER_QUESTION_SCHEMA = typebox_1.Type.Object({
|
|
504
|
+
questions: typebox_1.Type.Array(ASK_QUESTION_SCHEMA, { minItems: 1, maxItems: 4 }),
|
|
505
|
+
});
|
|
506
|
+
function formatToolResult(data, message) {
|
|
507
|
+
if (typeof data === "string") {
|
|
508
|
+
return { content: message ? `${message}\n${data}` : data, details: data };
|
|
509
|
+
}
|
|
510
|
+
const content = message
|
|
511
|
+
? `${message}\n${JSON.stringify(data, null, 2)}`
|
|
512
|
+
: JSON.stringify(data, null, 2);
|
|
513
|
+
return { content, details: data };
|
|
514
|
+
}
|
|
515
|
+
function isApprovalAskRequest(request) {
|
|
516
|
+
const question = request.questions[0];
|
|
517
|
+
if (!question || request.questions.length !== 1 || !question.options) {
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
const labels = question.options.map((option) => option.label);
|
|
521
|
+
return labels.length === 2 &&
|
|
522
|
+
labels[0] === "Approve" &&
|
|
523
|
+
labels[1] === "Reject" &&
|
|
524
|
+
question.allowOther === false;
|
|
525
|
+
}
|
|
526
|
+
async function askUserQuestionViaTool(request, interactive, rl) {
|
|
527
|
+
(0, interaction_1.validateAskUserQuestionRequest)(request);
|
|
528
|
+
if (interactive && rl) {
|
|
529
|
+
return (0, interaction_1.promptAskUserQuestionWithReadline)(rl, request);
|
|
530
|
+
}
|
|
531
|
+
const answers = {};
|
|
532
|
+
for (const [index, question] of request.questions.entries()) {
|
|
533
|
+
const key = question.header?.trim() || `Question ${index + 1}`;
|
|
534
|
+
answers[key] = "";
|
|
535
|
+
}
|
|
536
|
+
if (isApprovalAskRequest(request)) {
|
|
537
|
+
const key = request.questions[0]?.header?.trim() || "Decision";
|
|
538
|
+
answers[key] = "Approve";
|
|
539
|
+
}
|
|
540
|
+
return (0, interaction_1.createAskUserQuestionResponse)(request, answers);
|
|
541
|
+
}
|
|
542
|
+
function emitProgress(payload, json, verbose) {
|
|
543
|
+
if (json) {
|
|
544
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
switch (payload.phase) {
|
|
548
|
+
case "1":
|
|
549
|
+
if (payload.status === "skipped") {
|
|
550
|
+
process.stderr.write(`${DIM}Phase 1 skipped (--process provided)${RESET}\n`);
|
|
551
|
+
}
|
|
552
|
+
else if (payload.status === "started") {
|
|
553
|
+
process.stderr.write(`\n${BOLD}Phase 1${RESET} ${DIM}Interview / process definition via ${payload.harness}...${RESET}\n`);
|
|
554
|
+
}
|
|
555
|
+
else if (payload.status === "completed") {
|
|
556
|
+
process.stderr.write(`${GREEN}Phase 1 complete${RESET} ${DIM}${payload.processPath}${RESET}\n`);
|
|
557
|
+
}
|
|
558
|
+
else if (payload.status === "failed") {
|
|
559
|
+
process.stderr.write(`${RED}Phase 1 failed:${RESET} ${payload.error}\n`);
|
|
560
|
+
}
|
|
561
|
+
else if (payload.status === "interview") {
|
|
562
|
+
process.stderr.write(`${DIM}Interview answers: ${payload.answer}${RESET}\n`);
|
|
563
|
+
}
|
|
564
|
+
break;
|
|
565
|
+
case "2":
|
|
566
|
+
if (payload.status === "started") {
|
|
567
|
+
process.stderr.write(`\n${BOLD}Phase 2${RESET} ${DIM}Bound orchestration loop${RESET}\n`);
|
|
568
|
+
}
|
|
569
|
+
else if (payload.status === "run-created") {
|
|
570
|
+
process.stderr.write(`${GREEN}Run created${RESET} runId=${CYAN}${payload.runId}${RESET}\n`);
|
|
571
|
+
if (verbose)
|
|
572
|
+
process.stderr.write(` ${DIM}runDir: ${payload.runDir}${RESET}\n`);
|
|
573
|
+
}
|
|
574
|
+
else if (payload.status === "bound") {
|
|
575
|
+
if (payload.error) {
|
|
576
|
+
process.stderr.write(`${YELLOW}Session binding warning:${RESET} ${payload.error}\n`);
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
process.stderr.write(`${DIM}session bound via ${payload.harness}: ${payload.sessionId}${RESET}\n`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
else if (payload.status === "iteration") {
|
|
583
|
+
process.stderr.write(`\n${DIM}-- iteration ${payload.iteration} --${RESET} status=${payload.runStatus} pending=${payload.pendingEffects}\n`);
|
|
584
|
+
}
|
|
585
|
+
else if (payload.status === "effect") {
|
|
586
|
+
const icon = payload.effectStatus === "ok" ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;
|
|
587
|
+
process.stderr.write(` ${icon} ${MAGENTA}${payload.effectKind}${RESET} ${payload.effectTitle ?? payload.effectId}${payload.effectStatus === "error" ? ` ${RED}${payload.error}${RESET}` : ""}\n`);
|
|
588
|
+
}
|
|
589
|
+
else if (payload.status === "completed") {
|
|
590
|
+
process.stderr.write(`\n${GREEN}${BOLD}Run completed${RESET} ${DIM}(${payload.iteration} iterations)${RESET}\n`);
|
|
591
|
+
}
|
|
592
|
+
else if (payload.status === "failed") {
|
|
593
|
+
process.stderr.write(`\n${RED}${BOLD}Run failed:${RESET} ${payload.error}\n`);
|
|
594
|
+
}
|
|
595
|
+
break;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
function writeVerboseProcessDefinitionRecovery(json) {
|
|
599
|
+
if (!json) {
|
|
600
|
+
process.stderr.write(`${DIM}Phase 1 recovery: the agent did not report the process file, retrying with an explicit write-and-report instruction...${RESET}\n`);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
async function runProcessDefinitionPhase(args) {
|
|
604
|
+
const state = {};
|
|
605
|
+
const customTools = [
|
|
606
|
+
{
|
|
607
|
+
name: "AskUserQuestion",
|
|
608
|
+
label: "Ask User Question",
|
|
609
|
+
description: "Ask the user one to four structured clarification questions and receive structured answers.",
|
|
610
|
+
promptSnippet: "Ask the user focused clarification questions when you need missing requirements.",
|
|
611
|
+
parameters: ASK_USER_QUESTION_SCHEMA,
|
|
612
|
+
execute: async (_toolCallId, params) => {
|
|
613
|
+
const response = await askUserQuestionViaTool(params, args.interactive, args.rl);
|
|
614
|
+
emitProgress({
|
|
615
|
+
phase: "1",
|
|
616
|
+
status: "interview",
|
|
617
|
+
answer: JSON.stringify(response.answers),
|
|
618
|
+
}, args.json, args.verbose);
|
|
619
|
+
return formatToolResult(response, "AskUserQuestion completed.");
|
|
620
|
+
},
|
|
621
|
+
},
|
|
622
|
+
{
|
|
623
|
+
name: "babysitter_report_process_definition",
|
|
624
|
+
label: "Report Process Definition",
|
|
625
|
+
description: "Report that the process-definition phase is complete after the process file has been written.",
|
|
626
|
+
parameters: typebox_1.Type.Object({
|
|
627
|
+
processPath: typebox_1.Type.String(),
|
|
628
|
+
summary: typebox_1.Type.Optional(typebox_1.Type.String()),
|
|
629
|
+
}),
|
|
630
|
+
execute: (_toolCallId, params) => {
|
|
631
|
+
state.report = {
|
|
632
|
+
processPath: params.processPath,
|
|
633
|
+
summary: params.summary,
|
|
634
|
+
};
|
|
635
|
+
return formatToolResult(state.report, "Process definition reported.");
|
|
636
|
+
},
|
|
637
|
+
},
|
|
638
|
+
];
|
|
639
|
+
emitProgress({ phase: "1", status: "started", harness: "pi (agentic)" }, args.json, args.verbose);
|
|
640
|
+
const session = (0, piWrapper_1.createPiSession)({
|
|
641
|
+
workspace: args.workspace,
|
|
642
|
+
model: args.model,
|
|
643
|
+
toolsMode: "coding",
|
|
644
|
+
customTools,
|
|
645
|
+
appendSystemPrompt: [(0, sessionCreatePrompts_1.buildProcessDefinitionSystemPrompt)(args.outputPath, args.promptContext)],
|
|
646
|
+
ephemeral: true,
|
|
647
|
+
});
|
|
648
|
+
try {
|
|
649
|
+
await session.initialize();
|
|
650
|
+
let unsubscribe = null;
|
|
651
|
+
if (!args.json) {
|
|
652
|
+
process.stderr.write(`${DIM}Phase 1 agent is defining the process...${RESET}\n`);
|
|
653
|
+
unsubscribe = session.subscribe((event) => {
|
|
654
|
+
if (event.type === "text_delta") {
|
|
655
|
+
const text = event.text;
|
|
656
|
+
if (text)
|
|
657
|
+
process.stderr.write(text);
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
const result = await session.prompt(compressInternalHarnessPrompt(buildMetaPrompt(args.prompt, args.workspace ?? process.cwd()), args.compressionConfig, "agent"), 300_000);
|
|
662
|
+
if (unsubscribe)
|
|
663
|
+
unsubscribe();
|
|
664
|
+
if (!args.json)
|
|
665
|
+
process.stderr.write("\n");
|
|
666
|
+
if (!result.success) {
|
|
667
|
+
throw new exceptions_1.BabysitterRuntimeError("ProcessDefinitionFailed", result.output, { category: exceptions_1.ErrorCategory.External });
|
|
668
|
+
}
|
|
669
|
+
if (!state.report?.processPath) {
|
|
670
|
+
writeVerboseProcessDefinitionRecovery(args.json);
|
|
671
|
+
const recovery = await session.prompt(compressInternalHarnessPrompt([
|
|
672
|
+
"Recovery step:",
|
|
673
|
+
`- Write the full process file now to ${args.outputPath}`,
|
|
674
|
+
"- Then call babysitter_report_process_definition exactly once.",
|
|
675
|
+
"- Do not just describe the process in plain text.",
|
|
676
|
+
].join("\n"), args.compressionConfig, "agent"), 180_000);
|
|
677
|
+
if (!recovery.success) {
|
|
678
|
+
throw new exceptions_1.BabysitterRuntimeError("ProcessDefinitionFailed", recovery.output, { category: exceptions_1.ErrorCategory.External });
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (!state.report?.processPath) {
|
|
682
|
+
try {
|
|
683
|
+
await waitForProcessFile(args.outputPath, 5_000);
|
|
684
|
+
state.report = {
|
|
685
|
+
processPath: args.outputPath,
|
|
686
|
+
summary: "Recovered from missing process-definition tool report by using the expected output path.",
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
catch {
|
|
690
|
+
if (!args.interactive) {
|
|
691
|
+
throw new exceptions_1.BabysitterRuntimeError("ProcessDefinitionReportMissing", "The process-definition agent finished without calling babysitter_report_process_definition, and the expected process file was not created.", { category: exceptions_1.ErrorCategory.Runtime });
|
|
692
|
+
}
|
|
693
|
+
else {
|
|
694
|
+
throw new exceptions_1.BabysitterRuntimeError("ProcessDefinitionReportMissing", "The process-definition agent finished without calling babysitter_report_process_definition.", { category: exceptions_1.ErrorCategory.Runtime });
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
await waitForProcessFile(state.report.processPath);
|
|
699
|
+
await validateProcessExport(state.report.processPath);
|
|
700
|
+
emitProgress({
|
|
701
|
+
phase: "1",
|
|
702
|
+
status: "completed",
|
|
703
|
+
processPath: state.report.processPath,
|
|
704
|
+
harness: "pi (agentic)",
|
|
705
|
+
}, args.json, args.verbose);
|
|
706
|
+
return state.report.processPath;
|
|
707
|
+
}
|
|
708
|
+
catch (error) {
|
|
709
|
+
emitProgress({
|
|
710
|
+
phase: "1",
|
|
711
|
+
status: "failed",
|
|
712
|
+
harness: "pi (agentic)",
|
|
713
|
+
error: error instanceof Error ? error.message : String(error),
|
|
714
|
+
}, args.json, args.verbose);
|
|
715
|
+
throw error;
|
|
716
|
+
}
|
|
717
|
+
finally {
|
|
718
|
+
session.dispose();
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
async function runOrchestrationPhase(args) {
|
|
722
|
+
const processId = path.basename(args.processPath, path.extname(args.processPath));
|
|
723
|
+
const state = {
|
|
724
|
+
iteration: 0,
|
|
725
|
+
pendingActions: new Map(),
|
|
726
|
+
pendingEffectResults: new Map(),
|
|
727
|
+
};
|
|
728
|
+
let orchestrationSession = null;
|
|
729
|
+
const writeVerbose = (message) => {
|
|
730
|
+
if (!args.json && args.verbose) {
|
|
731
|
+
process.stderr.write(`${DIM}${message}${RESET}\n`);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
const summarizeAgentText = (text) => {
|
|
735
|
+
const normalized = text.replace(/\s+/g, " ").trim();
|
|
736
|
+
if (!normalized) {
|
|
737
|
+
return "(no summary emitted)";
|
|
738
|
+
}
|
|
739
|
+
return normalized.length > 240 ? `${normalized.slice(0, 237)}...` : normalized;
|
|
740
|
+
};
|
|
741
|
+
const describePendingActions = () => Array.from(state.pendingActions.values()).map((action) => ({
|
|
742
|
+
effectId: action.effectId,
|
|
743
|
+
kind: action.kind,
|
|
744
|
+
title: action.taskDef?.title,
|
|
745
|
+
harness: resolveTaskHarness(action, args.selectedHarnessName, args.discovered),
|
|
746
|
+
}));
|
|
747
|
+
const ensureTerminalResult = () => {
|
|
748
|
+
if (state.lastIterationResult?.status === "completed") {
|
|
749
|
+
return 0;
|
|
750
|
+
}
|
|
751
|
+
if (state.lastIterationResult?.status === "failed") {
|
|
752
|
+
return 1;
|
|
753
|
+
}
|
|
754
|
+
return null;
|
|
755
|
+
};
|
|
756
|
+
const customTools = [
|
|
757
|
+
{
|
|
758
|
+
name: "AskUserQuestion",
|
|
759
|
+
label: "Ask User Question",
|
|
760
|
+
description: "Ask the user one to four structured questions and receive structured answers.",
|
|
761
|
+
promptSnippet: "Use this for breakpoint approvals and required user clarification.",
|
|
762
|
+
parameters: ASK_USER_QUESTION_SCHEMA,
|
|
763
|
+
execute: async (_toolCallId, params) => {
|
|
764
|
+
const response = await askUserQuestionViaTool(params, args.interactive, args.rl);
|
|
765
|
+
state.lastAskUserQuestionResponse = response;
|
|
766
|
+
return formatToolResult(response, "AskUserQuestion completed.");
|
|
767
|
+
},
|
|
768
|
+
},
|
|
769
|
+
{
|
|
770
|
+
name: "babysitter_run_create",
|
|
771
|
+
label: "Babysitter Run Create",
|
|
772
|
+
description: "Create the babysitter run for the current process definition.",
|
|
773
|
+
parameters: typebox_1.Type.Object({
|
|
774
|
+
prompt: typebox_1.Type.Optional(typebox_1.Type.String()),
|
|
775
|
+
}),
|
|
776
|
+
execute: async (_toolCallId, params) => {
|
|
777
|
+
if (state.runId && state.runDir) {
|
|
778
|
+
return formatToolResult({ runId: state.runId, runDir: state.runDir }, "Run already exists.");
|
|
779
|
+
}
|
|
780
|
+
const result = await (0, createRun_1.createRun)({
|
|
781
|
+
runsDir: args.runsDir,
|
|
782
|
+
process: {
|
|
783
|
+
processId,
|
|
784
|
+
importPath: path.resolve(args.processPath),
|
|
785
|
+
},
|
|
786
|
+
prompt: params.prompt ?? args.prompt,
|
|
787
|
+
inputs: (params.prompt ?? args.prompt)
|
|
788
|
+
? { prompt: params.prompt ?? args.prompt }
|
|
789
|
+
: undefined,
|
|
790
|
+
});
|
|
791
|
+
state.runId = result.runId;
|
|
792
|
+
state.runDir = result.runDir;
|
|
793
|
+
emitProgress({
|
|
794
|
+
phase: "2",
|
|
795
|
+
status: "run-created",
|
|
796
|
+
runId: result.runId,
|
|
797
|
+
runDir: result.runDir,
|
|
798
|
+
}, args.json, args.verbose);
|
|
799
|
+
return formatToolResult(result, "Run created.");
|
|
800
|
+
},
|
|
801
|
+
},
|
|
802
|
+
{
|
|
803
|
+
name: "babysitter_bind_session",
|
|
804
|
+
label: "Babysitter Bind Session",
|
|
805
|
+
description: "Bind the orchestration run to the current harness session.",
|
|
806
|
+
parameters: typebox_1.Type.Object({}),
|
|
807
|
+
execute: async () => {
|
|
808
|
+
if (!state.runId || !state.runDir) {
|
|
809
|
+
throw new exceptions_1.BabysitterRuntimeError("RunNotCreated", "Create the run before binding the orchestration session.", { category: exceptions_1.ErrorCategory.Validation });
|
|
810
|
+
}
|
|
811
|
+
if (state.sessionBound) {
|
|
812
|
+
return formatToolResult(state.sessionBound, "Session is already bound.");
|
|
813
|
+
}
|
|
814
|
+
const adapter = (0, harness_1.getAdapterByName)(args.selectedHarnessName);
|
|
815
|
+
if (!adapter) {
|
|
816
|
+
throw new exceptions_1.BabysitterRuntimeError("HarnessAdapterMissing", `No harness adapter is registered for ${args.selectedHarnessName}.`, { category: exceptions_1.ErrorCategory.Configuration });
|
|
817
|
+
}
|
|
818
|
+
if ((args.selectedHarnessName === "pi" || args.selectedHarnessName === "oh-my-pi") &&
|
|
819
|
+
orchestrationSession?.sessionId) {
|
|
820
|
+
process.env.PI_SESSION_ID = process.env.PI_SESSION_ID || orchestrationSession.sessionId;
|
|
821
|
+
process.env.OMP_SESSION_ID = process.env.OMP_SESSION_ID || orchestrationSession.sessionId;
|
|
822
|
+
}
|
|
823
|
+
const sessionId = adapter.resolveSessionId({}) || orchestrationSession?.sessionId;
|
|
824
|
+
if (!sessionId) {
|
|
825
|
+
throw new exceptions_1.BabysitterRuntimeError("MissingHarnessSessionId", `Cannot resolve a session ID for harness ${args.selectedHarnessName}.`, { category: exceptions_1.ErrorCategory.Configuration });
|
|
826
|
+
}
|
|
827
|
+
state.sessionBound = await adapter.bindSession({
|
|
828
|
+
sessionId,
|
|
829
|
+
runId: state.runId,
|
|
830
|
+
runDir: state.runDir,
|
|
831
|
+
pluginRoot: adapter.resolvePluginRoot({}),
|
|
832
|
+
stateDir: path.resolve(args.workspace ?? process.cwd(), ".a5c"),
|
|
833
|
+
runsDir: args.runsDir,
|
|
834
|
+
maxIterations: args.maxIterations,
|
|
835
|
+
prompt: args.prompt ?? "",
|
|
836
|
+
verbose: args.verbose,
|
|
837
|
+
json: args.json,
|
|
838
|
+
});
|
|
839
|
+
if (state.sessionBound.fatal) {
|
|
840
|
+
throw new exceptions_1.BabysitterRuntimeError("SessionBindFatal", state.sessionBound.error ?? "Session binding failed fatally.", { category: exceptions_1.ErrorCategory.External });
|
|
841
|
+
}
|
|
842
|
+
emitProgress({
|
|
843
|
+
phase: "2",
|
|
844
|
+
status: "bound",
|
|
845
|
+
runId: state.runId,
|
|
846
|
+
runDir: state.runDir,
|
|
847
|
+
harness: state.sessionBound.harness,
|
|
848
|
+
sessionId: state.sessionBound.sessionId,
|
|
849
|
+
error: state.sessionBound.error,
|
|
850
|
+
}, args.json, args.verbose);
|
|
851
|
+
return formatToolResult(state.sessionBound, "Session bound.");
|
|
852
|
+
},
|
|
853
|
+
},
|
|
854
|
+
{
|
|
855
|
+
name: "babysitter_run_iterate",
|
|
856
|
+
label: "Babysitter Run Iterate",
|
|
857
|
+
description: "Run the next orchestration iteration and return pending effects or a terminal result.",
|
|
858
|
+
parameters: typebox_1.Type.Object({}),
|
|
859
|
+
execute: async () => {
|
|
860
|
+
if (!state.runDir) {
|
|
861
|
+
throw new exceptions_1.BabysitterRuntimeError("RunNotCreated", "Create the run before iterating it.", { category: exceptions_1.ErrorCategory.Validation });
|
|
862
|
+
}
|
|
863
|
+
if (state.iteration >= args.maxIterations) {
|
|
864
|
+
state.lastIterationResult = {
|
|
865
|
+
status: "failed",
|
|
866
|
+
error: { message: `Max iterations (${args.maxIterations}) reached without completion` },
|
|
867
|
+
};
|
|
868
|
+
emitProgress({
|
|
869
|
+
phase: "2",
|
|
870
|
+
status: "failed",
|
|
871
|
+
iteration: state.iteration,
|
|
872
|
+
runStatus: "failed",
|
|
873
|
+
error: `Max iterations (${args.maxIterations}) reached without completion`,
|
|
874
|
+
}, args.json, args.verbose);
|
|
875
|
+
return formatToolResult(state.lastIterationResult, "Iteration limit reached.");
|
|
876
|
+
}
|
|
877
|
+
state.iteration += 1;
|
|
878
|
+
state.pendingActions.clear();
|
|
879
|
+
state.pendingEffectResults.clear();
|
|
880
|
+
const result = await (0, orchestrateIteration_1.orchestrateIteration)({ runDir: state.runDir });
|
|
881
|
+
state.lastIterationResult = result;
|
|
882
|
+
if (result.status === "waiting") {
|
|
883
|
+
for (const action of result.nextActions) {
|
|
884
|
+
state.pendingActions.set(action.effectId, action);
|
|
885
|
+
}
|
|
886
|
+
emitProgress({
|
|
887
|
+
phase: "2",
|
|
888
|
+
status: "iteration",
|
|
889
|
+
iteration: state.iteration,
|
|
890
|
+
runStatus: "waiting",
|
|
891
|
+
pendingEffects: result.nextActions.length,
|
|
892
|
+
}, args.json, args.verbose);
|
|
893
|
+
}
|
|
894
|
+
else if (result.status === "completed") {
|
|
895
|
+
emitProgress({
|
|
896
|
+
phase: "2",
|
|
897
|
+
status: "completed",
|
|
898
|
+
iteration: state.iteration,
|
|
899
|
+
runStatus: "completed",
|
|
900
|
+
}, args.json, args.verbose);
|
|
901
|
+
}
|
|
902
|
+
else {
|
|
903
|
+
const errorMessage = result.error instanceof Error
|
|
904
|
+
? result.error.message
|
|
905
|
+
: typeof result.error === "object" &&
|
|
906
|
+
result.error !== null &&
|
|
907
|
+
"message" in result.error
|
|
908
|
+
? String(result.error.message)
|
|
909
|
+
: String(result.error);
|
|
910
|
+
emitProgress({
|
|
911
|
+
phase: "2",
|
|
912
|
+
status: "failed",
|
|
913
|
+
iteration: state.iteration,
|
|
914
|
+
runStatus: "failed",
|
|
915
|
+
error: errorMessage,
|
|
916
|
+
}, args.json, args.verbose);
|
|
917
|
+
}
|
|
918
|
+
return formatToolResult({
|
|
919
|
+
iteration: state.iteration,
|
|
920
|
+
...result,
|
|
921
|
+
}, "Iteration completed.");
|
|
922
|
+
},
|
|
923
|
+
},
|
|
924
|
+
{
|
|
925
|
+
name: "babysitter_execute_effect",
|
|
926
|
+
label: "Babysitter Execute Effect",
|
|
927
|
+
description: "Execute a non-breakpoint pending effect and stage the result for task posting.",
|
|
928
|
+
parameters: typebox_1.Type.Object({
|
|
929
|
+
effectId: typebox_1.Type.String(),
|
|
930
|
+
}),
|
|
931
|
+
execute: async (_toolCallId, params) => {
|
|
932
|
+
const action = state.pendingActions.get(params.effectId);
|
|
933
|
+
if (!action) {
|
|
934
|
+
throw new exceptions_1.BabysitterRuntimeError("PendingEffectNotFound", `No pending effect found for ${params.effectId}.`, { category: exceptions_1.ErrorCategory.Validation });
|
|
935
|
+
}
|
|
936
|
+
if (action.kind === "breakpoint") {
|
|
937
|
+
return formatToolResult({
|
|
938
|
+
effectId: params.effectId,
|
|
939
|
+
kind: action.kind,
|
|
940
|
+
message: "Use AskUserQuestion followed by babysitter_task_post_result for breakpoint effects.",
|
|
941
|
+
}, "Breakpoint effects require explicit AskUserQuestion handling.");
|
|
942
|
+
}
|
|
943
|
+
const taskHarness = resolveTaskHarness(action, args.selectedHarnessName, args.discovered);
|
|
944
|
+
let workerSession = null;
|
|
945
|
+
if (action.kind === "shell" || isPiHarness(taskHarness)) {
|
|
946
|
+
workerSession = (0, piWrapper_1.createPiSession)(buildPiWorkerSessionOptions({
|
|
947
|
+
action,
|
|
948
|
+
workspace: args.workspace,
|
|
949
|
+
model: args.model,
|
|
950
|
+
}));
|
|
951
|
+
}
|
|
952
|
+
try {
|
|
953
|
+
const effectResult = await resolveEffect(action, args.selectedHarnessName, {
|
|
954
|
+
workspace: args.workspace,
|
|
955
|
+
model: args.model,
|
|
956
|
+
interactive: false,
|
|
957
|
+
compressionConfig: args.compressionConfig,
|
|
958
|
+
}, workerSession, args.discovered, null, args.json);
|
|
959
|
+
state.pendingEffectResults.set(params.effectId, effectResult);
|
|
960
|
+
return formatToolResult({ effectId: params.effectId, effectResult }, "Effect executed and staged for task posting.");
|
|
961
|
+
}
|
|
962
|
+
finally {
|
|
963
|
+
workerSession?.dispose();
|
|
964
|
+
}
|
|
965
|
+
},
|
|
966
|
+
},
|
|
967
|
+
{
|
|
968
|
+
name: "babysitter_task_post_result",
|
|
969
|
+
label: "Babysitter Task Post Result",
|
|
970
|
+
description: "Persist the staged effect result, or post a breakpoint decision after AskUserQuestion.",
|
|
971
|
+
parameters: typebox_1.Type.Object({
|
|
972
|
+
effectId: typebox_1.Type.String(),
|
|
973
|
+
}),
|
|
974
|
+
execute: async (_toolCallId, params) => {
|
|
975
|
+
if (!state.runDir) {
|
|
976
|
+
throw new exceptions_1.BabysitterRuntimeError("RunNotCreated", "Create the run before posting task results.", { category: exceptions_1.ErrorCategory.Validation });
|
|
977
|
+
}
|
|
978
|
+
const action = state.pendingActions.get(params.effectId);
|
|
979
|
+
if (!action) {
|
|
980
|
+
throw new exceptions_1.BabysitterRuntimeError("PendingEffectNotFound", `No pending effect found for ${params.effectId}.`, { category: exceptions_1.ErrorCategory.Validation });
|
|
981
|
+
}
|
|
982
|
+
const startedAt = new Date().toISOString();
|
|
983
|
+
let effectResult = state.pendingEffectResults.get(params.effectId);
|
|
984
|
+
if (!effectResult && action.kind === "breakpoint") {
|
|
985
|
+
const question = action.taskDef?.question ??
|
|
986
|
+
action.taskDef?.title ??
|
|
987
|
+
"Breakpoint reached. Continue?";
|
|
988
|
+
const defaultResponse = (0, interaction_1.createAskUserQuestionResponse)((0, interaction_1.createApprovalAskUserQuestion)(question), { Decision: "Approve" });
|
|
989
|
+
const askResponse = state.lastAskUserQuestionResponse ?? defaultResponse;
|
|
990
|
+
const option = askResponse.answers.Decision ?? "Approve";
|
|
991
|
+
effectResult = {
|
|
992
|
+
status: "ok",
|
|
993
|
+
value: {
|
|
994
|
+
approved: option === "Approve",
|
|
995
|
+
option,
|
|
996
|
+
askUserQuestion: askResponse,
|
|
997
|
+
},
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
if (!effectResult) {
|
|
1001
|
+
throw new exceptions_1.BabysitterRuntimeError("EffectResultMissing", `No staged effect result exists for ${params.effectId}.`, { category: exceptions_1.ErrorCategory.Runtime });
|
|
1002
|
+
}
|
|
1003
|
+
const finishedAt = new Date().toISOString();
|
|
1004
|
+
await (0, commitEffectResult_1.commitEffectResult)({
|
|
1005
|
+
runDir: state.runDir,
|
|
1006
|
+
effectId: action.effectId,
|
|
1007
|
+
invocationKey: action.invocationKey,
|
|
1008
|
+
result: {
|
|
1009
|
+
status: effectResult.status,
|
|
1010
|
+
value: effectResult.value,
|
|
1011
|
+
error: effectResult.error,
|
|
1012
|
+
stdout: effectResult.stdout,
|
|
1013
|
+
stderr: effectResult.stderr,
|
|
1014
|
+
startedAt,
|
|
1015
|
+
finishedAt,
|
|
1016
|
+
},
|
|
1017
|
+
});
|
|
1018
|
+
emitProgress({
|
|
1019
|
+
phase: "2",
|
|
1020
|
+
status: "effect",
|
|
1021
|
+
effectId: action.effectId,
|
|
1022
|
+
effectKind: action.kind,
|
|
1023
|
+
effectTitle: action.taskDef?.title,
|
|
1024
|
+
effectStatus: effectResult.status,
|
|
1025
|
+
error: effectResult.status === "error"
|
|
1026
|
+
? (effectResult.error instanceof Error
|
|
1027
|
+
? effectResult.error.message
|
|
1028
|
+
: String(effectResult.error))
|
|
1029
|
+
: undefined,
|
|
1030
|
+
output: typeof effectResult.value === "string"
|
|
1031
|
+
? effectResult.value.slice(0, 200)
|
|
1032
|
+
: undefined,
|
|
1033
|
+
}, args.json, args.verbose);
|
|
1034
|
+
state.pendingActions.delete(params.effectId);
|
|
1035
|
+
state.pendingEffectResults.delete(params.effectId);
|
|
1036
|
+
if (action.kind === "breakpoint") {
|
|
1037
|
+
state.lastAskUserQuestionResponse = undefined;
|
|
1038
|
+
}
|
|
1039
|
+
return formatToolResult({
|
|
1040
|
+
effectId: params.effectId,
|
|
1041
|
+
status: effectResult.status,
|
|
1042
|
+
}, "Task result posted.");
|
|
1043
|
+
},
|
|
1044
|
+
},
|
|
1045
|
+
{
|
|
1046
|
+
name: "babysitter_finish_orchestration",
|
|
1047
|
+
label: "Finish Orchestration",
|
|
1048
|
+
description: "Report that the orchestration phase has reached a terminal state.",
|
|
1049
|
+
parameters: typebox_1.Type.Object({
|
|
1050
|
+
summary: typebox_1.Type.Optional(typebox_1.Type.String()),
|
|
1051
|
+
}),
|
|
1052
|
+
execute: (_toolCallId, params) => {
|
|
1053
|
+
state.finished = { summary: params.summary };
|
|
1054
|
+
return formatToolResult(state.finished, "Orchestration finish recorded.");
|
|
1055
|
+
},
|
|
1056
|
+
},
|
|
1057
|
+
];
|
|
1058
|
+
const tools = customTools;
|
|
1059
|
+
const getTool = (name) => tools.find((tool) => tool.name === name);
|
|
1060
|
+
const runCreateTool = getTool("babysitter_run_create");
|
|
1061
|
+
const bindSessionTool = getTool("babysitter_bind_session");
|
|
1062
|
+
const runIterateTool = getTool("babysitter_run_iterate");
|
|
1063
|
+
const executeEffectTool = getTool("babysitter_execute_effect");
|
|
1064
|
+
const taskPostTool = getTool("babysitter_task_post_result");
|
|
1065
|
+
const finishTool = getTool("babysitter_finish_orchestration");
|
|
1066
|
+
const invokeTool = async (tool, name, params = {}) => {
|
|
1067
|
+
if (!tool?.execute) {
|
|
1068
|
+
throw new exceptions_1.BabysitterRuntimeError("MissingSessionCreateTool", `Required orchestration tool is unavailable: ${name}`, { category: exceptions_1.ErrorCategory.Internal });
|
|
1069
|
+
}
|
|
1070
|
+
const result = tool.execute(`host-${name}`, params);
|
|
1071
|
+
return await Promise.resolve(result);
|
|
1072
|
+
};
|
|
1073
|
+
const runDeterministicPendingEffects = async (reason) => {
|
|
1074
|
+
const pending = describePendingActions();
|
|
1075
|
+
if (pending.length === 0) {
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
writeVerbose(`[phase2 fallback] ${reason}`);
|
|
1079
|
+
for (const effect of pending) {
|
|
1080
|
+
writeVerbose(`[phase2 fallback] resolving ${effect.effectId} (${effect.kind}) via ${effect.harness ?? args.selectedHarnessName}`);
|
|
1081
|
+
const action = state.pendingActions.get(effect.effectId);
|
|
1082
|
+
if (!action) {
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
if (action.kind !== "breakpoint") {
|
|
1086
|
+
await invokeTool(executeEffectTool, "babysitter_execute_effect", { effectId: effect.effectId });
|
|
1087
|
+
}
|
|
1088
|
+
await invokeTool(taskPostTool, "babysitter_task_post_result", { effectId: effect.effectId });
|
|
1089
|
+
}
|
|
1090
|
+
};
|
|
1091
|
+
const promptOrchestrationAgent = async (message, options) => {
|
|
1092
|
+
if (!orchestrationSession) {
|
|
1093
|
+
throw new exceptions_1.BabysitterRuntimeError("OrchestrationSessionMissing", "The orchestration PI session has not been created.", { category: exceptions_1.ErrorCategory.Runtime });
|
|
1094
|
+
}
|
|
1095
|
+
if (!args.json && args.verbose) {
|
|
1096
|
+
const label = options?.label ?? "phase2";
|
|
1097
|
+
process.stderr.write(`\n${DIM}[${label}] agent turn${RESET}\n`);
|
|
1098
|
+
}
|
|
1099
|
+
const result = await orchestrationSession.prompt(compressInternalHarnessPrompt(message, args.compressionConfig, "agent"), 900_000);
|
|
1100
|
+
if (!result.success) {
|
|
1101
|
+
throw new exceptions_1.BabysitterRuntimeError("OrchestrationAgentFailed", result.output, { category: exceptions_1.ErrorCategory.External });
|
|
1102
|
+
}
|
|
1103
|
+
writeVerbose(`[phase2 agent] ${summarizeAgentText(result.output)}`);
|
|
1104
|
+
if (options?.fallbackReason && state.pendingActions.size > 0) {
|
|
1105
|
+
await runDeterministicPendingEffects(options.fallbackReason);
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
orchestrationSession = (0, piWrapper_1.createPiSession)({
|
|
1109
|
+
workspace: args.workspace,
|
|
1110
|
+
model: args.model,
|
|
1111
|
+
toolsMode: "readonly",
|
|
1112
|
+
customTools,
|
|
1113
|
+
appendSystemPrompt: [(0, sessionCreatePrompts_1.buildOrchestrationSystemPrompt)(args.selectedHarnessName, args.promptContext)],
|
|
1114
|
+
ephemeral: true,
|
|
1115
|
+
});
|
|
1116
|
+
emitProgress({ phase: "2", status: "started", harness: args.selectedHarnessName }, args.json, args.verbose);
|
|
1117
|
+
let unsubscribe = null;
|
|
1118
|
+
try {
|
|
1119
|
+
await orchestrationSession.initialize();
|
|
1120
|
+
if (!args.json && args.verbose) {
|
|
1121
|
+
unsubscribe = orchestrationSession.subscribe((event) => {
|
|
1122
|
+
if (event.type === "text_delta") {
|
|
1123
|
+
const text = event.text;
|
|
1124
|
+
if (text)
|
|
1125
|
+
process.stderr.write(text);
|
|
1126
|
+
}
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
await promptOrchestrationAgent((0, sessionCreatePrompts_1.buildOrchestrationBootstrapPrompt)(path.resolve(args.processPath), args.prompt, args.maxIterations), { label: "phase2 bootstrap" });
|
|
1130
|
+
if (!state.runId || !state.runDir) {
|
|
1131
|
+
writeVerbose("[phase2 fallback] agent did not create a run; creating it in the host");
|
|
1132
|
+
await invokeTool(runCreateTool, "babysitter_run_create", args.prompt ? { prompt: args.prompt } : {});
|
|
1133
|
+
}
|
|
1134
|
+
if (!state.sessionBound) {
|
|
1135
|
+
writeVerbose("[phase2 fallback] agent did not bind the session; binding in the host");
|
|
1136
|
+
await invokeTool(bindSessionTool, "babysitter_bind_session");
|
|
1137
|
+
}
|
|
1138
|
+
if (!state.runId || !state.runDir) {
|
|
1139
|
+
throw new exceptions_1.BabysitterRuntimeError("RunNotCreated", "The orchestration session could not establish a run after bootstrap.", { category: exceptions_1.ErrorCategory.Runtime });
|
|
1140
|
+
}
|
|
1141
|
+
while (state.iteration < args.maxIterations) {
|
|
1142
|
+
const terminal = ensureTerminalResult();
|
|
1143
|
+
if (terminal !== null) {
|
|
1144
|
+
break;
|
|
1145
|
+
}
|
|
1146
|
+
const iterationBeforeTurn = state.iteration;
|
|
1147
|
+
await promptOrchestrationAgent((0, sessionCreatePrompts_1.buildOrchestrationTurnPrompt)({
|
|
1148
|
+
processPath: path.resolve(args.processPath),
|
|
1149
|
+
userPrompt: args.prompt,
|
|
1150
|
+
maxIterations: args.maxIterations,
|
|
1151
|
+
currentIteration: state.iteration,
|
|
1152
|
+
runId: state.runId,
|
|
1153
|
+
runDir: state.runDir,
|
|
1154
|
+
lastStatus: state.lastIterationResult?.status,
|
|
1155
|
+
pendingEffects: describePendingActions(),
|
|
1156
|
+
}), {
|
|
1157
|
+
label: `phase2 iteration ${state.iteration + 1}`,
|
|
1158
|
+
fallbackReason: "Agent left pending effects unresolved; the host resolved and posted them to keep the orchestration loop moving.",
|
|
1159
|
+
});
|
|
1160
|
+
if (ensureTerminalResult() !== null) {
|
|
1161
|
+
break;
|
|
1162
|
+
}
|
|
1163
|
+
if (state.iteration === iterationBeforeTurn && state.pendingActions.size === 0) {
|
|
1164
|
+
writeVerbose("[phase2 fallback] agent did not advance the run; executing one iteration in the host");
|
|
1165
|
+
await invokeTool(runIterateTool, "babysitter_run_iterate");
|
|
1166
|
+
}
|
|
1167
|
+
if (state.lastIterationResult?.status === "waiting" && state.pendingActions.size > 0) {
|
|
1168
|
+
await runDeterministicPendingEffects("Agent left pending effects unresolved after the turn; the host completed them deterministically.");
|
|
1169
|
+
}
|
|
1170
|
+
const postTurnTerminal = ensureTerminalResult();
|
|
1171
|
+
if (postTurnTerminal !== null) {
|
|
1172
|
+
break;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
if (state.lastIterationResult?.status !== "completed" && state.lastIterationResult?.status !== "failed") {
|
|
1176
|
+
state.lastIterationResult = {
|
|
1177
|
+
status: "failed",
|
|
1178
|
+
error: { message: `Max iterations (${args.maxIterations}) reached without completion` },
|
|
1179
|
+
};
|
|
1180
|
+
emitProgress({
|
|
1181
|
+
phase: "2",
|
|
1182
|
+
status: "failed",
|
|
1183
|
+
runId: state.runId,
|
|
1184
|
+
runDir: state.runDir,
|
|
1185
|
+
iteration: state.iteration,
|
|
1186
|
+
runStatus: "failed",
|
|
1187
|
+
error: `Max iterations (${args.maxIterations}) reached without completion`,
|
|
1188
|
+
}, args.json, args.verbose);
|
|
1189
|
+
}
|
|
1190
|
+
if (state.lastIterationResult?.status === "completed" || state.lastIterationResult?.status === "failed") {
|
|
1191
|
+
await invokeTool(finishTool, "babysitter_finish_orchestration", {
|
|
1192
|
+
summary: state.lastIterationResult.status === "completed"
|
|
1193
|
+
? `Run ${state.runId} completed after ${state.iteration} iterations.`
|
|
1194
|
+
: `Run ${state.runId} failed after ${state.iteration} iterations.`,
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
const exitCode = ensureTerminalResult();
|
|
1198
|
+
if (exitCode !== null) {
|
|
1199
|
+
return exitCode;
|
|
1200
|
+
}
|
|
1201
|
+
throw new exceptions_1.BabysitterRuntimeError("OrchestrationIncomplete", "The orchestration phase ended without a terminal run state.", { category: exceptions_1.ErrorCategory.Runtime });
|
|
1202
|
+
}
|
|
1203
|
+
catch (error) {
|
|
1204
|
+
emitProgress({
|
|
1205
|
+
phase: "2",
|
|
1206
|
+
status: "failed",
|
|
1207
|
+
runId: state.runId,
|
|
1208
|
+
runDir: state.runDir,
|
|
1209
|
+
iteration: state.iteration,
|
|
1210
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1211
|
+
}, args.json, args.verbose);
|
|
1212
|
+
return 1;
|
|
1213
|
+
}
|
|
1214
|
+
finally {
|
|
1215
|
+
if (unsubscribe)
|
|
1216
|
+
unsubscribe();
|
|
1217
|
+
if (!args.json && args.verbose)
|
|
1218
|
+
process.stderr.write("\n");
|
|
1219
|
+
orchestrationSession?.dispose();
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
async function handleSessionCreate(parsed) {
|
|
1223
|
+
const { prompt, harness: preferredHarness, processPath: providedProcessPath, workspace, model, maxIterations = 256, runsDir, json, verbose, } = parsed;
|
|
1224
|
+
const interactive = parsed.interactive ?? (process.stdin.isTTY === true && !json);
|
|
1225
|
+
const rl = interactive ? createReadlineInterface() : null;
|
|
1226
|
+
try {
|
|
1227
|
+
if (!prompt && !providedProcessPath) {
|
|
1228
|
+
const error = "Either --prompt or --process must be provided";
|
|
1229
|
+
if (json) {
|
|
1230
|
+
console.error(JSON.stringify({ error: "MISSING_PROMPT", message: error }, null, 2));
|
|
1231
|
+
}
|
|
1232
|
+
else {
|
|
1233
|
+
process.stderr.write(`${RED}Error:${RESET} ${error}\n`);
|
|
1234
|
+
}
|
|
1235
|
+
return 1;
|
|
1236
|
+
}
|
|
1237
|
+
const discovered = await (0, discovery_1.discoverHarnesses)();
|
|
1238
|
+
const selected = selectHarness(discovered, preferredHarness);
|
|
1239
|
+
const selectedHarnessName = preferredHarness === "pi" || preferredHarness === "oh-my-pi"
|
|
1240
|
+
? preferredHarness
|
|
1241
|
+
: (selected?.name ?? "pi");
|
|
1242
|
+
const compressionConfig = loadSessionCompressionConfig(workspace);
|
|
1243
|
+
const promptContext = buildPromptContext({
|
|
1244
|
+
workspace,
|
|
1245
|
+
selectedHarnessName,
|
|
1246
|
+
discovered,
|
|
1247
|
+
compressionConfig,
|
|
1248
|
+
});
|
|
1249
|
+
let processPath = providedProcessPath;
|
|
1250
|
+
if (processPath) {
|
|
1251
|
+
emitProgress({ phase: "1", status: "skipped", processPath }, json, verbose);
|
|
1252
|
+
}
|
|
1253
|
+
else {
|
|
1254
|
+
const workDir = workspace ?? process.cwd();
|
|
1255
|
+
processPath = await runProcessDefinitionPhase({
|
|
1256
|
+
prompt: prompt,
|
|
1257
|
+
outputPath: path.join(workDir, "generated-process.js"),
|
|
1258
|
+
workspace: workDir,
|
|
1259
|
+
model,
|
|
1260
|
+
interactive,
|
|
1261
|
+
rl,
|
|
1262
|
+
json,
|
|
1263
|
+
verbose,
|
|
1264
|
+
compressionConfig,
|
|
1265
|
+
promptContext,
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
return await runOrchestrationPhase({
|
|
1269
|
+
processPath,
|
|
1270
|
+
prompt,
|
|
1271
|
+
workspace,
|
|
1272
|
+
model,
|
|
1273
|
+
runsDir,
|
|
1274
|
+
maxIterations,
|
|
1275
|
+
json,
|
|
1276
|
+
verbose,
|
|
1277
|
+
interactive,
|
|
1278
|
+
rl,
|
|
1279
|
+
selectedHarnessName,
|
|
1280
|
+
discovered,
|
|
1281
|
+
compressionConfig,
|
|
1282
|
+
promptContext,
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
finally {
|
|
1286
|
+
rl?.close();
|
|
1287
|
+
}
|
|
1288
|
+
}
|