Central-daemon messenger for Claude Code sessions (rewrite of cmux-msg)

🇯🇵 README-ja.md
Central daemon behind the ccmsg web UI. The plugin's only job is to keep the daemon running: its hooks module starts the daemon when a session starts, if it isn't up, and adds nothing to the session's context. The daemon stays resident for the web UI, where the human user browses sessions, transcripts, and the read-only logs of past rooms, and types into a Claude Code session: the input is put into the session's own prompt box, as if typed there. Sessions send to each other with the plugin's send tool, and the daemon delivers each message straight into the recipient session (send_message, DR-0039 §3).
MVP + web UI implemented. Architecture is captured in DR-0001 / DR-0002 / DR-0003 / DR-0004, grounded in the verbatim primary sources under docs/research/. The daemon, CLI, protocol, and webui packages under packages/ are implemented and tested.
Requires bun (the CLI and daemon run on bun).
claude plugin marketplace add kawaz/claude-ccmsg
claude plugin install ccmsg-v1@ccmsg-v1
Update:
claude plugin marketplace update ccmsg-v1
claude plugin update ccmsg-v1@ccmsg-v1
The plugin's bin/ccmsg lives under a versioned plugin-cache path, so it isn't on your shell PATH by default. To use it from a shell, point an alias or a symlink in a stable dir on PATH at the version you want:
ln -sfn <plugin-cache>/bin/ccmsg ~/.local/bin/ccmsg
The launcher runs the CLI of the version it belongs to and never touches the ccmsg on PATH, so after a plugin update, point the symlink at the new version yourself (it breaks once the old version's cache is removed). See DR-0032 §2.2-4.
The daemon serves a web UI at http://127.0.0.1:8642 by default (for the human user: browse sessions, files, transcripts, and the read-only logs of past rooms, and type into a session). Binding is loopback-only and browser access is gated by an Origin check: loopback origins pass by default, a tailscale serve front for this port is detected and allowed automatically (zero config for remote/phone access over your tailnet), and other reverse-proxy origins can be added with CCMSG_HTTP_ALLOW_ORIGIN (comma-separated). A source-IP allowlist (CCMSG_HTTP_ALLOW, default loopback) remains as defense in depth, and CCMSG_HTTP_BIND (comma-separated host:port, off to disable) overrides the bind. Paths are locators (/r/<room> = a room log, /r/<room>/m<mid> = a message in it, /s/<sid>/files / /s/<sid>/timeline/… / /s/<sid>/status = a session); see webui-url-grammar and DR-0004.
sayccmsg say forwards its arguments to macOS's /usr/bin/say unchanged, and first tells the daemon which session spoke. With several Claude Code sessions running, a spoken notification is otherwise anonymous — the web UI's Sessions list marks the session that spoke with 📣, and that session's timeline shows what was said with a 既読 (read) button that clears the marker. The daemon keeps these records and their unread state in memory only, so a daemon restart forgets them.
Speech never depends on the recording: no session id, no running daemon, or a daemon that refuses the event all still speak. bin/say is a PATH shim that routes an ordinary say through this command, so every say on the machine — yours, a script's, an agent's — becomes attributable. Install it as a copy next to the ccmsg on your PATH (not a symlink: its target is a versioned plugin-cache dir that each update removes).
ccmsg say records are held in memory only. The room logs (<data dir>/rooms/r<N>.jsonl) are read-only: the web UI shows them, and nothing writes to them (DR-0036 §2).send tool; the daemon writes the message straight into the recipient's peer messaging socket and tells the sender whether it arrived, holding nothing for a later attempt (DR-0034, DR-0036 §1, DR-0039 §3). The person's input from the web UI is filled into the session's prompt box and submitted (DR-0035).0600 + UID check) for local clients. The web UI uses WebSocket (/ws) speaking the same protocol: the security layer is identity pinning to the User role, gated by loopback-only binds, a source-IP allowlist (loopback, CCMSG_HTTP_ALLOW) and browser Origin validation (loopback origins by default, extras via CCMSG_HTTP_ALLOW_ORIGIN, e.g. for tailscale serve).send / say / peers / launch tools, and the sidecar that takes the person's input), a user-facing CLI (peers, dump, status, daemon, stop, …), a subscribe command that streams a session's notifications, and the web UI. The CLI health-checks and auto-starts the daemon.packages/
protocol/ # shared types (wire protocol / XDG paths / version), overview: docs/design/protocol-package.md
daemon/ # central daemon (bun)
cli/ # CLI client (session sidecar + user CLI)
webui/ # web UI (hono + vanilla ESM, served by the daemon)
docs/
decisions/ # DR-NNNN decision records
research/ # primary sources (verbatim design statements)
issue/ # active issues (claude-local-issue plugin)
findings/ # confirmed facts
journal/ # chronological notes
runbooks/ # operational recipes
knowledge/ # static knowledge
design/ # design docs
MIT — see LICENSE. Copyright (c) Yoshiaki Kawazu.
hooks/register.bundle.js 2583 lines1// Generated by `just build-hooks` with bun 1.4.2 from register.ts; edit that file, not this one.
2var store$4;
3var DEFAULT_CONFIG = {
4 lang: undefined,
5 message: undefined,
6 abortEarly: undefined,
7 abortPipeEarly: undefined
8};
9function getGlobalConfig(config$1) {
10 if (!config$1 && !store$4)
11 return DEFAULT_CONFIG;
12 return {
13 lang: config$1?.lang ?? store$4?.lang,
14 message: config$1?.message,
15 abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
16 abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
17 };
18}
19var store$3;
20function getGlobalMessage(lang) {
21 return store$3?.get(lang);
22}
23var store$2;
24function getSchemaMessage(lang) {
25 return store$2?.get(lang);
26}
27var store$1;
28function getSpecificMessage(reference, lang) {
29 return store$1?.get(reference)?.get(lang);
30}
31function _stringify(input) {
32 const type = typeof input;
33 if (type === "string")
34 return `"${input}"`;
35 if (type === "number" || type === "bigint" || type === "boolean")
36 return `${input}`;
37 if (type === "object" || type === "function")
38 return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
39 return type;
40}
41function _addIssue(context, label, dataset, config$1, other) {
42 const input = other && "input" in other ? other.input : dataset.value;
43 const expected = other?.expected ?? context.expects ?? null;
44 const received = other?.received ?? /* @__PURE__ */ _stringify(input);
45 const issue = {
46 kind: context.kind,
47 type: context.type,
48 input,
49 expected,
50 received,
51 message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
52 requirement: context.requirement,
53 path: other?.path,
54 issues: other?.issues,
55 lang: config$1.lang,
56 abortEarly: config$1.abortEarly,
57 abortPipeEarly: config$1.abortPipeEarly
58 };
59 const isSchema = context.kind === "schema";
60 const message$1 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config$1.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
61 if (message$1 !== undefined)
62 issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
63 if (isSchema)
64 dataset.typed = false;
65 if (dataset.issues)
66 dataset.issues.push(issue);
67 else
68 dataset.issues = [issue];
69}
70function _isSameValueZero(value1, value2) {
71 return value1 === value2 || Number.isNaN(value1) && Number.isNaN(value2);
72}
73function _isValidObjectKey(object$1, key) {
74 return Object.prototype.hasOwnProperty.call(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
75}
76function _joinExpects(values$1, separator) {
77 const list = [...new Set(values$1)];
78 if (list.length > 1)
79 return `(${list.join(` ${separator} `)})`;
80 return list[0] ?? "never";
81}
82function _standardSchema(schema) {
83 schema["~standard"] = {
84 version: 1,
85 vendor: "valibot",
86 validate: (value$1) => schema["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig())
87 };
88 return schema;
89}
90function getDotPath(issue) {
91 if (issue.path) {
92 let key = "";
93 for (const item of issue.path)
94 if (typeof item.key === "string" || typeof item.key === "number")
95 if (key)
96 key += `.${item.key}`;
97 else
98 key += item.key;
99 else
100 return null;
101 return key;
102 }
103 return null;
104}
105function check(requirement, message$1) {
106 return {
107 kind: "validation",
108 type: "check",
109 reference: check,
110 async: false,
111 expects: null,
112 requirement,
113 message: message$1,
114 "~run"(dataset, config$1) {
115 if (dataset.typed && !this.requirement(dataset.value))
116 _addIssue(this, "input", dataset, config$1);
117 return dataset;
118 }
119 };
120}
121function maxLength(requirement, message$1) {
122 return {
123 kind: "validation",
124 type: "max_length",
125 reference: maxLength,
126 async: false,
127 expects: `<=${requirement}`,
128 requirement,
129 message: message$1,
130 "~run"(dataset, config$1) {
131 if (dataset.typed && dataset.value.length > this.requirement)
132 _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` });
133 return dataset;
134 }
135 };
136}
137function minLength(requirement, message$1) {
138 return {
139 kind: "validation",
140 type: "min_length",
141 reference: minLength,
142 async: false,
143 expects: `>=${requirement}`,
144 requirement,
145 message: message$1,
146 "~run"(dataset, config$1) {
147 if (dataset.typed && dataset.value.length < this.requirement)
148 _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` });
149 return dataset;
150 }
151 };
152}
153function minValue(requirement, message$1) {
154 return {
155 kind: "validation",
156 type: "min_value",
157 reference: minValue,
158 async: false,
159 expects: `>=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
160 requirement,
161 message: message$1,
162 "~run"(dataset, config$1) {
163 if (dataset.typed && !(dataset.value >= this.requirement))
164 _addIssue(this, "value", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });
165 return dataset;
166 }
167 };
168}
169function nonEmpty(message$1) {
170 return {
171 kind: "validation",
172 type: "non_empty",
173 reference: nonEmpty,
174 async: false,
175 expects: "!0",
176 message: message$1,
177 "~run"(dataset, config$1) {
178 if (dataset.typed && dataset.value.length === 0)
179 _addIssue(this, "length", dataset, config$1, { received: "0" });
180 return dataset;
181 }
182 };
183}
184function parseJson(config$1, message$1) {
185 return {
186 kind: "transformation",
187 type: "parse_json",
188 reference: parseJson,
189 config: config$1,
190 message: message$1,
191 async: false,
192 "~run"(dataset, config$2) {
193 try {
194 dataset.value = JSON.parse(dataset.value, this.config?.reviver);
195 } catch (error) {
196 if (error instanceof Error) {
197 _addIssue(this, "JSON", dataset, config$2, { received: `"${error.message}"` });
198 dataset.typed = false;
199 } else
200 throw error;
201 }
202 return dataset;
203 }
204 };
205}
206function _isPartiallyTyped(dataset, paths) {
207 if (dataset.issues)
208 for (const path of paths)
209 for (const issue of dataset.issues) {
210 let typed = false;
211 const bound = Math.min(path.length, issue.path?.length ?? 0);
212 for (let index = 0;index < bound; index++)
213 if (path[index] !== issue.path[index].key && (path[index] !== "$" || issue.path[index].type !== "array")) {
214 typed = true;
215 break;
216 }
217 if (!typed)
218 return false;
219 }
220 return true;
221}
222function partialCheck(paths, requirement, message$1) {
223 return {
224 kind: "validation",
225 type: "partial_check",
226 reference: partialCheck,
227 async: false,
228 expects: null,
229 paths,
230 requirement,
231 message: message$1,
232 "~run"(dataset, config$1) {
233 if ((dataset.typed || /* @__PURE__ */ _isPartiallyTyped(dataset, paths)) && !this.requirement(dataset.value))
234 _addIssue(this, "input", dataset, config$1);
235 return dataset;
236 }
237 };
238}
239function regex(requirement, message$1) {
240 return {
241 kind: "validation",
242 type: "regex",
243 reference: regex,
244 async: false,
245 expects: `${requirement}`,
246 requirement,
247 message: message$1,
248 "~run"(dataset, config$1) {
249 if (dataset.typed && !this.requirement.test(dataset.value))
250 _addIssue(this, "format", dataset, config$1);
251 return dataset;
252 }
253 };
254}
255function safeInteger(message$1) {
256 return {
257 kind: "validation",
258 type: "safe_integer",
259 reference: safeInteger,
260 async: false,
261 expects: null,
262 requirement: Number.isSafeInteger,
263 message: message$1,
264 "~run"(dataset, config$1) {
265 if (dataset.typed && !this.requirement(dataset.value))
266 _addIssue(this, "safe integer", dataset, config$1);
267 return dataset;
268 }
269 };
270}
271var ABORT_EARLY_CONFIG = { abortEarly: true };
272function getFallback(schema, dataset, config$1) {
273 return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
274}
275function forward(action, path) {
276 return {
277 ...action,
278 "~run"(dataset, config$1) {
279 const prevIssues = dataset.issues && [...dataset.issues];
280 dataset = action["~run"](dataset, config$1);
281 if (dataset.issues) {
282 for (const issue of dataset.issues)
283 if (!prevIssues?.includes(issue)) {
284 let pathInput = dataset.value;
285 for (const key of path) {
286 const pathValue = pathInput[key];
287 const pathItem = {
288 type: "unknown",
289 origin: "value",
290 input: pathInput,
291 key,
292 value: pathValue
293 };
294 if (issue.path)
295 issue.path.push(pathItem);
296 else
297 issue.path = [pathItem];
298 if (!pathValue)
299 break;
300 pathInput = pathValue;
301 }
302 }
303 }
304 return dataset;
305 }
306 };
307}
308function getDefault(schema, dataset, config$1) {
309 return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
310}
311function is(schema, input) {
312 return !schema["~run"]({ value: input }, ABORT_EARLY_CONFIG).issues;
313}
314function array(item, message$1) {
315 return _standardSchema({
316 kind: "schema",
317 type: "array",
318 reference: array,
319 expects: "Array",
320 async: false,
321 item,
322 message: message$1,
323 "~run"(dataset, config$1) {
324 const input = dataset.value;
325 if (Array.isArray(input)) {
326 dataset.typed = true;
327 dataset.value = [];
328 for (let key = 0;key < input.length; key++) {
329 const value$1 = input[key];
330 const itemDataset = this.item["~run"]({ value: value$1 }, config$1);
331 if (itemDataset.issues) {
332 const pathItem = {
333 type: "array",
334 origin: "value",
335 input,
336 key,
337 value: value$1
338 };
339 for (const issue of itemDataset.issues) {
340 if (issue.path)
341 issue.path.unshift(pathItem);
342 else
343 issue.path = [pathItem];
344 dataset.issues?.push(issue);
345 }
346 if (!dataset.issues)
347 dataset.issues = itemDataset.issues;
348 if (config$1.abortEarly) {
349 dataset.typed = false;
350 break;
351 }
352 }
353 if (!itemDataset.typed)
354 dataset.typed = false;
355 dataset.value.push(itemDataset.value);
356 }
357 } else
358 _addIssue(this, "type", dataset, config$1);
359 return dataset;
360 }
361 });
362}
363function boolean(message$1) {
364 return _standardSchema({
365 kind: "schema",
366 type: "boolean",
367 reference: boolean,
368 expects: "boolean",
369 async: false,
370 message: message$1,
371 "~run"(dataset, config$1) {
372 if (typeof dataset.value === "boolean")
373 dataset.typed = true;
374 else
375 _addIssue(this, "type", dataset, config$1);
376 return dataset;
377 }
378 });
379}
380function literal(literal_, message$1) {
381 return _standardSchema({
382 kind: "schema",
383 type: "literal",
384 reference: literal,
385 expects: /* @__PURE__ */ _stringify(literal_),
386 async: false,
387 literal: literal_,
388 message: message$1,
389 "~run"(dataset, config$1) {
390 if (/* @__PURE__ */ _isSameValueZero(dataset.value, this.literal))
391 dataset.typed = true;
392 else
393 _addIssue(this, "type", dataset, config$1);
394 return dataset;
395 }
396 });
397}
398function looseObject(entries$1, message$1) {
399 return _standardSchema({
400 kind: "schema",
401 type: "loose_object",
402 reference: looseObject,
403 expects: "Object",
404 async: false,
405 entries: entries$1,
406 message: message$1,
407 "~run"(dataset, config$1) {
408 const input = dataset.value;
409 if (input && typeof input === "object") {
410 dataset.typed = true;
411 dataset.value = {};
412 for (const key in this.entries) {
413 const valueSchema = this.entries[key];
414 if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== undefined) {
415 const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
416 const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
417 if (valueDataset.issues) {
418 const pathItem = {
419 type: "object",
420 origin: "value",
421 input,
422 key,
423 value: value$1
424 };
425 for (const issue of valueDataset.issues) {
426 if (issue.path)
427 issue.path.unshift(pathItem);
428 else
429 issue.path = [pathItem];
430 dataset.issues?.push(issue);
431 }
432 if (!dataset.issues)
433 dataset.issues = valueDataset.issues;
434 if (config$1.abortEarly) {
435 dataset.typed = false;
436 break;
437 }
438 }
439 if (!valueDataset.typed)
440 dataset.typed = false;
441 dataset.value[key] = valueDataset.value;
442 } else if (valueSchema.fallback !== undefined)
443 dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
444 else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
445 _addIssue(this, "key", dataset, config$1, {
446 input: undefined,
447 expected: `"${key}"`,
448 path: [{
449 type: "object",
450 origin: "key",
451 input,
452 key,
453 value: input[key]
454 }]
455 });
456 if (config$1.abortEarly)
457 break;
458 }
459 }
460 if (!dataset.issues || !config$1.abortEarly) {
461 for (const key in input)
462 if (/* @__PURE__ */ _isValidObjectKey(input, key) && !Object.prototype.hasOwnProperty.call(this.entries, key))
463 dataset.value[key] = input[key];
464 }
465 } else
466 _addIssue(this, "type", dataset, config$1);
467 return dataset;
468 }
469 });
470}
471function nullable(wrapped, default_) {
472 return _standardSchema({
473 kind: "schema",
474 type: "nullable",
475 reference: nullable,
476 expects: `(${wrapped.expects} | null)`,
477 async: false,
478 wrapped,
479 default: default_,
480 "~run"(dataset, config$1) {
481 if (dataset.value === null) {
482 if (this.default !== undefined)
483 dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
484 if (dataset.value === null) {
485 dataset.typed = true;
486 return dataset;
487 }
488 }
489 return this.wrapped["~run"](dataset, config$1);
490 }
491 });
492}
493function number(message$1) {
494 return _standardSchema({
495 kind: "schema",
496 type: "number",
497 reference: number,
498 expects: "number",
499 async: false,
500 message: message$1,
501 "~run"(dataset, config$1) {
502 if (typeof dataset.value === "number" && !isNaN(dataset.value))
503 dataset.typed = true;
504 else
505 _addIssue(this, "type", dataset, config$1);
506 return dataset;
507 }
508 });
509}
510function object(entries$1, message$1) {
511 return _standardSchema({
512 kind: "schema",
513 type: "object",
514 reference: object,
515 expects: "Object",
516 async: false,
517 entries: entries$1,
518 message: message$1,
519 "~run"(dataset, config$1) {
520 const input = dataset.value;
521 if (input && typeof input === "object") {
522 dataset.typed = true;
523 dataset.value = {};
524 for (const key in this.entries) {
525 const valueSchema = this.entries[key];
526 if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== undefined) {
527 const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
528 const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
529 if (valueDataset.issues) {
530 const pathItem = {
531 type: "object",
532 origin: "value",
533 input,
534 key,
535 value: value$1
536 };
537 for (const issue of valueDataset.issues) {
538 if (issue.path)
539 issue.path.unshift(pathItem);
540 else
541 issue.path = [pathItem];
542 dataset.issues?.push(issue);
543 }
544 if (!dataset.issues)
545 dataset.issues = valueDataset.issues;
546 if (config$1.abortEarly) {
547 dataset.typed = false;
548 break;
549 }
550 }
551 if (!valueDataset.typed)
552 dataset.typed = false;
553 dataset.value[key] = valueDataset.value;
554 } else if (valueSchema.fallback !== undefined)
555 dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
556 else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
557 _addIssue(this, "key", dataset, config$1, {
558 input: undefined,
559 expected: `"${key}"`,
560 path: [{
561 type: "object",
562 origin: "key",
563 input,
564 key,
565 value: input[key]
566 }]
567 });
568 if (config$1.abortEarly)
569 break;
570 }
571 }
572 } else
573 _addIssue(this, "type", dataset, config$1);
574 return dataset;
575 }
576 });
577}
578function optional(wrapped, default_) {
579 return _standardSchema({
580 kind: "schema",
581 type: "optional",
582 reference: optional,
583 expects: `(${wrapped.expects} | undefined)`,
584 async: false,
585 wrapped,
586 default: default_,
587 "~run"(dataset, config$1) {
588 if (dataset.value === undefined) {
589 if (this.default !== undefined)
590 dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
591 if (dataset.value === undefined) {
592 dataset.typed = true;
593 return dataset;
594 }
595 }
596 return this.wrapped["~run"](dataset, config$1);
597 }
598 });
599}
600function picklist(options, message$1) {
601 return _standardSchema({
602 kind: "schema",
603 type: "picklist",
604 reference: picklist,
605 expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"),
606 async: false,
607 options,
608 message: message$1,
609 "~run"(dataset, config$1) {
610 if (this.options.includes(dataset.value))
611 dataset.typed = true;
612 else
613 _addIssue(this, "type", dataset, config$1);
614 return dataset;
615 }
616 });
617}
618function strictObject(entries$1, message$1) {
619 return _standardSchema({
620 kind: "schema",
621 type: "strict_object",
622 reference: strictObject,
623 expects: "Object",
624 async: false,
625 entries: entries$1,
626 message: message$1,
627 "~run"(dataset, config$1) {
628 const input = dataset.value;
629 if (input && typeof input === "object") {
630 dataset.typed = true;
631 dataset.value = {};
632 for (const key in this.entries) {
633 const valueSchema = this.entries[key];
634 if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== undefined) {
635 const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
636 const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
637 if (valueDataset.issues) {
638 const pathItem = {
639 type: "object",
640 origin: "value",
641 input,
642 key,
643 value: value$1
644 };
645 for (const issue of valueDataset.issues) {
646 if (issue.path)
647 issue.path.unshift(pathItem);
648 else
649 issue.path = [pathItem];
650 dataset.issues?.push(issue);
651 }
652 if (!dataset.issues)
653 dataset.issues = valueDataset.issues;
654 if (config$1.abortEarly) {
655 dataset.typed = false;
656 break;
657 }
658 }
659 if (!valueDataset.typed)
660 dataset.typed = false;
661 dataset.value[key] = valueDataset.value;
662 } else if (valueSchema.fallback !== undefined)
663 dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
664 else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
665 _addIssue(this, "key", dataset, config$1, {
666 input: undefined,
667 expected: `"${key}"`,
668 path: [{
669 type: "object",
670 origin: "key",
671 input,
672 key,
673 value: input[key]
674 }]
675 });
676 if (config$1.abortEarly)
677 break;
678 }
679 }
680 if (!dataset.issues || !config$1.abortEarly) {
681 for (const key in input)
682 if (!Object.prototype.hasOwnProperty.call(this.entries, key)) {
683 _addIssue(this, "key", dataset, config$1, {
684 input: key,
685 expected: "never",
686 path: [{
687 type: "object",
688 origin: "key",
689 input,
690 key,
691 value: input[key]
692 }]
693 });
694 break;
695 }
696 }
697 } else
698 _addIssue(this, "type", dataset, config$1);
699 return dataset;
700 }
701 });
702}
703function string(message$1) {
704 return _standardSchema({
705 kind: "schema",
706 type: "string",
707 reference: string,
708 expects: "string",
709 async: false,
710 message: message$1,
711 "~run"(dataset, config$1) {
712 if (typeof dataset.value === "string")
713 dataset.typed = true;
714 else
715 _addIssue(this, "type", dataset, config$1);
716 return dataset;
717 }
718 });
719}
720function _subIssues(datasets) {
721 let issues;
722 if (datasets)
723 for (const dataset of datasets)
724 if (issues)
725 for (const issue of dataset.issues)
726 issues.push(issue);
727 else
728 issues = dataset.issues;
729 return issues;
730}
731function union(options, message$1) {
732 return _standardSchema({
733 kind: "schema",
734 type: "union",
735 reference: union,
736 expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
737 async: false,
738 options,
739 message: message$1,
740 "~run"(dataset, config$1) {
741 let validDataset;
742 let typedDatasets;
743 let untypedDatasets;
744 for (const schema of this.options) {
745 const optionDataset = schema["~run"]({ value: dataset.value }, config$1);
746 if (optionDataset.typed)
747 if (optionDataset.issues)
748 if (typedDatasets)
749 typedDatasets.push(optionDataset);
750 else
751 typedDatasets = [optionDataset];
752 else {
753 validDataset = optionDataset;
754 break;
755 }
756 else if (untypedDatasets)
757 untypedDatasets.push(optionDataset);
758 else
759 untypedDatasets = [optionDataset];
760 }
761 if (validDataset)
762 return validDataset;
763 if (typedDatasets) {
764 if (typedDatasets.length === 1)
765 return typedDatasets[0];
766 _addIssue(this, "type", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
767 dataset.typed = true;
768 } else if (untypedDatasets?.length === 1)
769 return untypedDatasets[0];
770 else
771 _addIssue(this, "type", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
772 return dataset;
773 }
774 });
775}
776function unknown() {
777 return _standardSchema({
778 kind: "schema",
779 type: "unknown",
780 reference: unknown,
781 expects: "unknown",
782 async: false,
783 "~run"(dataset) {
784 dataset.typed = true;
785 return dataset;
786 }
787 });
788}
789function variant(key, options, message$1) {
790 return _standardSchema({
791 kind: "schema",
792 type: "variant",
793 reference: variant,
794 expects: "Object",
795 async: false,
796 key,
797 options,
798 message: message$1,
799 "~run"(dataset, config$1) {
800 const input = dataset.value;
801 if (input && typeof input === "object") {
802 let outputDataset;
803 let maxDiscriminatorPriority = 0;
804 let invalidDiscriminatorKey = this.key;
805 let expectedDiscriminators = [];
806 const parseOptions = (variant$1, allKeys) => {
807 for (const schema of variant$1.options) {
808 if (schema.type === "variant")
809 parseOptions(schema, new Set(allKeys).add(schema.key));
810 else {
811 let keysAreValid = true;
812 let currentPriority = 0;
813 for (const currentKey of allKeys) {
814 const discriminatorSchema = schema.entries[currentKey];
815 if (currentKey in input ? discriminatorSchema["~run"]({
816 typed: false,
817 value: input[currentKey]
818 }, ABORT_EARLY_CONFIG).issues : discriminatorSchema.type !== "exact_optional" && discriminatorSchema.type !== "optional" && discriminatorSchema.type !== "nullish") {
819 keysAreValid = false;
820 if (invalidDiscriminatorKey !== currentKey && (maxDiscriminatorPriority < currentPriority || maxDiscriminatorPriority === currentPriority && (currentKey in input) && !(invalidDiscriminatorKey in input))) {
821 maxDiscriminatorPriority = currentPriority;
822 invalidDiscriminatorKey = currentKey;
823 expectedDiscriminators = [];
824 }
825 if (invalidDiscriminatorKey === currentKey)
826 expectedDiscriminators.push(schema.entries[currentKey].expects);
827 break;
828 }
829 currentPriority++;
830 }
831 if (keysAreValid) {
832 const optionDataset = schema["~run"]({ value: input }, config$1);
833 if (!outputDataset || !outputDataset.typed && optionDataset.typed)
834 outputDataset = optionDataset;
835 }
836 }
837 if (outputDataset && !outputDataset.issues)
838 break;
839 }
840 };
841 parseOptions(this, new Set([this.key]));
842 if (outputDataset)
843 return outputDataset;
844 _addIssue(this, "type", dataset, config$1, {
845 input: input[invalidDiscriminatorKey],
846 expected: /* @__PURE__ */ _joinExpects(expectedDiscriminators, "|"),
847 path: [{
848 type: "object",
849 origin: "value",
850 input,
851 key: invalidDiscriminatorKey,
852 value: input[invalidDiscriminatorKey]
853 }]
854 });
855 } else
856 _addIssue(this, "type", dataset, config$1);
857 return dataset;
858 }
859 });
860}
861function omit(schema, keys) {
862 const entries$1 = { ...schema.entries };
863 for (const key of keys)
864 delete entries$1[key];
865 return _standardSchema({
866 ...schema,
867 entries: entries$1
868 });
869}
870function pipe(...pipe$1) {
871 return _standardSchema({
872 ...pipe$1[0],
873 pipe: pipe$1,
874 "~run"(dataset, config$1) {
875 for (const item of pipe$1)
876 if (item.kind !== "metadata") {
877 if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
878 dataset.typed = false;
879 break;
880 }
881 if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly)
882 dataset = item["~run"](dataset, config$1);
883 }
884 return dataset;
885 }
886 });
887}
888function safeParse(schema, input, config$1) {
889 const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));
890 return {
891 typed: dataset.typed,
892 success: !dataset.issues,
893 output: dataset.value,
894 issues: dataset.issues
895 };
896}
897
898function failureOf(issues) {
899 const read = issues.map((issue) => ({
900 path: getDotPath(issue) ?? "",
901 message: issue.message
902 }));
903 return {
904 issues: read,
905 summary: read.map((i) => i.path === "" ? i.message : `${i.path}: ${i.message}`).join("; ")
906 };
907}
908function parseWith(schema, input, options = {}) {
909 const read = safeParse(schema, input, options.firstIssue === true ? { abortEarly: true, abortPipeEarly: true } : undefined);
910 return read.success ? { ok: true, value: read.output } : { ok: false, failure: failureOf(read.issues) };
911}
912var JsonTextSchema = pipe(string(), parseJson());
913function jsonText(schema) {
914 return pipe(string(), parseJson(), schema);
915}
916function errorText(e) {
917 return e instanceof Error ? `${e.name}: ${e.message}` : `a thrown ${typeof e}`;
918}
919
920var CommandRunInputSchema = looseObject({ command: optional(string()) });
921var AnyInputSchema = looseObject({});
922
923var GUIDANCE = 'このセッションでは ccmsg が使える。別のセッションへの送信、届いた <cross-session-message from="ccmsg:…"> への返信、見ている人への知らせ、別のセッションの起動は、先に skill ccmsg-v1:ccmsg を読んでから行う。';
924function guidanceText(webuiUrl) {
925 return webuiUrl === undefined ? GUIDANCE : `${GUIDANCE}
926ccmsg_url: ${webuiUrl}`;
927}
928function statusArgv(root) {
929 return [`${root}/bin/ccmsg`, "status"];
930}
931var STATUS_TIMEOUT_MS = 3000;
932var StatusTextSchema = jsonText(looseObject({ webui_url: optional(string()) }));
933async function webuiUrl($) {
934 try {
935 const run = await $.process.run(statusArgv($.plugin.root), { timeoutMs: STATUS_TIMEOUT_MS });
936 const read = parseWith(StatusTextSchema, run.stdout);
937 if (read.ok)
938 return read.value.webui_url;
939 $.ui.log(`ccmsg: status not read: ${read.failure.summary}`, { to: "debug" });
940 } catch (e) {
941 $.ui.log(`ccmsg: status failed: ${errorText(e)}`, { to: "debug" });
942 }
943 return;
944}
945var GuidedRecordSchema = object({ guided: boolean(), at: number() });
946var GUIDED_PREFIX = "guided:";
947function guidedKey(sid) {
948 return `${GUIDED_PREFIX}${sid}`;
949}
950var GUIDED_TTL_MS = 30 * 24 * 60 * 60 * 1000;
951var GUIDED_TOUCH_MS = 24 * 60 * 60 * 1000;
952async function guidedRecord($, key) {
953 const read = parseWith(GuidedRecordSchema, await $.store.get(key));
954 return read.ok ? read.value : undefined;
955}
956async function guide($, state) {
957 if (state.interactive !== true)
958 return;
959 try {
960 const key = guidedKey(await $.session.id());
961 const now = Math.floor(await $.clock.now());
962 const held = await guidedRecord($, key);
963 if (held?.guided === true) {
964 if (now - held.at > GUIDED_TOUCH_MS)
965 await $.store.set(key, { guided: true, at: now });
966 return;
967 }
968 const text = guidanceText(await webuiUrl($));
969 await $.session.append({ message: { type: "user", content: [{ type: "text", text }] } });
970 await $.store.set(key, { guided: true, at: now });
971 } catch (e) {
972 $.ui.log(`ccmsg: guidance not added: ${errorText(e)}`, { to: "debug" });
973 }
974}
975async function unguide($) {
976 try {
977 const key = guidedKey(await $.session.id());
978 await $.store.set(key, { guided: false, at: Math.floor(await $.clock.now()) });
979 } catch (e) {
980 $.ui.log(`ccmsg: could not mark the guidance for after the compaction: ${errorText(e)}`, {
981 to: "debug"
982 });
983 }
984}
985async function sweepGuided($) {
986 try {
987 const now = Math.floor(await $.clock.now());
988 for (const key of await $.store.keys()) {
989 if (!key.startsWith(GUIDED_PREFIX))
990 continue;
991 const held = await guidedRecord($, key);
992 if (held === undefined || now - held.at > GUIDED_TTL_MS)
993 await $.store.delete(key);
994 }
995 } catch (e) {
996 $.ui.log(`ccmsg: guidance records not swept: ${errorText(e)}`, { to: "debug" });
997 }
998}
999
1000var HYOUI_TIMEOUT_MS = 3000;
1001var ACCEPT_WAIT_MS = 3000;
1002function newPromptSendState() {
1003 return { queue: Promise.resolve() };
1004}
1005var PromptSubmitInputSchema = looseObject({
1006 text: optional(string()),
1007 origin: optional(looseObject({ kind: optional(string()) }))
1008});
1009var PromptSubmitResultSchema = looseObject({ drop: optional(string()) });
1010function hyouiEnterArgv(hyouiSessionId) {
1011 return ["hyoui", "input", hyouiSessionId, "key:Enter"];
1012}
1013function samePrompt(submitted, filled) {
1014 return submitted === filled || submitted === filled.trimEnd();
1015}
1016var UNCONFIRMED = { outcome: "unconfirmed" };
1017var SESSION_CHANGED = { outcome: "not_delivered", reason: "session_changed" };
1018async function stillCurrent($, state, request) {
1019 if (request.generation !== state.generation || request.sid !== state.sid)
1020 return false;
1021 return await $.session.id() === request.sid;
1022}
1023async function putBackUnsent($, text, draft) {
1024 const box = await $.prompt.read();
1025 if (box.text !== text)
1026 return false;
1027 const put = await $.prompt.fill({ text: draft, mode: "replace" });
1028 if (!put.isFilled)
1029 return false;
1030 return !(await $.prompt.read()).text.includes(text);
1031}
1032async function handlePromptSend($, state, request) {
1033 const hyouiSessionId = await $.env.get("HYOUI_SESSION_ID");
1034 if (!hyouiSessionId)
1035 return { outcome: "not_delivered", reason: "no_terminal" };
1036 const draft = (await $.prompt.read()).text;
1037 const filled = await $.prompt.fill({ text: request.text, mode: "replace" });
1038 if (!filled.isFilled)
1039 return { outcome: "not_delivered", reason: filled.refusal ?? "refused" };
1040 if (!await stillCurrent($, state, request)) {
1041 return await putBackUnsent($, request.text, draft) ? SESSION_CHANGED : UNCONFIRMED;
1042 }
1043 const accepted = Promise.withResolvers();
1044 state.awaiting = {
1045 text: request.text,
1046 accept: () => accepted.resolve(true),
1047 ...request.override !== undefined ? { override: request.override } : {}
1048 };
1049 state.restoring = { text: request.text, draft };
1050 let entered;
1051 try {
1052 const run = await $.process.run(hyouiEnterArgv(hyouiSessionId), {
1053 timeoutMs: HYOUI_TIMEOUT_MS
1054 });
1055 entered = run.exitCode === 0;
1056 } catch {
1057 entered = false;
1058 }
1059 const timer = $.clock.after(ACCEPT_WAIT_MS, () => accepted.resolve(false));
1060 const isAccepted = await accepted.promise;
1061 timer.cancel();
1062 if (state.awaiting?.text === request.text)
1063 state.awaiting = undefined;
1064 if (request.generation !== state.generation)
1065 return UNCONFIRMED;
1066 if (isAccepted)
1067 return { outcome: "accepted" };
1068 if (state.restoring?.text === request.text)
1069 state.restoring = undefined;
1070 if (await putBackUnsent($, request.text, draft)) {
1071 return { outcome: "not_delivered", reason: entered ? "not_submitted" : "enter_failed" };
1072 }
1073 return UNCONFIRMED;
1074}
1075async function putBackDraft($, submitted, draft) {
1076 const box = await $.prompt.read();
1077 if (box.text !== "" && box.text !== submitted) {
1078 $.ui.log(`ccmsg: kept the newly typed text; the earlier draft was: ${draft}`, {
1079 to: "debug"
1080 });
1081 return;
1082 }
1083 await $.prompt.fill({ text: draft, mode: "replace" });
1084}
1085async function promptSend($, state, request) {
1086 if (request.generation !== state.generation || request.sid !== state.sid) {
1087 $.ui.log(`ccmsg: prompt.send ${request.id} not filled: the session changed its id`, {
1088 to: "debug"
1089 });
1090 return { id: request.id, ok: true, result: SESSION_CHANGED };
1091 }
1092 return { id: request.id, ok: true, result: await handlePromptSend($, state, request) };
1093}
1094function queuePromptSend($, state, request) {
1095 const result = state.queue.then(() => promptSend($, state, request));
1096 state.queue = result.then(() => {
1097 return;
1098 }, () => {
1099 return;
1100 });
1101 return result;
1102}
1103async function promptSubmitted($, state, input, result) {
1104 if (input.text === undefined)
1105 return;
1106 const settled = parseWith(PromptSubmitResultSchema, result);
1107 const entered = settled.ok && settled.value.drop === undefined;
1108 const awaiting = state.awaiting;
1109 if (awaiting !== undefined) {
1110 if (entered && samePrompt(input.text, awaiting.text)) {
1111 state.awaiting = undefined;
1112 awaiting.accept();
1113 } else {
1114 $.ui.log(`ccmsg: prompt.submit ${JSON.stringify(input.text)} ${entered ? "is not" : "dropped, not"} the filled ${JSON.stringify(awaiting.text)}`, { to: "debug" });
1115 }
1116 }
1117 const restoring = state.restoring;
1118 if (!entered || restoring === undefined || !samePrompt(input.text, restoring.text))
1119 return;
1120 state.restoring = undefined;
1121 if (restoring.draft !== "")
1122 await putBackDraft($, restoring.text, restoring.draft);
1123}
1124
1125var SESSION_ID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1126
1127var LaunchModelSchema = picklist(["fable", "opus", "sonnet", "haiku"]);
1128var LaunchEffortSchema = picklist(["low", "medium", "high", "xhigh", "max"]);
1129var LaunchCwdSchema = pipe(string(), check((p) => p.startsWith("/"), "絶対パスで指定する"));
1130var NonEmptySchema = pipe(string(), minLength(1, "空にはできない (指定しない時は field ごと書かない)"));
1131var SessionUuidSchema = pipe(string(), regex(SESSION_ID_SHAPE, "小文字の uuid で指定する"));
1132var LaunchFieldsSchema = strictObject({
1133 cwd: LaunchCwdSchema,
1134 model: optional(LaunchModelSchema),
1135 effort: optional(LaunchEffortSchema),
1136 continue: optional(boolean()),
1137 resume: optional(SessionUuidSchema),
1138 resume_session_at: optional(SessionUuidSchema),
1139 fork_session: optional(boolean()),
1140 name: optional(NonEmptySchema),
1141 prompt: optional(NonEmptySchema)
1142});
1143function launchContinues(launch) {
1144 return launch.continue === true || launch.resume !== undefined;
1145}
1146function launchMakesSession(launch) {
1147 return !launchContinues(launch) || launch.fork_session === true;
1148}
1149var LAUNCH_CHOOSE_MESSAGE = "選んでください (continue も resume も無い新規の起動では必須)";
1150var NEEDS_SOURCE = "continue か resume と一緒に指定する";
1151var LaunchInputSchema = pipe(LaunchFieldsSchema, forward(partialCheck([["continue"], ["resume"]], (launch) => !(launch.continue === true && launch.resume !== undefined), "continue と resume は同時に指定できない"), ["resume"]), forward(partialCheck([["continue"], ["resume"], ["fork_session"]], (launch) => launch.fork_session !== true || launchContinues(launch), NEEDS_SOURCE), ["fork_session"]), forward(partialCheck([["fork_session"], ["resume_session_at"]], (launch) => launch.resume_session_at === undefined || launch.fork_session === true, "fork_session と一緒に指定する"), ["resume_session_at"]), forward(partialCheck([["continue"], ["resume"], ["model"]], (launch) => launchContinues(launch) || launch.model !== undefined, LAUNCH_CHOOSE_MESSAGE), ["model"]), forward(partialCheck([["continue"], ["resume"], ["effort"]], (launch) => launchContinues(launch) || launch.effort !== undefined, LAUNCH_CHOOSE_MESSAGE), ["effort"]));
1152var LaunchInputTextSchema = jsonText(LaunchInputSchema);
1153var LaunchToolFieldsSchema = omit(LaunchFieldsSchema, ["resume_session_at"]);
1154var LaunchCommandInputSchema = pipe(strictObject({
1155 ...LaunchFieldsSchema.entries,
1156 session_id: optional(SessionUuidSchema)
1157}), check(({ session_id: _id, ...launch }) => is(LaunchInputSchema, launch), "the launch does not read"), forward(partialCheck([["continue"], ["resume"], ["fork_session"], ["session_id"]], (input) => launchMakesSession(input) === (input.session_id !== undefined), "present exactly when the launch makes a session"), ["session_id"]));
1158var SessionLaunchResponseSchema = object({
1159 ok: literal(true),
1160 session_id: optional(SessionUuidSchema),
1161 exit_code: pipe(number(), safeInteger()),
1162 stdout: string(),
1163 stderr: string()
1164});
1165var SessionLaunchResponseTextSchema = jsonText(SessionLaunchResponseSchema);
1166function launchErrorText(error) {
1167 if (error.code === "internal") {
1168 return { started: "unknown", text: `起動したか確かめられなかった: ${error.msg}` };
1169 }
1170 return {
1171 started: "no",
1172 text: `ccmsg の daemon が起動を断ったので、起動していない (${error.code}): ${error.msg}`
1173 };
1174}
1175
1176var RequestOverrideSchema = object({
1177 model: optional(LaunchModelSchema),
1178 effort: optional(LaunchEffortSchema)
1179});
1180var RequestOverridePatchSchema = object({
1181 model: optional(nullable(LaunchModelSchema)),
1182 effort: optional(nullable(LaunchEffortSchema))
1183});
1184var RequestOverrideTargetSchema = picklist(["session", "once"]);
1185var RequestValuesSchema = object({
1186 model: nullable(pipe(string(), nonEmpty())),
1187 effort: nullable(pipe(string(), nonEmpty()))
1188});
1189var RequestOverrideStateSchema = object({
1190 session: RequestValuesSchema,
1191 once: RequestValuesSchema
1192});
1193function overridesAnything(override) {
1194 return override.model !== undefined || override.effort !== undefined;
1195}
1196function overrideModel(requestModel, family) {
1197 return requestModel?.endsWith("[1m]") === true ? `${family}[1m]` : family;
1198}
1199function overrideInForce(overrides) {
1200 const model = overrides.once?.model ?? overrides.session.model;