coopani-world-agent-bridge 0.1.4 → 0.1.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.5 - 2026-12-06
4
+
5
+ - Fixed lifecycle and delivery reliability: guarded `start()`/`stop()` race via run generation counter, handled timer promise rejections safely, and stopped archiving inbox briefs or consuming daily quota / marking `done/` receipts when `pushEvent` returns `contextDelivery: 'archive-only'` (hidden World) or when Host is stopped.
6
+ - Hardened `bridge-fs.ts` and `frontmatter.ts`: stripped Windows `\\?\` / `\\.\` prefixes, rejected drive-relative paths, resolved junctions/symlinks via `realpathSync`, blocked NTFS ADS (`:`) and Windows reserved device names, collapsed `..` in slugs, wrote owner locks atomically, cleaned up `.moving-*` on `EXDEV` retries, unescaped quoted frontmatter values, and fixed empty frontmatter block parsing (`---\n---\nbody`).
7
+ - Improved `world.ts` state, caching, and reading: eliminated the 500-file `knownDone` replay loop by intersecting with active `done/` entries, added size/mtime fingerprints to `inFlightPushed`, sorted `listBoxEntries` by `lstatSync` before reading only the top `limit` files, handled hot `bridgeDir` switches cleanly, guarded tools against `ownerConflict`, and added bounded chunked streaming in `bridge_read_note` aligned with frontmatter-stripped body offsets.
8
+ - Regenerated `describe.json` with `prompts` included and upgraded panel to `panel-0.1.5.{js,css}` (`ctx.timeout`, clipboard fallback inside `ctx.root`, `ctx.signal.aborted` checks, persistent `loadError` banner, `var(--on-accent)` button contrast).
9
+
3
10
  ## 0.1.4 - 2026-12-05
4
11
 
5
12
  - Added native OS folder picker button(「选择文件夹切换…」)using Coopanion `ctx.pickPath({ kind: 'directory' })` directly inside the panel, switching and initializing the 4 mailbox subdirectories in one click.
package/describe.json CHANGED
@@ -6,7 +6,10 @@
6
6
  "parameters": {
7
7
  "type": "object",
8
8
  "additionalProperties": false,
9
- "required": ["title", "content"],
9
+ "required": [
10
+ "title",
11
+ "content"
12
+ ],
10
13
  "properties": {
11
14
  "title": {
12
15
  "type": "string",
@@ -22,7 +25,9 @@
22
25
  }
23
26
  }
24
27
  },
25
- "tags": ["write"],
28
+ "tags": [
29
+ "write"
30
+ ],
26
31
  "summary": {
27
32
  "zh": "向外部 AI 编程工坊发件箱写入一篇便签或委托。",
28
33
  "en": "Writes a note or task handoff into the external agent outbox."
@@ -37,7 +42,11 @@
37
42
  "properties": {
38
43
  "box": {
39
44
  "type": "string",
40
- "enum": ["archived", "outbox", "done"],
45
+ "enum": [
46
+ "archived",
47
+ "outbox",
48
+ "done"
49
+ ],
41
50
  "description": "Which mailbox folder to list. Defaults to archived."
42
51
  },
43
52
  "limit": {
@@ -48,7 +57,9 @@
48
57
  }
49
58
  }
50
59
  },
51
- "tags": ["read"],
60
+ "tags": [
61
+ "read"
62
+ ],
52
63
  "summary": {
53
64
  "zh": "按时间倒序列出传书信箱的元数据清单(不含正文)。",
54
65
  "en": "Lists metadata of notes in archived, outbox, or done (newest first, no body)."
@@ -60,11 +71,18 @@
60
71
  "parameters": {
61
72
  "type": "object",
62
73
  "additionalProperties": false,
63
- "required": ["box", "filename"],
74
+ "required": [
75
+ "box",
76
+ "filename"
77
+ ],
64
78
  "properties": {
65
79
  "box": {
66
80
  "type": "string",
67
- "enum": ["archived", "outbox", "done"],
81
+ "enum": [
82
+ "archived",
83
+ "outbox",
84
+ "done"
85
+ ],
68
86
  "description": "Which mailbox folder to read from."
69
87
  },
70
88
  "filename": {
@@ -84,7 +102,9 @@
84
102
  }
85
103
  }
86
104
  },
87
- "tags": ["read"],
105
+ "tags": [
106
+ "read"
107
+ ],
88
108
  "summary": {
89
109
  "zh": "按文件名分段读取指定信箱中的单篇简报或便签正文。",
90
110
  "en": "Reads a specific note in pages by filename with path-traversal protection."
@@ -116,5 +136,13 @@
116
136
  },
117
137
  "trigger": "piggyback"
118
138
  }
139
+ ],
140
+ "prompts": [
141
+ {
142
+ "key": "worlds.agent-bridge.envPrompt",
143
+ "title": "工坊传书提示词",
144
+ "role": "envPrompt",
145
+ "content": "# 工坊传书(Agent Bridge)\n\n这里是桌面与外部 AI 编程工坊之间的双向传书信箱。\n\n**硬约束:**\n- **你只能看到工坊主动写进信箱的文字简报,看不到外部代码仓库、终端画面、报错日志或工坊是否在线;没写在简报里的细节绝不脑补。**\n- **收到工坊简报后,由你自己决定要不要回应、要不要记进长期记忆;普通进度同步若无需表态,直接静默消化即可,不要机械复读「收到」。**\n- **把便签放进发件箱只代表已投递,不代表外部工坊已开始执行;在收到「已被取走」回执前,不要假设对方已经处理。**\n- **信箱仅读取纯文本与 Markdown;若遇到图片或二进制附件提示,绝不编造其内容。**\n\n## 配合边界\n- 简报正文已随事件完整送达的,直接消化即可,无需再调读取工具重读。\n- 仅在有明确事项、任务或近期摘要需要转交外部工坊时才写外发便签,单次表达清楚,不要把普通闲聊拆成多封便签连发。\n"
146
+ }
119
147
  ]
120
148
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coopani-world-agent-bridge",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "description": "工坊传书(需 Coopanion 0.2.22+):通过纯本地目录信箱,打通外部 AI 编程助手(Antigravity / Claude Code / Cursor / Codex / WorkBuddy 等)与桌宠的双向简报与便签传递。",
6
6
  "author": {
@@ -31,8 +31,8 @@
31
31
  "displayName": "工坊传书",
32
32
  "describe": "describe.json",
33
33
  "icon": "assets/icon.svg",
34
- "webUiClient": "web/panel-0.1.4.js",
35
- "webUiStyle": "web/panel-0.1.4.css",
34
+ "webUiClient": "web/panel-0.1.5.js",
35
+ "webUiStyle": "web/panel-0.1.5.css",
36
36
  "tags": [
37
37
  "apps",
38
38
  "local",
package/src/bridge-fs.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  lstatSync,
6
6
  mkdirSync,
7
7
  readFileSync,
8
+ realpathSync,
8
9
  renameSync,
9
10
  rmSync,
10
11
  unlinkSync,
@@ -64,8 +65,42 @@ export function bridgeDirs(root: string): BridgeDirs {
64
65
  };
65
66
  }
66
67
 
68
+ function stripWinNamespacePrefix(p: string): string {
69
+ if (process.platform !== 'win32') return p;
70
+ if (/^\\\\[?.]\\UNC\\/i.test(p)) {
71
+ return '\\\\' + p.slice(8);
72
+ }
73
+ if (/^\\\\[?.]\\[A-Za-z]:/.test(p)) {
74
+ return p.slice(4);
75
+ }
76
+ return p;
77
+ }
78
+
79
+ function realpathBestEffort(p: string): string {
80
+ const resolved = resolve(stripWinNamespacePrefix(p));
81
+ const tail: string[] = [];
82
+ let cur = resolved;
83
+ while (!existsSync(cur)) {
84
+ const parent = dirname(cur);
85
+ if (parent === cur) break;
86
+ const base = cur.slice(parent.length).replace(/^[\\/]+/, '');
87
+ if (base) tail.unshift(base);
88
+ cur = parent;
89
+ }
90
+ let realBase = cur;
91
+ if (existsSync(cur)) {
92
+ try {
93
+ const fn = realpathSync.native ?? realpathSync;
94
+ realBase = stripWinNamespacePrefix(fn(cur));
95
+ } catch {
96
+ realBase = cur;
97
+ }
98
+ }
99
+ return tail.length > 0 ? resolve(realBase, ...tail) : resolve(realBase);
100
+ }
101
+
67
102
  function normForCompare(p: string): string {
68
- let out = resolve(p);
103
+ let out = realpathBestEffort(p);
69
104
  if (out.length > 3 && (out.endsWith('\\') || out.endsWith('/'))) {
70
105
  out = out.slice(0, -1);
71
106
  }
@@ -95,14 +130,22 @@ export function validateBridgeDir(rawDir: string, forbiddenDirs: readonly string
95
130
  reason: '尚未配置 bridgeDir(在扩展设置里填写一个独立目录即可开启传书)。',
96
131
  };
97
132
  }
98
- if (!isAbsolute(trimmed)) {
133
+ if (/^\\\\\.\\/.test(trimmed)) {
99
134
  return {
100
135
  ok: false,
101
136
  state: 'error',
102
- reason: 'bridgeDir 必须是绝对路径,请填入完整的本地文件夹路径。',
137
+ reason: 'bridgeDir 不能使用 Windows 设备命名空间路径(\\\\.\\)。',
103
138
  };
104
139
  }
105
- const resolved = resolve(trimmed);
140
+ const cleaned = stripWinNamespacePrefix(trimmed);
141
+ if (!isAbsolute(cleaned) || /^\\[^\\]/.test(cleaned) || /^[A-Za-z]:(?![\\/])/.test(cleaned)) {
142
+ return {
143
+ ok: false,
144
+ state: 'error',
145
+ reason: 'bridgeDir 必须是完整的绝对路径,请填入含盘符或根目录的本地文件夹路径。',
146
+ };
147
+ }
148
+ const resolved = resolve(cleaned);
106
149
  for (const rawForbidden of forbiddenDirs) {
107
150
  const f = typeof rawForbidden === 'string' ? rawForbidden.trim() : '';
108
151
  if (!f) continue;
@@ -136,8 +179,10 @@ export function validateBridgeDir(rawDir: string, forbiddenDirs: readonly string
136
179
  return { ok: true, dir: resolved, dirs };
137
180
  }
138
181
 
182
+ const WIN_RESERVED_STEMS = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
183
+
139
184
  /**
140
- * 严格校验信箱内单个文件名,防路径穿越、斜杠、空字节、盘符与符号链接逃逸。
185
+ * 严格校验信箱内单个文件名,防路径穿越、斜杠、空字节、ADS 流、保留设备名、盘符与符号链接逃逸。
141
186
  */
142
187
  export function assertSafeFilename(boxDir: string, filename: string): string {
143
188
  if (typeof filename !== 'string' || !filename.trim()) {
@@ -148,15 +193,20 @@ export function assertSafeFilename(boxDir: string, filename: string): string {
148
193
  name.includes('\0')
149
194
  || name.includes('/')
150
195
  || name.includes('\\')
196
+ || name.includes(':')
151
197
  || name.includes('..')
152
198
  || name.startsWith('.')
153
199
  || /^[A-Za-z]:/.test(name)
154
200
  ) {
155
- throw new Error(`非法文件名:${filename}(仅允许当前信箱内的纯文件名,禁止路径分隔符或 ..)。`);
201
+ throw new Error(`非法文件名:${filename}(仅允许当前信箱内的纯文件名,禁止路径分隔符、冒号或 ..)。`);
202
+ }
203
+ const stem = name.split('.')[0] ?? '';
204
+ if (WIN_RESERVED_STEMS.test(stem)) {
205
+ throw new Error(`非法文件名:${filename}(系统保留设备名)。`);
156
206
  }
157
- const resolvedBox = resolve(boxDir);
207
+ const resolvedBox = realpathBestEffort(boxDir);
158
208
  const target = resolve(resolvedBox, name);
159
- if (dirname(target) !== resolvedBox) {
209
+ if (normForCompare(dirname(target)) !== normForCompare(resolvedBox)) {
160
210
  throw new Error(`非法路径:${filename} 超出信箱目录边界。`);
161
211
  }
162
212
  if (existsSync(target)) {
@@ -164,6 +214,10 @@ export function assertSafeFilename(boxDir: string, filename: string): string {
164
214
  if (st.isSymbolicLink() || !st.isFile()) {
165
215
  throw new Error(`拒绝读取符号链接或非普通文件:${name}`);
166
216
  }
217
+ const realTarget = realpathBestEffort(target);
218
+ if (normForCompare(dirname(realTarget)) !== normForCompare(resolvedBox)) {
219
+ throw new Error(`拒绝读取目录外映射文件:${name}`);
220
+ }
167
221
  }
168
222
  return target;
169
223
  }
@@ -198,9 +252,11 @@ export function sanitizeTitleSlug(title: string): string {
198
252
  .replace(/[<>:"/\\|?*\u0000-\u001f]/g, ' ')
199
253
  .trim()
200
254
  .replace(/\s+/g, '-')
255
+ .replace(/\.{2,}/g, '-')
256
+ .replace(/-{2,}/g, '-')
201
257
  .replace(/^[.-]+|[.-]+$/g, '');
202
258
  if (!cleaned) return 'note';
203
- return cleaned.slice(0, 48).replace(/-+$/g, '') || 'note';
259
+ return cleaned.slice(0, 48).replace(/^[.-]+|[.-]+$/g, '') || 'note';
204
260
  }
205
261
 
206
262
  /** 构造稳定可控长度的 senderKey。 */
@@ -250,21 +306,52 @@ export async function moveFileAtomicWithRetry(
250
306
  const maxRetries = ops.retries ?? 5;
251
307
  const baseDelayMs = ops.baseDelayMs ?? 50;
252
308
 
253
- const targetName = allocateUniqueFile(destDir, desiredName);
254
- const dest = join(destDir, targetName);
309
+ let targetName = existsSync(join(destDir, desiredName))
310
+ ? allocateUniqueFile(destDir, desiredName)
311
+ : desiredName;
312
+ let dest = join(destDir, targetName);
313
+ let movedToDest = false;
255
314
 
256
315
  for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
316
+ if (movedToDest) {
317
+ try {
318
+ unlinkFn(src);
319
+ return targetName;
320
+ } catch (err) {
321
+ const code = (err as NodeJS.ErrnoException)?.code ?? '';
322
+ if (code === 'ENOENT') return targetName;
323
+ if (RETRY_CODES.has(code) && attempt < maxRetries) {
324
+ await sleep(baseDelayMs * (2 ** attempt));
325
+ continue;
326
+ }
327
+ throw err;
328
+ }
329
+ }
257
330
  try {
258
331
  renameFn(src, dest);
259
332
  return targetName;
260
333
  } catch (err) {
261
334
  const code = (err as NodeJS.ErrnoException)?.code ?? '';
262
335
  if (code === 'EXDEV') {
263
- const tmpDest = join(destDir, `.moving-${process.pid}-${Date.now()}-${targetName}`);
264
- copyFn(src, tmpDest);
265
- renameFn(tmpDest, dest);
266
- unlinkFn(src);
267
- return targetName;
336
+ const tmpDest = join(destDir, `.moving-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}-${targetName}`);
337
+ try {
338
+ copyFn(src, tmpDest);
339
+ renameFn(tmpDest, dest);
340
+ movedToDest = true;
341
+ unlinkFn(src);
342
+ return targetName;
343
+ } catch (exErr) {
344
+ if (!movedToDest) {
345
+ try { rmSync(tmpDest, { force: true }); } catch {}
346
+ }
347
+ const exCode = (exErr as NodeJS.ErrnoException)?.code ?? '';
348
+ if (movedToDest && exCode === 'ENOENT') return targetName;
349
+ if (RETRY_CODES.has(exCode) && attempt < maxRetries) {
350
+ await sleep(baseDelayMs * (2 ** attempt));
351
+ continue;
352
+ }
353
+ throw exErr;
354
+ }
268
355
  }
269
356
  if (RETRY_CODES.has(code) && attempt < maxRetries) {
270
357
  await sleep(baseDelayMs * (2 ** attempt));
@@ -330,10 +417,13 @@ export function isForeignActiveOwner(
330
417
  }
331
418
 
332
419
  export function writeOwnerLock(rootDir: string, rec: OwnerLockRecord): void {
420
+ const target = join(rootDir, OWNER_FILE);
421
+ const tmp = join(rootDir, `.agent-bridge-owner.tmp-${process.pid}-${Date.now()}`);
333
422
  try {
334
- writeFileSync(join(rootDir, OWNER_FILE), JSON.stringify(rec, null, 2) + '\n', 'utf8');
423
+ writeFileSync(tmp, JSON.stringify(rec, null, 2) + '\n', 'utf8');
424
+ renameSync(tmp, target);
335
425
  } catch {
336
- // ignore transient lock write failure
426
+ try { rmSync(tmp, { force: true }); } catch {}
337
427
  }
338
428
  }
339
429
 
@@ -10,9 +10,18 @@ function stripQuotes(value: string): string {
10
10
  if (trimmed.length >= 2) {
11
11
  const first = trimmed[0];
12
12
  const last = trimmed[trimmed.length - 1];
13
- if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
13
+ if (first === '"' && last === '"') {
14
+ try {
15
+ const unescaped = JSON.parse(trimmed);
16
+ if (typeof unescaped === 'string') return unescaped.trim();
17
+ } catch {
18
+ // fallback below
19
+ }
14
20
  return trimmed.slice(1, -1).trim();
15
21
  }
22
+ if (first === "'" && last === "'") {
23
+ return trimmed.slice(1, -1).replace(/''/g, "'").trim();
24
+ }
16
25
  }
17
26
  return trimmed;
18
27
  }
@@ -28,27 +37,30 @@ export function parseBriefDocument(raw: string, fallbackTitle: string): ParsedBr
28
37
  let priority: 'normal' | 'urgent' = 'normal';
29
38
  let body = normalized;
30
39
 
31
- if (normalized.startsWith('---\n')) {
32
- const closeIdx = normalized.indexOf('\n---', 4);
33
- if (closeIdx !== -1) {
34
- const afterClose = closeIdx + 4;
35
- const nextChar = normalized[afterClose];
36
- if (nextChar === undefined || nextChar === '\n') {
37
- const headerBlock = normalized.slice(4, closeIdx);
38
- body = normalized.slice(nextChar === '\n' ? afterClose + 1 : afterClose);
39
- for (const line of headerBlock.split('\n')) {
40
- const colon = line.indexOf(':');
41
- if (colon <= 0) continue;
42
- const key = line.slice(0, colon).trim().toLowerCase();
43
- const val = stripQuotes(line.slice(colon + 1));
44
- if (!val) continue;
45
- if (key === 'source') {
46
- source = val;
47
- } else if (key === 'title') {
48
- title = val;
49
- } else if (key === 'priority') {
50
- priority = val.toLowerCase() === 'urgent' ? 'urgent' : 'normal';
51
- }
40
+ const lines = normalized.split('\n');
41
+ if (lines[0] === '---') {
42
+ let closeLine = -1;
43
+ for (let i = 1; i < lines.length; i += 1) {
44
+ if (lines[i] === '---') {
45
+ closeLine = i;
46
+ break;
47
+ }
48
+ }
49
+ if (closeLine !== -1) {
50
+ const headerLines = lines.slice(1, closeLine);
51
+ body = lines.slice(closeLine + 1).join('\n');
52
+ for (const line of headerLines) {
53
+ const colon = line.indexOf(':');
54
+ if (colon <= 0) continue;
55
+ const key = line.slice(0, colon).trim().toLowerCase();
56
+ const val = stripQuotes(line.slice(colon + 1));
57
+ if (!val) continue;
58
+ if (key === 'source') {
59
+ source = val;
60
+ } else if (key === 'title') {
61
+ title = val;
62
+ } else if (key === 'priority') {
63
+ priority = val.toLowerCase() === 'urgent' ? 'urgent' : 'normal';
52
64
  }
53
65
  }
54
66
  }