@appchy/jarvis 0.1.37 → 0.1.39
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.
- package/bin/config-change.mjs +1 -1
- package/bin/jarvis.mjs +8 -12
- package/bin/pre-tool-use.mjs +2 -2
- package/bin/session-start.mjs +1 -1
- package/bin/stop.mjs +1 -1
- package/bin/user-prompt-submit.mjs +1 -1
- package/dist/bin.js +10168 -37341
- package/dist/bin.js.map +1 -1
- package/dist/data/backends.mjs +469 -0
- package/dist/data/chunk-7REP35VA.mjs +462 -0
- package/dist/data/chunk-AKQQC5IT.mjs +1224 -0
- package/dist/data/chunk-AYOJSS2F.mjs +72 -0
- package/dist/data/chunk-RRJ6KKYL.mjs +42 -0
- package/dist/data/chunk-YWSWQEJN.mjs +138 -0
- package/dist/data/embedders.mjs +80 -0
- package/dist/data/finders.mjs +35 -0
- package/dist/data/index.mjs +137 -0
- package/dist/data/linkers.mjs +83 -0
- package/dist/data/mcp.mjs +2624 -0
- package/dist/data/persistences.mjs +8 -0
- package/dist/data/rerankers.mjs +52 -0
- package/dist/data/stores.mjs +38 -0
- package/dist/hooks/config-change.js +7 -29
- package/dist/hooks/config-change.js.map +1 -1
- package/dist/hooks/pre-tool-use.js +129 -32
- package/dist/hooks/pre-tool-use.js.map +1 -1
- package/dist/hooks/session-start.js +72 -37
- package/dist/hooks/session-start.js.map +1 -1
- package/dist/hooks/stop.js +140 -32
- package/dist/hooks/stop.js.map +1 -1
- package/dist/hooks/user-prompt-submit.js +7 -29
- package/dist/hooks/user-prompt-submit.js.map +1 -1
- package/harness/assets/architecture-template.md +53 -0
- package/harness/assets/design-template.md +89 -0
- package/harness/assets/domains/architecture.md +43 -0
- package/harness/assets/domains/commercial.md +42 -0
- package/harness/assets/domains/design.md +42 -0
- package/harness/assets/domains/legal.md +43 -0
- package/harness/assets/domains/operations.md +39 -0
- package/harness/assets/domains/product.md +43 -0
- package/harness/assets/domains/quality.md +43 -0
- package/harness/assets/domains/security.md +44 -0
- package/harness/assets/domains/support.md +45 -0
- package/harness/assets/epic-template.md +85 -0
- package/harness/assets/feature-template.md +86 -0
- package/harness/assets/handoff-template.md +26 -0
- package/harness/assets/task-template.md +38 -0
- package/harness/assets/version-template.md +43 -0
- package/harness/harness/__init__.py +7 -0
- package/harness/harness/align.py +582 -0
- package/harness/harness/architecture.py +254 -0
- package/harness/harness/autonomy.py +374 -0
- package/harness/harness/branches.py +408 -0
- package/harness/harness/config.py +1482 -0
- package/harness/harness/coverage.py +199 -0
- package/harness/harness/epic.py +220 -0
- package/harness/harness/events.py +153 -0
- package/harness/harness/extend.py +99 -0
- package/harness/harness/frontmatter.py +218 -0
- package/harness/harness/gate.py +591 -0
- package/harness/harness/generate.py +267 -0
- package/harness/harness/git.py +775 -0
- package/harness/harness/ids.py +140 -0
- package/harness/harness/kickoff.py +231 -0
- package/harness/harness/lint.py +505 -0
- package/harness/harness/model.py +364 -0
- package/harness/harness/peers.py +187 -0
- package/harness/harness/product.py +29 -0
- package/harness/harness/registry.py +382 -0
- package/harness/harness/report.py +227 -0
- package/harness/harness/safety.py +387 -0
- package/harness/harness/scaffold.py +129 -0
- package/harness/harness/shard.py +63 -0
- package/harness/harness/shift.py +348 -0
- package/harness/harness/task.py +507 -0
- package/harness/harness/tree.py +258 -0
- package/harness/harness/version.py +305 -0
- package/harness/harness/wrap.py +217 -0
- package/harness/hooks/guard.py +259 -0
- package/harness/presets/appchy/PRESET.md +717 -0
- package/harness/presets/appchy/references/artifacts.md +539 -0
- package/harness/presets/appchy/references/graph.md +154 -0
- package/harness/presets/appchy/references/operations.md +444 -0
- package/harness/presets/appchy/references/research.md +216 -0
- package/harness/schema/work.config.schema.json +401 -0
- package/harness/test_work.py +5002 -0
- package/harness/work.py +534 -0
- package/package.json +34 -40
- package/bin/config-change.dev.mjs +0 -17
- package/bin/jarvis-dev.mjs +0 -30
- package/bin/pre-tool-use.dev.mjs +0 -23
- package/bin/session-start.dev.mjs +0 -17
- package/bin/stop.dev.mjs +0 -17
- package/bin/user-prompt-submit.dev.mjs +0 -17
- package/dev/bin.js +0 -38821
- package/dev/bin.js.map +0 -1
- package/dev/env.json +0 -1
- package/dev/hooks/config-change.js +0 -110
- package/dev/hooks/config-change.js.map +0 -1
- package/dev/hooks/pre-tool-use.js +0 -120
- package/dev/hooks/pre-tool-use.js.map +0 -1
- package/dev/hooks/session-start.js +0 -115
- package/dev/hooks/session-start.js.map +0 -1
- package/dev/hooks/stop.js +0 -112
- package/dev/hooks/stop.js.map +0 -1
- package/dev/hooks/user-prompt-submit.js +0 -111
- package/dev/hooks/user-prompt-submit.js.map +0 -1
- package/dist/env.json +0 -1
|
@@ -1,37 +1,69 @@
|
|
|
1
1
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
2
2
|
|
|
3
|
+
// src/harness.ts
|
|
4
|
+
import { spawnSync } from "child_process";
|
|
5
|
+
import { existsSync } from "fs";
|
|
6
|
+
import { dirname, join } from "path";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
var ENTRY = join("harness", "work.py");
|
|
9
|
+
var INTERPRETERS = ["python3", "python"];
|
|
10
|
+
var OLDEST = [3, 9];
|
|
11
|
+
var INSTALLED = ["jarvis", "work"];
|
|
12
|
+
function payload() {
|
|
13
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
for (let up = 0; up < 6; up++) {
|
|
15
|
+
if (existsSync(join(dir, ENTRY))) return join(dir, ENTRY);
|
|
16
|
+
const parent = dirname(dir);
|
|
17
|
+
if (parent === dir) break;
|
|
18
|
+
dir = parent;
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
function interpreter() {
|
|
23
|
+
for (const name of INTERPRETERS) {
|
|
24
|
+
const said = spawnSync(name, ["--version"], { encoding: "utf-8" });
|
|
25
|
+
if (said.status !== 0) continue;
|
|
26
|
+
const version = /(\d+)\.(\d+)/.exec(`${said.stdout}${said.stderr}`);
|
|
27
|
+
if (!version) continue;
|
|
28
|
+
const [major, minor] = [Number(version[1]), Number(version[2])];
|
|
29
|
+
if (major > OLDEST[0] || major === OLDEST[0] && minor >= OLDEST[1]) return name;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
function harness() {
|
|
34
|
+
const script = payload();
|
|
35
|
+
const python = interpreter();
|
|
36
|
+
return script && python ? [python, script] : INSTALLED;
|
|
37
|
+
}
|
|
38
|
+
function sessionContext(repo) {
|
|
39
|
+
return say(["context", "--project", repo]);
|
|
40
|
+
}
|
|
41
|
+
var PATIENCE = 1e4;
|
|
42
|
+
function say(args, timeout = PATIENCE) {
|
|
43
|
+
try {
|
|
44
|
+
const [command, ...prefix] = harness();
|
|
45
|
+
const ran = spawnSync(command, [...prefix, ...args], {
|
|
46
|
+
encoding: "utf-8",
|
|
47
|
+
timeout,
|
|
48
|
+
env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" }
|
|
49
|
+
});
|
|
50
|
+
if (ran.status !== 0) return null;
|
|
51
|
+
return ran.stdout.trim() ? ran.stdout.trimEnd() : null;
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
3
57
|
// src/hooks/drop.ts
|
|
4
58
|
import { appendFile, mkdir } from "fs/promises";
|
|
5
|
-
import { join } from "path";
|
|
59
|
+
import { join as join2 } from "path";
|
|
6
60
|
|
|
7
61
|
// src/config.ts
|
|
8
|
-
import fs from "fs";
|
|
9
62
|
import path from "path";
|
|
10
63
|
import os from "os";
|
|
11
|
-
import { fileURLToPath } from "url";
|
|
12
|
-
var __filename = fileURLToPath(import.meta.url);
|
|
13
|
-
var __dirname = path.dirname(__filename);
|
|
14
|
-
function isDev() {
|
|
15
|
-
const candidates = [
|
|
16
|
-
path.join(__dirname, "env.json"),
|
|
17
|
-
path.join(__dirname, "..", "env.json")
|
|
18
|
-
];
|
|
19
|
-
for (const envFile of candidates) {
|
|
20
|
-
try {
|
|
21
|
-
const data = JSON.parse(fs.readFileSync(envFile, "utf-8"));
|
|
22
|
-
return data.env === "development";
|
|
23
|
-
} catch {
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
return false;
|
|
27
|
-
}
|
|
28
|
-
function resolveConfigDir() {
|
|
29
|
-
if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;
|
|
30
|
-
const base = path.join(os.homedir(), ".jarvis");
|
|
31
|
-
return isDev() ? path.join(base, "dev") : base;
|
|
32
|
-
}
|
|
33
64
|
function configDir() {
|
|
34
|
-
|
|
65
|
+
if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;
|
|
66
|
+
return path.join(os.homedir(), ".jarvis");
|
|
35
67
|
}
|
|
36
68
|
function getHooksDir() {
|
|
37
69
|
return path.join(configDir(), "hooks");
|
|
@@ -39,9 +71,9 @@ function getHooksDir() {
|
|
|
39
71
|
|
|
40
72
|
// src/hooks/drop.ts
|
|
41
73
|
async function appendDrop(req) {
|
|
42
|
-
if (!req.sessionId || !req.
|
|
74
|
+
if (!req.sessionId || !req.type || !req.uniqId) {
|
|
43
75
|
process.stderr.write(
|
|
44
|
-
`[hook] skip ${req.
|
|
76
|
+
`[hook] skip ${req.type ?? "?"} missing field sessionId=${!!req.sessionId} uniqId=${!!req.uniqId}
|
|
45
77
|
`
|
|
46
78
|
);
|
|
47
79
|
return;
|
|
@@ -52,17 +84,17 @@ async function appendDrop(req) {
|
|
|
52
84
|
`);
|
|
53
85
|
});
|
|
54
86
|
const envelope = {
|
|
55
|
-
|
|
87
|
+
type: req.type,
|
|
56
88
|
sessionId: req.sessionId,
|
|
57
89
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
58
90
|
uniqId: req.uniqId,
|
|
59
91
|
data: req.data
|
|
60
92
|
};
|
|
61
|
-
const file =
|
|
93
|
+
const file = join2(dir, `${req.sessionId}.jsonl`);
|
|
62
94
|
try {
|
|
63
95
|
await appendFile(file, JSON.stringify(envelope) + "\n");
|
|
64
96
|
process.stderr.write(
|
|
65
|
-
`[hook] ${req.
|
|
97
|
+
`[hook] ${req.type} appended sessionId=${req.sessionId} uniqId=${req.uniqId}
|
|
66
98
|
`
|
|
67
99
|
);
|
|
68
100
|
} catch (err) {
|
|
@@ -89,21 +121,24 @@ function installHookTimeout(ms = 750) {
|
|
|
89
121
|
}
|
|
90
122
|
|
|
91
123
|
// src/hooks/session-start.ts
|
|
92
|
-
installHookTimeout();
|
|
124
|
+
installHookTimeout(8e3);
|
|
93
125
|
async function main() {
|
|
94
126
|
const p = await readHookStdin();
|
|
95
|
-
|
|
96
|
-
const
|
|
127
|
+
const repo = process.env.CLAUDE_PROJECT_DIR ?? p?.cwd ?? process.cwd();
|
|
128
|
+
const block = sessionContext(repo);
|
|
129
|
+
if (block) process.stdout.write(`${block}
|
|
130
|
+
`);
|
|
131
|
+
const sessionId = p?.session_id;
|
|
97
132
|
if (!sessionId) return;
|
|
98
133
|
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
99
|
-
const source = p
|
|
134
|
+
const source = p?.source ?? "startup";
|
|
100
135
|
const data = {
|
|
101
136
|
source,
|
|
102
|
-
...p
|
|
103
|
-
...p
|
|
137
|
+
...p?.transcript_path ? { transcriptPath: p.transcript_path } : {},
|
|
138
|
+
...p?.cwd ? { cwd: p.cwd } : {}
|
|
104
139
|
};
|
|
105
140
|
await appendDrop({
|
|
106
|
-
|
|
141
|
+
type: "session-start",
|
|
107
142
|
sessionId,
|
|
108
143
|
// ts-based uniqId — SessionStart can fire multiple times per session
|
|
109
144
|
// over its lifetime (e.g. one `startup` then later `resume`).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/drop.ts","../../src/config.ts","../../src/hooks/session-start.ts"],"sourcesContent":["/**\n * Shared helpers for CC hook scripts.\n *\n * Each hook script (pre-tool-use, session-start, stop, …) is a tiny\n * stdin → append-line → exit binary. They all write to the same per-\n * session JSONL at `<hooksDir>/<sessionId>.jsonl`. This module\n * concentrates the envelope shape and the atomic append so the per-\n * hook scripts stay <30 lines each.\n *\n * Hot-path constraints: NEVER block, NEVER network, NEVER read user\n * input. Pure stdin parse + filesystem append + exit. Worst-case one\n * `mkdir` + one `appendFile` per fire.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { getHooksDir } from \"../config\";\n\n/** Wire-format envelope written one-per-line to the hook JSONL.\n * The watcher in `sessions.ts` parses this exact shape — keep in sync. */\nexport interface HookDropEnvelope<TData = unknown> {\n kind: string;\n sessionId: string;\n ts: string;\n /** Idempotency key. Lets the watcher's replay-on-restart skip drops\n * whose effects were already emitted (see `HookCursor.applied`). */\n uniqId: string;\n data: TData;\n}\n\nexport interface AppendDropRequest<TData> {\n kind: string;\n sessionId: string;\n uniqId: string;\n data: TData;\n}\n\n/** Append one envelope line to the per-session hook JSONL. Atomic between\n * hook processes via POSIX `O_APPEND` (Node's `fs.appendFile`) — concurrent\n * appends from different CC sessions / hook kinds can't interleave bytes\n * within a line as long as the line stays < `PIPE_BUF` (4KB). Drops are\n * <1KB in practice, so this is safe without locks.\n *\n * Stderr logs are written so `tail -f ~/.jarvis[/dev]/hooks/hook.log` (when\n * CC pipes hook stderr there, which it does by default) shows what fired.\n * Stderr never breaks CC — it only watches stdout for decision JSON. */\nexport async function appendDrop<TData>(req: AppendDropRequest<TData>): Promise<void> {\n if (!req.sessionId || !req.kind || !req.uniqId) {\n process.stderr.write(\n `[hook] skip ${req.kind ?? \"?\"} missing field ` +\n `sessionId=${!!req.sessionId} uniqId=${!!req.uniqId}\\n`,\n );\n return;\n }\n const dir = getHooksDir();\n await mkdir(dir, { recursive: true }).catch((err) => {\n process.stderr.write(`[hook] mkdir failed ${dir}: ${err}\\n`);\n });\n const envelope: HookDropEnvelope<TData> = {\n kind: req.kind,\n sessionId: req.sessionId,\n ts: new Date().toISOString(),\n uniqId: req.uniqId,\n data: req.data,\n };\n const file = join(dir, `${req.sessionId}.jsonl`);\n try {\n await appendFile(file, JSON.stringify(envelope) + \"\\n\");\n process.stderr.write(\n `[hook] ${req.kind} appended sessionId=${req.sessionId} uniqId=${req.uniqId}\\n`,\n );\n } catch (err) {\n process.stderr.write(`[hook] append failed ${file}: ${err}\\n`);\n }\n}\n\n/** Read CC's hook payload from stdin. Returns `null` on parse failure\n * (never throws — the hook must never block CC). */\nexport async function readHookStdin<T = Record<string, unknown>>(): Promise<T | null> {\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n if (!raw) return null;\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\n/** Hard cap any hook so an exotic stdin stall can't pile up forever\n * before CC's terminal prompt fires. We exit 0 with no output → CC\n * proceeds with its normal permission flow. */\nexport function installHookTimeout(ms = 750): void {\n const timer = setTimeout(() => process.exit(0), ms);\n timer.unref();\n}\n","/**\n * Agent Config\n *\n * Manages ~/.jarvis/config.json — saved by `jarvis connect <token>`,\n * read on `jarvis start`.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport os from \"os\";\nimport { fileURLToPath } from \"url\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface AgentConfig {\n /** Cloud WS API URL (from connect token) */\n apiUrl?: string;\n /** JWT auth token (from connect token) */\n token?: string;\n /** Long-lived refresh token for obtaining new access tokens */\n refreshToken?: string;\n /** User ID */\n userId: string;\n /** Environment ID */\n envId?: string;\n /** Workspace root path for repo operations */\n workspacePath?: string;\n /** Web app URL for browser-based auth */\n appUrl?: string;\n /** Anthropic API key (for local-only use without cloud) */\n anthropicApiKey?: string;\n /** Use Anthropic subscription instead of API key */\n useSubscription?: boolean;\n /** When the config was last updated */\n connectedAt?: string;\n}\n\nexport interface ConnectToken {\n apiUrl: string;\n jwt: string;\n refreshToken: string;\n userId: string;\n envId: string;\n}\n\n// =============================================================================\n// Paths\n// =============================================================================\n\n// =============================================================================\n// Environment (single source of truth)\n// =============================================================================\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n/** Single source of truth for dev vs prod.\n * Two locations, picked by which file is shipped:\n * Dev: apps/cli/env.json (committed, `{ \"env\": \"development\" }`)\n * Prod: apps/cli/dist/env.json (written by tsup build, `{ \"env\": \"production\" }`)\n * We try the prod-style sibling first (next to bin.js when bundled), then fall\n * back to the dev-style parent path (one up from src/config.ts). The prod bundle\n * has no `..` parent env.json, and the dev source tree has no sibling env.json,\n * so the two never collide. Safe default if neither exists: prod. */\nexport function isDev(): boolean {\n const candidates = [\n path.join(__dirname, \"env.json\"),\n path.join(__dirname, \"..\", \"env.json\"),\n ];\n for (const envFile of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(envFile, \"utf-8\"));\n return data.env === \"development\";\n } catch {\n /* try next candidate */\n }\n }\n return false;\n}\n\nconst PROD_APP_URL = \"https://jarvis.appchy.com\";\nconst DEV_APP_URL = \"http://localhost:3000\";\n\nconst PROD_WS_URL = \"wss://jarvis.appchy.com/ws\";\nconst DEV_WS_URL = \"ws://localhost:7863\";\n\n/** App URL for the current environment. */\nexport function getDefaultAppUrl(): string {\n return isDev() ? (process.env.APP_URL || DEV_APP_URL) : PROD_APP_URL;\n}\n\n/** WS hub URL for the current environment. Hardcoded per build so the prod\n * binary can never subscribe to the dev hub (or vice versa) regardless of\n * what's stored in `config.apiUrl`. Dev permits a `JARVIS_UPSTREAM_URL`\n * override for tests/CI on a non-default port; prod has no escape hatch. */\nexport function getDefaultWsUrl(): string {\n return isDev() ? (process.env.JARVIS_UPSTREAM_URL || DEV_WS_URL) : PROD_WS_URL;\n}\n\n// =============================================================================\n// Config directory\n// =============================================================================\n\n/** Determine config directory.\n * - JARVIS_CONFIG_DIR env var takes priority (escape hatch for CI/testing)\n * - dev → ~/.jarvis/dev/\n * - prod → ~/.jarvis/\n *\n * Called fresh on every read so test environments that set\n * `JARVIS_CONFIG_DIR` AFTER module load still see the override — caching\n * the value at module init would lock tests onto the host's real\n * `~/.jarvis/dev/` and leak production state into the in-memory infra. */\nfunction resolveConfigDir(): string {\n if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;\n const base = path.join(os.homedir(), \".jarvis\");\n return isDev() ? path.join(base, \"dev\") : base;\n}\n\nfunction configDir(): string {\n return resolveConfigDir();\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\n/** Absolute path to the per-daemon config directory.\n * `prod` → `~/.jarvis/`, `dev` → `~/.jarvis/dev/`. */\nexport function getConfigDir(): string {\n return configDir();\n}\n\n/** Per-daemon directory for PreToolUse hook drop files. The CC hook script\n * writes `<sessionId>/<toolUseId>.json` here; the sessions watcher consumes\n * them. Prod and dev daemons each own their own subtree so a hook installed\n * for one never feeds the other. */\nexport function getHooksDir(): string {\n return path.join(configDir(), \"hooks\");\n}\n\n// =============================================================================\n// Operations\n// =============================================================================\n\nexport function loadConfig(): AgentConfig | null {\n try {\n const raw = fs.readFileSync(configFile(), \"utf-8\");\n return JSON.parse(raw) as AgentConfig;\n } catch {\n return null;\n }\n}\n\nexport function saveConfig(config: AgentConfig): void {\n fs.mkdirSync(configDir(), { recursive: true });\n fs.writeFileSync(configFile(), JSON.stringify(config, null, 2) + \"\\n\");\n}\n\nexport function clearConfig(): void {\n try {\n fs.unlinkSync(configFile());\n } catch {}\n}\n\nexport function parseConnectToken(token: string): ConnectToken {\n try {\n const decoded = Buffer.from(token, \"base64\").toString(\"utf-8\");\n const parsed = JSON.parse(decoded);\n if (!parsed.apiUrl || !parsed.jwt || !parsed.userId) {\n throw new Error(\"Invalid token: missing required fields (apiUrl, jwt, userId)\");\n }\n return parsed as ConnectToken;\n } catch (err) {\n if (err instanceof SyntaxError) {\n throw new Error(\"Invalid token: not valid base64-encoded JSON\");\n }\n throw err;\n }\n}\n\nexport function getConfigPath(): string {\n return configFile();\n}\n","/**\n * SessionStart hook — drops an envelope when CC starts/resumes a session.\n *\n * Used by the daemon to surface new external CC sessions in web/mobile\n * before CC's JSONL has been fully parsed — eliminating the chokidar\n * parse latency for fresh sessions.\n */\n\nimport { appendDrop, installHookTimeout, readHookStdin } from \"./drop\";\n\ninterface CcSessionStartInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n /** \"startup\" (fresh CLI), \"resume\" (--resume <id>), \"clear\" (/clear). */\n source?: string;\n}\n\ninterface SessionStartDropData {\n source: string;\n transcriptPath?: string;\n cwd?: string;\n}\n\ninstallHookTimeout();\n\nasync function main(): Promise<void> {\n const p = await readHookStdin<CcSessionStartInput>();\n if (!p) return;\n const sessionId = p.session_id;\n if (!sessionId) return;\n\n const ts = new Date().toISOString();\n const source = p.source ?? \"startup\";\n const data: SessionStartDropData = {\n source,\n ...(p.transcript_path ? { transcriptPath: p.transcript_path } : {}),\n ...(p.cwd ? { cwd: p.cwd } : {}),\n };\n\n await appendDrop<SessionStartDropData>({\n kind: \"session-start\",\n sessionId,\n // ts-based uniqId — SessionStart can fire multiple times per session\n // over its lifetime (e.g. one `startup` then later `resume`).\n uniqId: `session-start-${ts}`,\n data,\n });\n}\n\nvoid main().finally(() => process.exit(0));\n"],"mappings":";;;AAcA,SAAS,YAAY,aAAa;AAClC,SAAS,YAAY;;;ACRrB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AA6C9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,KAAK,QAAQ,UAAU;AAUlC,SAAS,QAAiB;AAC/B,QAAM,aAAa;AAAA,IACjB,KAAK,KAAK,WAAW,UAAU;AAAA,IAC/B,KAAK,KAAK,WAAW,MAAM,UAAU;AAAA,EACvC;AACA,aAAW,WAAW,YAAY;AAChC,QAAI;AACF,YAAM,OAAO,KAAK,MAAM,GAAG,aAAa,SAAS,OAAO,CAAC;AACzD,aAAO,KAAK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AQ,OAAO,MAAM,wBAAwB,IAAI,KAAK,GAAG;AAAA,CAAI;AAAA,EAC/D;AACF;AAIA,eAAsB,gBAAgE;AACpF,MAAI;AACF,UAAM,SAAmB,CAAC;AAC1B,qBAAiB,SAAS,QAAQ,OAAO;AACvC,aAAO,KAAK,OAAO,UAAU,WAAW,OAAO,KAAK,KAAK,IAAI,KAAK;AAAA,IACpE;AACA,UAAM,MAAM,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO;AAClD,QAAI,CAAC,IAAK,QAAO;AACjB,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAKO,SAAS,mBAAmB,KAAK,KAAW;AACjD,QAAM,QAAQ,WAAW,MAAM,QAAQ,KAAK,CAAC,GAAG,EAAE;AAClD,QAAM,MAAM;AACd;;;AE3EA,mBAAmB;AAEnB,eAAe,OAAsB;AACnC,QAAM,IAAI,MAAM,cAAmC;AACnD,MAAI,CAAC,EAAG;AACR,QAAM,YAAY,EAAE;AACpB,MAAI,CAAC,UAAW;AAEhB,QAAM,MAAK,oBAAI,KAAK,GAAE,YAAY;AAClC,QAAM,SAAS,EAAE,UAAU;AAC3B,QAAM,OAA6B;AAAA,IACjC;AAAA,IACA,GAAI,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,gBAAgB,IAAI,CAAC;AAAA,IACjE,GAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC;AAAA,EAChC;AAEA,QAAM,WAAiC;AAAA,IACrC,MAAM;AAAA,IACN;AAAA;AAAA;AAAA,IAGA,QAAQ,iBAAiB,EAAE;AAAA,IAC3B;AAAA,EACF,CAAC;AACH;AAEA,KAAK,KAAK,EAAE,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/harness.ts","../../src/hooks/drop.ts","../../src/config.ts","../../src/hooks/session-start.ts"],"sourcesContent":["/**\n * The work harness — where it ships, and what runs it.\n *\n * The harness owns the `work/` tree's invariants: bucket-is-status, tier derivation,\n * the id allocator and the completion gate. It used to live in a Claude Code plugin,\n * which made every write to the board require one vendor's plugin to be installed —\n * so an agent that speaks MCP but is not Claude Code could read the board and could\n * not touch it. It ships inside this package now, and `jarvis work` is the one door\n * onto it.\n *\n * It is Python, and this file is the whole of what Node needs to know about that: a\n * payload directory and an interpreter. Either can be missing, and a missing one is\n * REPORTED — `harness()` still answers, so a board stays readable and a write fails\n * where writes fail. What must not happen is what used to: a raw shell error, several\n * calls after the point where anything could be done about it.\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** The entry inside the payload. */\nconst ENTRY = join(\"harness\", \"work.py\");\n\n/** Interpreters to try, in order. Both names, because a machine that has Python\n * under only one of them is common enough that failing on it would be a bug. */\nconst INTERPRETERS = [\"python3\", \"python\"] as const;\n\n/**\n * The oldest Python the payload runs on, proven by running its own suite there.\n *\n * 3.9 rather than something newer on purpose: it is what macOS ships at\n * `/usr/bin/python3`, and therefore what a machine with nothing installed actually\n * has — which is precisely the machine this whole arrangement exists to serve. Two\n * annotations in the payload had to go to keep it, and that was the cheaper side of\n * the trade by a wide margin.\n */\nconst OLDEST = [3, 9] as const;\n\n/** How to run the harness: argv, up to but not including its subcommand. */\nexport type Harness = [command: string, ...args: string[]];\n\n/** What a consumer outside this repo has on its PATH, and the honest thing to\n * attempt when the payload cannot be resolved from here. */\nconst INSTALLED: Harness = [\"jarvis\", \"work\"];\n\n/**\n * The payload's entry script, or null when this build does not carry one.\n *\n * Resolved by walking up from this module rather than from `process.argv`, because\n * the answer must not depend on how the process was started: `tsx src/bin.ts`, the\n * bundled `dist/bin.js` and a re-spawned daemon all sit at different depths under\n * the same package root, and all three have to find the same files.\n */\nexport function payload(): string | null {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let up = 0; up < 6; up++) {\n if (existsSync(join(dir, ENTRY))) return join(dir, ENTRY);\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** The first interpreter on PATH new enough to run the payload, else null. */\nexport function interpreter(): string | null {\n for (const name of INTERPRETERS) {\n // The VERSION, not just an exit code. A name can exist on PATH as a stub that is\n // not a working interpreter — which is what macOS has until the command line\n // tools are installed — and an interpreter too old to parse the payload fails\n // with a traceback from inside it, which is the shape of error this whole file\n // exists to replace.\n const said = spawnSync(name, [\"--version\"], { encoding: \"utf-8\" });\n if (said.status !== 0) continue;\n const version = /(\\d+)\\.(\\d+)/.exec(`${said.stdout}${said.stderr}`);\n if (!version) continue;\n const [major, minor] = [Number(version[1]), Number(version[2])];\n if (major > OLDEST[0] || (major === OLDEST[0] && minor >= OLDEST[1])) return name;\n }\n return null;\n}\n\n/**\n * Why the harness cannot be reached from here, or null when it can.\n *\n * Phrased as what to do about it. `jarvis serve` reports this at startup, so it is\n * read by somebody who has just pointed an agent at their repo and has no other clue\n * that the board is about to refuse every write.\n */\nexport function harnessProblem(): string | null {\n if (!payload()) {\n return (\n \"this jarvis build carries no work harness — the board can be read but not \" +\n \"changed. Reinstall with `npm i -g @appchy/jarvis`.\"\n );\n }\n if (!interpreter()) {\n return (\n `the work harness needs Python ${OLDEST[0]}.${OLDEST[1]} or newer and this ` +\n \"machine has none on its PATH — the board can be read but not changed. \" +\n \"Install it, then try again.\"\n );\n }\n return null;\n}\n\n/**\n * How to run the harness.\n *\n * Never throws. A board whose harness is unreachable is still a board worth reading,\n * and refusing to build one would take the reads down with the writes; the caller\n * that needs to know asks `harnessProblem()`. The fallback names what a consumer\n * outside this repo actually has, so the failure a caller meets is a missing command\n * rather than a missing file.\n */\nexport function harness(): Harness {\n const script = payload();\n const python = interpreter();\n return script && python ? [python, script] : INSTALLED;\n}\n\n/**\n * The block a session opens with, for the repo at `repo` — or null when there is none.\n *\n * The harness composes every byte of it from that repo's own config: the board, its\n * standards, the decisions it has already taken, what each release is for. Nothing here\n * adds a word, and no caller of this may either — several doors serve these bytes now,\n * and a sentence any one of them typed itself is a sentence they could disagree about.\n *\n * **It never throws and never reports its own failure**, which is unlike everything else\n * in this file. Its first caller is a `SessionStart` hook: a message there greets somebody\n * with an error before they have typed anything, and a missing block is a far smaller harm\n * than a session that opens broken. A caller with somewhere to put a diagnosis asks\n * `harnessProblem()` for one.\n */\nexport function sessionContext(repo: string): string | null {\n return say([\"context\", \"--project\", repo]);\n}\n\n/**\n * The METHOD in full — how work is done here, on request.\n *\n * Split from {@link sessionContext} rather than folded into it, because the two are\n * asked at different moments and cost two orders of magnitude apart: the block a\n * session opens with is ~670 tokens of derived fact, and this is ~11,000 of prose. One\n * reader still, so a session cannot end up having read a different method than the\n * block told it to go and read.\n */\nexport function sessionMethod(repo: string): string | null {\n return say([\"method\", \"--project\", repo]);\n}\n\nexport interface EditContextRequest {\n repo: string;\n /** Repo-relative path the session is about to write. */\n file: string;\n /** Absent means the harness stays silent: it cannot promise once without one. */\n sessionId?: string;\n}\n\n/**\n * What a session must be told now that it is about to write this file — or null.\n *\n * The judgements no gate can catch, on the first write of a session, and which part of\n * the code it has walked into, the first time it writes under one. Both are the\n * harness's to word and to ration; this hands over a file and a session id and nothing\n * else, the same split {@link wrapReminder} uses.\n *\n * Never throws, for the reason {@link sessionContext} does not: its caller is a hook\n * firing before somebody's edit, and a hook that fails loudly interrupts them to report\n * a problem with a reminder.\n */\nexport function editContext(req: EditContextRequest): string | null {\n if (!req.file || !req.sessionId) return null;\n // Tighter than the shared ceiling: this one fires before somebody's edit, and a\n // rule that arrives seconds after the file was written has already missed.\n return say(\n [\"applies\", \"--file\", req.file, \"--project\", req.repo, \"--session\", req.sessionId],\n 2_000,\n );\n}\n\n/**\n * Everything a machine knows about finishing this session cleanly, for `repo` — or null\n * when the harness cannot answer.\n *\n * It writes nothing. What comes back is what only a machine can say: work that is not\n * in git, items the board still says somebody is on, the descriptions of the world this\n * run changed, what the tree disagrees with itself about, and the derived prompt that\n * opens the next session. The prose is the agent's to write, because a handoff is\n * judgement and a generated one reads as considered while being wrong.\n */\nexport function wrapBrief(repo: string): string | null {\n return say([\"wrap\", \"--project\", repo]);\n}\n\nexport interface WrapReminderRequest {\n repo: string;\n /** Tokens the session is holding right now. Zero or less means unknown. */\n used: number;\n sessionId?: string;\n}\n\nexport interface WrapReminderResponse {\n /** One line, for a surface that shows the reader a notice. */\n headline: string;\n /** The whole reminder, for the agent to act on. */\n note: string;\n}\n\n/**\n * Whether a session this full should be wrapping up, and what that means in `repo`.\n * Null when it should not, or when nothing can be said with confidence.\n *\n * **The measurement is the caller's and the judgement is the harness's**, and the\n * split is not arbitrary. How many tokens a session is holding is a thing only its\n * own client can answer, and every client answers it differently — while the\n * threshold, the wording, the once-a-session rule and whatever the repo adds are the\n * same whoever is asking. So this hands over a number, and a harness command that\n * took one vendor's log file is a harness that works for one vendor.\n *\n * Never throws, for the same reason {@link sessionContext} does not: its caller is a\n * hook, and a hook that fails loudly interrupts somebody mid-thought to report a\n * problem with a reminder.\n */\nexport function wrapReminder(req: WrapReminderRequest): WrapReminderResponse | null {\n if (!(req.used > 0)) return null;\n const said = say([\n \"remind\",\n \"--used\",\n String(req.used),\n \"--project\",\n req.repo,\n ...(req.sessionId ? [\"--session\", req.sessionId] : []),\n ]);\n if (!said) return null;\n try {\n const parsed = JSON.parse(said) as Partial<WrapReminderResponse>;\n if (!parsed.headline || !parsed.note) return null;\n return { headline: parsed.headline, note: parsed.note };\n } catch {\n return null;\n }\n}\n\n/**\n * How long a harness call may take before it is killed and read as \"no answer\".\n *\n * **Every caller here is a hook, and `installHookTimeout` cannot save one of them.**\n * That watchdog is a `setTimeout`, and a timer does not fire while a synchronous\n * `spawnSync` holds the thread — so an interpreter that is slow to start (a loaded\n * machine, a scanner intercepting the spawn, a repo on a network mount) blocks the\n * session for as long as it likes, past any ceiling the hook believes it set. The\n * bound has to be on the spawn itself. Generous, because being killed mid-answer is\n * the one failure worse than being slow.\n */\nconst PATIENCE = 10_000;\n\n/** What the harness said, or null — for a caller with nowhere to put a failure. */\nfunction say(args: string[], timeout = PATIENCE): string | null {\n try {\n const [command, ...prefix] = harness();\n const ran = spawnSync(command, [...prefix, ...args], {\n encoding: \"utf-8\",\n timeout,\n env: { ...process.env, PYTHONDONTWRITEBYTECODE: \"1\" },\n });\n // A killed child leaves a non-zero status (or none at all), so the timeout reads\n // as every other failure does: no answer, and nothing said about it.\n if (ran.status !== 0) return null;\n return ran.stdout.trim() ? ran.stdout.trimEnd() : null;\n } catch {\n return null;\n }\n}\n","/**\n * Shared helpers for CC hook scripts.\n *\n * Each hook script (pre-tool-use, session-start, stop, …) is a tiny\n * stdin → append-line → exit binary. They all write to the same per-\n * session JSONL at `<hooksDir>/<sessionId>.jsonl`. This module\n * concentrates the envelope shape and the atomic append so the per-\n * hook scripts stay <30 lines each.\n *\n * Hot-path constraints: NEVER block, NEVER network, NEVER read user\n * input. Pure stdin parse + filesystem append + exit. Worst-case one\n * `mkdir` + one `appendFile` per fire.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { getHooksDir } from \"../config\";\n\n/** Wire-format envelope written one-per-line to the hook JSONL.\n * The watcher in `sessions.ts` parses this exact shape — keep in sync. */\nexport interface HookDropEnvelope<TData = unknown> {\n type: string;\n sessionId: string;\n ts: string;\n /** Idempotency key. Lets the watcher's replay-on-restart skip drops\n * whose effects were already emitted (see `HookCursor.applied`). */\n uniqId: string;\n data: TData;\n}\n\nexport interface AppendDropRequest<TData> {\n type: string;\n sessionId: string;\n uniqId: string;\n data: TData;\n}\n\n/** Append one envelope line to the per-session hook JSONL. Atomic between\n * hook processes via POSIX `O_APPEND` (Node's `fs.appendFile`) — concurrent\n * appends from different CC sessions / hook types can't interleave bytes\n * within a line as long as the line stays < `PIPE_BUF` (4KB). Drops are\n * <1KB in practice, so this is safe without locks.\n *\n * Stderr logs are written so `tail -f ~/.jarvis/hooks/hook.log` (when\n * CC pipes hook stderr there, which it does by default) shows what fired.\n * Stderr never breaks CC — it only watches stdout for decision JSON. */\nexport async function appendDrop<TData>(req: AppendDropRequest<TData>): Promise<void> {\n if (!req.sessionId || !req.type || !req.uniqId) {\n process.stderr.write(\n `[hook] skip ${req.type ?? \"?\"} missing field ` +\n `sessionId=${!!req.sessionId} uniqId=${!!req.uniqId}\\n`,\n );\n return;\n }\n const dir = getHooksDir();\n await mkdir(dir, { recursive: true }).catch((err) => {\n process.stderr.write(`[hook] mkdir failed ${dir}: ${err}\\n`);\n });\n const envelope: HookDropEnvelope<TData> = {\n type: req.type,\n sessionId: req.sessionId,\n ts: new Date().toISOString(),\n uniqId: req.uniqId,\n data: req.data,\n };\n const file = join(dir, `${req.sessionId}.jsonl`);\n try {\n await appendFile(file, JSON.stringify(envelope) + \"\\n\");\n process.stderr.write(\n `[hook] ${req.type} appended sessionId=${req.sessionId} uniqId=${req.uniqId}\\n`,\n );\n } catch (err) {\n process.stderr.write(`[hook] append failed ${file}: ${err}\\n`);\n }\n}\n\n/** Read CC's hook payload from stdin. Returns `null` on parse failure\n * (never throws — the hook must never block CC). */\nexport async function readHookStdin<T = Record<string, unknown>>(): Promise<T | null> {\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n if (!raw) return null;\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\n/** Hard cap any hook so an exotic stdin stall can't pile up forever\n * before CC's terminal prompt fires. We exit 0 with no output → CC\n * proceeds with its normal permission flow. */\nexport function installHookTimeout(ms = 750): void {\n const timer = setTimeout(() => process.exit(0), ms);\n timer.unref();\n}\n","/**\n * Agent Config\n *\n * Manages ~/.jarvis/config.json — saved by `jarvis connect <token>`,\n * read on `jarvis start`.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport os from \"os\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface AgentConfig {\n /** The jarvis this machine joined — the address a person opens in a browser,\n * and what pairing talks to. Ours by default; `jarvis init --url <url>` joins\n * someone else's. */\n url?: string;\n /** WS hub URL this machine dials. Written once, by pairing, from the hub the\n * joined instance named — and never from a flag, an environment variable or\n * any later command. Re-pointing a machine means unpairing it first. */\n hubUrl?: string;\n /** JWT auth token (from connect token) */\n token?: string;\n /** Long-lived refresh token for obtaining new access tokens */\n refreshToken?: string;\n /** User ID */\n userId: string;\n /** Environment ID */\n envId?: string;\n /** Workspace root path for repo operations */\n workspacePath?: string;\n /** Anthropic API key (for local-only use without cloud) */\n anthropicApiKey?: string;\n /** Use Anthropic subscription instead of API key */\n useSubscription?: boolean;\n /** When the config was last updated */\n connectedAt?: string;\n}\n\nexport interface ConnectToken {\n hubUrl: string;\n jwt: string;\n refreshToken: string;\n userId: string;\n envId: string;\n}\n\n// =============================================================================\n// Environment\n// =============================================================================\n\n/** The jarvis a machine pairs with when nothing else is named. Only ever read\n * by pairing: `jarvis init --url <url>` joins someone else's instead, and the\n * hub URL is whatever that instance hands back. */\nexport const DEFAULT_URL = \"https://jarvis.appchy.com\";\n\n// =============================================================================\n// Config directory\n// =============================================================================\n\n/** The config dir is the machine's identity: what it paired as, and therefore\n * which hub it dials. One daemon per dir, so a second identity on the same\n * machine — a storage rig, a localhost instance — is a second dir, named by\n * `JARVIS_CONFIG_DIR`, never a second binary.\n *\n * Called fresh on every read so a test that sets `JARVIS_CONFIG_DIR` AFTER\n * module load still sees the override — caching at module init would lock it\n * onto the host's real `~/.jarvis/` and leak production state into the\n * in-memory infra. */\nfunction configDir(): string {\n if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;\n return path.join(os.homedir(), \".jarvis\");\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\n/** Absolute path to the per-daemon config directory — `~/.jarvis/` unless\n * `JARVIS_CONFIG_DIR` names another. */\nexport function getConfigDir(): string {\n return configDir();\n}\n\n/** Per-daemon directory for PreToolUse hook drop files. The CC hook script\n * writes `<sessionId>/<toolUseId>.json` here; the sessions watcher consumes\n * them. Each daemon owns the subtree under its own config dir, so a hook\n * installed for one never feeds another. */\nexport function getHooksDir(): string {\n return path.join(configDir(), \"hooks\");\n}\n\n// =============================================================================\n// Operations\n// =============================================================================\n\n/** Read the machine's config, accepting the names these two fields used to\n * carry. `appUrl`/`apiUrl` were renamed on 2026-08-15 — `apiUrl` never held an\n * API URL, it held the hub's. A config written before that still loads, and\n * `saveConfig` only ever writes the current names, so a machine heals itself on\n * its next write with nothing to run. Delete this tolerance once no config\n * predating the rename is in use. */\nexport function loadConfig(): AgentConfig | null {\n try {\n const stored = JSON.parse(fs.readFileSync(configFile(), \"utf-8\")) as AgentConfig &\n Partial<{ appUrl: string; apiUrl: string }>;\n const { appUrl, apiUrl, ...config } = stored;\n const url = config.url ?? appUrl;\n const hubUrl = config.hubUrl ?? apiUrl;\n return {\n ...config,\n ...(url !== undefined ? { url } : {}),\n ...(hubUrl !== undefined ? { hubUrl } : {}),\n };\n } catch {\n return null;\n }\n}\n\n/** Persist the machine's config.\n *\n * Refuses to move an already-paired machine to a different hub. A machine that\n * joins the wrong control plane hands it credentials, so re-pointing one is a\n * deliberate act — `jarvis unpair` (which clears the config) and then pair\n * again — rather than something a stale token or a mistyped command can do on\n * its way past. Re-pairing to the same hub is unaffected. */\nexport function saveConfig(config: AgentConfig): void {\n const paired = loadConfig();\n if (paired?.hubUrl && config.hubUrl && config.hubUrl !== paired.hubUrl) {\n throw new Error(\n `This machine is paired with ${paired.hubUrl} and cannot be moved to ${config.hubUrl}.\\n` +\n ` Run 'jarvis unpair' first if you mean to join a different jarvis.`,\n );\n }\n fs.mkdirSync(configDir(), { recursive: true });\n fs.writeFileSync(configFile(), JSON.stringify(config, null, 2) + \"\\n\");\n}\n\nexport function clearConfig(): void {\n try {\n fs.unlinkSync(configFile());\n } catch {}\n}\n\nexport function parseConnectToken(token: string): ConnectToken {\n try {\n const decoded = Buffer.from(token, \"base64\").toString(\"utf-8\");\n const parsed = JSON.parse(decoded);\n if (!parsed.hubUrl || !parsed.jwt || !parsed.userId) {\n throw new Error(\"Invalid token: missing required fields (hubUrl, jwt, userId)\");\n }\n return parsed as ConnectToken;\n } catch (err) {\n if (err instanceof SyntaxError) {\n throw new Error(\"Invalid token: not valid base64-encoded JSON\");\n }\n throw err;\n }\n}\n\nexport function getConfigPath(): string {\n return configFile();\n}\n","/**\n * SessionStart hook — two jobs, and neither may cost the other.\n *\n * It PRINTS the standing obligations for the repo the session is opening in, and it\n * drops an envelope the daemon uses to surface new external CC sessions in web/mobile\n * before CC's JSONL has been fully parsed — eliminating the chokidar parse latency for\n * fresh sessions.\n *\n * The print used to belong to a Claude Code plugin, which meant the one surface a\n * session cannot skip was the one surface that required a plugin. It moved here so the\n * plugin can go.\n *\n * **The print is not conditional on anything the envelope needs.** A payload with no\n * session id still gets the block, and so does one that fails to parse at all: the\n * envelope is a message to a daemon that may not be running, while the block is what\n * the person in front of the terminal is about to work from.\n */\n\nimport { sessionContext } from \"../harness\";\nimport { appendDrop, installHookTimeout, readHookStdin } from \"./drop\";\n\ninterface CcSessionStartInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n /** \"startup\" (fresh CLI), \"resume\" (--resume <id>), \"clear\" (/clear), \"compact\". */\n source?: string;\n}\n\ninterface SessionStartDropData {\n source: string;\n transcriptPath?: string;\n cwd?: string;\n}\n\n// Longer than the other hooks', because here the deadline can cost something. The\n// watchdog exits 0 with no output, and for this hook no output is a session opening\n// with no standards, no board and no method — so it is set to outlast the harness\n// (~0.4s on a warm repo) rather than to the reflex of a hook that only appends a line.\ninstallHookTimeout(8_000);\n\nasync function main(): Promise<void> {\n const p = await readHookStdin<CcSessionStartInput>();\n\n // Read from the environment first: CC sets it to the project ROOT, while `cwd` is\n // wherever the session happens to have been opened, which may be a subdirectory with\n // no config of its own.\n const repo = process.env.CLAUDE_PROJECT_DIR ?? p?.cwd ?? process.cwd();\n const block = sessionContext(repo);\n if (block) process.stdout.write(`${block}\\n`);\n\n const sessionId = p?.session_id;\n if (!sessionId) return;\n\n const ts = new Date().toISOString();\n const source = p?.source ?? \"startup\";\n const data: SessionStartDropData = {\n source,\n ...(p?.transcript_path ? { transcriptPath: p.transcript_path } : {}),\n ...(p?.cwd ? { cwd: p.cwd } : {}),\n };\n\n await appendDrop<SessionStartDropData>({\n type: \"session-start\",\n sessionId,\n // ts-based uniqId — SessionStart can fire multiple times per session\n // over its lifetime (e.g. one `startup` then later `resume`).\n uniqId: `session-start-${ts}`,\n data,\n });\n}\n\nvoid main().finally(() => process.exit(0));\n"],"mappings":";;;AAiBA,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAG9B,IAAM,QAAQ,KAAK,WAAW,SAAS;AAIvC,IAAM,eAAe,CAAC,WAAW,QAAQ;AAWzC,IAAM,SAAS,CAAC,GAAG,CAAC;AAOpB,IAAM,YAAqB,CAAC,UAAU,MAAM;AAUrC,SAAS,UAAyB;AACvC,MAAI,MAAM,QAAQ,cAAc,YAAY,GAAG,CAAC;AAChD,WAAS,KAAK,GAAG,KAAK,GAAG,MAAM;AAC7B,QAAI,WAAW,KAAK,KAAK,KAAK,CAAC,EAAG,QAAO,KAAK,KAAK,KAAK;AACxD,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK;AACpB,UAAM;AAAA,EACR;AACA,SAAO;AACT;AAGO,SAAS,cAA6B;AAC3C,aAAW,QAAQ,cAAc;AAM/B,UAAM,OAAO,UAAU,MAAM,CAAC,WAAW,GAAG,EAAE,UAAU,QAAQ,CAAC;AACjE,QAAI,KAAK,WAAW,EAAG;AACvB,UAAM,UAAU,eAAe,KAAK,GAAG,KAAK,MAAM,GAAG,KAAK,MAAM,EAAE;AAClE,QAAI,CAAC,QAAS;AACd,UAAM,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO,QAAQ,CAAC,C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D,QAAM,MAAM;AACd;;;AE5DA,mBAAmB,GAAK;AAExB,eAAe,OAAsB;AACnC,QAAM,IAAI,MAAM,cAAmC;AAKnD,QAAM,OAAO,QAAQ,IAAI,sBAAsB,GAAG,OAAO,QAAQ,IAAI;AACrE,QAAM,QAAQ,eAAe,IAAI;AACjC,MAAI,MAAO,SAAQ,OAAO,MAAM,GAAG,KAAK;AAAA,CAAI;AAE5C,QAAM,YAAY,GAAG;AACrB,MAAI,CAAC,UAAW;AAEhB,QAAM,MAAK,oBAAI,KAAK,GAAE,YAAY;AAClC,QAAM,SAAS,GAAG,UAAU;AAC5B,QAAM,OAA6B;AAAA,IACjC;AAAA,IACA,GAAI,GAAG,kBAAkB,EAAE,gBAAgB,EAAE,gBAAgB,IAAI,CAAC;AAAA,IAClE,GAAI,GAAG,MAAM,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC;AAAA,EACjC;AAEA,QAAM,WAAiC;AAAA,IACrC,MAAM;AAAA,IACN;AAAA;AAAA;AAAA,IAGA,QAAQ,iBAAiB,EAAE;AAAA,IAC3B;AAAA,EACF,CAAC;AACH;AAEA,KAAK,KAAK,EAAE,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC;","names":["join","join"]}
|
package/dist/hooks/stop.js
CHANGED
|
@@ -1,37 +1,90 @@
|
|
|
1
1
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
2
2
|
|
|
3
|
+
// src/hooks/stop.ts
|
|
4
|
+
import { open } from "fs/promises";
|
|
5
|
+
import { existsSync as existsSync2 } from "fs";
|
|
6
|
+
import { join as join3 } from "path";
|
|
7
|
+
|
|
8
|
+
// src/harness.ts
|
|
9
|
+
import { spawnSync } from "child_process";
|
|
10
|
+
import { existsSync } from "fs";
|
|
11
|
+
import { dirname, join } from "path";
|
|
12
|
+
import { fileURLToPath } from "url";
|
|
13
|
+
var ENTRY = join("harness", "work.py");
|
|
14
|
+
var INTERPRETERS = ["python3", "python"];
|
|
15
|
+
var OLDEST = [3, 9];
|
|
16
|
+
var INSTALLED = ["jarvis", "work"];
|
|
17
|
+
function payload() {
|
|
18
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
19
|
+
for (let up = 0; up < 6; up++) {
|
|
20
|
+
if (existsSync(join(dir, ENTRY))) return join(dir, ENTRY);
|
|
21
|
+
const parent = dirname(dir);
|
|
22
|
+
if (parent === dir) break;
|
|
23
|
+
dir = parent;
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
function interpreter() {
|
|
28
|
+
for (const name of INTERPRETERS) {
|
|
29
|
+
const said = spawnSync(name, ["--version"], { encoding: "utf-8" });
|
|
30
|
+
if (said.status !== 0) continue;
|
|
31
|
+
const version = /(\d+)\.(\d+)/.exec(`${said.stdout}${said.stderr}`);
|
|
32
|
+
if (!version) continue;
|
|
33
|
+
const [major, minor] = [Number(version[1]), Number(version[2])];
|
|
34
|
+
if (major > OLDEST[0] || major === OLDEST[0] && minor >= OLDEST[1]) return name;
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
function harness() {
|
|
39
|
+
const script = payload();
|
|
40
|
+
const python = interpreter();
|
|
41
|
+
return script && python ? [python, script] : INSTALLED;
|
|
42
|
+
}
|
|
43
|
+
function wrapReminder(req) {
|
|
44
|
+
if (!(req.used > 0)) return null;
|
|
45
|
+
const said = say([
|
|
46
|
+
"remind",
|
|
47
|
+
"--used",
|
|
48
|
+
String(req.used),
|
|
49
|
+
"--project",
|
|
50
|
+
req.repo,
|
|
51
|
+
...req.sessionId ? ["--session", req.sessionId] : []
|
|
52
|
+
]);
|
|
53
|
+
if (!said) return null;
|
|
54
|
+
try {
|
|
55
|
+
const parsed = JSON.parse(said);
|
|
56
|
+
if (!parsed.headline || !parsed.note) return null;
|
|
57
|
+
return { headline: parsed.headline, note: parsed.note };
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
var PATIENCE = 1e4;
|
|
63
|
+
function say(args, timeout = PATIENCE) {
|
|
64
|
+
try {
|
|
65
|
+
const [command, ...prefix] = harness();
|
|
66
|
+
const ran = spawnSync(command, [...prefix, ...args], {
|
|
67
|
+
encoding: "utf-8",
|
|
68
|
+
timeout,
|
|
69
|
+
env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" }
|
|
70
|
+
});
|
|
71
|
+
if (ran.status !== 0) return null;
|
|
72
|
+
return ran.stdout.trim() ? ran.stdout.trimEnd() : null;
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
3
78
|
// src/hooks/drop.ts
|
|
4
79
|
import { appendFile, mkdir } from "fs/promises";
|
|
5
|
-
import { join } from "path";
|
|
80
|
+
import { join as join2 } from "path";
|
|
6
81
|
|
|
7
82
|
// src/config.ts
|
|
8
|
-
import fs from "fs";
|
|
9
83
|
import path from "path";
|
|
10
84
|
import os from "os";
|
|
11
|
-
import { fileURLToPath } from "url";
|
|
12
|
-
var __filename = fileURLToPath(import.meta.url);
|
|
13
|
-
var __dirname = path.dirname(__filename);
|
|
14
|
-
function isDev() {
|
|
15
|
-
const candidates = [
|
|
16
|
-
path.join(__dirname, "env.json"),
|
|
17
|
-
path.join(__dirname, "..", "env.json")
|
|
18
|
-
];
|
|
19
|
-
for (const envFile of candidates) {
|
|
20
|
-
try {
|
|
21
|
-
const data = JSON.parse(fs.readFileSync(envFile, "utf-8"));
|
|
22
|
-
return data.env === "development";
|
|
23
|
-
} catch {
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
return false;
|
|
27
|
-
}
|
|
28
|
-
function resolveConfigDir() {
|
|
29
|
-
if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;
|
|
30
|
-
const base = path.join(os.homedir(), ".jarvis");
|
|
31
|
-
return isDev() ? path.join(base, "dev") : base;
|
|
32
|
-
}
|
|
33
85
|
function configDir() {
|
|
34
|
-
|
|
86
|
+
if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;
|
|
87
|
+
return path.join(os.homedir(), ".jarvis");
|
|
35
88
|
}
|
|
36
89
|
function getHooksDir() {
|
|
37
90
|
return path.join(configDir(), "hooks");
|
|
@@ -39,9 +92,9 @@ function getHooksDir() {
|
|
|
39
92
|
|
|
40
93
|
// src/hooks/drop.ts
|
|
41
94
|
async function appendDrop(req) {
|
|
42
|
-
if (!req.sessionId || !req.
|
|
95
|
+
if (!req.sessionId || !req.type || !req.uniqId) {
|
|
43
96
|
process.stderr.write(
|
|
44
|
-
`[hook] skip ${req.
|
|
97
|
+
`[hook] skip ${req.type ?? "?"} missing field sessionId=${!!req.sessionId} uniqId=${!!req.uniqId}
|
|
45
98
|
`
|
|
46
99
|
);
|
|
47
100
|
return;
|
|
@@ -52,17 +105,17 @@ async function appendDrop(req) {
|
|
|
52
105
|
`);
|
|
53
106
|
});
|
|
54
107
|
const envelope = {
|
|
55
|
-
|
|
108
|
+
type: req.type,
|
|
56
109
|
sessionId: req.sessionId,
|
|
57
110
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
58
111
|
uniqId: req.uniqId,
|
|
59
112
|
data: req.data
|
|
60
113
|
};
|
|
61
|
-
const file =
|
|
114
|
+
const file = join2(dir, `${req.sessionId}.jsonl`);
|
|
62
115
|
try {
|
|
63
116
|
await appendFile(file, JSON.stringify(envelope) + "\n");
|
|
64
117
|
process.stderr.write(
|
|
65
|
-
`[hook] ${req.
|
|
118
|
+
`[hook] ${req.type} appended sessionId=${req.sessionId} uniqId=${req.uniqId}
|
|
66
119
|
`
|
|
67
120
|
);
|
|
68
121
|
} catch (err) {
|
|
@@ -89,7 +142,9 @@ function installHookTimeout(ms = 750) {
|
|
|
89
142
|
}
|
|
90
143
|
|
|
91
144
|
// src/hooks/stop.ts
|
|
92
|
-
|
|
145
|
+
var TAIL_BYTES = 256 * 1024;
|
|
146
|
+
var TAIL_MAX = 8 * 1024 * 1024;
|
|
147
|
+
installHookTimeout(5e3);
|
|
93
148
|
async function main() {
|
|
94
149
|
const p = await readHookStdin();
|
|
95
150
|
if (!p) return;
|
|
@@ -102,11 +157,64 @@ async function main() {
|
|
|
102
157
|
...p.cwd ? { cwd: p.cwd } : {}
|
|
103
158
|
};
|
|
104
159
|
await appendDrop({
|
|
105
|
-
|
|
160
|
+
type: "stop",
|
|
106
161
|
sessionId,
|
|
107
162
|
uniqId: `stop-${ts}`,
|
|
108
163
|
data
|
|
109
164
|
});
|
|
165
|
+
await remind(p, sessionId);
|
|
166
|
+
}
|
|
167
|
+
async function remind(p, sessionId) {
|
|
168
|
+
const repo = process.env.CLAUDE_PROJECT_DIR ?? p.cwd;
|
|
169
|
+
if (!repo || !p.transcript_path) return;
|
|
170
|
+
if (!existsSync2(join3(repo, ".claude", "work.config.json"))) return;
|
|
171
|
+
const used = await measureContext(p.transcript_path);
|
|
172
|
+
const said = wrapReminder({ repo, used, sessionId });
|
|
173
|
+
if (!said) return;
|
|
174
|
+
process.stdout.write(
|
|
175
|
+
JSON.stringify({
|
|
176
|
+
systemMessage: said.headline,
|
|
177
|
+
hookSpecificOutput: { hookEventName: "Stop", additionalContext: said.note }
|
|
178
|
+
})
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
async function measureContext(transcript) {
|
|
182
|
+
let handle;
|
|
183
|
+
try {
|
|
184
|
+
handle = await open(transcript, "r");
|
|
185
|
+
const { size } = await handle.stat();
|
|
186
|
+
let want = TAIL_BYTES;
|
|
187
|
+
for (; ; ) {
|
|
188
|
+
const from = Math.max(0, size - want);
|
|
189
|
+
const buffer = Buffer.alloc(Math.min(want, size));
|
|
190
|
+
await handle.read(buffer, 0, buffer.length, from);
|
|
191
|
+
const lines = buffer.toString("utf-8").split("\n");
|
|
192
|
+
if (from > 0) lines.shift();
|
|
193
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
194
|
+
const used = tokensIn(lines[i] ?? "");
|
|
195
|
+
if (used) return used;
|
|
196
|
+
}
|
|
197
|
+
if (from === 0 || want >= TAIL_MAX) return 0;
|
|
198
|
+
want = Math.min(want * 2, TAIL_MAX);
|
|
199
|
+
}
|
|
200
|
+
} catch {
|
|
201
|
+
return 0;
|
|
202
|
+
} finally {
|
|
203
|
+
await handle?.close().catch(() => {
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function tokensIn(line) {
|
|
208
|
+
if (!line.trim()) return 0;
|
|
209
|
+
try {
|
|
210
|
+
const record = JSON.parse(line);
|
|
211
|
+
if (record.isSidechain) return 0;
|
|
212
|
+
const usage = record.message?.usage;
|
|
213
|
+
if (!usage) return 0;
|
|
214
|
+
return (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0);
|
|
215
|
+
} catch {
|
|
216
|
+
return 0;
|
|
217
|
+
}
|
|
110
218
|
}
|
|
111
219
|
void main().finally(() => process.exit(0));
|
|
112
220
|
//# sourceMappingURL=stop.js.map
|
package/dist/hooks/stop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/drop.ts","../../src/config.ts","../../src/hooks/stop.ts"],"sourcesContent":["/**\n * Shared helpers for CC hook scripts.\n *\n * Each hook script (pre-tool-use, session-start, stop, …) is a tiny\n * stdin → append-line → exit binary. They all write to the same per-\n * session JSONL at `<hooksDir>/<sessionId>.jsonl`. This module\n * concentrates the envelope shape and the atomic append so the per-\n * hook scripts stay <30 lines each.\n *\n * Hot-path constraints: NEVER block, NEVER network, NEVER read user\n * input. Pure stdin parse + filesystem append + exit. Worst-case one\n * `mkdir` + one `appendFile` per fire.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { getHooksDir } from \"../config\";\n\n/** Wire-format envelope written one-per-line to the hook JSONL.\n * The watcher in `sessions.ts` parses this exact shape — keep in sync. */\nexport interface HookDropEnvelope<TData = unknown> {\n kind: string;\n sessionId: string;\n ts: string;\n /** Idempotency key. Lets the watcher's replay-on-restart skip drops\n * whose effects were already emitted (see `HookCursor.applied`). */\n uniqId: string;\n data: TData;\n}\n\nexport interface AppendDropRequest<TData> {\n kind: string;\n sessionId: string;\n uniqId: string;\n data: TData;\n}\n\n/** Append one envelope line to the per-session hook JSONL. Atomic between\n * hook processes via POSIX `O_APPEND` (Node's `fs.appendFile`) — concurrent\n * appends from different CC sessions / hook kinds can't interleave bytes\n * within a line as long as the line stays < `PIPE_BUF` (4KB). Drops are\n * <1KB in practice, so this is safe without locks.\n *\n * Stderr logs are written so `tail -f ~/.jarvis[/dev]/hooks/hook.log` (when\n * CC pipes hook stderr there, which it does by default) shows what fired.\n * Stderr never breaks CC — it only watches stdout for decision JSON. */\nexport async function appendDrop<TData>(req: AppendDropRequest<TData>): Promise<void> {\n if (!req.sessionId || !req.kind || !req.uniqId) {\n process.stderr.write(\n `[hook] skip ${req.kind ?? \"?\"} missing field ` +\n `sessionId=${!!req.sessionId} uniqId=${!!req.uniqId}\\n`,\n );\n return;\n }\n const dir = getHooksDir();\n await mkdir(dir, { recursive: true }).catch((err) => {\n process.stderr.write(`[hook] mkdir failed ${dir}: ${err}\\n`);\n });\n const envelope: HookDropEnvelope<TData> = {\n kind: req.kind,\n sessionId: req.sessionId,\n ts: new Date().toISOString(),\n uniqId: req.uniqId,\n data: req.data,\n };\n const file = join(dir, `${req.sessionId}.jsonl`);\n try {\n await appendFile(file, JSON.stringify(envelope) + \"\\n\");\n process.stderr.write(\n `[hook] ${req.kind} appended sessionId=${req.sessionId} uniqId=${req.uniqId}\\n`,\n );\n } catch (err) {\n process.stderr.write(`[hook] append failed ${file}: ${err}\\n`);\n }\n}\n\n/** Read CC's hook payload from stdin. Returns `null` on parse failure\n * (never throws — the hook must never block CC). */\nexport async function readHookStdin<T = Record<string, unknown>>(): Promise<T | null> {\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n if (!raw) return null;\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\n/** Hard cap any hook so an exotic stdin stall can't pile up forever\n * before CC's terminal prompt fires. We exit 0 with no output → CC\n * proceeds with its normal permission flow. */\nexport function installHookTimeout(ms = 750): void {\n const timer = setTimeout(() => process.exit(0), ms);\n timer.unref();\n}\n","/**\n * Agent Config\n *\n * Manages ~/.jarvis/config.json — saved by `jarvis connect <token>`,\n * read on `jarvis start`.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport os from \"os\";\nimport { fileURLToPath } from \"url\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface AgentConfig {\n /** Cloud WS API URL (from connect token) */\n apiUrl?: string;\n /** JWT auth token (from connect token) */\n token?: string;\n /** Long-lived refresh token for obtaining new access tokens */\n refreshToken?: string;\n /** User ID */\n userId: string;\n /** Environment ID */\n envId?: string;\n /** Workspace root path for repo operations */\n workspacePath?: string;\n /** Web app URL for browser-based auth */\n appUrl?: string;\n /** Anthropic API key (for local-only use without cloud) */\n anthropicApiKey?: string;\n /** Use Anthropic subscription instead of API key */\n useSubscription?: boolean;\n /** When the config was last updated */\n connectedAt?: string;\n}\n\nexport interface ConnectToken {\n apiUrl: string;\n jwt: string;\n refreshToken: string;\n userId: string;\n envId: string;\n}\n\n// =============================================================================\n// Paths\n// =============================================================================\n\n// =============================================================================\n// Environment (single source of truth)\n// =============================================================================\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n/** Single source of truth for dev vs prod.\n * Two locations, picked by which file is shipped:\n * Dev: apps/cli/env.json (committed, `{ \"env\": \"development\" }`)\n * Prod: apps/cli/dist/env.json (written by tsup build, `{ \"env\": \"production\" }`)\n * We try the prod-style sibling first (next to bin.js when bundled), then fall\n * back to the dev-style parent path (one up from src/config.ts). The prod bundle\n * has no `..` parent env.json, and the dev source tree has no sibling env.json,\n * so the two never collide. Safe default if neither exists: prod. */\nexport function isDev(): boolean {\n const candidates = [\n path.join(__dirname, \"env.json\"),\n path.join(__dirname, \"..\", \"env.json\"),\n ];\n for (const envFile of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(envFile, \"utf-8\"));\n return data.env === \"development\";\n } catch {\n /* try next candidate */\n }\n }\n return false;\n}\n\nconst PROD_APP_URL = \"https://jarvis.appchy.com\";\nconst DEV_APP_URL = \"http://localhost:3000\";\n\nconst PROD_WS_URL = \"wss://jarvis.appchy.com/ws\";\nconst DEV_WS_URL = \"ws://localhost:7863\";\n\n/** App URL for the current environment. */\nexport function getDefaultAppUrl(): string {\n return isDev() ? (process.env.APP_URL || DEV_APP_URL) : PROD_APP_URL;\n}\n\n/** WS hub URL for the current environment. Hardcoded per build so the prod\n * binary can never subscribe to the dev hub (or vice versa) regardless of\n * what's stored in `config.apiUrl`. Dev permits a `JARVIS_UPSTREAM_URL`\n * override for tests/CI on a non-default port; prod has no escape hatch. */\nexport function getDefaultWsUrl(): string {\n return isDev() ? (process.env.JARVIS_UPSTREAM_URL || DEV_WS_URL) : PROD_WS_URL;\n}\n\n// =============================================================================\n// Config directory\n// =============================================================================\n\n/** Determine config directory.\n * - JARVIS_CONFIG_DIR env var takes priority (escape hatch for CI/testing)\n * - dev → ~/.jarvis/dev/\n * - prod → ~/.jarvis/\n *\n * Called fresh on every read so test environments that set\n * `JARVIS_CONFIG_DIR` AFTER module load still see the override — caching\n * the value at module init would lock tests onto the host's real\n * `~/.jarvis/dev/` and leak production state into the in-memory infra. */\nfunction resolveConfigDir(): string {\n if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;\n const base = path.join(os.homedir(), \".jarvis\");\n return isDev() ? path.join(base, \"dev\") : base;\n}\n\nfunction configDir(): string {\n return resolveConfigDir();\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\n/** Absolute path to the per-daemon config directory.\n * `prod` → `~/.jarvis/`, `dev` → `~/.jarvis/dev/`. */\nexport function getConfigDir(): string {\n return configDir();\n}\n\n/** Per-daemon directory for PreToolUse hook drop files. The CC hook script\n * writes `<sessionId>/<toolUseId>.json` here; the sessions watcher consumes\n * them. Prod and dev daemons each own their own subtree so a hook installed\n * for one never feeds the other. */\nexport function getHooksDir(): string {\n return path.join(configDir(), \"hooks\");\n}\n\n// =============================================================================\n// Operations\n// =============================================================================\n\nexport function loadConfig(): AgentConfig | null {\n try {\n const raw = fs.readFileSync(configFile(), \"utf-8\");\n return JSON.parse(raw) as AgentConfig;\n } catch {\n return null;\n }\n}\n\nexport function saveConfig(config: AgentConfig): void {\n fs.mkdirSync(configDir(), { recursive: true });\n fs.writeFileSync(configFile(), JSON.stringify(config, null, 2) + \"\\n\");\n}\n\nexport function clearConfig(): void {\n try {\n fs.unlinkSync(configFile());\n } catch {}\n}\n\nexport function parseConnectToken(token: string): ConnectToken {\n try {\n const decoded = Buffer.from(token, \"base64\").toString(\"utf-8\");\n const parsed = JSON.parse(decoded);\n if (!parsed.apiUrl || !parsed.jwt || !parsed.userId) {\n throw new Error(\"Invalid token: missing required fields (apiUrl, jwt, userId)\");\n }\n return parsed as ConnectToken;\n } catch (err) {\n if (err instanceof SyntaxError) {\n throw new Error(\"Invalid token: not valid base64-encoded JSON\");\n }\n throw err;\n }\n}\n\nexport function getConfigPath(): string {\n return configFile();\n}\n","/**\n * Stop hook — drops an envelope when CC's main agent finishes responding.\n *\n * Used by the daemon to flip \"thinking…\" indicators off in web/mobile\n * instantly, instead of waiting for CC's JSONL writes to settle and the\n * watcher's debounced tail to fire.\n */\n\nimport { appendDrop, installHookTimeout, readHookStdin } from \"./drop\";\n\ninterface CcStopInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n /** True iff this Stop was triggered by a hook (recursion guard). We\n * forward it so the daemon can ignore self-induced stops if needed. */\n stop_hook_active?: boolean;\n}\n\ninterface StopDropData {\n stopHookActive: boolean;\n transcriptPath?: string;\n cwd?: string;\n}\n\ninstallHookTimeout();\n\nasync function main(): Promise<void> {\n const p = await readHookStdin<CcStopInput>();\n if (!p) return;\n const sessionId = p.session_id;\n if (!sessionId) return;\n\n const ts = new Date().toISOString();\n const data: StopDropData = {\n stopHookActive: !!p.stop_hook_active,\n ...(p.transcript_path ? { transcriptPath: p.transcript_path } : {}),\n ...(p.cwd ? { cwd: p.cwd } : {}),\n };\n\n await appendDrop<StopDropData>({\n kind: \"stop\",\n sessionId,\n uniqId: `stop-${ts}`,\n data,\n });\n}\n\nvoid main().finally(() => process.exit(0));\n"],"mappings":";;;AAcA,SAAS,YAAY,aAAa;AAClC,SAAS,YAAY;;;ACRrB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AA6C9B,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,KAAK,QAAQ,UAAU;AAUlC,SAAS,QAAiB;AAC/B,QAAM,aAAa;AAAA,IACjB,KAAK,KAAK,WAAW,UAAU;AAAA,IAC/B,KAAK,KAAK,WAAW,MAAM,UAAU;AAAA,EACvC;AACA,aAAW,WAAW,YAAY;AAChC,QAAI;AACF,YAAM,OAAO,KAAK,MAAM,GAAG,aAAa,SAAS,OAAO,CAAC;AACzD,aAAO,KAAK,QAAQ;AAAA,IACtB,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;AAkCA,SAAS,mBAA2B;AAClC,MAAI,QAAQ,IAAI,kBAAmB,QAAO,QAAQ,IAAI;AACtD,QAAM,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,SAAS;AAC9C,SAAO,MAAM,IAAI,KAAK,KAAK,MAAM,KAAK,IAAI;AAC5C;AAEA,SAAS,YAAoB;AAC3B,SAAO,iBAAiB;AAC1B;AAgBO,SAAS,cAAsB;AACpC,SAAO,KAAK,KAAK,UAAU,GAAG,OAAO;AACvC;;;AD7FA,eAAsB,WAAkB,KAA8C;AACpF,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AS,mBAAmB,KAAK,KAAW;AACjD,QAAM,QAAQ,WAAW,MAAM,QAAQ,KAAK,CAAC,GAAG,EAAE;AAClD,QAAM,MAAM;AACd;;;AE1EA,mBAAmB;AAEnB,eAAe,OAAsB;AACnC,QAAM,IAAI,MAAM,cAA2B;AAC3C,MAAI,CAAC,EAAG;AACR,QAAM,YAAY,EAAE;AACpB,MAAI,CAAC,UAAW;AAEhB,QAAM,MAAK,oBAAI,KAAK,GAAE,YAAY;AAClC,QAAM,OAAqB;AAAA,IACzB,gBAAgB,CAAC,CAAC,EAAE;AAAA,IACpB,GAAI,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,gBAAgB,IAAI,CAAC;AAAA,IACjE,GAAI,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC;AAAA,EAChC;AAEA,QAAM,WAAyB;AAAA,IAC7B,MAAM;AAAA,IACN;AAAA,IACA,QAAQ,QAAQ,EAAE;AAAA,IAClB;AAAA,EACF,CAAC;AACH;AAEA,KAAK,KAAK,EAAE,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/stop.ts","../../src/harness.ts","../../src/hooks/drop.ts","../../src/config.ts"],"sourcesContent":["/**\n * Stop hook — two jobs, and only one of them is the daemon's.\n *\n * It drops an envelope when CC's main agent finishes responding, which flips\n * \"thinking…\" indicators off in web/mobile instantly instead of waiting for CC's JSONL\n * writes to settle and the watcher's debounced tail to fire. And it REMINDS a session\n * to finish cleanly once it is running out of room — the thing that used to live in a\n * Claude Code plugin, and that the session-opening block promises in every repo.\n *\n * **Why Stop and not PreCompact.** PreCompact is the obvious candidate and cannot do\n * this job: it may only CANCEL a compaction, never hand back an instruction. Stop\n * fires at the end of a turn, carries the transcript path, and is allowed to inject.\n * So the trigger is \"a turn ended and the conversation is large\" rather than\n * \"compaction is imminent\" — which is earlier, and earlier is the whole point.\n *\n * **The measurement is here and the judgement is the harness's.** Reading Claude\n * Code's own transcript is a Claude Code fact, so it happens in Claude Code's corner\n * of the product; the threshold, the wording and the once-a-session rule are the same\n * for every client and live where every client can reach them.\n */\n\nimport { open } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { wrapReminder } from \"../harness\";\nimport { appendDrop, installHookTimeout, readHookStdin } from \"./drop\";\n\ninterface CcStopInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n /** True iff this Stop was triggered by a hook (recursion guard). We\n * forward it so the daemon can ignore self-induced stops if needed. */\n stop_hook_active?: boolean;\n}\n\ninterface StopDropData {\n stopHookActive: boolean;\n transcriptPath?: string;\n cwd?: string;\n}\n\n/** How much of the transcript's tail to read looking for the newest usage record.\n * Transcripts reach tens of megabytes and this runs at the end of every turn, so\n * reading the whole file would tax each one to answer a question the last few lines\n * already settle. Doubles up to the max when a single record is larger than the\n * window — one tool result can exceed a megabyte on its own. */\nconst TAIL_BYTES = 256 * 1024;\nconst TAIL_MAX = 8 * 1024 * 1024;\n\n// Longer than a hook that only appends a line, because this one asks the harness a\n// question. Still far under CC's own limit: the watchdog is here for a stdin that\n// never closes, not to race the work.\ninstallHookTimeout(5_000);\n\nasync function main(): Promise<void> {\n const p = await readHookStdin<CcStopInput>();\n if (!p) return;\n const sessionId = p.session_id;\n if (!sessionId) return;\n\n const ts = new Date().toISOString();\n const data: StopDropData = {\n stopHookActive: !!p.stop_hook_active,\n ...(p.transcript_path ? { transcriptPath: p.transcript_path } : {}),\n ...(p.cwd ? { cwd: p.cwd } : {}),\n };\n\n await appendDrop<StopDropData>({\n type: \"stop\",\n sessionId,\n uniqId: `stop-${ts}`,\n data,\n });\n\n await remind(p, sessionId);\n}\n\nasync function remind(p: CcStopInput, sessionId: string): Promise<void> {\n const repo = process.env.CLAUDE_PROJECT_DIR ?? p.cwd;\n if (!repo || !p.transcript_path) return;\n // A repo that never configured the harness cannot have set a threshold, and asking\n // costs a process at the end of every turn. An existence check, not a read — the\n // harness stays the only thing that parses that file.\n if (!existsSync(join(repo, \".claude\", \"work.config.json\"))) return;\n\n const used = await measureContext(p.transcript_path);\n const said = wrapReminder({ repo, used, sessionId });\n if (!said) return;\n\n process.stdout.write(\n JSON.stringify({\n systemMessage: said.headline,\n hookSpecificOutput: { hookEventName: \"Stop\", additionalContext: said.note },\n }),\n );\n}\n\n/**\n * Tokens the session is holding, from the newest main-chain assistant turn — or 0.\n *\n * **Exact or nothing.** Claude Code records the API's own `usage` on every assistant\n * turn, so the live context is `input + cache_creation + cache_read` off the most\n * recent one: the number the model was actually charged for. Dividing the transcript's\n * file size by four is the tempting alternative and is wrong twice over — the\n * transcript is an append-only log of everything that ever happened, tool output long\n * since dropped from the window included, and it carries JSON framing that is not\n * context at all. Measured on a real session it read 452k where the truth was 277k.\n *\n * Sidechain turns are skipped: a subagent runs in its own window, and counting one\n * reports a context this session never had.\n */\nasync function measureContext(transcript: string): Promise<number> {\n let handle;\n try {\n handle = await open(transcript, \"r\");\n const { size } = await handle.stat();\n let want = TAIL_BYTES;\n for (;;) {\n const from = Math.max(0, size - want);\n const buffer = Buffer.alloc(Math.min(want, size));\n await handle.read(buffer, 0, buffer.length, from);\n const lines = buffer.toString(\"utf-8\").split(\"\\n\");\n // A partial first line is unparseable; drop it unless we hold the whole file.\n if (from > 0) lines.shift();\n for (let i = lines.length - 1; i >= 0; i--) {\n const used = tokensIn(lines[i] ?? \"\");\n if (used) return used;\n }\n if (from === 0 || want >= TAIL_MAX) return 0;\n want = Math.min(want * 2, TAIL_MAX);\n }\n } catch {\n return 0;\n } finally {\n await handle?.close().catch(() => {});\n }\n}\n\nfunction tokensIn(line: string): number {\n if (!line.trim()) return 0;\n try {\n const record = JSON.parse(line) as {\n isSidechain?: boolean;\n message?: { usage?: Record<string, number> };\n };\n if (record.isSidechain) return 0;\n const usage = record.message?.usage;\n if (!usage) return 0;\n return (\n (usage.input_tokens ?? 0) +\n (usage.cache_creation_input_tokens ?? 0) +\n (usage.cache_read_input_tokens ?? 0)\n );\n } catch {\n return 0;\n }\n}\n\nvoid main().finally(() => process.exit(0));\n","/**\n * The work harness — where it ships, and what runs it.\n *\n * The harness owns the `work/` tree's invariants: bucket-is-status, tier derivation,\n * the id allocator and the completion gate. It used to live in a Claude Code plugin,\n * which made every write to the board require one vendor's plugin to be installed —\n * so an agent that speaks MCP but is not Claude Code could read the board and could\n * not touch it. It ships inside this package now, and `jarvis work` is the one door\n * onto it.\n *\n * It is Python, and this file is the whole of what Node needs to know about that: a\n * payload directory and an interpreter. Either can be missing, and a missing one is\n * REPORTED — `harness()` still answers, so a board stays readable and a write fails\n * where writes fail. What must not happen is what used to: a raw shell error, several\n * calls after the point where anything could be done about it.\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** The entry inside the payload. */\nconst ENTRY = join(\"harness\", \"work.py\");\n\n/** Interpreters to try, in order. Both names, because a machine that has Python\n * under only one of them is common enough that failing on it would be a bug. */\nconst INTERPRETERS = [\"python3\", \"python\"] as const;\n\n/**\n * The oldest Python the payload runs on, proven by running its own suite there.\n *\n * 3.9 rather than something newer on purpose: it is what macOS ships at\n * `/usr/bin/python3`, and therefore what a machine with nothing installed actually\n * has — which is precisely the machine this whole arrangement exists to serve. Two\n * annotations in the payload had to go to keep it, and that was the cheaper side of\n * the trade by a wide margin.\n */\nconst OLDEST = [3, 9] as const;\n\n/** How to run the harness: argv, up to but not including its subcommand. */\nexport type Harness = [command: string, ...args: string[]];\n\n/** What a consumer outside this repo has on its PATH, and the honest thing to\n * attempt when the payload cannot be resolved from here. */\nconst INSTALLED: Harness = [\"jarvis\", \"work\"];\n\n/**\n * The payload's entry script, or null when this build does not carry one.\n *\n * Resolved by walking up from this module rather than from `process.argv`, because\n * the answer must not depend on how the process was started: `tsx src/bin.ts`, the\n * bundled `dist/bin.js` and a re-spawned daemon all sit at different depths under\n * the same package root, and all three have to find the same files.\n */\nexport function payload(): string | null {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let up = 0; up < 6; up++) {\n if (existsSync(join(dir, ENTRY))) return join(dir, ENTRY);\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** The first interpreter on PATH new enough to run the payload, else null. */\nexport function interpreter(): string | null {\n for (const name of INTERPRETERS) {\n // The VERSION, not just an exit code. A name can exist on PATH as a stub that is\n // not a working interpreter — which is what macOS has until the command line\n // tools are installed — and an interpreter too old to parse the payload fails\n // with a traceback from inside it, which is the shape of error this whole file\n // exists to replace.\n const said = spawnSync(name, [\"--version\"], { encoding: \"utf-8\" });\n if (said.status !== 0) continue;\n const version = /(\\d+)\\.(\\d+)/.exec(`${said.stdout}${said.stderr}`);\n if (!version) continue;\n const [major, minor] = [Number(version[1]), Number(version[2])];\n if (major > OLDEST[0] || (major === OLDEST[0] && minor >= OLDEST[1])) return name;\n }\n return null;\n}\n\n/**\n * Why the harness cannot be reached from here, or null when it can.\n *\n * Phrased as what to do about it. `jarvis serve` reports this at startup, so it is\n * read by somebody who has just pointed an agent at their repo and has no other clue\n * that the board is about to refuse every write.\n */\nexport function harnessProblem(): string | null {\n if (!payload()) {\n return (\n \"this jarvis build carries no work harness — the board can be read but not \" +\n \"changed. Reinstall with `npm i -g @appchy/jarvis`.\"\n );\n }\n if (!interpreter()) {\n return (\n `the work harness needs Python ${OLDEST[0]}.${OLDEST[1]} or newer and this ` +\n \"machine has none on its PATH — the board can be read but not changed. \" +\n \"Install it, then try again.\"\n );\n }\n return null;\n}\n\n/**\n * How to run the harness.\n *\n * Never throws. A board whose harness is unreachable is still a board worth reading,\n * and refusing to build one would take the reads down with the writes; the caller\n * that needs to know asks `harnessProblem()`. The fallback names what a consumer\n * outside this repo actually has, so the failure a caller meets is a missing command\n * rather than a missing file.\n */\nexport function harness(): Harness {\n const script = payload();\n const python = interpreter();\n return script && python ? [python, script] : INSTALLED;\n}\n\n/**\n * The block a session opens with, for the repo at `repo` — or null when there is none.\n *\n * The harness composes every byte of it from that repo's own config: the board, its\n * standards, the decisions it has already taken, what each release is for. Nothing here\n * adds a word, and no caller of this may either — several doors serve these bytes now,\n * and a sentence any one of them typed itself is a sentence they could disagree about.\n *\n * **It never throws and never reports its own failure**, which is unlike everything else\n * in this file. Its first caller is a `SessionStart` hook: a message there greets somebody\n * with an error before they have typed anything, and a missing block is a far smaller harm\n * than a session that opens broken. A caller with somewhere to put a diagnosis asks\n * `harnessProblem()` for one.\n */\nexport function sessionContext(repo: string): string | null {\n return say([\"context\", \"--project\", repo]);\n}\n\n/**\n * The METHOD in full — how work is done here, on request.\n *\n * Split from {@link sessionContext} rather than folded into it, because the two are\n * asked at different moments and cost two orders of magnitude apart: the block a\n * session opens with is ~670 tokens of derived fact, and this is ~11,000 of prose. One\n * reader still, so a session cannot end up having read a different method than the\n * block told it to go and read.\n */\nexport function sessionMethod(repo: string): string | null {\n return say([\"method\", \"--project\", repo]);\n}\n\nexport interface EditContextRequest {\n repo: string;\n /** Repo-relative path the session is about to write. */\n file: string;\n /** Absent means the harness stays silent: it cannot promise once without one. */\n sessionId?: string;\n}\n\n/**\n * What a session must be told now that it is about to write this file — or null.\n *\n * The judgements no gate can catch, on the first write of a session, and which part of\n * the code it has walked into, the first time it writes under one. Both are the\n * harness's to word and to ration; this hands over a file and a session id and nothing\n * else, the same split {@link wrapReminder} uses.\n *\n * Never throws, for the reason {@link sessionContext} does not: its caller is a hook\n * firing before somebody's edit, and a hook that fails loudly interrupts them to report\n * a problem with a reminder.\n */\nexport function editContext(req: EditContextRequest): string | null {\n if (!req.file || !req.sessionId) return null;\n // Tighter than the shared ceiling: this one fires before somebody's edit, and a\n // rule that arrives seconds after the file was written has already missed.\n return say(\n [\"applies\", \"--file\", req.file, \"--project\", req.repo, \"--session\", req.sessionId],\n 2_000,\n );\n}\n\n/**\n * Everything a machine knows about finishing this session cleanly, for `repo` — or null\n * when the harness cannot answer.\n *\n * It writes nothing. What comes back is what only a machine can say: work that is not\n * in git, items the board still says somebody is on, the descriptions of the world this\n * run changed, what the tree disagrees with itself about, and the derived prompt that\n * opens the next session. The prose is the agent's to write, because a handoff is\n * judgement and a generated one reads as considered while being wrong.\n */\nexport function wrapBrief(repo: string): string | null {\n return say([\"wrap\", \"--project\", repo]);\n}\n\nexport interface WrapReminderRequest {\n repo: string;\n /** Tokens the session is holding right now. Zero or less means unknown. */\n used: number;\n sessionId?: string;\n}\n\nexport interface WrapReminderResponse {\n /** One line, for a surface that shows the reader a notice. */\n headline: string;\n /** The whole reminder, for the agent to act on. */\n note: string;\n}\n\n/**\n * Whether a session this full should be wrapping up, and what that means in `repo`.\n * Null when it should not, or when nothing can be said with confidence.\n *\n * **The measurement is the caller's and the judgement is the harness's**, and the\n * split is not arbitrary. How many tokens a session is holding is a thing only its\n * own client can answer, and every client answers it differently — while the\n * threshold, the wording, the once-a-session rule and whatever the repo adds are the\n * same whoever is asking. So this hands over a number, and a harness command that\n * took one vendor's log file is a harness that works for one vendor.\n *\n * Never throws, for the same reason {@link sessionContext} does not: its caller is a\n * hook, and a hook that fails loudly interrupts somebody mid-thought to report a\n * problem with a reminder.\n */\nexport function wrapReminder(req: WrapReminderRequest): WrapReminderResponse | null {\n if (!(req.used > 0)) return null;\n const said = say([\n \"remind\",\n \"--used\",\n String(req.used),\n \"--project\",\n req.repo,\n ...(req.sessionId ? [\"--session\", req.sessionId] : []),\n ]);\n if (!said) return null;\n try {\n const parsed = JSON.parse(said) as Partial<WrapReminderResponse>;\n if (!parsed.headline || !parsed.note) return null;\n return { headline: parsed.headline, note: parsed.note };\n } catch {\n return null;\n }\n}\n\n/**\n * How long a harness call may take before it is killed and read as \"no answer\".\n *\n * **Every caller here is a hook, and `installHookTimeout` cannot save one of them.**\n * That watchdog is a `setTimeout`, and a timer does not fire while a synchronous\n * `spawnSync` holds the thread — so an interpreter that is slow to start (a loaded\n * machine, a scanner intercepting the spawn, a repo on a network mount) blocks the\n * session for as long as it likes, past any ceiling the hook believes it set. The\n * bound has to be on the spawn itself. Generous, because being killed mid-answer is\n * the one failure worse than being slow.\n */\nconst PATIENCE = 10_000;\n\n/** What the harness said, or null — for a caller with nowhere to put a failure. */\nfunction say(args: string[], timeout = PATIENCE): string | null {\n try {\n const [command, ...prefix] = harness();\n const ran = spawnSync(command, [...prefix, ...args], {\n encoding: \"utf-8\",\n timeout,\n env: { ...process.env, PYTHONDONTWRITEBYTECODE: \"1\" },\n });\n // A killed child leaves a non-zero status (or none at all), so the timeout reads\n // as every other failure does: no answer, and nothing said about it.\n if (ran.status !== 0) return null;\n return ran.stdout.trim() ? ran.stdout.trimEnd() : null;\n } catch {\n return null;\n }\n}\n","/**\n * Shared helpers for CC hook scripts.\n *\n * Each hook script (pre-tool-use, session-start, stop, …) is a tiny\n * stdin → append-line → exit binary. They all write to the same per-\n * session JSONL at `<hooksDir>/<sessionId>.jsonl`. This module\n * concentrates the envelope shape and the atomic append so the per-\n * hook scripts stay <30 lines each.\n *\n * Hot-path constraints: NEVER block, NEVER network, NEVER read user\n * input. Pure stdin parse + filesystem append + exit. Worst-case one\n * `mkdir` + one `appendFile` per fire.\n */\n\nimport { appendFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { getHooksDir } from \"../config\";\n\n/** Wire-format envelope written one-per-line to the hook JSONL.\n * The watcher in `sessions.ts` parses this exact shape — keep in sync. */\nexport interface HookDropEnvelope<TData = unknown> {\n type: string;\n sessionId: string;\n ts: string;\n /** Idempotency key. Lets the watcher's replay-on-restart skip drops\n * whose effects were already emitted (see `HookCursor.applied`). */\n uniqId: string;\n data: TData;\n}\n\nexport interface AppendDropRequest<TData> {\n type: string;\n sessionId: string;\n uniqId: string;\n data: TData;\n}\n\n/** Append one envelope line to the per-session hook JSONL. Atomic between\n * hook processes via POSIX `O_APPEND` (Node's `fs.appendFile`) — concurrent\n * appends from different CC sessions / hook types can't interleave bytes\n * within a line as long as the line stays < `PIPE_BUF` (4KB). Drops are\n * <1KB in practice, so this is safe without locks.\n *\n * Stderr logs are written so `tail -f ~/.jarvis/hooks/hook.log` (when\n * CC pipes hook stderr there, which it does by default) shows what fired.\n * Stderr never breaks CC — it only watches stdout for decision JSON. */\nexport async function appendDrop<TData>(req: AppendDropRequest<TData>): Promise<void> {\n if (!req.sessionId || !req.type || !req.uniqId) {\n process.stderr.write(\n `[hook] skip ${req.type ?? \"?\"} missing field ` +\n `sessionId=${!!req.sessionId} uniqId=${!!req.uniqId}\\n`,\n );\n return;\n }\n const dir = getHooksDir();\n await mkdir(dir, { recursive: true }).catch((err) => {\n process.stderr.write(`[hook] mkdir failed ${dir}: ${err}\\n`);\n });\n const envelope: HookDropEnvelope<TData> = {\n type: req.type,\n sessionId: req.sessionId,\n ts: new Date().toISOString(),\n uniqId: req.uniqId,\n data: req.data,\n };\n const file = join(dir, `${req.sessionId}.jsonl`);\n try {\n await appendFile(file, JSON.stringify(envelope) + \"\\n\");\n process.stderr.write(\n `[hook] ${req.type} appended sessionId=${req.sessionId} uniqId=${req.uniqId}\\n`,\n );\n } catch (err) {\n process.stderr.write(`[hook] append failed ${file}: ${err}\\n`);\n }\n}\n\n/** Read CC's hook payload from stdin. Returns `null` on parse failure\n * (never throws — the hook must never block CC). */\nexport async function readHookStdin<T = Record<string, unknown>>(): Promise<T | null> {\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n if (!raw) return null;\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n}\n\n/** Hard cap any hook so an exotic stdin stall can't pile up forever\n * before CC's terminal prompt fires. We exit 0 with no output → CC\n * proceeds with its normal permission flow. */\nexport function installHookTimeout(ms = 750): void {\n const timer = setTimeout(() => process.exit(0), ms);\n timer.unref();\n}\n","/**\n * Agent Config\n *\n * Manages ~/.jarvis/config.json — saved by `jarvis connect <token>`,\n * read on `jarvis start`.\n */\n\nimport fs from \"fs\";\nimport path from \"path\";\nimport os from \"os\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface AgentConfig {\n /** The jarvis this machine joined — the address a person opens in a browser,\n * and what pairing talks to. Ours by default; `jarvis init --url <url>` joins\n * someone else's. */\n url?: string;\n /** WS hub URL this machine dials. Written once, by pairing, from the hub the\n * joined instance named — and never from a flag, an environment variable or\n * any later command. Re-pointing a machine means unpairing it first. */\n hubUrl?: string;\n /** JWT auth token (from connect token) */\n token?: string;\n /** Long-lived refresh token for obtaining new access tokens */\n refreshToken?: string;\n /** User ID */\n userId: string;\n /** Environment ID */\n envId?: string;\n /** Workspace root path for repo operations */\n workspacePath?: string;\n /** Anthropic API key (for local-only use without cloud) */\n anthropicApiKey?: string;\n /** Use Anthropic subscription instead of API key */\n useSubscription?: boolean;\n /** When the config was last updated */\n connectedAt?: string;\n}\n\nexport interface ConnectToken {\n hubUrl: string;\n jwt: string;\n refreshToken: string;\n userId: string;\n envId: string;\n}\n\n// =============================================================================\n// Environment\n// =============================================================================\n\n/** The jarvis a machine pairs with when nothing else is named. Only ever read\n * by pairing: `jarvis init --url <url>` joins someone else's instead, and the\n * hub URL is whatever that instance hands back. */\nexport const DEFAULT_URL = \"https://jarvis.appchy.com\";\n\n// =============================================================================\n// Config directory\n// =============================================================================\n\n/** The config dir is the machine's identity: what it paired as, and therefore\n * which hub it dials. One daemon per dir, so a second identity on the same\n * machine — a storage rig, a localhost instance — is a second dir, named by\n * `JARVIS_CONFIG_DIR`, never a second binary.\n *\n * Called fresh on every read so a test that sets `JARVIS_CONFIG_DIR` AFTER\n * module load still sees the override — caching at module init would lock it\n * onto the host's real `~/.jarvis/` and leak production state into the\n * in-memory infra. */\nfunction configDir(): string {\n if (process.env.JARVIS_CONFIG_DIR) return process.env.JARVIS_CONFIG_DIR;\n return path.join(os.homedir(), \".jarvis\");\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\n/** Absolute path to the per-daemon config directory — `~/.jarvis/` unless\n * `JARVIS_CONFIG_DIR` names another. */\nexport function getConfigDir(): string {\n return configDir();\n}\n\n/** Per-daemon directory for PreToolUse hook drop files. The CC hook script\n * writes `<sessionId>/<toolUseId>.json` here; the sessions watcher consumes\n * them. Each daemon owns the subtree under its own config dir, so a hook\n * installed for one never feeds another. */\nexport function getHooksDir(): string {\n return path.join(configDir(), \"hooks\");\n}\n\n// =============================================================================\n// Operations\n// =============================================================================\n\n/** Read the machine's config, accepting the names these two fields used to\n * carry. `appUrl`/`apiUrl` were renamed on 2026-08-15 — `apiUrl` never held an\n * API URL, it held the hub's. A config written before that still loads, and\n * `saveConfig` only ever writes the current names, so a machine heals itself on\n * its next write with nothing to run. Delete this tolerance once no config\n * predating the rename is in use. */\nexport function loadConfig(): AgentConfig | null {\n try {\n const stored = JSON.parse(fs.readFileSync(configFile(), \"utf-8\")) as AgentConfig &\n Partial<{ appUrl: string; apiUrl: string }>;\n const { appUrl, apiUrl, ...config } = stored;\n const url = config.url ?? appUrl;\n const hubUrl = config.hubUrl ?? apiUrl;\n return {\n ...config,\n ...(url !== undefined ? { url } : {}),\n ...(hubUrl !== undefined ? { hubUrl } : {}),\n };\n } catch {\n return null;\n }\n}\n\n/** Persist the machine's config.\n *\n * Refuses to move an already-paired machine to a different hub. A machine that\n * joins the wrong control plane hands it credentials, so re-pointing one is a\n * deliberate act — `jarvis unpair` (which clears the config) and then pair\n * again — rather than something a stale token or a mistyped command can do on\n * its way past. Re-pairing to the same hub is unaffected. */\nexport function saveConfig(config: AgentConfig): void {\n const paired = loadConfig();\n if (paired?.hubUrl && config.hubUrl && config.hubUrl !== paired.hubUrl) {\n throw new Error(\n `This machine is paired with ${paired.hubUrl} and cannot be moved to ${config.hubUrl}.\\n` +\n ` Run 'jarvis unpair' first if you mean to join a different jarvis.`,\n );\n }\n fs.mkdirSync(configDir(), { recursive: true });\n fs.writeFileSync(configFile(), JSON.stringify(config, null, 2) + \"\\n\");\n}\n\nexport function clearConfig(): void {\n try {\n fs.unlinkSync(configFile());\n } catch {}\n}\n\nexport function parseConnectToken(token: string): ConnectToken {\n try {\n const decoded = Buffer.from(token, \"base64\").toString(\"utf-8\");\n const parsed = JSON.parse(decoded);\n if (!parsed.hubUrl || !parsed.jwt || !parsed.userId) {\n throw new Error(\"Invalid token: missing required fields (hubUrl, jwt, userId)\");\n }\n return parsed as ConnectToken;\n } catch (err) {\n if (err instanceof SyntaxError) {\n throw new Error(\"Invalid token: not valid base64-encoded JSON\");\n }\n throw err;\n }\n}\n\nexport function getConfigPath(): string {\n return configFile();\n}\n"],"mappings":";;;AAqBA,SAAS,YAAY;AACrB,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,QAAAC,aAAY;;;ACNrB,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAG9B,IAAM,QAAQ,KAAK,WAAW,SAAS;AAIvC,IAAM,eAAe,CAAC,WAAW,QAAQ;AAWzC,IAAM,SAAS,CAAC,GAAG,CAAC;AAOpB,IAAM,YAAqB,CAAC,UAAU,MAAM;AAUrC,SAAS,UAAyB;AACvC,MAAI,MAAM,QAAQ,cAAc,YAAY,GAAG,CAAC;AAChD,WAAS,KAAK,GAAG,KAAK,GAAG,MAAM;AAC7B,QAAI,WAAW,KAAK,KAAK,KAAK,CAAC,EAAG,QAAO,KAAK,KAAK,KAAK;AACxD,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK;AACpB,UAAM;AAAA,EACR;AACA,SAAO;AACT;AAGO,SAAS,cAA6B;AAC3C,aAAW,QAAQ,cAAc;AAM/B,UAAM,OAAO,UAAU,MAAM,CAAC,WAAW,GAAG,EAAE,UAAU,QAAQ,CAAC;AACjE,QAAI,KAAK,WAAW,EAAG;AACvB,UAAM,UAAU,eAAe,KAAK,GAAG,KAAK,MAAM,GAAG,KAAK,MAAM,EAAE;AAClE,QAAI,CAAC,QAAS;AACd,UAAM,CAAC,OAAO,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