@agentprojectcontext/apx 1.6.0 → 1.7.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 (27) hide show
  1. package/package.json +1 -1
  2. package/src/core/config.js +2 -0
  3. package/src/core/mascot.js +5 -7
  4. package/src/daemon/index.js +37 -2
  5. package/src/daemon/super-agent-tools/helpers.js +119 -0
  6. package/src/daemon/super-agent-tools/index.js +52 -0
  7. package/src/daemon/super-agent-tools/tools/add-project.js +36 -0
  8. package/src/daemon/super-agent-tools/tools/call-agent.js +45 -0
  9. package/src/daemon/super-agent-tools/tools/call-mcp.js +30 -0
  10. package/src/daemon/super-agent-tools/tools/call-runtime.js +107 -0
  11. package/src/daemon/super-agent-tools/tools/edit-file.js +44 -0
  12. package/src/daemon/super-agent-tools/tools/import-agent.js +48 -0
  13. package/src/daemon/super-agent-tools/tools/list-agents.js +36 -0
  14. package/src/daemon/super-agent-tools/tools/list-files.js +38 -0
  15. package/src/daemon/super-agent-tools/tools/list-mcps.js +48 -0
  16. package/src/daemon/super-agent-tools/tools/list-projects.js +20 -0
  17. package/src/daemon/super-agent-tools/tools/list-vault-agents.js +18 -0
  18. package/src/daemon/super-agent-tools/tools/read-agent-memory.js +28 -0
  19. package/src/daemon/super-agent-tools/tools/read-file.js +33 -0
  20. package/src/daemon/super-agent-tools/tools/run-shell.js +64 -0
  21. package/src/daemon/super-agent-tools/tools/search-messages.js +32 -0
  22. package/src/daemon/super-agent-tools/tools/send-telegram.js +30 -0
  23. package/src/daemon/super-agent-tools/tools/set-identity.js +35 -0
  24. package/src/daemon/super-agent-tools/tools/tail-messages.js +37 -0
  25. package/src/daemon/super-agent-tools/tools/write-file.js +33 -0
  26. package/src/daemon/super-agent-tools.js +1 -539
  27. package/src/daemon/super-agent.js +34 -7
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentprojectcontext/apx",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "APX — unified CLI + daemon for the Agent Project Context (APC) standard.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -46,6 +46,8 @@ const DEFAULT_CONFIG = {
46
46
  name: "apx",
47
47
  model: "", // e.g. "ollama:llama3.2:3b"
48
48
  system: "", // optional override; defaults baked into super-agent.js
49
+ permission_mode: "automatico", // total | automatico | permiso
50
+ allowed_tools: [], // used by permission_mode="permiso"
49
51
  },
50
52
  engines: {
51
53
  anthropic: { api_key: "" },
@@ -4,9 +4,7 @@
4
4
  const R = "\x1b[0m";
5
5
  const B = "\x1b[1m";
6
6
  const W = "\x1b[97m"; // bright white
7
- const K = "\x1b[30m"; // black
8
7
  const BK = "\x1b[40m"; // bg black
9
- const BW = "\x1b[47m"; // bg white
10
8
  const CY = "\x1b[36m";
11
9
  const YE = "\x1b[33m";
12
10
  const GR = "\x1b[32m";
@@ -34,10 +32,10 @@ const MOODS = {
34
32
  wave: {
35
33
  color: CY,
36
34
  lines: [
37
- ` ${BK}${W} ▄███████▄ ${R} 👋`,
38
- ` ${BK}${W} █ ${R}${B}██${R}${W} ${B}██${R}${BK}${W} █ ${R}`,
39
- ` ${BK}${W} █ ◕ ◕ █ ${R}`,
40
- ` ${BK}${W} █ ╰▽╯ █ ${R}`,
35
+ ` ${BK}${W} ▄███████▄ ${R} ${DI}/)${R}`,
36
+ ` ${BK}${W} █ ${R}${B}██${R}${W} ${B}██${R}${BK}${W} █ ${R} ${DI}//${R}`,
37
+ ` ${BK}${W} █ ◕ ◕ █ ${R} ${DI}//${R}`,
38
+ ` ${BK}${W} █ ╰▽╯ █ ${R}${DI}/${R}`,
41
39
  ` ${BK}${W} ▀███████▀ ${R}`,
42
40
  ` ${DI} ╱ ╲ ╱ ╲ ${R}`,
43
41
  ],
@@ -76,7 +74,7 @@ const MOODS = {
76
74
  excited: {
77
75
  color: BL,
78
76
  lines: [
79
- ` ${BK}${W} ▄███████▄ ${R} ${BL}⬆${R}`,
77
+ ` ${BK}${W} ▄███████▄ ${R} ${BL}↑${R}`,
80
78
  ` ${BK}${W} █ ${R}${B}██${R}${W} ${B}██${R}${BK}${W} █ ${R}`,
81
79
  ` ${BK}${W} █ ★ ★ █ ${R}`,
82
80
  ` ${BK}${W} █ ╰◡╯ █ ${R}`,
@@ -44,6 +44,32 @@ function writePid() {
44
44
  } catch {}
45
45
  }
46
46
 
47
+ function pidIsAlive(pid) {
48
+ if (!pid || pid === process.pid) return false;
49
+ try {
50
+ process.kill(pid, 0);
51
+ return true;
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ function claimSingleton() {
58
+ try {
59
+ if (fs.existsSync(PID_PATH)) {
60
+ const pid = parseInt(fs.readFileSync(PID_PATH, "utf8"), 10);
61
+ if (pidIsAlive(pid)) {
62
+ log(`fatal: apx-daemon already running with pid ${pid}`);
63
+ process.exit(1);
64
+ }
65
+ fs.unlinkSync(PID_PATH);
66
+ }
67
+ } catch (e) {
68
+ log(`fatal: cannot claim daemon pid file: ${e.message}`);
69
+ process.exit(1);
70
+ }
71
+ }
72
+
47
73
  function clearPid() {
48
74
  try {
49
75
  if (fs.existsSync(PID_PATH)) fs.unlinkSync(PID_PATH);
@@ -71,6 +97,7 @@ class RegistryCache {
71
97
 
72
98
  async function main() {
73
99
  ensureHome();
100
+ claimSingleton();
74
101
 
75
102
  const cfg = readConfig();
76
103
  const host = effectiveHost(cfg);
@@ -95,7 +122,6 @@ async function main() {
95
122
 
96
123
  const plugins = new PluginManager({ projects, config: cfg, log, registries });
97
124
  plugins.initAll();
98
- plugins.startAll();
99
125
 
100
126
  const scheduler = new RoutineScheduler({
101
127
  projects,
@@ -103,7 +129,6 @@ async function main() {
103
129
  globalConfig: cfg,
104
130
  log,
105
131
  });
106
- scheduler.start();
107
132
 
108
133
  const startedAt = Date.now();
109
134
  const app = buildApi({
@@ -130,10 +155,20 @@ async function main() {
130
155
  writePid();
131
156
  log(`apx-daemon ${PKG.version} listening on http://${host}:${port}`);
132
157
  log(`projects: ${projects.list().length} | plugins: ${Object.keys(plugins.status()).join(", ") || "(none)"}`);
158
+ plugins.startAll();
159
+ scheduler.start();
133
160
  // Fire wake-up message after a short delay so plugins (Telegram) are ready
134
161
  setTimeout(() => triggerWakeup(cfg, log), 3000);
135
162
  });
136
163
 
164
+ server.on("error", (e) => {
165
+ log(`fatal: listen ${host}:${port} failed: ${e.message}`);
166
+ plugins.stopAll();
167
+ registries.shutdown();
168
+ clearPid();
169
+ process.exit(1);
170
+ });
171
+
137
172
  function shutdown(signal) {
138
173
  log(`received ${signal}, shutting down...`);
139
174
  scheduler.stop();
@@ -0,0 +1,119 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export function projectMeta(projects, entry) {
5
+ const meta = projects.list().find((p) => p.id === entry.id);
6
+ return {
7
+ id: entry.id,
8
+ name: meta?.name || path.basename(entry.path),
9
+ path: entry.path,
10
+ };
11
+ }
12
+
13
+ export function resolveProject(projects, target, { allowMulti = false } = {}) {
14
+ if (target === undefined || target === null || target === "") {
15
+ if (allowMulti) return null;
16
+ const defaultProject = projects.get(0);
17
+ if (defaultProject) return defaultProject;
18
+ const all = projects.list();
19
+ if (all.length === 1) return projects.get(all[0].id);
20
+ throw new Error(`multiple projects registered (${all.length}); specify project=<id|name|path>`);
21
+ }
22
+
23
+ const tgt = String(target);
24
+ if (tgt.toLowerCase() === "default") {
25
+ const defaultProject = projects.get(0);
26
+ if (!defaultProject) throw new Error("default project not available");
27
+ return defaultProject;
28
+ }
29
+
30
+ if (typeof target === "number" || /^\d+$/.test(tgt)) {
31
+ const entry = projects.get(parseInt(tgt, 10));
32
+ if (!entry) throw new Error(`project id ${target} not found`);
33
+ return entry;
34
+ }
35
+
36
+ const all = projects.list();
37
+ const byPath = all.find((p) => p.path === path.resolve(tgt));
38
+ if (byPath) return projects.get(byPath.id);
39
+
40
+ const byName = all.find((p) => p.name === tgt);
41
+ if (byName) return projects.get(byName.id);
42
+
43
+ const tgtLow = tgt.toLowerCase();
44
+ const fuzzy = all.filter(
45
+ (p) => p.name.toLowerCase().includes(tgtLow) || p.path.toLowerCase().includes(tgtLow)
46
+ );
47
+ if (fuzzy.length === 1) return projects.get(fuzzy[0].id);
48
+ if (fuzzy.length > 1) {
49
+ throw new Error(`project "${tgt}" is ambiguous; matches: ${fuzzy.map((p) => p.name).join(", ")}`);
50
+ }
51
+ throw new Error(`project "${tgt}" not found`);
52
+ }
53
+
54
+ export function safePathJoin(root, sub = ".") {
55
+ const target = path.resolve(root, sub || ".");
56
+ const rootResolved = path.resolve(root);
57
+ if (target !== rootResolved && !target.startsWith(rootResolved + path.sep)) {
58
+ throw new Error(`path "${sub}" escapes the project root`);
59
+ }
60
+ return target;
61
+ }
62
+
63
+ export function skillsFromFields(fields = {}) {
64
+ if (Array.isArray(fields.Skills)) return fields.Skills;
65
+ return (fields.Skills || "").split(",").map((s) => s.trim()).filter(Boolean);
66
+ }
67
+
68
+ export function agentRow(agent) {
69
+ return {
70
+ slug: agent.slug,
71
+ role: agent.fields.Role || null,
72
+ model: agent.fields.Model || null,
73
+ language: agent.fields.Language || null,
74
+ description: agent.fields.Description || null,
75
+ skills: skillsFromFields(agent.fields),
76
+ };
77
+ }
78
+
79
+ export function buildAgentSystem(project, agent) {
80
+ const parts = [];
81
+ if (agent.fields.Description) parts.push(agent.fields.Description);
82
+ if (agent.fields.Role) parts.push(`Role: ${agent.fields.Role}`);
83
+ if (agent.fields.Language) parts.push(`Default language: ${agent.fields.Language}`);
84
+
85
+ const memPath = path.join(project.path, ".apc", "agents", agent.slug, "memory.md");
86
+ if (fs.existsSync(memPath)) parts.push("## Memory\n" + fs.readFileSync(memPath, "utf8"));
87
+
88
+ const apxSkill = path.join(project.path, ".apc", "skills", "apx.md");
89
+ if (fs.existsSync(apxSkill)) parts.push("## APX\n" + fs.readFileSync(apxSkill, "utf8"));
90
+
91
+ for (const skill of skillsFromFields(agent.fields)) {
92
+ const skillPath = path.join(project.path, ".apc", "skills", `${skill}.md`);
93
+ if (fs.existsSync(skillPath)) parts.push(`## Skill: ${skill}\n` + fs.readFileSync(skillPath, "utf8"));
94
+ }
95
+
96
+ return parts.join("\n\n");
97
+ }
98
+
99
+ export function createPermissionGuard(globalConfig = {}) {
100
+ const permissionMode = globalConfig.super_agent?.permission_mode || "automatico";
101
+ const allowedTools = new Set(globalConfig.super_agent?.allowed_tools || []);
102
+
103
+ return function requirePermission(tool, { dangerous = false, confirmed = false } = {}) {
104
+ if (permissionMode === "total") return;
105
+ if (permissionMode === "permiso" && !allowedTools.has(tool) && !confirmed) {
106
+ throw new Error(`requires_confirmation: permission_mode=permiso blocks ${tool}`);
107
+ }
108
+ if (permissionMode === "automatico" && dangerous && !confirmed) {
109
+ throw new Error(`requires_confirmation: permission_mode=automatico requires confirmation for ${tool}`);
110
+ }
111
+ };
112
+ }
113
+
114
+ export function confirmedProperty(description) {
115
+ return {
116
+ type: "boolean",
117
+ description: description || "true only after explicit user confirmation for this exact action",
118
+ };
119
+ }
@@ -0,0 +1,52 @@
1
+ import listProjects from "./tools/list-projects.js";
2
+ import listAgents from "./tools/list-agents.js";
3
+ import listVaultAgents from "./tools/list-vault-agents.js";
4
+ import importAgent from "./tools/import-agent.js";
5
+ import addProject from "./tools/add-project.js";
6
+ import listMcps from "./tools/list-mcps.js";
7
+ import readAgentMemory from "./tools/read-agent-memory.js";
8
+ import listFiles from "./tools/list-files.js";
9
+ import readFile from "./tools/read-file.js";
10
+ import writeFile from "./tools/write-file.js";
11
+ import editFile from "./tools/edit-file.js";
12
+ import runShell from "./tools/run-shell.js";
13
+ import tailMessages from "./tools/tail-messages.js";
14
+ import searchMessages from "./tools/search-messages.js";
15
+ import callAgent from "./tools/call-agent.js";
16
+ import callMcp from "./tools/call-mcp.js";
17
+ import callRuntime from "./tools/call-runtime.js";
18
+ import sendTelegram from "./tools/send-telegram.js";
19
+ import setIdentity from "./tools/set-identity.js";
20
+ import { createPermissionGuard } from "./helpers.js";
21
+
22
+ const TOOLS = [
23
+ listProjects,
24
+ listAgents,
25
+ listVaultAgents,
26
+ importAgent,
27
+ addProject,
28
+ listMcps,
29
+ readAgentMemory,
30
+ listFiles,
31
+ readFile,
32
+ writeFile,
33
+ editFile,
34
+ runShell,
35
+ tailMessages,
36
+ searchMessages,
37
+ callAgent,
38
+ callMcp,
39
+ callRuntime,
40
+ sendTelegram,
41
+ setIdentity,
42
+ ];
43
+
44
+ export const TOOL_SCHEMAS = TOOLS.map((tool) => tool.schema);
45
+
46
+ export function makeToolHandlers(ctx) {
47
+ const toolCtx = {
48
+ ...ctx,
49
+ requirePermission: createPermissionGuard(ctx.globalConfig || {}),
50
+ };
51
+ return Object.fromEntries(TOOLS.map((tool) => [tool.name, tool.makeHandler(toolCtx)]));
52
+ }
@@ -0,0 +1,36 @@
1
+ import path from "node:path";
2
+ import { readConfig, addProject as addProjectInConfig } from "../../../core/config.js";
3
+ import { confirmedProperty, projectMeta } from "../helpers.js";
4
+
5
+ export default {
6
+ name: "add_project",
7
+ schema: {
8
+ type: "function",
9
+ function: {
10
+ name: "add_project",
11
+ description: "Register an existing APC project path with the APX daemon. The path must contain AGENTS.md and .apc/project.json.",
12
+ parameters: {
13
+ type: "object",
14
+ properties: {
15
+ path: { type: "string", description: "absolute or relative filesystem path to an APC project" },
16
+ confirmed: confirmedProperty("true only after explicit user confirmation for this exact project registration"),
17
+ },
18
+ required: ["path"],
19
+ },
20
+ },
21
+ },
22
+ makeHandler: ({ projects, requirePermission }) => ({ path: projectPath, confirmed = false }) => {
23
+ requirePermission("add_project", { dangerous: true, confirmed });
24
+ if (!projectPath) throw new Error("add_project: path required");
25
+
26
+ const cfg = readConfig();
27
+ const result = addProjectInConfig(cfg, projectPath);
28
+ const p = projects.register(result.project.path);
29
+ return {
30
+ ok: true,
31
+ added: result.added,
32
+ project: projectMeta(projects, p),
33
+ normalized_path: path.resolve(projectPath),
34
+ };
35
+ },
36
+ };
@@ -0,0 +1,45 @@
1
+ import { callEngine } from "../../engines/index.js";
2
+ import { readAgents } from "../../../core/parser.js";
3
+ import { buildAgentSystem, resolveProject } from "../helpers.js";
4
+
5
+ export default {
6
+ name: "call_agent",
7
+ schema: {
8
+ type: "function",
9
+ function: {
10
+ name: "call_agent",
11
+ description: "Run a one-shot prompt through a project agent's configured LLM engine.",
12
+ parameters: {
13
+ type: "object",
14
+ properties: {
15
+ project: { type: "string" },
16
+ agent: { type: "string", description: "agent slug" },
17
+ prompt: { type: "string" },
18
+ },
19
+ required: ["agent", "prompt"],
20
+ },
21
+ },
22
+ },
23
+ makeHandler: ({ projects, globalConfig }) => async ({ project, agent: slug, prompt }) => {
24
+ const p = resolveProject(projects, project);
25
+ const agent = readAgents(p.path).find((a) => a.slug === slug);
26
+ if (!agent) throw new Error(`agent ${slug} not found`);
27
+ if (!agent.fields.Model) throw new Error(`agent ${slug} has no model`);
28
+
29
+ const result = await callEngine({
30
+ modelId: agent.fields.Model,
31
+ system: buildAgentSystem(p, agent),
32
+ messages: [{ role: "user", content: prompt }],
33
+ config: p.config || globalConfig,
34
+ });
35
+ p.logMessage({
36
+ agent_slug: slug,
37
+ channel: "engine",
38
+ direction: "out",
39
+ author: slug,
40
+ body: result.text,
41
+ meta: { invoked_by: "super_agent_tool", usage: result.usage },
42
+ });
43
+ return { text: result.text, usage: result.usage };
44
+ },
45
+ };
@@ -0,0 +1,30 @@
1
+ import { confirmedProperty, resolveProject } from "../helpers.js";
2
+
3
+ export default {
4
+ name: "call_mcp",
5
+ schema: {
6
+ type: "function",
7
+ function: {
8
+ name: "call_mcp",
9
+ description: "Call a tool on an MCP server registered in default or a project. Args is a JSON object.",
10
+ parameters: {
11
+ type: "object",
12
+ properties: {
13
+ project: { type: "string" },
14
+ mcp: { type: "string", description: "MCP server name" },
15
+ tool: { type: "string", description: "tool name on that MCP" },
16
+ args: { type: "object", description: "arguments object" },
17
+ confirmed: confirmedProperty("true only after explicit user confirmation for this exact MCP call"),
18
+ },
19
+ required: ["mcp", "tool"],
20
+ },
21
+ },
22
+ },
23
+ makeHandler: ({ projects, registries, requirePermission }) => async ({ project, mcp, tool, args = {}, confirmed = false }) => {
24
+ requirePermission("call_mcp", { dangerous: true, confirmed });
25
+ const p = resolveProject(projects, project);
26
+ if (!registries) throw new Error("MCP registry unavailable");
27
+ const registry = registries.for ? registries.for(p) : registries.ensure(p);
28
+ return registry.call(mcp, tool, args);
29
+ },
30
+ };
@@ -0,0 +1,107 @@
1
+ import { readAgents } from "../../../core/parser.js";
2
+ import { getRuntime, RUNTIME_IDS } from "../../runtimes/index.js";
3
+ import { buildAgentSystem, confirmedProperty, resolveProject } from "../helpers.js";
4
+
5
+ function resolveProjectForAgent(projects, project, slug) {
6
+ if (project) return resolveProject(projects, project);
7
+
8
+ const defaultProject = projects.get(0);
9
+ if (defaultProject && readAgents(defaultProject.path).find((a) => a.slug === slug)) {
10
+ return defaultProject;
11
+ }
12
+
13
+ const matches = [];
14
+ for (const entry of projects.list()) {
15
+ const p = projects.get(entry.id);
16
+ if (readAgents(p.path).find((a) => a.slug === slug)) matches.push(p);
17
+ }
18
+ if (matches.length === 1) return matches[0];
19
+ if (defaultProject) return defaultProject;
20
+ return resolveProject(projects, project);
21
+ }
22
+
23
+ export default {
24
+ name: "call_runtime",
25
+ schema: {
26
+ type: "function",
27
+ function: {
28
+ name: "call_runtime",
29
+ description: "Spawn an external CLI runtime (Claude Code, Codex, OpenCode, Aider) impersonating an APC agent.",
30
+ parameters: {
31
+ type: "object",
32
+ properties: {
33
+ project: { type: "string" },
34
+ agent: { type: "string", description: "APC agent slug from AGENTS.md, not runtime name" },
35
+ runtime: {
36
+ type: "string",
37
+ enum: ["claude-code", "codex", "opencode", "aider"],
38
+ description: "external CLI runtime",
39
+ },
40
+ prompt: { type: "string" },
41
+ timeout_s: { type: "integer", description: "seconds before SIGTERM; default 300" },
42
+ confirmed: confirmedProperty("true only after explicit user confirmation for this exact runtime command"),
43
+ },
44
+ required: ["agent", "runtime", "prompt"],
45
+ },
46
+ },
47
+ },
48
+ makeHandler: ({ projects, requirePermission }) => async ({ project, agent: slug, runtime, prompt, timeout_s = 300, confirmed = false }) => {
49
+ requirePermission("call_runtime", { dangerous: true, confirmed });
50
+
51
+ const p = resolveProjectForAgent(projects, project, slug);
52
+ const agent = readAgents(p.path).find((a) => a.slug === slug);
53
+ if (!agent) {
54
+ const directory = projects.list().map((entry) => ({
55
+ project: entry.name,
56
+ kind: entry.id === 0 ? "default" : "project",
57
+ path: entry.path,
58
+ agents: readAgents(projects.get(entry.id).path).map((a) => a.slug),
59
+ }));
60
+ return { error: `agent "${slug}" not found in selected project`, directory };
61
+ }
62
+
63
+ let rt;
64
+ try {
65
+ rt = getRuntime(runtime);
66
+ } catch (e) {
67
+ return { error: `${e.message}. Available runtimes: ${RUNTIME_IDS.join(", ")}` };
68
+ }
69
+
70
+ const r = await rt.run({
71
+ system: buildAgentSystem(p, agent),
72
+ prompt,
73
+ cwd: p.path,
74
+ timeoutMs: timeout_s * 1000,
75
+ });
76
+
77
+ p.logMessage({
78
+ agent_slug: slug,
79
+ channel: "runtime",
80
+ direction: "in",
81
+ author: "user",
82
+ body: prompt,
83
+ meta: { runtime, invoked_by: "super_agent_tool" },
84
+ });
85
+ p.logMessage({
86
+ agent_slug: slug,
87
+ channel: "runtime",
88
+ direction: "out",
89
+ author: slug,
90
+ body: r.output || "",
91
+ meta: {
92
+ runtime,
93
+ exit_code: r.exitCode,
94
+ external_session_path: r.externalSessionPath || null,
95
+ invoked_by: "super_agent_tool",
96
+ },
97
+ });
98
+
99
+ return {
100
+ runtime,
101
+ exit_code: r.exitCode,
102
+ output: (r.output || "").slice(0, 4000),
103
+ truncated: (r.output || "").length > 4000,
104
+ external_session_path: r.externalSessionPath || null,
105
+ };
106
+ },
107
+ };
@@ -0,0 +1,44 @@
1
+ import fs from "node:fs";
2
+ import { confirmedProperty, resolveProject, safePathJoin } from "../helpers.js";
3
+
4
+ export default {
5
+ name: "edit_file",
6
+ schema: {
7
+ type: "function",
8
+ function: {
9
+ name: "edit_file",
10
+ description: "Edit a UTF-8 text file inside default or a project by replacing one exact string with another.",
11
+ parameters: {
12
+ type: "object",
13
+ properties: {
14
+ project: { type: "string" },
15
+ path: { type: "string", description: "relative path inside the project" },
16
+ search: { type: "string", description: "exact text to replace" },
17
+ replace: { type: "string", description: "replacement text" },
18
+ all: { type: "boolean", description: "replace all matches; default false replaces one match" },
19
+ confirmed: confirmedProperty("true only after explicit user confirmation for this exact file edit"),
20
+ },
21
+ required: ["path", "search", "replace"],
22
+ },
23
+ },
24
+ },
25
+ makeHandler: ({ projects, requirePermission }) => ({ project, path, search, replace, all = false, confirmed = false }) => {
26
+ requirePermission("edit_file", { dangerous: true, confirmed });
27
+ if (!path) throw new Error("edit_file: path required");
28
+ if (!search) throw new Error("edit_file: search required");
29
+
30
+ const p = resolveProject(projects, project);
31
+ const target = safePathJoin(p.path, path);
32
+ if (!fs.existsSync(target)) throw new Error(`file not found: ${path}`);
33
+ const before = fs.readFileSync(target, "utf8");
34
+ const matches = before.split(search).length - 1;
35
+ if (matches === 0) throw new Error("search text not found");
36
+ if (!all && matches > 1) {
37
+ throw new Error(`search text appears ${matches} times; set all=true or use a more specific search`);
38
+ }
39
+
40
+ const after = all ? before.split(search).join(replace) : before.replace(search, replace);
41
+ fs.writeFileSync(target, after, "utf8");
42
+ return { ok: true, path: target, replacements: all ? matches : 1 };
43
+ },
44
+ };
@@ -0,0 +1,48 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { readVaultAgents, VAULT_DIR } from "../../../core/parser.js";
4
+ import { addImportedAgent, ensureAgentDir, regenerateAgentsMd } from "../../../core/scaffold.js";
5
+ import { confirmedProperty, projectMeta, resolveProject } from "../helpers.js";
6
+
7
+ export default {
8
+ name: "import_agent",
9
+ schema: {
10
+ type: "function",
11
+ function: {
12
+ name: "import_agent",
13
+ description: "Import an agent template from the APX vault into default or a registered project.",
14
+ parameters: {
15
+ type: "object",
16
+ properties: {
17
+ project: { type: "string", description: "project id/name/path; omit or use 'default' for ~/.apx/projects/default" },
18
+ agent: { type: "string", description: "agent slug from list_vault_agents" },
19
+ confirmed: confirmedProperty("true only after explicit user confirmation for this exact import"),
20
+ },
21
+ required: ["agent"],
22
+ },
23
+ },
24
+ },
25
+ makeHandler: ({ projects, requirePermission }) => ({ project, agent: slug, confirmed = false }) => {
26
+ requirePermission("import_agent", { dangerous: true, confirmed });
27
+ if (!slug) throw new Error("import_agent: agent required");
28
+
29
+ const vaultPath = path.join(VAULT_DIR, `${slug}.md`);
30
+ if (!fs.existsSync(vaultPath)) {
31
+ const available = readVaultAgents().map((a) => a.slug).join(", ") || "(none)";
32
+ throw new Error(`agent "${slug}" not found in vault. Available: ${available}`);
33
+ }
34
+
35
+ const p = resolveProject(projects, project || "default");
36
+ addImportedAgent(p.path, slug);
37
+ ensureAgentDir(p.path, slug);
38
+ regenerateAgentsMd(p.path);
39
+ projects.rebuild(p.id);
40
+
41
+ return {
42
+ ok: true,
43
+ agent: slug,
44
+ project: projectMeta(projects, p),
45
+ source: vaultPath,
46
+ };
47
+ },
48
+ };
@@ -0,0 +1,36 @@
1
+ import { readAgents } from "../../../core/parser.js";
2
+ import { agentRow, resolveProject } from "../helpers.js";
3
+
4
+ export default {
5
+ name: "list_agents",
6
+ schema: {
7
+ type: "function",
8
+ function: {
9
+ name: "list_agents",
10
+ description: "List agents. If project is omitted, returns all agents grouped by project, including default.",
11
+ parameters: {
12
+ type: "object",
13
+ properties: {
14
+ project: { type: "string", description: "project id, name, path, or substring; omit to list all projects" },
15
+ },
16
+ required: [],
17
+ },
18
+ },
19
+ },
20
+ makeHandler: ({ projects }) => ({ project } = {}) => {
21
+ const p = resolveProject(projects, project, { allowMulti: true });
22
+ if (p) return readAgents(p.path).map(agentRow);
23
+ return projects.list().map((entry) => {
24
+ const e = projects.get(entry.id);
25
+ return {
26
+ project: {
27
+ id: entry.id,
28
+ kind: entry.id === 0 ? "default" : "project",
29
+ name: entry.name,
30
+ path: entry.path,
31
+ },
32
+ agents: readAgents(e.path).map(agentRow),
33
+ };
34
+ });
35
+ },
36
+ };