@pal-code/core 0.0.11 → 0.0.12
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 +1 -1
- package/src/agent/fallback.ts +7 -0
- package/src/agent/file-roles.ts +183 -0
- package/src/agent/frontmatter.ts +105 -0
- package/src/agent/roles.ts +41 -5
- package/src/agent/run.ts +114 -4
- package/src/agent/skills.ts +177 -0
- package/src/agent/subagent-status.ts +78 -0
- package/src/config.ts +43 -2
- package/src/diagnostics-checks.ts +201 -0
- package/src/diagnostics.ts +173 -0
- package/src/extensions.ts +17 -1
- package/src/index.ts +21 -0
- package/src/lifecycle.ts +109 -0
- package/src/provider/openrouter.ts +16 -7
- package/src/registry.ts +5 -4
- package/src/tools/definitions.ts +16 -2
- package/src/tools/executor.ts +224 -12
package/package.json
CHANGED
package/src/agent/fallback.ts
CHANGED
|
@@ -179,6 +179,11 @@ export interface RunWithFallbackOptions {
|
|
|
179
179
|
*/
|
|
180
180
|
childExecuteTool?: RunAgentOptions['executeTool'];
|
|
181
181
|
signal?: AbortSignal;
|
|
182
|
+
/**
|
|
183
|
+
* Active primary agent name, threaded through to `runAgent` so lifecycle
|
|
184
|
+
* hooks see it in `TurnContext.primary`. `''` when the turn has none.
|
|
185
|
+
*/
|
|
186
|
+
primary?: string;
|
|
182
187
|
/** Read-only turn — `delegate` may not spawn anything that mutates state. */
|
|
183
188
|
readOnly?: boolean;
|
|
184
189
|
/**
|
|
@@ -219,6 +224,7 @@ export async function* runWithFallback(
|
|
|
219
224
|
executeTool,
|
|
220
225
|
childExecuteTool,
|
|
221
226
|
signal,
|
|
227
|
+
primary,
|
|
222
228
|
readOnly,
|
|
223
229
|
allowedTools,
|
|
224
230
|
createProvider = createProviderFor,
|
|
@@ -299,6 +305,7 @@ export async function* runWithFallback(
|
|
|
299
305
|
providerConfig,
|
|
300
306
|
executeTool,
|
|
301
307
|
signal,
|
|
308
|
+
primary,
|
|
302
309
|
});
|
|
303
310
|
return;
|
|
304
311
|
} catch (err) {
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File-based roles — `.pal/agents/*.md` from the project and `~/.pal/agents/`.
|
|
3
|
+
*
|
|
4
|
+
* Each file is a plain markdown doc: YAML-ish frontmatter (`name`, `model`,
|
|
5
|
+
* `tools`, `category`, plus optional `description`/`reasoning`/`max_rounds`)
|
|
6
|
+
* over a body that becomes the role's system prompt. This is the
|
|
7
|
+
* dotfile-shareable counterpart to the extension's `agents.json` — zero plugin
|
|
8
|
+
* runtime, committable, reviewable in a PR.
|
|
9
|
+
*
|
|
10
|
+
* Precedence (highest first):
|
|
11
|
+
* project file → user file → extension JSON config → built-in
|
|
12
|
+
*
|
|
13
|
+
* Files are layered *on top of* the registered provider: this module only owns
|
|
14
|
+
* the two file roots and returns plain `RoleSpec`s that slot into the existing
|
|
15
|
+
* two-axis model (`agent` | `category`). `roles.ts` consults it before the
|
|
16
|
+
* provider, so a file always shadows a JSON/built-in role of the same name and
|
|
17
|
+
* axis, and a project file shadows a user file.
|
|
18
|
+
*
|
|
19
|
+
* A malformed file is skipped with a `console.warn` — never a crash.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import {readFileSync} from 'fs';
|
|
23
|
+
import {homedir} from 'os';
|
|
24
|
+
import {basename, join} from 'path';
|
|
25
|
+
import type {RoleKind, RoleSpec} from './roles.js';
|
|
26
|
+
import {listMarkdownFiles, parseFrontmatter, parseToolsValue} from './frontmatter.js';
|
|
27
|
+
|
|
28
|
+
const DEFAULT_REASONING: NonNullable<RoleSpec['reasoning']> = 'medium';
|
|
29
|
+
const DEFAULT_MAX_ROUNDS = 5;
|
|
30
|
+
const DESCRIPTION_LIMIT = 100;
|
|
31
|
+
|
|
32
|
+
function skipFile(path: string, reason: string): null {
|
|
33
|
+
console.warn(`pal: ignoring ${path} — ${reason}`);
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function skipField(path: string, field: string, reason: string): void {
|
|
38
|
+
console.warn(`pal: ignoring ${field} in ${path} — ${reason}`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function firstBodyLine(body: string): string {
|
|
42
|
+
const line = body
|
|
43
|
+
.split('\n')
|
|
44
|
+
.map((l) => l.trim())
|
|
45
|
+
.find((l) => l !== '');
|
|
46
|
+
if (!line) return '';
|
|
47
|
+
const cleaned = line.replace(/^#+\s*/, '');
|
|
48
|
+
return cleaned.length > DESCRIPTION_LIMIT ? `${cleaned.slice(0, DESCRIPTION_LIMIT)}…` : cleaned;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function roleFrom(path: string, fields: Record<string, string>, body: string): RoleSpec | null {
|
|
52
|
+
const kindValue = fields.category ?? 'agent';
|
|
53
|
+
if (kindValue !== 'agent' && kindValue !== 'category') {
|
|
54
|
+
return skipFile(path, `unknown category "${kindValue}" (expected "agent" or "category")`);
|
|
55
|
+
}
|
|
56
|
+
const kind: RoleKind = kindValue;
|
|
57
|
+
|
|
58
|
+
let reasoning: RoleSpec['reasoning'] = DEFAULT_REASONING;
|
|
59
|
+
if (fields.reasoning !== undefined) {
|
|
60
|
+
if (fields.reasoning === 'low' || fields.reasoning === 'high') {
|
|
61
|
+
reasoning = fields.reasoning;
|
|
62
|
+
} else if (fields.reasoning !== 'medium') {
|
|
63
|
+
skipField(
|
|
64
|
+
path,
|
|
65
|
+
'reasoning',
|
|
66
|
+
`unknown value "${fields.reasoning}" (using ${DEFAULT_REASONING})`,
|
|
67
|
+
);
|
|
68
|
+
reasoning = DEFAULT_REASONING;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let maxRounds = DEFAULT_MAX_ROUNDS;
|
|
73
|
+
if (fields.max_rounds !== undefined) {
|
|
74
|
+
if (/^\d+$/.test(fields.max_rounds)) {
|
|
75
|
+
maxRounds = Number(fields.max_rounds);
|
|
76
|
+
} else {
|
|
77
|
+
skipField(
|
|
78
|
+
path,
|
|
79
|
+
'max_rounds',
|
|
80
|
+
`invalid value "${fields.max_rounds}" (using ${DEFAULT_MAX_ROUNDS})`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
let tools: string[] | undefined;
|
|
86
|
+
if (fields.tools !== undefined && fields.tools.trim() !== '') {
|
|
87
|
+
const parsed = parseToolsValue(fields.tools);
|
|
88
|
+
if (parsed === null) {
|
|
89
|
+
skipField(path, 'tools', `unparseable value "${fields.tools}" (using default tools)`);
|
|
90
|
+
} else {
|
|
91
|
+
tools = parsed;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const description = fields.description?.trim() || firstBodyLine(body);
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
name: fields.name?.trim() || basename(path, '.md'),
|
|
99
|
+
kind,
|
|
100
|
+
description,
|
|
101
|
+
model: fields.model?.trim() || undefined,
|
|
102
|
+
reasoning,
|
|
103
|
+
tools,
|
|
104
|
+
maxRounds,
|
|
105
|
+
systemPrompt: body,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function readRolesDir(dir: string): RoleSpec[] {
|
|
110
|
+
const roles: RoleSpec[] = [];
|
|
111
|
+
for (const path of listMarkdownFiles(dir)) {
|
|
112
|
+
let text: string;
|
|
113
|
+
try {
|
|
114
|
+
text = readFileSync(path, 'utf-8');
|
|
115
|
+
} catch (err) {
|
|
116
|
+
skipFile(path, err instanceof Error ? err.message : String(err));
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const parsed = parseFrontmatter(text);
|
|
121
|
+
if (parsed === null) {
|
|
122
|
+
skipFile(path, 'missing or malformed frontmatter');
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const role = roleFrom(path, parsed.fields, parsed.body);
|
|
127
|
+
if (role) roles.push(role);
|
|
128
|
+
}
|
|
129
|
+
return roles;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Scan two role roots. `userDir` is applied first so `projectDir` wins on a
|
|
134
|
+
* same-name/same-axis collision (project → user shadowing).
|
|
135
|
+
*/
|
|
136
|
+
export function scanFileRoles(projectDir: string, userDir: string): RoleSpec[] {
|
|
137
|
+
const byKey = new Map<string, RoleSpec>();
|
|
138
|
+
for (const role of [...readRolesDir(userDir), ...readRolesDir(projectDir)]) {
|
|
139
|
+
byKey.set(`${role.kind}:${role.name}`, role);
|
|
140
|
+
}
|
|
141
|
+
return [...byKey.values()];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface FileRolesCache {
|
|
145
|
+
projectDir: string;
|
|
146
|
+
userDir: string;
|
|
147
|
+
roles: RoleSpec[];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let cache: FileRolesCache | undefined;
|
|
151
|
+
|
|
152
|
+
function defaultRoots(): {projectDir: string; userDir: string} {
|
|
153
|
+
// Same convention as `agents.json`: project = cwd (see loadAgentsConfig),
|
|
154
|
+
// user = ~/.pal, resolved through os.homedir() so HOME/USERPROFILE overrides work.
|
|
155
|
+
return {
|
|
156
|
+
projectDir: join(process.cwd(), '.pal', 'agents'),
|
|
157
|
+
userDir: join(homedir(), '.pal', 'agents'),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** File roles from the default roots, cached until {@link clearFileRolesCache}. */
|
|
162
|
+
export function getFileRoles(): RoleSpec[] {
|
|
163
|
+
const roots = defaultRoots();
|
|
164
|
+
if (cache && cache.projectDir === roots.projectDir && cache.userDir === roots.userDir) {
|
|
165
|
+
return cache.roles;
|
|
166
|
+
}
|
|
167
|
+
cache = {
|
|
168
|
+
projectDir: roots.projectDir,
|
|
169
|
+
userDir: roots.userDir,
|
|
170
|
+
roles: scanFileRoles(roots.projectDir, roots.userDir),
|
|
171
|
+
};
|
|
172
|
+
return cache.roles;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Resolve a file-based role by name and axis, or null when no file defines it. */
|
|
176
|
+
export function resolveFileRole(name: string, kind: RoleKind): RoleSpec | null {
|
|
177
|
+
return getFileRoles().find((r) => r.name === name && r.kind === kind) ?? null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Drop the cache so `/reload` and tests pick up file edits. */
|
|
181
|
+
export function clearFileRolesCache(): void {
|
|
182
|
+
cache = undefined;
|
|
183
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hand-rolled frontmatter parser for plain-`.md` agent/skill files.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately tiny and dependency-free: we only need `key: value` pairs above
|
|
5
|
+
* a `---` delimiter, not real YAML. A file that doesn't match this shape is
|
|
6
|
+
* rejected up front (`null`) so the caller can warn and skip it rather than
|
|
7
|
+
* crash or silently mis-parse.
|
|
8
|
+
*
|
|
9
|
+
* Malformed input → `null`. The caller decides policy (warn + skip).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {readdirSync} from 'fs';
|
|
13
|
+
import {join} from 'path';
|
|
14
|
+
|
|
15
|
+
export interface Frontmatter {
|
|
16
|
+
/** Keys from the frontmatter block; values are unquoted strings. */
|
|
17
|
+
fields: Record<string, string>;
|
|
18
|
+
/** Everything after the closing `---` line. */
|
|
19
|
+
body: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Absolute paths of every `.md` file directly inside `dir`; [] when absent. */
|
|
23
|
+
export function listMarkdownFiles(dir: string): string[] {
|
|
24
|
+
try {
|
|
25
|
+
return readdirSync(dir, {withFileTypes: true})
|
|
26
|
+
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
|
|
27
|
+
.map((entry) => join(dir, entry.name));
|
|
28
|
+
} catch {
|
|
29
|
+
return []; // absent root is the normal "nothing here" case
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Strip one layer of matching surrounding quotes, if present. */
|
|
34
|
+
function unquote(value: string): string {
|
|
35
|
+
if (value.length >= 2) {
|
|
36
|
+
const first = value[0];
|
|
37
|
+
const last = value[value.length - 1];
|
|
38
|
+
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
|
|
39
|
+
return value.slice(1, -1);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Parse `---`-delimited frontmatter.
|
|
47
|
+
*
|
|
48
|
+
* Returns `null` when the file has no frontmatter block, the closing `---` is
|
|
49
|
+
* missing, or a line inside the block is not `key: value`.
|
|
50
|
+
*/
|
|
51
|
+
export function parseFrontmatter(text: string): Frontmatter | null {
|
|
52
|
+
const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
53
|
+
const lines = source.split(/\r?\n/);
|
|
54
|
+
|
|
55
|
+
if (lines[0]?.trim() !== '---') return null;
|
|
56
|
+
|
|
57
|
+
const fields: Record<string, string> = {};
|
|
58
|
+
let closing = -1;
|
|
59
|
+
|
|
60
|
+
for (let i = 1; i < lines.length; i++) {
|
|
61
|
+
const line = lines[i].trim();
|
|
62
|
+
if (line === '---') {
|
|
63
|
+
closing = i;
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
67
|
+
|
|
68
|
+
const colon = line.indexOf(':');
|
|
69
|
+
if (colon <= 0) return null; // not `key: value` → malformed
|
|
70
|
+
const key = line.slice(0, colon).trim();
|
|
71
|
+
if (key === '') return null;
|
|
72
|
+
fields[key] = unquote(line.slice(colon + 1).trim());
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (closing === -1) return null; // unterminated block
|
|
76
|
+
return {fields, body: lines.slice(closing + 1).join('\n')};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isStringArray(value: unknown): value is string[] {
|
|
80
|
+
return Array.isArray(value) && value.every((item) => typeof item === 'string');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Parse a `tools` frontmatter value: either a JSON array (`["a","b"]`) or a
|
|
85
|
+
* comma-separated list (`a, b`). Returns `null` when the value is present but
|
|
86
|
+
* unusable (bad JSON, non-string entries, no names) so the caller can warn.
|
|
87
|
+
*/
|
|
88
|
+
export function parseToolsValue(value: string): string[] | null {
|
|
89
|
+
const trimmed = value.trim();
|
|
90
|
+
if (trimmed.startsWith('[')) {
|
|
91
|
+
let parsed: unknown;
|
|
92
|
+
try {
|
|
93
|
+
parsed = JSON.parse(trimmed);
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return isStringArray(parsed) ? parsed : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const names = trimmed
|
|
101
|
+
.split(',')
|
|
102
|
+
.map((v) => unquote(v.trim()))
|
|
103
|
+
.filter((v) => v !== '');
|
|
104
|
+
return names.length > 0 ? names : null;
|
|
105
|
+
}
|
package/src/agent/roles.ts
CHANGED
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
* - `category` — implementation lane (build, deep, quick, architect, …)
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
+
import {loadAgentConfig} from '../config.js';
|
|
16
17
|
import {registry} from '../registry.js';
|
|
18
|
+
import {getFileRoles, resolveFileRole} from './file-roles.js';
|
|
17
19
|
|
|
18
20
|
export type RoleKind = 'agent' | 'category';
|
|
19
21
|
|
|
@@ -44,6 +46,12 @@ export interface RoleProvider {
|
|
|
44
46
|
list: () => RoleSpec[];
|
|
45
47
|
/** Concurrency cap for `delegate_parallel`. Defaults to 3 when omitted. */
|
|
46
48
|
maxParallel?: () => number;
|
|
49
|
+
/**
|
|
50
|
+
* Per-role token budget for a delegated child, in tokens. Resolved ONCE at
|
|
51
|
+
* the delegate call site and handed to the child's loop as plain data — the
|
|
52
|
+
* loop never looks up roles. `undefined` → no budget for that role.
|
|
53
|
+
*/
|
|
54
|
+
budget?: (roleName: string) => number | undefined;
|
|
47
55
|
/** Primary agents the user can Tab between. Omitted → none. */
|
|
48
56
|
listPrimary?: () => PrimarySpec[];
|
|
49
57
|
/** Name of the primary agent selected on startup. Omitted → first primary. */
|
|
@@ -105,20 +113,48 @@ export function clearRoleProvider(): void {
|
|
|
105
113
|
registry.roleProvider = null;
|
|
106
114
|
}
|
|
107
115
|
|
|
108
|
-
/**
|
|
116
|
+
/**
|
|
117
|
+
* Resolve a role by name and axis.
|
|
118
|
+
*
|
|
119
|
+
* Precedence: file-based role (`.pal/agents/*.md`, project before user) →
|
|
120
|
+
* provider role (extension JSON config over its built-ins) → null. Wiring the
|
|
121
|
+
* file layer here means every caller — `delegate`, the "Available:" hint,
|
|
122
|
+
* `buildRolesPrompt` — sees one consistent order.
|
|
123
|
+
*/
|
|
109
124
|
export function resolveRoleSpec(name: string, kind: RoleKind): RoleSpec | null {
|
|
125
|
+
const fromFiles = resolveFileRole(name, kind);
|
|
126
|
+
if (fromFiles) return fromFiles;
|
|
110
127
|
return registry.roleProvider?.resolve(name, kind) ?? null;
|
|
111
128
|
}
|
|
112
129
|
|
|
113
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* All roles: provider list with file-based roles layered on top (a file with
|
|
132
|
+
* the same name and axis replaces its JSON/built-in counterpart).
|
|
133
|
+
*/
|
|
114
134
|
export function listRoleSpecs(): RoleSpec[] {
|
|
115
|
-
|
|
135
|
+
const roles = [...(registry.roleProvider?.list() ?? [])];
|
|
136
|
+
for (const fileRole of getFileRoles()) {
|
|
137
|
+
const idx = roles.findIndex((r) => r.name === fileRole.name && r.kind === fileRole.kind);
|
|
138
|
+
if (idx >= 0) roles[idx] = fileRole;
|
|
139
|
+
else roles.push(fileRole);
|
|
140
|
+
}
|
|
141
|
+
return roles;
|
|
116
142
|
}
|
|
117
143
|
|
|
118
|
-
/**
|
|
144
|
+
/**
|
|
145
|
+
* Concurrency cap for delegate fan-out (`delegate_parallel` batches and the
|
|
146
|
+
* multi-delegate dispatch lane in `run.ts`).
|
|
147
|
+
*
|
|
148
|
+
* Precedence: explicit `.pal.json` `orchestration.max_parallel` → extension
|
|
149
|
+
* `agents.json` `max_parallel` (role provider) → `DEFAULT_MAX_PARALLEL`.
|
|
150
|
+
*/
|
|
119
151
|
export function getMaxParallel(): number {
|
|
120
152
|
try {
|
|
121
|
-
return
|
|
153
|
+
return (
|
|
154
|
+
loadAgentConfig().orchestration?.maxParallel ??
|
|
155
|
+
registry.roleProvider?.maxParallel?.() ??
|
|
156
|
+
DEFAULT_MAX_PARALLEL
|
|
157
|
+
);
|
|
122
158
|
} catch {
|
|
123
159
|
return DEFAULT_MAX_PARALLEL;
|
|
124
160
|
}
|
package/src/agent/run.ts
CHANGED
|
@@ -8,8 +8,11 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import {shouldCompact, compactionBoundary, summarizeRange} from '../compaction.js';
|
|
11
|
+
import {getDiagnosticsMode, takeDiagnosticsLine} from '../diagnostics.js';
|
|
12
|
+
import {emitLifecycleEvent, type TurnContext} from '../lifecycle.js';
|
|
11
13
|
import {complete} from '../provider/complete.js';
|
|
12
14
|
import type {Provider, StreamEvent} from '../provider/types.js';
|
|
15
|
+
import {getMaxParallel} from './roles.js';
|
|
13
16
|
|
|
14
17
|
// ---------------------------------------------------------------------------
|
|
15
18
|
// Conversation shape
|
|
@@ -124,6 +127,13 @@ export interface RunAgentOptions {
|
|
|
124
127
|
systemPrompt: string;
|
|
125
128
|
/** Max tool-call rounds (default 100). */
|
|
126
129
|
maxRounds?: number;
|
|
130
|
+
/**
|
|
131
|
+
* Per-role token budget for a DELEGATED child run, handed down as plain data
|
|
132
|
+
* by the delegate call site (never resolved here). Checked only at round
|
|
133
|
+
* boundaries; absent → no budget (the parent/orchestrator run never carries
|
|
134
|
+
* one).
|
|
135
|
+
*/
|
|
136
|
+
budget?: {roleName: string; limit: number};
|
|
127
137
|
/** Context window used to decide when to compact (default 100_000). */
|
|
128
138
|
contextLimit?: number;
|
|
129
139
|
/** Reasoning effort forwarded to the provider (default 'medium'). */
|
|
@@ -150,6 +160,12 @@ export interface RunAgentOptions {
|
|
|
150
160
|
* an `aborted` notice instead of `done`.
|
|
151
161
|
*/
|
|
152
162
|
signal?: AbortSignal;
|
|
163
|
+
/**
|
|
164
|
+
* Active primary agent name for this turn, surfaced to lifecycle hooks via
|
|
165
|
+
* `TurnContext.primary`. `''` when the turn has no primary — a delegate
|
|
166
|
+
* child's role is a different axis than the turn's primary.
|
|
167
|
+
*/
|
|
168
|
+
primary?: string;
|
|
153
169
|
/** Provider credentials handed to tools that spawn sub-agents. */
|
|
154
170
|
providerConfig: ChildProviderConfig;
|
|
155
171
|
/**
|
|
@@ -207,6 +223,9 @@ const PARALLEL_SAFE = new Set([
|
|
|
207
223
|
'repo_map',
|
|
208
224
|
]);
|
|
209
225
|
|
|
226
|
+
/** Delegate-family tools — dispatched through the bounded fan-out lane. */
|
|
227
|
+
const DELEGATE_TOOLS = new Set(['delegate', 'delegate_parallel']);
|
|
228
|
+
|
|
210
229
|
// ---------------------------------------------------------------------------
|
|
211
230
|
// Helpers
|
|
212
231
|
// ---------------------------------------------------------------------------
|
|
@@ -314,7 +333,8 @@ export function buildApiMessages(
|
|
|
314
333
|
): Array<Record<string, unknown>> {
|
|
315
334
|
// The summarized prefix is represented by `compactionNote` in the system
|
|
316
335
|
// prompt; sending it again would waste context and could contradict the note.
|
|
317
|
-
const visible =
|
|
336
|
+
const visible =
|
|
337
|
+
compactedUpto > 0 ? messages.slice(Math.min(compactedUpto, messages.length)) : messages;
|
|
318
338
|
const wire: Array<Record<string, unknown>> = [
|
|
319
339
|
{
|
|
320
340
|
role: 'system',
|
|
@@ -445,8 +465,33 @@ async function summarizeViaProvider(
|
|
|
445
465
|
*
|
|
446
466
|
* Terminates when the model stops requesting tools, when `maxRounds` is hit,
|
|
447
467
|
* or when the same tool call repeats `REPEAT_STOP` times.
|
|
468
|
+
*
|
|
469
|
+
* Wraps {@link agentTurn} with the extension lifecycle boundary hooks:
|
|
470
|
+
* `onTurnStart` before the loop begins, `onTurnEnd` in a `finally` so every
|
|
471
|
+
* exit path — done, abort, throw, or the consumer abandoning the generator —
|
|
472
|
+
* completes the turn.
|
|
448
473
|
*/
|
|
449
474
|
export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent> {
|
|
475
|
+
const turnId = `turn_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
|
|
476
|
+
const context = (): TurnContext => ({
|
|
477
|
+
turnId,
|
|
478
|
+
primary: opts.primary ?? '',
|
|
479
|
+
messageCount: opts.messages.length,
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
await emitLifecycleEvent('onTurnStart', context());
|
|
483
|
+
try {
|
|
484
|
+
yield* agentTurn(opts);
|
|
485
|
+
} finally {
|
|
486
|
+
await emitLifecycleEvent('onTurnEnd', context());
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* The round loop behind {@link runAgent}. Split out so the turn-boundary
|
|
492
|
+
* lifecycle hooks can wrap it in try/finally without re-indenting the loop.
|
|
493
|
+
*/
|
|
494
|
+
async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent> {
|
|
450
495
|
const {
|
|
451
496
|
messages,
|
|
452
497
|
tools,
|
|
@@ -458,6 +503,7 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
|
|
|
458
503
|
reasoningEffort = 'medium',
|
|
459
504
|
providerConfig,
|
|
460
505
|
executeTool,
|
|
506
|
+
budget,
|
|
461
507
|
signal,
|
|
462
508
|
compactedSeq = 0,
|
|
463
509
|
compactionNote: initialCompactionNote = '',
|
|
@@ -543,8 +589,29 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
|
|
|
543
589
|
const noteEntry = `[messages ${compactedUpto + 1}-${compactedUpto + midBoundary}]\n${midSummary}`;
|
|
544
590
|
compactionNote = compactionNote ? `${compactionNote}\n\n${noteEntry}` : noteEntry;
|
|
545
591
|
compactedUpto += midBoundary;
|
|
546
|
-
yield {
|
|
547
|
-
|
|
592
|
+
yield {
|
|
593
|
+
type: 'compacted',
|
|
594
|
+
boundary: compactedUpto,
|
|
595
|
+
summarized: midBoundary,
|
|
596
|
+
summary: midSummary,
|
|
597
|
+
};
|
|
598
|
+
yield {
|
|
599
|
+
type: 'notice',
|
|
600
|
+
text: `Context compacted mid-turn (${midBoundary} messages summarized).`,
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// One-line edit diagnostics from the previous round: the check ran off the
|
|
606
|
+
// critical path; take() resolves no later than its ~2s budget. Auto mode
|
|
607
|
+
// pushes it into the model's context; verify-only surfaces it to the user.
|
|
608
|
+
const diagLine = await takeDiagnosticsLine();
|
|
609
|
+
if (diagLine !== null) {
|
|
610
|
+
const diagMode = getDiagnosticsMode();
|
|
611
|
+
if (diagMode === 'auto') {
|
|
612
|
+
messages.push({role: 'user', content: diagLine});
|
|
613
|
+
} else if (diagMode === 'verify-only') {
|
|
614
|
+
yield {type: 'notice', text: diagLine};
|
|
548
615
|
}
|
|
549
616
|
}
|
|
550
617
|
|
|
@@ -614,9 +681,36 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
|
|
|
614
681
|
|
|
615
682
|
const byId = new Map<string, Awaited<ReturnType<typeof runOne>>>();
|
|
616
683
|
const parallel = displays.filter((d) => PARALLEL_SAFE.has(d.tc.name));
|
|
617
|
-
const
|
|
684
|
+
const delegates = displays.filter((d) => DELEGATE_TOOLS.has(d.tc.name));
|
|
685
|
+
const sequential = displays.filter(
|
|
686
|
+
(d) => !PARALLEL_SAFE.has(d.tc.name) && !DELEGATE_TOOLS.has(d.tc.name),
|
|
687
|
+
);
|
|
618
688
|
|
|
619
689
|
for (const r of await Promise.all(parallel.map(runOne))) byId.set(r.tc.id, r);
|
|
690
|
+
|
|
691
|
+
// Delegate fan-out: non-mutating children run in batches of `max_parallel`,
|
|
692
|
+
// then mutating children run strictly one at a time. Phases never overlap,
|
|
693
|
+
// so two writers can't race the same file; batches can't exceed the cap.
|
|
694
|
+
if (delegates.length > 0) {
|
|
695
|
+
const {delegateCallIsMutating} = await import('../tools/executor.js');
|
|
696
|
+
const flags = await Promise.all(
|
|
697
|
+
delegates.map((d) => delegateCallIsMutating(d.tc.name, d.tc.arguments)),
|
|
698
|
+
);
|
|
699
|
+
const fanOut = delegates.filter((_, i) => !flags[i]);
|
|
700
|
+
const serial = delegates.filter((_, i) => flags[i]);
|
|
701
|
+
|
|
702
|
+
const limit = Math.max(1, getMaxParallel());
|
|
703
|
+
for (let i = 0; i < fanOut.length; i += limit) {
|
|
704
|
+
for (const r of await Promise.all(fanOut.slice(i, i + limit).map(runOne))) {
|
|
705
|
+
byId.set(r.tc.id, r);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
for (const d of serial) {
|
|
709
|
+
const r = await runOne(d);
|
|
710
|
+
byId.set(r.tc.id, r);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
620
714
|
for (const d of sequential) {
|
|
621
715
|
const r = await runOne(d);
|
|
622
716
|
byId.set(r.tc.id, r);
|
|
@@ -665,6 +759,22 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunE
|
|
|
665
759
|
stoppedEarly = true;
|
|
666
760
|
break;
|
|
667
761
|
}
|
|
762
|
+
|
|
763
|
+
// Round boundary: cumulative prompt+completion vs the child's budget.
|
|
764
|
+
// Intentionally double-counts re-sent history — locked semantics.
|
|
765
|
+
if (budget) {
|
|
766
|
+
const used = totalInput + totalOutput;
|
|
767
|
+
if (used > budget.limit) {
|
|
768
|
+
const stopMessage = `Stopped: token budget ${budget.limit} exceeded (used ~${used})`;
|
|
769
|
+
yield {type: 'notice', text: stopMessage};
|
|
770
|
+
// Also streamed as text: executeChild builds the child's result string
|
|
771
|
+
// from text-delta events, so this is what puts the stop in front of
|
|
772
|
+
// the parent. Leading newlines keep the exact message intact after trim.
|
|
773
|
+
yield {type: 'text-delta', content: `\n\n${stopMessage}`};
|
|
774
|
+
stoppedEarly = true;
|
|
775
|
+
break;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
668
778
|
}
|
|
669
779
|
|
|
670
780
|
// ── Round cap reached → degrade gracefully ──
|