@netnodeag/kraftwerk 0.85.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 (84) hide show
  1. package/README.md +35 -8
  2. package/dist/acp.d.ts +35 -5
  3. package/dist/acp.js +47 -5
  4. package/dist/cli/kraftwerk.js +1 -1
  5. package/dist/cli/routines.d.ts +4 -2
  6. package/dist/cli/routines.js +30 -13
  7. package/dist/client/routes.d.ts +4 -0
  8. package/dist/client/routes.js +4 -0
  9. package/dist/core/agent-status.js +4 -3
  10. package/dist/core/attention.js +8 -4
  11. package/dist/core/chat/acp.d.ts +1 -1
  12. package/dist/core/chat/acp.js +2 -2
  13. package/dist/core/chat/context.js +12 -11
  14. package/dist/core/chat/sessions.js +2 -2
  15. package/dist/core/chat/state.d.ts +1 -1
  16. package/dist/core/chat/state.js +4 -4
  17. package/dist/core/chat/types.d.ts +6 -2
  18. package/dist/core/diagnose.js +13 -5
  19. package/dist/core/routines.d.ts +37 -11
  20. package/dist/core/routines.js +79 -27
  21. package/dist/core/skills.d.ts +2 -0
  22. package/dist/core/skills.js +2 -0
  23. package/dist/harnesses/acp.js +1 -1
  24. package/dist/server/api/agents.d.ts +1 -0
  25. package/dist/server/api/agents.js +9 -7
  26. package/dist/server/api/index.d.ts +20 -10
  27. package/dist/server/api/runs.d.ts +19 -10
  28. package/dist/server/api/runs.js +45 -2
  29. package/package.json +11 -11
  30. package/web/dist/assets/{clike-D_6L3tnO.js → clike-xvONpD0Z.js} +1 -1
  31. package/web/dist/assets/crystal-Bl6YKCG_.js +1 -0
  32. package/web/dist/assets/{dist-BMSAjH50.js → dist-5ezEzkN_.js} +1 -1
  33. package/web/dist/assets/{dist-BiYU4xIM.js → dist-B2YS2uAJ.js} +1 -1
  34. package/web/dist/assets/dist-B69hm6Vm.js +1 -0
  35. package/web/dist/assets/{dist-DHOMfMVu.js → dist-BP5gr3hs.js} +1 -1
  36. package/web/dist/assets/{dist-CO3dIZWI.js → dist-BTUFCkqp.js} +1 -1
  37. package/web/dist/assets/dist-BUzdcj0Z.js +13 -0
  38. package/web/dist/assets/{dist-p_qW90fR.js → dist-B_hSf4j-.js} +1 -1
  39. package/web/dist/assets/dist-BxtR6jpW.js +1 -0
  40. package/web/dist/assets/{dist-Dctj7Mr3.js → dist-C19mVzsE.js} +1 -1
  41. package/web/dist/assets/{dist-D7O3CloR.js → dist-C7_MMENm.js} +1 -1
  42. package/web/dist/assets/dist-CaaMxJ6G.js +23 -0
  43. package/web/dist/assets/dist-CdsW8_p8.js +1 -0
  44. package/web/dist/assets/dist-CmPMrdu5.js +1 -0
  45. package/web/dist/assets/{dist-KG4lrraG.js → dist-D5WlVRbV.js} +1 -1
  46. package/web/dist/assets/dist-DCuMQcQZ.js +1 -0
  47. package/web/dist/assets/{dist-itDgDZqI.js → dist-DGtJ3oS3.js} +1 -1
  48. package/web/dist/assets/dist-DI3h2IBG.js +1 -0
  49. package/web/dist/assets/{dist-B4DAVDkf.js → dist-DLUdIP27.js} +1 -1
  50. package/web/dist/assets/{dist-BA7UaMHM.js → dist-DjEPDfqF.js} +1 -1
  51. package/web/dist/assets/dist-DnBQdICn.js +1 -0
  52. package/web/dist/assets/{dist-f7v359XP.js → dist-DqznohzT.js} +1 -1
  53. package/web/dist/assets/{dist-Cj7AWBEE.js → dist-DxeKUyaX.js} +1 -1
  54. package/web/dist/assets/{dist-Ko3fuaif.js → dist-b2EG4KtU.js} +1 -1
  55. package/web/dist/assets/{dylan-BCDoL_-p.js → dylan-S7ucR4pR.js} +1 -1
  56. package/web/dist/assets/editor-DMiLLeME.js +121 -0
  57. package/web/dist/assets/groovy-CUrWKPia.js +1 -0
  58. package/web/dist/assets/index-CvxByvfI.css +2 -0
  59. package/web/dist/assets/index-lXKLZep2.js +485 -0
  60. package/web/dist/assets/javascript-lS2r2ifg.js +1 -0
  61. package/web/dist/assets/material-symbols-rounded-CIiHEKEa.woff2 +0 -0
  62. package/web/dist/assets/{nginx-8H7HVH4w.js → nginx-C-ORUuei.js} +1 -1
  63. package/web/dist/assets/{ntriples-B9h1VB_g.js → ntriples-CzMBulkp.js} +1 -1
  64. package/web/dist/assets/{powershell-BcIto6Sf.js → powershell-D8WpQPaX.js} +1 -1
  65. package/web/dist/assets/pug-BqCHZ5xT.js +1 -0
  66. package/web/dist/assets/{tiki-AK6FwT8q.js → tiki-CvUEFusT.js} +1 -1
  67. package/web/dist/index.html +2 -2
  68. package/web/dist/assets/crystal-Bsdphhtm.js +0 -1
  69. package/web/dist/assets/dist-BSkxIHR-.js +0 -23
  70. package/web/dist/assets/dist-BdZ5cNRp.js +0 -1
  71. package/web/dist/assets/dist-CAV2ttep.js +0 -1
  72. package/web/dist/assets/dist-CYzOYk_e.js +0 -13
  73. package/web/dist/assets/dist-Cfd7m1dl.js +0 -1
  74. package/web/dist/assets/dist-CiL3QW3G.js +0 -1
  75. package/web/dist/assets/dist-CzkTIkYD.js +0 -1
  76. package/web/dist/assets/dist-uPpneiLk.js +0 -1
  77. package/web/dist/assets/dist-xi1nJU9x.js +0 -1
  78. package/web/dist/assets/editor-ByKGQXvE.js +0 -120
  79. package/web/dist/assets/groovy-CUpZ7dEl.js +0 -1
  80. package/web/dist/assets/index-DcTsLgad.css +0 -2
  81. package/web/dist/assets/index-WvdkqCmZ.js +0 -473
  82. package/web/dist/assets/javascript-Bu8mWwtz.js +0 -1
  83. package/web/dist/assets/material-symbols-rounded-Dni8jOUD.woff2 +0 -0
  84. package/web/dist/assets/pug-3K-JMW4g.js +0 -1
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
 
package/dist/acp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ChildProcessWithoutNullStreams } from "node:child_process";
2
- import { ClientSideConnection, type Client, type McpServer, type SessionConfigOption, type SessionModeState } from "@agentclientprotocol/sdk";
2
+ import { type CancelNotification, type ClientContext, type CloseSessionRequest, type DeleteSessionRequest, type ForkSessionRequest, type InitializeRequest, type ListSessionsRequest, type NewSessionRequest, type PromptRequest, type ResumeSessionRequest, type SetSessionConfigOptionRequest, type SetSessionModeRequest, type CreateElicitationRequest, type CreateElicitationResponse, type McpServer, type RequestPermissionRequest, type RequestPermissionResponse, type SessionConfigOption, type SessionModeState, type SessionNotification } from "@agentclientprotocol/sdk/unstable";
3
3
  import type { McpServerConfig } from "./harness.js";
4
4
  /**
5
5
  * Agent Client Protocol plumbing shared by the inspector's chats and the
@@ -115,9 +115,38 @@ export declare function parseExtensionLine(line: string): AcpExtensionNotificati
115
115
  * byte-for-byte for the SDK. Lines may arrive split across chunks.
116
116
  */
117
117
  export declare function divertExtensionUpdates(source: ReadableStream<Uint8Array>, onExtension: (n: AcpExtensionNotification) => void): ReadableStream<Uint8Array>;
118
+ /**
119
+ * What kraftwerk answers when the agent calls: plain callbacks, wired to
120
+ * the SDK's client app by connectAcp. `extNotification` gets every
121
+ * notification the SDK has no handler for (the `_`-prefixed extensions),
122
+ * with its full wire name.
123
+ */
124
+ export interface AcpClient {
125
+ sessionUpdate(params: SessionNotification): void | Promise<void>;
126
+ requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse>;
127
+ createElicitation?(params: CreateElicitationRequest): Promise<CreateElicitationResponse>;
128
+ extNotification?(method: string, params: Record<string, unknown>): void | Promise<void>;
129
+ }
130
+ /** The calls kraftwerk makes to the agent, by name, over one connection. */
131
+ declare function agentCalls(ctx: ClientContext): {
132
+ initialize: (p: InitializeRequest) => Promise<import("@agentclientprotocol/sdk/unstable").InitializeResponse>;
133
+ newSession: (p: NewSessionRequest) => Promise<import("@agentclientprotocol/sdk/unstable").NewSessionResponse>;
134
+ resumeSession: (p: ResumeSessionRequest) => Promise<import("@agentclientprotocol/sdk/unstable").ResumeSessionResponse>;
135
+ listSessions: (p: ListSessionsRequest) => Promise<import("@agentclientprotocol/sdk/unstable").ListSessionsResponse>;
136
+ deleteSession: (p: DeleteSessionRequest) => Promise<import("@agentclientprotocol/sdk/unstable").DeleteSessionResponse>;
137
+ forkSession: (p: ForkSessionRequest) => Promise<import("@agentclientprotocol/sdk/unstable").ForkSessionResponse>;
138
+ prompt: (p: PromptRequest) => Promise<import("@agentclientprotocol/sdk/unstable").PromptResponse>;
139
+ setSessionMode: (p: SetSessionModeRequest) => Promise<import("@agentclientprotocol/sdk/unstable").SetSessionModeResponse>;
140
+ setSessionConfigOption: (p: SetSessionConfigOptionRequest) => Promise<import("@agentclientprotocol/sdk/unstable").SetSessionConfigOptionResponse>;
141
+ closeSession: (p: CloseSessionRequest) => Promise<import("@agentclientprotocol/sdk/unstable").CloseSessionResponse>;
142
+ cancel: (p: CancelNotification) => Promise<void>;
143
+ /** An extension request (`_`-prefixed wire name). */
144
+ extMethod: (method: string, params: Record<string, unknown>) => Promise<Record<string, unknown>>;
145
+ };
146
+ export type AcpConnection = ReturnType<typeof agentCalls>;
118
147
  export interface AcpProcess {
119
148
  child: ChildProcessWithoutNullStreams;
120
- conn: ClientSideConnection;
149
+ conn: AcpConnection;
121
150
  }
122
151
  /**
123
152
  * Spawn the adapter for `agent` in `cwd`, wire the ACP connection to
@@ -132,7 +161,7 @@ export interface AcpProcess {
132
161
  export declare function connectAcp(agent: AcpAgent, opts: {
133
162
  cwd: string;
134
163
  env: NodeJS.ProcessEnv;
135
- client: Client;
164
+ client: AcpClient;
136
165
  clientName: string;
137
166
  onExtension?: (n: AcpExtensionNotification) => void;
138
167
  /** The client answers form elicitations (`createElicitation` on the Client): agents may ask questions. */
@@ -145,9 +174,9 @@ export declare function connectAcp(agent: AcpAgent, opts: {
145
174
  * listing or deleting the agent's own sessions. The adapter is gone when
146
175
  * `fn` settles.
147
176
  */
148
- export declare function withAdapter<T>(agent: AcpAgent, cwd: string, fn: (conn: ClientSideConnection) => Promise<T>): Promise<T>;
177
+ export declare function withAdapter<T>(agent: AcpAgent, cwd: string, fn: (conn: AcpConnection) => Promise<T>): Promise<T>;
149
178
  /** The subset of the connection a session open needs (a test can stand in for it). */
150
- export type SessionOpener = Pick<ClientSideConnection, "newSession" | "resumeSession">;
179
+ export type SessionOpener = Pick<AcpConnection, "newSession" | "resumeSession">;
151
180
  export interface OpenedSession {
152
181
  sessionId: string;
153
182
  modes?: SessionModeState | null;
@@ -171,3 +200,4 @@ export declare function openSession(conn: SessionOpener, req: {
171
200
  mcpServers: McpServer[];
172
201
  _meta?: Record<string, unknown>;
173
202
  }, resume?: string): Promise<OpenedSession>;
203
+ export {};
package/dist/acp.js CHANGED
@@ -1,12 +1,26 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
2
4
  import { Readable, Writable } from "node:stream";
3
5
  import { fileURLToPath } from "node:url";
4
- import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION, } from "@agentclientprotocol/sdk";
6
+ import { client as clientApp, methods, ndJsonStream, PROTOCOL_VERSION, } from "@agentclientprotocol/sdk/unstable";
5
7
  import { workspaceEnv } from "./core/env.js";
6
8
  const ADAPTERS = {
7
- claude: "@agentclientprotocol/claude-agent-acp/dist/index.js",
8
- codex: "@agentclientprotocol/codex-acp/dist/index.js",
9
+ claude: "@agentclientprotocol/claude-agent-acp",
10
+ codex: "@agentclientprotocol/codex-acp",
9
11
  };
12
+ /**
13
+ * The adapter's executable: its package's `bin` (the packages' `exports`
14
+ * may hide dist/, and claude-agent-acp's main is a library, not the CLI).
15
+ */
16
+ function adapterEntry(agent) {
17
+ const pkgPath = fileURLToPath(import.meta.resolve(`${ADAPTERS[agent]}/package.json`));
18
+ const bin = JSON.parse(readFileSync(pkgPath, "utf8")).bin;
19
+ const rel = typeof bin === "string" ? bin : Object.values(bin ?? {})[0];
20
+ if (!rel)
21
+ throw new Error(`${ADAPTERS[agent]} names no executable`);
22
+ return path.join(path.dirname(pkgPath), rel);
23
+ }
10
24
  /** Effort tier -> Claude thinking budget (the adapter reads MAX_THINKING_TOKENS). */
11
25
  const CLAUDE_THINKING_BUDGET = {
12
26
  low: 2048,
@@ -148,6 +162,25 @@ export function divertExtensionUpdates(source, onExtension) {
148
162
  },
149
163
  }));
150
164
  }
165
+ /** The calls kraftwerk makes to the agent, by name, over one connection. */
166
+ function agentCalls(ctx) {
167
+ const a = methods.agent;
168
+ return {
169
+ initialize: (p) => ctx.request(a.initialize, p),
170
+ newSession: (p) => ctx.request(a.session.new, p),
171
+ resumeSession: (p) => ctx.request(a.session.resume, p),
172
+ listSessions: (p) => ctx.request(a.session.list, p),
173
+ deleteSession: (p) => ctx.request(a.session.delete, p),
174
+ forkSession: (p) => ctx.request(a.session.fork, p),
175
+ prompt: (p) => ctx.request(a.session.prompt, p),
176
+ setSessionMode: (p) => ctx.request(a.session.setMode, p),
177
+ setSessionConfigOption: (p) => ctx.request(a.session.setConfigOption, p),
178
+ closeSession: (p) => ctx.request(a.session.close, p),
179
+ cancel: (p) => ctx.notify(a.session.cancel, p),
180
+ /** An extension request (`_`-prefixed wire name). */
181
+ extMethod: (method, params) => ctx.request(method, params),
182
+ };
183
+ }
151
184
  /**
152
185
  * Spawn the adapter for `agent` in `cwd`, wire the ACP connection to
153
186
  * `client`, and run the initialize handshake. Process failures reach the
@@ -160,7 +193,7 @@ export function divertExtensionUpdates(source, onExtension) {
160
193
  */
161
194
  export async function connectAcp(agent, opts) {
162
195
  // KRAFTWERK_ACP_ADAPTER: a script standing in for the adapter (the tests' scripted fake agent).
163
- const entry = process.env.KRAFTWERK_ACP_ADAPTER || fileURLToPath(import.meta.resolve(ADAPTERS[agent]));
196
+ const entry = process.env.KRAFTWERK_ACP_ADAPTER || adapterEntry(agent);
164
197
  const child = spawn(process.execPath, [entry], {
165
198
  cwd: opts.cwd,
166
199
  stdio: ["pipe", "pipe", "pipe"],
@@ -178,7 +211,16 @@ export async function connectAcp(agent, opts) {
178
211
  if (opts.onExtension)
179
212
  output = divertExtensionUpdates(output, opts.onExtension);
180
213
  const stream = ndJsonStream(Writable.toWeb(child.stdin), output);
181
- const conn = new ClientSideConnection(() => opts.client, stream);
214
+ const c = opts.client;
215
+ let app = clientApp({ name: opts.clientName })
216
+ .onNotification(methods.client.session.update, ({ params }) => c.sessionUpdate(params))
217
+ .onRequest(methods.client.session.requestPermission, ({ params }) => c.requestPermission(params))
218
+ .onNotification("*", ({ method, params }) => c.extNotification?.(method, (params ?? {})));
219
+ if (c.createElicitation) {
220
+ const elicit = c.createElicitation.bind(c);
221
+ app = app.onRequest(methods.client.elicitation.create, ({ params }) => elicit(params));
222
+ }
223
+ const conn = agentCalls(app.connect(stream).agent);
182
224
  await conn.initialize({
183
225
  protocolVersion: PROTOCOL_VERSION,
184
226
  clientCapabilities: {
@@ -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
  };
@@ -1,4 +1,4 @@
1
- import { type ContentBlock, type SessionConfigOption, type SessionNotification } from "@agentclientprotocol/sdk";
1
+ import { type ContentBlock, type SessionConfigOption, type SessionNotification } from "@agentclientprotocol/sdk/unstable";
2
2
  import { type AcpAgent, type AcpExtensionNotification } from "../../acp.js";
3
3
  import { type BackendHooks, type BackendTuning, type ChatBackend, type PromptFile } from "./backend.js";
4
4
  import type { AuthStatus, ChatEvent, ConfigOption, ElicitationField, SessionFailure } from "./types.js";
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { promises as fs } from "node:fs";
3
3
  import { pathToFileURL } from "node:url";
4
- import { RequestError, } from "@agentclientprotocol/sdk";
4
+ import { RequestError, } from "@agentclientprotocol/sdk/unstable";
5
5
  import { adapterEnv, airMeta, connectAcp, EXT_METHODS, EXT_NOTIFICATIONS, fileChangeReportMeta, openSession, withAdapter, } from "../../acp.js";
6
6
  import { identityEnv } from "./backend.js";
7
7
  import { tempEnv } from "../temp.js";
@@ -498,7 +498,7 @@ export async function startAcpBackend(agent, cwd, hooks, tuning = {}) {
498
498
  if (dead)
499
499
  throw new Error(`${agent} agent process is gone`);
500
500
  try {
501
- const res = await conn.unstable_forkSession({ sessionId, ...sessionReq });
501
+ const res = await conn.forkSession({ sessionId, ...sessionReq });
502
502
  return res.sessionId;
503
503
  }
504
504
  catch (err) {
@@ -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);