dsh-mobile-plugin 0.5.136 → 0.5.137

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.
@@ -23,6 +23,9 @@ const MAX_TARGETS = 3;
23
23
  /** 一条事实最多几个分句。 */
24
24
  const MAX_CLAUSES = 3;
25
25
 
26
+ /** `apply_patch` 的路径要从补丁头里读,参数里没有单个 `file_path`。 */
27
+ const { patchFilePaths } = require('./patch-files.js');
28
+
26
29
  /** 删除类程序:高亮。 */
27
30
  const DELETE_PROGS = new Set(['rm', 'rmdir', 'unlink', 'shred']);
28
31
  /**
@@ -295,6 +298,15 @@ function callToPiece(toolName, args) {
295
298
  return { clause: `改 ${baseOf(p)}`, highlight: false, classKey: `${name}:${d}` };
296
299
  }
297
300
 
301
+ if (name === 'apply_patch') {
302
+ const paths = patchFilePaths(isRecord(args) ? args.input : '');
303
+ if (paths.length === 0) return { clause: '', highlight: false, classKey: 'tool:apply_patch' };
304
+ const head = baseOf(paths[0]);
305
+ const d = dirKeyOf(paths[0], opts.cwd);
306
+ const clause = paths.length === 1 ? `改 ${head}` : `改 ${head} 等 ${paths.length} 个文件`;
307
+ return { clause, highlight: false, classKey: `apply_patch:${d}` };
308
+ }
309
+
298
310
  if (name === 'read' || name === 'read_image') {
299
311
  const p = pathOf(args);
300
312
  if (!p) return { clause: '', highlight: false, classKey: `tool:${name}` };
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * `apply_patch` 的补丁正文 → 这次要改哪些文件。
5
+ *
6
+ * 宿主从 0.2.3 起把 `apply_patch` 默认摆到模型面前:一次调用能改好几个文件,路径写在补丁头
7
+ * 里(`*** Add File:` / `*** Update File:` / `*** Move to:`),参数里没有 `file_path`。手机
8
+ * 这边凡是「按路径说话」的地方(步骤摘要、审批卡的类别键)都得从补丁正文里读,否则那一行
9
+ * 只剩工具名。
10
+ *
11
+ * 规矩:删文件不算产出(点开也没有东西可看),移动只留落点(源文件已经没了)。路径相对会话
12
+ * 工作目录,显示前由调用方自己取最后一段。
13
+ */
14
+
15
+ /** 补丁头里那三种会留下文件的写法;`*** Update File:` 可能跟着 `*** Move to:` 改落点。 */
16
+ const FILE_HEADER = /^\*\*\* (?:Add|Update) File:\s*(.+)$/;
17
+ const MOVE_HEADER = /^\*\*\* Move to:\s*(.+)$/;
18
+
19
+ /**
20
+ * @param {unknown} patch 补丁正文(`apply_patch` 的 `input`)。
21
+ * @returns {string[]} 去重后的路径,按补丁里的出现顺序。
22
+ */
23
+ function patchFilePaths(patch) {
24
+ if (typeof patch !== 'string' || patch === '') return [];
25
+ const out = [];
26
+ /** 上一行落下的是不是「可能被 Move to 改掉的更新目标」。 */
27
+ let movable = false;
28
+ for (const raw of patch.split(/\r?\n/)) {
29
+ const line = raw.trim();
30
+ const file = FILE_HEADER.exec(line);
31
+ if (file) {
32
+ out.push(file[1].trim());
33
+ movable = line.startsWith('*** Update');
34
+ continue;
35
+ }
36
+ const move = MOVE_HEADER.exec(line);
37
+ if (move) {
38
+ if (movable && out.length > 0) out.pop();
39
+ out.push(move[1].trim());
40
+ movable = false;
41
+ }
42
+ }
43
+ return [...new Set(out.filter(Boolean))];
44
+ }
45
+
46
+ module.exports = { patchFilePaths };
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  const { toolResultState } = require('./tool-result-state.js');
13
+ const { patchFilePaths } = require('./patch-files.js');
13
14
 
14
15
  /** 一步摘要的字数上限:清单是一行省略,再长也看不见,白白占线路。 */
15
16
  const STEP_SUMMARY_MAX = 72;
@@ -96,6 +97,12 @@ function toolStepSummary(name, rawArgs) {
96
97
  case 'read':
97
98
  case 'read_image':
98
99
  return clampSummary(firstStringArg(args, ['file_path', 'path']) || firstStringArg(args, ['description']));
100
+ case 'apply_patch': {
101
+ // 参数里没有单个路径:一次能改好几个文件,路径在补丁头里。摘要取前三份,多了说个数。
102
+ const paths = patchFilePaths(firstStringArg(args, ['input', 'patch']));
103
+ if (paths.length === 0) return clampSummary(firstStringArg(args, ['description']));
104
+ return clampSummary(paths.length <= 3 ? paths.join('、') : `${paths.slice(0, 3).join('、')} 等 ${paths.length} 个`);
105
+ }
99
106
  case 'grep':
100
107
  case 'glob':
101
108
  return clampSummary(firstStringArg(args, ['pattern', 'query']) || firstStringArg(args, ['path']));
@@ -7,6 +7,7 @@ function createRoutePolicy() {
7
7
  exports.advanceRouteEvidenceRound = advanceRouteEvidenceRound;
8
8
  exports.noteRouteLatency = noteRouteLatency;
9
9
  exports.noteRouteFailure = noteRouteFailure;
10
+ exports.noteStreamDrop = noteStreamDrop;
10
11
  exports.noteRouteProven = noteRouteProven;
11
12
  exports.noteRouteVerified = noteRouteVerified;
12
13
  exports.noteRouteForeign = noteRouteForeign;
@@ -26,6 +27,9 @@ function createRoutePolicy() {
26
27
  const SETTLE_ROUNDS = 4;
27
28
  const FAMILY_FAILURE_TRIGGER = 2;
28
29
  const FAMILY_COOL_ROUNDS = 4;
30
+ const STREAM_DROP_STEP = 1.5;
31
+ const STREAM_DROP_MAX = 3;
32
+ const STREAM_DROP_DECAY_ROUNDS = 6;
29
33
  const factsByScope = new Map();
30
34
  function factsOf(scope) {
31
35
  let facts = factsByScope.get(scope);
@@ -33,7 +37,7 @@ function createRoutePolicy() {
33
37
  facts = {
34
38
  latency: new Map(), samples: new Map(), lossPenalty: new Map(), failurePenalty: new Map(),
35
39
  foreign: new Set(), evidenceAtRound: new Map(), evidenceRound: 0, staleRounds: 2, lastSwitch: null,
36
- familyFails: new Map(),
40
+ familyFails: new Map(), streamDrops: new Map(),
37
41
  };
38
42
  factsByScope.set(scope, facts);
39
43
  }
@@ -72,6 +76,10 @@ function createRoutePolicy() {
72
76
  if (facts.evidenceRound - entry.atRound > FAMILY_COOL_ROUNDS)
73
77
  facts.familyFails.delete(family);
74
78
  }
79
+ for (const [key, entry] of facts.streamDrops) {
80
+ if (facts.evidenceRound - entry.atRound > STREAM_DROP_DECAY_ROUNDS)
81
+ facts.streamDrops.delete(key);
82
+ }
75
83
  if (facts.lastSwitch && facts.evidenceRound - facts.lastSwitch.round > SETTLE_ROUNDS)
76
84
  facts.lastSwitch = null;
77
85
  }
@@ -112,6 +120,15 @@ function createRoutePolicy() {
112
120
  facts.familyFails.set(family, entry);
113
121
  }
114
122
  }
123
+ function noteStreamDrop(url, scope = '') {
124
+ const key = norm(url);
125
+ if (!key)
126
+ return;
127
+ const facts = factsOf(scope);
128
+ const prev = facts.streamDrops.get(key);
129
+ const penalty = Math.min(STREAM_DROP_MAX, (prev?.penalty ?? 1) * STREAM_DROP_STEP);
130
+ facts.streamDrops.set(key, { penalty, atRound: facts.evidenceRound });
131
+ }
115
132
  function noteRouteProven(url, scope = '') {
116
133
  const key = norm(url);
117
134
  if (!key)
@@ -143,7 +160,9 @@ function createRoutePolicy() {
143
160
  return facts && isFresh(facts, key) ? facts.latency.get(key) ?? null : null;
144
161
  }
145
162
  function penaltyFor(facts, key) {
146
- return (facts.lossPenalty.get(key) ?? 1) * (facts.failurePenalty.get(key) ?? 1);
163
+ return (facts.lossPenalty.get(key) ?? 1)
164
+ * (facts.failurePenalty.get(key) ?? 1)
165
+ * (facts.streamDrops.get(key)?.penalty ?? 1);
147
166
  }
148
167
  function routeCostOf(url, scope = '') {
149
168
  const facts = factsByScope.get(scope);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.136",
3
+ "version": "0.5.137",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",
@@ -117,23 +117,23 @@
117
117
  "yaml": "2.9.1"
118
118
  },
119
119
  "dshMobileReleaseNotes": {
120
- "version": "0.5.136",
120
+ "version": "0.5.137",
121
121
  "kinds": [
122
122
  "feature",
123
123
  "fix"
124
124
  ],
125
125
  "notes": {
126
- "zh-Hans": "- 零讯(ZeroNews)客户端会自动升级到新版:新版先下载好,等没人连着手机时再换上,全程不用你自己装。\n- 旧隧道指向旧端口时,插件会自动把它改到当前端口,不用再去控制台删掉重建,域名不会变。\n- 「网络 → 服务商」面板直接显示本月流量用量,超出套餐会标出来。\n- 手动关掉的服务商线路不会被自动重新拉起;自建 TCP 线路的配对自检不再报错。\n- 关闭「自动上报网络地址」后,推送不再带着旧令牌发出去。",
127
- "zh-Hant": "- 零訊(ZeroNews)用戶端會自動升級到新版:新版先下載好,等沒人連著手機時再換上,全程不用你自己裝。\n- 舊通道指向舊連接埠時,外掛會自動把它改到目前連接埠,不用再去主控台刪掉重建,網域不會變。\n- 「網路 → 服務商」面板直接顯示本月流量用量,超出方案會標示出來。\n- 手動關掉的服務商線路不會被自動重新拉起;自建 TCP 線路的配對自檢不再報錯。\n- 關閉「自動回報網路位址」後,推播不再帶著舊權杖送出。",
128
- "en": "- The ZeroNews client now upgrades itself: the new build is downloaded ahead of time and swapped in only while no phone is connected, with nothing to install by hand.\n- When an existing tunnel points at an old port, the plugin re-points it for you instead of asking you to delete and recreate it in the console; the domain stays the same.\n- The Network → Providers panel shows this cycle's traffic usage and flags it when you go over your plan.\n- Provider routes you turned off are no longer started automatically, and the pairing self-check no longer errors on self-hosted TCP routes.\n- With automatic address reporting turned off, push notifications no longer go out with a stale token.",
129
- "ja": "- ZeroNews クライアントが自動で新版になります。新版は先にダウンロードし、スマホがつながっていない間に切り替えるので、手動でのインストールは不要です。\n- 既存トンネルが古いポートを指している場合、コンソールで削除・再作成せずに現在のポートへ自動で向け直します(ドメインは変わりません)。\n- 「ネットワーク → プロバイダー」パネルに今月の通信量が表示され、プラン超過も分かります。\n- 手動で停止したプロバイダー回線が自動で起動し直されることはなくなり、自前 TCP 回線のペアリング自己診断もエラーにならなくなりました。\n- 「ネットワークアドレスの自動報告」をオフにすると、古いトークンでプッシュが送られなくなります。",
130
- "ko": "- ZeroNews 클라이언트가 새 버전으로 자동 업그레이드됩니다. 새 버전을 미리 받아 두고 휴대폰이 연결되지 않은 사이에 교체하므로 직접 설치할 필요가 없습니다.\n- 기존 터널이 예전 포트를 가리키면 콘솔에서 삭제·재생성하지 않아도 현재 포트로 자동 변경되며, 도메인은 그대로입니다.\n- '네트워크 → 공급자' 패널에서 이번 달 트래픽 사용량을 바로 볼 수 있고, 요금제 초과도 표시됩니다.\n- 직접 꺼 둔 공급자 회선이 자동으로 다시 켜지지 않으며, 자체 TCP 회선의 페어링 자체 점검도 오류를 내지 않습니다.\n- '네트워크 주소 자동 보고'를 끄면 오래된 토큰으로 푸시가 나가지 않습니다.",
131
- "de": "- Der ZeroNews-Client aktualisiert sich jetzt selbst: Die neue Version wird vorab geladen und erst eingespielt, wenn kein Telefon verbunden ist – keine manuelle Installation.\n- Zeigt ein bestehender Tunnel auf einen alten Port, wird er automatisch auf den aktuellen Port umgestellt, statt ihn in der Konsole zu löschen und neu anzulegen; die Domain bleibt gleich.\n- Das Panel „Netzwerk → Anbieter“ zeigt den Traffic-Verbrauch dieses Monats und markiert Überschreitungen des Tarifs.\n- Manuell gestoppte Anbieter-Routen werden nicht mehr automatisch gestartet, und die Kopplungs-Selbstprüfung eigener TCP-Routen meldet keinen Fehler mehr.\n- Ist die automatische Adressmeldung aus, gehen Push-Nachrichten nicht mehr mit einem alten Token raus.",
132
- "es": "- El cliente de ZeroNews ahora se actualiza solo: la nueva versión se descarga antes y se cambia cuando no hay ningún teléfono conectado, sin instalar nada a mano.\n- Si un túnel apunta a un puerto antiguo, el complemento lo cambia al puerto actual sin borrarlo ni recrearlo en la consola; el dominio no cambia.\n- El panel «Red → Proveedores» muestra el consumo de tráfico del mes y avisa cuando superas tu plan.\n- Las rutas de proveedor que apagaste a mano ya no se vuelven a iniciar solas, y la autocomprobación de las rutas TCP propias ya no da error.\n- Con el informe automático de direcciones desactivado, las notificaciones push ya no se envían con un token antiguo.",
133
- "fr": "- Le client ZeroNews se met à jour tout seul : la nouvelle version est téléchargée à l'avance et installée seulement quand aucun téléphone n'est connecté, sans intervention.\n- Si un tunnel pointe vers un ancien port, le plugin le repointe vers le port actuel au lieu de vous faire supprimer et recréer le tunnel dans la console ; le domaine ne change pas.\n- Le panneau « Réseau → Fournisseurs » affiche la consommation du mois et signale les dépassements de forfait.\n- Les lignes de fournisseur que vous avez coupées ne sont plus relancées automatiquement, et l'auto-test d'appairage des lignes TCP personnelles ne renvoie plus d'erreur.\n- Si le signalement automatique des adresses est désactivé, les notifications push ne partent plus avec un jeton périmé.",
134
- "pt": "- O cliente ZeroNews agora se atualiza sozinho: a nova versão é baixada antes e trocada só quando nenhum telefone está conectado, sem instalação manual.\n- Se um túnel aponta para uma porta antiga, o plugin redireciona para a porta atual em vez de pedir para excluir e recriar no console; o domínio não muda.\n- O painel «Rede → Provedores» mostra o consumo de tráfego do mês e avisa quando você passa do plano.\n- As rotas de provedor que você desligou não são mais iniciadas automaticamente, e a autoverificação de pareamento das rotas TCP próprias não dá mais erro.\n- Com o envio automático de endereços desligado, as notificações push não saem mais com um token antigo.",
135
- "ru": "- Клиент ZeroNews теперь обновляется сам: новая версия скачивается заранее и подменяется, только когда ни один телефон не подключён, — вручную ставить ничего не нужно.\n- Если существующий туннель указывает на старый порт, плагин сам переводит его на текущий порт, а не просит удалять и создавать заново в консоли; домен не меняется.\n- Панель «Сеть → Провайдеры» показывает расход трафика за месяц и отмечает превышение тарифа.\n- Отключённые вручную линии провайдера больше не запускаются сами, а самопроверка сопряжения собственных TCP-линий больше не выдаёт ошибку.\n- Если автоматический отчёт об адресах выключен, push-уведомления больше не отправляются со старым токеном.",
136
- "tr": "- ZeroNews istemcisi artık kendini güncelliyor: yeni sürüm önceden indirilir ve yalnızca hiç telefon bağlı değilken değiştirilir; elle kurmanız gerekmez.\n- Mevcut bir tünel eski bir bağlantı noktasını gösteriyorsa, konsolda silip yeniden oluşturmanız istenmez; tünel geçerli bağlantı noktasına yönlendirilir, alan adı değişmez.\n- \"Ağ → Sağlayıcılar\" paneli bu ayın trafik kullanımını gösterir ve paket aşımını işaretler.\n- Elle kapattığınız sağlayıcı hatları artık kendiliğinden başlatılmaz; kendi TCP hatlarınızın eşleştirme öz-testi de hata vermez.\n- \"Ağ adreslerini otomatik bildir\" kapalıyken push bildirimleri artık eski belirteçle gönderilmez."
126
+ "zh-Hans": "- 电脑端装上新版 DSH 后,模型一次改好几个文件时,过程清单会写清改的是哪些文件,审批卡也会说出改哪份,不再只剩一个工具名。\n- 对话里提到的文件,只要这一轮改过就仍然可以点开查看;新版默认的多文件改写方式也不会漏掉这些文件。",
127
+ "zh-Hant": "- 電腦端裝上新版 DSH 後,模型一次改好幾個檔案時,過程清單會寫清楚改的是哪些檔案,審批卡也會說出改哪一份,不再只剩一個工具名稱。\n- 對話裡提到的檔案,只要這一輪改過就仍然可以點開查看;新版預設的多檔案改寫方式也不會漏掉這些檔案。",
128
+ "en": "- With the new DSH release on your computer, when the model edits several files in one step the step list names those files and the approval card says which file it touches, instead of showing only a tool name.\n- Files mentioned in a reply stay tappable when they changed in that turn, including files edited through the new multi-file editing mode that DSH now uses by default.",
129
+ "ja": "- パソコン側の DSH を新しい版にすると、モデルが一度に複数のファイルを編集するときも、手順リストにどのファイルを編集しているかが出て、承認カードでも編集するファイルが分かります。ツール名だけの表示にはなりません。\n- 返信内で触れたファイルは、そのターンで変更されていれば引き続きタップして開けます。新しい DSH が既定で使う複数ファイル編集でも取りこぼしません。",
130
+ "ko": "- 컴퓨터의 DSH를 새 버전으로 올리면 모델이 한 번에 여러 파일을 고칠 때도 단계 목록에 어떤 파일을 고치는지 표시되고, 승인 카드에서도 어떤 파일인지 알 수 있습니다. 이제 도구 이름만 남지 않습니다.\n- 답변에서 언급한 파일은 그 턴에 변경되었다면 계속 눌러서 열 수 있습니다. 새 DSH가 기본으로 쓰는 여러 파일 편집 방식에서도 빠지지 않습니다.",
131
+ "de": "- Mit der neuen DSH-Version auf dem Rechner nennt die Schrittliste beim Bearbeiten mehrerer Dateien die betroffenen Dateien, und die Freigabekarte sagt, welche Datei geändert wird – statt nur eines Toolnamens.\n- In einer Antwort erwähnte Dateien bleiben antippbar, wenn sie in diesem Durchgang geändert wurden – auch bei der neuen Mehrfachbearbeitung, die DSH jetzt standardmäßig nutzt.",
132
+ "es": "- Con la nueva versión de DSH en el ordenador, cuando el modelo edita varios archivos de una vez la lista de pasos indica cuáles son y la tarjeta de aprobación dice qué archivo se toca, en lugar de mostrar solo el nombre de la herramienta.\n- Los archivos mencionados en una respuesta siguen siendo pulsables si cambiaron en ese turno, incluidos los editados con el nuevo modo de edición múltiple que DSH usa ahora por defecto.",
133
+ "fr": "- Avec la nouvelle version de DSH sur l'ordinateur, quand le modèle modifie plusieurs fichiers d'un coup, la liste des étapes indique lesquels et la carte d'approbation précise le fichier concerné, au lieu d'afficher seulement le nom de l'outil.\n- Les fichiers cités dans une réponse restent cliquables s'ils ont changé pendant ce tour, y compris ceux modifiés par le nouveau mode d'édition multiple que DSH utilise désormais par défaut.",
134
+ "pt": "- Com a nova versão do DSH no computador, quando o modelo edita vários arquivos de uma vez a lista de etapas mostra quais são e o cartão de aprovação diz qual arquivo será alterado, em vez de exibir só o nome da ferramenta.\n- Os arquivos citados numa resposta continuam tocáveis quando mudaram nesse turno, inclusive os editados pelo novo modo de edição múltipla que o DSH agora usa por padrão.",
135
+ "ru": "- С новой версией DSH на компьютере, когда модель правит несколько файлов за раз, в списке шагов видно, какие это файлы, а карточка подтверждения называет изменяемый файл, а не только имя инструмента.\n- Файлы, упомянутые в ответе, по-прежнему открываются нажатием, если они менялись в этом ходе, включая правки через новый режим множественного редактирования, который DSH теперь использует по умолчанию.",
136
+ "tr": "- Bilgisayardaki DSH yeni sürüme güncellendiğinde, model bir seferde birden çok dosyayı düzenlese bile adım listesi hangi dosyaların değiştiğini gösterir, onay kartı da hangi dosyanın değişeceğini söyler; artık yalnızca araç adı görünmez.\n- Yanıtta geçen dosyalar, o turda değiştiyse yine dokunarak açılabilir; DSH'nin artık varsayılan olarak kullandığı çoklu dosya düzenleme yöntemiyle yapılan değişiklikler de atlanmaz."
137
137
  }
138
138
  }
139
139
  }