ftown-bridge 0.30.9 → 0.30.11

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.
@@ -7,7 +7,25 @@ import type { HookAdapter, HookKind } from './hook-contract.js';
7
7
  */
8
8
  export declare const museSessionStartAdapter: HookAdapter;
9
9
  /**
10
- * Adapter registry. The four later porting tasks add one entry each and extend
11
- * IMPLEMENTED_HOOK_KINDS in the contract; they do not change the runner.
10
+ * Muse UserPromptSubmit — the SessionStart envelope plus `prompt`, present only
11
+ * when the native field is a string. No mail drain, no stdout.
12
+ */
13
+ export declare const museUserPromptSubmitAdapter: HookAdapter;
14
+ export declare const musePreToolUseAdapter: HookAdapter;
15
+ export declare const musePostToolUseAdapter: HookAdapter;
16
+ /** Muse Stop — posts the typed envelope, then drains mail into stdout. */
17
+ export declare const museStopAdapter: HookAdapter;
18
+ /**
19
+ * notify.sh — Claude/Codex/Cursor passthrough (and Grok's notification event).
20
+ * Stdin is forwarded unchanged with typed identity fields appended; absent,
21
+ * invalid or non-object stdin produces a `{hook_event_name}` fallback body. It
22
+ * stands down for a Grok non-notification event carrying `hookEventName`, is
23
+ * inert when no session owns the process, never drains mail and never writes
24
+ * stdout. Deliberately involves no jq or curl.
25
+ */
26
+ export declare const notifyAdapter: HookAdapter;
27
+ /**
28
+ * Adapter registry. All five Muse native events and notify are ported; the
29
+ * remaining grok/antigravity kinds still fail visibly in the runner.
12
30
  */
13
31
  export declare const HOOK_ADAPTERS: Readonly<Partial<Record<HookKind, HookAdapter>>>;
@@ -1,3 +1,27 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ /** Native hook stdin is always one JSON object; invalid input is a visible, non-blocking error. */
5
+ function parseMuseNative(input) {
6
+ let parsed;
7
+ try {
8
+ parsed = JSON.parse(input);
9
+ }
10
+ catch {
11
+ return { ok: false, error: { kind: 'invalid-json', message: 'native hook payload is not valid JSON' } };
12
+ }
13
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
14
+ return { ok: false, error: { kind: 'invalid-input', message: 'native hook payload must be a JSON object' } };
15
+ }
16
+ return { ok: true, native: parsed };
17
+ }
18
+ /** Missing/non-string native fields become empty strings, matching the old jq `// empty` lookup. */
19
+ function nativeString(value) {
20
+ return typeof value === 'string' ? value : '';
21
+ }
22
+ function fromPostResult(result) {
23
+ return result.ok ? { status: 'ok' } : { status: 'error', error: { kind: result.error.kind, message: result.error.message } };
24
+ }
1
25
  /**
2
26
  * Muse SessionStart — the end-to-end proof for the shared entry point.
3
27
  * Mirrors bridge/muse-plugin/lib/ftown-hook.sh: stdin is one JSON object whose
@@ -7,34 +31,257 @@
7
31
  export const museSessionStartAdapter = async ({ input, env, post }) => {
8
32
  if (!env.FTOWN_SESSION_ID)
9
33
  return { status: 'ok' };
10
- let parsed;
34
+ const parsed = parseMuseNative(input);
35
+ if (!parsed.ok)
36
+ return { status: 'error', error: parsed.error };
37
+ const payload = {
38
+ ftown_session_id: env.FTOWN_SESSION_ID,
39
+ ftown_session_source: 'env',
40
+ hook_event_name: 'SessionStart',
41
+ session_id: nativeString(parsed.native.session_id),
42
+ cwd: nativeString(parsed.native.cwd),
43
+ };
44
+ return fromPostResult(await post(payload));
45
+ };
46
+ /**
47
+ * Muse UserPromptSubmit — the SessionStart envelope plus `prompt`, present only
48
+ * when the native field is a string. No mail drain, no stdout.
49
+ */
50
+ export const museUserPromptSubmitAdapter = async ({ input, env, post }) => {
51
+ if (!env.FTOWN_SESSION_ID)
52
+ return { status: 'ok' };
53
+ const parsed = parseMuseNative(input);
54
+ if (!parsed.ok)
55
+ return { status: 'error', error: parsed.error };
56
+ const payload = {
57
+ ftown_session_id: env.FTOWN_SESSION_ID,
58
+ ftown_session_source: 'env',
59
+ hook_event_name: 'UserPromptSubmit',
60
+ session_id: nativeString(parsed.native.session_id),
61
+ cwd: nativeString(parsed.native.cwd),
62
+ ...(typeof parsed.native.prompt === 'string' ? { prompt: parsed.native.prompt } : {}),
63
+ };
64
+ return fromPostResult(await post(payload));
65
+ };
66
+ /**
67
+ * Muse tool events use an allowlist: identity, event name and string tool name /
68
+ * call id only. Arguments, results, cwd and the native session id never go on
69
+ * the wire. `muse-post-tool-use-failure` registers as muse-post-tool-use, so the
70
+ * same adapter covers success and failure.
71
+ */
72
+ function museToolAdapter(hook_event_name) {
73
+ return async ({ input, env, post }) => {
74
+ if (!env.FTOWN_SESSION_ID)
75
+ return { status: 'ok' };
76
+ const parsed = parseMuseNative(input);
77
+ if (!parsed.ok)
78
+ return { status: 'error', error: parsed.error };
79
+ const payload = {
80
+ ftown_session_id: env.FTOWN_SESSION_ID,
81
+ hook_event_name,
82
+ ...(typeof parsed.native.tool_name === 'string' ? { tool_name: parsed.native.tool_name } : {}),
83
+ ...(typeof parsed.native.tool_use_id === 'string' ? { tool_use_id: parsed.native.tool_use_id } : {}),
84
+ };
85
+ return fromPostResult(await post(payload));
86
+ };
87
+ }
88
+ export const musePreToolUseAdapter = museToolAdapter('PreToolUse');
89
+ export const musePostToolUseAdapter = museToolAdapter('PostToolUse');
90
+ /** One encrypted local API request through the same CLI the old shell helper used. */
91
+ function runSecureProxy(cli, request, env) {
92
+ return new Promise((resolve, reject) => {
93
+ const child = spawn(cli, ['security', 'proxy'], {
94
+ stdio: ['pipe', 'pipe', 'pipe'],
95
+ env: { ...process.env, ...env },
96
+ });
97
+ let stdout = '';
98
+ let settled = false;
99
+ const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
100
+ const finish = (result) => {
101
+ if (settled)
102
+ return;
103
+ settled = true;
104
+ clearTimeout(timer);
105
+ resolve(result);
106
+ };
107
+ child.stdout.setEncoding('utf8');
108
+ child.stdout.on('data', (chunk) => { if (stdout.length < 1_048_576)
109
+ stdout += chunk; });
110
+ child.stdin.on('error', () => { });
111
+ child.on('error', (error) => { clearTimeout(timer); reject(error); });
112
+ child.on('close', (code) => finish({ stdout, exitCode: code ?? 1 }));
113
+ child.stdin.end(request);
114
+ });
115
+ }
116
+ /** The installed `ftown` CLI is the secure bridge client; HOME keeps tests isolated. */
117
+ function resolveSecureCli(env) {
118
+ const homeCli = env.HOME ? join(env.HOME, '.ftown', 'bin', 'ftown') : undefined;
119
+ if (homeCli && existsSync(homeCli))
120
+ return homeCli;
121
+ return 'ftown';
122
+ }
123
+ /**
124
+ * Stop posts the hook first, then drains the inbox once (wait=0, marks
125
+ * delivered). Pending mail is emitted as hookSpecificOutput.additionalContext;
126
+ * an empty inbox, a down bridge or a missing CLI leaves stdout untouched. Best
127
+ * effort: a mail failure never turns into a hook error.
128
+ */
129
+ async function drainMuseMail(env, sessionId) {
130
+ const cli = resolveSecureCli(env);
131
+ if (!cli)
132
+ return undefined;
133
+ const request = JSON.stringify({
134
+ method: 'GET',
135
+ path: `/api/sessions/${encodeURIComponent(sessionId)}/inbox?wait=0`,
136
+ timeoutMs: 2000,
137
+ });
11
138
  try {
12
- parsed = JSON.parse(input);
139
+ const { stdout, exitCode } = await runSecureProxy(cli, request, env);
140
+ if (exitCode !== 0)
141
+ return undefined;
142
+ const parsed = JSON.parse(stdout);
143
+ if (!parsed || typeof parsed.status !== 'number' || parsed.status < 200 || parsed.status >= 300)
144
+ return undefined;
145
+ const messages = parsed.body?.messages;
146
+ if (!Array.isArray(messages) || messages.length === 0)
147
+ return undefined;
148
+ const formatted = messages.map((raw) => {
149
+ const message = (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {});
150
+ const from = (typeof message.fromName === 'string' && message.fromName)
151
+ || (typeof message.from === 'string' && message.from) || 'external';
152
+ const type = typeof message.type === 'string' ? message.type : 'message';
153
+ const body = typeof message.body === 'string' ? message.body : '';
154
+ return `[${nativeString(message.ts)}] ${from} (${type}): ${body}`;
155
+ }).join('\n');
156
+ return JSON.stringify({
157
+ hookSpecificOutput: {
158
+ hookEventName: 'Stop',
159
+ additionalContext: `[ftown mail]\n${formatted}`,
160
+ },
161
+ });
13
162
  }
14
163
  catch {
15
- return { status: 'error', error: { kind: 'invalid-json', message: 'native hook payload is not valid JSON' } };
16
- }
17
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
18
- return { status: 'error', error: { kind: 'invalid-input', message: 'native hook payload must be a JSON object' } };
164
+ return undefined;
19
165
  }
20
- const native = parsed;
166
+ }
167
+ /** Muse Stop — posts the typed envelope, then drains mail into stdout. */
168
+ export const museStopAdapter = async ({ input, env, post }) => {
169
+ if (!env.FTOWN_SESSION_ID)
170
+ return { status: 'ok' };
171
+ const parsed = parseMuseNative(input);
172
+ if (!parsed.ok)
173
+ return { status: 'error', error: parsed.error };
21
174
  const payload = {
22
175
  ftown_session_id: env.FTOWN_SESSION_ID,
23
176
  ftown_session_source: 'env',
24
- hook_event_name: 'SessionStart',
25
- session_id: typeof native.session_id === 'string' ? native.session_id : '',
26
- cwd: typeof native.cwd === 'string' ? native.cwd : '',
177
+ hook_event_name: 'Stop',
178
+ session_id: nativeString(parsed.native.session_id),
179
+ cwd: nativeString(parsed.native.cwd),
27
180
  };
28
181
  const result = await post(payload);
182
+ const stdout = await drainMuseMail(env, env.FTOWN_SESSION_ID);
183
+ const adapterResult = fromPostResult(result);
184
+ return stdout === undefined ? adapterResult : { ...adapterResult, stdout };
185
+ };
186
+ /**
187
+ * Resolve a session from `~/.ftown/session-registry.json` when no env session
188
+ * owns the process: `conversation_id` first, then `workspace_roots[0]`. Both
189
+ * keys are read from the injected HOME so an isolated hook environment cannot
190
+ * be redirected to the bridge process's home. Malformed/missing registries are
191
+ * inert, matching the old jq-based lookup.
192
+ */
193
+ function resolveRegistrySession(native, home) {
194
+ if (!home)
195
+ return undefined;
196
+ let parsed;
197
+ try {
198
+ parsed = JSON.parse(readFileSync(join(home, '.ftown', 'session-registry.json'), 'utf8'));
199
+ }
200
+ catch {
201
+ return undefined;
202
+ }
203
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
204
+ return undefined;
205
+ const registry = parsed;
206
+ const conversationId = native.conversation_id;
207
+ if (typeof conversationId === 'string' && conversationId) {
208
+ const byConversation = registry.byConversation;
209
+ if (byConversation && typeof byConversation === 'object' && !Array.isArray(byConversation)) {
210
+ const id = byConversation[conversationId];
211
+ if (typeof id === 'string' && id)
212
+ return { sessionId: id, source: 'conversation' };
213
+ }
214
+ }
215
+ const roots = native.workspace_roots;
216
+ const firstRoot = Array.isArray(roots) ? roots[0] : undefined;
217
+ if (typeof firstRoot === 'string' && firstRoot) {
218
+ const byWorkspace = registry.byWorkspace;
219
+ if (byWorkspace && typeof byWorkspace === 'object' && !Array.isArray(byWorkspace)) {
220
+ const id = byWorkspace[firstRoot];
221
+ if (typeof id === 'string' && id)
222
+ return { sessionId: id, source: 'workspace' };
223
+ }
224
+ }
225
+ return undefined;
226
+ }
227
+ /**
228
+ * notify.sh — Claude/Codex/Cursor passthrough (and Grok's notification event).
229
+ * Stdin is forwarded unchanged with typed identity fields appended; absent,
230
+ * invalid or non-object stdin produces a `{hook_event_name}` fallback body. It
231
+ * stands down for a Grok non-notification event carrying `hookEventName`, is
232
+ * inert when no session owns the process, never drains mail and never writes
233
+ * stdout. Deliberately involves no jq or curl.
234
+ */
235
+ export const notifyAdapter = async ({ input, env, post }) => {
236
+ let native;
237
+ try {
238
+ const parsed = JSON.parse(input);
239
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
240
+ native = parsed;
241
+ }
242
+ catch {
243
+ // Invalid JSON is not an error here: notify.sh forwards a fallback body.
244
+ }
245
+ // Grok runs Claude-compatible hooks too; its own hook handles its events.
246
+ // An inherited GROK_HOOK_EVENT must not silence Claude/Codex/Cursor, which
247
+ // do not send the camelCase hookEventName field.
248
+ if (env.GROK_HOOK_EVENT && env.GROK_HOOK_EVENT !== 'notification'
249
+ && native && typeof native.hookEventName === 'string' && native.hookEventName.length > 0) {
250
+ return { status: 'ok' };
251
+ }
252
+ let sessionId = env.FTOWN_SESSION_ID;
253
+ let source = sessionId ? 'env' : undefined;
254
+ if (!sessionId && native) {
255
+ const resolved = resolveRegistrySession(native, env.HOME);
256
+ if (resolved) {
257
+ sessionId = resolved.sessionId;
258
+ source = resolved.source;
259
+ }
260
+ }
261
+ if (!sessionId || !source)
262
+ return { status: 'ok' };
263
+ const payload = native
264
+ ? { ...native, ftown_session_id: sessionId, ftown_session_source: source }
265
+ : {
266
+ ftown_session_id: sessionId,
267
+ ftown_session_source: source,
268
+ hook_event_name: env.HOOK_EVENT_NAME || 'hook',
269
+ };
270
+ const result = await post(payload);
29
271
  if (result.ok)
30
272
  return { status: 'ok' };
31
273
  return { status: 'error', error: { kind: result.error.kind, message: result.error.message } };
32
274
  };
33
275
  /**
34
- * Adapter registry. The four later porting tasks add one entry each and extend
35
- * IMPLEMENTED_HOOK_KINDS in the contract; they do not change the runner.
276
+ * Adapter registry. All five Muse native events and notify are ported; the
277
+ * remaining grok/antigravity kinds still fail visibly in the runner.
36
278
  */
37
279
  export const HOOK_ADAPTERS = Object.freeze({
38
280
  'muse-session-start': museSessionStartAdapter,
281
+ 'muse-user-prompt-submit': museUserPromptSubmitAdapter,
282
+ 'muse-pre-tool-use': musePreToolUseAdapter,
283
+ 'muse-post-tool-use': musePostToolUseAdapter,
284
+ 'muse-stop': museStopAdapter,
285
+ notify: notifyAdapter,
39
286
  });
40
287
  //# sourceMappingURL=hook-adapters.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hook-adapters.js","sourceRoot":"","sources":["../src/hook-adapters.ts"],"names":[],"mappings":"AAOA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAgB,KAAK,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE;IACjF,IAAI,CAAC,GAAG,CAAC,gBAAgB;QAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IAEnD,IAAI,MAAe,CAAC;IACpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IAAC,MAAM,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AAoB,EAAE,uBAAuB;IAC7C,yBAAyB,EAAE,2BAA2B;IACtD,mBAAmB,EAAE,qBAAqB;IAC1C,oBAAoB,EAAE,sBAAsB;IAC5C,WAAW,EAAE,eAAe;IAC5B,MAAM,EAAE,aAAa;CACtB,CAAC,CAAC"}
package/hooks/notify.sh CHANGED
@@ -1,80 +1,33 @@
1
- #!/bin/bash
2
- INPUT=$(cat)
3
- # Grok runs Claude-compatible hooks too; ~/.ftown/grok-hook.sh is its channel. Stand down only
4
- # when GROK_HOOK_EVENT is set and is not "notification" (the Grok script does not forward that
5
- # event) AND the payload has a string hookEventName (Grok always sends it; Claude, Codex and
6
- # Cursor do not, so an inherited variable does not silence them).
7
- if [ -n "${GROK_HOOK_EVENT:-}" ] && [ "${GROK_HOOK_EVENT}" != "notification" ] \
8
- && printf '%s' "$INPUT" | jq -e '(.hookEventName | type) == "string" and (.hookEventName | length) > 0' >/dev/null 2>&1; then
9
- exit 0
10
- fi
11
-
12
- PORT="${FTOWN_HOOK_PORT:-}"
13
- SESSION_ID="${FTOWN_SESSION_ID:-}"
14
- TOKEN="${FTOWN_HOOK_TOKEN:-}"
15
- SOURCE=""
16
-
17
- BRIDGE_JSON="${FTOWN_BRIDGE_POINTER:-${HOME}/.ftown/bridge.json}"
18
- REGISTRY="${HOME}/.ftown/session-registry.json"
1
+ #!/usr/bin/env bash
2
+ # Compatibility shim for the installed notify hook. The real hook is the typed
3
+ # Node entry point `ftown-harness hook notify`; this file only locates it and
4
+ # execs it. No jq, curl, session lookup or network logic lives here.
5
+ set -u
6
+
7
+ # A stale install must never block its agent: report the drop on stderr and
8
+ # exit 0. Stderr is visible in the harness hook log; the event is simply lost.
9
+ stale() {
10
+ printf '%s\n' "ftown notify hook: $1 (notify event not delivered)" >&2
11
+ }
19
12
 
20
- if [ -z "$PORT" ] && [ -f "$BRIDGE_JSON" ]; then
21
- PORT=$(jq -r '.port // empty' "$BRIDGE_JSON" 2>/dev/null)
22
- if [ -z "$TOKEN" ]; then
23
- TOKEN=$(jq -r '.token // empty' "$BRIDGE_JSON" 2>/dev/null)
24
- fi
13
+ harness="${FTOWN_HARNESS:-}"
14
+ if [ -z "$harness" ] && [ -n "${HOME:-}" ] && [ -x "${HOME}/.ftown/bin/ftown-harness" ]; then
15
+ harness="${HOME}/.ftown/bin/ftown-harness"
25
16
  fi
26
-
27
- if [ -n "$SESSION_ID" ]; then
28
- SOURCE="env"
29
- elif [ -n "$INPUT" ]; then
30
- CONV=$(echo "$INPUT" | jq -r '.conversation_id // empty' 2>/dev/null)
31
- WS=$(echo "$INPUT" | jq -r '.workspace_roots[0] // empty' 2>/dev/null)
32
- if [ -f "$REGISTRY" ]; then
33
- if [ -n "$CONV" ]; then
34
- SESSION_ID=$(jq -r --arg c "$CONV" '.byConversation[$c] // empty' "$REGISTRY" 2>/dev/null)
35
- if [ -n "$SESSION_ID" ]; then
36
- SOURCE="conversation"
37
- fi
38
- fi
39
- if [ -z "$SESSION_ID" ] && [ -n "$WS" ]; then
40
- SESSION_ID=$(jq -r --arg w "$WS" '.byWorkspace[$w] // empty' "$REGISTRY" 2>/dev/null)
41
- if [ -n "$SESSION_ID" ]; then
42
- SOURCE="workspace"
43
- fi
44
- fi
45
- fi
17
+ if [ -z "$harness" ]; then
18
+ harness="$(command -v ftown-harness 2>/dev/null || true)"
46
19
  fi
47
20
 
48
- if [ -z "$PORT" ] || [ -z "$SESSION_ID" ]; then
21
+ if [ -z "$harness" ] || [ ! -x "$harness" ]; then
22
+ stale "ftown-harness is missing"
49
23
  exit 0
50
24
  fi
51
-
52
- PAYLOAD=$(echo "$INPUT" | jq -c --arg sid "$SESSION_ID" --arg src "$SOURCE" \
53
- '. + {ftown_session_id: $sid, ftown_session_source: $src}' 2>/dev/null)
54
- if [ -z "$PAYLOAD" ]; then
55
- PAYLOAD=$(jq -nc --arg sid "$SESSION_ID" --arg src "$SOURCE" --arg ev "${HOOK_EVENT_NAME:-hook}" \
56
- '{ftown_session_id: $sid, ftown_session_source: $src, hook_event_name: $ev}')
25
+ # Older ftown-harness builds have no 'hook' command; their CLI would print an
26
+ # "unknown command" error and exit non-zero. Probe first so an old install
27
+ # still exits 0 and leaves a clear, visible reason in the hook log.
28
+ if ! "$harness" hook --help >/dev/null 2>&1; then
29
+ stale "installed ftown-harness has no 'hook' command; upgrade ftown"
30
+ exit 0
57
31
  fi
58
32
 
59
- post_hook() {
60
- local port="$1" token="$2"
61
- local auth=()
62
- if [ -n "$token" ]; then
63
- auth=(-H "Authorization: Bearer ${token}")
64
- fi
65
- curl -sf -X POST "http://localhost:${port}/hook" \
66
- -H "Content-Type: application/json" \
67
- "${auth[@]}" \
68
- -d "$PAYLOAD" > /dev/null 2>&1
69
- }
70
-
71
- if ! post_hook "$PORT" "$TOKEN" && [ -f "$BRIDGE_JSON" ]; then
72
- # Env vars are stale inside tmux sessions that outlive their bridge; the
73
- # current bridge rewrites bridge.json with the live port/token on startup.
74
- BPORT=$(jq -r '.port // empty' "$BRIDGE_JSON" 2>/dev/null)
75
- BTOKEN=$(jq -r '.token // empty' "$BRIDGE_JSON" 2>/dev/null)
76
- if [ -n "$BPORT" ] && { [ "$BPORT" != "$PORT" ] || [ "$BTOKEN" != "$TOKEN" ]; }; then
77
- post_hook "$BPORT" "$BTOKEN"
78
- fi
79
- fi
80
- exit 0
33
+ exec "$harness" hook notify "$@"
@@ -1,142 +1,52 @@
1
1
  #!/bin/sh
2
2
  # ftown shared Muse hook helper (POSIX sh — invoked by the per-event hook
3
- # wrappers with argv, never symlinked).
3
+ # wrappers with argv, never symlinked). It is a compatibility shim only: the
4
+ # real hook is the typed Node entry point `ftown-harness hook <kind>`. No jq,
5
+ # curl, session lookup, POST or mail logic lives here.
6
+ #
4
7
  # Usage: ftown-hook.sh session-start|user-prompt-submit|pre-tool-use|post-tool-use|stop
5
8
  # (hook JSON payload on stdin)
6
- #
7
- # SessionStart: POST the native session_id + cwd + ftown ids to bridge /hook
8
- # (same route/shape as the pi/opencode hook posts). SessionStart is not an
9
- # activity event. UserPromptSubmit / PreToolUse / PostToolUse are posted under
10
- # those names so the board can classify thinking / tool_use / thinking.
11
- # PreToolUse and PostToolUse send only ftown_session_id, hook_event_name,
12
- # tool_name, and tool_use_id. Tool arguments and results stay off the wire.
13
- # PostToolUseFailure uses the same PostToolUse post: the failed call is over
14
- # and the turn continues. Stop: POST the hook, then drain the inbox; pending
15
- # mail is emitted as hookSpecificOutput.additionalContext JSON (never a
16
- # decision object). Mail delivery stays on Stop only.
17
- #
18
- # Always exits 0 and stays silent unless there is mail to deliver: hooks must
19
- # be fast fire-and-forget (5s budget) and never break the agent session.
20
9
 
21
- EVENT="${1:-}"
22
- case "$EVENT" in
23
- session-start) HOOK_EVENT="SessionStart" ;;
24
- user-prompt-submit) HOOK_EVENT="UserPromptSubmit" ;;
25
- pre-tool-use) HOOK_EVENT="PreToolUse" ;;
10
+ set -u
11
+
12
+ case "${1:-}" in
13
+ session-start) EVENT='SessionStart'; KIND='muse-session-start' ;;
14
+ user-prompt-submit) EVENT='UserPromptSubmit'; KIND='muse-user-prompt-submit' ;;
15
+ pre-tool-use) EVENT='PreToolUse'; KIND='muse-pre-tool-use' ;;
26
16
  # Success and failure both mean the tool call is finished and the turn goes
27
- # on. PostToolUse classifies as thinking; postToolUseFailure would go idle.
28
- post-tool-use) HOOK_EVENT="PostToolUse" ;;
29
- stop) HOOK_EVENT="Stop" ;;
17
+ # on; PostToolUse classifies as thinking, postToolUseFailure would go idle.
18
+ post-tool-use) EVENT='PostToolUse'; KIND='muse-post-tool-use' ;;
19
+ stop) EVENT='Stop'; KIND='muse-stop' ;;
30
20
  *) exit 0 ;;
31
21
  esac
32
22
 
33
23
  # Inert unless spawned by ftown.
34
24
  [ -n "${FTOWN_SESSION_ID:-}" ] || exit 0
35
- command -v curl >/dev/null 2>&1 || exit 0
36
- command -v jq >/dev/null 2>&1 || exit 0
37
25
 
38
- INPUT=$(cat)
39
- NATIVE_SID=$(printf '%s' "$INPUT" | jq -r '.session_id // empty' 2>/dev/null)
40
- NATIVE_CWD=$(printf '%s' "$INPUT" | jq -r '.cwd // empty' 2>/dev/null)
41
-
42
- # Endpoint candidates, mirroring the pi/opencode precedent: explicit env first,
43
- # then the bridge pointer the current bridge rewrites on every startup (a
44
- # resurrected session may hold a stale env port).
45
- CANDIDATES=""
46
- add_candidate() {
47
- case "$1" in ''|*[!0-9]*) return 0 ;; esac
48
- [ "$1" -gt 0 ] 2>/dev/null || return 0
49
- CANDIDATES="${CANDIDATES}$1 $2
50
- "
26
+ # A stale install must never block its agent: report the drop on stderr and
27
+ # exit 0. Stderr is visible in the harness hook log; the event is simply lost.
28
+ stale() {
29
+ printf '%s\n' "ftown muse hook: $1 ($EVENT event not delivered)" >&2
51
30
  }
52
- ENV_PORT="${FTOWN_HOOK_PORT:-}"
53
- ENV_TOKEN="${FTOWN_HOOK_TOKEN:-}"
54
- add_candidate "$ENV_PORT" "$ENV_TOKEN"
55
- BRIDGE_JSON="${FTOWN_BRIDGE_POINTER:-${HOME:-}/.ftown/bridge.json}"
56
- if [ -n "${HOME:-}" ] && [ -f "$BRIDGE_JSON" ]; then
57
- BPORT=$(jq -r '.port // empty' "$BRIDGE_JSON" 2>/dev/null)
58
- BTOKEN=$(jq -r '.token // empty' "$BRIDGE_JSON" 2>/dev/null)
59
- if [ -n "$BPORT" ] && { [ "$BPORT" != "$ENV_PORT" ] || [ "$BTOKEN" != "$ENV_TOKEN" ]; }; then
60
- add_candidate "$BPORT" "$BTOKEN"
61
- fi
62
- fi
63
- [ -n "$CANDIDATES" ] || exit 0
64
31
 
65
- # POST the hook payload; first 2xx wins. Fire-and-forget: failures are silent.
66
- post_hook() {
67
- _body="$1"
68
- while IFS=' ' read -r _port _token _rest; do
69
- [ -n "${_port:-}" ] || continue
70
- if [ -n "${_token:-}" ]; then
71
- _code=$(curl -s -o /dev/null -w '%{http_code}' -X POST "http://127.0.0.1:${_port}/hook" \
72
- -H 'Content-Type: application/json' -H "Authorization: Bearer ${_token}" \
73
- --connect-timeout 1 --max-time 2 -d "$_body" 2>/dev/null)
74
- else
75
- _code=$(curl -s -o /dev/null -w '%{http_code}' -X POST "http://127.0.0.1:${_port}/hook" \
76
- -H 'Content-Type: application/json' \
77
- --connect-timeout 1 --max-time 2 -d "$_body" 2>/dev/null)
78
- fi
79
- case "${_code:-}" in
80
- 2*) return 0 ;;
81
- esac
82
- done <<CANDIDATES_EOF
83
- $CANDIDATES
84
- CANDIDATES_EOF
85
- return 1
86
- }
32
+ harness="${FTOWN_HARNESS:-}"
33
+ if [ -z "$harness" ] && [ -n "${HOME:-}" ] && [ -x "${HOME}/.ftown/bin/ftown-harness" ]; then
34
+ harness="${HOME}/.ftown/bin/ftown-harness"
35
+ fi
36
+ if [ -z "$harness" ]; then
37
+ harness="$(command -v ftown-harness 2>/dev/null || true)"
38
+ fi
87
39
 
88
- # Tool posts are an allowlist: identity plus the tool name and call id.
89
- # Arguments, results, errors, cwd, and the native session id are not forwarded.
90
- if [ "$HOOK_EVENT" = "PreToolUse" ] || [ "$HOOK_EVENT" = "PostToolUse" ]; then
91
- PAYLOAD=$(printf '%s' "$INPUT" | jq -c \
92
- --arg sid "$FTOWN_SESSION_ID" \
93
- --arg ev "$HOOK_EVENT" \
94
- '{ftown_session_id: $sid, hook_event_name: $ev}
95
- + (if (.tool_name | type) == "string" then {tool_name: .tool_name} else {} end)
96
- + (if (.tool_use_id | type) == "string" then {tool_use_id: .tool_use_id} else {} end)' \
97
- 2>/dev/null) || PAYLOAD=$(jq -n -c --arg sid "$FTOWN_SESSION_ID" --arg ev "$HOOK_EVENT" \
98
- '{ftown_session_id: $sid, hook_event_name: $ev}')
99
- [ -n "$PAYLOAD" ] || exit 0
100
- post_hook "$PAYLOAD"
40
+ if [ -z "$harness" ] || [ ! -x "$harness" ]; then
41
+ stale 'ftown-harness is missing'
101
42
  exit 0
102
43
  fi
103
-
104
- # SessionStart, UserPromptSubmit, and Stop keep the original envelope.
105
- # Mail drain stays on Stop only.
106
- EXTRA=$(printf '%s' "$INPUT" | jq -c --arg ev "$HOOK_EVENT" '
107
- if $ev == "UserPromptSubmit" then
108
- if (.prompt | type) == "string" then {prompt: .prompt} else {} end
109
- else {} end
110
- ' 2>/dev/null) || true
111
- [ -n "${EXTRA:-}" ] || EXTRA='{}'
112
- PAYLOAD=$(jq -n -c \
113
- --arg sid "$FTOWN_SESSION_ID" \
114
- --arg ev "$HOOK_EVENT" \
115
- --arg nsid "${NATIVE_SID:-}" \
116
- --arg cwd "${NATIVE_CWD:-}" \
117
- --argjson extra "$EXTRA" \
118
- '{ftown_session_id: $sid, ftown_session_source: "env", hook_event_name: $ev, session_id: $nsid, cwd: $cwd} + $extra' \
119
- 2>/dev/null) || exit 0
120
- [ -n "$PAYLOAD" ] || exit 0
121
- post_hook "$PAYLOAD"
122
-
123
- # Stop also drains the inbox. Single wait=0 drain (marks delivered), then the
124
- # mail is printed as additionalContext — emission always succeeds, so no
125
- # peek/mark two-step like the interactive opencode flow.
126
- if [ "$HOOK_EVENT" = "Stop" ]; then
127
- SID_ENC=$(jq -n -r --arg s "$FTOWN_SESSION_ID" '$s | @uri' 2>/dev/null)
128
- [ -n "$SID_ENC" ] || exit 0
129
- FTOWN_SECURE_CLI=$(command -v ftown 2>/dev/null || true)
130
- [ -n "$FTOWN_SECURE_CLI" ] || FTOWN_SECURE_CLI="${HOME:-}/.ftown/bin/ftown"
131
- [ -x "$FTOWN_SECURE_CLI" ] || exit 0
132
- REQUEST=$(jq -n -c --arg path "/api/sessions/${SID_ENC}/inbox?wait=0" '{method:"GET",path:$path,timeoutMs:2000}') || exit 0
133
- INBOX=$(printf '%s' "$REQUEST" | "$FTOWN_SECURE_CLI" security proxy 2>/dev/null | jq -c 'select(.status >= 200 and .status < 300) | .body' 2>/dev/null)
134
- [ -n "$INBOX" ] || exit 0
135
- COUNT=$(printf '%s' "$INBOX" | jq -r '(.messages // []) | length' 2>/dev/null)
136
- if [ -n "$COUNT" ] && [ "$COUNT" -gt 0 ] 2>/dev/null; then
137
- printf '%s' "$INBOX" | jq -c \
138
- '{hookSpecificOutput: {hookEventName: "Stop", additionalContext: ("[ftown mail]\n" + ([(.messages // [])[] | "[\(.ts // "")] \(.fromName // .from // "external") (\(.type // "message")): \(.body // "")"] | join("\n")))}}' \
139
- 2>/dev/null || exit 0
140
- fi
44
+ # Older ftown-harness builds have no 'hook' command; their CLI would print an
45
+ # "unknown command" error and exit non-zero. Probe first so an old install
46
+ # still exits 0 and leaves a clear, visible reason in the hook log.
47
+ if ! "$harness" hook --help >/dev/null 2>&1; then
48
+ stale "installed ftown-harness has no 'hook' command; upgrade ftown"
49
+ exit 0
141
50
  fi
142
- exit 0
51
+
52
+ exec "$harness" hook "$KIND"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ftown-bridge",
3
- "version": "0.30.9",
3
+ "version": "0.30.11",
4
4
  "description": "CLI bridge for ftown — generic PTY-over-Centrifugo relay",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -73,5 +73,5 @@
73
73
  "overrides": {
74
74
  "qs": "6.16.1"
75
75
  },
76
- "gitHead": "bdd7bea519e49874334ae2efcc136723e4de5401"
76
+ "gitHead": "ef732e425b2577f9a65269f6257d559e1f8912e2"
77
77
  }