@wipcomputer/wip-ldm-os 0.4.73-alpha.3 → 0.4.73-alpha.30
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/LICENSE +52 -0
- package/bin/ldm.js +512 -95
- package/dist/bridge/chunk-3RG5ZIWI.js +10 -0
- package/dist/bridge/{chunk-LF7EMFBY.js → chunk-7NH6JBIO.js} +127 -49
- package/dist/bridge/cli.js +2 -1
- package/dist/bridge/core.d.ts +13 -1
- package/dist/bridge/core.js +4 -1
- package/dist/bridge/mcp-server.js +52 -7
- package/dist/bridge/openclaw.d.ts +5 -0
- package/dist/bridge/openclaw.js +11 -0
- package/docs/doc-pipeline/README.md +74 -0
- package/docs/doc-pipeline/TECHNICAL.md +79 -0
- package/lib/deploy.mjs +94 -10
- package/lib/detect.mjs +20 -6
- package/package.json +2 -2
- package/shared/docs/README.md.tmpl +2 -2
- package/shared/docs/how-install-works.md.tmpl +22 -2
- package/shared/docs/how-releases-work.md.tmpl +58 -42
- package/shared/docs/how-worktrees-work.md.tmpl +12 -7
- package/shared/rules/git-conventions.md +3 -3
- package/shared/rules/release-pipeline.md +1 -1
- package/shared/rules/security.md +1 -1
- package/shared/rules/workspace-boundaries.md +1 -1
- package/shared/rules/writing-style.md +1 -1
- package/shared/templates/claude-md-level1.md +7 -3
- package/src/bridge/core.ts +160 -56
- package/src/bridge/mcp-server.ts +93 -8
- package/src/bridge/openclaw.ts +14 -0
- package/src/hooks/inbox-check-hook.mjs +194 -0
- package/src/hooks/inbox-rewake-hook.mjs +338 -0
- package/src/hosted-mcp/.env.example +3 -0
- package/src/hosted-mcp/demo/agent.html +300 -0
- package/src/hosted-mcp/demo/agent.txt +84 -0
- package/src/hosted-mcp/demo/fallback.jpg +0 -0
- package/src/hosted-mcp/demo/footer.js +74 -0
- package/src/hosted-mcp/demo/index.html +1303 -0
- package/src/hosted-mcp/demo/login.html +548 -0
- package/src/hosted-mcp/demo/privacy.html +223 -0
- package/src/hosted-mcp/demo/sprites.jpg +0 -0
- package/src/hosted-mcp/demo/sprites.png +0 -0
- package/src/hosted-mcp/demo/tos.html +198 -0
- package/src/hosted-mcp/deploy.sh +70 -0
- package/src/hosted-mcp/ecosystem.config.cjs +14 -0
- package/src/hosted-mcp/inbox.mjs +64 -0
- package/src/hosted-mcp/legal/internet-services/terms/site.html +205 -0
- package/src/hosted-mcp/legal/privacy/en-ww/index.html +230 -0
- package/src/hosted-mcp/nginx/mcp-oauth.conf +98 -0
- package/src/hosted-mcp/nginx/mcp-server.conf +17 -0
- package/src/hosted-mcp/nginx/wip.computer.conf +45 -0
- package/src/hosted-mcp/package-lock.json +2092 -0
- package/src/hosted-mcp/package.json +23 -0
- package/src/hosted-mcp/prisma/migrations/20260406233014_init/migration.sql +68 -0
- package/src/hosted-mcp/prisma/migrations/migration_lock.toml +3 -0
- package/src/hosted-mcp/prisma/schema.prisma +57 -0
- package/src/hosted-mcp/prisma.config.ts +14 -0
- package/src/hosted-mcp/server.mjs +2079 -0
- package/src/hosted-mcp/tools.mjs +73 -0
- package/templates/hooks/pre-commit +5 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* LDM OS Inbox Check Hook
|
|
4
|
+
* UserPromptSubmit hook for Claude Code.
|
|
5
|
+
* Scans ~/.ldm/messages/ for pending messages addressed to this agent
|
|
6
|
+
* and surfaces them as additionalContext before CC responds.
|
|
7
|
+
*
|
|
8
|
+
* Follows guard.mjs pattern: stdin JSON in, stdout JSON out, exit 0 always.
|
|
9
|
+
* Does NOT mark messages as read... that's what lesa_check_inbox does.
|
|
10
|
+
* Zero external dependencies beyond node:fs and node:path.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
14
|
+
import { join, basename } from 'node:path';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
|
|
17
|
+
const HOME = homedir();
|
|
18
|
+
const MESSAGES_DIR = join(HOME, '.ldm', 'messages');
|
|
19
|
+
const LDM_CONFIG_PATH = join(HOME, '.ldm', 'config.json');
|
|
20
|
+
const TAG = '[inbox-check-hook]';
|
|
21
|
+
|
|
22
|
+
// ── Helpers ──
|
|
23
|
+
|
|
24
|
+
function readJSON(path) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function getAgentId() {
|
|
33
|
+
// Try LDM config first
|
|
34
|
+
const config = readJSON(LDM_CONFIG_PATH);
|
|
35
|
+
if (config?.agents) {
|
|
36
|
+
// Find the agent entry for this machine's claude-code harness
|
|
37
|
+
for (const [id, agent] of Object.entries(config.agents)) {
|
|
38
|
+
if (agent.harness === 'claude-code') return id;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return 'cc-mini';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function getSessionName(input) {
|
|
45
|
+
// 1. Try CC session file for the parent PID.
|
|
46
|
+
// CC writes /rename labels to ~/.claude/sessions/<pid>.json.
|
|
47
|
+
// This hook is spawned fresh each time by CC, so ppid = CC PID.
|
|
48
|
+
// Reading the session file picks up /rename and /resume labels
|
|
49
|
+
// without any env var or restart.
|
|
50
|
+
try {
|
|
51
|
+
const ccSessionPath = join(HOME, '.claude', 'sessions', `${process.ppid}.json`);
|
|
52
|
+
const data = JSON.parse(readFileSync(ccSessionPath, 'utf8'));
|
|
53
|
+
if (data.name && typeof data.name === 'string') {
|
|
54
|
+
return data.name;
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
// No session file. Normal for non-CC harnesses.
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 2. Env var override
|
|
61
|
+
// 3. CWD basename fallback
|
|
62
|
+
// 4. Default
|
|
63
|
+
return (
|
|
64
|
+
process.env.LDM_SESSION_NAME ||
|
|
65
|
+
process.env.CLAUDE_SESSION_NAME ||
|
|
66
|
+
basename(input?.cwd || process.cwd()) ||
|
|
67
|
+
'default'
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Check if a message's "to" field matches this agent.
|
|
73
|
+
* Supported targets:
|
|
74
|
+
* - exact agent ID (e.g. "cc-mini")
|
|
75
|
+
* - agent:session (e.g. "cc-mini:my-session")
|
|
76
|
+
* - agent:* (e.g. "cc-mini:*" ... all sessions of this agent)
|
|
77
|
+
* - "*" or "all" ... broadcast to everyone
|
|
78
|
+
* - exact session name match
|
|
79
|
+
*/
|
|
80
|
+
function messageMatchesAgent(to, agentId, sessionName) {
|
|
81
|
+
if (!to) return false;
|
|
82
|
+
|
|
83
|
+
// Broadcast targets
|
|
84
|
+
if (to === '*' || to === 'all') return true;
|
|
85
|
+
|
|
86
|
+
// Exact agent ID
|
|
87
|
+
if (to === agentId) return true;
|
|
88
|
+
|
|
89
|
+
// Agent wildcard: "cc-mini:*"
|
|
90
|
+
if (to === `${agentId}:*`) return true;
|
|
91
|
+
|
|
92
|
+
// Agent + specific session: "cc-mini:my-session"
|
|
93
|
+
if (to === `${agentId}:${sessionName}`) return true;
|
|
94
|
+
|
|
95
|
+
// Direct session name match
|
|
96
|
+
if (to === sessionName) return true;
|
|
97
|
+
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ── Main ──
|
|
102
|
+
|
|
103
|
+
async function main() {
|
|
104
|
+
let raw = '';
|
|
105
|
+
for await (const chunk of process.stdin) raw += chunk;
|
|
106
|
+
|
|
107
|
+
let input;
|
|
108
|
+
try {
|
|
109
|
+
input = JSON.parse(raw);
|
|
110
|
+
} catch {
|
|
111
|
+
// Bad input... exit clean with no context
|
|
112
|
+
process.stdout.write(JSON.stringify({}));
|
|
113
|
+
process.exit(0);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Fast exit if messages dir doesn't exist
|
|
117
|
+
if (!existsSync(MESSAGES_DIR)) {
|
|
118
|
+
process.stdout.write(JSON.stringify({}));
|
|
119
|
+
process.exit(0);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const agentId = getAgentId();
|
|
123
|
+
const sessionName = getSessionName(input);
|
|
124
|
+
|
|
125
|
+
// Scan for pending messages
|
|
126
|
+
let files;
|
|
127
|
+
try {
|
|
128
|
+
files = readdirSync(MESSAGES_DIR).filter(f => f.endsWith('.json'));
|
|
129
|
+
} catch {
|
|
130
|
+
process.stdout.write(JSON.stringify({}));
|
|
131
|
+
process.exit(0);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Fast exit if no message files
|
|
135
|
+
if (files.length === 0) {
|
|
136
|
+
process.stdout.write(JSON.stringify({}));
|
|
137
|
+
process.exit(0);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const pending = [];
|
|
141
|
+
const seen = new Set();
|
|
142
|
+
|
|
143
|
+
for (const file of files) {
|
|
144
|
+
const data = readJSON(join(MESSAGES_DIR, file));
|
|
145
|
+
if (!data) continue;
|
|
146
|
+
|
|
147
|
+
// Skip already-read messages (if the field exists)
|
|
148
|
+
if (data.read === true) continue;
|
|
149
|
+
|
|
150
|
+
// Check if addressed to us
|
|
151
|
+
if (!messageMatchesAgent(data.to, agentId, sessionName)) continue;
|
|
152
|
+
|
|
153
|
+
// Deduplicate by message ID
|
|
154
|
+
if (data.id && seen.has(data.id)) continue;
|
|
155
|
+
if (data.id) seen.add(data.id);
|
|
156
|
+
|
|
157
|
+
pending.push(data);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Fast exit if nothing pending
|
|
161
|
+
if (pending.length === 0) {
|
|
162
|
+
process.stdout.write(JSON.stringify({}));
|
|
163
|
+
process.exit(0);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Sort by timestamp (oldest first)
|
|
167
|
+
pending.sort((a, b) => (a.timestamp || '').localeCompare(b.timestamp || ''));
|
|
168
|
+
|
|
169
|
+
// Format output
|
|
170
|
+
const msgLines = pending
|
|
171
|
+
.map(m => `[${m.type || 'chat'}] from ${m.from || 'unknown'} (${m.timestamp || 'no timestamp'}):\n ${m.body || '(empty)'}`)
|
|
172
|
+
.join('\n\n');
|
|
173
|
+
|
|
174
|
+
const additionalContext =
|
|
175
|
+
`== Pending Messages (${pending.length}) ==\n` +
|
|
176
|
+
`You have ${pending.length} unread message(s). Review them and respond if needed. Use lesa_check_inbox to mark as read when done.\n\n` +
|
|
177
|
+
msgLines;
|
|
178
|
+
|
|
179
|
+
const output = {
|
|
180
|
+
hookSpecificOutput: {
|
|
181
|
+
hookEventName: 'UserPromptSubmit',
|
|
182
|
+
additionalContext,
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
process.stdout.write(JSON.stringify(output));
|
|
187
|
+
process.stderr.write(`${TAG} ${pending.length} pending message(s) for ${agentId}:${sessionName}\n`);
|
|
188
|
+
process.exit(0);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
main().catch(() => {
|
|
192
|
+
process.stdout.write(JSON.stringify({}));
|
|
193
|
+
process.exit(0);
|
|
194
|
+
});
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* LDM OS Inbox Rewake Hook
|
|
4
|
+
*
|
|
5
|
+
* asyncRewake background hook for Claude Code. Watches ~/.ldm/messages/
|
|
6
|
+
* with fs.watch and, when a new message addressed to this agent:session
|
|
7
|
+
* arrives, writes the message as a system-reminder to stderr and exits
|
|
8
|
+
* with code 2. Claude Code's harness wraps the stderr in a system-reminder
|
|
9
|
+
* task-notification that wakes the model if idle or gets injected mid-query
|
|
10
|
+
* if the model is busy. See:
|
|
11
|
+
*
|
|
12
|
+
* ai/product/plans-prds/bridge/2026-04-11--cc-mini--autonomous-push-architecture.md
|
|
13
|
+
*
|
|
14
|
+
* Attached as a Stop hook with asyncRewake: true. Fires after every CC
|
|
15
|
+
* turn. A lockfile prevents multiple instances from stacking across many
|
|
16
|
+
* Stop events: only the first instance acquires the lock and watches;
|
|
17
|
+
* subsequent instances see the lock held by a live process and exit 0
|
|
18
|
+
* silently. The lock is released when the watching instance exits
|
|
19
|
+
* (message caught, parent dead, hard timeout, or hard cancel).
|
|
20
|
+
*
|
|
21
|
+
* This hook is the "true push" layer 1 from the plan. Layers 2-4
|
|
22
|
+
* (UserPromptSubmit inbox-check hook, SessionStart boot hook, manual
|
|
23
|
+
* lesa_check_inbox) remain as independent fallbacks.
|
|
24
|
+
*
|
|
25
|
+
* Idempotent with inbox-check-hook.mjs: after firing, this hook marks
|
|
26
|
+
* the message file's `read` field to true so the UserPromptSubmit hook
|
|
27
|
+
* on the next user prompt does not re-surface the same message.
|
|
28
|
+
*
|
|
29
|
+
* Zero external dependencies beyond node:fs, node:path, node:os.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import {
|
|
33
|
+
existsSync,
|
|
34
|
+
readFileSync,
|
|
35
|
+
readdirSync,
|
|
36
|
+
writeFileSync,
|
|
37
|
+
unlinkSync,
|
|
38
|
+
watch,
|
|
39
|
+
} from 'node:fs';
|
|
40
|
+
import { join, basename } from 'node:path';
|
|
41
|
+
import { homedir } from 'node:os';
|
|
42
|
+
|
|
43
|
+
const HOME = homedir();
|
|
44
|
+
const MESSAGES_DIR = join(HOME, '.ldm', 'messages');
|
|
45
|
+
const LOCK_PATH = join(MESSAGES_DIR, '.rewake.lock');
|
|
46
|
+
const LDM_CONFIG_PATH = join(HOME, '.ldm', 'config.json');
|
|
47
|
+
const TAG = '[inbox-rewake-hook]';
|
|
48
|
+
|
|
49
|
+
// Hard safety timeout: the watcher exits after 6 hours no matter what,
|
|
50
|
+
// so it cannot leak forever if the parent check or lock cleanup misses.
|
|
51
|
+
const HARD_TIMEOUT_MS = 6 * 60 * 60 * 1000;
|
|
52
|
+
|
|
53
|
+
// Parent CC process liveness check: every minute, verify the parent PID
|
|
54
|
+
// is still alive. If the parent died while this background hook is
|
|
55
|
+
// running, exit cleanly so we do not orphan.
|
|
56
|
+
const PARENT_CHECK_INTERVAL_MS = 60 * 1000;
|
|
57
|
+
|
|
58
|
+
// ── Helpers (mirror inbox-check-hook.mjs) ──
|
|
59
|
+
|
|
60
|
+
function readJSON(path) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function getAgentId() {
|
|
69
|
+
const config = readJSON(LDM_CONFIG_PATH);
|
|
70
|
+
if (config?.agents) {
|
|
71
|
+
for (const [id, agent] of Object.entries(config.agents)) {
|
|
72
|
+
if (agent.harness === 'claude-code') return id;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return 'cc-mini';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function getSessionName(input) {
|
|
79
|
+
// Mirror inbox-check-hook.mjs: CC writes /rename labels to
|
|
80
|
+
// ~/.claude/sessions/<pid>.json, and this hook is spawned fresh by CC
|
|
81
|
+
// so ppid = CC PID. Reading the session file picks up /rename and
|
|
82
|
+
// /resume labels without any env var or restart.
|
|
83
|
+
try {
|
|
84
|
+
const ccSessionPath = join(HOME, '.claude', 'sessions', `${process.ppid}.json`);
|
|
85
|
+
const data = JSON.parse(readFileSync(ccSessionPath, 'utf8'));
|
|
86
|
+
if (data.name && typeof data.name === 'string') {
|
|
87
|
+
return data.name;
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
// No session file. Normal for non-CC harnesses.
|
|
91
|
+
}
|
|
92
|
+
return (
|
|
93
|
+
process.env.LDM_SESSION_NAME ||
|
|
94
|
+
process.env.CLAUDE_SESSION_NAME ||
|
|
95
|
+
basename(input?.cwd || process.cwd()) ||
|
|
96
|
+
'default'
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Check if a message's "to" field matches this agent:session.
|
|
102
|
+
* Same logic as inbox-check-hook.mjs so both hooks agree on routing.
|
|
103
|
+
*/
|
|
104
|
+
function messageMatchesAgent(to, agentId, sessionName) {
|
|
105
|
+
if (!to) return false;
|
|
106
|
+
if (to === '*' || to === 'all') return true;
|
|
107
|
+
if (to === agentId) return true;
|
|
108
|
+
if (to === `${agentId}:*`) return true;
|
|
109
|
+
if (to === `${agentId}:${sessionName}`) return true;
|
|
110
|
+
if (to === sessionName) return true;
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── Lock management ──
|
|
115
|
+
//
|
|
116
|
+
// A single machine may have seven or more concurrent CC sessions, each
|
|
117
|
+
// spawning its own rewake hook on every Stop event. Without a lock, we
|
|
118
|
+
// accumulate fs.watch handles forever and every new message fires all
|
|
119
|
+
// pending hooks simultaneously.
|
|
120
|
+
//
|
|
121
|
+
// The lock is per-session, keyed by agent:session, so different CC
|
|
122
|
+
// sessions do not block each other. The lock file lives at
|
|
123
|
+
// ~/.ldm/messages/.rewake.<agent>-<session>.lock and contains the PID
|
|
124
|
+
// of the watching process. Subsequent hook spawns in the same session
|
|
125
|
+
// see the lock, verify the PID is alive, and exit silently.
|
|
126
|
+
|
|
127
|
+
function lockPathFor(agentId, sessionName) {
|
|
128
|
+
// Replace any filesystem-unfriendly chars with '-' so session names
|
|
129
|
+
// like "memory:crystal" or "brainstorm (oc)" do not produce invalid
|
|
130
|
+
// filenames. Keeps alphanumerics, dashes, underscores.
|
|
131
|
+
const safe = `${agentId}-${sessionName}`.replace(/[^a-zA-Z0-9._-]/g, '-');
|
|
132
|
+
return join(MESSAGES_DIR, `.rewake.${safe}.lock`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function pidIsAlive(pid) {
|
|
136
|
+
try {
|
|
137
|
+
process.kill(pid, 0); // signal 0 is a liveness probe
|
|
138
|
+
return true;
|
|
139
|
+
} catch {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function acquireLock(lockPath) {
|
|
145
|
+
try {
|
|
146
|
+
if (existsSync(lockPath)) {
|
|
147
|
+
const raw = readFileSync(lockPath, 'utf8').trim();
|
|
148
|
+
const existing = parseInt(raw, 10);
|
|
149
|
+
if (existing && existing > 0 && pidIsAlive(existing)) {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
// Stale lock: previous holder is dead, take over.
|
|
153
|
+
try { unlinkSync(lockPath); } catch {}
|
|
154
|
+
}
|
|
155
|
+
} catch {}
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
writeFileSync(lockPath, String(process.pid));
|
|
159
|
+
return true;
|
|
160
|
+
} catch {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function releaseLock(lockPath) {
|
|
166
|
+
try {
|
|
167
|
+
if (!existsSync(lockPath)) return;
|
|
168
|
+
const raw = readFileSync(lockPath, 'utf8').trim();
|
|
169
|
+
const pid = parseInt(raw, 10);
|
|
170
|
+
if (pid === process.pid) {
|
|
171
|
+
unlinkSync(lockPath);
|
|
172
|
+
}
|
|
173
|
+
} catch {}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ── Message delivery ──
|
|
177
|
+
//
|
|
178
|
+
// When a match is found, we:
|
|
179
|
+
// 1. Mark the file's `read` field to true (so inbox-check-hook.mjs on
|
|
180
|
+
// the next UserPromptSubmit does not re-surface it).
|
|
181
|
+
// 2. Write the formatted message body to stderr.
|
|
182
|
+
// 3. Release the lock.
|
|
183
|
+
// 4. process.exit(2) to trigger Claude Code's asyncRewake wake path.
|
|
184
|
+
|
|
185
|
+
function markRead(filePath) {
|
|
186
|
+
try {
|
|
187
|
+
const data = readJSON(filePath);
|
|
188
|
+
if (!data) return;
|
|
189
|
+
data.read = true;
|
|
190
|
+
writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n');
|
|
191
|
+
} catch {
|
|
192
|
+
// Non-fatal. Worst case: inbox-check-hook surfaces the same message
|
|
193
|
+
// on the next UserPromptSubmit. That is still correct behavior; it
|
|
194
|
+
// just means the same message gets two surfaces.
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function fireMessage(msg, filePath, lockPath, agentId, sessionName) {
|
|
199
|
+
markRead(filePath);
|
|
200
|
+
|
|
201
|
+
const body =
|
|
202
|
+
`== Bridge Push (autonomous) ==\n` +
|
|
203
|
+
`You have 1 new message delivered by the inbox-rewake hook while you were idle. ` +
|
|
204
|
+
`The message was addressed to ${agentId}:${sessionName} and is now marked read in the inbox.\n\n` +
|
|
205
|
+
`[${msg.type || 'chat'}] from ${msg.from || 'unknown'} (${msg.timestamp || 'no timestamp'}):\n` +
|
|
206
|
+
`${msg.body || '(empty)'}\n\n` +
|
|
207
|
+
`Acknowledge or respond as appropriate. Use lesa_check_inbox or ldm_send_message to continue the thread.`;
|
|
208
|
+
|
|
209
|
+
process.stderr.write(body);
|
|
210
|
+
process.stderr.write(`\n${TAG} fired for ${msg.id || '(no id)'} to ${agentId}:${sessionName}\n`);
|
|
211
|
+
|
|
212
|
+
releaseLock(lockPath);
|
|
213
|
+
process.exit(2);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ── Main ──
|
|
217
|
+
|
|
218
|
+
async function main() {
|
|
219
|
+
// Drain stdin even if we ignore it. Hooks receive JSON per the CC
|
|
220
|
+
// hook protocol; we do not need any of the fields here.
|
|
221
|
+
let raw = '';
|
|
222
|
+
try {
|
|
223
|
+
for await (const chunk of process.stdin) raw += chunk;
|
|
224
|
+
} catch {}
|
|
225
|
+
|
|
226
|
+
let input = {};
|
|
227
|
+
try { input = JSON.parse(raw); } catch {}
|
|
228
|
+
|
|
229
|
+
if (!existsSync(MESSAGES_DIR)) {
|
|
230
|
+
// Nothing to watch. Exit silently. A future install will recreate.
|
|
231
|
+
process.exit(0);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const agentId = getAgentId();
|
|
235
|
+
const sessionName = getSessionName(input);
|
|
236
|
+
const lockPath = lockPathFor(agentId, sessionName);
|
|
237
|
+
const parentPid = process.ppid;
|
|
238
|
+
|
|
239
|
+
// Try to take the lock. If another instance of this session's rewake
|
|
240
|
+
// hook is already watching, exit silently and let them handle it.
|
|
241
|
+
if (!acquireLock(lockPath)) {
|
|
242
|
+
process.stderr.write(
|
|
243
|
+
`${TAG} another live instance holds ${basename(lockPath)}, exiting\n`,
|
|
244
|
+
);
|
|
245
|
+
process.exit(0);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Guarantee we release the lock on any exit path.
|
|
249
|
+
process.on('exit', () => releaseLock(lockPath));
|
|
250
|
+
process.on('SIGTERM', () => { releaseLock(lockPath); process.exit(0); });
|
|
251
|
+
process.on('SIGINT', () => { releaseLock(lockPath); process.exit(0); });
|
|
252
|
+
process.on('uncaughtException', (err) => {
|
|
253
|
+
process.stderr.write(`${TAG} uncaughtException: ${err.message}\n`);
|
|
254
|
+
releaseLock(lockPath);
|
|
255
|
+
process.exit(0);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// Track which message IDs we have already fired for in this run.
|
|
259
|
+
// fs.watch can fire multiple events for a single file write; the
|
|
260
|
+
// in-memory set prevents duplicate firings in the window between
|
|
261
|
+
// writing `read: true` to disk and the next scan picking it up.
|
|
262
|
+
const seen = new Set();
|
|
263
|
+
|
|
264
|
+
function inspectFile(filePath) {
|
|
265
|
+
const data = readJSON(filePath);
|
|
266
|
+
if (!data) return false;
|
|
267
|
+
if (data.read === true) return false;
|
|
268
|
+
if (data.id && seen.has(data.id)) return false;
|
|
269
|
+
if (!messageMatchesAgent(data.to, agentId, sessionName)) return false;
|
|
270
|
+
if (data.id) seen.add(data.id);
|
|
271
|
+
|
|
272
|
+
fireMessage(data, filePath, lockPath, agentId, sessionName);
|
|
273
|
+
return true; // fireMessage exits, but be explicit.
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function scanDir() {
|
|
277
|
+
try {
|
|
278
|
+
const files = readdirSync(MESSAGES_DIR).filter((f) => f.endsWith('.json'));
|
|
279
|
+
for (const file of files) {
|
|
280
|
+
if (inspectFile(join(MESSAGES_DIR, file))) return true;
|
|
281
|
+
}
|
|
282
|
+
} catch {}
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Initial scan: catch any messages that arrived between the previous
|
|
287
|
+
// hook instance exiting and this one starting up.
|
|
288
|
+
if (scanDir()) return;
|
|
289
|
+
|
|
290
|
+
// Set up the fs.watch for new messages.
|
|
291
|
+
let watcher;
|
|
292
|
+
try {
|
|
293
|
+
watcher = watch(MESSAGES_DIR, { persistent: true }, (eventType, filename) => {
|
|
294
|
+
if (!filename || !filename.endsWith('.json')) return;
|
|
295
|
+
// Re-scan on every event. fs.watch can coalesce or miss events
|
|
296
|
+
// under load, so scanning the directory is more reliable than
|
|
297
|
+
// trusting the filename argument alone.
|
|
298
|
+
scanDir();
|
|
299
|
+
});
|
|
300
|
+
} catch (e) {
|
|
301
|
+
process.stderr.write(`${TAG} fs.watch failed: ${e.message}\n`);
|
|
302
|
+
releaseLock(lockPath);
|
|
303
|
+
process.exit(0);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Parent process liveness check. If the CC session that spawned us
|
|
307
|
+
// has exited, stop watching and release the lock.
|
|
308
|
+
const parentCheck = setInterval(() => {
|
|
309
|
+
if (!pidIsAlive(parentPid)) {
|
|
310
|
+
process.stderr.write(`${TAG} parent pid ${parentPid} is dead, exiting\n`);
|
|
311
|
+
clearInterval(parentCheck);
|
|
312
|
+
if (watcher) watcher.close();
|
|
313
|
+
releaseLock(lockPath);
|
|
314
|
+
process.exit(0);
|
|
315
|
+
}
|
|
316
|
+
}, PARENT_CHECK_INTERVAL_MS);
|
|
317
|
+
|
|
318
|
+
// Hard safety timeout.
|
|
319
|
+
const hardTimeout = setTimeout(() => {
|
|
320
|
+
process.stderr.write(`${TAG} hard timeout after ${HARD_TIMEOUT_MS / 1000}s\n`);
|
|
321
|
+
clearInterval(parentCheck);
|
|
322
|
+
if (watcher) watcher.close();
|
|
323
|
+
releaseLock(lockPath);
|
|
324
|
+
process.exit(0);
|
|
325
|
+
}, HARD_TIMEOUT_MS);
|
|
326
|
+
|
|
327
|
+
// Let the timers keep the event loop alive. If either timer fires or
|
|
328
|
+
// the watcher fires a message match, the process exits and releases
|
|
329
|
+
// the lock.
|
|
330
|
+
process.stderr.write(
|
|
331
|
+
`${TAG} watching ${MESSAGES_DIR} for ${agentId}:${sessionName} (parent pid ${parentPid})\n`,
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
main().catch((err) => {
|
|
336
|
+
process.stderr.write(`${TAG} fatal in main: ${err && err.message}\n`);
|
|
337
|
+
process.exit(0);
|
|
338
|
+
});
|