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