diff --git a/README.md b/README.md index 5277d8d..b8f89ed 100644 --- a/README.md +++ b/README.md @@ -326,12 +326,13 @@ dsh-memory/ | Команда | Что делает | Подтверждение | |---|---|---| -| dsh_tree | Дерево папки в workspace | нет | -| dsh_read | Прочитать текстовый файл. Прямо до 512 КБ, с offset/limit до 2 МБ | нет | -| dsh_write | Записать файл целиком (создаёт папки). До 2 МБ | нет, кроме .env, package.json и lock-файлов | +| dsh_tree | Дерево папки в workspace. `ifMoreThan` — если записей больше, вернуть мету без дерева | нет | +| dsh_read | Прочитать текстовый файл. Прямо до 512 КБ, с offset/limit до 2 МБ. `maxBytes` — если файл больше, вернуть мету без content | нет | +| dsh_write | Записать файл (создаёт папки). До 2 МБ. `mode`: overwrite (дефолт) / create (fail если есть) / append | нет, кроме .env, package.json и lock-файлов | | dsh_edit | Заменить уникальный фрагмент в файле | нет, кроме тех же | -| dsh_search | Найти подстроку или regex в файлах | нет | +| dsh_search | Найти подстроку или regex в файлах. `ifMoreThan` — если совпадений больше, вернуть мету без matches | нет | | dsh_bash | Выполнить команду в консоли | да, если команда вне whitelist | +| dsh_script | Именованный python/mjs скрипт с declared inputs/outputs. Заменяет write→bash→read | да, всегда (по типу+имени, без кода) | | dsh_git_status | git status | нет | | dsh_git_diff | git diff | нет | | dsh_log | Прочитать последние записи лога вызовов | нет | @@ -477,7 +478,8 @@ Policy: destructive, shell - Работает с любым юникодом, многострочным текстом, фигурными скобками, кавычками, обратными слешами, доменами и URL без искажений - Многострочный oldText в dsh_edit работает - Не нужны обходы через .mjs и String.fromCharCode, можно писать напрямую -- Лимит 10 вызовов в одном сообщении +- Число вызовов в одном сообщении не ограничено: парсер читает все маркеры до конца текста +- Пакетный формат с политикой ошибок (см. ниже) **Минусы:** - Зависит от формата SSE-событий, который DeepSeek может поменять в любой момент diff --git a/content/content.js b/content/content.js index a72d63e..0c43107 100644 --- a/content/content.js +++ b/content/content.js @@ -61,7 +61,7 @@ if (pid.length === 0) return; if (pid === lastSsePid) { __uiLog('sse dup skipped ' + pid); return; } lastSsePid = pid; - var parsed = extractCalls(d.text, 10); + var parsed = extractCalls(d.text, 0); try { var __callSum = []; if (parsed ? (parsed.calls ? true : false) : false) { for (var __ci = 0; __ci < parsed.calls.length; __ci++) { var __c = parsed.calls[__ci]; __callSum.push({ i: __ci, tool: (__c ? String(__c.tool) : 'null'), hasArgs: (__c ? (__c.args ? true : false) : false), argsPreview: (__c ? String(JSON.stringify(__c.args || {})).slice(0, 400) : '') }) } } __debugReport({ ev: 'sse-parse', ts: Date.now(), pid: pid, execSource: execMode, consumed: (parsed ? parsed.consumed : -1), textLen: d.text.length, calls: __callSum, parsedCount: (parsed ? parsed.calls.length : 0), text: String(d.text).slice(0, 2000) }) } catch (e7) { } if (parsed ? (parsed.calls ? (parsed.calls.length > 0) : false) : false) { var validCount = 0; @@ -77,8 +77,8 @@ } if (validCount === 0) { if (UI) UI.setPhase('idle'); return; } if (UI) { if (UI.setDot) UI.setDot('ok-busy'); UI.setPhase('executing'); } - __uiLog('sse exec ' + parsed.calls.length + ' pid ' + pid); - pump(); + __uiLog('sse exec ' + parsed.calls.length + ' pid ' + pid + ' on_error ' + ((parsed.policy && parsed.policy.on_error) || 'continue')); + pump(parsed.policy); } } catch (e) { console.warn('[dsh-memory] sse-answer error', String(e)); } }); @@ -241,7 +241,7 @@ processed.add(m); continue; } - var hasMarker = text.indexOf(String.fromCharCode(10214)) !== -1 || text.indexOf('[DSH') !== -1; if (hasMarker && UI && UI.setDot) UI.setDot('busy'); var parsed = extractCalls(text, 10); + var hasMarker = text.indexOf(String.fromCharCode(10214)) !== -1 || text.indexOf('[DSH') !== -1; if (hasMarker && UI && UI.setDot) UI.setDot('busy'); var parsed = extractCalls(text, 0); if (!parsed) continue; if (!parsed.calls) continue; if (parsed.calls.length === 0) { if (hasMarker) { try { var __dh = hashText(text); if (!domDebugSeen.has(__dh) && domDebugCount < 3) { domDebugSeen.add(__dh); domDebugCount = domDebugCount + 1; __debugReport({ ev: 'dom-parse-fail', ts: Date.now(), execSource: execMode, textLen: text.length, msgText: String(text).slice(0, 2000) }) } } catch (e9) { } } continue; } @@ -253,7 +253,7 @@ if (parsed.calls.length === 0) { if (hasMarker) { try { var __dh = hashText(text for (k = 0; k < parsed.calls.length; k++) { var __dc = parsed.calls[k]; if (__dc && __dc.tool === 'invalid') { try { __debugReport({ ev: 'sse-exec-result', ts: Date.now(), pid: lastSsePid, execSource: execMode, tool: 'invalid', ok: false, errorCode: 'E_PARSE_INVALID', errorMsg: String((__dc.args && __dc.args._reason) || '') }) } catch (e) { } continue; } queue.push(__dc); } if (UI && UI.setDot) UI.setDot('ok-busy'); if (UI) UI.setPhase('executing'); } - pump(); + pump(parsed.policy); } function executeOne(call) { return BRIDGE.sendCall(call).then(function (res) { @@ -266,11 +266,19 @@ if (parsed.calls.length === 0) { if (hasMarker) { try { var __dh = hashText(text return res; }); } - function pump() { + var MUTATING_TOOLS = { dsh_write: 1, dsh_edit: 1, dsh_script: 1, dsh_bash: 1 }; + function pump(policy) { if (pumping) return; if (queue.length === 0) return; pumping = true; + var onError = (policy && policy.on_error) ? String(policy.on_error) : 'continue'; + var stopAll = false; + var failedTools = {}; + var failedMutating = false; var results = []; + var skipResult = function (call, reason) { + return { ok: false, skipped: true, error: { code: 'E_SKIPPED', message: reason }, tool: call.tool }; + }; var step = function () { if (queue.length === 0) { pumping = false; @@ -282,6 +290,9 @@ if (parsed.calls.length === 0) { if (hasMarker) { try { var __dh = hashText(text return; } var call = queue.shift(); + if (stopAll) { results.push(skipResult(call, 'on_error=stop: previous call failed')); return step(); } + if (onError === 'skip_same_tool' && failedTools[call.tool]) { results.push(skipResult(call, 'on_error=skip_same_tool')); return step(); } + if (onError === 'skip_mutating' && failedMutating && MUTATING_TOOLS[call.tool]) { results.push(skipResult(call, 'on_error=skip_mutating')); return step(); } executeOne(call).then(function (res) { try { __debugReport({ ev: 'sse-exec-result', ts: Date.now(), pid: lastSsePid, execSource: execMode, tool: (call ? String(call.tool) : 'null'), ok: (res ? (res.ok ? true : false) : false), errorCode: (res ? (res.error ? String(res.error.code || '') : '') : 'nores'), errorMsg: (res ? (res.error ? String(res.error.message || '').slice(0, 300) : '') : '') }) } catch (e8) { } if (res) { @@ -297,6 +308,7 @@ if (parsed.calls.length === 0) { if (hasMarker) { try { var __dh = hashText(text console.warn('[dsh-memory] call failed (no res)', call.tool); if (UI) UI.log('fail ' + call.tool + ' ' + JSON.stringify((res && res.error) || 'nores')); } + if (!res || !res.ok) { if (onError === 'stop') stopAll = true; if (onError === 'skip_same_tool') failedTools[call.tool] = true; if (onError === 'skip_mutating' && MUTATING_TOOLS[call.tool]) failedMutating = true; } }).catch(function (err) { console.warn('[dsh-memory] call throw', call.tool, String(err)); }).then(step); }; step(); diff --git a/content/parser.js b/content/parser.js index 52a8de9..16bf66d 100644 --- a/content/parser.js +++ b/content/parser.js @@ -75,25 +75,40 @@ function parseOne(text, startIdx) { const raw = text.slice(startIdx + OPEN_DSH.length, closeIdx); const obj = tryParseJson(raw); if (!obj || typeof obj !== 'object') return makeInvalid('json_parse_failed', raw, closeIdx, CLOSE_DSH.length); - if (!obj.tool) return makeInvalid('no_tool_field', raw, closeIdx, CLOSE_DSH.length); + if (!obj.tool && !Array.isArray(obj.batch)) return makeInvalid('no_tool_field', raw, closeIdx, CLOSE_DSH.length); return { call: obj, nextIdx: closeIdx + CLOSE_DSH.length }; } return null; } +// extractCalls(text, maxCalls): maxCalls <= 0 or null -> no limit (read until end). +// Batch format: {"batch":[{tool,args},...],"policy":{...}} expands into multiple calls. +// Legacy format: {tool,args} works as before. +// Returned policy is the first non-empty policy among batches (one policy per answer is expected). function extractCalls(text, maxCalls) { - const limit = Math.max(1, maxCalls | 0) || 3; + const limit = (maxCalls | 0) > 0 ? (maxCalls | 0) : Infinity; const calls = []; + let policy = null; let pos = 0; while (calls.length < limit) { const i = text.indexOf(L, pos); if (i < 0) break; const parsed = parseOne(text, i); if (!parsed) { pos = i + L.length; continue; } - calls.push(parsed.call); + const c = parsed.call; + if (c && Array.isArray(c.batch)) { + if (!policy && c.policy && typeof c.policy === 'object') policy = c.policy; + for (let k = 0; k < c.batch.length && calls.length < limit; k++) { + const item = c.batch[k]; + if (item && typeof item === 'object' && item.tool) calls.push(item); + else calls.push({ tool: 'invalid', args: { _reason: 'batch_item_no_tool', _raw: JSON.stringify(item || {}).slice(0, 200) } }); + } + } else { + calls.push(c); + } pos = parsed.nextIdx; } - return { calls: calls, consumed: pos }; + return { calls: calls, consumed: pos, policy: policy }; } function parseChatText(root) { @@ -112,7 +127,7 @@ function parseChatText(root) { if (texts.length > 0) break; } const joined = texts.join('\n'); - return extractCalls(joined, 10); + return extractCalls(joined, 0); } if (typeof module !== 'undefined' && module.exports) { module.exports = { diff --git a/test/parser.test.mjs b/test/parser.test.mjs index 4e32211..643b979 100644 --- a/test/parser.test.mjs +++ b/test/parser.test.mjs @@ -39,5 +39,23 @@ ok('FILE path', !!r3.calls[0] ? r3.calls[0].args.path === 't.php' : false); ok('FILE tool', !!r3.calls[0] ? r3.calls[0].tool === 'dsh_write' : false); ok('FILE content', !!r3.calls[0] ? r3.calls[0].args.content.indexOf('namespace app' + BS + 'models') !== -1 : false); +// Test 4: batch format expands into multiple calls with policy +const b1 = L + 'DSH' + R + LB + Q + 'batch' + Q + ':[' + LB + Q + 'tool' + Q + ':' + Q + 'dsh_read' + Q + ',' + Q + 'args' + Q + ':' + LB + Q + 'path' + Q + ':' + Q + 'a.txt' + Q + RB + RB + ',' + LB + Q + 'tool' + Q + ':' + Q + 'dsh_read' + Q + ',' + Q + 'args' + Q + ':' + LB + Q + 'path' + Q + ':' + Q + 'b.txt' + Q + RB + RB + '],' + Q + 'policy' + Q + ':' + LB + Q + 'on_error' + Q + ':' + Q + 'stop' + Q + RB + RB + L + '/DSH' + R; +const r4 = parser.extractCalls(b1, 0); +ok('batch count', r4.calls.length === 2); +ok('batch policy', !!r4.policy ? r4.policy.on_error === 'stop' : false); +ok('batch path1', !!r4.calls[0] ? r4.calls[0].args.path === 'a.txt' : false); +ok('batch path2', !!r4.calls[1] ? r4.calls[1].args.path === 'b.txt' : false); + +// Test 5: maxCalls=0 means no limit +let many = ''; +for (let i = 0; i < 20; i++) { many += L + 'DSH' + R + LB + Q + 'tool' + Q + ':' + Q + 'dsh_read' + Q + ',' + Q + 'args' + Q + ':' + LB + Q + 'path' + Q + ':' + Q + 'f' + i + '.txt' + Q + RB + RB + L + '/DSH' + R; } +const r5 = parser.extractCalls(many, 0); +ok('no limit count', r5.calls.length === 20); + +// Test 6: maxCalls=5 still works (backward compat) +const r6 = parser.extractCalls(many, 5); +ok('limit 5 count', r6.calls.length === 5); + console.log('passed ' + pass + ', failed ' + fail); if (fail > 0) process.exit(1);