Skip to content

feat: add CreateArtifact/UpdateArtifact tools + artifact injection - #1

Merged
dahai80 merged 2 commits into
mainfrom
feature/artifacts-engine-tools
Jul 25, 2026
Merged

dahai80 merged 2 commits into
mainfrom
feature/artifacts-engine-tools

Conversation

@dahai80

@dahai80 dahai80 commented Jul 25, 2026

Copy link
Copy Markdown
Owner

Summary

Register CreateArtifact and UpdateArtifact tools in fusion-code's tool pool and add pre-request artifact injection to the query pipeline.

Changes

New Tools

  • ArtifactCreateTool: Model calls this to store large generated content (>30 lines code / >1500 chars text) as artifacts. Returns a lightweight [Artifact: name | ID: art_xxx | Version: v1 | Type: code | Tokens: 4200 | Summary: ...] reference tag (~80 tokens instead of ~4200 for full content).
  • ArtifactUpdateTool: Model calls this to update an existing artifact with new content. Creates a new version automatically; previous versions preserved for rollback.

Pre-request Injection

  • artifactInjection.ts: Hooked into query.ts after applyToolResultBudget(), before snip. Replaces artifact reference tags in messages with full content before sending to the model. Graceful fallback — if artifacts-engine is offline, injection is silently skipped.

Tool Registration

  • Added to getAllBaseTools() in tools.ts
  • Added to FULL_TOOLS set for MLX large model tool filtering

Communication

  • Both tools and injection communicate with fusion-artifacts-engine via HTTP JSON-RPC on port 8900
  • Configurable via ARTIFACT_ENGINE_URL env var
  • Can be disabled via ARTIFACT_ENGINE_DISABLED=1

Dependency

  • Requires fusion-artifacts-engine running on port 8900

Testing

  • Build: bun run build
  • Runtime: start artifacts-engine, verify tools appear in model's tool list, test create/update cycle

dahai80 and others added 2 commits July 25, 2026 21:49
- ArtifactCreateTool: store large content as artifacts, returns reference tag
- ArtifactUpdateTool: update artifact with new version
- artifactInjection.ts: replace reference tags with full content before API call
- Registered in tools.ts + FULL_TOOLS for MLX
- HTTP JSON-RPC to artifacts-engine on port 8900

Co-Authored-By: Claude <[email protected]>
@dahai80
dahai80 merged commit e7e8f90 into main Jul 25, 2026
@dahai80
dahai80 deleted the feature/artifacts-engine-tools branch July 25, 2026 14:19
dahai80 added a commit that referenced this pull request Aug 20, 2026
enhance-0819.md §P4.2 spec #6 要求配置冲突检测 (FUSION_BASE_URL vs
ANTHROPIC_BASE_URL 残留陷阱)。cli.tsx:30-49 有 6 对 FUSION_* -> ANTHROPIC_*
映射,模式 `if (FUSION_X && !ANTHROPIC_X)`,两者都设置时 FUSION_* 被静默忽略。
用户以为 FUSION_BASE_URL 生效实则用 ANTHROPIC_BASE_URL,无任何告警。

新增 detectFusionEnvConflicts() 纯同步 helper,挂入 detectConfigurationIssues
warnings 数组,复用 Doctor.tsx:417 既有 render 路径 (不改 UI)。覆盖 6 对:
API_KEY / BASE_URL / AUTH_TOKEN / BETAS / MODEL / LOG。warning {issue, fix}
文案明确指出 FUSION_* 被忽略 + unset 修复动作。

范围 surgical: +38/-0 prod (doctorDiagnostic.ts),1 新测试文件 6 用例。
MLX 端口/网关/模型加载/OOM (#1-4 async probe) 与一键修复 (#7) 延后单独 iteration。

验证: typecheck 0; 6 新测 pass; 122 单测无回归; build + build:dev:full pass;
biome check 干净。Closes #89

Co-authored-by: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 20, 2026
enhance-0819.md §P4.2 定 7 项 /doctor 本地健康检查。审计 (iter #9/#10):
- ✅ #5 CLAUDE.md 裁剪 (已覆盖)
- ✅ #6 配置冲突 (PR #90)
- ⏳ #4 OOM/内存 (跨仓: MLX 无 memory 端点, 仅 POST /api/v1/gc mutating)
- ⏳ #7 一键修复 (远期)
- **真 gap = #1 MLX 网关连通 + #3 模型加载状态** — /doctor 此前完全不探 MLX

落地 detectMlxHealth(): 复用 model-status.ts 的 fetchMlxStatus
(/api/tags) + fetchMlxPs (/api/ps), 3s timeout。Gating: 仅当
shouldAutoUseFusionMlx() (MLX 配置 provider) — cloud-active 时跳过
避免 3s 浪费 + 噪音。两 warning: 不可达 (含 URL + 起服命令) / 已连通
但无模型 loaded (含可用模型名截断 + load 命令)。

不改 Doctor.tsx — diagnostic.warnings 已数据驱动渲染。#4 OOM 跨仓
延后 (fusion-mlx 需加 status 端点, 遵循 "上游问题先提 issue")。

验证: typecheck 0, 6 单测 pass, 122 全测 pass 无回归, build +
build:dev:full pass, git diff -w +62/-0 纯插入零 churn。

Co-authored-by: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 20, 2026
追 CC 2.1.196→2.1.234 Tier-1 特性批量落地 (13 PR):

变更自 v0.4.22:
- WS1 DirectoryAdded hook + Notification agent_* 类型 (#73)
- WS2 堆叠 slash-skill 调用, 最多 5 前导 (#74)
- LSP+filecache 内存泄漏 cap, 对齐 CC 2.1.208 (#76)
- skill body-defer 懒加载, item 9 (#78)
- SessionStart source "fork" 区分 fork 与 resume (#80)
- P2.1 子代理护栏 — 并发/会话/深度三限 (#82)
- P1.1 大输出 tool_result tail 预览 (#84)
- P4.1 --ax-screen-reader 入口点对齐 — env 别名 + settings key (#86)
- item 13 WebSearch per-session 搜索次数上限 (#88)
- P4.2 §6 /doctor FUSION_* vs ANTHROPIC_* 环境变量冲突检测 (#90)
- P4.2 #1+#3 /doctor MLX 网关连通 + 模型加载探测 (#92)
- item 4 MCP 工具自动后台化 FUSION_MCP_AUTO_BACKGROUND_MS (#94)
- item 22 审计日志凭证脱敏 (#96)

- package.json: version 0.4.22 → 0.4.23

Co-authored-by: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 25, 2026
…ff) (#135)

Route foreground bash commands to fusion-executor (Layer B hands, Rust+PyO3,
self-built built-in tools + sandbox) via UDS NDJSON-RPC. fusion-code src/services/llm/
= Layer A brain (SDK removed, self-built). This wires Layer A to Layer B.

Phase 1 (PRD architecture/fusion-executor-prd.md):
- src/services/executor/types.ts — TS types mirroring executor Rust models
  (snake_case serde verbatim): ExecutionRequest/ExecutionResult/Diagnostics/
  ExecutorStreamChunk. Exit-code constants (0/-124/-1).
- ExecutorClient.ts — UDS NDJSON-RPC client (NOT LSP Content-Length framing).
  Spawns the executor serve+sock persistent UDS server, spawn-gate prevents
  ENOENT, net.Socket + line buffer. Methods health/execute/executeStream
  (multi-frame share one id: chunk then done)/stop. Crash handling isStopping+onCrash.
- ExecutorInstance.ts — state machine stopped to starting to running to stopping
  to error, MAX_CRASH_RECOVERY=3, lazy-require client.
- manager.ts — module-scope singleton + generation counter + race-safe initPromise
  (mirrors lsp/manager.ts). Gate isEnvTruthy(FUSION_CODE_EXECUTOR_ENABLED),
  unset means init no-op (byte-identical). registerCleanup on init.
- executorDriver.ts — BashTool delegation seam. callBashViaExecutor async
  generator: builds ExecutionRequest, executeStream chunk to progress protocol
  (callback to queue bridge, bursts coalesce, fullOutput preserved), terminal
  ExecutionResult to ExecResult (code=exit_code, interrupted=timed_out).
  isExecutorRouteable excludes run_in_background (issue #1) + _simulatedSedEdit.
  No client returns null (fail-open). Test injection seam.
- BashTool.tsx — call() top lazy-require gate (isEnvTruthy guard keeps executor
  module graph out of disabled runtime path). Routeable calls callBashViaExecutor,
  else runShellCommand. Terminal null calls logExecutorFallback + in-process fallback.
- main.tsx — initializeExecutorManager() after LSP init (same trust gate).

Wire = NDJSON (executor fe-ipc writes serde_json::to_string(resp)+newline per frame),
not vscode-jsonrpc Content-Length. Exit codes: 0=ok, -124=timeout, -1=blocked.

Gate + fail-open: FUSION_CODE_EXECUTOR_ENABLED unset means BashTool uses runShellCommand,
zero diff. Executor binary missing/init failed/crash means getExecutorClient() undefined,
callBashViaExecutor returns null, in-process fallback, log warning. Background commands
stay on fusion-code spawnShellTask (executor issue #1 no background API).

Tests: 23 new (manager gate/disabled/fail-open/singleton; executorDriver routing/
mapping/streaming/fail-open). Injection seam avoids mock.module cross-file pollution.

Gates: typecheck 0 errors, 431 tests pass, executor files lint clean (added to CI
lint list), build:dev passes. Runtime gate confirmed in bundle (env unset to runShellCommand).

Phase 2 (diagnostics slicing) + Phase 3 (git snapshot + atomic rollback) follow-up;
Phase 3 blocked on executor issues #1/#2 upstream.

Co-authored-by: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 27, 2026
Caller-owned turn-level git snapshot at submitMessage entry + /rollback
manual command. Complementary to in-band auto-rollback (PR #139):
in-band = single-call self-contained + opt-in; turn-boundary = caller
owns the snapshot, model/user decides to /rollback — safer for the
edit-test-fail coding loop.

- types.ts: SnapshotResult/RollbackResult wire types
- ExecutorClient.ts: snapshotCreate/rollback client methods (UDS RPC)
- ExecutorInstance.ts: methods with ensureStarted health gate
- executorDriver.ts: ExecutorClientLike test seam extended
- turnSnapshot.ts (new): turn-boundary manager — takeTurnSnapshot
  (fail-soft, non-repo no-op), recordTurnFailure (counter, threshold 3),
  lastHint (staged hint drain), rollbackToTurn, ring of 5
- QueryEngine.ts: takeTurnSnapshot at submitMessage entry; case 'user'
  is_error scan + hint injection to mutableMessages
- commands/rollback/ (new): /rollback [turnId] local-jsx command
- tests: 21 unit tests (fake client: take/rollback, failure counter,
  non-repo no-op, ring bounds, default-off byte-identical)

Gate: default off, FUSION_CODE_EXECUTOR_TURN_SNAPSHOT=1 (strict truthy).
Byte-identical when env unset — takeTurnSnapshot no-op returns null,
no client calls, no ring entry, no hint. Double-gate with
FUSION_CODE_EXECUTOR_ENABLED (executor must be on too).

Co-authored-by: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 28, 2026
…odule (audit 1.1.1) (#174)

Fourth surgical extraction — pure-helper bundle class (matches PR #171
spinnerState.ts pattern). 5 chained pure derives moved out of REPL.tsx:

  isWaitingForApproval  (4 queue/pending inputs → boolean)
  isShowingLocalJSXCommand (toolJSX → boolean, phantom-overlay guard)
  titleIsAnimating      (isLoading + 2 above → boolean)
  sessionStatus         (2 above → TabStatusKind idle/busy/waiting)
  waitingFor            (sessionStatus + queues → string|undefined)

New src/utils/terminalApprovalState.ts (90 LOC):
  - deriveIsWaitingForApproval(input)
  - deriveIsShowingLocalJSXCommand(toolJSX)
  - deriveTerminalApprovalState(input) — aggregate, returns all 5
  Types: TerminalApprovalInput + TerminalApprovalState + ToolJsxLike.

REPL keeps the hook-bound vars (haikuTitle/setHaikuTitle useState,
haikuTitleAttemptedRef useRef, terminalTitleFromRename useAppState,
agentTitle, sessionTitle, terminalTitle) + the two useEffects
(prevent-sleep 1399, PID-file status push 1425). Only the 5 pure
derives (no hooks, no JSX) move out. REPL calls deriveTerminalApprovalState
once, destructures to same const names → downstream reads unchanged
(byte-identical). Removed now-unused TabStatusKind import from REPL
(helper owns the type now).

Why not the #1 survey-stack candidate: survey-stack is a leaf-component
(JSX, React-compiler form to preserve) — higher byte-identical risk.
This pure-helper bundle has no JSX, no hooks — plain functions, lowest
risk, matches the proven PR #171 extraction pattern.

Test: src/__tests__/utils/terminalApprovalState.test.tsx (14 tests):
  - isWaitingForApproval: empty=false, each queue/pending → true
  - isShowingLocalJSXCommand: null/undefined/false, phantom-overlay
    guard (isLocalJSXCommand true + jsx null = false), true case
  - aggregate: idle/busy/waiting + titleIsAnimating suppression,
    waitingFor fallthrough chain (approve→worker→sandbox→dialog→input),
    local-JSX suppresses animation when loading

REPL.tsx 6732 → 6715 (−17). Cumulative off 7096 god module:
  PR#168 −285 + PR#171 −70 + PR#172 −9 + this −17 = −381 LOC.

Gates: typecheck 0 / 735 tests (+14 new) / lint net-zero 4601 /
build:dev 3763 modules.

Co-authored-by: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 28, 2026
…State (audit 1.1.1) (#176) (#177)

Sixth surgical extraction for audit §1.1.1 god-module split.
Bundle 3 chained pure derives out of REPL.tsx (was 5748-5769):
  - usesSyncMessages (showStreamingText||!isLoading)
  - displayedMessages (agent view|sync|deferred, ref-preserving)
  - placeholderText (input-baseline gate)

src/utils/messageDisplayState.ts NEW — deriveUsesSyncMessages +
deriveDisplayedMessages + derivePlaceholderText + aggregate
deriveMessageDisplayState. No React, no hooks, deps as args.
Returns ORIGINAL array refs (no spread copy) — preserves ref-identity
for Messages memo + length checks downstream. Byte-identical to inline.

REPL keeps useDeferredValue(messages) + userInputBaselineRef ref;
calls deriveMessageDisplayState once, destructures to SAME const names
→ downstream reads unchanged.

Picked 7-dep bundle over survey #1 getFocusedInputDialog (90 LOC but 23
deps) — strategy = fewest-dep pure-helper = lowest byte-identical risk
(per proven PR #174/#175 pattern).

Tests: messageDisplayState.test.ts 19 tests — usesSyncMessages 3 arms,
displayedMessages ref-identity + agent-override + empty-array,
placeholderText baseline gate + agent suppress, aggregate 7 cases
including ref-identity assertion (not a copy).

REPL.tsx 6709 → 6696 (−13). Cumulative off 7096:
  #168(−285)+#171(−70)+#172(−9)+#174(−17)+#175(−6)+#176(−13) = −400 LOC.

Gates: typecheck 0 / 769 tests (+19) / lint net-zero 4601 / build:dev 3764.

Co-authored-by: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 30, 2026
…hase B #203 slice 1)

Phase B of audit 1.1.3 (follow-up to PR #202). PR #202 enforced the
service->UI direction (src/services/** react-free). This slice enforces the
reverse: consumers OUTSIDE src/services/** reach a migrated service subdir
only through its barrel (src/services/<subdir>/index), not a deep file.

Slice #1 ships the enforcement MECHANISM + migrates the single largest clean
subdir (mcp, 83 deep imports, no barrel). The mechanism is allowlist-based
(scripts/layer-lint-reverse.json migratedSubdirs) so it lands without forcing
the other 28 subdirs; future slices append subdirs + migrate them.

Changes:
- NEW src/services/mcp/index.ts: re-export barrel for 13 public mcp files.
  8 internal-only files NOT re-exported (kept private).
- NEW scripts/layer-lint-reverse.ts: custom reverse-boundary scanner.
  noRestrictedImports cannot express 'deep-but-not-barrel' -> regex scanner
  walking src/ minus src/services/**. Enforces only allowlisted subdirs.
- NEW scripts/layer-lint-reverse.json: allowlist config + allowDeepImports
  exemptions for 4 cycle-sensitive files kept at leaf imports.
- MOD package.json: lint:layers:reverse script + chained into lint:layers.
- MOD ~78 consumer files: repoint services/mcp/<deep>.js -> index.js.
- MOD 5 files (config.ts/xaaIdpLogin.ts/utils.ts/channelNotification.ts/
  pluginOnlyPolicy.ts): lazy-require settings accessor to break the eager
  export * cycle (settings -> types -> barrel -> config -> pluginOnlyPolicy
  -> settings re-entry -> isLoadingSettings TDZ). Call-time-neutral.

4 cycle-sensitive settings-cone files kept at leaf imports (exempted via
allowDeepImports): settings/validation.ts, settings/allErrors.ts,
settings/permissionValidation.ts, plugins/schemas.ts. Eager barrel import
there re-enters settings.ts mid-init. allowDeepImports documents the cycle.

Gates: typecheck 0; bun test 973 pass/0 fail; lint errors unchanged
(4600=4600, no new deviations); lint:layers both directions green.
Build:dev succeeds, +1 module (the barrel node; re-exports tree-shake at
symbol level, behavior-preserving; NOT byte-identical since the slice ships
a real barrel + 5 lazy-require blocks).

Real scope 238 deep imports / 29 subdirs (3x issue estimate). Remaining
slices queued: api (34), compact (15), lsp (11). analytics (48) deferred
(needs split-barrel design decision: inert event-log shim vs real growthbook/
metadata impl the barrel intentionally hides).

Co-Authored-By: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Sep 13, 2026
审计核实结论: v1 #1/#3、v2 P1×2/P2×6 已在前序提交修复; 本次落地剩余项。

- lint 存量清零 (23→0): useNodejsImportProtocol ×12 (biome --unsafe
  自动修)、noNonNullAssertion ×10 (守卫变量/for-of/?? "" 兜底逐处
  消除, 不改语义)、noExplicitAny ×11 (Tool.ts AnyToolDef 约束为有意
  any + biome-ignore, Parameters<> 消除 execute→call 适配器 any;
  mcpHelpers 测试改用 McpHTTPServerConfig 真实类型)、
  noTemplateCurlyInString ×9 (被测语法 fixture, biome-ignore 标注)、
  noImplicitAnyLet ×4 (显式类型标注, 不预调用)
- Tool.ts execute→call 适配器: 局部别名收窄 + Parameters<> 转发,
  消除 5×any + 1×!
- biome.json: React Compiler 生成文件 (ink/buddy/context/util.tsx)
  的 t0/t1 缓存槽模式加 linter overrides 豁免, 不手改生成产物
- Task.ts generateTaskId: for-of 消除 bytes[i]!
- 修复过程中两处自引入回归已当场修正: ToolDef 约束改写破坏 30+ 工具
  类型推断 (回退为 biome-ignore 方案); joinedLine 误改 const 触发
  noConstAssign (保持 let)

验证: tsc 0 错误; 1209 pass / 0 fail; lint 0 告警。

Co-Authored-By: AtomCode (glm5.3-flash) <[email protected]>
dahai80 added a commit that referenced this pull request Nov 20, 2026
docs(research): benchmark report #1 - competitor snapshot pinned
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant