Skip to content

Add @nodespace/agent-tools TypeScript gRPC client package (closes #1122) - #1146

Merged
malibio merged 2 commits into
mainfrom
feature/issue-1122-agent-tools-package
May 18, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-1122-agent-tools-package

Conversation

@malibio

@malibio malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Adds @nodespace/agent-tools, a pure-TypeScript npm package that exposes NodeSpace knowledge graph operations as callable functions for PTY-spawned agents (Claude Code, Codex, Gemini CLI, Pi, OpenCode).
  • All operations go through @grpc/grpc-js against nodespaced on localhost:50051 — no MCP server, no native bindings, no codegen step (proto is loaded at runtime via @grpc/proto-loader).
  • Exports five tool functions: searchSemantic, getNode, createNode, updateNode, getChildren, plus a typed ToolError for structured connection/RPC error handling.

Design Notes

  • The gRPC channel is a lazy singleton (created on first call, reused across calls). Address is overridable via the NODESPACED_ADDR env var, matching the daemon's own convention.
  • The proto file lives in packages/daemon/proto/node_service.proto and is loaded at runtime — no duplication, and the agent-tools package automatically stays in sync with the daemon's wire format.
  • gRPC errors are normalized to ToolError(code, message) where code is the grpc.status enum name (UNAVAILABLE, NOT_FOUND, etc.). Callers can branch on code without importing grpc-js.
  • parent_id === '' from the wire is normalized to undefined on the JS side so root nodes have a clean NodeResult shape.

Test plan

  • Frontend baseline before changes: 128 test files, 3918 tests passed
  • Frontend after changes: 128 test files, 3918 tests passed (no regressions)
  • Package tests: 3 test files, 15 tests passed
    • tools.test.ts — each tool function (happy path + error wrapping) using a spy on getClient
    • client.test.ts — proto loads, client is cached, resetClient returns a fresh instance
    • connection-error.test.ts — real call against an unused port surfaces as a ToolError (not an uncaught exception)
  • bun run build produces clean dist/ with .d.ts + sourcemaps
  • bunx tsc --noEmit passes strict type-check
  • Workspace bun run quality:fix clean (0 errors, 0 warnings)
  • Rust tests (bun run rust:test) skipped per CLAUDE.md guidance (no Rust changes in this PR)

Acceptance criteria

  • packages/agent-tools/ npm package created and added to the Bun workspace
  • @grpc/grpc-js client connects to nodespaced on localhost:50051
  • searchSemantic(query, limit?) calls SearchNodes in semantic mode
  • getNode(nodeId) calls GetNode
  • createNode(type, content, parentId?) calls CreateNode
  • updateNode(nodeId, content) calls UpdateNode
  • getChildren(nodeId) calls GetChildren
  • Connection error returns a structured ToolError, not an uncaught exception
  • Package builds cleanly
  • Unit tests cover each tool function and connection error handling
  • All workspace tests pass
  • Code passes bun run quality:fix

🤖 Generated with Claude Code

Create the shared TypeScript foundation that per-agent shims (Claude Code,
Codex, Gemini, Pi, OpenCode) will use to read and write the NodeSpace
knowledge graph during a session. Exposes five tool functions backed by a
pure-TS @grpc/grpc-js client against nodespaced on localhost:50051.

- searchSemantic(query, limit?) → SearchNodes in semantic mode
- getNode(nodeId) → GetNode
- createNode(type, content, parentId?) → CreateNode
- updateNode(nodeId, content) → UpdateNode
- getChildren(nodeId) → GetChildren

The gRPC channel is a lazy singleton; address is overridable via
NODESPACED_ADDR. All gRPC errors are normalized into a typed ToolError
with the grpc.status code as the error code, so connection failures
surface as structured errors instead of uncaught exceptions.

Proto is loaded at runtime via @grpc/proto-loader against
packages/daemon/proto/node_service.proto — no duplication, no codegen
step. 15 tests cover each tool function, proto loading, client caching,
and a real connection failure against an unused port.

Closes #1122

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Initial review of #1146 (closes #1122). The change introduces packages/agent-tools/, a pure-TypeScript gRPC client package exposing five NodeService operations for PTY-spawned agents. Implementation is clean, scope-disciplined, and well-tested.

Recommendation: Approve. All acceptance criteria are met, the design is appropriately minimal (KISS/YAGNI), and the few concerns below are non-blocking improvements / nits that can be addressed in a follow-up if desired.

Strengths

  • Scope discipline. Exactly the 5 functions specified, no speculative extras. DeleteNode correctly omitted per issue scope. No Watch/Chat streaming complexity dragged in.
  • No proto duplication. Loads packages/daemon/proto/node_service.proto at runtime via import.meta.url-relative path. Verified that the ../../daemon/proto/... path resolves correctly from both src/ and dist/ (both are one level deep inside the package).
  • Lazy singleton + override hook. getClient() / resetClient() is a clean pattern; NODESPACED_ADDR env override is genuinely useful for tests and is exercised by connection-error.test.ts.
  • Structured error mapping. toToolError maps grpc.status codes to readable names and gives UNAVAILABLE a friendlier message. Satisfies the "no uncaught exceptions on connection failure" criterion.
  • Real connection-error integration test. connection-error.test.ts exercises the actual gRPC path against 127.0.0.1:1 and asserts a ToolError surfaces — more valuable than a pure-mock check.
  • Standards compliance. No any, no console.*, no lint suppressions, kebab-case filenames, ESM + Node ESM imports with .js extensions, bunx for scripts, preinstall enforces Bun. TS strict mode on.

Acceptance criteria mapping

Criterion Status
Package created and in Bun workspace (packages/* glob) Met
@grpc/grpc-js client to localhost:50051 Met (with NODESPACED_ADDR override)
searchSemantic calls SearchNodes with semantic: true Met
getNode, createNode, updateNode, getChildren Met
Connection error returns structured ToolError Met (integration test covers it)
Builds cleanly Met (dist/ artifacts present)
Unit tests cover each tool + connection error Met (15 tests across 3 files, all passing)
Code passes quality:fix Met (script is tsc --noEmit)

Findings

Suggested Improvements

  • src/tools.ts:53-72 — callUnary uses Function type for dynamic method lookup. The Record<string, Function> cast (line 59) loses all type safety on the gRPC call and is the one place the package leans on stringly-typed dispatch. A type-safe alternative would dispatch on a small union and call the methods directly, e.g.:

    function callUnary<TReq, TRes>(method: 'searchNodes' | 'getNode' | 'createNode' | 'updateNode' | 'getChildren', req: TReq): Promise<TRes>

    with a switch that invokes client.searchNodes(...) etc. directly. The current shape works because proto-loader generates the same callback signature for every unary method, but a typo in a method-name string would only surface at runtime as INTERNAL: gRPC method "X" not found. Rationale: type safety at compile time over runtime defensive checks (the existing if (typeof fn !== 'function') branch is dead code in practice).

  • src/tools.ts:84-156 — UpdateNodeRequest proto semantics. In the proto, content, properties, and version are optional so callers can distinguish "no change" (field absent) from "clear value" (field present, empty). The current updateNode always sends content and also sends nodeType: '', addToCollection: '', removeFromCollection: '', lifecycleStatus: ''. With proto3 semantics the empty strings on the non-optional fields are equivalent to "absent" server-side, so this is functionally correct for the agent use case ("set content to X"). Worth a one-line comment in updateNode flagging that the request shape intentionally treats empty strings as "no change" for the non-optional fields, since the proto explicitly comments on this. (Improvement, not a correctness issue.)

  • src/tools.ts:41-51 — fromNodeResponse fallback returns content: ''. When nodeData is undefined (which the proto promises will always be populated for GetNode/CreateNode/UpdateNode), the fallback silently substitutes empty content. If the server ever returns a response without node_data due to a bug, callers get content: '' instead of a clear error. Consider throwing a ToolError('INTERNAL', 'NodeResponse missing node_data') instead. Rationale: fail-loud beats silent data corruption for an "impossible" branch.

  • src/client.ts:9 — Proto path is implicit and untested. The path '../../daemon/proto/node_service.proto' is correct today but couples the package to the workspace layout silently. If packages/daemon ever moves, the failure mode is a runtime loadSync exception with no obvious connection to the layout change. Two low-cost mitigations: (a) add a one-line test that asserts the proto file exists at the resolved path, or (b) export the resolved PROTO_PATH from the module so a smoke test can verify it. (Improvement; defer if the daemon layout is stable.)

  • package.json:23 — quality:fix is tsc --noEmit. This is type-check only — it does not run a linter or formatter. The repo standard quality:fix for desktop-app runs lint+format+autofix. For a brand-new package this is acceptable (there's no eslint/prettier config in this package yet), but the script name is slightly misleading. Either rename to typecheck and add quality:fix once ESLint config is added, or document that this package intentionally has no lint stage yet. The issue's acceptance criterion ("Code passes bun run quality:fix") is technically satisfied either way.

  • Root package.json integration. The new package is picked up by the packages/* workspace glob, but no root-level script wires agent-tools into test:all or quality:check. Right now bun run test:all from the repo root runs desktop-app + rust tests only — agent-tools tests are skipped. This should be wired in before this package has downstream consumers, otherwise regressions here won't fail CI. Rationale: a test that isn't run is a test that doesn't exist.

Nitpicks

  • Nit: src/client.ts:15-21 — NodeServiceClient declares method types as grpc.handleUnaryCall<unknown, unknown>. handleUnaryCall is the server-side handler type; the client-side methods have a different signature ((request, metadata?, options?, callback) => ClientUnaryCall). It "works" because the cast on line 41 is as unknown as NodeServiceClient and callUnary immediately re-casts to Record<string, Function>. Consider typing this as grpc.Client & { searchNodes: (req, cb) => grpc.ClientUnaryCall; ... } for accuracy; current shape is harmless but misleading to a reader.

  • Nit: src/tests/tools.test.ts:72,94,107,124,143,158,176,191,214,230,247 — Every test does const { fn } = await import('../tools.js'). Since the module is the same across calls and the mock is set up at module scope (line 16), a single top-level import { searchSemantic, getNode, ... } from '../tools.js' would simplify the tests and avoid re-importing the same module 12 times. (No correctness impact — vitest caches the import.)

  • Nit: src/tests/connection-error.test.ts:24 — Using port 1 is fine, but on some systems gRPC may take longer than the default vitest timeout to surface the connect failure. The 10-second override (line 34) is appropriate; just flagging that if this becomes flaky in CI, 127.0.0.1:0 or a never-routable address might be more reliable.

  • Nit: src/types.ts:13-21 — ToolError is exported as a class with public readonly code. Consider also setting Object.setPrototypeOf(this, ToolError.prototype) for robustness when this error is thrown across module boundaries in transpiled code. With ES2022 target this is generally unnecessary, but it's the standard belt-and-suspenders pattern for Error subclasses.

  • Nit: src/tools.ts:5-30 — The Proto* interfaces duplicate the proto schema in TypeScript. As the proto grows, drift between these and the real wire format is a maintenance risk. Not worth fixing now (codegen was explicitly avoided per the issue), but worth a comment pointing to node_service.proto as the source of truth.

Security & Performance

  • Security: No hardcoded secrets, no user-controlled SQL/shell, gRPC is local-only as documented. createInsecure() credentials are appropriate for localhost:50051. Error messages include err.details/err.message from gRPC which could in theory leak server-side info, but for a local IPC client this is fine and aids debugging.
  • Performance: Lazy singleton avoids per-call channel setup. No N+1 patterns, no unbounded buffering. The fromNodeData map is O(n) on result sets which is fine.

Net Assessment

This is a textbook example of a self-contained, scope-disciplined foundation package. The implementation makes good tradeoffs (runtime proto loading vs codegen, lazy singleton vs DI, manual TS interfaces vs ts-proto). The findings above are all polish-level — none of them affect correctness or the next-issue work that builds on top of this.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed. Recommendation: approve (cannot self-approve via gh). All acceptance criteria met, implementation is clean and scope-disciplined. See the detailed review comment on the PR for findings — all are non-blocking improvements/nits. The one worth following up before downstream consumers land: wire agent-tools tests into the root test:all so regressions are caught in CI.

Implementation changes:
- Replace stringly-typed `callUnary` dispatch with a typed `promisify`
  helper that takes a bound method reference. Eliminates the
  `Record<string, Function>` cast and the dead "method not found" branch.
- Fix `NodeServiceClient` interface: the methods are *client-side*
  unary calls (request + callback → ClientUnaryCall), not server-side
  `handleUnaryCall` handlers. Add a `UnaryMethod` type alias.
- `fromNodeResponse` now throws `ToolError('INTERNAL', ...)` when
  `nodeData` is missing instead of silently substituting empty content.
  The proto guarantees this field is populated; surface the bug.
- Export `PROTO_PATH` from client.ts and add a test that asserts the
  file exists on disk — guards against silent breakage if
  `packages/daemon` is ever relocated.
- Add comment in tools.ts pointing to `node_service.proto` as the
  source of truth for the `Proto*` interfaces (codegen was avoided
  per the issue; the drift risk is now documented).
- Add comment in `updateNode` explaining the empty-string semantics
  for the non-optional enum-like fields (proto3 treats empty as
  "no change", matching the proto's inline comments).
- Wire `agent-tools` into root `test:all` (new `test:agent-tools`
  script) and root `quality:fix` so regressions in this package
  fail CI from the repo root, not just from the package directory.
- Tests: use top-level imports instead of 12 dynamic re-imports;
  add a test for the new fail-loud behavior on missing node_data.

Skipped (with reasoning):
- `setPrototypeOf` in ToolError — with ES2022 target this is genuinely
  unnecessary (the reviewer flagged it as "generally unnecessary");
  adding it is cargo-cult belt-and-suspenders.
- Switching connection-error.test from port 1 to never-routable
  address — speculative flake mitigation; test currently passes in
  ~100ms. Revisit only if it actually goes flaky.
- Renaming `quality:fix` to `typecheck` — the issue AC names
  `quality:fix` verbatim; keeping the name. The script does what
  it can without an ESLint config in this package yet.

Test results:
- agent-tools: 17/17 passing (was 15; +2 new tests)
- desktop-app: 128/128 files, 3918/3918 tests (baseline preserved)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed

Pushed 09abe125 with the changes below.

Addressed (7)

  • tools.ts — typed dispatch. Replaced callUnary with a promisify helper that takes a bound method reference. Killed the Record<string, Function> cast and the dead "method not found" runtime check.
  • client.ts — correct client-side method type. NodeServiceClient now uses a UnaryMethod<TReq, TRes> alias matching the real (request, callback) => ClientUnaryCall shape instead of handleUnaryCall (server-side handler type).
  • tools.ts — fail-loud on missing node_data. fromNodeResponse now throws ToolError('INTERNAL', ...) instead of returning a NodeResult with empty content. New test covers this branch.
  • client.ts — export PROTO_PATH + new test asserting the file exists at the resolved path. Guards against silent breakage if packages/daemon is ever relocated.
  • tools.ts — source-of-truth comment. Added a comment on the Proto* interfaces pointing to node_service.proto and noting why codegen was avoided.
  • tools.ts — updateNode semantics comment. Documents that empty strings on the non-optional enum-like fields mean "no change" per proto3 semantics + the proto's inline comments.
  • Tests — top-level imports. Removed 12 dynamic await import('../tools.js') calls in tools.test.ts; the file now uses standard top-level imports.

Workspace wiring

  • Added test:agent-tools script and wired it into root test:all + test:all:db.
  • Wired agent-tools/quality:fix into root quality:fix and quality:check.

Regressions in this package will now fail CI from the repo root, not just from the package directory.

Skipped (with reasoning, 3)

  • setPrototypeOf(this, ToolError.prototype) — with ES2022 target this is genuinely unnecessary; the reviewer flagged it as "generally unnecessary." Adding it would be cargo-cult belt-and-suspenders.
  • Port 1 → never-routable address in connection-error.test.ts — speculative flake mitigation; the test currently passes in ~100ms. Will revisit only if it actually goes flaky in CI.
  • Renaming quality:fix to typecheck — the issue acceptance criterion names bun run quality:fix verbatim. Keeping the name to avoid an AC mismatch; the script does the right thing for a package that doesn't yet have an ESLint config.

Test results

  • @nodespace/agent-tools: 17/17 passing (was 15; +2 new tests for the fail-loud branch and proto-path existence check)
  • nodespace-app (desktop-app): 128/128 files, 3918/3918 tests (baseline preserved, no regressions)
  • bun run --cwd packages/desktop-app quality:fix: 0 errors, 0 warnings
  • bun run --cwd packages/agent-tools quality:fix: type-check clean

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The changes are all polish-level refactors (typed dispatch, accurate types, comments, test coverage of an existing branch) plus workspace wiring. No new functionality, no architectural shifts, no API changes. The test suite expanded by 2 tests, both directly covering the new behavior (proto-path existence, fail-loud on missing node_data). Frontend baseline preserved exactly. Ready for merge pending approval.

@malibio
malibio merged commit d4d3651 into main May 18, 2026
@malibio
malibio deleted the feature/issue-1122-agent-tools-package branch May 18, 2026 01:50
malibio added a commit that referenced this pull request Jun 22, 2026
…) (#1146)

* Add @nodespace/agent-tools TypeScript gRPC client package

Create the shared TypeScript foundation that per-agent shims (Claude Code,
Codex, Gemini, Pi, OpenCode) will use to read and write the NodeSpace
knowledge graph during a session. Exposes five tool functions backed by a
pure-TS @grpc/grpc-js client against nodespaced on localhost:50051.

- searchSemantic(query, limit?) → SearchNodes in semantic mode
- getNode(nodeId) → GetNode
- createNode(type, content, parentId?) → CreateNode
- updateNode(nodeId, content) → UpdateNode
- getChildren(nodeId) → GetChildren

The gRPC channel is a lazy singleton; address is overridable via
NODESPACED_ADDR. All gRPC errors are normalized into a typed ToolError
with the grpc.status code as the error code, so connection failures
surface as structured errors instead of uncaught exceptions.

Proto is loaded at runtime via @grpc/proto-loader against
packages/daemon/proto/node_service.proto — no duplication, no codegen
step. 15 tests cover each tool function, proto loading, client caching,
and a real connection failure against an unused port.

Closes #1122

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address PR #1146 review feedback

Implementation changes:
- Replace stringly-typed `callUnary` dispatch with a typed `promisify`
  helper that takes a bound method reference. Eliminates the
  `Record<string, Function>` cast and the dead "method not found" branch.
- Fix `NodeServiceClient` interface: the methods are *client-side*
  unary calls (request + callback → ClientUnaryCall), not server-side
  `handleUnaryCall` handlers. Add a `UnaryMethod` type alias.
- `fromNodeResponse` now throws `ToolError('INTERNAL', ...)` when
  `nodeData` is missing instead of silently substituting empty content.
  The proto guarantees this field is populated; surface the bug.
- Export `PROTO_PATH` from client.ts and add a test that asserts the
  file exists on disk — guards against silent breakage if
  `packages/daemon` is ever relocated.
- Add comment in tools.ts pointing to `node_service.proto` as the
  source of truth for the `Proto*` interfaces (codegen was avoided
  per the issue; the drift risk is now documented).
- Add comment in `updateNode` explaining the empty-string semantics
  for the non-optional enum-like fields (proto3 treats empty as
  "no change", matching the proto's inline comments).
- Wire `agent-tools` into root `test:all` (new `test:agent-tools`
  script) and root `quality:fix` so regressions in this package
  fail CI from the repo root, not just from the package directory.
- Tests: use top-level imports instead of 12 dynamic re-imports;
  add a test for the new fail-loud behavior on missing node_data.

Skipped (with reasoning):
- `setPrototypeOf` in ToolError — with ES2022 target this is genuinely
  unnecessary (the reviewer flagged it as "generally unnecessary");
  adding it is cargo-cult belt-and-suspenders.
- Switching connection-error.test from port 1 to never-routable
  address — speculative flake mitigation; test currently passes in
  ~100ms. Revisit only if it actually goes flaky.
- Renaming `quality:fix` to `typecheck` — the issue AC names
  `quality:fix` verbatim; keeping the name. The script does what
  it can without an ESLint config in this package yet.

Test results:
- agent-tools: 17/17 passing (was 15; +2 new tests)
- desktop-app: 128/128 files, 3918/3918 tests (baseline preserved)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
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