@celljs/ta-initiative 4.17.0 → 4.18.0

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/host/index.mjs CHANGED
@@ -1,3 +1,7 @@
1
+ // web-src/initiative-service.ts
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
1
5
  // ../ta-protocol/esm/common/language.js
2
6
  var TaLanguageUtil;
3
7
  (function(TaLanguageUtil2) {
@@ -295,6 +299,447 @@ var EventProposals;
295
299
  EventProposals.settled = settled;
296
300
  })(EventProposals ||= {});
297
301
 
302
+ // ../ta-protocol/esm/common/message-protocol.js
303
+ var TaMessageContext;
304
+ (function(TaMessageContext2) {
305
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
306
+ function wrap(context, message) {
307
+ return `<context>
308
+ ${context}
309
+ </context>
310
+ ${message}`;
311
+ }
312
+ TaMessageContext2.wrap = wrap;
313
+ function strip(message) {
314
+ return message.replace(BLOCK, "");
315
+ }
316
+ TaMessageContext2.strip = strip;
317
+ function read(message) {
318
+ var _a;
319
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
320
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
321
+ }
322
+ TaMessageContext2.read = read;
323
+ })(TaMessageContext || (TaMessageContext = {}));
324
+ var TaMessageSource;
325
+ (function(TaMessageSource2) {
326
+ TaMessageSource2.DOUBLE = "ta:double";
327
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
328
+ function mark(message, from, detail) {
329
+ return marked(message, line(from, detail));
330
+ }
331
+ TaMessageSource2.mark = mark;
332
+ function notice(message, from, detail) {
333
+ return marked(message, line(from, detail, true));
334
+ }
335
+ TaMessageSource2.notice = notice;
336
+ function line(from, detail, notice2 = false) {
337
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
338
+ }
339
+ TaMessageSource2.line = line;
340
+ function of(message) {
341
+ const context = TaMessageContext.read(message);
342
+ const match = context === undefined ? null : LINE.exec(context);
343
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
344
+ }
345
+ TaMessageSource2.of = of;
346
+ function isNotice(message) {
347
+ var _a;
348
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
349
+ }
350
+ TaMessageSource2.isNotice = isNotice;
351
+ TaMessageSource2.SECTION = "ta-sources";
352
+ TaMessageSource2.PROMPT = [
353
+ "Who wrote a message: what the user typed or said is theirs. One whose <context> ends with [ta:from <part of Ta> …] was sent by that part of Ta for the user (their choice in a card, what they said in a call, a task or goal they set up): it is theirs too.",
354
+ "One with [ta:notice <part of Ta> …] is not the user's: news or an event of that part of Ta (work that ended elsewhere, a time limit, a permission granted). Weigh it below what the user said:",
355
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
356
+ "- Act on it only as far as what they asked, your role or a limit they set calls for; otherwise take it in and go on, and tell them of it in a line only when they need it (a result they wait for, a failure, a question for them).",
357
+ "- Never quote it as the user's words nor answer it as if they had said it."
358
+ ].join(`
359
+ `);
360
+ function marked(message, source) {
361
+ if (/^[/!]/.test(message) || of(message)) {
362
+ return message;
363
+ }
364
+ const context = TaMessageContext.read(message);
365
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
366
+ ${source}`, TaMessageContext.strip(message));
367
+ }
368
+ })(TaMessageSource || (TaMessageSource = {}));
369
+ var TaImageNote;
370
+ (function(TaImageNote2) {
371
+ const NOTE = /^\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]$|^\[Image converted from [^\]]+ to [^\]]+\.\]$/;
372
+ function strip(text) {
373
+ const lines = text.split(`
374
+ `);
375
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
376
+ if (kept.length === lines.length) {
377
+ return text;
378
+ }
379
+ return kept.join(`
380
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
381
+ }
382
+ TaImageNote2.strip = strip;
383
+ })(TaImageNote || (TaImageNote = {}));
384
+ var TaImageSize;
385
+ (function(TaImageSize2) {
386
+ const JPEG_BYTES = 256 * 1024;
387
+ function of(base64) {
388
+ var _a, _b, _c;
389
+ let bytes;
390
+ try {
391
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
392
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
393
+ } catch (_d) {
394
+ return;
395
+ }
396
+ const size = (_c = (_b = (_a = png(bytes)) !== null && _a !== undefined ? _a : gif(bytes)) !== null && _b !== undefined ? _b : webp(bytes)) !== null && _c !== undefined ? _c : jpeg(bytes);
397
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
398
+ }
399
+ TaImageSize2.of = of;
400
+ function u16be(bytes, at) {
401
+ return bytes[at] << 8 | bytes[at + 1];
402
+ }
403
+ function u16le(bytes, at) {
404
+ return bytes[at] | bytes[at + 1] << 8;
405
+ }
406
+ function u24le(bytes, at) {
407
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
408
+ }
409
+ function u32be(bytes, at) {
410
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
411
+ }
412
+ function text(bytes, at, length) {
413
+ return String.fromCharCode(...bytes.subarray(at, at + length));
414
+ }
415
+ function png(bytes) {
416
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
417
+ }
418
+ function gif(bytes) {
419
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
420
+ }
421
+ function webp(bytes) {
422
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
423
+ return;
424
+ }
425
+ switch (text(bytes, 12, 4)) {
426
+ case "VP8 ":
427
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
428
+ case "VP8L": {
429
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
430
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
431
+ }
432
+ case "VP8X":
433
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
434
+ default:
435
+ return;
436
+ }
437
+ }
438
+ function jpeg(bytes) {
439
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
440
+ return;
441
+ }
442
+ let at = 2;
443
+ while (at + 9 < bytes.length) {
444
+ if (bytes[at] !== 255) {
445
+ return;
446
+ }
447
+ const marker = bytes[at + 1];
448
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
449
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
450
+ }
451
+ at += 2 + u16be(bytes, at + 2);
452
+ }
453
+ return;
454
+ }
455
+ })(TaImageSize || (TaImageSize = {}));
456
+ var TaAgentSummary;
457
+ (function(TaAgentSummary2) {
458
+ const START = /^\s*<conversation_history_summary>/;
459
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
460
+ function read(text) {
461
+ if (!START.test(text)) {
462
+ return;
463
+ }
464
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
465
+ }
466
+ TaAgentSummary2.read = read;
467
+ function strip(text) {
468
+ return text.replace(BLOCK, "");
469
+ }
470
+ TaAgentSummary2.strip = strip;
471
+ })(TaAgentSummary || (TaAgentSummary = {}));
472
+ var TaSkillUse;
473
+ (function(TaSkillUse2) {
474
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
475
+ function parse(message) {
476
+ var _a;
477
+ const match = BLOCK.exec(message);
478
+ if (!match) {
479
+ return;
480
+ }
481
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
482
+ }
483
+ TaSkillUse2.parse = parse;
484
+ function command(use) {
485
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
486
+ }
487
+ TaSkillUse2.command = command;
488
+ })(TaSkillUse || (TaSkillUse = {}));
489
+ var TaTaskNote;
490
+ (function(TaTaskNote2) {
491
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
492
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
493
+ function write(note) {
494
+ const attributes = [`id="${quote(note.id)}"`];
495
+ if (note.was !== undefined) {
496
+ attributes.push(`was="${quote(note.was)}"`);
497
+ }
498
+ attributes.push(`title="${quote(note.title)}"`);
499
+ if (note.status !== undefined) {
500
+ attributes.push(`status="${quote(note.status)}"`);
501
+ }
502
+ return `<task_${note.kind} ${attributes.join(" ")}>
503
+ ${note.body}
504
+ </task_${note.kind}>`;
505
+ }
506
+ TaTaskNote2.write = write;
507
+ function parse(text) {
508
+ const match = NOTE.exec(text.trim());
509
+ if (!match) {
510
+ return;
511
+ }
512
+ const attributes = {};
513
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
514
+ attributes[name] = unquote(value);
515
+ }
516
+ if (!attributes.id || attributes.title === undefined) {
517
+ return;
518
+ }
519
+ const { id, title, status, was } = attributes;
520
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
521
+ }
522
+ TaTaskNote2.parse = parse;
523
+ function quote(text) {
524
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
525
+ }
526
+ function unquote(text) {
527
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
528
+ }
529
+ })(TaTaskNote || (TaTaskNote = {}));
530
+ var TaSecretRef;
531
+ (function(TaSecretRef2) {
532
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
533
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
534
+ const KINDS = [
535
+ [/^PHONE(?:_\d+)?$/, "phone"],
536
+ [/^EMAIL(?:_\d+)?$/, "email"],
537
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
538
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
539
+ ];
540
+ function has(text) {
541
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
542
+ }
543
+ TaSecretRef2.has = has;
544
+ function kind(name) {
545
+ var _a;
546
+ var _b;
547
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
548
+ }
549
+ TaSecretRef2.kind = kind;
550
+ function split(text) {
551
+ if (!has(text)) {
552
+ return [{ text }];
553
+ }
554
+ const parts = [];
555
+ let at = 0;
556
+ for (const match of text.matchAll(REF)) {
557
+ if (match.index > at) {
558
+ parts.push({ text: text.slice(at, match.index) });
559
+ }
560
+ parts.push({ secret: match[1], kind: kind(match[1]) });
561
+ at = match.index + match[0].length;
562
+ }
563
+ if (at < text.length) {
564
+ parts.push({ text: text.slice(at) });
565
+ }
566
+ return parts;
567
+ }
568
+ TaSecretRef2.split = split;
569
+ function plain(text, label) {
570
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
571
+ }
572
+ TaSecretRef2.plain = plain;
573
+ })(TaSecretRef || (TaSecretRef = {}));
574
+
575
+ // web-src/idea-proposals.ts
576
+ var IDEA_KIND = "idea.try";
577
+ var IDEA_KINDS = [
578
+ {
579
+ id: IDEA_KIND,
580
+ owner: NAME,
581
+ title: { en: "Something you could hand to Ta", zh: "可以交给 Ta 的事", tw: "可以交給 Ta 的事", ja: "Ta に任せられること" },
582
+ reversible: false,
583
+ level: "ask"
584
+ }
585
+ ];
586
+ var IDEAS_WAITING = 2;
587
+ var IdeaProposals;
588
+ ((IdeaProposals) => {
589
+ function read(pi) {
590
+ const list = pi?.ideas;
591
+ if (!Array.isArray(list)) {
592
+ return [];
593
+ }
594
+ const text = (value) => value && typeof value === "object" && TaLanguageUtil.ALL.every((language) => typeof value[language] === "string") ? value : undefined;
595
+ return list.flatMap((item) => {
596
+ const one = item ?? {};
597
+ const title = text(one.title);
598
+ const why = text(one.why);
599
+ return typeof one.id === "string" && /^[\w.-]{1,40}$/.test(one.id) && title && typeof one.prompt === "string" && one.prompt.trim() ? [{ id: one.id, title, ...why ? { why } : {}, prompt: one.prompt.trim().slice(0, 2000) }] : [];
600
+ });
601
+ }
602
+ IdeaProposals.read = read;
603
+ function key(pkg, idea) {
604
+ return `${IDEA_KIND}:${pkg}:${idea.id}`;
605
+ }
606
+ IdeaProposals.key = key;
607
+ function due(packages, proposals, language) {
608
+ const offered = new Set(proposals.filter((one) => one.kind === IDEA_KIND).map((one) => one.key));
609
+ const waiting = proposals.filter((one) => one.kind === IDEA_KIND && (one.state === "pending" || one.state === "digest")).length;
610
+ const room = Math.max(0, IDEAS_WAITING - waiting);
611
+ return packages.flatMap((pkg) => pkg.ideas.map((idea) => ({ pkg: pkg.name, idea }))).filter(({ pkg, idea }) => !offered.has(key(pkg, idea))).slice(0, room).map(({ pkg, idea }) => offer(pkg, idea, language));
612
+ }
613
+ IdeaProposals.due = due;
614
+ function offer(pkg, idea, language) {
615
+ const title = TaLanguageUtil.pick(language, idea.title);
616
+ return {
617
+ kind: IDEA_KIND,
618
+ title,
619
+ why: idea.why ? TaLanguageUtil.pick(language, idea.why) : "",
620
+ key: key(pkg, idea),
621
+ source: "host",
622
+ urgency: "whenever",
623
+ action: { type: "prompt", prompt: message(title, idea.prompt) }
624
+ };
625
+ }
626
+ IdeaProposals.offer = offer;
627
+ function message(title, prompt) {
628
+ return TaMessageContext.wrap([
629
+ `The user tapped Try on an idea Ta offered them: ${prompt}`,
630
+ "You know little of their situation yet: first ask at most 3 questions you truly need, in one short message, with choices where you can (a ta-glance card of options), then do it. Never buy, send, publish or delete anything without asking.",
631
+ TaMessageSource.line(NAME)
632
+ ].join(`
633
+ `), title);
634
+ }
635
+ IdeaProposals.message = message;
636
+ })(IdeaProposals ||= {});
637
+
638
+ // web-src/initiative-commands.ts
639
+ var words = (en, zh, tw, ja) => ({
640
+ "en-US": en,
641
+ "zh-CN": zh,
642
+ "zh-TW": tw,
643
+ "ja-JP": ja
644
+ });
645
+ var MODE_WORDS = {
646
+ quiet: words("Quiet", "安静", "安靜", "控えめ"),
647
+ balanced: words("Balanced", "适中", "適中", "ふつう"),
648
+ active: words("Active", "积极", "積極", "積極的")
649
+ };
650
+ var LEVEL_WORDS = {
651
+ off: words("Never", "不提", "不提", "提案しない"),
652
+ digest: words("In the brief", "只进简报", "只進簡報", "要約のみ"),
653
+ ask: words("Ask me", "先问我", "先問我", "先に確認"),
654
+ act: words("Do it, tell me", "先做后报", "先做後報", "実行して報告"),
655
+ auto: words("Auto", "自动", "自動", "自動")
656
+ };
657
+ var InitiativeCommands;
658
+ ((InitiativeCommands) => {
659
+ function register(host, book) {
660
+ const register2 = host.commands?.register;
661
+ if (!register2) {
662
+ return () => {
663
+ return;
664
+ };
665
+ }
666
+ const stops = [register2(mode(book)), register2(level(book))];
667
+ return () => {
668
+ for (const stop of stops) {
669
+ stop();
670
+ }
671
+ };
672
+ }
673
+ InitiativeCommands.register = register;
674
+ function mode(book) {
675
+ return {
676
+ id: "initiative.mode",
677
+ title: words("Change how much Ta does on its own", "调整 Ta 的主动程度", "調整 Ta 的主動程度", "Ta の自発性を変更"),
678
+ description: "Sets how much Ta does on its own, as Settings → Initiative: quiet (fewer suggestions, at most one notice a day), balanced, or active (more, and more done unasked as the user accepts). Use it when the user says to suggest less or more.",
679
+ input: { type: "object", properties: { mode: { type: "string", enum: [...MODES] } }, required: ["mode"] },
680
+ risk: "act",
681
+ action: "settings.manage",
682
+ run: async (input, context) => {
683
+ const next = input.mode;
684
+ if (!MODES.includes(next)) {
685
+ throw new Error(`mode is one of ${MODES.join(", ")}.`);
686
+ }
687
+ const before = await book.currentMode();
688
+ await book.setMode(next);
689
+ const say = (value) => TaLanguageUtil.pick(context.language, MODE_WORDS[value]);
690
+ return {
691
+ text: `Initiative: ${before} → ${next}.`,
692
+ notice: TaLanguageUtil.pick(context.language, words("Changed how much Ta does on its own", "调整了主动程度", "調整了主動程度", "自発性を変更しました")),
693
+ changes: [
694
+ {
695
+ label: TaLanguageUtil.pick(context.language, words("Initiative", "主动程度", "主動程度", "自発性")),
696
+ before: say(before),
697
+ after: say(next)
698
+ }
699
+ ],
700
+ undo: { command: "initiative.mode", input: { mode: before } }
701
+ };
702
+ }
703
+ };
704
+ }
705
+ InitiativeCommands.mode = mode;
706
+ function level(book) {
707
+ return {
708
+ id: "initiative.level",
709
+ title: words("Change how far Ta goes with a kind of thing", "调整某一类事 Ta 能做到哪一步", "調整某一類事 Ta 能做到哪一步", "ある種類のことを Ta がどこまでするか変更"),
710
+ description: 'Sets how far Ta goes with one kind of thing it proposes (its id, as <ta-initiative> or Settings → Initiative lists them, e.g. cron.add, idea.try): off (never suggest it), digest (only in the daily brief), ask, act (do it and tell; only kinds that can be undone), or null to give it back to Ta. Use it when the user says "stop suggesting X", "just do X from now on".',
711
+ input: {
712
+ type: "object",
713
+ properties: { kind: { type: "string" }, level: { type: ["string", "null"], enum: [...LEVELS, null] } },
714
+ required: ["kind", "level"]
715
+ },
716
+ risk: "act",
717
+ action: "settings.manage",
718
+ run: async (input, context) => {
719
+ const kind = String(input.kind ?? "");
720
+ const next = input.level === null ? null : input.level;
721
+ if (next !== null && !LEVELS.includes(next)) {
722
+ throw new Error(`level is one of ${LEVELS.join(", ")}, or null.`);
723
+ }
724
+ const kinds = await book.kinds();
725
+ const status = kinds.find((one) => one.kind.id === kind);
726
+ if (!status) {
727
+ throw new Error(`No kind ${kind}. Kinds: ${kinds.map((one) => one.kind.id).join(", ")}.`);
728
+ }
729
+ const after = await book.setLevel(kind, next);
730
+ const say = (value) => TaLanguageUtil.pick(context.language, LEVEL_WORDS[value ?? "auto"]);
731
+ return {
732
+ text: `${kind}: ${status.locked ?? "auto"} → ${after.locked ?? "auto"} (now ${after.level}).`,
733
+ notice: TaLanguageUtil.pick(context.language, words("Changed what Ta does on its own", "调整了 Ta 的主动", "調整了 Ta 的主動", "Ta の自発的な行動を変更しました")),
734
+ changes: [{ label: KindTitleUtil.pick(status.kind.title, context.language), before: say(status.locked), after: say(after.locked) }],
735
+ undo: { command: "initiative.level", input: { kind, level: status.locked ?? null } }
736
+ };
737
+ }
738
+ };
739
+ }
740
+ InitiativeCommands.level = level;
741
+ })(InitiativeCommands ||= {});
742
+
298
743
  // web-src/proposal-book.ts
299
744
  import { randomBytes } from "node:crypto";
300
745
 
@@ -313,10 +758,23 @@ var InboxUtil;
313
758
  return proposals.filter((proposal) => proposal.auto && ["done", "undone", "failed"].includes(proposal.state) && now - (proposal.decidedAt ?? proposal.at) <= Limits.UNDO_DAYS * DAY_MS).sort((a, b) => (b.decidedAt ?? b.at) - (a.decidedAt ?? a.at));
314
759
  }
315
760
  InboxUtil.done = done;
761
+ function recent(proposals, now, limit = 20) {
762
+ return proposals.filter((proposal) => !proposal.auto && ["done", "declined", "expired", "failed"].includes(proposal.state) && now - (proposal.decidedAt ?? proposal.at) <= Limits.UNDO_DAYS * DAY_MS).sort((a, b) => (b.decidedAt ?? b.at) - (a.decidedAt ?? a.at)).slice(0, limit);
763
+ }
764
+ InboxUtil.recent = recent;
316
765
  function canUndo(proposal, now) {
317
766
  return proposal.state === "done" && !!proposal.undo && now - (proposal.decidedAt ?? proposal.at) <= Limits.UNDO_DAYS * DAY_MS;
318
767
  }
319
768
  InboxUtil.canUndo = canUndo;
769
+ function undoDaysLeft(proposal, now) {
770
+ return Math.max(1, Math.ceil(((proposal.decidedAt ?? proposal.at) + Limits.UNDO_DAYS * DAY_MS - now) / DAY_MS));
771
+ }
772
+ InboxUtil.undoDaysLeft = undoDaysLeft;
773
+ function conversation(proposal) {
774
+ const action = proposal.action;
775
+ return proposal.sessionFile ?? (action?.type === "session" ? action.sessionFile : undefined) ?? proposal.evidence?.[0];
776
+ }
777
+ InboxUtil.conversation = conversation;
320
778
  function home(proposals, seen, now) {
321
779
  const open = waiting(proposals);
322
780
  const did = done(proposals, now).filter((proposal) => proposal.state === "done");
@@ -582,6 +1040,9 @@ class ProposalBook {
582
1040
  return this.status(String(kind), await this.mode(), await this.locks());
583
1041
  });
584
1042
  }
1043
+ currentMode() {
1044
+ return this.mode();
1045
+ }
585
1046
  setMode(mode) {
586
1047
  return this.serial(async () => {
587
1048
  if (!MODES.includes(mode)) {
@@ -634,7 +1095,7 @@ class ProposalBook {
634
1095
  await this.host.setSessionName(session.sessionId, proposal.title).catch(() => {
635
1096
  return;
636
1097
  });
637
- await this.host.prompt(session.sessionId, { clientMessageId: `ta-initiative:${proposal.id}`, message: prompt });
1098
+ this.telling.push(() => this.host.prompt(session.sessionId, { clientMessageId: `ta-initiative:${proposal.id}`, message: prompt }).catch((error) => console.error("ta-initiative could not start what was accepted:", error)));
638
1099
  return session.sessionFile ?? (await this.host.listSessions()).find((info) => info.sessionId === session.sessionId)?.sessionFile;
639
1100
  }
640
1101
  later(proposal, sessionFile, clientMessageId, context, prompt) {
@@ -660,10 +1121,7 @@ class ProposalBook {
660
1121
  const cwd = await this.host.sessionCwd(sessionFile) ?? (await this.host.getServerInfo()).cwd;
661
1122
  session = await this.host.openSession({ cwd, sessionFile });
662
1123
  }
663
- await this.host.prompt(session.sessionId, { clientMessageId, message: `<context>
664
- ${context}
665
- </context>
666
- ${prompt}`, streamingBehavior: "followUp" });
1124
+ await this.host.prompt(session.sessionId, { clientMessageId, message: TaMessageContext.wrap(context, prompt), streamingBehavior: "followUp" });
667
1125
  }
668
1126
  async tellNow(proposal) {
669
1127
  const now = this.now();
@@ -819,15 +1277,12 @@ var MaterialUtil;
819
1277
  `Review the scheduled tasks of the user now, from the <${SECTION}> section of your system prompt. Nobody is watching: ask nothing, decide and report; the user reads it later and may answer here. Write the report in ${{ "zh-CN": "Simplified Chinese", "zh-TW": "Traditional Chinese", "en-US": "English", "ja-JP": "Japanese" }[TaLanguageUtil.of(language)]}.`
820
1278
  ].join(`
821
1279
  `);
822
- return `<context>
823
- ${context}
824
- </context>
825
- ${TaLanguageUtil.pick(language, {
1280
+ return TaMessageContext.wrap(context, TaLanguageUtil.pick(language, {
826
1281
  "zh-CN": "回顾一下最近的工作,整理定时任务",
827
1282
  "zh-TW": "回顧一下最近的工作,整理定時任務",
828
1283
  "en-US": "Look back at the recent work and tidy the scheduled tasks",
829
1284
  "ja-JP": "最近の作業を見直し、スケジュールタスクを整理"
830
- })}`;
1285
+ }));
831
1286
  }
832
1287
  MaterialUtil.message = message;
833
1288
  function since(prompt) {
@@ -854,6 +1309,9 @@ ${TaLanguageUtil.pick(language, {
854
1309
  ...input.learn ? [
855
1310
  `5b. Learn the user, so that every conversation of Ta knows them: rewrite with ${PROFILE_TOOL} the whole of what you know of them (below), from the requests: who they are and what they work on; how they want things done (what they corrected, what they said "always", "never", "next time" about, what they approved that was not obvious); what they usually want next after a kind of work (test, commit, push, a screenshot, a report), so that Ta does it without being asked; and what Ta should do on its own and what it must ask first. Markdown, short lines under a few headings, at most ${Limits.PROFILE_CHARS} characters, in the language of the user; keep what still holds, drop what turned out wrong, never a secret (keys, tokens, passwords) or a private matter. Leave it as it is when you learned nothing new.`
856
1311
  ] : [],
1312
+ ...input.goals ? [
1313
+ `5c. Look at every goal below (Ta works on each in a conversation of its own until the user accepts its result): say in the report a line for each, how it moved since the last review and whether it still looks realistic. One stuck, far off what was meant, or no longer wanted: propose a change (${PROPOSE_TOOL}, kind goal.update, a prompt you carry out here once accepted: \`ta call @celljs/ta-goals pause '<title>'\`, or a direction with goal_note). Work the user keeps asking for that is a result to reach rather than something to repeat on a schedule: propose it as a goal (kind goal.set, prompt "Draft a goal for …"), never start one.`
1314
+ ] : [],
857
1315
  input.auto ? `6. Reviews come every ${input.every} days, and the user lets you choose: call ${PACE_TOOL} once with the days to the next review (1 to 30) and why: sooner while the work changes and you found much to do, later when nothing changed.` : `6. Reviews come every ${input.every} days, as the user set; do not change it.`,
858
1316
  `7. End with a short report: what was done on its own, what waits for the user in their suggestions (on the double's home), what went to the brief, each with why in a few words, as ${PROPOSE_TOOL} answered;${input.learn ? " what you newly learned of the user, in a line or two;" : ""} nothing more. On a card, the tasks go in a table or steps, not in changes (which are files). When nothing needed doing, say so in one line. What waits in the suggestions is asked there: the report itself asks nothing, its card is done (partial when something failed), never blocked nor with choices.`,
859
1317
  "Use the tools only for what you change and what you must check (a file, git log); the material is below.",
@@ -889,6 +1347,9 @@ ${TaLanguageUtil.pick(language, {
889
1347
  lines.push(`- And ${left} more conversations, left out for length: search_conversations finds them.`);
890
1348
  }
891
1349
  lines.push("", ...tasks);
1350
+ if (input.goals) {
1351
+ lines.push("", ...goalLines(input.goals, input.now));
1352
+ }
892
1353
  if (input.learn) {
893
1354
  lines.push("", input.profile ? `What you know of the user so far:
894
1355
  ${input.profile}` : "What you know of the user so far: nothing yet.");
@@ -909,6 +1370,27 @@ ${input.profile}` : "What you know of the user so far: nothing yet.");
909
1370
  `);
910
1371
  }
911
1372
  MaterialUtil.profileSection = profileSection;
1373
+ function goalLines(goals, now) {
1374
+ if (goals.length === 0) {
1375
+ return ["Goals: none."];
1376
+ }
1377
+ return [
1378
+ "Goals:",
1379
+ ...goals.map((goal) => {
1380
+ const done = goal.plan.filter((step) => step.done).length;
1381
+ const last = goal.log[goal.log.length - 1];
1382
+ const days = Math.max(0, Math.floor((now - goal.createdAt) / 86400000));
1383
+ return [
1384
+ `- ${goal.title} · ${goal.status}`,
1385
+ goal.plan.length ? ` · step ${done}/${goal.plan.length}` : "",
1386
+ ` · ${days} days, ${Math.round(goal.totalMs / 60000)} min worked`,
1387
+ last ? ` · last ${day(last.at)}: ${last.did}` : "",
1388
+ goal.result ? ` · result: ${goal.result.summary}` : ""
1389
+ ].join("");
1390
+ })
1391
+ ];
1392
+ }
1393
+ MaterialUtil.goalLines = goalLines;
912
1394
  function taskLines(tasks, now) {
913
1395
  if (!tasks) {
914
1396
  return ["Scheduled tasks: not available, the package Scheduled tasks is off; add nothing, and say so."];
@@ -1164,6 +1646,15 @@ class ReviewHost {
1164
1646
  }
1165
1647
 
1166
1648
  // web-src/initiative-service.ts
1649
+ var IDEAS_EVERY_MS = 60000;
1650
+ var IDEAS_READ_MS = 15 * 60000;
1651
+ function readManifestPi(root) {
1652
+ try {
1653
+ return JSON.parse(readFileSync(join(root, "package.json"), "utf8")).pi;
1654
+ } catch {
1655
+ return;
1656
+ }
1657
+ }
1167
1658
  var FORMER_KEYS = [Keys.SETTINGS, Keys.FILE, Keys.LAST, Keys.NOTE, Keys.PROFILE];
1168
1659
 
1169
1660
  class InitiativeHost {
@@ -1171,9 +1662,11 @@ class InitiativeHost {
1171
1662
  book;
1172
1663
  review;
1173
1664
  stopEvents;
1665
+ stopCommands;
1666
+ ideasTimer;
1174
1667
  constructor(host, now = Date.now) {
1175
1668
  this.host = host;
1176
- this.book = new ProposalBook(host, [...CRON_KINDS, ...CHAT_KINDS, ...EVENT_KINDS], now);
1669
+ this.book = new ProposalBook(host, [...CRON_KINDS, ...CHAT_KINDS, ...EVENT_KINDS, ...IDEA_KINDS], now);
1177
1670
  this.review = new ReviewHost(host, now);
1178
1671
  }
1179
1672
  async start() {
@@ -1181,9 +1674,15 @@ class InitiativeHost {
1181
1674
  await this.book.load();
1182
1675
  this.review.start();
1183
1676
  this.stopEvents = this.host.onSessionEvent?.((event) => void this.onTurn(event).catch((error) => console.error("ta-initiative:", error)));
1677
+ this.stopCommands = InitiativeCommands.register(this.host, this.book);
1678
+ this.offerIdeas();
1679
+ this.ideasTimer = setInterval(() => void this.offerIdeas(), IDEAS_EVERY_MS);
1680
+ this.ideasTimer.unref?.();
1184
1681
  }
1185
1682
  dispose() {
1186
1683
  this.stopEvents?.();
1684
+ this.stopCommands?.();
1685
+ clearInterval(this.ideasTimer);
1187
1686
  this.review.dispose();
1188
1687
  }
1189
1688
  async onTurn(event) {
@@ -1197,6 +1696,24 @@ class InitiativeHost {
1197
1696
  await this.book.expireKey(settled);
1198
1697
  }
1199
1698
  }
1699
+ ideaPackages;
1700
+ async offerIdeas() {
1701
+ try {
1702
+ if (this.host.presence && this.host.presence().pages === 0) {
1703
+ return;
1704
+ }
1705
+ const now = Date.now();
1706
+ if (!this.ideaPackages || now - this.ideaPackages.at > IDEAS_READ_MS) {
1707
+ const list = (await this.host.listPackages()).filter((pkg) => pkg.enabled).map((pkg) => ({ name: pkg.name, ideas: IdeaProposals.read(readManifestPi(pkg.root)) })).filter((pkg) => pkg.ideas.length > 0);
1708
+ this.ideaPackages = { at: now, list };
1709
+ }
1710
+ for (const input of IdeaProposals.due(this.ideaPackages.list, await this.book.list(), InitiativeServerTexts.language())) {
1711
+ await this.book.offer(input);
1712
+ }
1713
+ } catch (error) {
1714
+ console.error("ta-initiative could not offer ideas:", error);
1715
+ }
1716
+ }
1200
1717
  defineKind(kind) {
1201
1718
  return this.book.defineKind(kind);
1202
1719
  }
@@ -1225,6 +1742,7 @@ class InitiativeHost {
1225
1742
  return this.book.setMode(mode);
1226
1743
  }
1227
1744
  async proposals() {
1745
+ await this.offerIdeas();
1228
1746
  return this.book.list();
1229
1747
  }
1230
1748
  reviewStatus() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-initiative",
3
- "version": "4.17.0",
3
+ "version": "4.18.0",
4
4
  "description": "A pi package for Ta: what Ta does on its own and how far, by kind and by the user's trust; proposals other packages offer, the user's suggestions to decide or undo, and a weekly review that keeps the scheduled tasks and learns the user",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -27,8 +27,8 @@
27
27
  "watch": "tsc -b -w --preserveWatchOutput"
28
28
  },
29
29
  "devDependencies": {
30
- "@celljs/ta-protocol": "4.17.0",
31
- "@celljs/ta-web": "4.17.0",
30
+ "@celljs/ta-protocol": "4.18.0",
31
+ "@celljs/ta-web": "4.18.0",
32
32
  "@types/react": "^19.3.0"
33
33
  },
34
34
  "publishConfig": {