anchor-ai-sdk 0.8.11 → 0.8.13

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.
Files changed (51) hide show
  1. package/README.md +45 -1
  2. package/dist/agents/index.d.ts +1 -0
  3. package/dist/agents/index.d.ts.map +1 -1
  4. package/dist/agents/index.js +1 -0
  5. package/dist/agents/index.js.map +1 -1
  6. package/dist/agents/types.d.ts +20 -0
  7. package/dist/agents/types.d.ts.map +1 -1
  8. package/dist/agents/workflow/index.d.ts +49 -0
  9. package/dist/agents/workflow/index.d.ts.map +1 -0
  10. package/dist/agents/workflow/index.js +46 -0
  11. package/dist/agents/workflow/index.js.map +1 -0
  12. package/dist/agents/workflow/prompt.d.ts +11 -0
  13. package/dist/agents/workflow/prompt.d.ts.map +1 -0
  14. package/dist/agents/workflow/prompt.js +25 -0
  15. package/dist/agents/workflow/prompt.js.map +1 -0
  16. package/dist/engine/context.d.ts +9 -3
  17. package/dist/engine/context.d.ts.map +1 -1
  18. package/dist/engine/context.js +23 -3
  19. package/dist/engine/context.js.map +1 -1
  20. package/dist/engine/loop.d.ts.map +1 -1
  21. package/dist/engine/loop.js +163 -21
  22. package/dist/engine/loop.js.map +1 -1
  23. package/dist/engine/types.d.ts +15 -0
  24. package/dist/engine/types.d.ts.map +1 -1
  25. package/dist/engine/workflow.d.ts +74 -0
  26. package/dist/engine/workflow.d.ts.map +1 -0
  27. package/dist/engine/workflow.js +125 -0
  28. package/dist/engine/workflow.js.map +1 -0
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/llm/index.d.ts +2 -0
  34. package/dist/llm/index.d.ts.map +1 -1
  35. package/dist/llm/index.js +1 -0
  36. package/dist/llm/index.js.map +1 -1
  37. package/dist/llm/openai-compatible.d.ts +9 -1
  38. package/dist/llm/openai-compatible.d.ts.map +1 -1
  39. package/dist/llm/openai-compatible.js +53 -2
  40. package/dist/llm/openai-compatible.js.map +1 -1
  41. package/dist/llm/types.d.ts +25 -0
  42. package/dist/llm/types.d.ts.map +1 -1
  43. package/dist/schema.d.ts +64 -0
  44. package/dist/schema.d.ts.map +1 -0
  45. package/dist/schema.js +166 -0
  46. package/dist/schema.js.map +1 -0
  47. package/dist/tools/finish.d.ts +15 -0
  48. package/dist/tools/finish.d.ts.map +1 -1
  49. package/dist/tools/finish.js +39 -12
  50. package/dist/tools/finish.js.map +1 -1
  51. package/package.json +1 -1
@@ -1,5 +1,7 @@
1
1
  import { createFinishTool } from "../tools/finish.js";
2
2
  import { validateRepos } from "../repo.js";
3
+ import { jsonSchemaOf, validateOutput } from "../schema.js";
4
+ import { checkEvidence, checkRejection, WORKFLOW_KICKOFF, workflowProseRejection, } from "./workflow.js";
3
5
  import { BudgetTracker, DEFAULT_BUDGET_LIMITS, DEFAULT_CHILD_SOFT_CAP, DEFAULT_MAX_OUTPUT_TOKENS, } from "./budgets.js";
4
6
  import { DEFAULT_TRUNCATED_REPLY_CHARS, DEFAULT_MAX_ASSISTANT_CHARS, elideReply, spillReply, } from "./elision.js";
5
7
  import { compactConversation, compactConversationStructured, DEFAULT_COMPACTION, estimateTokens, renderCompactionHandoff, } from "./compaction.js";
@@ -221,14 +223,80 @@ async function runOne(input, opts, chain = {}) {
221
223
  let completionGate;
222
224
  let verified = false;
223
225
  let finishGateAttempts = 0;
226
+ // A workflow bundle's contract (engine/workflow.ts). Its finish is required,
227
+ // gated on the check having passed in THIS run's own tool log, and carries a
228
+ // schema-validated output. Absent: every path below is today's behavior.
229
+ const workflow = opts.agent?.workflow;
230
+ const workflowLog = [];
231
+ let workflowOutput;
232
+ const workflowGate = (contract, output) => {
233
+ const problems = [];
234
+ const observed = checkEvidence(workflowLog, contract.check.command);
235
+ if (observed.status !== "passed")
236
+ problems.push(checkRejection(contract, observed));
237
+ let parsed;
238
+ if (contract.output) {
239
+ const name = contract.output.name;
240
+ if (output === undefined) {
241
+ problems.push(`finish rejected: \`output\` (${name}) is required — pass it on finish.`);
242
+ }
243
+ else {
244
+ const verdict = validateOutput(contract.output.schema, output);
245
+ if (verdict.ok)
246
+ parsed = { value: verdict.value };
247
+ else
248
+ problems.push(`finish rejected: \`output\` (${name}) does not match its schema — ${verdict.error}. Fix it and call finish again.`);
249
+ }
250
+ }
251
+ if (problems.length) {
252
+ const content = problems.join("\n\n");
253
+ emit({ type: "guardrail", kind: "finish_rejected", detail: content.slice(0, 500) });
254
+ return { ok: false, content };
255
+ }
256
+ return { ok: true, ...(parsed ? { parsed } : {}) };
257
+ };
224
258
  const finish = createFinishTool({
225
259
  ...(opts.handoff ? { handoff: opts.handoff } : {}),
226
- validate: async (input) => completionGate
227
- ? completionGate(input.summary, input.success)
228
- : { ok: true },
260
+ ...(workflow ? { required: true } : {}),
261
+ ...(workflow?.output
262
+ ? {
263
+ output: {
264
+ name: workflow.output.name,
265
+ schema: jsonSchemaOf(workflow.output.schema, workflow.output.jsonSchema),
266
+ ...(workflow.output.description
267
+ ? { description: workflow.output.description }
268
+ : {}),
269
+ },
270
+ }
271
+ : {}),
272
+ validate: async (input) => {
273
+ if (!workflow)
274
+ return completionGate
275
+ ? completionGate(input.summary, input.success)
276
+ : { ok: true };
277
+ const gate = workflowGate(workflow, input.output);
278
+ if (!gate.ok)
279
+ return gate;
280
+ const verdict = completionGate
281
+ ? await completionGate(input.summary, input.success)
282
+ : { ok: true };
283
+ if (verdict.ok && gate.parsed)
284
+ workflowOutput = gate.parsed;
285
+ return verdict;
286
+ },
229
287
  });
230
288
  if (opts.intrinsics?.finish !== false)
231
289
  available.set("finish", finish);
290
+ if (workflow) {
291
+ // A workflow never talks to anyone: finish is its only exit, nobody will
292
+ // answer a question, and nobody steers it from outside.
293
+ if (opts.intrinsics?.finish === false)
294
+ throw new Error(`workflow "${opts.agent?.name}" ends only through finish — intrinsics.finish cannot be false`);
295
+ if (available.has("ask_questions"))
296
+ throw new Error(`workflow "${opts.agent?.name}" cannot have ask_questions — no one answers a workflow's questions`);
297
+ if (chain.steer)
298
+ throw new Error(`workflow "${opts.agent?.name}" cannot run as a delegated team member — workflow runs are not steerable`);
299
+ }
232
300
  const missing = (strategy.requiredTools ?? []).filter((name) => !available.has(name));
233
301
  if (missing.length)
234
302
  throw new Error(`strategy "${strategy.name}" requires tools that were not supplied: ${missing.join(", ")}`);
@@ -262,7 +330,7 @@ async function runOne(input, opts, chain = {}) {
262
330
  phase = prior.phase;
263
331
  let summary = prior?.summary;
264
332
  let compaction = prior?.compaction;
265
- const budget = chain.budget ?? new BudgetTracker(opts.budgets);
333
+ const budget = chain.budget ?? new BudgetTracker(resolveBudgets(opts));
266
334
  const cancelGraceMs = opts.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
267
335
  const stallAfterMs = opts.stallAfterMs === false
268
336
  ? false
@@ -712,7 +780,11 @@ async function runOne(input, opts, chain = {}) {
712
780
  budget.record(compiled.usage);
713
781
  attachLedger(compiled.ledger);
714
782
  }
715
- const currentRequests = input.messages;
783
+ // The brief lives in the workflow's system prompt; a caller with no per-run
784
+ // facts to add may pass no messages, and the run still opens on a user turn.
785
+ const currentRequests = workflow && !input.messages.some((message) => message.role === "user")
786
+ ? [...input.messages, { role: "user", content: WORKFLOW_KICKOFF }]
787
+ : input.messages;
716
788
  const revivalOn = !!opts.revival;
717
789
  const revivalWarnAt = revivalWarnPercent(opts.revival ? opts.revival.warnAtPercent : undefined);
718
790
  let revivalWarned = false;
@@ -785,10 +857,12 @@ async function runOne(input, opts, chain = {}) {
785
857
  return out;
786
858
  const turn = turnState();
787
859
  if (turn) {
788
- // Keep the turn's final message last (tests and tool protocol both rely
789
- // on it); put the changing runtime state immediately before it so the
790
- // stable prefix is still reused.
791
- const insertAt = Math.max(1, out.length - 1);
860
+ // Tool results must directly follow the assistant turn that called
861
+ // them, so after a tool run the state goes last. A trailing user
862
+ // request (or nudge) stays last, with the state just before it. Either
863
+ // way the previous request is a prefix of this one up to the old block.
864
+ const last = out[out.length - 1];
865
+ const insertAt = last?.role === "user" ? Math.max(1, out.length - 1) : out.length;
792
866
  out.splice(insertAt, 0, {
793
867
  role: "user",
794
868
  content: turn,
@@ -841,9 +915,11 @@ async function runOne(input, opts, chain = {}) {
841
915
  return value;
842
916
  };
843
917
  const threshold = (name, value) => value === false ? false : positiveNumber(name, value);
844
- const repeatLimit = threshold("guardrails.repeatedToolCallLimit", opts.guardrails?.repeatedToolCallLimit ?? 3);
845
- const toolOnlyNudge = threshold("guardrails.toolOnlyNudgeLimit", opts.guardrails?.toolOnlyNudgeLimit ?? 8);
846
- const verboseTurnLimit = threshold("guardrails.verboseTurnLimit", opts.guardrails?.verboseTurnLimit ?? 8_000);
918
+ // The bundle may suggest guardrails; an explicit field wins, like budgets.
919
+ const guardrails = mergeDefined(opts.agent?.guardrails, opts.guardrails);
920
+ const repeatLimit = threshold("guardrails.repeatedToolCallLimit", guardrails.repeatedToolCallLimit ?? 3);
921
+ const toolOnlyNudge = threshold("guardrails.toolOnlyNudgeLimit", guardrails.toolOnlyNudgeLimit ?? 8);
922
+ const verboseTurnLimit = threshold("guardrails.verboseTurnLimit", guardrails.verboseTurnLimit ?? 8_000);
847
923
  const repeat = new RepeatTracker(repeatLimit);
848
924
  let verboseNudged = false;
849
925
  // Per-call output cap. The agent bundle may suggest one; an explicit engine
@@ -988,7 +1064,7 @@ async function runOne(input, opts, chain = {}) {
988
1064
  let softCapNudged = false;
989
1065
  /** Files the child has named in its tool calls, for progress. */
990
1066
  const touchedFiles = new Set();
991
- const proseCheckpoint = opts.guardrails?.proseCheckpoint ?? true;
1067
+ const proseCheckpoint = guardrails.proseCheckpoint ?? true;
992
1068
  // The shared mechanic lives in guardrails.ts; the policy (when a correction
993
1069
  // fires, and when it stops) stays here.
994
1070
  const courseCorrect = createCourseCorrect({
@@ -1504,6 +1580,17 @@ async function runOne(input, opts, chain = {}) {
1504
1580
  */
1505
1581
  const absorbJobs = async (finished, lost) => {
1506
1582
  for (const job of finished) {
1583
+ // A detached check that completed is still the engine's own observation.
1584
+ if (workflow && job.job.command !== undefined)
1585
+ workflowLog.push({
1586
+ tool: job.job.tool,
1587
+ ok: job.result.exitCode === 0 && !job.result.timedOut,
1588
+ meta: {
1589
+ command: job.job.command,
1590
+ exitCode: job.result.exitCode,
1591
+ timedOut: job.result.timedOut,
1592
+ },
1593
+ });
1507
1594
  messages.push({
1508
1595
  role: "user",
1509
1596
  // `runtime`, not `engine`: a job result is a fact, so it survives in
@@ -1704,6 +1791,12 @@ async function runOne(input, opts, chain = {}) {
1704
1791
  kind: "budget_exceeded",
1705
1792
  detail: over.detail,
1706
1793
  });
1794
+ // A workflow's budget is a hard stop and a failure: no partial success.
1795
+ if (workflow)
1796
+ return conclude("budget_exhausted", {
1797
+ ok: false,
1798
+ error: `workflow budget exhausted: ${over.detail}`,
1799
+ });
1707
1800
  // A child out of its OWN budget hands back what it has. The leader's
1708
1801
  // run continues; a worker hitting its cap is not the leader's failure.
1709
1802
  if (chain.child) {
@@ -1822,9 +1915,11 @@ async function runOne(input, opts, chain = {}) {
1822
1915
  // Compaction itself consumes budget; check again before inference.
1823
1916
  const after = budget.exceeded(stepsBefore + steps);
1824
1917
  if (after)
1825
- return conclude("budget_exceeded", {
1918
+ return conclude(workflow ? "budget_exhausted" : "budget_exceeded", {
1826
1919
  ok: false,
1827
- error: after.detail,
1920
+ error: workflow
1921
+ ? `workflow budget exhausted: ${after.detail}`
1922
+ : after.detail,
1828
1923
  });
1829
1924
  }
1830
1925
  }
@@ -1886,7 +1981,7 @@ async function runOne(input, opts, chain = {}) {
1886
1981
  `was still writing, is incomplete`,
1887
1982
  });
1888
1983
  }
1889
- const assistantTurn = assistantMessage(response);
1984
+ const assistantTurn = assistantMessage(response, opts.llm.reasoningPassback ?? false);
1890
1985
  messages.push(assistantTurn);
1891
1986
  // The model's own words get a boundary too (#77). A runaway reply is
1892
1987
  // replayed bounded while the transcript and the event stream keep it
@@ -1943,7 +2038,9 @@ async function runOne(input, opts, chain = {}) {
1943
2038
  // one runtime message and take the next turn. Once per run; a second
1944
2039
  // capped prose turn stalls, so this cannot loop.
1945
2040
  if (outputCapped) {
1946
- if (!outputCapContinued && proseCheckpoint) {
2041
+ // Turn lifecycle, not conversation: a workflow keeps it even with
2042
+ // the prose checkpoint off.
2043
+ if (!outputCapContinued && (proseCheckpoint || workflow)) {
1947
2044
  outputCapContinued = true;
1948
2045
  await courseCorrect({
1949
2046
  kind: "output_cap_continue",
@@ -1959,6 +2056,22 @@ async function runOne(input, opts, chain = {}) {
1959
2056
  `and returned no tool call — the reply is incomplete`,
1960
2057
  });
1961
2058
  }
2059
+ // A workflow has no reader: prose is never its result. Reject it like
2060
+ // any other ungated finish and keep going; the budget bounds this.
2061
+ if (workflow) {
2062
+ emit({
2063
+ type: "guardrail",
2064
+ kind: "finish_rejected",
2065
+ detail: `step ${steps} replied in prose without finish — a workflow ends only through its gated finish`,
2066
+ });
2067
+ messages.push({
2068
+ role: "user",
2069
+ origin: "engine",
2070
+ content: workflowProseRejection(workflow),
2071
+ });
2072
+ await persist();
2073
+ continue;
2074
+ }
1962
2075
  // The engine just asked for something visible, and the model answered
1963
2076
  // in prose and stopped. That is exactly the shape that cut a run off
1964
2077
  // mid-task (#78). Ask once whether the run is really over; the model
@@ -2026,6 +2139,12 @@ async function runOne(input, opts, chain = {}) {
2026
2139
  signal: toolSignal,
2027
2140
  pauseRequested: () => pauseRequested,
2028
2141
  onToolResult: (call, result) => {
2142
+ if (workflow)
2143
+ workflowLog.push({
2144
+ tool: call.name,
2145
+ ok: result.ok,
2146
+ ...(result.meta ? { meta: result.meta } : {}),
2147
+ });
2029
2148
  // Contract tools describe the ledger; they are not evidence about
2030
2149
  // the work and must not be recorded into the ledger they manage.
2031
2150
  if (!ledger || LEDGER_TOOL_NAMES.has(call.name)) {
@@ -2108,7 +2227,11 @@ async function runOne(input, opts, chain = {}) {
2108
2227
  // the model confirm; a second finish with nothing outstanding ends.
2109
2228
  if (await settleBeforeFinish())
2110
2229
  continue;
2111
- return conclude("finished", { ...declared, completion: "declared" });
2230
+ return conclude("finished", {
2231
+ ...declared,
2232
+ completion: "declared",
2233
+ ...(workflowOutput ? { output: workflowOutput.value } : {}),
2234
+ });
2112
2235
  }
2113
2236
  if (pauseRequested)
2114
2237
  return conclude("paused", {
@@ -2140,8 +2263,24 @@ async function runOne(input, opts, chain = {}) {
2140
2263
  return conclude("error", { ok: false, error });
2141
2264
  }
2142
2265
  }
2266
+ /**
2267
+ * Bundle defaults under explicit options, field by field. An explicit field
2268
+ * set to `undefined` does not erase the bundle's value.
2269
+ */
2270
+ function mergeDefined(defaults, explicit) {
2271
+ const merged = { ...defaults };
2272
+ for (const [key, value] of Object.entries(explicit ?? {})) {
2273
+ if (value !== undefined)
2274
+ merged[key] = value;
2275
+ }
2276
+ return merged;
2277
+ }
2278
+ /** The run's budget limits: the bundle's suggestion, then explicit options. */
2279
+ function resolveBudgets(opts) {
2280
+ return mergeDefined(opts.agent?.budgets, opts.budgets);
2281
+ }
2143
2282
  function seededBudget(opts, spend) {
2144
- const budget = new BudgetTracker(opts.budgets);
2283
+ const budget = new BudgetTracker(resolveBudgets(opts));
2145
2284
  budget.promptTokens = spend.promptTokens;
2146
2285
  budget.completionTokens = spend.completionTokens;
2147
2286
  budget.costUsd = spend.costUsd;
@@ -2222,7 +2361,7 @@ async function runChain(input, opts) {
2222
2361
  // A run normally spends at least one step, so the budget bounds the chain.
2223
2362
  // This counter only stops the one shape that spends nothing: an interjection
2224
2363
  // arriving before every single model call. No new public dial.
2225
- const maxZeroProgressRuns = Math.max(1, opts.budgets?.maxSteps ?? DEFAULT_BUDGET_LIMITS.maxSteps);
2364
+ const maxZeroProgressRuns = Math.max(1, resolveBudgets(opts).maxSteps ?? DEFAULT_BUDGET_LIMITS.maxSteps);
2226
2365
  let zeroProgressRuns = 0;
2227
2366
  const runs = [];
2228
2367
  let spend = {
@@ -2307,8 +2446,11 @@ async function runChain(input, opts) {
2307
2446
  return { ...result, runs };
2308
2447
  }
2309
2448
  export async function runAgent(input, opts) {
2310
- if (opts.inbox)
2449
+ if (opts.inbox) {
2450
+ if (opts.agent?.workflow)
2451
+ throw new Error(`anchor: workflow "${opts.agent.name}" is one-shot — EngineOptions.inbox (run chains and interjections) does not apply to a workflow agent`);
2311
2452
  return runChain(input, opts);
2453
+ }
2312
2454
  return runOne(input, opts);
2313
2455
  }
2314
2456
  //# sourceMappingURL=loop.js.map