| 1 | /** |
| 2 | * Named team-profile templates: config types, normalization, invocation |
| 3 | * parsing, and prompt rendering. |
| 4 | * |
| 5 | * Pure functions only — no I/O, no spawn. Runtime create/spawn stays in |
| 6 | * `tools.ts`; this module only turns a config map + a profile name into a |
| 7 | * validated, topologically ordered template (or parses `--profile` flags). |
| 8 | * |
| 9 | * @module dsh-agent-teams/profiles |
| 10 | */ |
| 11 | import { CAPTAIN_KEY, sanitizeKey } from "./state.js"; |
| 12 | /** Hard cap on named profiles so the usage prompt cannot grow without bound. */ |
| 13 | export const MAX_TEAM_PROFILES = 16; |
| 14 | /** Hard cap on seed tasks per profile. The software-delivery example has 13. */ |
| 15 | export const MAX_PROFILE_TASKS = 32; |
| 16 | /** Protocol excerpt length in the usage / prompt listing. */ |
| 17 | export const PROFILE_PROTOCOL_PROMPT_LIMIT = 240; |
| 18 | const PROFILE_KEYS = ['description', 'protocol', 'executionPrompt', 'fallback', 'members', 'tasks', 'taskPlanning', 'reviewPolicy']; |
| 19 | const REVIEW_POLICY_KEYS = ['requirementsMinRounds', 'requirementsMaxRounds', 'codeMaxRounds', 'maxRepairAttempts', 'requiredReviewers']; |
| 20 | const MEMBER_KEYS = ['name', 'role', 'provider', 'model', 'reasoning_effort', 'executionPrompt', 'fallback', 'tool_policy']; |
| 21 | const FALLBACK_KEYS = ['provider', 'model']; |
| 22 | const TASK_KEYS = ['id', 'subject', 'description', 'assignee', 'dependencies']; |
| 23 | /** |
| 24 | * Trim every profile key once, reject empty / colliding keys, and reject |
| 25 | * more than {@link MAX_TEAM_PROFILES} entries. Does not validate profile |
| 26 | * bodies — that belongs to {@link resolveTeamProfile}. |
| 27 | */ |
| 28 | export function listConfiguredProfiles(profiles) { |
| 29 | const record = asProfilesRecord(profiles); |
| 30 | const keys = Object.keys(record); |
| 31 | if (keys.length > MAX_TEAM_PROFILES) { |
| 32 | throw new Error(`too many AgentTeams profiles (${keys.length}); the limit is ${MAX_TEAM_PROFILES}`); |
| 33 | } |
| 34 | const seen = new Map(); |
| 35 | const listed = []; |
| 36 | for (const rawKey of keys) { |
| 37 | const name = rawKey.trim(); |
| 38 | if (name === '') { |
| 39 | throw new Error('configured AgentTeams profiles include an empty key'); |
| 40 | } |
| 41 | const previous = seen.get(name); |
| 42 | if (previous !== undefined) { |
| 43 | throw new Error(`configured AgentTeams profiles have duplicate key "${name}"`); |
| 44 | } |
| 45 | seen.set(name, rawKey); |
| 46 | listed.push({ name, config: record[rawKey] }); |
| 47 | } |
| 48 | return listed; |
| 49 | } |
| 50 | /** |
| 51 | * Render the usage-prompt listing. One line per profile: name, member count, |
| 52 | * task count, protocol excerpt (at most 240 characters). Returns `''` when |
| 53 | * nothing is configured so callers can omit the capability entirely. |
| 54 | */ |
| 55 | export function formatProfilesForPrompt(profiles) { |
| 56 | const listed = listConfiguredProfiles(profiles); |
| 57 | if (listed.length === 0) |
| 58 | return ''; |
| 59 | const lines = [ |
| 60 | 'Configured team profiles (pass profile= to agent_teams_create):', |
| 61 | ...listed.map((entry) => formatProfileListingLine(entry)), |
| 62 | ]; |
| 63 | return lines.join('\n'); |
| 64 | } |
| 65 | /** |
| 66 | * Walk `rawInput` from the front and eat standalone profile flags. Only |
| 67 | * `--profile <name>`, `--profile=<name>`, and `profile=<name>` count; the |
| 68 | * first ordinary token stops the scan so a mid-sentence `profile=` stays in |
| 69 | * the goal. A leading ordinary token is never treated as a profile name. |
| 70 | * |
| 71 | * `--profile "name"` strips one matching pair of quotes. Repeat flags and a |
| 72 | * `--profile` with no name throw. |
| 73 | */ |
| 74 | export function parseProfileInvocation(rawInput) { |
| 75 | const tokens = tokenize(rawInput); |
| 76 | let index = 0; |
| 77 | let profile; |
| 78 | while (index < tokens.length) { |
| 79 | const token = tokens[index]; |
| 80 | if (token === undefined) |
| 81 | break; |
| 82 | const parsed = parseLeadingProfileFlag(token, tokens[index + 1]); |
| 83 | if (parsed === undefined) |
| 84 | break; |
| 85 | if (profile !== undefined) { |
| 86 | throw new Error('duplicate AgentTeams profile flag'); |
| 87 | } |
| 88 | profile = parsed.name; |
| 89 | index += parsed.consumed; |
| 90 | } |
| 91 | const goal = tokens.slice(index).join(' '); |
| 92 | return profile === undefined ? { goal } : { goal, profile }; |
| 93 | } |
| 94 | /** |
| 95 | * Normalize and pre-validate one named profile. Failures throw before any |
| 96 | * caller should create a directory or spawn members. |
| 97 | */ |
| 98 | export function resolveTeamProfile(profiles, profileName, maxMembers) { |
| 99 | const listed = listConfiguredProfiles(profiles); |
| 100 | const name = profileName.trim(); |
| 101 | if (name === '') { |
| 102 | throw new Error('AgentTeams profile name must be a non-empty string'); |
| 103 | } |
| 104 | const match = listed.find((entry) => entry.name === name); |
| 105 | if (match === undefined) { |
| 106 | const available = listed.map((entry) => entry.name); |
| 107 | const shown = available.length === 0 ? '(none)' : available.join(', '); |
| 108 | throw new Error(`unknown AgentTeams profile "${name}" — configured profiles: ${shown}`); |
| 109 | } |
| 110 | return normalizeListedProfile(match, maxMembers); |
| 111 | } |
| 112 | function formatProfileListingLine(entry) { |
| 113 | const memberCount = Array.isArray(entry.config.members) ? entry.config.members.length : 0; |
| 114 | const planning = resolveProfileTaskPlanning(entry.config); |
| 115 | const graph = planning === 'captain' |
| 116 | ? 'captain planning' |
| 117 | : countLabel(Array.isArray(entry.config.tasks) ? entry.config.tasks.length : 0, 'task'); |
| 118 | const counts = `(${countLabel(memberCount, 'member')}, ${graph})`; |
| 119 | const summary = protocolSummary(entry.config.protocol) ?? protocolSummary(entry.config.description); |
| 120 | return summary === undefined |
| 121 | ? `- ${entry.name} ${counts}` |
| 122 | : `- ${entry.name} ${counts}: ${summary}`; |
| 123 | } |
| 124 | /** Public lookup used by activation text and status rendering. */ |
| 125 | export function resolveProfileTaskPlanning(config) { |
| 126 | return config?.taskPlanning === 'captain' ? 'captain' : 'seed'; |
| 127 | } |
| 128 | function countLabel(count, noun) { |
| 129 | return `${count} ${noun}${count === 1 ? '' : 's'}`; |
| 130 | } |
| 131 | function protocolSummary(protocol) { |
| 132 | if (typeof protocol !== 'string') |
| 133 | return undefined; |
| 134 | const collapsed = protocol.trim().replace(/\s+/gu, ' '); |
| 135 | if (collapsed === '') |
| 136 | return undefined; |
| 137 | return collapsed.length <= PROFILE_PROTOCOL_PROMPT_LIMIT |
| 138 | ? collapsed |
| 139 | : collapsed.slice(0, PROFILE_PROTOCOL_PROMPT_LIMIT); |
| 140 | } |
| 141 | function tokenize(rawInput) { |
| 142 | const trimmed = rawInput.trim(); |
| 143 | if (trimmed === '') |
| 144 | return []; |
| 145 | return trimmed.split(/\s+/u); |
| 146 | } |
| 147 | function parseLeadingProfileFlag(token, nextToken) { |
| 148 | if (token === '--profile') { |
| 149 | if (nextToken === undefined) { |
| 150 | throw new Error('--profile flag is missing a profile name'); |
| 151 | } |
| 152 | return { name: readProfileToken(nextToken), consumed: 2 }; |
| 153 | } |
| 154 | if (token.startsWith('--profile=')) { |
| 155 | return { name: readProfileToken(token.slice('--profile='.length)), consumed: 1 }; |
| 156 | } |
| 157 | if (token.startsWith('profile=')) { |
| 158 | return { name: readProfileToken(token.slice('profile='.length)), consumed: 1 }; |
| 159 | } |
| 160 | return undefined; |
| 161 | } |
| 162 | function readProfileToken(raw) { |
| 163 | const name = stripOneQuotePair(raw).trim(); |
| 164 | if (name === '') { |
| 165 | throw new Error('--profile flag is missing a profile name'); |
| 166 | } |
| 167 | return name; |
| 168 | } |
| 169 | /** Strip a single matching pair of `"` or `'` quotes; leave unmatched quotes alone. */ |
| 170 | function stripOneQuotePair(value) { |
| 171 | if (value.length < 2) |
| 172 | return value; |
| 173 | const first = value.at(0); |
| 174 | const last = value.at(-1); |
| 175 | if ((first === '"' && last === '"') || (first === "'" && last === "'")) { |
| 176 | return value.slice(1, -1); |
| 177 | } |
| 178 | return value; |
| 179 | } |
| 180 | function normalizeListedProfile(listed, maxMembers) { |
| 181 | const path = `profiles.${listed.name}`; |
| 182 | const raw = asRecord(listed.config, path); |
| 183 | assertAllowedKeys(raw, PROFILE_KEYS, path); |
| 184 | const description = optionalNonEmptyString(raw['description'], `${path}.description`); |
| 185 | const protocol = optionalNonEmptyString(raw['protocol'], `${path}.protocol`); |
| 186 | const executionPrompt = optionalNonEmptyString(raw['executionPrompt'], `${path}.executionPrompt`); |
| 187 | const fallback = normalizeFallback(raw['fallback'], `${path}.fallback`); |
| 188 | const taskPlanning = normalizeTaskPlanning(raw['taskPlanning'], `${path}.taskPlanning`); |
| 189 | const reviewPolicy = normalizeReviewPolicy(raw['reviewPolicy'], `${path}.reviewPolicy`); |
| 190 | const membersRaw = raw['members']; |
| 191 | if (!Array.isArray(membersRaw) || membersRaw.length === 0) { |
| 192 | throw new Error(`AgentTeams profile "${listed.name}" has no members`); |
| 193 | } |
| 194 | if (membersRaw.length > maxMembers) { |
| 195 | throw new Error(`profile "${listed.name}" has ${membersRaw.length} members but maxMembers is ${maxMembers}`); |
| 196 | } |
| 197 | const members = []; |
| 198 | const memberByName = new Map(); |
| 199 | const memberByKey = new Map(); |
| 200 | for (let index = 0; index < membersRaw.length; index += 1) { |
| 201 | const member = normalizeMember(membersRaw[index], `${path}.members[${index}]`, listed.name); |
| 202 | const key = sanitizeKey(member.name); |
| 203 | const colliding = memberByKey.get(key); |
| 204 | if (colliding !== undefined) { |
| 205 | throw new Error(`profile members "${colliding.name}" and "${member.name}" collapse to the same name`); |
| 206 | } |
| 207 | memberByName.set(member.name, member); |
| 208 | memberByKey.set(key, member); |
| 209 | members.push(member); |
| 210 | } |
| 211 | const tasksRaw = raw['tasks']; |
| 212 | if (tasksRaw === undefined) { |
| 213 | return omitUndefined({ |
| 214 | name: listed.name, |
| 215 | description, |
| 216 | protocol, |
| 217 | executionPrompt, |
| 218 | fallback, |
| 219 | taskPlanning, |
| 220 | reviewPolicy, |
| 221 | members, |
| 222 | tasks: [], |
| 223 | }); |
| 224 | } |
| 225 | if (!Array.isArray(tasksRaw)) { |
| 226 | throw new Error(`profiles.${listed.name}.tasks must be an array`); |
| 227 | } |
| 228 | if (tasksRaw.length > MAX_PROFILE_TASKS) { |
| 229 | throw new Error(`profile "${listed.name}" has ${tasksRaw.length} tasks but the limit is ${MAX_PROFILE_TASKS}`); |
| 230 | } |
| 231 | const requireAssignee = tasksRaw.length > 0; |
| 232 | const draftTasks = []; |
| 233 | const taskById = new Map(); |
| 234 | const taskByKey = new Map(); |
| 235 | for (let index = 0; index < tasksRaw.length; index += 1) { |
| 236 | const task = normalizeTask(tasksRaw[index], `${path}.tasks[${index}]`, listed.name, index, memberByName, memberByKey, requireAssignee); |
| 237 | const collidingId = taskById.get(task.id); |
| 238 | if (collidingId !== undefined) { |
| 239 | throw new Error(`profile "${listed.name}" has duplicate task id "${task.id}"`); |
| 240 | } |
| 241 | const key = sanitizeKey(task.id); |
| 242 | const collidingKey = taskByKey.get(key); |
| 243 | if (collidingKey !== undefined) { |
| 244 | throw new Error(`profile tasks "${collidingKey.id}" and "${task.id}" collapse to the same id`); |
| 245 | } |
| 246 | taskById.set(task.id, task); |
| 247 | taskByKey.set(key, task); |
| 248 | draftTasks.push(task); |
| 249 | } |
| 250 | const tasks = topoSortTasks(draftTasks, listed.name); |
| 251 | return omitUndefined({ |
| 252 | name: listed.name, |
| 253 | description, |
| 254 | protocol, |
| 255 | executionPrompt, |
| 256 | fallback, |
| 257 | taskPlanning, |
| 258 | reviewPolicy, |
| 259 | members, |
| 260 | tasks: taskPlanning === 'captain' ? [] : tasks, |
| 261 | }); |
| 262 | } |
| 263 | function normalizeTaskPlanning(value, path) { |
| 264 | if (value === undefined) |
| 265 | return 'seed'; |
| 266 | if (value === 'captain' || value === 'seed') |
| 267 | return value; |
| 268 | throw new Error(`${path} must be "captain" or "seed"`); |
| 269 | } |
| 270 | function normalizeReviewPolicy(value, path) { |
| 271 | if (value === undefined) |
| 272 | return undefined; |
| 273 | const raw = asRecord(value, path); |
| 274 | assertAllowedKeys(raw, REVIEW_POLICY_KEYS, path); |
| 275 | const requirementsMinRounds = optionalPositiveInt(raw['requirementsMinRounds'], `${path}.requirementsMinRounds`); |
| 276 | const requirementsMaxRounds = optionalPositiveInt(raw['requirementsMaxRounds'], `${path}.requirementsMaxRounds`); |
| 277 | const codeMaxRounds = optionalPositiveInt(raw['codeMaxRounds'], `${path}.codeMaxRounds`); |
| 278 | const maxRepairAttempts = optionalPositiveInt(raw['maxRepairAttempts'], `${path}.maxRepairAttempts`); |
| 279 | if (requirementsMinRounds !== undefined |
| 280 | && requirementsMaxRounds !== undefined |
| 281 | && requirementsMinRounds > requirementsMaxRounds) { |
| 282 | throw new Error(`${path}.requirementsMinRounds must be <= requirementsMaxRounds`); |
| 283 | } |
| 284 | let requiredReviewers; |
| 285 | if (raw['requiredReviewers'] !== undefined) { |
| 286 | if (!Array.isArray(raw['requiredReviewers'])) { |
| 287 | throw new Error(`${path}.requiredReviewers must be an array of strings`); |
| 288 | } |
| 289 | requiredReviewers = raw['requiredReviewers'].map((item, index) => { |
| 290 | if (typeof item !== 'string' || item.trim() === '') { |
| 291 | throw new Error(`${path}.requiredReviewers[${index}] must be a non-empty string`); |
| 292 | } |
| 293 | return item.trim(); |
| 294 | }); |
| 295 | } |
| 296 | return omitUndefined({ |
| 297 | requirementsMinRounds, |
| 298 | requirementsMaxRounds, |
| 299 | codeMaxRounds, |
| 300 | maxRepairAttempts, |
| 301 | requiredReviewers, |
| 302 | }); |
| 303 | } |
| 304 | function optionalPositiveInt(value, path) { |
| 305 | if (value === undefined) |
| 306 | return undefined; |
| 307 | if (!Number.isSafeInteger(value) || value < 1) { |
| 308 | throw new Error(`${path} must be a positive integer`); |
| 309 | } |
| 310 | return value; |
| 311 | } |
| 312 | function normalizeMember(value, path, profileName) { |
| 313 | const raw = asRecord(value, path); |
| 314 | assertAllowedKeys(raw, MEMBER_KEYS, path); |
| 315 | const name = requiredNonEmptyString(raw['name'], `${path}.name`, `profile "${profileName}" has a member with an empty name`); |
| 316 | if (isCaptainName(name)) { |
| 317 | throw new Error(`member name "${name}" is reserved for the captain`); |
| 318 | } |
| 319 | const role = optionalNonEmptyString(raw['role'], `${path}.role`); |
| 320 | const provider = optionalNonEmptyString(raw['provider'], `${path}.provider`); |
| 321 | const model = optionalNonEmptyString(raw['model'], `${path}.model`); |
| 322 | const reasoningEffort = optionalNonEmptyString(raw['reasoning_effort'], `${path}.reasoning_effort`); |
| 323 | const executionPrompt = optionalNonEmptyString(raw['executionPrompt'], `${path}.executionPrompt`); |
| 324 | const fallback = normalizeFallback(raw['fallback'], `${path}.fallback`); |
| 325 | const toolPolicy = optionalNonEmptyString(raw['tool_policy'], `${path}.tool_policy`); |
| 326 | if (provider !== undefined && model === undefined) { |
| 327 | throw new Error(`profile member "${name}" sets provider without model`); |
| 328 | } |
| 329 | return omitUndefined({ name, role, provider, model, reasoningEffort, executionPrompt, fallback, toolPolicy }); |
| 330 | } |
| 331 | function normalizeFallback(value, path) { |
| 332 | if (value === undefined) |
| 333 | return undefined; |
| 334 | const raw = asRecord(value, path); |
| 335 | assertAllowedKeys(raw, FALLBACK_KEYS, path); |
| 336 | const provider = requiredNonEmptyString(raw['provider'], `${path}.provider`, `${path}.provider must not be empty`); |
| 337 | const model = requiredNonEmptyString(raw['model'], `${path}.model`, `${path}.model must not be empty`); |
| 338 | return { provider, model }; |
| 339 | } |
| 340 | function normalizeTask(value, path, profileName, sourceIndex, memberByName, memberByKey, requireAssignee) { |
| 341 | const raw = asRecord(value, path); |
| 342 | assertAllowedKeys(raw, TASK_KEYS, path); |
| 343 | const id = requiredNonEmptyString(raw['id'], `${path}.id`, `profile "${profileName}" has a task with an empty id`); |
| 344 | const subject = requiredNonEmptyString(raw['subject'], `${path}.subject`, `profile task "${id}" is missing a subject`); |
| 345 | const description = optionalNonEmptyString(raw['description'], `${path}.description`); |
| 346 | const dependencies = normalizeDependencies(raw['dependencies'], `${path}.dependencies`, id); |
| 347 | const assignee = resolveTaskAssignee(raw['assignee'], `${path}.assignee`, id, requireAssignee, memberByName, memberByKey); |
| 348 | return omitUndefined({ |
| 349 | id, |
| 350 | subject, |
| 351 | description, |
| 352 | assignee, |
| 353 | dependencies, |
| 354 | sourceIndex, |
| 355 | }); |
| 356 | } |
| 357 | function normalizeDependencies(value, path, taskId) { |
| 358 | if (value === undefined) |
| 359 | return []; |
| 360 | if (!Array.isArray(value)) { |
| 361 | throw new Error(`${path} must be an array of task ids`); |
| 362 | } |
| 363 | const dependencies = []; |
| 364 | const seen = new Set(); |
| 365 | for (let index = 0; index < value.length; index += 1) { |
| 366 | const item = value[index]; |
| 367 | if (typeof item !== 'string') { |
| 368 | throw new Error(`${path}[${index}] must be a string`); |
| 369 | } |
| 370 | const dependency = item.trim(); |
| 371 | if (dependency === '') { |
| 372 | throw new Error(`${path}[${index}] must not be empty`); |
| 373 | } |
| 374 | if (dependency === taskId) { |
| 375 | throw new Error(`profile task "${taskId}" cannot depend on itself`); |
| 376 | } |
| 377 | if (seen.has(dependency)) |
| 378 | continue; |
| 379 | seen.add(dependency); |
| 380 | dependencies.push(dependency); |
| 381 | } |
| 382 | return dependencies; |
| 383 | } |
| 384 | function resolveTaskAssignee(value, path, taskId, required, memberByName, memberByKey) { |
| 385 | if (value === undefined) { |
| 386 | if (required) { |
| 387 | throw new Error(`profile task "${taskId}" is missing an assignee`); |
| 388 | } |
| 389 | return undefined; |
| 390 | } |
| 391 | if (typeof value !== 'string') { |
| 392 | throw new Error(`${path} must be a string`); |
| 393 | } |
| 394 | const trimmed = value.trim(); |
| 395 | if (trimmed === '') { |
| 396 | throw new Error(`profile task "${taskId}" is missing an assignee`); |
| 397 | } |
| 398 | if (isCaptainName(trimmed)) { |
| 399 | throw new Error(`profile task "${taskId}" cannot assign work to the captain`); |
| 400 | } |
| 401 | const exact = memberByName.get(trimmed); |
| 402 | if (exact !== undefined) |
| 403 | return exact.name; |
| 404 | const fuzzy = memberByKey.get(sanitizeKey(trimmed)); |
| 405 | if (fuzzy !== undefined) |
| 406 | return fuzzy.name; |
| 407 | throw new Error(`profile task "${taskId}" assignee "${trimmed}" is not a profile member`); |
| 408 | } |
| 409 | function topoSortTasks(tasks, profileName) { |
| 410 | const byId = new Map(tasks.map((task) => [task.id, task])); |
| 411 | for (const task of tasks) { |
| 412 | for (const dependency of task.dependencies) { |
| 413 | if (!byId.has(dependency)) { |
| 414 | throw new Error(`profile task "${task.id}" depends on unknown task "${dependency}"`); |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | const indegree = new Map(); |
| 419 | const outgoing = new Map(); |
| 420 | for (const task of tasks) { |
| 421 | indegree.set(task.id, 0); |
| 422 | outgoing.set(task.id, []); |
| 423 | } |
| 424 | for (const task of tasks) { |
| 425 | for (const dependency of task.dependencies) { |
| 426 | indegree.set(task.id, (indegree.get(task.id) ?? 0) + 1); |
| 427 | outgoing.get(dependency)?.push(task.id); |
| 428 | } |
| 429 | } |
| 430 | const ready = tasks |
| 431 | .filter((task) => (indegree.get(task.id) ?? 0) === 0) |
| 432 | .sort((left, right) => left.sourceIndex - right.sourceIndex); |
| 433 | const ordered = []; |
| 434 | while (ready.length > 0) { |
| 435 | const next = ready.shift(); |
| 436 | if (next === undefined) |
| 437 | break; |
| 438 | ordered.push(next); |
| 439 | for (const childId of outgoing.get(next.id) ?? []) { |
| 440 | const remaining = (indegree.get(childId) ?? 0) - 1; |
| 441 | indegree.set(childId, remaining); |
| 442 | if (remaining === 0) { |
| 443 | const child = byId.get(childId); |
| 444 | if (child === undefined) |
| 445 | continue; |
| 446 | ready.push(child); |
| 447 | ready.sort((left, right) => left.sourceIndex - right.sourceIndex); |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | if (ordered.length !== tasks.length) { |
| 452 | const cyclic = tasks |
| 453 | .filter((task) => !ordered.some((done) => done.id === task.id)) |
| 454 | .map((task) => task.id); |
| 455 | throw new Error(formatCycleError(profileName, cyclic)); |
| 456 | } |
| 457 | return ordered; |
| 458 | } |
| 459 | function formatCycleError(_profileName, cyclic) { |
| 460 | const first = cyclic[0] ?? 'unknown'; |
| 461 | const second = cyclic[1]; |
| 462 | if (cyclic.length === 1 || second === undefined) { |
| 463 | return `profile task "${first}" forms a dependency cycle`; |
| 464 | } |
| 465 | if (cyclic.length === 2) { |
| 466 | return `profile task "${first}" and "${second}" form a dependency cycle`; |
| 467 | } |
| 468 | const head = cyclic.slice(0, -1).map((id) => `"${id}"`).join(', '); |
| 469 | const tail = cyclic[cyclic.length - 1] ?? first; |
| 470 | return `profile tasks ${head}, and "${tail}" form a dependency cycle`; |
| 471 | } |
| 472 | function isCaptainName(name) { |
| 473 | return name.trim().toLowerCase() === CAPTAIN_KEY || sanitizeKey(name) === CAPTAIN_KEY; |
| 474 | } |
| 475 | function asProfilesRecord(profiles) { |
| 476 | if (profiles === undefined || profiles === null) |
| 477 | return {}; |
| 478 | if (typeof profiles !== 'object' || Array.isArray(profiles)) { |
| 479 | throw new Error('AgentTeams profiles must be an object map of named templates'); |
| 480 | } |
| 481 | return profiles; |
| 482 | } |
| 483 | function asRecord(value, path) { |
| 484 | if (typeof value !== 'object' || value === null || Array.isArray(value)) { |
| 485 | throw new Error(`${path} must be an object`); |
| 486 | } |
| 487 | return value; |
| 488 | } |
| 489 | function assertAllowedKeys(value, allowed, path) { |
| 490 | const allow = new Set(allowed); |
| 491 | for (const key of Object.keys(value)) { |
| 492 | if (allow.has(key)) |
| 493 | continue; |
| 494 | const suggestion = suggestField(key, allowed); |
| 495 | const hint = suggestion === undefined ? '' : `; did you mean ${suggestion}?`; |
| 496 | throw new Error(`${path}.${key} is unknown${hint}`); |
| 497 | } |
| 498 | } |
| 499 | function suggestField(unknown, allowed) { |
| 500 | const lower = unknown.toLowerCase(); |
| 501 | const exact = allowed.find((candidate) => candidate.toLowerCase() === lower); |
| 502 | if (exact !== undefined) |
| 503 | return exact; |
| 504 | let best; |
| 505 | let bestDistance = Infinity; |
| 506 | for (const candidate of allowed) { |
| 507 | const distance = levenshtein(lower, candidate.toLowerCase()); |
| 508 | if (distance < bestDistance) { |
| 509 | bestDistance = distance; |
| 510 | best = candidate; |
| 511 | } |
| 512 | } |
| 513 | if (best !== undefined && bestDistance <= 2) |
| 514 | return best; |
| 515 | return undefined; |
| 516 | } |
| 517 | function levenshtein(left, right) { |
| 518 | const rows = left.length + 1; |
| 519 | const cols = right.length + 1; |
| 520 | const grid = []; |
| 521 | for (let row = 0; row < rows; row += 1) { |
| 522 | const line = []; |
| 523 | for (let col = 0; col < cols; col += 1) { |
| 524 | if (row === 0) |
| 525 | line.push(col); |
| 526 | else if (col === 0) |
| 527 | line.push(row); |
| 528 | else |
| 529 | line.push(0); |
| 530 | } |
| 531 | grid.push(line); |
| 532 | } |
| 533 | for (let row = 1; row < rows; row += 1) { |
| 534 | for (let col = 1; col < cols; col += 1) { |
| 535 | const cost = left[row - 1] === right[col - 1] ? 0 : 1; |
| 536 | const del = (grid[row - 1]?.[col] ?? 0) + 1; |
| 537 | const ins = (grid[row]?.[col - 1] ?? 0) + 1; |
| 538 | const sub = (grid[row - 1]?.[col - 1] ?? 0) + cost; |
| 539 | const cell = grid[row]; |
| 540 | if (cell !== undefined) |
| 541 | cell[col] = Math.min(del, ins, sub); |
| 542 | } |
| 543 | } |
| 544 | return grid[left.length]?.[right.length] ?? 0; |
| 545 | } |
| 546 | function requiredNonEmptyString(value, path, emptyMessage) { |
| 547 | if (value === undefined || typeof value !== 'string') { |
| 548 | throw new Error(`${path} must be a string`); |
| 549 | } |
| 550 | const trimmed = value.trim(); |
| 551 | if (trimmed === '') |
| 552 | throw new Error(emptyMessage); |
| 553 | return trimmed; |
| 554 | } |
| 555 | function optionalNonEmptyString(value, path) { |
| 556 | if (value === undefined) |
| 557 | return undefined; |
| 558 | if (typeof value !== 'string') { |
| 559 | throw new Error(`${path} must be a string`); |
| 560 | } |
| 561 | const trimmed = value.trim(); |
| 562 | if (trimmed === '') { |
| 563 | throw new Error(`${path} must not be empty`); |
| 564 | } |
| 565 | return trimmed; |
| 566 | } |
| 567 | function omitUndefined(value) { |
| 568 | for (const key of Object.keys(value)) { |
| 569 | if (value[key] === undefined) |
| 570 | delete value[key]; |
| 571 | } |
| 572 | return value; |
| 573 | } |
| 574 |