@netnodeag/kraftwerk 0.104.0 → 0.105.1

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 (34) hide show
  1. package/README.md +10 -1
  2. package/dist/client/routes.d.ts +3 -0
  3. package/dist/client/routes.js +3 -0
  4. package/dist/core/chat/acp.js +4 -1
  5. package/dist/core/env.d.ts +4 -0
  6. package/dist/core/env.js +11 -1
  7. package/dist/core/harness-credentials.d.ts +47 -0
  8. package/dist/core/harness-credentials.js +107 -0
  9. package/dist/core/harness-status.d.ts +37 -0
  10. package/dist/core/harness-status.js +108 -0
  11. package/dist/server/api/harnesses.d.ts +21 -0
  12. package/dist/server/api/harnesses.js +54 -0
  13. package/dist/server/api/index.d.ts +19 -1
  14. package/dist/server/api/index.js +2 -0
  15. package/dist/server/api/router.js +1 -1
  16. package/dist/server/preview.d.ts +12 -0
  17. package/dist/server/preview.js +52 -0
  18. package/dist/server/server.js +36 -3
  19. package/package.json +1 -1
  20. package/web/dist/assets/{dist-Dv55aORJ.js → dist-B1XpD1Lm.js} +1 -1
  21. package/web/dist/assets/{dist-BG9MPqC7.js → dist-BNHxrmw6.js} +1 -1
  22. package/web/dist/assets/{dist-CfSpo_bP.js → dist-BUo-wCes.js} +1 -1
  23. package/web/dist/assets/{dist-CJk4RtqY.js → dist-C4DjPIrd.js} +1 -1
  24. package/web/dist/assets/{dist-QQHKzUGH.js → dist-CI324YX1.js} +1 -1
  25. package/web/dist/assets/{dist-BbST9sxK.js → dist-DA2q_iuY.js} +1 -1
  26. package/web/dist/assets/dist-DYeblH_P.js +1 -0
  27. package/web/dist/assets/{dist-C8wsDqpL.js → dist-Dx5saOON.js} +1 -1
  28. package/web/dist/assets/{dist-B09k-Kwi.js → dist-K55rjEIJ.js} +1 -1
  29. package/web/dist/assets/{dist-C0Ulmjwh.js → dist-K5WqExa2.js} +1 -1
  30. package/web/dist/assets/{dist-BrXAphjl.js → dist-kDsw_ny_.js} +1 -1
  31. package/web/dist/assets/{editor-Co8xGDnf.js → editor-BTjUXItl.js} +3 -3
  32. package/web/dist/assets/{index-CepQsH8H.js → index-CtmT2d2c.js} +9 -9
  33. package/web/dist/index.html +1 -1
  34. package/web/dist/assets/dist-DMU8iY9H.js +0 -1
package/README.md CHANGED
@@ -1646,7 +1646,16 @@ same interface ([src/harness.ts](src/harness.ts)):
1646
1646
  | CLIs | scoped allowlist `Bash(<name>:*)` | sandbox runs them anyway (hint only) | plain `bash` tool (no scoping) |
1647
1647
  | Quirks | none | no system-prompt flag (persona prepended to prompt); governance = workspace-write sandbox, not per-tool | `effort` maps 1:1 to `--thinking`; tool names lowercased |
1648
1648
 
1649
- Prerequisites per harness:
1649
+ Which harnesses a machine can use, and what each signs in with, is on one
1650
+ page: **settings → harnesses**. Claude and Codex can be given an API key
1651
+ there, Claude also a subscription's token (`claude setup-token`) — for a
1652
+ machine nobody logs in on, such as a sandbox in kraftwerk cloud. What is
1653
+ entered stays on that machine in `~/.kraftwerk/harness-credentials.json`
1654
+ (never in the workspace's files, so it is not synced), for one workspace or
1655
+ for every workspace there, and is handed to chats and runs as the variable
1656
+ the harness reads. The page shows a key by its last four characters only.
1657
+
1658
+ Prerequisites per harness, without a key from the settings:
1650
1659
 
1651
1660
  - **claude** needs Claude Code installed and logged in.
1652
1661
  - **codex** needs `brew install --cask codex` and `codex login`.
@@ -92,6 +92,9 @@ export declare const ROUTES: {
92
92
  readonly "git.push": readonly ["POST", "/api/git/push"];
93
93
  readonly "git.setupSync": readonly ["POST", "/api/git/sync-setup"];
94
94
  readonly "git.status": readonly ["GET", "/api/git"];
95
+ readonly "harnesses.list": readonly ["GET", "/api/harnesses"];
96
+ readonly "harnesses.removeCredential": readonly ["DELETE", "/api/harnesses/:id/credential"];
97
+ readonly "harnesses.setCredential": readonly ["PUT", "/api/harnesses/:id/credential"];
95
98
  readonly "hub.close": readonly ["POST", "/api/hub/close"];
96
99
  readonly "hub.list": readonly ["GET", "/api/hub"];
97
100
  readonly "hub.open": readonly ["POST", "/api/hub/open"];
@@ -93,6 +93,9 @@ export const ROUTES = {
93
93
  "git.push": ["POST", "/api/git/push"],
94
94
  "git.setupSync": ["POST", "/api/git/sync-setup"],
95
95
  "git.status": ["GET", "/api/git"],
96
+ "harnesses.list": ["GET", "/api/harnesses"],
97
+ "harnesses.removeCredential": ["DELETE", "/api/harnesses/:id/credential"],
98
+ "harnesses.setCredential": ["PUT", "/api/harnesses/:id/credential"],
96
99
  "hub.close": ["POST", "/api/hub/close"],
97
100
  "hub.list": ["GET", "/api/hub"],
98
101
  "hub.open": ["POST", "/api/hub/open"],
@@ -6,6 +6,7 @@ import { adapterEnv, applyTuningConfig, airMeta, connectAcp, EXT_METHODS, EXT_NO
6
6
  import { identityEnv } from "./backend.js";
7
7
  import { tempEnv } from "../temp.js";
8
8
  import { unattendedMode } from "./permissions.js";
9
+ import { noteHarnessAuth } from "../harness-status.js";
9
10
  /**
10
11
  * ACP-backed chat: spawn an adapter (claude-agent-acp / codex-acp / agy acp) as a
11
12
  * subprocess, speak Agent Client Protocol over its stdio, and translate
@@ -406,8 +407,10 @@ export async function startAcpBackend(agent, cwd, hooks, tuning = {}) {
406
407
  async extNotification(method, params) {
407
408
  if (method === EXT_NOTIFICATIONS.authStatus) {
408
409
  const auth = authStatusOf(params);
409
- if (auth)
410
+ if (auth) {
410
411
  hooks.emit({ type: "auth", ...auth });
412
+ noteHarnessAuth(agent, auth);
413
+ }
411
414
  }
412
415
  },
413
416
  };
@@ -7,6 +7,10 @@
7
7
  * directly: one process may serve several workspaces, and one team's
8
8
  * `.env` must not reach another's agents.
9
9
  *
10
+ * On top of that come the credentials the workspace's harnesses were given
11
+ * in the settings (harness-credentials.ts): kept on this machine, outside
12
+ * the workspace folder.
13
+ *
10
14
  * With one workspace per process the CLI has already applied that
11
15
  * workspace's `.env` to process.env, so the result is the same as before.
12
16
  */
package/dist/core/env.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { DOTENV_FILE, DOTENV_MARKER, parseDotenv } from "../dotenv.js";
4
+ import { applyCredentials } from "./harness-credentials.js";
4
5
  import { currentWorkspace } from "./workspace.js";
5
6
  /**
6
7
  * The environment a workspace's processes run with: this process's, plus
@@ -11,6 +12,10 @@ import { currentWorkspace } from "./workspace.js";
11
12
  * directly: one process may serve several workspaces, and one team's
12
13
  * `.env` must not reach another's agents.
13
14
  *
15
+ * On top of that come the credentials the workspace's harnesses were given
16
+ * in the settings (harness-credentials.ts): kept on this machine, outside
17
+ * the workspace folder.
18
+ *
14
19
  * With one workspace per process the CLI has already applied that
15
20
  * workspace's `.env` to process.env, so the result is the same as before.
16
21
  */
@@ -26,8 +31,11 @@ export function readWorkspaceDotenv(root) {
26
31
  /** The current workspace's environment (outside any workspace: process.env). */
27
32
  export function workspaceEnv() {
28
33
  let dotenv;
34
+ let root;
29
35
  try {
30
- dotenv = currentWorkspace().env;
36
+ const ws = currentWorkspace();
37
+ dotenv = ws.env;
38
+ root = ws.root;
31
39
  }
32
40
  catch {
33
41
  return { ...process.env };
@@ -41,5 +49,7 @@ export function workspaceEnv() {
41
49
  for (const [key, value] of Object.entries(dotenv))
42
50
  if (!process.env[key] || injected.has(key))
43
51
  env[key] = value;
52
+ // What a harness was given in the settings (harness-credentials.ts) is the most deliberate choice: it wins.
53
+ applyCredentials(root, env);
44
54
  return env;
45
55
  }
@@ -0,0 +1,47 @@
1
+ import type { HarnessId } from "../harness.js";
2
+ /**
3
+ * What a harness signs in with, when it is not the CLI login of whoever
4
+ * runs this machine: an API key, or a subscription's long-lived token.
5
+ * Entered in the settings (web: #/settings/harnesses), kept on this machine
6
+ * in ~/.kraftwerk/harness-credentials.json (0600) — never in the workspace
7
+ * folder, so kraftwerk sync cannot carry it to the others — and handed to
8
+ * everything the workspace spawns as the environment variable the harness
9
+ * reads (core/env.ts).
10
+ *
11
+ * scope "workspace": this workspace on this machine (its folder);
12
+ * "machine": every workspace here that has none of its own
13
+ * kind api_key | subscription_token — one per harness and scope; the
14
+ * other kind's variables are taken out of the environment, so
15
+ * what was chosen here is what the harness uses
16
+ *
17
+ * A value is written and never read back by anyone but the spawn: the API
18
+ * shows which kind is set, where, since when, and its last four characters.
19
+ */
20
+ export type CredentialKind = "api_key" | "subscription_token";
21
+ export type CredentialScope = "workspace" | "machine";
22
+ interface KindSpec {
23
+ /** The variables the harness reads it from. */
24
+ env: string[];
25
+ label: string;
26
+ /** Where the value comes from, for the form. */
27
+ hint: string;
28
+ }
29
+ /** What each harness can be given. A harness without an entry signs in with its own CLI only. */
30
+ export declare const CREDENTIAL_KINDS: Record<HarnessId, Partial<Record<CredentialKind, KindSpec>>>;
31
+ /** A stored credential as the API shows it: never the value. */
32
+ export interface CredentialInfo {
33
+ scope: CredentialScope;
34
+ kind: CredentialKind;
35
+ /** Its last four characters. */
36
+ ending: string;
37
+ setAt: number;
38
+ }
39
+ /** Set (or replace) what `harness` signs in with, for this workspace or the whole machine. Throws on a kind the harness does not take or a value that cannot be one. */
40
+ export declare function setCredential(root: string, harness: HarnessId, scope: CredentialScope, kind: CredentialKind, value: string): CredentialInfo;
41
+ /** Forget it; false when there was none in that scope. */
42
+ export declare function removeCredential(root: string, harness: HarnessId, scope: CredentialScope): boolean;
43
+ /** What `harness` uses in the workspace at `root`: its own, else the machine's; undefined when neither is set. */
44
+ export declare function credentialOf(root: string, harness: HarnessId): CredentialInfo | undefined;
45
+ /** Put the workspace's credentials into `env` (in place): each chosen kind's variables set, the harness's other ones gone. */
46
+ export declare function applyCredentials(root: string, env: NodeJS.ProcessEnv): void;
47
+ export {};
@@ -0,0 +1,107 @@
1
+ import { chmodSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ /** What each harness can be given. A harness without an entry signs in with its own CLI only. */
5
+ export const CREDENTIAL_KINDS = {
6
+ claude: {
7
+ api_key: { env: ["ANTHROPIC_API_KEY"], label: "API key", hint: "An Anthropic API key (console.anthropic.com), billed per use." },
8
+ subscription_token: { env: ["CLAUDE_CODE_OAUTH_TOKEN"], label: "subscription token", hint: "A long-lived token of a Claude subscription: run `claude setup-token` on a machine that is logged in." },
9
+ },
10
+ codex: {
11
+ api_key: { env: ["OPENAI_API_KEY", "CODEX_API_KEY"], label: "API key", hint: "An OpenAI API key (platform.openai.com), billed per use." },
12
+ },
13
+ pi: {},
14
+ antigravity: {},
15
+ };
16
+ /** Variables that would override a chosen kind, per harness: out of the environment once a credential is set. */
17
+ const OTHER_VARS = {
18
+ claude: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"],
19
+ codex: ["OPENAI_API_KEY", "CODEX_API_KEY"],
20
+ };
21
+ const storeFile = () => path.join(os.homedir(), ".kraftwerk", "harness-credentials.json");
22
+ const scopeKey = (scope, root) => (scope === "machine" ? "machine" : `ws:${path.resolve(root)}`);
23
+ let cache;
24
+ function read() {
25
+ const file = storeFile();
26
+ let mtimeMs;
27
+ try {
28
+ mtimeMs = statSync(file).mtimeMs;
29
+ }
30
+ catch {
31
+ return { version: 1, scopes: {} };
32
+ }
33
+ if (cache && cache.file === file && cache.mtimeMs === mtimeMs)
34
+ return cache.store;
35
+ let store = { version: 1, scopes: {} };
36
+ try {
37
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
38
+ if (parsed && typeof parsed.scopes === "object" && parsed.scopes)
39
+ store = { version: 1, scopes: parsed.scopes };
40
+ }
41
+ catch {
42
+ /* unreadable: as good as empty; the next write replaces it */
43
+ }
44
+ cache = { file, mtimeMs, store };
45
+ return store;
46
+ }
47
+ function write(store) {
48
+ const file = storeFile();
49
+ mkdirSync(path.dirname(file), { recursive: true });
50
+ const tmp = `${file}.${process.pid}.tmp`;
51
+ writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
52
+ chmodSync(tmp, 0o600);
53
+ renameSync(tmp, file);
54
+ cache = undefined;
55
+ }
56
+ /** Set (or replace) what `harness` signs in with, for this workspace or the whole machine. Throws on a kind the harness does not take or a value that cannot be one. */
57
+ export function setCredential(root, harness, scope, kind, value) {
58
+ if (!CREDENTIAL_KINDS[harness]?.[kind])
59
+ throw new Error(`${harness} takes no ${kind === "api_key" ? "API key" : "subscription token"} here — it signs in with its own CLI`);
60
+ const v = value.trim();
61
+ if (v.length < 8 || v.length > 4096 || /\s/.test(v))
62
+ throw new Error("that does not look like a key: 8 to 4096 characters, no spaces");
63
+ const store = structuredClone(read());
64
+ const key = scopeKey(scope, root);
65
+ const setAt = Date.now();
66
+ store.scopes[key] = { ...store.scopes[key], [harness]: { kind, value: v, setAt } };
67
+ write(store);
68
+ return { scope, kind, ending: v.slice(-4), setAt };
69
+ }
70
+ /** Forget it; false when there was none in that scope. */
71
+ export function removeCredential(root, harness, scope) {
72
+ const store = structuredClone(read());
73
+ const key = scopeKey(scope, root);
74
+ if (!store.scopes[key]?.[harness])
75
+ return false;
76
+ delete store.scopes[key][harness];
77
+ if (Object.keys(store.scopes[key]).length === 0)
78
+ delete store.scopes[key];
79
+ write(store);
80
+ return true;
81
+ }
82
+ function effective(root, harness) {
83
+ const store = read();
84
+ const ws = store.scopes[scopeKey("workspace", root)]?.[harness];
85
+ if (ws)
86
+ return { scope: "workspace", stored: ws };
87
+ const machine = store.scopes.machine?.[harness];
88
+ return machine ? { scope: "machine", stored: machine } : undefined;
89
+ }
90
+ /** What `harness` uses in the workspace at `root`: its own, else the machine's; undefined when neither is set. */
91
+ export function credentialOf(root, harness) {
92
+ const e = effective(root, harness);
93
+ return e ? { scope: e.scope, kind: e.stored.kind, ending: e.stored.value.slice(-4), setAt: e.stored.setAt } : undefined;
94
+ }
95
+ /** Put the workspace's credentials into `env` (in place): each chosen kind's variables set, the harness's other ones gone. */
96
+ export function applyCredentials(root, env) {
97
+ for (const harness of Object.keys(CREDENTIAL_KINDS)) {
98
+ const e = effective(root, harness);
99
+ const spec = e && CREDENTIAL_KINDS[harness][e.stored.kind];
100
+ if (!e || !spec)
101
+ continue;
102
+ for (const name of OTHER_VARS[harness] ?? [])
103
+ delete env[name];
104
+ for (const name of spec.env)
105
+ env[name] = e.stored.value;
106
+ }
107
+ }
@@ -0,0 +1,37 @@
1
+ import type { HarnessId } from "../harness.js";
2
+ import type { AuthStatus } from "./chat/types.js";
3
+ import { type CredentialInfo, type CredentialKind } from "./harness-credentials.js";
4
+ export interface HarnessStatus {
5
+ id: HarnessId;
6
+ label: string;
7
+ /** Usable here at all: an adapter or a CLI is there. */
8
+ available: boolean;
9
+ adapter?: {
10
+ version: string;
11
+ };
12
+ cli?: {
13
+ command: string;
14
+ path: string;
15
+ };
16
+ /** The CLI it needs when neither is there, to say what to install. */
17
+ needs?: string;
18
+ /** The kinds the settings can store for it. */
19
+ accepts: Array<{
20
+ kind: CredentialKind;
21
+ label: string;
22
+ hint: string;
23
+ }>;
24
+ credential?: CredentialInfo;
25
+ /** Names of variables set outside the settings (shell, .env) that it would read. */
26
+ env: string[];
27
+ login: "present" | "absent" | "unknown";
28
+ seen?: AuthStatus & {
29
+ at: number;
30
+ };
31
+ }
32
+ /** A chat's agent reported who it is signed in as (chat/acp.ts): remembered for the settings. */
33
+ export declare function noteHarnessAuth(id: string, auth: AuthStatus): void;
34
+ /** Forget what a harness last said: its credential changed, so the next chat says anew. */
35
+ export declare function forgetHarnessAuth(root: string, id: HarnessId): void;
36
+ /** Every harness, for the current workspace. */
37
+ export declare function harnessStatuses(): HarnessStatus[];
@@ -0,0 +1,108 @@
1
+ import { accessSync, constants, existsSync, readFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { workspaceEnv } from "./env.js";
6
+ import { CREDENTIAL_KINDS, credentialOf } from "./harness-credentials.js";
7
+ import { currentWorkspace } from "./workspace.js";
8
+ /**
9
+ * The harnesses this machine can run agents on, and what each would sign
10
+ * in with — the settings' answer to "why does the agent say it is not
11
+ * logged in" (web: #/settings/harnesses). Read from what is on disk and in
12
+ * the environment; no agent is started for it.
13
+ *
14
+ * runs how it can be driven here: the adapter bundled with kraftwerk
15
+ * (chats, `protocol: acp`), its CLI on the PATH (`protocol: cli`)
16
+ * credential what was entered in the settings (harness-credentials.ts)
17
+ * env a variable the harness reads that is set in the shell or the
18
+ * workspace's .env — the name only
19
+ * login the CLI's own login on this machine: its credentials file is
20
+ * there, is not, or cannot be told (macOS keeps Claude's in the keychain)
21
+ * seen who the agent said it is, the last time a chat on it started here
22
+ */
23
+ const ADAPTERS = {
24
+ claude: "@agentclientprotocol/claude-agent-acp",
25
+ codex: "@agentclientprotocol/codex-acp",
26
+ };
27
+ const CLI = { claude: "claude", codex: "codex", pi: "pi", antigravity: "agy" };
28
+ const LABEL = { claude: "Claude Code", codex: "Codex", pi: "pi", antigravity: "Antigravity" };
29
+ /** The CLI's own credentials file under HOME, where it keeps one. */
30
+ const LOGIN_FILE = {
31
+ claude: [".claude", ".credentials.json"],
32
+ codex: [".codex", "auth.json"],
33
+ };
34
+ function adapterVersion(pkg) {
35
+ try {
36
+ return JSON.parse(readFileSync(fileURLToPath(import.meta.resolve(`${pkg}/package.json`)), "utf8")).version;
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ }
42
+ function onPath(command, env) {
43
+ for (const dir of (env.PATH ?? "").split(path.delimiter)) {
44
+ if (!dir)
45
+ continue;
46
+ const file = path.join(dir, command);
47
+ try {
48
+ accessSync(file, constants.X_OK);
49
+ return file;
50
+ }
51
+ catch {
52
+ /* not here */
53
+ }
54
+ }
55
+ return undefined;
56
+ }
57
+ /** Who each harness last said it is, per workspace folder (this process only). */
58
+ const seen = new Map();
59
+ const seenKey = (root, id) => `${root}\n${id}`;
60
+ /** A chat's agent reported who it is signed in as (chat/acp.ts): remembered for the settings. */
61
+ export function noteHarnessAuth(id, auth) {
62
+ try {
63
+ seen.set(seenKey(currentWorkspace().root, id), { ...auth, at: Date.now() });
64
+ }
65
+ catch {
66
+ /* outside a workspace: nobody to tell */
67
+ }
68
+ }
69
+ /** Forget what a harness last said: its credential changed, so the next chat says anew. */
70
+ export function forgetHarnessAuth(root, id) {
71
+ seen.delete(seenKey(root, id));
72
+ }
73
+ /** Every harness, for the current workspace. */
74
+ export function harnessStatuses() {
75
+ const ws = currentWorkspace();
76
+ const env = workspaceEnv();
77
+ const home = os.homedir();
78
+ return Object.keys(CLI).map((id) => {
79
+ const version = ADAPTERS[id] ? adapterVersion(ADAPTERS[id]) : undefined;
80
+ const cliPath = onPath(CLI[id], env);
81
+ const kinds = CREDENTIAL_KINDS[id];
82
+ const credential = credentialOf(ws.root, id);
83
+ // What the shell or the .env brings by itself — not what the settings put there.
84
+ const outside = (name) => !!(process.env[name] || ws.env[name]);
85
+ const loginFile = LOGIN_FILE[id];
86
+ const login = !loginFile
87
+ ? "unknown"
88
+ : existsSync(path.join(home, ...loginFile))
89
+ ? "present"
90
+ : id === "claude" && process.platform === "darwin"
91
+ ? "unknown"
92
+ : "absent";
93
+ const last = seen.get(seenKey(ws.root, id));
94
+ return {
95
+ id,
96
+ label: LABEL[id],
97
+ available: !!version || !!cliPath,
98
+ ...(version ? { adapter: { version } } : {}),
99
+ ...(cliPath ? { cli: { command: CLI[id], path: cliPath } } : {}),
100
+ ...(!version && !cliPath ? { needs: CLI[id] } : {}),
101
+ accepts: Object.entries(kinds).map(([kind, k]) => ({ kind, label: k.label, hint: k.hint })),
102
+ ...(credential ? { credential } : {}),
103
+ env: [...new Set(Object.values(kinds).flatMap((k) => k.env))].filter(outside),
104
+ login,
105
+ ...(last ? { seen: last } : {}),
106
+ };
107
+ });
108
+ }
@@ -0,0 +1,21 @@
1
+ import * as z from "zod";
2
+ /** The harnesses agents run on here, and what each signs in with (core/harness-status.ts, core/harness-credentials.ts). */
3
+ export declare const harnessRoutes: (import("./router.js").Route<"harnesses.list", {
4
+ harnesses: import("../../core/harness-status.js").HarnessStatus[];
5
+ }, "/api/harnesses", undefined> | import("./router.js").Route<"harnesses.removeCredential", {
6
+ ok: boolean;
7
+ removed: boolean;
8
+ }, "/api/harnesses/:id/credential", undefined> | import("./router.js").Route<"harnesses.setCredential", {
9
+ ok: boolean;
10
+ credential: import("../../core/harness-credentials.js").CredentialInfo;
11
+ }, "/api/harnesses/:id/credential", z.ZodObject<{
12
+ kind: z.ZodEnum<{
13
+ api_key: "api_key";
14
+ subscription_token: "subscription_token";
15
+ }>;
16
+ value: z.ZodString;
17
+ scope: z.ZodDefault<z.ZodEnum<{
18
+ machine: "machine";
19
+ workspace: "workspace";
20
+ }>>;
21
+ }, z.core.$strip>>)[];
@@ -0,0 +1,54 @@
1
+ import * as z from "zod";
2
+ import { workspaceRoot } from "../../core/context.js";
3
+ import { CREDENTIAL_KINDS, removeCredential, setCredential } from "../../core/harness-credentials.js";
4
+ import { forgetHarnessAuth, harnessStatuses } from "../../core/harness-status.js";
5
+ import { ApiError, fail, route } from "./router.js";
6
+ const Scope = z.enum(["workspace", "machine"]).default("workspace");
7
+ /** What a harness signs in with; the value is stored and never returned. */
8
+ const Credential = z.object({ kind: z.enum(["api_key", "subscription_token"]), value: z.string().min(1), scope: Scope });
9
+ function harnessId(raw) {
10
+ if (!(raw in CREDENTIAL_KINDS))
11
+ fail(404, `no harness "${raw}"`);
12
+ return raw;
13
+ }
14
+ /** Where people sign in with their cloud account (a sandbox, `users: cloud`), keys are the owner's to set — a member uses them. */
15
+ function ownerOnly(c) {
16
+ if (c.trust.kind === "local" && c.trust.user && c.trust.user.role !== "owner")
17
+ fail(403, "only an owner of the workspace sets what its harnesses sign in with");
18
+ }
19
+ /** The harnesses agents run on here, and what each signs in with (core/harness-status.ts, core/harness-credentials.ts). */
20
+ export const harnessRoutes = [
21
+ route({ name: "harnesses.list", method: "GET", path: "/api/harnesses", summary: "every harness: usable here, what it signs in with (never a key's value)" }, async () => ({ harnesses: harnessStatuses() })),
22
+ route({
23
+ name: "harnesses.setCredential",
24
+ method: "PUT",
25
+ path: "/api/harnesses/:id/credential",
26
+ summary: "store what a harness signs in with {kind: api_key|subscription_token, value, scope: workspace|machine}",
27
+ access: "local",
28
+ errors: 400,
29
+ body: Credential,
30
+ }, async (c) => {
31
+ ownerOnly(c);
32
+ const id = harnessId(c.params.id);
33
+ const { kind, value, scope } = await c.body();
34
+ try {
35
+ const credential = setCredential(workspaceRoot(), id, scope, kind, value);
36
+ forgetHarnessAuth(workspaceRoot(), id);
37
+ return { ok: true, credential };
38
+ }
39
+ catch (err) {
40
+ throw new ApiError(400, err.message);
41
+ }
42
+ }),
43
+ route({ name: "harnesses.removeCredential", method: "DELETE", path: "/api/harnesses/:id/credential", summary: "forget a harness's stored credential ?scope=workspace|machine", access: "local" }, async (c) => {
44
+ ownerOnly(c);
45
+ const id = harnessId(c.params.id);
46
+ const scope = Scope.safeParse(c.query.get("scope") ?? undefined);
47
+ if (!scope.success)
48
+ fail(400, "scope is workspace or machine");
49
+ const removed = removeCredential(workspaceRoot(), id, scope.data);
50
+ if (removed)
51
+ forgetHarnessAuth(workspaceRoot(), id);
52
+ return { ok: true, removed };
53
+ }),
54
+ ];
@@ -553,7 +553,25 @@ export declare const routes: (Route<"agents.addJournal", {
553
553
  done: string[];
554
554
  error?: string;
555
555
  status: import("../../core/git.js").GitStatus;
556
- }>, "/api/git/sync-setup", undefined> | Route<"git.status", import("../../core/git.js").GitStatus, "/api/git", undefined> | Route<"hub.close", {
556
+ }>, "/api/git/sync-setup", undefined> | Route<"git.status", import("../../core/git.js").GitStatus, "/api/git", undefined> | Route<"harnesses.list", {
557
+ harnesses: import("../../core/harness-status.js").HarnessStatus[];
558
+ }, "/api/harnesses", undefined> | Route<"harnesses.removeCredential", {
559
+ ok: boolean;
560
+ removed: boolean;
561
+ }, "/api/harnesses/:id/credential", undefined> | Route<"harnesses.setCredential", {
562
+ ok: boolean;
563
+ credential: import("../../core/harness-credentials.js").CredentialInfo;
564
+ }, "/api/harnesses/:id/credential", z.ZodObject<{
565
+ kind: z.ZodEnum<{
566
+ api_key: "api_key";
567
+ subscription_token: "subscription_token";
568
+ }>;
569
+ value: z.ZodString;
570
+ scope: z.ZodDefault<z.ZodEnum<{
571
+ machine: "machine";
572
+ workspace: "workspace";
573
+ }>>;
574
+ }, z.core.$strip>> | Route<"hub.close", {
557
575
  ok: boolean;
558
576
  }, "/api/hub/close", z.ZodObject<{
559
577
  root: z.ZodString;
@@ -10,6 +10,7 @@ import { contactRoutes, eventRoutes, placeRoutes, refRoutes } from "./entities.j
10
10
  import { hubRoutes } from "./hub.js";
11
11
  import { fileRoutes } from "./files.js";
12
12
  import { gitRoutes } from "./git.js";
13
+ import { harnessRoutes } from "./harnesses.js";
13
14
  import { knowledgeRoutes } from "./knowledge.js";
14
15
  import { presentationRoutes } from "./presentations.js";
15
16
  import { projectRoutes } from "./projects.js";
@@ -47,6 +48,7 @@ const domainRoutes = [
47
48
  ...gitRoutes,
48
49
  ...vibeableRoutes,
49
50
  ...deviceRoutes,
51
+ ...harnessRoutes,
50
52
  ...cloudRoutes,
51
53
  ...hubRoutes,
52
54
  ];
@@ -47,7 +47,7 @@ export const statusByMessage = (missing) => (message) => missing.test(message) ?
47
47
  * record, settings, updates, restarts, identity, trash. server.ts already
48
48
  * keeps the session inside its workspace; this keeps it out of the machine.
49
49
  */
50
- const MEMBER_DENIED = /^(hub|devices|cloud|settings|server|update|workspaces|identity|trash)\./;
50
+ const MEMBER_DENIED = /^(hub|devices|cloud|settings|harnesses|server|update|workspaces|identity|trash)\./;
51
51
  /** …except asking who it is. */
52
52
  const MEMBER_ALLOWED = new Set(["devices.self"]);
53
53
  /** Why a caller may not use a route, or undefined when it may. */
@@ -1,5 +1,17 @@
1
1
  import http from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
+ /** A pass for the app `slug` of the workspace `workspace` (its slug here), as the path segment that carries it. */
4
+ export declare function vibeablePass(workspace: string, slug: string, now?: number): string;
5
+ /**
6
+ * Take the pass out of a preview path. `pathname` is the path without it
7
+ * either way; `valid` says whether it was there and holds for this app of
8
+ * this workspace, `slug` the app it names (undefined: not an app's path).
9
+ */
10
+ export declare function takeVibeablePass(workspace: string | undefined, pathname: string, now?: number): {
11
+ pathname: string;
12
+ slug?: string;
13
+ valid: boolean;
14
+ };
3
15
  /**
4
16
  * GET /vibeables/<slug>/<file>. Dot segments (.env, .git) are never served;
5
17
  * a directory answers with its index.html, and a directory url without the
@@ -1,3 +1,4 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
1
2
  import { createReadStream, promises as fs } from "node:fs";
2
3
  import http from "node:http";
3
4
  import net from "node:net";
@@ -58,7 +59,58 @@ const PREVIEW_HEADERS = {
58
59
  "cache-control": "no-store",
59
60
  "content-security-policy": VIBEABLE_CSP,
60
61
  "access-control-allow-origin": "*",
62
+ // A pass (below) is part of the address: it stays out of what the app tells other sites.
63
+ "referrer-policy": "same-origin",
61
64
  };
65
+ /* ---------- pass ---------- */
66
+ /**
67
+ * The sandboxed document has an opaque origin, so what it loads — its own
68
+ * style.css, app.js, images, fetch() — is a cross-site request to the
69
+ * browser: no SameSite cookie goes with it. Where a cookie is what lets the
70
+ * caller in (a signed-in user, a paired device, a member), the app's files
71
+ * would answer with the sign-in page and the app would show unstyled.
72
+ *
73
+ * So the first request, which does carry the cookie, is redirected to an
74
+ * address with a pass in it — /vibeables/<slug>/~<pass>/… — and the page's
75
+ * relative links stay under it. A pass opens one app's files of one
76
+ * workspace for PASS_TTL_MS and nothing else; it is signed with a secret
77
+ * this process made up, so none outlives a restart.
78
+ */
79
+ const PASS_TTL_MS = 12 * 60 * 60 * 1000;
80
+ const PASS_RE = /^~(\d{1,15})\.([A-Za-z0-9_-]{43})$/;
81
+ const passSecret = randomBytes(32);
82
+ const sign = (workspace, slug, exp) => createHmac("sha256", passSecret).update(`${workspace}\0${slug}\0${exp}`).digest("base64url");
83
+ /** A pass for the app `slug` of the workspace `workspace` (its slug here), as the path segment that carries it. */
84
+ export function vibeablePass(workspace, slug, now = Date.now()) {
85
+ const exp = now + PASS_TTL_MS;
86
+ return `~${exp}.${sign(workspace, slug, exp)}`;
87
+ }
88
+ /**
89
+ * Take the pass out of a preview path. `pathname` is the path without it
90
+ * either way; `valid` says whether it was there and holds for this app of
91
+ * this workspace, `slug` the app it names (undefined: not an app's path).
92
+ */
93
+ export function takeVibeablePass(workspace, pathname, now = Date.now()) {
94
+ const seg = pathname.split("/"); // ["", "vibeables", slug, maybe pass, ...rest]
95
+ let slug;
96
+ try {
97
+ slug = seg[2] ? safeVibeableSlug(decodeURIComponent(seg[2])) : undefined;
98
+ }
99
+ catch {
100
+ slug = undefined;
101
+ }
102
+ const m = PASS_RE.exec(seg[3] ?? "");
103
+ if (!m)
104
+ return { pathname, slug, valid: false };
105
+ seg.splice(3, 1);
106
+ const stripped = seg.length === 3 ? `${seg.join("/")}/` : seg.join("/");
107
+ const exp = Number(m[1]);
108
+ if (!slug || workspace === undefined || !(exp > now))
109
+ return { pathname: stripped, slug, valid: false };
110
+ const want = Buffer.from(sign(workspace, slug, exp));
111
+ const got = Buffer.from(m[2]);
112
+ return { pathname: stripped, slug, valid: want.length === got.length && timingSafeEqual(want, got) };
113
+ }
62
114
  /**
63
115
  * GET /vibeables/<slug>/<file>. Dot segments (.env, .git) are never served;
64
116
  * a directory answers with its index.html, and a directory url without the