@kienntpixon/dieu-phoi 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/setup.cjs ADDED
@@ -0,0 +1,266 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const core = require('../hook.cjs');
6
+
7
+ const PKG_ROOT = path.join(__dirname, '..');
8
+ const MARKER = 'dieu-phoi/bin/hook.cjs';
9
+
10
+ function tsStamp(d) {
11
+ const x = d || new Date();
12
+ const p = (n) => String(n).padStart(2, '0');
13
+ return `${x.getFullYear()}${p(x.getMonth() + 1)}${p(x.getDate())}-${p(x.getHours())}${p(x.getMinutes())}${p(x.getSeconds())}`;
14
+ }
15
+
16
+ function toSlash(p) {
17
+ return String(p).replace(/\\/g, '/');
18
+ }
19
+
20
+ /** Absolute node + absolute hook, both quoted, forward slashes (works in cmd, PowerShell, sh). */
21
+ function hookCommand(hookPath, nodePath) {
22
+ return `"${toSlash(nodePath || process.execPath)}" "${toSlash(hookPath)}"`;
23
+ }
24
+
25
+ function isOurs(h) {
26
+ return !!(h && typeof h.command === 'string' && toSlash(h.command).includes(MARKER));
27
+ }
28
+
29
+ /**
30
+ * Remove our hook entries from settings.hooks (in place). Only containers that we emptied
31
+ * are deleted; pre-existing empty arrays/objects are left alone. Returns number removed.
32
+ */
33
+ function stripOurHooks(settings) {
34
+ let removed = 0;
35
+ const hooks = settings.hooks;
36
+ if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return 0;
37
+ let emptiedEvent = false;
38
+ for (const event of Object.keys(hooks)) {
39
+ const groups = hooks[event];
40
+ if (!Array.isArray(groups)) continue;
41
+ const kept = [];
42
+ let touched = false;
43
+ for (const g of groups) {
44
+ if (!g || !Array.isArray(g.hooks)) { kept.push(g); continue; }
45
+ const rest = g.hooks.filter((h) => !isOurs(h));
46
+ if (rest.length === g.hooks.length) { kept.push(g); continue; }
47
+ touched = true;
48
+ removed += g.hooks.length - rest.length;
49
+ if (rest.length) kept.push(Object.assign({}, g, { hooks: rest }));
50
+ }
51
+ if (!touched) continue;
52
+ if (kept.length) hooks[event] = kept;
53
+ else { delete hooks[event]; emptiedEvent = true; }
54
+ }
55
+ if (emptiedEvent && !Object.keys(hooks).length) delete settings.hooks;
56
+ return removed;
57
+ }
58
+
59
+ /** True when settings already hold exactly our two entries with this command. */
60
+ function alreadyRegistered(settings, cmd) {
61
+ const hooks = settings && settings.hooks;
62
+ if (!hooks || typeof hooks !== 'object') return false;
63
+ let ours = 0;
64
+ let good = 0;
65
+ for (const event of Object.keys(hooks)) {
66
+ for (const g of Array.isArray(hooks[event]) ? hooks[event] : []) {
67
+ for (const h of (g && Array.isArray(g.hooks) ? g.hooks : [])) {
68
+ if (!isOurs(h)) continue;
69
+ ours++;
70
+ if (h.command !== cmd) continue;
71
+ if (event === 'PostToolUse' && g.matcher === 'Agent') good++;
72
+ else if (event === 'SubagentStop') good++;
73
+ }
74
+ }
75
+ }
76
+ return ours === 2 && good === 2;
77
+ }
78
+
79
+ function addOurHooks(settings, hookPath) {
80
+ const cmd = hookCommand(hookPath);
81
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {};
82
+ const h = settings.hooks;
83
+ if (!Array.isArray(h.PostToolUse)) h.PostToolUse = [];
84
+ h.PostToolUse.push({ matcher: 'Agent', hooks: [{ type: 'command', command: cmd, timeout: 10 }] });
85
+ if (!Array.isArray(h.SubagentStop)) h.SubagentStop = [];
86
+ h.SubagentStop.push({ hooks: [{ type: 'command', command: cmd, timeout: 10 }] });
87
+ }
88
+
89
+ function readSettings(file) {
90
+ if (!fs.existsSync(file)) return { exists: false, raw: null, obj: {} };
91
+ const raw = fs.readFileSync(file, 'utf8');
92
+ const txt = raw.replace(/^/, '');
93
+ if (!txt.trim()) return { exists: true, raw, obj: {} };
94
+ let obj;
95
+ try {
96
+ obj = JSON.parse(txt);
97
+ } catch (e) {
98
+ throw new Error(`Không đọc được ${file} (JSON lỗi: ${e.message}). Không sửa gì.`);
99
+ }
100
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
101
+ throw new Error(`${file} không phải object JSON. Không sửa gì.`);
102
+ }
103
+ return { exists: true, raw, obj };
104
+ }
105
+
106
+ /** Write settings only if content changes; back up the old file first. */
107
+ function writeSettings(file, before, obj) {
108
+ const next = `${JSON.stringify(obj, null, 2)}\n`;
109
+ if (before.exists && before.raw !== null && before.raw.replace(/\r\n/g, '\n') === next) {
110
+ return { changed: false, backup: null };
111
+ }
112
+ let backup = null;
113
+ if (before.exists) {
114
+ backup = `${file}.bak-dieu-phoi-${tsStamp()}`;
115
+ let i = 1;
116
+ while (fs.existsSync(backup)) backup = `${file}.bak-dieu-phoi-${tsStamp()}-${i++}`;
117
+ fs.copyFileSync(file, backup);
118
+ }
119
+ core.writeFileAtomic(file, next);
120
+ return { changed: true, backup };
121
+ }
122
+
123
+ function skillNameOf(dir) {
124
+ try {
125
+ const md = fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8');
126
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(md);
127
+ const m = fm && /^name:\s*["']?([^"'\s]+)/m.exec(fm[1]);
128
+ return m ? m[1] : null;
129
+ } catch (_) {
130
+ return null;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Locate the dieu-phoi skill: <claudeDir>/skills/dieu-phoi, else any
136
+ * <claudeDir>/skills/<x>/ with profile/profile.json whose SKILL.md name is dieu-phoi.
137
+ */
138
+ function findSkillDir(claudeDir) {
139
+ const skills = path.join(path.resolve(claudeDir), 'skills');
140
+ const direct = path.join(skills, 'dieu-phoi');
141
+ if (fs.existsSync(path.join(direct, 'profile', 'profile.json'))) return direct;
142
+ let entries = [];
143
+ try { entries = fs.readdirSync(skills, { withFileTypes: true }); } catch (_) { return null; }
144
+ for (const e of entries) {
145
+ if (!e.isDirectory() && !e.isSymbolicLink()) continue;
146
+ const dir = path.join(skills, e.name);
147
+ if (fs.existsSync(path.join(dir, 'profile', 'profile.json')) && skillNameOf(dir) === 'dieu-phoi') return dir;
148
+ }
149
+ if (fs.existsSync(path.join(direct, 'SKILL.md'))) return direct;
150
+ return null;
151
+ }
152
+
153
+ function skillVersionOf(dir) {
154
+ try {
155
+ const md = fs.readFileSync(path.join(dir, 'SKILL.md'), 'utf8');
156
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(md);
157
+ const m = fm && /^version:\s*["']?([^"'\s]+)/m.exec(fm[1]);
158
+ return m ? m[1] : null;
159
+ } catch (_) {
160
+ return null;
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Install: copy hook + pricing, register hooks, write config.
166
+ * opts: { claudeDir, dept, sinkUrl, sinkToken, skillDir }
167
+ */
168
+ function setup(opts) {
169
+ const claudeDir = path.resolve(opts.claudeDir);
170
+ const home = path.join(claudeDir, 'dieu-phoi');
171
+ const paths = core.pathsFor(home);
172
+ fs.mkdirSync(paths.bin, { recursive: true });
173
+ fs.mkdirSync(paths.data, { recursive: true });
174
+
175
+ // 1. hook + pricing (LF, self-contained)
176
+ for (const f of ['hook.cjs', 'pricing.json']) {
177
+ const src = fs.readFileSync(path.join(PKG_ROOT, f), 'utf8').replace(/\r\n/g, '\n');
178
+ core.writeFileAtomic(path.join(paths.bin, f), src);
179
+ }
180
+
181
+ // 2. config
182
+ const cfg = core.loadConfig(home);
183
+ if (opts.dept !== undefined) cfg.dept = String(opts.dept);
184
+ if (opts.sinkUrl !== undefined) cfg.sink_url = String(opts.sinkUrl);
185
+ if (opts.sinkToken !== undefined) cfg.sink_token = String(opts.sinkToken);
186
+ let skillDir = opts.skillDir ? path.resolve(opts.skillDir) : null;
187
+ if (!skillDir && cfg.skill_dir && fs.existsSync(path.join(cfg.skill_dir, 'profile', 'profile.json'))) {
188
+ skillDir = cfg.skill_dir;
189
+ }
190
+ if (!skillDir) skillDir = findSkillDir(claudeDir);
191
+ if (skillDir) {
192
+ cfg.skill_dir = toSlash(skillDir);
193
+ cfg.skill_version = skillVersionOf(skillDir) || cfg.skill_version || null;
194
+ }
195
+ if (!cfg.user_hash) cfg.user_hash = core.computeUserHash();
196
+ cfg.core_version = core.CORE_VERSION;
197
+ if (!cfg.installed_at) cfg.installed_at = core.nowIso();
198
+ core.writeFileAtomic(paths.config, `${JSON.stringify(cfg, null, 2)}\n`, 0o600);
199
+
200
+ // 3. settings.json
201
+ const settingsFile = path.join(claudeDir, 'settings.json');
202
+ const before = readSettings(settingsFile);
203
+ const obj = JSON.parse(JSON.stringify(before.obj));
204
+ const cmd = hookCommand(paths.hook);
205
+ let removed = 0;
206
+ let res = { changed: false, backup: null };
207
+ if (!(before.exists && alreadyRegistered(obj, cmd))) {
208
+ removed = stripOurHooks(obj);
209
+ addOurHooks(obj, paths.hook);
210
+ res = writeSettings(settingsFile, before, obj);
211
+ }
212
+
213
+ return {
214
+ home,
215
+ hook: paths.hook,
216
+ command: cmd,
217
+ settings: settingsFile,
218
+ settings_changed: res.changed,
219
+ backup: res.backup,
220
+ replaced_entries: removed,
221
+ config: cfg,
222
+ };
223
+ }
224
+
225
+ function uninstall(opts) {
226
+ const claudeDir = path.resolve(opts.claudeDir);
227
+ const home = path.join(claudeDir, 'dieu-phoi');
228
+ const settingsFile = path.join(claudeDir, 'settings.json');
229
+ const before = readSettings(settingsFile);
230
+ const obj = JSON.parse(JSON.stringify(before.obj));
231
+ const removed = stripOurHooks(obj);
232
+ let res = { changed: false, backup: null };
233
+ if (removed) res = writeSettings(settingsFile, before, obj);
234
+ const hookFile = core.pathsFor(home).hook;
235
+ let hookRemoved = false;
236
+ if (opts.purge && fs.existsSync(hookFile)) {
237
+ fs.unlinkSync(hookFile);
238
+ hookRemoved = true;
239
+ }
240
+ return { removed, settings: settingsFile, backup: res.backup, hook_removed: hookRemoved, data_kept: core.pathsFor(home).data };
241
+ }
242
+
243
+ /** Inspect settings for our registration. */
244
+ function registration(claudeDir) {
245
+ const file = path.join(path.resolve(claudeDir), 'settings.json');
246
+ const out = { file, PostToolUse: false, SubagentStop: false, commands: [] };
247
+ let obj;
248
+ try { obj = readSettings(file).obj; } catch (_) { return out; }
249
+ const hooks = obj.hooks || {};
250
+ for (const ev of ['PostToolUse', 'SubagentStop']) {
251
+ for (const g of Array.isArray(hooks[ev]) ? hooks[ev] : []) {
252
+ for (const h of (g && Array.isArray(g.hooks) ? g.hooks : [])) {
253
+ if (!isOurs(h)) continue;
254
+ if (ev === 'PostToolUse' && g.matcher && !/\bAgent\b/.test(g.matcher)) continue;
255
+ out[ev] = true;
256
+ out.commands.push(h.command);
257
+ }
258
+ }
259
+ }
260
+ return out;
261
+ }
262
+
263
+ module.exports = {
264
+ MARKER, setup, uninstall, registration, stripOurHooks, addOurHooks, alreadyRegistered, hookCommand,
265
+ skillVersionOf, findSkillDir, tsStamp,
266
+ };
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@kienntpixon/dieu-phoi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Hook + CLI ghi log subagent của Claude Code và chọn model/effort theo chi phí + thời gian tới lúc nghiệm thu.",
5
+ "license": "MIT",
6
+ "author": "kiennt <kiennt@pixon.games>",
7
+ "type": "commonjs",
8
+ "bin": {
9
+ "dieu-phoi": "bin/dieu-phoi.cjs"
10
+ },
11
+ "main": "hook.cjs",
12
+ "files": [
13
+ "bin/",
14
+ "lib/",
15
+ "hook.cjs",
16
+ "pricing.json",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "scripts": {
24
+ "test": "node --test"
25
+ },
26
+ "keywords": [
27
+ "claude-code",
28
+ "subagent",
29
+ "hooks",
30
+ "orchestration",
31
+ "cost"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }
package/pricing.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "_note": "USD per 1M tokens (API list price; used as a relative reference even on subscription plans). Thinking tokens are already inside output_tokens. Unknown model -> cost null. Override per model via config.json { \"pricing\": { \"models\": { ... } } }.",
3
+ "unit": "usd_per_million_tokens",
4
+ "cache_write_multipliers": {
5
+ "5m": 1.25,
6
+ "1h": 2,
7
+ "assumed": true,
8
+ "_note": "Cache write price = input price x multiplier. Multipliers are ASSUMED (standard Anthropic ratios), not confirmed for the 5.5 family."
9
+ },
10
+ "models": {
11
+ "claude-opus-5-5": { "input": 4, "output": 20, "cache_read": 0.2 },
12
+ "claude-sonnet-5-5": { "input": 2, "output": 10, "cache_read": 0.2 },
13
+ "claude-haiku-5-5": {
14
+ "input": 0.1,
15
+ "output": 0.5,
16
+ "cache_read": 0.01,
17
+ "long_context": {
18
+ "threshold_prompt_tokens": 100000,
19
+ "input": 0.5,
20
+ "output": 2.5,
21
+ "_note": "Applies per request when input + cache_write + cache_read > threshold. Cache write follows the raised input price; cache_read stays at base (not specified)."
22
+ }
23
+ }
24
+ }
25
+ }