@netnodeag/kraftwerk 0.86.0 → 0.87.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 (41) hide show
  1. package/README.md +35 -8
  2. package/dist/cli/kraftwerk.js +1 -1
  3. package/dist/cli/routines.d.ts +4 -2
  4. package/dist/cli/routines.js +30 -13
  5. package/dist/client/routes.d.ts +4 -0
  6. package/dist/client/routes.js +4 -0
  7. package/dist/core/agent-status.js +4 -3
  8. package/dist/core/attention.js +8 -4
  9. package/dist/core/chat/context.js +12 -11
  10. package/dist/core/chat/sessions.js +2 -2
  11. package/dist/core/chat/state.d.ts +1 -1
  12. package/dist/core/chat/state.js +4 -4
  13. package/dist/core/chat/types.d.ts +6 -2
  14. package/dist/core/diagnose.js +13 -5
  15. package/dist/core/routines.d.ts +37 -11
  16. package/dist/core/routines.js +79 -27
  17. package/dist/core/skills.d.ts +2 -0
  18. package/dist/core/skills.js +2 -0
  19. package/dist/server/api/agents.d.ts +1 -0
  20. package/dist/server/api/agents.js +9 -7
  21. package/dist/server/api/index.d.ts +20 -10
  22. package/dist/server/api/runs.d.ts +19 -10
  23. package/dist/server/api/runs.js +45 -2
  24. package/package.json +1 -1
  25. package/web/dist/assets/{dist-DaClI4_P.js → dist-5ezEzkN_.js} +1 -1
  26. package/web/dist/assets/{dist-BRwu-xz3.js → dist-B2YS2uAJ.js} +1 -1
  27. package/web/dist/assets/{dist-CYuFWOhW.js → dist-B69hm6Vm.js} +1 -1
  28. package/web/dist/assets/{dist-ciCcv6TG.js → dist-BP5gr3hs.js} +1 -1
  29. package/web/dist/assets/{dist-CVzVQqDH.js → dist-BTUFCkqp.js} +1 -1
  30. package/web/dist/assets/{dist-BmpFCYFq.js → dist-CaaMxJ6G.js} +1 -1
  31. package/web/dist/assets/{dist-D4JsX0B8.js → dist-DCuMQcQZ.js} +1 -1
  32. package/web/dist/assets/dist-DI3h2IBG.js +1 -0
  33. package/web/dist/assets/{dist-60Qxhb1I.js → dist-DLUdIP27.js} +1 -1
  34. package/web/dist/assets/{dist-1mbdSunG.js → dist-DnBQdICn.js} +1 -1
  35. package/web/dist/assets/{dist-CPeXTjYj.js → dist-DxeKUyaX.js} +1 -1
  36. package/web/dist/assets/{editor-CXOAhwnW.js → editor-DMiLLeME.js} +3 -3
  37. package/web/dist/assets/index-CvxByvfI.css +2 -0
  38. package/web/dist/assets/{index-BpESoZpK.js → index-lXKLZep2.js} +14 -14
  39. package/web/dist/index.html +2 -2
  40. package/web/dist/assets/dist-B89nfy4o.js +0 -1
  41. package/web/dist/assets/index-DEO_Q944.css +0 -2
package/README.md CHANGED
@@ -615,14 +615,15 @@ are reachable by path; opening a vibeable moves it into the app folder as
615
615
  in any chat.
616
616
 
617
617
  **Artifacts.** The rail's third row, under Chats, lists everything made in the
618
- workspace and its projects — workflows, knowledge bundles, apps,
619
- presentations, boards,
618
+ workspace and its projects — chats (the first tile; for now also still in the rail), workflows, routines, knowledge bundles, skills, apps,
619
+ presentations, boards, repositories,
620
620
  contacts, places and events — newest first, with the project each belongs to. A tile per
621
621
  enabled kind filters the list to that kind (click again for everything),
622
622
  and the + beside its label makes a new one; the search matches titles.
623
- Selecting a row shows the thing in the right column — a workflow's own
624
- view (run it from there), a knowledge bundle with its concepts, a deck's
625
- slides, the
623
+ Selecting a row shows the thing in the right column — a chat's conversation to
624
+ continue, a workflow's own
625
+ view (run it from there), a routine to edit and run, a knowledge bundle with its concepts, a skill's
626
+ instructions, a repository's changes and commits, a deck's slides, the
626
627
  app running, a board's columns, a contact to edit — with "open" to go
627
628
  where it lives. Places show on an OpenStreetMap map (all of them; a
628
629
  selected place is zoomed to, with its details under the map, and a dot on
@@ -1203,6 +1204,25 @@ orders for an employee. Definitions live next to the agent in
1203
1204
  `agents/<slug>/routines.yml` and are git-tracked. Run state (last run, last
1204
1205
  session, errors) lives in `<output>/routines-state.json`.
1205
1206
 
1207
+ A routine can also be defined on its own, not on an agent: the workspace's
1208
+ routines live in `agents/routines.yml`, each with the project it runs in and
1209
+ who gets the prompt. Both are optional — no `project` runs it for the whole
1210
+ workspace, no `agent` asks the project's assistant (or Ralv, when there is
1211
+ no project either):
1212
+
1213
+ ```yaml
1214
+ # agents/routines.yml
1215
+ - id: weekly-digest
1216
+ name: Weekly digest
1217
+ schedule: "0 9 * * 1"
1218
+ prompt: Summarize what happened this week and add it to the project's log.
1219
+ project: relaunch # its runs are filed under the project and briefed with it
1220
+ agent: max # who gets the prompt; leave out for the project's assistant
1221
+ enabled: true
1222
+ ```
1223
+
1224
+ An agent's own routines look the same, without `agent`:
1225
+
1206
1226
  ```yaml
1207
1227
  # agents/max/routines.yml
1208
1228
  - id: morning-check
@@ -1245,9 +1265,16 @@ system notification while any inspector tab is open. Items live in
1245
1265
  `output/notifications.json`; `GET /api/notifications` lists them,
1246
1266
  `POST /api/notifications/read` marks them, `DELETE /api/notifications` clears.
1247
1267
 
1248
- Manage routines on the agent page, where you can create, edit and
1249
- delete them, toggle enabled, hit "run now", and jump to the last run's
1250
- session. Schedules missed while the server is down are skipped, not replayed.
1268
+ Every routine is listed on **Artifacts** under Routines, with who it asks
1269
+ and when it fires next. The + there makes a workspace routine — pick the
1270
+ project (or the whole workspace) and the agent (or the project's assistant)
1271
+ in the form — and selecting one edits it in place, with "run now" and
1272
+ delete. An agent's own routines are managed on the agent page, where you can
1273
+ create, edit and delete them, toggle enabled, hit "run now", and jump to the
1274
+ last run's session. On the command line a workspace routine is agent `_`:
1275
+ `kraftwerk routines add _ --name ... --schedule ... --prompt ... [--project
1276
+ <slug>] [--agent <slug>]`. Schedules missed while the server is down are
1277
+ skipped, not replayed.
1251
1278
 
1252
1279
  ## Channels
1253
1280
 
@@ -41,7 +41,7 @@ import { runUi } from "./ui.js";
41
41
  * kraftwerk run [workflow] [text] run one (prompts interactively if omitted)
42
42
  * kraftwerk runs [show <id>] inspect past runs from their traces
43
43
  * kraftwerk knowledge ... Knowledge: OKF bundles (list/get/put/verify/...)
44
- * kraftwerk routines ... per-agent scheduled prompts (list/add/remove/enable/run/adopt)
44
+ * kraftwerk routines ... scheduled prompts, an agent's or the workspace's (list/add/remove/enable/run/adopt)
45
45
  * kraftwerk whoami this machine's identity (handle@machine), the runner routines name
46
46
  * kraftwerk ui start the inspector web UI (localhost:1981)
47
47
  * kraftwerk workspaces ... known workspaces on this machine (list/start/stop/forget)
@@ -1,7 +1,9 @@
1
1
  import type { Command } from "commander";
2
2
  /**
3
- * `kraftwerk routines` — CLI surface over per-agent scheduled prompts
4
- * (agents/<slug>/routines.yml). Definition CRUD works directly on the
3
+ * `kraftwerk routines` — CLI surface over scheduled prompts: an agent's own
4
+ * (agents/<slug>/routines.yml) and the workspace's (agents/routines.yml),
5
+ * addressed as agent `_`: those are defined on their own, with the project
6
+ * they run in (--project) and who gets the prompt (--agent). Definition CRUD works directly on the
5
7
  * files; `run` fires through the running inspector server, because the
6
8
  * session (chat) and the scheduler live there. `adopt` makes this machine
7
9
  * the runner (runs_on) of every unassigned routine and commits routines.yml.
@@ -3,11 +3,13 @@ import path from "node:path";
3
3
  import chalk from "chalk";
4
4
  import { resolveWorkspace } from "../config.js";
5
5
  import { setDefaultWorkspace, Workspace } from "../core/workspace.js";
6
- import { adoptUnassigned, deleteRoutine, listRoutines, routineStatuses, saveRoutine, } from "../core/routines.js";
6
+ import { adoptUnassigned, deleteRoutine, listRoutines, routineStatuses, saveRoutine, WORKSPACE_ROUTINES, } from "../core/routines.js";
7
7
  import { getAgent, listAgents } from "../core/agents.js";
8
8
  /**
9
- * `kraftwerk routines` — CLI surface over per-agent scheduled prompts
10
- * (agents/<slug>/routines.yml). Definition CRUD works directly on the
9
+ * `kraftwerk routines` — CLI surface over scheduled prompts: an agent's own
10
+ * (agents/<slug>/routines.yml) and the workspace's (agents/routines.yml),
11
+ * addressed as agent `_`: those are defined on their own, with the project
12
+ * they run in (--project) and who gets the prompt (--agent). Definition CRUD works directly on the
11
13
  * files; `run` fires through the running inspector server, because the
12
14
  * session (chat) and the scheduler live there. `adopt` makes this machine
13
15
  * the runner (runs_on) of every unassigned routine and commits routines.yml.
@@ -19,6 +21,9 @@ export async function initContext() {
19
21
  return { port: project.config.port ?? 1981 };
20
22
  }
21
23
  async function requireAgent(slug) {
24
+ // `_`: the workspace's own routines, no agent to look for.
25
+ if (slug === WORKSPACE_ROUTINES)
26
+ return;
22
27
  if (!(await getAgent(slug))) {
23
28
  console.error(chalk.red(`Agent "${slug}" not found (expected agents/${slug}/agent.yml).`));
24
29
  process.exit(2);
@@ -56,15 +61,15 @@ function routineLine(r) {
56
61
  export function registerRoutineCommands(program) {
57
62
  const routines = program
58
63
  .command("routines")
59
- .description("Per-agent scheduled prompts (agents/<slug>/routines.yml): list, add, run, ...");
64
+ .description("Scheduled prompts — an agent's (agents/<slug>/routines.yml) or the workspace's own (agent `_`): list, add, run, ...");
60
65
  routines
61
66
  .command("list", { isDefault: true })
62
67
  .description("List routines — all agents, or one agent with schedule state")
63
- .argument("[agent]", "Agent slug (folder under agents/)")
68
+ .argument("[agent]", "Agent slug (folder under agents/), or _ for the workspace's own")
64
69
  .option("--json", "Machine-readable output")
65
70
  .action(async (agent, opts) => {
66
71
  await initContext();
67
- const slugs = agent ? [agent] : (await listAgents()).map((m) => m.slug);
72
+ const slugs = agent ? [agent] : [...(await listAgents()).map((m) => m.slug), WORKSPACE_ROUTINES];
68
73
  if (agent)
69
74
  await requireAgent(agent);
70
75
  const all = {};
@@ -77,9 +82,11 @@ export function registerRoutineCommands(program) {
77
82
  if (rs.length === 0)
78
83
  continue;
79
84
  any = true;
80
- console.log(chalk.bold(slug));
81
- for (const r of rs)
82
- console.log(routineLine(r));
85
+ console.log(chalk.bold(slug === WORKSPACE_ROUTINES ? "_ (workspace)" : slug));
86
+ for (const r of rs) {
87
+ const where = slug === WORKSPACE_ROUTINES ? chalk.dim(` → ${r.agent ?? (r.project ? "the project's assistant" : "Ralv")}${r.project ? ` in ${r.project}` : ""}`) : "";
88
+ console.log(routineLine(r) + where);
89
+ }
83
90
  }
84
91
  if (!any) {
85
92
  console.log(chalk.yellow("No routines yet — add one with `kraftwerk routines add <agent> --name ... --schedule ... --prompt ...`."));
@@ -88,7 +95,7 @@ export function registerRoutineCommands(program) {
88
95
  routines
89
96
  .command("add")
90
97
  .description("Create or update a routine (same id = update)")
91
- .argument("<agent>", "Agent slug")
98
+ .argument("<agent>", "Agent slug, or _ for a workspace routine (defined on its own: see --project and --agent)")
92
99
  .requiredOption("--name <name>", 'Display name, e.g. "Morning triage"')
93
100
  .requiredOption("--schedule <cron>", '5-field cron ("0 9 * * 1-5") or @hourly/@daily/@weekly/@monthly')
94
101
  .option("--prompt <text>", "The prompt to post (or pipe it on stdin / use --file)")
@@ -96,9 +103,15 @@ export function registerRoutineCommands(program) {
96
103
  .option("--id <id>", "Routine id (default: derived from the name)")
97
104
  .option("--disabled", "Create it switched off")
98
105
  .option("--runs-on <identity>", "The machine that fires it, handle@machine (default: this one for a new routine, unchanged for an update)")
106
+ .option("--project <slug>", 'The project it runs in ("" for none: globally)')
107
+ .option("--agent <slug>", 'Workspace routines (_) only: who gets the prompt ("" for the project\'s assistant, or Ralv globally)')
99
108
  .action(async (agent, opts) => {
100
109
  await initContext();
101
110
  await requireAgent(agent);
111
+ if (opts.agent !== undefined && agent !== WORKSPACE_ROUTINES) {
112
+ console.error(chalk.red(`--agent is for workspace routines (\`kraftwerk routines add _ ...\`); this one is ${agent}'s own.`));
113
+ process.exit(2);
114
+ }
102
115
  const prompt = opts.prompt ??
103
116
  (opts.file ? await readFile(path.resolve(opts.file), "utf8") : process.stdin.isTTY ? "" : await readStdin());
104
117
  if (!prompt.trim()) {
@@ -114,6 +127,8 @@ export function registerRoutineCommands(program) {
114
127
  prompt,
115
128
  enabled: !opts.disabled,
116
129
  ...(opts.runsOn !== undefined ? { runsOn: opts.runsOn } : {}),
130
+ ...(opts.project !== undefined ? { project: opts.project } : {}),
131
+ ...(opts.agent !== undefined ? { agent: opts.agent } : {}),
117
132
  });
118
133
  const verb = existing.has(routine.id) ? "updated" : "created";
119
134
  console.log(`${chalk.green("✔")} ${verb} ${chalk.cyan(`${agent}/${routine.id}`)} ` +
@@ -193,7 +208,9 @@ export function registerRoutineCommands(program) {
193
208
  .action(async (agent, id, opts) => {
194
209
  const { port } = await initContext();
195
210
  const p = opts.port ? Number(opts.port) : port;
196
- const url = `http://localhost:${p}/api/agents/${encodeURIComponent(agent)}/routines/${encodeURIComponent(id)}/run`;
211
+ const url = agent === WORKSPACE_ROUTINES
212
+ ? `http://localhost:${p}/api/routines/${encodeURIComponent(id)}/run`
213
+ : `http://localhost:${p}/api/agents/${encodeURIComponent(agent)}/routines/${encodeURIComponent(id)}/run`;
197
214
  let body;
198
215
  try {
199
216
  body = (await (await fetch(url, { method: "POST" })).json());
@@ -206,7 +223,7 @@ export function registerRoutineCommands(program) {
206
223
  console.error(chalk.red(body.error ?? "run failed"));
207
224
  process.exit(2);
208
225
  }
209
- console.log(`${chalk.green("✔")} ${chalk.cyan(`${agent}/${id}`)} fired → session ${body.chatId}\n` +
210
- chalk.dim(` http://localhost:${p}/#/agents/${encodeURIComponent(agent)}/chat/${body.chatId}`));
226
+ console.log(`${chalk.green("✔")} ${chalk.cyan(`${agent}/${id}`)} fired → session ${body.chatId}` +
227
+ (agent === WORKSPACE_ROUTINES ? "" : `\n${chalk.dim(` http://localhost:${p}/#/agents/${encodeURIComponent(agent)}/chat/${body.chatId}`)}`));
211
228
  });
212
229
  }
@@ -146,7 +146,11 @@ export declare const ROUTES: {
146
146
  readonly "repos.remove": readonly ["DELETE", "/api/repos/:slug"];
147
147
  readonly "repos.update": readonly ["POST", "/api/repos/:slug/update"];
148
148
  readonly "routines.adopt": readonly ["POST", "/api/routines/adopt"];
149
+ readonly "routines.adoptOne": readonly ["POST", "/api/routines/:id/adopt"];
150
+ readonly "routines.delete": readonly ["DELETE", "/api/routines/:id"];
149
151
  readonly "routines.list": readonly ["GET", "/api/routines"];
152
+ readonly "routines.run": readonly ["POST", "/api/routines/:id/run"];
153
+ readonly "routines.save": readonly ["POST", "/api/routines"];
150
154
  readonly "runs.decide": readonly ["POST", "/api/runs/:id/decision"];
151
155
  readonly "runs.delete": readonly ["DELETE", "/api/runs/:id"];
152
156
  readonly "runs.file": readonly ["GET", "/api/runs/:id/file", "raw"];
@@ -147,7 +147,11 @@ export const ROUTES = {
147
147
  "repos.remove": ["DELETE", "/api/repos/:slug"],
148
148
  "repos.update": ["POST", "/api/repos/:slug/update"],
149
149
  "routines.adopt": ["POST", "/api/routines/adopt"],
150
+ "routines.adoptOne": ["POST", "/api/routines/:id/adopt"],
151
+ "routines.delete": ["DELETE", "/api/routines/:id"],
150
152
  "routines.list": ["GET", "/api/routines"],
153
+ "routines.run": ["POST", "/api/routines/:id/run"],
154
+ "routines.save": ["POST", "/api/routines"],
151
155
  "runs.decide": ["POST", "/api/runs/:id/decision"],
152
156
  "runs.delete": ["DELETE", "/api/runs/:id"],
153
157
  "runs.file": ["GET", "/api/runs/:id/file", "raw"],
@@ -1,13 +1,14 @@
1
1
  import { listAgents } from "./agents.js";
2
2
  import { agentActivity, listChats } from "./chat/sessions.js";
3
- import { routineStatuses } from "./routines.js";
3
+ import { routineStatuses, WORKSPACE_ROUTINES } from "./routines.js";
4
4
  export async function agentStatuses() {
5
- const [agents, chats] = await Promise.all([listAgents(), listChats()]);
5
+ const [agents, chats, shared] = await Promise.all([listAgents(), listChats(), routineStatuses(WORKSPACE_ROUTINES).catch(() => [])]);
6
6
  const live = agentActivity();
7
7
  const out = {};
8
8
  await Promise.all(agents.map(async (a) => {
9
9
  const act = live.get(a.slug);
10
- const routines = await routineStatuses(a.slug).catch(() => []);
10
+ // Its own routines, and the workspace's that name it.
11
+ const routines = [...(await routineStatuses(a.slug).catch(() => [])), ...shared.filter((r) => r.agent === a.slug)];
11
12
  const next = routines
12
13
  .filter((r) => r.nextRunAt)
13
14
  .sort((x, y) => x.nextRunAt.localeCompare(y.nextRunAt))[0];
@@ -3,7 +3,7 @@ import { getBoard, listAllBoards } from "./boards.js";
3
3
  import { waitingRequests } from "./chat/sessions.js";
4
4
  import { chatHref, listNotifications } from "./notifications.js";
5
5
  import { listProjects } from "./projects.js";
6
- import { runnerFindings } from "./routines.js";
6
+ import { runnerFindings, WORKSPACE_ROUTINES } from "./routines.js";
7
7
  export async function listAttention() {
8
8
  const [agents, projects, notes, runners, boards] = await Promise.all([
9
9
  listAgents().catch(() => []),
@@ -54,7 +54,8 @@ export async function listAttention() {
54
54
  .filter((n) => !n.readAt && (n.kind === "routine_failed" || n.kind === "run_failed"))
55
55
  .map((n) => {
56
56
  const owner = {};
57
- if (n.diagnose?.kind === "routine")
57
+ // A workspace routine may name no agent (a project's assistant or Ralv ran it).
58
+ if (n.diagnose?.kind === "routine" && n.diagnose.agent)
58
59
  owner.agent = agentOf(n.diagnose.agent);
59
60
  if (n.diagnose?.kind === "run")
60
61
  owner.workflow = n.title.replace(/ run .*$/, "");
@@ -75,8 +76,11 @@ export async function listAttention() {
75
76
  // to a chat). Routines of one agent: that profile and its rail entry; of several: the first agent's
76
77
  // profile, whose banner adopts across the whole workspace.
77
78
  const placed = (these) => {
78
- const slugs = [...new Set(these.map((r) => r.agent))];
79
- return slugs.length === 1
79
+ const slugs = [...new Set(these.map((r) => r.agent))].filter((s) => s !== WORKSPACE_ROUTINES);
80
+ // Only the workspace's own routines (agents/routines.yml): they are on Artifacts.
81
+ if (slugs.length === 0)
82
+ return { href: "/artifacts?kind=routines", owner: {} };
83
+ return slugs.length === 1 && these.every((r) => r.agent === slugs[0])
80
84
  ? { href: `/agents/${slugs[0]}/info`, owner: { agent: agentOf(slugs[0]) } }
81
85
  : { href: `/agents/${slugs[0]}/info`, owner: {} };
82
86
  };
@@ -241,6 +241,14 @@ export async function vibeableContext(slug, cwd) {
241
241
  `inspector's Git screen; keep secrets out of the folder (.env is git-ignored, node_modules too); leave ${VIBEABLE_CONFIG_FILE} valid YAML; ` +
242
242
  `when you switch the app to dev mode, say so and ask the user to press play in the pane. Reply briefly — the preview shows the result.`);
243
243
  }
244
+ /** What an unattended session (a routine's run, a task the board handed over) is told about working alone. */
245
+ const unattendedNote = (startedBy) => `\n\nThis session was started automatically by ${startedBy} — ` +
246
+ `nobody may be watching live. Complete the task autonomously. Edits inside the project ` +
247
+ `need no approval; anything your harness asks about (shell commands, network, files ` +
248
+ `outside the project) is shown to a human who may look later — say in one line why you ` +
249
+ `need it, then continue with what you can. A request nobody answers within ` +
250
+ `${unattendedTimeoutLabel()} is declined: report what you could not do and why, do ` +
251
+ `not retry it another way. End with a clear, self-contained summary of what you did and found.`;
244
252
  /** Base context per scope; scopeContext() appends the shared skills block. */
245
253
  async function baseScopeContext(scope, agent) {
246
254
  if (scope.kind === "agent") {
@@ -278,20 +286,12 @@ async function baseScopeContext(scope, agent) {
278
286
  `The working directory is the project root. Stay within your role; if a request is clearly outside it, ` +
279
287
  `say so and suggest which agent or tool fits better.` +
280
288
  (scope.task ? `\n\n${await taskContext(scope.task)}` : "") +
281
- (scope.routine || scope.task
282
- ? `\n\nThis session was started automatically by ${scope.routine ? `your scheduled routine "${scope.routine}"` : `the board: task ${scope.task} was given to you`} — ` +
283
- `nobody may be watching live. Complete the task autonomously. Edits inside the project ` +
284
- `need no approval; anything your harness asks about (shell commands, network, files ` +
285
- `outside the project) is shown to a human who may look later — say in one line why you ` +
286
- `need it, then continue with what you can. A request nobody answers within ` +
287
- `${unattendedTimeoutLabel()} is declined: report what you could not do and why, do ` +
288
- `not retry it another way. End with a clear, self-contained summary of what you did and found.`
289
- : ""));
289
+ (scope.routine || scope.task ? unattendedNote(scope.routine ? `your scheduled routine "${scope.routine}"` : `the board: task ${scope.task} was given to you`) : ""));
290
290
  }
291
291
  if (scope.kind === "project") {
292
292
  // Everything the project gathered — brief, state, records, links — plus
293
293
  // how to keep it current; see projects.ts for the block.
294
- return projectContext(scope.slug, `kraftwerk-chat/${agent}`);
294
+ return (await projectContext(scope.slug, `kraftwerk-chat/${agent}`)) + (scope.routine ? unattendedNote(`the scheduled routine "${scope.routine}" of this project`) : "");
295
295
  }
296
296
  if (scope.kind === "knowledge") {
297
297
  const { root, bundles } = await knowledgeIndex().catch(() => ({ root: "", bundles: [] }));
@@ -360,7 +360,8 @@ async function baseScopeContext(scope, agent) {
360
360
  `These are persistent agents (defined under agents/); the user talks to them on the ` +
361
361
  `Agents screen. Point the user there when a request clearly belongs to one of them.\n\n` +
362
362
  (await agentFilesContext({})) +
363
- `Answer questions about workflows and runs by reading the files above. Do not modify run outputs unless asked.`);
363
+ `Answer questions about workflows and runs by reading the files above. Do not modify run outputs unless asked.` +
364
+ (scope.routine ? unattendedNote(`the workspace's scheduled routine "${scope.routine}"`) : ""));
364
365
  }
365
366
  if (scope.kind === "run") {
366
367
  const run = await getRun(scope.runId);
@@ -178,7 +178,7 @@ export async function postMessage(id, text, opts = {}) {
178
178
  body: failed ? lastEventText(state, turnStart, "error") : lastEventText(state, turnStart, "text"),
179
179
  href: chatHref(state.meta),
180
180
  ...(failed ? { diagnose: routineRef(state.meta) } : {}),
181
- });
181
+ }).catch(() => { });
182
182
  }
183
183
  }
184
184
  catch (err) {
@@ -190,7 +190,7 @@ export async function postMessage(id, text, opts = {}) {
190
190
  body: err.message,
191
191
  href: chatHref(state.meta),
192
192
  diagnose: routineRef(state.meta),
193
- });
193
+ }).catch(() => { });
194
194
  }
195
195
  // A failed turn may mean a dead subprocess; drop it so the next
196
196
  // message spawns a fresh agent (thread history stays on disk).
@@ -58,7 +58,7 @@ export declare const isBusy: (state: ChatState) => boolean;
58
58
  export declare const seatAuthor: (seat: Seat) => Author | undefined;
59
59
  /** Routine-fired sessions: nobody is expected to be watching live. */
60
60
  export declare const isUnattended: (scope: ChatScope) => boolean;
61
- /** Diagnose handle for a failed routine session (only called for unattended agent scopes). */
61
+ /** Diagnose handle for a failed routine session (only called for unattended scopes); `agent` is "" when a project's assistant or Ralv ran it. */
62
62
  export declare function routineRef(meta: ChatMeta): DiagnoseRef | undefined;
63
63
  /** How the bell names a chat: its title ("⏰ Morning digest"), else the agent, else "chat". */
64
64
  export declare function chatLabel(meta: ChatMeta): string;
@@ -29,13 +29,13 @@ export const isBusy = (state) => [...state.seats.values()].some((s) => s.busy);
29
29
  /** The event author for a seat: channel members sign their events, the lone agent of a chat does not. */
30
30
  export const seatAuthor = (seat) => (seat.key === MAIN ? undefined : { kind: "agent", slug: seat.key });
31
31
  /** Routine-fired sessions: nobody is expected to be watching live. */
32
- export const isUnattended = (scope) => scope.kind === "agent" && (!!scope.routine || !!scope.task);
33
- /** Diagnose handle for a failed routine session (only called for unattended agent scopes). */
32
+ export const isUnattended = (scope) => scope.kind === "agent" ? !!scope.routine || !!scope.task : (scope.kind === "project" || scope.kind === "kraftwerk") && !!scope.routine;
33
+ /** Diagnose handle for a failed routine session (only called for unattended scopes); `agent` is "" when a project's assistant or Ralv ran it. */
34
34
  export function routineRef(meta) {
35
35
  const scope = meta.scope;
36
- if (scope.kind !== "agent" || !scope.routine)
36
+ if ((scope.kind !== "agent" && scope.kind !== "project" && scope.kind !== "kraftwerk") || !scope.routine)
37
37
  return undefined;
38
- return { kind: "routine", agent: scope.slug, routine: scope.routine, chatId: meta.id };
38
+ return { kind: "routine", agent: scope.kind === "agent" ? scope.slug : "", routine: scope.routine, chatId: meta.id };
39
39
  }
40
40
  /** How the bell names a chat: its title ("⏰ Morning digest"), else the agent, else "chat". */
41
41
  export function chatLabel(meta) {
@@ -8,8 +8,11 @@
8
8
  export type ChatAgentId = "claude" | "codex" | "pi";
9
9
  export type ChatScope = {
10
10
  kind: "general";
11
- } | {
11
+ }
12
+ /** Ralv. `routine`: a scheduled run of a workspace routine with no project and no agent — unattended. */
13
+ | {
12
14
  kind: "kraftwerk";
15
+ routine?: string;
13
16
  } | {
14
17
  kind: "run";
15
18
  runId: string;
@@ -24,10 +27,11 @@ export type ChatScope = {
24
27
  routine?: string;
25
28
  task?: string;
26
29
  }
27
- /** A project: the chat carries its brief, state, systems of record and links; see projects.ts. */
30
+ /** A project: the chat carries its brief, state, systems of record and links; see projects.ts. `routine`: a scheduled run for the project's assistant — unattended. */
28
31
  | {
29
32
  kind: "project";
30
33
  slug: string;
34
+ routine?: string;
31
35
  }
32
36
  /** A channel: several agents (and humans) share one transcript; see channels.ts. */
33
37
  | {
@@ -2,7 +2,7 @@ import path from "node:path";
2
2
  import { getOutputDir } from "./context.js";
3
3
  import { getAgent } from "./agents.js";
4
4
  import { getRun } from "./runs.js";
5
- import { listRoutines } from "./routines.js";
5
+ import { listRoutines, WORKSPACE_ROUTINES } from "./routines.js";
6
6
  import { createChat, getChat, postMessage } from "./chat/sessions.js";
7
7
  import { chatHref, getNotification, markNotificationsRead } from "./notifications.js";
8
8
  const FIX_INSTRUCTIONS = `Work in this order:\n` +
@@ -25,11 +25,19 @@ function runPrompt(run) {
25
25
  `\nRe-run with: KRAFTWERK_YES=1 npx kraftwerk run ${run.workflow ?? "<workflow>"} "${(run.request ?? "").replace(/"/g, '\\"')}"`);
26
26
  }
27
27
  async function routinePrompt(ref, agentExists) {
28
- const routine = (await listRoutines(ref.agent).catch(() => []))
29
- .find((r) => r.id === ref.routine);
28
+ // The agent's own routine, else one of the workspace's (agents/routines.yml) — those may name no agent at all.
29
+ const own = ref.agent ? (await listRoutines(ref.agent).catch(() => [])).find((r) => r.id === ref.routine) : undefined;
30
+ const shared = own ? undefined : (await listRoutines(WORKSPACE_ROUTINES).catch(() => [])).find((r) => r.id === ref.routine);
31
+ const routine = own ?? shared;
32
+ const whose = shared
33
+ ? `the workspace (agents/routines.yml${shared.project ? `, project "${shared.project}"` : ""}${ref.agent ? `, agent "${ref.agent}"` : ""})`
34
+ : `agent "${ref.agent}"`;
30
35
  const head = routine
31
- ? `The routine "${routine.name}" (schedule ${routine.schedule}) of agent "${ref.agent}" failed.\nIts prompt was:\n"""\n${routine.prompt}\n"""\n`
32
- : `A routine (${ref.routine}) of agent "${ref.agent}" failed.\n`;
36
+ ? `The routine "${routine.name}" (schedule ${routine.schedule}) of ${whose} failed.\nIts prompt was:\n"""\n${routine.prompt}\n"""\n`
37
+ : `A routine (${ref.routine}) of ${whose} failed.\n`;
38
+ if (shared && !ref.chatId) {
39
+ return `${head}\nThe session could not even start. Check the routine in agents/routines.yml: the project and agent it names must exist, and the harness must be installed and authenticated.\n\nPlease diagnose this failure.\n\n${FIX_INSTRUCTIONS}\nRe-run from Artifacts ("run" on the routine) or wait for the next scheduled time.`;
40
+ }
33
41
  let evidence;
34
42
  if (ref.chatId) {
35
43
  const chat = await getChat(ref.chatId).catch(() => null);
@@ -1,8 +1,16 @@
1
1
  /**
2
- * Routines: per-agent scheduled prompts — "message your agent every
3
- * weekday at 9". Definitions live next to the agent (git-tracked):
2
+ * Routines: scheduled prompts — "message your agent every weekday at 9".
3
+ * Definitions are git-tracked, in one of two places:
4
4
  *
5
- * agents/<slug>/routines.yml # list of { id, name, schedule, prompt, enabled }
5
+ * agents/<slug>/routines.yml # an agent's own: list of { id, name, schedule, prompt, enabled }
6
+ * agents/routines.yml # the workspace's: the same, each with optional `project` and `agent`
7
+ *
8
+ * A workspace routine is defined on its own, not on an agent: `project`
9
+ * names the project it runs in (absent: globally) and `agent` who gets the
10
+ * prompt (absent: the project's assistant, or Ralv when it runs globally).
11
+ * The functions here take an `owner`: an agent's slug, or WORKSPACE_ROUTINES
12
+ * for the workspace's file (which sits in the agents root because that
13
+ * folder is always among the synced paths).
6
14
  *
7
15
  * Runtime state (last run / last session / errors) is run-state, not
8
16
  * config, so it lives in <output>/routines-state.json. The scheduler is a
@@ -36,7 +44,13 @@ export interface Routine {
36
44
  runsOn?: string;
37
45
  /** Its runs' chats stay off remote callers' listings, and out of the cloud's report. */
38
46
  private?: boolean;
47
+ /** The project its runs are filed under and briefed with. Absent: it runs globally. */
48
+ project?: string;
49
+ /** A workspace routine's agent (slug). Absent: the project's assistant, or Ralv globally. An agent's own routine never carries it. */
50
+ agent?: string;
39
51
  }
52
+ /** The owner of the workspace's routines (agents/routines.yml): never a valid agent slug. */
53
+ export declare const WORKSPACE_ROUTINES = "_";
40
54
  /**
41
55
  * Who fires a routine, seen from this machine: here, on another identity,
42
56
  * or nobody (no runs_on).
@@ -66,7 +80,7 @@ interface CronSpec {
66
80
  export declare function parseCron(expr: string): CronSpec;
67
81
  /** Next matching instant after `from`, scanning up to 60 days; undefined if none. */
68
82
  export declare function nextRun(schedule: string, from?: Date): string | undefined;
69
- export declare function listRoutines(slug: string): Promise<Routine[]>;
83
+ export declare function listRoutines(owner: string): Promise<Routine[]>;
70
84
  export interface SaveRoutineInput {
71
85
  id?: string;
72
86
  name: string;
@@ -76,6 +90,10 @@ export interface SaveRoutineInput {
76
90
  /** Absent: kept as it is (a new routine gets this machine's identity). null or "": unassigned. */
77
91
  runsOn?: string | null;
78
92
  private?: boolean;
93
+ /** Absent: kept as it is. null or "": no project — it runs globally. */
94
+ project?: string | null;
95
+ /** Workspace routines only. Absent: kept as it is. null or "": the project's assistant, or Ralv globally. */
96
+ agent?: string | null;
79
97
  }
80
98
  export declare function saveRoutine(slug: string, input: SaveRoutineInput): Promise<Routine>;
81
99
  export declare function deleteRoutine(slug: string, id: string): Promise<void>;
@@ -88,21 +106,28 @@ export declare function mentionsWorkflow(prompt: string, w: {
88
106
  slug: string;
89
107
  name?: string;
90
108
  }): boolean;
91
- /** Every agent's routines with their run state, each with the workflows its prompt names (GET /api/routines). */
92
- export declare function allRoutines(workflows: {
93
- slug: string;
94
- name?: string;
95
- }[]): Promise<(RoutineStatus & {
96
- agent: {
109
+ /** A routine in the workspace-wide listing: where it is defined, who gets its prompt, the workflows it names. */
110
+ export type ListedRoutine = Omit<RoutineStatus, "agent"> & {
111
+ /** Where it is defined: an agent's slug, or WORKSPACE_ROUTINES. */
112
+ owner: string;
113
+ /** Who gets the prompt. Absent (workspace routines only): the project's assistant, or Ralv globally — or the agent named is gone. */
114
+ agent?: {
97
115
  slug: string;
98
116
  name: string;
99
117
  emoji: string;
100
118
  };
101
119
  workflows: string[];
102
- })[]>;
120
+ };
121
+ /** Every routine — the agents' and the workspace's — with its run state and the workflows its prompt names (GET /api/routines). */
122
+ export declare function allRoutines(workflows: {
123
+ slug: string;
124
+ name?: string;
125
+ }[]): Promise<ListedRoutine[]>;
103
126
  /** Whether a routine fires on the machine whose identity is `me`: enabled and runs_on exactly that. */
104
127
  export declare const firesHere: (r: Routine, me: string) => boolean;
105
128
  export declare function routineStatuses(slug: string): Promise<RoutineStatus[]>;
129
+ /** Where a routine is looked at and fixed: its agent's profile, or Artifacts for the workspace's. */
130
+ export declare const routineHref: (owner: string, id: string) => string;
106
131
  export declare function runRoutineNow(slug: string, id: string): Promise<{
107
132
  chatId: string;
108
133
  }>;
@@ -131,6 +156,7 @@ export declare function dueRoutines(now: Date, me?: string): Promise<{
131
156
  routine: Routine;
132
157
  }[]>;
133
158
  export interface RunnerRef {
159
+ /** Where it is defined: the agent's slug, or WORKSPACE_ROUTINES. */
134
160
  agent: string;
135
161
  id: string;
136
162
  name: string;