@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.
- package/LICENSE +21 -0
- package/README.md +88 -2
- package/dist/approval.d.ts +20 -0
- package/dist/approval.js +32 -0
- package/dist/assemble.d.ts +24 -0
- package/dist/assemble.js +19 -0
- package/dist/briefing.d.ts +12 -0
- package/dist/briefing.js +22 -0
- package/dist/capabilities.d.ts +2 -0
- package/dist/capabilities.js +6 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +39 -0
- package/dist/cli/init.d.ts +9 -0
- package/dist/cli/init.js +73 -0
- package/dist/credentials.d.ts +28 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +4 -0
- package/dist/group.d.ts +68 -0
- package/dist/group.js +89 -0
- package/dist/groups/cloudflare/client.d.ts +42 -0
- package/dist/groups/cloudflare/client.js +76 -0
- package/dist/groups/cloudflare/guidance.md +7 -0
- package/dist/groups/cloudflare/memory.d.ts +19 -0
- package/dist/groups/cloudflare/memory.js +43 -0
- package/dist/groups/cloudflare/tools.d.ts +3 -0
- package/dist/groups/cloudflare/tools.js +140 -0
- package/dist/groups/infisical/client.d.ts +30 -0
- package/dist/groups/infisical/client.js +133 -0
- package/dist/groups/infisical/guidance.md +8 -0
- package/dist/groups/infisical/memory.d.ts +18 -0
- package/dist/groups/infisical/memory.js +43 -0
- package/dist/groups/infisical/tools.d.ts +3 -0
- package/dist/groups/infisical/tools.js +88 -0
- package/dist/groups/mxroute/client.d.ts +90 -0
- package/dist/groups/mxroute/client.js +86 -0
- package/dist/groups/mxroute/guidance.md +13 -0
- package/dist/groups/mxroute/memory.d.ts +34 -0
- package/dist/groups/mxroute/memory.js +83 -0
- package/dist/groups/mxroute/tools.d.ts +3 -0
- package/dist/groups/mxroute/tools.js +158 -0
- package/dist/groups/openrouter/client.d.ts +66 -0
- package/dist/groups/openrouter/client.js +66 -0
- package/dist/groups/openrouter/guidance.md +7 -0
- package/dist/groups/openrouter/memory.d.ts +26 -0
- package/dist/groups/openrouter/memory.js +59 -0
- package/dist/groups/openrouter/tools.d.ts +3 -0
- package/dist/groups/openrouter/tools.js +130 -0
- package/dist/groups/registrar/client.d.ts +48 -0
- package/dist/groups/registrar/client.js +75 -0
- package/dist/groups/registrar/guidance.md +9 -0
- package/dist/groups/registrar/memory.d.ts +16 -0
- package/dist/groups/registrar/memory.js +27 -0
- package/dist/groups/registrar/tools.d.ts +4 -0
- package/dist/groups/registrar/tools.js +102 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +35 -0
- package/dist/policy.d.ts +12 -0
- package/dist/policy.js +1 -0
- package/dist/result.d.ts +2 -0
- package/dist/result.js +17 -0
- package/dist/runtime/agent.d.ts +28 -0
- package/dist/runtime/agent.js +28 -0
- package/dist/runtime/container.d.ts +8 -0
- package/dist/runtime/container.js +41 -0
- package/dist/runtime/run.d.ts +51 -0
- package/dist/runtime/run.js +152 -0
- package/dist/runtime/transcribe.d.ts +7 -0
- package/dist/runtime/transcribe.js +37 -0
- package/dist/runtime/turns.d.ts +13 -0
- package/dist/runtime/turns.js +23 -0
- package/dist/runtime/web/index.html +452 -0
- package/dist/runtime/web/server.d.ts +20 -0
- package/dist/runtime/web/server.js +150 -0
- package/dist/schemas.d.ts +2 -0
- package/dist/schemas.js +6 -0
- package/dist/secret-delivery.d.ts +18 -0
- package/dist/secret-delivery.js +45 -0
- package/dist/secret-store.d.ts +13 -0
- package/dist/secret-store.js +1 -0
- package/dist/secrets.d.ts +5 -0
- package/dist/secrets.js +13 -0
- package/package.json +61 -4
- package/template/Dockerfile +19 -0
- package/template/README.md +55 -0
- package/template/_dockerignore +7 -0
- package/template/_gitignore +4 -0
- package/template/entrypoint.sh +14 -0
- package/template/evals/notes.eval.ts +55 -0
- package/template/home/memory/README.md +1 -0
- package/template/home/prompts/system.md +15 -0
- package/template/src/agent.ts +47 -0
- package/template/src/groups/notes.ts +85 -0
- package/template/src/main.ts +4 -0
- package/template/test/agent.test.ts +22 -0
- package/template/tsconfig.json +17 -0
- package/template/vitest.config.ts +7 -0
package/dist/policy.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
export interface InfisicalPolicy {
|
|
3
|
+
readablePath: z.ZodType<string>;
|
|
4
|
+
writablePath: z.ZodType<string>;
|
|
5
|
+
envLabel(path: string): string;
|
|
6
|
+
}
|
|
7
|
+
export interface AgentPolicy {
|
|
8
|
+
agent: string;
|
|
9
|
+
operator: string;
|
|
10
|
+
maxKeyLimitUsd: number;
|
|
11
|
+
infisical: InfisicalPolicy;
|
|
12
|
+
}
|
package/dist/policy.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/result.d.ts
ADDED
package/dist/result.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ServiceError } from "./errors.js";
|
|
2
|
+
export async function result(run) {
|
|
3
|
+
try {
|
|
4
|
+
const value = await run();
|
|
5
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
6
|
+
}
|
|
7
|
+
catch (err) {
|
|
8
|
+
if (err instanceof ServiceError)
|
|
9
|
+
return `Error: ${err.message}`;
|
|
10
|
+
throw err;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
// The operator's name comes from the agent's policy (ADR-0003). The model
|
|
14
|
+
// never writes this copy; the gate decided the rejection.
|
|
15
|
+
export function rejected(reason, operator = "the operator") {
|
|
16
|
+
return `Not done: ${operator} did not approve (${reason}). Do not try again unless ${operator} asks.`;
|
|
17
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
|
|
2
|
+
import type { StructuredTool } from "@langchain/core/tools";
|
|
3
|
+
import { type BaseCheckpointSaver } from "@langchain/langgraph";
|
|
4
|
+
export declare const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
5
|
+
export declare const DEFAULT_TOOL_CALL_LIMIT = 25;
|
|
6
|
+
export declare function createAgentGraph(opts: {
|
|
7
|
+
model: BaseChatModel;
|
|
8
|
+
tools: StructuredTool[];
|
|
9
|
+
briefing: string;
|
|
10
|
+
checkpointer?: BaseCheckpointSaver;
|
|
11
|
+
toolCallLimit?: number;
|
|
12
|
+
}): import("langchain").ReactAgent<import("langchain").AgentTypeConfig<import("langchain").ResponseFormatUndefined, undefined, import("langchain").AnyAnnotationRoot, readonly [import("langchain").AgentMiddleware<import("zod/v3").ZodObject<{
|
|
13
|
+
threadToolCallCount: import("zod/v3").ZodDefault<import("zod/v3").ZodRecord<import("zod/v3").ZodString, import("zod/v3").ZodNumber>>;
|
|
14
|
+
runToolCallCount: import("zod/v3").ZodDefault<import("zod/v3").ZodRecord<import("zod/v3").ZodString, import("zod/v3").ZodNumber>>;
|
|
15
|
+
}, "strip", import("zod/v3").ZodTypeAny, {
|
|
16
|
+
threadToolCallCount: Record<string, number>;
|
|
17
|
+
runToolCallCount: Record<string, number>;
|
|
18
|
+
}, {
|
|
19
|
+
threadToolCallCount?: Record<string, number> | undefined;
|
|
20
|
+
runToolCallCount?: Record<string, number> | undefined;
|
|
21
|
+
}>, undefined, unknown, readonly (import("@langchain/core/tools").ServerTool | import("@langchain/core/tools").ClientTool)[], readonly []>], readonly (import("@langchain/core/tools").ServerTool | StructuredTool<import("@langchain/core/tools").ToolSchemaBase, any, any, any, unknown> | import("@langchain/core/tools").ClientTool)[], readonly []>>;
|
|
22
|
+
export type AgentGraph = ReturnType<typeof createAgentGraph>;
|
|
23
|
+
export declare function openRouterModel(opts: {
|
|
24
|
+
apiKey: string;
|
|
25
|
+
model: string;
|
|
26
|
+
title: string;
|
|
27
|
+
baseUrl?: string;
|
|
28
|
+
}): BaseChatModel;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { MemorySaver } from "@langchain/langgraph";
|
|
2
|
+
import { ChatOpenAI } from "@langchain/openai";
|
|
3
|
+
import { createAgent, toolCallLimitMiddleware } from "langchain";
|
|
4
|
+
export const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
5
|
+
// Upper limit of tool calls in one user turn. It stops a loop.
|
|
6
|
+
export const DEFAULT_TOOL_CALL_LIMIT = 25;
|
|
7
|
+
export function createAgentGraph(opts) {
|
|
8
|
+
return createAgent({
|
|
9
|
+
model: opts.model,
|
|
10
|
+
tools: opts.tools,
|
|
11
|
+
systemPrompt: opts.briefing,
|
|
12
|
+
checkpointer: opts.checkpointer ?? new MemorySaver(),
|
|
13
|
+
middleware: [toolCallLimitMiddleware({ runLimit: opts.toolCallLimit ?? DEFAULT_TOOL_CALL_LIMIT })],
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
// A chat model on OpenRouter (or any OpenAI-compatible endpoint). `title` is
|
|
17
|
+
// the X-Title header, which names the app in OpenRouter's activity list.
|
|
18
|
+
export function openRouterModel(opts) {
|
|
19
|
+
return new ChatOpenAI({
|
|
20
|
+
model: opts.model,
|
|
21
|
+
apiKey: opts.apiKey,
|
|
22
|
+
temperature: 0,
|
|
23
|
+
configuration: {
|
|
24
|
+
baseURL: opts.baseUrl ?? OPENROUTER_BASE_URL,
|
|
25
|
+
defaultHeaders: { "X-Title": opts.title },
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SecretStore } from "../secret-store.js";
|
|
2
|
+
import type { SecretSink } from "../secrets.js";
|
|
3
|
+
export declare function inboxSink(store: SecretStore, path: string, now?: () => Date): SecretSink;
|
|
4
|
+
export declare const noSink: SecretSink;
|
|
5
|
+
export declare function startHealth(port: number, host?: string): Promise<{
|
|
6
|
+
server: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
|
|
7
|
+
port: number;
|
|
8
|
+
}>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Container mode: no terminal. The web chat stays on 127.0.0.1 inside the pod
|
|
2
|
+
// (reach it with kubectl port-forward), and a health server on all addresses
|
|
3
|
+
// answers the kubelet.
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
// A new secret with no storeAt goes to an Infisical inbox folder, because no
|
|
6
|
+
// terminal is there to show it. The name holds the label and the time, so a
|
|
7
|
+
// second secret never replaces the first.
|
|
8
|
+
export function inboxSink(store, path, now = () => new Date()) {
|
|
9
|
+
return {
|
|
10
|
+
where: `the Infisical inbox folder ${path}`,
|
|
11
|
+
async deliver(label, value) {
|
|
12
|
+
const stamp = now().toISOString().replace(/[-:]/g, "").replace(/\..*$/, "").replace("T", "_");
|
|
13
|
+
const base = label.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "SECRET";
|
|
14
|
+
const head = /^[A-Z]/.test(base) ? base : `S_${base}`;
|
|
15
|
+
const name = `${head.slice(0, 110)}_${stamp}`;
|
|
16
|
+
await store.put({ path, name }, value);
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
// A sink for a container with no secret store. The tool reports the error.
|
|
21
|
+
export const noSink = {
|
|
22
|
+
async deliver(label) {
|
|
23
|
+
throw new Error(`no place for the new secret for ${label}: the agent runs in a container without Infisical. Call again with storeAt.`);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
export async function startHealth(port, host = "0.0.0.0") {
|
|
27
|
+
const server = createServer((req, res) => {
|
|
28
|
+
const path = new URL(req.url ?? "/", "http://x").pathname;
|
|
29
|
+
if (req.method === "GET" && path === "/healthz") {
|
|
30
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
31
|
+
res.end('{"status":"ok"}');
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
res.writeHead(404).end();
|
|
35
|
+
});
|
|
36
|
+
await new Promise((resolve, reject) => {
|
|
37
|
+
server.once("error", reject);
|
|
38
|
+
server.listen(port, host, () => resolve());
|
|
39
|
+
});
|
|
40
|
+
return { server, port: server.address().port };
|
|
41
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
|
|
2
|
+
import { type AnyGroup } from "../assemble.js";
|
|
3
|
+
import { type Credentials, type InfisicalConfig } from "../credentials.js";
|
|
4
|
+
import { HttpInfisical } from "../groups/infisical/client.js";
|
|
5
|
+
import type { AgentPolicy } from "../policy.js";
|
|
6
|
+
import type { SecretStore } from "../secret-store.js";
|
|
7
|
+
import type { SecretSink } from "../secrets.js";
|
|
8
|
+
export interface AgentConfig {
|
|
9
|
+
name: string;
|
|
10
|
+
model: string;
|
|
11
|
+
groups: readonly AnyGroup[];
|
|
12
|
+
system: string;
|
|
13
|
+
policy: AgentPolicy;
|
|
14
|
+
infisical?: InfisicalConfig & {
|
|
15
|
+
tokenKey: string;
|
|
16
|
+
};
|
|
17
|
+
identityFile?: URL | string;
|
|
18
|
+
modelKey?: string;
|
|
19
|
+
transcribeModel?: string;
|
|
20
|
+
toolCallLimit?: number;
|
|
21
|
+
envPrefix?: string;
|
|
22
|
+
port?: number;
|
|
23
|
+
healthPort?: number;
|
|
24
|
+
secretInbox?: string;
|
|
25
|
+
}
|
|
26
|
+
export declare function modelId(config: AgentConfig, env?: NodeJS.ProcessEnv): string;
|
|
27
|
+
export declare function buildAgent(config: AgentConfig, creds: Credentials, secrets: SecretSink, opts?: {
|
|
28
|
+
infisical?: SecretStore | undefined;
|
|
29
|
+
vaultHosts?: Set<string> | undefined;
|
|
30
|
+
model?: BaseChatModel;
|
|
31
|
+
}): {
|
|
32
|
+
graph: import("langchain").ReactAgent<import("langchain").AgentTypeConfig<import("langchain").ResponseFormatUndefined, undefined, import("langchain").AnyAnnotationRoot, readonly [import("langchain").AgentMiddleware<import("zod/v3").ZodObject<{
|
|
33
|
+
threadToolCallCount: import("zod/v3").ZodDefault<import("zod/v3").ZodRecord<import("zod/v3").ZodString, import("zod/v3").ZodNumber>>;
|
|
34
|
+
runToolCallCount: import("zod/v3").ZodDefault<import("zod/v3").ZodRecord<import("zod/v3").ZodString, import("zod/v3").ZodNumber>>;
|
|
35
|
+
}, "strip", import("zod/v3").ZodTypeAny, {
|
|
36
|
+
threadToolCallCount: Record<string, number>;
|
|
37
|
+
runToolCallCount: Record<string, number>;
|
|
38
|
+
}, {
|
|
39
|
+
threadToolCallCount?: Record<string, number> | undefined;
|
|
40
|
+
runToolCallCount?: Record<string, number> | undefined;
|
|
41
|
+
}>, undefined, unknown, readonly (import("@langchain/core/tools").ServerTool | import("@langchain/core/tools").ClientTool)[], readonly []>], readonly (import("@langchain/core/tools").ServerTool | import("langchain").StructuredTool<import("@langchain/core/tools").ToolSchemaBase, any, any, any, unknown> | import("@langchain/core/tools").ClientTool)[], readonly []>>;
|
|
42
|
+
groups: import("../group.ts").GroupStatus[];
|
|
43
|
+
tools: string[];
|
|
44
|
+
};
|
|
45
|
+
export declare function connectKeys(config: AgentConfig, env?: NodeJS.ProcessEnv): Promise<{
|
|
46
|
+
creds: Credentials<string>;
|
|
47
|
+
vaultHosts: Set<string> | undefined;
|
|
48
|
+
infisical: HttpInfisical | undefined;
|
|
49
|
+
}>;
|
|
50
|
+
export declare function isHeadless(config: AgentConfig, env?: NodeJS.ProcessEnv): boolean;
|
|
51
|
+
export declare function runAgent(config: AgentConfig, env?: NodeJS.ProcessEnv): Promise<void>;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// An agent as data, and the one function that runs it: keys, tool groups,
|
|
2
|
+
// the model, the terminal chat and the local web chat.
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { stderr, stdin, stdout } from "node:process";
|
|
6
|
+
import { assembleAgent, connectServices } from "../assemble.js";
|
|
7
|
+
import { isAgentVault, loadCredentials, loadIdentityCredentials, readIdentityFile, sessionHosts, } from "../credentials.js";
|
|
8
|
+
import { HttpInfisical } from "../groups/infisical/client.js";
|
|
9
|
+
import { createAgentGraph, openRouterModel } from "./agent.js";
|
|
10
|
+
import { inboxSink, noSink, startHealth } from "./container.js";
|
|
11
|
+
import { openRouterTranscriber } from "./transcribe.js";
|
|
12
|
+
import { resume, say } from "./turns.js";
|
|
13
|
+
import { startWeb } from "./web/server.js";
|
|
14
|
+
const prefixOf = (c) => c.envPrefix ?? c.name.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
|
|
15
|
+
export function modelId(config, env = process.env) {
|
|
16
|
+
return env[`${prefixOf(config)}_MODEL`] ?? config.model;
|
|
17
|
+
}
|
|
18
|
+
// Builds the agent with the tool groups that are on. Only the model key is
|
|
19
|
+
// required. In Agent Vault mode each key is a placeholder, so `vaultHosts`
|
|
20
|
+
// (the hosts of the session's services) decides instead.
|
|
21
|
+
export function buildAgent(config, creds, secrets, opts = {}) {
|
|
22
|
+
const services = connectServices(config.groups, {
|
|
23
|
+
holds: (k) => creds.holds(k),
|
|
24
|
+
get: (k) => creds.get(k),
|
|
25
|
+
store: opts.infisical,
|
|
26
|
+
});
|
|
27
|
+
const { tools, briefing, statuses } = assembleAgent({
|
|
28
|
+
groups: config.groups,
|
|
29
|
+
system: config.system,
|
|
30
|
+
policy: config.policy,
|
|
31
|
+
services,
|
|
32
|
+
secrets,
|
|
33
|
+
enable: {
|
|
34
|
+
has: (k) => creds.holds(k),
|
|
35
|
+
vaultHosts: opts.vaultHosts,
|
|
36
|
+
hosts: config.infisical ? { infisical: new URL(config.infisical.url).host } : {},
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
const model = opts.model ??
|
|
40
|
+
openRouterModel({ apiKey: creds.get(config.modelKey ?? "OPENROUTER_API_KEY"), model: modelId(config), title: config.name });
|
|
41
|
+
const graph = createAgentGraph({
|
|
42
|
+
model,
|
|
43
|
+
tools,
|
|
44
|
+
briefing,
|
|
45
|
+
...(config.toolCallLimit ? { toolCallLimit: config.toolCallLimit } : {}),
|
|
46
|
+
});
|
|
47
|
+
return { graph, groups: statuses, tools: tools.map((t) => t.name) };
|
|
48
|
+
}
|
|
49
|
+
// Gets the keys in the mode that the environment shows. Agent Vault wins: in
|
|
50
|
+
// that mode the process holds no keys at all. <PREFIX>_KEYS=user skips the
|
|
51
|
+
// identity file and uses the caller's own keys.
|
|
52
|
+
export async function connectKeys(config, env = process.env) {
|
|
53
|
+
const idFile = isAgentVault(env) || env[`${prefixOf(config)}_KEYS`] === "user" || !config.identityFile || !config.infisical
|
|
54
|
+
? undefined
|
|
55
|
+
: readIdentityFile(config.identityFile);
|
|
56
|
+
const identity = idFile && config.infisical ? await loadIdentityCredentials(idFile, config.infisical) : undefined;
|
|
57
|
+
const creds = identity?.creds ?? loadCredentials(env);
|
|
58
|
+
// Agent Vault: the session's services decide the tool groups, and the
|
|
59
|
+
// Infisical tools send a placeholder token that the proxy replaces.
|
|
60
|
+
const vaultHosts = creds.mode === "agent-vault" && config.infisical ? await sessionHosts(config.infisical.url, env) : undefined;
|
|
61
|
+
const infisical = identity?.infisical ??
|
|
62
|
+
(creds.mode === "agent-vault" && config.infisical && (!vaultHosts || vaultHosts.has(new URL(config.infisical.url).host))
|
|
63
|
+
? new HttpInfisical({ token: creds.get(config.infisical.tokenKey) }, { baseUrl: config.infisical.url, projectId: config.infisical.projectId, env: config.infisical.env })
|
|
64
|
+
: undefined);
|
|
65
|
+
return { creds, vaultHosts, infisical };
|
|
66
|
+
}
|
|
67
|
+
// Local only: the secret goes to this terminal, never to the model or the browser.
|
|
68
|
+
const terminalSink = {
|
|
69
|
+
async deliver(label, value) {
|
|
70
|
+
stderr.write(`\n New secret for ${label} (shown one time, save it now):\n ${value}\n\n`);
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
// Whether the agent runs in container mode: <PREFIX>_HEADLESS=1.
|
|
74
|
+
export function isHeadless(config, env = process.env) {
|
|
75
|
+
return env[`${prefixOf(config)}_HEADLESS`] === "1";
|
|
76
|
+
}
|
|
77
|
+
// Runs the agent. On a laptop: the terminal chat and the local web chat. In
|
|
78
|
+
// container mode (<PREFIX>_HEADLESS=1): the web chat and a health server, until
|
|
79
|
+
// SIGTERM or SIGINT.
|
|
80
|
+
export async function runAgent(config, env = process.env) {
|
|
81
|
+
const { name } = config;
|
|
82
|
+
const headless = isHeadless(config, env);
|
|
83
|
+
const { creds, vaultHosts, infisical } = await connectKeys(config, env);
|
|
84
|
+
if (creds.mode === "agent-vault" && config.infisical && !vaultHosts) {
|
|
85
|
+
stderr.write("Agent Vault: Infisical did not list the session's services, so every tool group is on.\n");
|
|
86
|
+
}
|
|
87
|
+
const inbox = config.secretInbox ?? (config.infisical ? `${config.infisical.path}/inbox` : undefined);
|
|
88
|
+
const sink = !headless ? terminalSink : infisical && inbox ? inboxSink(infisical, inbox) : noSink;
|
|
89
|
+
if (headless && sink === noSink) {
|
|
90
|
+
stderr.write("Container mode without Infisical: a new secret must go to Infisical with storeAt.\n");
|
|
91
|
+
}
|
|
92
|
+
const { graph, groups } = buildAgent(config, creds, sink, { infisical, vaultHosts });
|
|
93
|
+
const model = modelId(config, env);
|
|
94
|
+
const web = await startWeb(graph, {
|
|
95
|
+
port: Number(env[`${prefixOf(config)}_WEB_PORT`] ?? config.port ?? 4141),
|
|
96
|
+
info: { name, model, groups, keys: creds.mode },
|
|
97
|
+
transcribe: openRouterTranscriber(creds.get(config.modelKey ?? "OPENROUTER_API_KEY"), {
|
|
98
|
+
title: name,
|
|
99
|
+
...(config.transcribeModel ? { model: config.transcribeModel } : {}),
|
|
100
|
+
}),
|
|
101
|
+
});
|
|
102
|
+
const banner = `${name} (${model}, keys: ${creds.mode}, groups: ${groups.filter((g) => g.enabled).map((g) => g.name).join(", ") || "none"}).\n`;
|
|
103
|
+
if (headless) {
|
|
104
|
+
const health = await startHealth(Number(env[`${prefixOf(config)}_HEALTH_PORT`] ?? config.healthPort ?? 8080));
|
|
105
|
+
stdout.write(`${banner}Web chat on ${web.url} inside the container (use kubectl port-forward). Health: :${health.port}/healthz\n`);
|
|
106
|
+
await new Promise((resolve) => {
|
|
107
|
+
process.once("SIGTERM", resolve);
|
|
108
|
+
process.once("SIGINT", resolve);
|
|
109
|
+
});
|
|
110
|
+
web.server.close();
|
|
111
|
+
health.server.close();
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const rl = createInterface({ input: stdin, output: stdout });
|
|
115
|
+
async function decide(req) {
|
|
116
|
+
stdout.write(`\n ${name} wants to: ${req.summary}\n`);
|
|
117
|
+
const answer = (await rl.question(" Approve? Type yes to approve: ")).trim().toLowerCase();
|
|
118
|
+
if (answer === "yes")
|
|
119
|
+
return { approved: true, argsHash: req.argsHash };
|
|
120
|
+
const reason = (await rl.question(" Reason (optional): ")).trim();
|
|
121
|
+
return { approved: false, argsHash: req.argsHash, reason: reason || "rejected" };
|
|
122
|
+
}
|
|
123
|
+
const thread = randomUUID();
|
|
124
|
+
async function turn(line) {
|
|
125
|
+
let step = await say(graph, thread, line);
|
|
126
|
+
while (step.kind === "approvals") {
|
|
127
|
+
const decisions = {};
|
|
128
|
+
for (const item of step.items)
|
|
129
|
+
decisions[item.id] = await decide(item);
|
|
130
|
+
step = await resume(graph, thread, decisions);
|
|
131
|
+
}
|
|
132
|
+
stdout.write(`\n${name}: ${step.text}\n\n`);
|
|
133
|
+
}
|
|
134
|
+
stdout.write(banner +
|
|
135
|
+
`Web chat: ${web.url}\n` +
|
|
136
|
+
`Type here to chat in the terminal, or exit to stop.\n\n`);
|
|
137
|
+
for (;;) {
|
|
138
|
+
const line = (await rl.question("You: ")).trim();
|
|
139
|
+
if (!line)
|
|
140
|
+
continue;
|
|
141
|
+
if (line === "exit")
|
|
142
|
+
break;
|
|
143
|
+
try {
|
|
144
|
+
await turn(line);
|
|
145
|
+
}
|
|
146
|
+
catch (err) {
|
|
147
|
+
stderr.write(`\nError: ${err instanceof Error ? err.message : String(err)}\n\n`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
rl.close();
|
|
151
|
+
web.server.close();
|
|
152
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const DEFAULT_TRANSCRIBE_MODEL = "google/gemini-3.5-flash-lite";
|
|
2
|
+
export type Transcriber = (wav: Buffer) => Promise<string>;
|
|
3
|
+
export declare function openRouterTranscriber(apiKey: string, opts?: {
|
|
4
|
+
model?: string;
|
|
5
|
+
title?: string;
|
|
6
|
+
fetch?: typeof fetch;
|
|
7
|
+
}): Transcriber;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { OPENROUTER_BASE_URL } from "./agent.js";
|
|
2
|
+
import { ServiceError } from "../errors.js";
|
|
3
|
+
// A cheap audio model on OpenRouter: about $0.0001 for a short message.
|
|
4
|
+
export const DEFAULT_TRANSCRIBE_MODEL = "google/gemini-3.5-flash-lite";
|
|
5
|
+
// Speech to text with an audio model on OpenRouter, on the agent's own key.
|
|
6
|
+
export function openRouterTranscriber(apiKey, opts = {}) {
|
|
7
|
+
const f = opts.fetch ?? fetch;
|
|
8
|
+
return async (wav) => {
|
|
9
|
+
const res = await f(`${OPENROUTER_BASE_URL}/chat/completions`, {
|
|
10
|
+
method: "POST",
|
|
11
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", "X-Title": opts.title ?? "agent-kit" },
|
|
12
|
+
body: JSON.stringify({
|
|
13
|
+
model: opts.model ?? DEFAULT_TRANSCRIBE_MODEL,
|
|
14
|
+
temperature: 0,
|
|
15
|
+
messages: [
|
|
16
|
+
{
|
|
17
|
+
role: "user",
|
|
18
|
+
content: [
|
|
19
|
+
{
|
|
20
|
+
type: "text",
|
|
21
|
+
text: "Transcribe this audio exactly, in the language spoken. Reply with the transcript only. If there is no speech, reply with nothing.",
|
|
22
|
+
},
|
|
23
|
+
{ type: "input_audio", input_audio: { data: wav.toString("base64"), format: "wav" } },
|
|
24
|
+
],
|
|
25
|
+
},
|
|
26
|
+
],
|
|
27
|
+
}),
|
|
28
|
+
});
|
|
29
|
+
const json = (await res.json().catch(() => ({})));
|
|
30
|
+
if (!res.ok)
|
|
31
|
+
throw new ServiceError(`speech to text failed (${res.status}): ${json.error?.message ?? res.statusText}`);
|
|
32
|
+
const text = json.choices?.[0]?.message?.content;
|
|
33
|
+
const said = typeof text === "string" ? text.trim() : "";
|
|
34
|
+
// A model marks a recording with no speech as "<noise>", "[silence]" and so on.
|
|
35
|
+
return /^[<[(][^<>[\]()]*[>\])]\.?$/.test(said) ? "" : said;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AgentGraph } from "./agent.js";
|
|
2
|
+
import { type ApprovalDecision, type ApprovalRequest } from "../approval.js";
|
|
3
|
+
export type Step = {
|
|
4
|
+
kind: "reply";
|
|
5
|
+
text: string;
|
|
6
|
+
} | {
|
|
7
|
+
kind: "approvals";
|
|
8
|
+
items: (ApprovalRequest & {
|
|
9
|
+
id: string;
|
|
10
|
+
})[];
|
|
11
|
+
};
|
|
12
|
+
export declare const say: (agent: AgentGraph, thread: string, text: string) => Promise<Step>;
|
|
13
|
+
export declare const resume: (agent: AgentGraph, thread: string, decisions: Record<string, ApprovalDecision>) => Promise<Step>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Command } from "@langchain/langgraph";
|
|
2
|
+
import { isApprovalRequest } from "../approval.js";
|
|
3
|
+
const config = (thread) => ({ configurable: { thread_id: thread }, recursionLimit: 60 });
|
|
4
|
+
// One graph run: it ends with a reply, or stops at the approvals it needs.
|
|
5
|
+
async function run(agent, input, thread) {
|
|
6
|
+
const state = await agent.invoke(input, config(thread));
|
|
7
|
+
const pending = (state.__interrupt__ ?? []);
|
|
8
|
+
if (pending.length > 0) {
|
|
9
|
+
return {
|
|
10
|
+
kind: "approvals",
|
|
11
|
+
items: pending.map((p) => {
|
|
12
|
+
if (!isApprovalRequest(p.value))
|
|
13
|
+
throw new Error(`unknown interrupt: ${JSON.stringify(p.value)}`);
|
|
14
|
+
return { ...p.value, id: p.id };
|
|
15
|
+
}),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const last = state.messages.at(-1);
|
|
19
|
+
const text = typeof last?.content === "string" ? last.content : JSON.stringify(last?.content);
|
|
20
|
+
return { kind: "reply", text };
|
|
21
|
+
}
|
|
22
|
+
export const say = (agent, thread, text) => run(agent, { messages: [{ role: "user", content: text }] }, thread);
|
|
23
|
+
export const resume = (agent, thread, decisions) => run(agent, new Command({ resume: decisions }), thread);
|