osborn 0.9.270 → 0.9.272

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.
@@ -2236,6 +2236,22 @@ class ClaudeLLMStream extends llm.LLMStream {
2236
2236
  ? getSessionWorkspace(this.#opts.workingDirectory, sessionId)
2237
2237
  : null;
2238
2238
  const allowedTools = this.#opts.allowedTools || [];
2239
+ // Ensure the project working directory exists before handing it to the SDK as cwd.
2240
+ // The dashboard "new project" flow passes {base}/{slug} (e.g. /workspace/kachi) as the
2241
+ // working directory but nothing in the client → /api/token → agent chain ever creates
2242
+ // the folder. A brand-new project therefore ran on a non-existent cwd: tools silently
2243
+ // operated on the wrong path and nothing landed in the project (the "Kachi" bug —
2244
+ // session saved, folder absent). Guarded + recursive; also recreates a folder that was
2245
+ // recycled between resumes. Skipped when workingDirectory is unset (SDK → process.cwd()).
2246
+ if (this.#opts.workingDirectory && !existsSync(this.#opts.workingDirectory)) {
2247
+ try {
2248
+ mkdirSync(this.#opts.workingDirectory, { recursive: true });
2249
+ console.log(`📁 Created project working directory: ${this.#opts.workingDirectory}`);
2250
+ }
2251
+ catch (err) {
2252
+ console.log(`⚠️ Failed to create working directory ${this.#opts.workingDirectory}:`, err);
2253
+ }
2254
+ }
2239
2255
  const sdkOptions = {
2240
2256
  cwd: this.#opts.workingDirectory,
2241
2257
  permissionMode: this.#opts.permissionMode,
package/dist/env-keys.js CHANGED
@@ -31,6 +31,16 @@ export const AGENT_ENV_KEYS = [
31
31
  { key: 'RECALL_API_KEY', required: false, explicit: true, description: 'Recall.ai meeting bot.' },
32
32
  { key: 'RECALL_REGION', required: false, explicit: true, description: 'Recall.ai region.' },
33
33
  { key: 'SMITHERY_API_KEY', required: false, explicit: true, description: 'Smithery hosted-MCP catalog.' },
34
+ // Watch bridge (Track 1 — Pushover wrist yes/no)
35
+ { key: 'PUSHOVER_TOKEN', required: false, explicit: true, description: 'Pushover app token — emergency permission pushes to the wrist (pushover.ts).' },
36
+ { key: 'PUSHOVER_USER_KEY', required: false, explicit: true, description: 'Pushover user/group key receiving permission pushes.' },
37
+ { key: 'NTFY_URL', required: false, explicit: true, description: 'ntfy server base (https://ntfy.sh or self-hosted) — second Track 1 provider with Approve/Deny buttons.' },
38
+ { key: 'NTFY_TOPIC', required: false, explicit: true, description: 'ntfy topic permission asks are published to.' },
39
+ { key: 'NTFY_TOKEN', required: false, explicit: true, description: 'Optional ntfy access token for protected topics.' },
40
+ { key: 'WATCH_ACK_SECRET', required: false, explicit: true, description: 'HMAC secret signing watch-ack links; shared with the frontend /api/watch/ack route.' },
41
+ { key: 'OSBORN_PUBLIC_URL', required: false, explicit: true, description: 'This machine\'s public base URL, embedded in signed watch-ack links so the callback knows where to forward.' },
42
+ { key: 'WATCH_GATEWAY', required: false, explicit: true, description: 'Set "1" to start the Track 2 watchOS WS gateway (watch-gateway.ts) bridging the native watch app into the LiveKit room.' },
43
+ { key: 'WATCH_GATEWAY_PORT', required: false, explicit: true, description: 'Port for the Track 2 watch gateway WS server (default 8742).' },
34
44
  // Platform / infra
35
45
  { key: 'OSBORN_API_PORT', required: true, explicit: true, description: 'Agent HTTP server port.' },
36
46
  { key: 'OSBORN_CWD', required: false, explicit: true, description: 'Agent working directory.' },
package/dist/index.js CHANGED
@@ -48,6 +48,8 @@ import { storeExists, openStore, recentRows } from './session-store.js';
48
48
  import { getRecallClient } from './recall-client.js';
49
49
  import { MeetingTranscriptPoller } from './meeting-transcript-poller.js';
50
50
  import { missingRequiredEnv } from './env-keys.js';
51
+ import { armPermissionPush, handleWatchAck, setWatchResultHandler } from './pushover.js';
52
+ import { startWatchGateway } from './watch-gateway.js';
51
53
  import { noiseGate } from './noise-gate.js';
52
54
  import { listSecretStatus, setSecrets, deleteSecret } from './secrets-store.js';
53
55
  import { llm } from '@livekit/agents';
@@ -1005,6 +1007,31 @@ function startApiServer(workingDir, port) {
1005
1007
  });
1006
1008
  return;
1007
1009
  }
1010
+ // POST /watch/ack — landing for the Track 1 wrist bridge (Pushover ack OR
1011
+ // ntfy Approve/Deny buttons). The frontend /api/watch/ack/[qid] route
1012
+ // verifies the HMAC signature and forwards here; pushover.ts re-verifies
1013
+ // against its pending map before resolving the blocking permission.
1014
+ // Dormant unless a provider (PUSHOVER_*/NTFY_*) + WATCH_ACK_SECRET are set.
1015
+ if (req.method === 'POST' && url.pathname === '/watch/ack') {
1016
+ let body = '';
1017
+ req.on('data', (c) => { body += c; });
1018
+ req.on('end', () => {
1019
+ try {
1020
+ const { qid, receipt, allow } = JSON.parse(body || '{}');
1021
+ if (!qid)
1022
+ throw new Error('qid required');
1023
+ // allow defaults to true (Pushover ack = approve); ntfy's Deny button sends false.
1024
+ const ok = handleWatchAck(qid, receipt, allow !== false);
1025
+ res.writeHead(ok ? 200 : 404, { 'Content-Type': 'application/json' });
1026
+ res.end(JSON.stringify({ ok }));
1027
+ }
1028
+ catch (e) {
1029
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1030
+ res.end(JSON.stringify({ error: e.message }));
1031
+ }
1032
+ });
1033
+ return;
1034
+ }
1008
1035
  // GET /sessions/export — stream a gzipped tar of ~/.claude/projects/ AND
1009
1036
  // ~/.claude/skills/ to the client. Both directories ship in one archive so
1010
1037
  // a sync covers conversations (projects/) and learned skills together —
@@ -2083,6 +2110,23 @@ async function main() {
2083
2110
  // null while the agent is idle (between sessions).
2084
2111
  let activeRoom = null;
2085
2112
  let activeRoomName = null; // the temporary room name currently joined
2113
+ // Watch gateway (mobile Track 2): bridges the native watchOS app's WS audio
2114
+ // + JSON into the user's LiveKit room via rtc-node. Opt-in — dormant unless
2115
+ // WATCH_GATEWAY=1 (port WATCH_GATEWAY_PORT, default 8742).
2116
+ if (process.env.WATCH_GATEWAY === '1') {
2117
+ const livekitUrl = process.env.LIVEKIT_URL || '';
2118
+ if (livekitUrl) {
2119
+ startWatchGateway({
2120
+ port: parseInt(process.env.WATCH_GATEWAY_PORT || '8742', 10),
2121
+ livekitUrl,
2122
+ getActiveRoom: () => activeRoomName,
2123
+ mintToken: mintAgentToken,
2124
+ });
2125
+ }
2126
+ else {
2127
+ console.log('⌚️ Watch gateway: WATCH_GATEWAY=1 but LIVEKIT_URL unset — not starting');
2128
+ }
2129
+ }
2086
2130
  // Track state
2087
2131
  let pendingSessionClose = null; // Tracks async session close for reconnect safety
2088
2132
  let currentSession = null;
@@ -3700,6 +3744,19 @@ async function main() {
3700
3744
  // PipelineDirectLLM (llmOverride path) wraps its own ClaudeLLM and may not expose setTurbo.
3701
3745
  directLLM?.setTurbo?.(turboMode);
3702
3746
  currentLLM = directLLM;
3747
+ // Watch bridge (mobile Track 1): a wrist ack/expiry settles whatever
3748
+ // permission is currently pending. Re-registered per session — harmless,
3749
+ // the latest closure wins and they all resolve through currentLLM.
3750
+ setWatchResultHandler((allow, toolName) => {
3751
+ if (currentLLM?.hasPendingPermission?.()) {
3752
+ currentLLM.respondToPermission(allow);
3753
+ console.log(`⌚️ Watch bridge settled ${toolName}: ${allow ? 'approve' : 'deny'}`);
3754
+ }
3755
+ else {
3756
+ // Already answered via the web UI — a late ack/expiry is a no-op.
3757
+ console.log(`⌚️ Watch bridge ${allow ? 'ack' : 'expiry'} for ${toolName} — no pending permission, ignoring`);
3758
+ }
3759
+ });
3703
3760
  // P1 host-agent anchor: this dashboard-started session owns the room's env
3704
3761
  // and keeps it alive (agentsActive → true) so background dispatches survive.
3705
3762
  // Keep-alive keys off the hostActive boolean, NOT a session_id event;
@@ -3897,6 +3954,10 @@ async function main() {
3897
3954
  agentRole: 'direct',
3898
3955
  diff: diffString,
3899
3956
  });
3957
+ // Watch bridge (mobile Track 1): mirror this blocking question to the
3958
+ // wrist via Pushover. Fire-and-forget — dormant unless PUSHOVER_* env is
3959
+ // configured; web-UI answers always win (late wrist acks are no-ops).
3960
+ void armPermissionPush({ toolName, description }).catch(() => { });
3900
3961
  // Speak the descriptive request so user knows to respond
3901
3962
  //do not delete!! Leave this section commented out
3902
3963
  // say permission, request permission, ask for permission with session.say
@@ -5362,7 +5423,7 @@ async function main() {
5362
5423
  // No sessions at all (or new session chosen) — greet as new user
5363
5424
  try {
5364
5425
  console.log('👋 Sending greeting...');
5365
- await greetViaVoice("Hey! I'm Osborn, your AI research assistant. What are you working on today?");
5426
+ await greetViaVoice("Hey! I'm Osborn, your AI engineer — I write, run, and ship code while you talk. What should we build today?");
5366
5427
  console.log('✅ Greeting sent');
5367
5428
  }
5368
5429
  catch (err) {
@@ -0,0 +1,77 @@
1
+ /**
2
+ * pushover.ts — Track 1 watch bridge (yes/no on the wrist via Pushover).
3
+ *
4
+ * When the agent hits a blocking permission request and nobody answers in the
5
+ * web UI, this module fires an emergency (priority-2) Pushover notification.
6
+ * Pushover mirrors notifications to the Apple Watch, so a single tap on the
7
+ * wrist acknowledges it; Pushover then requests our callback URL (the
8
+ * frontend's /api/watch/ack/<token> route), which verifies the HMAC and POSTs
9
+ * back to this machine's /watch/ack endpoint — resolving the pending
10
+ * permission as ALLOW. If the push goes unacknowledged for the full expiry
11
+ * window, a receipts-API poll settles it as DENY and cancels further retries.
12
+ *
13
+ * Settled semantics (mobile plan, 2026-10-24): ack = yes · expiry = no.
14
+ *
15
+ * Env (all optional — the bridge is dormant unless a provider is configured):
16
+ * PUSHOVER_TOKEN app token from pushover.net ($5 one-time)
17
+ * PUSHOVER_USER_KEY user (or group) key to push to
18
+ * NTFY_URL ntfy server base (https://ntfy.sh or self-hosted)
19
+ * NTFY_TOPIC topic to publish permission asks to (Approve/Deny buttons)
20
+ * NTFY_TOKEN optional access token for protected ntfy topics
21
+ * WATCH_ACK_SECRET HMAC secret, shared with the frontend ack route
22
+ * OSBORN_PUBLIC_URL this machine's public base URL — embedded in the signed
23
+ * token so the frontend route knows where to forward
24
+ * OSBORN_FRONTEND_URL (existing) callback host, default www.voice-native.com
25
+ */
26
+ interface PushoverConfig {
27
+ token: string;
28
+ userKey: string;
29
+ secret: string;
30
+ publicUrl: string;
31
+ frontendUrl: string;
32
+ }
33
+ /** Signed-token payload. `a` (agent base URL) lets the stateless frontend
34
+ * callback route know where to forward the ack — no DB lookup needed. */
35
+ interface AckPayload {
36
+ n: string;
37
+ a: string;
38
+ t: number;
39
+ e: number;
40
+ }
41
+ export declare function setWatchResultHandler(fn: (allow: boolean, toolName: string) => void): void;
42
+ export declare function pushoverConfig(): PushoverConfig | null;
43
+ export declare function isWatchBridgeEnabled(): boolean;
44
+ export declare function signAckToken(payload: AckPayload, secret: string): string;
45
+ export declare function verifyAckToken(qid: string, secret: string): AckPayload | null;
46
+ /**
47
+ * ntfy (self-hostable, free) — second Track 1 provider. Where Pushover offers
48
+ * one tap (ack = approve, expiry = deny), ntfy notifications carry REAL
49
+ * Approve/Deny action buttons (http actions hitting the same ack route with
50
+ * ?ans=1|0). Configure NTFY_URL (server base — ntfy.sh or your own), NTFY_TOPIC,
51
+ * optional NTFY_TOKEN (access token for protected topics). Phone notifications
52
+ * only — the watch still gets it via phone mirroring (same as Pushover).
53
+ */
54
+ interface NtfyConfig {
55
+ url: string;
56
+ topic: string;
57
+ token?: string;
58
+ }
59
+ export declare function ntfyConfig(): NtfyConfig | null;
60
+ export declare function isNtfyEnabled(): boolean;
61
+ /**
62
+ * Mirror a blocking permission request to the wrist. Fire-and-forget: any
63
+ * failure (network, Pushover 4xx, missing env) just logs — the web UI remains
64
+ * the source of truth and the request still waits for it.
65
+ */
66
+ export declare function armPermissionPush(opts: {
67
+ toolName: string;
68
+ description: string;
69
+ }): Promise<void>;
70
+ /**
71
+ * Landing for the frontend ack route. Returns true when a pending push was
72
+ * settled. `allow` defaults to true (Pushover ack semantics = approve); the
73
+ * ntfy Deny button passes false explicitly. Idempotent: a replayed callback
74
+ * or a late ack after another path answered just returns false.
75
+ */
76
+ export declare function handleWatchAck(qid: string, receipt?: string, allow?: boolean): boolean;
77
+ export {};
@@ -0,0 +1,276 @@
1
+ /**
2
+ * pushover.ts — Track 1 watch bridge (yes/no on the wrist via Pushover).
3
+ *
4
+ * When the agent hits a blocking permission request and nobody answers in the
5
+ * web UI, this module fires an emergency (priority-2) Pushover notification.
6
+ * Pushover mirrors notifications to the Apple Watch, so a single tap on the
7
+ * wrist acknowledges it; Pushover then requests our callback URL (the
8
+ * frontend's /api/watch/ack/<token> route), which verifies the HMAC and POSTs
9
+ * back to this machine's /watch/ack endpoint — resolving the pending
10
+ * permission as ALLOW. If the push goes unacknowledged for the full expiry
11
+ * window, a receipts-API poll settles it as DENY and cancels further retries.
12
+ *
13
+ * Settled semantics (mobile plan, 2026-10-24): ack = yes · expiry = no.
14
+ *
15
+ * Env (all optional — the bridge is dormant unless a provider is configured):
16
+ * PUSHOVER_TOKEN app token from pushover.net ($5 one-time)
17
+ * PUSHOVER_USER_KEY user (or group) key to push to
18
+ * NTFY_URL ntfy server base (https://ntfy.sh or self-hosted)
19
+ * NTFY_TOPIC topic to publish permission asks to (Approve/Deny buttons)
20
+ * NTFY_TOKEN optional access token for protected ntfy topics
21
+ * WATCH_ACK_SECRET HMAC secret, shared with the frontend ack route
22
+ * OSBORN_PUBLIC_URL this machine's public base URL — embedded in the signed
23
+ * token so the frontend route knows where to forward
24
+ * OSBORN_FRONTEND_URL (existing) callback host, default www.voice-native.com
25
+ */
26
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
27
+ const PUSH_API = 'https://api.pushover.net/1';
28
+ const ACK_PATH = '/api/watch/ack';
29
+ // Emergency-push tuning (seconds): re-buzz every 30s for up to 10 minutes.
30
+ const RETRY_S = 30;
31
+ const EXPIRE_S = 600;
32
+ // Grace past expiry before the receipts poll decides (clock skew + delivery).
33
+ const EXPIRY_GRACE_MS = 5_000;
34
+ /** Pending pushes by qid. The permission system is single-slot, so in practice
35
+ * this holds at most one live record — a Map keeps ack matching O(1) anyway. */
36
+ const pending = new Map();
37
+ /** Registered by index.ts: resolves the currently-pending permission. */
38
+ let resultHandler = null;
39
+ export function setWatchResultHandler(fn) {
40
+ resultHandler = fn;
41
+ }
42
+ export function pushoverConfig() {
43
+ const token = process.env.PUSHOVER_TOKEN;
44
+ const userKey = process.env.PUSHOVER_USER_KEY;
45
+ const secret = process.env.WATCH_ACK_SECRET;
46
+ const publicUrl = (process.env.OSBORN_PUBLIC_URL || '').replace(/\/+$/, '');
47
+ const frontendUrl = (process.env.OSBORN_FRONTEND_URL || 'https://www.voice-native.com').replace(/\/+$/, '');
48
+ if (!token || !userKey || !secret || !publicUrl)
49
+ return null;
50
+ return { token, userKey, secret, publicUrl, frontendUrl };
51
+ }
52
+ export function isWatchBridgeEnabled() {
53
+ return pushoverConfig() !== null || ntfyConfig() !== null;
54
+ }
55
+ // --- token helpers ---------------------------------------------------------
56
+ const b64url = (buf) => Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
57
+ const b64urlParse = (s) => Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
58
+ function hmac(secret, data) {
59
+ return b64url(createHmac('sha256', secret).update(data).digest());
60
+ }
61
+ export function signAckToken(payload, secret) {
62
+ const body = b64url(JSON.stringify(payload));
63
+ return `${body}.${hmac(secret, body)}`;
64
+ }
65
+ export function verifyAckToken(qid, secret) {
66
+ const dot = qid.lastIndexOf('.');
67
+ if (dot <= 0)
68
+ return null;
69
+ const body = qid.slice(0, dot);
70
+ const sig = qid.slice(dot + 1);
71
+ const expected = hmac(secret, body);
72
+ const a = Buffer.from(sig);
73
+ const b = Buffer.from(expected);
74
+ if (a.length !== b.length || !timingSafeEqual(a, b))
75
+ return null;
76
+ try {
77
+ const payload = JSON.parse(b64urlParse(body).toString('utf-8'));
78
+ if (typeof payload.a !== 'string' || typeof payload.n !== 'string')
79
+ return null;
80
+ return payload;
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
86
+ export function ntfyConfig() {
87
+ const url = (process.env.NTFY_URL || '').replace(/\/+$/, '');
88
+ const topic = process.env.NTFY_TOPIC;
89
+ if (!url || !topic)
90
+ return null;
91
+ return { url, topic, token: process.env.NTFY_TOKEN || undefined };
92
+ }
93
+ export function isNtfyEnabled() {
94
+ return ntfyConfig() !== null;
95
+ }
96
+ /**
97
+ * Mirror a blocking permission request to the wrist. Fire-and-forget: any
98
+ * failure (network, Pushover 4xx, missing env) just logs — the web UI remains
99
+ * the source of truth and the request still waits for it.
100
+ */
101
+ export async function armPermissionPush(opts) {
102
+ const cfg = pushoverConfig();
103
+ const ntfy = ntfyConfig();
104
+ if (!cfg && !ntfy)
105
+ return;
106
+ // Single-slot guard: never stack pushes (the SDK won't fire a second
107
+ // permission until the first resolves, but be defensive).
108
+ for (const p of pending.values()) {
109
+ if (!p.settled) {
110
+ console.log(`⌚️ Watch bridge: push already pending (${p.toolName}), not arming another`);
111
+ return;
112
+ }
113
+ }
114
+ const secret = process.env.WATCH_ACK_SECRET || '';
115
+ const publicUrl = (process.env.OSBORN_PUBLIC_URL || '').replace(/\/+$/, '');
116
+ const frontendUrl = (process.env.OSBORN_FRONTEND_URL || 'https://www.voice-native.com').replace(/\/+$/, '');
117
+ if (!secret || !publicUrl)
118
+ return;
119
+ const now = Date.now();
120
+ const qid = signAckToken({ n: randomBytes(12).toString('hex'), a: publicUrl, t: now, e: now + EXPIRE_S * 1000 }, secret);
121
+ // One record serves both providers: whichever ack lands first settles it.
122
+ const record = {
123
+ qid,
124
+ receipt: '',
125
+ toolName: opts.toolName,
126
+ description: opts.description,
127
+ expiresAt: now + EXPIRE_S * 1000,
128
+ settled: false,
129
+ };
130
+ if (cfg) {
131
+ try {
132
+ const res = await fetch(`${PUSH_API}/messages.json`, {
133
+ method: 'POST',
134
+ body: new URLSearchParams({
135
+ token: cfg.token,
136
+ user: cfg.userKey,
137
+ title: 'Voice Native',
138
+ message: `${opts.description}\n\nTap to approve · ignore to deny`.slice(0, 1000),
139
+ priority: '2',
140
+ retry: String(RETRY_S),
141
+ expire: String(EXPIRE_S),
142
+ callback: `${frontendUrl}${ACK_PATH}/${qid}`,
143
+ }),
144
+ });
145
+ const body = (await res.json().catch(() => ({})));
146
+ if (!res.ok || !body.receipt) {
147
+ console.log(`⌚️ Watch bridge: pushover rejected (${res.status})`, body.errors || '');
148
+ }
149
+ else {
150
+ record.receipt = body.receipt;
151
+ }
152
+ }
153
+ catch (e) {
154
+ console.log('⌚️ Watch bridge: pushover send failed:', e instanceof Error ? e.message : e);
155
+ }
156
+ }
157
+ if (ntfy) {
158
+ // Approve/Deny buttons hit the SAME signed ack route with ?ans=1|0.
159
+ try {
160
+ const res = await fetch(ntfy.url, {
161
+ method: 'POST',
162
+ headers: {
163
+ 'Content-Type': 'application/json',
164
+ ...(ntfy.token ? { Authorization: `Bearer ${ntfy.token}` } : {}),
165
+ },
166
+ body: JSON.stringify({
167
+ topic: ntfy.topic,
168
+ title: 'Voice Native',
169
+ message: opts.description.slice(0, 1000),
170
+ priority: 4,
171
+ tags: ['computer'],
172
+ click: `${frontendUrl}/dashboard`,
173
+ actions: [
174
+ {
175
+ action: 'http',
176
+ label: 'Approve',
177
+ method: 'GET',
178
+ url: `${frontendUrl}${ACK_PATH}/${qid}?ans=1`,
179
+ },
180
+ {
181
+ action: 'http',
182
+ label: 'Deny',
183
+ method: 'GET',
184
+ url: `${frontendUrl}${ACK_PATH}/${qid}?ans=0`,
185
+ },
186
+ ],
187
+ }),
188
+ });
189
+ if (!res.ok)
190
+ console.log(`⌚️ Watch bridge: ntfy rejected (${res.status})`);
191
+ }
192
+ catch (e) {
193
+ console.log('⌚️ Watch bridge: ntfy send failed:', e instanceof Error ? e.message : e);
194
+ }
195
+ }
196
+ if (!record.receipt && !ntfy)
197
+ return; // nothing actually sent
198
+ record.expiryTimer = setTimeout(() => void settleExpired(record), EXPIRE_S * 1000 + EXPIRY_GRACE_MS);
199
+ pending.set(qid, record);
200
+ console.log(`⌚️ Watch bridge: armed for ${opts.toolName} (pushover=${cfg ? 'on' : 'off'} ntfy=${ntfy ? 'on' : 'off'}, expires in ${EXPIRE_S}s)`);
201
+ }
202
+ /**
203
+ * Landing for the frontend ack route. Returns true when a pending push was
204
+ * settled. `allow` defaults to true (Pushover ack semantics = approve); the
205
+ * ntfy Deny button passes false explicitly. Idempotent: a replayed callback
206
+ * or a late ack after another path answered just returns false.
207
+ */
208
+ export function handleWatchAck(qid, receipt, allow = true) {
209
+ const secret = process.env.WATCH_ACK_SECRET;
210
+ if (!secret)
211
+ return false;
212
+ if (!verifyAckToken(qid, secret)) {
213
+ console.log('⌚️ Watch bridge: ack token failed HMAC verification');
214
+ return false;
215
+ }
216
+ const record = pending.get(qid);
217
+ if (!record || record.settled)
218
+ return false;
219
+ if (receipt && record.receipt && receipt !== record.receipt) {
220
+ console.log('⌚️ Watch bridge: receipt mismatch — ignoring ack');
221
+ return false;
222
+ }
223
+ record.settled = true;
224
+ if (record.expiryTimer)
225
+ clearTimeout(record.expiryTimer);
226
+ pending.delete(qid);
227
+ console.log(`⌚️ Watch bridge: ACKED → ${allow ? 'approve' : 'deny'} ${record.toolName}`);
228
+ resultHandler?.(allow, record.toolName);
229
+ return true;
230
+ }
231
+ /**
232
+ * Expiry path: if Pushover says the notification was never acknowledged,
233
+ * settle as deny and cancel further retries (stops the watch buzzing). If it
234
+ * WAS acknowledged but our callback never landed (delivery hiccup), recover
235
+ * by treating it as approve. ntfy-only records (no receipt) just settle deny.
236
+ */
237
+ async function settleExpired(record) {
238
+ if (record.settled)
239
+ return;
240
+ const cfg = pushoverConfig();
241
+ // ntfy-only, or pushover send failed earlier: no receipts API — deny.
242
+ if (!cfg || !record.receipt) {
243
+ record.settled = true;
244
+ pending.delete(record.qid);
245
+ console.log(`⌚️ Watch bridge: unacknowledged at expiry → deny ${record.toolName}`);
246
+ resultHandler?.(false, record.toolName);
247
+ return;
248
+ }
249
+ try {
250
+ const res = await fetch(`${PUSH_API}/receipts/${record.receipt}.json?token=${encodeURIComponent(cfg.token)}`);
251
+ const body = (await res.json().catch(() => ({})));
252
+ record.settled = true;
253
+ pending.delete(record.qid);
254
+ if (body.acknowledged === 1) {
255
+ // Acked but the callback never reached us — recover as approve.
256
+ console.log(`⌚️ Watch bridge: expiry poll found late ack → approve ${record.toolName}`);
257
+ resultHandler?.(true, record.toolName);
258
+ }
259
+ else {
260
+ console.log(`⌚️ Watch bridge: unacknowledged at expiry → deny ${record.toolName}`);
261
+ resultHandler?.(false, record.toolName);
262
+ // Cancel remaining emergency retries so the wrist stops buzzing.
263
+ void fetch(`${PUSH_API}/receipts/${record.receipt}/cancel.json`, {
264
+ method: 'POST',
265
+ body: new URLSearchParams({ token: cfg.token }),
266
+ }).catch(() => { });
267
+ }
268
+ }
269
+ catch (e) {
270
+ // Poll failed — settle deny; the record is dropped either way.
271
+ console.log('⌚️ Watch bridge: receipts poll failed:', e instanceof Error ? e.message : e);
272
+ record.settled = true;
273
+ pending.delete(record.qid);
274
+ resultHandler?.(false, record.toolName);
275
+ }
276
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * watch-gateway.ts — Track 2 watch bridge (native watchOS app ↔ LiveKit room).
3
+ *
4
+ * watchOS has no WKWebView and LiveKit's Swift SDK will not target it
5
+ * (client-sdk-swift #288), so the native watch app (frontend/native/watchos/)
6
+ * speaks a tiny WebSocket protocol to THIS gateway running on the user's own
7
+ * machine, which bridges into their LiveKit room via @livekit/rtc-node:
8
+ *
9
+ * watch ──WS JSON (control)──► gateway ──RTC data channel──► room
10
+ * watch ──WS binary (Int16LE PCM 24kHz mono)──► gateway ──resample 48k──► published mic track
11
+ * watch ◄──WS binary (Int16LE PCM 24kHz mono)── gateway ◄──decode+resample── subscribed agent track
12
+ *
13
+ * Protocol (see also GatewayLink.swift — the two must stay in sync):
14
+ * C→S text {"type":"hello","watchId":string} — first message; joins the ACTIVE room
15
+ * {"type":"answer","qid":string,"allow":boolean} — question sheet response
16
+ * {"type":"ping"}
17
+ * C→S bin raw Int16LE mono PCM frames @24kHz (no header)
18
+ * S→C text {"type":"state","agent":"idle|listening|thinking|speaking","room":string}
19
+ * {"type":"question","qid":string,"text":string}
20
+ * {"type":"joined","room":string} / {"type":"error","message":string} / {"type":"pong"}
21
+ * S→C bin raw Int16LE mono PCM frames @24kHz (announced by {"type":"audio","rate":24000})
22
+ *
23
+ * One watch connection = one rtc-node Room. The gateway is dormant unless
24
+ * started (index.ts gates on WATCH_GATEWAY=1).
25
+ */
26
+ import { WebSocketServer } from 'ws';
27
+ export interface WatchGatewayOptions {
28
+ port: number;
29
+ livekitUrl: string;
30
+ /** Returns the room the user's session is currently joined to (null = none). */
31
+ getActiveRoom: () => string | null;
32
+ /** Mints a LiveKit JWT for the given room (publish+subscribe+data). */
33
+ mintToken: (room: string) => Promise<string>;
34
+ }
35
+ export declare function startWatchGateway(opts: WatchGatewayOptions): {
36
+ wss: WebSocketServer;
37
+ close: () => void;
38
+ };