@cognisphere-sh/cognisphere-harness 0.13.0 → 0.15.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 (33) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/dist-web/assets/{file-editor-CqGYKmT3.js → file-editor-DJydzVQK.js} +1 -1
  3. package/dist-web/assets/{index-CDE-jsH8.js → index-C2uTXv8R.js} +2 -2
  4. package/dist-web/index.html +1 -1
  5. package/home-template/docs/base-harness/README.md +25 -7
  6. package/home-template/docs/base-harness/skills.md +1 -1
  7. package/package.json +5 -4
  8. package/skills/create-plugin/CHANGELOG.md +7 -0
  9. package/skills/create-plugin/SKILL.md +10 -6
  10. package/src/agents/base-agent/system_prompts/0-base_prompt.md +2 -0
  11. package/src/agents/base-agent/workspace/router.ts +47 -0
  12. package/src/agents/base-agent/workspace/workflows/README.md +71 -0
  13. package/src/api/admin.ts +1 -1
  14. package/src/cli/agent.ts +1 -2
  15. package/src/core/agent-manager.ts +17 -9
  16. package/src/core/queue.ts +19 -6
  17. package/src/core/router.ts +258 -0
  18. package/src/core/runner.ts +273 -66
  19. package/src/core/types.ts +2 -14
  20. package/src/plugins/admin/index.ts +2 -2
  21. package/src/plugins/agent-messaging/index.ts +4 -3
  22. package/src/plugins/gws/index.ts +8 -120
  23. package/src/plugins/gws/seed/system_prompts/plugin-gws.md +8 -4
  24. package/src/plugins/scheduler/index.ts +4 -4
  25. package/src/plugins/scheduler/seed/system_prompts/plugin-scheduler.md +1 -1
  26. package/src/plugins/telegram/index.ts +4 -98
  27. package/src/plugins/telegram/seed/system_prompts/plugin-telegram.md +4 -6
  28. package/src/plugins/gws/seed/scripts/gws/routes +0 -117
  29. package/src/plugins/gws/seed/skills/gws/route-email/CHANGELOG.md +0 -14
  30. package/src/plugins/gws/seed/skills/gws/route-email/SKILL.md +0 -84
  31. package/src/plugins/telegram/seed/scripts/telegram/routes +0 -95
  32. package/src/plugins/telegram/seed/skills/telegram/route-chats/CHANGELOG.md +0 -7
  33. package/src/plugins/telegram/seed/skills/telegram/route-chats/SKILL.md +0 -63
@@ -0,0 +1,258 @@
1
+ import { accessSync, constants, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import type { Logger } from "./logger.js";
5
+
6
+ /**
7
+ * Agent-owned message routing. The router is the only thing that decides
8
+ * which thread a message goes to.
9
+ *
10
+ * Every message a plugin hands the runner (`notify`) goes through the agent's
11
+ * router, `workspace/router.ts`, which returns one or more thread ids. When it
12
+ * returns nothing, the thread is the message's `metadata.threadId` (set by a
13
+ * plugin that targets a thread, such as agent-messaging or the console), or
14
+ * `main`. A thread id `workflow:<name>` is a workflow: a static script in
15
+ * `workspace/workflows/<name>/` that a worker runs once per queued message.
16
+ *
17
+ * The router runs in the harness process and must be synchronous, so a message
18
+ * is in the queue the moment `notify` returns. It is reloaded when its file or
19
+ * the workflows change; a reload that fails keeps the last good router.
20
+ */
21
+
22
+ /** What the router sees. */
23
+ export interface RouterMessage {
24
+ notification: string;
25
+ pluginId: string;
26
+ channelId: string;
27
+ text: string;
28
+ metadata: Record<string, unknown>;
29
+ isSilent: boolean;
30
+ }
31
+
32
+ export interface WorkflowInfo {
33
+ name: string;
34
+ description: string;
35
+ }
36
+
37
+ export type RouteFn = (
38
+ msg: RouterMessage,
39
+ workflows: WorkflowInfo[],
40
+ ) => string | string[] | null | undefined | void;
41
+
42
+ export interface Workflow extends WorkflowInfo {
43
+ /** Absolute path of the script to run. */
44
+ script: string;
45
+ }
46
+
47
+ export interface Routing {
48
+ route: RouteFn | null;
49
+ workflows: Map<string, Workflow>;
50
+ /** Set when `router.ts` exists but failed to load. */
51
+ error?: string;
52
+ }
53
+
54
+ export const ROUTER_FILE = join("workspace", "router.ts");
55
+ export const WORKFLOWS_DIR = join("workspace", "workflows");
56
+ export const DEFAULT_THREAD = "main";
57
+ export const WORKFLOW_PREFIX = "workflow:";
58
+
59
+ /** The base agent's starter router and workflows folder. */
60
+ const BASE_WORKSPACE = fileURLToPath(new URL("../agents/base-agent/workspace", import.meta.url));
61
+
62
+ /** Give an agent the starter router and workflows README if it has none
63
+ * (agents created before routing existed). Never overwrites; a failure is
64
+ * logged, not thrown. */
65
+ export function seedRouting(agentDir: string, log: Logger): void {
66
+ for (const rel of ["router.ts", join("workflows", "README.md")]) {
67
+ const dest = join(agentDir, "workspace", rel);
68
+ try {
69
+ if (existsSync(dest)) continue;
70
+ mkdirSync(dirname(dest), { recursive: true });
71
+ cpSync(join(BASE_WORKSPACE, rel), dest);
72
+ } catch (err) {
73
+ log.error({ err, dest }, "could not seed routing file");
74
+ }
75
+ }
76
+ }
77
+
78
+ /** The workflow a thread id names (`workflow:<name>` → `<name>`), if any. */
79
+ export function workflowName(threadId: string): string | undefined {
80
+ return threadId.startsWith(WORKFLOW_PREFIX) ? threadId.slice(WORKFLOW_PREFIX.length) : undefined;
81
+ }
82
+
83
+ /** Directory entries, or none if it is missing or unreadable. */
84
+ function listDir(dir: string) {
85
+ try {
86
+ return readdirSync(dir, { withFileTypes: true });
87
+ } catch {
88
+ return [];
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Load the router and workflows of an agent. Never throws. A workflow with a
94
+ * bad `workflow.json` or a script that isn't executable is skipped (and
95
+ * logged).
96
+ */
97
+ export async function loadRouting(agentDir: string, log: Logger): Promise<Routing> {
98
+ const workflows = new Map<string, Workflow>();
99
+ const wfRoot = join(agentDir, WORKFLOWS_DIR);
100
+ for (const entry of listDir(wfRoot)) {
101
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
102
+ const dir = join(wfRoot, entry.name);
103
+ try {
104
+ const spec = JSON.parse(readFileSync(join(dir, "workflow.json"), "utf8")) as Record<
105
+ string,
106
+ unknown
107
+ >;
108
+ const description = typeof spec.description === "string" ? spec.description.trim() : "";
109
+ if (!description) throw new Error("workflow.json needs a description");
110
+ if (typeof spec.script !== "string" || !spec.script) {
111
+ throw new Error("workflow.json needs a script");
112
+ }
113
+ const script = join(dir, spec.script);
114
+ try {
115
+ accessSync(script, constants.X_OK);
116
+ } catch {
117
+ throw new Error(`script missing or not executable (chmod +x): ${spec.script}`);
118
+ }
119
+ workflows.set(entry.name, { name: entry.name, description, script });
120
+ } catch (err) {
121
+ log.error({ err, workflow: entry.name }, "workflow skipped");
122
+ }
123
+ }
124
+
125
+ let route: RouteFn | null = null;
126
+ let error: string | undefined;
127
+ const file = join(agentDir, ROUTER_FILE);
128
+ if (existsSync(file)) {
129
+ try {
130
+ // The harness process outlives every reload; the mtime query makes an
131
+ // edited router load fresh instead of from the module cache.
132
+ const url = `${pathToFileURL(file).href}?v=${statSync(file).mtimeMs}`;
133
+ const mod = (await import(url)) as { default?: unknown };
134
+ if (typeof mod.default !== "function") throw new Error("router.ts has no default export function");
135
+ route = mod.default as RouteFn;
136
+ } catch (err) {
137
+ error = err instanceof Error ? err.message : String(err);
138
+ log.error({ err, file }, "router failed to load");
139
+ }
140
+ }
141
+ log.info({ router: route !== null, workflows: [...workflows.keys()] }, "routing loaded");
142
+ return { route, workflows, ...(error ? { error } : {}) };
143
+ }
144
+
145
+ /** A cheap fingerprint of everything `loadRouting` reads, to detect edits. */
146
+ function routingStamp(agentDir: string): string {
147
+ const parts: string[] = [];
148
+ const stamp = (p: string) => {
149
+ try {
150
+ const s = statSync(p);
151
+ parts.push(`${p}:${s.mtimeMs}:${s.mode}`);
152
+ } catch {
153
+ parts.push(`${p}:-`);
154
+ }
155
+ };
156
+ stamp(join(agentDir, ROUTER_FILE));
157
+ const wfRoot = join(agentDir, WORKFLOWS_DIR);
158
+ stamp(wfRoot);
159
+ for (const d of listDir(wfRoot)) {
160
+ if (!d.isDirectory()) continue;
161
+ stamp(join(wfRoot, d.name));
162
+ for (const f of listDir(join(wfRoot, d.name))) stamp(join(wfRoot, d.name, f.name));
163
+ }
164
+ return parts.join("|");
165
+ }
166
+
167
+ /**
168
+ * Re-load routing whenever the router or a workflow changes, so the agent's
169
+ * own edits apply within `intervalMs`. A router that fails to reload keeps the
170
+ * previous router function (the new workflow list still applies). Returns a
171
+ * stop function.
172
+ */
173
+ export function watchRouting(
174
+ agentDir: string,
175
+ initial: Routing,
176
+ apply: (r: Routing) => void,
177
+ log: Logger,
178
+ intervalMs = 2000,
179
+ ): () => void {
180
+ let current = initial;
181
+ let last = routingStamp(agentDir);
182
+ let busy = false;
183
+ const timer = setInterval(() => {
184
+ if (busy) return;
185
+ const now = routingStamp(agentDir);
186
+ if (now === last) return;
187
+ last = now;
188
+ busy = true;
189
+ void loadRouting(agentDir, log)
190
+ .then((next) => {
191
+ if (next.error && current.route) {
192
+ log.error({ error: next.error }, "router reload failed; keeping the previous router");
193
+ next = { ...next, route: current.route };
194
+ }
195
+ current = next;
196
+ apply(next);
197
+ })
198
+ .catch((err: unknown) => log.error({ err }, "routing reload failed; keeping current routing"))
199
+ .finally(() => {
200
+ busy = false;
201
+ });
202
+ }, intervalMs);
203
+ timer.unref();
204
+ return () => clearInterval(timer);
205
+ }
206
+
207
+ /** Why a thread id can't be used, or null. Thread ids double as folder names
208
+ * (`sessions/<threadId>/`), and `workflow:` ids must name a loaded workflow. */
209
+ function badThreadId(id: string, routing: Routing | undefined): string | null {
210
+ // Same rule as the API's `isSafeId`, so every queued thread stays readable.
211
+ if (!id.trim()) return "empty thread id";
212
+ if (id.length > 256 || id.startsWith(".") || /[/\\\0]/.test(id)) return `unsafe thread id: ${id}`;
213
+ const wf = workflowName(id);
214
+ if (wf !== undefined && !routing?.workflows.has(wf)) return `unknown workflow: ${wf}`;
215
+ return null;
216
+ }
217
+
218
+ /**
219
+ * The threads a message goes to. Never throws. When the router is absent,
220
+ * returns nothing, throws or returns only invalid ids, the thread is
221
+ * `metadata.threadId` if valid, else `main`. An explicit `[]` drops it.
222
+ */
223
+ export function resolveThreads(routing: Routing | undefined, msg: RouterMessage, log: Logger): string[] {
224
+ const published = msg.metadata.threadId;
225
+ let fallback = DEFAULT_THREAD;
226
+ if (typeof published === "string" && published) {
227
+ const bad = badThreadId(published, routing);
228
+ if (bad) log.error({ reason: bad }, "metadata.threadId rejected; using main");
229
+ else fallback = published;
230
+ }
231
+ if (!routing?.route) return [fallback];
232
+
233
+ let out: ReturnType<RouteFn>;
234
+ try {
235
+ const infos = [...routing.workflows.values()].map(({ name, description }) => ({
236
+ name,
237
+ description,
238
+ }));
239
+ out = routing.route(msg, infos);
240
+ } catch (err) {
241
+ log.error({ err, fallback }, "router threw; using fallback thread");
242
+ return [fallback];
243
+ }
244
+ if (out == null) return [fallback];
245
+ const ids = Array.isArray(out) ? out : [out];
246
+ if (ids.length === 0) {
247
+ log.info({ plugin: msg.pluginId, notification: msg.notification }, "router dropped message");
248
+ return [];
249
+ }
250
+
251
+ const valid: string[] = [];
252
+ for (const id of ids as unknown[]) {
253
+ const bad = typeof id === "string" ? badThreadId(id, routing) : "not a string";
254
+ if (bad) log.error({ route: id, reason: bad }, "router returned an invalid thread id");
255
+ else if (!valid.includes(id as string)) valid.push(id as string);
256
+ }
257
+ return valid.length > 0 ? valid : [fallback];
258
+ }