@syengup/friday-channel-next 0.1.30 → 0.1.36

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 (71) hide show
  1. package/README.md +8 -4
  2. package/dist/src/agent/abort-run.d.ts +12 -1
  3. package/dist/src/agent/abort-run.js +24 -9
  4. package/dist/src/agent/media-bridge.d.ts +8 -1
  5. package/dist/src/agent/media-bridge.js +23 -2
  6. package/dist/src/agent-forward-runtime.d.ts +15 -0
  7. package/dist/src/agent-forward-runtime.js +2 -0
  8. package/dist/src/agent-id.d.ts +8 -0
  9. package/dist/src/agent-id.js +21 -0
  10. package/dist/src/channel-actions.js +45 -14
  11. package/dist/src/channel.js +22 -1
  12. package/dist/src/http/handlers/agent-config.d.ts +27 -0
  13. package/dist/src/http/handlers/agent-config.js +182 -0
  14. package/dist/src/http/handlers/agent-files.d.ts +21 -0
  15. package/dist/src/http/handlers/agent-files.js +137 -0
  16. package/dist/src/http/handlers/agent-tools-catalog.d.ts +10 -0
  17. package/dist/src/http/handlers/agent-tools-catalog.js +33 -0
  18. package/dist/src/http/handlers/agents-list.js +1 -19
  19. package/dist/src/http/handlers/cancel.js +12 -6
  20. package/dist/src/http/handlers/files.d.ts +16 -0
  21. package/dist/src/http/handlers/files.js +80 -12
  22. package/dist/src/http/handlers/messages.js +8 -3
  23. package/dist/src/http/handlers/models-list.d.ts +5 -0
  24. package/dist/src/http/handlers/models-list.js +8 -0
  25. package/dist/src/http/handlers/sessions-settings.js +15 -10
  26. package/dist/src/http/server.js +23 -0
  27. package/dist/src/link-preview/ssrf-guard.js +6 -2
  28. package/dist/src/media-fetch.js +4 -1
  29. package/dist/src/skills-discovery.d.ts +58 -0
  30. package/dist/src/skills-discovery.js +247 -0
  31. package/dist/src/thinking-levels.d.ts +21 -0
  32. package/dist/src/thinking-levels.js +48 -0
  33. package/dist/src/tool-catalog.d.ts +53 -0
  34. package/dist/src/tool-catalog.js +192 -0
  35. package/dist/src/version.js +1 -1
  36. package/package.json +1 -1
  37. package/src/agent/abort-run.ts +24 -8
  38. package/src/agent/media-bridge.test.ts +71 -0
  39. package/src/agent/media-bridge.ts +23 -1
  40. package/src/agent-forward-runtime.ts +11 -0
  41. package/src/agent-id.ts +24 -0
  42. package/src/channel-actions.test.ts +47 -0
  43. package/src/channel-actions.ts +38 -14
  44. package/src/channel.lifecycle.test.ts +41 -0
  45. package/src/channel.ts +23 -1
  46. package/src/http/handlers/agent-config.test.ts +205 -0
  47. package/src/http/handlers/agent-config.ts +218 -0
  48. package/src/http/handlers/agent-files.test.ts +136 -0
  49. package/src/http/handlers/agent-files.ts +149 -0
  50. package/src/http/handlers/agent-tools-catalog.ts +42 -0
  51. package/src/http/handlers/agents-list.ts +1 -22
  52. package/src/http/handlers/cancel.test.ts +12 -2
  53. package/src/http/handlers/cancel.ts +12 -6
  54. package/src/http/handlers/files.test.ts +114 -0
  55. package/src/http/handlers/files.ts +97 -13
  56. package/src/http/handlers/messages.ts +7 -2
  57. package/src/http/handlers/models-list.test.ts +114 -0
  58. package/src/http/handlers/models-list.ts +12 -0
  59. package/src/http/handlers/sessions-settings.ts +16 -11
  60. package/src/http/server.ts +24 -0
  61. package/src/link-preview/ssrf-guard.test.ts +7 -2
  62. package/src/link-preview/ssrf-guard.ts +5 -1
  63. package/src/media-fetch.test.ts +1 -1
  64. package/src/media-fetch.ts +4 -1
  65. package/src/openclaw.d.ts +25 -1
  66. package/src/skills-discovery.test.ts +148 -0
  67. package/src/skills-discovery.ts +248 -0
  68. package/src/thinking-levels.test.ts +143 -0
  69. package/src/thinking-levels.ts +68 -0
  70. package/src/tool-catalog.ts +252 -0
  71. package/src/version.ts +1 -1
@@ -0,0 +1,218 @@
1
+ /**
2
+ * GET/PUT /friday-next/agents/{id}/config
3
+ *
4
+ * Reads and edits a single agent's runtime configuration — the same fields
5
+ * OpenClaw's ControlUI manages, but written through the plugin's own config
6
+ * channel (`api.runtime.config.mutateConfigFile`, proven by plugin-upgrade) so
7
+ * NO OpenClaw core changes are needed. All edits land in `agents.list[]` of the
8
+ * host config file (`~/.clawrc`), exactly where ControlUI's `config.set` writes.
9
+ *
10
+ * Editable fields:
11
+ * - model → agents.list[i].model (string | {primary,fallbacks})
12
+ * - thinkingDefault → agents.list[i].thinkingDefault
13
+ * - tools → agents.list[i].tools ({profile,allow,alsoAllow,deny})
14
+ * - skills → agents.list[i].skills (string[]; [] disables all, absent inherits defaults)
15
+ *
16
+ * Clearing an override MUST delete the field (not leave a stale value) so the
17
+ * core's config merge falls back to `agents.defaults` — same hazard documented
18
+ * for the default-model bug. PUT therefore treats an explicit `null` as "clear".
19
+ */
20
+
21
+ import type { IncomingMessage, ServerResponse } from "node:http";
22
+ import { getFridayAgentForwardRuntime } from "../../agent-forward-runtime.js";
23
+ import { getUpgradeRuntime } from "../../upgrade-runtime.js";
24
+ import { normalizeAgentId } from "../../agent-id.js";
25
+ import { discoverAvailableSkills, type DiscoveredSkill } from "../../skills-discovery.js";
26
+ import { extractBearerToken } from "../middleware/auth.js";
27
+ import { readJsonBody } from "../middleware/body.js";
28
+ import { createFridayNextLogger } from "../../logging.js";
29
+
30
+ function json(res: ServerResponse, status: number, body: unknown): true {
31
+ res.statusCode = status;
32
+ res.setHeader("Content-Type", "application/json");
33
+ res.end(JSON.stringify(body));
34
+ return true;
35
+ }
36
+
37
+ export interface AgentToolsConfig {
38
+ profile?: string;
39
+ allow?: string[];
40
+ alsoAllow?: string[];
41
+ deny?: string[];
42
+ }
43
+
44
+ interface AgentConfigView {
45
+ id: string;
46
+ exists: boolean;
47
+ /** Raw model field verbatim (string or {primary,fallbacks}); undefined inherits defaults. */
48
+ model?: unknown;
49
+ thinkingDefault?: string;
50
+ tools?: AgentToolsConfig;
51
+ /** Configured skills allow-list; undefined = inherit defaults, [] = all disabled. */
52
+ skills?: string[];
53
+ /** Full catalog of loadable skills (id + source category + description), best-effort. */
54
+ availableSkills: DiscoveredSkill[];
55
+ }
56
+
57
+ function readString(value: unknown): string | undefined {
58
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
59
+ }
60
+
61
+ function readStringArray(value: unknown): string[] | undefined {
62
+ if (!Array.isArray(value)) return undefined;
63
+ const out = value.filter((v): v is string => typeof v === "string" && v.trim().length > 0).map((v) => v.trim());
64
+ return out;
65
+ }
66
+
67
+ function readToolsConfig(value: unknown): AgentToolsConfig | undefined {
68
+ if (!value || typeof value !== "object") return undefined;
69
+ const t = value as Record<string, unknown>;
70
+ const view: AgentToolsConfig = {};
71
+ const profile = readString(t.profile);
72
+ if (profile) view.profile = profile;
73
+ const allow = readStringArray(t.allow);
74
+ if (allow) view.allow = allow;
75
+ const alsoAllow = readStringArray(t.alsoAllow);
76
+ if (alsoAllow) view.alsoAllow = alsoAllow;
77
+ const deny = readStringArray(t.deny);
78
+ if (deny) view.deny = deny;
79
+ return view;
80
+ }
81
+
82
+ /** Locate the configured `agents.list[]` entry whose normalized id matches `agentId`. */
83
+ function findAgentEntry(cfg: unknown, agentId: string): Record<string, unknown> | undefined {
84
+ const agents = (cfg as Record<string, unknown> | undefined)?.agents as Record<string, unknown> | undefined;
85
+ const list = agents?.list as Array<Record<string, unknown>> | undefined;
86
+ if (!Array.isArray(list)) return undefined;
87
+ return list.find((a) => a && typeof a === "object" && normalizeAgentId(a.id) === agentId);
88
+ }
89
+
90
+ function buildConfigView(agentId: string): AgentConfigView {
91
+ const rt = getFridayAgentForwardRuntime();
92
+ const cfg = rt?.getConfig();
93
+ const entry = cfg ? findAgentEntry(cfg, agentId) : undefined;
94
+ return {
95
+ id: agentId,
96
+ exists: entry !== undefined,
97
+ model: entry?.model,
98
+ thinkingDefault: readString(entry?.thinkingDefault),
99
+ tools: readToolsConfig(entry?.tools),
100
+ // undefined = no `skills` field (inherit defaults); [] = field present but empty (all disabled).
101
+ skills: readStringArray(entry?.skills),
102
+ availableSkills: discoverAvailableSkills(cfg, agentId),
103
+ };
104
+ }
105
+
106
+ // --- PUT validation helpers --------------------------------------------------
107
+
108
+ /** A field present in the body: `undefined` = not sent (keep), `null` = clear, else new value. */
109
+ type Patch<T> = { sent: boolean; clear: boolean; value?: T };
110
+
111
+ function readPatch<T>(body: Record<string, unknown>, key: string, coerce: (raw: unknown) => T | undefined): Patch<T> {
112
+ if (!(key in body)) return { sent: false, clear: false };
113
+ const raw = body[key];
114
+ if (raw === null) return { sent: true, clear: true };
115
+ const value = coerce(raw);
116
+ if (value === undefined) return { sent: false, clear: false };
117
+ return { sent: true, clear: false, value };
118
+ }
119
+
120
+ function coerceModel(raw: unknown): unknown | undefined {
121
+ if (typeof raw === "string") return raw.trim() || undefined;
122
+ if (raw && typeof raw === "object") {
123
+ const primary = readString((raw as Record<string, unknown>).primary);
124
+ if (!primary) return undefined;
125
+ const fallbacks = readStringArray((raw as Record<string, unknown>).fallbacks);
126
+ return fallbacks && fallbacks.length > 0 ? { primary, fallbacks } : { primary };
127
+ }
128
+ return undefined;
129
+ }
130
+
131
+ function coerceTools(raw: unknown): AgentToolsConfig | undefined {
132
+ return readToolsConfig(raw);
133
+ }
134
+
135
+ /** Skills: array (incl. empty = disable all) only; non-arrays are rejected upstream. */
136
+ function coerceSkills(raw: unknown): string[] | undefined {
137
+ return Array.isArray(raw) ? readStringArray(raw) ?? [] : undefined;
138
+ }
139
+
140
+ // --- handler -----------------------------------------------------------------
141
+
142
+ export async function handleAgentConfig(
143
+ req: IncomingMessage,
144
+ res: ServerResponse,
145
+ rawAgentId: string,
146
+ ): Promise<boolean> {
147
+ if (req.method !== "GET" && req.method !== "PUT") {
148
+ return json(res, 405, { error: "Method Not Allowed" });
149
+ }
150
+ if (!extractBearerToken(req)) {
151
+ return json(res, 401, { error: "Unauthorized: bearer token mismatch" });
152
+ }
153
+
154
+ const agentId = normalizeAgentId(rawAgentId);
155
+
156
+ if (req.method === "GET") {
157
+ return json(res, 200, { ok: true, ...buildConfigView(agentId) });
158
+ }
159
+
160
+ // PUT — partial patch.
161
+ const body = await readJsonBody(req);
162
+ if (!body) return json(res, 400, { error: "Invalid or missing JSON body" });
163
+
164
+ const model = readPatch(body, "model", coerceModel);
165
+ const thinkingDefault = readPatch(body, "thinkingDefault", (r) => readString(r));
166
+ const tools = readPatch(body, "tools", coerceTools);
167
+ const skills = readPatch(body, "skills", coerceSkills);
168
+
169
+ if ("skills" in body && body.skills !== null && !Array.isArray(body.skills)) {
170
+ return json(res, 400, { error: "skills must be an array of skill ids, [] to disable all, or null to inherit defaults" });
171
+ }
172
+ if (!model.sent && !thinkingDefault.sent && !tools.sent && !skills.sent) {
173
+ return json(res, 400, { error: "No editable fields provided (model, thinkingDefault, tools, skills)" });
174
+ }
175
+
176
+ const upgrade = getUpgradeRuntime();
177
+ if (!upgrade) return json(res, 503, { error: "Config write runtime unavailable" });
178
+
179
+ const log = createFridayNextLogger("agent-config");
180
+ try {
181
+ await upgrade.mutateConfigFile({
182
+ afterWrite: { mode: "auto" },
183
+ mutate: (draftRaw) => {
184
+ const draft = draftRaw as Record<string, unknown>;
185
+ const agents = (draft.agents ??= {}) as Record<string, unknown>;
186
+ const list = (agents.list ??= []) as Array<Record<string, unknown>>;
187
+ let entry = list.find((a) => a && typeof a === "object" && normalizeAgentId(a.id) === agentId);
188
+ if (!entry) {
189
+ // Implicit agent (e.g. "main") with no list entry yet — create a bare one.
190
+ // Never set `default: true`: that would change default-agent resolution.
191
+ entry = { id: agentId };
192
+ list.push(entry);
193
+ }
194
+ applyField(entry, "model", model);
195
+ applyField(entry, "thinkingDefault", thinkingDefault);
196
+ applyField(entry, "tools", tools);
197
+ applyField(entry, "skills", skills);
198
+ },
199
+ });
200
+ } catch (err) {
201
+ const msg = err instanceof Error ? err.message : String(err);
202
+ log.error(`agent config write failed for "${agentId}": ${msg}`);
203
+ return json(res, 500, { error: "Failed to write agent config", detail: msg });
204
+ }
205
+
206
+ log.info(`agent config updated for "${agentId}"`);
207
+ return json(res, 200, { ok: true, ...buildConfigView(agentId) });
208
+ }
209
+
210
+ /** Apply a patch: clear → delete the key; set → assign; not sent → leave as-is. */
211
+ function applyField(entry: Record<string, unknown>, key: string, patch: Patch<unknown>): void {
212
+ if (!patch.sent) return;
213
+ if (patch.clear) {
214
+ delete entry[key];
215
+ return;
216
+ }
217
+ entry[key] = patch.value;
218
+ }
@@ -0,0 +1,136 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
2
+ import { EventEmitter } from "node:events";
3
+ import { Readable } from "node:stream";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { handleAgentFiles, CORE_AGENT_FILES } from "./agent-files.js";
8
+ import { setMockRuntime } from "../../test-support/mock-runtime.js";
9
+ import {
10
+ setFridayAgentForwardRuntime,
11
+ resetFridayAgentForwardRuntimeForTest,
12
+ } from "../../agent-forward-runtime.js";
13
+
14
+ class MockRes extends EventEmitter {
15
+ statusCode = 0;
16
+ headers: Record<string, string> = {};
17
+ body = "";
18
+ setHeader(name: string, value: string): void {
19
+ this.headers[name.toLowerCase()] = value;
20
+ }
21
+ end(body?: string): void {
22
+ if (body) this.body += body;
23
+ }
24
+ }
25
+
26
+ const AUTH = { authorization: "Bearer test-token" };
27
+
28
+ function makeReq(headers: Record<string, string> = {}, method = "GET", body?: unknown): any {
29
+ const stream = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]);
30
+ return Object.assign(stream, { method, url: "/friday-next/agents/main/files", headers });
31
+ }
32
+
33
+ function setWorkspace(workspace: string | undefined): void {
34
+ setFridayAgentForwardRuntime({
35
+ runtime: {
36
+ agent: {
37
+ session: { resolveStorePath: () => "", loadSessionStore: () => ({}) },
38
+ ...(workspace ? { resolveAgentWorkspaceDir: () => workspace } : {}),
39
+ },
40
+ config: { current: () => ({}) },
41
+ },
42
+ } as any);
43
+ }
44
+
45
+ describe("handleAgentFiles", () => {
46
+ let workspace: string;
47
+
48
+ beforeEach(() => {
49
+ setMockRuntime();
50
+ workspace = fs.mkdtempSync(path.join(os.tmpdir(), "friday-files-"));
51
+ setWorkspace(workspace);
52
+ });
53
+
54
+ afterEach(() => {
55
+ resetFridayAgentForwardRuntimeForTest();
56
+ fs.rmSync(workspace, { recursive: true, force: true });
57
+ });
58
+
59
+ it("rejects unsupported methods with 405", async () => {
60
+ const res = new MockRes();
61
+ await handleAgentFiles(makeReq(AUTH, "DELETE"), res as any, "main", undefined);
62
+ expect(res.statusCode).toBe(405);
63
+ });
64
+
65
+ it("rejects missing token with 401", async () => {
66
+ const res = new MockRes();
67
+ await handleAgentFiles(makeReq({}, "GET"), res as any, "main", undefined);
68
+ expect(res.statusCode).toBe(401);
69
+ });
70
+
71
+ it("503 when the workspace can't be resolved", async () => {
72
+ setWorkspace(undefined);
73
+ const res = new MockRes();
74
+ await handleAgentFiles(makeReq(AUTH), res as any, "main", undefined);
75
+ expect(res.statusCode).toBe(503);
76
+ });
77
+
78
+ it("GET lists every whitelist file with existence + size", async () => {
79
+ fs.writeFileSync(path.join(workspace, "IDENTITY.md"), "hello");
80
+ const res = new MockRes();
81
+ await handleAgentFiles(makeReq(AUTH), res as any, "main", undefined);
82
+ expect(res.statusCode).toBe(200);
83
+ const body = JSON.parse(res.body);
84
+ expect(body.files).toHaveLength(CORE_AGENT_FILES.length);
85
+ const identity = body.files.find((f: { name: string }) => f.name === "IDENTITY.md");
86
+ expect(identity).toEqual({ name: "IDENTITY.md", exists: true, bytes: 5 });
87
+ const soul = body.files.find((f: { name: string }) => f.name === "SOUL.md");
88
+ expect(soul).toEqual({ name: "SOUL.md", exists: false, bytes: 0 });
89
+ });
90
+
91
+ it("GET one file returns its content", async () => {
92
+ fs.writeFileSync(path.join(workspace, "AGENTS.md"), "# rules\n");
93
+ const res = new MockRes();
94
+ await handleAgentFiles(makeReq(AUTH), res as any, "main", "AGENTS.md");
95
+ expect(res.statusCode).toBe(200);
96
+ const body = JSON.parse(res.body);
97
+ expect(body).toMatchObject({ ok: true, name: "AGENTS.md", exists: true, content: "# rules\n" });
98
+ });
99
+
100
+ it("GET a missing whitelisted file returns exists:false with empty content", async () => {
101
+ const res = new MockRes();
102
+ await handleAgentFiles(makeReq(AUTH), res as any, "main", "MEMORY.md");
103
+ const body = JSON.parse(res.body);
104
+ expect(body).toMatchObject({ exists: false, content: "" });
105
+ });
106
+
107
+ it("rejects a non-whitelisted file name with 400", async () => {
108
+ const res = new MockRes();
109
+ await handleAgentFiles(makeReq(AUTH), res as any, "main", "secrets.env");
110
+ expect(res.statusCode).toBe(400);
111
+ });
112
+
113
+ it("rejects path-traversal names with 400", async () => {
114
+ const res = new MockRes();
115
+ await handleAgentFiles(makeReq(AUTH), res as any, "main", "../escape.md");
116
+ expect(res.statusCode).toBe(400);
117
+ });
118
+
119
+ it("PUT writes content and the file lands on disk", async () => {
120
+ const res = new MockRes();
121
+ await handleAgentFiles(
122
+ makeReq(AUTH, "PUT", { content: "You are Friday." }),
123
+ res as any,
124
+ "main",
125
+ "IDENTITY.md",
126
+ );
127
+ expect(res.statusCode).toBe(200);
128
+ expect(fs.readFileSync(path.join(workspace, "IDENTITY.md"), "utf-8")).toBe("You are Friday.");
129
+ });
130
+
131
+ it("PUT without a content string returns 400", async () => {
132
+ const res = new MockRes();
133
+ await handleAgentFiles(makeReq(AUTH, "PUT", { foo: 1 }), res as any, "main", "IDENTITY.md");
134
+ expect(res.statusCode).toBe(400);
135
+ });
136
+ });
@@ -0,0 +1,149 @@
1
+ /**
2
+ * GET/PUT /friday-next/agents/{id}/files[/{name}]
3
+ *
4
+ * Reads and edits an agent's core workspace files — the same whitelist ControlUI
5
+ * exposes (AGENTS/IDENTITY/SOUL/TOOLS/MEMORY/USER/HEARTBEAT/BOOTSTRAP.md). These
6
+ * are plain workspace files, not config: written directly via Node fs into the
7
+ * dir resolved by `api.runtime.agent.resolveAgentWorkspaceDir` (the same call
8
+ * agents-list uses to read IDENTITY.md). No config mutation, no gateway restart —
9
+ * the agent re-reads them on its next run.
10
+ *
11
+ * - GET /agents/{id}/files → status of every whitelist file
12
+ * - GET /agents/{id}/files/{name} → one file's content
13
+ * - PUT /agents/{id}/files/{name} → write one file (body: { content })
14
+ *
15
+ * Security: the file name MUST be in the whitelist (no path traversal), and the
16
+ * resolved path is re-checked to stay inside the workspace dir as defense in depth.
17
+ */
18
+
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import type { IncomingMessage, ServerResponse } from "node:http";
22
+ import { getFridayAgentForwardRuntime } from "../../agent-forward-runtime.js";
23
+ import { normalizeAgentId } from "../../agent-id.js";
24
+ import { extractBearerToken } from "../middleware/auth.js";
25
+ import { readJsonBody } from "../middleware/body.js";
26
+ import { createFridayNextLogger } from "../../logging.js";
27
+
28
+ /** Core workspace files an agent edits, mirroring ControlUI's `agents.files` whitelist. */
29
+ export const CORE_AGENT_FILES = [
30
+ "AGENTS.md",
31
+ "IDENTITY.md",
32
+ "SOUL.md",
33
+ "TOOLS.md",
34
+ "MEMORY.md",
35
+ "USER.md",
36
+ "HEARTBEAT.md",
37
+ "BOOTSTRAP.md",
38
+ ] as const;
39
+
40
+ const CORE_FILE_SET = new Set<string>(CORE_AGENT_FILES);
41
+
42
+ /** Max core-file size on write (256 KiB) — these are prompts, not data dumps. */
43
+ const MAX_FILE_BYTES = 256 * 1024;
44
+
45
+ function json(res: ServerResponse, status: number, body: unknown): true {
46
+ res.statusCode = status;
47
+ res.setHeader("Content-Type", "application/json");
48
+ res.end(JSON.stringify(body));
49
+ return true;
50
+ }
51
+
52
+ /** Resolve the agent's workspace dir, or undefined if the runtime can't. */
53
+ function resolveWorkspace(agentId: string): string | undefined {
54
+ const rt = getFridayAgentForwardRuntime();
55
+ if (!rt?.resolveAgentWorkspaceDir) return undefined;
56
+ try {
57
+ const dir = rt.resolveAgentWorkspaceDir(rt.getConfig(), agentId);
58
+ return dir || undefined;
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ }
63
+
64
+ /** Whitelisted, traversal-safe absolute path for `name` inside `workspace`, or null. */
65
+ function safeFilePath(workspace: string, name: string): string | null {
66
+ if (!CORE_FILE_SET.has(name)) return null;
67
+ const resolved = path.resolve(workspace, name);
68
+ // Defense in depth: the resolved path must sit directly inside the workspace.
69
+ if (path.dirname(resolved) !== path.resolve(workspace)) return null;
70
+ return resolved;
71
+ }
72
+
73
+ export async function handleAgentFiles(
74
+ req: IncomingMessage,
75
+ res: ServerResponse,
76
+ rawAgentId: string,
77
+ fileName: string | undefined,
78
+ ): Promise<boolean> {
79
+ const method = req.method;
80
+ if (method !== "GET" && method !== "PUT") {
81
+ return json(res, 405, { error: "Method Not Allowed" });
82
+ }
83
+ if (!extractBearerToken(req)) {
84
+ return json(res, 401, { error: "Unauthorized: bearer token mismatch" });
85
+ }
86
+
87
+ const agentId = normalizeAgentId(rawAgentId);
88
+ const workspace = resolveWorkspace(agentId);
89
+ if (!workspace) return json(res, 503, { error: "Agent workspace not resolvable" });
90
+
91
+ // GET /files — list whitelist status.
92
+ if (method === "GET" && !fileName) {
93
+ const files = CORE_AGENT_FILES.map((name) => {
94
+ try {
95
+ const stat = fs.statSync(path.join(workspace, name));
96
+ return { name, exists: true, bytes: stat.size };
97
+ } catch {
98
+ return { name, exists: false, bytes: 0 };
99
+ }
100
+ });
101
+ return json(res, 200, { ok: true, id: agentId, files });
102
+ }
103
+
104
+ if (!fileName || !CORE_FILE_SET.has(fileName)) {
105
+ return json(res, 400, {
106
+ error: `Unknown core file; allowed: ${CORE_AGENT_FILES.join(", ")}`,
107
+ });
108
+ }
109
+ const filePath = safeFilePath(workspace, fileName);
110
+ if (!filePath) return json(res, 400, { error: "Invalid file name" });
111
+
112
+ if (method === "GET") {
113
+ try {
114
+ const content = fs.readFileSync(filePath, "utf-8");
115
+ return json(res, 200, { ok: true, id: agentId, name: fileName, exists: true, content });
116
+ } catch {
117
+ return json(res, 200, { ok: true, id: agentId, name: fileName, exists: false, content: "" });
118
+ }
119
+ }
120
+
121
+ // PUT — write content.
122
+ const body = await readJsonBody(req);
123
+ if (!body || typeof body.content !== "string") {
124
+ return json(res, 400, { error: "Missing required field: content (string)" });
125
+ }
126
+ const content = body.content;
127
+ if (Buffer.byteLength(content, "utf-8") > MAX_FILE_BYTES) {
128
+ return json(res, 413, { error: `content exceeds ${MAX_FILE_BYTES} bytes` });
129
+ }
130
+
131
+ const log = createFridayNextLogger("agent-files");
132
+ try {
133
+ fs.mkdirSync(workspace, { recursive: true });
134
+ fs.writeFileSync(filePath, content, "utf-8");
135
+ } catch (err) {
136
+ const msg = err instanceof Error ? err.message : String(err);
137
+ log.error(`write ${fileName} for "${agentId}" failed: ${msg}`);
138
+ return json(res, 500, { error: "Failed to write file", detail: msg });
139
+ }
140
+
141
+ log.info(`wrote ${fileName} for "${agentId}" (${Buffer.byteLength(content, "utf-8")} bytes)`);
142
+ return json(res, 200, {
143
+ ok: true,
144
+ id: agentId,
145
+ name: fileName,
146
+ exists: true,
147
+ bytes: Buffer.byteLength(content, "utf-8"),
148
+ });
149
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * GET /friday-next/agents/{id}/tools/catalog
3
+ *
4
+ * Returns the agent's full tool catalog (core + plugin tools, grouped by category,
5
+ * with descriptions, profiles, and per-tool effective `enabled`/`inProfile` state) for
6
+ * the app's toolbox editor — mirroring ControlUI. Edits are saved via the existing
7
+ * `PUT /agents/{id}/config` (tools.{profile,allow,alsoAllow,deny}).
8
+ */
9
+
10
+ import type { IncomingMessage, ServerResponse } from "node:http";
11
+ import { getFridayAgentForwardRuntime } from "../../agent-forward-runtime.js";
12
+ import { normalizeAgentId } from "../../agent-id.js";
13
+ import { buildAgentToolsCatalog } from "../../tool-catalog.js";
14
+ import { extractBearerToken } from "../middleware/auth.js";
15
+
16
+ function json(res: ServerResponse, status: number, body: unknown): true {
17
+ res.statusCode = status;
18
+ res.setHeader("Content-Type", "application/json");
19
+ res.end(JSON.stringify(body));
20
+ return true;
21
+ }
22
+
23
+ export async function handleAgentToolsCatalog(
24
+ req: IncomingMessage,
25
+ res: ServerResponse,
26
+ rawAgentId: string,
27
+ ): Promise<boolean> {
28
+ if (req.method !== "GET") {
29
+ return json(res, 405, { error: "Method Not Allowed" });
30
+ }
31
+ if (!extractBearerToken(req)) {
32
+ return json(res, 401, { error: "Unauthorized: bearer token mismatch" });
33
+ }
34
+
35
+ const agentId = normalizeAgentId(rawAgentId);
36
+ const cfg = getFridayAgentForwardRuntime()?.getConfig();
37
+ const catalog = await buildAgentToolsCatalog(cfg, agentId);
38
+ if (!catalog) {
39
+ return json(res, 503, { error: "Tool catalog unavailable" });
40
+ }
41
+ return json(res, 200, { ok: true, id: agentId, ...catalog });
42
+ }
@@ -6,11 +6,7 @@ import {
6
6
  type FridayAgentForwardRuntime,
7
7
  } from "../../agent-forward-runtime.js";
8
8
  import { extractBearerToken } from "../middleware/auth.js";
9
-
10
- const DEFAULT_AGENT_ID = "main";
11
-
12
- /** Agent ids already in path/shell-safe form skip the slug rewrite below. */
13
- const SAFE_AGENT_ID = /^[a-z0-9][a-z0-9_-]*$/;
9
+ import { DEFAULT_AGENT_ID, normalizeAgentId } from "../../agent-id.js";
14
10
 
15
11
  export interface FridayAgentEntry {
16
12
  id: string;
@@ -29,23 +25,6 @@ interface ResolvedAgents {
29
25
  defaultAgentId: string;
30
26
  }
31
27
 
32
- /**
33
- * Mirror of OpenClaw's `normalizeAgentId` (src/routing/session-key.ts): trim,
34
- * lowercase, keep path/shell-safe. Empty → "main".
35
- */
36
- function normalizeAgentId(value: unknown): string {
37
- const trimmed = typeof value === "string" ? value.trim() : "";
38
- if (!trimmed) return DEFAULT_AGENT_ID;
39
- const lowered = trimmed.toLowerCase();
40
- if (SAFE_AGENT_ID.test(lowered)) return lowered;
41
- return (
42
- lowered
43
- .replace(/[^a-z0-9_-]+/g, "-")
44
- .replace(/^-+|-+$/g, "")
45
- .slice(0, 64) || DEFAULT_AGENT_ID
46
- );
47
- }
48
-
49
28
  /** Extract a primary model ref from the `model` field (string or {primary,...}). */
50
29
  function resolvePrimaryModel(model: unknown): string | undefined {
51
30
  if (typeof model === "string") return readString(model);
@@ -47,7 +47,7 @@ describe("handleCancel", () => {
47
47
  expect((res as unknown as MockRes).statusCode).toBe(401);
48
48
  });
49
49
 
50
- it("returns 400 for missing runId", async () => {
50
+ it("returns 400 when neither sessionKey nor runId is provided", async () => {
51
51
  const req = mockReq("POST", { authorization: "Bearer test-token" });
52
52
  const res = new MockRes() as unknown as ServerResponse;
53
53
  const p = handleCancel(req as unknown as IncomingMessage, res);
@@ -56,7 +56,17 @@ describe("handleCancel", () => {
56
56
  expect((res as unknown as MockRes).statusCode).toBe(400);
57
57
  });
58
58
 
59
- it("untracks run under Vitest (abort skipped)", async () => {
59
+ it("accepts sessionKey and returns 200 (abort skipped under Vitest)", async () => {
60
+ const req = mockReq("POST", { authorization: "Bearer test-token" });
61
+ const res = new MockRes() as unknown as ServerResponse;
62
+ const p = handleCancel(req as unknown as IncomingMessage, res);
63
+ req.end(JSON.stringify({ sessionKey: "sk-1" }));
64
+ await p;
65
+ expect((res as unknown as MockRes).statusCode).toBe(200);
66
+ expect(JSON.parse((res as unknown as MockRes).body)).toMatchObject({ ok: true, sessionKey: "sk-1" });
67
+ });
68
+
69
+ it("untracks run by runId fallback under Vitest (abort skipped)", async () => {
60
70
  const req = mockReq("POST", { authorization: "Bearer test-token" });
61
71
  const res = new MockRes() as unknown as ServerResponse;
62
72
  const spyUntrack = vi.spyOn(sseEmitter, "untrackRun").mockImplementation(() => {});
@@ -1,5 +1,6 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { abortRun } from "../../agent/abort-run.js";
2
+ import { abortRunForSessionKey } from "../../agent/abort-run.js";
3
+ import { getRunRoute } from "../../run-metadata.js";
3
4
  import { sseEmitter } from "../../sse/emitter.js";
4
5
  import { readJsonBody } from "../middleware/body.js";
5
6
  import { extractBearerToken } from "../middleware/auth.js";
@@ -20,16 +21,21 @@ export async function handleCancel(req: IncomingMessage, res: ServerResponse): P
20
21
  }
21
22
  const body = await readJsonBody(req);
22
23
  const runId = typeof body?.runId === "string" ? body.runId.trim() : "";
23
- if (!runId) {
24
+ // sessionKey is the primary identifier (one active run per session); runId is a
25
+ // back-compat fallback for older apps — resolve it to a sessionKey via the run route.
26
+ const sessionKey =
27
+ (typeof body?.sessionKey === "string" ? body.sessionKey.trim() : "") ||
28
+ (runId ? getRunRoute(runId)?.sessionKey?.trim() ?? "" : "");
29
+ if (!sessionKey && !runId) {
24
30
  res.statusCode = 400;
25
31
  res.setHeader("Content-Type", "application/json");
26
- res.end(JSON.stringify({ error: "Missing runId" }));
32
+ res.end(JSON.stringify({ error: "Missing sessionKey or runId" }));
27
33
  return true;
28
34
  }
29
- await abortRun(runId);
30
- sseEmitter.untrackRun(runId);
35
+ const result = sessionKey ? await abortRunForSessionKey(sessionKey) : { aborted: false, drained: false };
36
+ if (runId) sseEmitter.untrackRun(runId);
31
37
  res.statusCode = 200;
32
38
  res.setHeader("Content-Type", "application/json");
33
- res.end(JSON.stringify({ ok: true, runId, cancelled: true }));
39
+ res.end(JSON.stringify({ ok: true, sessionKey, runId, cancelled: true, ...result }));
34
40
  return true;
35
41
  }