Compare commits
164 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 025059bbc7 | |||
| bc732bb513 | |||
| 522786d21d | |||
| 84cc4c6e8d | |||
| f96b1014a2 | |||
| 3cafff8789 | |||
| 69e23eb1f6 | |||
| 1841599980 | |||
| 6f9994b3ea | |||
| 55070f1597 | |||
| b3940860b6 | |||
| 5c38a23fe4 | |||
| 9e7273dde1 | |||
| 42080b6d6d | |||
| c3df8b833d | |||
| 8694e3a20c | |||
| 9def03d4e3 | |||
| bd7625f947 | |||
| 0a547fbe17 | |||
| 331e3f32bd | |||
| 7db1d986ab | |||
| 6042a6c5f5 | |||
| bff916a3ac | |||
| b8c03dafa2 | |||
| 04bcef47ac | |||
| e92978f3eb | |||
| 695a24432a | |||
| 2889b98dcf | |||
| a356ab36a8 | |||
| 2078748e7f | |||
| d283f9b08b | |||
| af7b4f3d50 | |||
| 954f8fa79e | |||
| cdfe9c0947 | |||
| c645c5faa7 | |||
| 8bde01bdac | |||
| 1373ceec21 | |||
| 838b7f73f8 | |||
| c56423a33c | |||
| 6edc0de7bd | |||
| 3d31fe37db | |||
| 6840ae0fb1 | |||
| af61d6327a | |||
| 79d443839d | |||
| 5770a2f4cb | |||
| 9f1f0aa191 | |||
| 69ffee329e | |||
| d2c3c5e715 | |||
| 11f81f40fd | |||
| a057df54f5 | |||
| 0da1c739fb | |||
| 9ec9bf906c | |||
| cf790048ad | |||
| 11d1711619 | |||
| 7d464e8a32 | |||
| 8880168edd | |||
| 33b6ab5eea | |||
| 32d1683d0b | |||
| 917d60f9f8 | |||
| e41a80c92f | |||
| c25fe16260 | |||
| d240466d6d | |||
| 33a4af3984 | |||
| 274c3b2646 | |||
| 6b6100340b | |||
| 35b68b11f9 | |||
| 13d618ba66 | |||
| b60952cbfe | |||
| c13ff9fc98 | |||
| 6e010706ec | |||
| 75615e81ca | |||
| 097a4f6f9f | |||
| 898853d948 | |||
| 573e043cb1 | |||
| 76961d503a | |||
| f839ca7427 | |||
| fb1888efb7 | |||
| 5f3244d09e | |||
| 1e932321c8 | |||
| a24eaad1c9 | |||
| 357fdf2777 | |||
| a66fb4ff2c | |||
| 8e3ba68d58 | |||
| 6e04f1afb5 | |||
| 110cb44d41 | |||
| f06e7467ce | |||
| 412491568f | |||
| d2e1520a14 | |||
| 0a18ac6c15 | |||
| 45a23a3417 | |||
| ae239b0102 | |||
| 3a2d21f1ac | |||
| 40a559e8db | |||
| 28320fc1d4 | |||
| cbc8fc62c7 | |||
| 1f93fa8b1b | |||
| c6f9940ab2 | |||
| 9c66455d2a | |||
| 2215065a2e | |||
| f8b8b90a3b | |||
| 1bcf0e1ae9 | |||
| b49f5072b1 | |||
| 63ebe6ab9c | |||
| f192c4947c | |||
| 7fd749b475 | |||
| dfe9e436e8 | |||
| 72902ee6fb | |||
| 819403e940 | |||
| 58284c6230 | |||
| 66ce68a93f | |||
| 4bd181fc21 | |||
| 3143767d78 | |||
| 666fc4b794 | |||
| 7af73b06d7 | |||
| 0811234f3e | |||
| b64a7d248d | |||
| e7b08d914f | |||
| 3a9455f28c | |||
| 05e53ec38c | |||
| dbdd0e1d6f | |||
| 8146e29f7e | |||
| c110774dc7 | |||
| c0a5775fb5 | |||
| f844a23bb2 | |||
| 04e8759d41 | |||
| 78725135aa | |||
| 2ff64ff0b2 | |||
| 7a8e7cd9ae | |||
| b58eed1698 | |||
| c92c9cc244 | |||
| a2bf43e9ef | |||
| 49bac7e4a8 | |||
| 5aac7e3ca0 | |||
| d86585bf5c | |||
| 88e2b58711 | |||
| d259383645 | |||
| 2d7ee300a4 | |||
| 57fa4e3b7a | |||
| 0f1917f26b | |||
| 6e9c5e87e9 | |||
| d8bb892425 | |||
| 064a112c6b | |||
| 24d103c658 | |||
| 2d8e3da943 | |||
| 3081dab246 | |||
| fdc422c16e | |||
| 5e3f8db193 | |||
| f5bf5f7987 | |||
| 3ec12b7c72 | |||
| fa4d4b7f6a | |||
| 43beaafab5 | |||
| 21a20005cb | |||
| e1b3c587aa | |||
| da2bbab80c | |||
| 5a59e1ece4 | |||
| aea03ba9e7 | |||
| 54bc05e48f | |||
| 3ef0d98a16 | |||
| 5a6c8d8b30 | |||
| 1cd918c2b9 | |||
| e96d4a67bc | |||
| 8994fd03f6 | |||
| 0595130f16 | |||
| 37eccc425e |
@@ -48,4 +48,4 @@ Add any other context about the problem here.
|
||||
- [Troubleshooting Guide](https://github.com/micro/go-micro/tree/master/internal/website/docs/getting-started.md)
|
||||
- [Examples](https://github.com/micro/go-micro/tree/master/examples)
|
||||
- [API Reference](https://pkg.go.dev/go-micro.dev/v5)
|
||||
- [Discord Community](https://discord.gg/WeMU5AGxD)
|
||||
- [Discord Community](https://discord.gg/G8Gk5j3uXr)
|
||||
|
||||
@@ -39,4 +39,4 @@ Add any other context, code examples, or screenshots about the feature request h
|
||||
- [Roadmap](https://github.com/micro/go-micro/blob/master/ROADMAP.md)
|
||||
- [Contributing Guide](https://github.com/micro/go-micro/blob/master/CONTRIBUTING.md)
|
||||
- [Architecture Docs](https://github.com/micro/go-micro/tree/master/internal/website/docs/architecture.md)
|
||||
- [Discord Community](https://discord.gg/WeMU5AGxD)
|
||||
- [Discord Community](https://discord.gg/G8Gk5j3uXr)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# North Star
|
||||
|
||||
The direction the loop aligns every increment to. Depth lives in
|
||||
[`internal/docs/THESIS.md`](../../internal/docs/THESIS.md); this is the short,
|
||||
operative version the planner and builder read each run.
|
||||
|
||||
## Mission
|
||||
|
||||
Make building an **agent** as easy as building a **service**, on one runtime.
|
||||
Go Micro is a holistic agent harness and service framework encapsulating the
|
||||
lifecycle of **services → agents → workflows** — pluggable, progressive, and
|
||||
AI-native by default.
|
||||
|
||||
## Right now — developer adoption
|
||||
|
||||
The framework's depth is strong; the **on-ramp** is the gap. Weight the developer
|
||||
experience — a walkable first-agent tutorial, discoverable examples, docs
|
||||
wayfinding, install friction, debugging, the 0→1 and 0→hero path — **at least as
|
||||
highly as internal hardening**. A developer succeeding on their first agent
|
||||
matters more right now than another conformance/observability/interop increment.
|
||||
Do not let the queue fill entirely with internal depth work.
|
||||
|
||||
## Guardrails
|
||||
|
||||
- One concern per PR; small and reversible.
|
||||
- The gate is green CI (`go build`, `go test`, `golangci-lint`, `make harness`),
|
||||
not human review — keep the suite strong; the loop is only as good as its evaluator.
|
||||
- **Off-limits without a human** (surface as notes, never auto-merge): breaking
|
||||
public-API changes, brand/positioning/marketing copy, new dependencies,
|
||||
architectural rewrites, product-default changes with broad behavioral impact.
|
||||
- Stay on `claude/*` / `codex/*` branches; base PRs on `master`. See
|
||||
[`CODEX.md`](../../CODEX.md) and [`internal/docs/CONTINUOUS_IMPROVEMENT.md`](../../internal/docs/CONTINUOUS_IMPROVEMENT.md).
|
||||
@@ -21,7 +21,8 @@ changes, architectural rewrites. Those go to the human.
|
||||
|
||||
## Work queue (ranked)
|
||||
|
||||
1. **CI-verify cross-provider agent scenario conformance** ([#3432](https://github.com/micro/go-micro/issues/3432)) — failure-summary classification shipped via #3430 and closed the cancellation/retry contract (#3425), after provider-backed `ai.Stream` conformance (#3423), agent OpenTelemetry (#3418), durable checkpoint resume (#3414), A2A streaming fallback (#3410), the consolidated developer-flow harness (#3399), and the deploy checkpoint in the 0→hero harness (#3384). With the main failure/resilience and 0→hero contracts now covered, the highest-value remaining Now-phase gap is proving the same services → agents → workflows scenario across providers: tool discovery/calls, memory/run metadata, streaming fallback, and flow/gateway boundaries need one no-secret CI contract plus key-gated live-provider checks so builders do not experience provider-specific seams.
|
||||
1. **Broaden provider-backed agent streaming end to end** ([#3857](https://github.com/micro/go-micro/issues/3857)) — #3861 closed the durable agent resume discoverability gap, and there are no open `codex` PRs in flight. Streaming is now the highest-value remaining Next-phase increment because the README, website, and roadmap all sell an interactive services → agents → workflows lifecycle; responsive `micro chat`, provider-backed `ai.Stream`, and A2A long-task UX are part of the adoption on-ramp, not just internal depth. Keep this scoped to additive provider-backed coverage, mock/live-provider tests, and discoverable support status so developers can trust the chat/agent/A2A path without a public-API rewrite.
|
||||
2. **Add an AP2 mandate layer over A2A and x402** ([#3552](https://github.com/micro/go-micro/issues/3552)) — this remains a forward interop investment, not a Now/Next blocker: Go Micro already has A2A agents and x402 paid tools, so a small signed-mandate foundation can keep agent payments aligned with the open-protocol story without pulling the queue ahead of adoption, resilience, streaming, or durable agent operation. Keep it additive and opt-in while the AP2/FIDO work settles.
|
||||
|
||||
_Seeded by Claude Code from the roadmap + open issues; thereafter maintained by the
|
||||
architecture-review pass._
|
||||
@@ -0,0 +1,14 @@
|
||||
<!--
|
||||
The BUILDER prompt — go-micro's continuous-improvement increment. Editable
|
||||
policy; the workflow prepends the agent @mention and substitutes __ISSUE__
|
||||
before posting. Keep __ISSUE__ literal.
|
||||
-->
|
||||
Run one continuous-improvement increment per `internal/docs/CONTINUOUS_IMPROVEMENT.md`, aligned to the North Star in `.github/loop/NORTH_STAR.md` (the services → agents → workflows lifecycle, with developer adoption as the current goal).
|
||||
|
||||
PICK THE WORK FROM THE QUEUE: read `.github/loop/PRIORITIES.md` and take the highest-ranked item whose linked issue is still OPEN — that is your task, and its issue number is the one you close. If `PRIORITIES.md` is missing or every listed item's issue is already closed, fall back to the single highest-value roadmap / open-issue / improvement-radar item yourself.
|
||||
|
||||
Implement it, and VERIFY `go build ./...`, `go test ./...`, and `golangci-lint run ./...`.
|
||||
|
||||
Open the PR YOURSELF from the shell — do NOT use the make_pr tool (in this environment it only records metadata and never creates a PR). Create a uniquely-named branch under the `codex/` prefix: `git switch -c codex/increment-__ISSUE__`, then `git push -u origin codex/increment-__ISSUE__`, then `gh pr create --base master --label codex --title "<title>" --body "<body; include 'Closes #<the priority issue you built>' so it leaves the queue, and 'Closes #__ISSUE__' for this run's tracker>"`. Finally enable auto-merge so GitHub merges it once CI is green: `gh pr merge --squash --auto --delete-branch`.
|
||||
|
||||
One concern per PR. Stay out of breaking public API and brand/positioning copy — surface those as notes for the human instead.
|
||||
@@ -0,0 +1,14 @@
|
||||
<!--
|
||||
The COHERENCE prompt — go-micro's DevRel pass (public-surface coherence +
|
||||
CHANGELOG upkeep + changelog blog). Editable policy; the workflow prepends the
|
||||
agent @mention and substitutes __ISSUE__ before posting. Keep __ISSUE__ literal.
|
||||
-->
|
||||
Act as DevRel for go-micro. Do these, in order.
|
||||
|
||||
COHERENCE AUDIT. Audit the public surface — `README.md`, `internal/website/` (landing `index.html` + `docs/`), and the blog under `internal/website/blog/` — for coherence with the North Star in `.github/loop/NORTH_STAR.md` (an agent harness and service framework; the services → agents → workflows lifecycle). Look for: places where README / website / docs contradict each other, are stale, or describe behavior that has since changed (cross-check against the code and recently merged PRs); whether the README is crisp and leads with the harness positioning; and one to three genuinely blog-worthy items from recently shipped work.
|
||||
|
||||
CHANGELOG UPKEEP (safe factual task — goes in the auto-merged PR). Keep `CHANGELOG.md` living, in Keep-a-Changelog format with newest content at the top under `## [Unreleased]`. Enumerate PRs merged to master since the last update (`gh pr list --state merged --base master --limit 60 --json number,title,mergedAt,labels`) and add a concise, user-facing entry for each genuine change not yet recorded under the right `### Added` / `### Changed` / `### Fixed` / `### Documentation` subheading — SKIP internal loop/CI/priorities-refresh churn. If a new `vX.Y.Z` tag was cut since the last run (`git fetch --tags --force`), rename `## [Unreleased]` to `## [X.Y.Z] - <Month YYYY>` and open a fresh empty `## [Unreleased]` above it. Do not invent entries.
|
||||
|
||||
CHANGELOG BLOG POST (blog voice — do NOT auto-merge). If, and only if, enough user-facing work has accumulated since the last changelog post to be worth reading (roughly a week's worth; not a near-empty post every day), draft a short "What's new in Go Micro" post as the next-numbered file in `internal/website/blog/`, mirroring the latest post's frontmatter and prev-nav, and add an entry at the top of `internal/website/blog/index.html`. Base it strictly on the CHANGELOG.
|
||||
|
||||
THEN: (A) post a findings report as a comment on this issue (#__ISSUE__) — what's aligned, what drifted, what you fixed, the CHANGELOG entries added, and whether you drafted a blog post (and why/why not). (B) Open ONE auto-merging PR for the SAFE factual work only — coherence/crispness fixes AND the CHANGELOG update (NOT brand/positioning rewrites, NOT the blog post): `git switch -c codex/coherence-__ISSUE__`, `git push -u origin codex/coherence-__ISSUE__`, `gh pr create --base master --label codex --title "<title>" --body "<summary, Closes #__ISSUE__>"`, then `gh pr merge --squash --auto --delete-branch`. (C) If you drafted a changelog blog post, open it as a SEPARATE PR (`codex/coherence-blog-__ISSUE__`, title prefixed `blog:`) and do NOT enable auto-merge — leave it for the human. Same for any brand/positioning copy. Do not use the make_pr tool.
|
||||
@@ -0,0 +1,16 @@
|
||||
<!--
|
||||
The PLANNER prompt — go-micro's "architect / founder lens". Editable policy;
|
||||
the workflow prepends the agent @mention and substitutes __ISSUE__ (this run's
|
||||
tracking issue) before posting. Keep __ISSUE__ literal.
|
||||
-->
|
||||
Act as the architect — the founder lens — for go-micro, running continuously alongside the builders. Hold the whole picture: how the harness, the framework, and the developer UX fit together, what is in flight and what just merged, what to prioritize next, and what is missing or has drifted.
|
||||
|
||||
(1) TRACK STATE — scan recently merged PRs and open `codex` PRs/issues to see what shipped and what is being built right now, so the queue reflects reality (drop done items, don't re-queue in-flight work).
|
||||
|
||||
(2) ASSESS against the North Star in `.github/loop/NORTH_STAR.md` — lead with its Mission (*make building an agent as easy as building a service, on one runtime*) and re-derive alignment from the CANON: the blog under `internal/website/blog`, the `README`, and the website (read these, don't rely on the North Star alone), then `ROADMAP.md` (Now → Next → Later). Judge every priority against the mission: does it make the services → agents → workflows lifecycle simpler, more cohesive, and more operable? CURRENT GOAL — developer adoption: weight the on-ramp (walkable first-agent tutorial, discoverable examples, docs wayfinding, install friction, debugging, 0→1 and 0→hero) at least as highly as internal hardening; do not let the queue fill entirely with internal depth work. Look at coherence and seams across the core packages (agent, ai, flow, gateway/mcp, gateway/a2a, model, server, store, registry) and the dev inner loop (scaffold → run → chat → inspect → deploy). Flag drift in either direction: work drifting from the mission, or the North Star/website drifting from the lived story in the blog.
|
||||
|
||||
(3) MAINTAIN THE QUEUE in `.github/loop/PRIORITIES.md` — a SINGLE ordered list, highest-value first, each item linking a scoped, CI-verifiable issue (#N); roadmap phase is the primary ordering, internal findings (cohesion gaps, DX friction, missing pieces) interleaved by value. For any prioritized gap with no issue, file one: `gh issue create --label codex --label enhancement --title "<scoped task>" --body "<goal, scope, acceptance criteria>"`.
|
||||
|
||||
OUTPUT: post a concise assessment as a comment on this issue (#__ISSUE__) — what shipped, what's in flight, the top risks/gaps, and the reasoning behind the ranking. If the ranking actually changed, open ONE PR for `.github/loop/PRIORITIES.md`: `git switch -c codex/planner-__ISSUE__`, `git push -u origin codex/planner-__ISSUE__`, `gh pr create --base master --label codex --title "<title>" --body "<summary, Closes #__ISSUE__>"`, then `gh pr merge --squash --auto --delete-branch`. If the queue is already accurate, just close this issue (`gh issue close __ISSUE__`).
|
||||
|
||||
Do NOT make breaking public-API or architectural changes yourself — surface those in the assessment as notes for the human, never as auto-merged changes. Open the PR yourself from the shell with `gh`; do not use the make_pr tool (it is a no-op stub).
|
||||
@@ -0,0 +1,14 @@
|
||||
<!--
|
||||
The TRIAGE prompt — go-micro's CI-failure feedback path. Editable policy; the
|
||||
workflow prepends the agent @mention and substitutes __ISSUE__ (this tracking
|
||||
issue) and __RUNURL__ (the failed run) before posting. Keep both literal.
|
||||
-->
|
||||
Triage the failed CI run at __RUNURL__. It may be the linter (Lint), the unit/integration tests (Run Tests), or the provider-conformance harness (Harness (E2E)).
|
||||
|
||||
Read the logs and root-cause each distinct failure. DEDUPE against open issues — if a failure matches an existing issue, comment "recurred" there instead of filing a duplicate.
|
||||
|
||||
For each genuine, self-contained defect, file a scoped issue (`gh issue create --label codex --label enhancement --title "<scoped fix>" --body "<root cause, where, acceptance criteria>"`) so the increment loop builds it and the next CI/harness run verifies it. A lint or test failure on master is a real regression — file it so it is fixed promptly; do NOT ignore it.
|
||||
|
||||
IGNORE only genuine transient flakes — live-model latency, provider outages, rate limits, network timeouts with no code cause (mostly relevant to the harness). Anything needing a breaking or architectural change: file it as `needs-human` and describe it, rather than auto-queuing it as a routine fix.
|
||||
|
||||
Close this issue (`gh issue close __ISSUE__`) when triage is done. Open any PR yourself from the shell with `gh`; do not use the make_pr tool.
|
||||
@@ -1,51 +0,0 @@
|
||||
name: Architecture Review
|
||||
|
||||
# Continuous high-altitude oversight of the whole framework and harness — the
|
||||
# "founder lens" of the autonomous loop (internal/docs/CONTINUOUS_IMPROVEMENT.md).
|
||||
# Where DevRel watches the public story and the increment loop ships code, the
|
||||
# architect watches the SYSTEM and runs alongside the builders: it tracks what is
|
||||
# in flight and what just merged, keeps the roadmap priorities live, and judges
|
||||
# cohesion (harness <-> framework <-> dev UX), missing pieces, and realignment.
|
||||
#
|
||||
# Its OUTPUT is the ranked queue in internal/docs/PRIORITIES.md plus an assessment
|
||||
# — NOT large refactors. Breaking public-API and architectural changes stay with
|
||||
# the human (see CONTINUOUS_IMPROVEMENT.md).
|
||||
#
|
||||
# Runs hourly, offset before the increment loop (:29) so it re-prioritizes and
|
||||
# THEN the loop builds the new top of the queue. Opens a fresh issue and
|
||||
# dispatches Codex via CODEX_TRIGGER_TOKEN.
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "59 * * * *" # hourly at :59, just before the :29 increment run (tunable)
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: architecture-review
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Open an architecture review issue and dispatch Codex
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
|
||||
HAS_TRIGGER_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [ "$HAS_TRIGGER_TOKEN" != "true" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping (Codex ignores Actions-bot comments)."
|
||||
exit 0
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "Architecture review #$RUN_NUMBER" \
|
||||
--body "Continuous architecture / harness oversight against the North Star in internal/docs/THESIS.md. Output: a re-ranked internal/docs/PRIORITIES.md (only if it changed) plus an assessment.")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching Codex (Architect)."
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body \
|
||||
"@codex Act as the architect — the founder lens — for go-micro, running continuously alongside the builders. Hold the whole picture: how the harness, the framework, and the developer UX fit together cohesively, what is in flight and what just merged, what to prioritize next on the roadmap, and what is missing or has drifted. Each run: (1) TRACK STATE — scan recently merged PRs and open codex PRs/issues to see what shipped and what is being built right now, so the queue reflects reality (drop done items, don't re-queue in-flight work). (2) ASSESS against the North Star in internal/docs/THESIS.md — lead with its Mission (*the problem we solve: make building an agent as easy as building a service, on one runtime*) and re-derive alignment from the CANON it names (the blog under internal/website/blog, the README, and the website — read these, don't rely on THESIS.md alone), then ROADMAP.md (Now → Next → Later). Judge every priority against the mission: does it make the services → agents → workflows lifecycle simpler, more cohesive, and more operable? Look at coherence and seams across the core packages (agent, ai, flow, gateway/mcp, gateway/a2a, model, server, store, registry), the dev inner loop (scaffold → run → chat → inspect → deploy), missing pieces, duplication/drift, and realignment. Flag drift in EITHER direction: work drifting from the mission, or the North Star/website drifting from the lived story in the blog (which needs re-grounding in the canon). (3) MAINTAIN THE QUEUE in internal/docs/PRIORITIES.md — a SINGLE ordered list, highest-value first, each item linking a scoped CI-verifiable issue (#N); roadmap phase is the primary ordering, internal findings (cohesion gaps, DX friction, missing pieces) interleaved by value. For any prioritized gap that has no issue yet, file one: \`gh issue create --label codex --label enhancement --title \"<scoped task>\" --body \"<goal, scope, acceptance criteria>\"\`. OUTPUT: post a concise assessment as a comment on this issue (#$ISSUE_NUM) — what shipped, what's in flight, the top risks/gaps/missing pieces, and the reasoning behind the ranking. If the ranking actually changed, open ONE PR for PRIORITIES.md: \`git switch -c codex/architect-$ISSUE_NUM\`, \`git push -u origin codex/architect-$ISSUE_NUM\`, \`gh pr create --base master --label codex --title \"<title>\" --body \"<summary, Closes #$ISSUE_NUM>\"\`, then \`gh pr merge --squash --auto --delete-branch\`. If the queue is already accurate and correctly ranked, do NOT open a PR — just close this issue (\`gh issue close $ISSUE_NUM\`). Do NOT make breaking public-API or architectural changes yourself — surface those in the assessment as notes for the human, never as auto-merged changes. Do not use the make_pr tool (it is a no-op stub)."
|
||||
@@ -1,65 +0,0 @@
|
||||
name: Continuous Improvement
|
||||
|
||||
# Durable backbone for the autonomous improvement loop
|
||||
# (see internal/docs/CONTINUOUS_IMPROVEMENT.md).
|
||||
#
|
||||
# A Claude Max subscription provides no API key for CI, so the loop is driven by
|
||||
# Codex rather than Claude Code: on a cadence this opens a fresh tracking issue and
|
||||
# posts an @codex instruction on it, and Codex runs one improvement increment, opens
|
||||
# a PR (git push + gh pr create — the make_pr tool is a no-op stub), and enables
|
||||
# GitHub auto-merge (gh pr merge --auto) so the PR lands once the required CI checks
|
||||
# pass. No separate merge sweep — branch protection + native auto-merge is the gate.
|
||||
# (See the per-issue rationale below.)
|
||||
#
|
||||
# Codex does NOT respond to comments authored by the github-actions bot, so the
|
||||
# dispatch is GATED on a CODEX_TRIGGER_TOKEN secret (a PAT for a user account Codex
|
||||
# follows). Until that secret is set the workflow runs but no-ops — this avoids
|
||||
# piling up @codex comments that Codex silently ignores. The moment the secret is
|
||||
# added the loop activates with no further change.
|
||||
#
|
||||
# Each run opens a FRESH issue and dispatches Codex there, rather than re-commenting
|
||||
# on one tracker issue. Codex derives its PR branch name from the triggering issue's
|
||||
# context, so repeated dispatches on a single issue all collapse onto one branch name
|
||||
# (codex/github-mention-<that-issue-slug>) — the first increment opens a PR, the rest
|
||||
# collide on the occupied branch and silently fail to open one. A unique issue per
|
||||
# run gives each increment its own branch and a clean PR. The dispatch asks Codex to
|
||||
# "Closes #<issue>" so each tracking issue auto-closes when its PR merges.
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "29 * * * *" # hourly, off-minute (tune as needed)
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: continuous-improvement
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Open a fresh increment issue and dispatch Codex
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
|
||||
HAS_TRIGGER_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [ "$HAS_TRIGGER_TOKEN" != "true" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping dispatch."
|
||||
echo "Codex ignores comments from the github-actions bot, so posting now"
|
||||
echo "would only create noise. Add a CODEX_TRIGGER_TOKEN secret (a PAT for"
|
||||
echo "a user account Codex follows) to activate the loop."
|
||||
exit 0
|
||||
fi
|
||||
# A unique issue per run → unique codex/ branch → no collisions.
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "Continuous improvement increment #$RUN_NUMBER" \
|
||||
--body "Autonomous continuous-improvement increment. North Star: internal/docs/THESIS.md; charter: internal/docs/CONTINUOUS_IMPROVEMENT.md. Tracker: #3024.")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching Codex."
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body \
|
||||
"@codex Run one continuous-improvement increment per internal/docs/CONTINUOUS_IMPROVEMENT.md, aligned to the North Star in internal/docs/THESIS.md (the holistic services → agents → workflows lifecycle). PICK THE WORK FROM THE QUEUE: read internal/docs/PRIORITIES.md and take the highest-ranked item whose linked issue is still OPEN — that is your task, and its issue number is the one you close. (If PRIORITIES.md is missing or every listed item's issue is already closed, fall back to picking the single highest-value roadmap/issue/improvement-radar item yourself.) Implement it, and verify \`go build ./...\`, \`go test ./...\`, and \`golangci-lint run ./...\`. Then open the PR YOURSELF from the shell — do NOT use the make_pr tool (in this environment it only records metadata and never creates a PR). Create a uniquely-named branch under the codex/ prefix and open the PR from it: \`git switch -c codex/increment-$ISSUE_NUM\`, then \`git push -u origin codex/increment-$ISSUE_NUM\`, then \`gh pr create --base master --label codex --title \"<title>\" --body \"<body; include 'Closes #<the priority issue you built>' so it leaves the queue, and 'Closes #$ISSUE_NUM' for this run's tracker>\"\`. Finally enable auto-merge so GitHub merges it once CI is green: \`gh pr merge --squash --auto --delete-branch\`. The gh CLI is installed and authenticated and origin points to $REPO. One concern per PR; stay out of brand/positioning copy and breaking public API."
|
||||
@@ -1,47 +0,0 @@
|
||||
name: DevRel Review
|
||||
|
||||
# Daily higher-altitude coherence pass over the PUBLIC surface — README,
|
||||
# website (landing + docs), and blog — part of the autonomous loop
|
||||
# (internal/docs/CONTINUOUS_IMPROVEMENT.md). The hourly increment loop ships
|
||||
# code; this keeps the story coherent: docs/website aligned, README crisp, and
|
||||
# a steady supply of things worth blogging about.
|
||||
#
|
||||
# Like the increment loop it opens a fresh issue and dispatches Codex via
|
||||
# CODEX_TRIGGER_TOKEN (Codex ignores Actions-bot comments). Autonomy boundary:
|
||||
# SAFE factual-alignment and crispness fixes auto-merge; brand/positioning copy
|
||||
# and blog drafts are surfaced in the report for the human, never auto-merged.
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "0 7 * * *" # daily, 07:00 UTC (tunable)
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: devrel-review
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Open a DevRel review issue and dispatch Codex
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
|
||||
HAS_TRIGGER_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [ "$HAS_TRIGGER_TOKEN" != "true" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping (Codex ignores Actions-bot comments)."
|
||||
exit 0
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "DevRel coherence review #$RUN_NUMBER" \
|
||||
--body "Daily DevRel / coherence pass over README, website (landing + docs), and the blog. North Star: internal/docs/THESIS.md.")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching Codex (DevRel)."
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body \
|
||||
"@codex Act as DevRel for go-micro. Audit the PUBLIC surface — \`README.md\`, \`internal/website/\` (landing \`index.html\` + \`docs/\`), and the blog under \`internal/website/blog/\` — for coherence with the North Star in internal/docs/THESIS.md (an agent harness and service framework; the services → agents → workflows lifecycle). Look for: (1) places where README / website / docs contradict each other, are stale, or describe behavior that has since changed (cross-check against the code and recent merged PRs / CHANGELOG.md); (2) whether the README is crisp and leads with the harness positioning; (3) one to three genuinely blog-worthy items from recently shipped work. Then do BOTH of these: (A) post a concise findings report as a comment on this issue (#$ISSUE_NUM) — what is aligned, what drifted, what you fixed, and the blog ideas; (B) for SAFE factual-alignment and crispness fixes only (NOT brand/marketing/positioning rewrites), open one PR: \`git switch -c codex/devrel-$ISSUE_NUM\`, \`git push -u origin codex/devrel-$ISSUE_NUM\`, \`gh pr create --base master --label codex --title \"<title>\" --body \"<summary, including 'Closes #$ISSUE_NUM'>\"\`, then \`gh pr merge --squash --auto --delete-branch\`. Leave brand/positioning copy and blog drafts for the human — describe them in the report, do NOT open auto-merging PRs for them. Do not use the make_pr tool (it is a no-op stub). If you touch code, verify go build/test/golangci-lint. Stay out of breaking public-API changes."
|
||||
@@ -12,8 +12,22 @@ on:
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
schedule:
|
||||
- cron: "17 6 * * *" # daily, so the world is exercised even without changes
|
||||
- cron: "17 * * * *" # hourly, so real-model conformance keeps pace with the dev/loop velocity
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
providers:
|
||||
description: "Comma-separated providers for live conformance (default: all supported)"
|
||||
required: false
|
||||
default: "anthropic,openai,gemini,groq,minimax,mistral,together,atlascloud"
|
||||
harnesses:
|
||||
description: "Comma-separated harnesses for live conformance"
|
||||
required: false
|
||||
default: "agent,universe,agent-flow,plan-delegate,a2a-stream-fallback"
|
||||
require_configured:
|
||||
description: "Fail selected live providers that do not have repository secrets"
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
harness:
|
||||
@@ -50,14 +64,32 @@ jobs:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
|
||||
MINIMAX_API_KEY: ${{ secrets.MINIMAX_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
TOGETHER_API_KEY: ${{ secrets.TOGETHER_API_KEY }}
|
||||
ATLASCLOUD_API_KEY: ${{ secrets.ATLASCLOUD_API_KEY }}
|
||||
# Atlas Cloud's default chat model was failing the agent/tool-use
|
||||
# conformance harnesses; run it against a stronger tool-use model.
|
||||
# Override with an Actions variable ATLASCLOUD_MODEL if the exact
|
||||
# catalog id differs (Atlas uses org/model ids).
|
||||
ATLASCLOUD_MODEL: ${{ vars.ATLASCLOUD_MODEL || 'minimaxai/minimax-m3' }}
|
||||
run: |
|
||||
go run ./internal/harness/provider-conformance \
|
||||
-summary-json provider-conformance-summary.json \
|
||||
-summary-markdown provider-conformance-summary.md \
|
||||
PROVIDERS="${{ github.event.inputs.providers || 'anthropic,openai,gemini,groq,minimax,mistral,together,atlascloud' }}"
|
||||
HARNESSES="${{ github.event.inputs.harnesses || 'agent,universe,agent-flow,plan-delegate,a2a-stream-fallback' }}"
|
||||
REQUIRE_CONFIGURED="${{ github.event.inputs.require_configured || 'false' }}"
|
||||
|
||||
args=(
|
||||
-providers "$PROVIDERS"
|
||||
-harnesses "$HARNESSES"
|
||||
-summary-json provider-conformance-summary.json
|
||||
-summary-markdown provider-conformance-summary.md
|
||||
-capabilities-markdown provider-capabilities.md
|
||||
)
|
||||
if [ "$REQUIRE_CONFIGURED" = "true" ]; then
|
||||
args+=( -require-configured )
|
||||
fi
|
||||
|
||||
go run ./internal/harness/provider-conformance "${args[@]}"
|
||||
- name: Publish provider conformance summary
|
||||
if: always()
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
name: "Loop: Builder"
|
||||
|
||||
# Generated by `micro loop init`. A dispatch role of the autonomous loop: on a
|
||||
# cadence it opens a fresh tracking issue and posts the instruction in
|
||||
# .github/loop/prompts/builder.md to the agent (@codex).
|
||||
#
|
||||
# The workflow is the MECHANISM; that prompt file is the editable POLICY —
|
||||
# change what this role does by editing the prompt, not this YAML. A FRESH
|
||||
# issue per run is deliberate: agents derive the PR branch name from the
|
||||
# triggering issue, so reusing one tracker collapses every run onto one branch.
|
||||
#
|
||||
# Gated on CODEX_TRIGGER_TOKEN: the agent ignores @mentions from the
|
||||
# github-actions bot, so dispatch posts as a real user (a PAT). No token → no-op.
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "29 * * * *"
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: loop-builder
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4 # needed to read the prompt file
|
||||
- name: Dispatch builder
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
|
||||
HAS_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [ "$HAS_TOKEN" != "true" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping (the agent ignores bot @mentions)."
|
||||
exit 0
|
||||
fi
|
||||
PROMPT=".github/loop/prompts/builder.md"
|
||||
if [ ! -f "$PROMPT" ]; then
|
||||
echo "missing $PROMPT — run 'micro loop init'." >&2
|
||||
exit 1
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "Loop: build increment #$RUN_NUMBER" \
|
||||
--body "Autonomous builder pass. Direction: .github/loop/NORTH_STAR.md; queue: .github/loop/PRIORITIES.md.")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching builder."
|
||||
# The prompt file is the policy; strip its editorial <!-- --> header and
|
||||
# substitute the tracking issue number (__ISSUE__) at runtime.
|
||||
{
|
||||
echo "@codex"
|
||||
echo
|
||||
sed -e '/<!--/,/-->/d' -e "s/__ISSUE__/$ISSUE_NUM/g" "$PROMPT"
|
||||
} > "$RUNNER_TEMP/loop-body.md"
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/loop-body.md"
|
||||
@@ -0,0 +1,60 @@
|
||||
name: "Loop: Coherence"
|
||||
|
||||
# Generated by `micro loop init`. A dispatch role of the autonomous loop: on a
|
||||
# cadence it opens a fresh tracking issue and posts the instruction in
|
||||
# .github/loop/prompts/coherence.md to the agent (@codex).
|
||||
#
|
||||
# The workflow is the MECHANISM; that prompt file is the editable POLICY —
|
||||
# change what this role does by editing the prompt, not this YAML. A FRESH
|
||||
# issue per run is deliberate: agents derive the PR branch name from the
|
||||
# triggering issue, so reusing one tracker collapses every run onto one branch.
|
||||
#
|
||||
# Gated on CODEX_TRIGGER_TOKEN: the agent ignores @mentions from the
|
||||
# github-actions bot, so dispatch posts as a real user (a PAT). No token → no-op.
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "0 7 * * *"
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: loop-coherence
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4 # needed to read the prompt file
|
||||
- name: Dispatch coherence
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
|
||||
HAS_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [ "$HAS_TOKEN" != "true" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping (the agent ignores bot @mentions)."
|
||||
exit 0
|
||||
fi
|
||||
PROMPT=".github/loop/prompts/coherence.md"
|
||||
if [ ! -f "$PROMPT" ]; then
|
||||
echo "missing $PROMPT — run 'micro loop init'." >&2
|
||||
exit 1
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "Loop: coherence review #$RUN_NUMBER" \
|
||||
--body "Autonomous coherence pass. Direction: .github/loop/NORTH_STAR.md; queue: .github/loop/PRIORITIES.md.")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching coherence."
|
||||
# The prompt file is the policy; strip its editorial <!-- --> header and
|
||||
# substitute the tracking issue number (__ISSUE__) at runtime.
|
||||
{
|
||||
echo "@codex"
|
||||
echo
|
||||
sed -e '/<!--/,/-->/d' -e "s/__ISSUE__/$ISSUE_NUM/g" "$PROMPT"
|
||||
} > "$RUNNER_TEMP/loop-body.md"
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/loop-body.md"
|
||||
@@ -0,0 +1,60 @@
|
||||
name: "Loop: Planner"
|
||||
|
||||
# Generated by `micro loop init`. A dispatch role of the autonomous loop: on a
|
||||
# cadence it opens a fresh tracking issue and posts the instruction in
|
||||
# .github/loop/prompts/planner.md to the agent (@codex).
|
||||
#
|
||||
# The workflow is the MECHANISM; that prompt file is the editable POLICY —
|
||||
# change what this role does by editing the prompt, not this YAML. A FRESH
|
||||
# issue per run is deliberate: agents derive the PR branch name from the
|
||||
# triggering issue, so reusing one tracker collapses every run onto one branch.
|
||||
#
|
||||
# Gated on CODEX_TRIGGER_TOKEN: the agent ignores @mentions from the
|
||||
# github-actions bot, so dispatch posts as a real user (a PAT). No token → no-op.
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "59 * * * *"
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: loop-planner
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4 # needed to read the prompt file
|
||||
- name: Dispatch planner
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
|
||||
HAS_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [ "$HAS_TOKEN" != "true" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping (the agent ignores bot @mentions)."
|
||||
exit 0
|
||||
fi
|
||||
PROMPT=".github/loop/prompts/planner.md"
|
||||
if [ ! -f "$PROMPT" ]; then
|
||||
echo "missing $PROMPT — run 'micro loop init'." >&2
|
||||
exit 1
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "Loop: planning review #$RUN_NUMBER" \
|
||||
--body "Autonomous planner pass. Direction: .github/loop/NORTH_STAR.md; queue: .github/loop/PRIORITIES.md.")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching planner."
|
||||
# The prompt file is the policy; strip its editorial <!-- --> header and
|
||||
# substitute the tracking issue number (__ISSUE__) at runtime.
|
||||
{
|
||||
echo "@codex"
|
||||
echo
|
||||
sed -e '/<!--/,/-->/d' -e "s/__ISSUE__/$ISSUE_NUM/g" "$PROMPT"
|
||||
} > "$RUNNER_TEMP/loop-body.md"
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/loop-body.md"
|
||||
@@ -0,0 +1,76 @@
|
||||
name: "Loop: Release"
|
||||
|
||||
# Generated by `micro loop init`. Cuts the next PATCH tag
|
||||
# (vMAJOR.MINOR.PATCH+1) when the default branch has new commits
|
||||
# since the latest such tag, and pushes it with a PAT (CODEX_TRIGGER_TOKEN) so any
|
||||
# tag-triggered release workflow fires. Minor/major bumps stay with a human.
|
||||
#
|
||||
# The tag MUST be pushed with a PAT, not the default GITHUB_TOKEN: a tag pushed
|
||||
# by GITHUB_TOKEN does not trigger other workflows (Actions blocks that recursion).
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "0 23 * * *"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: loop-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # need full history + all tags
|
||||
# Do NOT persist the default GITHUB_TOKEN as a git credential: it would
|
||||
# be sent on the PAT push below and override it, so the tag push would
|
||||
# authenticate as github-actions[bot] and 403. Letting the PAT in the
|
||||
# push URL be the only credential is the whole point.
|
||||
persist-credentials: false
|
||||
- name: Cut the next patch tag if there are new commits
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
if [ -z "$RELEASE_TOKEN" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping."
|
||||
exit 0
|
||||
fi
|
||||
git fetch --tags --force
|
||||
|
||||
LATEST=$(git tag --list 'v*.*.*' --sort=-v:refname | head -1)
|
||||
if [ -z "$LATEST" ]; then
|
||||
echo "no vMAJOR.MINOR.PATCH tag found — aborting so nothing weird gets tagged."
|
||||
exit 1
|
||||
fi
|
||||
echo "latest tag: $LATEST"
|
||||
|
||||
COUNT=$(git rev-list --count "$LATEST"..HEAD)
|
||||
echo "commits since $LATEST: $COUNT"
|
||||
if [ "$COUNT" -eq 0 ]; then
|
||||
echo "no new commits since $LATEST — no release."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ver="${LATEST#v}"
|
||||
major="${ver%%.*}"
|
||||
rest="${ver#*.}"
|
||||
minor="${rest%%.*}"
|
||||
patch="${rest#*.}"
|
||||
case "$major.$minor.$patch" in
|
||||
[0-9]*.[0-9]*.[0-9]*) ;;
|
||||
*) echo "unexpected tag shape: $LATEST" ; exit 1 ;;
|
||||
esac
|
||||
NEXT="v${major}.${minor}.$((patch + 1))"
|
||||
echo "cutting: $NEXT ($COUNT commits since $LATEST)"
|
||||
|
||||
git config user.name "loop release bot"
|
||||
git config user.email "noreply@users.noreply.github.com"
|
||||
git tag -a "$NEXT" -m "Release $NEXT — automated patch ($COUNT commits since $LATEST)"
|
||||
git push "https://x-access-token:${RELEASE_TOKEN}@github.com/${REPO}.git" "$NEXT"
|
||||
echo "Pushed $NEXT."
|
||||
@@ -0,0 +1,57 @@
|
||||
name: "Loop: Triage"
|
||||
|
||||
# Generated by `micro loop init`. The feedback path of the evaluator: when a CI
|
||||
# workflow (Harness (E2E), Lint, Run Tests) fails on a non-PR run, dispatch the agent
|
||||
# (@codex) with the instruction in .github/loop/prompts/triage.md
|
||||
# to root-cause the failure and file scoped fix issues back into the queue — so
|
||||
# failures become fixes with no human in the middle. Gated on CODEX_TRIGGER_TOKEN.
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["Harness (E2E)", "Lint", "Run Tests"]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: loop-triage
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
# Only real failures on branch pushes/schedules — not PR-run failures, which
|
||||
# the PR author already sees.
|
||||
if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event != 'pull_request' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4 # needed to read the prompt file
|
||||
- name: Dispatch triage
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
|
||||
HAS_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_ID: ${{ github.event.workflow_run.id }}
|
||||
RUN_URL: ${{ github.event.workflow_run.html_url }}
|
||||
WORKFLOW_NAME: ${{ github.event.workflow_run.name }}
|
||||
run: |
|
||||
if [ "$HAS_TOKEN" != "true" ]; then
|
||||
echo "CODEX_TRIGGER_TOKEN is not set — skipping."
|
||||
exit 0
|
||||
fi
|
||||
PROMPT=".github/loop/prompts/triage.md"
|
||||
if [ ! -f "$PROMPT" ]; then
|
||||
echo "missing $PROMPT — run 'micro loop init'." >&2
|
||||
exit 1
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "Loop: triage failed run $RUN_ID ($WORKFLOW_NAME)" \
|
||||
--body "The '$WORKFLOW_NAME' workflow failed on a non-PR run: $RUN_URL")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching triage."
|
||||
{
|
||||
echo "@codex"
|
||||
echo
|
||||
sed -e '/<!--/,/-->/d' -e "s/__ISSUE__/$ISSUE_NUM/g" -e "s#__RUNURL__#$RUN_URL#g" "$PROMPT"
|
||||
} > "$RUNNER_TEMP/loop-body.md"
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/loop-body.md"
|
||||
@@ -62,6 +62,7 @@ examples/mcp/hello/hello
|
||||
/plan-delegate
|
||||
/agent-plan-delegate
|
||||
/micro-mcp-gateway
|
||||
/agent-ollama
|
||||
|
||||
# Local Jekyll / Bundler artifacts
|
||||
internal/website/.bundle/
|
||||
|
||||
+56
-2
@@ -2,8 +2,62 @@
|
||||
|
||||
All notable changes to Go Micro are documented here.
|
||||
|
||||
Format follows [Keep a Changelog](https://keepachangelog.com/). Go Micro uses
|
||||
calendar-based versions (YYYY.MM) for the AI-native era.
|
||||
Format follows [Keep a Changelog](https://keepachangelog.com/) and versions
|
||||
follow [Semantic Versioning](https://semver.org/), matching the git tags and
|
||||
[GitHub releases](https://github.com/micro/go-micro/releases) (`v6.MINOR.PATCH`).
|
||||
Patch releases are cut automatically as the loop merges improvements; the
|
||||
`[Unreleased]` section below is kept current between tags and rolled into the
|
||||
next version when it ships.
|
||||
|
||||
> Earlier `2026.0x` headings are historical calendar-style markers from before
|
||||
> v6 tagging; they are kept for continuity and not reused.
|
||||
|
||||
---
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- **MiniMax provider** — run agents against MiniMax's `MiniMax-M3` model via its OpenAI-compatible endpoint, with tool calling and streaming; auto-detected from the base URL. (`ai/minimax/`)
|
||||
|
||||
### Fixed
|
||||
- **Plan/delegate completion** — agents now continue unfinished plan steps more reliably, fail checkpointed runs that leave delegated plans unfinished, recover from unknown plan-delegate tool calls, avoid duplicate side effects, and complete timeout paths deterministically. (`agent/`)
|
||||
- **AtlasCloud tool calls** — streaming and request fallback handling now recovers tool-call results from provider responses that omit the expected structured fields. (`ai/atlascloud/`)
|
||||
|
||||
---
|
||||
|
||||
## [6.3.13] - July 2026
|
||||
|
||||
### Added
|
||||
- **`micro loop`** — scaffold an autonomous improvement loop into any repository: GitHub Actions workflows dispatched to an @mention-driven coding agent, across up to five roles — `planner` (ranked queue), `builder` (top item as a single-concern PR, auto-merged on green CI), `triage` (CI failures → fix issues), and opt-in `coherence` (docs/CHANGELOG alignment) and `release` (daily patch tag). Each dispatch role's instruction lives in an editable `.github/loop/prompts/<role>.md` file — the workflow is the mechanism, the prompt is the policy — so a repo customizes behavior without forking the CLI. `micro loop init --roles …` writes it all; `micro loop verify` checks the wiring. This is the loop that maintains go-micro itself, generalized. (`cmd/micro/loop/`)
|
||||
|
||||
### Changed
|
||||
- **x402 payments** — settlement now covers CDP facilitator authentication and conformance edge cases. (`wrapper/x402/`)
|
||||
|
||||
### Fixed
|
||||
- **Plan/delegate harnessing** — side effects and notifications are now idempotent and deterministic across duplicate, alias, order-scoped, and reachability scenarios. (`agent/`, `internal/harness/`)
|
||||
|
||||
### Documentation
|
||||
- **First-agent on-ramp** — quickstart docs now connect the no-secret first-agent transcript, example map, and 0→hero path. (`README.md`, `internal/website/docs/`)
|
||||
- **Ollama provider docs** — the provider surface, capability matrix, and examples now document local and cloud behavior. (`internal/website/docs/`, `examples/agent-ollama/`)
|
||||
|
||||
---
|
||||
|
||||
## [6.3.12] - July 2026
|
||||
|
||||
### Added
|
||||
- **Ollama provider** — run agents against open-weight models locally (`/api/chat`, NDJSON streaming) or via Ollama Cloud (OpenAI-compatible `/v1/chat/completions`, SSE), auto-detected from the base URL, with tool calling in both modes. Point any agent at a non-default endpoint with the new `agent.BaseURL` / `micro.AgentBaseURL` option. (`ai/ollama/`, `examples/agent-ollama/`)
|
||||
- **Retrieval-backed agent memory** — agents can recall relevant prior turns by similarity, not just the recent window, with a summarizer hook that compacts older history so long conversations stay in budget. (`agent/`)
|
||||
- **Scheduled flows** — a flow can run an agent (or any step) on a cron-style schedule, with the dispatch traced end to end. (`flow/`)
|
||||
- **Flow verification/grader loop** — a workflow can grade its own step output against a rubric and retry until it passes, plus run-trace analysis to surface where a flow spends its time. (`flow/`)
|
||||
- **A2A streaming & continuity** — outbound agent streaming flows through the A2A binding (`message/stream`), with `tasks/resubscribe` and `input-required` handoffs for multi-turn interop. (`gateway/a2a/`)
|
||||
|
||||
### Changed
|
||||
- **Agent tool-call resilience** — opt-in retries around agent tool calls, and a fallback that executes tool calls emitted as text by weaker models so they still make progress. (`agent/`)
|
||||
- **Hardened agent durability** — terminal failure statuses are classified and surfaced, and durable resume-after-restart is covered by tests. (`agent/`)
|
||||
|
||||
### Documentation
|
||||
- **"Your first agent" walkthrough** and a canonical 0-to-hero reference path, lowering the on-ramp from install to a running agent. (`internal/website/docs/`)
|
||||
- **Discord** linked prominently across the README, website nav/footer, and docs. (`https://discord.gg/G8Gk5j3uXr`)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -6,6 +6,17 @@ Thank you for your interest in contributing to Go Micro! This document provides
|
||||
|
||||
Be respectful, inclusive, and collaborative. We're all here to build great software together.
|
||||
|
||||
## How Go Micro is built
|
||||
|
||||
Go Micro is developed by an **autonomous improvement loop** — a planner, a
|
||||
generator, and a separate evaluator, running as scheduled GitHub Actions with a
|
||||
human setting direction. It's the framework's own thesis (an agent operating a
|
||||
system) pointed at itself: an agent harness, built by agents. The full process —
|
||||
the planner → generator → evaluator pipeline, the correctness-only merge gate, and
|
||||
the guardrails — is documented in
|
||||
[`internal/docs/CONTINUOUS_IMPROVEMENT.md`](internal/docs/CONTINUOUS_IMPROVEMENT.md).
|
||||
Human contributions follow the same gate: green CI, one concern per PR.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Fork the repository
|
||||
|
||||
@@ -8,7 +8,7 @@ LDFLAGS = -X $(GIT_IMPORT).BuildDate=$(BUILD_DATE) -X $(GIT_IMPORT).GitCommit=$(
|
||||
# GORELEASER_DOCKER_IMAGE = ghcr.io/goreleaser/goreleaser-cross:v1.25.7
|
||||
GORELEASER_DOCKER_IMAGE = ghcr.io/goreleaser/goreleaser:latest
|
||||
|
||||
.PHONY: test test-race test-coverage harness provider-conformance lint fmt install-tools proto clean help gorelease-dry-run gorelease-dry-run-docker
|
||||
.PHONY: test test-race test-coverage harness install-smoke provider-conformance-mock provider-conformance lint fmt install-tools proto clean help gorelease-dry-run gorelease-dry-run-docker
|
||||
|
||||
# Default target
|
||||
help:
|
||||
@@ -19,6 +19,8 @@ help:
|
||||
@echo " make test-coverage - Run tests with coverage"
|
||||
@echo " make lint - Run linter"
|
||||
@echo " make harness - Run deterministic getting-started and end-to-end harnesses"
|
||||
@echo " make install-smoke - Verify the local install.sh and first-run CLI smoke path"
|
||||
@echo " make provider-conformance-mock - Run cross-provider harness with deterministic mock provider"
|
||||
@echo " make provider-conformance - Run harnesses against configured live providers"
|
||||
@echo " make fmt - Format code"
|
||||
@echo " make install-tools - Install development tools"
|
||||
@@ -47,9 +49,21 @@ test-coverage:
|
||||
# This mirrors the default CI path so local dogfooding catches scaffold,
|
||||
# run/chat/inspect, and 0→hero regressions before a PR is opened.
|
||||
harness:
|
||||
$(MAKE) install-smoke
|
||||
go test ./cmd/micro/cli/new -run TestZeroToOne -count=1
|
||||
./internal/harness/zero-to-hero-ci/run.sh
|
||||
go run ./internal/harness/agent-flow
|
||||
$(MAKE) provider-conformance-mock
|
||||
|
||||
# Verify the documented install script and first-run CLI command boundaries without
|
||||
# provider keys or network access.
|
||||
install-smoke:
|
||||
./internal/harness/install-smoke/run.sh
|
||||
|
||||
# Run the shared provider conformance contract with the deterministic mock
|
||||
# provider. This is the no-secret path used by CI and local dogfooding to keep
|
||||
# provider-facing agent/tool semantics covered on every machine.
|
||||
provider-conformance-mock:
|
||||
go run ./internal/harness/provider-conformance -providers mock
|
||||
|
||||
# Run the same harnesses against every configured live provider. Providers
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# Go Micro [](https://pkg.go.dev/go-micro.dev/v6?tab=doc) [](https://goreportcard.com/report/github.com/go-micro/go-micro)
|
||||
# Go Micro [](https://pkg.go.dev/go-micro.dev/v6?tab=doc) [](https://goreportcard.com/report/github.com/go-micro/go-micro) [](https://discord.gg/G8Gk5j3uXr)
|
||||
|
||||
Go Micro is an **agent harness** and service framework for Go.
|
||||
|
||||
**Community:** questions, ideas, or just want to build alongside us? [Join the Discord](https://discord.gg/G8Gk5j3uXr).
|
||||
|
||||
A harness is the runtime around an agent: the tools it can call, the memory it keeps, the guardrails that bound it, the workflows that trigger it, the services it depends on, and the protocols other agents use to reach it.
|
||||
|
||||
Go Micro gives you the harness as Go code. Build an agent and it gets a model, memory, tools, planning, delegation, guardrails, and service discovery; it is reachable over [MCP](https://modelcontextprotocol.io/) and [A2A](https://a2a-protocol.org). Write services and every endpoint becomes an AI-callable tool. Orchestrate the deterministic parts with durable flows. Agents, services, and flows share one runtime because an agent is a distributed system, and building one is building a service.
|
||||
@@ -14,7 +16,7 @@ Go Micro gives you the harness as Go code. Build an agent and it gets a model, m
|
||||
|
||||
<a href="https://go-micro.dev/blog/8"><img src="https://www.atlascloud.ai/logo.svg" height="26" /></a>
|
||||
|
||||
**Want to support Go Micro and see your logo here?** [Become a sponsor](https://discord.gg/WeMU5AGxD) — reach out on Discord.
|
||||
**Want to support Go Micro and see your logo here?** [Become a sponsor](https://discord.gg/G8Gk5j3uXr) — reach out on Discord.
|
||||
|
||||
## Commercial Support
|
||||
|
||||
@@ -23,6 +25,7 @@ Running Go Micro in production, or building on it and want help? Paid **support,
|
||||
## Contents
|
||||
|
||||
- [Quick Start](#quick-start)
|
||||
- [First agent on-ramp](#first-agent-on-ramp)
|
||||
- [Why an Agent Harness](#why-an-agent-harness)
|
||||
- [Writing Services](#writing-services)
|
||||
- [Building Agents](#building-agents) — [Plan & Delegate](#plan--delegate), [Pluggable](#batteries-included-pluggable), [Paid tools (x402)](#paid-tools-x402), [A2A](#reachable-by-other-agents-a2a)
|
||||
@@ -44,7 +47,7 @@ Install the CLI:
|
||||
curl -fsSL https://go-micro.dev/install.sh | sh
|
||||
|
||||
# Or with Go
|
||||
go install go-micro.dev/v6/cmd/micro@v6
|
||||
go install go-micro.dev/v6/cmd/micro@latest
|
||||
```
|
||||
|
||||
### Fastest start — no API key
|
||||
@@ -64,14 +67,37 @@ curl -X POST http://localhost:8080/api/helloworld/Helloworld.Call \
|
||||
-H 'Content-Type: application/json' -d '{"name":"World"}'
|
||||
```
|
||||
|
||||
This scaffold → run → call path is covered by the no-secret CI harness. To run
|
||||
the same local contract (including the 0→hero services → agents → workflows path,
|
||||
This install → scaffold → run → call path is covered by no-secret CI harnesses. To
|
||||
verify just the local installer and first-run CLI boundaries without network
|
||||
access or provider keys, use:
|
||||
|
||||
```bash
|
||||
make install-smoke
|
||||
```
|
||||
|
||||
To run the broader local contract (including the [0→hero services → agents → workflows path](internal/website/docs/guides/zero-to-hero.md),
|
||||
chat/inspect CLI boundaries, and deploy dry-run), use:
|
||||
|
||||
```bash
|
||||
make harness
|
||||
```
|
||||
|
||||
### First agent on-ramp
|
||||
|
||||
After install and the first `micro new`/`micro run` smoke check, take the
|
||||
walkable agent path in this order:
|
||||
|
||||
1. [No-secret first-agent transcript](internal/website/docs/guides/no-secret-first-agent.md) — run the
|
||||
maintained support agent with a mock model and see services → agents → workflows succeed without a key.
|
||||
2. [Your First Agent](internal/website/docs/guides/your-first-agent.md) — build a
|
||||
service-backed agent and talk to it with `micro chat`.
|
||||
3. [Debugging your agent](internal/website/docs/guides/debugging-agents.md) — use
|
||||
`micro agent inspect`, run history, memory, and provider checks when the first
|
||||
conversation does something unexpected.
|
||||
4. [0→hero Reference](internal/website/docs/guides/zero-to-hero.md) — complete the
|
||||
services → agents → workflows loop with scaffold, run, chat, inspect, flow
|
||||
history, and deploy dry-run commands that match the maintained harness.
|
||||
|
||||
### Generate from a prompt — with an LLM key
|
||||
|
||||
Set a provider key, describe what you want, and the AI designs services, writes handlers, compiles, and starts them:
|
||||
@@ -306,7 +332,7 @@ MCP exposes your services as tools; A2A exposes your agents as agents. See the [
|
||||
| MCP gateway | Every endpoint is an AI tool automatically |
|
||||
| A2A gateway | Every agent is reachable over the Agent2Agent protocol; cards generated from the registry (`micro a2a`) |
|
||||
| Payments (x402) | Opt-in per-call payments for tools via the x402 standard; pluggable facilitator (Base, Solana, …) |
|
||||
| 7 LLM providers | Anthropic, OpenAI, Gemini, Groq, Mistral, Together, Atlas Cloud |
|
||||
| 9 LLM providers | Anthropic, OpenAI, Gemini, Groq, Mistral, Together, Atlas Cloud, MiniMax, Ollama (local + cloud) |
|
||||
| Interactive console | `micro run` includes a chat console for talking to services |
|
||||
| Service generation | `micro run --prompt` — describe a system, get running services |
|
||||
|
||||
@@ -401,8 +427,10 @@ Swap providers with a single import — same interface everywhere:
|
||||
| Google Gemini | `gemini-2.5-flash` |
|
||||
| Groq | `llama-3.3-70b-versatile` |
|
||||
| Mistral | `mistral-large-latest` |
|
||||
| Together AI | `Llama-3.3-70B-Instruct-Turbo` |
|
||||
| Atlas Cloud | `llama-3.3-70b` |
|
||||
| Together AI | `meta-llama/Llama-3.3-70B-Instruct-Turbo` |
|
||||
| Atlas Cloud | `deepseek-ai/DeepSeek-V3-0324` |
|
||||
| MiniMax | `MiniMax-M3` |
|
||||
| Ollama | `llama3.2` (local) |
|
||||
|
||||
```go
|
||||
m := ai.New("anthropic", ai.WithAPIKey(key))
|
||||
@@ -415,6 +443,7 @@ resp, _ := m.Generate(ctx, &ai.Request{Prompt: "hello"})
|
||||
- [multi-service](examples/multi-service/) — Multiple services in one binary
|
||||
- [mcp](examples/mcp/) — MCP integration with AI agents
|
||||
- [agent-plan-delegate](examples/agent-plan-delegate/) — Agent planning and multi-agent delegation
|
||||
- [agent-durable](examples/agent-durable/) — Checkpoint and resume an agent run without replaying completed tool side effects
|
||||
- [grpc-interop](examples/grpc-interop/) — Call go-micro from any gRPC client
|
||||
|
||||
See [all examples](examples/README.md).
|
||||
@@ -423,6 +452,8 @@ See [all examples](examples/README.md).
|
||||
|
||||
- [Getting Started](internal/website/docs/getting-started.md)
|
||||
- [AI Integration](internal/website/docs/ai-integration.md)
|
||||
- [Your First Agent](internal/website/docs/guides/your-first-agent.md)
|
||||
- [0→hero Reference](internal/website/docs/guides/zero-to-hero.md)
|
||||
- [Agents and Workflows](internal/website/docs/guides/agents-and-workflows.md)
|
||||
- [Agent Design](internal/docs/AGENT_DESIGN.md)
|
||||
- [Plan & Delegate](internal/website/docs/guides/plan-delegate.md)
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ hosted service, enterprise tier, or venture funding. See
|
||||
## Contributing & feedback
|
||||
|
||||
Pick an item, open an issue to discuss the approach, and submit a PR. Or join the
|
||||
[Discord](https://discord.gg/WeMU5AGxD). Include tests, run `make test` and
|
||||
[Discord](https://discord.gg/G8Gk5j3uXr). Include tests, run `make test` and
|
||||
`make lint`.
|
||||
|
||||
## Version support
|
||||
|
||||
+1
-1
@@ -174,6 +174,6 @@ We currently do not offer a bug bounty program, but we greatly appreciate respon
|
||||
|
||||
For security questions that are not vulnerabilities, please:
|
||||
- Open a discussion: https://github.com/micro/go-micro/discussions
|
||||
- Join Discord: https://discord.gg/WeMU5AGxD
|
||||
- Join Discord: https://discord.gg/G8Gk5j3uXr
|
||||
- Email: support@go-micro.dev
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/gateway/a2a"
|
||||
)
|
||||
|
||||
func TestA2AStreamUsesAgentChatPathWithTools(t *testing.T) {
|
||||
var sawTool bool
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
if opts.ToolHandler == nil {
|
||||
t.Fatal("model was not wired with agent tool handler")
|
||||
}
|
||||
result := opts.ToolHandler(ctx, ai.ToolCall{
|
||||
ID: "call-1",
|
||||
Name: "echo",
|
||||
Input: map[string]any{"value": "a2a-stream"},
|
||||
})
|
||||
if !strings.Contains(result.Content, "a2a-stream-ok") {
|
||||
t.Fatalf("tool result = %q, want marker", result.Content)
|
||||
}
|
||||
return &ai.Response{Answer: "streamed " + result.Content}, nil
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
a := newTestAgent(Name("stream-agent"), WithTool("echo", "echo text", nil, func(ctx context.Context, input map[string]any) (string, error) {
|
||||
sawTool = true
|
||||
if info, ok := ai.RunInfoFrom(ctx); !ok || info.RunID == "" || info.Agent != "stream-agent" {
|
||||
t.Fatalf("RunInfo = %+v ok=%v, want stream-agent run", info, ok)
|
||||
}
|
||||
if input["value"] != "a2a-stream" {
|
||||
t.Fatalf("tool input = %+v, want a2a-stream", input)
|
||||
}
|
||||
return "a2a-stream-ok", nil
|
||||
}))
|
||||
h := a2a.NewAgentStreamHandler(
|
||||
a2a.Card("stream-agent", "http://example.invalid/stream-agent", "", nil),
|
||||
func(ctx context.Context, text string) (string, error) {
|
||||
resp, err := a.Ask(ctx, text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resp.Reply, nil
|
||||
},
|
||||
a.streamAskAI,
|
||||
)
|
||||
|
||||
body := []byte(`{"jsonrpc":"2.0","id":1,"method":"message/stream","params":{"message":{"role":"user","parts":[{"kind":"text","text":"run stream tool"}],"kind":"message"}}}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body))
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, req)
|
||||
|
||||
if !sawTool {
|
||||
t.Fatal("A2A stream did not execute the agent tool path")
|
||||
}
|
||||
if ct := rr.Result().Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/event-stream") {
|
||||
t.Fatalf("content-type = %q, want text/event-stream", ct)
|
||||
}
|
||||
if !strings.Contains(rr.Body.String(), "a2a-stream-ok") {
|
||||
t.Fatalf("stream body missing tool marker: %s", rr.Body.String())
|
||||
}
|
||||
|
||||
var final struct {
|
||||
Result struct {
|
||||
Status struct {
|
||||
State string `json:"state"`
|
||||
} `json:"status"`
|
||||
Artifacts []struct {
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"parts"`
|
||||
} `json:"artifacts"`
|
||||
} `json:"result"`
|
||||
Error any `json:"error"`
|
||||
}
|
||||
for _, line := range strings.Split(strings.TrimSpace(rr.Body.String()), "\n") {
|
||||
line = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "data: "))
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &final); err != nil {
|
||||
t.Fatalf("decode event %q: %v", line, err)
|
||||
}
|
||||
}
|
||||
if final.Error != nil {
|
||||
t.Fatalf("final event error: %+v", final.Error)
|
||||
}
|
||||
if final.Result.Status.State != "completed" {
|
||||
t.Fatalf("final state = %q, want completed", final.Result.Status.State)
|
||||
}
|
||||
if len(final.Result.Artifacts) != 1 || len(final.Result.Artifacts[0].Parts) != 1 || !strings.Contains(final.Result.Artifacts[0].Parts[0].Text, "a2a-stream-ok") {
|
||||
t.Fatalf("final artifacts = %+v, want tool marker", final.Result.Artifacts)
|
||||
}
|
||||
}
|
||||
+99
-35
@@ -19,6 +19,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
pb "go-micro.dev/v6/agent/proto"
|
||||
@@ -33,6 +34,7 @@ import (
|
||||
_ "go-micro.dev/v6/ai/gemini"
|
||||
_ "go-micro.dev/v6/ai/groq"
|
||||
_ "go-micro.dev/v6/ai/mistral"
|
||||
_ "go-micro.dev/v6/ai/ollama"
|
||||
_ "go-micro.dev/v6/ai/openai"
|
||||
_ "go-micro.dev/v6/ai/together"
|
||||
)
|
||||
@@ -148,6 +150,9 @@ func (a *agentImpl) setupWithToolHandler(handler ai.ToolHandler) {
|
||||
if a.opts.Model != "" {
|
||||
modelOpts = append(modelOpts, ai.WithModel(a.opts.Model))
|
||||
}
|
||||
if a.opts.BaseURL != "" {
|
||||
modelOpts = append(modelOpts, ai.WithBaseURL(a.opts.BaseURL))
|
||||
}
|
||||
|
||||
// Reuse the existing tools instance: its name map is populated by
|
||||
// discoverTools, and rebuilding it here would orphan a base handler that
|
||||
@@ -177,7 +182,9 @@ func (a *agentImpl) setupWithToolHandler(handler ai.ToolHandler) {
|
||||
case a.ephemeral:
|
||||
a.mem = NewInMemory(a.opts.HistoryLimit)
|
||||
case a.opts.MemoryCompaction.MaxMessages > 0:
|
||||
a.mem = NewCompactingMemory(a.stateStore(), "history", a.opts.MemoryCompaction.MaxMessages, a.opts.MemoryCompaction.KeepRecent)
|
||||
a.mem = NewCompactingMemoryWithOptions(a.stateStore(), "history", a.opts.MemoryCompaction)
|
||||
case a.opts.MemoryRetrievalLimit > 0:
|
||||
a.mem = NewRetrievalMemory(a.stateStore(), "history", a.opts.MemoryRetrievalLimit)
|
||||
default:
|
||||
a.mem = NewMemory(a.stateStore(), "history", a.opts.HistoryLimit)
|
||||
}
|
||||
@@ -271,6 +278,9 @@ func (a *agentImpl) askLocked(ctx context.Context, runID, message, parentRunID s
|
||||
return nil, err
|
||||
}
|
||||
ctx, endRun := a.startRun(ctx, message)
|
||||
if existing != nil {
|
||||
a.recordTimelineEvent(ctx, RunEvent{Time: time.Now(), RunID: runID, ParentID: parentRunID, Agent: a.opts.Name, Kind: "resume", Name: run.State.Stage})
|
||||
}
|
||||
defer func() { endRun(err) }()
|
||||
|
||||
messages := a.mem.Messages()
|
||||
@@ -283,41 +293,77 @@ func (a *agentImpl) askLocked(ctx context.Context, runID, message, parentRunID s
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := ai.GenerateWithRetry(ctx, a.model, &ai.Request{
|
||||
Prompt: message,
|
||||
SystemPrompt: a.buildPrompt(),
|
||||
Tools: toolList,
|
||||
Messages: messages,
|
||||
}, ai.GeneratePolicy{
|
||||
Timeout: a.opts.ModelTimeout,
|
||||
MaxAttempts: a.opts.ModelMaxAttempts,
|
||||
Backoff: a.opts.ModelRetryBackoff,
|
||||
})
|
||||
if err != nil {
|
||||
run.Status = "failed"
|
||||
run.Steps[0].Status = "failed"
|
||||
run.Steps[0].Error = err.Error()
|
||||
if a.currentRun != nil {
|
||||
run.Steps = a.currentRun.Steps
|
||||
}
|
||||
_ = a.saveRun(ctx, run)
|
||||
return nil, err
|
||||
}
|
||||
if a.pause != nil && a.opts.Checkpoint != nil {
|
||||
run.Status = "paused"
|
||||
run.State.Stage = agentApprovalStep
|
||||
run.State.Data = []byte(message)
|
||||
if a.pause.Tool == toolHumanInput {
|
||||
run.State.Stage = agentInputStep
|
||||
_ = run.State.Set(inputPause{OriginalMessage: message, Prompt: a.pause.Message})
|
||||
}
|
||||
run.Steps[0].Status = "paused"
|
||||
run.Steps[0].Error = a.pause.Message
|
||||
run.Steps[0].Result = a.pause.Tool
|
||||
if err := a.saveRun(ctx, run); err != nil {
|
||||
const maxPlanCompletionTurns = 3
|
||||
var resp *ai.Response
|
||||
for planCompletionTurn := 0; ; planCompletionTurn++ {
|
||||
resp, err = ai.GenerateWithRetry(ctx, a.model, &ai.Request{
|
||||
Prompt: message,
|
||||
SystemPrompt: a.buildPrompt(),
|
||||
Tools: toolList,
|
||||
Messages: messages,
|
||||
}, ai.GeneratePolicy{
|
||||
Timeout: a.opts.ModelTimeout,
|
||||
MaxAttempts: a.opts.ModelMaxAttempts,
|
||||
Backoff: a.opts.ModelRetryBackoff,
|
||||
})
|
||||
if err != nil {
|
||||
run.Status = agentRunFailureStatus(err)
|
||||
if a.currentRun != nil {
|
||||
run.Steps = a.currentRun.Steps
|
||||
}
|
||||
if len(run.Steps) == 0 {
|
||||
run.Steps = []flow.StepRecord{{Name: agentAskStep}}
|
||||
}
|
||||
run.Steps[0].Status = run.Status
|
||||
run.Steps[0].Error = err.Error()
|
||||
_ = a.saveRun(ctx, run)
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("agent run %s paused for approval: %s", run.ID, a.pause.Message)
|
||||
if a.pause != nil && a.opts.Checkpoint != nil {
|
||||
run.Status = "paused"
|
||||
run.State.Stage = agentApprovalStep
|
||||
run.State.Data = []byte(message)
|
||||
if a.pause.Tool == toolHumanInput {
|
||||
run.State.Stage = agentInputStep
|
||||
_ = run.State.Set(inputPause{OriginalMessage: message, Prompt: a.pause.Message})
|
||||
}
|
||||
run.Steps[0].Status = "paused"
|
||||
run.Steps[0].Error = a.pause.Message
|
||||
run.Steps[0].Result = a.pause.Tool
|
||||
if err := a.saveRun(ctx, run); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("agent run %s paused for approval: %s", run.ID, a.pause.Message)
|
||||
}
|
||||
|
||||
if len(resp.ToolCalls) == 0 {
|
||||
if calls, answer, ok := a.executeTextToolCalls(ctx, resp.Reply, toolList); ok {
|
||||
resp.ToolCalls = calls
|
||||
if resp.Answer == "" {
|
||||
resp.Answer = answer
|
||||
}
|
||||
trimmedReply := strings.TrimSpace(resp.Reply)
|
||||
if strings.HasPrefix(trimmedReply, "{") || strings.HasPrefix(trimmedReply, "[") || strings.HasPrefix(trimmedReply, "```") {
|
||||
resp.Reply = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if a.opts.Checkpoint != nil {
|
||||
if unfinished := a.unfinishedPlanSteps(); len(unfinished) > 0 && planCompletionTurn < maxPlanCompletionTurns {
|
||||
if resp.Reply != "" {
|
||||
a.mem.Add("assistant", resp.Reply)
|
||||
}
|
||||
if resp.Answer != "" {
|
||||
a.mem.Add("assistant", resp.Answer)
|
||||
}
|
||||
message = "Continue the run. These plan steps are still unfinished and must be completed before a final answer: " + strings.Join(unfinished, ", ")
|
||||
a.mem.Add("user", message)
|
||||
messages = a.mem.Messages()
|
||||
continue
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if resp.Reply != "" {
|
||||
@@ -342,6 +388,24 @@ func (a *agentImpl) askLocked(ctx context.Context, runID, message, parentRunID s
|
||||
RunID: a.runID,
|
||||
ParentID: parentRunID,
|
||||
}
|
||||
if a.opts.Checkpoint != nil {
|
||||
if unfinished := a.unfinishedPlanSteps(); len(unfinished) > 0 {
|
||||
err = fmt.Errorf("agent run %s has unfinished plan steps: %s", run.ID, strings.Join(unfinished, ", "))
|
||||
run.Status = "failed"
|
||||
run.State.Stage = agentAskStep
|
||||
run.State.Data = []byte(message)
|
||||
if a.currentRun != nil {
|
||||
run.Steps = a.currentRun.Steps
|
||||
}
|
||||
if len(run.Steps) == 0 {
|
||||
run.Steps = []flow.StepRecord{{Name: agentAskStep}}
|
||||
}
|
||||
run.Steps[0].Status = "failed"
|
||||
run.Steps[0].Error = err.Error()
|
||||
_ = a.saveRun(ctx, run)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
run.Status = "done"
|
||||
run.State.Stage = ""
|
||||
if b, marshalErr := json.Marshal(res); marshalErr == nil {
|
||||
@@ -419,7 +483,7 @@ func (a *agentImpl) Run() error {
|
||||
return "", err
|
||||
}
|
||||
return resp.Reply, nil
|
||||
}, a.Stream)
|
||||
}, a.streamAskAI)
|
||||
go func() {
|
||||
if err := http.ListenAndServe(a.opts.A2AAddress, handler); err != nil {
|
||||
fmt.Printf("agent %s A2A server: %v\n", a.opts.Name, err)
|
||||
|
||||
+163
-1
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
codecBytes "go-micro.dev/v6/codec/bytes"
|
||||
@@ -121,6 +122,7 @@ func (a *agentImpl) toolHandler() ai.ToolHandler {
|
||||
// so the result runs plan → step → loop → approve → checkpoint → base.
|
||||
h := a.baseHandler()
|
||||
h = a.toolTimeoutWrap(h)
|
||||
h = a.toolRetryWrap(h)
|
||||
h = a.checkpointToolWrap(h)
|
||||
h = a.approveWrap(h)
|
||||
h = a.loopWrap(h)
|
||||
@@ -164,6 +166,99 @@ func (a *agentImpl) toolTimeoutWrap(next ai.ToolHandler) ai.ToolHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// toolRetryWrap retries transient tool failures with bounded backoff. It is
|
||||
// opt-in because tools can have side effects; guardrail refusals and caller
|
||||
// cancellation are never retried.
|
||||
func (a *agentImpl) toolRetryWrap(next ai.ToolHandler) ai.ToolHandler {
|
||||
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
|
||||
maxAttempts := a.opts.ToolMaxAttempts
|
||||
if maxAttempts <= 0 {
|
||||
maxAttempts = 1
|
||||
}
|
||||
|
||||
var res ai.ToolResult
|
||||
for attempt := 1; attempt <= maxAttempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return errResult(call.ID, err.Error())
|
||||
}
|
||||
res = next(ctx, call)
|
||||
if !retryableToolResult(res) || attempt == maxAttempts || ctx.Err() != nil {
|
||||
return annotateToolAttempts(res, attempt)
|
||||
}
|
||||
|
||||
t := time.NewTimer(toolRetryBackoff(attempt, a.opts.ToolRetryBackoff))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if !t.Stop() {
|
||||
<-t.C
|
||||
}
|
||||
return errResult(call.ID, ctx.Err().Error())
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
return annotateToolAttempts(res, maxAttempts)
|
||||
}
|
||||
}
|
||||
|
||||
func retryableToolResult(res ai.ToolResult) bool {
|
||||
if res.Refused != "" {
|
||||
return false
|
||||
}
|
||||
msg := toolErrorMessage(res)
|
||||
if msg == "" {
|
||||
return false
|
||||
}
|
||||
return ai.IsTransientError(fmt.Errorf("%s", msg))
|
||||
}
|
||||
|
||||
func toolErrorMessage(res ai.ToolResult) string {
|
||||
if m, ok := res.Value.(map[string]string); ok {
|
||||
return m["error"]
|
||||
}
|
||||
if m, ok := res.Value.(map[string]any); ok {
|
||||
if v, ok := m["error"].(string); ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
var decoded map[string]string
|
||||
if err := json.Unmarshal([]byte(res.Content), &decoded); err == nil {
|
||||
return decoded["error"]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func annotateToolAttempts(res ai.ToolResult, attempts int) ai.ToolResult {
|
||||
if attempts <= 1 {
|
||||
return res
|
||||
}
|
||||
res.Attempts = attempts
|
||||
if m, ok := res.Value.(map[string]string); ok {
|
||||
cp := map[string]any{}
|
||||
for k, v := range m {
|
||||
cp[k] = v
|
||||
}
|
||||
cp["attempts"] = attempts
|
||||
res.Value = cp
|
||||
if b, err := json.Marshal(cp); err == nil {
|
||||
res.Content = string(b)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func toolRetryBackoff(attempt int, base time.Duration) time.Duration {
|
||||
if base <= 0 {
|
||||
base = 200 * time.Millisecond
|
||||
}
|
||||
if shift := attempt - 1; shift > 0 {
|
||||
base <<= shift
|
||||
}
|
||||
if base > 30*time.Second {
|
||||
return 30 * time.Second
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// baseHandler executes a tool call: a developer custom tool, the built-in
|
||||
// delegate, or an RPC to the service. It is the innermost handler.
|
||||
func (a *agentImpl) baseHandler() ai.ToolHandler {
|
||||
@@ -195,7 +290,11 @@ func (a *agentImpl) planWrap(next ai.ToolHandler) ai.ToolHandler {
|
||||
if call.Name == toolPlan {
|
||||
return a.handlePlan(call)
|
||||
}
|
||||
return next(ctx, call)
|
||||
res := next(ctx, call)
|
||||
if res.Refused == "" && toolErrorMessage(res) == "" {
|
||||
a.completeNextPlanStep()
|
||||
}
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,6 +372,68 @@ func (a *agentImpl) handlePlan(call ai.ToolCall) ai.ToolResult {
|
||||
return ai.ToolResult{ID: call.ID, Value: call.Input, Content: string(data)}
|
||||
}
|
||||
|
||||
func (a *agentImpl) completeNextPlanStep() {
|
||||
plan := a.loadPlan()
|
||||
if plan == "" {
|
||||
return
|
||||
}
|
||||
var data map[string]any
|
||||
if err := json.Unmarshal([]byte(plan), &data); err != nil {
|
||||
return
|
||||
}
|
||||
steps, ok := data["steps"].([]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for _, raw := range steps {
|
||||
step, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
status, _ := step["status"].(string)
|
||||
if status == "" || status == "pending" || status == "in_progress" {
|
||||
step["status"] = "done"
|
||||
b, err := json.Marshal(data)
|
||||
if err == nil {
|
||||
_ = a.stateStore().Write(&store.Record{Key: planKey, Value: b})
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *agentImpl) unfinishedPlanSteps() []string {
|
||||
plan := a.loadPlan()
|
||||
if plan == "" {
|
||||
return nil
|
||||
}
|
||||
var data map[string]any
|
||||
if err := json.Unmarshal([]byte(plan), &data); err != nil {
|
||||
return nil
|
||||
}
|
||||
steps, ok := data["steps"].([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var unfinished []string
|
||||
for _, raw := range steps {
|
||||
step, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
status, _ := step["status"].(string)
|
||||
if status != "" && status != "pending" && status != "in_progress" {
|
||||
continue
|
||||
}
|
||||
task, _ := step["task"].(string)
|
||||
if task == "" {
|
||||
task = "<unnamed>"
|
||||
}
|
||||
unfinished = append(unfinished, task)
|
||||
}
|
||||
return unfinished
|
||||
}
|
||||
|
||||
// handleHumanInput records that the model needs operator input before it can continue.
|
||||
func (a *agentImpl) handleHumanInput(call ai.ToolCall) ai.ToolResult {
|
||||
prompt, _ := call.Input["prompt"].(string)
|
||||
@@ -338,6 +499,7 @@ func (a *agentImpl) handleDelegate(ctx context.Context, call ai.ToolCall) ai.Too
|
||||
ModelCallTimeout(a.opts.ModelTimeout),
|
||||
ModelRetry(a.opts.ModelMaxAttempts, a.opts.ModelRetryBackoff),
|
||||
ToolCallTimeout(a.opts.ToolTimeout),
|
||||
ToolRetry(a.opts.ToolMaxAttempts, a.opts.ToolRetryBackoff),
|
||||
TraceProvider(a.opts.TraceProvider),
|
||||
)
|
||||
// Record lineage so the sub-agent's tool calls carry this run as parent.
|
||||
|
||||
+20
-1
@@ -49,6 +49,12 @@ func (a *agentImpl) saveRun(ctx context.Context, run flow.Run) error {
|
||||
if err := a.opts.Checkpoint.Save(ctx, run); err != nil {
|
||||
return fmt.Errorf("agent %s checkpoint save: %w", a.opts.Name, err)
|
||||
}
|
||||
if info, ok := ai.RunInfoFrom(ctx); ok {
|
||||
a.recordTimelineEvent(ctx, RunEvent{
|
||||
Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent,
|
||||
Kind: "checkpoint", Name: run.State.Stage, Status: run.Status,
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -165,13 +171,26 @@ func (a *agentImpl) pending(ctx context.Context) ([]flow.Run, error) {
|
||||
|
||||
func terminalAgentRunStatus(status string) bool {
|
||||
switch status {
|
||||
case "done", "canceled", "expired":
|
||||
case "done", "canceled", "timeout", "rate_limited", "expired":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func agentRunFailureStatus(err error) string {
|
||||
switch ai.ClassifyError(err) {
|
||||
case ai.ErrorKindCanceled:
|
||||
return "canceled"
|
||||
case ai.ErrorKindTimeout:
|
||||
return "timeout"
|
||||
case ai.ErrorKindRateLimited:
|
||||
return "rate_limited"
|
||||
default:
|
||||
return "failed"
|
||||
}
|
||||
}
|
||||
|
||||
func (a *agentImpl) checkpointToolWrap(next ai.ToolHandler) ai.ToolHandler {
|
||||
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
|
||||
if a.opts.Checkpoint == nil || a.currentRun == nil {
|
||||
|
||||
@@ -7,7 +7,10 @@ import (
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/client"
|
||||
codecBytes "go-micro.dev/v6/codec/bytes"
|
||||
"go-micro.dev/v6/flow"
|
||||
"go-micro.dev/v6/registry"
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
|
||||
@@ -102,6 +105,189 @@ func TestResumeFailedCheckpointDoesNotReplayCompletedTool(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointSkipsDuplicateToolWithinAsk(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cp := flow.StoreCheckpoint(store.NewMemoryStore(), "tool-dedupe-agent")
|
||||
toolRuns := 0
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
if opts.ToolHandler == nil {
|
||||
t.Fatal("missing tool handler")
|
||||
}
|
||||
opts.ToolHandler(ctx, ai.ToolCall{ID: "plan-1", Name: toolPlan, Input: map[string]any{
|
||||
"steps": []any{
|
||||
map[string]any{"task": "create Design task", "status": "pending"},
|
||||
},
|
||||
}})
|
||||
for i := 0; i < 3; i++ {
|
||||
res := opts.ToolHandler(ctx, ai.ToolCall{ID: "call-1", Name: "external.create", Input: map[string]any{"title": "Design"}})
|
||||
if res.Content != "created Design" {
|
||||
t.Fatalf("tool result %d = %q, want cached created Design", i, res.Content)
|
||||
}
|
||||
}
|
||||
return &ai.Response{Reply: "done"}, nil
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
a := newTestAgent(Name("tool-dedupe-agent"), WithCheckpoint(cp),
|
||||
WithTool("external.create", "create once", nil, func(context.Context, map[string]any) (string, error) {
|
||||
toolRuns++
|
||||
return "created Design", nil
|
||||
}))
|
||||
if _, err := a.Ask(ctx, "create Design once"); err != nil {
|
||||
t.Fatalf("Ask: %v", err)
|
||||
}
|
||||
if toolRuns != 1 {
|
||||
t.Fatalf("tool executions = %d, want duplicate calls within the run replayed from checkpoint", toolRuns)
|
||||
}
|
||||
if plan := a.loadPlan(); !strings.Contains(plan, `"status":"done"`) {
|
||||
t.Fatalf("plan = %s, want completed action marked done", plan)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointContinuesRunWithUnfinishedPlanStep(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cp := flow.StoreCheckpoint(store.NewMemoryStore(), "unfinished-plan-agent")
|
||||
|
||||
reg := registry.NewMemoryRegistry()
|
||||
if err := reg.Register(®istry.Service{
|
||||
Name: "comms",
|
||||
Metadata: map[string]string{"type": "agent"},
|
||||
Nodes: []*registry.Node{{Id: "comms-1", Address: "127.0.0.1:0"}},
|
||||
}); err != nil {
|
||||
t.Fatalf("register comms agent: %v", err)
|
||||
}
|
||||
|
||||
delegateCalls := 0
|
||||
fc := &fakeClient{Client: client.DefaultClient}
|
||||
fc.callFn = func(ctx context.Context, req client.Request, rsp interface{}) error {
|
||||
delegateCalls++
|
||||
if req.Service() != "comms" || req.Endpoint() != "Agent.Chat" {
|
||||
t.Fatalf("delegate RPC = %s %s, want comms Agent.Chat", req.Service(), req.Endpoint())
|
||||
}
|
||||
frame := rsp.(*codecBytes.Frame)
|
||||
frame.Data = []byte(`{"reply":"owner notified","agent":"comms"}`)
|
||||
return nil
|
||||
}
|
||||
|
||||
modelCalls := 0
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
modelCalls++
|
||||
if opts.ToolHandler == nil {
|
||||
t.Fatal("missing tool handler")
|
||||
}
|
||||
switch modelCalls {
|
||||
case 1:
|
||||
opts.ToolHandler(ctx, ai.ToolCall{ID: "plan-1", Name: toolPlan, Input: map[string]any{
|
||||
"steps": []any{
|
||||
map[string]any{"task": "create launch tasks", "status": "done"},
|
||||
map[string]any{"task": "delegate readiness notification to comms", "status": "in_progress"},
|
||||
},
|
||||
}})
|
||||
return &ai.Response{Reply: "tasks are ready"}, nil
|
||||
case 2:
|
||||
if !strings.Contains(req.Prompt, "delegate readiness notification to comms") {
|
||||
t.Fatalf("continuation prompt = %q, want unfinished step", req.Prompt)
|
||||
}
|
||||
res := opts.ToolHandler(ctx, ai.ToolCall{ID: "delegate-1", Name: toolDelegate, Input: map[string]any{"task": "Notify owner@acme.com that the launch plan is ready", "to": "comms"}})
|
||||
if !strings.Contains(res.Content, "owner notified") {
|
||||
t.Fatalf("delegate result = %q, want owner notified", res.Content)
|
||||
}
|
||||
return &ai.Response{Reply: "all done"}, nil
|
||||
default:
|
||||
t.Fatalf("unexpected model call %d", modelCalls)
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
a := newTestAgent(Name("unfinished-plan-agent"), WithCheckpoint(cp), WithRegistry(reg), WithClient(fc))
|
||||
resp, err := a.Ask(ctx, "create tasks and notify owner")
|
||||
if err != nil {
|
||||
t.Fatalf("Ask: %v", err)
|
||||
}
|
||||
if resp.Reply != "all done" {
|
||||
t.Fatalf("reply = %q, want final continuation reply", resp.Reply)
|
||||
}
|
||||
if modelCalls != 2 {
|
||||
t.Fatalf("model calls = %d, want initial plus continuation", modelCalls)
|
||||
}
|
||||
if delegateCalls != 1 {
|
||||
t.Fatalf("delegate calls = %d, want exactly one", delegateCalls)
|
||||
}
|
||||
if unfinished := a.unfinishedPlanSteps(); len(unfinished) != 0 {
|
||||
t.Fatalf("unfinished plan steps = %v, want none", unfinished)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeFailedCheckpointAfterFreshAgentRestart(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cp := flow.StoreCheckpoint(store.NewMemoryStore(), "restart-resume-agent")
|
||||
toolRuns := 0
|
||||
modelCalls := 0
|
||||
failFirst := true
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
modelCalls++
|
||||
if opts.ToolHandler != nil {
|
||||
res := opts.ToolHandler(ctx, ai.ToolCall{ID: "call-1", Name: "external.provision", Input: map[string]any{"service": "api"}})
|
||||
if res.Content != "provisioned" {
|
||||
t.Fatalf("tool result = %q, want provisioned", res.Content)
|
||||
}
|
||||
}
|
||||
if failFirst {
|
||||
failFirst = false
|
||||
return nil, errors.New("process stopped after tool checkpoint")
|
||||
}
|
||||
return &ai.Response{Reply: "resumed after restart"}, nil
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
newAgent := func() *agentImpl {
|
||||
return newTestAgent(Name("restart-resume-agent"), WithCheckpoint(cp),
|
||||
WithTool("external.provision", "provision service once", nil, func(context.Context, map[string]any) (string, error) {
|
||||
toolRuns++
|
||||
return "provisioned", nil
|
||||
}))
|
||||
}
|
||||
|
||||
first := newAgent()
|
||||
_, err := first.Ask(ctx, "provision api")
|
||||
if err == nil {
|
||||
t.Fatal("Ask succeeded, want simulated process stop")
|
||||
}
|
||||
if toolRuns != 1 {
|
||||
t.Fatalf("tool executions after failed Ask = %d, want 1", toolRuns)
|
||||
}
|
||||
runs, err := Pending(ctx, first)
|
||||
if err != nil {
|
||||
t.Fatalf("Pending before restart: %v", err)
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("Pending before restart returned %d runs, want 1", len(runs))
|
||||
}
|
||||
|
||||
restarted := newAgent()
|
||||
resp, err := Resume(ctx, restarted, runs[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("Resume after restart: %v", err)
|
||||
}
|
||||
if resp.Reply != "resumed after restart" || resp.RunID != runs[0].ID {
|
||||
t.Fatalf("response = %#v, want resumed reply on original run id", resp)
|
||||
}
|
||||
if toolRuns != 1 {
|
||||
t.Fatalf("tool executions after restart resume = %d, want checkpointed tool not replayed", toolRuns)
|
||||
}
|
||||
if modelCalls != 2 {
|
||||
t.Fatalf("model calls = %d, want initial call plus resumed call", modelCalls)
|
||||
}
|
||||
loaded, ok, err := cp.Load(ctx, runs[0].ID)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("Load resumed run ok=%v err=%v", ok, err)
|
||||
}
|
||||
if loaded.Status != "done" || loaded.ParentID != runs[0].ParentID {
|
||||
t.Fatalf("loaded run status/parent = %s/%s, want done/%s", loaded.Status, loaded.ParentID, runs[0].ParentID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeFailedCheckpointDoesNotDuplicateCompactedMemory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
st := store.NewMemoryStore()
|
||||
|
||||
@@ -171,3 +171,50 @@ func TestAgentProviderConformanceFakeError(t *testing.T) {
|
||||
t.Fatalf("Ask error = %v, want conformance provider failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentExecutesProviderTextToolCallFallback(t *testing.T) {
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
if opts.ToolHandler == nil {
|
||||
return nil, errors.New("missing tool handler")
|
||||
}
|
||||
return &ai.Response{
|
||||
Reply: `{"name":"conformance_echo","input":{"value":"agent-conformance"}}`,
|
||||
}, nil
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
var sawTool bool
|
||||
a := New(
|
||||
Name("conformance-text-tool"),
|
||||
Provider("fake"),
|
||||
WithRegistry(registry.NewMemoryRegistry()),
|
||||
WithStore(store.NewMemoryStore()),
|
||||
WithMemory(NewInMemory(4)),
|
||||
WithTool("conformance_echo", "Echo a conformance value.", map[string]any{
|
||||
"value": map[string]any{"type": "string"},
|
||||
}, func(ctx context.Context, input map[string]any) (string, error) {
|
||||
sawTool = true
|
||||
if input["value"] != "agent-conformance" {
|
||||
return "", fmt.Errorf("unexpected value %v", input["value"])
|
||||
}
|
||||
return `{"marker":"agent-conformance-ok"}`, nil
|
||||
}),
|
||||
)
|
||||
|
||||
resp, err := a.Ask(context.Background(), "Run the text tool call fallback.")
|
||||
if err != nil {
|
||||
t.Fatalf("Ask: %v", err)
|
||||
}
|
||||
if !sawTool {
|
||||
t.Fatal("text tool call fallback did not execute the tool")
|
||||
}
|
||||
if len(resp.ToolCalls) != 1 || resp.ToolCalls[0].Name != "conformance_echo" {
|
||||
t.Fatalf("ToolCalls = %+v, want conformance_echo", resp.ToolCalls)
|
||||
}
|
||||
if !strings.Contains(resp.Reply, "agent-conformance-ok") {
|
||||
t.Fatalf("Reply = %q, want tool result marker", resp.Reply)
|
||||
}
|
||||
if strings.Contains(resp.Reply, `"name":"conformance_echo"`) {
|
||||
t.Fatalf("Reply = %q, want tool result instead of raw JSON", resp.Reply)
|
||||
}
|
||||
}
|
||||
|
||||
+55
-9
@@ -24,6 +24,12 @@ type Memory interface {
|
||||
Clear()
|
||||
}
|
||||
|
||||
// MemorySummaryFunc turns older conversation messages into a compact
|
||||
// replacement message for active context. It is called while the default
|
||||
// memory is locked, so implementations should be deterministic and avoid
|
||||
// calling back into the same memory instance.
|
||||
type MemorySummaryFunc func([]ai.Message) ai.Message
|
||||
|
||||
// MemoryCompaction configures deterministic, store-backed context compaction
|
||||
// for the default memory implementation. When the retained conversation grows
|
||||
// past MaxMessages, older turns are collapsed into a summary message while the
|
||||
@@ -31,6 +37,7 @@ type Memory interface {
|
||||
type MemoryCompaction struct {
|
||||
MaxMessages int
|
||||
KeepRecent int
|
||||
Summarize MemorySummaryFunc
|
||||
}
|
||||
|
||||
// MemoryRecall is implemented by memory backends that can retrieve durable
|
||||
@@ -49,11 +56,29 @@ func NewMemory(s store.Store, key string, limit int) Memory {
|
||||
return m
|
||||
}
|
||||
|
||||
// NewRetrievalMemory returns store-backed memory that keeps a bounded active
|
||||
// conversation and archives every turn for retrieval. It is useful when callers
|
||||
// want relevant durable recall without summary compaction in the active context.
|
||||
// A nil store or empty key keeps only the active in-process buffer.
|
||||
func NewRetrievalMemory(s store.Store, key string, activeLimit int) Memory {
|
||||
m := &storeMemory{store: s, key: key, hist: ai.NewHistory(activeLimit), retrieveAll: true}
|
||||
m.load()
|
||||
return m
|
||||
}
|
||||
|
||||
// NewCompactingMemory returns store-backed memory with explicit compaction and
|
||||
// retrieval controls. It keeps all messages in the backing store, compacts older
|
||||
// turns into a deterministic summary when the conversation exceeds maxMessages,
|
||||
// and lets callers recall relevant prior turns with Recall.
|
||||
func NewCompactingMemory(s store.Store, key string, maxMessages, keepRecent int) Memory {
|
||||
return NewCompactingMemoryWithOptions(s, key, MemoryCompaction{MaxMessages: maxMessages, KeepRecent: keepRecent})
|
||||
}
|
||||
|
||||
// NewCompactingMemoryWithOptions returns store-backed memory configured with
|
||||
// explicit compaction options, including an optional summarization hook.
|
||||
func NewCompactingMemoryWithOptions(s store.Store, key string, compaction MemoryCompaction) Memory {
|
||||
maxMessages := compaction.MaxMessages
|
||||
keepRecent := compaction.KeepRecent
|
||||
if keepRecent <= 0 {
|
||||
keepRecent = maxMessages / 2
|
||||
}
|
||||
@@ -69,6 +94,7 @@ func NewCompactingMemory(s store.Store, key string, maxMessages, keepRecent int)
|
||||
compaction: MemoryCompaction{
|
||||
MaxMessages: maxMessages,
|
||||
KeepRecent: keepRecent,
|
||||
Summarize: compaction.Summarize,
|
||||
},
|
||||
}
|
||||
m.load()
|
||||
@@ -84,16 +110,20 @@ func NewInMemory(limit int) Memory {
|
||||
// storeMemory is the default Memory: an ai.History buffer optionally
|
||||
// persisted to a store.
|
||||
type storeMemory struct {
|
||||
mu sync.Mutex
|
||||
store store.Store
|
||||
key string
|
||||
hist *ai.History
|
||||
compaction MemoryCompaction
|
||||
archive []ai.Message
|
||||
mu sync.Mutex
|
||||
store store.Store
|
||||
key string
|
||||
hist *ai.History
|
||||
compaction MemoryCompaction
|
||||
archive []ai.Message
|
||||
retrieveAll bool
|
||||
}
|
||||
|
||||
func (m *storeMemory) Add(role, content string) {
|
||||
m.mu.Lock()
|
||||
if m.retrieveAll {
|
||||
m.archive = append(m.archive, ai.Message{Role: role, Content: content})
|
||||
}
|
||||
m.hist.Add(role, content)
|
||||
m.mu.Unlock()
|
||||
m.compact()
|
||||
@@ -117,6 +147,8 @@ func (m *storeMemory) Clear() {
|
||||
// Recall returns archived messages whose content contains words from query.
|
||||
// It is deterministic and provider-neutral: no embeddings or model calls are
|
||||
// required, but semantic/vector stores can replace Memory for richer retrieval.
|
||||
// When created with NewRetrievalMemory the archive contains every persisted
|
||||
// turn; when created with NewCompactingMemory it contains compacted older turns.
|
||||
func (m *storeMemory) Recall(query string, limit int) []ai.Message {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@@ -170,6 +202,9 @@ func (m *storeMemory) load() {
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.archive = state.Archive
|
||||
if m.retrieveAll && len(m.archive) == 0 {
|
||||
m.archive = append(m.archive, state.Messages...)
|
||||
}
|
||||
for _, msg := range state.Messages {
|
||||
m.hist.Add(msg.Role, msg.Content)
|
||||
}
|
||||
@@ -213,9 +248,13 @@ func (m *storeMemory) compact() {
|
||||
older := msgs[:cut]
|
||||
recent := msgs[cut:]
|
||||
m.archive = append(m.archive, older...)
|
||||
summary := ai.Message{
|
||||
Role: "system",
|
||||
Content: fmt.Sprintf("Conversation memory summary: %s", summarizeMessages(older)),
|
||||
summarize := m.compaction.Summarize
|
||||
if summarize == nil {
|
||||
summarize = defaultMemorySummary
|
||||
}
|
||||
summary := summarize(older)
|
||||
if summary.Role == "" {
|
||||
summary.Role = "system"
|
||||
}
|
||||
m.hist.Reset()
|
||||
m.hist.Add(summary.Role, summary.Content)
|
||||
@@ -224,6 +263,13 @@ func (m *storeMemory) compact() {
|
||||
}
|
||||
}
|
||||
|
||||
func defaultMemorySummary(msgs []ai.Message) ai.Message {
|
||||
return ai.Message{
|
||||
Role: "system",
|
||||
Content: fmt.Sprintf("Conversation memory summary: %s", summarizeMessages(msgs)),
|
||||
}
|
||||
}
|
||||
|
||||
func summarizeMessages(msgs []ai.Message) string {
|
||||
var b strings.Builder
|
||||
for i, msg := range msgs {
|
||||
|
||||
@@ -3,9 +3,11 @@ package agent
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/registry"
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
@@ -62,6 +64,49 @@ func TestWithMemoryUsed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetrievalMemoryArchivesAllTurnsAndRanksRelevant(t *testing.T) {
|
||||
st := store.NewMemoryStore()
|
||||
m := NewRetrievalMemory(st, "agent/retrieval/history", 2)
|
||||
m.Add("user", "alpha budget is 42")
|
||||
m.Add("assistant", "noted")
|
||||
m.Add("user", "beta owner is lee")
|
||||
m.Add("assistant", "tracked")
|
||||
m.Add("user", "alpha owner is sam")
|
||||
|
||||
if got := len(m.Messages()); got != 2 {
|
||||
t.Fatalf("active messages = %d, want bounded history of 2", got)
|
||||
}
|
||||
|
||||
recall, ok := m.(MemoryRecall)
|
||||
if !ok {
|
||||
t.Fatal("retrieval memory should support recall")
|
||||
}
|
||||
recalled := recall.Recall("alpha budget", 2)
|
||||
if len(recalled) == 0 {
|
||||
t.Fatal("expected relevant recalled turns")
|
||||
}
|
||||
if got := recalled[0].Content.(string); !strings.Contains(got, "alpha budget is 42") {
|
||||
t.Fatalf("top recall = %q, want archived alpha budget turn", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetrievalMemoryPersistsArchiveAcrossReload(t *testing.T) {
|
||||
st := store.NewMemoryStore()
|
||||
m := NewRetrievalMemory(st, "agent/retrieval/reload", 1)
|
||||
m.Add("user", "alpha budget is 42")
|
||||
m.Add("assistant", "noted")
|
||||
m.Add("user", "beta budget is 7")
|
||||
|
||||
reloaded := NewRetrievalMemory(st, "agent/retrieval/reload", 1)
|
||||
recalled := reloaded.(MemoryRecall).Recall("alpha budget", 1)
|
||||
if len(recalled) != 1 {
|
||||
t.Fatalf("recalled %d messages, want 1", len(recalled))
|
||||
}
|
||||
if got := recalled[0].Content.(string); !strings.Contains(got, "alpha budget is 42") {
|
||||
t.Fatalf("reloaded recall = %q, want alpha budget", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompactingMemoryRecallRanksSpecificMatches(t *testing.T) {
|
||||
m := NewCompactingMemory(store.NewMemoryStore(), "agent/rank/history", 3, 1).(MemoryRecall)
|
||||
writer := m.(Memory)
|
||||
@@ -102,6 +147,36 @@ func TestCompactingMemoryArchivePersistsAndReloads(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompactingMemoryUsesCustomSummarizerAndReloadsRecall(t *testing.T) {
|
||||
st := store.NewMemoryStore()
|
||||
m := NewCompactingMemoryWithOptions(st, "agent/custom/history", MemoryCompaction{
|
||||
MaxMessages: 3,
|
||||
KeepRecent: 1,
|
||||
Summarize: func(msgs []ai.Message) ai.Message {
|
||||
return ai.Message{Role: "system", Content: "custom summary count=" + strconv.Itoa(len(msgs))}
|
||||
},
|
||||
})
|
||||
m.Add("user", "alpha budget is 42")
|
||||
m.Add("assistant", "noted")
|
||||
m.Add("user", "beta budget is 7")
|
||||
m.Add("assistant", "noted")
|
||||
|
||||
msgs := m.Messages()
|
||||
if len(msgs) == 0 || msgs[0].Content != "custom summary count=3" {
|
||||
t.Fatalf("summary = %#v, want custom summarizer output", msgs)
|
||||
}
|
||||
|
||||
reloaded := NewCompactingMemoryWithOptions(st, "agent/custom/history", MemoryCompaction{MaxMessages: 3, KeepRecent: 1})
|
||||
recall := reloaded.(MemoryRecall)
|
||||
recalled := recall.Recall("alpha budget", 1)
|
||||
if len(recalled) != 1 {
|
||||
t.Fatalf("recalled %d messages, want 1", len(recalled))
|
||||
}
|
||||
if got := recalled[0].Content.(string); !strings.Contains(got, "alpha budget is 42") {
|
||||
t.Fatalf("reloaded recall = %q, want alpha budget", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A custom tool is offered to the model and dispatched to its handler.
|
||||
func TestWithToolExposedAndDispatched(t *testing.T) {
|
||||
var got map[string]any
|
||||
|
||||
+50
-1
@@ -40,6 +40,7 @@ type Options struct {
|
||||
Provider string
|
||||
Model string
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Address string
|
||||
Registry registry.Registry
|
||||
Client client.Client
|
||||
@@ -60,10 +61,19 @@ type Options struct {
|
||||
// applied before custom tools, delegate, and service RPC calls so context
|
||||
// deadlines propagate consistently through the agent loop.
|
||||
ToolTimeout time.Duration
|
||||
// ToolMaxAttempts bounds tool execution attempts including the first call.
|
||||
// Default 1; retries are opt-in because tools can have side effects.
|
||||
ToolMaxAttempts int
|
||||
// ToolRetryBackoff is the base delay between transient tool failures.
|
||||
ToolRetryBackoff time.Duration
|
||||
|
||||
// Memory is the agent's conversation memory. Nil = the default
|
||||
// store-backed memory (durable across restarts).
|
||||
Memory Memory
|
||||
// MemoryRetrievalLimit enables retrieval-backed default memory without
|
||||
// compaction. The active conversation stays bounded to this many messages
|
||||
// while every turn is archived for deterministic recall.
|
||||
MemoryRetrievalLimit int
|
||||
// MemoryCompaction enables deterministic compaction/retrieval on the
|
||||
// default store-backed memory. Custom Memory implementations can expose
|
||||
// retrieval by implementing MemoryRecall.
|
||||
@@ -117,6 +127,8 @@ func newOptions(opts ...Option) Options {
|
||||
ModelMaxAttempts: 1, // retries opt-in via ModelRetry (see field doc)
|
||||
ModelRetryBackoff: 100 * time.Millisecond,
|
||||
ToolTimeout: 30 * time.Second,
|
||||
ToolMaxAttempts: 1,
|
||||
ToolRetryBackoff: 100 * time.Millisecond,
|
||||
// On by default and lenient: identical repeated calls are a
|
||||
// no-progress loop, never useful. Set LoopLimit(0) to disable.
|
||||
LoopLimit: 3,
|
||||
@@ -157,6 +169,12 @@ func APIKey(k string) Option {
|
||||
return func(o *Options) { o.APIKey = k }
|
||||
}
|
||||
|
||||
// BaseURL sets the base URL for the LLM provider. Use this to point
|
||||
// the provider at a non-default endpoint (e.g., local Ollama, a proxy).
|
||||
func BaseURL(url string) Option {
|
||||
return func(o *Options) { o.BaseURL = url }
|
||||
}
|
||||
|
||||
// Address sets the network address for the agent's service endpoint.
|
||||
// Use "127.0.0.1:0" in local harnesses/tests to bind an ephemeral loopback
|
||||
// port and avoid advertising the default service address.
|
||||
@@ -225,6 +243,16 @@ func ModelRetry(maxAttempts int, backoff time.Duration) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// ToolRetry sets the tool retry budget and backoff for transient failures.
|
||||
// Attempts include the first call. Retries are opt-in because tools may have
|
||||
// side effects; keep handlers idempotent before enabling this.
|
||||
func ToolRetry(maxAttempts int, backoff time.Duration) Option {
|
||||
return func(o *Options) {
|
||||
o.ToolMaxAttempts = maxAttempts
|
||||
o.ToolRetryBackoff = backoff
|
||||
}
|
||||
}
|
||||
|
||||
// WithA2A makes Run serve the agent over the A2A protocol on addr (e.g.
|
||||
// ":4000"), so other agents can reach it directly by URL without a
|
||||
// separate gateway. The agent stays a normal go-micro service as well;
|
||||
@@ -240,19 +268,40 @@ func WithMemory(m Memory) Option {
|
||||
return func(o *Options) { o.Memory = m }
|
||||
}
|
||||
|
||||
// RetrievalMemory enables deterministic, store-backed retrieval memory for
|
||||
// the default agent memory without compaction. Active context is capped at
|
||||
// activeLimit messages while every turn is archived in the store for Recall.
|
||||
func RetrievalMemory(activeLimit int) Option {
|
||||
return func(o *Options) {
|
||||
o.MemoryRetrievalLimit = activeLimit
|
||||
if o.MemoryRecallLimit == 0 {
|
||||
o.MemoryRecallLimit = 5
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CompactMemory enables deterministic, store-backed memory compaction for the
|
||||
// default agent memory. Older turns are summarized once active context exceeds
|
||||
// maxMessages, keepRecent newest turns remain verbatim, and recalled archived
|
||||
// turns are injected into matching future asks.
|
||||
func CompactMemory(maxMessages, keepRecent int) Option {
|
||||
return func(o *Options) {
|
||||
o.MemoryCompaction = MemoryCompaction{MaxMessages: maxMessages, KeepRecent: keepRecent}
|
||||
o.MemoryCompaction.MaxMessages = maxMessages
|
||||
o.MemoryCompaction.KeepRecent = keepRecent
|
||||
if o.MemoryRecallLimit == 0 {
|
||||
o.MemoryRecallLimit = 5
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MemorySummarizer sets the deterministic summarization hook used by the
|
||||
// default compacting memory. It is optional; without it, compacted memory uses
|
||||
// a provider-neutral text summary. The hook receives the older messages being
|
||||
// removed from active context and returns the replacement summary message.
|
||||
func MemorySummarizer(fn MemorySummaryFunc) Option {
|
||||
return func(o *Options) { o.MemoryCompaction.Summarize = fn }
|
||||
}
|
||||
|
||||
// MemoryRecallLimit sets how many archived turns a memory backend may inject
|
||||
// into a model request for the current Ask. Use 0 to disable retrieval.
|
||||
func MemoryRecallLimit(n int) Option {
|
||||
|
||||
+69
-22
@@ -22,23 +22,30 @@ const (
|
||||
spanNameModelCall = "agent.model.call"
|
||||
spanNameToolCall = "agent.tool.call"
|
||||
|
||||
AttrRunID = "agent.run.id"
|
||||
AttrParentRunID = "agent.run.parent_id"
|
||||
AttrAgentName = "agent.name"
|
||||
AttrProvider = "agent.model.provider"
|
||||
AttrModel = "agent.model.name"
|
||||
AttrLatencyMS = "agent.latency_ms"
|
||||
AttrInputTokens = "agent.tokens.input"
|
||||
AttrOutputTokens = "agent.tokens.output"
|
||||
AttrTotalTokens = "agent.tokens.total"
|
||||
AttrAttempt = "agent.model.attempt"
|
||||
AttrMaxAttempts = "agent.model.max_attempts"
|
||||
AttrToolName = "agent.tool.name"
|
||||
AttrDelegate = "agent.delegate"
|
||||
AttrGuardrailBlock = "agent.guardrail.block"
|
||||
AttrRefusal = "agent.refusal"
|
||||
AttrInputChars = "agent.input.chars"
|
||||
AttrErrorKind = "agent.error.kind"
|
||||
AttrRunID = "agent.run.id"
|
||||
AttrParentRunID = "agent.run.parent_id"
|
||||
AttrAgentName = "agent.name"
|
||||
AttrProvider = "agent.model.provider"
|
||||
AttrModel = "agent.model.name"
|
||||
AttrLatencyMS = "agent.latency_ms"
|
||||
AttrInputTokens = "agent.tokens.input"
|
||||
AttrOutputTokens = "agent.tokens.output"
|
||||
AttrTotalTokens = "agent.tokens.total"
|
||||
AttrAttempt = "agent.model.attempt"
|
||||
AttrMaxAttempts = "agent.model.max_attempts"
|
||||
AttrToolName = "agent.tool.name"
|
||||
AttrDelegate = "agent.delegate"
|
||||
AttrGuardrailBlock = "agent.guardrail.block"
|
||||
AttrRefusal = "agent.refusal"
|
||||
AttrInputChars = "agent.input.chars"
|
||||
AttrErrorKind = "agent.error.kind"
|
||||
AttrCheckpointStatus = "agent.checkpoint.status"
|
||||
AttrCheckpointStage = "agent.checkpoint.stage"
|
||||
AttrFlowName = "agent.flow.name"
|
||||
AttrFlowStep = "agent.flow.step"
|
||||
AttrDispatch = "agent.dispatch"
|
||||
AttrTrigger = "agent.trigger"
|
||||
AttrRunEventKind = "agent.event.kind"
|
||||
)
|
||||
|
||||
type RunEvent struct {
|
||||
@@ -57,6 +64,7 @@ type RunEvent struct {
|
||||
LatencyMS int64 `json:"latency_ms,omitempty"`
|
||||
Tokens Usage `json:"tokens,omitempty"`
|
||||
Refused string `json:"refused,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ErrorKind string `json:"error_kind,omitempty"`
|
||||
InputChars int `json:"input_chars,omitempty"`
|
||||
@@ -121,8 +129,12 @@ func (a *agentImpl) startRun(ctx context.Context, message string) (context.Conte
|
||||
}
|
||||
}
|
||||
|
||||
ctx, span := a.tracer().Start(ctx, spanNameRun, trace.WithSpanKind(trace.SpanKindInternal), trace.WithAttributes(
|
||||
attribute.String(AttrRunID, info.RunID), attribute.String(AttrParentRunID, info.ParentID), attribute.String(AttrAgentName, info.Agent)))
|
||||
attrs := appendRunInfoAttributes([]attribute.KeyValue{
|
||||
attribute.String(AttrRunID, info.RunID),
|
||||
attribute.String(AttrParentRunID, info.ParentID),
|
||||
attribute.String(AttrAgentName, info.Agent),
|
||||
}, info)
|
||||
ctx, span := a.tracer().Start(ctx, spanNameRun, trace.WithSpanKind(trace.SpanKindInternal), trace.WithAttributes(attrs...))
|
||||
a.recordSpanEvent(span, runEvent)
|
||||
return ctx, func(err error) {
|
||||
latency := time.Since(start).Milliseconds()
|
||||
@@ -168,16 +180,17 @@ func (m *tracedModel) Generate(ctx context.Context, req *ai.Request, opts ...ai.
|
||||
return resp, err
|
||||
}
|
||||
|
||||
ctx, span := m.a.tracer().Start(ctx, spanNameModelCall, trace.WithAttributes(
|
||||
attrs := appendRunInfoAttributes([]attribute.KeyValue{
|
||||
attribute.String(AttrRunID, info.RunID),
|
||||
attribute.String(AttrParentRunID, info.ParentID),
|
||||
attribute.String(AttrAgentName, info.Agent),
|
||||
attribute.String(AttrProvider, provider),
|
||||
attribute.String(AttrModel, model),
|
||||
))
|
||||
}, info)
|
||||
ctx, span := m.a.tracer().Start(ctx, spanNameModelCall, trace.WithAttributes(attrs...))
|
||||
resp, err := m.Model.Generate(ctx, req, opts...)
|
||||
dur := time.Since(start).Milliseconds()
|
||||
attrs := []attribute.KeyValue{attribute.Int64(AttrLatencyMS, dur)}
|
||||
attrs = []attribute.KeyValue{attribute.Int64(AttrLatencyMS, dur)}
|
||||
if info.Attempt > 0 {
|
||||
attrs = append(attrs, attribute.Int(AttrAttempt, info.Attempt))
|
||||
}
|
||||
@@ -289,6 +302,15 @@ func classifyToolError(err string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *agentImpl) recordTimelineEvent(ctx context.Context, e RunEvent) {
|
||||
span := trace.SpanFromContext(ctx)
|
||||
if span.SpanContext().IsValid() {
|
||||
a.recordSpanEvent(span, e)
|
||||
return
|
||||
}
|
||||
a.recordRunEvent(e)
|
||||
}
|
||||
|
||||
func (a *agentImpl) recordSpanEvent(span trace.Span, e RunEvent) {
|
||||
if sc := span.SpanContext(); sc.IsValid() {
|
||||
e.TraceID = sc.TraceID().String()
|
||||
@@ -302,6 +324,7 @@ func runEventAttributes(e RunEvent) []attribute.KeyValue {
|
||||
attrs := []attribute.KeyValue{
|
||||
attribute.String(AttrRunID, e.RunID),
|
||||
attribute.String(AttrAgentName, e.Agent),
|
||||
attribute.String(AttrRunEventKind, e.Kind),
|
||||
}
|
||||
if e.ParentID != "" {
|
||||
attrs = append(attrs, attribute.String(AttrParentRunID, e.ParentID))
|
||||
@@ -337,6 +360,30 @@ func runEventAttributes(e RunEvent) []attribute.KeyValue {
|
||||
if e.ErrorKind != "" {
|
||||
attrs = append(attrs, attribute.String(AttrErrorKind, e.ErrorKind))
|
||||
}
|
||||
if e.Kind == "checkpoint" {
|
||||
if e.Status != "" {
|
||||
attrs = append(attrs, attribute.String(AttrCheckpointStatus, e.Status))
|
||||
}
|
||||
if e.Name != "" {
|
||||
attrs = append(attrs, attribute.String(AttrCheckpointStage, e.Name))
|
||||
}
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
func appendRunInfoAttributes(attrs []attribute.KeyValue, info ai.RunInfo) []attribute.KeyValue {
|
||||
if info.Flow != "" {
|
||||
attrs = append(attrs, attribute.String(AttrFlowName, info.Flow))
|
||||
}
|
||||
if info.Step != "" {
|
||||
attrs = append(attrs, attribute.String(AttrFlowStep, info.Step))
|
||||
}
|
||||
if info.Dispatch != "" {
|
||||
attrs = append(attrs, attribute.String(AttrDispatch, info.Dispatch))
|
||||
}
|
||||
if info.Trigger != "" {
|
||||
attrs = append(attrs, attribute.String(AttrTrigger, info.Trigger))
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
|
||||
+71
-1
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/flow"
|
||||
"go-micro.dev/v6/store"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
@@ -278,7 +279,8 @@ func spanEventHasRunInfo(events []trace.Event, name, runID, agentName string) bo
|
||||
continue
|
||||
}
|
||||
attrs := spanAttributes(event.Attributes)
|
||||
if attrs[AttrRunID] == runID && attrs[AttrAgentName] == agentName {
|
||||
wantKind := strings.TrimPrefix(name, "agent.")
|
||||
if attrs[AttrRunID] == runID && attrs[AttrAgentName] == agentName && attrs[AttrRunEventKind] == wantKind {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -388,6 +390,74 @@ func TestAgentRunTimelineRecordsModelAndToolWithoutTraceProvider(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentCheckpointAndResumeTimelineEvents(t *testing.T) {
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
tp := trace.NewTracerProvider(trace.WithSyncer(exp))
|
||||
st := store.NewMemoryStore()
|
||||
cp := flow.StoreCheckpoint(st, "resume-otel-agent")
|
||||
first := true
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
if first {
|
||||
first = false
|
||||
return nil, errors.New("temporary provider failure")
|
||||
}
|
||||
return &ai.Response{Reply: "resumed"}, nil
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
a := newTestAgent(Name("resume-otel-agent"), WithStore(st), WithCheckpoint(cp), TraceProvider(tp))
|
||||
_, err := a.Ask(context.Background(), "resume me")
|
||||
if err == nil {
|
||||
t.Fatal("Ask succeeded, want simulated failure")
|
||||
}
|
||||
|
||||
runs, err := cp.List(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("checkpointed runs = %d, want 1", len(runs))
|
||||
}
|
||||
resp, err := Resume(context.Background(), a, runs[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("Resume: %v", err)
|
||||
}
|
||||
if resp.Reply != "resumed" {
|
||||
t.Fatalf("reply = %q, want resumed", resp.Reply)
|
||||
}
|
||||
|
||||
events, err := LoadRunEvents(st, "resume-otel-agent", runs[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]bool{"checkpoint": false, "resume": false}
|
||||
for _, e := range events {
|
||||
if _, ok := seen[e.Kind]; ok {
|
||||
seen[e.Kind] = true
|
||||
}
|
||||
}
|
||||
for kind, ok := range seen {
|
||||
if !ok {
|
||||
t.Fatalf("missing %s event in timeline: %#v", kind, events)
|
||||
}
|
||||
}
|
||||
|
||||
var resumeSpanEvent bool
|
||||
for _, s := range exp.GetSpans().Snapshots() {
|
||||
if s.Name() != spanNameRun {
|
||||
continue
|
||||
}
|
||||
for _, e := range s.Events() {
|
||||
if e.Name == "agent.resume" {
|
||||
resumeSpanEvent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !resumeSpanEvent {
|
||||
t.Fatal("run span missing agent.resume event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRunEventsSortsTimelineKeys(t *testing.T) {
|
||||
st := store.NewMemoryStore()
|
||||
scoped := store.Scope(st, "agent", "runner")
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/flow"
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
|
||||
func TestAskCancellationAbortsPromptly(t *testing.T) {
|
||||
@@ -129,3 +131,129 @@ func TestToolCallTimeoutPropagatesDeadlineToCustomTool(t *testing.T) {
|
||||
t.Fatalf("tool call took %s, want bounded timeout", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAskCancellationDuringToolCallFailsRun(t *testing.T) {
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
if opts.ToolHandler == nil {
|
||||
t.Fatal("missing tool handler")
|
||||
}
|
||||
res := opts.ToolHandler(ctx, ai.ToolCall{ID: "call-1", Name: "cancel-self"})
|
||||
if !strings.Contains(res.Content, context.Canceled.Error()) {
|
||||
t.Fatalf("tool result = %q, want cancellation error", res.Content)
|
||||
}
|
||||
return &ai.Response{Reply: "should not succeed"}, nil
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
a := newTestAgent(
|
||||
Name("cancel-during-tool"),
|
||||
WithTool("cancel-self", "cancel the run context", nil, func(context.Context, map[string]any) (string, error) {
|
||||
cancel()
|
||||
return "", context.Canceled
|
||||
}),
|
||||
)
|
||||
|
||||
_, err := a.Ask(ctx, "cancel during tool")
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Ask error = %v, want context canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAskCheckpointRecordsTerminalOperationalFailureStatus(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{name: "canceled", err: context.Canceled, want: "canceled"},
|
||||
{name: "timeout", err: context.DeadlineExceeded, want: "timeout"},
|
||||
{name: "rate limited", err: testStatusError{code: 429}, want: "rate_limited"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cp := flow.StoreCheckpoint(store.NewMemoryStore(), "terminal-"+strings.ReplaceAll(tt.name, " ", "-"))
|
||||
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
|
||||
return nil, tt.err
|
||||
}
|
||||
defer func() { fakeGen = nil }()
|
||||
|
||||
a := newTestAgent(Name("terminal-"+strings.ReplaceAll(tt.name, " ", "-")), WithCheckpoint(cp))
|
||||
_, err := a.Ask(context.Background(), "fail safely")
|
||||
if err == nil {
|
||||
t.Fatal("Ask succeeded, want failure")
|
||||
}
|
||||
|
||||
runs, err := cp.List(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("checkpointed runs = %d, want 1", len(runs))
|
||||
}
|
||||
if runs[0].Status != tt.want {
|
||||
t.Fatalf("run status = %q, want %q", runs[0].Status, tt.want)
|
||||
}
|
||||
if len(runs[0].Steps) == 0 || runs[0].Steps[0].Status != tt.want {
|
||||
t.Fatalf("step status = %#v, want %q", runs[0].Steps, tt.want)
|
||||
}
|
||||
if pending, err := Pending(context.Background(), a); err != nil || len(pending) != 0 {
|
||||
t.Fatalf("Pending = %#v, %v; want no terminal run", pending, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type testStatusError struct {
|
||||
code int
|
||||
}
|
||||
|
||||
func (e testStatusError) Error() string { return "provider status error" }
|
||||
|
||||
func (e testStatusError) StatusCode() int { return e.code }
|
||||
|
||||
func TestToolRetryRetriesTransientToolErrorsThenSucceeds(t *testing.T) {
|
||||
attempts := 0
|
||||
a := newTestAgent(
|
||||
Name("tool-retry-success"),
|
||||
ToolRetry(3, time.Millisecond),
|
||||
WithTool("flaky", "flaky tool", nil, func(context.Context, map[string]any) (string, error) {
|
||||
attempts++
|
||||
if attempts < 3 {
|
||||
return "", context.DeadlineExceeded
|
||||
}
|
||||
return "ok", nil
|
||||
}),
|
||||
)
|
||||
|
||||
content := toolContent(a.toolHandler(), "flaky", nil)
|
||||
if content != "ok" {
|
||||
t.Fatalf("tool result = %q, want ok", content)
|
||||
}
|
||||
if attempts != 3 {
|
||||
t.Fatalf("attempts = %d, want 3", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolRetryDoesNotRetryGuardrailRefusals(t *testing.T) {
|
||||
attempts := 0
|
||||
a := newTestAgent(
|
||||
Name("tool-retry-refusal"),
|
||||
MaxSteps(1),
|
||||
ToolRetry(3, time.Millisecond),
|
||||
WithTool("counted", "counted tool", nil, func(context.Context, map[string]any) (string, error) {
|
||||
attempts++
|
||||
return "ok", nil
|
||||
}),
|
||||
)
|
||||
h := a.toolHandler()
|
||||
_ = toolContent(h, "counted", nil)
|
||||
content := toolContent(h, "counted", nil)
|
||||
if !strings.Contains(content, "step limit reached") {
|
||||
t.Fatalf("tool result = %q, want step-limit refusal", content)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Fatalf("attempts = %d, want only the allowed tool call to execute", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +181,43 @@ func (a *agentImpl) resumeWithStreamEvents(ctx context.Context, runID string, ev
|
||||
return a.askLocked(ctx, run.ID, string(run.State.Data), run.ParentID, &run, false)
|
||||
}
|
||||
|
||||
type agentStreamAdapter struct {
|
||||
stream AgentStream
|
||||
}
|
||||
|
||||
func (s *agentStreamAdapter) Recv() (*ai.Response, error) {
|
||||
for {
|
||||
event, err := s.stream.Recv()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if event == nil {
|
||||
continue
|
||||
}
|
||||
switch event.Type {
|
||||
case StreamEventToken:
|
||||
if event.Token == "" {
|
||||
continue
|
||||
}
|
||||
return &ai.Response{Reply: event.Token}, nil
|
||||
case StreamEventDone:
|
||||
return nil, io.EOF
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *agentStreamAdapter) Close() error {
|
||||
return s.stream.Close()
|
||||
}
|
||||
|
||||
func (a *agentImpl) streamAskAI(ctx context.Context, message string) (ai.Stream, error) {
|
||||
stream, err := a.StreamAsk(ctx, message)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &agentStreamAdapter{stream: stream}, nil
|
||||
}
|
||||
|
||||
type agentStream struct {
|
||||
events <-chan *StreamEvent
|
||||
done <-chan struct{}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
var fencedJSONBlock = regexp.MustCompile("(?s)```(?:json)?\\s*(.*?)\\s*```")
|
||||
|
||||
type textToolCall struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Tool string `json:"tool"`
|
||||
Input map[string]any `json:"input"`
|
||||
Arguments map[string]any `json:"arguments"`
|
||||
}
|
||||
|
||||
// executeTextToolCalls is a compatibility fallback for providers that return a
|
||||
// tool call as text JSON instead of a structured tool_calls field. It only runs
|
||||
// calls whose names match the tools offered to the model, so ordinary JSON
|
||||
// answers are left untouched.
|
||||
func (a *agentImpl) executeTextToolCalls(ctx context.Context, reply string, tools []ai.Tool) ([]ai.ToolCall, string, bool) {
|
||||
calls := parseTextToolCalls(reply, tools)
|
||||
if len(calls) == 0 {
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
handler := a.toolHandler()
|
||||
results := make([]string, 0, len(calls))
|
||||
for i := range calls {
|
||||
result := handler(ctx, calls[i])
|
||||
calls[i].Result = result.Content
|
||||
if result.Refused != "" {
|
||||
calls[i].Error = result.Refused
|
||||
}
|
||||
if result.Content != "" {
|
||||
results = append(results, result.Content)
|
||||
}
|
||||
}
|
||||
return calls, strings.Join(results, "\n"), true
|
||||
}
|
||||
|
||||
func parseTextToolCalls(text string, tools []ai.Tool) []ai.ToolCall {
|
||||
allowed := map[string]bool{}
|
||||
for _, tool := range tools {
|
||||
allowed[tool.Name] = true
|
||||
if tool.OriginalName != "" {
|
||||
allowed[tool.OriginalName] = true
|
||||
}
|
||||
}
|
||||
if len(allowed) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, candidate := range jsonCandidates(text) {
|
||||
if calls := decodeTextToolCalls(candidate, allowed); len(calls) > 0 {
|
||||
return calls
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func jsonCandidates(text string) []string {
|
||||
trimmed := strings.TrimSpace(text)
|
||||
var out []string
|
||||
if trimmed != "" {
|
||||
out = append(out, trimmed)
|
||||
}
|
||||
for _, match := range fencedJSONBlock.FindAllStringSubmatch(text, -1) {
|
||||
if len(match) > 1 {
|
||||
out = append(out, strings.TrimSpace(match[1]))
|
||||
}
|
||||
}
|
||||
if start, end := strings.IndexAny(text, "[{"), strings.LastIndexAny(text, "]}"); start >= 0 && end > start {
|
||||
out = append(out, strings.TrimSpace(text[start:end+1]))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decodeTextToolCalls(candidate string, allowed map[string]bool) []ai.ToolCall {
|
||||
var root any
|
||||
if err := json.Unmarshal([]byte(candidate), &root); err != nil {
|
||||
return nil
|
||||
}
|
||||
return collectTextToolCalls(root, allowed)
|
||||
}
|
||||
|
||||
func collectTextToolCalls(v any, allowed map[string]bool) []ai.ToolCall {
|
||||
switch x := v.(type) {
|
||||
case []any:
|
||||
var out []ai.ToolCall
|
||||
for _, item := range x {
|
||||
out = append(out, collectTextToolCalls(item, allowed)...)
|
||||
}
|
||||
return out
|
||||
case map[string]any:
|
||||
if nested, ok := firstNestedToolCalls(x); ok {
|
||||
return collectTextToolCalls(nested, allowed)
|
||||
}
|
||||
call := mapToTextToolCall(x)
|
||||
name := call.Name
|
||||
if name == "" {
|
||||
name = call.Tool
|
||||
}
|
||||
input := call.Input
|
||||
if input == nil {
|
||||
input = call.Arguments
|
||||
}
|
||||
if name == "" || !allowed[name] || input == nil {
|
||||
return nil
|
||||
}
|
||||
id := call.ID
|
||||
if id == "" {
|
||||
id = fmt.Sprintf("text-call-%s", strings.ReplaceAll(name, ".", "_"))
|
||||
}
|
||||
return []ai.ToolCall{{ID: id, Name: name, Input: input}}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func firstNestedToolCalls(m map[string]any) (any, bool) {
|
||||
for _, key := range []string{"tool_calls", "toolCalls", "calls"} {
|
||||
if v, ok := m[key]; ok {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func mapToTextToolCall(m map[string]any) textToolCall {
|
||||
b, _ := json.Marshal(m)
|
||||
var call textToolCall
|
||||
_ = json.Unmarshal(b, &call)
|
||||
return call
|
||||
}
|
||||
@@ -300,6 +300,20 @@ Default base URL: `https://api.atlascloud.ai`
|
||||
|
||||
Atlas Cloud is an enterprise AI infrastructure platform offering high-performance LLM APIs. It exposes an OpenAI-compatible chat completions endpoint with tool calling support.
|
||||
|
||||
### MiniMax
|
||||
|
||||
```go
|
||||
m := ai.New("minimax",
|
||||
ai.WithAPIKey("your-key"),
|
||||
ai.WithModel("MiniMax-M3"), // default
|
||||
)
|
||||
```
|
||||
|
||||
Default model: `MiniMax-M3`
|
||||
Default base URL: `https://api.minimax.io`
|
||||
|
||||
MiniMax offers its flagship MiniMax-M3 model via an OpenAI-compatible chat completions endpoint.
|
||||
|
||||
## Auto-Detection
|
||||
|
||||
Use `AutoDetectProvider()` to detect the provider from a base URL:
|
||||
|
||||
+95
-15
@@ -27,6 +27,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -51,12 +52,28 @@ type Provider struct {
|
||||
opts ai.Options
|
||||
}
|
||||
|
||||
type atlasToolCall struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"function"`
|
||||
}
|
||||
|
||||
// NewProvider creates a new Atlas Cloud provider.
|
||||
func NewProvider(opts ...ai.Option) *Provider {
|
||||
options := ai.NewOptions(opts...)
|
||||
|
||||
if options.Model == "" {
|
||||
options.Model = "deepseek-ai/DeepSeek-V3-0324"
|
||||
// Allow the chat model to be selected via the ATLASCLOUD_MODEL env var
|
||||
// (e.g. to run CI conformance against a stronger tool-use model) without
|
||||
// a code change; fall back to a sensible default otherwise.
|
||||
if m := os.Getenv("ATLASCLOUD_MODEL"); m != "" {
|
||||
options.Model = m
|
||||
} else {
|
||||
options.Model = "deepseek-ai/DeepSeek-V3-0324"
|
||||
}
|
||||
}
|
||||
if options.BaseURL == "" {
|
||||
options.BaseURL = "https://api.atlascloud.ai"
|
||||
@@ -113,7 +130,7 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
|
||||
apiReq["tools"] = tools
|
||||
}
|
||||
|
||||
resp, rawMessage, err := p.callAPI(ctx, apiReq)
|
||||
resp, rawMessage, err := p.callAPI(ctx, "chat", apiReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -123,6 +140,7 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
|
||||
}
|
||||
|
||||
if p.opts.ToolHandler != nil {
|
||||
var toolResults []string
|
||||
followUpMessages := append(messages, map[string]any{
|
||||
"role": "assistant",
|
||||
"content": rawMessage["content"],
|
||||
@@ -131,6 +149,9 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
|
||||
|
||||
for _, tc := range resp.ToolCalls {
|
||||
content := p.opts.ToolHandler(ctx, tc).Content
|
||||
if content != "" {
|
||||
toolResults = append(toolResults, content)
|
||||
}
|
||||
followUpMessages = append(followUpMessages, map[string]any{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.ID,
|
||||
@@ -143,9 +164,14 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
|
||||
"messages": followUpMessages,
|
||||
}
|
||||
|
||||
followUpResp, _, err := p.callAPI(ctx, followUpReq)
|
||||
if err == nil && followUpResp.Reply != "" {
|
||||
followUpResp, _, err := p.callAPI(ctx, "tool-follow-up", followUpReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if followUpResp.Reply != "" {
|
||||
resp.Answer = followUpResp.Reply
|
||||
} else if len(toolResults) > 0 {
|
||||
resp.Answer = strings.Join(toolResults, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,6 +181,10 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
|
||||
// Stream generates a streaming response from Atlas Cloud's OpenAI-compatible
|
||||
// chat completions endpoint, emitting content deltas as they arrive.
|
||||
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
|
||||
if len(req.Tools) > 0 {
|
||||
return nil, fmt.Errorf("%w: atlascloud streaming does not expose tools", ai.ErrStreamingUnsupported)
|
||||
}
|
||||
|
||||
messages := []map[string]any{
|
||||
{"role": "system", "content": req.SystemPrompt},
|
||||
}
|
||||
@@ -259,7 +289,7 @@ func (s *atlasStream) Close() error {
|
||||
return s.body.Close()
|
||||
}
|
||||
|
||||
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, map[string]any, error) {
|
||||
func (p *Provider) callAPI(ctx context.Context, phase string, req map[string]any) (*ai.Response, map[string]any, error) {
|
||||
reqBody, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
|
||||
@@ -282,20 +312,14 @@ func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Respons
|
||||
|
||||
respBody, _ := io.ReadAll(httpResp.Body)
|
||||
if httpResp.StatusCode != http.StatusOK {
|
||||
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
|
||||
return nil, nil, fmt.Errorf("API error (%s) during atlascloud %s request (%s): %s", httpResp.Status, phase, atlascloudRequestSummary(req), string(respBody))
|
||||
}
|
||||
|
||||
var chatResp struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
ToolCalls []struct {
|
||||
ID string `json:"id"`
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"function"`
|
||||
} `json:"tool_calls"`
|
||||
Content string `json:"content"`
|
||||
ToolCalls []atlasToolCall `json:"tool_calls"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
@@ -327,12 +351,68 @@ func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Respons
|
||||
|
||||
rawMessage := map[string]any{
|
||||
"content": choice.Message.Content,
|
||||
"tool_calls": choice.Message.ToolCalls,
|
||||
"tool_calls": normalizeAtlasCloudToolCalls(choice.Message.ToolCalls),
|
||||
}
|
||||
|
||||
return response, rawMessage, nil
|
||||
}
|
||||
|
||||
func normalizeAtlasCloudToolCalls(toolCalls []atlasToolCall) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(toolCalls))
|
||||
for _, tc := range toolCalls {
|
||||
toolType := tc.Type
|
||||
if toolType == "" {
|
||||
toolType = "function"
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": tc.ID,
|
||||
"type": toolType,
|
||||
"function": map[string]any{
|
||||
"name": tc.Function.Name,
|
||||
"arguments": tc.Function.Arguments,
|
||||
},
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func atlascloudRequestSummary(req map[string]any) string {
|
||||
parts := []string{}
|
||||
if model, ok := req["model"].(string); ok && model != "" {
|
||||
parts = append(parts, "model="+model)
|
||||
}
|
||||
if messages, ok := req["messages"].([]map[string]any); ok {
|
||||
parts = append(parts, fmt.Sprintf("messages=%d", len(messages)))
|
||||
if len(messages) > 0 {
|
||||
last := messages[len(messages)-1]
|
||||
if role, ok := last["role"].(string); ok && role != "" {
|
||||
parts = append(parts, "last_role="+role)
|
||||
}
|
||||
if _, ok := last["tool_call_id"].(string); ok {
|
||||
parts = append(parts, "last_has_tool_call_id=true")
|
||||
}
|
||||
}
|
||||
}
|
||||
if tools, ok := req["tools"].([]map[string]any); ok {
|
||||
names := make([]string, 0, len(tools))
|
||||
for _, tool := range tools {
|
||||
fn, _ := tool["function"].(map[string]any)
|
||||
name, _ := fn["name"].(string)
|
||||
if name != "" {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("tools=%d", len(tools)))
|
||||
if len(names) > 0 {
|
||||
parts = append(parts, "tool_names="+strings.Join(names, ","))
|
||||
}
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "request_context=unavailable"
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
const defaultImageModel = "openai/gpt-image-2/text-to-image"
|
||||
|
||||
// GenerateImage creates an image using Atlas Cloud's async image API.
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
@@ -140,6 +141,187 @@ func TestProvider_Stream(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_StreamWithToolsFallsBack(t *testing.T) {
|
||||
p := NewProvider(ai.WithAPIKey("test-key"))
|
||||
_, err := p.Stream(context.Background(), &ai.Request{
|
||||
Prompt: "call a tool",
|
||||
Tools: []ai.Tool{{
|
||||
Name: "fallback_echo",
|
||||
Description: "echo fallback marker",
|
||||
Properties: map[string]any{"value": map[string]any{"type": "string"}},
|
||||
}},
|
||||
})
|
||||
if !errors.Is(err, ai.ErrStreamingUnsupported) {
|
||||
t.Fatalf("Stream with tools error = %v, want ErrStreamingUnsupported", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_GenerateToolCallEmptyFollowUpUsesToolResult(t *testing.T) {
|
||||
var calls int
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/chat/completions" {
|
||||
t.Errorf("path = %s, want /v1/chat/completions", r.URL.Path)
|
||||
}
|
||||
calls++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch calls {
|
||||
case 1:
|
||||
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"","tool_calls":[{"id":"call-1","function":{"name":"conformance_echo","arguments":"{\"value\":\"agent-conformance\"}"}}]}}]}`))
|
||||
case 2:
|
||||
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":""}}]}`))
|
||||
default:
|
||||
t.Fatalf("unexpected API call %d", calls)
|
||||
}
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
p := NewProvider(
|
||||
ai.WithAPIKey("test-key"),
|
||||
ai.WithBaseURL(ts.URL),
|
||||
ai.WithToolHandler(func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
|
||||
if call.Name != "conformance_echo" {
|
||||
t.Fatalf("tool name = %q, want conformance_echo", call.Name)
|
||||
}
|
||||
return ai.ToolResult{ID: call.ID, Content: `{"marker":"agent-conformance-ok"}`}
|
||||
}),
|
||||
)
|
||||
resp, err := p.Generate(context.Background(), &ai.Request{
|
||||
Prompt: "call a tool",
|
||||
Tools: []ai.Tool{{
|
||||
Name: "conformance_echo",
|
||||
Description: "echo conformance marker",
|
||||
Properties: map[string]any{"value": map[string]any{"type": "string"}},
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Generate returned error: %v", err)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("API calls = %d, want 2", calls)
|
||||
}
|
||||
if resp.Answer != `{"marker":"agent-conformance-ok"}` {
|
||||
t.Fatalf("Answer = %q, want tool result fallback", resp.Answer)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_GenerateMinimaxToolRequests(t *testing.T) {
|
||||
var bodies []map[string]any
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("decode request: %v", err)
|
||||
}
|
||||
bodies = append(bodies, body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch len(bodies) {
|
||||
case 1:
|
||||
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"","tool_calls":[{"id":"call-1","function":{"name":"conformance_echo","arguments":"{\"value\":\"agent-conformance\"}"}}]}}]}`))
|
||||
case 2:
|
||||
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"done"}}]}`))
|
||||
default:
|
||||
t.Fatalf("unexpected API call %d", len(bodies))
|
||||
}
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
p := NewProvider(
|
||||
ai.WithAPIKey("test-key"),
|
||||
ai.WithBaseURL(ts.URL),
|
||||
ai.WithModel("minimaxai/minimax-m3"),
|
||||
ai.WithToolHandler(func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
|
||||
return ai.ToolResult{ID: call.ID, Content: `{"marker":"agent-conformance-ok"}`}
|
||||
}),
|
||||
)
|
||||
resp, err := p.Generate(context.Background(), &ai.Request{
|
||||
SystemPrompt: "You are helpful.",
|
||||
Prompt: "call a tool",
|
||||
Tools: []ai.Tool{{
|
||||
Name: "conformance_echo",
|
||||
Description: "echo conformance marker",
|
||||
Properties: map[string]any{"value": map[string]any{"type": "string"}},
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Generate returned error: %v", err)
|
||||
}
|
||||
if resp.Answer != "done" {
|
||||
t.Fatalf("Answer = %q, want done", resp.Answer)
|
||||
}
|
||||
if len(bodies) != 2 {
|
||||
t.Fatalf("captured requests = %d, want 2", len(bodies))
|
||||
}
|
||||
if got := bodies[0]["model"]; got != "minimaxai/minimax-m3" {
|
||||
t.Fatalf("initial model = %v", got)
|
||||
}
|
||||
tools, ok := bodies[0]["tools"].([]any)
|
||||
if !ok || len(tools) != 1 {
|
||||
t.Fatalf("initial tools = %#v, want one tool", bodies[0]["tools"])
|
||||
}
|
||||
tool := tools[0].(map[string]any)
|
||||
if tool["type"] != "function" {
|
||||
t.Fatalf("tool type = %v, want function", tool["type"])
|
||||
}
|
||||
fn := tool["function"].(map[string]any)
|
||||
if fn["name"] != "conformance_echo" {
|
||||
t.Fatalf("tool function name = %v", fn["name"])
|
||||
}
|
||||
params := fn["parameters"].(map[string]any)
|
||||
if params["type"] != "object" {
|
||||
t.Fatalf("parameters type = %v, want object", params["type"])
|
||||
}
|
||||
|
||||
followUpMessages := bodies[1]["messages"].([]any)
|
||||
if len(followUpMessages) != 4 {
|
||||
t.Fatalf("follow-up messages = %d, want 4", len(followUpMessages))
|
||||
}
|
||||
assistant := followUpMessages[2].(map[string]any)
|
||||
if assistant["role"] != "assistant" {
|
||||
t.Fatalf("assistant role = %v", assistant["role"])
|
||||
}
|
||||
assistantCalls := assistant["tool_calls"].([]any)
|
||||
assistantCall := assistantCalls[0].(map[string]any)
|
||||
if assistantCall["type"] != "function" {
|
||||
t.Fatalf("assistant tool call type = %v, want function", assistantCall["type"])
|
||||
}
|
||||
toolResult := followUpMessages[3].(map[string]any)
|
||||
if toolResult["role"] != "tool" || toolResult["tool_call_id"] != "call-1" {
|
||||
t.Fatalf("tool result message = %#v", toolResult)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_GenerateToolCallHTTPErrorIncludesRequestContext(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, `{"code":400,"msg":"bad request"}`, http.StatusBadRequest)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
p := NewProvider(
|
||||
ai.WithAPIKey("test-key"),
|
||||
ai.WithBaseURL(ts.URL),
|
||||
ai.WithModel("minimaxai/minimax-m3"),
|
||||
)
|
||||
_, err := p.Generate(context.Background(), &ai.Request{
|
||||
Prompt: "call a tool",
|
||||
Tools: []ai.Tool{{
|
||||
Name: "conformance_echo",
|
||||
Description: "echo conformance marker",
|
||||
Properties: map[string]any{"value": map[string]any{"type": "string"}},
|
||||
}},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("Generate error = nil, want 400")
|
||||
}
|
||||
msg := err.Error()
|
||||
for _, want := range []string{"400 Bad Request", "atlascloud chat request", "model=minimaxai/minimax-m3", "tools=1", "tool_names=conformance_echo"} {
|
||||
if !strings.Contains(msg, want) {
|
||||
t.Fatalf("error %q missing %q", msg, want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(msg, "test-key") {
|
||||
t.Fatalf("error leaked API key: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Registration(t *testing.T) {
|
||||
m := ai.New("atlascloud", ai.WithAPIKey("test"))
|
||||
if m == nil {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
_ "go-micro.dev/v6/ai/atlascloud"
|
||||
_ "go-micro.dev/v6/ai/gemini"
|
||||
_ "go-micro.dev/v6/ai/groq"
|
||||
_ "go-micro.dev/v6/ai/minimax"
|
||||
_ "go-micro.dev/v6/ai/mistral"
|
||||
_ "go-micro.dev/v6/ai/openai"
|
||||
_ "go-micro.dev/v6/ai/together"
|
||||
@@ -16,7 +17,7 @@ import (
|
||||
|
||||
func TestRegisteredProviders(t *testing.T) {
|
||||
got := ai.RegisteredProviders("")
|
||||
want := []string{"anthropic", "atlascloud", "gemini", "groq", "mistral", "openai", "together"}
|
||||
want := []string{"anthropic", "atlascloud", "gemini", "groq", "minimax", "mistral", "openai", "together"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("RegisteredProviders() = %#v, want %#v", got, want)
|
||||
}
|
||||
@@ -34,7 +35,7 @@ func TestRegisteredProviders(t *testing.T) {
|
||||
}
|
||||
|
||||
got = ai.RegisteredProviders("stream")
|
||||
want = []string{"atlascloud", "groq", "mistral", "openai", "together"}
|
||||
want = []string{"atlascloud", "groq", "minimax", "mistral", "openai", "together"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("RegisteredProviders(stream) = %#v, want %#v", got, want)
|
||||
}
|
||||
@@ -47,6 +48,7 @@ func TestCapabilityRows(t *testing.T) {
|
||||
{Provider: "atlascloud", Capabilities: ai.Capabilities{Model: true, Image: true, Video: true, Stream: true}},
|
||||
{Provider: "gemini", Capabilities: ai.Capabilities{Model: true}},
|
||||
{Provider: "groq", Capabilities: ai.Capabilities{Model: true, Stream: true}},
|
||||
{Provider: "minimax", Capabilities: ai.Capabilities{Model: true, Stream: true}},
|
||||
{Provider: "mistral", Capabilities: ai.Capabilities{Model: true, Stream: true}},
|
||||
{Provider: "openai", Capabilities: ai.Capabilities{Model: true, Image: true, Stream: true}},
|
||||
{Provider: "together", Capabilities: ai.Capabilities{Model: true, Stream: true}},
|
||||
@@ -59,7 +61,7 @@ func TestCapabilityRows(t *testing.T) {
|
||||
func TestCapabilityMatrix(t *testing.T) {
|
||||
matrix := ai.CapabilityMatrix()
|
||||
|
||||
for _, provider := range []string{"anthropic", "atlascloud", "gemini", "groq", "mistral", "openai", "together"} {
|
||||
for _, provider := range []string{"anthropic", "atlascloud", "gemini", "groq", "minimax", "mistral", "openai", "together"} {
|
||||
caps, ok := matrix[provider]
|
||||
if !ok {
|
||||
t.Fatalf("CapabilityMatrix missing %q", provider)
|
||||
@@ -88,7 +90,7 @@ func TestRegisterStream(t *testing.T) {
|
||||
}
|
||||
|
||||
got := ai.RegisteredProviders("stream")
|
||||
want := []string{"atlascloud", "groq", "mistral", "openai", "test-stream", "together"}
|
||||
want := []string{"atlascloud", "groq", "minimax", "mistral", "openai", "test-stream", "together"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("RegisteredProviders(stream) = %#v, want %#v", got, want)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
// Package minimax implements the MiniMax model provider.
|
||||
//
|
||||
// MiniMax offers its flagship MiniMax-M3 model via an OpenAI-compatible
|
||||
// chat completions endpoint.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// import _ "go-micro.dev/v6/ai/minimax"
|
||||
//
|
||||
// m := ai.New("minimax",
|
||||
// ai.WithAPIKey("your-api-key"),
|
||||
// )
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/ai/internal/openaiapi"
|
||||
)
|
||||
|
||||
func init() {
|
||||
ai.Register("minimax", func(opts ...ai.Option) ai.Model {
|
||||
return NewProvider(opts...)
|
||||
})
|
||||
ai.RegisterStream("minimax")
|
||||
}
|
||||
|
||||
type Provider struct {
|
||||
opts ai.Options
|
||||
}
|
||||
|
||||
func NewProvider(opts ...ai.Option) *Provider {
|
||||
options := ai.NewOptions(opts...)
|
||||
if options.Model == "" {
|
||||
options.Model = "MiniMax-M3"
|
||||
}
|
||||
if options.BaseURL == "" {
|
||||
options.BaseURL = "https://api.minimax.io"
|
||||
}
|
||||
return &Provider{opts: options}
|
||||
}
|
||||
|
||||
func (p *Provider) Init(opts ...ai.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&p.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Provider) Options() ai.Options { return p.opts }
|
||||
func (p *Provider) String() string { return "minimax" }
|
||||
|
||||
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
|
||||
var tools []map[string]any
|
||||
for _, t := range req.Tools {
|
||||
tools = append(tools, map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": t.Name,
|
||||
"description": t.Description,
|
||||
"parameters": map[string]any{
|
||||
"type": "object",
|
||||
"properties": t.Properties,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
messages := []map[string]any{
|
||||
{"role": "system", "content": req.SystemPrompt},
|
||||
{"role": "user", "content": req.Prompt},
|
||||
}
|
||||
|
||||
apiReq := map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": messages,
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
apiReq["tools"] = tools
|
||||
}
|
||||
|
||||
resp, rawMessage, err := p.callAPI(ctx, apiReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(resp.ToolCalls) == 0 {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
if p.opts.ToolHandler != nil {
|
||||
followUpMessages := append(messages, map[string]any{
|
||||
"role": "assistant",
|
||||
"content": rawMessage["content"],
|
||||
"tool_calls": rawMessage["tool_calls"],
|
||||
})
|
||||
for _, tc := range resp.ToolCalls {
|
||||
content := p.opts.ToolHandler(ctx, tc).Content
|
||||
followUpMessages = append(followUpMessages, map[string]any{
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.ID,
|
||||
"content": content,
|
||||
})
|
||||
}
|
||||
followUpResp, _, err := p.callAPI(ctx, map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": followUpMessages,
|
||||
})
|
||||
if err == nil && followUpResp.Reply != "" {
|
||||
resp.Answer = followUpResp.Reply
|
||||
}
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
|
||||
return openaiapi.Stream(ctx, p.opts, req, "/v1/chat/completions")
|
||||
}
|
||||
|
||||
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, map[string]any, error) {
|
||||
reqBody, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/chat/completions"
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
|
||||
|
||||
httpResp, err := http.DefaultClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("API request failed: %w", err)
|
||||
}
|
||||
defer httpResp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(httpResp.Body)
|
||||
if httpResp.StatusCode != http.StatusOK {
|
||||
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
|
||||
}
|
||||
|
||||
var chatResp struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
ToolCalls []struct {
|
||||
ID string `json:"id"`
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"function"`
|
||||
} `json:"tool_calls"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(respBody, &chatResp); err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
|
||||
}
|
||||
if len(chatResp.Choices) == 0 {
|
||||
return nil, nil, fmt.Errorf("no response from API")
|
||||
}
|
||||
|
||||
choice := chatResp.Choices[0]
|
||||
response := &ai.Response{Reply: choice.Message.Content}
|
||||
|
||||
for _, tc := range choice.Message.ToolCalls {
|
||||
var input map[string]any
|
||||
if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
|
||||
input = map[string]any{}
|
||||
}
|
||||
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Input: input,
|
||||
})
|
||||
}
|
||||
|
||||
rawMessage := map[string]any{
|
||||
"content": choice.Message.Content,
|
||||
"tool_calls": choice.Message.ToolCalls,
|
||||
}
|
||||
|
||||
return response, rawMessage, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package minimax
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
func TestProvider_String(t *testing.T) {
|
||||
if NewProvider().String() != "minimax" {
|
||||
t.Errorf("got %q", NewProvider().String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Defaults(t *testing.T) {
|
||||
opts := NewProvider().Options()
|
||||
if opts.Model != "MiniMax-M3" {
|
||||
t.Errorf("default model = %q", opts.Model)
|
||||
}
|
||||
if opts.BaseURL != "https://api.minimax.io" {
|
||||
t.Errorf("default base URL = %q", opts.BaseURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Init(t *testing.T) {
|
||||
p := NewProvider()
|
||||
if err := p.Init(ai.WithModel("m"), ai.WithAPIKey("k")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Options().Model != "m" || p.Options().APIKey != "k" {
|
||||
t.Error("Init did not apply options")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Generate_NoAPIKey(t *testing.T) {
|
||||
if _, err := NewProvider().Generate(context.Background(), &ai.Request{Prompt: "hi"}); err == nil {
|
||||
t.Error("expected error without API key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Stream(t *testing.T) {
|
||||
var sawStream bool
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/chat/completions" {
|
||||
t.Fatalf("path = %s, want /v1/chat/completions", r.URL.Path)
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatalf("decode request: %v", err)
|
||||
}
|
||||
sawStream, _ = body["stream"].(bool)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"hel\"}}]}\n\n"))
|
||||
_, _ = w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"lo\"}}]}\n\n"))
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
p := NewProvider(ai.WithAPIKey("test-key"), ai.WithBaseURL(ts.URL))
|
||||
stream, err := p.Stream(context.Background(), &ai.Request{Prompt: "Hello"})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream returned error: %v", err)
|
||||
}
|
||||
defer stream.Close()
|
||||
if !sawStream {
|
||||
t.Fatal("stream request did not set stream=true")
|
||||
}
|
||||
|
||||
first, err := stream.Recv()
|
||||
if err != nil || first.Reply != "hel" {
|
||||
t.Fatalf("first chunk = %#v, %v; want hel", first, err)
|
||||
}
|
||||
second, err := stream.Recv()
|
||||
if err != nil || second.Reply != "lo" {
|
||||
t.Fatalf("second chunk = %#v, %v; want lo", second, err)
|
||||
}
|
||||
if _, err := stream.Recv(); !errors.Is(err, io.EOF) {
|
||||
t.Fatalf("final error = %v, want EOF", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Registration(t *testing.T) {
|
||||
m := ai.New("minimax", ai.WithAPIKey("test"))
|
||||
if m == nil {
|
||||
t.Fatal("provider not registered")
|
||||
}
|
||||
if m.String() != "minimax" {
|
||||
t.Errorf("got %q", m.String())
|
||||
}
|
||||
}
|
||||
+16
-10
@@ -93,9 +93,10 @@ func (c ToolCall) Scan(v any) error {
|
||||
|
||||
// ToolResult represents the result of a tool execution
|
||||
type ToolResult struct {
|
||||
ID string // Tool call ID (for correlation)
|
||||
Value any // Structured result (optional)
|
||||
Content string // Tool execution result (JSON string), shown to the model
|
||||
ID string // Tool call ID (for correlation)
|
||||
Value any // Structured result (optional)
|
||||
Content string // Tool execution result (JSON string), shown to the model
|
||||
Attempts int `json:"attempts,omitempty"` // Tool execution attempts, set when retried.
|
||||
// Refused names the reason a guardrail blocked the call before it ran
|
||||
// ("max_steps", "loop", "approval"); empty when the call executed. A
|
||||
// tool wrapper can switch on it to build reliability tooling — react to
|
||||
@@ -121,13 +122,16 @@ const (
|
||||
// tell which provider attempt produced the call and whether it is part of a
|
||||
// retry budget. They are zero when no model-attempt context is known.
|
||||
type RunInfo struct {
|
||||
RunID string // correlation id for this agent or flow run
|
||||
ParentID string // the run that delegated to this one, if any
|
||||
Agent string // the agent's name
|
||||
Flow string // the flow's name, when the call is part of a workflow
|
||||
Step string // the flow step currently executing, when known
|
||||
Attempt int // current model Generate attempt, starting at 1 when known
|
||||
MaxAttempts int // configured model Generate attempt budget when known
|
||||
RunID string // correlation id for this agent or flow run
|
||||
ParentID string // the run that delegated to this one, if any
|
||||
Agent string // the agent's name
|
||||
Flow string // the flow's name, when the call is part of a workflow
|
||||
Step string // the flow step currently executing, when known
|
||||
Attempt int // current model Generate attempt, starting at 1 when known
|
||||
MaxAttempts int // configured model Generate attempt budget when known
|
||||
VerificationFeedback string // feedback from the previous failed verifier attempt, when retrying a flow step
|
||||
Dispatch string // how the run was dispatched (direct, broker, schedule, resume) when known
|
||||
Trigger string // external trigger or schedule label that started the run, when known
|
||||
}
|
||||
|
||||
type runInfoKey struct{}
|
||||
@@ -208,6 +212,8 @@ func AutoDetectProvider(baseURL string) string {
|
||||
return "gemini"
|
||||
case strings.Contains(baseURL, "groq"):
|
||||
return "groq"
|
||||
case strings.Contains(baseURL, "minimax"):
|
||||
return "minimax"
|
||||
case strings.Contains(baseURL, "mistral"):
|
||||
return "mistral"
|
||||
case strings.Contains(baseURL, "together"):
|
||||
|
||||
@@ -0,0 +1,729 @@
|
||||
// Package ollama implements the Ollama model provider.
|
||||
//
|
||||
// Ollama runs open-weight models locally (or via Ollama Cloud). This
|
||||
// provider supports two API styles:
|
||||
//
|
||||
// - Native (/api/chat): local Ollama servers (default, http://localhost:11434)
|
||||
// - OpenAI-compatible (/v1/chat/completions): Ollama Cloud (https://ollama.com/v1)
|
||||
//
|
||||
// The provider auto-detects which style to use based on the base URL.
|
||||
// Set OLLAMA_BASE_URL to point at your server (local or cloud).
|
||||
//
|
||||
// Usage (local):
|
||||
//
|
||||
// import _ "go-micro.dev/v6/ai/ollama"
|
||||
//
|
||||
// m := ai.New("ollama",
|
||||
// ai.WithBaseURL("http://localhost:11434"),
|
||||
// ai.WithModel("llama3.2"),
|
||||
// )
|
||||
//
|
||||
// Usage (Ollama Cloud):
|
||||
//
|
||||
// m := ai.New("ollama",
|
||||
// ai.WithBaseURL("https://ollama.com/v1"),
|
||||
// ai.WithAPIKey("your-key"),
|
||||
// ai.WithModel("gpt-oss:120b"),
|
||||
// )
|
||||
package ollama
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
func init() {
|
||||
ai.Register("ollama", func(opts ...ai.Option) ai.Model {
|
||||
return NewProvider(opts...)
|
||||
})
|
||||
ai.RegisterStream("ollama")
|
||||
}
|
||||
|
||||
// Provider implements the ai.Model interface for Ollama.
|
||||
type Provider struct {
|
||||
opts ai.Options
|
||||
|
||||
// cloudOverride forces cloud mode for testing. When true, the provider
|
||||
// uses the OpenAI-compatible endpoint regardless of the base URL.
|
||||
cloudOverride bool
|
||||
}
|
||||
|
||||
// NewProvider creates a new Ollama provider.
|
||||
func NewProvider(opts ...ai.Option) *Provider {
|
||||
options := ai.NewOptions(opts...)
|
||||
if options.Model == "" {
|
||||
options.Model = "llama3.2"
|
||||
}
|
||||
if options.BaseURL == "" {
|
||||
options.BaseURL = "http://localhost:11434"
|
||||
}
|
||||
return &Provider{opts: options}
|
||||
}
|
||||
|
||||
// Init initializes the provider with options.
|
||||
func (p *Provider) Init(opts ...ai.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&p.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Options returns the provider options.
|
||||
func (p *Provider) Options() ai.Options { return p.opts }
|
||||
|
||||
// String returns the provider name.
|
||||
func (p *Provider) String() string { return "ollama" }
|
||||
|
||||
// isCloud returns true when the base URL points at Ollama Cloud (ollama.com),
|
||||
// which uses the OpenAI-compatible /v1/chat/completions endpoint instead of
|
||||
// the native /api/chat.
|
||||
func (p *Provider) isCloud() bool {
|
||||
if p.cloudOverride {
|
||||
return true
|
||||
}
|
||||
return strings.Contains(p.opts.BaseURL, "ollama.com")
|
||||
}
|
||||
|
||||
// chatPath returns the API endpoint path for chat completions.
|
||||
func (p *Provider) chatPath() string {
|
||||
if p.isCloud() {
|
||||
return "/v1/chat/completions"
|
||||
}
|
||||
return "/api/chat"
|
||||
}
|
||||
|
||||
// streamPath returns the API endpoint path for streaming chat.
|
||||
// Ollama Cloud uses the same /v1/chat/completions with stream:true.
|
||||
// Local Ollama uses /api/chat with stream:true.
|
||||
func (p *Provider) streamPath() string {
|
||||
return p.chatPath()
|
||||
}
|
||||
|
||||
// Generate generates a response from the Ollama model.
|
||||
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
|
||||
if p.isCloud() {
|
||||
return p.generateOpenAI(ctx, req)
|
||||
}
|
||||
return p.generateNative(ctx, req)
|
||||
}
|
||||
|
||||
// Stream generates a streaming response.
|
||||
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
|
||||
if p.isCloud() {
|
||||
return p.streamOpenAI(ctx, req)
|
||||
}
|
||||
return p.streamNative(ctx, req)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OpenAI-compatible mode (Ollama Cloud: ollama.com/v1)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (p *Provider) generateOpenAI(ctx context.Context, req *ai.Request) (*ai.Response, error) {
|
||||
var tools []map[string]any
|
||||
for _, t := range req.Tools {
|
||||
tools = append(tools, map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": t.Name,
|
||||
"description": t.Description,
|
||||
"parameters": map[string]any{
|
||||
"type": "object",
|
||||
"properties": t.Properties,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
messages := buildOpenAIMessages(req)
|
||||
apiReq := map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": messages,
|
||||
"stream": false,
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
apiReq["tools"] = tools
|
||||
}
|
||||
if p.opts.MaxTokens > 0 {
|
||||
apiReq["max_tokens"] = p.opts.MaxTokens
|
||||
}
|
||||
|
||||
resp, rawMsg, err := p.callOpenAI(ctx, apiReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// No tool calls or no handler — return as-is.
|
||||
if len(resp.ToolCalls) == 0 || p.opts.ToolHandler == nil {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Tool execution loop.
|
||||
convMessages := append(messages, map[string]any{
|
||||
"role": "assistant",
|
||||
"content": rawMsg.content,
|
||||
"tool_calls": rawMsg.toolCalls,
|
||||
})
|
||||
|
||||
pendingCalls := resp.ToolCalls
|
||||
for round := 0; round < 10; round++ {
|
||||
for i := range pendingCalls {
|
||||
result := p.opts.ToolHandler(ctx, pendingCalls[i])
|
||||
pendingCalls[i].Result = result.Content
|
||||
convMessages = append(convMessages, map[string]any{
|
||||
"role": "tool",
|
||||
"tool_call_id": pendingCalls[i].ID,
|
||||
"content": result.Content,
|
||||
})
|
||||
}
|
||||
|
||||
followUpReq := map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": convMessages,
|
||||
"stream": false,
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
followUpReq["tools"] = tools
|
||||
}
|
||||
if p.opts.MaxTokens > 0 {
|
||||
followUpReq["max_tokens"] = p.opts.MaxTokens
|
||||
}
|
||||
|
||||
followUpResp, followUpRaw, err := p.callOpenAI(ctx, followUpReq)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
if len(followUpResp.ToolCalls) > 0 {
|
||||
resp.ToolCalls = append(resp.ToolCalls, followUpResp.ToolCalls...)
|
||||
pendingCalls = followUpResp.ToolCalls
|
||||
convMessages = append(convMessages, map[string]any{
|
||||
"role": "assistant",
|
||||
"content": followUpRaw.content,
|
||||
"tool_calls": followUpRaw.toolCalls,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
if followUpResp.Reply != "" {
|
||||
resp.Answer = followUpResp.Reply
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (p *Provider) callOpenAI(ctx context.Context, req map[string]any) (*ai.Response, *rawChatMessage, error) {
|
||||
reqBody, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + p.chatPath()
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
if p.opts.APIKey != "" {
|
||||
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
|
||||
}
|
||||
|
||||
httpResp, err := http.DefaultClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("API request failed: %w", err)
|
||||
}
|
||||
defer httpResp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(httpResp.Body)
|
||||
if httpResp.StatusCode != http.StatusOK {
|
||||
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
|
||||
}
|
||||
|
||||
var chatResp struct {
|
||||
Usage struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
ToolCalls []struct {
|
||||
ID string `json:"id"`
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"function"`
|
||||
} `json:"tool_calls"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(respBody, &chatResp); err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
|
||||
}
|
||||
if len(chatResp.Choices) == 0 {
|
||||
return nil, nil, fmt.Errorf("no response from API")
|
||||
}
|
||||
|
||||
choice := chatResp.Choices[0]
|
||||
response := &ai.Response{
|
||||
Reply: choice.Message.Content,
|
||||
Usage: ai.Usage{
|
||||
InputTokens: chatResp.Usage.PromptTokens,
|
||||
OutputTokens: chatResp.Usage.CompletionTokens,
|
||||
TotalTokens: chatResp.Usage.TotalTokens,
|
||||
},
|
||||
}
|
||||
|
||||
var rawToolCalls []map[string]any
|
||||
for _, tc := range choice.Message.ToolCalls {
|
||||
var input map[string]any
|
||||
if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
|
||||
input = map[string]any{}
|
||||
}
|
||||
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Input: input,
|
||||
})
|
||||
rawToolCalls = append(rawToolCalls, map[string]any{
|
||||
"id": tc.ID,
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": tc.Function.Name,
|
||||
"arguments": tc.Function.Arguments,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
raw := &rawChatMessage{
|
||||
content: choice.Message.Content,
|
||||
toolCalls: rawToolCalls,
|
||||
}
|
||||
return response, raw, nil
|
||||
}
|
||||
|
||||
func (p *Provider) streamOpenAI(ctx context.Context, req *ai.Request) (ai.Stream, error) {
|
||||
messages := buildOpenAIMessages(req)
|
||||
apiReq := map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": messages,
|
||||
"stream": true,
|
||||
"stream_options": map[string]any{"include_usage": true},
|
||||
}
|
||||
if p.opts.MaxTokens > 0 {
|
||||
apiReq["max_tokens"] = p.opts.MaxTokens
|
||||
}
|
||||
|
||||
reqBody, err := json.Marshal(apiReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal stream request: %w", err)
|
||||
}
|
||||
|
||||
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + p.streamPath()
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create stream request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Accept", "text/event-stream")
|
||||
if p.opts.APIKey != "" {
|
||||
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
|
||||
}
|
||||
|
||||
httpResp, err := http.DefaultClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stream API request failed: %w", err)
|
||||
}
|
||||
if httpResp.StatusCode != http.StatusOK {
|
||||
defer httpResp.Body.Close()
|
||||
respBody, _ := io.ReadAll(httpResp.Body)
|
||||
return nil, fmt.Errorf("stream API error (%s): %s", httpResp.Status, string(respBody))
|
||||
}
|
||||
|
||||
return &sseStream{body: httpResp.Body, scanner: bufio.NewScanner(httpResp.Body)}, nil
|
||||
}
|
||||
|
||||
// buildOpenAIMessages converts an ai.Request into the OpenAI chat message format.
|
||||
func buildOpenAIMessages(req *ai.Request) []map[string]any {
|
||||
messages := []map[string]any{}
|
||||
if req.SystemPrompt != "" {
|
||||
messages = append(messages, map[string]any{"role": "system", "content": req.SystemPrompt})
|
||||
}
|
||||
for _, m := range req.Messages {
|
||||
messages = append(messages, map[string]any{"role": m.Role, "content": m.Content})
|
||||
}
|
||||
if req.Prompt != "" {
|
||||
messages = append(messages, map[string]any{"role": "user", "content": req.Prompt})
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// sseStream reads OpenAI-style server-sent events (used by Ollama Cloud).
|
||||
type sseStream struct {
|
||||
body io.ReadCloser
|
||||
scanner *bufio.Scanner
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (s *sseStream) Recv() (*ai.Response, error) {
|
||||
for s.scanner.Scan() {
|
||||
line := strings.TrimSpace(s.scanner.Text())
|
||||
if line == "" || strings.HasPrefix(line, ":") {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(line, "data:") {
|
||||
continue
|
||||
}
|
||||
data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
if data == "[DONE]" {
|
||||
return nil, io.EOF
|
||||
}
|
||||
var chunk struct {
|
||||
Choices []struct {
|
||||
Delta struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"delta"`
|
||||
} `json:"choices"`
|
||||
Usage *struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &chunk); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse stream chunk: %w", err)
|
||||
}
|
||||
if len(chunk.Choices) > 0 && chunk.Choices[0].Delta.Content != "" {
|
||||
return &ai.Response{Reply: chunk.Choices[0].Delta.Content}, nil
|
||||
}
|
||||
if chunk.Usage != nil {
|
||||
return &ai.Response{Usage: ai.Usage{
|
||||
InputTokens: chunk.Usage.PromptTokens,
|
||||
OutputTokens: chunk.Usage.CompletionTokens,
|
||||
TotalTokens: chunk.Usage.TotalTokens,
|
||||
}}, nil
|
||||
}
|
||||
}
|
||||
if err := s.scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
func (s *sseStream) Close() error {
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
s.closed = true
|
||||
return s.body.Close()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Native mode (local Ollama: localhost:11434/api/chat)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (p *Provider) generateNative(ctx context.Context, req *ai.Request) (*ai.Response, error) {
|
||||
var tools []map[string]any
|
||||
for _, t := range req.Tools {
|
||||
tools = append(tools, map[string]any{
|
||||
"type": "function",
|
||||
"function": map[string]any{
|
||||
"name": t.Name,
|
||||
"description": t.Description,
|
||||
"parameters": map[string]any{
|
||||
"type": "object",
|
||||
"properties": t.Properties,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
messages := []map[string]any{}
|
||||
if req.SystemPrompt != "" {
|
||||
messages = append(messages, map[string]any{"role": "system", "content": req.SystemPrompt})
|
||||
}
|
||||
for _, m := range req.Messages {
|
||||
messages = append(messages, map[string]any{"role": m.Role, "content": m.Content})
|
||||
}
|
||||
if req.Prompt != "" {
|
||||
messages = append(messages, map[string]any{"role": "user", "content": req.Prompt})
|
||||
}
|
||||
|
||||
apiReq := map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": messages,
|
||||
"stream": false,
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
apiReq["tools"] = tools
|
||||
}
|
||||
if p.opts.MaxTokens > 0 {
|
||||
apiReq["options"] = map[string]any{"num_predict": p.opts.MaxTokens}
|
||||
}
|
||||
|
||||
resp, rawMsg, err := p.callNative(ctx, apiReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(resp.ToolCalls) == 0 || p.opts.ToolHandler == nil {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
convMessages := append(messages, map[string]any{
|
||||
"role": "assistant",
|
||||
"content": rawMsg.content,
|
||||
})
|
||||
if len(rawMsg.toolCalls) > 0 {
|
||||
convMessages[len(convMessages)-1]["tool_calls"] = rawMsg.toolCalls
|
||||
}
|
||||
|
||||
pendingCalls := resp.ToolCalls
|
||||
for round := 0; round < 10; round++ {
|
||||
for i := range pendingCalls {
|
||||
result := p.opts.ToolHandler(ctx, pendingCalls[i])
|
||||
pendingCalls[i].Result = result.Content
|
||||
convMessages = append(convMessages, map[string]any{
|
||||
"role": "tool",
|
||||
"content": result.Content,
|
||||
})
|
||||
}
|
||||
|
||||
followUpReq := map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": convMessages,
|
||||
"stream": false,
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
followUpReq["tools"] = tools
|
||||
}
|
||||
if p.opts.MaxTokens > 0 {
|
||||
followUpReq["options"] = map[string]any{"num_predict": p.opts.MaxTokens}
|
||||
}
|
||||
|
||||
followUpResp, followUpRaw, err := p.callNative(ctx, followUpReq)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
if len(followUpResp.ToolCalls) > 0 {
|
||||
resp.ToolCalls = append(resp.ToolCalls, followUpResp.ToolCalls...)
|
||||
pendingCalls = followUpResp.ToolCalls
|
||||
convMessages = append(convMessages, map[string]any{
|
||||
"role": "assistant",
|
||||
"content": followUpRaw.content,
|
||||
})
|
||||
if len(followUpRaw.toolCalls) > 0 {
|
||||
convMessages[len(convMessages)-1]["tool_calls"] = followUpRaw.toolCalls
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if followUpResp.Reply != "" {
|
||||
resp.Answer = followUpResp.Reply
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (p *Provider) callNative(ctx context.Context, req map[string]any) (*ai.Response, *rawChatMessage, error) {
|
||||
reqBody, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
|
||||
}
|
||||
|
||||
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + p.chatPath()
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
if p.opts.APIKey != "" {
|
||||
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
|
||||
}
|
||||
|
||||
httpResp, err := http.DefaultClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("API request failed: %w", err)
|
||||
}
|
||||
defer httpResp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(httpResp.Body)
|
||||
if httpResp.StatusCode != http.StatusOK {
|
||||
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
|
||||
}
|
||||
|
||||
var chatResp struct {
|
||||
Message struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
ToolCalls []struct {
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments any `json:"arguments"`
|
||||
} `json:"function"`
|
||||
} `json:"tool_calls"`
|
||||
} `json:"message"`
|
||||
Done bool `json:"done"`
|
||||
PromptEvalCount int `json:"prompt_eval_count"`
|
||||
EvalCount int `json:"eval_count"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(respBody, &chatResp); err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
|
||||
}
|
||||
|
||||
response := &ai.Response{
|
||||
Reply: chatResp.Message.Content,
|
||||
Usage: ai.Usage{
|
||||
InputTokens: chatResp.PromptEvalCount,
|
||||
OutputTokens: chatResp.EvalCount,
|
||||
TotalTokens: chatResp.PromptEvalCount + chatResp.EvalCount,
|
||||
},
|
||||
}
|
||||
|
||||
var rawToolCalls []map[string]any
|
||||
for _, tc := range chatResp.Message.ToolCalls {
|
||||
var input map[string]any
|
||||
switch v := tc.Function.Arguments.(type) {
|
||||
case string:
|
||||
if err := json.Unmarshal([]byte(v), &input); err != nil {
|
||||
input = map[string]any{}
|
||||
}
|
||||
case map[string]any:
|
||||
input = v
|
||||
default:
|
||||
input = map[string]any{}
|
||||
}
|
||||
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
|
||||
Name: tc.Function.Name,
|
||||
Input: input,
|
||||
})
|
||||
rawToolCalls = append(rawToolCalls, map[string]any{
|
||||
"function": map[string]any{
|
||||
"name": tc.Function.Name,
|
||||
"arguments": tc.Function.Arguments,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
raw := &rawChatMessage{
|
||||
content: chatResp.Message.Content,
|
||||
toolCalls: rawToolCalls,
|
||||
}
|
||||
return response, raw, nil
|
||||
}
|
||||
|
||||
func (p *Provider) streamNative(ctx context.Context, req *ai.Request) (ai.Stream, error) {
|
||||
messages := []map[string]any{}
|
||||
if req.SystemPrompt != "" {
|
||||
messages = append(messages, map[string]any{"role": "system", "content": req.SystemPrompt})
|
||||
}
|
||||
for _, m := range req.Messages {
|
||||
messages = append(messages, map[string]any{"role": m.Role, "content": m.Content})
|
||||
}
|
||||
if req.Prompt != "" {
|
||||
messages = append(messages, map[string]any{"role": "user", "content": req.Prompt})
|
||||
}
|
||||
|
||||
apiReq := map[string]any{
|
||||
"model": p.opts.Model,
|
||||
"messages": messages,
|
||||
"stream": true,
|
||||
}
|
||||
if p.opts.MaxTokens > 0 {
|
||||
apiReq["options"] = map[string]any{"num_predict": p.opts.MaxTokens}
|
||||
}
|
||||
|
||||
reqBody, err := json.Marshal(apiReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal stream request: %w", err)
|
||||
}
|
||||
|
||||
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + p.streamPath()
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create stream request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
if p.opts.APIKey != "" {
|
||||
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
|
||||
}
|
||||
|
||||
httpResp, err := http.DefaultClient.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stream API request failed: %w", err)
|
||||
}
|
||||
if httpResp.StatusCode != http.StatusOK {
|
||||
defer httpResp.Body.Close()
|
||||
respBody, _ := io.ReadAll(httpResp.Body)
|
||||
return nil, fmt.Errorf("stream API error (%s): %s", httpResp.Status, string(respBody))
|
||||
}
|
||||
|
||||
return &ndjsonStream{body: httpResp.Body, scanner: bufio.NewScanner(httpResp.Body)}, nil
|
||||
}
|
||||
|
||||
// ndjsonStream reads newline-delimited JSON (used by local Ollama).
|
||||
type ndjsonStream struct {
|
||||
body io.ReadCloser
|
||||
scanner *bufio.Scanner
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (s *ndjsonStream) Recv() (*ai.Response, error) {
|
||||
for s.scanner.Scan() {
|
||||
line := strings.TrimSpace(s.scanner.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var chunk struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
Done bool `json:"done"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &chunk); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse stream chunk: %w", err)
|
||||
}
|
||||
if chunk.Done {
|
||||
return nil, io.EOF
|
||||
}
|
||||
if chunk.Message.Content != "" {
|
||||
return &ai.Response{Reply: chunk.Message.Content}, nil
|
||||
}
|
||||
}
|
||||
if err := s.scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, io.EOF
|
||||
}
|
||||
|
||||
func (s *ndjsonStream) Close() error {
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
s.closed = true
|
||||
return s.body.Close()
|
||||
}
|
||||
|
||||
// rawChatMessage holds the raw assistant content and tool calls for
|
||||
// follow-up messages.
|
||||
type rawChatMessage struct {
|
||||
content string
|
||||
toolCalls []map[string]any
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package ollama
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Provider basics
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestProvider_String(t *testing.T) {
|
||||
p := NewProvider()
|
||||
if p.String() != "ollama" {
|
||||
t.Errorf("Expected 'ollama', got '%s'", p.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Init(t *testing.T) {
|
||||
p := NewProvider()
|
||||
err := p.Init(
|
||||
ai.WithModel("test-model"),
|
||||
ai.WithAPIKey("test-key"),
|
||||
ai.WithBaseURL("https://test.com"),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Init failed: %v", err)
|
||||
}
|
||||
opts := p.Options()
|
||||
if opts.Model != "test-model" {
|
||||
t.Errorf("Expected model 'test-model', got '%s'", opts.Model)
|
||||
}
|
||||
if opts.APIKey != "test-key" {
|
||||
t.Errorf("Expected API key 'test-key', got '%s'", opts.APIKey)
|
||||
}
|
||||
if opts.BaseURL != "https://test.com" {
|
||||
t.Errorf("Expected base URL 'https://test.com', got '%s'", opts.BaseURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_Defaults(t *testing.T) {
|
||||
p := NewProvider()
|
||||
opts := p.Options()
|
||||
if opts.Model != "llama3.2" {
|
||||
t.Errorf("Expected default model 'llama3.2', got '%s'", opts.Model)
|
||||
}
|
||||
if opts.BaseURL != "http://localhost:11434" {
|
||||
t.Errorf("Expected default base URL 'http://localhost:11434', got '%s'", opts.BaseURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvider_IsCloud(t *testing.T) {
|
||||
local := NewProvider(ai.WithBaseURL("http://localhost:11434"))
|
||||
if local.isCloud() {
|
||||
t.Error("localhost should not be cloud")
|
||||
}
|
||||
cloud := NewProvider(ai.WithBaseURL("https://ollama.com/v1"))
|
||||
if !cloud.isCloud() {
|
||||
t.Error("ollama.com should be cloud")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Native mode (local Ollama: /api/chat)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestNative_Generate(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/chat" {
|
||||
t.Errorf("Expected /api/chat, got %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{
|
||||
"model": "llama3.2",
|
||||
"message": {"role": "assistant", "content": "Hello from local Ollama!"},
|
||||
"done": true,
|
||||
"prompt_eval_count": 10,
|
||||
"eval_count": 5
|
||||
}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p := NewProvider(ai.WithBaseURL(srv.URL), ai.WithModel("llama3.2"))
|
||||
resp, err := p.Generate(context.Background(), &ai.Request{
|
||||
Prompt: "Hi",
|
||||
SystemPrompt: "You are helpful",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Generate failed: %v", err)
|
||||
}
|
||||
if resp.Reply != "Hello from local Ollama!" {
|
||||
t.Errorf("Expected 'Hello from local Ollama!', got '%s'", resp.Reply)
|
||||
}
|
||||
if resp.Usage.TotalTokens != 15 {
|
||||
t.Errorf("Expected total tokens 15, got %d", resp.Usage.TotalTokens)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNative_GenerateWithToolCall(t *testing.T) {
|
||||
callCount := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
callCount++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if callCount == 1 {
|
||||
w.Write([]byte(`{
|
||||
"model": "llama3.2",
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [{"function": {"name": "get_weather", "arguments": "{\"city\":\"Seoul\"}"}}]
|
||||
},
|
||||
"done": true
|
||||
}`))
|
||||
} else {
|
||||
w.Write([]byte(`{
|
||||
"model": "llama3.2",
|
||||
"message": {"role": "assistant", "content": "The weather in Seoul is sunny."},
|
||||
"done": true
|
||||
}`))
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
handler := func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
|
||||
if call.Name != "get_weather" {
|
||||
t.Errorf("Expected tool 'get_weather', got '%s'", call.Name)
|
||||
}
|
||||
return ai.ToolResult{ID: call.ID, Content: `{"temp": 22, "condition": "sunny"}`}
|
||||
}
|
||||
|
||||
p := NewProvider(
|
||||
ai.WithBaseURL(srv.URL),
|
||||
ai.WithModel("llama3.2"),
|
||||
ai.WithToolHandler(handler),
|
||||
)
|
||||
resp, err := p.Generate(context.Background(), &ai.Request{
|
||||
Prompt: "What's the weather?",
|
||||
Tools: []ai.Tool{{
|
||||
Name: "get_weather",
|
||||
Description: "Get weather",
|
||||
Properties: map[string]any{"city": map[string]any{"type": "string"}},
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Generate failed: %v", err)
|
||||
}
|
||||
if len(resp.ToolCalls) == 0 {
|
||||
t.Error("Expected tool calls")
|
||||
}
|
||||
if resp.Answer != "The weather in Seoul is sunny." {
|
||||
t.Errorf("Expected final answer, got '%s'", resp.Answer)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNative_Stream(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"message":{"role":"assistant","content":"Hello"},"done":false}` + "\n"))
|
||||
w.Write([]byte(`{"message":{"role":"assistant","content":" world"},"done":false}` + "\n"))
|
||||
w.Write([]byte(`{"message":{"role":"assistant","content":""},"done":true}` + "\n"))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p := NewProvider(ai.WithBaseURL(srv.URL), ai.WithModel("llama3.2"))
|
||||
stream, err := p.Stream(context.Background(), &ai.Request{Prompt: "Hi"})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream failed: %v", err)
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
var chunks []string
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if resp.Reply != "" {
|
||||
chunks = append(chunks, resp.Reply)
|
||||
}
|
||||
}
|
||||
result := strings.Join(chunks, "")
|
||||
if result != "Hello world" {
|
||||
t.Errorf("Expected 'Hello world', got '%s'", result)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cloud mode (Ollama Cloud: /v1/chat/completions)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestCloud_Generate(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/chat/completions" {
|
||||
t.Errorf("Expected /v1/chat/completions, got %s", r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
||||
"choices": [{"message": {"role": "assistant", "content": "Hello from Ollama Cloud!"}}]
|
||||
}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p := NewProvider(ai.WithBaseURL(srv.URL), ai.WithModel("gemma4:31b-cloud"), ai.WithAPIKey("test-key"))
|
||||
p.cloudOverride = true
|
||||
resp, err := p.Generate(context.Background(), &ai.Request{
|
||||
Prompt: "Hi",
|
||||
SystemPrompt: "You are helpful",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Generate failed: %v", err)
|
||||
}
|
||||
if resp.Reply != "Hello from Ollama Cloud!" {
|
||||
t.Errorf("Expected 'Hello from Ollama Cloud!', got '%s'", resp.Reply)
|
||||
}
|
||||
if resp.Usage.TotalTokens != 15 {
|
||||
t.Errorf("Expected total tokens 15, got %d", resp.Usage.TotalTokens)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloud_GenerateWithToolCall(t *testing.T) {
|
||||
callCount := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
callCount++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if callCount == 1 {
|
||||
w.Write([]byte(`{
|
||||
"choices": [{"message": {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [{"id": "call_1", "function": {"name": "search", "arguments": "{\"query\":\"go interfaces\"}"}}]
|
||||
}}]
|
||||
}`))
|
||||
} else {
|
||||
w.Write([]byte(`{
|
||||
"choices": [{"message": {"role": "assistant", "content": "Go interfaces are implicit."}}]
|
||||
}`))
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
handler := func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
|
||||
return ai.ToolResult{ID: call.ID, Content: `{"results": ["Go interfaces are implicit"]}`}
|
||||
}
|
||||
|
||||
p := NewProvider(
|
||||
ai.WithBaseURL(srv.URL),
|
||||
ai.WithModel("gemma4:31b-cloud"),
|
||||
ai.WithAPIKey("test-key"),
|
||||
ai.WithToolHandler(handler),
|
||||
)
|
||||
p.cloudOverride = true
|
||||
resp, err := p.Generate(context.Background(), &ai.Request{
|
||||
Prompt: "Search for Go interfaces",
|
||||
Tools: []ai.Tool{{
|
||||
Name: "search",
|
||||
Description: "Search the knowledge base",
|
||||
Properties: map[string]any{"query": map[string]any{"type": "string"}},
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Generate failed: %v", err)
|
||||
}
|
||||
if len(resp.ToolCalls) == 0 {
|
||||
t.Error("Expected tool calls")
|
||||
}
|
||||
if resp.Answer != "Go interfaces are implicit." {
|
||||
t.Errorf("Expected final answer, got '%s'", resp.Answer)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloud_Stream(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n"))
|
||||
w.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\" cloud\"}}]}\n\n"))
|
||||
w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p := NewProvider(
|
||||
ai.WithBaseURL(srv.URL),
|
||||
ai.WithModel("gemma4:31b-cloud"),
|
||||
ai.WithAPIKey("test-key"),
|
||||
)
|
||||
p.cloudOverride = true
|
||||
stream, err := p.Stream(context.Background(), &ai.Request{Prompt: "Hi"})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream failed: %v", err)
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
var chunks []string
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if resp.Reply != "" {
|
||||
chunks = append(chunks, resp.Reply)
|
||||
}
|
||||
}
|
||||
result := strings.Join(chunks, "")
|
||||
if result != "Hello cloud" {
|
||||
t.Errorf("Expected 'Hello cloud', got '%s'", result)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestProvider_APIError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
w.Write([]byte(`{"error": "model not found"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p := NewProvider(ai.WithBaseURL(srv.URL), ai.WithModel("nonexistent"))
|
||||
_, err := p.Generate(context.Background(), &ai.Request{Prompt: "Hi"})
|
||||
if err == nil {
|
||||
t.Error("Expected error on API failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "API error") {
|
||||
t.Errorf("Expected 'API error' in message, got '%s'", err.Error())
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -99,15 +99,19 @@ func GenerateWithRetry(ctx context.Context, m Model, req *Request, policy Genera
|
||||
}
|
||||
resp, err := m.Generate(callCtx, req, opts...)
|
||||
cancel()
|
||||
|
||||
// Caller cancellation/deadline always wins and is not retried, even if
|
||||
// a provider or tool loop swallowed the canceled tool result and returned
|
||||
// a final response. This keeps agent runs from appearing successful after
|
||||
// their controlling context was abandoned.
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return nil, ctxErr
|
||||
}
|
||||
if err == nil {
|
||||
return resp, nil
|
||||
}
|
||||
last = err
|
||||
|
||||
// Caller cancellation/deadline always wins and is not retried.
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
transient := IsTransientError(err)
|
||||
if attempt == policy.MaxAttempts || !transient {
|
||||
if attempt > 1 || transient {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
_ "go-micro.dev/v6/ai/atlascloud"
|
||||
_ "go-micro.dev/v6/ai/gemini"
|
||||
_ "go-micro.dev/v6/ai/groq"
|
||||
_ "go-micro.dev/v6/ai/minimax"
|
||||
_ "go-micro.dev/v6/ai/mistral"
|
||||
_ "go-micro.dev/v6/ai/openai"
|
||||
_ "go-micro.dev/v6/ai/together"
|
||||
@@ -150,6 +152,109 @@ func TestStreamProvidersCloseCancelsInFlightRequest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamProvidersPropagateProviderErrors(t *testing.T) {
|
||||
for _, provider := range conformingStreamProviders(t) {
|
||||
provider := provider
|
||||
t.Run(provider, func(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "upstream quota exhausted", http.StatusTooManyRequests)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
stream, err := ai.New(provider, ai.WithAPIKey("test-key"), ai.WithBaseURL(ts.URL)).Stream(context.Background(), &ai.Request{Prompt: "Hello"})
|
||||
if err == nil {
|
||||
_ = stream.Close()
|
||||
t.Fatal("Stream returned nil error for provider failure")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "429") || !strings.Contains(err.Error(), "upstream quota exhausted") {
|
||||
t.Fatalf("Stream error = %v, want provider status and body", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "test-key") {
|
||||
t.Fatal("provider error leaked API key")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamProvidersHonorCanceledContextBeforeRequest(t *testing.T) {
|
||||
for _, provider := range conformingStreamProviders(t) {
|
||||
provider := provider
|
||||
t.Run(provider, func(t *testing.T) {
|
||||
var sawRequest bool
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sawRequest = true
|
||||
http.Error(w, "unexpected request", http.StatusInternalServerError)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
stream, err := ai.New(provider, ai.WithAPIKey("test-key"), ai.WithBaseURL(ts.URL)).Stream(ctx, &ai.Request{Prompt: "Hello"})
|
||||
if err == nil {
|
||||
_ = stream.Close()
|
||||
t.Fatal("Stream returned nil error for canceled context")
|
||||
}
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Stream error = %v, want context.Canceled", err)
|
||||
}
|
||||
if sawRequest {
|
||||
t.Fatal("provider sent request after context was already canceled")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredProviderStreamsSkipWithoutCredentials(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
provider string
|
||||
keyEnv string
|
||||
modelEnv string
|
||||
}{
|
||||
{provider: "openai", keyEnv: "OPENAI_API_KEY", modelEnv: "OPENAI_MODEL"},
|
||||
{provider: "groq", keyEnv: "GROQ_API_KEY", modelEnv: "GROQ_MODEL"},
|
||||
{provider: "mistral", keyEnv: "MISTRAL_API_KEY", modelEnv: "MISTRAL_MODEL"},
|
||||
{provider: "together", keyEnv: "TOGETHER_API_KEY", modelEnv: "TOGETHER_MODEL"},
|
||||
{provider: "atlascloud", keyEnv: "ATLASCLOUD_API_KEY", modelEnv: "ATLASCLOUD_MODEL"},
|
||||
} {
|
||||
tc := tc
|
||||
t.Run(tc.provider, func(t *testing.T) {
|
||||
key := os.Getenv(tc.keyEnv)
|
||||
if key == "" {
|
||||
t.Skipf("%s not set; skipping configured provider stream check", tc.keyEnv)
|
||||
}
|
||||
|
||||
opts := []ai.Option{ai.WithAPIKey(key)}
|
||||
if model := os.Getenv(tc.modelEnv); model != "" {
|
||||
opts = append(opts, ai.WithModel(model))
|
||||
}
|
||||
stream, err := ai.New(tc.provider, opts...).Stream(context.Background(), &ai.Request{Prompt: "Reply with exactly: ok"})
|
||||
if err != nil {
|
||||
t.Fatalf("Stream returned error: %v", err)
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
deadline := time.After(30 * time.Second)
|
||||
for {
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Fatal("timed out waiting for provider stream chunk")
|
||||
default:
|
||||
}
|
||||
chunk, err := stream.Recv()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
t.Fatal("provider stream ended without content")
|
||||
}
|
||||
t.Fatalf("Recv returned error: %v", err)
|
||||
}
|
||||
if chunk.Reply != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsupportedProvidersReturnStreamingUnsupportedAndStayUnregistered(t *testing.T) {
|
||||
for _, provider := range []string{"anthropic", "gemini"} {
|
||||
provider := provider
|
||||
@@ -174,6 +279,7 @@ func conformingStreamProviders(t *testing.T) []string {
|
||||
allowed := map[string]struct{}{
|
||||
"atlascloud": {},
|
||||
"groq": {},
|
||||
"minimax": {},
|
||||
"mistral": {},
|
||||
"openai": {},
|
||||
"together": {},
|
||||
@@ -184,7 +290,7 @@ func conformingStreamProviders(t *testing.T) []string {
|
||||
out = append(out, provider)
|
||||
}
|
||||
}
|
||||
want := []string{"atlascloud", "groq", "mistral", "openai", "together"}
|
||||
want := []string{"atlascloud", "groq", "minimax", "mistral", "openai", "together"}
|
||||
if !reflect.DeepEqual(out, want) {
|
||||
t.Fatalf("conforming stream providers = %#v, want %#v (registered stream providers: %#v)", out, want, providers)
|
||||
}
|
||||
|
||||
@@ -625,3 +625,54 @@ Scopes provide fine-grained access control over which tokens can call which serv
|
||||
The gateway's scope system uses `auth.Account` from the go-micro framework. Scopes on accounts are the same `[]string` field used by the framework's `auth.Rules` and `wrapper/auth` package. The gateway stores scope requirements in the default store under `endpoint-scopes/<service>.<endpoint>` keys and checks them on every HTTP request.
|
||||
|
||||
For service-level (RPC) auth within the go-micro mesh, use the `wrapper/auth` package which provides `auth.Rules` with priority-based access control. See the [auth wrapper documentation](../../wrapper/auth/README.md) for details.
|
||||
|
||||
## Self-improving loop (`micro loop`)
|
||||
|
||||
Turn a repository into a self-improving one: GitHub Actions workflows that
|
||||
dispatch a coding agent to plan, build, and triage — gated by CI. This is the
|
||||
same loop that maintains go-micro itself, generalized so any repo (and any
|
||||
@mention-driven agent) can use it.
|
||||
|
||||
```bash
|
||||
micro loop init # scaffold the loop into the current repo
|
||||
micro loop verify # check a repo is wired correctly
|
||||
```
|
||||
|
||||
`micro loop init` writes the selected roles' workflows, their prompts, and a queue. Choose roles with `--roles` (default `planner,builder,triage`; `--roles all` for everything):
|
||||
|
||||
| Role | Workflow | What it does |
|
||||
|------|----------|--------------|
|
||||
| Planner | `loop-planner.yml` | Keeps a ranked queue in `.github/loop/PRIORITIES.md` |
|
||||
| Builder | `loop-builder.yml` | Builds the top open item as a single-concern PR, auto-merged on green CI |
|
||||
| Triage | `loop-triage.yml` | Turns CI failures into scoped fix issues, back into the queue |
|
||||
| Coherence | `loop-coherence.yml` | Keeps README/docs/CHANGELOG aligned with the North Star *(opt-in)* |
|
||||
| Release | `loop-release.yml` | Cuts the next patch tag when the branch has new commits *(opt-in)* |
|
||||
|
||||
The workflows are the **mechanism**; each dispatch role's instruction is an editable file in `.github/loop/prompts/` — the **policy**. Edit those prompts (and `.github/loop/NORTH_STAR.md`) to steer the loop without touching the CLI. That split is what lets go-micro itself use `micro loop` while keeping its own richer prompts.
|
||||
|
||||
Common flags:
|
||||
|
||||
```bash
|
||||
micro loop init \
|
||||
--roles all \
|
||||
--agent @codex \
|
||||
--token-secret LOOP_TOKEN \
|
||||
--branch main \
|
||||
--ci-workflow CI
|
||||
```
|
||||
|
||||
- `--roles`: which roles to scaffold (`planner,builder,triage`, or `all`)
|
||||
- `--agent`: how the workflows summon the agent (an `@mention`)
|
||||
- `--token-secret`: repo secret holding the driving user PAT
|
||||
- `--branch`: base branch for the loop's PRs
|
||||
- `--ci-workflow`: `name:` of the CI workflow triage watches
|
||||
- `--tag-prefix`: tag prefix the release role matches and bumps (default `v`)
|
||||
|
||||
Two things the CLI can't do for you (and `micro loop verify` reminds you of):
|
||||
|
||||
1. **Add the token secret.** The agent ignores `@mentions` from the
|
||||
`github-actions` bot, so dispatch posts as a real user via a PAT stored in
|
||||
the `--token-secret` repo secret. The workflows no-op until it's set.
|
||||
2. **Set branch protection.** Require the CI checks with **0 approving reviews**
|
||||
so the builder's native auto-merge lands PRs the moment CI is green — that
|
||||
green-CI gate is the loop's only safety mechanism, so keep the suite strong.
|
||||
|
||||
@@ -36,6 +36,14 @@ func init() {
|
||||
Name: "agent",
|
||||
Usage: "Manage AI agents",
|
||||
Subcommands: []*cli.Command{
|
||||
{
|
||||
Name: "preflight",
|
||||
Aliases: []string{"doctor"},
|
||||
Usage: "Check local prerequisites before the first provider-backed agent",
|
||||
Action: func(c *cli.Context) error {
|
||||
return runAgentPreflight(os.Stdout, defaultPreflightDeps())
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "list",
|
||||
Usage: "List registered agents",
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"go-micro.dev/v6/cmd"
|
||||
)
|
||||
|
||||
type preflightCheck struct {
|
||||
Name string
|
||||
OK bool
|
||||
Detail string
|
||||
Fix string
|
||||
Next string
|
||||
}
|
||||
|
||||
type preflightDeps struct {
|
||||
lookPath func(string) (string, error)
|
||||
commandOutput func(string, ...string) ([]byte, error)
|
||||
executable func() (string, error)
|
||||
version func() string
|
||||
getenv func(string) string
|
||||
listen func(string, string) (net.Listener, error)
|
||||
}
|
||||
|
||||
func defaultPreflightDeps() preflightDeps {
|
||||
return preflightDeps{
|
||||
lookPath: exec.LookPath,
|
||||
commandOutput: func(name string, args ...string) ([]byte, error) { return exec.Command(name, args...).CombinedOutput() },
|
||||
executable: os.Executable,
|
||||
version: func() string { return cmd.App().Version },
|
||||
getenv: os.Getenv,
|
||||
listen: net.Listen,
|
||||
}
|
||||
}
|
||||
|
||||
func runAgentPreflight(w io.Writer, deps preflightDeps) error {
|
||||
checks := agentPreflightChecks(deps)
|
||||
failures := 0
|
||||
fmt.Fprintln(w, "First-agent preflight")
|
||||
for _, check := range checks {
|
||||
mark := "✓"
|
||||
if !check.OK {
|
||||
mark = "✗"
|
||||
failures++
|
||||
}
|
||||
fmt.Fprintf(w, " %s %s — %s\n", mark, check.Name, check.Detail)
|
||||
if !check.OK && check.Fix != "" {
|
||||
fmt.Fprintf(w, " Fix: %s\n", check.Fix)
|
||||
}
|
||||
if !check.OK && check.Next != "" {
|
||||
fmt.Fprintf(w, " Next: %s\n", check.Next)
|
||||
}
|
||||
}
|
||||
if failures > 0 {
|
||||
return fmt.Errorf("first-agent preflight failed: %d check(s) need attention", failures)
|
||||
}
|
||||
fmt.Fprintln(w, "\nReady for the first-agent walkthrough: micro run, then open http://localhost:8080/agent or use micro chat.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func agentPreflightChecks(deps preflightDeps) []preflightCheck {
|
||||
if deps.lookPath == nil {
|
||||
deps.lookPath = exec.LookPath
|
||||
}
|
||||
if deps.commandOutput == nil {
|
||||
deps.commandOutput = func(name string, args ...string) ([]byte, error) { return exec.Command(name, args...).CombinedOutput() }
|
||||
}
|
||||
if deps.executable == nil {
|
||||
deps.executable = os.Executable
|
||||
}
|
||||
if deps.version == nil {
|
||||
deps.version = func() string { return cmd.App().Version }
|
||||
}
|
||||
if deps.getenv == nil {
|
||||
deps.getenv = os.Getenv
|
||||
}
|
||||
if deps.listen == nil {
|
||||
deps.listen = net.Listen
|
||||
}
|
||||
|
||||
checks := []preflightCheck{checkGoToolchain(deps), checkMicroBinary(deps), checkProviderKey(deps), checkPortAvailable(deps, ":8080", "micro run gateway and /agent playground")}
|
||||
return checks
|
||||
}
|
||||
|
||||
func checkGoToolchain(deps preflightDeps) preflightCheck {
|
||||
path, err := deps.lookPath("go")
|
||||
if err != nil {
|
||||
return preflightCheck{Name: "Go toolchain", Detail: "go was not found on PATH", Fix: "Install Go 1.24 or newer from https://go.dev/doc/install and ensure go is on PATH.", Next: "After installing Go, rerun micro agent preflight, then continue with docs/guides/your-first-agent.html."}
|
||||
}
|
||||
out, err := deps.commandOutput("go", "version")
|
||||
if err != nil {
|
||||
return preflightCheck{Name: "Go toolchain", Detail: strings.TrimSpace(string(out)), Fix: "Ensure the go command runs successfully (try `go version`) before starting the agent walkthrough.", Next: "Use docs/guides/debugging-agents.html after the toolchain check passes if an agent run still fails."}
|
||||
}
|
||||
version := firstLine(out)
|
||||
if !goVersionAtLeast(version, 1, 24) {
|
||||
return preflightCheck{Name: "Go toolchain", Detail: fmt.Sprintf("%s (%s)", version, path), Fix: "Upgrade to Go 1.24 or newer before running generated services.", Next: "Rerun micro agent preflight, then continue with docs/guides/your-first-agent.html."}
|
||||
}
|
||||
return preflightCheck{Name: "Go toolchain", OK: true, Detail: fmt.Sprintf("%s (%s)", version, path)}
|
||||
}
|
||||
|
||||
func checkMicroBinary(deps preflightDeps) preflightCheck {
|
||||
exe, err := deps.executable()
|
||||
if err != nil || exe == "" {
|
||||
return preflightCheck{Name: "micro binary", Detail: "micro executable path is unavailable", Fix: "Install the micro CLI or run this check through `go run ./cmd/micro agent preflight` from the repository.", Next: "Then follow docs/getting-started.html for the scaffold -> run path."}
|
||||
}
|
||||
version := deps.version()
|
||||
if version == "" {
|
||||
version = "version unavailable"
|
||||
}
|
||||
return preflightCheck{Name: "micro binary", OK: true, Detail: fmt.Sprintf("%s (%s)", version, exe)}
|
||||
}
|
||||
|
||||
func checkProviderKey(deps preflightDeps) preflightCheck {
|
||||
keys := []string{"MICRO_AI_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GEMINI_API_KEY", "GROQ_API_KEY", "MISTRAL_API_KEY", "TOGETHER_API_KEY", "ATLASCLOUD_API_KEY"}
|
||||
var found []string
|
||||
for _, k := range keys {
|
||||
if deps.getenv(k) != "" {
|
||||
found = append(found, k)
|
||||
}
|
||||
}
|
||||
if len(found) == 0 {
|
||||
return preflightCheck{Name: "provider API key", Detail: "no supported provider key found", Fix: "Export MICRO_AI_API_KEY or a provider key such as ANTHROPIC_API_KEY before running provider-backed agents.", Next: "For a no-secret path, run the mock-model walkthrough in docs/guides/no-secret-first-agent.html; for real providers, see docs/guides/debugging-agents.html#provider-failures."}
|
||||
}
|
||||
return preflightCheck{Name: "provider API key", OK: true, Detail: "found " + strings.Join(found, ", ")}
|
||||
}
|
||||
|
||||
func checkPortAvailable(deps preflightDeps, addr, use string) preflightCheck {
|
||||
ln, err := deps.listen("tcp", addr)
|
||||
if err != nil {
|
||||
return preflightCheck{Name: "local port " + addr, Detail: "busy or unavailable for " + use, Fix: "Stop the process using " + addr + " (for example, `lsof -i :8080`) or run `micro run --address` with a free port.", Next: "Once the gateway starts, open http://localhost:8080/agent or continue with docs/guides/your-first-agent.html#chat-with-your-agent."}
|
||||
}
|
||||
_ = ln.Close()
|
||||
return preflightCheck{Name: "local port " + addr, OK: true, Detail: "available for " + use}
|
||||
}
|
||||
|
||||
func firstLine(b []byte) string {
|
||||
s := strings.TrimSpace(string(b))
|
||||
if i := strings.IndexByte(s, '\n'); i >= 0 {
|
||||
return s[:i]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func goVersionAtLeast(line string, wantMajor, wantMinor int) bool {
|
||||
idx := strings.Index(line, "go1.")
|
||||
if idx < 0 {
|
||||
return false
|
||||
}
|
||||
var major, minor int
|
||||
if _, err := fmt.Sscanf(line[idx:], "go%d.%d", &major, &minor); err != nil {
|
||||
return false
|
||||
}
|
||||
if major != wantMajor {
|
||||
return major > wantMajor
|
||||
}
|
||||
return minor >= wantMinor
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type stubListener struct{}
|
||||
|
||||
func (stubListener) Accept() (net.Conn, error) { return nil, errors.New("closed") }
|
||||
func (stubListener) Close() error { return nil }
|
||||
func (stubListener) Addr() net.Addr { return stubAddr(":8080") }
|
||||
|
||||
type stubAddr string
|
||||
|
||||
func (a stubAddr) Network() string { return "tcp" }
|
||||
func (a stubAddr) String() string { return string(a) }
|
||||
|
||||
func TestRunAgentPreflightPassesWithKeyAndFreePort(t *testing.T) {
|
||||
deps := preflightDeps{
|
||||
lookPath: func(name string) (string, error) { return "/usr/bin/" + name, nil },
|
||||
commandOutput: func(name string, args ...string) ([]byte, error) {
|
||||
return []byte("go version go1.24.0 linux/amd64\n"), nil
|
||||
},
|
||||
executable: func() (string, error) { return "/usr/local/bin/micro", nil },
|
||||
getenv: func(key string) string {
|
||||
if key == "ANTHROPIC_API_KEY" {
|
||||
return "set"
|
||||
}
|
||||
return ""
|
||||
},
|
||||
listen: func(network, address string) (net.Listener, error) { return stubListener{}, nil },
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := runAgentPreflight(&out, deps); err != nil {
|
||||
t.Fatalf("runAgentPreflight() error = %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{"First-agent preflight", "✓ Go toolchain", "✓ micro binary", "✓ provider API key", "✓ local port :8080", "Ready for the first-agent walkthrough"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("output missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAgentPreflightReportsActionableFailures(t *testing.T) {
|
||||
deps := preflightDeps{
|
||||
lookPath: func(name string) (string, error) { return "", errors.New("not found") },
|
||||
executable: func() (string, error) { return "", errors.New("unknown") },
|
||||
getenv: func(key string) string { return "" },
|
||||
listen: func(network, address string) (net.Listener, error) { return nil, errors.New("in use") },
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
err := runAgentPreflight(&out, deps)
|
||||
if err == nil {
|
||||
t.Fatal("runAgentPreflight() error = nil")
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{"✗ Go toolchain", "go was not found on PATH", "https://go.dev/doc/install", "docs/guides/your-first-agent.html", "✗ micro binary", "go run ./cmd/micro agent preflight", "✗ provider API key", "docs/guides/no-secret-first-agent.html", "docs/guides/debugging-agents.html#provider-failures", "✗ local port :8080", "lsof -i :8080", "micro run --address"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("output missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunAgentPreflightReportsOldGoVersion(t *testing.T) {
|
||||
deps := preflightDeps{
|
||||
lookPath: func(name string) (string, error) { return "/usr/bin/" + name, nil },
|
||||
commandOutput: func(name string, args ...string) ([]byte, error) {
|
||||
return []byte("go version go1.23.9 linux/amd64\n"), nil
|
||||
},
|
||||
executable: func() (string, error) { return "/usr/local/bin/micro", nil },
|
||||
getenv: func(key string) string {
|
||||
if key == "ANTHROPIC_API_KEY" {
|
||||
return "set"
|
||||
}
|
||||
return ""
|
||||
},
|
||||
listen: func(network, address string) (net.Listener, error) { return stubListener{}, nil },
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
err := runAgentPreflight(&out, deps)
|
||||
if err == nil {
|
||||
t.Fatal("runAgentPreflight() error = nil")
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{"✗ Go toolchain", "go1.23.9", "Upgrade to Go 1.24 or newer", "Rerun micro agent preflight"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("output missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoVersionAtLeast(t *testing.T) {
|
||||
tests := []struct {
|
||||
line string
|
||||
want bool
|
||||
}{
|
||||
{line: "go version go1.24.0 linux/amd64", want: true},
|
||||
{line: "go version go1.25.1 linux/amd64", want: true},
|
||||
{line: "go version go1.23.9 linux/amd64", want: false},
|
||||
{line: "unexpected", want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := goVersionAtLeast(tt.line, 1, 24); got != tt.want {
|
||||
t.Fatalf("goVersionAtLeast(%q) = %v, want %v", tt.line, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFirstLine(t *testing.T) {
|
||||
if got := firstLine([]byte("one\ntwo")); got != "one" {
|
||||
t.Fatalf("firstLine() = %q", got)
|
||||
}
|
||||
if got := firstLine([]byte(" single ")); got != "single" {
|
||||
t.Fatalf("firstLine() = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,30 @@ import (
|
||||
_ "go-micro.dev/v6/cmd/micro/cli/remote"
|
||||
)
|
||||
|
||||
const docsWayfinding = `First-agent and 0→hero docs:
|
||||
|
||||
1. No-secret first-agent transcript
|
||||
https://go-micro.dev/docs/guides/no-secret-first-agent.html
|
||||
Run the maintained support agent without a provider key:
|
||||
go test ./internal/harness/zero-to-hero-ci -run TestNoSecretFirstAgentTranscript -count=1
|
||||
|
||||
2. Your First Agent
|
||||
https://go-micro.dev/docs/guides/your-first-agent.html
|
||||
Build a service-backed agent, then use:
|
||||
micro agent preflight
|
||||
micro run
|
||||
micro chat
|
||||
|
||||
3. Debugging your agent
|
||||
https://go-micro.dev/docs/guides/debugging-agents.html
|
||||
Inspect agent runs and memory with:
|
||||
micro inspect agent
|
||||
micro runs <agent>
|
||||
|
||||
4. 0→hero Reference
|
||||
https://go-micro.dev/docs/guides/zero-to-hero.html
|
||||
Walk the scaffold → run → chat → inspect → deploy dry-run lifecycle.`
|
||||
|
||||
func genProtoHandler(c *cli.Context) error {
|
||||
cmd := exec.Command("find", ".", "-name", "*.proto", "-exec", "protoc", "--proto_path=.", "--micro_out=.", "--go_out=.", `{}`, `;`)
|
||||
cmd.Stdout = os.Stdout
|
||||
@@ -96,6 +120,17 @@ func init() {
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docs",
|
||||
Usage: "Show the first-agent and 0→hero documentation path",
|
||||
Description: `Print the maintained adoption on-ramp for new Go Micro developers:
|
||||
the no-secret first-agent transcript, Your First Agent, debugging guide, and
|
||||
0→hero lifecycle reference.`,
|
||||
Action: func(ctx *cli.Context) error {
|
||||
fmt.Fprintln(ctx.App.Writer, docsWayfinding)
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "call",
|
||||
Usage: "Call a service",
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
microcmd "go-micro.dev/v6/cmd"
|
||||
)
|
||||
|
||||
func TestFirstAgentWalkthroughCLIBoundaries(t *testing.T) {
|
||||
commands := map[string]bool{}
|
||||
subcommands := map[string]map[string]bool{}
|
||||
for _, command := range microcmd.DefaultCmd.App().Commands {
|
||||
commands[command.Name] = true
|
||||
for _, subcommand := range command.Subcommands {
|
||||
if subcommands[command.Name] == nil {
|
||||
subcommands[command.Name] = map[string]bool{}
|
||||
}
|
||||
subcommands[command.Name][subcommand.Name] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, want := range []string{"new", "run", "chat", "inspect", "agent", "docs"} {
|
||||
if !commands[want] {
|
||||
t.Fatalf("first-agent walkthrough missing %q command", want)
|
||||
}
|
||||
}
|
||||
if !subcommands["agent"]["preflight"] {
|
||||
t.Fatal("first-agent walkthrough missing preflight boundary: agent preflight")
|
||||
}
|
||||
if !subcommands["inspect"]["agent"] {
|
||||
t.Fatal("first-agent walkthrough missing inspect boundary: inspect agent")
|
||||
}
|
||||
|
||||
chat := commandByName(t, "chat")
|
||||
if !strings.Contains(chat.Description, "services") || !strings.Contains(chat.Description, "agent") {
|
||||
t.Fatalf("micro chat should describe the service-to-agent walkthrough boundary; description was %q", chat.Description)
|
||||
}
|
||||
|
||||
docs := commandByName(t, "docs")
|
||||
if !strings.Contains(docs.Usage, "first-agent") || !strings.Contains(docs.Usage, "0→hero") {
|
||||
t.Fatalf("micro docs should advertise the first-agent and 0→hero docs path; usage was %q", docs.Usage)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
app := cli.NewApp()
|
||||
app.Writer = &out
|
||||
if err := docs.Action(cli.NewContext(app, nil, nil)); err != nil {
|
||||
t.Fatalf("micro docs failed: %v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"no-secret-first-agent.html",
|
||||
"your-first-agent.html",
|
||||
"debugging-agents.html",
|
||||
"zero-to-hero.html",
|
||||
"micro agent preflight",
|
||||
"micro run",
|
||||
"micro chat",
|
||||
"micro inspect agent",
|
||||
} {
|
||||
if !strings.Contains(out.String(), want) {
|
||||
t.Fatalf("micro docs output missing %q:\n%s", want, out.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func commandByName(t *testing.T, name string) *cli.Command {
|
||||
t.Helper()
|
||||
for _, command := range microcmd.DefaultCmd.App().Commands {
|
||||
if command.Name == name {
|
||||
return command
|
||||
}
|
||||
}
|
||||
t.Fatalf("missing command %q", name)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
// Package loop implements the 'micro loop' command, which scaffolds and
|
||||
// verifies an autonomous improvement loop for a repository.
|
||||
//
|
||||
// The loop is a set of GitHub Actions workflows that dispatch a coding agent by
|
||||
// @mention on a fresh tracking issue each run. It has up to five roles:
|
||||
//
|
||||
// planner keeps a ranked queue in .github/loop/PRIORITIES.md
|
||||
// builder builds the top open item as a single-concern PR (auto-merged on green CI)
|
||||
// triage turns CI failures into scoped fix issues back into the queue
|
||||
// coherence keeps README/docs/CHANGELOG aligned with the North Star (opt-in)
|
||||
// release cuts the next patch tag when the branch has new commits (opt-in)
|
||||
//
|
||||
// The workflows are the MECHANISM; each dispatch role's instruction lives in an
|
||||
// editable .github/loop/prompts/<role>.md file — the POLICY. That split is what
|
||||
// lets any repo (including go-micro itself) customize behavior by editing prompt
|
||||
// files rather than forking the CLI. `micro loop init` writes it all; `micro
|
||||
// loop verify` checks the wiring.
|
||||
package loop
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
"go-micro.dev/v6/cmd"
|
||||
)
|
||||
|
||||
//go:embed templates/*
|
||||
var templatesFS embed.FS
|
||||
|
||||
// config is the substitution surface for the templates — the whole config-vs-core
|
||||
// boundary. The workflows and prompts are the reusable core; these are what a
|
||||
// given repo tunes.
|
||||
type config struct {
|
||||
// Shared.
|
||||
DefaultBranch string // base branch for the loop's PRs (e.g. main)
|
||||
AgentMention string // how the workflows summon the agent (e.g. @codex)
|
||||
TokenSecret string // repo secret holding the user PAT that drives dispatch
|
||||
CIWorkflow string // human-readable CI workflow name(s) triage watches
|
||||
CIWorkflowsYAML string // the same as a YAML array literal, e.g. ["Lint", "Run Tests"]
|
||||
|
||||
// Per-dispatch-role (set while rendering each one).
|
||||
Role string
|
||||
WorkflowName string
|
||||
IssueTitle string
|
||||
Group string
|
||||
Cron string
|
||||
|
||||
// Release role.
|
||||
TagPrefix string // tag prefix to match/bump, e.g. "v"
|
||||
ReleaseCron string
|
||||
}
|
||||
|
||||
// dispatchRole is a cron-driven role rendered from templates/dispatch.yml.tmpl.
|
||||
type dispatchRole struct {
|
||||
workflowName string
|
||||
issueTitle string
|
||||
group string
|
||||
cronFlag string
|
||||
defaultCron string
|
||||
}
|
||||
|
||||
var dispatchRoles = map[string]dispatchRole{
|
||||
"planner": {"Loop: Planner", "Loop: planning review", "loop-planner", "planner-cron", "0 * * * *"},
|
||||
"builder": {"Loop: Builder", "Loop: build increment", "loop-builder", "builder-cron", "30 * * * *"},
|
||||
"coherence": {"Loop: Coherence", "Loop: coherence review", "loop-coherence", "coherence-cron", "0 7 * * *"},
|
||||
}
|
||||
|
||||
// allRoles is the full set, in a stable order, for --roles=all and help text.
|
||||
var allRoles = []string{"planner", "builder", "triage", "coherence", "release"}
|
||||
|
||||
const (
|
||||
promptDir = ".github/loop/prompts"
|
||||
loopDir = ".github/loop"
|
||||
wfDir = ".github/workflows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmd.Register(&cli.Command{
|
||||
Name: "loop",
|
||||
Usage: "Scaffold an autonomous improvement loop for a repository",
|
||||
Description: `Set up a self-improving loop for a repo: GitHub Actions workflows that
|
||||
dispatch a coding agent to plan, build, triage, and (optionally) keep docs
|
||||
coherent and cut releases — gated by CI.
|
||||
|
||||
Roles (choose with --roles, default: planner,builder,triage):
|
||||
planner keeps a ranked queue in .github/loop/PRIORITIES.md
|
||||
builder builds the top open item as a single-concern PR (auto-merged on green CI)
|
||||
triage turns CI failures into scoped fix issues back into the queue
|
||||
coherence keeps README/docs/CHANGELOG aligned with the North Star
|
||||
release cuts the next patch tag when the branch has new commits
|
||||
|
||||
Each dispatch role's instruction is an editable file in .github/loop/prompts/ —
|
||||
edit those to steer behavior. Direction lives in .github/loop/NORTH_STAR.md.
|
||||
|
||||
Examples:
|
||||
# Scaffold the default loop (planner, builder, triage)
|
||||
micro loop init
|
||||
|
||||
# The full loop, all five roles
|
||||
micro loop init --roles all
|
||||
|
||||
# Customize the agent, token secret, base branch, and CI workflow name
|
||||
micro loop init --agent @codex --token-secret LOOP_TOKEN \
|
||||
--branch main --ci-workflow CI
|
||||
|
||||
# Check that a repo is wired correctly
|
||||
micro loop verify`,
|
||||
Subcommands: []*cli.Command{
|
||||
{
|
||||
Name: "init",
|
||||
Usage: "Scaffold the loop workflows, prompts, and queue into a repo",
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{Name: "dir", Usage: "Target repo directory", Value: "."},
|
||||
&cli.StringFlag{Name: "roles", Usage: "Comma-separated roles, or 'all'", Value: "planner,builder,triage"},
|
||||
&cli.StringFlag{Name: "branch", Usage: "Base branch for the loop's PRs (auto-detected if empty)"},
|
||||
&cli.StringFlag{Name: "agent", Usage: "How the workflows summon the agent (an @mention)", Value: "@codex"},
|
||||
&cli.StringFlag{Name: "token-secret", Usage: "Repo secret holding the user PAT that drives dispatch", Value: "LOOP_TOKEN"},
|
||||
&cli.StringFlag{Name: "ci-workflow", Usage: "CI workflow name(s) triage watches for failures (comma-separated)", Value: "CI"},
|
||||
&cli.StringFlag{Name: "planner-cron", Usage: "Cron schedule for the planner", Value: "0 * * * *"},
|
||||
&cli.StringFlag{Name: "builder-cron", Usage: "Cron schedule for the builder", Value: "30 * * * *"},
|
||||
&cli.StringFlag{Name: "coherence-cron", Usage: "Cron schedule for the coherence role", Value: "0 7 * * *"},
|
||||
&cli.StringFlag{Name: "release-cron", Usage: "Cron schedule for the release role", Value: "0 23 * * *"},
|
||||
&cli.StringFlag{Name: "tag-prefix", Usage: "Tag prefix the release role matches and bumps", Value: "v"},
|
||||
&cli.BoolFlag{Name: "force", Usage: "Overwrite existing loop files"},
|
||||
},
|
||||
Action: runInit,
|
||||
},
|
||||
{
|
||||
Name: "verify",
|
||||
Usage: "Verify a repo is wired for the loop",
|
||||
Flags: []cli.Flag{&cli.StringFlag{Name: "dir", Usage: "Target repo directory", Value: "."}},
|
||||
Action: runVerify,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func runInit(c *cli.Context) error {
|
||||
dir := c.String("dir")
|
||||
roles, err := parseRoles(c.String("roles"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ciNames := splitCSV(c.String("ci-workflow"))
|
||||
cfg := config{
|
||||
DefaultBranch: c.String("branch"),
|
||||
AgentMention: strings.TrimSpace(c.String("agent")),
|
||||
TokenSecret: strings.TrimSpace(c.String("token-secret")),
|
||||
CIWorkflow: strings.Join(ciNames, ", "),
|
||||
CIWorkflowsYAML: yamlStringArray(ciNames),
|
||||
TagPrefix: c.String("tag-prefix"),
|
||||
ReleaseCron: c.String("release-cron"),
|
||||
}
|
||||
if cfg.DefaultBranch == "" {
|
||||
cfg.DefaultBranch = detectDefaultBranch(dir)
|
||||
}
|
||||
if !strings.HasPrefix(cfg.AgentMention, "@") {
|
||||
cfg.AgentMention = "@" + cfg.AgentMention
|
||||
}
|
||||
|
||||
crons := map[string]string{
|
||||
"planner": c.String("planner-cron"),
|
||||
"builder": c.String("builder-cron"),
|
||||
"coherence": c.String("coherence-cron"),
|
||||
}
|
||||
|
||||
if err := scaffold(dir, cfg, roles, crons, c.Bool("force")); err != nil {
|
||||
return err
|
||||
}
|
||||
printNextSteps(cfg, roles)
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseRoles resolves the --roles flag into a validated, stable-ordered set.
|
||||
func parseRoles(spec string) ([]string, error) {
|
||||
if strings.TrimSpace(spec) == "all" {
|
||||
return append([]string(nil), allRoles...), nil
|
||||
}
|
||||
want := map[string]bool{}
|
||||
for _, r := range strings.Split(spec, ",") {
|
||||
r = strings.TrimSpace(r)
|
||||
if r == "" {
|
||||
continue
|
||||
}
|
||||
if !isRole(r) {
|
||||
return nil, fmt.Errorf("unknown role %q (valid: %s, or 'all')", r, strings.Join(allRoles, ", "))
|
||||
}
|
||||
want[r] = true
|
||||
}
|
||||
if len(want) == 0 {
|
||||
return nil, fmt.Errorf("no roles selected")
|
||||
}
|
||||
var out []string
|
||||
for _, r := range allRoles { // preserve canonical order
|
||||
if want[r] {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// splitCSV splits a comma-separated flag into trimmed, non-empty values.
|
||||
func splitCSV(s string) []string {
|
||||
var out []string
|
||||
for _, v := range strings.Split(s, ",") {
|
||||
if v = strings.TrimSpace(v); v != "" {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
out = []string{"CI"}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// yamlStringArray renders names as a YAML/JSON flow array, e.g. ["Lint", "Run Tests"].
|
||||
// Names are known workflow display names (no embedded quotes), so a simple quote is safe.
|
||||
func yamlStringArray(names []string) string {
|
||||
quoted := make([]string, len(names))
|
||||
for i, n := range names {
|
||||
quoted[i] = fmt.Sprintf("%q", n)
|
||||
}
|
||||
return "[" + strings.Join(quoted, ", ") + "]"
|
||||
}
|
||||
|
||||
func isRole(r string) bool {
|
||||
for _, x := range allRoles {
|
||||
if x == r {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// scaffold renders the selected roles into dir. The split is deliberate:
|
||||
// - Workflows are the MECHANISM — regenerated, and overwritten with --force.
|
||||
// - Prompts, NORTH_STAR, and PRIORITIES are the POLICY — written once and
|
||||
// never clobbered, even with --force, so re-running init to refresh the
|
||||
// workflow mechanics can't wipe curated instructions, direction, or queue.
|
||||
func scaffold(dir string, cfg config, roles []string, crons map[string]string, force bool) error {
|
||||
for _, role := range roles {
|
||||
switch role {
|
||||
case "triage":
|
||||
if err := renderTo(dir, "templates/loop-triage.yml.tmpl", filepath.Join(wfDir, "loop-triage.yml"), cfg, force); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := renderKeep(dir, "templates/prompts/triage.md.tmpl", filepath.Join(promptDir, "triage.md"), cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
case "release":
|
||||
if err := renderTo(dir, "templates/loop-release.yml.tmpl", filepath.Join(wfDir, "loop-release.yml"), cfg, force); err != nil {
|
||||
return err
|
||||
}
|
||||
default: // dispatch roles
|
||||
d := dispatchRoles[role]
|
||||
rc := cfg
|
||||
rc.Role = role
|
||||
rc.WorkflowName = d.workflowName
|
||||
rc.IssueTitle = d.issueTitle
|
||||
rc.Group = d.group
|
||||
rc.Cron = crons[role]
|
||||
if rc.Cron == "" {
|
||||
rc.Cron = d.defaultCron
|
||||
}
|
||||
if err := renderTo(dir, "templates/dispatch.yml.tmpl", filepath.Join(wfDir, "loop-"+role+".yml"), rc, force); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := renderKeep(dir, "templates/prompts/"+role+".md.tmpl", filepath.Join(promptDir, role+".md"), cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Direction + queue: policy, written once, never clobbered.
|
||||
if err := renderKeep(dir, "templates/NORTH_STAR.md", filepath.Join(loopDir, "NORTH_STAR.md"), cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
return renderKeep(dir, "templates/PRIORITIES.md", filepath.Join(loopDir, "PRIORITIES.md"), cfg)
|
||||
}
|
||||
|
||||
// renderTo renders a template with cfg and writes it to dir/dest (honoring force).
|
||||
func renderTo(dir, tmplName, dest string, cfg config, force bool) error {
|
||||
rendered, err := render(tmplName, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFile(filepath.Join(dir, dest), rendered, force); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf(" wrote %s\n", dest)
|
||||
return nil
|
||||
}
|
||||
|
||||
// renderKeep writes dir/dest only if it does not already exist — used for
|
||||
// policy files (prompts, North Star, queue) so re-running init never clobbers
|
||||
// customizations, regardless of --force.
|
||||
func renderKeep(dir, tmplName, dest string, cfg config) error {
|
||||
full := filepath.Join(dir, dest)
|
||||
if fileExists(full) {
|
||||
fmt.Printf(" kept %s (already exists)\n", dest)
|
||||
return nil
|
||||
}
|
||||
rendered, err := render(tmplName, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFile(full, rendered, true); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf(" wrote %s\n", dest)
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyState reports what's wrong with dir's loop setup: warnings are
|
||||
// non-fatal, missing are required files that aren't present.
|
||||
func verifyState(dir string) (warnings, missing []string) {
|
||||
// A loop needs direction, a queue, and at least one role workflow.
|
||||
for _, dest := range []string{filepath.Join(loopDir, "NORTH_STAR.md"), filepath.Join(loopDir, "PRIORITIES.md")} {
|
||||
if !fileExists(filepath.Join(dir, dest)) {
|
||||
missing = append(missing, dest)
|
||||
}
|
||||
}
|
||||
|
||||
present := presentLoopWorkflows(dir)
|
||||
if len(present) == 0 {
|
||||
missing = append(missing, wfDir+"/loop-*.yml (no role workflows found)")
|
||||
}
|
||||
|
||||
// Every dispatch/triage role workflow needs its prompt file. (release has none.)
|
||||
for _, role := range present {
|
||||
if role == "release" {
|
||||
continue
|
||||
}
|
||||
prompt := filepath.Join(promptDir, role+".md")
|
||||
if !fileExists(filepath.Join(dir, prompt)) {
|
||||
missing = append(missing, prompt+" (prompt for the loop-"+role+" workflow)")
|
||||
}
|
||||
}
|
||||
|
||||
// The loop is only as good as its gate.
|
||||
if !hasCIWorkflow(dir) {
|
||||
warnings = append(warnings, "no non-loop workflow found in "+wfDir+" — the loop needs a CI gate (build/test/lint) to merge safely")
|
||||
}
|
||||
return warnings, missing
|
||||
}
|
||||
|
||||
// presentLoopWorkflows returns the role names for which a loop-<role>.yml exists.
|
||||
func presentLoopWorkflows(dir string) []string {
|
||||
entries, err := os.ReadDir(filepath.Join(dir, wfDir))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, e := range entries {
|
||||
name := e.Name()
|
||||
if !strings.HasPrefix(name, "loop-") {
|
||||
continue
|
||||
}
|
||||
role := strings.TrimSuffix(strings.TrimSuffix(strings.TrimPrefix(name, "loop-"), ".yml"), ".yaml")
|
||||
out = append(out, role)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func runVerify(c *cli.Context) error {
|
||||
dir := c.String("dir")
|
||||
warnings, missing := verifyState(dir)
|
||||
|
||||
for _, m := range missing {
|
||||
fmt.Printf(" MISSING %s\n", m)
|
||||
}
|
||||
for _, w := range warnings {
|
||||
fmt.Printf(" WARN %s\n", w)
|
||||
}
|
||||
|
||||
if len(missing) > 0 {
|
||||
return fmt.Errorf("loop is not fully scaffolded (%d item(s) missing) — run `micro loop init`", len(missing))
|
||||
}
|
||||
|
||||
fmt.Printf(" OK loop is wired: %s\n", strings.Join(presentLoopWorkflows(dir), ", "))
|
||||
fmt.Println()
|
||||
fmt.Println("Reminders the CLI can't check:")
|
||||
fmt.Println(" • The token secret must be set in the repo (Settings → Secrets).")
|
||||
fmt.Println(" • Branch protection must require the CI checks with 0 approvals,")
|
||||
fmt.Println(" so the builder's auto-merge can land PRs on green CI.")
|
||||
if len(warnings) > 0 {
|
||||
return fmt.Errorf("%d warning(s) — see above", len(warnings))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func render(tmplName string, cfg config) ([]byte, error) {
|
||||
b, err := templatesFS.ReadFile(tmplName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Custom delimiters so GitHub Actions' own ${{ }} expressions pass through
|
||||
// untouched — only << >> placeholders are substituted.
|
||||
t, err := template.New(filepath.Base(tmplName)).Delims("<<", ">>").Option("missingkey=error").Parse(string(b))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse %s: %w", tmplName, err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := t.Execute(&buf, cfg); err != nil {
|
||||
return nil, fmt.Errorf("render %s: %w", tmplName, err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func writeFile(path string, content []byte, force bool) error {
|
||||
if fileExists(path) && !force {
|
||||
return fmt.Errorf("%s already exists (use --force to overwrite)", path)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, content, 0o644)
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
// hasCIWorkflow reports whether .github/workflows holds any workflow that is
|
||||
// not one of the loop's own (i.e. a plausible CI gate).
|
||||
func hasCIWorkflow(dir string) bool {
|
||||
entries, err := os.ReadDir(filepath.Join(dir, wfDir))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
if strings.HasPrefix(name, "loop-") {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(name, ".yml") || strings.HasSuffix(name, ".yaml") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// detectDefaultBranch best-effort resolves the repo's default branch, falling
|
||||
// back to "main".
|
||||
func detectDefaultBranch(dir string) string {
|
||||
out, err := exec.Command("git", "-C", dir, "symbolic-ref", "--short", "refs/remotes/origin/HEAD").Output()
|
||||
if err == nil {
|
||||
ref := strings.TrimSpace(string(out))
|
||||
if i := strings.LastIndex(ref, "/"); i >= 0 {
|
||||
ref = ref[i+1:]
|
||||
}
|
||||
if ref != "" {
|
||||
return ref
|
||||
}
|
||||
}
|
||||
return "main"
|
||||
}
|
||||
|
||||
func printNextSteps(cfg config, roles []string) {
|
||||
fmt.Printf(`
|
||||
Loop scaffolded (%s). Next steps (the CLI can't do these for you):
|
||||
|
||||
1. Edit .github/loop/NORTH_STAR.md — the direction the loop aligns to.
|
||||
Seed .github/loop/PRIORITIES.md with a few real items.
|
||||
Tune the per-role instructions in .github/loop/prompts/ if you like.
|
||||
|
||||
2. Add a repo secret named %s: a fine-grained user PAT (contents + pull
|
||||
requests + issues write) for an account the agent (%s) responds to.
|
||||
The workflows no-op until this secret exists.
|
||||
|
||||
3. Ensure a CI workflow named %q exists and that branch protection on %q
|
||||
requires its checks with 0 approving reviews — that green-CI gate is
|
||||
what lets the builder auto-merge safely.
|
||||
|
||||
4. Commit these files, then trigger a run from the Actions tab.
|
||||
|
||||
Verify anytime with: micro loop verify
|
||||
`, strings.Join(roles, ", "), cfg.TokenSecret, cfg.AgentMention, cfg.CIWorkflow, cfg.DefaultBranch)
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testCfg = config{
|
||||
DefaultBranch: "main",
|
||||
AgentMention: "@codex",
|
||||
TokenSecret: "LOOP_TOKEN",
|
||||
CIWorkflow: "CI",
|
||||
CIWorkflowsYAML: `["CI"]`,
|
||||
TagPrefix: "v",
|
||||
ReleaseCron: "0 23 * * *",
|
||||
}
|
||||
|
||||
var testCrons = map[string]string{"planner": "0 * * * *", "builder": "30 * * * *", "coherence": "0 7 * * *"}
|
||||
|
||||
// renderable is every template a full scaffold touches, with the per-role config
|
||||
// applied the same way scaffold does.
|
||||
func renderCases() map[string]config {
|
||||
cases := map[string]config{
|
||||
"templates/loop-triage.yml.tmpl": testCfg,
|
||||
"templates/loop-release.yml.tmpl": testCfg,
|
||||
"templates/prompts/triage.md.tmpl": testCfg,
|
||||
"templates/prompts/planner.md.tmpl": testCfg,
|
||||
"templates/prompts/builder.md.tmpl": testCfg,
|
||||
"templates/prompts/coherence.md.tmpl": testCfg,
|
||||
}
|
||||
for role, d := range dispatchRoles {
|
||||
rc := testCfg
|
||||
rc.Role, rc.WorkflowName, rc.IssueTitle, rc.Group, rc.Cron = role, d.workflowName, d.issueTitle, d.group, d.defaultCron
|
||||
cases["dispatch:"+role] = rc
|
||||
}
|
||||
return cases
|
||||
}
|
||||
|
||||
func TestRenderIsPlaceholderFreeAndKeepsGHAExpressions(t *testing.T) {
|
||||
for name, cfg := range renderCases() {
|
||||
tmplName := name
|
||||
if strings.HasPrefix(name, "dispatch:") {
|
||||
tmplName = "templates/dispatch.yml.tmpl"
|
||||
}
|
||||
rendered, err := render(tmplName, cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("render %s: %v", name, err)
|
||||
}
|
||||
s := string(rendered)
|
||||
|
||||
// No unresolved substitution delimiters remain in any template.
|
||||
if strings.Contains(s, "<<") || strings.Contains(s, ">>") {
|
||||
t.Errorf("%s still contains << >> placeholders", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseBranchSubstitutedIntoPrompts(t *testing.T) {
|
||||
// The base branch appears in the PR-opening instructions of these prompts.
|
||||
for _, p := range []string{"planner", "builder", "coherence"} {
|
||||
s := mustRender(t, "templates/prompts/"+p+".md.tmpl", testCfg)
|
||||
if !strings.Contains(s, "--base main") {
|
||||
t.Errorf("%s prompt missing substituted base branch", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkflowTemplatesPreserveGHAAndAreStructural(t *testing.T) {
|
||||
// Only the workflow YAML templates (not the markdown prompts).
|
||||
wf := map[string]config{
|
||||
"templates/loop-triage.yml.tmpl": testCfg,
|
||||
"templates/loop-release.yml.tmpl": testCfg,
|
||||
}
|
||||
for role, d := range dispatchRoles {
|
||||
rc := testCfg
|
||||
rc.Role, rc.WorkflowName, rc.IssueTitle, rc.Group, rc.Cron = role, d.workflowName, d.issueTitle, d.group, d.defaultCron
|
||||
wf["dispatch:"+role] = rc
|
||||
}
|
||||
for name, cfg := range wf {
|
||||
tmplName := name
|
||||
if strings.HasPrefix(name, "dispatch:") {
|
||||
tmplName = "templates/dispatch.yml.tmpl"
|
||||
}
|
||||
s := mustRender(t, tmplName, cfg)
|
||||
if !strings.Contains(s, "${{ secrets.LOOP_TOKEN") {
|
||||
t.Errorf("%s lost its ${{ secrets.LOOP_TOKEN }} expression", name)
|
||||
}
|
||||
for _, key := range []string{"name:", "on:", "jobs:"} {
|
||||
if !strings.Contains(s, key) {
|
||||
t.Errorf("%s missing top-level %q", name, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchWorkflowsStripPromptComments(t *testing.T) {
|
||||
// The posted body must not include the prompt's editorial <!-- --> header;
|
||||
// the workflow strips it. Guard the sed directive in both dispatch paths.
|
||||
rc := testCfg
|
||||
d := dispatchRoles["planner"]
|
||||
rc.Role, rc.WorkflowName, rc.IssueTitle, rc.Group, rc.Cron = "planner", d.workflowName, d.issueTitle, d.group, d.defaultCron
|
||||
for _, tc := range []struct {
|
||||
name, tmpl string
|
||||
cfg config
|
||||
}{
|
||||
{"dispatch", "templates/dispatch.yml.tmpl", rc},
|
||||
{"triage", "templates/loop-triage.yml.tmpl", testCfg},
|
||||
} {
|
||||
s := mustRender(t, tc.tmpl, tc.cfg)
|
||||
if !strings.Contains(s, `/<!--/,/-->/d`) {
|
||||
t.Errorf("%s workflow does not strip prompt HTML comments before posting", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPromptsLeaveRuntimeTokensLiteral(t *testing.T) {
|
||||
// __ISSUE__ must survive render (the workflow substitutes it at runtime).
|
||||
for _, p := range []string{"planner", "builder", "coherence", "triage"} {
|
||||
s := mustRender(t, "templates/prompts/"+p+".md.tmpl", testCfg)
|
||||
if !strings.Contains(s, "__ISSUE__") {
|
||||
t.Errorf("%s prompt lost its __ISSUE__ runtime token", p)
|
||||
}
|
||||
}
|
||||
// triage additionally uses __RUNURL__.
|
||||
if s := mustRender(t, "templates/prompts/triage.md.tmpl", testCfg); !strings.Contains(s, "__RUNURL__") {
|
||||
t.Error("triage prompt lost its __RUNURL__ runtime token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScaffoldAllRolesWritesEverything(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
mustWrite(t, filepath.Join(dir, wfDir, "ci.yml"), "name: CI\n")
|
||||
|
||||
roles := []string{"planner", "builder", "triage", "coherence", "release"}
|
||||
if err := scaffold(dir, testCfg, roles, testCrons, false); err != nil {
|
||||
t.Fatalf("scaffold: %v", err)
|
||||
}
|
||||
|
||||
wantWorkflows := []string{"loop-planner.yml", "loop-builder.yml", "loop-triage.yml", "loop-coherence.yml", "loop-release.yml"}
|
||||
for _, w := range wantWorkflows {
|
||||
if !fileExists(filepath.Join(dir, wfDir, w)) {
|
||||
t.Errorf("expected %s", w)
|
||||
}
|
||||
}
|
||||
// Dispatch + triage roles have prompts; release does not.
|
||||
for _, p := range []string{"planner.md", "builder.md", "triage.md", "coherence.md"} {
|
||||
if !fileExists(filepath.Join(dir, promptDir, p)) {
|
||||
t.Errorf("expected prompt %s", p)
|
||||
}
|
||||
}
|
||||
if fileExists(filepath.Join(dir, promptDir, "release.md")) {
|
||||
t.Error("release should not have a prompt")
|
||||
}
|
||||
if _, missing := verifyState(dir); len(missing) != 0 {
|
||||
t.Errorf("verify reported missing after full scaffold: %v", missing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScaffoldDefaultRolesOmitsOptional(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := scaffold(dir, testCfg, []string{"planner", "builder", "triage"}, testCrons, false); err != nil {
|
||||
t.Fatalf("scaffold: %v", err)
|
||||
}
|
||||
if fileExists(filepath.Join(dir, wfDir, "loop-coherence.yml")) {
|
||||
t.Error("coherence should not be written by default")
|
||||
}
|
||||
if fileExists(filepath.Join(dir, wfDir, "loop-release.yml")) {
|
||||
t.Error("release should not be written by default")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReinitForceKeepsPromptsRefreshesWorkflows(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
roles := []string{"planner", "builder", "triage"}
|
||||
if err := scaffold(dir, testCfg, roles, testCrons, false); err != nil {
|
||||
t.Fatalf("scaffold: %v", err)
|
||||
}
|
||||
|
||||
// Customize a prompt and edit direction/queue, as a real user would.
|
||||
customPrompt := filepath.Join(dir, promptDir, "builder.md")
|
||||
mustWrite(t, customPrompt, "MY CUSTOM BUILDER POLICY")
|
||||
northStar := filepath.Join(dir, loopDir, "NORTH_STAR.md")
|
||||
mustWrite(t, northStar, "MY MISSION")
|
||||
|
||||
// Re-run with --force to refresh workflow mechanics.
|
||||
if err := scaffold(dir, testCfg, roles, testCrons, true); err != nil {
|
||||
t.Fatalf("re-scaffold --force: %v", err)
|
||||
}
|
||||
|
||||
// Policy (prompt, North Star) must survive --force untouched.
|
||||
if b, _ := os.ReadFile(customPrompt); string(b) != "MY CUSTOM BUILDER POLICY" {
|
||||
t.Errorf("--force clobbered a customized prompt: %q", b)
|
||||
}
|
||||
if b, _ := os.ReadFile(northStar); string(b) != "MY MISSION" {
|
||||
t.Errorf("--force clobbered the North Star: %q", b)
|
||||
}
|
||||
// Mechanism (workflow) must be regenerated (present and non-empty).
|
||||
if b, _ := os.ReadFile(filepath.Join(dir, wfDir, "loop-builder.yml")); !strings.Contains(string(b), "Loop: Builder") {
|
||||
t.Error("--force did not refresh the workflow")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCIWorkflowListRendersAsYAMLArray(t *testing.T) {
|
||||
if got := yamlStringArray([]string{"Harness (E2E)", "Lint", "Run Tests"}); got != `["Harness (E2E)", "Lint", "Run Tests"]` {
|
||||
t.Errorf("yamlStringArray = %q", got)
|
||||
}
|
||||
if got := splitCSV("Harness (E2E), Lint ,Run Tests"); strings.Join(got, "|") != "Harness (E2E)|Lint|Run Tests" {
|
||||
t.Errorf("splitCSV = %v", got)
|
||||
}
|
||||
if got := splitCSV(" "); strings.Join(got, "|") != "CI" {
|
||||
t.Errorf("splitCSV empty should default to CI, got %v", got)
|
||||
}
|
||||
// The triage workflow must embed the array so workflow_run watches all of them.
|
||||
cfg := testCfg
|
||||
cfg.CIWorkflowsYAML = `["Harness (E2E)", "Lint", "Run Tests"]`
|
||||
s := mustRender(t, "templates/loop-triage.yml.tmpl", cfg)
|
||||
if !strings.Contains(s, `workflows: ["Harness (E2E)", "Lint", "Run Tests"]`) {
|
||||
t.Errorf("triage workflow does not watch the CI workflow list:\n%s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRoles(t *testing.T) {
|
||||
if got, err := parseRoles("all"); err != nil || len(got) != len(allRoles) {
|
||||
t.Errorf("all => %v, %v", got, err)
|
||||
}
|
||||
// Canonical order preserved regardless of input order.
|
||||
got, err := parseRoles("release,planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Join(got, ",") != "planner,release" {
|
||||
t.Errorf("expected canonical order planner,release; got %v", got)
|
||||
}
|
||||
if _, err := parseRoles("bogus"); err == nil {
|
||||
t.Error("expected error for unknown role")
|
||||
}
|
||||
if _, err := parseRoles(""); err == nil {
|
||||
t.Error("expected error for empty roles")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyMissingPromptFails(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := scaffold(dir, testCfg, []string{"planner", "builder", "triage"}, testCrons, false); err != nil {
|
||||
t.Fatalf("scaffold: %v", err)
|
||||
}
|
||||
// Delete a prompt → verify must flag it.
|
||||
if err := os.Remove(filepath.Join(dir, promptDir, "builder.md")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, missing := verifyState(dir)
|
||||
found := false
|
||||
for _, m := range missing {
|
||||
if strings.Contains(m, "builder.md") {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("expected verify to flag the missing builder prompt; got %v", missing)
|
||||
}
|
||||
}
|
||||
|
||||
func mustRender(t *testing.T, tmplName string, cfg config) string {
|
||||
t.Helper()
|
||||
b, err := render(tmplName, cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("render %s: %v", tmplName, err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func mustWrite(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# North Star
|
||||
|
||||
> **Edit this file.** It is the single source of direction the loop aligns every
|
||||
> increment to. The planner ranks work against it; the builder builds toward it.
|
||||
> Be concrete — vague direction produces vague increments.
|
||||
|
||||
## Mission
|
||||
|
||||
<One or two sentences: the problem this repository solves and who it's for.>
|
||||
|
||||
## Right now
|
||||
|
||||
<The current priority — what "better" means this month. The planner weights the
|
||||
queue toward this.>
|
||||
|
||||
## Guardrails
|
||||
|
||||
- One concern per PR; small and reversible.
|
||||
- The gate is green CI, not a human review — keep the test/lint suite strong,
|
||||
because the loop is only as good as its evaluator.
|
||||
- **Off-limits without a human** (surface as notes, never auto-merge): breaking
|
||||
public API changes, brand/positioning/marketing copy, new dependencies,
|
||||
architectural rewrites, product-default changes with broad behavioral impact.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Priorities
|
||||
|
||||
A single ranked queue, highest-value first. Each item links a scoped issue the
|
||||
loop can build and CI can verify. The **planner** keeps this current; the
|
||||
**builder** takes the top item whose issue is still open.
|
||||
|
||||
<!--
|
||||
Seed this with a few real items to give the loop a running start, e.g.:
|
||||
|
||||
1. Add retry with backoff to the HTTP client — #123
|
||||
2. Document the config file format — #124
|
||||
3. Fix flaky timeout in the cache tests — #125
|
||||
|
||||
The planner will re-rank, drop completed items, and file issues for new gaps.
|
||||
Reorder or edit this file at any time to redirect the loop.
|
||||
-->
|
||||
@@ -0,0 +1,60 @@
|
||||
name: "<< .WorkflowName >>"
|
||||
|
||||
# Generated by `micro loop init`. A dispatch role of the autonomous loop: on a
|
||||
# cadence it opens a fresh tracking issue and posts the instruction in
|
||||
# .github/loop/prompts/<< .Role >>.md to the agent (<< .AgentMention >>).
|
||||
#
|
||||
# The workflow is the MECHANISM; that prompt file is the editable POLICY —
|
||||
# change what this role does by editing the prompt, not this YAML. A FRESH
|
||||
# issue per run is deliberate: agents derive the PR branch name from the
|
||||
# triggering issue, so reusing one tracker collapses every run onto one branch.
|
||||
#
|
||||
# Gated on << .TokenSecret >>: the agent ignores @mentions from the
|
||||
# github-actions bot, so dispatch posts as a real user (a PAT). No token → no-op.
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "<< .Cron >>"
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: << .Group >>
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4 # needed to read the prompt file
|
||||
- name: Dispatch << .Role >>
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.<< .TokenSecret >> || github.token }}
|
||||
HAS_TOKEN: ${{ secrets.<< .TokenSecret >> != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [ "$HAS_TOKEN" != "true" ]; then
|
||||
echo "<< .TokenSecret >> is not set — skipping (the agent ignores bot @mentions)."
|
||||
exit 0
|
||||
fi
|
||||
PROMPT=".github/loop/prompts/<< .Role >>.md"
|
||||
if [ ! -f "$PROMPT" ]; then
|
||||
echo "missing $PROMPT — run 'micro loop init'." >&2
|
||||
exit 1
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "<< .IssueTitle >> #$RUN_NUMBER" \
|
||||
--body "Autonomous << .Role >> pass. Direction: .github/loop/NORTH_STAR.md; queue: .github/loop/PRIORITIES.md.")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching << .Role >>."
|
||||
# The prompt file is the policy; strip its editorial <!-- --> header and
|
||||
# substitute the tracking issue number (__ISSUE__) at runtime.
|
||||
{
|
||||
echo "<< .AgentMention >>"
|
||||
echo
|
||||
sed -e '/<!--/,/-->/d' -e "s/__ISSUE__/$ISSUE_NUM/g" "$PROMPT"
|
||||
} > "$RUNNER_TEMP/loop-body.md"
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/loop-body.md"
|
||||
@@ -0,0 +1,76 @@
|
||||
name: "Loop: Release"
|
||||
|
||||
# Generated by `micro loop init`. Cuts the next PATCH tag
|
||||
# (<< .TagPrefix >>MAJOR.MINOR.PATCH+1) when the default branch has new commits
|
||||
# since the latest such tag, and pushes it with a PAT (<< .TokenSecret >>) so any
|
||||
# tag-triggered release workflow fires. Minor/major bumps stay with a human.
|
||||
#
|
||||
# The tag MUST be pushed with a PAT, not the default GITHUB_TOKEN: a tag pushed
|
||||
# by GITHUB_TOKEN does not trigger other workflows (Actions blocks that recursion).
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
schedule:
|
||||
- cron: "<< .ReleaseCron >>"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: loop-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # need full history + all tags
|
||||
# Do NOT persist the default GITHUB_TOKEN as a git credential: it would
|
||||
# be sent on the PAT push below and override it, so the tag push would
|
||||
# authenticate as github-actions[bot] and 403. Letting the PAT in the
|
||||
# push URL be the only credential is the whole point.
|
||||
persist-credentials: false
|
||||
- name: Cut the next patch tag if there are new commits
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.<< .TokenSecret >> }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
if [ -z "$RELEASE_TOKEN" ]; then
|
||||
echo "<< .TokenSecret >> is not set — skipping."
|
||||
exit 0
|
||||
fi
|
||||
git fetch --tags --force
|
||||
|
||||
LATEST=$(git tag --list '<< .TagPrefix >>*.*.*' --sort=-v:refname | head -1)
|
||||
if [ -z "$LATEST" ]; then
|
||||
echo "no << .TagPrefix >>MAJOR.MINOR.PATCH tag found — aborting so nothing weird gets tagged."
|
||||
exit 1
|
||||
fi
|
||||
echo "latest tag: $LATEST"
|
||||
|
||||
COUNT=$(git rev-list --count "$LATEST"..HEAD)
|
||||
echo "commits since $LATEST: $COUNT"
|
||||
if [ "$COUNT" -eq 0 ]; then
|
||||
echo "no new commits since $LATEST — no release."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ver="${LATEST#<< .TagPrefix >>}"
|
||||
major="${ver%%.*}"
|
||||
rest="${ver#*.}"
|
||||
minor="${rest%%.*}"
|
||||
patch="${rest#*.}"
|
||||
case "$major.$minor.$patch" in
|
||||
[0-9]*.[0-9]*.[0-9]*) ;;
|
||||
*) echo "unexpected tag shape: $LATEST" ; exit 1 ;;
|
||||
esac
|
||||
NEXT="<< .TagPrefix >>${major}.${minor}.$((patch + 1))"
|
||||
echo "cutting: $NEXT ($COUNT commits since $LATEST)"
|
||||
|
||||
git config user.name "loop release bot"
|
||||
git config user.email "noreply@users.noreply.github.com"
|
||||
git tag -a "$NEXT" -m "Release $NEXT — automated patch ($COUNT commits since $LATEST)"
|
||||
git push "https://x-access-token:${RELEASE_TOKEN}@github.com/${REPO}.git" "$NEXT"
|
||||
echo "Pushed $NEXT."
|
||||
@@ -0,0 +1,57 @@
|
||||
name: "Loop: Triage"
|
||||
|
||||
# Generated by `micro loop init`. The feedback path of the evaluator: when a CI
|
||||
# workflow (<< .CIWorkflow >>) fails on a non-PR run, dispatch the agent
|
||||
# (<< .AgentMention >>) with the instruction in .github/loop/prompts/triage.md
|
||||
# to root-cause the failure and file scoped fix issues back into the queue — so
|
||||
# failures become fixes with no human in the middle. Gated on << .TokenSecret >>.
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: << .CIWorkflowsYAML >>
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: loop-triage
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
# Only real failures on branch pushes/schedules — not PR-run failures, which
|
||||
# the PR author already sees.
|
||||
if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event != 'pull_request' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4 # needed to read the prompt file
|
||||
- name: Dispatch triage
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.<< .TokenSecret >> || github.token }}
|
||||
HAS_TOKEN: ${{ secrets.<< .TokenSecret >> != '' }}
|
||||
REPO: ${{ github.repository }}
|
||||
RUN_ID: ${{ github.event.workflow_run.id }}
|
||||
RUN_URL: ${{ github.event.workflow_run.html_url }}
|
||||
WORKFLOW_NAME: ${{ github.event.workflow_run.name }}
|
||||
run: |
|
||||
if [ "$HAS_TOKEN" != "true" ]; then
|
||||
echo "<< .TokenSecret >> is not set — skipping."
|
||||
exit 0
|
||||
fi
|
||||
PROMPT=".github/loop/prompts/triage.md"
|
||||
if [ ! -f "$PROMPT" ]; then
|
||||
echo "missing $PROMPT — run 'micro loop init'." >&2
|
||||
exit 1
|
||||
fi
|
||||
ISSUE_URL=$(gh issue create --repo "$REPO" \
|
||||
--title "Loop: triage failed run $RUN_ID ($WORKFLOW_NAME)" \
|
||||
--body "The '$WORKFLOW_NAME' workflow failed on a non-PR run: $RUN_URL")
|
||||
ISSUE_NUM="${ISSUE_URL##*/}"
|
||||
echo "Opened issue #$ISSUE_NUM — dispatching triage."
|
||||
{
|
||||
echo "<< .AgentMention >>"
|
||||
echo
|
||||
sed -e '/<!--/,/-->/d' -e "s/__ISSUE__/$ISSUE_NUM/g" -e "s#__RUNURL__#$RUN_URL#g" "$PROMPT"
|
||||
} > "$RUNNER_TEMP/loop-body.md"
|
||||
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/loop-body.md"
|
||||
@@ -0,0 +1,14 @@
|
||||
<!--
|
||||
The BUILDER prompt — the editable policy for the builder role. The workflow
|
||||
prepends the agent @mention and substitutes __ISSUE__ before posting. Keep
|
||||
__ISSUE__ literal.
|
||||
-->
|
||||
Build one increment for this repository, aligned to `.github/loop/NORTH_STAR.md`.
|
||||
|
||||
PICK THE WORK: take the highest-ranked item in `.github/loop/PRIORITIES.md` whose linked issue is still OPEN — that is your task, and its issue is the one you close. If the queue is empty or every item's issue is closed, pick the single highest-value improvement yourself.
|
||||
|
||||
Implement it, then VERIFY the project builds, tests, and lints (use the commands documented in the README or the CI workflow).
|
||||
|
||||
Open the PR YOURSELF from the shell — do NOT use a make_pr tool (it may be a no-op stub): `git switch -c loop/increment-__ISSUE__`, `git push -u origin loop/increment-__ISSUE__`, `gh pr create --base << .DefaultBranch >> --title "<title>" --body "<body; include 'Closes #<the item's issue>' so it leaves the queue, and 'Closes #__ISSUE__' for this run's tracker>"`, then `gh pr merge --squash --auto --delete-branch` so it lands once CI is green.
|
||||
|
||||
One concern per PR. Stay out of breaking public API changes and brand/positioning copy — surface those as notes for a human instead.
|
||||
@@ -0,0 +1,14 @@
|
||||
<!--
|
||||
The COHERENCE (DevRel) prompt — the editable policy for the coherence role. The
|
||||
workflow prepends the agent @mention and substitutes __ISSUE__ before posting.
|
||||
Keep __ISSUE__ literal.
|
||||
-->
|
||||
Act as DevRel for this repository — keep the public story coherent and honest.
|
||||
|
||||
Audit the public surface — `README`, docs, and any website/blog — for coherence with `.github/loop/NORTH_STAR.md`: places that contradict each other, are stale, or describe behavior that has since changed (cross-check against the code and recently merged PRs). If the repo keeps a `CHANGELOG.md`, reconcile its `[Unreleased]` section against what actually merged.
|
||||
|
||||
SAFE factual-alignment and crispness fixes (and the CHANGELOG upkeep): open ONE PR and auto-merge it — `git switch -c loop/coherence-__ISSUE__`, `git push -u origin loop/coherence-__ISSUE__`, `gh pr create --base << .DefaultBranch >> --title "<title>" --body "<summary, Closes #__ISSUE__>"`, then `gh pr merge --squash --auto --delete-branch`.
|
||||
|
||||
Brand / positioning / marketing copy and any opinion blog posts are NOT auto-merge material — the public voice stays with a human. Describe them in a comment on this issue, or open a PR WITHOUT enabling auto-merge, and leave it for review.
|
||||
|
||||
Post a short findings report as a comment on this issue (#__ISSUE__): what's aligned, what drifted, what you fixed. Open PRs yourself from the shell with `gh`; do not use a make_pr tool.
|
||||
@@ -0,0 +1,15 @@
|
||||
<!--
|
||||
The PLANNER prompt. This file is the editable policy for the planner role —
|
||||
change what the planner does by editing this text. The workflow prepends the
|
||||
agent @mention and substitutes __ISSUE__ (this run's tracking issue) before
|
||||
posting it. Keep __ISSUE__ literal.
|
||||
-->
|
||||
Act as the planner for this repository.
|
||||
|
||||
(1) Read `.github/loop/NORTH_STAR.md` for direction, then scan recently merged PRs and open issues so the queue reflects reality — drop done items, don't re-queue work already in flight.
|
||||
|
||||
(2) Maintain a SINGLE ranked queue in `.github/loop/PRIORITIES.md`, highest-value first, each item linking a scoped, CI-verifiable issue (#N). For any prioritized gap that has no issue, file one: `gh issue create --title "<scoped task>" --body "<goal, scope, acceptance criteria>"`.
|
||||
|
||||
(3) If the ranking actually changed, open ONE PR for `PRIORITIES.md`: `git switch -c loop/planner-__ISSUE__`, `git push -u origin loop/planner-__ISSUE__`, `gh pr create --base << .DefaultBranch >> --title "<title>" --body "<summary, Closes #__ISSUE__>"`, then `gh pr merge --squash --auto --delete-branch`. If the queue is already accurate, just close this issue (`gh issue close __ISSUE__`).
|
||||
|
||||
Do NOT make breaking or architectural changes yourself — surface those as notes for a human. Open the PR yourself from the shell with `gh`; do not use a make_pr tool (it may be a no-op stub).
|
||||
@@ -0,0 +1,14 @@
|
||||
<!--
|
||||
The TRIAGE prompt — the editable policy for the triage role. The workflow
|
||||
prepends the agent @mention and substitutes __ISSUE__ (this tracking issue) and
|
||||
__RUNURL__ (the failed CI run) before posting. Keep both literal.
|
||||
-->
|
||||
Triage the failed CI run at __RUNURL__.
|
||||
|
||||
Read the logs and root-cause each distinct failure. DEDUPE against open issues — if a failure matches an existing issue, comment "recurred" there instead of filing a duplicate.
|
||||
|
||||
For each genuine, self-contained defect, file a scoped issue (`gh issue create --title "<scoped fix>" --body "<root cause, where, acceptance criteria>"`) so the planner/builder can pick it up and the next CI run verifies it.
|
||||
|
||||
IGNORE transient flakes — network blips, provider outages, timeouts with no code cause. Anything needing a breaking or architectural change: label it `needs-human` and describe it, rather than auto-filing it as a routine fix.
|
||||
|
||||
Close this issue (`gh issue close __ISSUE__`) when triage is done.
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
_ "go-micro.dev/v6/cmd/micro/cli/deploy"
|
||||
_ "go-micro.dev/v6/cmd/micro/flow"
|
||||
_ "go-micro.dev/v6/cmd/micro/inspect"
|
||||
_ "go-micro.dev/v6/cmd/micro/loop"
|
||||
_ "go-micro.dev/v6/cmd/micro/mcp"
|
||||
_ "go-micro.dev/v6/cmd/micro/resource"
|
||||
_ "go-micro.dev/v6/cmd/micro/run"
|
||||
|
||||
@@ -498,10 +498,13 @@ func printBanner(services []*serviceProcess, gw *server.Gateway, watching bool,
|
||||
fmt.Printf(" Dashboard \033[36mhttp://localhost%s\033[0m\n", gw.Addr())
|
||||
fmt.Printf(" API \033[36mhttp://localhost%s/api/{service}/{method}\033[0m\n", gw.Addr())
|
||||
fmt.Printf(" Agent \033[36mhttp://localhost%s/agent\033[0m\n", gw.Addr())
|
||||
// MCP tools are served on the gateway by default — every endpoint is an
|
||||
// AI-callable tool, so surface it rather than hiding it behind a flag.
|
||||
fmt.Printf(" MCP Tools \033[36mhttp://localhost%s/mcp/tools\033[0m\n", gw.Addr())
|
||||
fmt.Printf(" Health \033[36mhttp://localhost%s/health\033[0m\n", gw.Addr())
|
||||
if mcpAddr != "" {
|
||||
fmt.Printf(" MCP \033[36mhttp://localhost%s\033[0m\n", mcpAddr)
|
||||
fmt.Printf(" MCP Tools \033[36mhttp://localhost%s/mcp/tools\033[0m\n", mcpAddr)
|
||||
// Optional standalone MCP protocol server (e.g. for MCP clients).
|
||||
fmt.Printf(" MCP Server \033[36mhttp://localhost%s\033[0m (full MCP protocol)\n", mcpAddr)
|
||||
fmt.Printf(" WebSocket \033[36mws://localhost%s/mcp/ws\033[0m\n", mcpAddr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,4 +324,4 @@ Apache 2.0 - See [LICENSE](../../LICENSE) for details.
|
||||
## Support
|
||||
|
||||
- GitHub Discussions: https://github.com/micro/go-micro/discussions
|
||||
- Discord: https://discord.gg/WeMU5AGxD
|
||||
- Discord: https://discord.gg/G8Gk5j3uXr
|
||||
|
||||
@@ -102,4 +102,4 @@ pytest tests/integration/ -v
|
||||
## Questions?
|
||||
|
||||
- GitHub Discussions: https://github.com/micro/go-micro/discussions
|
||||
- Discord: https://discord.gg/WeMU5AGxD
|
||||
- Discord: https://discord.gg/G8Gk5j3uXr
|
||||
|
||||
@@ -370,4 +370,4 @@ Apache 2.0 - See [LICENSE](../../LICENSE) for details.
|
||||
## Support
|
||||
|
||||
- GitHub Discussions: https://github.com/micro/go-micro/discussions
|
||||
- Discord: https://discord.gg/WeMU5AGxD
|
||||
- Discord: https://discord.gg/G8Gk5j3uXr
|
||||
|
||||
+82
-31
@@ -1,14 +1,34 @@
|
||||
# Go Micro Examples
|
||||
|
||||
This directory contains runnable examples demonstrating various go-micro features and patterns.
|
||||
This directory contains runnable examples that take you through the Go Micro
|
||||
lifecycle: start with a service, expose it as agent-usable capability, then
|
||||
coordinate work with workflows.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Each example can be run with `go run .` from its directory.
|
||||
Each example can be run with `go run .` from its directory unless its README says
|
||||
otherwise. If you are new to the repo, follow the first-agent path below instead
|
||||
of reading the directories alphabetically.
|
||||
|
||||
## Examples
|
||||
## Recommended first-agent path
|
||||
|
||||
### [hello-world](./hello-world/)
|
||||
| Step | Start here | What you learn | Next step |
|
||||
|------|------------|----------------|-----------|
|
||||
| 1. First service | [`hello-world`](./hello-world/) | Create and register a basic RPC service, add a handler, call it with a client, and expose health checks. | Move to [`agent-demo`](./agent-demo/) to see services used by an agent. |
|
||||
| 2. First agent | [`agent-demo`](./agent-demo/) | Run a small project-management app with Projects, Tasks, and Team services plus an agent playground. | Compare with the maintained 0-to-hero path in [`support`](./support/). |
|
||||
| 3. First workflow | [`support`](./support/) | Follow typed services into an agent chat loop, an event-driven `intake` flow, and an approval gate in one runnable reference. | Deepen the workflow model with [`flow-durable`](./flow-durable/). |
|
||||
|
||||
For the shortest AI-tooling bridge, the MCP path is
|
||||
[`mcp/hello`](./mcp/hello/) → [`mcp/crud`](./mcp/crud/) →
|
||||
[`mcp/workflow`](./mcp/workflow/). For debugging and production hardening, keep
|
||||
[`agent-wrap-tool`](./agent-wrap-tool/), [`agent-durable`](./agent-durable/), and
|
||||
[`deployment`](./deployment/) nearby.
|
||||
|
||||
## Lifecycle map
|
||||
|
||||
### 1. Services — learn the runtime foundation
|
||||
|
||||
#### [hello-world](./hello-world/)
|
||||
Basic RPC service demonstrating core concepts:
|
||||
- Service creation and registration
|
||||
- Handler implementation
|
||||
@@ -21,7 +41,7 @@ cd hello-world
|
||||
go run .
|
||||
```
|
||||
|
||||
### [web-service](./web-service/)
|
||||
#### [web-service](./web-service/)
|
||||
HTTP web service with service discovery:
|
||||
- HTTP handlers
|
||||
- Service registration
|
||||
@@ -34,7 +54,7 @@ cd web-service
|
||||
go run .
|
||||
```
|
||||
|
||||
### [multi-service](./multi-service/)
|
||||
#### [multi-service](./multi-service/)
|
||||
Multiple services in a single binary — the modular monolith pattern:
|
||||
- Isolated server, client, store, and cache per service
|
||||
- Shared registry and broker for inter-service communication
|
||||
@@ -47,44 +67,76 @@ cd multi-service
|
||||
go run .
|
||||
```
|
||||
|
||||
### [deployment](./deployment/)
|
||||
#### [deployment](./deployment/)
|
||||
Docker Compose deployment with MCP gateway, Consul registry, and Jaeger tracing:
|
||||
- Production-like architecture in one `docker-compose up`
|
||||
- Standalone MCP gateway connected to service registry
|
||||
- Distributed tracing with OpenTelemetry + Jaeger
|
||||
|
||||
### MCP Examples
|
||||
### 2. Agents — turn services into tool-using teammates
|
||||
|
||||
#### [agent-demo](./agent-demo/)
|
||||
Recommended first agent: a multi-service project management app with Projects,
|
||||
Tasks, and Team services, seed data, and agent playground integration.
|
||||
|
||||
#### [agent-plan-delegate](./agent-plan-delegate/)
|
||||
The two built-in agent capabilities in a small multi-agent system:
|
||||
- **plan** — an agent records an ordered plan in its store-backed memory before doing multi-step work
|
||||
- **delegate** — an agent hands a subtask to another agent (over RPC if it's registered, else to an ephemeral sub-agent)
|
||||
|
||||
#### [agent-wrap-tool](./agent-wrap-tool/)
|
||||
Middleware around an agent's tool execution with `AgentWrapTool`, the tool-side analogue of client/server wrappers:
|
||||
- **observe** — time every tool call and record per-tool metrics, correlated by call ID
|
||||
- **retry** — re-run a call whose result is an error, recovering from a transient failure before the model sees it
|
||||
|
||||
#### [agent-durable](./agent-durable/)
|
||||
Durable agent runs that can be checkpointed and resumed, useful once your first
|
||||
agent needs predictable recovery behavior.
|
||||
|
||||
#### [agent-human-input](./agent-human-input/)
|
||||
Human-in-the-loop agent interaction for decisions that need an explicit person
|
||||
before the run can continue.
|
||||
|
||||
#### [agent-ollama](./agent-ollama/)
|
||||
Local-model agent wiring for developers experimenting with Ollama-backed model
|
||||
calls.
|
||||
|
||||
### 3. Workflows — coordinate longer-running work
|
||||
|
||||
#### [support](./support/)
|
||||
A maintained 0-to-hero reference path in one runnable file:
|
||||
- **scaffold** typed `customers`, `tickets`, and `notify` services
|
||||
- **run/chat** with a support agent that uses those services as tools
|
||||
- **inspect** the event-driven `intake` flow and approval gate
|
||||
- **CI** keeps the deterministic mock-model journey runnable with `go test ./examples/support`
|
||||
|
||||
#### [flow-durable](./flow-durable/)
|
||||
A workflow as ordered, checkpointed steps that survives a crash and resumes where it stopped:
|
||||
- **steps** — a flow is a task with stages (`reserve → charge → confirm`), not just one LLM turn
|
||||
- **Checkpoint** — each step is persisted; on `Resume`, completed steps are not re-run (no duplicate side effects)
|
||||
|
||||
#### [flow-loop](./flow-loop/)
|
||||
A looping flow example for repeated workflow steps.
|
||||
|
||||
### 4. MCP and agent integration examples
|
||||
|
||||
See the [mcp/](./mcp/) directory for AI agent integration examples:
|
||||
- **[hello](./mcp/hello/)** - Minimal MCP service (start here)
|
||||
- **[crud](./mcp/crud/)** - CRUD contact book with full agent documentation
|
||||
- **[workflow](./mcp/workflow/)** - Cross-service orchestration via AI agents
|
||||
- **[documented](./mcp/documented/)** - All MCP features with auth scopes
|
||||
- **[platform](./mcp/platform/)** - Platform-oriented MCP service example
|
||||
|
||||
### [agent-demo](./agent-demo/)
|
||||
Multi-service project management app (Projects, Tasks, Team) with seed data and agent playground integration.
|
||||
## Other examples
|
||||
|
||||
### [agent-plan-delegate](./agent-plan-delegate/)
|
||||
The two built-in agent capabilities in a small multi-agent system:
|
||||
- **plan** — an agent records an ordered plan in its store-backed memory before doing multi-step work
|
||||
- **delegate** — an agent hands a subtask to another agent (over RPC if it's registered, else to an ephemeral sub-agent)
|
||||
### [auth](./auth/)
|
||||
Authentication and authorization example.
|
||||
|
||||
### [agent-wrap-tool](./agent-wrap-tool/)
|
||||
Middleware around an agent's tool execution with `AgentWrapTool`, the tool-side analogue of client/server wrappers:
|
||||
- **observe** — time every tool call and record per-tool metrics, correlated by call ID
|
||||
- **retry** — re-run a call whose result is an error, recovering from a transient failure before the model sees it
|
||||
### [graceful-stop](./graceful-stop/)
|
||||
Graceful shutdown behavior for long-running services.
|
||||
|
||||
### [flow-durable](./flow-durable/)
|
||||
A workflow as ordered, checkpointed steps that survives a crash and resumes where it stopped:
|
||||
- **steps** — a flow is a task with stages (`reserve → charge → confirm`), not just one LLM turn
|
||||
- **Checkpoint** — each step is persisted; on `Resume`, completed steps are not re-run (no duplicate side effects)
|
||||
|
||||
### [support](./support/)
|
||||
A maintained 0-to-hero reference path in one runnable file:
|
||||
- **scaffold** typed `customers`, `tickets`, and `notify` services
|
||||
- **run/chat** with a support agent that uses those services as tools
|
||||
- **inspect** the event-driven `intake` flow and approval gate
|
||||
- **CI** keeps the deterministic mock-model journey runnable with `go test ./examples/support`
|
||||
### [grpc-interop](./grpc-interop/)
|
||||
gRPC interoperability example.
|
||||
|
||||
## Coming Soon
|
||||
|
||||
@@ -106,6 +158,5 @@ To add a new example:
|
||||
1. Create a new directory
|
||||
2. Add a descriptive README.md
|
||||
3. Include working code with comments
|
||||
4. Add to this index
|
||||
4. Add to this index under the lifecycle stage it supports
|
||||
5. Ensure it runs with `go run .`
|
||||
|
||||
|
||||
@@ -18,6 +18,19 @@ run and `micro.AgentResume` continues it from the saved checkpoint. The final
|
||||
`tool executions: 1` line is the important bit: the reservation tool was not
|
||||
called a second time during resume.
|
||||
|
||||
## When to use this instead of a durable flow
|
||||
|
||||
Use a durable flow when the path is known ahead of time: ordered service calls,
|
||||
retries, timers, compensation, and a precise resume stage such as `reserve` or
|
||||
`charge`. Use a checkpointed agent run when the path is open-ended and the model
|
||||
may choose tools dynamically, but completed tool side effects still must not be
|
||||
replayed after a crash or provider failure.
|
||||
|
||||
They compose: keep deterministic business process in `flow-durable`, then hand
|
||||
off the judgment-heavy step to a checkpointed agent when the workflow needs
|
||||
model-directed tool use. Both use the same `Checkpoint` backend, so inspection
|
||||
and recovery can share one run-history store.
|
||||
|
||||
In a service, use the same pattern at startup:
|
||||
|
||||
```go
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDurableAgentExampleResumesWithoutReplayingTool(t *testing.T) {
|
||||
out := captureStdout(t, main)
|
||||
if !strings.Contains(out, "simulated process interruption after checkpointed tool call") {
|
||||
t.Fatalf("example output %q did not show the initial interrupted run", out)
|
||||
}
|
||||
if !strings.Contains(out, "resumed reply: sku-123 is reserved; no duplicate reservation was made") {
|
||||
t.Fatalf("example output %q did not show the resumed response", out)
|
||||
}
|
||||
if !strings.Contains(out, "tool executions: 1") {
|
||||
t.Fatalf("example output %q did not prove the tool was not replayed", out)
|
||||
}
|
||||
}
|
||||
|
||||
func captureStdout(t *testing.T, fn func()) string {
|
||||
t.Helper()
|
||||
|
||||
old := os.Stdout
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("pipe stdout: %v", err)
|
||||
}
|
||||
os.Stdout = w
|
||||
|
||||
var buf bytes.Buffer
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_, _ = io.Copy(&buf, r)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
fn()
|
||||
|
||||
_ = w.Close()
|
||||
os.Stdout = old
|
||||
<-done
|
||||
_ = r.Close()
|
||||
return buf.String()
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
// Agent Ollama — a self-contained agent powered by Ollama Cloud.
|
||||
//
|
||||
// This example demonstrates the full harness loop — service tools, custom
|
||||
// tools, agent memory, guardrails, and streaming — using the Ollama
|
||||
// provider with gpt-oss:120b on Ollama Cloud.
|
||||
//
|
||||
// It creates a "knowledge" service with two endpoints (Add, Search) that
|
||||
// the agent discovers as tools, plus a custom "current_time" tool. The
|
||||
// agent answers natural-language questions by calling those tools.
|
||||
//
|
||||
// Run (Ollama Cloud — default):
|
||||
//
|
||||
// OLLAMA_API_KEY=your-key go run main.go
|
||||
//
|
||||
// Run (local Ollama):
|
||||
//
|
||||
// OLLAMA_BASE_URL=http://localhost:11434 \
|
||||
// OLLAMA_MODEL=llama3.2 \
|
||||
// go run main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6"
|
||||
"go-micro.dev/v6/agent"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// knowledge service — a tiny in-memory knowledge base
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type KnowledgeEntry struct {
|
||||
ID string `json:"id" description:"Unique entry identifier"`
|
||||
Topic string `json:"topic" description:"Topic or category"`
|
||||
Content string `json:"content" description:"The knowledge content"`
|
||||
}
|
||||
|
||||
type AddKnowledgeRequest struct {
|
||||
Topic string `json:"topic" description:"Topic or category (required)"`
|
||||
Content string `json:"content" description:"The knowledge content (required)"`
|
||||
}
|
||||
|
||||
type AddKnowledgeResponse struct {
|
||||
Entry *KnowledgeEntry `json:"entry" description:"The added entry"`
|
||||
}
|
||||
|
||||
type SearchKnowledgeRequest struct {
|
||||
Topic string `json:"topic,omitempty" description:"Filter by topic (optional)"`
|
||||
Keyword string `json:"keyword,omitempty" description:"Search keyword in content (optional)"`
|
||||
}
|
||||
|
||||
type SearchKnowledgeResponse struct {
|
||||
Entries []*KnowledgeEntry `json:"entries" description:"Matching entries"`
|
||||
}
|
||||
|
||||
type KnowledgeService struct {
|
||||
mu sync.RWMutex
|
||||
entries []*KnowledgeEntry
|
||||
nextID int
|
||||
}
|
||||
|
||||
// Add stores a new knowledge entry.
|
||||
//
|
||||
// @example {"topic": "go", "content": "Go interfaces are implicit."}
|
||||
func (s *KnowledgeService) Add(ctx context.Context, req *AddKnowledgeRequest, rsp *AddKnowledgeResponse) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.nextID++
|
||||
e := &KnowledgeEntry{
|
||||
ID: fmt.Sprintf("kb-%d", s.nextID),
|
||||
Topic: req.Topic,
|
||||
Content: req.Content,
|
||||
}
|
||||
s.entries = append(s.entries, e)
|
||||
rsp.Entry = e
|
||||
return nil
|
||||
}
|
||||
|
||||
// Search finds knowledge entries by topic or keyword.
|
||||
//
|
||||
// @example {"topic": "go"}
|
||||
// @example {"keyword": "interface"}
|
||||
func (s *KnowledgeService) Search(ctx context.Context, req *SearchKnowledgeRequest, rsp *SearchKnowledgeResponse) error {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for _, e := range s.entries {
|
||||
if req.Topic != "" && !strings.EqualFold(e.Topic, req.Topic) {
|
||||
continue
|
||||
}
|
||||
if req.Keyword != "" && !strings.Contains(strings.ToLower(e.Content), strings.ToLower(req.Keyword)) {
|
||||
continue
|
||||
}
|
||||
rsp.Entries = append(rsp.Entries, e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// main
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func main() {
|
||||
// Ollama Cloud is the default. Override with env vars for local Ollama.
|
||||
baseURL := os.Getenv("OLLAMA_BASE_URL")
|
||||
if baseURL == "" {
|
||||
baseURL = "https://ollama.com/v1"
|
||||
}
|
||||
model := os.Getenv("OLLAMA_MODEL")
|
||||
if model == "" {
|
||||
model = "gpt-oss:120b"
|
||||
}
|
||||
apiKey := os.Getenv("OLLAMA_API_KEY")
|
||||
|
||||
fmt.Println("╔══════════════════════════════════════════╗")
|
||||
fmt.Println("║ Ollama-Powered Go Micro Agent ║")
|
||||
fmt.Println("╚══════════════════════════════════════════╝")
|
||||
fmt.Println()
|
||||
fmt.Printf(" Ollama URL: %s\n", baseURL)
|
||||
fmt.Printf(" Model: %s\n", model)
|
||||
if apiKey != "" {
|
||||
fmt.Printf(" API Key: (set)\n")
|
||||
} else {
|
||||
fmt.Printf(" API Key: (none — set OLLAMA_API_KEY)\n")
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
// 1. Start the knowledge service. Its handlers become agent tools.
|
||||
svc := micro.NewService("knowledge")
|
||||
svc.Handle(new(KnowledgeService))
|
||||
go svc.Run()
|
||||
|
||||
// Give the service a moment to register.
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// 2. Create the agent. It discovers the knowledge service endpoints
|
||||
// as tools automatically, plus gets a custom "current_time" tool.
|
||||
ag := micro.NewAgent("ollama-assistant",
|
||||
micro.AgentServices("knowledge"),
|
||||
micro.AgentPrompt(
|
||||
"You are a helpful knowledge assistant. You can search and add to "+
|
||||
"a knowledge base using the knowledge service tools. "+
|
||||
"When asked about the current time, use the current_time tool. "+
|
||||
"Be concise and factual.",
|
||||
),
|
||||
micro.AgentProvider("ollama"),
|
||||
micro.AgentModel(model),
|
||||
micro.AgentAPIKey(apiKey),
|
||||
micro.AgentBaseURL(baseURL),
|
||||
micro.AgentMaxSteps(10),
|
||||
micro.AgentLoopLimit(3),
|
||||
// Custom tool — any function, not tied to a service.
|
||||
agent.WithTool(
|
||||
"current_time",
|
||||
"Get the current date and time in a human-readable format",
|
||||
map[string]any{
|
||||
"timezone": map[string]any{
|
||||
"type": "string",
|
||||
"description": "Optional timezone (defaults to local)",
|
||||
},
|
||||
},
|
||||
func(ctx context.Context, input map[string]any) (string, error) {
|
||||
tz, _ := input["timezone"].(string)
|
||||
if tz == "" {
|
||||
return time.Now().Format("2006-01-02 15:04:05 MST"), nil
|
||||
}
|
||||
loc, err := time.LoadLocation(tz)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("unknown timezone: %s", tz)
|
||||
}
|
||||
return time.Now().In(loc).Format("2006-01-02 15:04:05 MST"), nil
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
// 3. Seed initial knowledge via the agent's first question.
|
||||
questions := []string{
|
||||
"What time is it now?",
|
||||
"Add a new knowledge entry: topic 'go', content 'Go interfaces are implicit — a type implements an interface by having the required methods.'",
|
||||
"Add another entry: topic 'go', content 'Go is a statically typed, compiled language designed at Google.'",
|
||||
"Add another entry: topic 'ai', content 'Large language models generate text by predicting the next token in a sequence.'",
|
||||
"Search the knowledge base for entries about Go.",
|
||||
"Search for everything in the knowledge base.",
|
||||
}
|
||||
|
||||
fmt.Println("─── Agent Demo ───")
|
||||
fmt.Println()
|
||||
|
||||
for i, q := range questions {
|
||||
fmt.Printf("Q%d: %s\n", i+1, q)
|
||||
fmt.Print("A: ")
|
||||
|
||||
resp, err := ag.Ask(context.Background(), q)
|
||||
if err != nil {
|
||||
fmt.Printf("error: %v\n", err)
|
||||
fmt.Println()
|
||||
continue
|
||||
}
|
||||
|
||||
// Show tool calls the agent made.
|
||||
if len(resp.ToolCalls) > 0 {
|
||||
for _, tc := range resp.ToolCalls {
|
||||
args, _ := json.Marshal(tc.Input)
|
||||
fmt.Printf(" [tool] %s(%s)\n", tc.Name, string(args))
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println(resp.Reply)
|
||||
if resp.Reply == "" && len(resp.ToolCalls) == 0 {
|
||||
fmt.Println("(no response)")
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
// 4. Streaming demonstration.
|
||||
fmt.Println("─── Streaming Demo ───")
|
||||
fmt.Println()
|
||||
streamQ := "Explain what Go Micro is in two sentences."
|
||||
fmt.Printf("Q: %s\n", streamQ)
|
||||
fmt.Print("A: ")
|
||||
|
||||
stream, err := ag.Stream(context.Background(), streamQ)
|
||||
if err != nil {
|
||||
fmt.Printf("stream error: %v\n", err)
|
||||
} else {
|
||||
for {
|
||||
chunk, err := stream.Recv()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if chunk.Reply != "" {
|
||||
fmt.Print(chunk.Reply)
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("Done.")
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
// AnalyzeOptions configures Analyze.
|
||||
type AnalyzeOptions struct {
|
||||
// MaxFeedbackSamples bounds the number of representative grader feedback
|
||||
// strings retained per candidate. Values <= 0 use a small default.
|
||||
MaxFeedbackSamples int
|
||||
}
|
||||
|
||||
// AnalyzeOption configures Analyze.
|
||||
type AnalyzeOption func(*AnalyzeOptions)
|
||||
|
||||
// AnalyzeMaxFeedbackSamples sets how many grader feedback examples are kept for
|
||||
// each candidate in the report.
|
||||
func AnalyzeMaxFeedbackSamples(n int) AnalyzeOption {
|
||||
return func(o *AnalyzeOptions) { o.MaxFeedbackSamples = n }
|
||||
}
|
||||
|
||||
// Report is the machine-readable output of Analyze. Candidates are ordered from
|
||||
// worst to best so an agent, CLI, or human can pick the first improvement to try.
|
||||
type Report struct {
|
||||
Candidates []Candidate `json:"candidates"`
|
||||
}
|
||||
|
||||
// Candidate identifies one underperforming flow step and the trace evidence that
|
||||
// made it worth improving.
|
||||
type Candidate struct {
|
||||
Step string `json:"step"`
|
||||
Metric string `json:"metric"`
|
||||
Score float64 `json:"score"`
|
||||
Runs int `json:"runs"`
|
||||
Failures int `json:"failures"`
|
||||
PassRate float64 `json:"pass_rate"`
|
||||
ErrorRate float64 `json:"error_rate"`
|
||||
AverageRetries float64 `json:"average_retries"`
|
||||
P50Latency time.Duration `json:"p50_latency"`
|
||||
P95Latency time.Duration `json:"p95_latency"`
|
||||
SampleFeedback []string `json:"sample_feedback,omitempty"`
|
||||
RunIDs []string `json:"run_ids,omitempty"`
|
||||
}
|
||||
|
||||
// Analyze aggregates a bounded window of persisted flow runs and returns ranked
|
||||
// hill-climbing candidates. It uses the same Run records read by Checkpoint.List:
|
||||
// failed verification fields in step results drive pass-rate and feedback, step
|
||||
// status drives error rate, and retry attempts contribute retry pressure. An
|
||||
// empty window returns an empty report.
|
||||
func Analyze(runs []Run, opts ...AnalyzeOption) Report {
|
||||
o := AnalyzeOptions{MaxFeedbackSamples: 3}
|
||||
for _, opt := range opts {
|
||||
opt(&o)
|
||||
}
|
||||
if o.MaxFeedbackSamples <= 0 {
|
||||
o.MaxFeedbackSamples = 3
|
||||
}
|
||||
|
||||
stats := map[string]*stepStats{}
|
||||
for _, run := range runs {
|
||||
for _, step := range run.Steps {
|
||||
if step.Name == "" {
|
||||
continue
|
||||
}
|
||||
s := stats[step.Name]
|
||||
if s == nil {
|
||||
s = &stepStats{}
|
||||
stats[step.Name] = s
|
||||
}
|
||||
s.runs++
|
||||
s.runIDs = appendUnique(s.runIDs, run.ID)
|
||||
if step.Attempts > 1 {
|
||||
s.retries += step.Attempts - 1
|
||||
}
|
||||
if step.Status == "failed" || step.Error != "" {
|
||||
s.errors++
|
||||
}
|
||||
if len(run.Steps) > 0 && !run.Started.IsZero() && !run.Updated.IsZero() {
|
||||
s.latencies = append(s.latencies, run.Updated.Sub(run.Started)/time.Duration(len(run.Steps)))
|
||||
}
|
||||
passed, feedback, ok := verificationFields(step.Result)
|
||||
if ok {
|
||||
s.graded++
|
||||
if !passed {
|
||||
s.gradeFailures++
|
||||
if feedback != "" && len(s.feedback) < o.MaxFeedbackSamples {
|
||||
s.feedback = append(s.feedback, feedback)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
report := Report{}
|
||||
for step, s := range stats {
|
||||
if s.runs == 0 {
|
||||
continue
|
||||
}
|
||||
failures := s.errors + s.gradeFailures
|
||||
passRate := 1.0
|
||||
if s.graded > 0 {
|
||||
passRate = float64(s.graded-s.gradeFailures) / float64(s.graded)
|
||||
} else if s.errors > 0 {
|
||||
passRate = float64(s.runs-s.errors) / float64(s.runs)
|
||||
}
|
||||
errorRate := float64(s.errors) / float64(s.runs)
|
||||
avgRetries := float64(s.retries) / float64(s.runs)
|
||||
score := float64(s.gradeFailures)*3 + float64(s.errors)*2 + avgRetries
|
||||
metric := "pass_rate"
|
||||
if s.gradeFailures == 0 && s.errors > 0 {
|
||||
metric = "error_rate"
|
||||
} else if s.gradeFailures == 0 && s.errors == 0 && s.retries > 0 {
|
||||
metric = "retry_count"
|
||||
}
|
||||
report.Candidates = append(report.Candidates, Candidate{
|
||||
Step: step, Metric: metric, Score: score, Runs: s.runs, Failures: failures,
|
||||
PassRate: passRate, ErrorRate: errorRate, AverageRetries: avgRetries,
|
||||
P50Latency: percentile(s.latencies, 0.50), P95Latency: percentile(s.latencies, 0.95),
|
||||
SampleFeedback: append([]string(nil), s.feedback...), RunIDs: append([]string(nil), s.runIDs...),
|
||||
})
|
||||
}
|
||||
sort.SliceStable(report.Candidates, func(i, j int) bool {
|
||||
a, b := report.Candidates[i], report.Candidates[j]
|
||||
if a.Score == b.Score {
|
||||
return a.Step < b.Step
|
||||
}
|
||||
return a.Score > b.Score
|
||||
})
|
||||
return report
|
||||
}
|
||||
|
||||
type stepStats struct {
|
||||
runs, graded, gradeFailures, errors, retries int
|
||||
feedback, runIDs []string
|
||||
latencies []time.Duration
|
||||
}
|
||||
|
||||
// PromptOptimizer proposes prompt improvements for a candidate without mutating
|
||||
// the source flow. Applying the returned prompt stays explicitly gated by the caller.
|
||||
type PromptOptimizer struct{ model ai.Model }
|
||||
|
||||
// LLMOptimizer returns an optimizer that asks model to revise prompts for
|
||||
// Analyze candidates. The model is injected so tests and callers can use mocks.
|
||||
func LLMOptimizer(model ai.Model) *PromptOptimizer { return &PromptOptimizer{model: model} }
|
||||
|
||||
// OptimizePrompt asks the model for a revised prompt for candidate using the
|
||||
// current prompt and trace feedback. It returns only the proposal; it never
|
||||
// modifies a Flow, Step, or Checkpoint.
|
||||
func (o *PromptOptimizer) OptimizePrompt(ctx context.Context, candidate Candidate, currentPrompt string) (string, error) {
|
||||
if o == nil || o.model == nil {
|
||||
return "", fmt.Errorf("flow: LLMOptimizer requires a model")
|
||||
}
|
||||
prompt := fmt.Sprintf("Revise this workflow step prompt to improve the failing step.\nStep: %s\nMetric: %s\nScore: %.2f\nFeedback:\n- %s\n\nCurrent prompt:\n%s\n\nReturn only the revised prompt.", candidate.Step, candidate.Metric, candidate.Score, strings.Join(candidate.SampleFeedback, "\n- "), currentPrompt)
|
||||
resp, err := o.model.Generate(ctx, &ai.Request{Prompt: prompt})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
proposal := strings.TrimSpace(resp.Answer)
|
||||
if proposal == "" {
|
||||
proposal = strings.TrimSpace(resp.Reply)
|
||||
}
|
||||
if proposal == "" {
|
||||
return "", fmt.Errorf("flow: LLMOptimizer returned an empty prompt")
|
||||
}
|
||||
return proposal, nil
|
||||
}
|
||||
|
||||
func verificationFields(result string) (bool, string, bool) {
|
||||
if result == "" {
|
||||
return false, "", false
|
||||
}
|
||||
var obj map[string]any
|
||||
if err := json.Unmarshal([]byte(result), &obj); err != nil {
|
||||
return false, "", false
|
||||
}
|
||||
v, ok := obj["verification_passed"].(bool)
|
||||
if !ok {
|
||||
return false, "", false
|
||||
}
|
||||
fb, _ := obj["verification_feedback"].(string)
|
||||
return v, fb, true
|
||||
}
|
||||
|
||||
func appendUnique(values []string, value string) []string {
|
||||
if value == "" {
|
||||
return values
|
||||
}
|
||||
for _, v := range values {
|
||||
if v == value {
|
||||
return values
|
||||
}
|
||||
}
|
||||
return append(values, value)
|
||||
}
|
||||
|
||||
func percentile(values []time.Duration, p float64) time.Duration {
|
||||
if len(values) == 0 {
|
||||
return 0
|
||||
}
|
||||
sorted := append([]time.Duration(nil), values...)
|
||||
sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
|
||||
idx := int(float64(len(sorted)-1) * p)
|
||||
return sorted[idx]
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
func TestAnalyzeRanksFailedGraderStepAbovePassingStep(t *testing.T) {
|
||||
now := time.Now()
|
||||
runs := []Run{
|
||||
{ID: "run-1", Started: now, Updated: now.Add(time.Second), Steps: []StepRecord{
|
||||
{Name: "draft", Status: "done", Attempts: 2, Result: `{"verification_passed":false,"verification_feedback":"cite sources"}`},
|
||||
{Name: "publish", Status: "done", Attempts: 1, Result: `{"verification_passed":true,"verification_feedback":"ok"}`},
|
||||
}},
|
||||
{ID: "run-2", Started: now, Updated: now.Add(2 * time.Second), Steps: []StepRecord{
|
||||
{Name: "draft", Status: "done", Attempts: 1, Result: `{"verification_passed":false,"verification_feedback":"too vague"}`},
|
||||
{Name: "publish", Status: "done", Attempts: 1, Result: `{"verification_passed":true,"verification_feedback":"ok"}`},
|
||||
}},
|
||||
}
|
||||
|
||||
report := Analyze(runs)
|
||||
if len(report.Candidates) != 2 {
|
||||
t.Fatalf("Analyze returned %d candidates, want 2", len(report.Candidates))
|
||||
}
|
||||
if got := report.Candidates[0].Step; got != "draft" {
|
||||
t.Fatalf("top candidate = %q, want draft", got)
|
||||
}
|
||||
if report.Candidates[0].PassRate != 0 {
|
||||
t.Fatalf("draft pass rate = %v, want 0", report.Candidates[0].PassRate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnalyzeCarriesFeedbackSamplesAndRunIDs(t *testing.T) {
|
||||
report := Analyze([]Run{{ID: "run-9", Steps: []StepRecord{{
|
||||
Name: "grade", Status: "done", Attempts: 3,
|
||||
Result: `{"verification_passed":false,"verification_feedback":"include totals"}`,
|
||||
}}}})
|
||||
if len(report.Candidates) != 1 {
|
||||
t.Fatalf("candidates = %d, want 1", len(report.Candidates))
|
||||
}
|
||||
c := report.Candidates[0]
|
||||
if len(c.SampleFeedback) != 1 || c.SampleFeedback[0] != "include totals" {
|
||||
t.Fatalf("feedback = %#v, want include totals", c.SampleFeedback)
|
||||
}
|
||||
if len(c.RunIDs) != 1 || c.RunIDs[0] != "run-9" {
|
||||
t.Fatalf("run ids = %#v, want run-9", c.RunIDs)
|
||||
}
|
||||
if c.AverageRetries != 2 {
|
||||
t.Fatalf("average retries = %v, want 2", c.AverageRetries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnalyzeEmptyWindowReturnsEmptyReport(t *testing.T) {
|
||||
if got := Analyze(nil); len(got.Candidates) != 0 {
|
||||
t.Fatalf("empty Analyze candidates = %d, want 0", len(got.Candidates))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLLMOptimizerReturnsProposalWithoutMutatingFlow(t *testing.T) {
|
||||
f := New("optimize", Prompt("original prompt"))
|
||||
before := f.opts.Prompt
|
||||
optimizer := LLMOptimizer(&optimizerModel{reply: "revised prompt"})
|
||||
proposal, err := optimizer.OptimizePrompt(context.Background(), Candidate{Step: "draft", Metric: "pass_rate", SampleFeedback: []string{"cite sources"}}, before)
|
||||
if err != nil {
|
||||
t.Fatalf("OptimizePrompt returned error: %v", err)
|
||||
}
|
||||
if !strings.Contains(proposal, "revised") {
|
||||
t.Fatalf("proposal = %q, want revised prompt", proposal)
|
||||
}
|
||||
if f.opts.Prompt != before {
|
||||
t.Fatalf("flow prompt mutated to %q, want %q", f.opts.Prompt, before)
|
||||
}
|
||||
}
|
||||
|
||||
type optimizerModel struct{ reply string }
|
||||
|
||||
func (m *optimizerModel) Init(...ai.Option) error { return nil }
|
||||
func (m *optimizerModel) Options() ai.Options { return ai.Options{} }
|
||||
func (m *optimizerModel) Generate(context.Context, *ai.Request, ...ai.GenerateOption) (*ai.Response, error) {
|
||||
return &ai.Response{Reply: m.reply}, nil
|
||||
}
|
||||
func (m *optimizerModel) Stream(context.Context, *ai.Request, ...ai.GenerateOption) (ai.Stream, error) {
|
||||
return nil, ai.ErrStreamingUnsupported
|
||||
}
|
||||
func (m *optimizerModel) String() string { return "optimizer" }
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"go-micro.dev/v6/client"
|
||||
codecbytes "go-micro.dev/v6/codec/bytes"
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
|
||||
// fakeClient embeds the default client (so NewRequest works) and
|
||||
@@ -65,3 +66,65 @@ func TestExecuteDispatchesToAgent(t *testing.T) {
|
||||
t.Errorf("rendered prompt = %q, want %q", results[0].Prompt, "welcome bob")
|
||||
}
|
||||
}
|
||||
|
||||
// A caller-owned schedule can trigger an agent workflow without a human chat
|
||||
// prompt and still leave the normal flow run metadata behind for inspection.
|
||||
func TestScheduledAgentRunHarnessContract(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cp := StoreCheckpoint(store.NewMemoryStore(), "scheduled-contract")
|
||||
f := New("scheduled-contract",
|
||||
Trigger("schedule.daily"),
|
||||
WithCheckpoint(cp),
|
||||
Steps(Step{Name: "summarize", Run: Dispatch("ops-agent")}),
|
||||
)
|
||||
|
||||
var parentID string
|
||||
f.client = &fakeClient{
|
||||
Client: client.DefaultClient,
|
||||
callFn: func(req client.Request, rsp interface{}) error {
|
||||
if req.Service() != "ops-agent" || req.Endpoint() != "Agent.Chat" {
|
||||
t.Fatalf("dispatched to %s.%s, want ops-agent.Agent.Chat", req.Service(), req.Endpoint())
|
||||
}
|
||||
reqFrame := req.Body().(*codecbytes.Frame)
|
||||
var body map[string]string
|
||||
if err := json.Unmarshal(reqFrame.Data, &body); err != nil {
|
||||
t.Fatalf("request body: %v", err)
|
||||
}
|
||||
parentID = body["parent_id"]
|
||||
if body["message"] != "run unattended daily ops review" {
|
||||
t.Fatalf("message = %q, want scheduled payload", body["message"])
|
||||
}
|
||||
frame := rsp.(*codecbytes.Frame)
|
||||
frame.Data = []byte(`{"reply":"review queued","agent":"ops-agent","parent_id":"` + parentID + `"}`)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
if err := Scheduled(f, "run unattended daily ops review").Tick(ctx); err != nil {
|
||||
t.Fatalf("scheduled tick: %v", err)
|
||||
}
|
||||
if parentID == "" {
|
||||
t.Fatal("dispatch did not receive the scheduled flow run id as parent_id")
|
||||
}
|
||||
|
||||
runs, err := cp.List(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("list scheduled runs: %v", err)
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("got %d runs, want 1", len(runs))
|
||||
}
|
||||
run := runs[0]
|
||||
if run.ID != parentID {
|
||||
t.Fatalf("run ID = %q, parent_id = %q", run.ID, parentID)
|
||||
}
|
||||
if run.Flow != "scheduled-contract" || run.Status != "done" {
|
||||
t.Fatalf("run = %+v, want scheduled-contract done", run)
|
||||
}
|
||||
if got := run.State.String(); got != "review queued" {
|
||||
t.Fatalf("run result = %q, want agent reply", got)
|
||||
}
|
||||
if len(run.Steps) != 1 || run.Steps[0].Name != "summarize" || run.Steps[0].Status != "done" {
|
||||
t.Fatalf("steps = %+v, want summarize done", run.Steps)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package flow_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"go-micro.dev/v6/flow"
|
||||
)
|
||||
|
||||
func ExampleVerify() {
|
||||
generate := func(_ context.Context, in flow.State) (flow.State, error) {
|
||||
if strings.Contains(in.String(), "feedback") {
|
||||
in.Data = []byte(`{"answer":"include a source"}`)
|
||||
return in, nil
|
||||
}
|
||||
in.Data = []byte(`{"answer":"draft"}`)
|
||||
return in, nil
|
||||
}
|
||||
grader := func(_ context.Context, out flow.State) (bool, string, error) {
|
||||
return strings.Contains(out.String(), "source"), "add a source", nil
|
||||
}
|
||||
|
||||
out, _ := flow.Verify(generate, grader, flow.VerifyMaxAttempts(2))(context.Background(), flow.State{})
|
||||
fmt.Println(strings.Contains(out.String(), `"verification_passed":true`))
|
||||
// Output: true
|
||||
}
|
||||
|
||||
func ExampleAnalyze() {
|
||||
runs := []flow.Run{{
|
||||
ID: "run-1",
|
||||
Steps: []flow.StepRecord{{
|
||||
Name: "draft",
|
||||
Status: "done",
|
||||
Result: `{"verification_passed":false,"verification_feedback":"add a source"}`,
|
||||
}},
|
||||
}}
|
||||
|
||||
report := flow.Analyze(runs)
|
||||
fmt.Println(report.Candidates[0].Step)
|
||||
fmt.Println(report.Candidates[0].SampleFeedback[0])
|
||||
// Output:
|
||||
// draft
|
||||
// add a source
|
||||
}
|
||||
+10
-2
@@ -76,6 +76,7 @@ type Result struct {
|
||||
Answer string `json:"answer,omitempty"`
|
||||
ToolCalls []string `json:"tool_calls,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ErrorKind string `json:"error_kind,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Duration float64 `json:"duration_seconds"`
|
||||
}
|
||||
@@ -141,7 +142,8 @@ func (f *Flow) Register(reg registry.Registry, br broker.Broker, cl client.Clien
|
||||
if f.opts.TriggerTopic != "" {
|
||||
sub, err := br.Subscribe(f.opts.TriggerTopic, func(p broker.Event) error {
|
||||
data := string(p.Message().Body)
|
||||
if err := f.Execute(context.Background(), data); err != nil {
|
||||
ctx := ai.WithRunInfo(context.Background(), ai.RunInfo{Dispatch: "broker", Trigger: f.opts.TriggerTopic})
|
||||
if err := f.Execute(ctx, data); err != nil {
|
||||
f.log.Logf(logger.ErrorLevel, "Flow %s failed: %v", f.name, err)
|
||||
}
|
||||
return nil
|
||||
@@ -222,7 +224,10 @@ func (f *Flow) Execute(ctx context.Context, data string) error {
|
||||
}
|
||||
|
||||
runID := uuid.New().String()
|
||||
ctx = ai.WithRunInfo(ctx, ai.RunInfo{RunID: runID, Flow: f.name})
|
||||
info, _ := ai.RunInfoFrom(ctx)
|
||||
info.RunID = runID
|
||||
info.Flow = f.name
|
||||
ctx = ai.WithRunInfo(ctx, info)
|
||||
|
||||
start := time.Now()
|
||||
|
||||
@@ -246,6 +251,7 @@ func (f *Flow) Execute(ctx context.Context, data string) error {
|
||||
result.Duration = time.Since(start).Seconds()
|
||||
if err != nil {
|
||||
result.Error = err.Error()
|
||||
result.ErrorKind = string(ai.ClassifyError(err))
|
||||
f.record(result)
|
||||
return err
|
||||
}
|
||||
@@ -261,6 +267,7 @@ func (f *Flow) Execute(ctx context.Context, data string) error {
|
||||
if err != nil {
|
||||
result.Duration = time.Since(start).Seconds()
|
||||
result.Error = err.Error()
|
||||
result.ErrorKind = string(ai.ClassifyError(err))
|
||||
f.record(result)
|
||||
return fmt.Errorf("discover tools: %w", err)
|
||||
}
|
||||
@@ -274,6 +281,7 @@ func (f *Flow) Execute(ctx context.Context, data string) error {
|
||||
|
||||
if err != nil {
|
||||
result.Error = err.Error()
|
||||
result.ErrorKind = string(ai.ClassifyError(err))
|
||||
f.record(result)
|
||||
return err
|
||||
}
|
||||
|
||||
+45
-14
@@ -16,13 +16,18 @@ const (
|
||||
spanNameFlowRun = "flow.run"
|
||||
spanNameFlowStep = "flow.step"
|
||||
|
||||
AttrFlowRunID = "flow.run.id"
|
||||
AttrFlowParentID = "flow.run.parent_id"
|
||||
AttrFlowName = "flow.name"
|
||||
AttrFlowStepName = "flow.step.name"
|
||||
AttrFlowStatus = "flow.status"
|
||||
AttrFlowAttempts = "flow.step.attempts"
|
||||
AttrFlowLatencyMS = "flow.latency_ms"
|
||||
AttrFlowRunID = "flow.run.id"
|
||||
AttrFlowParentID = "flow.run.parent_id"
|
||||
AttrFlowName = "flow.name"
|
||||
AttrFlowStepName = "flow.step.name"
|
||||
AttrFlowStatus = "flow.status"
|
||||
AttrFlowAttempts = "flow.step.attempts"
|
||||
AttrFlowLatencyMS = "flow.latency_ms"
|
||||
AttrFlowErrorKind = "flow.error.kind"
|
||||
AttrFlowVerificationStatus = "flow.verification.status"
|
||||
AttrFlowVerificationNote = "flow.verification.note"
|
||||
AttrFlowDispatch = "flow.dispatch"
|
||||
AttrFlowTrigger = "flow.trigger"
|
||||
)
|
||||
|
||||
func (f *Flow) tracer() trace.Tracer {
|
||||
@@ -33,12 +38,15 @@ func (f *Flow) startRunSpan(ctx context.Context, run Run) (context.Context, func
|
||||
if f.opts.TraceProvider == nil {
|
||||
return ctx, func(Run, error) {}
|
||||
}
|
||||
ctx, span := f.tracer().Start(ctx, spanNameFlowRun, trace.WithSpanKind(trace.SpanKindInternal), trace.WithAttributes(
|
||||
info, _ := ai.RunInfoFrom(ctx)
|
||||
attrs := []attribute.KeyValue{
|
||||
attribute.String(AttrFlowRunID, run.ID),
|
||||
attribute.String(AttrFlowParentID, run.ParentID),
|
||||
attribute.String(AttrFlowName, f.name),
|
||||
attribute.String(AttrFlowStatus, run.Status),
|
||||
))
|
||||
}
|
||||
attrs = appendRunInfoDispatch(attrs, info)
|
||||
ctx, span := f.tracer().Start(ctx, spanNameFlowRun, trace.WithSpanKind(trace.SpanKindInternal), trace.WithAttributes(attrs...))
|
||||
start := time.Now()
|
||||
return ctx, func(done Run, err error) {
|
||||
span.SetAttributes(
|
||||
@@ -47,6 +55,7 @@ func (f *Flow) startRunSpan(ctx context.Context, run Run) (context.Context, func
|
||||
)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetAttributes(attribute.String(AttrFlowErrorKind, string(ai.ClassifyError(err))))
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
@@ -55,29 +64,51 @@ func (f *Flow) startRunSpan(ctx context.Context, run Run) (context.Context, func
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Flow) runStepSpan(ctx context.Context, step Step, in State) (State, int, error) {
|
||||
func (f *Flow) runStepSpan(ctx context.Context, step Step, in State) (State, int, Verification, error) {
|
||||
if f.opts.TraceProvider == nil {
|
||||
return f.runStep(ctx, step, in)
|
||||
}
|
||||
info, _ := ai.RunInfoFrom(ctx)
|
||||
ctx, span := f.tracer().Start(ctx, spanNameFlowStep, trace.WithAttributes(
|
||||
attrs := []attribute.KeyValue{
|
||||
attribute.String(AttrFlowRunID, info.RunID),
|
||||
attribute.String(AttrFlowParentID, info.ParentID),
|
||||
attribute.String(AttrFlowName, f.name),
|
||||
attribute.String(AttrFlowStepName, step.Name),
|
||||
))
|
||||
}
|
||||
attrs = appendRunInfoDispatch(attrs, info)
|
||||
ctx, span := f.tracer().Start(ctx, spanNameFlowStep, trace.WithAttributes(attrs...))
|
||||
start := time.Now()
|
||||
out, attempts, err := f.runStep(ctx, step, in)
|
||||
out, attempts, verification, err := f.runStep(ctx, step, in)
|
||||
span.SetAttributes(
|
||||
attribute.Int(AttrFlowAttempts, attempts),
|
||||
attribute.Int64(AttrFlowLatencyMS, time.Since(start).Milliseconds()),
|
||||
)
|
||||
if verification.Passed {
|
||||
span.SetAttributes(attribute.String(AttrFlowVerificationStatus, "passed"))
|
||||
}
|
||||
if verification.Feedback != "" {
|
||||
span.SetAttributes(attribute.String(AttrFlowVerificationNote, verification.Feedback))
|
||||
if !verification.Passed {
|
||||
span.SetAttributes(attribute.String(AttrFlowVerificationStatus, "failed"))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetAttributes(attribute.String(AttrFlowErrorKind, string(ai.ClassifyError(err))))
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
span.End()
|
||||
return out, attempts, err
|
||||
return out, attempts, verification, err
|
||||
}
|
||||
|
||||
func appendRunInfoDispatch(attrs []attribute.KeyValue, info ai.RunInfo) []attribute.KeyValue {
|
||||
if info.Dispatch != "" {
|
||||
attrs = append(attrs, attribute.String(AttrFlowDispatch, info.Dispatch))
|
||||
}
|
||||
if info.Trigger != "" {
|
||||
attrs = append(attrs, attribute.String(AttrFlowTrigger, info.Trigger))
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
@@ -74,3 +74,29 @@ func flowSpanAttributes(attrs []attribute.KeyValue) map[string]string {
|
||||
func withTestRunInfo(ctx context.Context, runID string) context.Context {
|
||||
return ai.WithRunInfo(ctx, ai.RunInfo{RunID: runID, Agent: "planner"})
|
||||
}
|
||||
|
||||
func TestScheduledFlowOpenTelemetryDispatchAttributes(t *testing.T) {
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
tp := trace.NewTracerProvider(trace.WithSyncer(exp))
|
||||
|
||||
step := Step{Name: "summarize", Run: func(ctx context.Context, in State) (State, error) {
|
||||
in.Data = []byte("queued")
|
||||
return in, nil
|
||||
}}
|
||||
f := New("scheduled-observed", Trigger("schedule.daily"), WithCheckpoint(StoreCheckpoint(store.NewMemoryStore(), "scheduled-observed")), TraceProvider(tp), Steps(step))
|
||||
if err := Scheduled(f, "daily ops review").Tick(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, span := range exp.GetSpans().Snapshots() {
|
||||
if span.Name() != spanNameFlowRun {
|
||||
continue
|
||||
}
|
||||
attrs := flowSpanAttributes(span.Attributes())
|
||||
if attrs[AttrFlowDispatch] != "schedule" || attrs[AttrFlowTrigger] != "schedule.daily" {
|
||||
t.Fatalf("scheduled run span dispatch attributes = %#v", attrs)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatal("flow run span not emitted")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
// Schedule binds a flow to a recurring work item without introducing a
|
||||
// scheduler service. It is a small harness contract: callers own the clock,
|
||||
// Go Micro owns turning each tick into the same inspectable flow run used for
|
||||
// broker events and direct Execute calls.
|
||||
type Schedule struct {
|
||||
flow *Flow
|
||||
data string
|
||||
}
|
||||
|
||||
// Scheduled returns a deterministic scheduled-run harness for this flow.
|
||||
// Tests and event loops can call Tick directly; production processes can wire
|
||||
// the same contract to time.Ticker through RunEvery. Each tick calls Execute, so
|
||||
// checkpointed run history, parent/run metadata, cancellation, and inspection
|
||||
// stay on the normal flow surfaces.
|
||||
func Scheduled(f *Flow, data string) Schedule {
|
||||
return Schedule{flow: f, data: data}
|
||||
}
|
||||
|
||||
// Tick starts one scheduled run immediately and returns when that run finishes.
|
||||
func (s Schedule) Tick(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
info, _ := ai.RunInfoFrom(ctx)
|
||||
info.Dispatch = "schedule"
|
||||
if info.Trigger == "" {
|
||||
info.Trigger = s.flow.opts.TriggerTopic
|
||||
}
|
||||
if info.Trigger == "" {
|
||||
info.Trigger = "schedule"
|
||||
}
|
||||
return s.flow.Execute(ai.WithRunInfo(ctx, info), s.data)
|
||||
}
|
||||
|
||||
// RunEvery drives scheduled runs from a ticker until ctx is canceled. It does
|
||||
// not persist schedule definitions or host a scheduler; it only adapts a caller
|
||||
// owned cadence to Tick.
|
||||
func (s Schedule) RunEvery(ctx context.Context, interval time.Duration) error {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
if err := s.Tick(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+85
-21
@@ -52,22 +52,53 @@ func (s State) String() string { return string(s.Data) }
|
||||
// returns the next state.
|
||||
type StepFunc func(ctx context.Context, in State) (State, error)
|
||||
|
||||
// Step is one unit of a flow — a named action with an optional retry
|
||||
// override. There is one Step kind; the action is the Run func, and the
|
||||
// Call/LLM/Agent helpers produce the common ones.
|
||||
// Verifier grades a step output before the flow advances. Returning
|
||||
// Passed=false converts the grade into a retryable VerificationError, so
|
||||
// the existing step retry/supervision path can feed Feedback into the next
|
||||
// attempt through ai.RunInfo.VerificationFeedback.
|
||||
type Verifier func(ctx context.Context, out State) (Verification, error)
|
||||
|
||||
// Verification is the verifier's deterministic grade for one step attempt.
|
||||
type Verification struct {
|
||||
Passed bool
|
||||
Feedback string
|
||||
}
|
||||
|
||||
// VerificationError reports a failed grade. It is returned from runStep so
|
||||
// existing retry, checkpoint, and trace paths handle verifier failures the
|
||||
// same way they handle step execution failures.
|
||||
type VerificationError struct {
|
||||
Step string
|
||||
Feedback string
|
||||
}
|
||||
|
||||
func (e *VerificationError) Error() string {
|
||||
if e.Feedback == "" {
|
||||
return fmt.Sprintf("flow: verification failed for step %q", e.Step)
|
||||
}
|
||||
return fmt.Sprintf("flow: verification failed for step %q: %s", e.Step, e.Feedback)
|
||||
}
|
||||
|
||||
// Step is one unit of a flow — a named action with optional retry and
|
||||
// verification hooks. There is one Step kind; the action is the Run func,
|
||||
// and the Call/LLM/Agent helpers produce the common ones.
|
||||
type Step struct {
|
||||
Name string
|
||||
Run StepFunc
|
||||
Retry int // per-step override of the flow's retry (0 = use the flow default)
|
||||
Name string
|
||||
Run StepFunc
|
||||
Retry int // per-step override of the flow's retry (0 = use the flow default)
|
||||
Verify Verifier // optional grade; failed grades retry the step with feedback in RunInfo
|
||||
}
|
||||
|
||||
// StepRecord is the recorded outcome of one step within a run.
|
||||
type StepRecord struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"` // pending | in_progress | done | failed
|
||||
Attempts int `json:"attempts"`
|
||||
Result string `json:"result,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"` // pending | in_progress | done | failed
|
||||
Attempts int `json:"attempts"`
|
||||
Result string `json:"result,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ErrorKind string `json:"error_kind,omitempty"`
|
||||
VerificationStatus string `json:"verification_status,omitempty"` // passed | failed
|
||||
VerificationNote string `json:"verification_note,omitempty"`
|
||||
}
|
||||
|
||||
// Run is the persisted record of one flow execution — what a Checkpoint
|
||||
@@ -402,7 +433,12 @@ func (f *Flow) Pending(ctx context.Context) ([]Run, error) {
|
||||
func (f *Flow) runFrom(ctx context.Context, run Run) (Run, error) {
|
||||
steps := f.opts.Steps
|
||||
ctx = withDeps(ctx, &runDeps{client: f.client, model: f.model, tools: f.toolSet})
|
||||
ctx = ai.WithRunInfo(ctx, ai.RunInfo{RunID: run.ID, ParentID: run.ParentID, Agent: f.name, Flow: f.name})
|
||||
info, _ := ai.RunInfoFrom(ctx)
|
||||
info.RunID = run.ID
|
||||
info.ParentID = run.ParentID
|
||||
info.Agent = f.name
|
||||
info.Flow = f.name
|
||||
ctx = ai.WithRunInfo(ctx, info)
|
||||
ctx, finishSpan := f.startRunSpan(ctx, run)
|
||||
var spanErr error
|
||||
defer func() { finishSpan(run, spanErr) }()
|
||||
@@ -425,12 +461,14 @@ func (f *Flow) runFrom(ctx context.Context, run Run) (Run, error) {
|
||||
return run, err
|
||||
}
|
||||
|
||||
out, attempts, err := f.runStepSpan(ctx, step, run.State)
|
||||
out, attempts, verification, err := f.runStepSpan(ctx, step, run.State)
|
||||
run.Steps[i].Attempts = attempts
|
||||
applyVerificationRecord(&run.Steps[i], verification)
|
||||
if err != nil {
|
||||
spanErr = err
|
||||
run.Steps[i].Status = "failed"
|
||||
run.Steps[i].Error = err.Error()
|
||||
run.Steps[i].ErrorKind = string(ai.ClassifyError(err))
|
||||
run.Status = "failed"
|
||||
if saveErr := f.save(ctx, run); saveErr != nil {
|
||||
spanErr = saveErr
|
||||
@@ -474,40 +512,65 @@ func (f *Flow) runFrom(ctx context.Context, run Run) (Run, error) {
|
||||
// runStep runs one step, retrying on error up to the resolved retry count.
|
||||
// A step with no Run function is a configuration error, and a canceled run
|
||||
// stops retrying immediately rather than burning the rest of its budget.
|
||||
func (f *Flow) runStep(ctx context.Context, step Step, in State) (State, int, error) {
|
||||
func (f *Flow) runStep(ctx context.Context, step Step, in State) (State, int, Verification, error) {
|
||||
if step.Run == nil {
|
||||
return in, 0, fmt.Errorf("flow: step %q has no Run function", step.Name)
|
||||
return in, 0, Verification{}, fmt.Errorf("flow: step %q has no Run function", step.Name)
|
||||
}
|
||||
retries := f.opts.Retry
|
||||
if step.Retry > 0 {
|
||||
retries = step.Retry
|
||||
}
|
||||
var lastErr error
|
||||
var lastVerification Verification
|
||||
var feedback string
|
||||
for attempt := 1; attempt <= retries+1; attempt++ {
|
||||
// Stop the moment the run's context is canceled or its deadline
|
||||
// passes — a canceled run shouldn't keep retrying, and the context
|
||||
// error is surfaced so callers can detect cancellation upstream.
|
||||
if err := ctx.Err(); err != nil {
|
||||
return in, attempt - 1, err
|
||||
return in, attempt - 1, lastVerification, err
|
||||
}
|
||||
attemptCtx := ctx
|
||||
if info, ok := ai.RunInfoFrom(ctx); ok {
|
||||
info.Step = step.Name
|
||||
ctx = ai.WithRunInfo(ctx, info)
|
||||
info.VerificationFeedback = feedback
|
||||
attemptCtx = ai.WithRunInfo(ctx, info)
|
||||
}
|
||||
out, err := step.Run(attemptCtx, in)
|
||||
if err == nil && step.Verify != nil {
|
||||
lastVerification, err = step.Verify(attemptCtx, out)
|
||||
if err == nil && !lastVerification.Passed {
|
||||
err = &VerificationError{Step: step.Name, Feedback: lastVerification.Feedback}
|
||||
}
|
||||
}
|
||||
out, err := step.Run(ctx, in)
|
||||
if err == nil {
|
||||
return out, attempt, nil
|
||||
return out, attempt, lastVerification, nil
|
||||
}
|
||||
lastErr = err
|
||||
if verr, ok := err.(*VerificationError); ok {
|
||||
feedback = verr.Feedback
|
||||
}
|
||||
if attempt <= retries && f.opts.RetryBackoff > 0 {
|
||||
select {
|
||||
case <-time.After(f.opts.RetryBackoff):
|
||||
case <-ctx.Done():
|
||||
return in, attempt, ctx.Err()
|
||||
return in, attempt, lastVerification, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
return in, retries + 1, lastErr
|
||||
return in, retries + 1, lastVerification, lastErr
|
||||
}
|
||||
|
||||
func applyVerificationRecord(record *StepRecord, verification Verification) {
|
||||
if verification.Passed {
|
||||
record.VerificationStatus = "passed"
|
||||
}
|
||||
if verification.Feedback != "" {
|
||||
record.VerificationNote = truncate(verification.Feedback, 200)
|
||||
if !verification.Passed {
|
||||
record.VerificationStatus = "failed"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Flow) save(ctx context.Context, run Run) error {
|
||||
@@ -555,6 +618,7 @@ func resultFromRun(trigger string, run Run) Result {
|
||||
r.ToolCalls = append(r.ToolCalls, s.Name+":"+s.Status)
|
||||
if s.Error != "" {
|
||||
r.Error = s.Error
|
||||
r.ErrorKind = s.ErrorKind
|
||||
}
|
||||
}
|
||||
if run.Status == "done" {
|
||||
|
||||
@@ -548,3 +548,37 @@ func TestStateSetScan(t *testing.T) {
|
||||
t.Errorf("round-trip failed: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlowFailureRecordsErrorKind(t *testing.T) {
|
||||
cp := StoreCheckpoint(store.NewMemoryStore(), "failure-kind")
|
||||
f := New("failure-kind",
|
||||
WithCheckpoint(cp),
|
||||
Steps(Step{Name: "limited", Run: func(_ context.Context, in State) (State, error) {
|
||||
return in, errors.New("rate limit exceeded")
|
||||
}}),
|
||||
)
|
||||
|
||||
err := f.Execute(context.Background(), "payload")
|
||||
if err == nil {
|
||||
t.Fatal("Execute error = nil, want failure")
|
||||
}
|
||||
|
||||
runs, listErr := cp.List(context.Background())
|
||||
if listErr != nil {
|
||||
t.Fatalf("List: %v", listErr)
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("runs = %d, want 1", len(runs))
|
||||
}
|
||||
if got := runs[0].Steps[0].ErrorKind; got != string(ai.ErrorKindRateLimited) {
|
||||
t.Fatalf("step error kind = %q, want %q", got, ai.ErrorKindRateLimited)
|
||||
}
|
||||
|
||||
results := f.Results()
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("results = %d, want 1", len(results))
|
||||
}
|
||||
if got := results[0].ErrorKind; got != string(ai.ErrorKindRateLimited) {
|
||||
t.Fatalf("result error kind = %q, want %q", got, ai.ErrorKindRateLimited)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
|
||||
func TestFlowStepVerificationRetriesWithFeedback(t *testing.T) {
|
||||
var attempts int
|
||||
var feedback []string
|
||||
step := Step{
|
||||
Name: "draft",
|
||||
Retry: 1,
|
||||
Run: func(ctx context.Context, in State) (State, error) {
|
||||
attempts++
|
||||
info, ok := ai.RunInfoFrom(ctx)
|
||||
if !ok {
|
||||
t.Fatal("RunInfo missing from verified step")
|
||||
}
|
||||
feedback = append(feedback, info.VerificationFeedback)
|
||||
if info.VerificationFeedback == "add evidence" {
|
||||
in.Data = []byte("answer with evidence")
|
||||
} else {
|
||||
in.Data = []byte("answer")
|
||||
}
|
||||
return in, nil
|
||||
},
|
||||
Verify: func(ctx context.Context, out State) (Verification, error) {
|
||||
if out.String() == "answer with evidence" {
|
||||
return Verification{Passed: true, Feedback: "meets rubric"}, nil
|
||||
}
|
||||
return Verification{Feedback: "add evidence"}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cp := StoreCheckpoint(store.NewMemoryStore(), "verified")
|
||||
f := New("verified", WithCheckpoint(cp), Steps(step))
|
||||
if err := f.Execute(context.Background(), "question"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("attempts = %d, want 2", attempts)
|
||||
}
|
||||
if len(feedback) != 2 || feedback[0] != "" || feedback[1] != "add evidence" {
|
||||
t.Fatalf("feedback = %#v, want empty then verifier feedback", feedback)
|
||||
}
|
||||
runs, err := cp.List(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("runs = %d, want 1", len(runs))
|
||||
}
|
||||
stepRecord := runs[0].Steps[0]
|
||||
if stepRecord.Status != "done" || stepRecord.Attempts != 2 || stepRecord.VerificationStatus != "passed" || stepRecord.VerificationNote != "meets rubric" {
|
||||
t.Fatalf("step record = %#v", stepRecord)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlowStepVerificationFailureIsCheckpointed(t *testing.T) {
|
||||
step := Step{
|
||||
Name: "grade",
|
||||
Run: func(ctx context.Context, in State) (State, error) {
|
||||
in.Data = []byte("bad")
|
||||
return in, nil
|
||||
},
|
||||
Verify: func(ctx context.Context, out State) (Verification, error) {
|
||||
return Verification{Feedback: "missing citation"}, nil
|
||||
},
|
||||
}
|
||||
|
||||
cp := StoreCheckpoint(store.NewMemoryStore(), "verified-fail")
|
||||
f := New("verified-fail", WithCheckpoint(cp), Steps(step))
|
||||
err := f.Execute(context.Background(), "question")
|
||||
if err == nil {
|
||||
t.Fatal("Execute succeeded, want verification failure")
|
||||
}
|
||||
var verr *VerificationError
|
||||
if !errors.As(err, &verr) {
|
||||
t.Fatalf("error = %T %v, want VerificationError", err, err)
|
||||
}
|
||||
if verr.Feedback != "missing citation" {
|
||||
t.Fatalf("feedback = %q, want missing citation", verr.Feedback)
|
||||
}
|
||||
runs, listErr := cp.List(context.Background())
|
||||
if listErr != nil {
|
||||
t.Fatal(listErr)
|
||||
}
|
||||
if len(runs) != 1 {
|
||||
t.Fatalf("runs = %d, want 1", len(runs))
|
||||
}
|
||||
stepRecord := runs[0].Steps[0]
|
||||
if runs[0].Status != "failed" || stepRecord.VerificationStatus != "failed" || stepRecord.VerificationNote != "missing citation" {
|
||||
t.Fatalf("run = %#v step = %#v", runs[0], stepRecord)
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/ai"
|
||||
)
|
||||
|
||||
// Grader checks a step output against a rubric. It returns pass=true when the
|
||||
// output is acceptable; otherwise feedback should explain what the next attempt
|
||||
// should fix.
|
||||
type Grader func(ctx context.Context, out State) (pass bool, feedback string, err error)
|
||||
|
||||
// VerifyOptions configure Verify.
|
||||
type VerifyOptions struct {
|
||||
// MaxAttempts bounds how many times the body can run. Default 2.
|
||||
MaxAttempts int
|
||||
// Backoff waits between failed grades. Zero means retry immediately.
|
||||
Backoff time.Duration
|
||||
// FeedbackField is the JSON field used to thread grader feedback into the
|
||||
// next attempt's input. Default "feedback".
|
||||
FeedbackField string
|
||||
}
|
||||
|
||||
// VerifyOption configures Verify.
|
||||
type VerifyOption func(*VerifyOptions)
|
||||
|
||||
// VerifyMaxAttempts sets the total attempt budget for Verify. Values <= 0 use
|
||||
// the default of 2.
|
||||
func VerifyMaxAttempts(n int) VerifyOption { return func(o *VerifyOptions) { o.MaxAttempts = n } }
|
||||
|
||||
// VerifyBackoff sets the delay between failed verification attempts.
|
||||
func VerifyBackoff(d time.Duration) VerifyOption { return func(o *VerifyOptions) { o.Backoff = d } }
|
||||
|
||||
// VerifyFeedbackField sets the JSON field used to pass grader feedback to the
|
||||
// next body attempt. Empty values use "feedback".
|
||||
func VerifyFeedbackField(field string) VerifyOption {
|
||||
return func(o *VerifyOptions) { o.FeedbackField = field }
|
||||
}
|
||||
|
||||
// Verify runs body, grades its output, and retries with grader feedback threaded
|
||||
// into the next input until the grader passes or MaxAttempts is exhausted. It is
|
||||
// a StepFunc, so it composes directly as Step.Run with Loop, LLM, Call, Agent, or
|
||||
// any code-defined step.
|
||||
//
|
||||
// On a failed grade, Verify adds the feedback to the next attempt's input as a
|
||||
// JSON field named "feedback" (or VerifyFeedbackField). When all attempts fail,
|
||||
// it returns the last output without error, annotated with verification fields so
|
||||
// the run can keep the bounded failure outcome in its state:
|
||||
// "verification_passed": false, "verification_feedback", and
|
||||
// "verification_attempts".
|
||||
func Verify(body StepFunc, grader Grader, opts ...VerifyOption) StepFunc {
|
||||
o := VerifyOptions{MaxAttempts: 2, FeedbackField: "feedback"}
|
||||
for _, op := range opts {
|
||||
op(&o)
|
||||
}
|
||||
if o.MaxAttempts <= 0 {
|
||||
o.MaxAttempts = 2
|
||||
}
|
||||
if o.FeedbackField == "" {
|
||||
o.FeedbackField = "feedback"
|
||||
}
|
||||
return func(ctx context.Context, in State) (State, error) {
|
||||
if body == nil {
|
||||
return in, fmt.Errorf("flow: Verify requires a body step")
|
||||
}
|
||||
if grader == nil {
|
||||
return in, fmt.Errorf("flow: Verify requires a grader")
|
||||
}
|
||||
cur := in
|
||||
last := in
|
||||
feedback := ""
|
||||
for attempt := 1; attempt <= o.MaxAttempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return last, err
|
||||
}
|
||||
if feedback != "" {
|
||||
var err error
|
||||
cur, err = stateWithField(cur, o.FeedbackField, feedback)
|
||||
if err != nil {
|
||||
return last, err
|
||||
}
|
||||
}
|
||||
out, err := body(ctx, cur)
|
||||
if err != nil {
|
||||
return last, fmt.Errorf("verify attempt %d: %w", attempt, err)
|
||||
}
|
||||
last = out
|
||||
pass, fb, err := grader(ctx, out)
|
||||
if err != nil {
|
||||
return last, fmt.Errorf("verify grade attempt %d: %w", attempt, err)
|
||||
}
|
||||
if pass {
|
||||
return stateWithVerification(out, true, fb, attempt)
|
||||
}
|
||||
feedback = fb
|
||||
cur = in
|
||||
if attempt < o.MaxAttempts && o.Backoff > 0 {
|
||||
select {
|
||||
case <-time.After(o.Backoff):
|
||||
case <-ctx.Done():
|
||||
return last, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
return stateWithVerification(last, false, feedback, o.MaxAttempts)
|
||||
}
|
||||
}
|
||||
|
||||
// LLMGrader returns a grader that asks the flow model to judge the latest output
|
||||
// against rubric. The model should answer with pass/fail plus short feedback.
|
||||
// It reuses the flow's configured model, so it must run inside a flow.
|
||||
func LLMGrader(rubric string) Grader {
|
||||
return func(ctx context.Context, out State) (bool, string, error) {
|
||||
d := depsFrom(ctx)
|
||||
if d == nil || d.model == nil {
|
||||
return false, "", fmt.Errorf("flow: LLMGrader requires a flow model (set Provider/APIKey)")
|
||||
}
|
||||
prompt := fmt.Sprintf("Grade the latest result against this rubric:\n%s\n\nLatest result:\n%s\n\nAnswer with PASS or FAIL on the first line, followed by one short feedback sentence.", rubric, out.String())
|
||||
resp, err := d.model.Generate(ctx, &ai.Request{Prompt: prompt})
|
||||
if err != nil {
|
||||
return false, "", err
|
||||
}
|
||||
reply := resp.Answer
|
||||
if reply == "" {
|
||||
reply = resp.Reply
|
||||
}
|
||||
return parseGrade(reply)
|
||||
}
|
||||
}
|
||||
|
||||
func parseGrade(reply string) (bool, string, error) {
|
||||
text := strings.TrimSpace(reply)
|
||||
if text == "" {
|
||||
return false, "", fmt.Errorf("flow: LLMGrader returned an empty grade")
|
||||
}
|
||||
lines := strings.SplitN(text, "\n", 2)
|
||||
first := strings.ToLower(strings.TrimSpace(lines[0]))
|
||||
feedback := ""
|
||||
if len(lines) > 1 {
|
||||
feedback = strings.TrimSpace(lines[1])
|
||||
}
|
||||
pass := strings.HasPrefix(first, "pass") || isAffirmative(first)
|
||||
if !pass && feedback == "" {
|
||||
feedback = text
|
||||
}
|
||||
return pass, feedback, nil
|
||||
}
|
||||
|
||||
func stateWithField(s State, field, value string) (State, error) {
|
||||
var obj map[string]any
|
||||
if len(s.Data) > 0 && json.Unmarshal(s.Data, &obj) == nil && obj != nil {
|
||||
obj[field] = value
|
||||
return stateWithObject(s, obj)
|
||||
}
|
||||
obj = map[string]any{field: value}
|
||||
if len(s.Data) > 0 {
|
||||
obj["data"] = s.String()
|
||||
}
|
||||
return stateWithObject(s, obj)
|
||||
}
|
||||
|
||||
func stateWithVerification(s State, passed bool, feedback string, attempts int) (State, error) {
|
||||
var obj map[string]any
|
||||
if len(s.Data) > 0 && json.Unmarshal(s.Data, &obj) == nil && obj != nil {
|
||||
obj["verification_passed"] = passed
|
||||
obj["verification_feedback"] = feedback
|
||||
obj["verification_attempts"] = attempts
|
||||
return stateWithObject(s, obj)
|
||||
}
|
||||
obj = map[string]any{
|
||||
"data": s.String(),
|
||||
"verification_passed": passed,
|
||||
"verification_feedback": feedback,
|
||||
"verification_attempts": attempts,
|
||||
}
|
||||
return stateWithObject(s, obj)
|
||||
}
|
||||
|
||||
func stateWithObject(s State, obj map[string]any) (State, error) {
|
||||
b, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
s.Data = b
|
||||
return s, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package flow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVerifyPassesFirstTry(t *testing.T) {
|
||||
attempts := 0
|
||||
step := Verify(func(_ context.Context, in State) (State, error) {
|
||||
attempts++
|
||||
in.Data = []byte(`{"answer":"ok"}`)
|
||||
return in, nil
|
||||
}, func(context.Context, State) (bool, string, error) {
|
||||
return true, "looks good", nil
|
||||
}, VerifyMaxAttempts(3))
|
||||
|
||||
out, err := step(context.Background(), State{})
|
||||
if err != nil {
|
||||
t.Fatalf("Verify returned error: %v", err)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Fatalf("body attempts = %d, want 1", attempts)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := out.Scan(&got); err != nil {
|
||||
t.Fatalf("scan output: %v", err)
|
||||
}
|
||||
if got["verification_passed"] != true {
|
||||
t.Fatalf("verification_passed = %v, want true", got["verification_passed"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRetriesWithFeedback(t *testing.T) {
|
||||
attempts := 0
|
||||
var secondInput map[string]string
|
||||
step := Verify(func(_ context.Context, in State) (State, error) {
|
||||
attempts++
|
||||
if attempts == 2 {
|
||||
if err := in.Scan(&secondInput); err != nil {
|
||||
t.Fatalf("scan second input: %v", err)
|
||||
}
|
||||
}
|
||||
in.Data = []byte(`{"answer":"draft"}`)
|
||||
return in, nil
|
||||
}, func(_ context.Context, _ State) (bool, string, error) {
|
||||
return attempts >= 2, "include citations", nil
|
||||
}, VerifyMaxAttempts(3))
|
||||
|
||||
out, err := step(context.Background(), State{Data: []byte(`{"topic":"agents"}`)})
|
||||
if err != nil {
|
||||
t.Fatalf("Verify returned error: %v", err)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("body attempts = %d, want 2", attempts)
|
||||
}
|
||||
if secondInput["feedback"] != "include citations" {
|
||||
t.Fatalf("feedback = %q, want include citations", secondInput["feedback"])
|
||||
}
|
||||
if !strings.Contains(out.String(), `"verification_passed":true`) {
|
||||
t.Fatalf("output missing successful verification annotation: %s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExhaustsAttemptsReturnsLastOutput(t *testing.T) {
|
||||
attempts := 0
|
||||
step := Verify(func(_ context.Context, in State) (State, error) {
|
||||
attempts++
|
||||
in.Data = []byte(`{"answer":"still wrong"}`)
|
||||
return in, nil
|
||||
}, func(context.Context, State) (bool, string, error) {
|
||||
return false, "try again", nil
|
||||
}, VerifyMaxAttempts(2))
|
||||
|
||||
out, err := step(context.Background(), State{})
|
||||
if err != nil {
|
||||
t.Fatalf("Verify returned error: %v", err)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("body attempts = %d, want 2", attempts)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := out.Scan(&got); err != nil {
|
||||
t.Fatalf("scan output: %v", err)
|
||||
}
|
||||
if got["verification_passed"] != false {
|
||||
t.Fatalf("verification_passed = %v, want false", got["verification_passed"])
|
||||
}
|
||||
if got["verification_feedback"] != "try again" {
|
||||
t.Fatalf("verification_feedback = %v, want try again", got["verification_feedback"])
|
||||
}
|
||||
if got["verification_attempts"] != float64(2) {
|
||||
t.Fatalf("verification_attempts = %v, want 2", got["verification_attempts"])
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -180,6 +180,8 @@ type Provider struct {
|
||||
type Capabilities struct {
|
||||
Streaming bool `json:"streaming"`
|
||||
PushNotifications bool `json:"pushNotifications"`
|
||||
TaskResubscribe bool `json:"taskResubscribe"`
|
||||
InputRequired bool `json:"inputRequired"`
|
||||
}
|
||||
|
||||
// Skill is a capability advertised on the Agent Card.
|
||||
@@ -349,7 +351,7 @@ func Card(name, url, description string, services []string) AgentCard {
|
||||
URL: url,
|
||||
Version: "1.0.0",
|
||||
ProtocolVersion: protocolVersion,
|
||||
Capabilities: Capabilities{Streaming: true, PushNotifications: true},
|
||||
Capabilities: Capabilities{Streaming: true, PushNotifications: true, TaskResubscribe: true, InputRequired: true},
|
||||
DefaultInputModes: []string{"text/plain"},
|
||||
DefaultOutputModes: []string{"text/plain"},
|
||||
Skills: skills,
|
||||
|
||||
@@ -91,6 +91,9 @@ func TestAgentCardFromRegistry(t *testing.T) {
|
||||
if card.ProtocolVersion == "" {
|
||||
t.Errorf("card missing protocolVersion: %+v", card)
|
||||
}
|
||||
if !card.Capabilities.TaskResubscribe || !card.Capabilities.InputRequired {
|
||||
t.Errorf("card capabilities = %+v, want task resubscribe and input-required advertised", card.Capabilities)
|
||||
}
|
||||
if got := skillIDs(card.Skills); strings.Join(got, ",") != "task,project" {
|
||||
t.Errorf("skill IDs = %v, want [task project]", got)
|
||||
}
|
||||
|
||||
+74
-1
@@ -1,11 +1,13 @@
|
||||
package a2a
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -135,6 +137,77 @@ func (c *Client) SendMessage(ctx context.Context, message Message) (*Task, error
|
||||
return &task, nil
|
||||
}
|
||||
|
||||
// Resubscribe reconnects to a retained or active task stream and returns task
|
||||
// snapshots as the remote agent emits updates. The returned channel is closed
|
||||
// when the task reaches a terminal state or ctx is canceled.
|
||||
func (c *Client) Resubscribe(ctx context.Context, taskID string) (<-chan Task, <-chan error) {
|
||||
tasks := make(chan Task, 8)
|
||||
errs := make(chan error, 1)
|
||||
go func() {
|
||||
defer close(tasks)
|
||||
defer close(errs)
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"jsonrpc": "2.0",
|
||||
"id": uuid.New().String(),
|
||||
"method": "tasks/resubscribe",
|
||||
"params": getParams{ID: taskID},
|
||||
})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
errs <- fmt.Errorf("tasks/resubscribe: status %d", resp.StatusCode)
|
||||
return
|
||||
}
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if !strings.HasPrefix(line, "data:") {
|
||||
continue
|
||||
}
|
||||
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
if payload == "" {
|
||||
continue
|
||||
}
|
||||
var out struct {
|
||||
Result Task `json:"result"`
|
||||
Error *rpcError `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(payload), &out); err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
if out.Error != nil {
|
||||
errs <- fmt.Errorf("a2a tasks/resubscribe: %s (%d)", out.Error.Message, out.Error.Code)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
errs <- ctx.Err()
|
||||
return
|
||||
case tasks <- out.Result:
|
||||
}
|
||||
if terminal(out.Result.Status.State) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
errs <- err
|
||||
}
|
||||
}()
|
||||
return tasks, errs
|
||||
}
|
||||
|
||||
// SetPushNotificationConfig asks the remote agent to POST updates for taskID to cfg.URL.
|
||||
func (c *Client) SetPushNotificationConfig(ctx context.Context, taskID string, cfg PushNotificationConfig) error {
|
||||
_, err := c.call(ctx, "tasks/pushNotificationConfig/set", pushConfigParams{
|
||||
@@ -193,7 +266,7 @@ func (c *Client) call(ctx context.Context, method string, params any) (json.RawM
|
||||
|
||||
func terminal(state string) bool {
|
||||
switch state {
|
||||
case "completed", "failed", "canceled", "rejected":
|
||||
case "completed", "failed", "canceled", "rejected", "input-required":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -3,8 +3,10 @@ package a2a
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -110,3 +112,57 @@ func TestClientContinuesTaskAndConfiguresPush(t *testing.T) {
|
||||
t.Fatal("timed out waiting for push update")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientResubscribeStreamsRetainedAndLiveTask(t *testing.T) {
|
||||
d := newDispatcher()
|
||||
initial := &Task{ID: "task-1", ContextID: "ctx-1", Kind: "task", Status: TaskStatus{State: stateWorking, Timestamp: time.Now().UTC().Format(time.RFC3339)}}
|
||||
d.store(initial)
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
d.serve(w, r, func(context.Context, string) (string, error) { return "", nil })
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
tasks, errs := NewClient(ts.URL).Resubscribe(ctx, initial.ID)
|
||||
|
||||
first := <-tasks
|
||||
if first.ID != initial.ID || first.Status.State != stateWorking {
|
||||
t.Fatalf("first resubscribe task = %+v, want retained working task", first)
|
||||
}
|
||||
final := &Task{ID: initial.ID, ContextID: initial.ContextID, Kind: "task", Status: TaskStatus{State: stateCompleted, Timestamp: time.Now().UTC().Format(time.RFC3339)}, Artifacts: []Artifact{textArtifact("done")}}
|
||||
d.store(final)
|
||||
second := <-tasks
|
||||
if second.ID != final.ID || second.Status.State != stateCompleted || textOf(second.Artifacts[0].Parts) != "done" {
|
||||
t.Fatalf("second resubscribe task = %+v, want live completed task", second)
|
||||
}
|
||||
if _, ok := <-tasks; ok {
|
||||
t.Fatal("resubscribe task channel stayed open after terminal update")
|
||||
}
|
||||
select {
|
||||
case err := <-errs:
|
||||
if err != nil {
|
||||
t.Fatalf("resubscribe error = %v", err)
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSendMessageReturnsInputRequiredTask(t *testing.T) {
|
||||
card := Card("solo", "http://localhost:4000", "", []string{"task"})
|
||||
h := NewAgentHandler(card, func(context.Context, string) (string, error) {
|
||||
return "", errors.New("input-required: provide approval code")
|
||||
})
|
||||
ts := httptest.NewServer(h)
|
||||
defer ts.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
task, err := NewClient(ts.URL).SendMessage(ctx, Message{Parts: []Part{{Kind: "text", Text: "approve?"}}})
|
||||
if err != nil {
|
||||
t.Fatalf("SendMessage: %v", err)
|
||||
}
|
||||
if task.Status.State != stateInputRequired || !strings.Contains(textOf(task.Artifacts[0].Parts), "provide approval code") {
|
||||
t.Fatalf("task = %+v, want input-required handoff", task)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,18 @@ consistent across providers.
|
||||
The companion `TestAgentProviderConformanceFakeError` keeps provider error
|
||||
propagation covered locally without relying on external credentials.
|
||||
|
||||
## Local no-secret conformance
|
||||
|
||||
Use `make provider-conformance-mock` to run the same provider conformance harness
|
||||
through the deterministic mock provider. That target requires no API keys and is
|
||||
what `make harness` delegates to after the 0→1 and 0→hero scenarios, so every PR
|
||||
continues to exercise the provider-facing agent/tool contract without spending
|
||||
live model credits.
|
||||
|
||||
Use `make provider-conformance` when you want the live-provider sweep: providers
|
||||
without keys are skipped, and configured providers must satisfy the same harness
|
||||
contract.
|
||||
|
||||
## Scheduled CI
|
||||
|
||||
The daily/manual `Harness (E2E)` workflow runs the same matrix with
|
||||
|
||||
@@ -10,6 +10,36 @@ and can stop or revert anything at any time.
|
||||
> **services → agents → workflows**. Judge each change against it — work that
|
||||
> doesn't move toward that lifecycle isn't an improvement, however clean.
|
||||
|
||||
## The pipeline (planner → generator → evaluator)
|
||||
|
||||
The development process is an operational instance of the long-running-agent
|
||||
harness pattern ([Anthropic on harness design](https://www.anthropic.com/engineering/harness-design-long-running-apps)) —
|
||||
a planner, a generator, and a *separate* evaluator — distributed across GitHub
|
||||
Actions instead of subagents. Each role is a workflow:
|
||||
|
||||
| Role | Workflow (action name) | What it does |
|
||||
|------|------------------------|--------------|
|
||||
| **Planner** | `loop-planner.yml` — *Loop: Planner* | Tracks live state, prioritizes the roadmap + an internal scan, and maintains the ranked queue in [`.github/loop/PRIORITIES.md`](../../.github/loop/PRIORITIES.md). Decides *what*. |
|
||||
| **Generator** | `loop-builder.yml` — *Loop: Builder (Generator)* | Builds the top open queue item as a single-concern PR (via Codex) and self-merges on green CI. Does the work. |
|
||||
| **Evaluator** | `harness.yml` — *Harness (E2E)*, plus the CI gate (`tests.yaml`, `lint.yaml`) | Grades every change: the mock harness + unit/lint on each push/PR, and real-model conformance hourly. A *separate* grader — never the generator judging itself. |
|
||||
| **Evaluator → feedback** | `loop-triage.yml` — *Loop: Triage (Evaluator feedback)* | When a gate workflow (Lint, Run Tests, or the harness) fails on a non-PR run, root-causes, dedupes, and files scoped fix issues back into the planner's queue. The hill-climbing feedback path. |
|
||||
| **Coherence** | `loop-coherence.yml` — *Loop: Coherence* | Keeps README/website/docs/blog aligned with the North Star, keeps `CHANGELOG.md` living (reconciling `[Unreleased]` against merged PRs and rolling it into version headings as tags cut), and drafts the changelog blog post. |
|
||||
| **Release** | `loop-release.yml` — *Loop: Release (daily patch)* | Cuts a daily patch tag when master has new commits, so the *installable* framework tracks the loop's improvements (triggers `release.yml`/goreleaser). Minor/major bumps stay with the human. |
|
||||
|
||||
Generation is separated from evaluation on purpose: an agent grading its own work
|
||||
reliably over-rates it, so **CI and the harness — not the builder — are the gate**.
|
||||
The human sets direction and owns the calls that need taste (see Guardrails).
|
||||
|
||||
> **Go Micro dogfoods its own tool.** These `.github/workflows/loop-*.yml` files
|
||||
> are generated by [`micro loop`](../../cmd/micro/loop) (`micro loop init --roles all`).
|
||||
> The workflows are the *mechanism*; each role's instruction is the editable
|
||||
> *policy* in [`.github/loop/prompts/`](../../.github/loop/prompts), and the
|
||||
> direction/queue live in [`.github/loop/NORTH_STAR.md`](../../.github/loop/NORTH_STAR.md)
|
||||
> and [`.github/loop/PRIORITIES.md`](../../.github/loop/PRIORITIES.md). To change
|
||||
> what a role does, edit its prompt — not the YAML. Re-run `micro loop init
|
||||
> --roles all --force` to regenerate the workflow mechanics (it won't clobber the
|
||||
> North Star, queue, or prompts).
|
||||
|
||||
## Autonomy
|
||||
|
||||
Full autonomy, **no approval gates**. Each increment: Claude Code picks the work,
|
||||
@@ -72,7 +102,7 @@ Grounded in real signal, never speculative rewrites. Each cycle draws from:
|
||||
tracking issue for each increment and dispatches Codex there. It needs a
|
||||
`CODEX_TRIGGER_TOKEN` repo secret from a user account Codex responds to;
|
||||
without that secret the workflow deliberately no-ops to avoid ignored bot
|
||||
comments. See `.github/workflows/continuous-improvement.yml` and the mechanics
|
||||
comments. See `.github/workflows/loop-builder.yml` and the mechanics
|
||||
below.
|
||||
|
||||
## How the durable loop works (mechanics)
|
||||
@@ -127,18 +157,25 @@ The hourly loop ships increments; two periodic passes keep the *whole* heading i
|
||||
the right direction. Both use the same mechanism (fresh issue → `@codex` →
|
||||
output) but produce direction and coherence, not just code.
|
||||
|
||||
- **DevRel — daily** (`.github/workflows/devrel-review.yml`). Audits the public
|
||||
- **Coherence (DevRel) — daily** (`.github/workflows/loop-coherence.yml`, prompt `.github/loop/prompts/coherence.md`). Audits the public
|
||||
surface (README, website landing + docs, blog) for coherence with the North
|
||||
Star, README crispness, and blog-worthy material. **Autonomy boundary:** safe
|
||||
factual-alignment and crispness fixes auto-merge like any increment;
|
||||
brand/positioning copy and blog drafts are *surfaced in a report* for the
|
||||
human, never auto-merged.
|
||||
- **Architect — continuous (hourly)** (`.github/workflows/architecture-review.yml`).
|
||||
Star, README crispness, and blog-worthy material. It also keeps `CHANGELOG.md`
|
||||
living: each run reconciles the `[Unreleased]` section against the PRs that
|
||||
actually merged (Keep-a-Changelog format, user-facing entries only — internal
|
||||
loop/CI churn is skipped), and rolls `[Unreleased]` into a dated version
|
||||
heading whenever a new `v6.MINOR.PATCH` tag has been cut (by `loop-release`).
|
||||
When enough user-facing work has accumulated (roughly weekly, not a near-empty
|
||||
post every day) it also drafts a "what's new" changelog blog post narrating it.
|
||||
**Autonomy boundary:** safe factual-alignment and crispness fixes — *including
|
||||
the `CHANGELOG.md` upkeep* — auto-merge like any increment; brand/positioning
|
||||
copy and the changelog blog post are opened as a PR (or surfaced in the report)
|
||||
and left for the human to review/merge — blog voice stays with the human.
|
||||
- **Planner (Architect) — continuous (hourly)** (`.github/workflows/loop-planner.yml`, prompt `.github/loop/prompts/planner.md`).
|
||||
The *founder lens*, running alongside the builders. Each run it **tracks live
|
||||
state** (what just merged, what's in flight), **prioritizes the roadmap**
|
||||
(`ROADMAP.md`, Now → Next → Later) against an internal scan (lifecycle gaps, API
|
||||
coherence and seams, dev-UX friction, missing pieces, drift/realignment), and
|
||||
**maintains the ranked queue** in [`PRIORITIES.md`](PRIORITIES.md) — re-ranking
|
||||
**maintains the ranked queue** in [`.github/loop/PRIORITIES.md`](../../.github/loop/PRIORITIES.md) — re-ranking
|
||||
to reflect reality, backing each top item with a scoped issue, and posting an
|
||||
assessment. It runs at `:59`, just before the `:29` increment, so it
|
||||
re-prioritizes and *then* the loop builds the new top. **Its output is the
|
||||
@@ -154,6 +191,22 @@ roadmap-driven by default, not a fresh guess every hour. Cadence is tunable in e
|
||||
workflow's `cron`; the human can reorder `PRIORITIES.md` or its issues at any time
|
||||
to redirect. Codex is serial, so these passes queue behind any in-flight increment.
|
||||
|
||||
## Failure triage (the feedback loop)
|
||||
|
||||
The loop also closes on its own failures. `.github/workflows/loop-triage.yml`
|
||||
fires when a gate workflow — **Lint**, **Run Tests**, or the provider-conformance
|
||||
**Harness (E2E)** — finishes with `conclusion: failure` on a non-PR run (so a red
|
||||
lint or test on `master`, not just a harness failure, becomes a fix issue). It
|
||||
dispatches Codex to **triage** the failing run: read the logs, root-cause each
|
||||
distinct failure, **dedupe** against open issues (comment "recurred" rather than
|
||||
filing a duplicate), and file a scoped `codex`/`enhancement` issue for each genuine,
|
||||
self-contained defect — which the increment loop then builds and the next run
|
||||
verifies. Genuine transient flakes (live-model latency, provider outages) are
|
||||
ignored; anything needing a breaking or architectural change is escalated as
|
||||
`needs-human` instead of auto-built. This is
|
||||
the hill-climbing layer: CI/harness failures become fixes with no human in the
|
||||
middle, short of a decision that's genuinely the human's.
|
||||
|
||||
## Stop / redirect
|
||||
|
||||
- In-session: `CronDelete <id>` (or end the session).
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// A2A stream fallback harness.
|
||||
//
|
||||
// It exercises the gateway boundary that fronts an agent over A2A. The agent is
|
||||
// configured with tools and memory, but its model streaming path deliberately
|
||||
// reports ai.ErrStreamingUnsupported; the A2A gateway must fall back to the
|
||||
// normal Ask path and still complete the same tool-calling run.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/agent"
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/gateway/a2a"
|
||||
"go-micro.dev/v6/internal/harness/harnessutil"
|
||||
"go-micro.dev/v6/registry"
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
|
||||
type mockModel struct{ opts ai.Options }
|
||||
|
||||
func newMock(opts ...ai.Option) ai.Model {
|
||||
m := &mockModel{}
|
||||
_ = m.Init(opts...)
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *mockModel) Init(opts ...ai.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m *mockModel) Options() ai.Options { return m.opts }
|
||||
func (m *mockModel) String() string { return "mock" }
|
||||
func (m *mockModel) Stream(context.Context, *ai.Request, ...ai.GenerateOption) (ai.Stream, error) {
|
||||
return nil, ai.ErrStreamingUnsupported
|
||||
}
|
||||
func (m *mockModel) Generate(ctx context.Context, req *ai.Request, _ ...ai.GenerateOption) (*ai.Response, error) {
|
||||
if req.Prompt == "" {
|
||||
return nil, errors.New("missing prompt")
|
||||
}
|
||||
if len(req.Messages) == 0 || req.Messages[len(req.Messages)-1].Role != "user" {
|
||||
return nil, fmt.Errorf("missing user history: %+v", req.Messages)
|
||||
}
|
||||
if len(req.Tools) == 0 || m.opts.ToolHandler == nil {
|
||||
return nil, errors.New("missing tools or tool handler")
|
||||
}
|
||||
res := m.opts.ToolHandler(ctx, ai.ToolCall{ID: "a2a-fallback-call", Name: "fallback_echo", Input: map[string]any{"value": "a2a-fallback"}})
|
||||
if res.Content == "" {
|
||||
return nil, errors.New("empty tool result")
|
||||
}
|
||||
return &ai.Response{Reply: "fallback completed", Answer: res.Content, ToolCalls: []ai.ToolCall{{ID: "a2a-fallback-call", Name: "fallback_echo", Input: map[string]any{"value": "a2a-fallback"}, Result: res.Content}}}, nil
|
||||
}
|
||||
|
||||
func providerKey(provider string) string {
|
||||
if v := os.Getenv("MICRO_AI_API_KEY"); v != "" {
|
||||
return v
|
||||
}
|
||||
env := map[string]string{
|
||||
"anthropic": "ANTHROPIC_API_KEY", "openai": "OPENAI_API_KEY",
|
||||
"gemini": "GEMINI_API_KEY", "groq": "GROQ_API_KEY", "mistral": "MISTRAL_API_KEY",
|
||||
"together": "TOGETHER_API_KEY", "atlascloud": "ATLASCLOUD_API_KEY",
|
||||
}[provider]
|
||||
return os.Getenv(env)
|
||||
}
|
||||
|
||||
func main() {
|
||||
provider := flag.String("provider", "mock", "LLM provider: mock (default), anthropic, openai, ...")
|
||||
flag.Parse()
|
||||
|
||||
apiKey := ""
|
||||
if *provider == "mock" {
|
||||
ai.Register("mock", newMock)
|
||||
} else {
|
||||
apiKey = providerKey(*provider)
|
||||
if apiKey == "" {
|
||||
fmt.Printf("no API key for provider %q — set MICRO_AI_API_KEY or the provider's key env\n", *provider)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("\n\033[1mA2A streaming fallback conformance (provider: %s)\033[0m\n", *provider)
|
||||
reg := registry.NewMemoryRegistry()
|
||||
st := store.NewMemoryStore()
|
||||
var sawTool, sawRunInfo bool
|
||||
agentOpts := []agent.Option{
|
||||
agent.Name("a2a-fallback"),
|
||||
agent.Provider(*provider),
|
||||
agent.APIKey(apiKey),
|
||||
agent.Prompt("Use fallback_echo exactly once with value a2a-fallback, then answer with the tool result."),
|
||||
agent.WithRegistry(reg),
|
||||
agent.WithStore(st),
|
||||
agent.WithMemory(agent.NewInMemory(8)),
|
||||
agent.ModelCallTimeout(45 * time.Second),
|
||||
agent.WithTool("fallback_echo", "Echo the A2A fallback marker.", map[string]any{
|
||||
"value": map[string]any{"type": "string", "description": "value to echo"},
|
||||
}, func(ctx context.Context, input map[string]any) (string, error) {
|
||||
sawTool = true
|
||||
info, ok := ai.RunInfoFrom(ctx)
|
||||
if !ok || info.RunID == "" || info.Agent != "a2a-fallback" {
|
||||
return "", fmt.Errorf("unexpected run info: %+v", info)
|
||||
}
|
||||
sawRunInfo = true
|
||||
if input["value"] != "a2a-fallback" {
|
||||
return "", fmt.Errorf("unexpected value %v", input["value"])
|
||||
}
|
||||
return `{"marker":"a2a-fallback-ok"}`, nil
|
||||
}),
|
||||
}
|
||||
agentOpts = append(agentOpts, harnessutil.AgentOptions(*provider)...)
|
||||
ag := agent.New(agentOpts...)
|
||||
|
||||
card := a2a.Card("a2a-fallback", "http://example.invalid/a2a-fallback", "", nil)
|
||||
handler := a2a.NewAgentStreamHandler(card, func(ctx context.Context, text string) (string, error) {
|
||||
resp, err := ag.Ask(ctx, text)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resp.Reply, nil
|
||||
}, ag.Stream)
|
||||
|
||||
body := []byte(`{"jsonrpc":"2.0","id":1,"method":"message/stream","params":{"message":{"role":"user","parts":[{"kind":"text","text":"Run the A2A fallback conformance check."}],"kind":"message"}}}`)
|
||||
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
res := rr.Result()
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
fmt.Fprintf(os.Stderr, "unexpected status %d: %s\n", res.StatusCode, b)
|
||||
os.Exit(1)
|
||||
}
|
||||
if ct := res.Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/event-stream") {
|
||||
fmt.Fprintf(os.Stderr, "content-type = %q, want text/event-stream\n", ct)
|
||||
os.Exit(1)
|
||||
}
|
||||
summary, err := readSSESummary(res.Body)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if summary.State != "completed" {
|
||||
fmt.Fprintf(os.Stderr, "stream final state = %q, want completed; payload: %s\n", summary.State, summary.Payload)
|
||||
os.Exit(1)
|
||||
}
|
||||
if !summary.HasArtifactText {
|
||||
fmt.Fprintf(os.Stderr, "stream completed without artifact text: %s\n", summary.Payload)
|
||||
os.Exit(1)
|
||||
}
|
||||
if !sawTool || !sawRunInfo {
|
||||
fmt.Fprintf(os.Stderr, "tool=%v runInfo=%v\n", sawTool, sawRunInfo)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println("\n\033[32m✓ A2A message/stream fell back to Ask and preserved tool/run metadata\033[0m")
|
||||
}
|
||||
|
||||
type streamSummary struct {
|
||||
Payload string
|
||||
State string
|
||||
HasArtifactText bool
|
||||
}
|
||||
|
||||
func readSSESummary(r io.Reader) (streamSummary, error) {
|
||||
scanner := bufio.NewScanner(r)
|
||||
var event strings.Builder
|
||||
var summary streamSummary
|
||||
seen := false
|
||||
flush := func() error {
|
||||
data := strings.TrimSpace(event.String())
|
||||
event.Reset()
|
||||
if data == "" {
|
||||
return nil
|
||||
}
|
||||
var envelope struct {
|
||||
Result struct {
|
||||
Status struct {
|
||||
State string `json:"state"`
|
||||
} `json:"status"`
|
||||
Artifacts []struct {
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"parts"`
|
||||
} `json:"artifacts"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &envelope); err != nil {
|
||||
return fmt.Errorf("SSE data event is not JSON: %s", data)
|
||||
}
|
||||
seen = true
|
||||
summary.Payload += data + "\n"
|
||||
if envelope.Result.Status.State != "" {
|
||||
summary.State = envelope.Result.Status.State
|
||||
}
|
||||
for _, artifact := range envelope.Result.Artifacts {
|
||||
for _, part := range artifact.Parts {
|
||||
if strings.TrimSpace(part.Text) != "" {
|
||||
summary.HasArtifactText = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if strings.TrimSpace(line) == "" {
|
||||
if err := flush(); err != nil {
|
||||
return streamSummary{}, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
data, ok := strings.CutPrefix(line, "data:")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if event.Len() > 0 {
|
||||
event.WriteByte('\n')
|
||||
}
|
||||
event.WriteString(strings.TrimSpace(data))
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return streamSummary{}, err
|
||||
}
|
||||
if err := flush(); err != nil {
|
||||
return streamSummary{}, err
|
||||
}
|
||||
if !seen {
|
||||
return streamSummary{}, errors.New("no SSE data received")
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadSSESummaryUsesCompletedTaskInvariants(t *testing.T) {
|
||||
summary, err := readSSESummary(strings.NewReader("data: {\"jsonrpc\":\"2.0\",\"result\":{\"status\":{\"state\":\"working\"}}}\n\n" +
|
||||
"data: {\"jsonrpc\":\"2.0\",\"result\":{\"status\":{\"state\":\"completed\"},\"artifacts\":[{\"parts\":[{\"kind\":\"text\",\"text\":\"provider-specific answer\"}]}]}}\n\n"))
|
||||
if err != nil {
|
||||
t.Fatalf("readSSESummary() error = %v", err)
|
||||
}
|
||||
if summary.State != "completed" {
|
||||
t.Fatalf("State = %q, want completed", summary.State)
|
||||
}
|
||||
if !summary.HasArtifactText {
|
||||
t.Fatal("HasArtifactText = false, want true")
|
||||
}
|
||||
if strings.Contains(summary.Payload, "a2a-fallback-ok") {
|
||||
t.Fatalf("test fixture should not rely on marker text: %s", summary.Payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadSSESummaryRejectsNonJSONData(t *testing.T) {
|
||||
_, err := readSSESummary(strings.NewReader("data: not-json\n\n"))
|
||||
if err == nil {
|
||||
t.Fatal("readSSESummary() error = nil, want non-JSON error")
|
||||
}
|
||||
}
|
||||
@@ -25,10 +25,9 @@ import (
|
||||
"go-micro.dev/v6/agent"
|
||||
"go-micro.dev/v6/ai"
|
||||
"go-micro.dev/v6/broker"
|
||||
"go-micro.dev/v6/client"
|
||||
"go-micro.dev/v6/flow"
|
||||
"go-micro.dev/v6/internal/harness/harnessutil"
|
||||
"go-micro.dev/v6/registry"
|
||||
"go-micro.dev/v6/selector"
|
||||
"go-micro.dev/v6/service"
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
@@ -203,8 +202,9 @@ func main() {
|
||||
fmt.Println("broker connect:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
cl := client.NewClient(client.Registry(reg), client.Selector(selector.NewSelector(selector.Registry(reg))))
|
||||
cl := harnessutil.Client(*provider, reg)
|
||||
mem := store.NewMemoryStore()
|
||||
liveAgentOpts := harnessutil.AgentOptions(*provider)
|
||||
|
||||
wsSvc := new(WorkspaceService)
|
||||
ws := service.New(service.Name("workspace"), service.Address("127.0.0.1:0"), service.Registry(reg), service.Client(cl))
|
||||
@@ -217,7 +217,7 @@ func main() {
|
||||
go nt.Run()
|
||||
|
||||
// The onboarder agent, registered so the flow can reach it over RPC.
|
||||
onboarder := agent.New(
|
||||
onboarderOpts := []agent.Option{
|
||||
agent.Name("onboarder"),
|
||||
agent.Address("127.0.0.1:0"),
|
||||
agent.Services("workspace", "notify"),
|
||||
@@ -225,7 +225,9 @@ func main() {
|
||||
agent.Provider(*provider),
|
||||
agent.APIKey(apiKey),
|
||||
agent.WithRegistry(reg), agent.WithClient(cl), agent.WithStore(mem),
|
||||
)
|
||||
}
|
||||
onboarderOpts = append(onboarderOpts, liveAgentOpts...)
|
||||
onboarder := agent.New(onboarderOpts...)
|
||||
go onboarder.Run()
|
||||
defer onboarder.Stop()
|
||||
|
||||
@@ -238,6 +240,7 @@ func main() {
|
||||
flow.Trigger("events.user.created"),
|
||||
flow.Agent("onboarder"),
|
||||
flow.Prompt("A new user signed up: {{.Data}}. Get them set up."),
|
||||
flow.Timeout(harnessutil.LiveTimeout(*provider)),
|
||||
)
|
||||
if err := f.Register(reg, br, cl); err != nil {
|
||||
fmt.Println("flow register:", err)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package harnessutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/agent"
|
||||
"go-micro.dev/v6/client"
|
||||
"go-micro.dev/v6/registry"
|
||||
"go-micro.dev/v6/selector"
|
||||
)
|
||||
|
||||
const (
|
||||
// LiveTimeoutEnv overrides the per-call deadline used by live-provider
|
||||
// harness runs. It intentionally does not affect deterministic mock runs.
|
||||
LiveTimeoutEnv = "GO_MICRO_HARNESS_LIVE_TIMEOUT"
|
||||
// DefaultLiveTimeout is generous enough for slow but correct hosted models
|
||||
// while still bounding genuinely stuck live conformance runs.
|
||||
DefaultLiveTimeout = 5 * time.Minute
|
||||
)
|
||||
|
||||
// LiveTimeout returns the harness per-call timeout for live providers. Mock runs
|
||||
// keep their historical fast defaults by returning zero.
|
||||
func LiveTimeout(provider string) time.Duration {
|
||||
if provider == "mock" {
|
||||
return 0
|
||||
}
|
||||
if raw := os.Getenv(LiveTimeoutEnv); raw != "" {
|
||||
d, err := time.ParseDuration(raw)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid %s=%q; using %s\n", LiveTimeoutEnv, raw, DefaultLiveTimeout)
|
||||
return DefaultLiveTimeout
|
||||
}
|
||||
return d
|
||||
}
|
||||
return DefaultLiveTimeout
|
||||
}
|
||||
|
||||
// Client returns an in-memory-registry client. Live provider harnesses get a
|
||||
// larger request timeout so an otherwise correct agent run is not cut off by the
|
||||
// default 30-second RPC deadline; mock runs are unchanged.
|
||||
func Client(provider string, reg registry.Registry) client.Client {
|
||||
opts := []client.Option{
|
||||
client.Registry(reg),
|
||||
client.Selector(selector.NewSelector(selector.Registry(reg))),
|
||||
}
|
||||
if d := LiveTimeout(provider); d > 0 {
|
||||
opts = append(opts, client.RequestTimeout(d))
|
||||
}
|
||||
return client.NewClient(opts...)
|
||||
}
|
||||
|
||||
// AgentOptions applies the same live-provider timeout to model and tool calls.
|
||||
// The empty result for mock runs preserves their deterministic timing.
|
||||
func AgentOptions(provider string) []agent.Option {
|
||||
if d := LiveTimeout(provider); d > 0 {
|
||||
return []agent.Option{agent.ModelCallTimeout(d), agent.ToolCallTimeout(d)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package harnessutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLiveTimeoutLeavesMockUnchanged(t *testing.T) {
|
||||
t.Setenv(LiveTimeoutEnv, "2m")
|
||||
if got := LiveTimeout("mock"); got != 0 {
|
||||
t.Fatalf("LiveTimeout(mock) = %s, want 0", got)
|
||||
}
|
||||
if opts := AgentOptions("mock"); len(opts) != 0 {
|
||||
t.Fatalf("AgentOptions(mock) length = %d, want 0", len(opts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveTimeoutUsesDefaultForLiveProviders(t *testing.T) {
|
||||
t.Setenv(LiveTimeoutEnv, "")
|
||||
if got := LiveTimeout("atlascloud"); got != DefaultLiveTimeout {
|
||||
t.Fatalf("LiveTimeout(live) = %s, want %s", got, DefaultLiveTimeout)
|
||||
}
|
||||
if opts := AgentOptions("atlascloud"); len(opts) != 2 {
|
||||
t.Fatalf("AgentOptions(live) length = %d, want 2", len(opts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveTimeoutCanBeOverridden(t *testing.T) {
|
||||
t.Setenv(LiveTimeoutEnv, "90s")
|
||||
if got := LiveTimeout("anthropic"); got != 90*time.Second {
|
||||
t.Fatalf("LiveTimeout override = %s, want 90s", got)
|
||||
}
|
||||
}
|
||||
Executable
+61
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env bash
|
||||
# Smoke-test the documented install.sh path without network access.
|
||||
# It builds the local CLI, packages it like a release archive, installs it into a
|
||||
# temporary bin directory through internal/scripts/install.sh, then checks the
|
||||
# first-run command boundaries shown in the getting-started docs.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)
|
||||
TMP_DIR=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP_DIR"' EXIT
|
||||
|
||||
ARCHIVE_DIR="$TMP_DIR/archive"
|
||||
INSTALL_DIR="$TMP_DIR/install"
|
||||
ARCHIVE="$TMP_DIR/micro-local.tar.gz"
|
||||
mkdir -p "$ARCHIVE_DIR" "$INSTALL_DIR"
|
||||
|
||||
CGO_ENABLED=0 go build -o "$ARCHIVE_DIR/micro" ./cmd/micro
|
||||
chmod +x "$ARCHIVE_DIR/micro"
|
||||
tar -C "$ARCHIVE_DIR" -czf "$ARCHIVE" micro
|
||||
|
||||
MICRO_INSTALL_DIR="$INSTALL_DIR" \
|
||||
MICRO_INSTALL_ARCHIVE="$ARCHIVE" \
|
||||
MICRO_VERSION="local-smoke" \
|
||||
PATH="$INSTALL_DIR:$PATH" \
|
||||
"$ROOT/internal/scripts/install.sh" > "$TMP_DIR/install.out"
|
||||
|
||||
MICRO="$INSTALL_DIR/micro"
|
||||
if [[ ! -x "$MICRO" ]]; then
|
||||
echo "installed micro binary not found at $MICRO" >&2
|
||||
cat "$TMP_DIR/install.out" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
require_output() {
|
||||
local description=$1
|
||||
local expected=$2
|
||||
shift 2
|
||||
local output
|
||||
if ! output=$("$MICRO" "$@" 2>&1); then
|
||||
echo "micro $* failed while checking $description" >&2
|
||||
echo "$output" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$output" != *"$expected"* ]]; then
|
||||
echo "micro $* missing expected text '$expected' for $description" >&2
|
||||
echo "$output" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
require_output "version" "micro version" --version
|
||||
require_output "root help" "COMMANDS" --help
|
||||
require_output "service scaffold" "micro new" new --help
|
||||
require_output "first-agent preflight" "preflight" agent preflight --help
|
||||
require_output "local runtime" "micro run" run --help
|
||||
require_output "agent chat" "micro chat" chat --help
|
||||
require_output "agent inspection" "micro inspect agent" inspect agent --help
|
||||
require_output "flow inspection" "micro inspect flow" inspect flow --help
|
||||
|
||||
echo "✓ install smoke path verified"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user