UNPKG

akm-cli

Version:

akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur

366 lines (365 loc) • 16.2 kB
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. /** * Experimental: the `steps:` dispatch arm. Runs the prepared steps in order, * stops at the first failure, and records every step in the run's history row * (`metadata_json.steps`). A shell step runs like a `run:` task; a prompt step * dispatches like a command task; a `task:` step runs another task through the * injected `taskStepRunner`. * * Values: every step sees the run's inputs as `AKM_PARAMS` and the earlier * steps' results as `AKM_STEPS` (JSON keyed by step name). `AKM_INPUTS` is * never set. A prompt step has no child env on a direct-model connection, so * the same two values are appended to its prompt as text. */ import { dispatchPreparedCommandInvocation } from "../../commands/command/command-execution.js"; import { isRecord } from "../../core/common.js"; import { UsageError } from "../../core/errors.js"; import { childProcessEnv } from "../../core/paths.js"; import { runManagedSubprocess } from "../../core/subprocess.js"; import { sortExecutionJson } from "../../execution/json.js"; import { isRefused, jsonParser, structuredLoop } from "../../llm/structured.js"; import { abortOnTermination, finishAttempt } from "./attempt-lifecycle.js"; import { taskProcessEnv } from "./provenance.js"; import { withUnattendedTimeout } from "./run-command-task.js"; import { shellCommand } from "./run-native-task.js"; import { DEFAULT_SCHEDULED_TASK_TIMEOUT_MS } from "./run-workflow-task.js"; import { appendHistory, readTaskHistory, taskBundle } from "./task-history.js"; import { appendStreamLines, persistRunLog, processFailure, scrubTaskOutput } from "./task-log.js"; /** A step's result is kept to this many bytes of text. */ export const STEP_RESULT_MAX_BYTES = 32 * 1024; /** A `run:` step's stdout is read up to this many bytes; the result keeps a prefix. */ const STEP_CAPTURE_MAX_BYTES = 64 * 1024; /** The serialized `AKM_STEPS` handed to a step may not exceed this. */ export const STEPS_CONTEXT_MAX_BYTES = 96 * 1024; function bound(text) { const bytes = Buffer.byteLength(text); if (bytes <= STEP_RESULT_MAX_BYTES) return text; return `${Buffer.from(text).subarray(0, STEP_RESULT_MAX_BYTES).toString("utf8")}\n[truncated ${bytes - STEP_RESULT_MAX_BYTES} bytes]`; } function stepKind(step) { return step.kind === "shell" ? "run" : step.kind === "command" ? "prompt" : "task"; } /** * `--resume`: the leading steps of this task's latest run that completed (or * were themselves reused), with their stored results. Runs before the new * attempt is reserved, so the latest history row is the previous run. */ export function resolveResume(task) { const previous = readTaskHistory({ id: task.taskId, limit: 1 })[0]; if (!previous || previous.status !== "failed" || !previous.steps) { throw new UsageError(`Task ${JSON.stringify(task.taskId)} has no failed steps run to resume. Run it without --resume.`, "INVALID_FLAG_VALUE"); } const names = task.steps.map((step) => `${step.name}:${stepKind(step)}`); const before = previous.steps.map((step) => `${step.name}:${step.kind}`); if (names.length !== before.length || names.some((entry, index) => entry !== before[index])) { throw new UsageError(`Task ${JSON.stringify(task.taskId)} changed its steps since the failed run. Run it without --resume.`, "INVALID_FLAG_VALUE"); } const reused = []; for (const step of previous.steps) { if ((step.status !== "completed" && step.status !== "reused") || step.result === undefined) break; reused.push(step); } return { restart: reused.length, reused }; } function jsonBlock(label, value) { return `## ${label}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``; } /** The prompt with the run's values and earlier results appended as text, plus any correction. */ function promptContent(content, params, stepValues, correction) { const parts = [content]; if (Object.keys(params).length > 0) parts.push(jsonBlock("Task values", params)); if (Object.keys(stepValues).length > 0) parts.push(jsonBlock("Earlier steps", stepValues)); if (correction) parts.push(correction.text); return parts.join("\n\n"); } function replyCheck(expect) { return jsonParser((candidate) => { if (!isRecord(candidate)) { return { ok: false, errors: ["the reply is not a JSON object"], reason: "validation_error" }; } const missing = expect.filter((key) => candidate[key] === undefined); return missing.length === 0 ? { ok: true, value: candidate } : { ok: false, errors: [`the reply lacks: ${missing.join(", ")}`], reason: "validation_error" }; }); } /** An agent's reply held to `expect:`: asked once more, with what failed the check, when it does. */ export function expectLoop(expect, dispatch) { return structuredLoop({ dispatch, parse: replyCheck(expect), attempts: 2, correct: (refusal) => `Your previous reply failed the check: ${refusal.errors.join("; ")}. ` + `Reply again with ONLY a JSON object containing the keys: ${expect.join(", ")}.`, }); } export async function runStepsTask(input) { const { task, logPath, startedAt, now, provenance, options } = input; const params = task.params; const paramsJson = JSON.stringify(sortExecutionJson(params)); const lines = [`[akm task] task=${task.taskId} kind=steps steps=${task.steps.length}`]; const dbLines = [{ line: lines[0] }]; const records = []; const values = {}; const stored = new Map(); for (const step of input.resume?.reused ?? []) { const result = step.result; const planned = task.steps[records.length]; values[step.name] = planned?.kind === "command" && planned.expect ? safeParseObject(result) : result; stored.set(step.name, result); records.push({ ...step, status: "reused", durationMs: 0, attempts: 0 }); } const { abort, stop } = abortOnTermination(); let failure; try { for (let index = records.length; index < task.steps.length; index++) { const step = task.steps[index]; if (failure) { records.push({ name: step.name, kind: stepKind(step), status: "skipped", durationMs: 0, attempts: 0 }); continue; } const stepsJson = JSON.stringify(values); let outcome = { ok: false, reason: "not run", lines: [], dbLines: [] }; let attempts = 0; const begun = now(); for (let attempt = 0; attempt <= step.retries; attempt++) { attempts += 1; if (Buffer.byteLength(stepsJson) > STEPS_CONTEXT_MAX_BYTES) { outcome = { ok: false, reason: `earlier step results total over ${STEPS_CONTEXT_MAX_BYTES} bytes (AKM_STEPS limit)`, lines: [], dbLines: [], }; break; } outcome = await runStep(step, { task, options, provenance, paramsJson, stepsJson, values, abort }); if (outcome.ok || abort.signal.aborted) break; } const durationMs = Math.max(0, now().getTime() - begun.getTime()); const header = `[akm task] step=${step.name} kind=${stepKind(step)} attempts=${attempts} ok=${outcome.ok}`; // Loops, not spreads: a step can print more lines than a call accepts as arguments. lines.push(header); for (const line of outcome.lines) lines.push(line); dbLines.push({ level: outcome.ok ? "info" : "error", line: header }); for (const row of outcome.dbLines) dbLines.push(row); const text = outcome.value === undefined ? "" : typeof outcome.value === "string" ? outcome.value : JSON.stringify(outcome.value); const record = { name: step.name, kind: stepKind(step), status: outcome.ok ? "completed" : "failed", durationMs, attempts, ...(!outcome.ok && outcome.reason ? { reason: scrubTaskOutput(task, outcome.reason) } : {}), ...(outcome.startedAt ? { startedAt: outcome.startedAt } : {}), }; if (outcome.ok) { values[step.name] = outcome.value ?? ""; stored.set(step.name, text); } else { failure = { name: step.name, reason: record.reason ?? "failed" }; } records.push(record); } } finally { stop(); } const finishedAt = finishAttempt(startedAt, now()); persistRunLog({ taskId: task.taskId, startedAtIso: startedAt.toISOString(), finishedAtIso: finishedAt.toISOString(), logPath, fileText: `${lines.join("\n")}\n`, dbLines, redactNames: task.redact, environment: task.environment, }); // The bounded results are kept only for a failed run, where `--resume` reuses them. const steps = records.map((record) => failure && (record.status === "completed" || record.status === "reused") && stored.has(record.name) ? { ...record, result: scrubTaskOutput(task, stored.get(record.name)) } : stripResult(record)); const result = { id: task.taskId, status: failure ? "failed" : "completed", startedAt: startedAt.toISOString(), finishedAt: finishedAt.toISOString(), durationMs: finishedAt.getTime() - startedAt.getTime(), log: logPath, ...taskBundle(task.taskRef), target: { kind: "steps" }, ...(failure ? { detail: { reason: "step_failed", error: `${failure.name}: ${failure.reason}` } } : {}), steps, }; appendHistory(result, input.historyReserved, provenance.scheduled); return result; } function stripResult(record) { const { result: _result, ...rest } = record; return rest; } function safeParseObject(text) { try { const parsed = JSON.parse(text); return isRecord(parsed) ? parsed : text; } catch { return text; } } async function runStep(step, ctx) { if (step.kind === "shell") return runShellStep(step, ctx); if (step.kind === "command") return runPromptStep(step, ctx); return runTaskStep(step, ctx); } async function runShellStep(step, ctx) { const { options, provenance } = ctx; const env = { ...childProcessEnv(), ...step.environment, ...taskProcessEnv(process.env, provenance, ctx.task.taskRef), AKM_PARAMS: ctx.paramsJson, AKM_STEPS: ctx.stepsJson, }; // A step reads AKM_STEPS; the retired AKM_INPUTS must stay unset so a script still reading it fails. delete env.AKM_INPUTS; const timeoutMs = step.timeoutMs !== undefined ? step.timeoutMs : DEFAULT_SCHEDULED_TASK_TIMEOUT_MS; const result = await runManagedSubprocess(shellCommand(step), { capture: true, cwd: step.cwd, env, windowsVerbatimArguments: step.shell === "cmd", timeoutMs, maxOutputBytes: STEP_CAPTURE_MAX_BYTES, signal: ctx.abort.signal, ...(options.spawnFn ? { spawnFn: options.spawnFn } : {}), ...(options.setTimeoutFn ? { setTimeoutFn: options.setTimeoutFn } : {}), ...(options.clearTimeoutFn ? { clearTimeoutFn: options.clearTimeoutFn } : {}), }); const out = { ok: false, lines: [], dbLines: [] }; if (result.spawnError) { const { reason, error } = processFailure(result); out.reason = `${reason}: ${error}`; out.lines.push(`spawn_error=${error}`); out.dbLines.push({ level: "error", line: `spawn_error=${error}` }); return out; } const exitCode = result.exitCode ?? (result.timedOut ? 143 : 1); out.lines.push(`exit_code=${exitCode}`); out.dbLines.push({ level: exitCode === 0 ? "info" : "error", line: `exit_code=${exitCode}` }); if (result.timedOut) { out.lines.push(`timed_out=true timeout_ms=${timeoutMs}`); out.dbLines.push({ level: "error", line: `timed_out=true timeout_ms=${timeoutMs}` }); } if (result.stdout) { out.lines.push("--- stdout ---", result.stdout); appendStreamLines(out.dbLines, result.stdout, "stdout", "info"); } if (result.stderr) { out.lines.push("--- stderr ---", result.stderr); appendStreamLines(out.dbLines, result.stderr, "stderr", "error"); } if (result.timedOut || result.aborted || exitCode !== 0) { const { reason, error } = processFailure({ ...result, exitCode }); out.reason = reason === "non_zero_exit" ? `${reason}: ${error}` : reason; } else { out.ok = true; out.value = bound(result.stdout); } return out; } async function runPromptStep(step, ctx) { const params = ctx.task.params; const invocation = withUnattendedTimeout(step.invocation); const out = { ok: false, lines: [], dbLines: [] }; const dispatch = async (correction) => { const content = promptContent(invocation.request.command.content, params, ctx.values, correction); const rebuilt = { ...invocation, request: { ...invocation.request, command: { ...invocation.request.command, content } }, }; const result = await dispatchPreparedCommandInvocation(rebuilt, { ...(ctx.options.runAgentImpl ? { runAgent: ctx.options.runAgentImpl } : {}), eventSource: ctx.provenance.eventSource, env: { AKM_TASK_REF: ctx.task.taskRef }, signal: ctx.abort.signal, }); out.lines.push(`engine=${result.engine} ok=${result.ok} exit_code=${result.exitCode ?? "null"}`); if (result.stdout) { out.lines.push("--- agent stdout ---", result.stdout); appendStreamLines(out.dbLines, result.stdout, "stdout", "info"); } if (result.stderr) { out.lines.push("--- agent stderr ---", result.stderr); appendStreamLines(out.dbLines, result.stderr, "stderr", "error"); } return result.ok ? { ok: true, raw: result.stdout } : { ok: false, failure: result.reason ?? result.error ?? "dispatch failed" }; }; if (!step.expect) { const first = await dispatch(); if (!first.ok) out.reason = first.failure; else { out.ok = true; out.value = bound(first.raw); } return out; } const loop = await expectLoop(step.expect, dispatch); if (loop.ok) { out.ok = true; out.value = loop.value; } else if (isRefused(loop)) { out.reason = `reply_check_failed: ${loop.errors.join("; ")}`; } else { out.reason = loop.failure; } return out; } async function runTaskStep(step, ctx) { const runner = ctx.options.taskStepRunner; const out = { ok: false, lines: [], dbLines: [] }; if (!runner) { out.reason = "task steps need the CLI task runner"; return out; } try { const result = await runner.run(step.ref); out.startedAt = result.startedAt; out.lines.push(`task=${step.ref} status=${result.status} started_at=${result.startedAt}`); if (result.status === "completed") { out.ok = true; out.value = ""; } else { out.reason = `task ${step.ref} ${result.status}${result.detail?.error ? `: ${result.detail.error}` : ""}`; } } catch (error) { out.reason = `task ${step.ref} could not run: ${error instanceof Error ? error.message : String(error)}`; } return out; }