clay-server 5.2.0-beta.5 → 5.2.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/lib/claude-hook-installer.js +1 -267
  2. package/lib/claude-jsonl-watcher.js +1 -204
  3. package/lib/clay-skill-install.js +1 -33
  4. package/lib/cli-sessions.js +1 -300
  5. package/lib/codex-defaults.js +1 -28
  6. package/lib/context-usage.js +3 -2
  7. package/lib/daemon.js +5 -55
  8. package/lib/default-ai-runtime.js +4 -8
  9. package/lib/email-mcp-server.js +1 -1
  10. package/lib/kiro-defaults.js +1 -22
  11. package/lib/mcp-proxy.js +2 -32
  12. package/lib/mcp-query-bridge.js +1 -1
  13. package/lib/mcp-source-adapters.js +1 -91
  14. package/lib/mcp-source-context.js +1 -42
  15. package/lib/mcp-source-discovery.js +1 -169
  16. package/lib/mcp-source-plugins.js +1 -68
  17. package/lib/mcp-source-restrictions.js +1 -47
  18. package/lib/mcp-tool-policy.js +1 -26
  19. package/lib/os-user-diagnostics.js +2 -4
  20. package/lib/os-users.js +4 -65
  21. package/lib/project-connection.js +8 -7
  22. package/lib/project-http.js +4 -4
  23. package/lib/project-mcp.js +2 -2
  24. package/lib/project-pair-result-delivery.js +2 -2
  25. package/lib/project-pair-usage.js +12 -13
  26. package/lib/project-pending-message-queue.js +3 -1
  27. package/lib/project-session-history-actions.js +5 -3
  28. package/lib/project-session-pair.js +1 -1
  29. package/lib/project-session-runtime-actions.js +2 -1
  30. package/lib/project-session-spawn.js +2 -3
  31. package/lib/project-session-vendor.js +2 -1
  32. package/lib/project-sessions.js +18 -26
  33. package/lib/project-user-message.js +1 -0
  34. package/lib/project-vendor-login.js +6 -36
  35. package/lib/public/app.js +1 -0
  36. package/lib/public/css/messages.css +6 -2
  37. package/lib/public/modules/app-favicon.js +11 -2
  38. package/lib/public/modules/app-header.js +4 -2
  39. package/lib/public/modules/app-loop-ui.js +2 -0
  40. package/lib/public/modules/app-messages.js +36 -5
  41. package/lib/public/modules/app-notifications.js +1 -2
  42. package/lib/public/modules/app-panels.js +61 -123
  43. package/lib/public/modules/app-rate-limit.js +7 -27
  44. package/lib/public/modules/chat-render-runtime.js +3 -0
  45. package/lib/public/modules/mcp-connection-view.js +1 -1
  46. package/lib/public/modules/permission-control.js +5 -4
  47. package/lib/public/modules/scheduler.js +2 -0
  48. package/lib/public/modules/session-create-form.js +10 -10
  49. package/lib/public/modules/settings-defaults.js +27 -28
  50. package/lib/public/modules/tools.js +2 -1
  51. package/lib/public/modules/tui-grab.js +1 -2
  52. package/lib/public/modules/vendor-login-browser.js +5 -3
  53. package/lib/public/modules/vendor-login.js +2 -2
  54. package/lib/public/modules/vendor-priority.js +15 -1
  55. package/lib/public/muse-avatar.svg +4 -0
  56. package/lib/safe-bash-commands.js +3 -45
  57. package/lib/sdk-bridge.js +127 -395
  58. package/lib/sdk-foreground-admission.js +16 -0
  59. package/lib/sdk-mcp-descriptors.js +2 -37
  60. package/lib/sdk-message-processor.js +50 -17
  61. package/lib/sdk-quota-snapshot.js +1 -1
  62. package/lib/sdk-response-recovery.js +1 -155
  63. package/lib/sdk-worker.js +2 -677
  64. package/lib/server.js +1 -1
  65. package/lib/session-fork-history.js +21 -0
  66. package/lib/session-hygiene.js +3 -35
  67. package/lib/session-permission-mode.js +4 -3
  68. package/lib/session-skill-scope.js +11 -0
  69. package/lib/sessions.js +17 -89
  70. package/lib/tool-llm.js +1 -1
  71. package/lib/tui-transcript-index.js +1 -132
  72. package/lib/vendor-login-browser.js +1 -11
  73. package/lib/yoke/acp-agent-profiles.js +5 -3
  74. package/lib/yoke/adapters/antigravity.js +3 -14
  75. package/lib/yoke/adapters/claude-query-contract.js +9 -0
  76. package/lib/yoke/adapters/claude.js +7 -42
  77. package/lib/yoke/adapters/codex-query-contract.js +24 -0
  78. package/lib/yoke/adapters/codex.js +1 -0
  79. package/lib/yoke/adapters/kiro.js +3 -1
  80. package/lib/yoke/adapters/muse-query-contract.js +7 -0
  81. package/lib/yoke/adapters/muse.js +122 -0
  82. package/lib/yoke/auth-events.js +17 -0
  83. package/lib/yoke/claude-hook-installer.js +267 -0
  84. package/lib/yoke/claude-jsonl-watcher.js +204 -0
  85. package/lib/yoke/claude-maintenance.js +55 -0
  86. package/lib/yoke/claude-permission-patterns.js +53 -0
  87. package/lib/yoke/claude-response-recovery.js +155 -0
  88. package/lib/yoke/claude-transcript-hygiene.js +34 -0
  89. package/lib/yoke/clay-skill-install.js +33 -0
  90. package/lib/yoke/cli-sessions.js +300 -0
  91. package/lib/yoke/codex-app-server.js +7 -12
  92. package/lib/yoke/configuration.js +13 -0
  93. package/lib/yoke/discovery.js +70 -0
  94. package/lib/yoke/errors.js +8 -0
  95. package/lib/yoke/host-environment.js +7 -0
  96. package/lib/yoke/index.js +9 -51
  97. package/lib/yoke/interface.js +116 -0
  98. package/lib/yoke/kiro-acp-server.js +5 -5
  99. package/lib/yoke/legacy-sessions.js +89 -0
  100. package/lib/yoke/login-protocol.js +25 -0
  101. package/lib/yoke/maintenance.js +12 -0
  102. package/lib/yoke/mcp-proxy.js +32 -0
  103. package/lib/yoke/mcp-source-adapters.js +91 -0
  104. package/lib/yoke/mcp-source-context.js +42 -0
  105. package/lib/yoke/mcp-source-discovery.js +169 -0
  106. package/lib/yoke/mcp-source-plugins.js +68 -0
  107. package/lib/yoke/mcp-source-restrictions.js +47 -0
  108. package/lib/yoke/mcp-tool-policy-normalize.js +28 -0
  109. package/lib/yoke/model-preferences.js +6 -0
  110. package/lib/yoke/muse-artifacts.js +36 -0
  111. package/lib/yoke/muse-controls.js +50 -0
  112. package/lib/yoke/muse-input.js +64 -0
  113. package/lib/yoke/muse-items.js +157 -0
  114. package/lib/yoke/muse-policy.js +52 -0
  115. package/lib/yoke/muse-query.js +428 -0
  116. package/lib/yoke/muse-runtime.js +211 -0
  117. package/lib/yoke/muse-services.js +79 -0
  118. package/lib/yoke/muse-skills.js +79 -0
  119. package/lib/yoke/muse-turns.js +71 -0
  120. package/lib/yoke/options/acp.js +2 -0
  121. package/lib/yoke/options/antigravity.js +2 -0
  122. package/lib/yoke/options/claude.js +21 -0
  123. package/lib/yoke/options/codex-defaults.js +29 -0
  124. package/lib/yoke/options/codex-settings.js +21 -0
  125. package/lib/yoke/options/codex.js +6 -0
  126. package/lib/yoke/options/kiro-defaults.js +22 -0
  127. package/lib/yoke/options/kiro.js +5 -0
  128. package/lib/yoke/options/muse.js +5 -0
  129. package/lib/yoke/provider-contract.js +5 -0
  130. package/lib/yoke/providers/antigravity-executable.js +8 -0
  131. package/lib/yoke/providers/claude-executable.js +40 -0
  132. package/lib/yoke/providers/claude-model-descriptions.js +14 -0
  133. package/lib/yoke/providers/claude-process.js +97 -0
  134. package/lib/yoke/providers/claude-provision.js +75 -0
  135. package/lib/yoke/providers/codex-errors.js +8 -0
  136. package/lib/yoke/providers/muse-executable.js +17 -0
  137. package/lib/yoke/provisioning.js +6 -0
  138. package/lib/yoke/query-options.js +10 -0
  139. package/lib/yoke/response-recovery.js +41 -0
  140. package/lib/yoke/sdk-mcp-descriptors.js +37 -0
  141. package/lib/yoke/sdk-server-factory.js +7 -0
  142. package/lib/yoke/session-history.js +8 -0
  143. package/lib/yoke/session-tool-transport.js +31 -13
  144. package/lib/yoke/settings.js +23 -0
  145. package/lib/yoke/source-locations.js +4 -0
  146. package/lib/yoke/title-query.js +18 -7
  147. package/lib/yoke/tui-transcript-index.js +132 -0
  148. package/lib/yoke/usage.js +48 -0
  149. package/lib/yoke/user-input.js +13 -0
  150. package/lib/yoke/vendor-registry.js +81 -1
  151. package/package.json +3 -2
@@ -1,267 +1 @@
1
- // claude-hook-installer.js
2
- //
3
- // Registers Clay's notification webhook in `~/.claude/settings.json` so the
4
- // `claude` CLI fires a request to the Clay daemon whenever it surfaces a
5
- // Notification (permission requests, idle prompts, etc.). This is what makes
6
- // TUI sessions feel like first-class Clay sessions: the user gets the same
7
- // toasts and push notifications they would in GUI mode.
8
- //
9
- // Design notes:
10
- // - Settings merge is idempotent: existing hooks are preserved, ours are
11
- // identified by a marker substring so re-runs don't duplicate them.
12
- // - The hook command uses curl with --max-time / --connect-timeout so that
13
- // a downed daemon can't stall claude's UI for more than ~1s.
14
- // - Multi-user mode: caller passes one home directory per OS user; we
15
- // write each user's own settings.json so per-user filtering works.
16
-
17
- var fs = require("fs");
18
- var path = require("path");
19
- var { buildClayBashAllowPatterns, isClayManagedBashPattern } = require("./safe-bash-commands");
20
-
21
- // Substring that uniquely identifies a Clay-installed hook entry so we can
22
- // safely remove/replace it without touching user-authored hooks.
23
- var CLAY_HOOK_MARKER = "clay:tui-notify";
24
-
25
- // Allow-patterns Clay manages in ~/.claude/settings.json `permissions.allow`.
26
- // The Bash(...) patterns are GENERATED from safe-bash-commands.js so this
27
- // list and sdk-bridge.js `checkToolWhitelist` can never drift - there is one
28
- // source of truth for which bash commands Clay auto-approves.
29
- //
30
- // Pattern syntax note: claude 2.x uses the space-wildcard form `Bash(cmd *)`
31
- // for prefix matching. The older colon form `Bash(cmd:*)` is flagged as
32
- // legacy in the CLI and no longer reliably matches argument-bearing commands
33
- // (the TUI kept prompting for read-only invocations like `ls -la`). The
34
- // generator emits the modern form plus a bare `Bash(cmd)` for zero-arg use.
35
- //
36
- // User-authored entries are preserved -- on re-install we only strip patterns
37
- // that are Clay-managed (current generated list or the legacy colon shape).
38
- var CLAY_MANAGED_ALLOW = [
39
- // Read-only built-in tools (no side effects).
40
- "Read", "Glob", "Grep", "WebFetch", "WebSearch",
41
-
42
- // Clay's own MCP servers. Strictly read/safe by design.
43
- "mcp__clay-browser__browser_watch_tab",
44
- "mcp__clay-browser__browser_unwatch_tab",
45
- "mcp__clay-debate__propose_debate",
46
- "mcp__clay-mate-creation__propose_mate",
47
- "mcp__clay-history__*",
48
- "mcp__clay-workspace__read_owner_screen",
49
- "mcp__clay-workspace__inspect_owner_screen_change",
50
- "mcp__clay-workspace__control_owner_screen",
51
- "mcp__clay-workspace__inspect_project_control",
52
- "mcp__clay-workspace__control_project_lifecycle",
53
- "mcp__clay-workspace__discover_product_controls",
54
- "mcp__clay-workspace__list_owned_mates",
55
- "mcp__clay-workspace__begin_schedule_control_interview",
56
- "mcp__clay-workspace__read_schedule_controls",
57
- "mcp__clay-workspace__inspect_schedule_change",
58
- "mcp__clay-workspace__control_schedules",
59
- "mcp__clay-workspace__read_mate_chat_control",
60
- "mcp__clay-workspace__inspect_mate_chat_change",
61
- "mcp__clay-workspace__control_mate_chat",
62
- "mcp__clay-workspace__read_project_workspace",
63
- "mcp__clay-workspace__read_workspace_receipt",
64
- "mcp__clay-workspace__inspect_workspace_change",
65
- "mcp__clay-workspace__control_project_workspace",
66
- "mcp__clay-workspace__read_project_records",
67
- "mcp__clay-workspace__inspect_project_record_change",
68
- "mcp__clay-workspace__control_project_records",
69
- "mcp__clay-workspace__read_mate_knowledge_control",
70
- "mcp__clay-workspace__inspect_mate_knowledge_change",
71
- "mcp__clay-workspace__control_mate_knowledge",
72
- "mcp__clay-workspace__inspect_mate_control",
73
- "mcp__clay-workspace__control_mate_lifecycle",
74
- "mcp__clay-workspace__inspect_session_control",
75
- "mcp__clay-workspace__control_project_session",
76
- "mcp__clay-workspace__list_projects",
77
- "mcp__clay-workspace__list_project_sessions",
78
- "mcp__clay-workspace__search_project_history",
79
- "mcp__clay-workspace__read_project_session",
80
- "mcp__clay-workspace__search_workspace_history",
81
- "mcp__clay-workspace__list_workspace_activity",
82
- "mcp__clay-workspace__propose_project_assignment",
83
- "mcp__clay-workspace__propose_project_follow_up",
84
- "mcp__clay-workspace__get_assignment_status",
85
- "mcp__clay-tools__clay_tool_list",
86
- "mcp__clay-tools__clay_tool_snapshot",
87
- "mcp__clay-tools__clay_tool_act",
88
- "mcp__clay-tools__clay_tool_set",
89
- "mcp__clay-tools__clay_tool_source",
90
- // Email: read-side only. Send / reply / mark_read still prompt.
91
- "mcp__clay-email__clay_read_email",
92
- "mcp__clay-email__clay_read_email_body",
93
- "mcp__clay-email__clay_search_email",
94
- "mcp__clay-email__clay_list_labels",
95
- ].concat(buildClayBashAllowPatterns());
96
-
97
- function buildHookCommand(notifyUrl) {
98
- // Read stdin once (the JSON Claude Code pipes in), then post it. --max-time
99
- // and --connect-timeout cap total hook latency around ~1s even if the
100
- // daemon is down. --insecure (-k) is needed because Clay's optional TLS
101
- // mode uses a locally generated CA that curl won't trust by default;
102
- // safe to skip verification since we're going to 127.0.0.1. Output is
103
- // silenced so it doesn't leak into the TUI. The marker comment keeps the
104
- // entry recognizable when we re-merge.
105
- var insecure = notifyUrl.indexOf("https://") === 0 ? " --insecure" : "";
106
- return "curl --silent --show-error --max-time 1 --connect-timeout 1" + insecure +
107
- " -X POST -H 'Content-Type: application/json' --data-binary @- " +
108
- JSON.stringify(notifyUrl) + " > /dev/null 2>&1 # " + CLAY_HOOK_MARKER;
109
- }
110
-
111
- function readSettings(settingsPath) {
112
- try {
113
- var raw = fs.readFileSync(settingsPath, "utf8");
114
- return JSON.parse(raw);
115
- } catch (e) {
116
- return {};
117
- }
118
- }
119
-
120
- function writeSettings(settingsPath, data) {
121
- var dir = path.dirname(settingsPath);
122
- try { fs.mkdirSync(dir, { recursive: true }); } catch (e) {}
123
- fs.writeFileSync(settingsPath, JSON.stringify(data, null, 2) + "\n");
124
- }
125
-
126
- // Merge our Notification hook into the user's settings.json without
127
- // clobbering anything else. Returns true if the file changed.
128
- function mergeHook(settingsPath, command) {
129
- var data = readSettings(settingsPath);
130
- if (!data.hooks || typeof data.hooks !== "object") data.hooks = {};
131
- if (!Array.isArray(data.hooks.Notification)) data.hooks.Notification = [];
132
-
133
- // Strip any prior Clay entries before inserting the fresh one so port /
134
- // URL changes propagate cleanly.
135
- var before = JSON.stringify(data.hooks.Notification);
136
- var cleaned = [];
137
- for (var i = 0; i < data.hooks.Notification.length; i++) {
138
- var group = data.hooks.Notification[i];
139
- if (!group || !Array.isArray(group.hooks)) { cleaned.push(group); continue; }
140
- var filtered = group.hooks.filter(function (h) {
141
- return !(h && typeof h.command === "string" && h.command.indexOf(CLAY_HOOK_MARKER) !== -1);
142
- });
143
- if (filtered.length > 0) cleaned.push({ matcher: group.matcher || "", hooks: filtered });
144
- else if (group.matcher) cleaned.push(group);
145
- }
146
- data.hooks.Notification = cleaned;
147
-
148
- data.hooks.Notification.push({
149
- matcher: "",
150
- hooks: [{ type: "command", command: command }],
151
- });
152
-
153
- var after = JSON.stringify(data.hooks.Notification);
154
- if (before === after) return false;
155
- writeSettings(settingsPath, data);
156
- return true;
157
- }
158
-
159
- /**
160
- * Install (or refresh) the Notification hook in one or more user home dirs.
161
- *
162
- * opts:
163
- * notifyUrl -- full URL Clay listens on, e.g. "http://127.0.0.1:2633/api/tui-notify".
164
- * homeDirs -- array of absolute paths to user home directories. Each one
165
- * gets its own settings.json updated. Defaults to [os.homedir()].
166
- *
167
- * Returns { installed: [paths], errors: [{path, error}] } so the caller can log.
168
- */
169
- function installNotificationHook(opts) {
170
- opts = opts || {};
171
- var os = require("os");
172
- var homes = opts.homeDirs && opts.homeDirs.length ? opts.homeDirs : [os.homedir()];
173
- var notifyUrl = opts.notifyUrl;
174
- if (!notifyUrl) throw new Error("installNotificationHook: notifyUrl is required");
175
-
176
- var command = buildHookCommand(notifyUrl);
177
- var installed = [];
178
- var errors = [];
179
- for (var i = 0; i < homes.length; i++) {
180
- var home = homes[i];
181
- if (!home) continue;
182
- var settingsPath = path.join(home, ".claude", "settings.json");
183
- try {
184
- var changed = mergeHook(settingsPath, command);
185
- if (changed) installed.push(settingsPath);
186
- } catch (e) {
187
- errors.push({ path: settingsPath, error: e && e.message ? e.message : String(e) });
188
- }
189
- }
190
- return { installed: installed, errors: errors };
191
- }
192
-
193
- // Old colon-prefix Bash patterns Clay wrote before claude 2.x: Bash(ls:*),
194
- // Bash(git status:*), etc. Stripped on upgrade so they don't linger next to
195
- // the modern space-wildcard form. Modern Clay patterns never contain ":)" so
196
- // this only catches the deprecated shape; it can't tell a user-authored colon
197
- // pattern apart, but claude is phasing the colon form out anyway.
198
- function isLegacyClayPattern(p) {
199
- if (typeof p !== "string") return false;
200
- if (p.indexOf("Bash(") === 0 && p.indexOf(":*)") !== -1) return true;
201
- return false;
202
- }
203
-
204
- // Merge Clay's managed allow-list into permissions.allow without disturbing
205
- // the user's own entries. "Ours" = exact membership in CLAY_MANAGED_ALLOW
206
- // (the non-Bash built-in / MCP entries) OR isClayManagedBashPattern (any
207
- // shape of a bash command we own, so stale variants from older versions get
208
- // swept) OR the legacy colon shape. Everything else is preserved, then the
209
- // fresh list is appended. Because the Bash patterns are generated from
210
- // safe-bash-commands.js, a re-install always writes the current set and can
211
- // never leave a stale Clay block behind.
212
- function mergeAllowList(settingsPath, patterns) {
213
- var data = readSettings(settingsPath);
214
- if (!data.permissions || typeof data.permissions !== "object") data.permissions = {};
215
- var allow = Array.isArray(data.permissions.allow) ? data.permissions.allow : [];
216
-
217
- var managedSet = {};
218
- for (var i = 0; i < CLAY_MANAGED_ALLOW.length; i++) managedSet[CLAY_MANAGED_ALLOW[i]] = true;
219
-
220
- var preserved = allow.filter(function (p) {
221
- if (managedSet[p]) return false;
222
- if (isClayManagedBashPattern(p)) return false;
223
- if (isLegacyClayPattern(p)) return false;
224
- return true;
225
- });
226
- var next = preserved.concat(patterns);
227
-
228
- var before = JSON.stringify(allow);
229
- var after = JSON.stringify(next);
230
- if (before === after) return false;
231
-
232
- data.permissions.allow = next;
233
- writeSettings(settingsPath, data);
234
- return true;
235
- }
236
-
237
- /**
238
- * Install (or refresh) Clay's auto-approve patterns into permissions.allow
239
- * for one or more user home dirs. Mirrors installNotificationHook's API.
240
- */
241
- function installAllowList(opts) {
242
- opts = opts || {};
243
- var os = require("os");
244
- var homes = opts.homeDirs && opts.homeDirs.length ? opts.homeDirs : [os.homedir()];
245
- var patterns = (opts.patterns && opts.patterns.length) ? opts.patterns : CLAY_MANAGED_ALLOW;
246
- var installed = [];
247
- var errors = [];
248
- for (var i = 0; i < homes.length; i++) {
249
- var home = homes[i];
250
- if (!home) continue;
251
- var settingsPath = path.join(home, ".claude", "settings.json");
252
- try {
253
- var changed = mergeAllowList(settingsPath, patterns);
254
- if (changed) installed.push(settingsPath);
255
- } catch (e) {
256
- errors.push({ path: settingsPath, error: e && e.message ? e.message : String(e) });
257
- }
258
- }
259
- return { installed: installed, errors: errors };
260
- }
261
-
262
- module.exports = {
263
- installNotificationHook: installNotificationHook,
264
- installAllowList: installAllowList,
265
- CLAY_HOOK_MARKER: CLAY_HOOK_MARKER,
266
- CLAY_MANAGED_ALLOW: CLAY_MANAGED_ALLOW,
267
- };
1
+ module.exports = require("./yoke/claude-hook-installer");
@@ -1,204 +1 @@
1
- // claude-jsonl-watcher.js
2
- //
3
- // Tails the per-session jsonl that Claude Code writes to
4
- // ~/.claude/projects/<encoded-cwd>/<cliSessionId>.jsonl, parsing new lines
5
- // for title events:
6
- //
7
- // {"type":"ai-title","aiTitle":"..."} - auto-generated after the
8
- // first exchange
9
- // {"type":"custom-title","customTitle":"..."} - explicit /title or
10
- // similar override
11
- //
12
- // Used by Clay TUI sessions to mirror claude's session naming into the
13
- // sidebar so they don't sit as "New Session" forever.
14
- //
15
- // Public API:
16
- // start(jsonlPath, onTitle) -> stop()
17
- // onTitle(title, source) where source is "ai-title" or "custom-title".
18
- // stop() detaches the watcher and clears any timer.
19
-
20
- var fs = require("fs");
21
- var path = require("path");
22
-
23
- function pickLatestTitle(lines, current) {
24
- // Walk lines in order; the final ai-title and custom-title win. Custom
25
- // beats ai because users explicitly chose it.
26
- var ai = current.aiTitle || null;
27
- var custom = current.customTitle || null;
28
- for (var i = 0; i < lines.length; i++) {
29
- var raw = lines[i].trim();
30
- if (!raw || raw[0] !== "{") continue;
31
- var obj = null;
32
- try { obj = JSON.parse(raw); } catch (e) { continue; }
33
- if (!obj || !obj.type) continue;
34
- if (obj.type === "ai-title" && typeof obj.aiTitle === "string") {
35
- ai = obj.aiTitle;
36
- } else if (obj.type === "custom-title" && typeof obj.customTitle === "string") {
37
- custom = obj.customTitle;
38
- }
39
- }
40
- current.aiTitle = ai;
41
- current.customTitle = custom;
42
- return custom || ai;
43
- }
44
-
45
- // Pull the latest visible "text" block from any new assistant entries.
46
- // Thinking and tool_use blocks are skipped - they're internals, not the
47
- // response surface. Returns the most recent text seen, or null.
48
- function extractLatestAssistantText(lines, seenUuids) {
49
- var latest = null;
50
- for (var i = 0; i < lines.length; i++) {
51
- var raw = lines[i].trim();
52
- if (!raw || raw[0] !== "{") continue;
53
- var obj = null;
54
- try { obj = JSON.parse(raw); } catch (e) { continue; }
55
- if (!obj || obj.type !== "assistant" || !obj.message) continue;
56
- if (obj.uuid && seenUuids[obj.uuid]) continue;
57
- if (obj.uuid) seenUuids[obj.uuid] = true;
58
- var blocks = obj.message.content || [];
59
- if (!Array.isArray(blocks)) continue;
60
- for (var j = 0; j < blocks.length; j++) {
61
- var b = blocks[j];
62
- if (b && b.type === "text" && typeof b.text === "string" && b.text.trim()) {
63
- latest = b.text;
64
- }
65
- }
66
- }
67
- return latest;
68
- }
69
-
70
- /**
71
- * Watch a Claude Code session jsonl for title and response updates.
72
- *
73
- * start(jsonlPath, { onTitle, onResponse }) -> stop()
74
- *
75
- * onTitle(text, source) fires on ai-title / custom-title updates.
76
- * onResponse(text) fires on new assistant text blocks (debounced so
77
- * a multi-block turn coalesces to one callback,
78
- * using only the *final* visible text). Pre-existing
79
- * entries from before start() are ignored - the
80
- * initial scan seeds the "seen" set so we don't
81
- * spam notifications when the watcher boots up.
82
- */
83
- function start(jsonlPath, opts) {
84
- if (!jsonlPath) return function () {};
85
- var onTitle = (opts && typeof opts.onTitle === "function") ? opts.onTitle : null;
86
- var onResponse = (opts && typeof opts.onResponse === "function") ? opts.onResponse : null;
87
- if (!onTitle && !onResponse) return function () {};
88
-
89
- var pos = 0;
90
- var leftover = "";
91
- var current = { aiTitle: null, customTitle: null };
92
- var lastTitleEmitted = null;
93
- var seenAssistantUuids = {};
94
- var didInitialScan = false;
95
- var responseDebounceTimer = null;
96
- var pendingResponseText = null;
97
- var lastResponseEmitted = null;
98
- var watcher = null;
99
- var pollTimer = null;
100
- var stopped = false;
101
-
102
- var RESPONSE_DEBOUNCE_MS = 1500;
103
- function maybeFireResponse() {
104
- if (responseDebounceTimer) clearTimeout(responseDebounceTimer);
105
- responseDebounceTimer = setTimeout(function () {
106
- responseDebounceTimer = null;
107
- if (!pendingResponseText) return;
108
- if (pendingResponseText === lastResponseEmitted) return;
109
- var t = pendingResponseText;
110
- pendingResponseText = null;
111
- lastResponseEmitted = t;
112
- try { if (onResponse) onResponse(t); } catch (e) {}
113
- }, RESPONSE_DEBOUNCE_MS);
114
- }
115
-
116
- function readNew() {
117
- if (stopped) return;
118
- try {
119
- var stat = fs.statSync(jsonlPath);
120
- if (stat.size <= pos) return;
121
- var fd = fs.openSync(jsonlPath, "r");
122
- var len = stat.size - pos;
123
- var buf = Buffer.alloc(len);
124
- fs.readSync(fd, buf, 0, len, pos);
125
- fs.closeSync(fd);
126
- pos = stat.size;
127
- var chunk = leftover + buf.toString("utf8");
128
- var parts = chunk.split("\n");
129
- // Last fragment may be a partial line; hold it for next read.
130
- leftover = parts.pop();
131
-
132
- // Title side: fire whenever we see a new value.
133
- if (onTitle) {
134
- var resolved = pickLatestTitle(parts, current);
135
- if (resolved && resolved !== lastTitleEmitted) {
136
- lastTitleEmitted = resolved;
137
- try { onTitle(resolved, current.customTitle === resolved ? "custom-title" : "ai-title"); } catch (e) {}
138
- }
139
- }
140
-
141
- // Response side: collect new assistant text blocks. Initial scan
142
- // seeds the "seen" set silently so old history doesn't fire.
143
- var latest = extractLatestAssistantText(parts, seenAssistantUuids);
144
- if (onResponse && didInitialScan && latest) {
145
- pendingResponseText = latest;
146
- maybeFireResponse();
147
- }
148
- } catch (e) {
149
- // File may not exist yet; readNew is called again on the next event.
150
- }
151
- }
152
-
153
- function arm() {
154
- if (stopped) return;
155
- if (watcher) return;
156
- try {
157
- watcher = fs.watch(jsonlPath, { persistent: false }, function () {
158
- readNew();
159
- });
160
- watcher.on("error", function () {
161
- try { watcher.close(); } catch (e) {}
162
- watcher = null;
163
- // Fall back to polling; some filesystems (network mounts) don't
164
- // deliver fs.watch events reliably.
165
- });
166
- } catch (e) {
167
- // Path doesn't exist yet; rely on the poll loop to retry once it appears.
168
- }
169
- }
170
-
171
- // Initial pass to capture anything already written before we attached.
172
- // didInitialScan stays false during this pass so onResponse doesn't fire
173
- // for old history; subsequent reads (live updates) will emit.
174
- readNew();
175
- didInitialScan = true;
176
- arm();
177
-
178
- // Poll every 2s as a safety net for fs.watch misses and for the
179
- // "file doesn't exist yet" boot case.
180
- pollTimer = setInterval(function () {
181
- if (!watcher) arm();
182
- readNew();
183
- }, 2000);
184
-
185
- return function stop() {
186
- stopped = true;
187
- if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
188
- if (responseDebounceTimer) { clearTimeout(responseDebounceTimer); responseDebounceTimer = null; }
189
- if (watcher) { try { watcher.close(); } catch (e) {} watcher = null; }
190
- };
191
- }
192
-
193
- // Resolve the jsonl path for a (cwd, cliSessionId) without depending on
194
- // utils.js so this module stays self-contained.
195
- function jsonlPathFor(home, cwd, cliSessionId) {
196
- if (!home || !cwd || !cliSessionId) return null;
197
- var encoded = cwd.replace(/[^a-zA-Z0-9]/g, "-");
198
- return path.join(home, ".claude", "projects", encoded, cliSessionId + ".jsonl");
199
- }
200
-
201
- module.exports = {
202
- start: start,
203
- jsonlPathFor: jsonlPathFor,
204
- };
1
+ module.exports = require("./yoke/claude-jsonl-watcher");
@@ -1,33 +1 @@
1
- // Runs under the requesting OS identity. The installer only sees a private staging project.
2
- var fs = require('fs');
3
- var path = require('path');
4
- var spawn = require('child_process').spawn;
5
- var storage = require('./clay-skill-storage');
6
- var base = process.argv[2];
7
- var name = process.argv[3];
8
- var url = process.argv[4];
9
- if (!storage.isClaySkill(name) || !/^https:\/\//i.test(url)) throw new Error('Invalid Clay skill install request');
10
- storage.directory(path.join(base, '.clay'));
11
- var stage = fs.mkdtempSync(path.join(base, '.clay', 'skill-install-'));
12
- var child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['skills', 'add', url, '--skill', name, '--yes', '--agent', 'claude-code'], { cwd: stage, stdio: 'inherit', env: process.env });
13
- function cleanup() { fs.rmSync(stage, { recursive: true, force: true }); }
14
- child.on('error', function (error) { console.error(error.message); cleanup(); process.exitCode = 1; });
15
- process.on('SIGTERM', function () { child.kill('SIGTERM'); });
16
- child.on('close', function (code) {
17
- try {
18
- if (code !== 0) throw new Error('Skill installer exited with code ' + code);
19
- var candidates = ['.agents', '.claude'].map(function (vendor) { return path.join(stage, vendor, 'skills', name); });
20
- var source = candidates.find(function (dir) { return fs.existsSync(path.join(dir, 'SKILL.md')); });
21
- if (!source) throw new Error('Installer did not create the requested skill in the private staging project');
22
- var root = storage.privateRoot(base); storage.directory(root);
23
- var destination = path.join(root, name);
24
- var pending = path.join(root, '.' + name + '-' + process.pid);
25
- fs.cpSync(source, pending, { recursive: true, dereference: true });
26
- if (fs.existsSync(destination)) {
27
- var backups = path.join(base, '.clay', 'skill-backups'); storage.directory(backups);
28
- fs.renameSync(destination, path.join(backups, name + '-' + Date.now()));
29
- }
30
- fs.renameSync(pending, destination);
31
- } catch (error) { console.error(error.message); process.exitCode = 1; }
32
- finally { cleanup(); }
33
- });
1
+ require("./yoke/clay-skill-install");