@jeffober/thatch 0.1.41 → 0.1.42
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/README.md +21 -11
- package/bin/release +4 -1
- package/bin/thatch +189 -33
- package/docs/dev/README.md +6 -4
- package/docs/dev/features/cli.md +20 -9
- package/docs/dev/features/cross-session-chat.md +125 -66
- package/docs/dev/features/multi-host.md +4 -3
- package/docs/dev/features/watchers.md +113 -23
- package/docs/dev/mcp-parity.md +1 -1
- package/docs/user/README.md +3 -2
- package/docs/user/cli.md +57 -9
- package/docs/user/cross-session-chat.md +72 -24
- package/docs/user/watchers.md +61 -16
- package/package.json +2 -1
- package/src/chat-names.ts +6 -7
- package/src/chat.ts +479 -148
- package/src/config.ts +34 -1
- package/src/db.ts +54 -6
- package/src/index.ts +87 -24
- package/src/prompts.ts +114 -50
- package/src/tool-defs.ts +294 -97
- package/src/tools.ts +2 -0
- package/src/watchers.ts +358 -23
package/src/tool-defs.ts
CHANGED
|
@@ -3,20 +3,24 @@ import type { ThatchDB, DedupCandidate, MemoryRow } from "./db";
|
|
|
3
3
|
import type { EmbeddingModel } from "./embeddings";
|
|
4
4
|
import {
|
|
5
5
|
CONFIG_SECTIONS,
|
|
6
|
+
chatEnabled,
|
|
7
|
+
chatPrefsSchema,
|
|
6
8
|
loadConfig,
|
|
9
|
+
mergeChatPrefs,
|
|
7
10
|
mergeNotificationPrefs,
|
|
8
11
|
notificationDefaults,
|
|
9
12
|
notificationPrefsSchema,
|
|
10
13
|
saveConfig,
|
|
14
|
+
type ChatPrefs,
|
|
11
15
|
type Config,
|
|
12
16
|
type ConfigSection,
|
|
13
17
|
type NotificationPrefs,
|
|
14
18
|
} from "./config";
|
|
15
19
|
import { sendNotification, defaultSpawner, type NotifyChannel, type Spawner } from "./notify";
|
|
16
|
-
import { predictionVerb } from "./prompts";
|
|
20
|
+
import { predictionVerb, chatInboxFrame } from "./prompts";
|
|
17
21
|
import { resolveOpencodeDbPath, SessionDB, partToTimelineEntry, partToFullJson, messageToFullJson } from "./session-db";
|
|
18
|
-
import { PR_EVENT_TYPES, BRANCH_EVENT_TYPES, type WatcherRegistry, type PrWatcherEventType, type BranchWatcherEventType } from "./watchers";
|
|
19
|
-
import { CHAT_STALE_MINUTES, isStale, renderChatParticipant,
|
|
22
|
+
import { PR_EVENT_TYPES, BRANCH_EVENT_TYPES, commandTargetLabel, type WatcherRegistry, type PrWatcherEventType, type BranchWatcherEventType } from "./watchers";
|
|
23
|
+
import { CHAT_STALE_MINUTES, isStale, renderChatParticipant, type ChatHostKind } from "./chat";
|
|
20
24
|
|
|
21
25
|
// Near-duplicate thresholds for matcher/prediction/behavior dedup at
|
|
22
26
|
// creation time. Matches the thatch_find_duplicates threshold (0.85).
|
|
@@ -75,6 +79,9 @@ export interface CoreContext {
|
|
|
75
79
|
* path - MCP hosts have no poller, no event bus, and no way to deliver a
|
|
76
80
|
* proactive prompt, so watch tools are opencode-only. */
|
|
77
81
|
watchers?: WatcherRegistry;
|
|
82
|
+
/** The plugin host's project directory. Command watchers run their
|
|
83
|
+
* commands here. Only wired on the opencode path, alongside watchers. */
|
|
84
|
+
projectDir?: string;
|
|
78
85
|
/** Injectable command runner for notify_user. Defaults to Bun.spawn.
|
|
79
86
|
* Tests inject a mock so notifications never actually fire or speak. */
|
|
80
87
|
spawner?: Spawner;
|
|
@@ -891,6 +898,15 @@ function renderNotificationSection(prefs: NotificationPrefs | undefined): string
|
|
|
891
898
|
return lines.join("\n");
|
|
892
899
|
}
|
|
893
900
|
|
|
901
|
+
/** Renders the chat section. Both fields default to on. */
|
|
902
|
+
function renderChatSection(prefs: ChatPrefs | undefined): string {
|
|
903
|
+
return [
|
|
904
|
+
"chat:",
|
|
905
|
+
` enabled: ${prefs?.enabled ?? "<unset>"} (default: on)`,
|
|
906
|
+
` autoRegister: ${prefs?.autoRegister ?? "<unset>"} (default: on; opencode sessions join the chat directory automatically)`,
|
|
907
|
+
].join("\n");
|
|
908
|
+
}
|
|
909
|
+
|
|
894
910
|
/** Drops keys explicitly set to undefined so a merge never overwrites. */
|
|
895
911
|
function stripUndefined(obj: Record<string, unknown>): Record<string, unknown> {
|
|
896
912
|
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
|
|
@@ -904,7 +920,7 @@ const configGetDef: ToolDef = {
|
|
|
904
920
|
"The config file (~/.config/thatch/config.json, beside thatch.db) is " +
|
|
905
921
|
"also hand-editable. Call this before config_set.",
|
|
906
922
|
args: {
|
|
907
|
-
section: z.enum(["notifications"]).optional().describe(
|
|
923
|
+
section: z.enum(["notifications", "chat"]).optional().describe(
|
|
908
924
|
"Restrict output to one section. Omit to read all sections.",
|
|
909
925
|
),
|
|
910
926
|
},
|
|
@@ -919,6 +935,9 @@ const configGetDef: ToolDef = {
|
|
|
919
935
|
if (name === "notifications") {
|
|
920
936
|
lines.push(renderNotificationSection(loaded.config.notifications));
|
|
921
937
|
}
|
|
938
|
+
if (name === "chat") {
|
|
939
|
+
lines.push(renderChatSection(loaded.config.chat));
|
|
940
|
+
}
|
|
922
941
|
}
|
|
923
942
|
lines.push("", `file: ${loaded.path}`);
|
|
924
943
|
return lines.join("\n");
|
|
@@ -950,24 +969,50 @@ const configSetDef: ToolDef = {
|
|
|
950
969
|
"Notification preferences to update. Fields you omit keep their " +
|
|
951
970
|
"current values.",
|
|
952
971
|
),
|
|
972
|
+
chat: z.strictObject({
|
|
973
|
+
enabled: z.boolean().optional().describe(
|
|
974
|
+
"Cross-session chat on/off. Unset or true is the default; false " +
|
|
975
|
+
"makes every chat tool refuse and stops wake delivery.",
|
|
976
|
+
),
|
|
977
|
+
autoRegister: z.boolean().optional().describe(
|
|
978
|
+
"Whether opencode sessions join the chat directory automatically " +
|
|
979
|
+
"(assigned names). Unset or true is the default; false restores " +
|
|
980
|
+
"opt-in joining via chat_register only.",
|
|
981
|
+
),
|
|
982
|
+
}).optional().describe(
|
|
983
|
+
"Chat preferences to update. Fields you omit keep their current " +
|
|
984
|
+
"values.",
|
|
985
|
+
),
|
|
953
986
|
},
|
|
954
987
|
async execute(args) {
|
|
955
988
|
const loaded = loadConfig();
|
|
956
989
|
const config: Config = { ...loaded.config };
|
|
957
|
-
const
|
|
958
|
-
|
|
990
|
+
const notifPatch = args.notifications as Record<string, unknown> | undefined;
|
|
991
|
+
const chatPatch = args.chat as Record<string, unknown> | undefined;
|
|
992
|
+
const notifClean = notifPatch ? stripUndefined(notifPatch) : {};
|
|
993
|
+
const chatClean = chatPatch ? stripUndefined(chatPatch) : {};
|
|
994
|
+
if (Object.keys(notifClean).length === 0 && Object.keys(chatClean).length === 0) {
|
|
959
995
|
return (
|
|
960
996
|
"Nothing to update: pass a section with fields to change.\n" +
|
|
961
|
-
renderNotificationSection(config.notifications)
|
|
997
|
+
renderNotificationSection(config.notifications) + "\n" +
|
|
998
|
+
renderChatSection(config.chat)
|
|
999
|
+
);
|
|
1000
|
+
}
|
|
1001
|
+
if (Object.keys(notifClean).length > 0) {
|
|
1002
|
+
config.notifications = notificationPrefsSchema.parse(
|
|
1003
|
+
mergeNotificationPrefs(config.notifications, notifClean),
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
if (Object.keys(chatClean).length > 0) {
|
|
1007
|
+
config.chat = chatPrefsSchema.parse(
|
|
1008
|
+
mergeChatPrefs(config.chat, chatClean),
|
|
962
1009
|
);
|
|
963
1010
|
}
|
|
964
|
-
config.notifications = notificationPrefsSchema.parse(
|
|
965
|
-
mergeNotificationPrefs(config.notifications, stripUndefined(patch)),
|
|
966
|
-
);
|
|
967
1011
|
const path = saveConfig(config);
|
|
968
1012
|
return (
|
|
969
1013
|
`[saved] ${path}\n` +
|
|
970
|
-
renderNotificationSection(config.notifications)
|
|
1014
|
+
(Object.keys(notifClean).length > 0 ? renderNotificationSection(config.notifications) + "\n" : "") +
|
|
1015
|
+
(Object.keys(chatClean).length > 0 ? renderChatSection(config.chat) : "")
|
|
971
1016
|
);
|
|
972
1017
|
},
|
|
973
1018
|
};
|
|
@@ -1166,14 +1211,17 @@ const watchCreateDef: ToolDef = {
|
|
|
1166
1211
|
name: "watch_create",
|
|
1167
1212
|
description:
|
|
1168
1213
|
"Watch a GitHub PR for events and get notified in this session when they " +
|
|
1169
|
-
"happen
|
|
1170
|
-
"
|
|
1171
|
-
"
|
|
1172
|
-
"
|
|
1173
|
-
"
|
|
1174
|
-
"
|
|
1175
|
-
"
|
|
1176
|
-
"
|
|
1214
|
+
"happen: new top-level comments, inline review comments and replies, " +
|
|
1215
|
+
"review thread resolutions, new commits (head SHA change), PR status " +
|
|
1216
|
+
"changes, title/description edits, and completed CI check runs. For CI " +
|
|
1217
|
+
"waits: a short bounded wait (about 2-3 minutes) is fine as a single " +
|
|
1218
|
+
"in-turn gh poll; for longer or unknown waits, use this watcher instead " +
|
|
1219
|
+
"of sleep-polling. The watcher polls about every 60s by default - the " +
|
|
1220
|
+
"first check lands within ~60s of creation. Notifications carry a short " +
|
|
1221
|
+
"machine summary (event type, actor, and for CI the check name and " +
|
|
1222
|
+
"conclusion); use the gh CLI only for logs and further details. Watches " +
|
|
1223
|
+
"live until cancelled, the session ends, or opencode restarts. Requires " +
|
|
1224
|
+
"the gh CLI.",
|
|
1177
1225
|
args: {
|
|
1178
1226
|
pr: z.number().int().positive().describe(
|
|
1179
1227
|
"The PR number to watch.",
|
|
@@ -1184,6 +1232,11 @@ const watchCreateDef: ToolDef = {
|
|
|
1184
1232
|
events: z.array(z.enum(PR_EVENT_TYPES as [PrWatcherEventType, ...PrWatcherEventType[]])).optional().describe(
|
|
1185
1233
|
"Which event types to watch. Omit for all PR event types.",
|
|
1186
1234
|
),
|
|
1235
|
+
once: z.boolean().optional().describe(
|
|
1236
|
+
"Fire only once: after the first matching event happens, the watcher " +
|
|
1237
|
+
"cancels itself. Use for one-shot waits like 'tell me when this run " +
|
|
1238
|
+
"finishes'. Default false - a standing watch.",
|
|
1239
|
+
),
|
|
1187
1240
|
},
|
|
1188
1241
|
opencodeOnly: true,
|
|
1189
1242
|
async execute(args, ctx, host) {
|
|
@@ -1195,18 +1248,21 @@ const watchCreateDef: ToolDef = {
|
|
|
1195
1248
|
}
|
|
1196
1249
|
const repo = (args.repo as string | undefined) ?? ctx.defaultStore;
|
|
1197
1250
|
const events = (args.events as PrWatcherEventType[] | undefined) ?? [...PR_EVENT_TYPES];
|
|
1198
|
-
const result = await ctx.watchers.createPr(host.sessionID, repo, args.pr as number, events);
|
|
1251
|
+
const result = await ctx.watchers.createPr(host.sessionID, repo, args.pr as number, events, { once: args.once === true });
|
|
1199
1252
|
if (!result.ok) return `Watcher not created: ${result.error}`;
|
|
1200
1253
|
const w = result.watcher;
|
|
1201
1254
|
return (
|
|
1202
1255
|
`[watching] ${w.repo}#${w.pr}\n` +
|
|
1203
1256
|
`id: ${w.id}\n` +
|
|
1204
1257
|
`events: ${w.events.join(", ")}\n` +
|
|
1258
|
+
(w.once ? `mode: one-shot - auto-cancels after the first event\n` : "") +
|
|
1205
1259
|
`head: ${w.state.headSha.slice(0, 7)} (${w.state.state}${w.state.merged ? ", merged" : ""})\n\n` +
|
|
1206
|
-
`The baseline is captured now - only changes from this point notify
|
|
1260
|
+
`The baseline is captured now - only changes from this point notify, ` +
|
|
1261
|
+
`and the first poll lands within ~${ctx.watchers.pollSeconds}s. ` +
|
|
1207
1262
|
`You will receive a system notification in this session when a watched event happens. ` +
|
|
1208
|
-
`State any handling policy for those notifications now (e.g. what to act on, what just to report)
|
|
1209
|
-
`
|
|
1263
|
+
`State any handling policy for those notifications now (e.g. what to act on, what just to report) - ` +
|
|
1264
|
+
`the notification carries a short machine summary (for CI: check name and conclusion), ` +
|
|
1265
|
+
`and you fetch details with the gh CLI only when you decide to act.`
|
|
1210
1266
|
);
|
|
1211
1267
|
},
|
|
1212
1268
|
};
|
|
@@ -1234,8 +1290,11 @@ const watchListDef: ToolDef = {
|
|
|
1234
1290
|
const minutesLeft = (w: { expiresAt: number }) => Math.max(0, Math.round((w.expiresAt - Date.now()) / 60_000));
|
|
1235
1291
|
return watchers
|
|
1236
1292
|
.map((w) => {
|
|
1293
|
+
if (w.source === "command") {
|
|
1294
|
+
return `${w.id}: cmd: ${commandTargetLabel(w.command)} [${w.source}]${w.once ? " [once]" : ""} events=[${w.events.join(",")}] expires in ${minutesLeft(w)}m lastExit=${w.state.lastExit}`;
|
|
1295
|
+
}
|
|
1237
1296
|
const target = w.source === "pr" ? `${w.repo}#${w.pr}` : `${w.repo}@${w.branch}`;
|
|
1238
|
-
return `${w.id}: ${target} [${w.source}] events=[${w.events.join(",")}] expires in ${minutesLeft(w)}m head=${w.state.headSha.slice(0, 7)}`;
|
|
1297
|
+
return `${w.id}: ${target} [${w.source}]${w.once ? " [once]" : ""} events=[${w.events.join(",")}] expires in ${minutesLeft(w)}m head=${w.state.headSha.slice(0, 7)}`;
|
|
1239
1298
|
})
|
|
1240
1299
|
.join("\n");
|
|
1241
1300
|
},
|
|
@@ -1254,10 +1313,15 @@ const watchBranchCreateDef: ToolDef = {
|
|
|
1254
1313
|
"when things happen on it: branch_commit when new commits land (e.g. a " +
|
|
1255
1314
|
"PR merged), branch_ci when a check run on the head completes, and " +
|
|
1256
1315
|
"branch_workflow when a GitHub Actions workflow run starts or finishes " +
|
|
1257
|
-
"on the branch.
|
|
1258
|
-
"
|
|
1259
|
-
"
|
|
1260
|
-
"
|
|
1316
|
+
"on the branch. This is how you watch CI against main or wait for a " +
|
|
1317
|
+
"post-merge build. For CI waits: a short bounded wait (about 2-3 " +
|
|
1318
|
+
"minutes) is fine as a single in-turn gh poll; for longer or unknown " +
|
|
1319
|
+
"waits, use this watcher instead of sleep-polling. Optionally filter to " +
|
|
1320
|
+
"workflow names (substring match). The watcher polls about every 60s by " +
|
|
1321
|
+
"default - the first check lands within ~60s of creation. Notifications " +
|
|
1322
|
+
"carry a short machine summary (event type, and for CI and workflow " +
|
|
1323
|
+
"runs the name and conclusion); use the gh CLI only for logs and " +
|
|
1324
|
+
"further details. Watches live until cancelled, the session ends, or " +
|
|
1261
1325
|
"opencode restarts. Requires the gh CLI.",
|
|
1262
1326
|
args: {
|
|
1263
1327
|
branch: z.string().describe(
|
|
@@ -1272,6 +1336,11 @@ const watchBranchCreateDef: ToolDef = {
|
|
|
1272
1336
|
workflows: z.array(z.string()).optional().describe(
|
|
1273
1337
|
"Only notify for workflow runs whose name contains one of these substrings (case-insensitive). Omit for all workflows.",
|
|
1274
1338
|
),
|
|
1339
|
+
once: z.boolean().optional().describe(
|
|
1340
|
+
"Fire only once: after the first matching event happens, the watcher " +
|
|
1341
|
+
"cancels itself. Use for one-shot waits like 'tell me when this run " +
|
|
1342
|
+
"finishes'. Default false - a standing watch.",
|
|
1343
|
+
),
|
|
1275
1344
|
},
|
|
1276
1345
|
opencodeOnly: true,
|
|
1277
1346
|
async execute(args, ctx, host) {
|
|
@@ -1289,6 +1358,7 @@ const watchBranchCreateDef: ToolDef = {
|
|
|
1289
1358
|
args.branch as string,
|
|
1290
1359
|
events,
|
|
1291
1360
|
(args.workflows as string[] | undefined) ?? [],
|
|
1361
|
+
{ once: args.once === true },
|
|
1292
1362
|
);
|
|
1293
1363
|
if (!result.ok) return `Watcher not created: ${result.error}`;
|
|
1294
1364
|
const w = result.watcher;
|
|
@@ -1297,11 +1367,84 @@ const watchBranchCreateDef: ToolDef = {
|
|
|
1297
1367
|
`id: ${w.id}\n` +
|
|
1298
1368
|
`events: ${w.events.join(", ")}\n` +
|
|
1299
1369
|
(w.workflows.length > 0 ? `workflow filter: ${w.workflows.join(", ")}\n` : "") +
|
|
1370
|
+
(w.once ? `mode: one-shot - auto-cancels after the first event\n` : "") +
|
|
1300
1371
|
`head: ${w.state.headSha.slice(0, 7)}\n\n` +
|
|
1301
|
-
`The baseline is captured now - only changes from this point notify
|
|
1372
|
+
`The baseline is captured now - only changes from this point notify, ` +
|
|
1373
|
+
`and the first poll lands within ~${ctx.watchers.pollSeconds}s. ` +
|
|
1302
1374
|
`You will receive a system notification in this session when a watched event happens. ` +
|
|
1303
|
-
`State any handling policy for those notifications now (e.g. what to act on, what just to report)
|
|
1304
|
-
`
|
|
1375
|
+
`State any handling policy for those notifications now (e.g. what to act on, what just to report) - ` +
|
|
1376
|
+
`the notification carries a short machine summary (for CI: check name and conclusion), ` +
|
|
1377
|
+
`and you fetch details with the gh CLI only when you decide to act.`
|
|
1378
|
+
);
|
|
1379
|
+
},
|
|
1380
|
+
};
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* Registers a background watcher on a local shell command. The command is a
|
|
1384
|
+
* CONDITION VARIABLE, not a data pipe: the poller re-runs it every cycle and
|
|
1385
|
+
* reads only its exit code - stdout and stderr are discarded, never delivered.
|
|
1386
|
+
* The session gets one synthetic notification the first time the command
|
|
1387
|
+
* exits 0, and the watcher cancels itself. This is the generic "wait for an
|
|
1388
|
+
* arbitrary condition" escape hatch: wait for a marker file, an endpoint to
|
|
1389
|
+
* come up, a lock to clear. opencode-only, like the other watch tools.
|
|
1390
|
+
* Requires bash, not the gh CLI.
|
|
1391
|
+
*/
|
|
1392
|
+
const watchCommandCreateDef: ToolDef = {
|
|
1393
|
+
name: "watch_command_create",
|
|
1394
|
+
description:
|
|
1395
|
+
"Register a local shell command as a background condition and get " +
|
|
1396
|
+
"notified in this session when it first exits 0. THE COMMAND IS A " +
|
|
1397
|
+
"CONDITION VARIABLE, NOT A DATA PIPE: the watcher only reads its exit " +
|
|
1398
|
+
"code - stdout and stderr are discarded, never returned to you. Write " +
|
|
1399
|
+
"the command as a fast, idempotent status check (exit 0 = the wait is " +
|
|
1400
|
+
"over) such as 'test -f marker', 'curl -sf endpoint >/dev/null', or a " +
|
|
1401
|
+
"'gh run list --json' query - NOT a command whose output you want, and " +
|
|
1402
|
+
"NOT a blocking wait (no 'gh run watch', 'tail -f', or 'sleep': the " +
|
|
1403
|
+
"per-run timeout kills a blocking command each cycle, wasting up to " +
|
|
1404
|
+
"30s of the shared poll cycle on a check that can never succeed). " +
|
|
1405
|
+
"Use this for long or unknown-duration waits on any local condition " +
|
|
1406
|
+
"instead of sleep-polling. The command runs in this project directory " +
|
|
1407
|
+
"via bash -c about every 60s, killed at a 30s per-run timeout " +
|
|
1408
|
+
"(THATCH_WATCH_COMMAND_TIMEOUT_SECONDS overrides; a timed-out run " +
|
|
1409
|
+
"means not-done-yet). One-shot by design: it fires once on the first " +
|
|
1410
|
+
"exit 0, auto-cancels, and the notification carries only the exit code " +
|
|
1411
|
+
"and duration - re-run the command or read logs yourself if you need " +
|
|
1412
|
+
"details. The command runs once at registration as validation: if it " +
|
|
1413
|
+
"already exits 0 the watcher is refused (the condition is already met - " +
|
|
1414
|
+
"proceed instead), and a command-not-found (exit 127) is refused too. " +
|
|
1415
|
+
"Counts against the per-session watcher limit; expires with the " +
|
|
1416
|
+
"session's other watchers.",
|
|
1417
|
+
args: {
|
|
1418
|
+
command: z.string().min(1).describe(
|
|
1419
|
+
"The shell command to run as a condition: a fast, idempotent status " +
|
|
1420
|
+
"check that exits 0 when the wait is over. Its output is discarded.",
|
|
1421
|
+
),
|
|
1422
|
+
},
|
|
1423
|
+
opencodeOnly: true,
|
|
1424
|
+
async execute(args, ctx, host) {
|
|
1425
|
+
if (!host) {
|
|
1426
|
+
return "Watching is unavailable: this host did not provide a session context.";
|
|
1427
|
+
}
|
|
1428
|
+
if (!ctx.watchers) {
|
|
1429
|
+
return "Watching is unavailable: no watcher registry was wired by this host.";
|
|
1430
|
+
}
|
|
1431
|
+
if (!ctx.projectDir) {
|
|
1432
|
+
return "Watching is unavailable: no project directory was wired by this host.";
|
|
1433
|
+
}
|
|
1434
|
+
const command = args.command as string;
|
|
1435
|
+
const result = await ctx.watchers.createCommand(host.sessionID, command, ctx.projectDir);
|
|
1436
|
+
if (!result.ok) return `Watcher not created: ${result.error}`;
|
|
1437
|
+
const w = result.watcher;
|
|
1438
|
+
return (
|
|
1439
|
+
`[watching] cmd: ${commandTargetLabel(w.command)}\n` +
|
|
1440
|
+
`id: ${w.id}\n` +
|
|
1441
|
+
`mode: one-shot - fires on the first exit 0, then auto-cancels\n` +
|
|
1442
|
+
`lastExit: ${w.state.lastExit} (baseline exit code; 124 = the baseline run was killed at the timeout)\n\n` +
|
|
1443
|
+
`The command re-runs about every ${ctx.watchers.pollSeconds}s and the first check already happened at registration - ` +
|
|
1444
|
+
`the next run lands within ~${ctx.watchers.pollSeconds}s. ` +
|
|
1445
|
+
`You will receive a system notification when the command exits 0; it carries the exit code and duration only. ` +
|
|
1446
|
+
`State any handling policy for that notification now (e.g. what to do once the condition is met) - ` +
|
|
1447
|
+
`the notification is the signal, not the data: re-run the command or read logs yourself when it arrives.`
|
|
1305
1448
|
);
|
|
1306
1449
|
},
|
|
1307
1450
|
};
|
|
@@ -1314,7 +1457,7 @@ const watchCancelDef: ToolDef = {
|
|
|
1314
1457
|
name: "watch_cancel",
|
|
1315
1458
|
description: "Cancel one of this session's watchers by id. opencode-only.",
|
|
1316
1459
|
args: {
|
|
1317
|
-
id: z.string().describe("The watcher id from watch_create, watch_branch_create, or watch_list."),
|
|
1460
|
+
id: z.string().describe("The watcher id from watch_create, watch_branch_create, watch_command_create, or watch_list."),
|
|
1318
1461
|
},
|
|
1319
1462
|
opencodeOnly: true,
|
|
1320
1463
|
async execute(args, ctx, host) {
|
|
@@ -1351,6 +1494,18 @@ const watchCancelDef: ToolDef = {
|
|
|
1351
1494
|
* the same change as chatEchoText and its tests.
|
|
1352
1495
|
*/
|
|
1353
1496
|
|
|
1497
|
+
/**
|
|
1498
|
+
* Refusal text when the user disabled cross-session chat by config. Every
|
|
1499
|
+
* chat tool returns this so the model can report the toggle to the user
|
|
1500
|
+
* instead of concluding the feature is broken.
|
|
1501
|
+
*/
|
|
1502
|
+
function chatDisabledReply(): string {
|
|
1503
|
+
return (
|
|
1504
|
+
"[disabled] Cross-session chat is off (chat.enabled: false in the thatch config). " +
|
|
1505
|
+
"Use thatch config_set { chat: { enabled: true } } to re-enable if the user asks."
|
|
1506
|
+
);
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1354
1509
|
/**
|
|
1355
1510
|
* Resolves the chat identity for a tool call. opencode supplies the host
|
|
1356
1511
|
* session; MCP hosts (host === undefined) declare theirs with the `as`
|
|
@@ -1362,6 +1517,9 @@ async function resolveChatIdentity(
|
|
|
1362
1517
|
host: HostToolContext | undefined,
|
|
1363
1518
|
as: unknown,
|
|
1364
1519
|
): Promise<{ ok: true; sessionID: string; kind: ChatHostKind } | { ok: false; error: string }> {
|
|
1520
|
+
if (!chatEnabled(loadConfig().config)) {
|
|
1521
|
+
return { ok: false, error: chatDisabledReply() };
|
|
1522
|
+
}
|
|
1365
1523
|
if (host) return { ok: true, sessionID: host.sessionID, kind: "opencode" };
|
|
1366
1524
|
if (typeof as !== "string" || !as.trim()) {
|
|
1367
1525
|
return {
|
|
@@ -1381,98 +1539,119 @@ async function resolveChatIdentity(
|
|
|
1381
1539
|
}
|
|
1382
1540
|
|
|
1383
1541
|
/** The zod arg shared by chat tools whose MCP mode needs the caller's
|
|
1384
|
-
*
|
|
1385
|
-
*
|
|
1542
|
+
* assigned name: MCP hosts have no session context, so identity is passed
|
|
1543
|
+
* as the name the host's thatch hook printed (names are assigned by
|
|
1544
|
+
* thatch, never claimed). opencode ignores it. */
|
|
1386
1545
|
function mcpIdentityArg() {
|
|
1387
1546
|
return z.string().optional().describe(
|
|
1388
|
-
"Your
|
|
1547
|
+
"Your assigned display name - the one your host's thatch hook printed, " +
|
|
1548
|
+
"or that chat_register returned. Only needed on hosts without session " +
|
|
1389
1549
|
"context (Claude Code, Cursor); opencode supplies your identity itself.",
|
|
1390
1550
|
);
|
|
1391
1551
|
}
|
|
1392
1552
|
|
|
1393
|
-
/**
|
|
1394
|
-
*
|
|
1553
|
+
/**
|
|
1554
|
+
* The delivery-model notes appended to registration output, one per host
|
|
1555
|
+
* kind. Without these a session has no way to learn how mail reaches it,
|
|
1556
|
+
* and defaults to sleep-polling its inbox. The wake prompt is an opencode
|
|
1557
|
+
* capability; other hosts learn about pending mail at their next prompt.
|
|
1558
|
+
*/
|
|
1559
|
+
function wakeDeliveryNote(): string {
|
|
1560
|
+
return "\nDelivery: you are woken automatically in this session when a message arrives - no need to poll (a busy session gets the wake when its turn ends).\n";
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1395
1563
|
function degradedDeliveryNote(): string {
|
|
1396
|
-
return "\
|
|
1564
|
+
return "\nDelivery: wake-up is opencode-only; on this host pending mail is reported at your next prompt (chat_read, chat_status, or the flush-tools hook line).\n";
|
|
1397
1565
|
}
|
|
1398
1566
|
|
|
1399
1567
|
/**
|
|
1400
|
-
* Joins the chat directory
|
|
1401
|
-
*
|
|
1402
|
-
*
|
|
1403
|
-
*
|
|
1568
|
+
* Joins the chat directory (or reports/renews an existing registration).
|
|
1569
|
+
* Names are assigned by thatch, never claimed: there is no name or topic
|
|
1570
|
+
* argument, and registration is the gate for both directions. MCP hosts
|
|
1571
|
+
* without a hook-printed name get a fresh per-conversation identity.
|
|
1404
1572
|
*/
|
|
1405
1573
|
const chatRegisterDef: ToolDef = {
|
|
1406
1574
|
name: "chat_register",
|
|
1407
1575
|
description:
|
|
1408
1576
|
"Join the cross-session chat directory so other sessions on this " +
|
|
1409
1577
|
"machine can message you and you can message them (works from opencode, " +
|
|
1410
|
-
"Claude Code, and Cursor).
|
|
1411
|
-
"
|
|
1412
|
-
"
|
|
1413
|
-
"
|
|
1414
|
-
"
|
|
1415
|
-
"
|
|
1416
|
-
"
|
|
1417
|
-
"
|
|
1578
|
+
"Claude Code, and Cursor). Display names are assigned by thatch, never " +
|
|
1579
|
+
"chosen: a slug plus a never-reused counter (the slug comes from your " +
|
|
1580
|
+
"session title when one exists, otherwise from a built-in pool), so a " +
|
|
1581
|
+
"name always refers to the same session and cannot be claimed by anyone " +
|
|
1582
|
+
"else. Call with no arguments to join, to rejoin after chat_unregister, " +
|
|
1583
|
+
"or to check your assigned name (opencode sessions are usually " +
|
|
1584
|
+
"registered automatically already). On hosts without session context, " +
|
|
1585
|
+
"pass `as` with the name your thatch hook printed for you, or omit it " +
|
|
1586
|
+
"to be assigned a fresh identity for this conversation. Delivery: " +
|
|
1587
|
+
"opencode sessions are woken automatically when mail arrives; on other " +
|
|
1588
|
+
"hosts pending mail is reported at your next prompt. Only top-level " +
|
|
1589
|
+
"sessions should register; never register a sub-agent session.",
|
|
1418
1590
|
args: {
|
|
1419
|
-
name: z.string().optional().describe(
|
|
1420
|
-
"Custom display name. Omit to draw one from the built-in name pool.",
|
|
1421
|
-
),
|
|
1422
|
-
topic: z.string().optional().describe(
|
|
1423
|
-
"One line about what this session is working on (shown to other " +
|
|
1424
|
-
"sessions in chat_list). Omit on re-register to keep the existing " +
|
|
1425
|
-
"topic; pass an empty string to clear it.",
|
|
1426
|
-
),
|
|
1427
1591
|
as: mcpIdentityArg(),
|
|
1428
1592
|
},
|
|
1429
1593
|
async execute(args, ctx, host) {
|
|
1430
|
-
|
|
1431
|
-
const topic = typeof args.topic === "string" ? args.topic : null;
|
|
1594
|
+
if (!chatEnabled(loadConfig().config)) return chatDisabledReply();
|
|
1432
1595
|
const kind: ChatHostKind = host ? "opencode" : "mcp";
|
|
1433
|
-
// MCP
|
|
1434
|
-
//
|
|
1435
|
-
//
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1596
|
+
// MCP reclaim: `as` must name an EXISTING registration - the identity
|
|
1597
|
+
// printed by the host's thatch hook for this conversation. Names are
|
|
1598
|
+
// assigned, so there is no claim path; a stale name from an old
|
|
1599
|
+
// conversation still resolves to the same row it always did.
|
|
1600
|
+
const asName = host ? null : typeof args.as === "string" ? args.as.trim() : null;
|
|
1601
|
+
if (!host && !asName) {
|
|
1602
|
+
// Fresh identity for this conversation: without session context or a
|
|
1603
|
+
// hook-printed name there is nothing stable to anchor to, and a new
|
|
1604
|
+
// conversation is a new peer anyway. Persistent identity on MCP hosts
|
|
1605
|
+
// comes from the hook, which re-registers the same session ID and
|
|
1606
|
+
// prints the assigned name each prompt.
|
|
1607
|
+
const sessionID = `mcp_${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
|
|
1608
|
+
const res = ctx.db.registerChatSession(sessionID, ctx.defaultStore, null, kind);
|
|
1609
|
+
if (!res.ok) return `Registration failed: ${res.error}`;
|
|
1440
1610
|
return (
|
|
1441
|
-
`[registered] ${
|
|
1611
|
+
`[registered] ${res.name}\n` +
|
|
1442
1612
|
`session_id: ${sessionID}\n` +
|
|
1443
1613
|
`project: ${ctx.defaultStore}\n` +
|
|
1444
|
-
|
|
1445
|
-
// confirmation shows the roster value, not the raw input.
|
|
1446
|
-
(result.topic ? `topic: ${result.topic}\n` : "") +
|
|
1447
|
-
(host ? "" : degradedDeliveryNote()) +
|
|
1614
|
+
degradedDeliveryNote() +
|
|
1448
1615
|
`\n` +
|
|
1449
|
-
`
|
|
1450
|
-
`
|
|
1616
|
+
`This identity is fresh for this conversation. If your host runs the ` +
|
|
1617
|
+
`thatch hook, its output names your persistent identity - use that ` +
|
|
1618
|
+
`as the 'as' argument on other chat tools. Use chat_list to see who ` +
|
|
1619
|
+
`is available.`
|
|
1451
1620
|
);
|
|
1452
1621
|
}
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
return
|
|
1622
|
+
if (!host) {
|
|
1623
|
+
const row = ctx.db.findChatSession(asName!);
|
|
1624
|
+
if (!row) {
|
|
1625
|
+
return `No registered session named "${asName}" - names are assigned by thatch (your host hook prints yours); you cannot claim a new one.`;
|
|
1626
|
+
}
|
|
1627
|
+
return (
|
|
1628
|
+
`[registered] ${row.name}\n` +
|
|
1629
|
+
`session_id: ${row.session_id}\n` +
|
|
1630
|
+
`project: ${row.project ?? ctx.defaultStore}\n` +
|
|
1631
|
+
degradedDeliveryNote() +
|
|
1632
|
+
`\n` +
|
|
1633
|
+
`You were already registered. Other sessions can message you by name ` +
|
|
1634
|
+
`with chat_send, or reach everyone at once with chat_broadcast; use ` +
|
|
1635
|
+
`chat_list to see who else is available.`
|
|
1636
|
+
);
|
|
1459
1637
|
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1638
|
+
// An explicit join clears the leave tombstone BEFORE registering:
|
|
1639
|
+
// "I want back in" is the opposite of "I left", and the tombstone must
|
|
1640
|
+
// not block the rejoin it is supposed to yield to. (register() treats
|
|
1641
|
+
// a tombstoned opencode session as blocked; the tombstone is for the
|
|
1642
|
+
// idle path, not for the model's explicit intent.)
|
|
1643
|
+
ctx.db.clearChatLeaveTombstone?.(host.sessionID);
|
|
1644
|
+
const res = ctx.db.registerChatSession(host.sessionID, ctx.defaultStore, null, kind);
|
|
1645
|
+
if (!res.ok) return `Registration failed: ${res.error}`;
|
|
1466
1646
|
return (
|
|
1467
|
-
`[registered] ${
|
|
1468
|
-
`session_id: ${
|
|
1647
|
+
`[registered] ${res.name}\n` +
|
|
1648
|
+
`session_id: ${host.sessionID}\n` +
|
|
1469
1649
|
`project: ${ctx.defaultStore}\n` +
|
|
1470
|
-
(
|
|
1471
|
-
(host ? "" : degradedDeliveryNote()) +
|
|
1650
|
+
wakeDeliveryNote() +
|
|
1472
1651
|
`\n` +
|
|
1473
|
-
|
|
1474
|
-
`
|
|
1475
|
-
`
|
|
1652
|
+
`Other sessions can now message you by name with chat_send, or reach ` +
|
|
1653
|
+
`everyone at once with chat_broadcast; use chat_list to see who else ` +
|
|
1654
|
+
`is available.`
|
|
1476
1655
|
);
|
|
1477
1656
|
},
|
|
1478
1657
|
};
|
|
@@ -1493,7 +1672,7 @@ const chatListDef: ToolDef = {
|
|
|
1493
1672
|
if (!identity.ok) return identity.error;
|
|
1494
1673
|
const sessions = ctx.db.listChatSessions();
|
|
1495
1674
|
if (sessions.length === 0) {
|
|
1496
|
-
return "No sessions registered. chat_register
|
|
1675
|
+
return "No sessions registered. Sessions join the directory automatically on their first idle (opencode), or via chat_register - you would be the first.";
|
|
1497
1676
|
}
|
|
1498
1677
|
const unread = ctx.db.unreadChatCount(identity.sessionID);
|
|
1499
1678
|
const lines = sessions.map((s) => {
|
|
@@ -1506,7 +1685,17 @@ const chatListDef: ToolDef = {
|
|
|
1506
1685
|
const mailbox = self ? (unread > 0 ? ` ${unread} unread` : "") : "";
|
|
1507
1686
|
return `- ${s.name} (${s.session_id.slice(0, 12)})${project} ${liveness}${topic}${self ? " [you]" : ""}${mailbox}`;
|
|
1508
1687
|
});
|
|
1509
|
-
|
|
1688
|
+
// The name-stability note closes the roster because it answers the
|
|
1689
|
+
// question a reader asking "is this the same X as before?" needs:
|
|
1690
|
+
// assigned names are unique forever; only hook-anchored MCP identities
|
|
1691
|
+
// can be revisited by an old name.
|
|
1692
|
+
return (
|
|
1693
|
+
`[chat] ${sessions.length} session${sessions.length === 1 ? "" : "s"} registered\n` +
|
|
1694
|
+
`${lines.join("\n")}\n` +
|
|
1695
|
+
`Names are assigned by thatch and never reused or reassigned, so the ` +
|
|
1696
|
+
`same name is always the same session. A name whose row shows stale or ` +
|
|
1697
|
+
`idle has not been seen recently.`
|
|
1698
|
+
);
|
|
1510
1699
|
},
|
|
1511
1700
|
};
|
|
1512
1701
|
|
|
@@ -1571,7 +1760,11 @@ const chatReadDef: ToolDef = {
|
|
|
1571
1760
|
const sender = renderChatParticipant(m.from_name, m.from_session);
|
|
1572
1761
|
return `[from ${sender}, ${formatChatTimestamp(m.created_at)}] ${m.body}`;
|
|
1573
1762
|
});
|
|
1574
|
-
|
|
1763
|
+
// The frame is the injection boundary: bodies are other agents' text,
|
|
1764
|
+
// so the tool output marks everything between the fences as untrusted
|
|
1765
|
+
// data (chatInboxFrame in prompts.ts). The persisted rows are
|
|
1766
|
+
// untouched - the frame exists only in this output.
|
|
1767
|
+
return `${chatInboxFrame(lines, messages.length)}\n(${messages.length} message${messages.length === 1 ? "" : "s"}, marked read)`;
|
|
1575
1768
|
},
|
|
1576
1769
|
};
|
|
1577
1770
|
|
|
@@ -1663,7 +1856,10 @@ const chatStatusDef: ToolDef = {
|
|
|
1663
1856
|
}
|
|
1664
1857
|
return (
|
|
1665
1858
|
`[chat] registered as ${status.name}: ${status.pending} unread of ${status.total} total` +
|
|
1666
|
-
(status.pending > 0 ? " - call chat_read to read them." : ".")
|
|
1859
|
+
(status.pending > 0 ? " - call chat_read to read them." : ".") +
|
|
1860
|
+
(host
|
|
1861
|
+
? " You are woken automatically when a message arrives - no need to poll."
|
|
1862
|
+
: " Pending mail is reported at your next prompt; chat_read drains it.")
|
|
1667
1863
|
);
|
|
1668
1864
|
},
|
|
1669
1865
|
};
|
|
@@ -1701,6 +1897,7 @@ export const TOOL_DEFS: ToolDef[] = [
|
|
|
1701
1897
|
sessionGetDef,
|
|
1702
1898
|
watchCreateDef,
|
|
1703
1899
|
watchBranchCreateDef,
|
|
1900
|
+
watchCommandCreateDef,
|
|
1704
1901
|
watchListDef,
|
|
1705
1902
|
watchCancelDef,
|
|
1706
1903
|
chatRegisterDef,
|
package/src/tools.ts
CHANGED
|
@@ -18,6 +18,7 @@ export function createTools(
|
|
|
18
18
|
extractionPayloadProvider?: CoreContext["extractionPayloadProvider"];
|
|
19
19
|
drainExtractionQueue?: CoreContext["drainExtractionQueue"];
|
|
20
20
|
watcherRegistry?: WatcherRegistry;
|
|
21
|
+
projectDir?: string;
|
|
21
22
|
},
|
|
22
23
|
): Record<string, ReturnType<typeof tool>> {
|
|
23
24
|
const ctx: CoreContext = {
|
|
@@ -27,6 +28,7 @@ export function createTools(
|
|
|
27
28
|
extractionPayloadProvider: extensions?.extractionPayloadProvider,
|
|
28
29
|
drainExtractionQueue: extensions?.drainExtractionQueue,
|
|
29
30
|
watchers: extensions?.watcherRegistry,
|
|
31
|
+
projectDir: extensions?.projectDir,
|
|
30
32
|
};
|
|
31
33
|
|
|
32
34
|
const tools: Record<string, ReturnType<typeof tool>> = {};
|