@honcho-ai/claude-honcho 0.4.0 → 0.4.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.
@@ -1,803 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- // src/config.ts
4
- import { join as join3, dirname as dirname2 } from "path";
5
- import { fileURLToPath } from "url";
6
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
7
-
8
- // node_modules/@honcho-ai/harness-plugin-core/dist/config.js
9
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
10
- import { homedir } from "node:os";
11
- import { join as join2 } from "node:path";
12
-
13
- // node_modules/@honcho-ai/harness-plugin-core/dist/legacy/v01.js
14
- var isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
15
- var str = (v) => typeof v === "string" && v ? v : undefined;
16
- function v01Reader(file, host) {
17
- const hosts = isObj(file.hosts) ? file.hosts : {};
18
- const v1 = typeof file.schemaVersion === "number" && file.schemaVersion >= 1;
19
- const pick = (b) => {
20
- const o = isObj(b) ? b : {};
21
- if (v1)
22
- return { apiKey: isObj(o.auth) ? str(o.auth.apiKey) : undefined, peerName: str(o.peerName), workspace: str(o.workspace), baseUrl: str(o.baseUrl) };
23
- return {
24
- apiKey: (isObj(o.auth) ? str(o.auth.apiKey) : undefined) ?? str(o.apiKey),
25
- peerName: str(o.peerName),
26
- workspace: str(o.workspace) ?? str(o.workspaceId),
27
- baseUrl: str(o.baseUrl) ?? str(o.environmentUrl) ?? (isObj(o.endpoint) ? str(o.endpoint.baseUrl) : undefined)
28
- };
29
- };
30
- const own = pick(hosts[host]);
31
- const top = pick(file);
32
- return {
33
- apiKey: own.apiKey ?? top.apiKey,
34
- peerName: own.peerName ?? top.peerName,
35
- workspace: own.workspace ?? top.workspace,
36
- aiPeer: isObj(hosts[host]) ? str(hosts[host].aiPeer) : undefined,
37
- baseUrl: own.baseUrl ?? top.baseUrl
38
- };
39
- }
40
-
41
- // node_modules/@honcho-ai/harness-plugin-core/dist/oauth.js
42
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
43
- import { dirname, join } from "node:path";
44
- var OAUTH_TOKEN_URL = "https://api.honcho.dev/oauth/token";
45
- var OAUTH_SCOPE = "write";
46
- var REQUEST_TIMEOUT_MS = 1e4;
47
- var REFRESH_SKEW_S = 60;
48
- var LOCK_STALE_MS = REQUEST_TIMEOUT_MS + 5000;
49
- var LOCK_WAIT_MS = LOCK_STALE_MS + 5000;
50
- var PERMANENT_ERRORS = new Set(["invalid_grant", "invalid_client", "unauthorized_client"]);
51
-
52
- class OAuthError extends Error {
53
- code;
54
- constructor(code, description) {
55
- super(description || code);
56
- this.code = code;
57
- this.name = "OAuthError";
58
- }
59
- }
60
- function isCloud(baseUrl) {
61
- return normalizeBaseUrl(baseUrl || DEFAULT_BASE_URL) === DEFAULT_BASE_URL;
62
- }
63
- function accessValid(t, skewS = REFRESH_SKEW_S, nowS = Date.now() / 1000) {
64
- return !!t?.accessToken && nowS < t.accessExpiresAt - skewS;
65
- }
66
- async function post(url, form, t) {
67
- const f = t?.fetch ?? fetch;
68
- let res;
69
- try {
70
- res = await f(url, {
71
- method: "POST",
72
- headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
73
- body: new URLSearchParams(form).toString(),
74
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
75
- });
76
- } catch (e) {
77
- throw new OAuthError("connection_error", `could not reach ${url}: ${e.message}`);
78
- }
79
- let body = null;
80
- try {
81
- body = await res.json();
82
- } catch {
83
- body = null;
84
- }
85
- return { status: res.status, body };
86
- }
87
- function errorOf(r) {
88
- const b = r.body;
89
- if (b && typeof b === "object" && typeof b.error === "string")
90
- return new OAuthError(b.error, b.error_description);
91
- return new OAuthError("invalid_response");
92
- }
93
- function tokensFrom(body, clientId, prev) {
94
- if (!body || typeof body.access_token !== "string" || !Number.isFinite(Number(body.expires_in))) {
95
- throw new OAuthError("invalid_response", "malformed token response");
96
- }
97
- return {
98
- accessToken: body.access_token,
99
- refreshToken: body.refresh_token || prev?.refreshToken || "",
100
- accessExpiresAt: Math.floor(Date.now() / 1000) + Number(body.expires_in),
101
- clientId,
102
- scope: body.scope || prev?.scope || OAUTH_SCOPE
103
- };
104
- }
105
- async function refreshAccessToken(prev, opts = {}) {
106
- const r = await post(opts.tokenUrl ?? OAUTH_TOKEN_URL, { grant_type: "refresh_token", refresh_token: prev.refreshToken, client_id: prev.clientId }, opts);
107
- if (r.status !== 200)
108
- throw errorOf(r);
109
- return tokensFrom(r.body, prev.clientId, prev);
110
- }
111
- function isObj2(v) {
112
- return v !== null && typeof v === "object" && !Array.isArray(v);
113
- }
114
- function asTokens(v) {
115
- if (!isObj2(v) || typeof v.accessToken !== "string" || !v.accessToken)
116
- return;
117
- return {
118
- accessToken: v.accessToken,
119
- refreshToken: typeof v.refreshToken === "string" ? v.refreshToken : "",
120
- accessExpiresAt: Number(v.accessExpiresAt) || 0,
121
- clientId: typeof v.clientId === "string" ? v.clientId : "",
122
- scope: typeof v.scope === "string" ? v.scope : ""
123
- };
124
- }
125
- function readFile(path) {
126
- if (!existsSync(path))
127
- return {};
128
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
129
- return isObj2(parsed) ? parsed : {};
130
- }
131
- function readGrant(file, host, legacy) {
132
- return asTokens(effectiveBlock(file, host, legacy).oauth);
133
- }
134
- function holderAlive(token, ageMs) {
135
- if (token === "")
136
- return ageMs < 1000;
137
- const pid = Number(token.split(":")[0]);
138
- if (!Number.isInteger(pid) || pid <= 0)
139
- return true;
140
- try {
141
- process.kill(pid, 0);
142
- return true;
143
- } catch (e) {
144
- return e.code === "EPERM";
145
- }
146
- }
147
- async function withConfigLock(path, fn) {
148
- const lock = `${path}.lock`;
149
- mkdirSync(dirname(path), { recursive: true });
150
- const start = Date.now();
151
- let fd;
152
- while (fd === undefined) {
153
- try {
154
- fd = openSync(lock, "wx", 384);
155
- } catch (e) {
156
- if (e.code !== "EEXIST")
157
- throw e;
158
- try {
159
- const age = Date.now() - statSync(lock).mtimeMs;
160
- if (age > LOCK_STALE_MS || !holderAlive(readFileSync(lock, "utf-8"), age))
161
- unlinkSync(lock);
162
- } catch {}
163
- if (Date.now() - start > LOCK_WAIT_MS)
164
- throw new Error(`timed out waiting for ${lock}`);
165
- await new Promise((r) => setTimeout(r, 50 + Math.random() * 50));
166
- }
167
- }
168
- const token = `${process.pid}:${Math.random().toString(36).slice(2)}`;
169
- try {
170
- writeFileSync(fd, token);
171
- return await fn();
172
- } finally {
173
- closeSync(fd);
174
- try {
175
- if (readFileSync(lock, "utf-8") === token)
176
- unlinkSync(lock);
177
- } catch {}
178
- }
179
- }
180
- function writeFileAtomic(path, data) {
181
- const tmp = join(dirname(path), `.${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2)}.tmp`);
182
- writeFileSync(tmp, JSON.stringify(data, null, 2) + `
183
- `, { mode: 384 });
184
- renameSync(tmp, path);
185
- }
186
- async function updateConfigFile(path, mutate) {
187
- await withConfigLock(path, async () => {
188
- const file = readFile(path);
189
- mutate(file);
190
- writeFileAtomic(path, file);
191
- });
192
- }
193
- function setGrant(file, host, tokens) {
194
- const block = hostBlock(file, host);
195
- if (tokens)
196
- block.oauth = tokens;
197
- else
198
- delete block.oauth;
199
- }
200
- function serverOf(block, baseUrl, env) {
201
- return baseUrl ?? (env.HONCHO_BASE_URL || undefined) ?? (typeof block.baseUrl === "string" && block.baseUrl ? block.baseUrl : undefined);
202
- }
203
- function pickCredential(file, opts) {
204
- const env = opts.env ?? process.env;
205
- if (env.HONCHO_API_KEY)
206
- return { token: env.HONCHO_API_KEY, source: "env" };
207
- const block = effectiveBlock(file, opts.host, opts.legacy);
208
- const g = isCloud(serverOf(block, opts.baseUrl, env)) ? asTokens(block.oauth) : undefined;
209
- if (g)
210
- return { token: g.accessToken, source: "oauth", expiresAt: g.accessExpiresAt, ...accessValid(g, 0) ? {} : { expired: true } };
211
- return typeof block.apiKey === "string" && block.apiKey ? { token: block.apiKey, source: "apiKey" } : null;
212
- }
213
- async function ensureFreshCredential(opts) {
214
- const env = opts.env ?? process.env;
215
- if (env.HONCHO_API_KEY)
216
- return { token: env.HONCHO_API_KEY, source: "env" };
217
- let file;
218
- try {
219
- file = readFile(opts.path);
220
- } catch {
221
- file = {};
222
- }
223
- const block = effectiveBlock(file, opts.host, opts.legacy);
224
- const g = isCloud(serverOf(block, opts.baseUrl, env)) ? asTokens(block.oauth) : undefined;
225
- if (!g || accessValid(g) || !g.refreshToken)
226
- return pickCredential(file, opts);
227
- let error;
228
- try {
229
- await withConfigLock(opts.path, async () => {
230
- const current = readGrant(readFile(opts.path), opts.host, opts.legacy);
231
- if (!current || accessValid(current))
232
- return;
233
- const next = await refreshAccessToken(current, opts);
234
- const latest = readFile(opts.path);
235
- setGrant(latest, opts.host, next);
236
- writeFileAtomic(opts.path, latest);
237
- });
238
- } catch (e) {
239
- error = e instanceof OAuthError ? e.code : e.message;
240
- }
241
- try {
242
- file = readFile(opts.path);
243
- } catch {}
244
- const cred = pickCredential(file, opts);
245
- if (cred && error) {
246
- cred.error = error;
247
- if (PERMANENT_ERRORS.has(error))
248
- cred.reauthRequired = true;
249
- }
250
- return cred;
251
- }
252
-
253
- // node_modules/@honcho-ai/harness-plugin-core/dist/config.js
254
- var DEFAULT_BASE_URL = "https://api.honcho.dev";
255
- var CONFIG_SCHEMA_VERSION = 2;
256
- function isObj3(v) {
257
- return v !== null && typeof v === "object" && !Array.isArray(v);
258
- }
259
- function str2(v) {
260
- return typeof v === "string" && v ? v : undefined;
261
- }
262
- function normalizeBaseUrl(input) {
263
- let s = input.trim();
264
- if (!s)
265
- return s;
266
- if (!s.startsWith("http://") && !s.startsWith("https://")) {
267
- const host = s.split("/")[0].split(":")[0].toLowerCase();
268
- const local = host === "localhost" || host === "127.0.0.1" || host === "::1";
269
- s = `${local ? "http" : "https"}://${s}`;
270
- }
271
- try {
272
- const u = new URL(s);
273
- u.hostname = u.hostname.toLowerCase();
274
- const path = u.pathname === "/" ? "" : u.pathname.replace(/\/+$/, "");
275
- return `${u.protocol}//${u.host}${path}`;
276
- } catch {
277
- return s;
278
- }
279
- }
280
- function resolveConfig(file, opts) {
281
- const env = opts.env ?? process.env;
282
- const { host } = opts;
283
- const block = effectiveBlock(file, host, opts.legacy);
284
- return {
285
- host,
286
- peerName: str2(env.HONCHO_PEER_NAME) ?? str2(block.peerName) ?? str2(env.USER) ?? str2(env.USERNAME) ?? "user",
287
- workspace: str2(env.HONCHO_WORKSPACE) ?? str2(block.workspace) ?? opts.defaults?.workspace ?? host,
288
- aiPeer: str2(env.HONCHO_AI_PEER) ?? str2(block.aiPeer) ?? opts.defaults?.aiPeer ?? host,
289
- baseUrl: normalizeBaseUrl(str2(env.HONCHO_BASE_URL) ?? str2(block.baseUrl) ?? DEFAULT_BASE_URL),
290
- warnings: checkConfig(file).map((i) => i.message)
291
- };
292
- }
293
- function configPath(env = process.env) {
294
- if (env.HONCHO_CONFIG_PATH)
295
- return env.HONCHO_CONFIG_PATH;
296
- const home = env.HOME || env.USERPROFILE || homedir();
297
- return join2(home, ".honcho", "config.json");
298
- }
299
- function readConfigFile(env = process.env) {
300
- const path = configPath(env);
301
- if (!existsSync2(path))
302
- return {};
303
- try {
304
- const parsed = JSON.parse(readFileSync2(path, "utf-8"));
305
- return isObj3(parsed) ? parsed : {};
306
- } catch {
307
- return {};
308
- }
309
- }
310
- async function saveHost(path, host, patch, legacy) {
311
- await updateConfigFile(path, (file) => {
312
- if (isNewer(file))
313
- throw new Error(`${path} was written by a newer Honcho plugin; update this one.`);
314
- const block = writeBlock(file, host, hostMigration(file, host, [], legacy));
315
- if ("baseUrl" in patch && !("apiKey" in patch) && !sameServer(patch.baseUrl, str2(block.baseUrl)))
316
- delete block.apiKey;
317
- for (const [k, v] of Object.entries(patch)) {
318
- if (v === undefined)
319
- delete block[k];
320
- else
321
- block[k] = v;
322
- }
323
- block.schemaVersion = CONFIG_SCHEMA_VERSION;
324
- });
325
- }
326
- var MOVABLE = ["apiKey", "peerName", "workspace", "aiPeer", "baseUrl"];
327
- function isNewer(file) {
328
- return isObj3(file) && typeof file.schemaVersion === "number" && file.schemaVersion > CONFIG_SCHEMA_VERSION;
329
- }
330
- function isMigrated(block) {
331
- return isObj3(block) && typeof block.schemaVersion === "number" && block.schemaVersion >= CONFIG_SCHEMA_VERSION;
332
- }
333
- function sameServer(a, b) {
334
- return normalizeBaseUrl(a ?? DEFAULT_BASE_URL) === normalizeBaseUrl(b ?? DEFAULT_BASE_URL);
335
- }
336
- var LEGACY_HOST_KEYS = ["auth", "endpoint", "environmentUrl", "workspaceId"];
337
- function isGrant(v) {
338
- return isObj3(v) && typeof v.accessToken === "string" && v.accessToken !== "";
339
- }
340
- function legacyGrantOf(b) {
341
- return !isGrant(b.oauth) && isObj3(b.auth) && isObj3(b.auth.oauth) ? b.auth.oauth : undefined;
342
- }
343
- function checkConfig(file) {
344
- if (!isObj3(file))
345
- return [];
346
- if (isNewer(file)) {
347
- return [{ path: "schemaVersion", message: `This file is schema version ${file.schemaVersion}, newer than this plugin understands; update the plugin.` }];
348
- }
349
- const issues = [];
350
- const hosts = isObj3(file.hosts) ? file.hosts : {};
351
- const byWorkspace = new Map;
352
- for (const h of Object.keys(hosts).filter((k) => isObj3(hosts[k]))) {
353
- const block = hosts[h];
354
- const peer = str2(block.peerName);
355
- if (!peer)
356
- continue;
357
- const ws = str2(block.workspace) ?? h;
358
- const peers = byWorkspace.get(ws) ?? new Map;
359
- peers.set(peer, [...peers.get(peer) ?? [], h]);
360
- byWorkspace.set(ws, peers);
361
- }
362
- for (const [ws, peers] of byWorkspace) {
363
- if (peers.size < 2)
364
- continue;
365
- const list = [...peers].map(([p, hs]) => `${hs.join(", ")}: "${p}"`).join("; ");
366
- issues.push({ path: "hosts", message: `Hosts in workspace "${ws}" use different peerNames (${list}), so the user is split across peers.` });
367
- }
368
- return issues;
369
- }
370
- function hostMigration(file, host, deadKeys = [], legacy = v01Reader) {
371
- if (isNewer(file))
372
- return { set: {}, remove: [] };
373
- const f = isObj3(file) ? file : {};
374
- const hosts = isObj3(f.hosts) ? f.hosts : {};
375
- const block = isObj3(hosts[host]) ? hosts[host] : {};
376
- const set = {};
377
- const drop = [];
378
- const grant = legacyGrantOf(block);
379
- if (grant)
380
- set.oauth = grant;
381
- if (!isMigrated(block)) {
382
- const old = { ...legacy(f, host) };
383
- const signedIn = isGrant(block.oauth) || grant !== undefined;
384
- if (old.baseUrl && sameServer(old.baseUrl, undefined))
385
- old.baseUrl = undefined;
386
- for (const key of MOVABLE) {
387
- if (signedIn && (key === "apiKey" || key === "baseUrl"))
388
- continue;
389
- if (old[key] !== undefined && block[key] !== old[key])
390
- set[key] = old[key];
391
- else if (old[key] === undefined && block[key] !== undefined)
392
- drop.push(key);
393
- }
394
- set.schemaVersion = CONFIG_SCHEMA_VERSION;
395
- }
396
- const remove = [...drop, ...LEGACY_HOST_KEYS, ...deadKeys].filter((k) => (k in block) && !(k in set));
397
- return { set, remove };
398
- }
399
- function effectiveBlock(file, host, legacy) {
400
- return writeBlock(structuredClone(isObj3(file) ? file : {}), host, hostMigration(file, host, [], legacy));
401
- }
402
- function hostBlock(file, host) {
403
- if (host === "__proto__" || host === "constructor" || host === "prototype")
404
- throw new Error(`invalid host name: ${host}`);
405
- if (!isObj3(file.hosts))
406
- file.hosts = {};
407
- return isObj3(file.hosts[host]) ? file.hosts[host] : file.hosts[host] = {};
408
- }
409
- function writeBlock(file, host, { set, remove }) {
410
- const block = hostBlock(file, host);
411
- Object.assign(block, set);
412
- for (const k of remove)
413
- delete block[k];
414
- return block;
415
- }
416
- async function migrateHost(path, host, deadKeys = [], legacy) {
417
- const peek = hostMigration(readConfigFile({ HONCHO_CONFIG_PATH: path }), host, deadKeys, legacy);
418
- if (!Object.keys(peek.set).length && !peek.remove.length)
419
- return [];
420
- let changed = [];
421
- await updateConfigFile(path, (file) => {
422
- const m = hostMigration(file, host, deadKeys, legacy);
423
- changed = [...Object.keys(m.set).filter((k) => k !== "schemaVersion"), ...m.remove.map((k) => `-${k}`)];
424
- if (Object.keys(m.set).length || m.remove.length)
425
- writeBlock(file, host, m);
426
- });
427
- return changed;
428
- }
429
- // node_modules/@honcho-ai/harness-plugin-core/dist/legacy/claude-honcho.js
430
- var isObj4 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
431
- var str3 = (v) => typeof v === "string" && v ? v : undefined;
432
- function claudeHonchoReader(file, host) {
433
- const hosts = isObj4(file.hosts) ? file.hosts : {};
434
- const found = hosts[host] ?? hosts[host.replace(/_/g, "-")] ?? hosts[host.replace(/-/g, "_")];
435
- const block = isObj4(found) ? found : undefined;
436
- const endpoint = block?.endpoint ?? file.endpoint;
437
- const override = file.globalOverride === true;
438
- return {
439
- apiKey: str3(block?.apiKey) ?? str3(file.apiKey),
440
- baseUrl: str3(endpoint?.baseUrl)?.replace(/\/v3\/?$/, "") ?? (endpoint?.environment === "local" ? "http://localhost:8000" : undefined),
441
- peerName: str3(file.peerName),
442
- workspace: str3(override || !block ? file.workspace : block.workspace),
443
- aiPeer: str3(override ? file.aiPeer ?? block?.aiPeer : block ? block.aiPeer : file[host === "cursor" ? "cursorPeer" : "claudePeer"])
444
- };
445
- }
446
- // node_modules/@honcho-ai/harness-plugin-core/dist/telemetry.js
447
- var HEADER_HOST = "X-Honcho-Host";
448
- var HEADER_PLUGIN = "X-Honcho-Plugin";
449
- var HEADER_AGENT_MODEL = "X-Honcho-Agent-Model";
450
- function sanitize(value) {
451
- if (typeof value !== "string")
452
- return;
453
- const s = value.replace(/[\r\n]+/g, " ").trim();
454
- return s || undefined;
455
- }
456
- function token(name, ver) {
457
- const clean = (v) => sanitize(v)?.replace(/[\s()/;]+/g, "-");
458
- const n = clean(name);
459
- const v = clean(ver);
460
- if (n && v)
461
- return `${n}/${v}`;
462
- return n || v;
463
- }
464
- function hostHeaderValue(id = {}) {
465
- const host = token(id.host, id.hostVersion);
466
- if (!host)
467
- return;
468
- const platform = token(id.platform ?? process.platform, undefined);
469
- return platform ? `${host} (${platform})` : host;
470
- }
471
- function pluginHeaderValue(id = {}) {
472
- return token(id.plugin, id.pluginVersion);
473
- }
474
- function telemetryHeaders(id = {}, extra) {
475
- const headers = {};
476
- const host = hostHeaderValue(id);
477
- const plugin = pluginHeaderValue(id);
478
- const model = sanitize(id.model);
479
- if (host)
480
- headers[HEADER_HOST] = host;
481
- if (plugin)
482
- headers[HEADER_PLUGIN] = plugin;
483
- if (model)
484
- headers[HEADER_AGENT_MODEL] = model;
485
- if (extra) {
486
- for (const [k, v] of Object.entries(extra)) {
487
- const value = sanitize(v);
488
- if (value)
489
- headers[k] = value;
490
- }
491
- }
492
- return headers;
493
- }
494
- // src/config.ts
495
- var LEGACY = claudeHonchoReader;
496
- function sanitizeForSessionName(s) {
497
- return s.toLowerCase().replace(/[^a-z0-9-_]/g, "-");
498
- }
499
- var _detectedHost = null;
500
- function setDetectedHost(host) {
501
- _detectedHost = host;
502
- }
503
- function getDetectedHost() {
504
- return _detectedHost ?? "claude_code";
505
- }
506
- function detectHost(stdinInput) {
507
- const envHost = process.env.HONCHO_HOST;
508
- if (envHost === "cursor" || envHost === "claude_code" || envHost === "obsidian")
509
- return envHost;
510
- if (stdinInput?.cursor_version)
511
- return "cursor";
512
- if (process.env.CURSOR_PROJECT_DIR)
513
- return "cursor";
514
- return "claude_code";
515
- }
516
- var DEFAULT_WORKSPACE = {
517
- cursor: "cursor",
518
- claude_code: "claude_code",
519
- obsidian: "obsidian"
520
- };
521
- var DEFAULT_AI_PEER = {
522
- cursor: "cursor",
523
- claude_code: "claude",
524
- obsidian: "honcho"
525
- };
526
- var _stdinText = null;
527
- function cacheStdin(text) {
528
- _stdinText = text;
529
- }
530
- function getCachedStdin() {
531
- return _stdinText;
532
- }
533
- async function readStdinText() {
534
- const chunks = [];
535
- for await (const chunk of process.stdin)
536
- chunks.push(chunk);
537
- return Buffer.concat(chunks).toString("utf-8");
538
- }
539
- async function initHook() {
540
- const stdinText = await readStdinText();
541
- cacheStdin(stdinText);
542
- let input = {};
543
- try {
544
- input = JSON.parse(stdinText || "{}");
545
- } catch {
546
- process.exit(0);
547
- }
548
- if (input.cursor_version)
549
- process.exit(0);
550
- setDetectedHost(detectHost(input));
551
- }
552
- function getConfigPath() {
553
- return configPath();
554
- }
555
- function getConfigDir() {
556
- return dirname2(configPath());
557
- }
558
- function configExists() {
559
- return existsSync3(configPath());
560
- }
561
- function getPluginVersion() {
562
- const root = process.env.CLAUDE_PLUGIN_ROOT;
563
- const candidates = [
564
- ...root ? [join3(root, ".claude-plugin", "plugin.json")] : [],
565
- fileURLToPath(new URL("../.claude-plugin/plugin.json", import.meta.url))
566
- ];
567
- for (const manifest of candidates) {
568
- try {
569
- const version = JSON.parse(readFileSync3(manifest, "utf-8")).version;
570
- if (typeof version === "string" && version)
571
- return version;
572
- } catch {}
573
- }
574
- return "unknown";
575
- }
576
- function legacyEndpoint(value) {
577
- if (value === "local")
578
- return "http://localhost:8000";
579
- if (value?.startsWith("http"))
580
- return value.replace(/\/v3\/?$/, "");
581
- return;
582
- }
583
- function legacyEnv(host = getDetectedHost()) {
584
- const env = process.env;
585
- const peerVar = host === "cursor" ? "HONCHO_CURSOR_PEER" : "HONCHO_CLAUDE_PEER";
586
- const candidates = [
587
- ["HONCHO_BASE_URL", "baseUrl", "HONCHO_ENDPOINT", legacyEndpoint(env.HONCHO_ENDPOINT)],
588
- ["HONCHO_AI_PEER", "aiPeer", peerVar, env[peerVar] || undefined]
589
- ];
590
- const set = candidates.filter(([newVar, , , value]) => value && !env[newVar]);
591
- if (!set.length)
592
- return {};
593
- const block = effectiveBlock(readConfigFile(), host, LEGACY);
594
- if (block.apiKey || block.oauth)
595
- return {};
596
- return Object.fromEntries(set.filter(([, setting]) => !block[setting]).map(([newVar, , oldVar, value]) => [newVar, [oldVar, value]]));
597
- }
598
- function honchoEnv(host) {
599
- const legacy = Object.entries(legacyEnv(host));
600
- if (!legacy.length)
601
- return process.env;
602
- return { ...process.env, ...Object.fromEntries(legacy.map(([k, [, value]]) => [k, value])) };
603
- }
604
- function resolveHost(host) {
605
- return resolveConfig(readConfigFile(), {
606
- host,
607
- env: honchoEnv(host),
608
- defaults: { workspace: DEFAULT_WORKSPACE[host], aiPeer: DEFAULT_AI_PEER[host] },
609
- legacy: LEGACY
610
- });
611
- }
612
- function isLoggingEnabled(host = getDetectedHost()) {
613
- if (process.env.HONCHO_LOGGING === "false")
614
- return false;
615
- const file = readConfigFile();
616
- const hosts = file.hosts && typeof file.hosts === "object" ? file.hosts : {};
617
- const own = [hosts[host], hosts[host.replace(/_/g, "-")]].map((block) => block && typeof block === "object" ? block.logging : undefined).find((v) => v !== undefined);
618
- return (own ?? file.logging) !== false;
619
- }
620
- function loadConfig2(host = getDetectedHost()) {
621
- const cfg = resolveHost(host);
622
- const cred = pickCredential(readConfigFile(), { host, baseUrl: cfg.baseUrl, env: honchoEnv(host), legacy: LEGACY });
623
- if (!cred)
624
- return null;
625
- const { token, ...authState } = cred;
626
- return {
627
- apiKey: token,
628
- auth: { ...authState, host },
629
- peerName: cfg.peerName,
630
- workspace: cfg.workspace,
631
- aiPeer: cfg.aiPeer,
632
- baseUrl: cfg.baseUrl
633
- };
634
- }
635
- async function saveConfig(config, field) {
636
- const host = getDetectedHost();
637
- const env = honchoEnv(host);
638
- const write = (key, envVar) => key === field || !env[envVar];
639
- const patch = {};
640
- if (write("peerName", "HONCHO_PEER_NAME"))
641
- patch.peerName = config.peerName;
642
- if (write("workspace", "HONCHO_WORKSPACE"))
643
- patch.workspace = config.workspace === DEFAULT_WORKSPACE[host] ? undefined : config.workspace;
644
- if (write("aiPeer", "HONCHO_AI_PEER"))
645
- patch.aiPeer = config.aiPeer === DEFAULT_AI_PEER[host] ? undefined : config.aiPeer;
646
- if (write("baseUrl", "HONCHO_BASE_URL"))
647
- patch.baseUrl = config.baseUrl === DEFAULT_BASE_URL ? undefined : config.baseUrl;
648
- await saveHost(configPath(), host, patch, LEGACY);
649
- }
650
- function getConfigIssues(host = getDetectedHost()) {
651
- return checkConfig(readConfigFile()).filter((i) => i.path === "schemaVersion" || i.path === "hosts" && i.message.includes(host)).map((i) => i.message);
652
- }
653
- var DEAD_HOST_KEYS = [
654
- "sessionStrategy",
655
- "sessionPeerPrefix",
656
- "sessions",
657
- "injection",
658
- "contextRefresh",
659
- "messageUpload",
660
- "reasoningLevel",
661
- "statusline",
662
- "saveToolUse",
663
- "saveGitEvents",
664
- "redactPatterns",
665
- "rememberTool",
666
- "observationMode",
667
- "saveMessages",
668
- "enabled",
669
- "globalOverride",
670
- "linkedHosts"
671
- ];
672
- async function migrateConfig(host = getDetectedHost()) {
673
- try {
674
- const changed = await migrateHost(configPath(), host, DEAD_HOST_KEYS, LEGACY);
675
- if (changed.length)
676
- return `[honcho] Moved your Honcho settings into hosts.${host} in ~/.honcho/config.json.`;
677
- } catch {}
678
- return;
679
- }
680
- function getSessionName(sessionId) {
681
- const id = sessionId || process.env.CLAUDE_CODE_SESSION_ID;
682
- return id ? sanitizeForSessionName(id) : null;
683
- }
684
- function getKnownHosts() {
685
- const hosts = readConfigFile().hosts;
686
- return hosts && typeof hosts === "object" ? Object.keys(hosts) : [];
687
- }
688
- async function refreshCredential(config) {
689
- const host = config.auth?.host ?? getDetectedHost();
690
- const cred = await ensureFreshCredential({ path: configPath(), host, baseUrl: config.baseUrl, env: honchoEnv(host), legacy: LEGACY });
691
- if (!cred)
692
- return;
693
- const { token, ...authState } = cred;
694
- config.apiKey = token;
695
- config.auth = { ...authState, host };
696
- }
697
- function getAuthNotice(config) {
698
- if (config.auth?.reauthRequired) {
699
- return "[honcho] Your Honcho sign-in has expired. Run /honcho setup to sign in again.";
700
- }
701
- return;
702
- }
703
- function getHonchoBaseUrl(config) {
704
- return `${config.baseUrl}/v3`;
705
- }
706
- function getTelemetryHeaders(host = getDetectedHost()) {
707
- return telemetryHeaders({
708
- host: host.replace(/_/g, "-"),
709
- plugin: "claude-honcho",
710
- pluginVersion: getPluginVersion()
711
- });
712
- }
713
- function getHonchoClientOptions(config) {
714
- return {
715
- apiKey: config.apiKey,
716
- baseURL: getHonchoBaseUrl(config),
717
- workspaceId: config.workspace,
718
- timeout: 120000,
719
- maxRetries: 1,
720
- defaultHeaders: getTelemetryHeaders()
721
- };
722
- }
723
- function isProductionEndpoint(config) {
724
- return config.baseUrl === DEFAULT_BASE_URL;
725
- }
726
- function getEndpointInfo(config) {
727
- return { type: isProductionEndpoint(config) ? "production" : "custom", url: config.baseUrl };
728
- }
729
-
730
- // src/state.ts
731
- import { homedir as homedir2 } from "os";
732
- import { join as join4 } from "path";
733
- import { writeFileSync as writeFileSync2, unlinkSync as unlinkSync2 } from "fs";
734
- var DIR = join4(homedir2(), ".honcho");
735
- function stateFile(sessionId) {
736
- return join4(DIR, sessionId ? `state-${sessionId}.json` : "state.json");
737
- }
738
- function sessionFile(sessionId) {
739
- return join4(DIR, sessionId ? `session-${sessionId}.json` : "session.json");
740
- }
741
- function noticeFile(sessionId) {
742
- return join4(DIR, `notice-${sessionId}.json`);
743
- }
744
- function isModActive() {
745
- return process.env.HONCHO_MOD_UI === "1";
746
- }
747
- function setNotice(text, sessionId) {
748
- try {
749
- writeFileSync2(noticeFile(sessionId), JSON.stringify({ text }));
750
- } catch {}
751
- }
752
- function setMemoryState(phase, detail, sessionId) {
753
- try {
754
- writeFileSync2(stateFile(sessionId), JSON.stringify({ phase, since: Date.now(), detail }));
755
- } catch {}
756
- }
757
- function setSessionLink(url, name, sessionId) {
758
- try {
759
- writeFileSync2(sessionFile(sessionId), JSON.stringify({ url, name }));
760
- } catch {}
761
- }
762
- function clearSessionFiles(sessionId) {
763
- if (!sessionId)
764
- return;
765
- for (const f of [stateFile(sessionId), sessionFile(sessionId), noticeFile(sessionId)]) {
766
- try {
767
- unlinkSync2(f);
768
- } catch {}
769
- }
770
- }
771
-
772
- // src/hooks/pre-tool-honcho.ts
773
- var LABELS = {
774
- search: "searching",
775
- chat: "asking",
776
- create_conclusion: "writing",
777
- list_conclusions: "listing",
778
- delete_conclusion: "writing",
779
- get_config: "config",
780
- set_config: "config"
781
- };
782
- async function handlePreToolHoncho() {
783
- if (isModActive())
784
- process.exit(0);
785
- try {
786
- const raw = getCachedStdin();
787
- const input = raw && raw.trim() ? JSON.parse(raw) : {};
788
- const toolName = input.tool_name ?? "";
789
- const verb = toolName.replace(/^mcp__plugin_honcho_honcho__/, "");
790
- setMemoryState("querying", LABELS[verb] ?? verb ?? "tool", input.session_id);
791
- } catch {}
792
- process.exit(0);
793
- }
794
- async function main() {
795
- await initHook();
796
- await handlePreToolHoncho();
797
- }
798
-
799
- // hooks/pre-tool-honcho.ts
800
- await main();
801
-
802
- //# debugId=F1F92C66A06367F864756E2164756E21
803
- //# sourceMappingURL=pre-tool-honcho.js.map