@rubics-code/agent-kit 0.0.0-stage → 0.2.0

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 (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -2
  3. package/dist/approval.d.ts +20 -0
  4. package/dist/approval.js +32 -0
  5. package/dist/assemble.d.ts +24 -0
  6. package/dist/assemble.js +19 -0
  7. package/dist/briefing.d.ts +12 -0
  8. package/dist/briefing.js +22 -0
  9. package/dist/capabilities.d.ts +2 -0
  10. package/dist/capabilities.js +6 -0
  11. package/dist/cli/bin.d.ts +2 -0
  12. package/dist/cli/bin.js +39 -0
  13. package/dist/cli/init.d.ts +9 -0
  14. package/dist/cli/init.js +73 -0
  15. package/dist/credentials.d.ts +28 -0
  16. package/dist/credentials.js +134 -0
  17. package/dist/errors.d.ts +2 -0
  18. package/dist/errors.js +4 -0
  19. package/dist/group.d.ts +68 -0
  20. package/dist/group.js +89 -0
  21. package/dist/groups/cloudflare/client.d.ts +42 -0
  22. package/dist/groups/cloudflare/client.js +76 -0
  23. package/dist/groups/cloudflare/guidance.md +7 -0
  24. package/dist/groups/cloudflare/memory.d.ts +19 -0
  25. package/dist/groups/cloudflare/memory.js +43 -0
  26. package/dist/groups/cloudflare/tools.d.ts +3 -0
  27. package/dist/groups/cloudflare/tools.js +140 -0
  28. package/dist/groups/infisical/client.d.ts +30 -0
  29. package/dist/groups/infisical/client.js +133 -0
  30. package/dist/groups/infisical/guidance.md +8 -0
  31. package/dist/groups/infisical/memory.d.ts +18 -0
  32. package/dist/groups/infisical/memory.js +43 -0
  33. package/dist/groups/infisical/tools.d.ts +3 -0
  34. package/dist/groups/infisical/tools.js +88 -0
  35. package/dist/groups/mxroute/client.d.ts +90 -0
  36. package/dist/groups/mxroute/client.js +86 -0
  37. package/dist/groups/mxroute/guidance.md +13 -0
  38. package/dist/groups/mxroute/memory.d.ts +34 -0
  39. package/dist/groups/mxroute/memory.js +83 -0
  40. package/dist/groups/mxroute/tools.d.ts +3 -0
  41. package/dist/groups/mxroute/tools.js +158 -0
  42. package/dist/groups/openrouter/client.d.ts +66 -0
  43. package/dist/groups/openrouter/client.js +66 -0
  44. package/dist/groups/openrouter/guidance.md +7 -0
  45. package/dist/groups/openrouter/memory.d.ts +26 -0
  46. package/dist/groups/openrouter/memory.js +59 -0
  47. package/dist/groups/openrouter/tools.d.ts +3 -0
  48. package/dist/groups/openrouter/tools.js +130 -0
  49. package/dist/groups/registrar/client.d.ts +48 -0
  50. package/dist/groups/registrar/client.js +75 -0
  51. package/dist/groups/registrar/guidance.md +9 -0
  52. package/dist/groups/registrar/memory.d.ts +16 -0
  53. package/dist/groups/registrar/memory.js +27 -0
  54. package/dist/groups/registrar/tools.d.ts +4 -0
  55. package/dist/groups/registrar/tools.js +102 -0
  56. package/dist/index.d.ts +35 -0
  57. package/dist/index.js +35 -0
  58. package/dist/policy.d.ts +12 -0
  59. package/dist/policy.js +1 -0
  60. package/dist/result.d.ts +2 -0
  61. package/dist/result.js +17 -0
  62. package/dist/runtime/agent.d.ts +28 -0
  63. package/dist/runtime/agent.js +28 -0
  64. package/dist/runtime/container.d.ts +8 -0
  65. package/dist/runtime/container.js +41 -0
  66. package/dist/runtime/run.d.ts +51 -0
  67. package/dist/runtime/run.js +152 -0
  68. package/dist/runtime/transcribe.d.ts +7 -0
  69. package/dist/runtime/transcribe.js +37 -0
  70. package/dist/runtime/turns.d.ts +13 -0
  71. package/dist/runtime/turns.js +23 -0
  72. package/dist/runtime/web/index.html +452 -0
  73. package/dist/runtime/web/server.d.ts +20 -0
  74. package/dist/runtime/web/server.js +150 -0
  75. package/dist/schemas.d.ts +2 -0
  76. package/dist/schemas.js +6 -0
  77. package/dist/secret-delivery.d.ts +18 -0
  78. package/dist/secret-delivery.js +45 -0
  79. package/dist/secret-store.d.ts +13 -0
  80. package/dist/secret-store.js +1 -0
  81. package/dist/secrets.d.ts +5 -0
  82. package/dist/secrets.js +13 -0
  83. package/package.json +61 -4
  84. package/template/Dockerfile +19 -0
  85. package/template/README.md +55 -0
  86. package/template/_dockerignore +7 -0
  87. package/template/_gitignore +4 -0
  88. package/template/entrypoint.sh +14 -0
  89. package/template/evals/notes.eval.ts +55 -0
  90. package/template/home/memory/README.md +1 -0
  91. package/template/home/prompts/system.md +15 -0
  92. package/template/src/agent.ts +47 -0
  93. package/template/src/groups/notes.ts +85 -0
  94. package/template/src/main.ts +4 -0
  95. package/template/test/agent.test.ts +22 -0
  96. package/template/tsconfig.json +17 -0
  97. package/template/vitest.config.ts +7 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rubics Code
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # @rubics-code/agent-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The machinery for an agent: tool groups, the approval gate, secret delivery, key loading (env, Infisical Agent Vault, Infisical identity), the agent loop, a terminal chat, a local web chat, and a container mode. An agent gives data; the Kit does the rest.
4
+
5
+ Each write tool goes through an approval gate: the operator sees a summary that code writes from the arguments, never the model, and must approve it. A new secret (a password, an API key) never goes into the conversation. It goes to the operator's terminal, or into Infisical.
6
+
7
+ ## Install
8
+
9
+ Node 24 or later.
10
+
11
+ ```bash
12
+ npm install @rubics-code/agent-kit
13
+ ```
14
+
15
+ ## Make a new agent
16
+
17
+ ```bash
18
+ npx @rubics-code/agent-kit init scout
19
+ ```
20
+
21
+ This makes `agents/scout/` with the agent as data (`src/agent.ts`), an example tool group with a write tool behind the approval gate, a system prompt, tests, evals, a Dockerfile, and an entrypoint for Agent Vault. `--dir` sets another folder, and `--operator` names who approves the actions (default: your git `user.name`). The agent is its own npm package with its own `package-lock.json`, which the Dockerfile needs.
22
+
23
+ ## An agent
24
+
25
+ ```ts
26
+ import { readFileSync } from "node:fs";
27
+ import { type AgentConfig, cloudflareGroup, infisicalGroup, runAgent } from "@rubics-code/agent-kit";
28
+
29
+ export const SCOUT: AgentConfig = {
30
+ name: "Scout",
31
+ model: "deepseek/deepseek-v4-flash-0731",
32
+ groups: [cloudflareGroup, infisicalGroup],
33
+ system: readFileSync(new URL("../home/prompts/system.md", import.meta.url), "utf8"),
34
+ policy: { agent: "Scout", operator: "Greg", maxKeyLimitUsd: 20, infisical: { /* readablePath, writablePath, envLabel */ } },
35
+ infisical: { url: "https://secrets.example.com", projectId: "…", path: "/scout", env: () => "prod", tokenKey: "SCOUT_INFISICAL_TOKEN" },
36
+ };
37
+
38
+ await runAgent(SCOUT);
39
+ ```
40
+
41
+ Run it with `node src/main.ts`. Node 24 runs TypeScript directly.
42
+
43
+ ## A tool group
44
+
45
+ A group is one `ToolGroupDef` object: an id, a name, the service host (for Agent Vault), the env keys, a setup hint, the briefing guidance, `connect` (keys to client), and `tools` (client to tools). Make each write tool with `approvedTool`, so the operator must approve it. Add the group to the agent's `groups` list. A group can live in the agent's own repo.
46
+
47
+ ## Env variables
48
+
49
+ `<PREFIX>` is the agent's name in upper case, or `envPrefix`.
50
+
51
+ | Variable | Use |
52
+ | --- | --- |
53
+ | `<PREFIX>_MODEL` | Replaces the pinned model, for a test. |
54
+ | `<PREFIX>_WEB_PORT` | The web chat port. Default 4141. |
55
+ | `<PREFIX>_KEYS=user` | Skips the identity file and uses your own keys. |
56
+ | `<PREFIX>_HEADLESS=1` | Container mode: no terminal, a health server, and new secrets go to Infisical. |
57
+ | `<PREFIX>_HEALTH_PORT` | The health port in container mode. Default 8080. |
58
+
59
+ ## Container mode
60
+
61
+ The web chat stays on `127.0.0.1` inside the container. Reach it with `kubectl port-forward`. `GET /healthz` answers on all addresses. A new secret with no `storeAt` goes to the Infisical folder `<infisical.path>/inbox` (or `secretInbox`). In an image, start the agent behind Agent Vault with the Infisical CLI. The CLI mints a session with a machine identity, then removes the identity before the agent starts:
62
+
63
+ ```sh
64
+ exec infisical agent-vault run --no-skills -- \
65
+ env -u INFISICAL_UNIVERSAL_AUTH_CLIENT_ID -u INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET node src/main.ts
66
+ ```
67
+
68
+ Set `INFISICAL_DOMAIN`, `INFISICAL_AGENT_VAULT_PROXY_ADDRESS`, `INFISICAL_AGENT_VAULT_PROJECT_ID`, `INFISICAL_AGENT_VAULT_ACCESS_BUNDLE`, `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` and `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET`, and `NODE_USE_ENV_PROXY=1`. The `infisical/cli` image holds a static binary at `/bin/infisical` that you can copy into a `node:24-slim` image.
69
+
70
+ ## Build and checks
71
+
72
+ | Command | What it does |
73
+ | --- | --- |
74
+ | `npm test` | The tests. `test/fixture.ts` is a test agent. |
75
+ | `npm run type-check` | Type-checks `src/` and `test/`. |
76
+ | `npm run build` | Compiles `src/` to `dist/` and copies the `.md` and `.html` files that the code reads. |
77
+ | `npm run pack-check` | Packs the package, installs the tarball in an empty folder, runs a consumer, type-checks a consumer file, and makes an agent with `init` that must pass its own type-check and tests. |
78
+
79
+ ## Release
80
+
81
+ Make a GitHub release with a tag `v<major>.<minor>.<patch>`, for example `v0.2.0`. The `release` workflow sets that version, runs the tests, and publishes to npm. `version` in `package.json` stays `0.0.0`: the tag is the version. A release that is marked as a prerelease goes to the npm tag `next`.
82
+
83
+ The workflow uses trusted publishing (OIDC), so no npm token is stored, and npm adds provenance. The first release can use a short-lived `NPM_TOKEN` secret in the `npm` environment, because npm lets you add a trusted publisher only to a package that exists.
84
+
85
+ Until 1.0, a minor version can break the interface.
86
+
87
+ ## License
88
+
89
+ MIT
@@ -0,0 +1,20 @@
1
+ export interface ApprovalRequest {
2
+ kind: "approval";
3
+ tool: string;
4
+ summary: string;
5
+ args: Record<string, unknown>;
6
+ argsHash: string;
7
+ }
8
+ export interface ApprovalDecision {
9
+ approved: boolean;
10
+ argsHash: string;
11
+ reason?: string;
12
+ }
13
+ export declare function isApprovalRequest(value: unknown): value is ApprovalRequest;
14
+ export declare function hashArgs(args: Record<string, unknown>): string;
15
+ export declare function requireApproval(tool: string, summary: string, args: Record<string, unknown>): {
16
+ approved: true;
17
+ } | {
18
+ approved: false;
19
+ reason: string;
20
+ };
@@ -0,0 +1,32 @@
1
+ import { createHash } from "node:crypto";
2
+ import { interrupt } from "@langchain/langgraph";
3
+ export function isApprovalRequest(value) {
4
+ return typeof value === "object" && value !== null && value.kind === "approval";
5
+ }
6
+ export function hashArgs(args) {
7
+ return createHash("sha256").update(canonical(args)).digest("hex");
8
+ }
9
+ function canonical(value) {
10
+ if (Array.isArray(value))
11
+ return `[${value.map(canonical).join(",")}]`;
12
+ if (value && typeof value === "object") {
13
+ const entries = Object.entries(value)
14
+ .filter(([, v]) => v !== undefined)
15
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
16
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
17
+ }
18
+ return JSON.stringify(value);
19
+ }
20
+ // Pauses the graph until the operator decides. The tool body re-runs from the
21
+ // start on resume, so nothing with a side effect may come before this call.
22
+ export function requireApproval(tool, summary, args) {
23
+ const request = { kind: "approval", tool, summary, args, argsHash: hashArgs(args) };
24
+ const decision = interrupt(request);
25
+ if (!decision || decision.approved !== true) {
26
+ return { approved: false, reason: decision?.reason ?? "rejected" };
27
+ }
28
+ if (decision.argsHash !== request.argsHash) {
29
+ return { approved: false, reason: "the approval does not match these arguments" };
30
+ }
31
+ return { approved: true };
32
+ }
@@ -0,0 +1,24 @@
1
+ import type { StructuredTool } from "@langchain/core/tools";
2
+ import { type ConnectContext, type GroupStatus, type ToolGroupDef } from "./group.js";
3
+ import type { AgentPolicy } from "./policy.js";
4
+ import type { SecretSink } from "./secrets.js";
5
+ export type AnyGroup = ToolGroupDef<unknown>;
6
+ export type Services = Partial<Record<string, unknown>>;
7
+ export interface Enable {
8
+ has(key: string): boolean;
9
+ vaultHosts?: Set<string> | undefined;
10
+ hosts?: Record<string, string | undefined>;
11
+ }
12
+ export declare function connectServices(groups: readonly AnyGroup[], ctx: ConnectContext): Services;
13
+ export declare function assembleAgent(opts: {
14
+ groups: readonly AnyGroup[];
15
+ system: string;
16
+ policy: AgentPolicy;
17
+ services: Services;
18
+ secrets: SecretSink;
19
+ enable: Enable;
20
+ }): {
21
+ tools: StructuredTool[];
22
+ briefing: string;
23
+ statuses: GroupStatus[];
24
+ };
@@ -0,0 +1,19 @@
1
+ import { assembleBriefing } from "./briefing.js";
2
+ import { mountedTools, reviewGroup } from "./group.js";
3
+ import { infisicalGroup } from "./groups/infisical/tools.js";
4
+ // Makes each group's service from the session's keys.
5
+ export function connectServices(groups, ctx) {
6
+ return Object.fromEntries(groups.map((def) => [def.id, def.connect(ctx)]));
7
+ }
8
+ export function assembleAgent(opts) {
9
+ const { groups, policy, services } = opts;
10
+ const statuses = groups.map((def) => reviewGroup(def, { has: opts.enable.has, hasStore: !!services[infisicalGroup.id], vaultHosts: opts.enable.vaultHosts }, { host: opts.enable.hosts?.[def.id] }));
11
+ // Mount a service only when its group is on. In Agent Vault mode every key
12
+ // is a placeholder, so a service can exist for a host the session lacks.
13
+ const on = (id) => statuses.some((s) => s.id === id && s.enabled);
14
+ const store = on(infisicalGroup.id) ? services[infisicalGroup.id] : undefined;
15
+ const shared = { secrets: opts.secrets, store, policy };
16
+ const tools = groups.flatMap((def) => mountedTools(def, on(def.id) ? services[def.id] : undefined, shared));
17
+ const briefing = assembleBriefing({ system: opts.system, defs: groups, statuses, policy });
18
+ return { tools, briefing, statuses };
19
+ }
@@ -0,0 +1,12 @@
1
+ import type { GroupStatus } from "./group.js";
2
+ import type { AgentPolicy } from "./policy.js";
3
+ export interface GuidanceLike {
4
+ id: string;
5
+ guidance: string;
6
+ }
7
+ export declare function assembleBriefing(opts: {
8
+ system: string;
9
+ defs: readonly GuidanceLike[];
10
+ statuses: readonly GroupStatus[];
11
+ policy: AgentPolicy;
12
+ }): string;
@@ -0,0 +1,22 @@
1
+ // The briefing: the agent's system prompt, the guidance of every included
2
+ // group, and the capability note. Placeholders in the prose — {{operator}},
3
+ // {{agent}}, {{maxKeyLimitUsd}} — are substituted from the policy. The model
4
+ // never writes any of it.
5
+ import { capabilityNote } from "./capabilities.js";
6
+ export function assembleBriefing(opts) {
7
+ const fill = (text) => text
8
+ .replaceAll("{{operator}}", opts.policy.operator)
9
+ .replaceAll("{{agent}}", opts.policy.agent)
10
+ .replaceAll("{{maxKeyLimitUsd}}", String(opts.policy.maxKeyLimitUsd));
11
+ const byId = new Map(opts.defs.map((d) => [d.id, d]));
12
+ const parts = [fill(opts.system)];
13
+ for (const status of opts.statuses) {
14
+ if (!status.enabled)
15
+ continue;
16
+ const def = byId.get(status.id);
17
+ if (def?.guidance)
18
+ parts.push(fill(def.guidance));
19
+ }
20
+ parts.push(capabilityNote(opts.statuses, opts.policy.operator));
21
+ return parts.join("\n\n");
22
+ }
@@ -0,0 +1,2 @@
1
+ import type { GroupStatus } from "./group.js";
2
+ export declare function capabilityNote(groups: readonly GroupStatus[], operator: string): string;
@@ -0,0 +1,6 @@
1
+ export function capabilityNote(groups, operator) {
2
+ const lines = groups.map((g) => g.enabled
3
+ ? `- ${g.name}: on.`
4
+ : `- ${g.name}: OFF. Missing: ${g.missing.join(", ")}. ${g.setup}`);
5
+ return `Your tool groups now. If ${operator} asks why a tool is not there, give this reason:\n${lines.join("\n")}`;
6
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // npx @rubics-code/agent-kit init <name> [--dir <folder>] [--operator <name>]
3
+ import { execFileSync } from "node:child_process";
4
+ import { relative, resolve } from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ import { initAgent } from "./init.js";
7
+ const USAGE = `Usage: agent-kit init <name> [--dir <folder>] [--operator <name>]
8
+
9
+ <name> lower case letters, digits and dashes, for example scout
10
+ --dir the new folder (default: agents/<name>)
11
+ --operator who approves the agent's actions (default: your git user.name)
12
+ `;
13
+ function gitUser() {
14
+ try {
15
+ return execFileSync("git", ["config", "user.name"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim().split(/\s+/)[0];
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ const { values, positionals } = parseArgs({
22
+ allowPositionals: true,
23
+ options: { dir: { type: "string" }, operator: { type: "string" }, help: { type: "boolean", short: "h" } },
24
+ });
25
+ const [command, name] = positionals;
26
+ if (values.help || command !== "init" || !name) {
27
+ process.stdout.write(USAGE);
28
+ process.exit(values.help ? 0 : 1);
29
+ }
30
+ const dir = resolve(values.dir ?? `agents/${name}`);
31
+ try {
32
+ const files = initAgent({ name, dir, operator: values.operator ?? gitUser() });
33
+ const rel = relative(process.cwd(), dir) || ".";
34
+ process.stdout.write(`Made ${rel} (${files.length} files).\n\nNext:\n cd ${rel}\n npm install\n OPENROUTER_API_KEY=... npm run chat\n\nRead ${rel}/README.md for the tool groups, Infisical and container mode.\n`);
35
+ }
36
+ catch (err) {
37
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
38
+ process.exit(1);
39
+ }
@@ -0,0 +1,9 @@
1
+ export declare const AGENT_NAME: RegExp;
2
+ export interface InitOptions {
3
+ name: string;
4
+ dir: string;
5
+ operator?: string | undefined;
6
+ }
7
+ export declare const displayName: (name: string) => string;
8
+ export declare const envPrefix: (display: string) => string;
9
+ export declare function initAgent(opts: InitOptions): string[];
@@ -0,0 +1,73 @@
1
+ // Makes a new agent folder from the template beside this package.
2
+ import { cpSync, existsSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const root = new URL("../../", import.meta.url);
6
+ const TEMPLATE = fileURLToPath(new URL("template/", root));
7
+ export const AGENT_NAME = /^[a-z][a-z0-9-]{0,39}$/;
8
+ // scout -> Scout, ops-bot -> Ops Bot.
9
+ export const displayName = (name) => name
10
+ .split("-")
11
+ .filter(Boolean)
12
+ .map((w) => w[0].toUpperCase() + w.slice(1))
13
+ .join(" ");
14
+ // The same rule as runAgent's default env prefix.
15
+ export const envPrefix = (display) => display.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
16
+ function kitPackage() {
17
+ return JSON.parse(readFileSync(new URL("package.json", root), "utf8"));
18
+ }
19
+ function packageJson(name, display, kit) {
20
+ const pick = (from, keys) => Object.fromEntries(keys.map((k) => [k, from[k]]));
21
+ // 0.0.0 is the version in the kit's own repo; a release sets the real one.
22
+ const kitRange = kit.version === "0.0.0" ? "*" : `^${kit.version}`;
23
+ return `${JSON.stringify({
24
+ name,
25
+ version: "0.1.0",
26
+ private: true,
27
+ type: "module",
28
+ description: `${display}, an agent on ${kit.name}`,
29
+ engines: { node: ">=24" },
30
+ scripts: {
31
+ chat: "node src/main.ts",
32
+ "type-check": "tsc --noEmit",
33
+ test: "vitest run test/",
34
+ eval: "vitest run evals/",
35
+ },
36
+ dependencies: { [kit.name]: kitRange, ...pick(kit.dependencies, ["langchain", "zod"]) },
37
+ devDependencies: pick(kit.devDependencies, ["@types/node", "typescript", "vitest"]),
38
+ }, null, 2)}\n`;
39
+ }
40
+ // Writes the agent folder and returns the paths it made, relative to `dir`.
41
+ export function initAgent(opts) {
42
+ if (!AGENT_NAME.test(opts.name)) {
43
+ throw new Error(`"${opts.name}" is not a valid agent name. Use lower case letters, digits and dashes, for example scout.`);
44
+ }
45
+ if (existsSync(opts.dir))
46
+ throw new Error(`${opts.dir} exists. Give a new folder.`);
47
+ const display = displayName(opts.name);
48
+ const values = {
49
+ name: opts.name,
50
+ Name: display,
51
+ NAME: envPrefix(display),
52
+ operator: opts.operator?.trim() || "the operator",
53
+ };
54
+ cpSync(TEMPLATE, opts.dir, { recursive: true });
55
+ const made = [];
56
+ for (const entry of readdirSync(opts.dir, { recursive: true, withFileTypes: true })) {
57
+ if (!entry.isFile())
58
+ continue;
59
+ let file = join(entry.parentPath, entry.name);
60
+ // npm drops .gitignore from a package, so the template holds _gitignore.
61
+ if (entry.name.startsWith("_")) {
62
+ const dotted = join(entry.parentPath, `.${entry.name.slice(1)}`);
63
+ renameSync(file, dotted);
64
+ file = dotted;
65
+ }
66
+ const text = readFileSync(file, "utf8").replace(/\{\{(\w+)\}\}/g, (all, key) => values[key] ?? all);
67
+ writeFileSync(file, text);
68
+ made.push(file.slice(opts.dir.length + 1));
69
+ }
70
+ writeFileSync(join(opts.dir, "package.json"), packageJson(opts.name, display, kitPackage()));
71
+ made.push("package.json");
72
+ return made.sort();
73
+ }
@@ -0,0 +1,28 @@
1
+ import { HttpInfisical } from "./groups/infisical/client.js";
2
+ export interface Credentials<K extends string = string> {
3
+ mode: "env" | "agent-vault" | "identity";
4
+ get(name: K): string;
5
+ optional(name: K): string | undefined;
6
+ holds(name: string): boolean;
7
+ }
8
+ export interface InfisicalConfig {
9
+ url: string;
10
+ projectId: string;
11
+ path: string;
12
+ env: (path: string) => string;
13
+ }
14
+ export declare const placeholder: (name: string) => string;
15
+ export declare function isAgentVault(env?: NodeJS.ProcessEnv): boolean;
16
+ export declare function loadCredentials<K extends string = string>(env?: NodeJS.ProcessEnv): Credentials<K>;
17
+ export declare function readIdentityFile(file: URL | string): NodeJS.ProcessEnv | undefined;
18
+ export declare function loadIdentityCredentials<K extends string = string>(env: NodeJS.ProcessEnv, config: InfisicalConfig, opts?: {
19
+ fetch?: typeof fetch;
20
+ }): Promise<{
21
+ creds: Credentials<K>;
22
+ infisical: HttpInfisical;
23
+ }>;
24
+ export declare function sessionHosts(infisicalUrl: string, env?: NodeJS.ProcessEnv, f?: typeof fetch): Promise<Set<string> | undefined>;
25
+ export declare function sessionToken(env?: NodeJS.ProcessEnv): string | undefined;
26
+ export declare function groupKeys(groups: readonly {
27
+ keys: readonly string[];
28
+ }[]): string[];
@@ -0,0 +1,134 @@
1
+ // How an agent gets its keys. Three modes:
2
+ // - env: `infisical run` puts the real values in the environment.
3
+ // - agent-vault: `infisical agent-vault run` starts the agent behind the Agent
4
+ // Vault proxy. The agent sends placeholders such as __MXROUTE_API_KEY__, and
5
+ // the proxy puts in the real values, so the process never holds a key. The
6
+ // session's services (sessionHosts) decide which tool groups are on.
7
+ // - identity: the agent logs in with its Infisical machine identity and reads
8
+ // its keys from its own Infisical folder.
9
+ // The Agent Vault services must use the placeholders that `placeholder` makes.
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { parseEnv } from "node:util";
12
+ import { HttpInfisical } from "./groups/infisical/client.js";
13
+ export const placeholder = (name) => `__${name}__`;
14
+ // `infisical agent-vault run` puts the session token into HTTPS_PROXY as the
15
+ // password of the user x-agent-vault. Some CLI versions also set
16
+ // INFISICAL_AGENT_VAULT_SESSION_TOKEN; 0.45.4 does not.
17
+ export function isAgentVault(env = process.env) {
18
+ if (env.INFISICAL_AGENT_VAULT_SESSION_TOKEN)
19
+ return true;
20
+ try {
21
+ return new URL(env.HTTPS_PROXY ?? env.https_proxy ?? "").username === "x-agent-vault";
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ // Env mode or Agent Vault mode, from the environment.
28
+ export function loadCredentials(env = process.env) {
29
+ if (isAgentVault(env)) {
30
+ if (!env.HTTPS_PROXY)
31
+ throw new Error("Agent Vault mode: HTTPS_PROXY is not set");
32
+ // Without it, Node's fetch ignores HTTPS_PROXY and sends the placeholders
33
+ // directly to the API.
34
+ if (env.NODE_USE_ENV_PROXY !== "1")
35
+ throw new Error("Agent Vault mode: set NODE_USE_ENV_PROXY=1");
36
+ const present = (name) => {
37
+ if (env[name])
38
+ throw new Error(`Agent Vault mode: ${name} is in the environment. Remove it.`);
39
+ return placeholder(name);
40
+ };
41
+ return { mode: "agent-vault", get: present, optional: present, holds: (name) => !env[name] };
42
+ }
43
+ return {
44
+ mode: "env",
45
+ get(name) {
46
+ const value = env[name];
47
+ if (!value)
48
+ throw new Error(`${name} is not set`);
49
+ return value;
50
+ },
51
+ optional: (name) => env[name] || undefined,
52
+ holds: (name) => !!env[name],
53
+ };
54
+ }
55
+ // The agent's identity file, read directly. A shell can export its own
56
+ // INFISICAL_CLIENT_ID (for example from a repo-root .env), and node
57
+ // --env-file never replaces a variable that is set, so the file must not go
58
+ // through the environment.
59
+ export function readIdentityFile(file) {
60
+ if (!existsSync(file))
61
+ return undefined;
62
+ const v = parseEnv(readFileSync(file, "utf8"));
63
+ if (!v.INFISICAL_CLIENT_ID || !v.INFISICAL_CLIENT_SECRET) {
64
+ throw new Error(`${file instanceof URL ? file.pathname : file} needs INFISICAL_CLIENT_ID and INFISICAL_CLIENT_SECRET`);
65
+ }
66
+ return { INFISICAL_CLIENT_ID: v.INFISICAL_CLIENT_ID, INFISICAL_CLIENT_SECRET: v.INFISICAL_CLIENT_SECRET };
67
+ }
68
+ // Identity mode. It removes the client secret from the given object after
69
+ // the client has it.
70
+ export async function loadIdentityCredentials(env, config, opts = {}) {
71
+ const clientId = env.INFISICAL_CLIENT_ID;
72
+ const clientSecret = env.INFISICAL_CLIENT_SECRET;
73
+ if (!clientId || !clientSecret)
74
+ throw new Error("Identity mode: INFISICAL_CLIENT_ID and INFISICAL_CLIENT_SECRET are not set");
75
+ delete env.INFISICAL_CLIENT_SECRET;
76
+ const infisical = new HttpInfisical({ clientId, clientSecret }, {
77
+ baseUrl: config.url,
78
+ projectId: config.projectId,
79
+ env: config.env,
80
+ ...(opts.fetch ? { fetch: opts.fetch } : {}),
81
+ });
82
+ const values = await infisical.readAll(config.path);
83
+ return {
84
+ infisical,
85
+ creds: {
86
+ mode: "identity",
87
+ get(name) {
88
+ const value = values[name];
89
+ if (!value)
90
+ throw new Error(`${name} is not in Infisical ${config.path}`);
91
+ return value;
92
+ },
93
+ optional: (name) => values[name] || undefined,
94
+ holds: (name) => !!values[name],
95
+ },
96
+ };
97
+ }
98
+ export async function sessionHosts(infisicalUrl, env = process.env, f = fetch) {
99
+ const base = (env.INFISICAL_AGENT_VAULT_URL || infisicalUrl).replace(/\/+$/, "").replace(/\/api$/, "");
100
+ const token = sessionToken(env);
101
+ try {
102
+ const res = await f(`${base}/api/v1/agent-vault/session/services`, {
103
+ headers: { Accept: "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
104
+ });
105
+ if (!res.ok)
106
+ return undefined;
107
+ const json = (await res.json());
108
+ const hosts = (json.services ?? [])
109
+ .filter((s) => !s.status || s.status === "ready")
110
+ .flatMap((s) => s.hosts ?? [])
111
+ .map((h) => h.toLowerCase().replace(/:443$/, ""));
112
+ return new Set(hosts);
113
+ }
114
+ catch {
115
+ return undefined;
116
+ }
117
+ }
118
+ // The session token is the password in HTTPS_PROXY (user x-agent-vault), so
119
+ // the agent holds it already; it grants this session only.
120
+ export function sessionToken(env = process.env) {
121
+ if (env.INFISICAL_AGENT_VAULT_SESSION_TOKEN)
122
+ return env.INFISICAL_AGENT_VAULT_SESSION_TOKEN;
123
+ try {
124
+ const url = new URL(env.HTTPS_PROXY ?? env.https_proxy ?? "");
125
+ return url.username === "x-agent-vault" && url.password ? decodeURIComponent(url.password) : undefined;
126
+ }
127
+ catch {
128
+ return undefined;
129
+ }
130
+ }
131
+ // Every key that a group list can turn on, for a key list or a check.
132
+ export function groupKeys(groups) {
133
+ return [...new Set(groups.flatMap((g) => g.keys))];
134
+ }
@@ -0,0 +1,2 @@
1
+ export declare class ServiceError extends Error {
2
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,4 @@
1
+ // An error from an outside service. Tools show its message to the model;
2
+ // other errors stop the turn.
3
+ export class ServiceError extends Error {
4
+ }
@@ -0,0 +1,68 @@
1
+ import type { StructuredTool } from "@langchain/core/tools";
2
+ import { z } from "zod";
3
+ import type { AgentPolicy } from "./policy.js";
4
+ import type { SecretSink } from "./secrets.js";
5
+ import type { SecretStore } from "./secret-store.js";
6
+ export interface SharedDeps {
7
+ secrets: SecretSink;
8
+ store?: SecretStore | undefined;
9
+ policy: AgentPolicy;
10
+ }
11
+ export interface ToolMeta {
12
+ name: string;
13
+ approval: boolean;
14
+ }
15
+ export interface ToolGroupDef<S> {
16
+ id: string;
17
+ name: string;
18
+ host: string;
19
+ keys: readonly string[];
20
+ setup: string;
21
+ guidance: string;
22
+ review?(env: EnableEnv): {
23
+ enabled: boolean;
24
+ missing: string[];
25
+ setup?: string;
26
+ };
27
+ connect(ctx: ConnectContext): S | undefined;
28
+ tools(service: S, shared: SharedDeps): StructuredTool[];
29
+ }
30
+ export interface ConnectContext {
31
+ holds(key: string): boolean;
32
+ get(key: string): string;
33
+ store?: SecretStore | undefined;
34
+ }
35
+ export declare function holdsAll(ctx: ConnectContext, keys: readonly string[]): boolean;
36
+ export declare function approvedTool<S extends z.ZodType, D = undefined>(def: {
37
+ name: string;
38
+ description: string;
39
+ operator: string;
40
+ schema: S;
41
+ prepare: (args: z.infer<S>) => Promise<{
42
+ summary: string;
43
+ args?: Record<string, unknown>;
44
+ data?: D;
45
+ early?: string;
46
+ }>;
47
+ run: (args: z.infer<S>, data: D) => Promise<unknown>;
48
+ }): StructuredTool;
49
+ export declare function toolCatalog(tools: readonly StructuredTool[]): ToolMeta[];
50
+ export declare function defCatalog(def: ToolGroupDef<unknown>): ToolMeta[];
51
+ export declare function mountedTools<S>(def: ToolGroupDef<S>, service: S | undefined, shared: SharedDeps): StructuredTool[];
52
+ export interface EnableEnv {
53
+ has(key: string): boolean;
54
+ hasStore: boolean;
55
+ vaultHosts?: Set<string> | undefined;
56
+ host?: string | undefined;
57
+ }
58
+ export interface GroupStatus {
59
+ id: string;
60
+ name: string;
61
+ enabled: boolean;
62
+ missing: string[];
63
+ setup: string;
64
+ catalog: ToolMeta[];
65
+ }
66
+ export declare function reviewGroup(def: ToolGroupDef<unknown>, env: EnableEnv, opts?: {
67
+ host?: string | undefined;
68
+ }): GroupStatus;