officepals 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/bin/officepals.mjs +196 -0
- package/package.json +39 -4
- package/src/hook.mjs +370 -0
- package/src/install.mjs +197 -0
- package/src/paths.mjs +20 -0
- package/src/server.mjs +289 -0
- package/src/sessions.mjs +73 -0
- package/src/state.mjs +295 -0
- package/src/stats.mjs +72 -0
- package/src/title.mjs +100 -0
- package/web/index.html +2946 -0
- package/web/tool-kinds.js +43 -0
- package/web/vendor/three/CSS2DRenderer.js +238 -0
- package/web/vendor/three/LICENSE +21 -0
- package/web/vendor/three/OrbitControls.js +1523 -0
- package/web/vendor/three/README.md +5 -0
- package/web/vendor/three/RoundedBoxGeometry.js +155 -0
- package/web/vendor/three/three.module.min.js +6 -0
package/src/hook.mjs
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// officepals hook relay for Claude Code.
|
|
3
|
+
//
|
|
4
|
+
// Claude Code runs this for each hook event with the event JSON on stdin. It
|
|
5
|
+
// keeps only what the office needs (ids, names, a short label such as a file's
|
|
6
|
+
// base name) and forwards that to the local officepals server, then exits.
|
|
7
|
+
//
|
|
8
|
+
// Rules this script never breaks:
|
|
9
|
+
// - it prints NOTHING (Claude Code reads hook stdout as instructions),
|
|
10
|
+
// - it always exits 0 and never waits long, so it can't slow or block Claude,
|
|
11
|
+
// - prompts, file contents, command lines and tool output never leave it.
|
|
12
|
+
//
|
|
13
|
+
// Self-contained on purpose: `officepals install` copies it to
|
|
14
|
+
// ~/.officepals/hooks/, outside any npx cache that might be cleaned up.
|
|
15
|
+
import * as fs from 'node:fs';
|
|
16
|
+
import * as http from 'node:http';
|
|
17
|
+
import * as os from 'node:os';
|
|
18
|
+
import * as path from 'node:path';
|
|
19
|
+
import { pathToFileURL } from 'node:url';
|
|
20
|
+
|
|
21
|
+
const TIMEOUT_MS = 800;
|
|
22
|
+
const MAX_LABEL = 48;
|
|
23
|
+
|
|
24
|
+
const clip = (s, max = MAX_LABEL) => {
|
|
25
|
+
if (typeof s !== 'string') return undefined;
|
|
26
|
+
const one = s.replace(/\s+/g, ' ').trim();
|
|
27
|
+
return one.length > max ? one.slice(0, max - 1) + '…' : one || undefined;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const MAX_STEPS = 30;
|
|
31
|
+
const STEP_STATUS = new Set(['pending', 'in_progress', 'completed']);
|
|
32
|
+
const steps = (list, text) =>
|
|
33
|
+
list.slice(0, MAX_STEPS).filter((x) => x && typeof x === 'object').map((x) => ({
|
|
34
|
+
t: clip(text(x), 40) ?? '',
|
|
35
|
+
s: STEP_STATUS.has(x.status) ? x.status : 'pending',
|
|
36
|
+
}));
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A to-do list being written or ticked off, from whichever tool the session
|
|
40
|
+
* keeps it with: the whole list ({ plan }) or a change to it ({ planStep }).
|
|
41
|
+
* TodoWrite { todos: [{ content, status }] }
|
|
42
|
+
* …__update_plan (Claude app) { items: [{ content, status }] } | { advance } | { done: [n], start: n }
|
|
43
|
+
* …__wrap_up (Claude app) ticks the whole list off
|
|
44
|
+
*/
|
|
45
|
+
export function planOf(tool, input) {
|
|
46
|
+
if (typeof tool !== 'string' || !input || typeof input !== 'object') return undefined;
|
|
47
|
+
if (tool === 'TodoWrite' && Array.isArray(input.todos)) return { plan: steps(input.todos, (x) => x.content ?? x.activeForm) };
|
|
48
|
+
if (tool.startsWith('mcp__') && tool.endsWith('__update_plan')) {
|
|
49
|
+
if (Array.isArray(input.items)) return { plan: steps(input.items, (x) => x.content) };
|
|
50
|
+
const step = {};
|
|
51
|
+
if (input.advance === true) step.advance = true;
|
|
52
|
+
if (Array.isArray(input.done)) step.done = input.done.filter(Number.isInteger).slice(0, MAX_STEPS);
|
|
53
|
+
if (Number.isInteger(input.start)) step.start = input.start;
|
|
54
|
+
return Object.keys(step).length ? { planStep: step } : undefined;
|
|
55
|
+
}
|
|
56
|
+
if (tool.startsWith('mcp__') && tool.endsWith('__wrap_up')) return { planStep: { finish: true } };
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The step a to-do tool says is in progress (TodoWrite on older setups). */
|
|
61
|
+
export function todoInProgress(tool, input) {
|
|
62
|
+
if (tool !== 'TodoWrite' || !input || !Array.isArray(input.todos)) return undefined;
|
|
63
|
+
const item = input.todos.find((t) => t && t.status === 'in_progress');
|
|
64
|
+
return item ? clip(item.activeForm ?? item.content) : undefined;
|
|
65
|
+
}
|
|
66
|
+
const base = (p) => (typeof p === 'string' && p ? path.basename(p) : undefined);
|
|
67
|
+
const host = (u) => {
|
|
68
|
+
try {
|
|
69
|
+
return new URL(u).hostname;
|
|
70
|
+
} catch {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// What kind of shell command it is: only the kind leaves the relay, never the command.
|
|
76
|
+
const RUNNERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
|
|
77
|
+
const TEST_TOOLS = new Set(['jest', 'vitest', 'mocha', 'pytest', 'py.test', 'rspec', 'phpunit', 'ava', 'tap', 'karma', 'cypress',
|
|
78
|
+
'eslint', 'prettier', 'ruff', 'mypy', 'flake8', 'pylint', 'rubocop', 'golangci-lint', 'shellcheck', 'stylelint', 'biome']);
|
|
79
|
+
const BUILD_TOOLS = new Set(['make', 'cmake', 'ninja', 'tsc', 'webpack', 'rollup', 'esbuild', 'xcodebuild', 'gradle', 'gradlew', 'mvn', 'msbuild']);
|
|
80
|
+
const LOOK_TOOLS = new Set(['ls', 'cat', 'head', 'tail', 'less', 'more', 'grep', 'rg', 'ag', 'find', 'fd', 'tree', 'wc', 'file', 'stat',
|
|
81
|
+
'du', 'df', 'pwd', 'which', 'whereis', 'awk', 'jq', 'diff', 'cmp', 'readlink', 'realpath', 'basename', 'dirname', 'nl', 'sort', 'uniq']);
|
|
82
|
+
const INSTALL_SUBS = new Set(['install', 'i', 'ci', 'add', 'remove', 'rm', 'uninstall', 'un', 'update', 'up', 'upgrade']);
|
|
83
|
+
const KIND_ORDER = ['test', 'build', 'install', 'git', 'look']; // when a line does several things
|
|
84
|
+
|
|
85
|
+
function kindOfWords(w) {
|
|
86
|
+
const base = (x) => (x ?? '').split('/').pop();
|
|
87
|
+
let [p, a, b] = [base(w[0]), w[1] ?? '', w[2] ?? ''];
|
|
88
|
+
if (['npx', 'bunx'].includes(p) || ((p === 'pnpm' || p === 'yarn') && a === 'dlx')) {
|
|
89
|
+
const rest = w.slice(p === 'npx' || p === 'bunx' ? 1 : 2).filter((x) => !x.startsWith('-'));
|
|
90
|
+
return rest.length ? kindOfWords(rest) : undefined;
|
|
91
|
+
}
|
|
92
|
+
if (RUNNERS.has(p)) {
|
|
93
|
+
const script = a === 'run' || a === 'run-script' ? b : a;
|
|
94
|
+
if (/^(test|t)\b|^test[:-]|^(lint|typecheck|check|e2e)\b/.test(script)) return 'test';
|
|
95
|
+
if (/^(build|compile|bundle|dist)\b/.test(script)) return 'build';
|
|
96
|
+
if (INSTALL_SUBS.has(a) || (p === 'yarn' && !a)) return 'install';
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
if (p === 'git' || p === 'gh') return 'git';
|
|
100
|
+
if (TEST_TOOLS.has(p) || (p === 'playwright' && a === 'test')) return 'test';
|
|
101
|
+
if (p === 'node' && w.includes('--test')) return 'test';
|
|
102
|
+
if (/^python3?$/.test(p) && a === '-m' && ['pytest', 'unittest'].includes(b)) return 'test';
|
|
103
|
+
if (['go', 'cargo', 'swift', 'make', 'dotnet', 'deno', 'mix'].includes(p) && /^(test|check)$/.test(a)) return 'test';
|
|
104
|
+
if (['cargo', 'go', 'swift', 'dotnet', 'docker', 'next', 'vite', 'astro', 'nuxt'].includes(p) && a === 'build') return 'build';
|
|
105
|
+
if (BUILD_TOOLS.has(p)) return 'build';
|
|
106
|
+
if (/^pip3?$/.test(p) || (/^python3?$/.test(p) && a === '-m' && b === 'pip')) return w.includes('install') || w.includes('uninstall') ? 'install' : undefined;
|
|
107
|
+
if (p === 'uv' && ['add', 'remove', 'sync', 'pip'].includes(a)) return 'install';
|
|
108
|
+
if (['brew', 'apt', 'apt-get', 'port', 'gem', 'pod', 'bundle', 'poetry', 'composer'].includes(p) && /^(install|add|upgrade|update|require|remove)$/.test(a || 'install')) return 'install';
|
|
109
|
+
if (p === 'cargo' && ['add', 'install'].includes(a)) return 'install';
|
|
110
|
+
if (p === 'go' && (a === 'get' || (a === 'mod' && b === 'tidy'))) return 'install';
|
|
111
|
+
if (p === 'sed') return w.some((x) => /^-i/.test(x)) ? undefined : 'look';
|
|
112
|
+
if (LOOK_TOOLS.has(p)) return 'look';
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The kind of a shell command: test, build, install, git or look (else undefined). */
|
|
117
|
+
export function commandKind(command) {
|
|
118
|
+
if (typeof command !== 'string' || !command.trim()) return undefined;
|
|
119
|
+
const kinds = new Set();
|
|
120
|
+
for (const part of command.split(/&&|\|\||;|\||\n/)) {
|
|
121
|
+
let w = part.trim().split(/\s+/).filter(Boolean);
|
|
122
|
+
while (w.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w[0]) || ['sudo', 'time', 'env', 'exec', 'command', 'nohup'].includes(w[0]))) w = w.slice(1);
|
|
123
|
+
if (!w.length || w[0] === 'cd' || w[0] === 'echo' || w[0] === '(' || w[0].startsWith('#')) continue;
|
|
124
|
+
const k = kindOfWords(w.map((x) => x.replace(/^["'(]+|["')]+$/g, '')));
|
|
125
|
+
if (k) kinds.add(k);
|
|
126
|
+
}
|
|
127
|
+
return KIND_ORDER.find((k) => kinds.has(k));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// How risky a permission request is, judged here so the command itself never
|
|
131
|
+
// has to leave: only { level: 'high' | 'medium' | 'low', why } does.
|
|
132
|
+
const SENSITIVE_FILE = /(^|[\\/])(\.env(\.[\w.-]+)?$|\.ssh[\\/]|id_(rsa|ed25519|ecdsa|dsa)\b|\.aws[\\/]|\.npmrc$|\.netrc$|\.pypirc$|\.git-credentials$|[^\\/]*(credential|secret)[^\\/]*$|[^\\/]+\.(pem|key|p12|pfx)$|\.(zsh|bash)rc$|\.(bash_)?profile$|\.claude[\\/]settings[^\\/]*\.json$)/i;
|
|
133
|
+
const BASH_RISKS = [
|
|
134
|
+
[/\bsudo\b/, 'high', 'sudo'],
|
|
135
|
+
[/\b(curl|wget)\b[^|;&]*\|\s*(sudo\s+)?(ba|z)?sh\b/, 'high', 'pipe-shell'],
|
|
136
|
+
[/\brm\s+(-[a-zA-Z]*[rRf][a-zA-Z]*\s+)+/, 'high', 'delete'],
|
|
137
|
+
[/\bgit\s+push\b[^;&|]*(--force\b|--force-with-lease\b|\s-f\b)/, 'high', 'force-push'],
|
|
138
|
+
[/\bgit\s+(reset\s+--hard|clean\s+-[a-zA-Z]*f|checkout\s+--\s|restore\s+(\.|--staged\s+\.|--worktree))/, 'high', 'discard'],
|
|
139
|
+
[/\b(npm|yarn|pnpm|bun)\s+publish\b|\bcargo\s+publish\b|\btwine\s+upload\b|\bgh\s+release\s+create\b|\bgem\s+push\b/, 'high', 'publish'],
|
|
140
|
+
[/\b(drop\s+(table|database|schema)|truncate\s+table)\b/i, 'high', 'db-drop'],
|
|
141
|
+
[/\bterraform\s+(apply|destroy)\b|\bkubectl\s+(apply|delete)\b|\bvercel\b[^;&|]*--prod\b|\bfly(ctl)?\s+deploy\b|\bfirebase\s+deploy\b|\bnetlify\s+deploy\b[^;&|]*--prod\b/, 'high', 'deploy'],
|
|
142
|
+
[/\bgit\s+push\b/, 'medium', 'push'],
|
|
143
|
+
[/\b(chmod|chown)\b/, 'medium', 'perms'],
|
|
144
|
+
[/\b(kill|pkill|killall)\b/, 'medium', 'kill'],
|
|
145
|
+
[/\brm\b/, 'medium', 'delete'],
|
|
146
|
+
[/\b(curl|wget|ssh|scp|rsync|nc)\b/, 'medium', 'network'],
|
|
147
|
+
];
|
|
148
|
+
const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
|
|
149
|
+
|
|
150
|
+
/** Is `file` inside the project folder `cwd`? (Unknown: assume so.) */
|
|
151
|
+
function insideProject(file, cwd) {
|
|
152
|
+
if (typeof cwd !== 'string' || !cwd) return true;
|
|
153
|
+
const rel = path.relative(cwd, path.resolve(cwd, file));
|
|
154
|
+
return !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function riskOf(tool, input, cwd) {
|
|
158
|
+
if (!input || typeof input !== 'object') return undefined;
|
|
159
|
+
if (tool === 'Bash') {
|
|
160
|
+
const line = String(input.command ?? '');
|
|
161
|
+
for (const [re, level, why] of BASH_RISKS) if (re.test(line)) return { level, why };
|
|
162
|
+
const kind = commandKind(line);
|
|
163
|
+
if (kind === 'install') return { level: 'medium', why: 'install' };
|
|
164
|
+
if (kind === 'look') return { level: 'low', why: 'read-only' };
|
|
165
|
+
if (kind === 'git') return { level: 'low', why: 'git' };
|
|
166
|
+
if (kind === 'test' || kind === 'build') return { level: 'low', why: 'runs-code' };
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
const writes = WRITE_TOOLS.has(tool);
|
|
170
|
+
if (writes || tool === 'Read') {
|
|
171
|
+
const file = input.file_path ?? input.notebook_path;
|
|
172
|
+
if (typeof file !== 'string' || !file) return undefined;
|
|
173
|
+
if (SENSITIVE_FILE.test(file)) return { level: 'high', why: writes ? 'sensitive-write' : 'sensitive-read' };
|
|
174
|
+
if (!insideProject(file, cwd)) return { level: 'medium', why: writes ? 'outside-write' : 'outside-read' };
|
|
175
|
+
return { level: 'low', why: writes ? 'edit' : 'read' };
|
|
176
|
+
}
|
|
177
|
+
if (tool === 'WebFetch' || tool === 'WebSearch') return { level: 'low', why: 'web' };
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** A short, harmless label for what a tool call is about. */
|
|
182
|
+
export function labelFor(tool, input) {
|
|
183
|
+
if (!input || typeof input !== 'object') return undefined;
|
|
184
|
+
switch (tool) {
|
|
185
|
+
case 'Read':
|
|
186
|
+
case 'Edit':
|
|
187
|
+
case 'Write':
|
|
188
|
+
case 'MultiEdit':
|
|
189
|
+
return base(input.file_path);
|
|
190
|
+
case 'NotebookEdit':
|
|
191
|
+
return base(input.notebook_path);
|
|
192
|
+
case 'Grep':
|
|
193
|
+
case 'Glob':
|
|
194
|
+
return clip(input.pattern);
|
|
195
|
+
case 'Bash':
|
|
196
|
+
// The description Claude writes for the command, else just the program name.
|
|
197
|
+
return clip(input.description) ?? clip(String(input.command ?? '').split(/\s+/)[0]);
|
|
198
|
+
case 'WebFetch':
|
|
199
|
+
return host(input.url);
|
|
200
|
+
case 'WebSearch':
|
|
201
|
+
return clip(input.query);
|
|
202
|
+
case 'Task':
|
|
203
|
+
case 'Agent':
|
|
204
|
+
return clip(input.subagent_type) ?? clip(input.description);
|
|
205
|
+
case 'AskUserQuestion':
|
|
206
|
+
// What it wants to know (Claude's own words, clipped).
|
|
207
|
+
return clip(Array.isArray(input.questions) ? input.questions[0]?.question : input.question, 60);
|
|
208
|
+
case 'ExitPlanMode': {
|
|
209
|
+
// The plan's title: its first line.
|
|
210
|
+
const first = String(input.plan ?? '').split('\n').find((l) => l.trim());
|
|
211
|
+
return clip(first?.replace(/^[#>*\-\s]+/, ''), 60);
|
|
212
|
+
}
|
|
213
|
+
default:
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ── Codex ──────────────────────────────────────────────────────
|
|
219
|
+
// Codex's hooks send the same events as Claude Code's, with a few tools of
|
|
220
|
+
// its own; they're renamed to the ones the office knows.
|
|
221
|
+
|
|
222
|
+
/** The files an apply_patch touches ("*** Update File: src/a.ts"). */
|
|
223
|
+
export function patchFiles(patch) {
|
|
224
|
+
if (typeof patch !== 'string') return [];
|
|
225
|
+
return [...patch.matchAll(/^\*\*\* (Add|Update|Delete) File: (.+)$/gm)].map((m) => ({ op: m[1], path: m[2].trim() }));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** A shell command as one line (Codex may pass ["bash", "-lc", "…"]). */
|
|
229
|
+
function commandLine(cmd) {
|
|
230
|
+
if (typeof cmd === 'string') return cmd;
|
|
231
|
+
if (!Array.isArray(cmd)) return '';
|
|
232
|
+
const parts = cmd.map(String);
|
|
233
|
+
if (/^(ba|z)?sh$/.test(path.basename(parts[0] ?? '')) && /^-\w*c$/.test(parts[1] ?? '')) return parts.slice(2).join(' ');
|
|
234
|
+
return parts.join(' ');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** A Codex payload in Claude Code's terms: tool names and inputs the office knows. */
|
|
238
|
+
export function fromCodex(raw) {
|
|
239
|
+
const out = { ...raw };
|
|
240
|
+
const input = raw.tool_input && typeof raw.tool_input === 'object' ? raw.tool_input : {};
|
|
241
|
+
switch (raw.tool_name) {
|
|
242
|
+
case 'Bash':
|
|
243
|
+
case 'exec_command':
|
|
244
|
+
case 'shell':
|
|
245
|
+
out.tool_name = 'Bash';
|
|
246
|
+
out.tool_input = { ...input, command: commandLine(input.command ?? input.cmd) };
|
|
247
|
+
break;
|
|
248
|
+
case 'apply_patch': {
|
|
249
|
+
const files = patchFiles(input.command ?? input.input ?? input.patch);
|
|
250
|
+
out.tool_name = files.length && files.every((f) => f.op === 'Add') ? 'Write' : 'Edit';
|
|
251
|
+
out.tool_input = files.length ? { file_path: files[0].path } : {};
|
|
252
|
+
out.extraFiles = Math.max(0, files.length - 1);
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
case 'update_plan':
|
|
256
|
+
out.tool_name = 'TodoWrite';
|
|
257
|
+
out.tool_input = Array.isArray(input.plan) ? { todos: input.plan.map((p) => ({ content: p?.step, status: p?.status })) } : {};
|
|
258
|
+
break;
|
|
259
|
+
case 'spawn_agent':
|
|
260
|
+
out.tool_name = 'Agent';
|
|
261
|
+
out.tool_input = { subagent_type: input.agent_type ?? input.name, description: input.description };
|
|
262
|
+
break;
|
|
263
|
+
case 'view_image':
|
|
264
|
+
out.tool_name = 'Read';
|
|
265
|
+
out.tool_input = { file_path: input.path };
|
|
266
|
+
break;
|
|
267
|
+
default:
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
return out;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Reduce a raw hook payload to the event the office understands. */
|
|
274
|
+
export function toEvent(raw, provider = 'claude') {
|
|
275
|
+
if (provider === 'codex' && raw && typeof raw === 'object') raw = fromCodex(raw);
|
|
276
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
277
|
+
const session = typeof raw.session_id === 'string' ? raw.session_id : null;
|
|
278
|
+
const event = typeof raw.hook_event_name === 'string' ? raw.hook_event_name : null;
|
|
279
|
+
if (!session || !event) return null;
|
|
280
|
+
const out = { provider, session, event };
|
|
281
|
+
if (typeof raw.agent_id === 'string') out.agent = raw.agent_id;
|
|
282
|
+
if (typeof raw.agent_type === 'string') out.agentType = clip(raw.agent_type);
|
|
283
|
+
if (typeof raw.tool_name === 'string') out.tool = raw.tool_name;
|
|
284
|
+
if (typeof raw.tool_use_id === 'string') out.toolUseId = raw.tool_use_id;
|
|
285
|
+
if (typeof raw.notification_type === 'string') out.notification = raw.notification_type;
|
|
286
|
+
if (typeof raw.source === 'string') out.source = raw.source;
|
|
287
|
+
const project = base(raw.cwd);
|
|
288
|
+
if (project) out.project = project;
|
|
289
|
+
let label = labelFor(raw.tool_name, raw.tool_input);
|
|
290
|
+
if (label && raw.extraFiles) label = `${label} +${raw.extraFiles}`; // a patch over several files
|
|
291
|
+
if (label) out.label = label;
|
|
292
|
+
if (raw.tool_name === 'Bash') {
|
|
293
|
+
const kind = commandKind(raw.tool_input?.command);
|
|
294
|
+
if (kind) out.cmd = kind;
|
|
295
|
+
}
|
|
296
|
+
if (event === 'PermissionRequest') {
|
|
297
|
+
const risk = riskOf(raw.tool_name, raw.tool_input, raw.cwd);
|
|
298
|
+
if (risk) out.risk = risk;
|
|
299
|
+
}
|
|
300
|
+
// The session's own log, so the office can read the title Claude Code gave
|
|
301
|
+
// the conversation. Only the path is sent; the server reads it locally.
|
|
302
|
+
// (Codex's log format isn't stable: its titles come from its session index instead.)
|
|
303
|
+
if (provider === 'claude' && typeof raw.transcript_path === 'string' && raw.transcript_path.endsWith('.jsonl')) out.transcript = raw.transcript_path;
|
|
304
|
+
// To-do steps (only when the session has the task tools): what it's on now.
|
|
305
|
+
const todo = todoInProgress(raw.tool_name, raw.tool_input);
|
|
306
|
+
if (todo) out.todo = todo;
|
|
307
|
+
// The whole to-do list, so the office's whiteboard can show it (PreToolUse only:
|
|
308
|
+
// that's when it changes).
|
|
309
|
+
if (event === 'PreToolUse') Object.assign(out, planOf(raw.tool_name, raw.tool_input));
|
|
310
|
+
if (typeof raw.task_id === 'string') out.taskId = raw.task_id;
|
|
311
|
+
if (typeof raw.task_subject === 'string') out.taskSubject = clip(raw.task_subject);
|
|
312
|
+
const input = raw.tool_input && typeof raw.tool_input === 'object' ? raw.tool_input : null;
|
|
313
|
+
if (raw.tool_name === 'TaskUpdate' && input) {
|
|
314
|
+
const id = input.taskId ?? input.task_id ?? input.id;
|
|
315
|
+
if (typeof id === 'string' || typeof id === 'number') out.taskId = String(id);
|
|
316
|
+
if (typeof input.status === 'string') out.taskStatus = input.status;
|
|
317
|
+
const subject = clip(input.activeForm ?? input.subject);
|
|
318
|
+
if (subject) out.taskSubject = subject;
|
|
319
|
+
}
|
|
320
|
+
return out;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function readServer() {
|
|
324
|
+
const home = process.env.OFFICEPALS_HOME || path.join(os.homedir(), '.officepals');
|
|
325
|
+
try {
|
|
326
|
+
const s = JSON.parse(fs.readFileSync(path.join(home, 'server.json'), 'utf-8'));
|
|
327
|
+
return Number.isInteger(s.port) && typeof s.token === 'string' ? s : null;
|
|
328
|
+
} catch {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function post(server, body) {
|
|
334
|
+
return new Promise((resolve) => {
|
|
335
|
+
const req = http.request(
|
|
336
|
+
{
|
|
337
|
+
host: '127.0.0.1',
|
|
338
|
+
port: server.port,
|
|
339
|
+
path: '/hooks',
|
|
340
|
+
method: 'POST',
|
|
341
|
+
headers: { 'content-type': 'application/json', 'x-officepals-token': server.token },
|
|
342
|
+
timeout: TIMEOUT_MS,
|
|
343
|
+
},
|
|
344
|
+
(res) => {
|
|
345
|
+
res.resume();
|
|
346
|
+
res.on('end', resolve);
|
|
347
|
+
},
|
|
348
|
+
);
|
|
349
|
+
req.on('timeout', () => req.destroy());
|
|
350
|
+
req.on('error', resolve);
|
|
351
|
+
req.end(body);
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function main() {
|
|
356
|
+
let input = '';
|
|
357
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
358
|
+
// `node relay.mjs codex` is how Codex runs it.
|
|
359
|
+
const event = toEvent(JSON.parse(input), process.argv[2] === 'codex' ? 'codex' : 'claude');
|
|
360
|
+
const server = event && readServer();
|
|
361
|
+
if (server) await post(server, JSON.stringify(event));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Run only when executed as a script (tests import labelFor/toEvent).
|
|
365
|
+
const script = process.argv[1];
|
|
366
|
+
if (script && (import.meta.url === pathToFileURL(script).href || script.endsWith('relay.mjs'))) {
|
|
367
|
+
main()
|
|
368
|
+
.catch(() => {})
|
|
369
|
+
.finally(() => process.exit(0));
|
|
370
|
+
}
|
package/src/install.mjs
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// Install / uninstall officepals' hook entries in ~/.claude/settings.json
|
|
2
|
+
// (Claude Code) and ~/.codex/hooks.json (Codex: same format, its own events).
|
|
3
|
+
//
|
|
4
|
+
// - Never rewrites what it doesn't own: other hooks and settings are kept
|
|
5
|
+
// as they are, and an unreadable or oddly shaped file aborts the change.
|
|
6
|
+
// - A one-time backup (settings.json.officepals.backup) is made before the
|
|
7
|
+
// first change.
|
|
8
|
+
// - Our entries run the relay script asynchronously, so Claude Code never
|
|
9
|
+
// waits on the office.
|
|
10
|
+
import * as fs from 'node:fs';
|
|
11
|
+
import * as path from 'node:path';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
|
|
14
|
+
import { claudeSettingsPath, codexHooksPath, hookScriptPath } from './paths.mjs';
|
|
15
|
+
|
|
16
|
+
export const HOOK_EVENTS = [
|
|
17
|
+
'SessionStart',
|
|
18
|
+
'SessionEnd',
|
|
19
|
+
'UserPromptSubmit',
|
|
20
|
+
'PreToolUse',
|
|
21
|
+
'PostToolUse',
|
|
22
|
+
'PostToolUseFailure',
|
|
23
|
+
'PermissionRequest',
|
|
24
|
+
'Notification',
|
|
25
|
+
'Stop',
|
|
26
|
+
'SubagentStart',
|
|
27
|
+
'SubagentStop',
|
|
28
|
+
'TaskCreated',
|
|
29
|
+
'TaskCompleted',
|
|
30
|
+
];
|
|
31
|
+
/** The events Codex sends (it has no Notification or Task events). */
|
|
32
|
+
export const CODEX_EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PermissionRequest', 'PostToolUse', 'Stop', 'SubagentStart', 'SubagentStop'];
|
|
33
|
+
const EVENTS = { claude: HOOK_EVENTS, codex: CODEX_EVENTS };
|
|
34
|
+
const fileFor = (provider) => (provider === 'codex' ? codexHooksPath() : claudeSettingsPath());
|
|
35
|
+
|
|
36
|
+
export const BACKUP_SUFFIX = '.officepals.backup';
|
|
37
|
+
// The relay in the default ~/.officepals location; Codex runs it with "codex".
|
|
38
|
+
const DEFAULT_SCRIPT = {
|
|
39
|
+
claude: /[\\/]\.officepals[\\/]hooks[\\/]relay\.mjs"?$/,
|
|
40
|
+
codex: /[\\/]\.officepals[\\/]hooks[\\/]relay\.mjs"? codex$/,
|
|
41
|
+
};
|
|
42
|
+
// Entries written under the earlier name, cozy-agents: replaced on install,
|
|
43
|
+
// removed on uninstall. (Its relay talks to a server that no longer exists.)
|
|
44
|
+
const LEGACY_SCRIPT = {
|
|
45
|
+
claude: /[\\/]\.cozy-agents[\\/]hooks[\\/]claude-hook\.mjs"?$/,
|
|
46
|
+
codex: /[\\/]\.cozy-agents[\\/]hooks[\\/]claude-hook\.mjs"? codex$/,
|
|
47
|
+
};
|
|
48
|
+
const isLegacy = (h, provider = 'claude') => h && typeof h.command === 'string' && LEGACY_SCRIPT[provider].test(h.command.trim());
|
|
49
|
+
/** The hook command. Forward slashes on Windows too: Node takes them, and
|
|
50
|
+
* Claude Code may run hooks through Git Bash, where a backslash escapes. */
|
|
51
|
+
export const commandFor = (script, platform = process.platform, provider = 'claude') =>
|
|
52
|
+
`node "${platform === 'win32' ? script.replace(/\\/g, '/') : script}"${provider === 'codex' ? ' codex' : ''}`;
|
|
53
|
+
|
|
54
|
+
/** One of our entries: the command we write for this install's relay, or a
|
|
55
|
+
* relay in the default ~/.officepals location (installs made before a
|
|
56
|
+
* custom home was set). */
|
|
57
|
+
const isOurs = (h, script, provider = 'claude') =>
|
|
58
|
+
h && typeof h.command === 'string' &&
|
|
59
|
+
(h.command.trim() === commandFor(script, undefined, provider) || DEFAULT_SCRIPT[provider].test(h.command.trim()));
|
|
60
|
+
|
|
61
|
+
export class SettingsError extends Error {}
|
|
62
|
+
|
|
63
|
+
function readSettings(file) {
|
|
64
|
+
if (!fs.existsSync(file)) return {};
|
|
65
|
+
let data;
|
|
66
|
+
try {
|
|
67
|
+
data = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
68
|
+
} catch {
|
|
69
|
+
throw new SettingsError(`${file} isn't valid JSON — fix it first; nothing was changed.`);
|
|
70
|
+
}
|
|
71
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
72
|
+
throw new SettingsError(`${file} isn't a JSON object — nothing was changed.`);
|
|
73
|
+
}
|
|
74
|
+
if (data.hooks !== undefined && (typeof data.hooks !== 'object' || data.hooks === null || Array.isArray(data.hooks))) {
|
|
75
|
+
throw new SettingsError(`"hooks" in ${file} isn't an object — nothing was changed.`);
|
|
76
|
+
}
|
|
77
|
+
return data;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function writeSettings(file, data) {
|
|
81
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
82
|
+
const mode = fs.existsSync(file) ? fs.statSync(file).mode & 0o777 : 0o600;
|
|
83
|
+
const tmp = `${file}.officepals.tmp`;
|
|
84
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode });
|
|
85
|
+
replaceFile(tmp, file);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Move tmp over file. On Windows a rename fails while another program (an
|
|
89
|
+
* editor, a virus scanner) has the file open, so retry, then copy over it. */
|
|
90
|
+
function replaceFile(tmp, file) {
|
|
91
|
+
for (let attempt = 0; ; attempt++) {
|
|
92
|
+
try {
|
|
93
|
+
fs.renameSync(tmp, file);
|
|
94
|
+
return;
|
|
95
|
+
} catch (err) {
|
|
96
|
+
if (!['EPERM', 'EACCES', 'EBUSY'].includes(err.code)) throw err;
|
|
97
|
+
if (attempt < 5) {
|
|
98
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50 * (attempt + 1)); // brief pause
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
fs.copyFileSync(tmp, file);
|
|
102
|
+
fs.unlinkSync(tmp);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Hooks left by cozy-agents (this project's earlier name). */
|
|
109
|
+
export function hasLegacyHooks(file = claudeSettingsPath(), provider = 'claude') {
|
|
110
|
+
let data;
|
|
111
|
+
try {
|
|
112
|
+
data = readSettings(file);
|
|
113
|
+
} catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
return Object.values(data.hooks ?? {}).some(
|
|
117
|
+
(groups) => Array.isArray(groups) && groups.some((g) => g?.hooks?.some?.((h) => isLegacy(h, provider))),
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function areHooksInstalled(file = claudeSettingsPath(), script = hookScriptPath(), provider = 'claude') {
|
|
122
|
+
let data;
|
|
123
|
+
try {
|
|
124
|
+
data = readSettings(file);
|
|
125
|
+
} catch {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
return Object.values(data.hooks ?? {}).some(
|
|
129
|
+
(groups) => Array.isArray(groups) && groups.some((g) => g?.hooks?.some?.((h) => isOurs(h, script, provider))),
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function installHooks({ provider = 'claude', file = fileFor(provider), script = hookScriptPath() } = {}) {
|
|
134
|
+
const events = EVENTS[provider];
|
|
135
|
+
const data = readSettings(file);
|
|
136
|
+
const hooks = (data.hooks ??= {});
|
|
137
|
+
for (const event of events) {
|
|
138
|
+
if (hooks[event] !== undefined && !Array.isArray(hooks[event])) {
|
|
139
|
+
throw new SettingsError(`hooks.${event} in ${file} isn't an array — nothing was changed.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// The relay lives outside any npx cache, so it keeps working after a clean-up.
|
|
144
|
+
fs.mkdirSync(path.dirname(script), { recursive: true, mode: 0o700 });
|
|
145
|
+
fs.copyFileSync(fileURLToPath(new URL('./hook.mjs', import.meta.url)), script);
|
|
146
|
+
|
|
147
|
+
if (fs.existsSync(file) && !fs.existsSync(file + BACKUP_SUFFIX)) fs.copyFileSync(file, file + BACKUP_SUFFIX);
|
|
148
|
+
|
|
149
|
+
// cozy-agents' entries make way for ours.
|
|
150
|
+
let migrated = 0;
|
|
151
|
+
for (const event of Object.keys(hooks)) {
|
|
152
|
+
if (!Array.isArray(hooks[event])) continue;
|
|
153
|
+
hooks[event] = hooks[event].flatMap((g) => {
|
|
154
|
+
if (!g || !Array.isArray(g.hooks)) return [g];
|
|
155
|
+
const rest = g.hooks.filter((h) => !isLegacy(h, provider));
|
|
156
|
+
migrated += g.hooks.length - rest.length;
|
|
157
|
+
return rest.length || g.hooks.length === 0 ? [{ ...g, hooks: rest }] : [];
|
|
158
|
+
});
|
|
159
|
+
if (hooks[event].length === 0) delete hooks[event];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const entry = { type: 'command', command: commandFor(script, undefined, provider), timeout: 5, async: true };
|
|
163
|
+
let added = 0;
|
|
164
|
+
for (const event of events) {
|
|
165
|
+
const groups = (hooks[event] ??= []);
|
|
166
|
+
if (groups.some((g) => g?.hooks?.some?.((h) => isOurs(h, script, provider)))) continue;
|
|
167
|
+
groups.push({ matcher: '', hooks: [entry] });
|
|
168
|
+
added++;
|
|
169
|
+
}
|
|
170
|
+
if (added > 0 || migrated > 0) writeSettings(file, data);
|
|
171
|
+
return { added, migrated, backup: file + BACKUP_SUFFIX };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function uninstallHooks({ provider = 'claude', file = fileFor(provider), script = hookScriptPath() } = {}) {
|
|
175
|
+
if (!fs.existsSync(file)) return { removed: 0 };
|
|
176
|
+
const data = readSettings(file);
|
|
177
|
+
let removed = 0;
|
|
178
|
+
for (const [event, groups] of Object.entries(data.hooks ?? {})) {
|
|
179
|
+
if (!Array.isArray(groups)) continue;
|
|
180
|
+
const kept = [];
|
|
181
|
+
for (const g of groups) {
|
|
182
|
+
if (!g || !Array.isArray(g.hooks)) {
|
|
183
|
+
kept.push(g);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const rest = g.hooks.filter((h) => !isOurs(h, script, provider) && !isLegacy(h, provider));
|
|
187
|
+
removed += g.hooks.length - rest.length;
|
|
188
|
+
if (rest.length > 0) kept.push({ ...g, hooks: rest });
|
|
189
|
+
else if (g.hooks.length === 0) kept.push(g); // an empty group we didn't make
|
|
190
|
+
}
|
|
191
|
+
if (kept.length > 0) data.hooks[event] = kept;
|
|
192
|
+
else if (groups.length > 0) delete data.hooks[event]; // we emptied it
|
|
193
|
+
}
|
|
194
|
+
if (data.hooks && Object.keys(data.hooks).length === 0) delete data.hooks;
|
|
195
|
+
if (removed > 0) writeSettings(file, data);
|
|
196
|
+
return { removed };
|
|
197
|
+
}
|
package/src/paths.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Where officepals keeps its files: ~/.officepals (override with OFFICEPALS_HOME).
|
|
2
|
+
import * as os from 'node:os';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_PORT = 4747;
|
|
6
|
+
|
|
7
|
+
export function homeDir() {
|
|
8
|
+
return process.env.OFFICEPALS_HOME || path.join(os.homedir(), '.officepals');
|
|
9
|
+
}
|
|
10
|
+
export const serverFile = () => path.join(homeDir(), 'server.json');
|
|
11
|
+
export const statsFile = () => path.join(homeDir(), 'stats.json');
|
|
12
|
+
/** Where the earlier name, cozy-agents, kept its files (for moving them over). */
|
|
13
|
+
export const legacyHomeDir = () => path.join(os.homedir(), '.cozy-agents');
|
|
14
|
+
export const hookScriptPath = () => path.join(homeDir(), 'hooks', 'relay.mjs');
|
|
15
|
+
/** Codex keeps its user hooks in $CODEX_HOME/hooks.json (~/.codex by default). */
|
|
16
|
+
export const codexHome = () => process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
|
|
17
|
+
export const codexHooksPath = () => process.env.OFFICEPALS_CODEX_HOOKS || path.join(codexHome(), 'hooks.json');
|
|
18
|
+
export const codexIndexPath = () => process.env.OFFICEPALS_CODEX_INDEX || path.join(codexHome(), 'session_index.jsonl');
|
|
19
|
+
export const claudeSettingsPath = () =>
|
|
20
|
+
process.env.OFFICEPALS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
|