@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.
@@ -0,0 +1,708 @@
1
+ // ../ta-protocol/esm/common/ta-extension-host.js
2
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
3
+ var TA_HOST_EVENT = "ta:host";
4
+ var TaHostUtil;
5
+ (function(TaHostUtil2) {
6
+ TaHostUtil2.WAIT_MS = 1000;
7
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
8
+ return new Promise((resolve) => {
9
+ let heard = false;
10
+ let answered = false;
11
+ const timer = setTimeout(() => resolve(undefined), waitMs);
12
+ const request = {
13
+ name,
14
+ heard: () => {
15
+ heard = true;
16
+ },
17
+ resolve: (answer) => {
18
+ answered = true;
19
+ clearTimeout(timer);
20
+ resolve(answer);
21
+ }
22
+ };
23
+ events.emit(TA_HOST_EVENT, request);
24
+ if (!heard && !answered) {
25
+ clearTimeout(timer);
26
+ resolve(undefined);
27
+ }
28
+ });
29
+ }
30
+ TaHostUtil2.reach = reach;
31
+ function marked(systemPrompt, mark) {
32
+ return role(systemPrompt).includes(mark);
33
+ }
34
+ TaHostUtil2.marked = marked;
35
+ function role(systemPrompt) {
36
+ if (!systemPrompt) {
37
+ return "";
38
+ }
39
+ const open = `<addendum>
40
+ `;
41
+ const start = systemPrompt.indexOf(open);
42
+ const context = systemPrompt.indexOf(`<project_context>
43
+ `);
44
+ if (start < 0 || context >= 0 && context < start) {
45
+ return "";
46
+ }
47
+ const end = systemPrompt.indexOf(`
48
+ </addendum>`, start);
49
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
50
+ }
51
+ TaHostUtil2.role = role;
52
+ })(TaHostUtil || (TaHostUtil = {}));
53
+ var TA_WITH_OTHERS_MARK = "[ta:speaks-with-others]";
54
+ var TA_TELLS_OF_ITS_TURNS_MARK = "[ta:tells-of-its-turns]";
55
+ var TA_ASK_ENTRY = "ta-ask";
56
+ var TaAskUtil;
57
+ (function(TaAskUtil2) {
58
+ const LENGTH = 120;
59
+ function entry(question) {
60
+ const line = question.replace(/\s+/g, " ").trim();
61
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
62
+ }
63
+ TaAskUtil2.entry = entry;
64
+ function asking(entries) {
65
+ var _a;
66
+ for (let i = entries.length - 1;i >= 0; i--) {
67
+ const entry2 = entries[i];
68
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
69
+ return;
70
+ }
71
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
72
+ return read(entry2);
73
+ }
74
+ }
75
+ return;
76
+ }
77
+ TaAskUtil2.asking = asking;
78
+ function next(asked, entry2) {
79
+ var _a;
80
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
81
+ return;
82
+ }
83
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
84
+ }
85
+ TaAskUtil2.next = next;
86
+ function read(found) {
87
+ var _a;
88
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
89
+ if (typeof question !== "string" || !question.trim()) {
90
+ return;
91
+ }
92
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
93
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
94
+ }
95
+ })(TaAskUtil || (TaAskUtil = {}));
96
+
97
+ // web-src/goal-protocol.ts
98
+ var NAME = "@celljs/ta-goals";
99
+ var CARD = "ta-goal";
100
+ var RESULT = "ta-goal-result";
101
+ var SECTION = "ta-goals";
102
+ var GOAL_MARK = "[ta:goal]";
103
+ var Keys;
104
+ ((Keys) => {
105
+ Keys.GOALS = "goals";
106
+ Keys.SETTINGS = "settings";
107
+ })(Keys ||= {});
108
+ var Limits;
109
+ ((Limits) => {
110
+ Limits.ACTIVE = 3;
111
+ Limits.ACTIVE_MAX = 8;
112
+ Limits.FAILURES = 3;
113
+ Limits.EVENTS = 10;
114
+ Limits.EVENT_CHARS = 2000;
115
+ Limits.SETTLE_MS = 5000;
116
+ Limits.WATCH = 10;
117
+ Limits.BRIEF_LINES = 6;
118
+ Limits.PACE_MS = 4 * 60 * 60000;
119
+ Limits.PACE_MIN_MS = 15 * 60000;
120
+ Limits.PACE_MAX_MS = 7 * 24 * 60 * 60000;
121
+ Limits.BUDGET_MS = 2 * 60 * 60000;
122
+ Limits.BUDGET_MAX_MS = 12 * 60 * 60000;
123
+ Limits.BUSY_MS = 10 * 60000;
124
+ Limits.LOG = 60;
125
+ Limits.ITEMS = 20;
126
+ Limits.TEXT = 400;
127
+ Limits.SLEEP_MS = 60000;
128
+ })(Limits ||= {});
129
+
130
+ // web-src/goal-util.ts
131
+ var GoalUtil;
132
+ ((GoalUtil) => {
133
+ const STATUSES = ["working", "review", "done", "paused"];
134
+ function duration(value) {
135
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
136
+ return Math.round(value * 60000);
137
+ }
138
+ if (typeof value !== "string") {
139
+ return;
140
+ }
141
+ const text2 = value.trim().toLowerCase().replace(/^every\s+/, "");
142
+ const parts = /^(?:(\d+(?:\.\d+)?)d)?\s*(?:(\d+(?:\.\d+)?)h)?\s*(?:(\d+(?:\.\d+)?)m(?:in)?)?$/.exec(text2);
143
+ if (!text2 || !parts || !(parts[1] || parts[2] || parts[3])) {
144
+ return;
145
+ }
146
+ const ms = (Number(parts[1] ?? 0) * 24 * 60 + Number(parts[2] ?? 0) * 60 + Number(parts[3] ?? 0)) * 60000;
147
+ return ms > 0 ? Math.round(ms) : undefined;
148
+ }
149
+ GoalUtil.duration = duration;
150
+ function line(value) {
151
+ if (typeof value !== "string") {
152
+ return "";
153
+ }
154
+ const text2 = value.replace(/\s+/g, " ").trim();
155
+ return text2.length > Limits.TEXT ? `${text2.slice(0, Limits.TEXT - 1)}…` : text2;
156
+ }
157
+ GoalUtil.line = line;
158
+ function lines(value) {
159
+ const list = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
160
+ return [...new Set(list.map(line).filter(Boolean))].slice(0, Limits.ITEMS);
161
+ }
162
+ GoalUtil.lines = lines;
163
+ function clamp(value, min, max) {
164
+ return Math.min(max, Math.max(min, value));
165
+ }
166
+ function draft(input, defaults = settings(undefined)) {
167
+ const given = input && typeof input === "object" ? input : {};
168
+ const title = line(given.title);
169
+ if (!title) {
170
+ throw new Error("A goal needs a title: what to achieve, in a line.");
171
+ }
172
+ const doneWhen = lines(given.doneWhen);
173
+ if (doneWhen.length === 0) {
174
+ throw new Error("A goal needs doneWhen: how it is judged done, each a check the user can see.");
175
+ }
176
+ const pace = duration(given.every);
177
+ const budget = duration(given.budget);
178
+ return {
179
+ title,
180
+ doneWhen,
181
+ constraints: lines(given.constraints),
182
+ askFirst: lines(given.askFirst),
183
+ paceMs: clamp(pace ?? defaults.paceMs, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS),
184
+ budgetMs: clamp(budget ?? defaults.budgetMs, Limits.PACE_MIN_MS, Limits.BUDGET_MAX_MS)
185
+ };
186
+ }
187
+ GoalUtil.draft = draft;
188
+ function settings(value) {
189
+ const given = value && typeof value === "object" ? value : {};
190
+ const number = (key, fallback, min, max) => typeof given[key] === "number" && Number.isFinite(given[key]) ? clamp(Math.round(given[key]), min, max) : fallback;
191
+ return {
192
+ paceMs: number("paceMs", Limits.PACE_MS, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS),
193
+ budgetMs: number("budgetMs", Limits.BUDGET_MS, Limits.PACE_MIN_MS, Limits.BUDGET_MAX_MS),
194
+ active: number("active", Limits.ACTIVE, 1, Limits.ACTIVE_MAX)
195
+ };
196
+ }
197
+ GoalUtil.settings = settings;
198
+ function brief(goals) {
199
+ const items = goals.flatMap((goal) => [
200
+ ...goal.log.slice(-Limits.BRIEF_LINES).map((entry) => ({
201
+ at: entry.at,
202
+ text: `${goal.title}: ${entry.did}${entry.next ? ` (next: ${entry.next})` : ""}`
203
+ })),
204
+ ...goal.status === "review" ? [{ at: goal.updatedAt, text: `${goal.title}: its result waits for the user to accept` }] : [],
205
+ ...goal.status === "paused" && (goal.failures ?? 0) >= Limits.FAILURES ? [{ at: goal.updatedAt, text: `${goal.title}: paused after ${Limits.FAILURES} failed turns in a row` }] : []
206
+ ]);
207
+ return {
208
+ section: "Progress of the user's goals, each worked on by Ta in a conversation of its own",
209
+ 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.",
210
+ items: items.sort((a, b) => a.at - b.at).slice(-30)
211
+ };
212
+ }
213
+ GoalUtil.brief = brief;
214
+ function card(code) {
215
+ const given = json(code);
216
+ const title = line(given?.title);
217
+ if (!given || !title) {
218
+ return;
219
+ }
220
+ const pace = duration(given.every);
221
+ const budget = duration(given.budget);
222
+ return {
223
+ title,
224
+ doneWhen: lines(given.doneWhen),
225
+ constraints: lines(given.constraints),
226
+ askFirst: lines(given.askFirst),
227
+ ...pace ? { paceMs: clamp(pace, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS) } : {},
228
+ ...budget ? { budgetMs: clamp(budget, Limits.PACE_MIN_MS, Limits.BUDGET_MAX_MS) } : {}
229
+ };
230
+ }
231
+ GoalUtil.card = card;
232
+ function result(input) {
233
+ const given = input && typeof input === "object" ? input : undefined;
234
+ const summary = line(given?.summary);
235
+ if (!given || !summary) {
236
+ return;
237
+ }
238
+ const criteria = (Array.isArray(given.criteria) ? given.criteria : []).map((item) => {
239
+ const one = item && typeof item === "object" ? item : { text: item };
240
+ const evidence = line(one.evidence);
241
+ return { text: line(one.text), met: one.met !== false, ...evidence ? { evidence } : {} };
242
+ }).filter((item) => item.text).slice(0, Limits.ITEMS);
243
+ return { summary, criteria, outputs: lines(given.outputs) };
244
+ }
245
+ GoalUtil.result = result;
246
+ function resultCard(code) {
247
+ return result(json(code));
248
+ }
249
+ GoalUtil.resultCard = resultCard;
250
+ function change(input) {
251
+ const given = input && typeof input === "object" ? input : {};
252
+ const change2 = {};
253
+ if (Array.isArray(given.plan)) {
254
+ change2.plan = given.plan.map((item) => {
255
+ const one = item && typeof item === "object" ? item : { text: item };
256
+ return { text: line(one.text), done: one.done === true };
257
+ }).filter((step) => step.text).slice(0, Limits.ITEMS);
258
+ }
259
+ const did = line(given.did);
260
+ const next = line(given.next);
261
+ if (did) {
262
+ change2.did = did;
263
+ }
264
+ if (next) {
265
+ change2.next = next;
266
+ }
267
+ const wake = duration(given.wakeIn);
268
+ if (wake) {
269
+ change2.wakeMs = clamp(wake, Limits.PACE_MIN_MS, Limits.PACE_MAX_MS);
270
+ }
271
+ if (given.status !== undefined) {
272
+ if (!STATUSES.includes(given.status)) {
273
+ throw new Error(`status is one of ${STATUSES.join(", ")}.`);
274
+ }
275
+ change2.status = given.status;
276
+ }
277
+ const result2 = GoalUtil.result(given.result);
278
+ if (result2) {
279
+ change2.result = result2;
280
+ }
281
+ if (given.watch !== undefined) {
282
+ change2.watch = lines(given.watch).slice(0, Limits.WATCH);
283
+ }
284
+ return change2;
285
+ }
286
+ GoalUtil.change = change;
287
+ function short(ms) {
288
+ const minutes = Math.round(ms / 60000);
289
+ if (minutes % 1440 === 0) {
290
+ return `${minutes / 1440}d`;
291
+ }
292
+ const hours = Math.floor(minutes / 60);
293
+ const rest = minutes % 60;
294
+ return hours ? `${hours}h${rest ? `${rest}m` : ""}` : `${rest}m`;
295
+ }
296
+ GoalUtil.short = short;
297
+ function day(at) {
298
+ const date = new Date(at);
299
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
300
+ }
301
+ GoalUtil.day = day;
302
+ function left(goal, now) {
303
+ const used = goal.used.day === day(now) ? goal.used.ms : 0;
304
+ return Math.max(0, goal.budgetMs - used);
305
+ }
306
+ GoalUtil.left = left;
307
+ function tomorrow(now) {
308
+ const date = new Date(now);
309
+ date.setHours(24, 5, 0, 0);
310
+ return date.getTime();
311
+ }
312
+ GoalUtil.tomorrow = tomorrow;
313
+ function find(goals, ref) {
314
+ const key = String(ref ?? "").trim();
315
+ 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);
316
+ }
317
+ GoalUtil.find = find;
318
+ function progress(goal) {
319
+ return { done: goal.plan.filter((step) => step.done).length, total: goal.plan.length };
320
+ }
321
+ GoalUtil.progress = progress;
322
+ function ignored(name) {
323
+ return /(^|[\\/])(\.git|node_modules|dist|lib|esm|build|out|\.turbo|\.next|coverage)([\\/]|$)/.test(name);
324
+ }
325
+ GoalUtil.ignored = ignored;
326
+ function event(events, text2) {
327
+ const said = text2.length > Limits.EVENT_CHARS ? `${text2.slice(0, Limits.EVENT_CHARS - 1)}…` : text2;
328
+ return [...events ?? [], said].slice(-Limits.EVENTS);
329
+ }
330
+ GoalUtil.event = event;
331
+ function context(goal, now, hookUrl) {
332
+ const list = (items) => items.length ? items.map((item) => `- ${item}`).join(`
333
+ `) : "- (none)";
334
+ const plan = goal.plan.length ? goal.plan.map((step) => `- [${step.done ? "x" : " "}] ${step.text}`).join(`
335
+ `) : "- (no plan yet: make one)";
336
+ const log = goal.log.slice(-8).map((entry) => `- ${new Date(entry.at).toISOString().slice(0, 16)} ${entry.did}${entry.next ? ` / next: ${entry.next}` : ""}`);
337
+ const minutes = (ms) => `${Math.round(ms / 60000)} min`;
338
+ return [
339
+ `Goal: ${goal.title}`,
340
+ `Turn: ${goal.turns + 1}`,
341
+ "Done when:",
342
+ list(goal.doneWhen),
343
+ "Constraints:",
344
+ list(goal.constraints),
345
+ "Ask the user first before:",
346
+ list(goal.askFirst),
347
+ "Plan:",
348
+ plan,
349
+ "Log (latest last):",
350
+ log.length ? log.join(`
351
+ `) : "- (nothing yet)",
352
+ `Pace: a turn every ${minutes(goal.paceMs)}; work left today: ${minutes(left(goal, now))} of ${minutes(goal.budgetMs)}.`,
353
+ `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"}.`,
354
+ ...goal.events?.length ? ["Since the last turn:", ...goal.events.map((event2) => `- ${event2}`)] : []
355
+ ].join(`
356
+ `);
357
+ }
358
+ GoalUtil.context = context;
359
+ function json(code) {
360
+ try {
361
+ const value = JSON.parse(code);
362
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
363
+ } catch {
364
+ return;
365
+ }
366
+ }
367
+ function blocks(reply, language) {
368
+ const found = [];
369
+ let fence;
370
+ for (const text2 of reply.split(`
371
+ `)) {
372
+ if (!fence) {
373
+ const opening = /^\s*(`{3,}|~{3,})\s*([\w-]*)/.exec(text2);
374
+ if (opening) {
375
+ fence = { mark: opening[1], lines: [], ours: opening[2] === language };
376
+ }
377
+ continue;
378
+ }
379
+ const mark = /^\s*(`{3,}|~{3,})\s*$/.exec(text2)?.[1];
380
+ if (mark && mark[0] === fence.mark[0] && mark.length >= fence.mark.length) {
381
+ if (fence.ours) {
382
+ found.push(fence.lines.join(`
383
+ `));
384
+ }
385
+ fence = undefined;
386
+ } else {
387
+ fence.lines.push(text2);
388
+ }
389
+ }
390
+ return found;
391
+ }
392
+ GoalUtil.blocks = blocks;
393
+ function text(content) {
394
+ if (typeof content === "string") {
395
+ return content;
396
+ }
397
+ return Array.isArray(content) ? content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
398
+ `) : "";
399
+ }
400
+ GoalUtil.text = text;
401
+ })(GoalUtil ||= {});
402
+
403
+ // web-src/goal-prompt.ts
404
+ var GoalPrompt;
405
+ ((GoalPrompt) => {
406
+ function draft(settings) {
407
+ const every = GoalUtil.short(settings.paceMs);
408
+ const budget = GoalUtil.short(settings.budgetMs);
409
+ 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})}`;
410
+ }
411
+ 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]}`;
412
+ function section(goals, settings) {
413
+ 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>"}'\`)`;
414
+ const note = `goal_note (without it, \`ta call ${NAME} note '<title>' '<direction>'\`)`;
415
+ const listed = goals.filter((goal) => goal.status === "working" || goal.status === "review");
416
+ const now = listed.length ? `Goals at work now:
417
+ ${listed.map((goal) => {
418
+ const done = goal.plan.filter((step) => step.done).length;
419
+ return `- ${goal.title} (${goal.status === "review" ? "its result waits for the user" : `${done}/${goal.plan.length} steps`})`;
420
+ }).join(`
421
+ `)}` : "No goal is at work now.";
422
+ return [
423
+ '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.',
424
+ `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.`,
425
+ `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.`,
426
+ '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.',
427
+ `At most ${settings.active} goals work at once.`,
428
+ now
429
+ ].join(`
430
+ `);
431
+ }
432
+ GoalPrompt.section = section;
433
+ function role() {
434
+ return [
435
+ `${GOAL_MARK} ${TA_TELLS_OF_ITS_TURNS_MARK}`,
436
+ "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.",
437
+ '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.',
438
+ "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.",
439
+ "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.",
440
+ "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.",
441
+ `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.`,
442
+ "Reply in the user's language."
443
+ ].join(`
444
+ `);
445
+ }
446
+ GoalPrompt.role = role;
447
+ GoalPrompt.START_TOOL = {
448
+ name: "start_goal",
449
+ label: "Start goal",
450
+ 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.",
451
+ promptSnippet: "Start a goal the user agreed to",
452
+ parameters: {
453
+ type: "object",
454
+ properties: {
455
+ title: { type: "string", description: "What to achieve, in a line, in the language of the user." },
456
+ doneWhen: { type: "array", items: { type: "string" }, description: "How it is judged done: checks the user can verify." },
457
+ constraints: { type: "array", items: { type: "string" }, description: "What to keep to; the directions of the user." },
458
+ askFirst: { type: "array", items: { type: "string" }, description: "Steps to stop at and ask the user before." },
459
+ every: { type: "string", description: "How often to work on it: 30m, 4h, 1d (default 4h)." },
460
+ budget: { type: "string", description: "Work a day at most: 1h, 2h (default 2h)." }
461
+ },
462
+ required: ["title", "doneWhen"]
463
+ }
464
+ };
465
+ GoalPrompt.NOTE_TOOL = {
466
+ name: "goal_note",
467
+ label: "Tell a goal",
468
+ 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.",
469
+ promptSnippet: "Give a goal at work a direction of the user's",
470
+ parameters: {
471
+ type: "object",
472
+ properties: {
473
+ goal: { type: "string", description: "Its title." },
474
+ note: { type: "string", description: "The direction, in the user's words." }
475
+ },
476
+ required: ["goal", "note"]
477
+ }
478
+ };
479
+ GoalPrompt.UPDATE_TOOL = {
480
+ name: "goal_update",
481
+ label: "Update goal",
482
+ 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.",
483
+ promptSnippet: "Record how the goal stands",
484
+ parameters: {
485
+ type: "object",
486
+ properties: {
487
+ plan: {
488
+ type: "array",
489
+ items: { type: "object", properties: { text: { type: "string" }, done: { type: "boolean" } }, required: ["text"] },
490
+ description: "The whole plan as it stands now, a few steps."
491
+ },
492
+ did: { type: "string", description: "What this turn did, in a line, in the language of the user." },
493
+ next: { type: "string", description: "What comes next, in a line." },
494
+ wakeIn: { type: "string", description: "When the next turn should come, when not at the pace: 30m, 2h, 1d." },
495
+ watch: {
496
+ type: "array",
497
+ items: { type: "string" },
498
+ description: "Files or folders of this directory whose changes wake the goal from now on; [] watches nothing."
499
+ },
500
+ status: { type: "string", enum: ["working", "review", "done", "paused"] },
501
+ result: {
502
+ type: "object",
503
+ description: "With status review: the same as the result block.",
504
+ properties: {
505
+ summary: { type: "string" },
506
+ criteria: { type: "array", items: { type: "object" } },
507
+ outputs: { type: "array", items: { type: "string" } }
508
+ }
509
+ }
510
+ }
511
+ }
512
+ };
513
+ })(GoalPrompt ||= {});
514
+
515
+ // ../ta-protocol/esm/common/language.js
516
+ var TaLanguageUtil;
517
+ (function(TaLanguageUtil2) {
518
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
519
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
520
+ function of(tag) {
521
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
522
+ if (/^zh(\b|-)/.test(said)) {
523
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
524
+ }
525
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
526
+ }
527
+ TaLanguageUtil2.of = of;
528
+ function server(env = typeof process === "undefined" ? {} : process.env) {
529
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
530
+ }
531
+ TaLanguageUtil2.server = server;
532
+ function pick(language, words) {
533
+ return words[of(language)];
534
+ }
535
+ TaLanguageUtil2.pick = pick;
536
+ function say(words) {
537
+ return words[server()];
538
+ }
539
+ TaLanguageUtil2.say = say;
540
+ function chinese(language) {
541
+ return of(language).startsWith("zh");
542
+ }
543
+ TaLanguageUtil2.chinese = chinese;
544
+ function cjk(language) {
545
+ return of(language) !== "en-US";
546
+ }
547
+ TaLanguageUtil2.cjk = cjk;
548
+ function list(language, items) {
549
+ return items.join(cjk(language) ? "、" : ", ");
550
+ }
551
+ TaLanguageUtil2.list = list;
552
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
553
+
554
+ // web-src/server-texts.ts
555
+ var GoalServerTexts;
556
+ ((GoalServerTexts) => {
557
+ function begin() {
558
+ return TaLanguageUtil.say({
559
+ "zh-CN": "开始推进这个目标",
560
+ "zh-TW": "開始推進這個目標",
561
+ "en-US": "Start on this goal",
562
+ "ja-JP": "この目標に取りかかる"
563
+ });
564
+ }
565
+ GoalServerTexts.begin = begin;
566
+ function wake() {
567
+ return TaLanguageUtil.say({
568
+ "zh-CN": "继续推进这个目标",
569
+ "zh-TW": "繼續推進這個目標",
570
+ "en-US": "Go on with this goal",
571
+ "ja-JP": "この目標を進める"
572
+ });
573
+ }
574
+ GoalServerTexts.wake = wake;
575
+ function noted(text) {
576
+ return TaLanguageUtil.say({
577
+ "zh-CN": `补充一个方向:${text}`,
578
+ "zh-TW": `補充一個方向:${text}`,
579
+ "en-US": `One more direction: ${text}`,
580
+ "ja-JP": `方向をひとつ追加:${text}`
581
+ });
582
+ }
583
+ GoalServerTexts.noted = noted;
584
+ function stuck(count) {
585
+ return TaLanguageUtil.say({
586
+ "zh-CN": `连续 ${count} 轮失败,已暂停,等你看看`,
587
+ "zh-TW": `連續 ${count} 輪失敗,已暫停,等你看看`,
588
+ "en-US": `Paused after ${count} failed turns in a row, for you to look at`,
589
+ "ja-JP": `${count} 回続けて失敗したため一時停止しました。確認をお待ちしています`
590
+ });
591
+ }
592
+ GoalServerTexts.stuck = stuck;
593
+ function startIt(title) {
594
+ return TaLanguageUtil.say({
595
+ "zh-CN": `开始这个目标吗:${title}`,
596
+ "zh-TW": `開始這個目標嗎:${title}`,
597
+ "en-US": `Start this goal: ${title}`,
598
+ "ja-JP": `この目標を始めますか:${title}`
599
+ });
600
+ }
601
+ GoalServerTexts.startIt = startIt;
602
+ function acceptIt(summary) {
603
+ return TaLanguageUtil.say({
604
+ "zh-CN": `验收结果:${summary}`,
605
+ "zh-TW": `驗收結果:${summary}`,
606
+ "en-US": `Accept the result: ${summary}`,
607
+ "ja-JP": `結果を確認:${summary}`
608
+ });
609
+ }
610
+ GoalServerTexts.acceptIt = acceptIt;
611
+ })(GoalServerTexts ||= {});
612
+
613
+ // web-src/extension.ts
614
+ var CRON_RUN_MARK = "<ta-cron-run>";
615
+ function activate(pi) {
616
+ let reached;
617
+ const reach = () => reached ??= TaHostUtil.reach(pi.events, NAME).then((answer) => answer?.service);
618
+ const book = async () => {
619
+ const service = await reach();
620
+ if (!service) {
621
+ throw new Error("Goals need the Ta service: start it with `ta serve` (or open Ta Desktop).");
622
+ }
623
+ return service;
624
+ };
625
+ let place = "none";
626
+ function tool(name, on) {
627
+ const active = pi.getActiveTools();
628
+ const has = active.includes(name);
629
+ if (on && !has) {
630
+ pi.setActiveTools([...active, name]);
631
+ } else if (!on && has) {
632
+ pi.setActiveTools(active.filter((other) => other !== name));
633
+ }
634
+ }
635
+ pi.on("session_start", () => {
636
+ reach();
637
+ });
638
+ pi.on("before_agent_start", async (event, ctx) => {
639
+ const service = await reach().catch(() => {
640
+ return;
641
+ });
642
+ const prompt = ctx.getSystemPrompt?.();
643
+ const role = TaHostUtil.role(prompt);
644
+ place = !service ? "none" : TaHostUtil.marked(prompt, GOAL_MARK) ? "goal" : ctx.sessionManager.getSessionFile() && !role.includes(CRON_RUN_MARK) && !role.includes(TA_WITH_OTHERS_MARK) ? "user" : "none";
645
+ tool(GoalPrompt.START_TOOL.name, place === "user");
646
+ tool(GoalPrompt.NOTE_TOOL.name, place === "user");
647
+ tool(GoalPrompt.UPDATE_TOOL.name, place === "goal");
648
+ if (place === "user" && service) {
649
+ const [goals, settings] = await Promise.all([service.list().catch(() => []), service.settings()]);
650
+ event.systemPromptOptions.sections = { ...event.systemPromptOptions.sections, [SECTION]: GoalPrompt.section(goals, settings) };
651
+ }
652
+ return;
653
+ });
654
+ pi.on("agent_end", (event) => {
655
+ if (place === "none") {
656
+ return;
657
+ }
658
+ const answer = [...event.messages ?? []].reverse().find((message) => message.role === "assistant");
659
+ if (!answer || answer.stopReason === "aborted" || answer.stopReason === "error") {
660
+ return;
661
+ }
662
+ const reply = GoalUtil.text(answer.content);
663
+ const result = GoalUtil.blocks(reply, RESULT).map(GoalUtil.resultCard).find(Boolean);
664
+ const card = GoalUtil.blocks(reply, CARD).map(GoalUtil.card).find(Boolean);
665
+ const question = result ? GoalServerTexts.acceptIt(result.summary) : card ? GoalServerTexts.startIt(card.title) : undefined;
666
+ if (question) {
667
+ pi.appendEntry(TA_ASK_ENTRY, TaAskUtil.entry(question));
668
+ }
669
+ });
670
+ pi.registerTool({
671
+ ...GoalPrompt.START_TOOL,
672
+ execute: async (_id, params, _signal, _update, ctx) => {
673
+ const goal = await (await book()).start(params, { cwd: ctx.cwd, origin: ctx.sessionManager.getSessionFile() });
674
+ const hours = (ms) => `${Math.round(ms / 3600000 * 10) / 10}h`;
675
+ return {
676
+ content: [
677
+ {
678
+ type: "text",
679
+ text: `Started "${goal.title}" in a conversation of its own: it plans and works at its pace (a turn every ${hours(goal.paceMs)}, at most ${hours(goal.budgetMs)} a day) and comes back with the result to accept. Tell the user so in a line; do not do its work here.`
680
+ }
681
+ ],
682
+ details: { id: goal.id, sessionFile: goal.sessionFile }
683
+ };
684
+ }
685
+ });
686
+ pi.registerTool({
687
+ ...GoalPrompt.NOTE_TOOL,
688
+ execute: async (_id, params) => {
689
+ const goal = await (await book()).note(String(params?.goal ?? ""), String(params?.note ?? ""));
690
+ return { content: [{ type: "text", text: `"${goal.title}" reads it on its next turn, which comes soon.` }], details: undefined };
691
+ }
692
+ });
693
+ pi.registerTool({
694
+ ...GoalPrompt.UPDATE_TOOL,
695
+ execute: async (_id, params, _signal, _update, ctx) => {
696
+ const file = ctx.sessionManager.getSessionFile();
697
+ if (!file) {
698
+ throw new Error("This conversation is no goal.");
699
+ }
700
+ const goal = await (await book()).update(file, params);
701
+ const said = goal.status === "review" ? `Recorded. Now end your reply with the ${RESULT} block, for the user to accept.` : goal.status === "done" ? "The goal is done. Say so in one line." : goal.status === "paused" ? "The goal is paused until the user resumes it." : `Recorded. The next turn comes ${goal.nextAt ? `at ${new Date(goal.nextAt).toISOString().slice(0, 16)} UTC` : "at its pace"}; end this turn.`;
702
+ return { content: [{ type: "text", text: said }], details: undefined };
703
+ }
704
+ });
705
+ }
706
+ export {
707
+ activate as default
708
+ };