@celljs/ta-cloud-handoff 0.0.0-stage → 4.37.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/README.en.md ADDED
@@ -0,0 +1,22 @@
1
+ # Cell - Ta Cloud Handoff
2
+
3
+ A pi package that comes with Ta (on by default, off in Settings → Extensions): **when your computer has to go, a conversation goes on in your cloud workspace, and comes back when you do.** Work runs on your computer first (it needs what is there); the cloud is a standby. Design: [docs/design/ta-cloud-handoff.md](../../docs/design/ta-cloud-handoff.md).
4
+
5
+ It needs a cloud workspace in Settings → Remote hosts (`ta://<name>`, the address of a gateway or any Ta service and a token), and the conversation's folder in a git repository of this computer with a commit.
6
+
7
+ - **Go on in the cloud**: the menu of the conversation in the lists (an entry for each cloud workspace), or say so in it (the tool `cloud_handoff`, which goes once the turn ends). The conversation stops here, then the whole work of the repository goes: its history (the branch's whole history the first time, only new commits after), changes not committed, new files, files deleted, byte for byte, done only when both sides make the same git tree. What git ignores (dependencies, builds, `.env`) stays; the cloud installs again as the project does. There it is at the same path when it can be (the paths of the conversation still hold), else under `~/ta-handoff/<path>`. Then the session file goes, with a note at its end (the model reads it, the page draws a line). A turn running here goes on there; otherwise it is just there, to carry on with there.
8
+ - **While it is away**: it is tagged Cloud in the lists and takes no message here. What only the computer can do (its apps, desktop, devices, network, keychain) the cloud notes with the tool `later_on_computer`, and goes on with the rest.
9
+ - **Bring back to this computer**: the same menu. It stops there, then the cloud's work comes back: the files become the cloud's when nothing changed here (its commits on the branch here too); merged three ways from where they parted when both changed; left as they are here when both changed the same file, the cloud's kept at `refs/ta-handoff/<id>/cloud` for the agent to compare. What was said there follows the conversation here, with a note; it goes on here by itself when the cloud was cut off, left steps for the computer, or the files conflict.
10
+
11
+ Methods of the host (`callPackageHost('@celljs/ta-cloud-handoff', …)`): `list()`, `handOff(sessionFile, cloud?)`, `handOffAfterTurn(sessionFile, cloud?)`, `takeBack(id)`, `away(sessionFile)`. Commands, files and the Ta service of the cloud go through `TaExtensionHost.cloud`; tokens stay in `ta serve`.
12
+
13
+ - **By itself, and back** (Settings → Devices → Cloud handoff, on by default): as the computer sleeps (its lid closed) or runs low unplugged (auto: 15 minutes left as the system estimates, else 10%; or 10/20/30%), the conversations that run go on in the cloud; on macOS, `ta-power` of Ta Desktop holds the sleep till that is done (20 s at most). Once the computer is back (awake, or plugged in) and the turn there ended, those come back by themselves. As a conversation starts to run, the history of its repository goes to the cloud ahead, so a handoff carries only what came after. The power events are the host's (`TaExtensionHost.power`); elsewhere `ta power sleep|wake` tells Ta.
14
+
15
+ Not yet (step three on in the design): the cloud taking over a computer that died, crashed or went offline; folders left out; snapshots of the environment; folders outside git.
16
+
17
+ ## Development
18
+
19
+ ```bash
20
+ bun run build
21
+ bun test ./lib
22
+ ```
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta Cloud Handoff
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ta 自带的 pi 包(默认开启,可在 设置 → 扩展 关闭):**电脑要走开时,把对话交给云端工作区接着做,回来再接回本机。** 任务默认在本机跑(依赖本机环境),云端只是热备。设计记录见 [docs/design/ta-cloud-handoff.md](../../docs/design/ta-cloud-handoff.md)。
4
+
5
+ 前提:在 设置 → 远程主机 里加了云端工作区(`ta://<名字>`,网关或任何 Ta 服务的地址 + 令牌),对话的目录在本机的一个有提交的 git 仓库里。
6
+
7
+ - **交给云端接着做**:对话列表里对话的菜单(有几个云端工作区就有几项),或在对话里说"交给云端接着做"(工具 `cloud_handoff`,这一轮结束后再走)。对话先在本机停下,再把仓库的整个工作状态带过去:已提交的历史(第一次带当前分支的全部历史,之后只带新增的提交)、没提交的改动、新文件、删掉的文件,一个字节不差,两边算出同一个 git tree 才算成功;git 忽略的文件(依赖、构建产物、`.env`)不带,云端按项目自己的方式重装。云端能建同一路径就用同一路径(对话里的路径都还对),否则放在 `~/ta-handoff/<原路径>`。对话文件随后带过去,末尾加一条说明(模型读得到,页面上是一行"换到云端接着做");本机这一轮在跑就在云端接着跑,没在跑就只是放过去,在云端那边接着聊。
8
+ - **在云端时**:列表里这个对话带"云端"标签,本机不再接受新消息(会提示去云端看或先接回)。云端遇到只有本机能做的事(本机应用、桌面、设备、内网、钥匙串),用工具 `later_on_computer` 记下,接着做其余的。
9
+ - **接回本机**:同一个菜单。先停下云端,再把云端的改动带回来:本机这期间没改就直接变成云端的样子(云端的提交也接到本机分支上);本机也改了就按切走时的状态三方合并;两边改了同一个文件就保持本机不动,云端的版本放在 `refs/ta-handoff/<id>/cloud`,并告诉 Agent 去比对。云端说过的话接到本机对话后面,末尾一条"从云端接回本机";云端被打断、留了本机要做的事、或有冲突时,本机自动接着做。
10
+
11
+ 宿主方法(`callPackageHost('@celljs/ta-cloud-handoff', …)`):`list()` 给出在云端的对话和可用的云端工作区;`handOff(sessionFile, cloud?)`;`handOffAfterTurn(sessionFile, cloud?)`;`takeBack(id)`;`away(sessionFile)`。云端的命令、文件和 Ta 服务经 `TaExtensionHost.cloud` 调用,令牌不离开 `ta serve`。
12
+
13
+ - **自动交出与接回**(设置 → 设备与连接 → 云端接力,默认开):合盖或睡眠时、没接电源且电量低时(自动 = 系统估计剩 15 分钟,估不出按 10%;或 10/20/30%),正在跑的对话自动交给云端;macOS 上桌面版的 `ta-power` 会拖住睡眠,等交接完(最多 20 秒)。电脑醒来或接上电源、云端这一轮做完,自动交出的对话自动接回。对话一开始跑就把仓库历史提前送到云端,交出时只带之后的改动。电源事件来自宿主 `TaExtensionHost.power`,其他系统可用 `ta power sleep|wake` 告诉 Ta。
14
+
15
+ 还没做(设计第 8 节第三步起):电脑没电直接关机、崩溃、断网时云端接管;按目录排除;云端环境快照;不在 git 里的目录。
16
+
17
+ ## 开发
18
+
19
+ ```bash
20
+ bun run build
21
+ bun test ./lib
22
+ ```
@@ -0,0 +1,398 @@
1
+ // ../ta-protocol/esm/common/ta-extension-host.js
2
+ var TA_CLOUD_OUTPUT_BYTES = 1024 * 1024;
3
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
4
+ var TA_HOST_EVENT = "ta:host";
5
+ var TaHostUtil;
6
+ (function(TaHostUtil2) {
7
+ TaHostUtil2.WAIT_MS = 1000;
8
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
9
+ return new Promise((resolve) => {
10
+ let heard = false;
11
+ let answered = false;
12
+ const timer = setTimeout(() => resolve(undefined), waitMs);
13
+ const request = {
14
+ name,
15
+ heard: () => {
16
+ heard = true;
17
+ },
18
+ resolve: (answer) => {
19
+ answered = true;
20
+ clearTimeout(timer);
21
+ resolve(answer);
22
+ }
23
+ };
24
+ events.emit(TA_HOST_EVENT, request);
25
+ if (!heard && !answered) {
26
+ clearTimeout(timer);
27
+ resolve(undefined);
28
+ }
29
+ });
30
+ }
31
+ TaHostUtil2.reach = reach;
32
+ function marked(systemPrompt, mark) {
33
+ return role(systemPrompt).includes(mark);
34
+ }
35
+ TaHostUtil2.marked = marked;
36
+ function role(systemPrompt) {
37
+ if (!systemPrompt) {
38
+ return "";
39
+ }
40
+ const open = `<addendum>
41
+ `;
42
+ const start = systemPrompt.indexOf(open);
43
+ const context = systemPrompt.indexOf(`<project_context>
44
+ `);
45
+ if (start < 0 || context >= 0 && context < start) {
46
+ return "";
47
+ }
48
+ const end = systemPrompt.indexOf(`
49
+ </addendum>`, start);
50
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
51
+ }
52
+ TaHostUtil2.role = role;
53
+ })(TaHostUtil || (TaHostUtil = {}));
54
+ var TA_DOUBLE_LOOK = {
55
+ name: "@celljs/ta-web",
56
+ key: "assistant.species",
57
+ given: ["trex", "triceratops", "stegosaurus", "brachiosaurus", "velociraptor", "ankylosaurus", "pteranodon", "parasaurolophus"]
58
+ };
59
+ var TaDoubleLookUtil;
60
+ (function(TaDoubleLookUtil2) {
61
+ function given(id) {
62
+ let hash = 2166136261;
63
+ for (let i = 0;i < id.length; i++) {
64
+ hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
65
+ }
66
+ return TA_DOUBLE_LOOK.given[(hash >>> 0) % TA_DOUBLE_LOOK.given.length];
67
+ }
68
+ TaDoubleLookUtil2.given = given;
69
+ })(TaDoubleLookUtil || (TaDoubleLookUtil = {}));
70
+ var TA_WITH_OTHERS_MARK = "[ta:speaks-with-others]";
71
+
72
+ // ../ta-protocol/esm/common/confine-protocol.js
73
+ var TA_CONFINED_MARK = "[ta:confined]";
74
+ var AT = String.raw`(?:^|[;&|(\`]|\$\()\s*(?:sudo\s+|env\s+(?:\S+=\S*\s+)*|npx\s+|bunx\s+|pnpm\s+(?:exec|dlx)\s+|yarn\s+dlx\s+|exec\s+|xargs\s+(?:-\S+\s+)*)*`;
75
+ var command = (names) => new RegExp(`${AT}(?:${names})(?=\\s|$|[;&|)])`, "m");
76
+ var BLOCKED = [
77
+ [/\bgit\b[^\n;&|]*\s(?:push|send-email|request-pull)\b/, "pushing: the user puts the work out once they looked at it"],
78
+ [/\bgit\b[^\n;&|]*\sremote\s+(?:add|set-url|rename|remove|rm)\b/, "changing the remotes"],
79
+ [/\bgit\b[^\n;&|]*\sconfig\b[^\n;&|]*(?:credential|url\.|core\.sshcommand|core\.hookspath)/i, "changing how git reaches others"],
80
+ [/\b(?:publish|unpublish|deprecate)\b/, "publishing"],
81
+ [
82
+ command("wrangler|vercel|netlify|flyctl|fly|firebase|heroku|gh|aws|gcloud|az|kubectl|helm|terraform|pulumi|docker|podman|eas|fastlane|xcrun\\s+altool|twine"),
83
+ "deploying, or the tools of a cloud"
84
+ ],
85
+ [command("ssh|scp|sftp|rsync|nc|ncat|netcat|telnet|ftp|socat"), "reaching other machines"],
86
+ [
87
+ /\b(?:curl|wget|http|https|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[^\n;&|]*(?:\s-[a-zA-Z]*[dFT]\b|\s--(?:data|upload|form|post|put|json)|\s-X\s*(?:POST|PUT|PATCH|DELETE)|\s-Method\s+(?:Post|Put|Patch|Delete)|\s-Body\b|\s-InFile\b)/i,
88
+ "sending data out"
89
+ ],
90
+ [
91
+ /(?:~|\$HOME|\$\{HOME\}|\$env:USERPROFILE|\/Users\/[^/\s]+|\/home\/[^/\s]+|\/root)[\\/]\.(?:ssh|aws|gnupg|netrc|npmrc|yarnrc|pypirc|zshenv|zshrc|zprofile|bashrc|bash_profile|profile|docker|kube|ta|codebuddy|claude|cursor|config[\\/](?:gh|gcloud|hub))\b/i,
92
+ "the user's secrets and settings"
93
+ ],
94
+ [/\bsecurity\s+(?:find|dump|export)-/, "the keychain"],
95
+ [command("printenv|env|set|export\\s+-p|declare\\s+-x|Get-ChildItem\\s+env:|gci\\s+env:|dir\\s+env:"), "printing the environment (it holds tokens)"],
96
+ [command("sudo|su|doas|osascript|launchctl|crontab|defaults\\s+write|schtasks|reg"), "acting as the system"],
97
+ [/\brm\s+-[a-zA-Z]*[rR][a-zA-Z]*\s+(?:-[a-zA-Z]+\s+)*(?:\/|~|\$HOME|\$\{HOME\})(?:\s|$|\/\s|\/\*)/, "deleting outside its directory"]
98
+ ];
99
+ var TaConfineUtil;
100
+ (function(TaConfineUtil2) {
101
+ TaConfineUtil2.FILE_TOOLS = ["read", "edit", "write", "grep", "find", "ls"];
102
+ TaConfineUtil2.COMMAND_TOOLS = ["bash", "powershell"];
103
+ function confine(role) {
104
+ return role.includes(TA_CONFINED_MARK) ? role : `${TA_CONFINED_MARK}
105
+ ${role}`;
106
+ }
107
+ TaConfineUtil2.confine = confine;
108
+ function confined(systemPrompt) {
109
+ return TaHostUtil.marked(systemPrompt, TA_CONFINED_MARK);
110
+ }
111
+ TaConfineUtil2.confined = confined;
112
+ function blocked(commandText) {
113
+ var _a;
114
+ const text = String(commandText !== null && commandText !== undefined ? commandText : "");
115
+ return (_a = BLOCKED.find(([pattern]) => pattern.test(text))) === null || _a === undefined ? undefined : _a[1];
116
+ }
117
+ TaConfineUtil2.blocked = blocked;
118
+ })(TaConfineUtil || (TaConfineUtil = {}));
119
+
120
+ // web-src/handoff-protocol.ts
121
+ var NAME = "@celljs/ta-cloud-handoff";
122
+ var HandoffSettingsUtil;
123
+ ((HandoffSettingsUtil) => {
124
+ HandoffSettingsUtil.AUTO_MINUTES = 15;
125
+ HandoffSettingsUtil.AUTO_PERCENT = 10;
126
+ HandoffSettingsUtil.PERCENTS = [10, 20, 30];
127
+ function of(stored) {
128
+ const value = stored && typeof stored === "object" ? stored : {};
129
+ return {
130
+ sleep: value.sleep !== false,
131
+ battery: value.battery !== false,
132
+ threshold: typeof value.threshold === "number" && HandoffSettingsUtil.PERCENTS.includes(value.threshold) ? value.threshold : "auto",
133
+ bringBack: value.bringBack !== false
134
+ };
135
+ }
136
+ HandoffSettingsUtil.of = of;
137
+ function low(battery, settings) {
138
+ if (!battery || battery.plugged) {
139
+ return false;
140
+ }
141
+ if (settings.threshold !== "auto") {
142
+ return battery.percent <= settings.threshold;
143
+ }
144
+ return battery.minutesLeft !== undefined ? battery.minutesLeft <= HandoffSettingsUtil.AUTO_MINUTES : battery.percent <= HandoffSettingsUtil.AUTO_PERCENT;
145
+ }
146
+ HandoffSettingsUtil.low = low;
147
+ })(HandoffSettingsUtil ||= {});
148
+ var HANDOFF_TOOL = "cloud_handoff";
149
+ var LATER_TOOL = "later_on_computer";
150
+ var LATER_ENTRY = "ta-cloud-handoff-later";
151
+ var NOTE_ENTRY = "ta-cloud-handoff";
152
+
153
+ // ../ta-protocol/esm/common/language.js
154
+ var TaLanguageUtil;
155
+ (function(TaLanguageUtil2) {
156
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
157
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
158
+ function of(tag) {
159
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
160
+ if (/^zh(\b|-)/.test(said)) {
161
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
162
+ }
163
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
164
+ }
165
+ TaLanguageUtil2.of = of;
166
+ function server(env = typeof process === "undefined" ? {} : process.env) {
167
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
168
+ }
169
+ TaLanguageUtil2.server = server;
170
+ function pick(language, words) {
171
+ return words[of(language)];
172
+ }
173
+ TaLanguageUtil2.pick = pick;
174
+ function say(words) {
175
+ return words[server()];
176
+ }
177
+ TaLanguageUtil2.say = say;
178
+ function chinese(language) {
179
+ return of(language).startsWith("zh");
180
+ }
181
+ TaLanguageUtil2.chinese = chinese;
182
+ function cjk(language) {
183
+ return of(language) !== "en-US";
184
+ }
185
+ TaLanguageUtil2.cjk = cjk;
186
+ function list(language, items) {
187
+ return items.join(cjk(language) ? "、" : ", ");
188
+ }
189
+ TaLanguageUtil2.list = list;
190
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
191
+
192
+ // web-src/server-texts.ts
193
+ var WHY = {
194
+ asked: "as the user asked",
195
+ sleep: "by itself as the user's computer was about to sleep (its lid closed, most likely)",
196
+ battery: "by itself as the battery of the user's computer ran low"
197
+ };
198
+ var HandoffTexts;
199
+ ((HandoffTexts) => {
200
+ function toCloud(options) {
201
+ return [
202
+ `This conversation moved from the user's computer to the cloud workspace ${options.cloud}, ${WHY[options.why ?? "asked"]}, to go on while their computer is away.`,
203
+ options.root === options.cloudRoot ? `- The files of ${options.root} are here at the same path, as they were: commits, changes and new files alike.` : `- The files of ${options.root} of the user's computer are here at ${options.cloudRoot}, as they were: commits, changes and new files alike. Read paths of the conversation so far under ${options.root} as under ${options.cloudRoot}.`,
204
+ "- What git ignores (installed dependencies, builds, .env files) did not come along: install or build again, as the project does, when you need them.",
205
+ options.cut ? "- The last turn was stopped as it moved: a command that ran then was cut off. Check what it did, and run it again if needed." : "",
206
+ `- Leave what only the user's computer can do (its apps, desktop, devices, local network, keychain, signed-in tools): note each with the tool ${LATER_TOOL} (without it, list them at the end of your reply under "Back on the computer"), and go on with the rest.`,
207
+ "- Push, publish or deploy only if the user asked for it in this conversation.",
208
+ options.goOn ? "- Go on with the work where it stopped." : ""
209
+ ].filter(Boolean).join(`
210
+ `);
211
+ }
212
+ HandoffTexts.toCloud = toCloud;
213
+ function back(options) {
214
+ const files = {
215
+ same: "The files are as they were: nothing changed in the cloud.",
216
+ taken: "The files here are now as the cloud left them.",
217
+ merged: "The files here are the cloud's work merged with what changed here meanwhile.",
218
+ conflict: `The files here were left as they were: these were changed both here and in the cloud: ${options.conflicts.join(", ")}. The cloud's work is in the commit ${options.ref}: compare and bring it in.`
219
+ };
220
+ return [
221
+ `This conversation came back from the cloud workspace ${options.cloud} to the user's computer.`,
222
+ `- ${files[options.files] ?? ""}`,
223
+ options.commits ? `- ${options.commits} commit(s) made in the cloud are on the branch here.` : "",
224
+ options.ref && options.files !== "conflict" ? `- HEAD moved here meanwhile: the cloud's commits are kept at ${options.ref}.` : "",
225
+ options.later.length ? `- Left for this computer: ${options.later.map((item) => `
226
+ - ${item}`).join("")}` : "",
227
+ options.goOn ? "- Go on here: do what was left for this computer, and look at the files if they need it." : ""
228
+ ].filter(Boolean).join(`
229
+ `);
230
+ }
231
+ HandoffTexts.back = back;
232
+ function goOn(note) {
233
+ const cloud = note.cloud;
234
+ const head = note.to === "cloud" && note.why === "sleep" ? TaLanguageUtil.say({
235
+ "zh-CN": `电脑要睡眠了,换到云端接着做 · ${cloud}`,
236
+ "zh-TW": `電腦要睡眠了,換到雲端接著做 · ${cloud}`,
237
+ "en-US": `The computer is going to sleep: going on in the cloud · ${cloud}`,
238
+ "ja-JP": `パソコンがスリープするのでクラウドで続ける · ${cloud}`
239
+ }) : note.to === "cloud" && note.why === "battery" ? TaLanguageUtil.say({
240
+ "zh-CN": `电量低,换到云端接着做 · ${cloud}`,
241
+ "zh-TW": `電量低,換到雲端接著做 · ${cloud}`,
242
+ "en-US": `Battery low: going on in the cloud · ${cloud}`,
243
+ "ja-JP": `電池残量が少ないのでクラウドで続ける · ${cloud}`
244
+ }) : note.to === "cloud" ? TaLanguageUtil.say({
245
+ "zh-CN": `换到云端接着做 · ${cloud}`,
246
+ "zh-TW": `換到雲端接著做 · ${cloud}`,
247
+ "en-US": `Going on in the cloud · ${cloud}`,
248
+ "ja-JP": `クラウドで続ける · ${cloud}`
249
+ }) : TaLanguageUtil.say({
250
+ "zh-CN": `从云端 ${cloud} 接回本机`,
251
+ "zh-TW": `從雲端 ${cloud} 接回本機`,
252
+ "en-US": `Back on this computer from ${cloud}`,
253
+ "ja-JP": `クラウド ${cloud} からこのパソコンに戻しました`
254
+ });
255
+ const conflicts = note.conflicts?.length ?? 0;
256
+ const later = note.later?.length ?? 0;
257
+ const more = [
258
+ conflicts ? TaLanguageUtil.say({
259
+ "zh-CN": `${conflicts} 个文件两边都改过`,
260
+ "zh-TW": `${conflicts} 個檔案兩邊都改過`,
261
+ "en-US": `${conflicts} file(s) changed on both sides`,
262
+ "ja-JP": `${conflicts} 個のファイルが両方で変更`
263
+ }) : "",
264
+ later ? TaLanguageUtil.say({
265
+ "zh-CN": `${later} 件事留给本机做`,
266
+ "zh-TW": `${later} 件事留給本機做`,
267
+ "en-US": `${later} step(s) left for this computer`,
268
+ "ja-JP": `${later} 件をこのパソコンで`
269
+ }) : ""
270
+ ].filter(Boolean);
271
+ return [head, ...more].join(" · ");
272
+ }
273
+ HandoffTexts.goOn = goOn;
274
+ function away(cloud) {
275
+ return TaLanguageUtil.say({
276
+ "zh-CN": `这个对话正在云端 ${cloud} 接着做:去那边看,或在对话列表的菜单里点“接回本机”再继续。`,
277
+ "zh-TW": `這個對話正在雲端 ${cloud} 接著做:去那邊看,或在對話列表的選單裡點「接回本機」再繼續。`,
278
+ "en-US": `This conversation goes on in the cloud workspace ${cloud}: follow it there, or bring it back from its menu in the list to go on here.`,
279
+ "ja-JP": `この会話はクラウド ${cloud} で続いています。そちらで見るか、一覧のメニューの「パソコンに戻す」で戻してから続けてください。`
280
+ });
281
+ }
282
+ HandoffTexts.away = away;
283
+ function stayed(reason) {
284
+ return TaLanguageUtil.say({
285
+ "zh-CN": `没能换到云端(${reason}),在本机接着做`,
286
+ "zh-TW": `沒能換到雲端(${reason}),在本機接著做`,
287
+ "en-US": `It did not move to the cloud (${reason}): going on here`,
288
+ "ja-JP": `クラウドへ移せませんでした(${reason})。このパソコンで続けます`
289
+ });
290
+ }
291
+ HandoffTexts.stayed = stayed;
292
+ function failed(reason) {
293
+ return `Moving this conversation to the cloud failed: ${reason}. It stays on this computer; tell the user in a line.`;
294
+ }
295
+ HandoffTexts.failed = failed;
296
+ })(HandoffTexts ||= {});
297
+
298
+ // web-src/extension.ts
299
+ function inCloud(ctx) {
300
+ const notes = (ctx.sessionManager.getBranch?.() ?? []).filter((entry) => entry.type === "custom_message" && entry.customType === NOTE_ENTRY);
301
+ return notes.at(-1)?.details?.to === "cloud";
302
+ }
303
+ function forOthers(ctx) {
304
+ const prompt = ctx.getSystemPrompt?.();
305
+ return TaHostUtil.marked(prompt, TA_WITH_OTHERS_MARK) || TaHostUtil.marked(prompt, TA_CONFINED_MARK);
306
+ }
307
+ function activate(pi) {
308
+ let reached;
309
+ const reach = () => reached ??= TaHostUtil.reach(pi.events, NAME).then((answer) => answer?.service);
310
+ function tool(name, on) {
311
+ const active = pi.getActiveTools();
312
+ if (on && !active.includes(name)) {
313
+ pi.setActiveTools([...active, name]);
314
+ } else if (!on && active.includes(name)) {
315
+ pi.setActiveTools(active.filter((other) => other !== name));
316
+ }
317
+ }
318
+ pi.on("session_start", () => {
319
+ reach();
320
+ });
321
+ pi.on("before_agent_start", async (_event, ctx) => {
322
+ const cloud = inCloud(ctx);
323
+ const service = cloud || forOthers(ctx) ? undefined : await reach().catch(() => {
324
+ return;
325
+ });
326
+ const file = ctx.sessionManager.getSessionFile();
327
+ const offer = !!service && !!file && (await service.list().catch(() => {
328
+ return;
329
+ }))?.workspaces.length;
330
+ tool(HANDOFF_TOOL, !!offer);
331
+ tool(LATER_TOOL, cloud);
332
+ });
333
+ pi.on("input", async (_event, ctx) => {
334
+ const file = ctx.sessionManager.getSessionFile();
335
+ const away = file ? await (await reach().catch(() => {
336
+ return;
337
+ }))?.away(file).catch(() => {
338
+ return;
339
+ }) : undefined;
340
+ if (!away) {
341
+ return { action: "continue" };
342
+ }
343
+ ctx.ui?.notify(HandoffTexts.away(away.cloud), "warning");
344
+ return { action: "handled" };
345
+ });
346
+ pi.registerTool({
347
+ name: HANDOFF_TOOL,
348
+ label: "Go on in the cloud",
349
+ description: "Moves this conversation to the user's cloud workspace once this turn ends, and it goes on there: its files (committed or not) and what was said. For when the user's computer is going away (low battery, lid to close, leaving) and the work should not stop. Only when the user asks for it.",
350
+ promptSnippet: "Move this conversation to the cloud to go on there",
351
+ parameters: {
352
+ type: "object",
353
+ properties: { cloud: { type: "string", description: "The name of the cloud workspace; default the first." } }
354
+ },
355
+ execute: async (_id, params, _signal, _update, ctx) => {
356
+ if (forOthers(ctx)) {
357
+ throw new Error("A conversation that works for others stays on this computer.");
358
+ }
359
+ const service = await reach();
360
+ const file = ctx.sessionManager.getSessionFile();
361
+ if (!service || !file) {
362
+ throw new Error("Moving to the cloud needs the Ta service and a conversation kept in a file.");
363
+ }
364
+ const moved = await service.handOffAfterTurn(file, params.cloud);
365
+ return {
366
+ content: [
367
+ {
368
+ type: "text",
369
+ text: moved ? `Moved to the cloud workspace ${moved.cloud}: it goes on there.` : "It moves to the cloud workspace once this turn ends, and goes on there. End the turn now: tell the user so in a line, and do nothing else here."
370
+ }
371
+ ],
372
+ details: moved ? { cloud: moved.cloud } : {}
373
+ };
374
+ }
375
+ });
376
+ pi.registerTool({
377
+ name: LATER_TOOL,
378
+ label: "Leave for the computer",
379
+ description: "Notes a step only the user's computer can do (its apps, desktop, devices, local network, keychain, signed-in tools), to be done there once the conversation comes back. Then go on with the rest.",
380
+ promptSnippet: "Note a step for the user's computer",
381
+ parameters: {
382
+ type: "object",
383
+ properties: { what: { type: "string", description: "The step, in a line: what to do and why it needs the computer." } },
384
+ required: ["what"]
385
+ },
386
+ execute: async (_id, params) => {
387
+ const what = String(params.what ?? "").trim();
388
+ if (!what) {
389
+ throw new Error("Say the step in a line.");
390
+ }
391
+ pi.appendEntry(LATER_ENTRY, { what });
392
+ return { content: [{ type: "text", text: `Noted for the user's computer: ${what}. Go on with the rest.` }], details: { what } };
393
+ }
394
+ });
395
+ }
396
+ export {
397
+ activate as default
398
+ };