@honcho-ai/claude-honcho 0.3.3 → 0.4.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.
Files changed (36) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +111 -335
  3. package/dist/hooks/pre-tool-honcho.js +551 -605
  4. package/dist/hooks/pre-tool-honcho.js.map +11 -9
  5. package/dist/hooks/save-user-message.js +1741 -1057
  6. package/dist/hooks/save-user-message.js.map +24 -19
  7. package/dist/hooks/session-end.js +559 -617
  8. package/dist/hooks/session-end.js.map +11 -9
  9. package/dist/hooks/session-start.js +1938 -1304
  10. package/dist/hooks/session-start.js.map +31 -22
  11. package/dist/hooks/stop.js +1785 -1157
  12. package/dist/hooks/stop.js.map +25 -19
  13. package/dist/hooks/user-prompt.js +696 -16571
  14. package/dist/hooks/user-prompt.js.map +13 -90
  15. package/dist/mcp-server.js +1689 -1676
  16. package/dist/mcp-server.js.map +23 -20
  17. package/dist/skills/backfill-runner.js +1824 -911
  18. package/dist/skills/backfill-runner.js.map +27 -20
  19. package/dist/skills/{setup-runner.js → pane-runner.js} +1910 -1020
  20. package/dist/{hooks/pre-compact.js.map → skills/pane-runner.js.map} +28 -24
  21. package/dist/skills/status-runner.js +1568 -753
  22. package/dist/skills/status-runner.js.map +23 -19
  23. package/hooks/hooks.json +10 -42
  24. package/hooks/register.tsx +574 -0
  25. package/package.json +1 -1
  26. package/skills/insights/SKILL.md +3 -7
  27. package/dist/hooks/post-tool-use.js +0 -16905
  28. package/dist/hooks/post-tool-use.js.map +0 -97
  29. package/dist/hooks/pre-compact.js +0 -17087
  30. package/dist/skills/setup-runner.js.map +0 -95
  31. package/scripts/honcho-statusline.sh +0 -101
  32. package/skills/briefing/SKILL.md +0 -20
  33. package/skills/config/SKILL.md +0 -288
  34. package/skills/import/SKILL.md +0 -73
  35. package/skills/setup/SKILL.md +0 -60
  36. package/skills/status/SKILL.md +0 -30
@@ -1,274 +1,449 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
3
  // src/config.ts
4
- import { homedir as homedir2 } from "os";
5
- import { join as join3, basename, dirname, resolve, sep } from "path";
4
+ import { join as join3, dirname as dirname2 } from "path";
6
5
  import { fileURLToPath } from "url";
7
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
6
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
8
7
 
9
- // src/git.ts
10
- import { execSync } from "child_process";
11
- import { existsSync } from "fs";
12
- import { join } from "path";
13
- function isGitRepo(cwd) {
14
- return existsSync(join(cwd, ".git"));
15
- }
16
- function gitCommand(cwd, args) {
17
- try {
18
- return execSync(`git ${args}`, { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
19
- } catch {
20
- return null;
21
- }
22
- }
23
- function captureGitState(cwd) {
24
- if (!isGitRepo(cwd)) {
25
- return null;
26
- }
27
- const branch = gitCommand(cwd, "rev-parse --abbrev-ref HEAD") || "unknown";
28
- const commit = gitCommand(cwd, "rev-parse --short HEAD") || "unknown";
29
- const commitMessage = gitCommand(cwd, "log -1 --format=%s") || "";
30
- const statusOutput = gitCommand(cwd, "status --porcelain") || "";
31
- const isDirty = statusOutput.length > 0;
32
- const dirtyFiles = isDirty ? statusOutput.split(`
33
- `).filter((line) => line.trim()).map((line) => line.slice(3).trim()).slice(0, 20) : [];
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);
34
32
  return {
35
- branch,
36
- commit,
37
- commitMessage,
38
- isDirty,
39
- dirtyFiles,
40
- timestamp: new Date().toISOString()
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
41
38
  };
42
39
  }
43
40
 
44
- // src/cache.ts
45
- import { homedir } from "os";
46
- import { join as join2 } from "path";
47
- import { existsSync as existsSync2, readFileSync, writeFileSync, mkdirSync } from "fs";
48
- var CACHE_DIR = join2(homedir(), ".honcho");
49
- var ID_CACHE_FILE = join2(CACHE_DIR, "cache.json");
50
- var CONTEXT_CACHE_FILE = join2(CACHE_DIR, "context-cache.json");
51
- function ensureCacheDir() {
52
- if (!existsSync2(CACHE_DIR)) {
53
- mkdirSync(CACHE_DIR, { recursive: true });
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";
54
58
  }
55
59
  }
56
- function loadIdCache() {
57
- ensureCacheDir();
58
- if (!existsSync2(ID_CACHE_FILE)) {
59
- return {};
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}`);
60
78
  }
79
+ let body = null;
61
80
  try {
62
- return JSON.parse(readFileSync(ID_CACHE_FILE, "utf-8"));
81
+ body = await res.json();
63
82
  } catch {
64
- return {};
83
+ body = null;
65
84
  }
85
+ return { status: res.status, body };
66
86
  }
67
- function saveIdCache(cache) {
68
- ensureCacheDir();
69
- writeFileSync(ID_CACHE_FILE, JSON.stringify(cache, null, 2));
70
- }
71
- function setCachedSessionId(cwd, name, id, instanceId) {
72
- const cache = loadIdCache();
73
- if (!cache.sessions)
74
- cache.sessions = {};
75
- cache.sessions[cwd] = { name, id, updatedAt: new Date().toISOString(), instanceId };
76
- saveIdCache(cache);
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");
77
92
  }
78
- function getLastActiveCwd() {
79
- const cache = loadIdCache();
80
- if (!cache.sessions)
81
- return null;
82
- let latest = null;
83
- for (const [cwd, entry] of Object.entries(cache.sessions)) {
84
- if (!latest || entry.updatedAt > latest.updatedAt) {
85
- latest = { cwd, updatedAt: entry.updatedAt };
86
- }
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");
87
96
  }
88
- return latest?.cwd || null;
89
- }
90
- function getClaudeInstanceId() {
91
- const cache = loadIdCache();
92
- return cache.claudeInstanceId || null;
93
- }
94
- function setClaudeInstanceId(instanceId) {
95
- const cache = loadIdCache();
96
- cache.claudeInstanceId = instanceId;
97
- saveIdCache(cache);
98
- }
99
- function getInstanceIdForCwd(cwd) {
100
- const cache = loadIdCache();
101
- return cache.sessions?.[cwd]?.instanceId ?? null;
102
- }
103
- var CONTEXT_CACHE_KNOWN_KEYS = new Set([
104
- "claudeContext",
105
- "summaries",
106
- "messageCount"
107
- ]);
108
- function loadContextCache() {
109
- ensureCacheDir();
110
- if (!existsSync2(CONTEXT_CACHE_FILE)) {
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))
111
127
  return {};
112
- }
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;
113
140
  try {
114
- const raw = JSON.parse(readFileSync(CONTEXT_CACHE_FILE, "utf-8"));
115
- let cleaned = false;
116
- for (const key of Object.keys(raw)) {
117
- if (!CONTEXT_CACHE_KNOWN_KEYS.has(key)) {
118
- delete raw[key];
119
- cleaned = true;
120
- }
121
- }
122
- if (cleaned) {
123
- writeFileSync(CONTEXT_CACHE_FILE, JSON.stringify(raw, null, 2));
124
- }
125
- return raw;
126
- } catch {
127
- return {};
141
+ process.kill(pid, 0);
142
+ return true;
143
+ } catch (e) {
144
+ return e.code === "EPERM";
128
145
  }
129
146
  }
130
- function saveContextCache(cache) {
131
- ensureCacheDir();
132
- writeFileSync(CONTEXT_CACHE_FILE, JSON.stringify(cache, null, 2));
133
- }
134
- function incrementMessageCount() {
135
- const cache = loadContextCache();
136
- cache.messageCount = (cache.messageCount || 0) + 1;
137
- saveContextCache(cache);
138
- return cache.messageCount;
139
- }
140
- function getMessageCount() {
141
- const cache = loadContextCache();
142
- return cache.messageCount || 0;
143
- }
144
- function resetMessageCount() {
145
- const cache = loadContextCache();
146
- cache.messageCount = 0;
147
- saveContextCache(cache);
148
- }
149
- var GIT_STATE_FILE = join2(CACHE_DIR, "git-state.json");
150
- function loadGitStateCache() {
151
- ensureCacheDir();
152
- if (!existsSync2(GIT_STATE_FILE)) {
153
- return {};
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
+ }
154
167
  }
168
+ const token = `${process.pid}:${Math.random().toString(36).slice(2)}`;
155
169
  try {
156
- return JSON.parse(readFileSync(GIT_STATE_FILE, "utf-8"));
157
- } catch {
158
- return {};
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 {}
159
178
  }
160
179
  }
161
- function saveGitStateCache(cache) {
162
- ensureCacheDir();
163
- writeFileSync(GIT_STATE_FILE, JSON.stringify(cache, null, 2));
164
- }
165
- function getCachedGitState(cwd) {
166
- const cache = loadGitStateCache();
167
- return cache[cwd] || null;
168
- }
169
- function setCachedGitState(cwd, state) {
170
- const cache = loadGitStateCache();
171
- cache[cwd] = state;
172
- saveGitStateCache(cache);
173
- }
174
- function detectGitChanges(previous, current) {
175
- const changes = [];
176
- if (!previous) {
177
- changes.push({
178
- type: "initial",
179
- description: `Session started on branch '${current.branch}' at ${current.commit}`
180
- });
181
- return changes;
182
- }
183
- if (previous.branch !== current.branch) {
184
- changes.push({
185
- type: "branch_switch",
186
- description: `Branch switched from '${previous.branch}' to '${current.branch}'`,
187
- from: previous.branch,
188
- to: current.branch
189
- });
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 = {};
190
222
  }
191
- if (previous.commit !== current.commit) {
192
- changes.push({
193
- type: "new_commits",
194
- description: `New commit: ${current.commit} - ${current.commitMessage}`,
195
- from: previous.commit,
196
- to: current.commit
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);
197
237
  });
238
+ } catch (e) {
239
+ error = e instanceof OAuthError ? e.code : e.message;
198
240
  }
199
- if (!previous.isDirty && current.isDirty) {
200
- changes.push({
201
- type: "files_changed",
202
- description: `Uncommitted changes detected: ${current.dirtyFiles.slice(0, 5).join(", ")}${current.dirtyFiles.length > 5 ? "..." : ""}`
203
- });
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;
204
249
  }
205
- return changes;
250
+ return cred;
206
251
  }
207
- var MAX_MESSAGE_SIZE = 24000;
208
- function chunkContent(content, maxSize = MAX_MESSAGE_SIZE) {
209
- if (content.length <= maxSize) {
210
- return [content];
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}`;
211
270
  }
212
- const chunks = [];
213
- let remaining = content;
214
- while (remaining.length > 0) {
215
- if (remaining.length <= maxSize) {
216
- chunks.push(remaining);
217
- break;
218
- }
219
- let splitIndex = remaining.lastIndexOf(`
220
- `, maxSize);
221
- if (splitIndex <= 0 || splitIndex < maxSize * 0.25) {
222
- splitIndex = remaining.lastIndexOf(" ", maxSize);
223
- }
224
- if (splitIndex <= 0 || splitIndex < maxSize * 0.25) {
225
- splitIndex = maxSize;
226
- }
227
- chunks.push(remaining.slice(0, splitIndex));
228
- remaining = remaining.slice(splitIndex).trimStart();
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;
229
278
  }
230
- if (chunks.length > 1) {
231
- return chunks.map((chunk, i) => `[Part ${i + 1}/${chunks.length}] ${chunk}`);
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 {};
232
308
  }
233
- return chunks;
234
- }
235
- var HONCHO_MAX_BATCH = 100;
236
- async function addMessagesBatched(session, messages, resolveFallback) {
237
- let active = session;
238
- let usedFallback = false;
239
- for (let i = 0;i < messages.length; i += HONCHO_MAX_BATCH) {
240
- const batch = messages.slice(i, i + HONCHO_MAX_BATCH);
241
- try {
242
- await active.addMessages(batch);
243
- } catch (e) {
244
- if (usedFallback || !resolveFallback)
245
- throw e;
246
- active = await resolveFallback(e);
247
- usedFallback = true;
248
- await active.addMessages(batch);
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;
249
322
  }
250
- }
323
+ block.schemaVersion = CONFIG_SCHEMA_VERSION;
324
+ });
251
325
  }
252
- function clearIdCache() {
253
- ensureCacheDir();
254
- writeFileSync(ID_CACHE_FILE, "{}");
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;
255
329
  }
256
- function clearPeerCache() {
257
- const cache = loadIdCache();
258
- delete cache.peers;
259
- saveIdCache(cache);
330
+ function isMigrated(block) {
331
+ return isObj3(block) && typeof block.schemaVersion === "number" && block.schemaVersion >= CONFIG_SCHEMA_VERSION;
260
332
  }
261
- function clearUserContextOnly() {
262
- const cache = loadContextCache();
263
- delete cache.userContext;
264
- saveContextCache(cache);
333
+ function sameServer(a, b) {
334
+ return normalizeBaseUrl(a ?? DEFAULT_BASE_URL) === normalizeBaseUrl(b ?? DEFAULT_BASE_URL);
265
335
  }
266
- function clearClaudeContextOnly() {
267
- const cache = loadContextCache();
268
- delete cache.claudeContext;
269
- saveContextCache(cache);
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
+ };
270
445
  }
271
- // node_modules/@honcho-ai/harness-plugin-core/src/telemetry.ts
446
+ // node_modules/@honcho-ai/harness-plugin-core/dist/telemetry.js
272
447
  var HEADER_HOST = "X-Honcho-Host";
273
448
  var HEADER_PLUGIN = "X-Honcho-Plugin";
274
449
  var HEADER_AGENT_MODEL = "X-Honcho-Agent-Model";
@@ -317,31 +492,10 @@ function telemetryHeaders(id = {}, extra) {
317
492
  return headers;
318
493
  }
319
494
  // src/config.ts
495
+ var LEGACY = claudeHonchoReader;
320
496
  function sanitizeForSessionName(s) {
321
497
  return s.toLowerCase().replace(/[^a-z0-9-_]/g, "-");
322
498
  }
323
- var SESSION_START_COMPONENTS = ["directives", "summary", "peerCard", "peerRepresentation", "briefing"];
324
- var PER_TURN_COMPONENTS = ["userContext", "assistantContext", "sessionContext", "dialectic"];
325
- function normalizePerTurn(components) {
326
- return components.map((c) => c === "context" ? "userContext" : c);
327
- }
328
- var DEFAULT_INJECTION = {
329
- sessionStart: ["directives", "summary", "peerCard"],
330
- perTurn: ["userContext"],
331
- showContents: [],
332
- searchTopK: 10,
333
- maxConclusions: 15,
334
- searchMaxDistance: 0.6,
335
- searchQuerySource: "prompt",
336
- sessionContextTokens: 1500,
337
- dialecticTemplate: "Return a compact, factual list of anything from the user's history — preferences, prior decisions, relevant past work — that would help with the following. Write in the third person as background notes; do not address the user, ask questions, or offer next steps. If nothing relevant exists, say so in one line. Relevant to: %{user_query}",
338
- dialecticReasoning: "medium"
339
- };
340
- var REASONING_LEVELS = ["minimal", "low", "medium", "high", "max"];
341
- var HONCHO_BASE_URLS = {
342
- production: "https://api.honcho.dev/v3",
343
- local: "http://localhost:8000/v3"
344
- };
345
499
  var _detectedHost = null;
346
500
  function setDetectedHost(host) {
347
501
  _detectedHost = host;
@@ -369,13 +523,6 @@ var DEFAULT_AI_PEER = {
369
523
  claude_code: "claude",
370
524
  obsidian: "honcho"
371
525
  };
372
- function coerceBoolean(value) {
373
- if (typeof value === "string") {
374
- const v = value.trim().toLowerCase();
375
- return v !== "false" && v !== "0" && v !== "";
376
- }
377
- return Boolean(value);
378
- }
379
526
  var _stdinText = null;
380
527
  function cacheStdin(text) {
381
528
  _stdinText = text;
@@ -402,31 +549,14 @@ async function initHook() {
402
549
  process.exit(0);
403
550
  setDetectedHost(detectHost(input));
404
551
  }
405
- function deepEqual(a, b) {
406
- if (a === b)
407
- return true;
408
- if (a == null || b == null)
409
- return a === b;
410
- if (typeof a !== typeof b)
411
- return false;
412
- if (typeof a !== "object")
413
- return false;
414
- const aObj = a;
415
- const bObj = b;
416
- const keys = new Set([...Object.keys(aObj), ...Object.keys(bObj)]);
417
- for (const key of keys) {
418
- if (!deepEqual(aObj[key], bObj[key]))
419
- return false;
420
- }
421
- return true;
422
- }
423
- var CONFIG_DIR = join3(homedir2(), ".honcho");
424
- var CONFIG_FILE = join3(CONFIG_DIR, "config.json");
425
552
  function getConfigPath() {
426
- return CONFIG_FILE;
553
+ return configPath();
554
+ }
555
+ function getConfigDir() {
556
+ return dirname2(configPath());
427
557
  }
428
558
  function configExists() {
429
- return existsSync3(CONFIG_FILE);
559
+ return existsSync3(configPath());
430
560
  }
431
561
  function getPluginVersion() {
432
562
  const root = process.env.CLAUDE_PLUGIN_ROOT;
@@ -436,330 +566,142 @@ function getPluginVersion() {
436
566
  ];
437
567
  for (const manifest of candidates) {
438
568
  try {
439
- const version = JSON.parse(readFileSync2(manifest, "utf-8")).version;
569
+ const version = JSON.parse(readFileSync3(manifest, "utf-8")).version;
440
570
  if (typeof version === "string" && version)
441
571
  return version;
442
572
  } catch {}
443
573
  }
444
574
  return "unknown";
445
575
  }
446
- function loadConfig2(host) {
447
- const resolvedHost = host ?? getDetectedHost();
448
- if (configExists()) {
449
- try {
450
- const content = readFileSync2(CONFIG_FILE, "utf-8");
451
- const raw = JSON.parse(content);
452
- return resolveConfig2(raw, resolvedHost);
453
- } catch {}
454
- }
455
- return loadConfigFromEnv(resolvedHost);
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;
456
582
  }
457
- function resolveConfig2(raw, host) {
458
- const hostBlock = raw.hosts?.[host] ?? raw.hosts?.[host.replace(/_/g, "-")] ?? raw.hosts?.[host.replace(/-/g, "_")];
459
- const apiKey = process.env.HONCHO_API_KEY || hostBlock?.apiKey || raw.apiKey;
460
- if (!apiKey)
461
- return null;
462
- const peerName = raw.peerName || process.env.HONCHO_PEER_NAME || process.env.USER || process.env.USERNAME || "user";
463
- let workspace;
464
- let aiPeer;
465
- if (raw.globalOverride === true) {
466
- workspace = raw.workspace ?? DEFAULT_WORKSPACE[host];
467
- aiPeer = raw.aiPeer ?? hostBlock?.aiPeer ?? DEFAULT_AI_PEER[host];
468
- } else if (hostBlock) {
469
- workspace = hostBlock.workspace ?? DEFAULT_WORKSPACE[host];
470
- aiPeer = hostBlock.aiPeer ?? DEFAULT_AI_PEER[host];
471
- } else {
472
- workspace = process.env.HONCHO_WORKSPACE ?? raw.workspace ?? DEFAULT_WORKSPACE[host];
473
- if (host === "cursor") {
474
- aiPeer = raw.cursorPeer ?? DEFAULT_AI_PEER["cursor"];
475
- } else {
476
- aiPeer = raw.claudePeer ?? DEFAULT_AI_PEER["claude_code"];
477
- }
478
- }
479
- const config = {
480
- apiKey,
481
- peerName,
482
- workspace,
483
- aiPeer,
484
- sessionStrategy: hostBlock?.sessionStrategy ?? raw.sessionStrategy,
485
- sessionPeerPrefix: hostBlock?.sessionPeerPrefix ?? raw.sessionPeerPrefix,
486
- sessions: raw.sessions,
487
- saveMessages: hostBlock?.saveMessages ?? raw.saveMessages,
488
- saveToolUse: hostBlock?.saveToolUse ?? raw.saveToolUse,
489
- saveGitEvents: hostBlock?.saveGitEvents ?? raw.saveGitEvents,
490
- reasoningLevel: hostBlock?.reasoningLevel ?? raw.reasoningLevel,
491
- observationMode: hostBlock?.observationMode ?? raw.observationMode,
492
- messageUpload: hostBlock?.messageUpload ?? raw.messageUpload,
493
- contextRefresh: hostBlock?.contextRefresh ?? raw.contextRefresh,
494
- endpoint: hostBlock?.endpoint ?? raw.endpoint,
495
- redactPatterns: hostBlock?.redactPatterns ?? raw.redactPatterns,
496
- injection: hostBlock?.injection ?? raw.injection,
497
- rememberTool: hostBlock?.rememberTool ?? raw.rememberTool,
498
- enabled: hostBlock?.enabled ?? raw.enabled,
499
- logging: hostBlock?.logging ?? raw.logging,
500
- globalOverride: raw.globalOverride
501
- };
502
- return mergeWithEnvVars(config);
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
+ });
503
611
  }
504
- function loadConfigFromEnv(host) {
505
- const apiKey = process.env.HONCHO_API_KEY;
506
- if (!apiKey) {
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)
507
624
  return null;
508
- }
509
- const resolvedHost = host ?? getDetectedHost();
510
- const peerName = process.env.HONCHO_PEER_NAME || process.env.USER || process.env.USERNAME || "user";
511
- const workspace = process.env.HONCHO_WORKSPACE || DEFAULT_WORKSPACE[resolvedHost];
512
- const hostPeerEnv = resolvedHost === "cursor" ? process.env.HONCHO_CURSOR_PEER : process.env.HONCHO_CLAUDE_PEER;
513
- const aiPeer = process.env.HONCHO_AI_PEER || hostPeerEnv || DEFAULT_AI_PEER[resolvedHost];
514
- const endpoint = process.env.HONCHO_ENDPOINT;
515
- const config = {
516
- apiKey,
517
- peerName,
518
- workspace,
519
- aiPeer,
520
- saveMessages: process.env.HONCHO_SAVE_MESSAGES !== "false",
521
- saveToolUse: process.env.HONCHO_SAVE_TOOL_USE === "true",
522
- saveGitEvents: process.env.HONCHO_SAVE_GIT_EVENTS === "true",
523
- enabled: process.env.HONCHO_ENABLED !== "false",
524
- logging: process.env.HONCHO_LOGGING !== "false"
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
525
633
  };
526
- if (endpoint) {
527
- if (endpoint === "local") {
528
- config.endpoint = { environment: "local" };
529
- } else if (endpoint.startsWith("http")) {
530
- config.endpoint = { baseUrl: endpoint };
531
- }
532
- }
533
- return config;
534
- }
535
- function mergeWithEnvVars(config) {
536
- if (process.env.HONCHO_API_KEY) {
537
- config.apiKey = process.env.HONCHO_API_KEY;
538
- }
539
- if (process.env.HONCHO_PEER_NAME) {
540
- config.peerName = process.env.HONCHO_PEER_NAME;
541
- }
542
- if (process.env.HONCHO_ENABLED === "false") {
543
- config.enabled = false;
544
- }
545
- if (process.env.HONCHO_LOGGING === "false") {
546
- config.logging = false;
547
- }
548
- if (process.env.HONCHO_SAVE_TOOL_USE !== undefined) {
549
- config.saveToolUse = process.env.HONCHO_SAVE_TOOL_USE === "true";
550
- }
551
- if (process.env.HONCHO_SAVE_GIT_EVENTS !== undefined) {
552
- config.saveGitEvents = process.env.HONCHO_SAVE_GIT_EVENTS === "true";
553
- }
554
- return config;
555
634
  }
556
- function saveConfig(config) {
557
- if (!existsSync3(CONFIG_DIR)) {
558
- mkdirSync2(CONFIG_DIR, { recursive: true });
559
- }
560
- let existing = {};
561
- if (existsSync3(CONFIG_FILE)) {
562
- try {
563
- existing = JSON.parse(readFileSync2(CONFIG_FILE, "utf-8"));
564
- } catch {}
565
- }
566
- if (config.sessions !== undefined) {
567
- existing.sessions = config.sessions;
568
- }
635
+ async function saveConfig(config, field) {
569
636
  const host = getDetectedHost();
570
- if (!existing.hosts)
571
- existing.hosts = {};
572
- const existingHost = existing.hosts[host] ?? {};
573
- const hostEntry = {};
574
- const setHostIfExplicit = (key, value, rootValue) => {
575
- if (value === undefined)
576
- return;
577
- const hasHostOverride = Object.prototype.hasOwnProperty.call(existingHost, key);
578
- if (hasHostOverride || !deepEqual(value, rootValue)) {
579
- hostEntry[key] = value;
580
- }
581
- };
582
- setHostIfExplicit("workspace", config.workspace, existing.workspace ?? DEFAULT_WORKSPACE[host]);
583
- setHostIfExplicit("aiPeer", config.aiPeer, existing.aiPeer ?? DEFAULT_AI_PEER[host]);
584
- const enabledForSave = process.env.HONCHO_ENABLED === "false" && config.enabled === false ? existingHost.enabled : config.enabled;
585
- const loggingForSave = process.env.HONCHO_LOGGING === "false" && config.logging === false ? existingHost.logging : config.logging;
586
- setHostIfExplicit("enabled", enabledForSave, existing.enabled);
587
- setHostIfExplicit("logging", loggingForSave, existing.logging);
588
- setHostIfExplicit("saveMessages", config.saveMessages, existing.saveMessages);
589
- setHostIfExplicit("sessionStrategy", config.sessionStrategy, existing.sessionStrategy);
590
- setHostIfExplicit("sessionPeerPrefix", config.sessionPeerPrefix, existing.sessionPeerPrefix);
591
- setHostIfExplicit("reasoningLevel", config.reasoningLevel, existing.reasoningLevel);
592
- setHostIfExplicit("observationMode", config.observationMode, existing.observationMode);
593
- setHostIfExplicit("messageUpload", config.messageUpload, existing.messageUpload);
594
- setHostIfExplicit("contextRefresh", config.contextRefresh, existing.contextRefresh);
595
- setHostIfExplicit("redactPatterns", config.redactPatterns, existing.redactPatterns);
596
- setHostIfExplicit("endpoint", config.endpoint, existing.endpoint);
597
- setHostIfExplicit("injection", config.injection, existing.injection);
598
- setHostIfExplicit("rememberTool", config.rememberTool, existing.rememberTool);
599
- if (existingHost.apiKey !== undefined) {
600
- hostEntry.apiKey = existingHost.apiKey;
601
- }
602
- existing.hosts[host] = hostEntry;
603
- writeFileSync2(CONFIG_FILE, JSON.stringify(existing, null, 2));
604
- }
605
- function saveRootField(field, value) {
606
- if (!existsSync3(CONFIG_DIR)) {
607
- mkdirSync2(CONFIG_DIR, { recursive: true });
608
- }
609
- let existing = {};
610
- if (existsSync3(CONFIG_FILE)) {
611
- try {
612
- existing = JSON.parse(readFileSync2(CONFIG_FILE, "utf-8"));
613
- } catch {}
614
- }
615
- existing[field] = value;
616
- writeFileSync2(CONFIG_FILE, JSON.stringify(existing, null, 2));
617
- }
618
- function resolveWorktreeMainRoot(dir) {
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()) {
619
673
  try {
620
- const gitPath = join3(dir, ".git");
621
- if (!statSync(gitPath).isFile())
622
- return null;
623
- const match = readFileSync2(gitPath, "utf-8").match(/^gitdir:\s*(.+?)\s*$/m);
624
- if (!match)
625
- return null;
626
- const gitdir = resolve(dir, match[1]);
627
- const idx = gitdir.lastIndexOf(`${sep}worktrees${sep}`);
628
- if (idx === -1)
629
- return null;
630
- const gitContainer = gitdir.slice(0, idx);
631
- if (basename(gitContainer) === ".git")
632
- return dirname(gitContainer);
633
- if (gitContainer.endsWith(".git"))
634
- return gitContainer;
635
- return null;
636
- } catch {
637
- return null;
638
- }
639
- }
640
- var MAX_GIT_WALK_UP = 12;
641
- function worktreeMainRootFor(cwd) {
642
- try {
643
- let dir = resolve(cwd);
644
- for (let i = 0;i < MAX_GIT_WALK_UP; i++) {
645
- if (existsSync3(join3(dir, ".git")))
646
- return resolveWorktreeMainRoot(dir);
647
- const parent = dirname(dir);
648
- if (parent === dir)
649
- break;
650
- dir = parent;
651
- }
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.`;
652
677
  } catch {}
653
- return null;
678
+ return;
654
679
  }
655
- function getSessionForPath(cwd, mainRoot) {
656
- const config = loadConfig2();
657
- if (!config?.sessions)
658
- return null;
659
- if (config.sessions[cwd])
660
- return config.sessions[cwd];
661
- const mr = mainRoot === undefined ? worktreeMainRootFor(cwd) : mainRoot;
662
- if (mr && config.sessions[mr])
663
- return config.sessions[mr];
664
- return null;
665
- }
666
- function deriveSessionName(strategy, cwd, opts = {}) {
667
- const usePrefix = opts.sessionPeerPrefix !== false;
668
- const peerPart = opts.peerName ? sanitizeForSessionName(opts.peerName) : "user";
669
- const repoPart = sanitizeForSessionName(basename(cwd));
670
- const base = usePrefix ? `${peerPart}-${repoPart}` : repoPart;
671
- switch (strategy) {
672
- case "git-branch": {
673
- if (opts.branch) {
674
- const branchPart = sanitizeForSessionName(opts.branch);
675
- return `${base}-${branchPart}`;
676
- }
677
- return base;
678
- }
679
- case "chat-instance": {
680
- if (opts.instanceId) {
681
- return usePrefix ? `${peerPart}-chat-${opts.instanceId}` : `chat-${opts.instanceId}`;
682
- }
683
- return base;
684
- }
685
- case "per-directory":
686
- default:
687
- return base;
688
- }
680
+ function getSessionName(sessionId) {
681
+ const id = sessionId || process.env.CLAUDE_CODE_SESSION_ID;
682
+ return id ? sanitizeForSessionName(id) : null;
689
683
  }
690
- function getSessionName(cwd, instanceId) {
691
- const config = loadConfig2();
692
- const strategy = config?.sessionStrategy ?? "per-directory";
693
- const mainRoot = worktreeMainRootFor(cwd);
694
- if (strategy === "per-directory") {
695
- const configuredSession = getSessionForPath(cwd, mainRoot);
696
- if (configuredSession) {
697
- return configuredSession;
698
- }
699
- }
700
- let branch;
701
- if (strategy === "git-branch") {
702
- branch = captureGitState(cwd)?.branch;
703
- }
704
- let resolvedInstanceId;
705
- if (strategy === "chat-instance") {
706
- resolvedInstanceId = instanceId || getInstanceIdForCwd(cwd) || getClaudeInstanceId() || undefined;
707
- }
708
- return deriveSessionName(strategy, mainRoot ?? cwd, {
709
- peerName: config?.peerName,
710
- sessionPeerPrefix: config?.sessionPeerPrefix,
711
- branch,
712
- instanceId: resolvedInstanceId
713
- });
684
+ function getKnownHosts() {
685
+ const hosts = readConfigFile().hosts;
686
+ return hosts && typeof hosts === "object" ? Object.keys(hosts) : [];
714
687
  }
715
- function setSessionForPath(cwd, sessionName) {
716
- const config = loadConfig2();
717
- if (!config)
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)
718
692
  return;
719
- if (!config.sessions) {
720
- config.sessions = {};
721
- }
722
- config.sessions[cwd] = sessionName;
723
- saveConfig(config);
693
+ const { token, ...authState } = cred;
694
+ config.apiKey = token;
695
+ config.auth = { ...authState, host };
724
696
  }
725
- function getInjectionConfig(config) {
726
- const injection = (config === undefined ? loadConfig2() : config)?.injection;
727
- const resolved = { ...DEFAULT_INJECTION, ...injection ?? {} };
728
- resolved.perTurn = Array.isArray(resolved.perTurn) ? normalizePerTurn(resolved.perTurn) : DEFAULT_INJECTION.perTurn;
729
- resolved.showContents = Array.isArray(resolved.showContents) ? normalizePerTurn(resolved.showContents) : DEFAULT_INJECTION.showContents;
730
- return resolved;
731
- }
732
- function isLoggingEnabled() {
733
- const config = loadConfig2();
734
- return config?.logging !== false;
735
- }
736
- function isPluginEnabled() {
737
- const config = loadConfig2();
738
- return config?.enabled !== false;
739
- }
740
- function getKnownHosts() {
741
- const cfgPath = getConfigPath();
742
- if (!existsSync3(cfgPath))
743
- return [];
744
- try {
745
- const raw = JSON.parse(readFileSync2(cfgPath, "utf-8"));
746
- return raw.hosts ? Object.keys(raw.hosts) : [];
747
- } catch {
748
- return [];
749
- }
750
- }
751
- function getHonchoBaseUrlForEndpoint(endpoint) {
752
- if (endpoint?.baseUrl) {
753
- const url = endpoint.baseUrl;
754
- return url.endsWith("/v3") ? url : `${url}/v3`;
755
- }
756
- if (endpoint?.environment === "local") {
757
- return HONCHO_BASE_URLS.local;
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.";
758
700
  }
759
- return HONCHO_BASE_URLS.production;
701
+ return;
760
702
  }
761
703
  function getHonchoBaseUrl(config) {
762
- return getHonchoBaseUrlForEndpoint(config.endpoint);
704
+ return `${config.baseUrl}/v3`;
763
705
  }
764
706
  function getTelemetryHeaders(host = getDetectedHost()) {
765
707
  return telemetryHeaders({
@@ -778,47 +720,51 @@ function getHonchoClientOptions(config) {
778
720
  defaultHeaders: getTelemetryHeaders()
779
721
  };
780
722
  }
781
- function getEndpointInfo(config) {
782
- if (config.endpoint?.baseUrl) {
783
- return { type: "custom", url: config.endpoint.baseUrl };
784
- }
785
- if (config.endpoint?.environment === "local") {
786
- return { type: "local", url: HONCHO_BASE_URLS.local };
787
- }
788
- return { type: "production", url: HONCHO_BASE_URLS.production };
723
+ function isProductionEndpoint(config) {
724
+ return config.baseUrl === DEFAULT_BASE_URL;
789
725
  }
790
- var VALID_ENVIRONMENTS = new Set(["production", "local"]);
791
- function getObservationMode(config) {
792
- return config.observationMode ?? "unified";
726
+ function getEndpointInfo(config) {
727
+ return { type: isProductionEndpoint(config) ? "production" : "custom", url: config.baseUrl };
793
728
  }
794
729
 
795
730
  // src/state.ts
796
- import { homedir as homedir3 } from "os";
731
+ import { homedir as homedir2 } from "os";
797
732
  import { join as join4 } from "path";
798
- import { writeFileSync as writeFileSync3, unlinkSync } from "fs";
799
- var DIR = join4(homedir3(), ".honcho");
733
+ import { writeFileSync as writeFileSync2, unlinkSync as unlinkSync2 } from "fs";
734
+ var DIR = join4(homedir2(), ".honcho");
800
735
  function stateFile(sessionId) {
801
736
  return join4(DIR, sessionId ? `state-${sessionId}.json` : "state.json");
802
737
  }
803
738
  function sessionFile(sessionId) {
804
739
  return join4(DIR, sessionId ? `session-${sessionId}.json` : "session.json");
805
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
+ }
806
752
  function setMemoryState(phase, detail, sessionId) {
807
753
  try {
808
- writeFileSync3(stateFile(sessionId), JSON.stringify({ phase, since: Date.now(), detail }));
754
+ writeFileSync2(stateFile(sessionId), JSON.stringify({ phase, since: Date.now(), detail }));
809
755
  } catch {}
810
756
  }
811
757
  function setSessionLink(url, name, sessionId) {
812
758
  try {
813
- writeFileSync3(sessionFile(sessionId), JSON.stringify({ url, name }));
759
+ writeFileSync2(sessionFile(sessionId), JSON.stringify({ url, name }));
814
760
  } catch {}
815
761
  }
816
762
  function clearSessionFiles(sessionId) {
817
763
  if (!sessionId)
818
764
  return;
819
- for (const f of [stateFile(sessionId), sessionFile(sessionId)]) {
765
+ for (const f of [stateFile(sessionId), sessionFile(sessionId), noticeFile(sessionId)]) {
820
766
  try {
821
- unlinkSync(f);
767
+ unlinkSync2(f);
822
768
  } catch {}
823
769
  }
824
770
  }
@@ -827,8 +773,6 @@ function clearSessionFiles(sessionId) {
827
773
  var LABELS = {
828
774
  search: "searching",
829
775
  chat: "asking",
830
- get_context: "context",
831
- get_representation: "recall",
832
776
  create_conclusion: "writing",
833
777
  list_conclusions: "listing",
834
778
  delete_conclusion: "writing",
@@ -836,6 +780,8 @@ var LABELS = {
836
780
  set_config: "config"
837
781
  };
838
782
  async function handlePreToolHoncho() {
783
+ if (isModActive())
784
+ process.exit(0);
839
785
  try {
840
786
  const raw = getCachedStdin();
841
787
  const input = raw && raw.trim() ? JSON.parse(raw) : {};
@@ -853,5 +799,5 @@ async function main() {
853
799
  // hooks/pre-tool-honcho.ts
854
800
  await main();
855
801
 
856
- //# debugId=0D79439C2A9A5A0B64756E2164756E21
802
+ //# debugId=F1F92C66A06367F864756E2164756E21
857
803
  //# sourceMappingURL=pre-tool-honcho.js.map