@agent-assembly/sdk 0.0.1-beta.3 → 0.0.1-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +36 -23
  2. package/dist/cjs/core/gateway-resolver.js +73 -3
  3. package/dist/cjs/core/init-assembly.js +155 -33
  4. package/dist/cjs/core/redact.js +63 -0
  5. package/dist/cjs/gateway/client.js +63 -1
  6. package/dist/cjs/gateway/index.js +2 -1
  7. package/dist/cjs/hooks/ai-sdk.js +46 -10
  8. package/dist/cjs/hooks/langchain.js +12 -3
  9. package/dist/cjs/hooks/mastra.js +10 -6
  10. package/dist/cjs/hooks/openai-agents.js +1 -3
  11. package/dist/cjs/index.js +9 -1
  12. package/dist/cjs/native/client.js +94 -25
  13. package/dist/cjs/op-control.js +159 -17
  14. package/dist/cjs/runtime.js +73 -7
  15. package/dist/cjs/wrappers/with-assembly.js +89 -32
  16. package/dist/esm/core/gateway-resolver.js +72 -3
  17. package/dist/esm/core/gateway-resolver.js.map +1 -1
  18. package/dist/esm/core/init-assembly.js +154 -32
  19. package/dist/esm/core/init-assembly.js.map +1 -1
  20. package/dist/esm/core/redact.js +59 -0
  21. package/dist/esm/core/redact.js.map +1 -0
  22. package/dist/esm/gateway/client.js +62 -1
  23. package/dist/esm/gateway/client.js.map +1 -1
  24. package/dist/esm/gateway/index.js +1 -1
  25. package/dist/esm/gateway/index.js.map +1 -1
  26. package/dist/esm/hooks/ai-sdk.js +46 -10
  27. package/dist/esm/hooks/ai-sdk.js.map +1 -1
  28. package/dist/esm/hooks/langchain.js +12 -3
  29. package/dist/esm/hooks/langchain.js.map +1 -1
  30. package/dist/esm/hooks/mastra.js +10 -6
  31. package/dist/esm/hooks/mastra.js.map +1 -1
  32. package/dist/esm/hooks/openai-agents.js +1 -3
  33. package/dist/esm/hooks/openai-agents.js.map +1 -1
  34. package/dist/esm/index.js +6 -0
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/native/client.js +91 -24
  37. package/dist/esm/native/client.js.map +1 -1
  38. package/dist/esm/op-control.js +124 -17
  39. package/dist/esm/op-control.js.map +1 -1
  40. package/dist/esm/runtime.js +72 -7
  41. package/dist/esm/runtime.js.map +1 -1
  42. package/dist/esm/wrappers/with-assembly.js +89 -32
  43. package/dist/esm/wrappers/with-assembly.js.map +1 -1
  44. package/dist/types/core/gateway-resolver.d.ts +18 -1
  45. package/dist/types/core/gateway-resolver.d.ts.map +1 -1
  46. package/dist/types/core/init-assembly.d.ts +2 -1
  47. package/dist/types/core/init-assembly.d.ts.map +1 -1
  48. package/dist/types/core/redact.d.ts +28 -0
  49. package/dist/types/core/redact.d.ts.map +1 -0
  50. package/dist/types/gateway/client.d.ts +17 -0
  51. package/dist/types/gateway/client.d.ts.map +1 -1
  52. package/dist/types/gateway/index.d.ts +1 -1
  53. package/dist/types/gateway/index.d.ts.map +1 -1
  54. package/dist/types/hooks/ai-sdk.d.ts +13 -0
  55. package/dist/types/hooks/ai-sdk.d.ts.map +1 -1
  56. package/dist/types/hooks/langchain.d.ts +11 -0
  57. package/dist/types/hooks/langchain.d.ts.map +1 -1
  58. package/dist/types/hooks/mastra.d.ts.map +1 -1
  59. package/dist/types/hooks/openai-agents.d.ts.map +1 -1
  60. package/dist/types/index.d.ts +4 -1
  61. package/dist/types/index.d.ts.map +1 -1
  62. package/dist/types/native/client.d.ts +44 -0
  63. package/dist/types/native/client.d.ts.map +1 -1
  64. package/dist/types/op-control.d.ts +71 -7
  65. package/dist/types/op-control.d.ts.map +1 -1
  66. package/dist/types/runtime.d.ts +27 -5
  67. package/dist/types/runtime.d.ts.map +1 -1
  68. package/dist/types/types/assembly-config.d.ts +6 -0
  69. package/dist/types/types/assembly-config.d.ts.map +1 -1
  70. package/dist/types/wrappers/index.d.ts +1 -1
  71. package/dist/types/wrappers/index.d.ts.map +1 -1
  72. package/dist/types/wrappers/with-assembly.d.ts +25 -0
  73. package/dist/types/wrappers/with-assembly.d.ts.map +1 -1
  74. package/native/aa-ffi-node/index.d.ts +82 -1
  75. package/package.json +18 -5
package/README.md CHANGED
@@ -122,6 +122,20 @@ system. The matrix is enforced by `.github/workflows/test-matrix.yml`:
122
122
  Older Node.js lines (≤ 16) are unsupported because the napi-rs ABI used by the native
123
123
  binding requires Node 18.18 or newer.
124
124
 
125
+ ## Framework compatibility
126
+
127
+ `initAssembly()` auto-detects and governs five optional framework integrations
128
+ (LangChain.js, LangGraph.js, Vercel AI SDK, Mastra, OpenAI Agents). The full table —
129
+ each framework's optional peer dependency, supported version range, and current status
130
+ (including the [known Vercel AI SDK caveat](https://lightning-dust-mite.atlassian.net/browse/AAASM-3532)) —
131
+ is the **authoritative** reference and lives on the docs site:
132
+ [Framework compatibility](https://ai-agent-assembly.github.io/node-sdk/compatibility-versioning/compatibility).
133
+
134
+ For the product-wide, cross-SDK index/hub that links every language SDK's matrix, see the
135
+ core documentation:
136
+ [Framework compatibility index](https://ai-agent-assembly.github.io/agent-assembly/stable/reference/framework-compatibility.html)
137
+ (the `/stable/` link goes live at GA).
138
+
125
139
  ## How it works
126
140
 
127
141
  The SDK is a thin TypeScript wrapper around the Agent Assembly Rust runtime. It reaches
@@ -136,16 +150,16 @@ call is checked against policy before it runs.
136
150
 
137
151
  ## What the package exports
138
152
 
139
- | Export | Purpose |
140
- | ------ | ------- |
141
- | `initAssembly(config)` | Set up governance and auto-wire detected frameworks. The main entrypoint. |
142
- | `withAssembly(tools, options)` | Lower-level wrapper to govern a tool map when you manage the gateway client yourself. |
143
- | `createNoopGatewayClient(mode)` | Build an allow-all `GatewayClient` for offline demos and tests, or as a base to wrap. |
144
- | `PolicyViolationError` | Thrown by a governed tool when the gateway client denies the call. |
145
- | `currentAgentId()`, `runWithAgentId()` | Read and set the active agent id in the async-context lineage store. |
146
- | `encodeAuditEvent()` / `decodeAuditEvent()` (and the call-stack codecs) | Encode and decode audit events to and from their wire shape. |
147
- | `findAasmBinary()`, `INSTALL_HINT` | Locate the bundled `aasm` runtime binary and the install hint shown when it is missing. |
148
- | `ENFORCEMENT_MODES` | The allowed `enforcementMode` values. |
153
+ | Export | Purpose |
154
+ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
155
+ | `initAssembly(config)` | Set up governance and auto-wire detected frameworks. The main entrypoint. |
156
+ | `withAssembly(tools, options)` | Lower-level wrapper to govern a tool map when you manage the gateway client yourself. |
157
+ | `createNoopGatewayClient(mode)` | Build an allow-all `GatewayClient` for offline demos and tests, or as a base to wrap. |
158
+ | `PolicyViolationError` | Thrown by a governed tool when the gateway client denies the call. |
159
+ | `currentAgentId()`, `runWithAgentId()` | Read and set the active agent id in the async-context lineage store. |
160
+ | `encodeAuditEvent()` / `decodeAuditEvent()` (and the call-stack codecs) | Encode and decode audit events to and from their wire shape. |
161
+ | `findAasmBinary()`, `INSTALL_HINT` | Locate the bundled `aasm` runtime binary and the install hint shown when it is missing. |
162
+ | `ENFORCEMENT_MODES` | The allowed `enforcementMode` values. |
149
163
 
150
164
  Type-only exports (`AssemblyConfig`, `AssemblyContext`, `AssemblyMode`, `EnforcementMode`,
151
165
  `ToolMap`, `GatewayClient`, the `Gateway*` governance types, and friends) are documented in
@@ -157,11 +171,7 @@ the [API reference](https://ai-agent-assembly.github.io/node-sdk/api-reference).
157
171
  in-process policies you can build one yourself — no running gateway required:
158
172
 
159
173
  ```ts
160
- import {
161
- createNoopGatewayClient,
162
- withAssembly,
163
- type GatewayClient
164
- } from "@agent-assembly/sdk";
174
+ import { createNoopGatewayClient, withAssembly, type GatewayClient } from "@agent-assembly/sdk";
165
175
 
166
176
  // Allow-all client — handy for offline smoke tests:
167
177
  withAssembly(
@@ -285,15 +295,15 @@ and is re-published on every push to `master` via the `publish-docs.yml` workflo
285
295
  decisions it enforces are made by the core Rust runtime; the protocol it speaks is shared
286
296
  across all SDKs.
287
297
 
288
- | Project | What it is |
289
- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
290
- | [agent-assembly](https://github.com/ai-agent-assembly/agent-assembly) | Core Rust runtime — gateway, policy engine, proxy, eBPF, CLI (`aasm`). The protocol specification lives here. |
291
- | [Documentation site](https://ai-agent-assembly.github.io/agent-assembly-docs/) | Canonical, cross-repo documentation for the whole platform. |
292
- | [python-sdk](https://github.com/ai-agent-assembly/python-sdk) | Sibling SDK for Python. |
293
- | [go-sdk](https://github.com/ai-agent-assembly/go-sdk) | Sibling SDK for Go. |
298
+ | Project | What it is |
299
+ | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
300
+ | [agent-assembly](https://github.com/ai-agent-assembly/agent-assembly) | Core Rust runtime — gateway, policy engine, proxy, eBPF, CLI (`aasm`). The protocol specification lives here. |
301
+ | [Documentation site](https://ai-agent-assembly.github.io/agent-assembly-docs/) | Canonical, cross-repo documentation for the whole platform. |
302
+ | [python-sdk](https://github.com/ai-agent-assembly/python-sdk) | Sibling SDK for Python. |
303
+ | [go-sdk](https://github.com/ai-agent-assembly/go-sdk) | Sibling SDK for Go. |
294
304
  | [agent-assembly-examples](https://github.com/ai-agent-assembly/agent-assembly-examples) | Runnable examples — learn by running small, framework-specific Node.js/TypeScript (and Python/Go) samples for policy enforcement, approvals, audit, trace, and runtime workflows. |
295
- | [Release notes](https://github.com/ai-agent-assembly/node-sdk/releases) | Per-version changelog for this package. |
296
- | [Organization profile](https://github.com/ai-agent-assembly) | Index of every Agent Assembly repository and its status. |
305
+ | [Release notes](https://github.com/ai-agent-assembly/node-sdk/releases) | Per-version changelog for this package. |
306
+ | [Organization profile](https://github.com/ai-agent-assembly) | Index of every Agent Assembly repository and its status. |
297
307
 
298
308
  ## Support & security
299
309
 
@@ -304,5 +314,8 @@ across all SDKs.
304
314
  via the repository's
305
315
  [security advisories](https://github.com/ai-agent-assembly/node-sdk/security/advisories)
306
316
  page so a fix can be coordinated before disclosure.
317
+ - **Canonical package names + verifying your install** — see [SECURITY.md](./SECURITY.md)
318
+ for the authoritative `@agent-assembly/*` package list (to spot typosquats) and how to
319
+ verify npm provenance (`npm audit signatures`) and the per-release CycloneDX SBOM.
307
320
  - **Contributing** — see [CONTRIBUTING.md](./CONTRIBUTING.md) for environment setup, the
308
321
  adapter-authoring guide, and the test/commit conventions.
@@ -33,7 +33,8 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.__testing = exports.AASM_AUTO_START_ARGV = exports.LEGACY_ENV_API_KEY = exports.LEGACY_ENV_GATEWAY_URL = exports.ENV_API_KEY = exports.ENV_GATEWAY_URL = exports.DEFAULT_CONFIG_FILE_PATH = exports.DEFAULT_AUTO_START_TIMEOUT_MS = exports.DEFAULT_PROBE_TIMEOUT_MS = exports.DEFAULT_HEALTHZ_PATH = exports.DEFAULT_GATEWAY_URL = void 0;
36
+ exports.__testing = exports.AASM_AUTO_START_ARGV = exports.LEGACY_ENV_API_KEY = exports.LEGACY_ENV_GATEWAY_URL = exports.ENV_AUTO_START = exports.ENV_API_KEY = exports.ENV_GATEWAY_URL = exports.DEFAULT_CONFIG_FILE_PATH = exports.DEFAULT_AUTO_START_TIMEOUT_MS = exports.DEFAULT_PROBE_TIMEOUT_MS = exports.DEFAULT_HEALTHZ_PATH = exports.DEFAULT_GATEWAY_URL = void 0;
37
+ exports.assertAllowedAasmPath = assertAllowedAasmPath;
37
38
  exports.probeHealthz = probeHealthz;
38
39
  exports.waitForHealthz = waitForHealthz;
39
40
  exports.loadConfigFile = loadConfigFile;
@@ -61,7 +62,9 @@ const index_js_1 = require("../errors/index.js");
61
62
  * as deprecated aliases (a one-time warning is logged when a legacy name
62
63
  * supplies the value)
63
64
  * 3. Config file (~/.aasm/config.yaml, optional js-yaml soft dep)
64
- * 4. Local default: probe http://localhost:7391, auto-start if absent
65
+ * 4. Local default: probe http://localhost:7391; when absent, auto-start the
66
+ * local `aasm` gateway ONLY if `AA_AUTO_START` is opted in and the binary
67
+ * resolves to an allow-listed install dir — otherwise raise an error.
65
68
  */
66
69
  exports.DEFAULT_GATEWAY_URL = "http://localhost:7391";
67
70
  exports.DEFAULT_HEALTHZ_PATH = "/healthz";
@@ -70,6 +73,56 @@ exports.DEFAULT_AUTO_START_TIMEOUT_MS = 5000;
70
73
  exports.DEFAULT_CONFIG_FILE_PATH = "~/.aasm/config.yaml";
71
74
  exports.ENV_GATEWAY_URL = "AA_GATEWAY_URL";
72
75
  exports.ENV_API_KEY = "AA_API_KEY";
76
+ /**
77
+ * Opt-in gate for auto-starting a local gateway. Auto-start spawns the `aasm`
78
+ * binary resolved from `$PATH`, so it is gated behind an explicit opt-in rather
79
+ * than running silently: a `$PATH` entry an attacker can write to would
80
+ * otherwise be executed by any process that calls `initAssembly()`. Set to
81
+ * `1`/`true`/`yes` to permit auto-start.
82
+ */
83
+ exports.ENV_AUTO_START = "AA_AUTO_START";
84
+ /** Truthy values that enable {@link ENV_AUTO_START}. */
85
+ function autoStartEnabled() {
86
+ const raw = process.env[exports.ENV_AUTO_START]?.trim().toLowerCase();
87
+ return raw === "1" || raw === "true" || raw === "yes";
88
+ }
89
+ /**
90
+ * Directories an auto-started `aasm` binary is permitted to live in. The
91
+ * resolved path must be absolute and sit inside one of these install roots,
92
+ * which blocks a `$PATH`-injected `./aasm` (cwd) or a binary planted in an
93
+ * arbitrary writable directory from being spawned. Mirrors the documented
94
+ * install locations (Homebrew, system, user-local, cargo).
95
+ */
96
+ function allowedInstallDirs() {
97
+ const home = (0, node_os_1.homedir)();
98
+ return [
99
+ "/usr/local/bin",
100
+ "/usr/bin",
101
+ "/opt/homebrew/bin",
102
+ (0, node_path_1.join)(home, ".local", "bin"),
103
+ (0, node_path_1.join)(home, ".cargo", "bin"),
104
+ "/usr/local/cargo/bin",
105
+ ];
106
+ }
107
+ /**
108
+ * Throw {@link ConfigurationError} unless `aasmPath` is an absolute path inside
109
+ * an allow-listed install directory (see {@link allowedInstallDirs}). This is
110
+ * the integrity gate for the auto-start subprocess — without it the SDK would
111
+ * execute whatever `aasm` happened to be first on `$PATH`.
112
+ */
113
+ function assertAllowedAasmPath(aasmPath) {
114
+ if (!(0, node_path_1.isAbsolute)(aasmPath)) {
115
+ throw new index_js_1.ConfigurationError(`Refusing to auto-start a non-absolute 'aasm' path: ${aasmPath}. ` +
116
+ `Set ${exports.ENV_GATEWAY_URL} to an already-running gateway instead.`);
117
+ }
118
+ const resolved = (0, node_path_1.resolve)(aasmPath);
119
+ const ok = allowedInstallDirs().some((dir) => resolved.startsWith(dir + "/"));
120
+ if (!ok) {
121
+ throw new index_js_1.ConfigurationError(`Refusing to auto-start 'aasm' from an untrusted location: ${resolved}. ` +
122
+ `Install it under one of: ${allowedInstallDirs().join(", ")}, ` +
123
+ `or set ${exports.ENV_GATEWAY_URL} to an already-running gateway.`);
124
+ }
125
+ }
73
126
  /**
74
127
  * Deprecated environment-variable names, kept as backwards-compatible aliases.
75
128
  *
@@ -154,7 +207,11 @@ async function waitForHealthz(baseUrl, timeoutMs = exports.DEFAULT_AUTO_START_TI
154
207
  return probeHealthz(baseUrl);
155
208
  }
156
209
  function expandHome(p) {
157
- return p.startsWith("~") ? (0, node_path_1.resolve)((0, node_os_1.homedir)(), p.slice(p.startsWith("~/") ? 2 : 1)) : p;
210
+ if (!p.startsWith("~")) {
211
+ return p;
212
+ }
213
+ const prefixLength = p.startsWith("~/") ? 2 : 1;
214
+ return (0, node_path_1.resolve)((0, node_os_1.homedir)(), p.slice(prefixLength));
158
215
  }
159
216
  /**
160
217
  * Load ``~/.aasm/config.yaml`` if present.
@@ -246,6 +303,11 @@ async function autoStartGateway(baseUrl = exports.DEFAULT_GATEWAY_URL, timeoutMs
246
303
  throw new index_js_1.ConfigurationError(`No gateway found at ${baseUrl} and 'aasm' is not on PATH. ` +
247
304
  "Install it with: npm install -g @agent-assembly/cli (or pnpm add -g)");
248
305
  }
306
+ // Integrity gate: only spawn an absolute path from an allow-listed install
307
+ // dir, and surface the resolved path so the operator can see exactly which
308
+ // binary the SDK is about to execute.
309
+ assertAllowedAasmPath(aasmPath);
310
+ console.info(`[agent-assembly] auto-starting gateway from ${aasmPath}`);
249
311
  _seams.spawnAasm(aasmPath);
250
312
  if (!(await waitForHealthz(baseUrl, timeoutMs))) {
251
313
  throw new index_js_1.GatewayError(`Auto-started gateway at ${baseUrl} did not become ready ` +
@@ -276,6 +338,14 @@ async function resolveGatewayUrl(explicit) {
276
338
  if (await _seams.probeHealthz(exports.DEFAULT_GATEWAY_URL)) {
277
339
  return exports.DEFAULT_GATEWAY_URL;
278
340
  }
341
+ // Auto-start is opt-in: spawning the local `aasm` binary is a privileged
342
+ // side effect, so a missing gateway is a hard error unless the operator has
343
+ // explicitly enabled AA_AUTO_START.
344
+ if (!autoStartEnabled()) {
345
+ throw new index_js_1.ConfigurationError(`No gateway found at ${exports.DEFAULT_GATEWAY_URL}. Start one with 'aasm start ` +
346
+ `--mode local', set ${exports.ENV_GATEWAY_URL} to a running gateway, or set ` +
347
+ `${exports.ENV_AUTO_START}=1 to allow the SDK to auto-start a local gateway.`);
348
+ }
279
349
  await _seams.autoStartGateway(exports.DEFAULT_GATEWAY_URL);
280
350
  return exports.DEFAULT_GATEWAY_URL;
281
351
  }
@@ -42,6 +42,7 @@ exports.initAssembly = initAssembly;
42
42
  const node_module_1 = require("node:module");
43
43
  const client_js_1 = require("../gateway/client.js");
44
44
  const client_js_2 = require("../native/client.js");
45
+ const index_js_1 = require("../errors/index.js");
45
46
  const enforcement_mode_js_1 = require("../types/enforcement-mode.js");
46
47
  const ai_sdk_detection_js_1 = require("../hooks/ai-sdk-detection.js");
47
48
  const ai_sdk_js_1 = require("../hooks/ai-sdk.js");
@@ -51,8 +52,9 @@ const mastra_detection_js_1 = require("../hooks/mastra-detection.js");
51
52
  const mastra_js_1 = require("../hooks/mastra.js");
52
53
  const openai_agents_detection_js_1 = require("../hooks/openai-agents-detection.js");
53
54
  const openai_agents_js_1 = require("../hooks/openai-agents.js");
54
- const index_js_1 = require("../lineage/index.js");
55
+ const index_js_2 = require("../lineage/index.js");
55
56
  const gateway_resolver_js_1 = require("./gateway-resolver.js");
57
+ const redact_js_1 = require("./redact.js");
56
58
  const requireFromCwd = (0, node_module_1.createRequire)(`${process.cwd()}/`);
57
59
  /** Env-var fallback for ``gatewayUrl`` read at ``initAssembly`` entry. */
58
60
  exports.ENV_GATEWAY_URL = "AA_GATEWAY_URL";
@@ -76,14 +78,73 @@ function buildRegistrationEvent(config) {
76
78
  event.enforcement_mode = config.enforcementMode;
77
79
  return event;
78
80
  }
79
- function createClient(config) {
81
+ /**
82
+ * Build the {@link RegisterOptions} for the native `register` gRPC call
83
+ * (AAASM-3400) from the resolved config and the detected frameworks. `name`
84
+ * falls back to `agentId`; `framework` is the first detected framework (or
85
+ * `"none"` when running without an adapter); `gatewayEndpoint` is set only when
86
+ * a gateway URL was resolved so the native default endpoint resolution is
87
+ * preserved when it was not. `teamId` / `parentAgentId` carry the agent's
88
+ * team-budget scoping and topology lineage to the gateway (AAASM-3415); each is
89
+ * set only when present so an unset field stays absent.
90
+ */
91
+ function buildRegisterOptions(config, frameworks) {
92
+ const agentId = config.agentId ?? "";
93
+ return {
94
+ agentId,
95
+ name: config.name ?? agentId,
96
+ framework: frameworks[0] ?? "none",
97
+ ...(config.gatewayUrl ? { gatewayEndpoint: config.gatewayUrl } : {}),
98
+ ...(config.teamId ? { teamId: config.teamId } : {}),
99
+ ...(config.parentAgentId ? { parentAgentId: config.parentAgentId } : {})
100
+ };
101
+ }
102
+ /**
103
+ * The only built-in {@link AssemblyMode} for which {@link createClient}
104
+ * constructs a gateway client whose `check()` consults a real authoritative
105
+ * verdict (the native `queryPolicy` against a reachable `aa-runtime`). Every
106
+ * other mode falls back to the allow-all no-op client.
107
+ */
108
+ const CHECK_CAPABLE_MODE = "napi-inprocess";
109
+ function createClient(config, nativeClientOverride) {
80
110
  const mode = config.mode ?? "auto";
81
111
  if (config.gatewayClient) {
82
112
  return config.gatewayClient;
83
113
  }
114
+ // AAASM-3105 (fail closed): the no-op gateway client's `check()` is allow-all,
115
+ // so registering under live `"enforce"` while routing through it would let a
116
+ // policy-denied action proceed unchecked — a silent fail-open. When the caller
117
+ // explicitly asks for `"enforce"` but supplies no check-capable mode (and no
118
+ // own `gatewayClient`), refuse loudly instead of pretending to enforce. An
119
+ // omitted `enforcementMode` keeps the pre-feature behavior (server-side
120
+ // default), and `"observe"` / `"disabled"` intentionally let actions through.
121
+ if (config.enforcementMode === "enforce" && mode !== CHECK_CAPABLE_MODE) {
122
+ throw new index_js_1.ConfigurationError(`enforcementMode "enforce" requires a check-capable client, but mode "${mode}" ` +
123
+ `routes through the allow-all no-op gateway client, which cannot block a ` +
124
+ `denied action. Use mode "${CHECK_CAPABLE_MODE}", supply your own ` +
125
+ `gatewayClient, or set enforcementMode to "observe"/"disabled".`);
126
+ }
84
127
  // HTTP routes use controlPlaneUrl when set, otherwise fall back to the
85
128
  // resolved gatewayUrl so pre-feature callers keep their existing base URL.
86
129
  const httpBaseUrl = config.controlPlaneUrl ?? config.gatewayUrl;
130
+ // AAASM-3050: in napi-inprocess mode, route `check()` through the native
131
+ // runtime so a reachable aa-runtime's DENY actually blocks a tool. The
132
+ // native primitive fails open when the runtime is absent or slow, and the
133
+ // gateway client swallows local faults, so this never blocks without a
134
+ // runtime — preserving the pre-feature fail-open behavior.
135
+ if (mode === "napi-inprocess") {
136
+ // Reuse the caller-supplied native client when present so the registered
137
+ // session (the one `register()` stored the gateway token on) is the same
138
+ // session `queryPolicy` runs against. Standalone callers (and the routing
139
+ // tests) get a freshly-built client instead.
140
+ const nativeClient = nativeClientOverride ??
141
+ (0, client_js_2.createNativeClient)({
142
+ gateway: config.gatewayUrl ?? "",
143
+ apiKey: config.apiKey ?? "",
144
+ mode: "napi-inprocess"
145
+ });
146
+ return (0, client_js_1.createNativeGatewayClient)(mode, nativeClient, config.agentId, httpBaseUrl);
147
+ }
87
148
  return (0, client_js_1.createNoopGatewayClient)(mode, httpBaseUrl);
88
149
  }
89
150
  function isPackageInstalled(packageName) {
@@ -177,7 +238,7 @@ async function patchDetectedVercelAiSdk(client, frameworks, agentId) {
177
238
  }
178
239
  return (0, ai_sdk_js_1.patchVercelAiSdk)({
179
240
  gatewayClient: client,
180
- ...(agentId !== undefined ? { agentId } : {})
241
+ ...(agentId === undefined ? {} : { agentId })
181
242
  });
182
243
  }
183
244
  async function patchDetectedLangGraph(frameworks, agentId) {
@@ -198,7 +259,13 @@ async function patchDetectedOpenAIAgents(client, frameworks) {
198
259
  }
199
260
  return (0, openai_agents_js_1.patchOpenAIAgents)({ gatewayClient: client });
200
261
  }
201
- async function initAssembly(config = {}) {
262
+ /**
263
+ * Validate caller-supplied `initAssembly` config, throwing `RangeError` on the
264
+ * two fields that can arrive malformed from non-TS callers (plain JS, JSON
265
+ * config, dynamic input). Extracted to keep `initAssembly` below the cognitive
266
+ * complexity threshold; behaviour-preserving.
267
+ */
268
+ function validateConfig(config) {
202
269
  if (config.delegationReason !== undefined && config.delegationReason.length > 256) {
203
270
  throw new RangeError("delegationReason must be <= 256 characters");
204
271
  }
@@ -208,9 +275,51 @@ async function initAssembly(config = {}) {
208
275
  if (config.enforcementMode !== undefined && !enforcement_mode_js_1.ENFORCEMENT_MODES.includes(config.enforcementMode)) {
209
276
  throw new RangeError(`enforcementMode must be one of: ${enforcement_mode_js_1.ENFORCEMENT_MODES.join(", ")} (got: ${String(config.enforcementMode)})`);
210
277
  }
278
+ }
279
+ /**
280
+ * Run every framework detect-and-patch path for the resolved config. Extracted
281
+ * from `initAssembly` to keep its cognitive complexity below threshold;
282
+ * behaviour-preserving (same calls, same order).
283
+ */
284
+ async function applyFrameworkPatches(config, client, frameworks) {
285
+ const langChainHandler = await registerLangChainHandler(config, client, frameworks);
286
+ const wrappedLangChainTools = await wrapLangChainTools(config, client, frameworks);
287
+ const vercelAiSdkPatched = await patchDetectedVercelAiSdk(client, frameworks, config.agentId);
288
+ const openAIAgentsPatched = await patchDetectedOpenAIAgents(client, frameworks);
289
+ const langGraphPatched = await patchDetectedLangGraph(frameworks, config.agentId);
290
+ const mastraPatched = await patchDetectedMastra(frameworks, config.agentId);
291
+ return {
292
+ langChainHandler,
293
+ wrappedLangChainTools,
294
+ vercelAiSdkPatched,
295
+ openAIAgentsPatched,
296
+ langGraphPatched,
297
+ mastraPatched
298
+ };
299
+ }
300
+ /**
301
+ * Build the deduped list of active adapter ids from the registered adapters plus
302
+ * whichever framework patches actually took effect. Extracted from
303
+ * `initAssembly` to keep its cognitive complexity below threshold.
304
+ */
305
+ function buildActiveAdapters(adapters, patches) {
306
+ return [
307
+ ...new Set([
308
+ ...adapters.map((adapter) => adapter.id),
309
+ ...(patches.langChainHandler ? ["langchain-js"] : []),
310
+ ...(patches.wrappedLangChainTools.length > 0 ? ["langchain-js"] : []),
311
+ ...(patches.vercelAiSdkPatched ? ["vercel-ai-sdk"] : []),
312
+ ...(patches.openAIAgentsPatched ? ["openai-agents"] : []),
313
+ ...(patches.langGraphPatched ? ["langgraph-js"] : []),
314
+ ...(patches.mastraPatched ? ["mastra"] : [])
315
+ ])
316
+ ];
317
+ }
318
+ async function initAssembly(config = {}) {
319
+ validateConfig(config);
211
320
  // Auto-populate parentAgentId from the async context store when not explicitly provided.
212
321
  // This allows child agents spawned inside framework hooks to inherit lineage automatically.
213
- const resolvedParentAgentId = config.parentAgentId ?? (0, index_js_1.currentAgentId)();
322
+ const resolvedParentAgentId = config.parentAgentId ?? (0, index_js_2.currentAgentId)();
214
323
  // Env-var fallbacks read at entry: explicit config field > env-var > the
215
324
  // downstream resolver chain (which may itself error if required and absent).
216
325
  const gatewayUrlInput = config.gatewayUrl ?? process.env[exports.ENV_GATEWAY_URL];
@@ -221,47 +330,60 @@ async function initAssembly(config = {}) {
221
330
  ...config,
222
331
  gatewayUrl: resolvedGatewayUrl,
223
332
  apiKey: resolvedApiKey,
224
- ...(controlPlaneUrlInput !== undefined ? { controlPlaneUrl: controlPlaneUrlInput } : {}),
333
+ ...(controlPlaneUrlInput === undefined ? {} : { controlPlaneUrl: controlPlaneUrlInput }),
225
334
  ...(resolvedParentAgentId ? { parentAgentId: resolvedParentAgentId } : {})
226
335
  };
227
- const client = createClient(resolvedConfig);
228
336
  const frameworks = detectFrameworks();
229
- const adapters = await registerAdapters(frameworks);
230
- await startNetworkLayerIfNeeded(client, resolvedConfig);
231
- // Send topology registration event through the native transport on every boot
232
- // except sdk-only mode (which has no sidecar to register with).
337
+ // Build the native transport up front (every mode except sdk-only, which has
338
+ // no sidecar) so the same session backs both the gateway client's `check()`
339
+ // and the agent registration the gateway token `register()` stores on the
340
+ // session is then attached to every subsequent `queryPolicy` request.
233
341
  let nativeClient;
234
342
  if (resolvedConfig.mode !== "sdk-only") {
235
343
  nativeClient = (0, client_js_2.createNativeClient)({
236
344
  gateway: resolvedGatewayUrl,
237
345
  apiKey: resolvedApiKey,
238
- mode: resolvedConfig.mode === "napi-inprocess" ? "napi-inprocess" : "grpc-sidecar",
346
+ mode: resolvedConfig.mode === "napi-inprocess" ? "napi-inprocess" : "grpc-sidecar"
239
347
  });
348
+ }
349
+ const client = createClient(resolvedConfig, nativeClient);
350
+ const adapters = await registerAdapters(frameworks);
351
+ await startNetworkLayerIfNeeded(client, resolvedConfig);
352
+ if (nativeClient !== undefined) {
353
+ // AAASM-3403: register the agent over the native SDK→gateway gRPC call so
354
+ // the gateway issues a credential token (stored on this session) that
355
+ // unblocks subsequent policy queries. Advisory: a failed registration must
356
+ // not abort init — the agent proceeds unregistered and the proxy / eBPF
357
+ // layers remain authoritative.
358
+ try {
359
+ await nativeClient.register(buildRegisterOptions(resolvedConfig, frameworks));
360
+ }
361
+ catch (error) {
362
+ // Redact any Bearer/auth credential the error message might carry before
363
+ // it reaches the console — the apiKey/credentialToken must never be logged
364
+ // (AAASM-3645).
365
+ console.warn(`[agent-assembly] agent registration failed; proceeding unregistered: ${(0, redact_js_1.redactErrorMessage)(error)}`);
366
+ }
367
+ // Topology lineage metadata still flows as an audit event (parent / team /
368
+ // delegation), which `register` does not carry.
240
369
  nativeClient.sendEvent(buildRegistrationEvent(resolvedConfig));
241
370
  }
242
- const langChainHandler = await registerLangChainHandler(resolvedConfig, client, frameworks);
243
- const wrappedLangChainTools = await wrapLangChainTools(resolvedConfig, client, frameworks);
244
- const vercelAiSdkPatched = await patchDetectedVercelAiSdk(client, frameworks, resolvedConfig.agentId);
245
- const openAIAgentsPatched = await patchDetectedOpenAIAgents(client, frameworks);
246
- const langGraphPatched = await patchDetectedLangGraph(frameworks, resolvedConfig.agentId);
247
- const mastraPatched = await patchDetectedMastra(frameworks, resolvedConfig.agentId);
371
+ const patches = await applyFrameworkPatches(resolvedConfig, client, frameworks);
248
372
  return {
249
- activeAdapters: [
250
- ...new Set([
251
- ...adapters.map((adapter) => adapter.id),
252
- ...(langChainHandler ? ["langchain-js"] : []),
253
- ...(wrappedLangChainTools.length > 0 ? ["langchain-js"] : []),
254
- ...(vercelAiSdkPatched ? ["vercel-ai-sdk"] : []),
255
- ...(openAIAgentsPatched ? ["openai-agents"] : []),
256
- ...(langGraphPatched ? ["langgraph-js"] : []),
257
- ...(mastraPatched ? ["mastra"] : [])
258
- ])
259
- ],
260
- ...(resolvedConfig.parentAgentId !== undefined && { parentAgentId: resolvedConfig.parentAgentId }),
373
+ activeAdapters: buildActiveAdapters(adapters, patches),
374
+ ...(resolvedConfig.parentAgentId !== undefined && {
375
+ parentAgentId: resolvedConfig.parentAgentId
376
+ }),
261
377
  ...(resolvedConfig.teamId !== undefined && { teamId: resolvedConfig.teamId }),
262
- ...(resolvedConfig.delegationReason !== undefined && { delegationReason: resolvedConfig.delegationReason }),
263
- ...(resolvedConfig.spawnedByTool !== undefined && { spawnedByTool: resolvedConfig.spawnedByTool }),
264
- ...(resolvedConfig.enforcementMode !== undefined && { enforcementMode: resolvedConfig.enforcementMode }),
378
+ ...(resolvedConfig.delegationReason !== undefined && {
379
+ delegationReason: resolvedConfig.delegationReason
380
+ }),
381
+ ...(resolvedConfig.spawnedByTool !== undefined && {
382
+ spawnedByTool: resolvedConfig.spawnedByTool
383
+ }),
384
+ ...(resolvedConfig.enforcementMode !== undefined && {
385
+ enforcementMode: resolvedConfig.enforcementMode
386
+ }),
265
387
  shutdown: async () => {
266
388
  for (const adapter of adapters) {
267
389
  await adapter.shutdown?.();
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /**
3
+ * Secret-redaction helpers for diagnostic / log output (AAASM-3645).
4
+ *
5
+ * The resolved `apiKey` and the proto `credentialToken` must never reach
6
+ * `console.*` or an accidental `JSON.stringify` dump. These helpers give the
7
+ * SDK a single, audited way to render config/diagnostics for logging with the
8
+ * credential fields stripped.
9
+ *
10
+ * NOTE: the generated `CheckActionRequest.toJSON()` (src/proto/generated) is
11
+ * wire-only — it serializes `credentialToken` for transport and must never be
12
+ * passed to a logger. Use {@link redactSecrets} on any object you intend to log.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.REDACTED = void 0;
16
+ exports.redactSecrets = redactSecrets;
17
+ exports.redactErrorMessage = redactErrorMessage;
18
+ /**
19
+ * Object keys (lower-cased) whose values are credentials and must never be
20
+ * logged. Matching is case-insensitive, so list the lower-case form only —
21
+ * `apiKey`, `apikey`, `API_KEY` all match `"apikey"`.
22
+ */
23
+ const SECRET_KEYS = new Set([
24
+ "apikey",
25
+ "api_key",
26
+ "credentialtoken",
27
+ "credential_token",
28
+ "authorization",
29
+ "token"
30
+ ]);
31
+ /** Placeholder substituted for any redacted credential value. */
32
+ exports.REDACTED = "<redacted>";
33
+ /**
34
+ * Return a deep copy of `value` with every credential-bearing field replaced by
35
+ * {@link REDACTED}, safe to pass to `console.*` / `JSON.stringify`. Matching is
36
+ * case-insensitive on the key name. Non-object inputs are returned unchanged.
37
+ */
38
+ function redactSecrets(value) {
39
+ if (Array.isArray(value)) {
40
+ return value.map((item) => redactSecrets(item));
41
+ }
42
+ if (value !== null && typeof value === "object") {
43
+ const out = {};
44
+ for (const [key, val] of Object.entries(value)) {
45
+ out[key] = SECRET_KEYS.has(key.toLowerCase()) ? exports.REDACTED : redactSecrets(val);
46
+ }
47
+ return out;
48
+ }
49
+ return value;
50
+ }
51
+ /**
52
+ * Render an unknown error for a log message with any `Bearer <token>` / API-key
53
+ * substring scrubbed. Defends the registration-failure warning path: a wrapped
54
+ * transport error could in principle carry an auth header in its message, so we
55
+ * strip the bearer credential before it reaches `console.*` (AAASM-3645).
56
+ */
57
+ function redactErrorMessage(error) {
58
+ const raw = String(error);
59
+ // Replace the credential that follows a `Bearer ` / `Authorization:` marker.
60
+ return raw
61
+ .replace(/(Bearer\s+)[\w.\-+/=]+/gi, `$1${exports.REDACTED}`)
62
+ .replace(/(Authorization\s*[:=]\s*)\S+/gi, `$1${exports.REDACTED}`);
63
+ }
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createNoopGatewayClient = createNoopGatewayClient;
4
+ exports.createNativeGatewayClient = createNativeGatewayClient;
4
5
  function createNoopGatewayClient(mode, httpBaseUrl) {
5
6
  return {
6
7
  mode,
7
- ...(httpBaseUrl !== undefined ? { httpBaseUrl } : {}),
8
+ ...(httpBaseUrl === undefined ? {} : { httpBaseUrl }),
8
9
  start: async () => undefined,
9
10
  close: async () => undefined,
10
11
  check: async () => ({ denied: false, pending: false }),
@@ -14,3 +15,64 @@ function createNoopGatewayClient(mode, httpBaseUrl) {
14
15
  scanPrompts: async () => undefined
15
16
  };
16
17
  }
18
+ /**
19
+ * Translate a governance check request into the native `queryPolicy` query
20
+ * shape (AAASM-3047). The runtime reads `agent_id`, `action_type`, and — for
21
+ * tool calls — `tool_name` / `args`.
22
+ */
23
+ function toNativeQuery(request, agentId) {
24
+ const query = {
25
+ agent_id: agentId ?? "",
26
+ action_type: request.action
27
+ };
28
+ if (request.toolName !== undefined) {
29
+ query.tool_name = request.toolName;
30
+ }
31
+ if (request.args !== undefined) {
32
+ query.args = request.args;
33
+ }
34
+ return query;
35
+ }
36
+ /**
37
+ * Gateway client backed by the in-process native runtime (AAASM-3050).
38
+ *
39
+ * `check()` asks a reachable `aa-runtime` for an authoritative verdict via the
40
+ * native `queryPolicy` primitive and maps it onto a `GatewayDecision`:
41
+ * - `deny` → `{ denied: true }` (the wrapper throws `PolicyViolationError`)
42
+ * - `pending` → `{ pending: true }` (routes to the approval path)
43
+ * - allow / redact / unspecified → `{ denied: false }`
44
+ *
45
+ * **Fail-open (security-critical):** the SDK is advisory, not a security
46
+ * boundary. The native primitive already returns `allow` when the runtime is
47
+ * unreachable or too slow; on top of that, any local fault while querying is
48
+ * swallowed here and resolves neutral, so a missing or degraded runtime never
49
+ * blocks the agent. The proxy / eBPF layers remain authoritative.
50
+ */
51
+ function createNativeGatewayClient(mode, nativeClient, agentId, httpBaseUrl) {
52
+ return {
53
+ mode,
54
+ ...(httpBaseUrl === undefined ? {} : { httpBaseUrl }),
55
+ start: async () => undefined,
56
+ close: async () => {
57
+ await nativeClient.close();
58
+ },
59
+ check: async (request) => {
60
+ try {
61
+ const verdict = await nativeClient.queryPolicy(toNativeQuery(request, agentId));
62
+ return {
63
+ denied: verdict.denied ?? false,
64
+ pending: verdict.pending ?? false,
65
+ ...(verdict.reason === undefined ? {} : { reason: verdict.reason })
66
+ };
67
+ }
68
+ catch {
69
+ // Fail open: a local fault talking to the runtime must never block.
70
+ return { denied: false, pending: false };
71
+ }
72
+ },
73
+ waitForApproval: async () => ({ denied: false }),
74
+ record: async () => undefined,
75
+ recordResult: async () => undefined,
76
+ scanPrompts: async () => undefined
77
+ };
78
+ }
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createNoopGatewayClient = void 0;
3
+ exports.createNoopGatewayClient = exports.createNativeGatewayClient = void 0;
4
4
  var client_js_1 = require("./client.js");
5
+ Object.defineProperty(exports, "createNativeGatewayClient", { enumerable: true, get: function () { return client_js_1.createNativeGatewayClient; } });
5
6
  Object.defineProperty(exports, "createNoopGatewayClient", { enumerable: true, get: function () { return client_js_1.createNoopGatewayClient; } });