Commit Graph
151 Commits
Author SHA1 Message Date
chenchenandClaude Opus 4.8 f6da9c541e fix(agent): 异步回填加 Pending 状态守卫,避免覆盖用户 stop/delete
按 Fasthei 复审意见修并发状态机边界:
- 成功/失败回填都加 WHERE deployment_id=? AND LOWER(status)='pending',
  让 Pending->running / Pending->failed 成为 own-or-nothing 转换。
- 成功但 0 行(用户在 AM 启动窗口内 stop/delete/cancel):重读记录记日志,
  删除 AM 刚起的 orphan runtime,绝不把记录改回 running。
- 失败仅在我方拥有 Pending->failed 转换时才 revoke model token;用户已 stop/delete
  时交给对应路径(delete 已 revoke、stop 有意保留 key),避免重复/遗漏。
- 补竞态测试 StoppedDuringStart_NoResurrect:AM 启动被 hold 到记录置 stopped 后才返回,
  断言记录保持 stopped、不回填 runtime_id、orphan runtime 被删除。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 17:17:40 +08:00
chenchenandClaude Opus 4.8 da854277d3 test(agent): 异步部署的确定性测试(不阻塞 + Pending→running / →failed)
- 慢 AM mock 验证 startTemplateAgentAsync 立即返回(不阻塞 30s)。
- Pending 记录在 AM 响应后自动回填 running + runtime_id + subdomain。
- AM 失败时记录标 failed + failure_reason,不卡在 Pending。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 16:48:29 +08:00
chenchenandClaude Opus 4.8 a1a5b6037b fix(agent): 部署 agent 改异步,避免网关 504 + 回滚
POST /api/heicode/agents 原本在请求里同步阻塞 ~30s 等 AM 起 agent。Azure 网关
~20s 超时 → 504 → 请求 context 被取消 → AM 调用中止 → 部署回滚(agent 建不出)。

改为:先把 agent 存为 Pending 立即返回;AM 启动放到 context.Background() 的后台
goroutine(脱离请求 context),成功回填 subdomain/runtime_id/status,失败标记
status=failed 并吊销已铸的模型 key。客户端经已合并的列表刷新看 Pending→running。

go build ./... 通过;controller vet 干净。

影响面:仅 Manager(HM) 部署路径。客户端契约:deploy 现在立即返回 Pending(原为
阻塞后 running 或 504);AM 失败在列表里表现为 status=failed(原为同步
RUNTIME_UNAVAILABLE)。客户端本就轮询列表等 running。不改计费/密钥/审计。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 16:43:46 +08:00
zsbgnw12andGitHub b3d864b29b fix(agent): refresh list status from AM
Refresh non-terminal agent statuses before returning /api/heicode/agents.
2026-06-08 16:22:21 +08:00
cbbdd66c2e docs(reference): correct permission-modes precision per official en page (#16)
Verified against code.claude.com/docs/en/permission-modes and fixed 6 points:
1. acceptEdits: add PowerShell tool auto-approvals (Set-Content/Add-Content/
   Clear-Content/Remove-Item + aliases) and env-prefix/process-wrapper note.
2. Protected paths: .claude exception is ONLY .claude/worktrees (was wrongly
   widened to commands/agents/skills); add per-mode protected-write table.
3. defaultMode:"auto" ignored from project files since v2.1.142+.
4. dontAsk: read-only Bash commands also run without allow rules; explicit ask
   rules are denied (not prompted).
5. auto conversational boundary: stays in force until user lifts it; Claude's own
   judgment doesn't lift it; lost on context compaction; use deny rule for hard.
6. auto consecutive-failure fallback: 3-in-a-row / 20-total pauses & re-prompts;
   -p non-interactive aborts the session. Plus dropped broad allow-rules on entry.

Co-authored-by: chenchen <chenchen@xinghanlab.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 15:26:52 +08:00
efb0016f5c fix(secret): 撤销资源时删除 Key Vault 凭证材料 (#4) (#13)
#4:撤销资源此前只把 DB 状态置 "revoked",真凭证仍留在 Azure Key Vault。
现在 DeleteResource 同时删除 KV 中的 secret(best-effort:DB 撤销已提交,
外部 KV 失败只记日志、不阻塞响应)。

- secret_store.go:新增 deleteSecret / purgeSecret / rotateSecret
  (AKV REST,api-version=7.4,与 putSecret/getJSONSecret 同风格;404 幂等)。
  ※ 该文件受组织权限策略保护、自动化无读写权,本段由 HM owner 手动粘贴,
    审阅者请核对其与本意一致。
- resource.go:DeleteResource 在撤销事务提交后调用 deleteSecret(resource.SecretRef)。

本轮为 #4 最小修复(堵住"撤销后 KV 材料残留"的洞)。后续仍待:
purgeSecret 接入 30/90 天生命周期、轮换流程。

go build ./... 与 go vet 通过。

影响面(组织规则第 10 条):仅 Manager(HM) —— 涉密钥/安全/审计。
不影响 Client / Swarm / AM 契约 / CodeGW / 计费 / 发布链路。

Refs #4

Co-authored-by: chenchen <chenchen@xinghanlab.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 15:26:47 +08:00
zsbgnw12andGitHub 696dfecc9d docs(heicode): set Azure Key Vault as secret-store baseline
Align Manager docs with code-enforced azkv:// secret_ref baseline.

Reviewed: docs-only, no code/runtime impact. Follow-up required in heicodeDocs to remove OpenBao/vault:// drift.
2026-06-07 22:49:58 +08:00
zsbgnw12andGitHub 6d360454dd fix(relay): return errors instead of panic for Claude conversion stubs
Replace unimplemented ConvertClaudeRequest panic stubs with explicit not implemented errors across 11 relay adaptors.

Reviewed: narrow relay hardening only; no billing/secrets/Agent-Swarm/product semantic changes.
2026-06-07 19:59:21 +08:00
chenchenandClaude Opus 4.8 c220dc75da docs(reference): make Claude controls digest clearer & complete
Adds a reading guide, the full 6 permission modes (incl. dontAsk) + auto-mode
admin enablement toggle, confirmed role facts (UsageView roles; full matrix is
external; iam pages 404), deep permission-rule syntax (Bash spacing, Read/Edit
anchors, MCP/Agent), real MCP credential mechanisms (headersHelper/${VAR}/OAuth),
expanded usage/cost/attribution/analytics, plus two big appendices: verbatim
config examples (A1–A10) and step-by-step end-to-end flows (managed-settings
lifecycle, MCP allow/deny worked example, auto-mode force-push decision, auth
credential selection). Sourced from re-fetching the 6 core docs + permission-
modes/permissions/mcp/costs/monitoring-usage/analytics.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 17:04:29 +08:00
chenchenandClaude Opus 4.8 5dc99946f0 docs(design): HM product tiers (Individual/Teams/Enterprise) + commercialization boundaries
Aligns HM's capabilities to three tiers mirroring Claude's proven split, grounded
in HM's existing primitives. Defines positioning + billing per tier, a capability
× tier matrix (use layer = Individual; manage/allocate = Teams; compliance/hard-
enforcement/private = Enterprise) with HM code landing points, the Teams-hook vs
Enterprise-moat rationale, HM's differentiators over Claude (gateway-side hard
cost control, signed per-org policy push, server-side hard enforcement, native
agent catalog), a P0–P3 rollout mapping, and the open pricing decisions to settle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 16:53:44 +08:00
chenchenandClaude Opus 4.8 12f3cf21df docs(reference): add Individual/Teams/Enterprise tier breakdown to Claude digest
Expands §1.2 into a proper three-tier section: positioning per tier, a
capability × tier table (with source + whether the doc is explicit), the
billing differences, and the documented contradiction (authentication lists
"managed policy settings" as Enterprise-only while the server-managed-settings
feature page says Teams+ can use it). Also flags that most controls hinge on
provider (Anthropic-direct + admin write access) rather than subscription tier.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 16:41:58 +08:00
chenchenandClaude Opus 4.8 edb7090055 docs(reference): faithful Claude Code enterprise controls digest (zh)
Standalone reading reference faithfully consolidating the six official Claude
docs (admin-setup, authentication, server-managed-settings, settings,
managed-mcp, auto-mode-config): auth methods + precedence, roles/seats/admin,
settings scope precedence & merge rules, server-managed-settings mechanism,
full managed-only/permissions/model/sandbox/MCP key reference, managed-mcp
seven modes + allow/deny evaluation, auto-mode classifier, usage/audit, and
quick-reference tables. No HM design — pure Claude reference for study.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 16:34:29 +08:00
chenchenandClaude Opus 4.8 88240dc79e docs(design): HM team-control design referencing Claude Code enterprise paradigm
Synthesizes Claude's admin-setup/authentication/server-managed-settings/settings/
managed-mcp/auto-mode docs into a team-management design for HM, mapped onto the
analogy (client≈Claude Code, HM≈Claude.ai admin console, AM≈cloud agent) and
grounded in HM's existing primitives (new-api users/groups/sk-token model-limits/
quota, plus our V2 device auth, resource bindings, agent templates, /v1 gateway).
Covers org/team/seat model, roles, allocation, managed-settings push over the V2
channel, managed agent/tool catalog, auth/SSO, auto-mode, audit, and a phased plan.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 16:27:50 +08:00
chenchenandClaude Opus 4.8 f4968b8072 fix(agent): review fixes — deployable-template gating, stopped-status guard, UI consistency
Backend:
- loadAgentTemplate now requires status='active' — a known template_key can no
  longer deploy a template an admin deactivated (matches the client list).
- refreshAgentStatus no longer lets AM's eventually-consistent live status
  resurrect a user-initiated "stopped" agent.
- HeicodeStopAgent persists via field-level Updates (not a stale full-row Save),
  matching refreshAgentStatus discipline.
- Drop dead amStartResult.AccessToken field (AM's token is never used; HM mints
  its own per-agent token).

Frontend:
- deploy-agent statusLabel: add the missing pending/starting → 启动中 branch so a
  just-deployed agent isn't shown as raw English fallback.
- cockpit 最近部署: map template_id → Chinese template name (consistent with the
  deploy/status pages) instead of showing the raw key.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 11:06:49 +08:00
chenchenandClaude Opus 4.8 c05b27de6a revert: drop outbound env-key logging; root cause was AM stale prod image
Token IS transmitted by HM (confirmed); the agent didn't enforce it because AM
hadn't deployed the image containing the §5 check to production. So the debug
log is unnecessary — removed. Contract §0.1 updated: token-check is "code-ready,
pending AM prod image", not a HM gap. UI access-token/direct-URL display kept.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 00:28:53 +08:00
chenchenandClaude Opus 4.8 05de8f50e4 feat(agent): log outbound env keys to AM; show direct URL + access token in 运行状态
- runtime: log the env KEY NAMES (never values) sent to AM on start, so we can
  confirm AGENT_ACCESS_TOKEN is actually transmitted without leaking secrets.
- web/运行状态: detail panel now shows the full direct-connect URL (copyable) and
  the per-agent access token (masked + reveal + copy) with a hint that the client
  sends it as X-Agent-Access-Token. These are what's actually needed to hand the
  agent to a client / test it — previously only the bare hostname was shown.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 00:16:28 +08:00
chenchenandClaude Opus 4.8 c171bb70ee docs(integration): record 2026-06-04 end-to-end re-test against AM's updated runtime
AM shipped its updated runtime + fixes; live re-test confirms deploy → running
→ direct /health & /message/send (task completed) → stop → delete all pass, and
HM's per-agent access_token is minted + returned (non-empty UUID). Two AM-side
gaps remain: (1) the running agent does NOT enforce X-Agent-Access-Token
(no-token request still 200, agent card auth_required=None) — token isolation
not actually active; (2) subdomain is http:// (token + api_key in cleartext).
Contract §0.1 and client doc status notes updated accordingly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 23:50:09 +08:00
chenchenandClaude Opus 4.8 f128f4d03f docs(integration): professional accuracy pass on client + AM contract
- AM contract: fix stale lifecycle path defaults in the env-override table
  (/agents/{agent_id}, /agents/{agent_id}/stop — matches code, not the old
  /api/agent/... values); correct the self-check create line to POST /agents;
  align the verify-endpoint example to the real production response shape
  (user_id is a string, agent_id included, miss returns {valid:false}).
- Client API: §0 overview now states HM mints the per-agent access_token
  (AM no longer "returns" it).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 22:42:55 +08:00
chenchenandClaude Opus 4.8 ed46acd4d3 docs(agent): fix stale runtime comments about token injection
amStartTemplateAgent no longer claims OPENAI_API_KEY is uninjected or that
access_token is left empty for a future V2 path: the handler now mints +
injects both OPENAI_API_KEY and the per-agent AGENT_ACCESS_TOKEN (forwarded
as-is), and HM returns its own access_token to the client.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 22:29:40 +08:00
chenchenandClaude Opus 4.8 b01bba53f0 docs(agent): lock client↔agent auth to option ① (agent-local token compare)
Per the chosen design, the agent authorizes callers by comparing the request
header X-Agent-Access-Token against its env AGENT_ACCESS_TOKEN (constant-time),
no HM round-trip. AM contract §3.1 now states ① as the agreed integration with
Python pseudo-code; the /agent-access/verify endpoint is demoted to an optional
fallback. Client API §6 spells out the client's job: send X-Agent-Access-Token
on every direct-connect request.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 22:23:41 +08:00
chenchenandClaude Opus 4.8 e326964362 feat(agent): per-agent client↔agent access token for per-user authorization
HM now mints a random per-agent access token at deploy, injects it into the
agent env (AGENT_ACCESS_TOKEN + HEICODE_AGENT_ID) and returns it to the
deploying client (agent list access_token). Only the owning user receives it,
so only they can drive the agent — closing the gap where any valid sk- could
drive any agent and exfiltrate its mounted resources.

AM authorizes the caller either locally (compare to its env token) or via the
new public POST /api/heicode/agent-access/verify {agent_id, access_token} ->
{valid, user_id} (constant-time compare, no info leak on miss). AM may opt out.

Docs: AM contract §3.1 + client API §6 updated; access_token no longer empty.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 21:58:10 +08:00
chenchenandClaude Opus 4.8 3a2ad36e5d fix(web): show unsupported resources (vm) disabled; Overview uses new-model framing
1) Deploy Sub Agent: stop hiding resource types AM doesn't support yet (vm) —
   show them but disabled with a "暂不支持" badge + tooltip, so users see their
   bindings instead of wondering where the vm went.
2) Overview (概述/cockpit): replaced the old task-model status cards
   (Running/Completed/Failed/裁决 + "code delivery runs") with template-agent
   semantics — Agent 总数 / 运行中 / 启动中 / 异常, "最近部署 · 我的 Agent",
   all Chinese. Dropped unused t()/useTranslation/PlayCircle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:59:12 +08:00
chenchenandClaude Opus 4.8 c4316f7fcd feat(web): new "运行状态" page (new-model agent status, not old task fields)
Re-add a run-status menu (I shouldn't have removed it) but showing ONLY what the
template-agent model actually has — no old 待确认/sub_agile/子任务流/智能体任务图/
产物/SK快照/合并时间线. New /agent-status page:
- summary counts (total / running / starting / other)
- agent list (template Chinese name, live status badge, subdomain, #resources)
- detail panel: live status (polls /agents/{id}/status from AM), copyable
  subdomain, mounted resources (names from /api/resources), runtime_id, timestamps.
Sidebar item "运行状态" + zh key added; build + tsc clean; route registered.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:46:22 +08:00
chenchenandClaude Opus 4.8 b7d1927a5b docs(integration): update AM contract to current state + real-test results
- new §0.1 联调结果: real production test outcomes — create POST /agents works
  (returns access_info.domain/namespace), DELETE /agents/{id} 500s (AM
  UnboundLocalError bug), POST /agents/{id}/stop 404 (no endpoint), agent stays
  Pending / subdomain unreachable. The 3 AM-side blockers listed up top.
- OPENAI_API_KEY is now injected (a minted user new-api sk-, billed to the user,
  revoked on delete; verified working at /v1) — §1.1 env + §2 updated.
- §3 client<->agent: now documents AM's A2A protocol (message/send · stream),
  api_key auth, and flags the per-user isolation security gap.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:36:23 +08:00
chenchenandClaude Opus 4.8 d19920d1d0 fix(web): remove old "运行总览" task UI; Overview shows new template agents
The old /deployments (运行总览) + /tasks/$id pages rendered the new template agents
with meaningless old sub-task fields (待确认/sub_agile/子任务流/智能体任务图/产物/
SK快照/合并时间线 — all empty). Removed the whole old-model UI cluster and pointed
the Overview dashboard at the real new endpoint:

- deleted features/agent-console, features/agent-hub, features/tasks and the
  routes /deployments and /tasks/$id.
- cockpit (Overview) now lists deployed template agents from /api/heicode/agents
  (status counts + recent agents), not the old listAgentDeployments.
- removed the "运行总览" sidebar item + dead /deployments links in footer /
  top-nav / sidebar-config.
- routeTree regenerated; frontend build + tsc clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:32:03 +08:00
chenchenandClaude Opus 4.8 0b2aeac51d docs(integration): update client API doc to production-verified reality
Ran the full desktop-client flow against production (real account) and updated
the doc to the verified responses:
- capabilities model = gpt-5.4; modes still returned but ignored.
- agent object: access_token is "" (AM issues none — connect via A2A api_key),
  subdomain is a host (dep-xxx.taijiagnet.com), status starts Pending; real
  binding_ids; shown as "生产实测" examples.
- §4: clarified the template `model` field is a role-tier hint (opus), not the
  runtime model (gpt-5.4 injected at deploy).
- §5: stop currently fails / delete returns runtime_cleanup:"failed" (AM stop
  missing + delete bug); HM removes the local record regardless.
- §6: must wait for status=running / health 200 before connecting; noted the
  agent currently stays Pending and the subdomain isn't reachable yet (AM side).
- top banner: per-endpoint production verification note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 17:07:30 +08:00
chenchenandClaude Opus 4.8 436b079c16 feat(agent): inject OPENAI_API_KEY (minted sk-) so the agent can call HM /v1
Deploy now also passes OPENAI_API_KEY (the 3rd of OPENAI_BASE_URL/MODEL_NAME/
OPENAI_API_KEY AM expects). HM mints a hidden, unlimited-quota sk- token for the
user per agent ("sk-"+key, billed to the user), injects it as OPENAI_API_KEY, and
stores the token id on the deployment. The token is revoked on delete and rolled
back if AM start / persist fails (no leaked keys). gateway accepts Bearer
sk-<key> (middleware strips sk-).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 16:44:17 +08:00
chenchenandClaude Opus 4.8 1d81002c2d fix(agent): default MODEL_NAME=gpt-5.4 for started agents (not template tier)
Preset templates carry a Claude-style frontmatter model (opus/sonnet) which is
NOT a model on the HM gateway. Passing it as MODEL_NAME would make the agent's
model calls fail. Now MODEL_NAME defaults to the gateway model gpt-5.4
(env AGENT_RUNTIME_DEFAULT_MODEL); a non-Claude-tier template model is honored.
Tests + AM contract doc updated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 16:25:21 +08:00
chenchenandClaude Opus 4.8 b33bcf90bd feat(device): desktop client self-logout endpoint
POST /api/devices/logout (UserOrV2DeviceAuth): a device-signed client revokes its
OWN bound token via the signed X-Heicode-Device-Id (cannot touch other devices);
a session/JWT caller may pass {device_id}. Idempotent. The existing DELETE
/api/devices/:id revoke is session-only, so device clients had no self-logout —
this closes that gap. Documented in the client API doc §1.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 16:15:47 +08:00
chenchenandClaude Opus 4.8 557fb2b829 test(agent): fix status round-trip path assertion to /agents/{id}
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 15:48:09 +08:00
chenchenandClaude Opus 4.8 f1637c3ecd fix(agent): resilient delete — always remove local record even if AM delete fails
Real test showed AM's DELETE /agents/{id} currently 500s (AM bug), which left the
HM record permanently undeletable. HeicodeDeleteAgent now treats the AM delete as
best-effort: on AM failure it logs + still removes the local record and returns
runtime_cleanup:"failed" so the user can always clear their list. (Stop stays
strict — AM has no /stop endpoint yet, pending their confirmation.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 15:47:23 +08:00
chenchenandClaude Opus 4.8 27459bb476 fix(agent): align AM lifecycle paths to /agents/{id} (real-test: create works)
Real production test (user account) confirmed HM->AM POST /agents creates a real
agent (returned subdomain + status). But stop/delete still used the old
/api/agent/agents/{id} defaults and 404'd. Aligned status/stop/delete defaults to
the same namespace as create: /agents/{id}, /agents/{id}/stop. AM contract doc
notes these are HM's best guess pending AM's confirmation of the real lifecycle
endpoints (their doc only specified create).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 15:41:34 +08:00
chenchenandClaude Opus 4.8 074a3cc7e7 feat(agent): align HM to AM's coding_a2a_agent contract
Adapt HM's template-agent integration to AM's actual CODING_A2A API (per their
doc), keeping it isolated in agent_template_runtime.go:

- start payload -> AM's POST /agents { name, template:"coding_a2a_agent",
  framework:"A2A", config:{user_id,...}, env } with the template .md folded into
  env.AGENT_INSTRUCTION_TEXT, template_key -> AGENT_ROLE_NAME, model gateway via
  OPENAI_BASE_URL + MODEL_NAME (OPENAI_API_KEY left to the client per A2A request).
- response parse -> access_info.domain/external_ip -> subdomain, namespace/name
  -> runtime_id; AM issues no access_token (client uses A2A api_key).
- env names aligned to AM: GIT_DEFAULT_BRANCH, POSTGRES_* (was PG_*),
  AZURE_BLOB_ACCOUNT_NAME/CONTAINER/ACCOUNT_KEY (was BLOB_*); source keys aligned
  to the resource-binding form (db_name/username/database_password/access_key).
  Only AM-supported types (git/mysql/postgres/azure-blob); vm/redis/mongo/bucket
  now rejected as unsupported until AM adds them.
- frontend: resources page splits DB into MySQL/PostgreSQL (correct provider),
  drops vm; deploy page hides unsupported resource types.
- docs: AM contract + client doc updated to the real env names, payload, and the
  A2A direct-connect (message/send · message/stream) + api_key auth.
- tests updated for the new env names + AM payload/response shape. All green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 15:30:33 +08:00
chenchenandClaude Opus 4.8 e21cc1e81e docs(integration): HM<->AM interface contract for the template-agent model
Hand-off doc for the agent_management team: the 4 endpoints AM must implement
(start/status/stop/delete) with exact request/response (grounded in the isolated
adapter agent_template_runtime.go), the env naming convention AM templates must
read (git/vm/db/blob/bucket), AM's responsibilities (inject .env, validate the
agent access token, models via HM /v1/*, no secret leakage), the client<->agent
direct SSE contract AM needs to define, security requirements, the env-overridable
paths, and a joint integration checklist.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 14:47:34 +08:00
chenchenandClaude Opus 4.8 ac32a2db51 fix(agent): encrypt agent access_token at rest (AES-256-GCM via CryptoSecret)
Closes the last review finding: the AM-issued access_token was stored in plaintext
in agent_deployments. Now sealed with common.SealWithCryptoSecret on write and
unsealed on read — the client still receives the plaintext token (no contract
change), but a DB dump no longer exposes live agent tokens. Legacy/plaintext
values and an unset CryptoSecret degrade gracefully (pass-through). Round-trip test added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 14:35:15 +08:00
chenchenandClaude Opus 4.8 7a48155568 fix(agent): apply review findings (backend data-integrity + frontend error UX)
Two review agents (backend + frontend) audited the template-agent feature. Real
findings fixed (verified the one false-positive — okOrThrow already reads the
top-level success because the response interceptor returns response, not
response.data):

Backend:
- buildAgentEnvFromBindings now filters status='active' so a revoked/disabled
  binding can't still have its KV secret resolved + injected.
- same-type binding env collision (e.g. two git repos -> GIT_REPO_URL) now errors
  instead of silently overwriting.
- refreshAgentStatus uses a field-level Updates (status/updated_at) instead of
  Save(full row) to avoid clobbering a concurrent stop/delete.
- tests added: same-type collision rejected, inactive binding rejected.

Frontend:
- deploy/stop/delete now pass noBusinessError so the global interceptor stops
  double-toasting the raw English backend message; okOrThrow+onError give one
  friendly Chinese error. Extracted okOrThrow/noBusinessError into lib/api.ts.
- resources page revoke + create + KV-secret-write now check success (okOrThrow)
  so a failed unbind / credential write no longer falsely reports success.
- clipboard copy wrapped in try/catch (no false "copied" on failure).
- resources group label shows Chinese resource-type names.

Go + frontend builds/tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 14:24:25 +08:00
chenchenandClaude Opus 4.8 479cd61a07 docs(integration): complete + correct the desktop client API doc
Review of the client doc against the real code found and fixed:
- §1 auth was not self-contained (deferred the canonical to the deprecated doc).
  Inlined the full signing contract verified against middleware/device_signature.go:
  the exact header set, the fixed-order canonical string (method/path/ts/nonce/
  fingerprint/eph_pubkey/sha256(body)), ed25519(sha256(canonical)), the heicode-aead-v1
  encrypted-body rules, and the X-Heicode-Auth-Error / X-Heicode-Server-Time failure
  headers.
- §2 auth mismatch (accuracy bug): /api/user/self is UserAuth (session/JWT), NOT
  device-signed — a device-only client cannot call it. Marked it optional and
  clarified the two different auth schemes (/api/user/self* vs /api/heicode/*).
- §8: documented that failures return HTTP 200 with success:false (client MUST
  read success), and that error.retryable is always false (decide retry by code).
- §10 inventory: corrected /api/user/self auth + added /self/models.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 10:57:43 +08:00
chenchenandClaude Opus 4.8 15b17f39b0 docs: remove obsolete 普通 sub (old model) integration docs
The 普通 sub task-orchestration model was replaced by the template-agent model
and its backend deleted. Removed the now-obsolete docs describing it:
- heicode-desktop-sub-agile-api.md, heicode-desktop-subagile-e2e-demo.md
- heicode-desktop-unified-api.md, heicode-sub-mode-flow-spec.md
- 普通sub敏捷模式-AgentManager对接任务清单.md
- AgentManager普通sub{产物回调缺失问题,剩余补充要求,联调整改要求}.md

Fixed dangling references in the new docs (client-api / template-agent-model).
Swarm (蜂群) docs kept — different mode, out of scope.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 09:56:17 +08:00
chenchenandClaude Opus 4.8 16cca5df1c fix(agent): review fixes — success-check, template name, seed Once, update guard
Full review of the template-agent code surfaced and fixed:
- [frontend, critical] deploy/stop/delete treated HTTP-200-with-success:false as
  success (backend agentError returns 200 per new-api convention) -> a failed
  call wrongly toasted success. Added okOrThrow() that inspects the envelope and
  throws the server (or a friendly Chinese) message so onError fires.
- [frontend] "我的 Agent" showed the raw template key (architect) instead of the
  Chinese name; now resolves name via the templates list.
- [backend] ensureAgentTemplatesSeeded consumed sync.Once even when model.DB was
  nil (would permanently skip seeding) -> DB check moved outside the Once.
- [backend] AdminUpdateAgentTemplate could wipe name_zh/definition with empty
  values -> guard those critical fields.
- [security] warn when starting an agent with secret-bearing env over a non-HTTPS
  AM URL (secrets must not transit the network in clear).

Go + frontend build/tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 00:59:03 +08:00
chenchenandClaude Opus 4.8 c4e84258b7 docs(integration): desktop client API doc for the template-agent model
New authoritative client doc (heicode-desktop-client-api.md): the desktop client
lists its agents from HM, gets each agent's subdomain + access_token, and
connects to the agent directly over SSE; models for both client and agent go
through HM /v1/*. Grounded in the production-verified responses (19 Chinese
templates, agent list/deploy/status shapes, error codes). Marks the old
unified-api doc (sub task-orchestration) as superseded.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 00:41:07 +08:00
chenchenandClaude Opus 4.8 8823bf5e5d feat(web): add "部署 Sub Agent" menu + page (pick resources + template -> deploy)
Customer-facing, plain Chinese (no env/technical jargon). New sidebar item
"部署 Sub Agent" -> /deploy-agent. The page:
- Step 1: pick which bound resources the agent may use (multi-select cards from
  /api/resources).
- Step 2: pick an agent template (cards show Chinese name + description from
  /api/heicode/agent-templates).
- Deploy -> POST /api/heicode/agents {template_id, binding_ids}.
- "我的 Agent" list (/api/heicode/agents) with status, copy-address, stop, delete.

Frontend builds clean (tsc + rsbuild; routeTree regenerated). zh label added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 00:25:12 +08:00
chenchenandClaude Opus 4.8 4605cf4f62 feat(agent): HM-maintained agent template library (md), sent to AM on deploy
Templates now live in HM (not AM). A template is a Claude-Code style subagent
.md definition; HM passes it to AM at deploy time.

- model AgentTemplate (agent_templates): template_key, name_zh / description_zh
  (Chinese display for the console), model, definition (full .md), source, status.
- 19 presets from oh-my-claudecode (MIT, NOTICE.md attribution) embedded via
  go:embed and idempotently seeded; Chinese name+desc mapping in code.
- GET /api/heicode/agent-templates now reads HM's library (Chinese name/desc),
  not AM. Admin CRUD at /api/agent-templates (AdminAuth).
- deploy loads the chosen template and sends {template_key, agent_definition (md),
  model, env, callback_url} to AM via a generic /api/agent/agents/start; removed
  the AM-template-listing path. AM adapter still isolated (amStartArgs).
- tests: frontmatter parse, seed (19 + 架构顾问), start round-trip asserts
  agent_definition in payload. All green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-04 00:05:08 +08:00
chenchenandClaude Opus 4.8 692506c9fc chore(agent): remove dead artifact-revision & cloud-deployment models (phase B)
After phase A removed the old client task layer, AgentArtifactRevision and
AgentCloudDeployment became unreferenced (their only consumers — the deleted
heicode_task_create/project_artifacts/artifact_edits/cloud_deploy — are gone).
Removed the structs + their AutoMigrate entries. Existing tables are left in
place (harmless, no model) and can be dropped later if desired.

Option B teardown: kept the shared platform backend still used by the web
console / runtime callbacks (admin /api/agent/*, approvals, leases, callbacks,
AgentArtifact, sk-snapshots, withDisplayStatus). Build + controller/model/router
tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 23:36:43 +08:00
chenchenandClaude Opus 4.8 3863296f85 chore(agent): remove old client sub-task API (phase A of legacy teardown)
The template-agent model replaces the old sub/swarm task orchestration. Removed
the entire client-facing task surface:
- routes: registerHeicodeTaskRoutes (all /heicode/{sub-agile,swarm}/tasks/*) and
  GET /heicode/deployment-targets.
- controllers deleted: heicode_task_create, heicode_client_routes,
  heicode_project_artifacts, heicode_artifact_edits, heicode_cloud_deploy
  (+ the agent_deliverable_secret_test that covered the deleted markdown-project
  parsing).

Build + controller/router/model tests green. Shared backend (AgentDeployment,
agent_runtime_client helpers, admin /api/agent/*) intentionally kept — trimmed in
the next phase.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 23:29:22 +08:00
chenchenandClaude Opus 4.8 19fd4f3326 refactor(agent): built-in per-type env mapping; fix start timeout, orphan, guards
Replace the user-facing env_map mistake with a built-in env convention keyed by
resource type + provider — users never see/edit env names; they only fill plain
resource fields. Supports git (gitea/github/gitlab), vm, database
(mysql/pg/redis/mongo, with alias normalisation), storage (azure blob / bucket).
Lenient: missing optional fields are skipped; only unsupported type or a KV read
failure errors.

Other issues found in review and fixed:
- start timeout: template-agent start now uses a longer timeout (default 60s,
  AGENT_RUNTIME_START_TIMEOUT_SECONDS) since AM provisions synchronously — 5s
  would time out. amTemplateDo takes a per-call timeout.
- orphan agent: if AM start succeeds but the Manager record fails to persist, the
  orphan is rolled back (best-effort amDeleteTemplateAgent).
- findUserTemplateAgent now guards template_id<>'' so the new endpoints can't
  touch a legacy task deployment.
- binding_ids defaults to [] (not null).
- removed ResourceBinding.EnvMap field entirely.

Tests rewritten for the built-in convention (blob metadata-only, db provider
prefixes incl pg/mg aliases, git provider-agnostic names, ownership, unsupported
type, empty); adapter round-trip + router tests still pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 22:48:29 +08:00
chenchenandClaude Opus 4.8 65a71f6b35 feat(agent): pull live template-agent status from AM (no callback needed)
- amGetAgentStatus: HM pulls a running agent's status from AM on demand
  (is it alive / crashed), isolated in the AM adapter like the rest.
- GET /api/heicode/agents/:id/status + status refresh on GET /:id detail,
  best-effort (keeps last-known status if AM is unreachable; never blocks read).
- tests: httptest-backed round-trip tests for amStartTemplateAgent and
  amGetAgentStatus against a fake AM (validates the full request/parse path);
  router registration still clean. All pass.

Note: no required-resource validation added — HM injects whatever bindings the
user selected into the agent .env (per env_map); AM reads what it needs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 22:04:00 +08:00
chenchenandClaude Opus 4.8 cdbc43baeb feat(agent): template-agent deploy/list/stop API (AM contract isolated)
HM-side logic for the template-agent model, written against a proposed AM
contract that is fully isolated in agent_template_runtime.go — when AM ships its
real API, only the default paths + response field names in that one file change.

- agent_template_runtime.go: AM adapter (list templates, start template agent
  with env, stop/delete) reusing the existing runtime config/url/envelope helpers.
- agent_template_handlers.go: GET /api/heicode/agent-templates; POST /api/heicode/
  agents (resolve bindings -> env, start via AM, persist subdomain+token);
  GET /agents, GET/:id, POST/:id/stop, DELETE/:id. Owner-scoped; env never logged.
- reuses AgentDeployment as the agent record (TemplateID/Subdomain/AccessToken/
  BindingIDsJSON) and buildAgentEnvFromBindings for env assembly.
- routes wired under /api/heicode (UserOrV2DeviceAuth), verified no registration
  panic (router tests pass).
- agent_template_test.go: 7 independent unit tests (env assembly metadata-only,
  ownership, secret-without-ref, unknown-source, empty; path substitution;
  response mapping) — all pass without AM/KV.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 21:55:24 +08:00
chenchenandClaude Opus 4.8 8ecab2c270 feat(controller): env assembly from resource bindings for template agents
buildAgentEnvFromBindings resolves selected resource bindings into a flat env map
for a template agent's .env at start: non-secret values from Metadata, secret
values resolved from Key Vault (getJSONSecret) only here, lazily, never persisted.
AM-independent foundation for the deploy-agent flow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 21:43:34 +08:00
chenchenandClaude Opus 4.8 efdc360499 feat(model): add template-agent fields (reuse AgentDeployment + ResourceBinding.EnvMap)
Additive, AutoMigrate-friendly (new columns only, cross-DB safe). Foundation for
the template-agent + direct-connect model:
- AgentDeployment: TemplateID, Subdomain, AccessToken, BindingIDsJSON — reuse the
  existing deployment record as the deployed-agent record instead of a new table.
- ResourceBinding.EnvMap: declares which env vars a binding exposes to a template
  agent at start (non-secret from Metadata; secret resolved from KV only at start).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 21:41:19 +08:00
chenchenandClaude Opus 4.8 b40a29102e docs(integration): correct teardown after dependency analysis (avoid over-deletion)
Verified the old-model code surface against the repo. Found the new template-agent
model is an EVOLUTION of the existing deployment control plane, not greenfield —
so several files are mixed and must NOT be whole-deleted:

- agent_runtime_client.go: AM HTTP client (config/url/headers/create/stop/status/
  health) is reused by the new StartAgent/StopAgent AND by capabilities; only
  withDisplayStatus + artifact/budget helpers are old.
- agent_control_plane.go: AgentCreate/List/Get/StopUserDeployment + AgentDeployment
  table are the backbone the new agent record reuses; only per-deployment task
  sub-handlers and the withDisplayStatus calls (1191/1200/1222) are old.
- agent_task_bridge.go: resolveResourceBindingIntoGrant is reused for env assembly.
- AgentDeployment table: KEEP and extend (subdomain/access_token/binding_ids)
  instead of new heicode_agent table + DropTable. Reconciled the model doc to match.
- Added agent_runtime_http_smoke_test.go to the sync-fix list.

Adds a §0.0 dependency/impact analysis answering: coverage, shared-feature impact,
and impact on the new APIs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 21:37:07 +08:00