@honcho-ai/claude-honcho 0.3.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +21 -0
- package/dist/chunk-084dpgp3.js +556 -0
- package/dist/chunk-084dpgp3.js.map +10 -0
- package/dist/chunk-49wja30f.js +20 -0
- package/dist/chunk-49wja30f.js.map +10 -0
- package/dist/chunk-4ryv9310.js +15534 -0
- package/dist/chunk-4ryv9310.js.map +87 -0
- package/dist/chunk-4zgbdwm4.js +261 -0
- package/dist/chunk-4zgbdwm4.js.map +10 -0
- package/dist/chunk-6yybt92z.js +106 -0
- package/dist/chunk-6yybt92z.js.map +9 -0
- package/dist/chunk-9pntsn3x.js +35 -0
- package/dist/chunk-9pntsn3x.js.map +10 -0
- package/dist/chunk-d2gc13m0.js +161 -0
- package/dist/chunk-d2gc13m0.js.map +11 -0
- package/dist/chunk-dxbm7kmf.js +331 -0
- package/dist/chunk-dxbm7kmf.js.map +10 -0
- package/dist/chunk-gnp95nzg.js +438 -0
- package/dist/chunk-gnp95nzg.js.map +12 -0
- package/dist/chunk-jgtvcc65.js +90 -0
- package/dist/chunk-jgtvcc65.js.map +10 -0
- package/dist/chunk-jr0fd6n2.js +181 -0
- package/dist/chunk-jr0fd6n2.js.map +11 -0
- package/dist/chunk-wm6hvkcv.js +245 -0
- package/dist/chunk-wm6hvkcv.js.map +10 -0
- package/dist/chunk-xdntcesh.js +15450 -0
- package/dist/chunk-xdntcesh.js.map +86 -0
- package/dist/chunk-xtdvbfxw.js +146 -0
- package/dist/chunk-xtdvbfxw.js.map +10 -0
- package/dist/chunk-yfrrc1d5.js +838 -0
- package/dist/chunk-yfrrc1d5.js.map +12 -0
- package/dist/hooks/post-tool-use.js +220 -0
- package/dist/hooks/post-tool-use.js.map +11 -0
- package/dist/hooks/pre-compact.js +217 -0
- package/dist/hooks/pre-compact.js.map +12 -0
- package/dist/hooks/pre-tool-honcho.js +38 -0
- package/dist/hooks/pre-tool-honcho.js.map +11 -0
- package/dist/hooks/save-user-message.js +96 -0
- package/dist/hooks/save-user-message.js.map +11 -0
- package/dist/hooks/session-end.js +51 -0
- package/dist/hooks/session-end.js.map +11 -0
- package/dist/hooks/session-start.js +246 -0
- package/dist/hooks/session-start.js.map +12 -0
- package/dist/hooks/stop.js +158 -0
- package/dist/hooks/stop.js.map +11 -0
- package/dist/hooks/user-prompt.js +19 -0
- package/dist/hooks/user-prompt.js.map +10 -0
- package/dist/mcp-server.js +13640 -0
- package/dist/mcp-server.js.map +110 -0
- package/dist/skills/backfill-runner.js +245 -0
- package/dist/skills/backfill-runner.js.map +10 -0
- package/dist/skills/setup-runner.js +339 -0
- package/dist/skills/setup-runner.js.map +12 -0
- package/dist/skills/status-runner.js +86 -0
- package/dist/skills/status-runner.js.map +10 -0
- package/hooks/hooks.json +108 -0
- package/mcp-servers.json +10 -0
- package/package.json +19 -0
- package/scripts/check-version.sh +50 -0
- package/scripts/honcho-statusline.sh +101 -0
- package/skills/briefing/SKILL.md +20 -0
- package/skills/config/SKILL.md +288 -0
- package/skills/import/SKILL.md +73 -0
- package/skills/insights/SKILL.md +109 -0
- package/skills/interview/SKILL.md +61 -0
- package/skills/setup/SKILL.md +60 -0
- package/skills/status/SKILL.md +30 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
import {
|
|
4
|
+
Spinner
|
|
5
|
+
} from "../chunk-4zgbdwm4.js";
|
|
6
|
+
import {
|
|
7
|
+
setMemoryState
|
|
8
|
+
} from "../chunk-9pntsn3x.js";
|
|
9
|
+
import {
|
|
10
|
+
formatVerboseBlock,
|
|
11
|
+
formatVerboseList
|
|
12
|
+
} from "../chunk-xtdvbfxw.js";
|
|
13
|
+
import {
|
|
14
|
+
require_dist
|
|
15
|
+
} from "../chunk-4ryv9310.js";
|
|
16
|
+
import {
|
|
17
|
+
logApiCall,
|
|
18
|
+
logHook,
|
|
19
|
+
setLogContext
|
|
20
|
+
} from "../chunk-jr0fd6n2.js";
|
|
21
|
+
import {
|
|
22
|
+
__toESM,
|
|
23
|
+
getCachedStdin,
|
|
24
|
+
getHonchoClientOptions,
|
|
25
|
+
getObservationMode,
|
|
26
|
+
getSessionName,
|
|
27
|
+
isPluginEnabled,
|
|
28
|
+
loadConfig,
|
|
29
|
+
readStdinText
|
|
30
|
+
} from "../chunk-yfrrc1d5.js";
|
|
31
|
+
|
|
32
|
+
// src/config.ts
|
|
33
|
+
import { homedir } from "os";
|
|
34
|
+
import { join, basename, dirname, resolve, sep } from "path";
|
|
35
|
+
var _detectedHost = null;
|
|
36
|
+
function setDetectedHost(host) {
|
|
37
|
+
_detectedHost = host;
|
|
38
|
+
}
|
|
39
|
+
function detectHost(stdinInput) {
|
|
40
|
+
const envHost = process.env.HONCHO_HOST;
|
|
41
|
+
if (envHost === "cursor" || envHost === "claude_code" || envHost === "obsidian")
|
|
42
|
+
return envHost;
|
|
43
|
+
if (stdinInput?.cursor_version)
|
|
44
|
+
return "cursor";
|
|
45
|
+
if (process.env.CURSOR_PROJECT_DIR)
|
|
46
|
+
return "cursor";
|
|
47
|
+
return "claude_code";
|
|
48
|
+
}
|
|
49
|
+
var _stdinText = null;
|
|
50
|
+
function cacheStdin(text) {
|
|
51
|
+
_stdinText = text;
|
|
52
|
+
}
|
|
53
|
+
async function readStdinText2() {
|
|
54
|
+
const chunks = [];
|
|
55
|
+
for await (const chunk of process.stdin)
|
|
56
|
+
chunks.push(chunk);
|
|
57
|
+
return Buffer.concat(chunks).toString("utf-8");
|
|
58
|
+
}
|
|
59
|
+
async function initHook() {
|
|
60
|
+
const stdinText = await readStdinText2();
|
|
61
|
+
cacheStdin(stdinText);
|
|
62
|
+
let input = {};
|
|
63
|
+
try {
|
|
64
|
+
input = JSON.parse(stdinText || "{}");
|
|
65
|
+
} catch {
|
|
66
|
+
process.exit(0);
|
|
67
|
+
}
|
|
68
|
+
if (input.cursor_version)
|
|
69
|
+
process.exit(0);
|
|
70
|
+
setDetectedHost(detectHost(input));
|
|
71
|
+
}
|
|
72
|
+
var CONFIG_DIR = join(homedir(), ".honcho");
|
|
73
|
+
var CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
|
74
|
+
var VALID_ENVIRONMENTS = new Set(["production", "local"]);
|
|
75
|
+
|
|
76
|
+
// src/hooks/pre-compact.ts
|
|
77
|
+
var import_sdk = __toESM(require_dist(), 1);
|
|
78
|
+
function formatMemoryCard(config, sessionName, userContext, claudeContext, summaries, userDialectic, claudeDialectic) {
|
|
79
|
+
const parts = [];
|
|
80
|
+
parts.push(`## HONCHO MEMORY ANCHOR (Pre-Compaction Injection)
|
|
81
|
+
This context is being injected because the conversation is about to be summarized.
|
|
82
|
+
These conclusions MUST be preserved in the summary.
|
|
83
|
+
|
|
84
|
+
### Session Identity
|
|
85
|
+
- User: ${config.peerName}
|
|
86
|
+
- AI: ${config.aiPeer}
|
|
87
|
+
- Workspace: ${config.workspace}
|
|
88
|
+
- Session: ${sessionName}`);
|
|
89
|
+
const userPeerCard = userContext?.peerCard;
|
|
90
|
+
if (userPeerCard?.length > 0) {
|
|
91
|
+
parts.push(`### ${config.peerName}'s Profile (PRESERVE)
|
|
92
|
+
${userPeerCard.join(`
|
|
93
|
+
`)}`);
|
|
94
|
+
}
|
|
95
|
+
const userRep = userContext?.representation;
|
|
96
|
+
if (typeof userRep === "string" && userRep.trim()) {
|
|
97
|
+
parts.push(`### Key Conclusions About ${config.peerName} (PRESERVE)
|
|
98
|
+
${userRep}`);
|
|
99
|
+
}
|
|
100
|
+
const claudeRep = claudeContext?.representation;
|
|
101
|
+
if (typeof claudeRep === "string" && claudeRep.trim()) {
|
|
102
|
+
parts.push(`### ${config.aiPeer}'s Recent Work (PRESERVE)
|
|
103
|
+
${claudeRep}`);
|
|
104
|
+
}
|
|
105
|
+
const shortSummary = summaries?.shortSummary;
|
|
106
|
+
if (shortSummary?.content) {
|
|
107
|
+
parts.push(`### Session Context (PRESERVE)
|
|
108
|
+
${shortSummary.content}`);
|
|
109
|
+
}
|
|
110
|
+
if (userDialectic) {
|
|
111
|
+
parts.push(`### AI Understanding of ${config.peerName} (PRESERVE)
|
|
112
|
+
${userDialectic}`);
|
|
113
|
+
}
|
|
114
|
+
if (claudeDialectic) {
|
|
115
|
+
parts.push(`### ${config.aiPeer}'s Self-Reflection (PRESERVE)
|
|
116
|
+
${claudeDialectic}`);
|
|
117
|
+
}
|
|
118
|
+
parts.push(`### End Memory Anchor
|
|
119
|
+
The above context represents persistent memory from Honcho.
|
|
120
|
+
When summarizing this conversation, ensure these conclusions are preserved.`);
|
|
121
|
+
return parts.join(`
|
|
122
|
+
|
|
123
|
+
`);
|
|
124
|
+
}
|
|
125
|
+
async function handlePreCompact() {
|
|
126
|
+
const config = loadConfig();
|
|
127
|
+
if (!config) {
|
|
128
|
+
process.exit(0);
|
|
129
|
+
}
|
|
130
|
+
if (!isPluginEnabled()) {
|
|
131
|
+
process.exit(0);
|
|
132
|
+
}
|
|
133
|
+
let hookInput = {};
|
|
134
|
+
try {
|
|
135
|
+
const input = getCachedStdin() ?? await readStdinText();
|
|
136
|
+
if (input.trim()) {
|
|
137
|
+
hookInput = JSON.parse(input);
|
|
138
|
+
}
|
|
139
|
+
} catch {}
|
|
140
|
+
const cwd = hookInput.workspace_roots?.[0] || hookInput.cwd || process.cwd();
|
|
141
|
+
const trigger = hookInput.trigger || "auto";
|
|
142
|
+
setLogContext(cwd, getSessionName(cwd));
|
|
143
|
+
logHook("pre-compact", `Compaction triggered (${trigger})`);
|
|
144
|
+
const spinner = new Spinner({ style: "neural" });
|
|
145
|
+
if (trigger === "auto") {
|
|
146
|
+
spinner.start("anchoring memory before compaction");
|
|
147
|
+
}
|
|
148
|
+
setMemoryState("compacting", undefined, hookInput.session_id);
|
|
149
|
+
try {
|
|
150
|
+
const honcho = new import_sdk.Honcho(getHonchoClientOptions(config));
|
|
151
|
+
const sessionName = getSessionName(cwd);
|
|
152
|
+
const observationMode = getObservationMode(config);
|
|
153
|
+
const session = await honcho.session(sessionName);
|
|
154
|
+
const userPeer = await honcho.peer(config.peerName);
|
|
155
|
+
const aiPeer = await honcho.peer(config.aiPeer);
|
|
156
|
+
const contextPeer = observationMode === "unified" ? userPeer : aiPeer;
|
|
157
|
+
const contextTarget = observationMode === "unified" ? undefined : config.peerName;
|
|
158
|
+
const contextLabel = observationMode === "unified" ? "userPeer.context()" : `aiPeer.context(target=${config.peerName})`;
|
|
159
|
+
if (trigger === "auto") {
|
|
160
|
+
spinner.update("fetching memory context");
|
|
161
|
+
}
|
|
162
|
+
logApiCall(contextLabel, "GET", observationMode === "unified" ? "self" : `target=${config.peerName}`);
|
|
163
|
+
logApiCall("session.summaries", "GET", sessionName);
|
|
164
|
+
logApiCall("peer.chat", "POST", "dialectic queries x2");
|
|
165
|
+
const dialecticArgs = observationMode === "unified" ? { session, reasoningLevel: config.reasoningLevel ?? "low" } : { target: config.peerName, session, reasoningLevel: config.reasoningLevel ?? "low" };
|
|
166
|
+
const [userContextResult, summariesResult, userChatResult, claudeChatResult] = await Promise.allSettled([
|
|
167
|
+
contextPeer.context({
|
|
168
|
+
...contextTarget ? { target: contextTarget } : {},
|
|
169
|
+
maxConclusions: 30,
|
|
170
|
+
includeMostFrequent: true
|
|
171
|
+
}),
|
|
172
|
+
session.summaries(),
|
|
173
|
+
contextPeer.chat(`Summarize the most important things to remember about ${config.peerName}. Focus on their preferences, working style, current projects, and any critical context that should survive a conversation summary.`, dialecticArgs),
|
|
174
|
+
contextPeer.chat(`What are the most important things that were worked on with ${config.peerName}? Summarize key context that should be preserved.`, dialecticArgs)
|
|
175
|
+
]);
|
|
176
|
+
const userContext = userContextResult.status === "fulfilled" ? userContextResult.value : null;
|
|
177
|
+
const summaries = summariesResult.status === "fulfilled" ? summariesResult.value : null;
|
|
178
|
+
const verboseBlocks = [];
|
|
179
|
+
verboseBlocks.push(formatVerboseBlock(`pre-compact ${contextLabel}`, userContext?.representation));
|
|
180
|
+
verboseBlocks.push(formatVerboseList("pre-compact peerCard", userContext?.peerCard));
|
|
181
|
+
const userDialectic = userChatResult.status === "fulfilled" ? userChatResult.value : null;
|
|
182
|
+
const claudeDialectic = claudeChatResult.status === "fulfilled" ? claudeChatResult.value : null;
|
|
183
|
+
const memoryCard = formatMemoryCard(config, sessionName, userContext, null, summaries, userDialectic, claudeDialectic);
|
|
184
|
+
if (trigger === "auto") {
|
|
185
|
+
spinner.stop("memory anchored");
|
|
186
|
+
}
|
|
187
|
+
setMemoryState("idle", undefined, hookInput.session_id);
|
|
188
|
+
if (userDialectic) {
|
|
189
|
+
verboseBlocks.push(formatVerboseBlock(`pre-compact peer.chat(user) → "${config.peerName}"`, userDialectic));
|
|
190
|
+
}
|
|
191
|
+
if (claudeDialectic) {
|
|
192
|
+
verboseBlocks.push(formatVerboseBlock(`pre-compact peer.chat(claude) → "${config.aiPeer}"`, claudeDialectic));
|
|
193
|
+
}
|
|
194
|
+
logHook("pre-compact", `Memory anchored (${memoryCard.length} chars)`);
|
|
195
|
+
const verboseOutput = verboseBlocks.filter(Boolean).join(`
|
|
196
|
+
`);
|
|
197
|
+
console.log(`[${config.aiPeer}/Honcho Memory Anchor]
|
|
198
|
+
|
|
199
|
+
${memoryCard}${verboseOutput}`);
|
|
200
|
+
process.exit(0);
|
|
201
|
+
} catch (error) {
|
|
202
|
+
logHook("pre-compact", `Error: ${error}`, { error: String(error) });
|
|
203
|
+
if (trigger === "auto") {
|
|
204
|
+
spinner.fail("memory anchor failed");
|
|
205
|
+
}
|
|
206
|
+
setMemoryState("idle", undefined, hookInput.session_id);
|
|
207
|
+
console.error(`[honcho] Pre-compact warning: ${error}`);
|
|
208
|
+
process.exit(0);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// hooks/pre-compact.ts
|
|
213
|
+
await initHook();
|
|
214
|
+
await handlePreCompact();
|
|
215
|
+
|
|
216
|
+
//# debugId=3295B20DC4BCF58464756E2164756E21
|
|
217
|
+
//# sourceMappingURL=pre-compact.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/config.ts", "../../src/hooks/pre-compact.ts", "../../hooks/pre-compact.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { homedir } from \"os\";\nimport { join, basename, dirname, resolve, sep } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from \"fs\";\nimport { captureGitState } from \"./git.js\";\nimport { getInstanceIdForCwd, getClaudeInstanceId } from \"./cache.js\";\n\nfunction sanitizeForSessionName(s: string): string {\n return s.toLowerCase().replace(/[^a-z0-9-_]/g, \"-\");\n}\n\nexport interface MessageUploadConfig {\n /** Truncate user messages to this many tokens (undefined = no limit) */\n maxUserTokens?: number;\n /** Truncate assistant messages to this many tokens (undefined = no limit) */\n maxAssistantTokens?: number;\n /** Summarize assistant messages instead of sending full text (default: false) */\n summarizeAssistant?: boolean;\n}\n\nexport interface ContextRefreshConfig {\n /** Refresh context every N messages (default: 30) */\n messageThreshold?: number;\n /** Cache TTL in seconds (default: 300) */\n ttlSeconds?: number;\n /** Skip dialectic chat() calls in user-prompt hook (default: false) */\n skipDialectic?: boolean;\n}\n\nexport interface LocalContextConfig {\n /** Max entries in claude-context.md (default: 50) */\n maxEntries?: number;\n}\n\n// ============================================\n// Composable injection (DEV-2088 + DEV-2024)\n// ============================================\n\n/**\n * Components the SessionStart hook may emit once per session. The tuple is the\n * single source of truth: the union type derives from it, and set_config\n * validation builds its allow-set and error text from the same array — so\n * adding a component is a one-line edit with no drift between layers.\n * - \"directives\": static memory-usage guidance (treat injected memory as\n * background, use chat/search, save insights) — formerly a manual \"paste\n * this into your CLAUDE.md\" README step; now shipped every session instead.\n * - \"summary\": the SDK `session.summaries().long` narrative.\n * - \"peerCard\" / \"peerRepresentation\": the two fields of a single context() call,\n * each injected at full length (no per-field caps — inclusion is the only lever).\n * - \"briefing\": a static nudge to call the `get_briefing` MCP tool instead of\n * injecting summary/peerCard inline — the tool call renders as an expandable\n * row in the UI, making the briefing user-visible. Use in place of\n * \"summary\"/\"peerCard\", not alongside them (the content would land twice).\n */\nexport const SESSION_START_COMPONENTS = [\"directives\", \"summary\", \"peerCard\", \"peerRepresentation\", \"briefing\"] as const;\nexport type SessionStartComponent = (typeof SESSION_START_COMPONENTS)[number];\n\n/**\n * Components the UserPromptSubmit hook may emit per non-trivial prompt.\n * - \"userContext\": a fresh, prompt-scoped peer.context() blob for the user\n * peer, whose semantic retrieval is shaped by the searchTopK/\n * searchMaxDistance/maxConclusions knobs below.\n * - \"assistantContext\": the same peer.context() fetch, but for the AI peer —\n * what Honcho has derived about the assistant itself.\n * - \"sessionContext\": recent raw messages from the currently mapped Honcho\n * session via session.context() (summary off, no search), which can span\n * other Claude instances sharing the session name.\n * - \"dialectic\": a reasoned peer.chat() answer over the representation, seeded\n * from `dialecticTemplate` (the prompt substituted into %{user_query}) at the\n * `dialecticReasoning` tier. Off by default — chat() is far slower than\n * context() (~12s at medium), so it runs on its own budget, not the 4s\n * context race, and stays under the 30s UserPromptSubmit harness ceiling.\n *\n * A \"search\" component (filtered semantic search over inductive conclusions)\n * was scoped out: `level` is not filterable through the API, so it needs a\n * honcho-backend + SDK change before it can ship. See the plan.\n */\nexport const PER_TURN_COMPONENTS = [\"userContext\", \"assistantContext\", \"sessionContext\", \"dialectic\"] as const;\nexport type PerTurnComponent = (typeof PER_TURN_COMPONENTS)[number];\n\n/** Pre-split configs stored `\"context\"` for what is now \"userContext\". */\nexport function normalizePerTurn(components: string[]): PerTurnComponent[] {\n return components.map((c) => (c === \"context\" ? \"userContext\" : c)) as PerTurnComponent[];\n}\n\n/**\n * The `injection` config block: turns the two hardcoded injection surfaces\n * into a composable, config-driven menu. Each surface selects zero or more\n * components; the retrieval knobs shape whatever those components emit.\n */\nexport interface InjectionConfig {\n /** Components emitted once at session open (default: [\"directives\", \"summary\", \"peerCard\"]). */\n sessionStart?: SessionStartComponent[];\n /** Components emitted per non-trivial prompt (default: [\"userContext\"]). */\n perTurn?: PerTurnComponent[];\n /** Per-turn components whose full injected payload is printed to the terminal.\n * Components not listed still inject; they just report a one-line summary\n * instead of their contents (default: [] — summaries only). */\n showContents?: PerTurnComponent[];\n /** Top-K conclusions pulled by context()'s semantic search (default: 10). */\n searchTopK?: number;\n /** Max conclusions injected per context() call (default: 15). */\n maxConclusions?: number;\n /** Max cosine distance for context()'s semantic search — lower is stricter\n * (default: 0.6). */\n searchMaxDistance?: number;\n /** What drives the per-turn semantic search: the raw \"prompt\" (default)\n * or extracted \"topics\". */\n searchQuerySource?: \"topics\" | \"prompt\";\n /** Token budget for the per-turn \"sessionContext\" message fetch (default: 1500). */\n sessionContextTokens?: number;\n /** Query template for the per-turn \"dialectic\" component. The user's prompt\n * is substituted into every `%{user_query}` (default: surface anything from\n * the user's history relevant to the prompt). */\n dialecticTemplate?: string;\n /** Reasoning tier for the per-turn \"dialectic\" chat() call (default: \"low\").\n * Kept separate from the top-level `reasoningLevel` so per-turn dialectic can\n * stay cheap on the hot path without lowering the tier used elsewhere. */\n dialecticReasoning?: ReasoningLevel;\n}\n\n/** Resolved injection defaults: memory-usage directives + session summary +\n * peer card at session start, a fresh user-peer context() per turn. Retrieval knobs\n * are tuned for a lean per-turn block — topK 10 for recall, a 0.6 cosine\n * distance, searching on the raw prompt. No component prints its contents. */\nexport const DEFAULT_INJECTION: Required<InjectionConfig> = {\n sessionStart: [\"directives\", \"summary\", \"peerCard\"],\n perTurn: [\"userContext\"],\n showContents: [],\n searchTopK: 10,\n maxConclusions: 15,\n searchMaxDistance: 0.6,\n searchQuerySource: \"prompt\",\n sessionContextTokens: 1500,\n dialecticTemplate:\n \"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}\",\n dialecticReasoning: \"medium\",\n};\n\nexport const REASONING_LEVELS = [\"minimal\", \"low\", \"medium\", \"high\", \"max\"] as const;\nexport type ReasoningLevel = (typeof REASONING_LEVELS)[number];\n\nexport type SessionStrategy = \"per-directory\" | \"git-branch\" | \"chat-instance\";\n\nexport type StatuslineMode = \"on\" | \"off\";\n\nexport type HonchoEnvironment = \"production\" | \"local\";\n\nexport interface HonchoEndpointConfig {\n /** \"production\" (SaaS) or \"local\" (localhost:8000) */\n environment?: HonchoEnvironment;\n /** Custom URL override (takes precedence over environment) */\n baseUrl?: string;\n}\n\nconst HONCHO_BASE_URLS = {\n production: \"https://api.honcho.dev/v3\",\n local: \"http://localhost:8000/v3\",\n} as const;\n\n// ============================================\n// Host Detection\n// ============================================\n\nexport type HonchoHost = \"cursor\" | \"claude_code\" | \"obsidian\";\n\nexport type ObservationMode = \"unified\" | \"directional\";\n\nexport interface HostConfig {\n /** Honcho workspace name for this host */\n workspace?: string;\n /** AI peer name for this host (e.g. \"claude\", \"cursor\") */\n aiPeer?: string;\n /**\n * Honcho API key scoped to this host. Takes precedence over the root\n * `apiKey` field, but is still overridden by the HONCHO_API_KEY env var.\n * Useful when different hosts (claude_code, cursor, opencode) authenticate\n * against different Honcho orgs or workspaces.\n */\n apiKey?: string;\n\n /** Per-host overrides for settings that may differ across tools */\n enabled?: boolean;\n logging?: boolean;\n saveMessages?: boolean;\n saveToolUse?: boolean;\n saveGitEvents?: boolean;\n sessionStrategy?: SessionStrategy;\n sessionPeerPrefix?: boolean;\n /** Default reasoning level for Honcho dialectic calls (default: \"medium\") */\n reasoningLevel?: ReasoningLevel;\n /**\n * Observation mode (default: \"unified\").\n * \"unified\": all agents write to user's self-observation collection (observer=user, observed=user).\n * \"directional\": this AI keeps its own view of the user (observer=aiPeer, observed=user).\n */\n observationMode?: ObservationMode;\n messageUpload?: MessageUploadConfig;\n contextRefresh?: ContextRefreshConfig;\n localContext?: LocalContextConfig;\n endpoint?: HonchoEndpointConfig;\n /** Composable injection config (session-start + per-turn component menus). */\n injection?: InjectionConfig;\n /** Register the on-demand `honcho_remember` MCP tool (default: false). */\n rememberTool?: boolean;\n}\n\nlet _detectedHost: HonchoHost | null = null;\n\nexport function setDetectedHost(host: HonchoHost): void {\n _detectedHost = host;\n}\n\nexport function getDetectedHost(): HonchoHost {\n return _detectedHost ?? \"claude_code\";\n}\n\nexport function detectHost(stdinInput?: Record<string, unknown>): HonchoHost {\n // Explicit env var override (used by install scripts and external tooling)\n const envHost = process.env.HONCHO_HOST;\n if (envHost === \"cursor\" || envHost === \"claude_code\" || envHost === \"obsidian\") return envHost;\n\n if (stdinInput?.cursor_version) return \"cursor\";\n // Cursor sets CURSOR_PROJECT_DIR for child processes (incl. Claude Code inside Cursor)\n if (process.env.CURSOR_PROJECT_DIR) return \"cursor\";\n return \"claude_code\";\n}\n\nconst DEFAULT_WORKSPACE: Record<HonchoHost, string> = {\n \"cursor\": \"cursor\",\n \"claude_code\": \"claude_code\",\n \"obsidian\": \"obsidian\",\n};\n\nconst DEFAULT_AI_PEER: Record<HonchoHost, string> = {\n \"cursor\": \"cursor\",\n \"claude_code\": \"claude\",\n \"obsidian\": \"honcho\",\n};\n\nexport function getDefaultWorkspace(host?: HonchoHost): string {\n return DEFAULT_WORKSPACE[host ?? getDetectedHost()];\n}\n\nexport function getDefaultAiPeer(host?: HonchoHost): string {\n return DEFAULT_AI_PEER[host ?? getDetectedHost()];\n}\n\n// MCP tool arguments may arrive as strings; Boolean(\"false\") is true.\nexport function coerceBoolean(value: unknown): boolean {\n if (typeof value === \"string\") {\n const v = value.trim().toLowerCase();\n return v !== \"false\" && v !== \"0\" && v !== \"\";\n }\n return Boolean(value);\n}\n\n// Stdin cache: entry points read stdin once via initHook(),\n// handlers consume from cache via getCachedStdin().\nlet _stdinText: string | null = null;\n\nexport function cacheStdin(text: string): void {\n _stdinText = text;\n}\n\nexport function getCachedStdin(): string | null {\n return _stdinText;\n}\n\n/** Runtime-agnostic stdin read (hooks run under bun in dev, node when bundled). */\nexport async function readStdinText(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf-8\");\n}\n\n/**\n * Shared hook entry point initialization.\n * Reads stdin once, caches it, detects host, and exits early for unsupported hosts.\n * Must be called at the top of every hook entry point before the handler.\n */\nexport async function initHook(): Promise<void> {\n const stdinText = await readStdinText();\n cacheStdin(stdinText);\n let input: Record<string, unknown> = {};\n try { input = JSON.parse(stdinText || \"{}\"); } catch { process.exit(0); }\n if (input.cursor_version) process.exit(0);\n setDetectedHost(detectHost(input));\n}\n\n// ============================================\n// Config Types\n// ============================================\n\n/** Raw shape of ~/.honcho/config.json on disk */\ninterface HonchoFileConfig {\n apiKey?: string;\n peerName?: string;\n workspace?: string;\n aiPeer?: string;\n sessions?: Record<string, string>;\n saveMessages?: boolean;\n /** Save [Tool] action summaries to Honcho (default: false) */\n saveToolUse?: boolean;\n /** Save [Git External] state-change events to Honcho (default: false) */\n saveGitEvents?: boolean;\n messageUpload?: MessageUploadConfig;\n contextRefresh?: ContextRefreshConfig;\n endpoint?: HonchoEndpointConfig;\n localContext?: LocalContextConfig;\n enabled?: boolean;\n logging?: boolean;\n sessionStrategy?: SessionStrategy;\n /** Prefix session names with peerName (default: true, disable for solo use) */\n sessionPeerPrefix?: boolean;\n /** Default reasoning level for Honcho dialectic calls (default: \"medium\") */\n reasoningLevel?: ReasoningLevel;\n /** Observation mode (default: \"unified\") */\n observationMode?: ObservationMode;\n /** Memory statusLine visibility: \"on\" (default) · \"off\" */\n statusline?: StatuslineMode;\n /** Composable injection config (session-start + per-turn component menus). */\n injection?: InjectionConfig;\n /** Register the on-demand `honcho_remember` MCP tool (default: false). */\n rememberTool?: boolean;\n hosts?: Record<string, HostConfig>;\n /** When true, flat workspace/aiPeer fields apply to ALL hosts,\n * ignoring host-specific blocks. When false (default), each host\n * uses its own block and flat fields are fallbacks only. */\n globalOverride?: boolean;\n // Legacy flat fields (read-only fallbacks when no hosts block)\n cursorPeer?: string;\n claudePeer?: string;\n}\n\n/** Resolved runtime config consumed by all other code.\n * Host-specific fields (workspace, aiPeer) are resolved from the hosts block\n * or legacy flat fields in HonchoFileConfig. */\nexport interface HonchoCLAUDEConfig {\n /** The user's peer name */\n peerName: string;\n /** Honcho API key */\n apiKey: string;\n /** Honcho workspace name (resolved per-host) */\n workspace: string;\n /** AI peer name (resolved per-host, e.g. \"claude\" for claude-code) */\n aiPeer: string;\n\n /** How sessions are named: per-directory, git-branch, or chat-instance */\n sessionStrategy?: SessionStrategy;\n /** Prefix session names with peerName (default: true, disable for solo use) */\n sessionPeerPrefix?: boolean;\n /** Map of directory path -> session name overrides */\n sessions?: Record<string, string>;\n /** Save messages to Honcho (default: true) */\n saveMessages?: boolean;\n /** Save [Tool] action summaries to Honcho (default: false — low signal, redundant with assistant reasoning) */\n saveToolUse?: boolean;\n /** Save [Git External] state-change events to Honcho (default: false — machine plumbing, not user input) */\n saveGitEvents?: boolean;\n /** Default reasoning level for Honcho dialectic calls (default: \"medium\") */\n reasoningLevel?: ReasoningLevel;\n /**\n * Observation mode (default: \"unified\").\n * \"unified\": all agents write to user's self-observation collection.\n * \"directional\": this AI keeps its own per-AI view of the user.\n */\n observationMode?: ObservationMode;\n /** Memory statusLine visibility: \"on\" (default) · \"off\" */\n statusline?: StatuslineMode;\n /** Token-based upload limits */\n messageUpload?: MessageUploadConfig;\n /** Context retrieval settings */\n contextRefresh?: ContextRefreshConfig;\n /** SaaS vs local instance config */\n endpoint?: HonchoEndpointConfig;\n /** Local claude-context.md settings */\n localContext?: LocalContextConfig;\n /** Composable injection config (session-start + per-turn component menus) */\n injection?: InjectionConfig;\n /** Register the on-demand `honcho_remember` MCP tool (default: false).\n * Not a hook-injection surface — a deliberate, model-invoked recall tool. */\n rememberTool?: boolean;\n /** Temporarily disable plugin (default: true) */\n enabled?: boolean;\n /** Enable file logging to ~/.honcho/ (default: true) */\n logging?: boolean;\n /** When true, flat workspace/aiPeer fields apply to ALL hosts */\n globalOverride?: boolean;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a == null || b == null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return false;\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const keys = new Set([...Object.keys(aObj), ...Object.keys(bObj)]);\n for (const key of keys) {\n if (!deepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n}\n\nconst CONFIG_DIR = join(homedir(), \".honcho\");\nconst CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\n\nexport function getConfigDir(): string {\n return CONFIG_DIR;\n}\n\nexport function getConfigPath(): string {\n return CONFIG_FILE;\n}\n\nexport function configExists(): boolean {\n return existsSync(CONFIG_FILE);\n}\n\n/**\n * The plugin's own version, read from plugin.json — the same source the\n * version-check script uses. Returns \"unknown\" when the manifest can't be\n * located, so callers never advertise a stale hardcoded number.\n */\nexport function getPluginVersion(): string {\n // CLAUDE_PLUGIN_ROOT when the host sets it; otherwise one hop up from this\n // module, which holds in both layouts (src/ in dev, the dist/ chunk bundled).\n const root = process.env.CLAUDE_PLUGIN_ROOT;\n const candidates = [\n ...(root ? [join(root, \".claude-plugin\", \"plugin.json\")] : []),\n fileURLToPath(new URL(\"../.claude-plugin/plugin.json\", import.meta.url)),\n ];\n for (const manifest of candidates) {\n try {\n const version = (JSON.parse(readFileSync(manifest, \"utf-8\")) as { version?: unknown }).version;\n if (typeof version === \"string\" && version) return version;\n } catch {\n // Try the next candidate\n }\n }\n return \"unknown\";\n}\n\n/**\n * Load config from file, with environment variable fallbacks.\n * Host-specific fields are resolved from the hosts block in the config file.\n */\nexport function loadConfig(host?: HonchoHost): HonchoCLAUDEConfig | null {\n const resolvedHost = host ?? getDetectedHost();\n\n if (configExists()) {\n try {\n const content = readFileSync(CONFIG_FILE, \"utf-8\");\n const raw = JSON.parse(content) as HonchoFileConfig;\n return resolveConfig(raw, resolvedHost);\n } catch {\n // Fall through to env-only config\n }\n }\n return loadConfigFromEnv(resolvedHost);\n}\n\nfunction resolveConfig(raw: HonchoFileConfig, host: HonchoHost): HonchoCLAUDEConfig | null {\n const hostBlock = raw.hosts?.[host]\n ?? raw.hosts?.[host.replace(/_/g, \"-\")]\n ?? raw.hosts?.[host.replace(/-/g, \"_\")];\n\n // Resolution order: env var > host-scoped apiKey > root apiKey.\n const apiKey = process.env.HONCHO_API_KEY || hostBlock?.apiKey || raw.apiKey;\n if (!apiKey) return null;\n\n const peerName = raw.peerName || process.env.HONCHO_PEER_NAME || process.env.USER || process.env.USERNAME || \"user\";\n\n // Resolve host-specific fields\n let workspace: string;\n let aiPeer: string;\n\n if (raw.globalOverride === true) {\n // Global override: flat fields apply to ALL hosts\n workspace = raw.workspace ?? DEFAULT_WORKSPACE[host];\n aiPeer = raw.aiPeer ?? hostBlock?.aiPeer ?? DEFAULT_AI_PEER[host];\n } else if (hostBlock) {\n // Host-specific block takes precedence\n workspace = hostBlock.workspace ?? DEFAULT_WORKSPACE[host];\n aiPeer = hostBlock.aiPeer ?? DEFAULT_AI_PEER[host];\n } else {\n // Legacy flat-field fallback for configs written before hosts block.\n // Env var is respected here (matching main-branch behavior) so it gets\n // captured into the hosts block on first saveConfig(), after which the\n // env var becomes redundant and is safely ignored.\n workspace = process.env.HONCHO_WORKSPACE ?? raw.workspace ?? DEFAULT_WORKSPACE[host];\n if (host === \"cursor\") {\n aiPeer = raw.cursorPeer ?? DEFAULT_AI_PEER[\"cursor\"];\n } else {\n aiPeer = raw.claudePeer ?? DEFAULT_AI_PEER[\"claude_code\"];\n }\n }\n\n // Per-host settings: check hosts.<name>.X first, fall back to root X.\n // This lets the user set global defaults at root (via CLI) while\n // individual integrations can override per-host without touching root.\n const config: HonchoCLAUDEConfig = {\n apiKey,\n peerName,\n workspace,\n aiPeer,\n sessionStrategy: hostBlock?.sessionStrategy ?? raw.sessionStrategy,\n sessionPeerPrefix: hostBlock?.sessionPeerPrefix ?? raw.sessionPeerPrefix,\n sessions: raw.sessions,\n saveMessages: hostBlock?.saveMessages ?? raw.saveMessages,\n saveToolUse: hostBlock?.saveToolUse ?? raw.saveToolUse,\n saveGitEvents: hostBlock?.saveGitEvents ?? raw.saveGitEvents,\n reasoningLevel: hostBlock?.reasoningLevel ?? raw.reasoningLevel,\n observationMode: hostBlock?.observationMode ?? raw.observationMode,\n messageUpload: hostBlock?.messageUpload ?? raw.messageUpload,\n contextRefresh: hostBlock?.contextRefresh ?? raw.contextRefresh,\n endpoint: hostBlock?.endpoint ?? raw.endpoint,\n localContext: hostBlock?.localContext ?? raw.localContext,\n injection: hostBlock?.injection ?? raw.injection,\n rememberTool: hostBlock?.rememberTool ?? raw.rememberTool,\n enabled: hostBlock?.enabled ?? raw.enabled,\n logging: hostBlock?.logging ?? raw.logging,\n globalOverride: raw.globalOverride,\n };\n\n return mergeWithEnvVars(config);\n}\n\n/**\n * Load config purely from environment variables.\n * Returns null if HONCHO_API_KEY is not set.\n * HONCHO_WORKSPACE is respected here (no file config to conflict with).\n */\nexport function loadConfigFromEnv(host?: HonchoHost): HonchoCLAUDEConfig | null {\n const apiKey = process.env.HONCHO_API_KEY;\n if (!apiKey) {\n return null;\n }\n\n const resolvedHost = host ?? getDetectedHost();\n const peerName = process.env.HONCHO_PEER_NAME || process.env.USER || process.env.USERNAME || \"user\";\n const workspace = process.env.HONCHO_WORKSPACE || DEFAULT_WORKSPACE[resolvedHost];\n const hostPeerEnv = resolvedHost === \"cursor\"\n ? process.env.HONCHO_CURSOR_PEER\n : process.env.HONCHO_CLAUDE_PEER;\n const aiPeer = process.env.HONCHO_AI_PEER || hostPeerEnv || DEFAULT_AI_PEER[resolvedHost];\n const endpoint = process.env.HONCHO_ENDPOINT;\n\n const config: HonchoCLAUDEConfig = {\n apiKey,\n peerName,\n workspace,\n aiPeer,\n saveMessages: process.env.HONCHO_SAVE_MESSAGES !== \"false\",\n saveToolUse: process.env.HONCHO_SAVE_TOOL_USE === \"true\",\n saveGitEvents: process.env.HONCHO_SAVE_GIT_EVENTS === \"true\",\n enabled: process.env.HONCHO_ENABLED !== \"false\",\n logging: process.env.HONCHO_LOGGING !== \"false\",\n };\n\n if (endpoint) {\n if (endpoint === \"local\") {\n config.endpoint = { environment: \"local\" };\n } else if (endpoint.startsWith(\"http\")) {\n config.endpoint = { baseUrl: endpoint };\n }\n }\n\n return config;\n}\n\n/**\n * Merge file-based config with environment variable overrides.\n * Only merges global (non-host-specific) env vars. workspace and aiPeer\n * are host-specific fields already resolved by resolveConfig() from the\n * hosts block -- generic env vars like HONCHO_WORKSPACE must not override\n * them here, otherwise a value set for one host clobbers the other.\n * (HONCHO_WORKSPACE IS respected in loadConfigFromEnv when no file exists.)\n */\nfunction mergeWithEnvVars(config: HonchoCLAUDEConfig): HonchoCLAUDEConfig {\n if (process.env.HONCHO_API_KEY) {\n config.apiKey = process.env.HONCHO_API_KEY;\n }\n if (process.env.HONCHO_PEER_NAME) {\n config.peerName = process.env.HONCHO_PEER_NAME;\n }\n if (process.env.HONCHO_ENABLED === \"false\") {\n config.enabled = false;\n }\n if (process.env.HONCHO_LOGGING === \"false\") {\n config.logging = false;\n }\n if (process.env.HONCHO_SAVE_TOOL_USE !== undefined) {\n config.saveToolUse = process.env.HONCHO_SAVE_TOOL_USE === \"true\";\n }\n if (process.env.HONCHO_SAVE_GIT_EVENTS !== undefined) {\n config.saveGitEvents = process.env.HONCHO_SAVE_GIT_EVENTS === \"true\";\n }\n return config;\n}\n\n/**\n * Write-back: read-merge-write to avoid clobbering other hosts' config.\n *\n * Convention:\n * - Root-level keys (apiKey, peerName, enabled, etc.) are owned by\n * the user or the honcho CLI. This integration NEVER writes them.\n * - hosts.<this-host> is owned by this integration and carries all\n * per-host settings (workspace, aiPeer, enabled, logging, ...).\n * - sessions is shared across hosts -- written at root.\n *\n * resolveConfig() reads host block first, falls back to root, so the\n * user's root-level defaults still apply until overridden per-host.\n */\nexport function saveConfig(config: HonchoCLAUDEConfig): void {\n if (!existsSync(CONFIG_DIR)) {\n mkdirSync(CONFIG_DIR, { recursive: true });\n }\n\n // Re-read from disk to avoid clobbering other tools' changes\n let existing: HonchoFileConfig = {};\n if (existsSync(CONFIG_FILE)) {\n try {\n existing = JSON.parse(readFileSync(CONFIG_FILE, \"utf-8\"));\n } catch {\n // Start fresh if corrupt\n }\n }\n\n // Sessions are shared across hosts -- write at root\n if (config.sessions !== undefined) {\n existing.sessions = config.sessions;\n }\n\n // Everything else goes in the host block.\n // Keep workspace/aiPeer host-local, but avoid materializing root defaults\n // into new host overrides. This preserves root fallback behavior.\n const host = getDetectedHost();\n if (!existing.hosts) existing.hosts = {};\n const existingHost: HostConfig = existing.hosts[host] ?? {};\n\n const hostEntry: HostConfig = {};\n\n const setHostIfExplicit = <K extends keyof HostConfig>(\n key: K,\n value: HostConfig[K],\n rootValue: unknown\n ) => {\n if (value === undefined) return;\n const hasHostOverride = Object.prototype.hasOwnProperty.call(existingHost, key);\n if (hasHostOverride || !deepEqual(value, rootValue)) {\n hostEntry[key] = value;\n }\n };\n\n // Only persist workspace/aiPeer to host block if the block already had them\n // or if they differ from the default for this host. This prevents root\n // fallback values from being materialized into host overrides.\n setHostIfExplicit(\"workspace\", config.workspace, existing.workspace ?? DEFAULT_WORKSPACE[host]);\n setHostIfExplicit(\"aiPeer\", config.aiPeer, existing.aiPeer ?? DEFAULT_AI_PEER[host]);\n\n // Don't persist env-only overrides to the host block.\n // mergeWithEnvVars() may have set enabled=false or logging=false from\n // HONCHO_ENABLED / HONCHO_LOGGING env vars — those are runtime overrides\n // that should not be materialized to disk.\n const enabledForSave = process.env.HONCHO_ENABLED === \"false\" && config.enabled === false\n ? existingHost.enabled // preserve what was on disk\n : config.enabled;\n const loggingForSave = process.env.HONCHO_LOGGING === \"false\" && config.logging === false\n ? existingHost.logging\n : config.logging;\n\n setHostIfExplicit(\"enabled\", enabledForSave, existing.enabled);\n setHostIfExplicit(\"logging\", loggingForSave, existing.logging);\n setHostIfExplicit(\"saveMessages\", config.saveMessages, existing.saveMessages);\n setHostIfExplicit(\"sessionStrategy\", config.sessionStrategy, existing.sessionStrategy);\n setHostIfExplicit(\"sessionPeerPrefix\", config.sessionPeerPrefix, existing.sessionPeerPrefix);\n setHostIfExplicit(\"reasoningLevel\", config.reasoningLevel, existing.reasoningLevel);\n setHostIfExplicit(\"observationMode\", config.observationMode, existing.observationMode);\n setHostIfExplicit(\"messageUpload\", config.messageUpload, existing.messageUpload);\n setHostIfExplicit(\"contextRefresh\", config.contextRefresh, existing.contextRefresh);\n setHostIfExplicit(\"localContext\", config.localContext, existing.localContext);\n setHostIfExplicit(\"endpoint\", config.endpoint, existing.endpoint);\n setHostIfExplicit(\"injection\", config.injection, existing.injection);\n setHostIfExplicit(\"rememberTool\", config.rememberTool, existing.rememberTool);\n\n // Preserve a host-scoped apiKey already on disk. This integration never writes\n // apiKey (config.apiKey is the *resolved* key — env/root — and must not be\n // materialized here), but must not drop hosts.<host>.apiKey on rewrite.\n if (existingHost.apiKey !== undefined) {\n hostEntry.apiKey = existingHost.apiKey;\n }\n\n existing.hosts[host] = hostEntry;\n\n writeFileSync(CONFIG_FILE, JSON.stringify(existing, null, 2));\n}\n\n/**\n * Write a single root-level field to config.json.\n * ONLY for explicit user-directed actions (MCP set_config) on fields\n * that are genuinely global (apiKey, peerName, globalOverride).\n * Hooks and routine operations must NEVER call this.\n */\nexport function saveRootField(field: string, value: unknown): void {\n if (!existsSync(CONFIG_DIR)) {\n mkdirSync(CONFIG_DIR, { recursive: true });\n }\n\n let existing: Record<string, unknown> = {};\n if (existsSync(CONFIG_FILE)) {\n try {\n existing = JSON.parse(readFileSync(CONFIG_FILE, \"utf-8\"));\n } catch {}\n }\n\n existing[field] = value;\n writeFileSync(CONFIG_FILE, JSON.stringify(existing, null, 2));\n}\n\nexport function getClaudeSettingsPath(): string {\n return join(homedir(), \".claude\", \"settings.json\");\n}\n\nexport function getClaudeSettingsDir(): string {\n return join(homedir(), \".claude\");\n}\n\n/** Main repository root for a linked worktree, parsed from dir's `.git`\n * pointer file. Handles standard (`<repo>/.git/worktrees/<n>`) and bare-hub\n * (`<hub>.git/worktrees/<n>`) layouts; null for regular repositories and\n * anything else (submodules, separate-git-dir). */\nexport function resolveWorktreeMainRoot(dir: string): string | null {\n try {\n const gitPath = join(dir, \".git\");\n if (!statSync(gitPath).isFile()) return null;\n const match = readFileSync(gitPath, \"utf-8\").match(/^gitdir:\\s*(.+?)\\s*$/m);\n if (!match) return null;\n const gitdir = resolve(dir, match[1]);\n const idx = gitdir.lastIndexOf(`${sep}worktrees${sep}`);\n if (idx === -1) return null;\n const gitContainer = gitdir.slice(0, idx);\n if (basename(gitContainer) === \".git\") return dirname(gitContainer);\n if (gitContainer.endsWith(\".git\")) return gitContainer;\n return null;\n } catch {\n return null;\n }\n}\n\n// Bound on the .git lookup walk; cwds nested deeper keep per-directory naming.\nconst MAX_GIT_WALK_UP = 12;\n\n/** Main repository root when cwd is inside a linked git worktree, else null. */\nexport function worktreeMainRootFor(cwd: string): string | null {\n try {\n let dir = resolve(cwd);\n for (let i = 0; i < MAX_GIT_WALK_UP; i++) {\n if (existsSync(join(dir, \".git\"))) return resolveWorktreeMainRoot(dir);\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n } catch {\n /* ignore */\n }\n return null;\n}\n\nexport function getSessionForPath(cwd: string, mainRoot?: string | null): string | null {\n const config = loadConfig();\n if (!config?.sessions) return null;\n if (config.sessions[cwd]) return config.sessions[cwd];\n // Worktrees without a mapping of their own share the main repo's session.\n const mr = mainRoot === undefined ? worktreeMainRootFor(cwd) : mainRoot;\n if (mr && config.sessions[mr]) return config.sessions[mr];\n return null;\n}\n\nexport function deriveSessionName(\n strategy: SessionStrategy,\n cwd: string,\n opts: { peerName?: string; sessionPeerPrefix?: boolean; branch?: string; instanceId?: string } = {}\n): string {\n const usePrefix = opts.sessionPeerPrefix !== false; // default true\n const peerPart = opts.peerName ? sanitizeForSessionName(opts.peerName) : \"user\";\n const repoPart = sanitizeForSessionName(basename(cwd));\n const base = usePrefix ? `${peerPart}-${repoPart}` : repoPart;\n\n switch (strategy) {\n case \"git-branch\": {\n if (opts.branch) {\n const branchPart = sanitizeForSessionName(opts.branch);\n return `${base}-${branchPart}`;\n }\n return base;\n }\n case \"chat-instance\": {\n if (opts.instanceId) {\n return usePrefix ? `${peerPart}-chat-${opts.instanceId}` : `chat-${opts.instanceId}`;\n }\n return base;\n }\n case \"per-directory\":\n default:\n return base;\n }\n}\n\n/** Session name derived from strategy. Manual overrides only apply to per-directory.\n * @param instanceId - Explicit instance ID for chat-instance strategy. Falls back to\n * per-cwd cache, then global cache. Callers should pass hookInput.session_id\n * when available to avoid cross-session collision from the global cache.\n */\nexport function getSessionName(cwd: string, instanceId?: string): string {\n const config = loadConfig();\n const strategy = config?.sessionStrategy ?? \"per-directory\";\n const mainRoot = worktreeMainRootFor(cwd);\n\n // Manual overrides only apply to per-directory strategy.\n // For chat-instance and git-branch, the session name is always derived dynamically.\n if (strategy === \"per-directory\") {\n const configuredSession = getSessionForPath(cwd, mainRoot);\n if (configuredSession) {\n return configuredSession;\n }\n }\n\n // Resolve live env state, then delegate to the pure deriver.\n let branch: string | undefined;\n if (strategy === \"git-branch\") {\n branch = captureGitState(cwd)?.branch;\n }\n let resolvedInstanceId: string | undefined;\n if (strategy === \"chat-instance\") {\n // Prefer explicit instanceId > per-cwd cache > global cache (legacy)\n resolvedInstanceId = instanceId || getInstanceIdForCwd(cwd) || getClaudeInstanceId() || undefined;\n }\n\n // Worktrees derive from the main repo's path; branch still comes from the\n // worktree's own checkout above.\n return deriveSessionName(strategy, mainRoot ?? cwd, {\n peerName: config?.peerName,\n sessionPeerPrefix: config?.sessionPeerPrefix,\n branch,\n instanceId: resolvedInstanceId,\n });\n}\n\nexport function setSessionForPath(cwd: string, sessionName: string): void {\n const config = loadConfig();\n if (!config) return;\n if (!config.sessions) {\n config.sessions = {};\n }\n config.sessions[cwd] = sessionName;\n saveConfig(config);\n}\n\nexport function getAllSessions(): Record<string, string> {\n const config = loadConfig();\n return config?.sessions || {};\n}\n\nexport function removeSessionForPath(cwd: string): void {\n const config = loadConfig();\n if (!config?.sessions) return;\n delete config.sessions[cwd];\n saveConfig(config);\n}\n\nexport function getMessageUploadConfig(): MessageUploadConfig {\n const config = loadConfig();\n return {\n maxUserTokens: config?.messageUpload?.maxUserTokens ?? undefined,\n maxAssistantTokens: config?.messageUpload?.maxAssistantTokens ?? undefined,\n summarizeAssistant: config?.messageUpload?.summarizeAssistant ?? false,\n };\n}\n\nexport function getContextRefreshConfig(): ContextRefreshConfig {\n const config = loadConfig();\n return {\n messageThreshold: config?.contextRefresh?.messageThreshold ?? 30,\n ttlSeconds: config?.contextRefresh?.ttlSeconds ?? 300,\n skipDialectic: config?.contextRefresh?.skipDialectic ?? false,\n };\n}\n\nexport function getLocalContextConfig(): LocalContextConfig {\n const config = loadConfig();\n return {\n maxEntries: config?.localContext?.maxEntries ?? 50,\n };\n}\n\n/**\n * Resolved injection config with every field defaulted. Callers get a fully\n * populated object so they never repeat the fallback literals. Config comes\n * from parsed JSON, so absent keys simply don't appear — the spread over\n * DEFAULT_INJECTION defaults them, while an explicit `[]` is preserved.\n *\n * Pass the already-loaded config (hooks have it in scope) to avoid a second\n * disk read + parse on the per-turn hot path; omit it for a standalone lookup.\n */\nexport function getInjectionConfig(config?: HonchoCLAUDEConfig | null): Required<InjectionConfig> {\n const injection = (config === undefined ? loadConfig() : config)?.injection;\n const resolved = { ...DEFAULT_INJECTION, ...(injection ?? {}) };\n // Guard hand-edited configs: a non-array component list falls back to the default.\n resolved.perTurn = Array.isArray(resolved.perTurn)\n ? normalizePerTurn(resolved.perTurn)\n : DEFAULT_INJECTION.perTurn;\n resolved.showContents = Array.isArray(resolved.showContents)\n ? normalizePerTurn(resolved.showContents)\n : DEFAULT_INJECTION.showContents;\n return resolved;\n}\n\nexport function isLoggingEnabled(): boolean {\n const config = loadConfig();\n return config?.logging !== false;\n}\n\nexport function isPluginEnabled(): boolean {\n const config = loadConfig();\n return config?.enabled !== false;\n}\n\nexport function setPluginEnabled(enabled: boolean): void {\n const config = loadConfig();\n if (!config) return;\n config.enabled = enabled;\n saveConfig(config);\n}\n\n\n\n/**\n * Get all known host keys from the config file's hosts block.\n */\nexport function getKnownHosts(): string[] {\n const cfgPath = getConfigPath();\n if (!existsSync(cfgPath)) return [];\n try {\n const raw = JSON.parse(readFileSync(cfgPath, \"utf-8\"));\n return raw.hosts ? Object.keys(raw.hosts) : [];\n } catch {\n return [];\n }\n}\n\n/** Simple token estimation (chars / 4) */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n\nexport function truncateToTokens(text: string, maxTokens: number): string {\n const estimatedChars = maxTokens * 4;\n if (text.length <= estimatedChars) {\n return text;\n }\n return text.slice(0, estimatedChars - 3) + \"...\";\n}\n\nexport interface HonchoClientOptions {\n apiKey: string;\n baseURL: string;\n workspaceId: string;\n timeout?: number;\n maxRetries?: number;\n}\n\n/** Get the base URL for Honcho API. Priority: baseUrl > environment > production */\nexport function getHonchoBaseUrlForEndpoint(endpoint?: HonchoEndpointConfig): string {\n if (endpoint?.baseUrl) {\n const url = endpoint.baseUrl;\n return url.endsWith(\"/v3\") ? url : `${url}/v3`;\n }\n if (endpoint?.environment === \"local\") {\n return HONCHO_BASE_URLS.local;\n }\n return HONCHO_BASE_URLS.production;\n}\n\n/** Get the base URL for a resolved runtime config. */\nexport function getHonchoBaseUrl(config: HonchoCLAUDEConfig): string {\n return getHonchoBaseUrlForEndpoint(config.endpoint);\n}\n\nexport function getHonchoClientOptions(config: HonchoCLAUDEConfig): HonchoClientOptions {\n return {\n apiKey: config.apiKey,\n baseURL: getHonchoBaseUrl(config),\n workspaceId: config.workspace,\n timeout: 120000,\n maxRetries: 1,\n };\n}\n\nexport function getEndpointInfo(config: HonchoCLAUDEConfig): { type: string; url: string } {\n if (config.endpoint?.baseUrl) {\n return { type: \"custom\", url: config.endpoint.baseUrl };\n }\n if (config.endpoint?.environment === \"local\") {\n return { type: \"local\", url: HONCHO_BASE_URLS.local };\n }\n return { type: \"production\", url: HONCHO_BASE_URLS.production };\n}\n\nconst VALID_ENVIRONMENTS = new Set<HonchoEnvironment>([\"production\", \"local\"]);\n\n/** Returns the resolved observation mode, defaulting to \"unified\". */\nexport function getObservationMode(config: HonchoCLAUDEConfig): ObservationMode {\n return config.observationMode ?? \"unified\";\n}\n\nexport function setEndpoint(environment?: HonchoEnvironment, baseUrl?: string): void {\n const config = loadConfig();\n if (!config) return;\n if (environment && !VALID_ENVIRONMENTS.has(environment)) return;\n config.endpoint = { environment, baseUrl };\n saveConfig(config);\n}\n",
|
|
6
|
+
"import { Honcho } from \"@honcho-ai/sdk\";\nimport { loadConfig, getSessionForPath, getSessionName, getHonchoClientOptions, isPluginEnabled, getCachedStdin, readStdinText, getObservationMode } from \"../config.js\";\nimport { Spinner } from \"../spinner.js\";\nimport { setMemoryState } from \"../state.js\";\nimport { logHook, logApiCall, setLogContext } from \"../log.js\";\nimport { formatVerboseBlock, formatVerboseList } from \"../visual.js\";\n\n\ninterface HookInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n trigger?: \"manual\" | \"auto\";\n custom_instructions?: string;\n workspace_roots?: string[];\n}\n\n/**\n * Format a compact memory card that survives summarization\n * This is injected RIGHT BEFORE compaction so it becomes part of the summary\n */\nfunction formatMemoryCard(\n config: { peerName: string; aiPeer: string; workspace: string },\n sessionName: string,\n userContext: any,\n claudeContext: any,\n summaries: any,\n userDialectic: string | null,\n claudeDialectic: string | null\n): string {\n const parts: string[] = [];\n\n // Header - identity anchor\n parts.push(`## HONCHO MEMORY ANCHOR (Pre-Compaction Injection)\nThis context is being injected because the conversation is about to be summarized.\nThese conclusions MUST be preserved in the summary.\n\n### Session Identity\n- User: ${config.peerName}\n- AI: ${config.aiPeer}\n- Workspace: ${config.workspace}\n- Session: ${sessionName}`);\n\n // User profile - critical to preserve\n const userPeerCard = userContext?.peerCard;\n if (userPeerCard?.length > 0) {\n parts.push(`### ${config.peerName}'s Profile (PRESERVE)\n${userPeerCard.join(\"\\n\")}`);\n }\n\n // Key user conclusions\n const userRep = userContext?.representation;\n if (typeof userRep === \"string\" && userRep.trim()) {\n parts.push(`### Key Conclusions About ${config.peerName} (PRESERVE)\\n${userRep}`);\n }\n\n // Claude's self-context - what was I working on\n const claudeRep = claudeContext?.representation;\n if (typeof claudeRep === \"string\" && claudeRep.trim()) {\n parts.push(`### ${config.aiPeer}'s Recent Work (PRESERVE)\\n${claudeRep}`);\n }\n\n // Session summary - what we were doing\n const shortSummary = summaries?.shortSummary;\n if (shortSummary?.content) {\n parts.push(`### Session Context (PRESERVE)\n${shortSummary.content}`);\n }\n\n // Fresh dialectic insights - expensive but worth it at compaction time\n if (userDialectic) {\n parts.push(`### AI Understanding of ${config.peerName} (PRESERVE)\n${userDialectic}`);\n }\n\n if (claudeDialectic) {\n parts.push(`### ${config.aiPeer}'s Self-Reflection (PRESERVE)\n${claudeDialectic}`);\n }\n\n parts.push(`### End Memory Anchor\nThe above context represents persistent memory from Honcho.\nWhen summarizing this conversation, ensure these conclusions are preserved.`);\n\n return parts.join(\"\\n\\n\");\n}\n\nexport async function handlePreCompact(): Promise<void> {\n const config = loadConfig();\n if (!config) {\n // No config, nothing to inject\n process.exit(0);\n }\n\n // Early exit if plugin is disabled\n if (!isPluginEnabled()) {\n process.exit(0);\n }\n\n let hookInput: HookInput = {};\n try {\n const input = getCachedStdin() ?? await readStdinText();\n if (input.trim()) {\n hookInput = JSON.parse(input);\n }\n } catch {\n // No input, continue with defaults\n }\n\n const cwd = hookInput.workspace_roots?.[0] || hookInput.cwd || process.cwd();\n const trigger = hookInput.trigger || \"auto\";\n\n // Set log context\n setLogContext(cwd, getSessionName(cwd));\n\n logHook(\"pre-compact\", `Compaction triggered (${trigger})`);\n\n // Show spinner for auto compaction (context window full)\n const spinner = new Spinner({ style: \"neural\" });\n if (trigger === \"auto\") {\n spinner.start(\"anchoring memory before compaction\");\n }\n setMemoryState(\"compacting\", undefined, hookInput.session_id);\n\n try {\n const honcho = new Honcho(getHonchoClientOptions(config));\n const sessionName = getSessionName(cwd);\n const observationMode = getObservationMode(config);\n\n // Get session and peers using new fluent API\n const session = await honcho.session(sessionName);\n const userPeer = await honcho.peer(config.peerName);\n const aiPeer = await honcho.peer(config.aiPeer);\n\n // unified: user self-observations — query via userPeer.\n // directional: ai cross-observations — query via aiPeer with target.\n const contextPeer = observationMode === \"unified\" ? userPeer : aiPeer;\n const contextTarget = observationMode === \"unified\" ? undefined : config.peerName;\n const contextLabel = observationMode === \"unified\" ? \"userPeer.context()\" : `aiPeer.context(target=${config.peerName})`;\n\n if (trigger === \"auto\") {\n spinner.update(\"fetching memory context\");\n }\n\n logApiCall(contextLabel, \"GET\", observationMode === \"unified\" ? \"self\" : `target=${config.peerName}`);\n logApiCall(\"session.summaries\", \"GET\", sessionName);\n logApiCall(\"peer.chat\", \"POST\", \"dialectic queries x2\");\n\n // Fetch ALL context in parallel - this is the RIGHT time for expensive calls\n // because the context is about to be reset anyway\n const dialecticArgs = observationMode === \"unified\"\n ? { session, reasoningLevel: config.reasoningLevel ?? \"low\" }\n : { target: config.peerName, session, reasoningLevel: config.reasoningLevel ?? \"low\" };\n\n const [userContextResult, summariesResult, userChatResult, claudeChatResult] =\n await Promise.allSettled([\n contextPeer.context({\n ...(contextTarget ? { target: contextTarget } : {}),\n maxConclusions: 30,\n includeMostFrequent: true,\n }),\n // Session summaries\n session.summaries(),\n // Fresh dialectic - ask about user (worth the cost at compaction time)\n contextPeer.chat(\n `Summarize the most important things to remember about ${config.peerName}. Focus on their preferences, working style, current projects, and any critical context that should survive a conversation summary.`,\n dialecticArgs\n ),\n // Fresh dialectic - what were we working on together\n contextPeer.chat(\n `What are the most important things that were worked on with ${config.peerName}? Summarize key context that should be preserved.`,\n dialecticArgs\n ),\n ]);\n\n // Extract results\n const userContext = userContextResult.status === \"fulfilled\" ? userContextResult.value : null;\n const summaries = summariesResult.status === \"fulfilled\" ? summariesResult.value : null;\n\n // Build verbose output blocks — these will be appended to stdout after the\n // memory card. PreCompact stdout is only shown in Ctrl+O, so verbose data\n // is hidden by default and visible when the user presses Ctrl+O.\n const verboseBlocks: string[] = [];\n verboseBlocks.push(formatVerboseBlock(`pre-compact ${contextLabel}`, (userContext as any)?.representation));\n verboseBlocks.push(formatVerboseList(\"pre-compact peerCard\", (userContext as any)?.peerCard));\n\n const userDialectic =\n userChatResult.status === \"fulfilled\"\n ? userChatResult.value\n : null;\n const claudeDialectic =\n claudeChatResult.status === \"fulfilled\"\n ? claudeChatResult.value\n : null;\n\n // Format the memory card\n const memoryCard = formatMemoryCard(\n config,\n sessionName,\n userContext,\n null,\n summaries,\n userDialectic,\n claudeDialectic\n );\n\n if (trigger === \"auto\") {\n spinner.stop(\"memory anchored\");\n }\n setMemoryState(\"idle\", undefined, hookInput.session_id);\n\n // Add dialectic responses to verbose output\n if (userDialectic) {\n verboseBlocks.push(formatVerboseBlock(`pre-compact peer.chat(user) → \"${config.peerName}\"`, userDialectic));\n }\n if (claudeDialectic) {\n verboseBlocks.push(formatVerboseBlock(`pre-compact peer.chat(claude) → \"${config.aiPeer}\"`, claudeDialectic));\n }\n\n logHook(\"pre-compact\", `Memory anchored (${memoryCard.length} chars)`);\n\n // Output memory card to stdout, followed by verbose API data.\n // PreCompact stdout is only shown in Ctrl+O, so the verbose blocks\n // are hidden by default and visible when the user presses Ctrl+O.\n const verboseOutput = verboseBlocks.filter(Boolean).join(\"\\n\");\n console.log(`[${config.aiPeer}/Honcho Memory Anchor]\\n\\n${memoryCard}${verboseOutput}`);\n process.exit(0);\n } catch (error) {\n logHook(\"pre-compact\", `Error: ${error}`, { error: String(error) });\n if (trigger === \"auto\") {\n spinner.fail(\"memory anchor failed\");\n }\n setMemoryState(\"idle\", undefined, hookInput.session_id);\n // Don't block compaction on failure\n console.error(`[honcho] Pre-compact warning: ${error}`);\n process.exit(0);\n }\n}\n",
|
|
7
|
+
"#!/usr/bin/env bun\nimport { initHook } from \"../src/config.js\";\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Ae;AAAA,MACjB,cAAc,KAAK,mBAAmB,kCAAiC,OAAO,aAAa,aAAa,CAAC;AAAA,IAC3G;AAAA,IACA,IAAI,iBAAiB;AAAA,MACnB,cAAc,KAAK,mBAAmB,oCAAmC,OAAO,WAAW,eAAe,CAAC;AAAA,IAC7G;AAAA,IAEA,QAAQ,eAAe,oBAAoB,WAAW,eAAe;AAAA,IAKrE,MAAM,gBAAgB,cAAc,OAAO,OAAO,EAAE,KAAK;AAAA,CAAI;AAAA,IAC7D,QAAQ,IAAI,IAAI,OAAO;AAAA;AAAA,EAAmC,aAAa,eAAe;AAAA,IACtF,QAAQ,KAAK,CAAC;AAAA,IACd,OAAO,OAAO;AAAA,IACd,QAAQ,eAAe,UAAU,SAAS,EAAE,OAAO,OAAO,KAAK,EAAE,CAAC;AAAA,IAClE,IAAI,YAAY,QAAQ;AAAA,MACtB,QAAQ,KAAK,sBAAsB;AAAA,IACrC;AAAA,IACA,eAAe,QAAQ,WAAW,UAAU,UAAU;AAAA,IAEtD,QAAQ,MAAM,iCAAiC,OAAO;AAAA,IACtD,QAAQ,KAAK,CAAC;AAAA;AAAA;;;ACvOlB,MAAM,SAAS;AACf,MAAM,iBAAiB;",
|
|
10
|
+
"debugId": "3295B20DC4BCF58464756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import {
|
|
3
|
+
setMemoryState
|
|
4
|
+
} from "../chunk-9pntsn3x.js";
|
|
5
|
+
import {
|
|
6
|
+
getCachedStdin,
|
|
7
|
+
initHook
|
|
8
|
+
} from "../chunk-yfrrc1d5.js";
|
|
9
|
+
|
|
10
|
+
// src/hooks/pre-tool-honcho.ts
|
|
11
|
+
var LABELS = {
|
|
12
|
+
search: "searching",
|
|
13
|
+
chat: "asking",
|
|
14
|
+
get_context: "context",
|
|
15
|
+
get_representation: "recall",
|
|
16
|
+
create_conclusion: "writing",
|
|
17
|
+
list_conclusions: "listing",
|
|
18
|
+
delete_conclusion: "writing",
|
|
19
|
+
get_config: "config",
|
|
20
|
+
set_config: "config"
|
|
21
|
+
};
|
|
22
|
+
async function handlePreToolHoncho() {
|
|
23
|
+
try {
|
|
24
|
+
const raw = getCachedStdin();
|
|
25
|
+
const input = raw && raw.trim() ? JSON.parse(raw) : {};
|
|
26
|
+
const toolName = input.tool_name ?? "";
|
|
27
|
+
const verb = toolName.replace(/^mcp__plugin_honcho_honcho__/, "");
|
|
28
|
+
setMemoryState("querying", LABELS[verb] ?? verb ?? "tool", input.session_id);
|
|
29
|
+
} catch {}
|
|
30
|
+
process.exit(0);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// hooks/pre-tool-honcho.ts
|
|
34
|
+
await initHook();
|
|
35
|
+
await handlePreToolHoncho();
|
|
36
|
+
|
|
37
|
+
//# debugId=EA24B718CF1FC96964756E2164756E21
|
|
38
|
+
//# sourceMappingURL=pre-tool-honcho.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hooks/pre-tool-honcho.ts", "../../hooks/pre-tool-honcho.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { getCachedStdin } from \"../config.js\";\nimport { setMemoryState } from \"../state.js\";\n\n// Maps each honcho MCP tool to the short verb the statusline flashes while the\n// call is in flight. Anything unmapped falls back to the raw tool suffix.\nconst LABELS: Record<string, string> = {\n search: \"searching\",\n chat: \"asking\",\n get_context: \"context\",\n get_representation: \"recall\",\n create_conclusion: \"writing\",\n list_conclusions: \"listing\",\n delete_conclusion: \"writing\",\n get_config: \"config\",\n set_config: \"config\",\n};\n\n// PreToolUse for honcho MCP tools only — flashes which memory tool Claude is\n// calling onto the statusline. Best-effort and dependency-light so it adds\n// negligible latency to the tool call.\nexport async function handlePreToolHoncho(): Promise<void> {\n try {\n const raw = getCachedStdin();\n const input = raw && raw.trim() ? JSON.parse(raw) : {};\n const toolName: string = input.tool_name ?? \"\";\n const verb = toolName.replace(/^mcp__plugin_honcho_honcho__/, \"\");\n setMemoryState(\"querying\", LABELS[verb] ?? verb ?? \"tool\", input.session_id);\n } catch {\n // never block the tool call\n }\n process.exit(0);\n}\n",
|
|
6
|
+
"#!/usr/bin/env bun\nimport { initHook } from \"../src/config.js\";\nimport { handlePreToolHoncho } from \"../src/hooks/pre-tool-honcho.js\";\n\nawait initHook();\nawait handlePreToolHoncho();\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";;;;;;;;;;AAKA,IAAM,SAAiC;AAAA,EACrC,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,aAAa;AAAA,EACb,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,mBAAmB;AAAA,EACnB,YAAY;AAAA,EACZ,YAAY;AACd;AAKA,eAAsB,mBAAmB,GAAkB;AAAA,EACzD,IAAI;AAAA,IACF,MAAM,MAAM,eAAe;AAAA,IAC3B,MAAM,QAAQ,OAAO,IAAI,KAAK,IAAI,KAAK,MAAM,GAAG,IAAI,CAAC;AAAA,IACrD,MAAM,WAAmB,MAAM,aAAa;AAAA,IAC5C,MAAM,OAAO,SAAS,QAAQ,gCAAgC,EAAE;AAAA,IAChE,eAAe,YAAY,OAAO,SAAS,QAAQ,QAAQ,MAAM,UAAU;AAAA,IAC3E,MAAM;AAAA,EAGR,QAAQ,KAAK,CAAC;AAAA;;;AC1BhB,MAAM,SAAS;AACf,MAAM,oBAAoB;",
|
|
9
|
+
"debugId": "EA24B718CF1FC96964756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import {
|
|
3
|
+
isHarnessInjected,
|
|
4
|
+
isTerseReply
|
|
5
|
+
} from "../chunk-dxbm7kmf.js";
|
|
6
|
+
import"../chunk-49wja30f.js";
|
|
7
|
+
import"../chunk-9pntsn3x.js";
|
|
8
|
+
import"../chunk-xtdvbfxw.js";
|
|
9
|
+
import {
|
|
10
|
+
require_dist
|
|
11
|
+
} from "../chunk-4ryv9310.js";
|
|
12
|
+
import {
|
|
13
|
+
logApiCall,
|
|
14
|
+
logHook,
|
|
15
|
+
setLogContext
|
|
16
|
+
} from "../chunk-jr0fd6n2.js";
|
|
17
|
+
import {
|
|
18
|
+
__toESM,
|
|
19
|
+
addMessagesBatched,
|
|
20
|
+
chunkContent,
|
|
21
|
+
getCachedStdin,
|
|
22
|
+
getHonchoClientOptions,
|
|
23
|
+
getInstanceIdForCwd,
|
|
24
|
+
getSessionName,
|
|
25
|
+
initHook,
|
|
26
|
+
isPluginEnabled,
|
|
27
|
+
loadConfig,
|
|
28
|
+
readStdinText
|
|
29
|
+
} from "../chunk-yfrrc1d5.js";
|
|
30
|
+
|
|
31
|
+
// src/hooks/save-user-message.ts
|
|
32
|
+
var import_sdk = __toESM(require_dist(), 1);
|
|
33
|
+
async function handleSaveUserMessage() {
|
|
34
|
+
const config = loadConfig();
|
|
35
|
+
if (!config) {
|
|
36
|
+
process.exit(0);
|
|
37
|
+
}
|
|
38
|
+
if (!isPluginEnabled() || config.saveMessages === false) {
|
|
39
|
+
process.exit(0);
|
|
40
|
+
}
|
|
41
|
+
let hookInput = {};
|
|
42
|
+
try {
|
|
43
|
+
const input = getCachedStdin() ?? await readStdinText();
|
|
44
|
+
if (input.trim()) {
|
|
45
|
+
hookInput = JSON.parse(input);
|
|
46
|
+
}
|
|
47
|
+
} catch {
|
|
48
|
+
process.exit(0);
|
|
49
|
+
}
|
|
50
|
+
const prompt = hookInput.prompt || "";
|
|
51
|
+
if (!prompt.trim()) {
|
|
52
|
+
process.exit(0);
|
|
53
|
+
}
|
|
54
|
+
const cwd = hookInput.workspace_roots?.[0] || hookInput.cwd || process.cwd();
|
|
55
|
+
const instanceId = hookInput.session_id || getInstanceIdForCwd(cwd);
|
|
56
|
+
const sessionName = getSessionName(cwd, instanceId || undefined);
|
|
57
|
+
setLogContext(cwd, sessionName);
|
|
58
|
+
if (isHarnessInjected(prompt)) {
|
|
59
|
+
logHook("save-user-message", "Skipping upload (harness-injected content, not user input)");
|
|
60
|
+
process.exit(0);
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
await postUserMessage(config, prompt, instanceId || undefined, sessionName);
|
|
64
|
+
} catch (e) {
|
|
65
|
+
logHook("save-user-message", `Upload failed: ${e}`);
|
|
66
|
+
}
|
|
67
|
+
process.exit(0);
|
|
68
|
+
}
|
|
69
|
+
async function postUserMessage(config, prompt, instanceId, sessionName) {
|
|
70
|
+
const honcho = new import_sdk.Honcho(getHonchoClientOptions(config));
|
|
71
|
+
const noEnsure = () => Promise.resolve();
|
|
72
|
+
const userPeer = new import_sdk.Peer(config.peerName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);
|
|
73
|
+
const createdAt = new Date().toISOString();
|
|
74
|
+
const configuration = isTerseReply(prompt) ? { reasoning: { enabled: false } } : undefined;
|
|
75
|
+
const messages = chunkContent(prompt).map((chunk) => userPeer.message(chunk, {
|
|
76
|
+
createdAt,
|
|
77
|
+
metadata: {
|
|
78
|
+
instance_id: instanceId || undefined,
|
|
79
|
+
session_affinity: sessionName
|
|
80
|
+
},
|
|
81
|
+
...configuration ? { configuration } : {}
|
|
82
|
+
}));
|
|
83
|
+
logApiCall("session.addMessages", "POST", `user prompt (${prompt.length} chars, ${messages.length} msg, direct)`);
|
|
84
|
+
const session = new import_sdk.Session(sessionName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);
|
|
85
|
+
await addMessagesBatched(session, messages, (e) => {
|
|
86
|
+
logHook("save-user-message", `Direct upload failed, retrying via get-or-create: ${e}`);
|
|
87
|
+
return honcho.session(sessionName);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// hooks/save-user-message.ts
|
|
92
|
+
await initHook();
|
|
93
|
+
await handleSaveUserMessage();
|
|
94
|
+
|
|
95
|
+
//# debugId=AB3B67AF50C5235164756E2164756E21
|
|
96
|
+
//# sourceMappingURL=save-user-message.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hooks/save-user-message.ts", "../../hooks/save-user-message.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { Honcho, Session, Peer } from \"@honcho-ai/sdk\";\nimport { loadConfig, getSessionName, getHonchoClientOptions, isPluginEnabled, getCachedStdin, readStdinText } from \"../config.js\";\nimport { getInstanceIdForCwd, chunkContent, addMessagesBatched } from \"../cache.js\";\nimport { logHook, logApiCall, setLogContext } from \"../log.js\";\nimport { isHarnessInjected, isTerseReply } from \"./user-prompt.js\";\n\ninterface HookInput {\n prompt?: string;\n cwd?: string;\n session_id?: string;\n workspace_roots?: string[];\n}\n\n/**\n * Async UserPromptSubmit companion to user-prompt.ts: persists the user's\n * prompt to Honcho off the turn's critical path.\n *\n * This runs as a separate `async: true` hook so the write never blocks the\n * model's response. It's the write half of UserPromptSubmit; user-prompt.ts is\n * the read half (context/dialectic injection), which stays synchronous because\n * its additionalContext must reach the model before it answers this turn.\n *\n * Being async, it runs detached — it awaits the upload to completion here\n * rather than racing process exit, so a slow POST still lands.\n */\nexport async function handleSaveUserMessage(): Promise<void> {\n const config = loadConfig();\n if (!config) {\n process.exit(0);\n }\n\n if (!isPluginEnabled() || config.saveMessages === false) {\n process.exit(0);\n }\n\n let hookInput: HookInput = {};\n try {\n const input = getCachedStdin() ?? await readStdinText();\n if (input.trim()) {\n hookInput = JSON.parse(input);\n }\n } catch {\n process.exit(0);\n }\n\n const prompt = hookInput.prompt || \"\";\n if (!prompt.trim()) {\n process.exit(0);\n }\n\n const cwd = hookInput.workspace_roots?.[0] || hookInput.cwd || process.cwd();\n const instanceId = hookInput.session_id || getInstanceIdForCwd(cwd);\n const sessionName = getSessionName(cwd, instanceId || undefined);\n\n setLogContext(cwd, sessionName);\n\n if (isHarnessInjected(prompt)) {\n logHook(\"save-user-message\", \"Skipping upload (harness-injected content, not user input)\");\n process.exit(0);\n }\n\n try {\n await postUserMessage(config, prompt, instanceId || undefined, sessionName);\n } catch (e) {\n logHook(\"save-user-message\", `Upload failed: ${e}`);\n }\n\n process.exit(0);\n}\n\n// Upload a user prompt. SessionStart already created the session/peers, so we\n// use local handles with a noEnsure stub to skip the get-or-create round-trip,\n// falling back to a real lookup only if the direct POST fails.\nasync function postUserMessage(\n config: any,\n prompt: string,\n instanceId: string | undefined,\n sessionName: string,\n): Promise<void> {\n const honcho = new Honcho(getHonchoClientOptions(config));\n const noEnsure = () => Promise.resolve();\n\n const userPeer = new Peer(config.peerName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);\n const createdAt = new Date().toISOString();\n const configuration = isTerseReply(prompt) ? { reasoning: { enabled: false } } : undefined;\n const messages = chunkContent(prompt).map((chunk) =>\n userPeer.message(chunk, {\n createdAt,\n metadata: {\n instance_id: instanceId || undefined,\n session_affinity: sessionName,\n },\n ...(configuration ? { configuration } : {}),\n })\n );\n\n logApiCall(\"session.addMessages\", \"POST\", `user prompt (${prompt.length} chars, ${messages.length} msg, direct)`);\n const session = new Session(sessionName, honcho.workspaceId, honcho.http, undefined, undefined, noEnsure);\n await addMessagesBatched(session, messages, (e) => {\n logHook(\"save-user-message\", `Direct upload failed, retrying via get-or-create: ${e}`);\n return honcho.session(sessionName);\n });\n}\n",
|
|
6
|
+
"#!/usr/bin/env bun\nimport { initHook } from \"../src/config.js\";\nimport { handleSaveUserMessage } from \"../src/hooks/save-user-message.js\";\n\nawait initHook();\nawait handleSaveUserMessage();\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAyBA,eAAsB,qBAAqB,GAAkB;AAAA,EAC3D,MAAM,SAAS,WAAW;AAAA,EAC1B,IAAI,CAAC,QAAQ;AAAA,IACX,QAAQ,KAAK,CAAC;AAAA,EAChB;AAA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IAAI,KAAK,EAAE,YAAY;AAAA,EACzC,MAAM,gBAAgB,aAAa,MAAM,IAAI,EAAE,WAAW,EAAE,SAAS,MAAM,EAAE,IAAI;AAAA,EACjF,MAAM,WAAW,aAAa,MAAM,EAAE,IAAI,CAAC,UACzC,SAAS,QAAQ,OAAO;AAAA,IACtB;AAAA,IACA,UAAU;AAAA,MACR,aAAa,cAAc;AAAA,MAC3B,kBAAkB;AAAA,IACpB;AAAA,OACI,gBAAgB,EAAE,cAAc,IAAI,CAAC;AAAA,EAC3C,CAAC,CACH;AAAA,EAEA,WAAW,uBAAuB,QAAQ,gBAAgB,OAAO,iBAAiB,SAAS,qBAAqB;AAAA,EAChH,MAAM,UAAU,IAAI,mBAAQ,aAAa,OAAO,aAAa,OAAO,MAAM,WAAW,WAAW,QAAQ;AAAA,EACxG,MAAM,mBAAmB,SAAS,UAAU,CAAC,MAAM;AAAA,IACjD,QAAQ,qBAAqB,qDAAqD,GAAG;AAAA,IACrF,OAAO,OAAO,QAAQ,WAAW;AAAA,GAClC;AAAA;;;ACjGH,MAAM,SAAS;AACf,MAAM,sBAAsB;",
|
|
9
|
+
"debugId": "AB3B67AF50C5235164756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import {
|
|
3
|
+
clearSessionFiles
|
|
4
|
+
} from "../chunk-9pntsn3x.js";
|
|
5
|
+
import {
|
|
6
|
+
logHook,
|
|
7
|
+
setLogContext
|
|
8
|
+
} from "../chunk-jr0fd6n2.js";
|
|
9
|
+
import {
|
|
10
|
+
getCachedStdin,
|
|
11
|
+
getInstanceIdForCwd,
|
|
12
|
+
getSessionName,
|
|
13
|
+
initHook,
|
|
14
|
+
isPluginEnabled,
|
|
15
|
+
loadConfig,
|
|
16
|
+
readStdinText
|
|
17
|
+
} from "../chunk-yfrrc1d5.js";
|
|
18
|
+
|
|
19
|
+
// src/hooks/session-end.ts
|
|
20
|
+
async function handleSessionEnd() {
|
|
21
|
+
const config = loadConfig();
|
|
22
|
+
if (!config) {
|
|
23
|
+
process.exit(0);
|
|
24
|
+
}
|
|
25
|
+
if (!isPluginEnabled()) {
|
|
26
|
+
process.exit(0);
|
|
27
|
+
}
|
|
28
|
+
let hookInput = {};
|
|
29
|
+
try {
|
|
30
|
+
const input = getCachedStdin() ?? await readStdinText();
|
|
31
|
+
if (input.trim()) {
|
|
32
|
+
hookInput = JSON.parse(input);
|
|
33
|
+
}
|
|
34
|
+
} catch {}
|
|
35
|
+
const cwd = hookInput.workspace_roots?.[0] || hookInput.cwd || process.cwd();
|
|
36
|
+
const reason = hookInput.reason || "unknown";
|
|
37
|
+
const instanceId = hookInput.session_id || getInstanceIdForCwd(cwd);
|
|
38
|
+
const sessionName = getSessionName(cwd, instanceId || undefined);
|
|
39
|
+
setLogContext(cwd, sessionName);
|
|
40
|
+
logHook("session-end", `Session ending`, { reason });
|
|
41
|
+
clearSessionFiles(hookInput.session_id);
|
|
42
|
+
logHook("session-end", "Session ended — no upload (messages saved live)");
|
|
43
|
+
process.exit(0);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// hooks/session-end.ts
|
|
47
|
+
await initHook();
|
|
48
|
+
await handleSessionEnd();
|
|
49
|
+
|
|
50
|
+
//# debugId=E1DAA73E44B8E07D64756E2164756E21
|
|
51
|
+
//# sourceMappingURL=session-end.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hooks/session-end.ts", "../../hooks/session-end.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { loadConfig, getSessionName, isPluginEnabled, getCachedStdin, readStdinText } from \"../config.js\";\nimport { getInstanceIdForCwd } from \"../cache.js\";\nimport { clearSessionFiles } from \"../state.js\";\nimport { logHook, setLogContext } from \"../log.js\";\n\n\ninterface HookInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n reason?: string;\n workspace_roots?: string[];\n}\n\n/**\n * SessionEnd hook — must return instantly. On /exit the harness aborts slow\n * hooks and surfaces \"SessionEnd hook failed: Hook cancelled\", so nothing here\n * touches the network. Messages upload live from the other hooks, and the old\n * [Session ended] marker only ever derived lifecycle exhaust (\"claude's\n * session ended at ...\") — write-only telemetry, never read back.\n */\nexport async function handleSessionEnd(): Promise<void> {\n const config = loadConfig();\n if (!config) {\n process.exit(0);\n }\n\n if (!isPluginEnabled()) {\n process.exit(0);\n }\n\n let hookInput: HookInput = {};\n try {\n const input = getCachedStdin() ?? await readStdinText();\n if (input.trim()) {\n hookInput = JSON.parse(input);\n }\n } catch {\n // Continue with defaults\n }\n\n const cwd = hookInput.workspace_roots?.[0] || hookInput.cwd || process.cwd();\n const reason = hookInput.reason || \"unknown\";\n const instanceId = hookInput.session_id || getInstanceIdForCwd(cwd);\n const sessionName = getSessionName(cwd, instanceId || undefined);\n\n setLogContext(cwd, sessionName);\n logHook(\"session-end\", `Session ending`, { reason });\n\n clearSessionFiles(hookInput.session_id);\n logHook(\"session-end\", \"Session ended — no upload (messages saved live)\");\n process.exit(0);\n}\n",
|
|
6
|
+
"#!/usr/bin/env bun\nimport { initHook } from \"../src/config.js\";\nimport { handleSessionEnd } from \"../src/hooks/session-end.js\";\n\nawait initHook();\nawait handleSessionEnd();\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAqBA,eAAsB,gBAAgB,GAAkB;AAAA,EACtD,MAAM,SAAS,WAAW;AAAA,EAC1B,IAAI,CAAC,QAAQ;AAAA,IACX,QAAQ,KAAK,CAAC;AAAA,EAChB;AAAA,EAEA,IAAI,CAAC,gBAAgB,GAAG;AAAA,IACtB,QAAQ,KAAK,CAAC;AAAA,EAChB;AAAA,EAEA,IAAI,YAAuB,CAAC;AAAA,EAC5B,IAAI;AAAA,IACF,MAAM,QAAQ,eAAe,KAAK,MAAM,cAAc;AAAA,IACtD,IAAI,MAAM,KAAK,GAAG;AAAA,MAChB,YAAY,KAAK,MAAM,KAAK;AAAA,IAC9B;AAAA,IACA,MAAM;AAAA,EAIR,MAAM,MAAM,UAAU,kBAAkB,MAAM,UAAU,OAAO,QAAQ,IAAI;AAAA,EAC3E,MAAM,SAAS,UAAU,UAAU;AAAA,EACnC,MAAM,aAAa,UAAU,cAAc,oBAAoB,GAAG;AAAA,EAClE,MAAM,cAAc,eAAe,KAAK,cAAc,SAAS;AAAA,EAE/D,cAAc,KAAK,WAAW;AAAA,EAC9B,QAAQ,eAAe,kBAAkB,EAAE,OAAO,CAAC;AAAA,EAEnD,kBAAkB,UAAU,UAAU;AAAA,EACtC,QAAQ,eAAe,iDAAgD;AAAA,EACvE,QAAQ,KAAK,CAAC;AAAA;;;AC/ChB,MAAM,SAAS;AACf,MAAM,iBAAiB;",
|
|
9
|
+
"debugId": "E1DAA73E44B8E07D64756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|