@celljs/ta-goals 0.0.0-stage → 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 ADDED
@@ -0,0 +1,1386 @@
1
+ // web-src/host.ts
2
+ import { watch } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { isAbsolute, join } from "node:path";
5
+
6
+ // ../ta-protocol/esm/common/message-protocol.js
7
+ var TaMessageContext;
8
+ (function(TaMessageContext2) {
9
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
10
+ function wrap(context, message) {
11
+ return `<context>
12
+ ${context}
13
+ </context>
14
+ ${message}`;
15
+ }
16
+ TaMessageContext2.wrap = wrap;
17
+ function strip(message) {
18
+ return message.replace(BLOCK, "");
19
+ }
20
+ TaMessageContext2.strip = strip;
21
+ function read(message) {
22
+ var _a;
23
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
24
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
25
+ }
26
+ TaMessageContext2.read = read;
27
+ })(TaMessageContext || (TaMessageContext = {}));
28
+ var TaMessageSource;
29
+ (function(TaMessageSource2) {
30
+ TaMessageSource2.DOUBLE = "ta:double";
31
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
32
+ function mark(message, from, detail) {
33
+ return marked(message, line(from, detail));
34
+ }
35
+ TaMessageSource2.mark = mark;
36
+ function notice(message, from, detail) {
37
+ return marked(message, line(from, detail, true));
38
+ }
39
+ TaMessageSource2.notice = notice;
40
+ function line(from, detail, notice2 = false) {
41
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
42
+ }
43
+ TaMessageSource2.line = line;
44
+ function of(message) {
45
+ const context = TaMessageContext.read(message);
46
+ const match = context === undefined ? null : LINE.exec(context);
47
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
48
+ }
49
+ TaMessageSource2.of = of;
50
+ function isNotice(message) {
51
+ var _a;
52
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
53
+ }
54
+ TaMessageSource2.isNotice = isNotice;
55
+ TaMessageSource2.SECTION = "ta-sources";
56
+ TaMessageSource2.PROMPT = [
57
+ "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.",
58
+ "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:",
59
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
60
+ "- 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).",
61
+ "- Never quote it as the user's words nor answer it as if they had said it."
62
+ ].join(`
63
+ `);
64
+ function marked(message, source) {
65
+ if (/^[/!]/.test(message) || of(message)) {
66
+ return message;
67
+ }
68
+ const context = TaMessageContext.read(message);
69
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
70
+ ${source}`, TaMessageContext.strip(message));
71
+ }
72
+ })(TaMessageSource || (TaMessageSource = {}));
73
+ var TaImageNote;
74
+ (function(TaImageNote2) {
75
+ 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 [^\]]+\.\]$/;
76
+ function strip(text) {
77
+ const lines = text.split(`
78
+ `);
79
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
80
+ if (kept.length === lines.length) {
81
+ return text;
82
+ }
83
+ return kept.join(`
84
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
85
+ }
86
+ TaImageNote2.strip = strip;
87
+ })(TaImageNote || (TaImageNote = {}));
88
+ var TaImageSize;
89
+ (function(TaImageSize2) {
90
+ const JPEG_BYTES = 256 * 1024;
91
+ function of(base64) {
92
+ var _a, _b, _c;
93
+ let bytes;
94
+ try {
95
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
96
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
97
+ } catch (_d) {
98
+ return;
99
+ }
100
+ 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);
101
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
102
+ }
103
+ TaImageSize2.of = of;
104
+ function u16be(bytes, at) {
105
+ return bytes[at] << 8 | bytes[at + 1];
106
+ }
107
+ function u16le(bytes, at) {
108
+ return bytes[at] | bytes[at + 1] << 8;
109
+ }
110
+ function u24le(bytes, at) {
111
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
112
+ }
113
+ function u32be(bytes, at) {
114
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
115
+ }
116
+ function text(bytes, at, length) {
117
+ return String.fromCharCode(...bytes.subarray(at, at + length));
118
+ }
119
+ function png(bytes) {
120
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
121
+ }
122
+ function gif(bytes) {
123
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
124
+ }
125
+ function webp(bytes) {
126
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
127
+ return;
128
+ }
129
+ switch (text(bytes, 12, 4)) {
130
+ case "VP8 ":
131
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
132
+ case "VP8L": {
133
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
134
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
135
+ }
136
+ case "VP8X":
137
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
138
+ default:
139
+ return;
140
+ }
141
+ }
142
+ function jpeg(bytes) {
143
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
144
+ return;
145
+ }
146
+ let at = 2;
147
+ while (at + 9 < bytes.length) {
148
+ if (bytes[at] !== 255) {
149
+ return;
150
+ }
151
+ const marker = bytes[at + 1];
152
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
153
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
154
+ }
155
+ at += 2 + u16be(bytes, at + 2);
156
+ }
157
+ return;
158
+ }
159
+ })(TaImageSize || (TaImageSize = {}));
160
+ var TaAgentSummary;
161
+ (function(TaAgentSummary2) {
162
+ const START = /^\s*<conversation_history_summary>/;
163
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
164
+ function read(text) {
165
+ if (!START.test(text)) {
166
+ return;
167
+ }
168
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
169
+ }
170
+ TaAgentSummary2.read = read;
171
+ function strip(text) {
172
+ return text.replace(BLOCK, "");
173
+ }
174
+ TaAgentSummary2.strip = strip;
175
+ })(TaAgentSummary || (TaAgentSummary = {}));
176
+ var TaSkillUse;
177
+ (function(TaSkillUse2) {
178
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
179
+ function parse(message) {
180
+ var _a;
181
+ const match = BLOCK.exec(message);
182
+ if (!match) {
183
+ return;
184
+ }
185
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
186
+ }
187
+ TaSkillUse2.parse = parse;
188
+ function command(use) {
189
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
190
+ }
191
+ TaSkillUse2.command = command;
192
+ })(TaSkillUse || (TaSkillUse = {}));
193
+ var TaTaskNote;
194
+ (function(TaTaskNote2) {
195
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
196
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
197
+ function write(note) {
198
+ const attributes = [`id="${quote(note.id)}"`];
199
+ if (note.was !== undefined) {
200
+ attributes.push(`was="${quote(note.was)}"`);
201
+ }
202
+ attributes.push(`title="${quote(note.title)}"`);
203
+ if (note.status !== undefined) {
204
+ attributes.push(`status="${quote(note.status)}"`);
205
+ }
206
+ return `<task_${note.kind} ${attributes.join(" ")}>
207
+ ${note.body}
208
+ </task_${note.kind}>`;
209
+ }
210
+ TaTaskNote2.write = write;
211
+ function parse(text) {
212
+ const match = NOTE.exec(text.trim());
213
+ if (!match) {
214
+ return;
215
+ }
216
+ const attributes = {};
217
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
218
+ attributes[name] = unquote(value);
219
+ }
220
+ if (!attributes.id || attributes.title === undefined) {
221
+ return;
222
+ }
223
+ const { id, title, status, was } = attributes;
224
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
225
+ }
226
+ TaTaskNote2.parse = parse;
227
+ function quote(text) {
228
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
229
+ }
230
+ function unquote(text) {
231
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
232
+ }
233
+ })(TaTaskNote || (TaTaskNote = {}));
234
+ var TaSecretRef;
235
+ (function(TaSecretRef2) {
236
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
237
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
238
+ const KINDS = [
239
+ [/^PHONE(?:_\d+)?$/, "phone"],
240
+ [/^EMAIL(?:_\d+)?$/, "email"],
241
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
242
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
243
+ ];
244
+ function has(text) {
245
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
246
+ }
247
+ TaSecretRef2.has = has;
248
+ function kind(name) {
249
+ var _a;
250
+ var _b;
251
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
252
+ }
253
+ TaSecretRef2.kind = kind;
254
+ function split(text) {
255
+ if (!has(text)) {
256
+ return [{ text }];
257
+ }
258
+ const parts = [];
259
+ let at = 0;
260
+ for (const match of text.matchAll(REF)) {
261
+ if (match.index > at) {
262
+ parts.push({ text: text.slice(at, match.index) });
263
+ }
264
+ parts.push({ secret: match[1], kind: kind(match[1]) });
265
+ at = match.index + match[0].length;
266
+ }
267
+ if (at < text.length) {
268
+ parts.push({ text: text.slice(at) });
269
+ }
270
+ return parts;
271
+ }
272
+ TaSecretRef2.split = split;
273
+ function plain(text, label) {
274
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
275
+ }
276
+ TaSecretRef2.plain = plain;
277
+ })(TaSecretRef || (TaSecretRef = {}));
278
+
279
+ // ../ta-protocol/esm/common/ta-extension-host.js
280
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
281
+ var TA_HOST_EVENT = "ta:host";
282
+ var TaHostUtil;
283
+ (function(TaHostUtil2) {
284
+ TaHostUtil2.WAIT_MS = 1000;
285
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
286
+ return new Promise((resolve) => {
287
+ let heard = false;
288
+ let answered = false;
289
+ const timer = setTimeout(() => resolve(undefined), waitMs);
290
+ const request = {
291
+ name,
292
+ heard: () => {
293
+ heard = true;
294
+ },
295
+ resolve: (answer) => {
296
+ answered = true;
297
+ clearTimeout(timer);
298
+ resolve(answer);
299
+ }
300
+ };
301
+ events.emit(TA_HOST_EVENT, request);
302
+ if (!heard && !answered) {
303
+ clearTimeout(timer);
304
+ resolve(undefined);
305
+ }
306
+ });
307
+ }
308
+ TaHostUtil2.reach = reach;
309
+ function marked(systemPrompt, mark) {
310
+ return role(systemPrompt).includes(mark);
311
+ }
312
+ TaHostUtil2.marked = marked;
313
+ function role(systemPrompt) {
314
+ if (!systemPrompt) {
315
+ return "";
316
+ }
317
+ const open = `<addendum>
318
+ `;
319
+ const start = systemPrompt.indexOf(open);
320
+ const context = systemPrompt.indexOf(`<project_context>
321
+ `);
322
+ if (start < 0 || context >= 0 && context < start) {
323
+ return "";
324
+ }
325
+ const end = systemPrompt.indexOf(`
326
+ </addendum>`, start);
327
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
328
+ }
329
+ TaHostUtil2.role = role;
330
+ })(TaHostUtil || (TaHostUtil = {}));
331
+ var TA_TELLS_OF_ITS_TURNS_MARK = "[ta:tells-of-its-turns]";
332
+ var TA_BRIEF_SOURCE = "brief";
333
+ var TA_ASK_ENTRY = "ta-ask";
334
+ var TaAskUtil;
335
+ (function(TaAskUtil2) {
336
+ const LENGTH = 120;
337
+ function entry(question) {
338
+ const line = question.replace(/\s+/g, " ").trim();
339
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
340
+ }
341
+ TaAskUtil2.entry = entry;
342
+ function asking(entries) {
343
+ var _a;
344
+ for (let i = entries.length - 1;i >= 0; i--) {
345
+ const entry2 = entries[i];
346
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
347
+ return;
348
+ }
349
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
350
+ return read(entry2);
351
+ }
352
+ }
353
+ return;
354
+ }
355
+ TaAskUtil2.asking = asking;
356
+ function next(asked, entry2) {
357
+ var _a;
358
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
359
+ return;
360
+ }
361
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
362
+ }
363
+ TaAskUtil2.next = next;
364
+ function read(found) {
365
+ var _a;
366
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
367
+ if (typeof question !== "string" || !question.trim()) {
368
+ return;
369
+ }
370
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
371
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
372
+ }
373
+ })(TaAskUtil || (TaAskUtil = {}));
374
+
375
+ // web-src/goal-protocol.ts
376
+ var NAME = "@celljs/ta-goals";
377
+ var CARD = "ta-goal";
378
+ var RESULT = "ta-goal-result";
379
+ var GOAL_MARK = "[ta:goal]";
380
+ var Keys;
381
+ ((Keys) => {
382
+ Keys.GOALS = "goals";
383
+ Keys.SETTINGS = "settings";
384
+ })(Keys ||= {});
385
+ var Limits;
386
+ ((Limits) => {
387
+ Limits.ACTIVE = 3;
388
+ Limits.ACTIVE_MAX = 8;
389
+ Limits.FAILURES = 3;
390
+ Limits.EVENTS = 10;
391
+ Limits.EVENT_CHARS = 2000;
392
+ Limits.SETTLE_MS = 5000;
393
+ Limits.WATCH = 10;
394
+ Limits.BRIEF_LINES = 6;
395
+ Limits.PACE_MS = 4 * 60 * 60000;
396
+ Limits.PACE_MIN_MS = 15 * 60000;
397
+ Limits.PACE_MAX_MS = 7 * 24 * 60 * 60000;
398
+ Limits.BUDGET_MS = 2 * 60 * 60000;
399
+ Limits.BUDGET_MAX_MS = 12 * 60 * 60000;
400
+ Limits.BUSY_MS = 10 * 60000;
401
+ Limits.LOG = 60;
402
+ Limits.ITEMS = 20;
403
+ Limits.TEXT = 400;
404
+ Limits.SLEEP_MS = 60000;
405
+ })(Limits ||= {});
406
+
407
+ // web-src/goal-kinds.ts
408
+ var GOAL_KINDS = [
409
+ {
410
+ id: "goal.set",
411
+ owner: NAME,
412
+ title: {
413
+ en: "Hand a result you keep coming back to over as a goal",
414
+ zh: "把反复在追的结果交给 Ta 当目标",
415
+ tw: "把反覆在追的結果交給 Ta 當目標",
416
+ ja: "何度も追っている結果を目標として任せる"
417
+ },
418
+ reversible: false,
419
+ level: "ask"
420
+ },
421
+ {
422
+ id: "goal.update",
423
+ owner: NAME,
424
+ title: {
425
+ en: "Change a goal at work (pause it, a direction, its pace)",
426
+ zh: "调整进行中的目标(暂停、方向、节奏)",
427
+ tw: "調整進行中的目標(暫停、方向、節奏)",
428
+ ja: "進行中の目標を調整(一時停止、方向、ペース)"
429
+ },
430
+ reversible: false,
431
+ level: "ask"
432
+ }
433
+ ];
434
+
435
+ // web-src/goal-util.ts
436
+ var GoalUtil;
437
+ ((GoalUtil) => {
438
+ const STATUSES = ["working", "review", "done", "paused"];
439
+ function duration(value) {
440
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
441
+ return Math.round(value * 60000);
442
+ }
443
+ if (typeof value !== "string") {
444
+ return;
445
+ }
446
+ const text2 = value.trim().toLowerCase().replace(/^every\s+/, "");
447
+ const parts = /^(?:(\d+(?:\.\d+)?)d)?\s*(?:(\d+(?:\.\d+)?)h)?\s*(?:(\d+(?:\.\d+)?)m(?:in)?)?$/.exec(text2);
448
+ if (!text2 || !parts || !(parts[1] || parts[2] || parts[3])) {
449
+ return;
450
+ }
451
+ const ms = (Number(parts[1] ?? 0) * 24 * 60 + Number(parts[2] ?? 0) * 60 + Number(parts[3] ?? 0)) * 60000;
452
+ return ms > 0 ? Math.round(ms) : undefined;
453
+ }
454
+ GoalUtil.duration = duration;
455
+ function line(value) {
456
+ if (typeof value !== "string") {
457
+ return "";
458
+ }
459
+ const text2 = value.replace(/\s+/g, " ").trim();
460
+ return text2.length > Limits.TEXT ? `${text2.slice(0, Limits.TEXT - 1)}…` : text2;
461
+ }
462
+ GoalUtil.line = line;
463
+ function lines(value) {
464
+ const list = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
465
+ return [...new Set(list.map(line).filter(Boolean))].slice(0, Limits.ITEMS);
466
+ }
467
+ GoalUtil.lines = lines;
468
+ function clamp(value, min, max) {
469
+ return Math.min(max, Math.max(min, value));
470
+ }
471
+ function draft(input, defaults = settings(undefined)) {
472
+ const given = input && typeof input === "object" ? input : {};
473
+ const title = line(given.title);
474
+ if (!title) {
475
+ throw new Error("A goal needs a title: what to achieve, in a line.");
476
+ }
477
+ const doneWhen = lines(given.doneWhen);
478
+ if (doneWhen.length === 0) {
479
+ throw new Error("A goal needs doneWhen: how it is judged done, each a check the user can see.");
480
+ }
481
+ const pace = duration(given.every);
482
+ const budget = duration(given.budget);
483
+ return {
484
+ title,
485
+ doneWhen,
486
+ constraints: lines(given.constraints),
487
+ askFirst: lines(given.askFirst),
488
+ paceMs: clamp(pace ?? defaults.paceMs, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS),
489
+ budgetMs: clamp(budget ?? defaults.budgetMs, Limits.PACE_MIN_MS, Limits.BUDGET_MAX_MS)
490
+ };
491
+ }
492
+ GoalUtil.draft = draft;
493
+ function settings(value) {
494
+ const given = value && typeof value === "object" ? value : {};
495
+ const number = (key, fallback, min, max) => typeof given[key] === "number" && Number.isFinite(given[key]) ? clamp(Math.round(given[key]), min, max) : fallback;
496
+ return {
497
+ paceMs: number("paceMs", Limits.PACE_MS, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS),
498
+ budgetMs: number("budgetMs", Limits.BUDGET_MS, Limits.PACE_MIN_MS, Limits.BUDGET_MAX_MS),
499
+ active: number("active", Limits.ACTIVE, 1, Limits.ACTIVE_MAX)
500
+ };
501
+ }
502
+ GoalUtil.settings = settings;
503
+ function brief(goals) {
504
+ const items = goals.flatMap((goal) => [
505
+ ...goal.log.slice(-Limits.BRIEF_LINES).map((entry) => ({
506
+ at: entry.at,
507
+ text: `${goal.title}: ${entry.did}${entry.next ? ` (next: ${entry.next})` : ""}`
508
+ })),
509
+ ...goal.status === "review" ? [{ at: goal.updatedAt, text: `${goal.title}: its result waits for the user to accept` }] : [],
510
+ ...goal.status === "paused" && (goal.failures ?? 0) >= Limits.FAILURES ? [{ at: goal.updatedAt, text: `${goal.title}: paused after ${Limits.FAILURES} failed turns in a row` }] : []
511
+ ]);
512
+ return {
513
+ section: "Progress of the user's goals, each worked on by Ta in a conversation of its own",
514
+ instruction: "One line per goal that moved since the last brief: where it is now, in the words of the user. First a result that waits for the user to accept, or a goal that stopped; leave out goals that did not move.",
515
+ items: items.sort((a, b) => a.at - b.at).slice(-30)
516
+ };
517
+ }
518
+ GoalUtil.brief = brief;
519
+ function card(code) {
520
+ const given = json(code);
521
+ const title = line(given?.title);
522
+ if (!given || !title) {
523
+ return;
524
+ }
525
+ const pace = duration(given.every);
526
+ const budget = duration(given.budget);
527
+ return {
528
+ title,
529
+ doneWhen: lines(given.doneWhen),
530
+ constraints: lines(given.constraints),
531
+ askFirst: lines(given.askFirst),
532
+ ...pace ? { paceMs: clamp(pace, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS) } : {},
533
+ ...budget ? { budgetMs: clamp(budget, Limits.PACE_MIN_MS, Limits.BUDGET_MAX_MS) } : {}
534
+ };
535
+ }
536
+ GoalUtil.card = card;
537
+ function result(input) {
538
+ const given = input && typeof input === "object" ? input : undefined;
539
+ const summary = line(given?.summary);
540
+ if (!given || !summary) {
541
+ return;
542
+ }
543
+ const criteria = (Array.isArray(given.criteria) ? given.criteria : []).map((item) => {
544
+ const one = item && typeof item === "object" ? item : { text: item };
545
+ const evidence = line(one.evidence);
546
+ return { text: line(one.text), met: one.met !== false, ...evidence ? { evidence } : {} };
547
+ }).filter((item) => item.text).slice(0, Limits.ITEMS);
548
+ return { summary, criteria, outputs: lines(given.outputs) };
549
+ }
550
+ GoalUtil.result = result;
551
+ function resultCard(code) {
552
+ return result(json(code));
553
+ }
554
+ GoalUtil.resultCard = resultCard;
555
+ function change(input) {
556
+ const given = input && typeof input === "object" ? input : {};
557
+ const change2 = {};
558
+ if (Array.isArray(given.plan)) {
559
+ change2.plan = given.plan.map((item) => {
560
+ const one = item && typeof item === "object" ? item : { text: item };
561
+ return { text: line(one.text), done: one.done === true };
562
+ }).filter((step) => step.text).slice(0, Limits.ITEMS);
563
+ }
564
+ const did = line(given.did);
565
+ const next = line(given.next);
566
+ if (did) {
567
+ change2.did = did;
568
+ }
569
+ if (next) {
570
+ change2.next = next;
571
+ }
572
+ const wake = duration(given.wakeIn);
573
+ if (wake) {
574
+ change2.wakeMs = clamp(wake, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS);
575
+ }
576
+ if (given.status !== undefined) {
577
+ if (!STATUSES.includes(given.status)) {
578
+ throw new Error(`status is one of ${STATUSES.join(", ")}.`);
579
+ }
580
+ change2.status = given.status;
581
+ }
582
+ const result2 = GoalUtil.result(given.result);
583
+ if (result2) {
584
+ change2.result = result2;
585
+ }
586
+ if (given.watch !== undefined) {
587
+ change2.watch = lines(given.watch).slice(0, Limits.WATCH);
588
+ }
589
+ return change2;
590
+ }
591
+ GoalUtil.change = change;
592
+ function short(ms) {
593
+ const minutes = Math.round(ms / 60000);
594
+ if (minutes % 1440 === 0) {
595
+ return `${minutes / 1440}d`;
596
+ }
597
+ const hours = Math.floor(minutes / 60);
598
+ const rest = minutes % 60;
599
+ return hours ? `${hours}h${rest ? `${rest}m` : ""}` : `${rest}m`;
600
+ }
601
+ GoalUtil.short = short;
602
+ function day(at) {
603
+ const date = new Date(at);
604
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
605
+ }
606
+ GoalUtil.day = day;
607
+ function left(goal, now) {
608
+ const used = goal.used.day === day(now) ? goal.used.ms : 0;
609
+ return Math.max(0, goal.budgetMs - used);
610
+ }
611
+ GoalUtil.left = left;
612
+ function tomorrow(now) {
613
+ const date = new Date(now);
614
+ date.setHours(24, 5, 0, 0);
615
+ return date.getTime();
616
+ }
617
+ GoalUtil.tomorrow = tomorrow;
618
+ function find(goals, ref) {
619
+ const key = String(ref ?? "").trim();
620
+ return goals.find((goal) => goal.id === key || !!goal.sessionFile && goal.sessionFile === key) ?? [...goals].sort((a, b) => b.createdAt - a.createdAt).find((goal) => goal.title === key);
621
+ }
622
+ GoalUtil.find = find;
623
+ function progress(goal) {
624
+ return { done: goal.plan.filter((step) => step.done).length, total: goal.plan.length };
625
+ }
626
+ GoalUtil.progress = progress;
627
+ function ignored(name) {
628
+ return /(^|[\\/])(\.git|node_modules|dist|lib|esm|build|out|\.turbo|\.next|coverage)([\\/]|$)/.test(name);
629
+ }
630
+ GoalUtil.ignored = ignored;
631
+ function event(events, text2) {
632
+ const said = text2.length > Limits.EVENT_CHARS ? `${text2.slice(0, Limits.EVENT_CHARS - 1)}…` : text2;
633
+ return [...events ?? [], said].slice(-Limits.EVENTS);
634
+ }
635
+ GoalUtil.event = event;
636
+ function context(goal, now, hookUrl) {
637
+ const list = (items) => items.length ? items.map((item) => `- ${item}`).join(`
638
+ `) : "- (none)";
639
+ const plan = goal.plan.length ? goal.plan.map((step) => `- [${step.done ? "x" : " "}] ${step.text}`).join(`
640
+ `) : "- (no plan yet: make one)";
641
+ const log = goal.log.slice(-8).map((entry) => `- ${new Date(entry.at).toISOString().slice(0, 16)} ${entry.did}${entry.next ? ` / next: ${entry.next}` : ""}`);
642
+ const minutes = (ms) => `${Math.round(ms / 60000)} min`;
643
+ return [
644
+ `Goal: ${goal.title}`,
645
+ `Turn: ${goal.turns + 1}`,
646
+ "Done when:",
647
+ list(goal.doneWhen),
648
+ "Constraints:",
649
+ list(goal.constraints),
650
+ "Ask the user first before:",
651
+ list(goal.askFirst),
652
+ "Plan:",
653
+ plan,
654
+ "Log (latest last):",
655
+ log.length ? log.join(`
656
+ `) : "- (nothing yet)",
657
+ `Pace: a turn every ${minutes(goal.paceMs)}; work left today: ${minutes(left(goal, now))} of ${minutes(goal.budgetMs)}.`,
658
+ `Wakes also on: ${[goal.watch?.length ? `changes to ${goal.watch.join(", ")}` : "", hookUrl ? `a POST to ${hookUrl} (what is posted is told)` : ""].filter(Boolean).join("; ") || "nothing else"}.`,
659
+ ...goal.events?.length ? ["Since the last turn:", ...goal.events.map((event2) => `- ${event2}`)] : []
660
+ ].join(`
661
+ `);
662
+ }
663
+ GoalUtil.context = context;
664
+ function json(code) {
665
+ try {
666
+ const value = JSON.parse(code);
667
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
668
+ } catch {
669
+ return;
670
+ }
671
+ }
672
+ function blocks(reply, language) {
673
+ const found = [];
674
+ let fence;
675
+ for (const text2 of reply.split(`
676
+ `)) {
677
+ if (!fence) {
678
+ const opening = /^\s*(`{3,}|~{3,})\s*([\w-]*)/.exec(text2);
679
+ if (opening) {
680
+ fence = { mark: opening[1], lines: [], ours: opening[2] === language };
681
+ }
682
+ continue;
683
+ }
684
+ const mark = /^\s*(`{3,}|~{3,})\s*$/.exec(text2)?.[1];
685
+ if (mark && mark[0] === fence.mark[0] && mark.length >= fence.mark.length) {
686
+ if (fence.ours) {
687
+ found.push(fence.lines.join(`
688
+ `));
689
+ }
690
+ fence = undefined;
691
+ } else {
692
+ fence.lines.push(text2);
693
+ }
694
+ }
695
+ return found;
696
+ }
697
+ GoalUtil.blocks = blocks;
698
+ function text(content) {
699
+ if (typeof content === "string") {
700
+ return content;
701
+ }
702
+ return Array.isArray(content) ? content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
703
+ `) : "";
704
+ }
705
+ GoalUtil.text = text;
706
+ })(GoalUtil ||= {});
707
+
708
+ // web-src/goal-prompt.ts
709
+ var GoalPrompt;
710
+ ((GoalPrompt) => {
711
+ function draft(settings) {
712
+ const every = GoalUtil.short(settings.paceMs);
713
+ const budget = GoalUtil.short(settings.budgetMs);
714
+ return `{"title": string, "doneWhen": [checks the user can see], "constraints"?: [what to keep to, how], "askFirst"?: [steps to stop at and ask the user before], "every"?: "${every}" (how often to work on it, 15m to 7d; the user's default ${every}), "budget"?: "${budget}" (work a day at most; the user's default ${budget})}`;
715
+ }
716
+ const OUTCOME = `{"summary": string, "criteria": [{"text": a check of doneWhen, "met": true | false, "evidence": what shows it}], "outputs": [paths, links, pages where the result is]}`;
717
+ function section(goals, settings) {
718
+ const start = `call start_goal with the same fields (without that tool, run \`ta call ${NAME} start '<the JSON of the card>' '{"cwd": "<this directory>"}'\`)`;
719
+ const note = `goal_note (without it, \`ta call ${NAME} note '<title>' '<direction>'\`)`;
720
+ const listed = goals.filter((goal) => goal.status === "working" || goal.status === "review");
721
+ const now = listed.length ? `Goals at work now:
722
+ ${listed.map((goal) => {
723
+ const done = goal.plan.filter((step) => step.done).length;
724
+ return `- ${goal.title} (${goal.status === "review" ? "its result waits for the user" : `${done}/${goal.plan.length} steps`})`;
725
+ }).join(`
726
+ `)}` : "No goal is at work now.";
727
+ return [
728
+ 'What the user tells you is one of three. A request: something to do now; do it, as always. A goal: a result to reach that takes several steps, days, or means not known yet ("get the cold start under 1 s", "two articles a week this month"); Ta pursues it on its own until done. A direction: how things should go, a preference.',
729
+ `For a goal: ask at most 3 questions you truly need, then draft it as a fenced block of language ${CARD} holding JSON, which Ta draws as a card with Start: ${draft(settings)}. Each check of doneWhen must be one the user can verify (a number, a file, something to show). Do not start the work of a goal here. Once the user starts it (taps Start or says so), ${start}: it works in a conversation of its own, at its pace, asks the user only when it must, and comes back with the result to accept. Then tell the user in one line where it is.`,
730
+ `A direction about a goal at work goes to it with ${note}; any other direction is the user's way, kept as they say. When unsure whether it is a request or a goal, treat it as a request.`,
731
+ 'When you notice a result the user keeps coming back to over days, not yet a goal, you may propose handing it over: propose with kind goal.set, its prompt "Draft a goal for …" (accepted, you draft the card here). Never start a goal unasked.',
732
+ `At most ${settings.active} goals work at once.`,
733
+ now
734
+ ].join(`
735
+ `);
736
+ }
737
+ GoalPrompt.section = section;
738
+ function role() {
739
+ return [
740
+ `${GOAL_MARK} ${TA_TELLS_OF_ITS_TURNS_MARK}`,
741
+ "You pursue one goal of the user's, in this conversation of its own, over days if need be. Each turn starts with a message whose <context> holds the goal as it stands: what to achieve, how it is judged done, its constraints, what to ask the user first, the plan, the log and the work left today. Nobody may be watching.",
742
+ 'In each turn: read the goal; take the next step of the plan (make the plan first, a few steps, if there is none); do it with whatever you have (files, commands, the web, other coding agents; a team of agents with create_agent and create_channel for work several hands do better, whose members answer within your turn; a scheduled task for what must recur); keep to the constraints. Stop and ask the user, with a ta-glance card of options, before a step listed under "ask the user first", and before anything that cannot be undone (pushing, publishing, deleting, paying, writing to others). Those steps come before what <ta-initiative> lets you do on your own: in this goal you never do them unasked. Do not ask for what you can find out, and do not propose next steps: the plan is yours to follow.',
743
+ "End every turn by calling goal_update: the plan as it stands (each step done or not), what you did in one line, what comes next, and wakeIn when the next turn should come sooner or later than the pace. Keep replies short: a line of what was done, unless you ask.",
744
+ "When the next step waits for something to happen rather than for a time (a build, a file someone writes, a run of CI on this computer), do not poll: give goal_update watch (files or folders of this directory) or have a git hook or a script post to the webhook of the goal (its address is in the context); the next turn comes as it happens and is told what. What your own turn changes wakes nothing.",
745
+ "When the plan stops working (failures again and again, a constraint in the way), stop and ask the user, with a new plan to choose.",
746
+ `When you believe every check of "done when" holds, call goal_update with status review, then end your reply with a fenced block of language ${RESULT} holding JSON: ${OUTCOME}. Never call the goal done yourself: the user accepts it. When the user accepts it, call goal_update with status done and say one line. When they say something is missing, call goal_update with status working and go on with it.`,
747
+ "Reply in the user's language."
748
+ ].join(`
749
+ `);
750
+ }
751
+ GoalPrompt.role = role;
752
+ GoalPrompt.START_TOOL = {
753
+ name: "start_goal",
754
+ label: "Start goal",
755
+ description: "Starts a goal the user agreed to (they tapped Start on its ta-goal card, or said so): Ta pursues it in a conversation of its own, at its pace and within its budget, and comes back with the result for the user to accept. Give the fields of the card.",
756
+ promptSnippet: "Start a goal the user agreed to",
757
+ parameters: {
758
+ type: "object",
759
+ properties: {
760
+ title: { type: "string", description: "What to achieve, in a line, in the language of the user." },
761
+ doneWhen: { type: "array", items: { type: "string" }, description: "How it is judged done: checks the user can verify." },
762
+ constraints: { type: "array", items: { type: "string" }, description: "What to keep to; the directions of the user." },
763
+ askFirst: { type: "array", items: { type: "string" }, description: "Steps to stop at and ask the user before." },
764
+ every: { type: "string", description: "How often to work on it: 30m, 4h, 1d (default 4h)." },
765
+ budget: { type: "string", description: "Work a day at most: 1h, 2h (default 2h)." }
766
+ },
767
+ required: ["title", "doneWhen"]
768
+ }
769
+ };
770
+ GoalPrompt.NOTE_TOOL = {
771
+ name: "goal_note",
772
+ label: "Tell a goal",
773
+ description: "Gives a goal at work a direction of the user's (a constraint more, a change of course); it reads it on its next turn, which comes soon.",
774
+ promptSnippet: "Give a goal at work a direction of the user's",
775
+ parameters: {
776
+ type: "object",
777
+ properties: {
778
+ goal: { type: "string", description: "Its title." },
779
+ note: { type: "string", description: "The direction, in the user's words." }
780
+ },
781
+ required: ["goal", "note"]
782
+ }
783
+ };
784
+ GoalPrompt.UPDATE_TOOL = {
785
+ name: "goal_update",
786
+ label: "Update goal",
787
+ description: "Records how the goal of this conversation stands, at the end of each turn: the plan, what was done, what comes next, when to come back; status review once every check of done holds (then the result block), done once the user accepted, working when they said something is missing, paused when the user asks to stop for now.",
788
+ promptSnippet: "Record how the goal stands",
789
+ parameters: {
790
+ type: "object",
791
+ properties: {
792
+ plan: {
793
+ type: "array",
794
+ items: { type: "object", properties: { text: { type: "string" }, done: { type: "boolean" } }, required: ["text"] },
795
+ description: "The whole plan as it stands now, a few steps."
796
+ },
797
+ did: { type: "string", description: "What this turn did, in a line, in the language of the user." },
798
+ next: { type: "string", description: "What comes next, in a line." },
799
+ wakeIn: { type: "string", description: "When the next turn should come, when not at the pace: 30m, 2h, 1d." },
800
+ watch: {
801
+ type: "array",
802
+ items: { type: "string" },
803
+ description: "Files or folders of this directory whose changes wake the goal from now on; [] watches nothing."
804
+ },
805
+ status: { type: "string", enum: ["working", "review", "done", "paused"] },
806
+ result: {
807
+ type: "object",
808
+ description: "With status review: the same as the result block.",
809
+ properties: {
810
+ summary: { type: "string" },
811
+ criteria: { type: "array", items: { type: "object" } },
812
+ outputs: { type: "array", items: { type: "string" } }
813
+ }
814
+ }
815
+ }
816
+ }
817
+ };
818
+ })(GoalPrompt ||= {});
819
+
820
+ // web-src/goal-triggers.ts
821
+ class GoalWatchers {
822
+ options;
823
+ watching = new Map;
824
+ pending = new Map;
825
+ constructor(options) {
826
+ this.options = options;
827
+ }
828
+ sync(goals) {
829
+ const wanted = new Map(goals.filter((goal) => goal.status === "working" && goal.watch?.length && !goal.cwd.startsWith("ssh://") && this.options.watch).map((goal) => [goal.id, goal]));
830
+ for (const [id, watched] of [...this.watching]) {
831
+ const goal = wanted.get(id);
832
+ if (!goal || keyOf(goal) !== watched.key) {
833
+ this.stop(id);
834
+ }
835
+ }
836
+ for (const [id, goal] of wanted) {
837
+ if (this.watching.has(id)) {
838
+ continue;
839
+ }
840
+ const stops = (goal.watch ?? []).slice(0, Limits.WATCH).map((path) => {
841
+ try {
842
+ return this.options.watch(goal.cwd, path, (name) => this.changed(id, name));
843
+ } catch {
844
+ return () => {
845
+ return;
846
+ };
847
+ }
848
+ });
849
+ this.watching.set(id, { key: keyOf(goal), stops });
850
+ }
851
+ }
852
+ dispose() {
853
+ for (const id of [...this.watching.keys()]) {
854
+ this.stop(id);
855
+ }
856
+ }
857
+ changed(id, name) {
858
+ if (GoalUtil.ignored(name) || this.options.busy(id)) {
859
+ return;
860
+ }
861
+ const pending = this.pending.get(id) ?? { names: new Set, cancel: () => {
862
+ return;
863
+ } };
864
+ pending.cancel();
865
+ pending.names.add(name);
866
+ pending.cancel = this.options.later(() => {
867
+ this.pending.delete(id);
868
+ this.options.fire(id, [...pending.names].slice(0, 30));
869
+ }, Limits.SETTLE_MS);
870
+ this.pending.set(id, pending);
871
+ }
872
+ stop(id) {
873
+ for (const stop of this.watching.get(id)?.stops ?? []) {
874
+ stop();
875
+ }
876
+ this.watching.delete(id);
877
+ this.pending.get(id)?.cancel();
878
+ this.pending.delete(id);
879
+ }
880
+ }
881
+ function keyOf(goal) {
882
+ return `${goal.cwd}
883
+ ${(goal.watch ?? []).join(`
884
+ `)}`;
885
+ }
886
+
887
+ // ../ta-protocol/esm/common/language.js
888
+ var TaLanguageUtil;
889
+ (function(TaLanguageUtil2) {
890
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
891
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
892
+ function of(tag) {
893
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
894
+ if (/^zh(\b|-)/.test(said)) {
895
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
896
+ }
897
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
898
+ }
899
+ TaLanguageUtil2.of = of;
900
+ function server(env = typeof process === "undefined" ? {} : process.env) {
901
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
902
+ }
903
+ TaLanguageUtil2.server = server;
904
+ function pick(language, words) {
905
+ return words[of(language)];
906
+ }
907
+ TaLanguageUtil2.pick = pick;
908
+ function say(words) {
909
+ return words[server()];
910
+ }
911
+ TaLanguageUtil2.say = say;
912
+ function chinese(language) {
913
+ return of(language).startsWith("zh");
914
+ }
915
+ TaLanguageUtil2.chinese = chinese;
916
+ function cjk(language) {
917
+ return of(language) !== "en-US";
918
+ }
919
+ TaLanguageUtil2.cjk = cjk;
920
+ function list(language, items) {
921
+ return items.join(cjk(language) ? "、" : ", ");
922
+ }
923
+ TaLanguageUtil2.list = list;
924
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
925
+
926
+ // web-src/server-texts.ts
927
+ var GoalServerTexts;
928
+ ((GoalServerTexts) => {
929
+ function begin() {
930
+ return TaLanguageUtil.say({
931
+ "zh-CN": "开始推进这个目标",
932
+ "zh-TW": "開始推進這個目標",
933
+ "en-US": "Start on this goal",
934
+ "ja-JP": "この目標に取りかかる"
935
+ });
936
+ }
937
+ GoalServerTexts.begin = begin;
938
+ function wake() {
939
+ return TaLanguageUtil.say({
940
+ "zh-CN": "继续推进这个目标",
941
+ "zh-TW": "繼續推進這個目標",
942
+ "en-US": "Go on with this goal",
943
+ "ja-JP": "この目標を進める"
944
+ });
945
+ }
946
+ GoalServerTexts.wake = wake;
947
+ function noted(text) {
948
+ return TaLanguageUtil.say({
949
+ "zh-CN": `补充一个方向:${text}`,
950
+ "zh-TW": `補充一個方向:${text}`,
951
+ "en-US": `One more direction: ${text}`,
952
+ "ja-JP": `方向をひとつ追加:${text}`
953
+ });
954
+ }
955
+ GoalServerTexts.noted = noted;
956
+ function stuck(count) {
957
+ return TaLanguageUtil.say({
958
+ "zh-CN": `连续 ${count} 轮失败,已暂停,等你看看`,
959
+ "zh-TW": `連續 ${count} 輪失敗,已暫停,等你看看`,
960
+ "en-US": `Paused after ${count} failed turns in a row, for you to look at`,
961
+ "ja-JP": `${count} 回続けて失敗したため一時停止しました。確認をお待ちしています`
962
+ });
963
+ }
964
+ GoalServerTexts.stuck = stuck;
965
+ function startIt(title) {
966
+ return TaLanguageUtil.say({
967
+ "zh-CN": `开始这个目标吗:${title}`,
968
+ "zh-TW": `開始這個目標嗎:${title}`,
969
+ "en-US": `Start this goal: ${title}`,
970
+ "ja-JP": `この目標を始めますか:${title}`
971
+ });
972
+ }
973
+ GoalServerTexts.startIt = startIt;
974
+ function acceptIt(summary) {
975
+ return TaLanguageUtil.say({
976
+ "zh-CN": `验收结果:${summary}`,
977
+ "zh-TW": `驗收結果:${summary}`,
978
+ "en-US": `Accept the result: ${summary}`,
979
+ "ja-JP": `結果を確認:${summary}`
980
+ });
981
+ }
982
+ GoalServerTexts.acceptIt = acceptIt;
983
+ })(GoalServerTexts ||= {});
984
+
985
+ // web-src/goal-book.ts
986
+ var INITIATIVE = "@celljs/ta-initiative";
987
+ var HOOK_PATH = "/api/hooks/ta-goals/";
988
+
989
+ class GoalBook {
990
+ host;
991
+ options;
992
+ goals = [];
993
+ queue = Promise.resolve();
994
+ cancel;
995
+ stopEvents;
996
+ disposed = false;
997
+ briefed;
998
+ defined = false;
999
+ watchers;
1000
+ constructor(host, options = {
1001
+ now: () => Date.now(),
1002
+ later: (run, ms) => {
1003
+ const timer = setTimeout(run, ms);
1004
+ return () => clearTimeout(timer);
1005
+ }
1006
+ }) {
1007
+ this.host = host;
1008
+ this.options = options;
1009
+ this.watchers = new GoalWatchers({
1010
+ watch: options.watch,
1011
+ later: options.later,
1012
+ busy: (id) => {
1013
+ return this.goals.find((goal) => goal.id === id)?.turnAt !== undefined;
1014
+ },
1015
+ fire: (id, names) => void this.event(id, `Files changed: ${names.join(", ")}`).catch(() => {
1016
+ return;
1017
+ })
1018
+ });
1019
+ }
1020
+ async begin() {
1021
+ const kept = await this.host.getExtensionData(NAME, Keys.GOALS).catch(() => {
1022
+ return;
1023
+ });
1024
+ const goals = Array.isArray(kept) ? kept.filter((goal) => goal && typeof goal.id === "string") : [];
1025
+ this.goals = goals.map(({ turnAt: _, ...goal }) => goal);
1026
+ if (goals.some((goal) => goal.turnAt !== undefined)) {
1027
+ await this.save().catch(() => {
1028
+ return;
1029
+ });
1030
+ }
1031
+ this.stopEvents = this.host.onSessionEvent((event) => {
1032
+ const at = this.options.now();
1033
+ this.serial(() => this.heard(event, at)).catch(() => {
1034
+ return;
1035
+ });
1036
+ });
1037
+ this.schedule();
1038
+ this.watchers.sync(this.goals);
1039
+ this.define();
1040
+ }
1041
+ dispose() {
1042
+ this.disposed = true;
1043
+ this.cancel?.();
1044
+ this.stopEvents?.();
1045
+ this.watchers.dispose();
1046
+ }
1047
+ list() {
1048
+ this.define();
1049
+ return Promise.resolve(this.goals.map((goal) => ({ ...goal })));
1050
+ }
1051
+ async define() {
1052
+ if (this.defined) {
1053
+ return;
1054
+ }
1055
+ try {
1056
+ for (const kind of GOAL_KINDS) {
1057
+ await this.host.callPackageHost(INITIATIVE, "defineKind", [kind]);
1058
+ }
1059
+ this.defined = true;
1060
+ } catch {}
1061
+ }
1062
+ event(ref, text) {
1063
+ return this.serial(async () => {
1064
+ const goal = this.find(ref);
1065
+ if (goal.status !== "working") {
1066
+ return;
1067
+ }
1068
+ const now = this.options.now();
1069
+ const next = { ...goal, events: GoalUtil.event(goal.events, text), nextAt: now, updatedAt: now };
1070
+ await this.replace(next);
1071
+ return { ...next };
1072
+ });
1073
+ }
1074
+ async webhook(request) {
1075
+ const secret = typeof request?.path === "string" ? request.path.split("/")[0] : "";
1076
+ const goal = secret ? this.goals.find((each) => each.status === "working" && !!each.hook && same(each.hook, secret)) : undefined;
1077
+ if (!goal) {
1078
+ throw new Error("No goal has this webhook.");
1079
+ }
1080
+ const body = typeof request.body === "string" ? request.body.trim() : "";
1081
+ await this.event(goal.id, body ? `Its webhook was called with:
1082
+ ${body}` : "Its webhook was called, with nothing sent.");
1083
+ return { woke: goal.id };
1084
+ }
1085
+ async hookUrl(ref) {
1086
+ const goal = this.find(ref);
1087
+ const base = goal.hook && await this.options.serverUrl?.();
1088
+ return base ? `${base.replace(/\/$/, "")}${HOOK_PATH}${goal.hook}` : undefined;
1089
+ }
1090
+ async get(ref) {
1091
+ return { ...this.find(ref) };
1092
+ }
1093
+ async start(input, where = {}) {
1094
+ const { goal, send } = await this.serial(async () => {
1095
+ const settings = await this.settings();
1096
+ const draft = GoalUtil.draft(input, settings);
1097
+ const working = this.goals.filter((goal3) => goal3.status === "working");
1098
+ if (working.length >= settings.active) {
1099
+ throw new Error(`${settings.active} goals are at work already (${working.map((goal3) => goal3.title).join("; ")}): the user pauses one, or waits for one to end.`);
1100
+ }
1101
+ const cwd = typeof where.cwd === "string" && where.cwd ? where.cwd : (await this.host.getServerInfo()).cwd;
1102
+ if (!cwd) {
1103
+ throw new Error("Say the directory the goal works in (cwd).");
1104
+ }
1105
+ const now = this.options.now();
1106
+ const goal2 = {
1107
+ ...draft,
1108
+ id: `g${now.toString(36)}${Math.random().toString(36).slice(2, 6)}`,
1109
+ cwd,
1110
+ ...where.origin ? { origin: where.origin } : {},
1111
+ status: "working",
1112
+ plan: [],
1113
+ log: [],
1114
+ createdAt: now,
1115
+ updatedAt: now,
1116
+ used: { day: GoalUtil.day(now), ms: 0 },
1117
+ totalMs: 0,
1118
+ turns: 0,
1119
+ hook: secret()
1120
+ };
1121
+ const opened = await this.host.openSession({ cwd, appendSystemPrompt: GoalPrompt.role() });
1122
+ await this.host.setSessionName(opened.sessionId, draft.title).catch(() => {
1123
+ return;
1124
+ });
1125
+ goal2.sessionFile = opened.sessionFile ?? (await this.host.getState(opened.sessionId)).sessionFile;
1126
+ this.goals = [...this.goals, goal2];
1127
+ await this.save();
1128
+ return { goal: goal2, send: await this.turn(goal2, opened.sessionId, GoalServerTexts.begin()) };
1129
+ });
1130
+ await send();
1131
+ return this.get(goal.id);
1132
+ }
1133
+ update(ref, input) {
1134
+ return this.serial(async () => {
1135
+ const change = GoalUtil.change(input);
1136
+ const now = this.options.now();
1137
+ const goal = this.find(ref);
1138
+ const status = change.status ?? goal.status;
1139
+ const ended = status === "done" && goal.status !== "done";
1140
+ const next = {
1141
+ ...goal,
1142
+ ...change.plan ? { plan: change.plan } : {},
1143
+ ...change.result ? { result: change.result } : {},
1144
+ ...change.watch ? { watch: change.watch } : {},
1145
+ status,
1146
+ log: change.did ? [...goal.log, { at: now, did: change.did, ...change.next ? { next: change.next } : {} }].slice(-Limits.LOG) : goal.log,
1147
+ updatedAt: now,
1148
+ ...ended ? { endedAt: now } : {}
1149
+ };
1150
+ if (status === "working") {
1151
+ next.nextAt = change.wakeMs ? now + change.wakeMs : goal.nextAt ?? undefined;
1152
+ } else {
1153
+ delete next.nextAt;
1154
+ }
1155
+ if (status !== "done") {
1156
+ delete next.endedAt;
1157
+ }
1158
+ await this.replace(next);
1159
+ return { ...next };
1160
+ });
1161
+ }
1162
+ note(ref, text) {
1163
+ return this.serial(async () => {
1164
+ const said = GoalUtil.line(text);
1165
+ if (!said) {
1166
+ throw new Error("Say the direction (note).");
1167
+ }
1168
+ const goal = this.find(ref);
1169
+ const now = this.options.now();
1170
+ const next = {
1171
+ ...goal,
1172
+ constraints: [...goal.constraints.filter((item) => item !== said), said].slice(-Limits.ITEMS),
1173
+ log: [...goal.log, { at: now, did: GoalServerTexts.noted(said) }].slice(-Limits.LOG),
1174
+ updatedAt: now,
1175
+ ...goal.status === "working" ? { nextAt: now } : {}
1176
+ };
1177
+ await this.replace(next);
1178
+ return { ...next };
1179
+ });
1180
+ }
1181
+ wake(ref) {
1182
+ return this.serial(async () => {
1183
+ const goal = this.find(ref);
1184
+ if (goal.status !== "working") {
1185
+ throw new Error(`The goal is ${goal.status}: resume it first.`);
1186
+ }
1187
+ const next = { ...goal, nextAt: this.options.now(), updatedAt: this.options.now() };
1188
+ await this.replace(next);
1189
+ return { ...next };
1190
+ });
1191
+ }
1192
+ pause(ref) {
1193
+ return this.serial(async () => {
1194
+ const { nextAt: _, ...goal } = this.find(ref);
1195
+ const next = { ...goal, status: "paused", updatedAt: this.options.now() };
1196
+ await this.replace(next);
1197
+ return { ...next };
1198
+ });
1199
+ }
1200
+ resume(ref) {
1201
+ return this.serial(async () => {
1202
+ const goal = this.find(ref);
1203
+ if (goal.status === "working") {
1204
+ return { ...goal };
1205
+ }
1206
+ const working = this.goals.filter((other) => other.status === "working");
1207
+ const { active } = await this.settings();
1208
+ if (working.length >= active) {
1209
+ throw new Error(`${active} goals are at work already: pause one first.`);
1210
+ }
1211
+ const { endedAt: _, ...rest } = goal;
1212
+ const now = this.options.now();
1213
+ const next = { ...rest, status: "working", nextAt: now, updatedAt: now, failures: 0 };
1214
+ await this.replace(next);
1215
+ return { ...next };
1216
+ });
1217
+ }
1218
+ remove(ref) {
1219
+ return this.serial(async () => {
1220
+ const goal = this.find(ref);
1221
+ this.goals = this.goals.filter((other) => other.id !== goal.id);
1222
+ await this.save();
1223
+ });
1224
+ }
1225
+ find(ref) {
1226
+ const goal = GoalUtil.find(this.goals, ref);
1227
+ if (!goal) {
1228
+ throw new Error(`No goal "${ref}". Goals: ${this.goals.map((each) => each.title).join("; ") || "none"}.`);
1229
+ }
1230
+ return goal;
1231
+ }
1232
+ async replace(goal) {
1233
+ this.goals = this.goals.map((other) => other.id === goal.id ? goal : other);
1234
+ await this.save();
1235
+ }
1236
+ async settings() {
1237
+ return GoalUtil.settings(await this.host.getExtensionData(NAME, Keys.SETTINGS).catch(() => {
1238
+ return;
1239
+ }));
1240
+ }
1241
+ async save() {
1242
+ await this.host.setExtensionData(NAME, Keys.GOALS, this.goals);
1243
+ const brief = GoalUtil.brief(this.goals);
1244
+ const text = JSON.stringify(brief);
1245
+ if (text !== this.briefed) {
1246
+ this.briefed = text;
1247
+ await this.host.setExtensionData(NAME, TA_BRIEF_SOURCE, brief);
1248
+ }
1249
+ this.schedule();
1250
+ this.watchers.sync(this.goals);
1251
+ }
1252
+ async heard(event, now) {
1253
+ const file = event.sessionFile;
1254
+ const goal = file ? this.goals.find((each) => each.sessionFile === file) : undefined;
1255
+ if (!goal || !file) {
1256
+ return;
1257
+ }
1258
+ if (event.type === "turn_start") {
1259
+ await this.replace({ ...goal, turnAt: now });
1260
+ return;
1261
+ }
1262
+ const { turnAt: started, ...rest } = goal;
1263
+ const ms = started === undefined ? 0 : Math.max(0, now - started);
1264
+ const today = GoalUtil.day(now);
1265
+ const used = goal.used.day === today ? goal.used.ms + ms : ms;
1266
+ const failures = event.error && !event.aborted ? (goal.failures ?? 0) + 1 : 0;
1267
+ const next = { ...rest, used: { day: today, ms: used }, totalMs: goal.totalMs + ms, failures };
1268
+ if (next.status === "working" && failures >= Limits.FAILURES) {
1269
+ delete next.nextAt;
1270
+ next.status = "paused";
1271
+ next.updatedAt = now;
1272
+ next.log = [...goal.log, { at: now, did: GoalServerTexts.stuck(failures) }].slice(-Limits.LOG);
1273
+ } else if (next.status === "working" && next.events?.length) {
1274
+ next.nextAt = now;
1275
+ } else if (next.status === "working" && (next.nextAt === undefined || next.nextAt <= now)) {
1276
+ next.nextAt = now + next.paceMs;
1277
+ }
1278
+ await this.replace(next);
1279
+ }
1280
+ schedule() {
1281
+ this.cancel?.();
1282
+ this.cancel = undefined;
1283
+ if (this.disposed) {
1284
+ return;
1285
+ }
1286
+ const due = this.goals.filter((goal) => goal.status === "working" && goal.nextAt !== undefined).map((goal) => goal.nextAt);
1287
+ if (due.length === 0) {
1288
+ return;
1289
+ }
1290
+ const wait = Math.min(Limits.SLEEP_MS, Math.max(0, Math.min(...due) - this.options.now()));
1291
+ this.cancel = this.options.later(() => void this.tick(), wait);
1292
+ }
1293
+ async tick() {
1294
+ const sends = await this.serial(async () => {
1295
+ const now = this.options.now();
1296
+ const found = [];
1297
+ for (const goal of this.goals.filter((each) => each.status === "working" && each.nextAt !== undefined && each.nextAt <= now)) {
1298
+ const send = await this.due(goal, now).catch((error) => void console.error(`${NAME}: ${goal.title}: ${String(error)}`));
1299
+ if (send) {
1300
+ found.push(send);
1301
+ }
1302
+ }
1303
+ return found;
1304
+ }).catch(() => []);
1305
+ for (const send of sends) {
1306
+ await send().catch((error) => console.error(`${NAME}: ${String(error)}`));
1307
+ }
1308
+ this.schedule();
1309
+ }
1310
+ async due(goal, now) {
1311
+ if (GoalUtil.left(goal, now) <= 0) {
1312
+ await this.replace({ ...goal, nextAt: GoalUtil.tomorrow(now) });
1313
+ return;
1314
+ }
1315
+ const open = goal.sessionFile ? (await this.host.listSessions()).find((info) => info.sessionFile === goal.sessionFile) : undefined;
1316
+ if (open?.isStreaming) {
1317
+ await this.replace({ ...goal, nextAt: now + Limits.BUSY_MS });
1318
+ return;
1319
+ }
1320
+ if (!goal.sessionFile) {
1321
+ await this.replace({ ...goal, status: "paused", updatedAt: now });
1322
+ throw new Error("Its conversation is gone: paused.");
1323
+ }
1324
+ const sessionId = open?.sessionId ?? (await this.host.openSession({ cwd: goal.cwd, sessionFile: goal.sessionFile })).sessionId;
1325
+ return this.turn(goal, sessionId, GoalServerTexts.wake());
1326
+ }
1327
+ async turn(goal, sessionId, words) {
1328
+ const now = this.options.now();
1329
+ const { nextAt: _, events: __, ...rest } = goal;
1330
+ const next = { ...rest, turns: goal.turns + 1, updatedAt: now };
1331
+ await this.replace(next);
1332
+ const hookUrl = goal.hook ? await this.hookUrl(goal.id).catch(() => {
1333
+ return;
1334
+ }) : undefined;
1335
+ const message = TaMessageContext.wrap(`${GoalUtil.context(goal, now, hookUrl)}
1336
+ ${TaMessageSource.line(NAME)}`, words);
1337
+ return () => this.host.prompt(sessionId, { clientMessageId: `${goal.id}_${next.turns}`, message });
1338
+ }
1339
+ serial(run) {
1340
+ const done = this.queue.then(run, run);
1341
+ this.queue = done.catch(() => {
1342
+ return;
1343
+ });
1344
+ return done;
1345
+ }
1346
+ }
1347
+ function secret() {
1348
+ return [...crypto.getRandomValues(new Uint8Array(16))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
1349
+ }
1350
+ function same(a, b) {
1351
+ let differ = a.length ^ b.length;
1352
+ for (let index = 0;index < Math.max(a.length, b.length); index++) {
1353
+ differ |= (a.charCodeAt(index) || 0) ^ (b.charCodeAt(index) || 0);
1354
+ }
1355
+ return differ === 0;
1356
+ }
1357
+
1358
+ // web-src/host.ts
1359
+ async function activate(host) {
1360
+ const book = new GoalBook(host, {
1361
+ now: () => Date.now(),
1362
+ later: (run, ms) => {
1363
+ const timer = setTimeout(run, ms);
1364
+ return () => clearTimeout(timer);
1365
+ },
1366
+ watch: (cwd, path, changed) => {
1367
+ const watcher = watch(isAbsolute(path) ? path : join(cwd, path), { recursive: true, persistent: false }, (_kind, name) => changed(name ? String(name) : path));
1368
+ watcher.on("error", () => {
1369
+ return;
1370
+ });
1371
+ return () => watcher.close();
1372
+ },
1373
+ serverUrl: async () => {
1374
+ const info = await readFile(join(host.agentDir, "serve.json"), "utf8").catch(() => {
1375
+ return;
1376
+ });
1377
+ const url = info && JSON.parse(info).url;
1378
+ return url ? new URL(url.replace(/^ws/, "http")).origin : undefined;
1379
+ }
1380
+ });
1381
+ await book.begin();
1382
+ return book;
1383
+ }
1384
+ export {
1385
+ activate as default
1386
+ };