Browse Source

feat-a1-a1-5-memory-state-two-layer

master
Serge Shutov 2 weeks ago
parent
commit
240cebec3e
  1. 3
      bridge/config.json
  2. 13
      bridge/guard.js
  3. 42
      bridge/server.js
  4. 3
      content/content.js
  5. 4
      content/panel.js
  6. 20
      content/storage-bridge.js
  7. 3
      manifest.json
  8. 6
      memory/state.json

3
bridge/config.json

@ -8,5 +8,6 @@ @@ -8,5 +8,6 @@
"bashTimeoutMaxMs": 120000,
"handoffTimeoutMs": 300000,
"handoffTimeoutMaxMs": 1800000,
"dailySendLimit": 100000
"dailySendLimit": 100000,
"memoryDir": "memory"
}

13
bridge/guard.js

@ -214,6 +214,18 @@ function validatePath(config, workspace, relPath, forWrite) { @@ -214,6 +214,18 @@ function validatePath(config, workspace, relPath, forWrite) {
}
/** 确保路径字符串打码(审计日志用):64 位 hex、sk- 开头的串。 */
function resolveMemoryDir(config, bridgeDir) {
const rel = String(config.memoryDir || 'memory').trim();
if (!rel) throw new ToolError('E_FORBIDDEN_PATH', 'memoryDir empty');
if (path.isAbsolute(rel)) throw new ToolError('E_FORBIDDEN_PATH', 'memoryDir relative only');
const projectRoot = path.dirname(bridgeDir);
const abs = path.resolve(projectRoot, rel);
const rc = path.relative(projectRoot, abs);
if (rc.startsWith('..')) throw new ToolError('E_FORBIDDEN_PATH', 'memoryDir outside project root');
if (path.isAbsolute(rc)) throw new ToolError('E_FORBIDDEN_PATH', 'memoryDir outside project root');
return abs;
}
function redact(text) {
if (typeof text !== 'string') return text;
return text
@ -226,6 +238,7 @@ module.exports = { @@ -226,6 +238,7 @@ module.exports = {
ToolError,
loadConfig,
resolveWorkspace,
resolveMemoryDir,
validatePath,
looksBinaryByExt,
sniffBinary,

42
bridge/server.js

@ -9,7 +9,7 @@ const http = require('http'); @@ -9,7 +9,7 @@ const http = require('http');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { loadConfig, ToolError, redact, resolveWorkspace } = require('./guard');
const { loadConfig, ToolError, redact, resolveWorkspace, resolveMemoryDir } = require('./guard');
const { TOOL_DEFS, runTool } = require('./tools');
const { HandoffManager, dshProbe } = require('./handoff');
@ -73,7 +73,7 @@ function sendJson(res, status, obj) { @@ -73,7 +73,7 @@ function sendJson(res, status, obj) {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': 'http://127.0.0.1:8766',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
});
res.end(body);
}
@ -129,7 +129,9 @@ async function handle(req, res, pathname, body) { @@ -129,7 +129,9 @@ async function handle(req, res, pathname, body) {
return {
ok: true,
name: 'dsh-memory',
version: '0.3.0',
version: '0.3.1',
workspace: config.allowedRoots[0],
memoryDir: resolveMemoryDir(config, BRIDGE_DIR),
allowedRoots: config.allowedRoots,
dsh: { binFound: probe.binFound, bin: probe.bin, nodeSource: probe.node ? probe.node.source : null },
};
@ -193,6 +195,36 @@ async function handle(req, res, pathname, body) { @@ -193,6 +195,36 @@ async function handle(req, res, pathname, body) {
audit({ op: 'handoff-start', workspace: workspace || config.allowedRoots[0], runId: r.runId, planMs: Date.now() - started });
return { ok: true, ...r };
}
case '/memory/state': {
const memDir = resolveMemoryDir(config, BRIDGE_DIR);
const stateFile = path.join(memDir, 'state.json');
if (req.method === 'GET') {
let content = null;
try { content = fs.readFileSync(stateFile, 'utf8'); }
catch (e) { if (e.code !== 'ENOENT') throw e; }
if (content === null) {
return { ok: true, data: { version: 1, updatedAt: new Date().toISOString(), memories: {}, skills: [] } };
}
try { return { ok: true, data: JSON.parse(content) }; }
catch { throw new ToolError('E_INTERNAL', 'invalid JSON'); }
}
if (req.method === 'PUT') {
const b = body || {};
const memOk = b.memories && typeof b.memories === 'object' && !Array.isArray(b.memories);
const next = {
version: 1,
updatedAt: new Date().toISOString(),
memories: memOk ? b.memories : {},
skills: Array.isArray(b.skills) ? b.skills : [],
};
fs.mkdirSync(memDir, { recursive: true });
const tmp = stateFile + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf8');
fs.renameSync(tmp, stateFile);
return { ok: true, data: next };
}
throw new ToolError('E_ARGS_INVALID', 'GET or PUT only');
}
default:
// /handoff/:runId 与 /handoff/:runId/cancel
const m = pathname.match(/^\/handoff\/([A-Za-z0-9-]+)(\/cancel)?$/);
@ -229,7 +261,7 @@ const server = http.createServer(async (req, res) => { @@ -229,7 +261,7 @@ const server = http.createServer(async (req, res) => {
res.writeHead(204, {
'Access-Control-Allow-Origin': 'http://127.0.0.1:8766',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
});
res.end();
return;
@ -246,7 +278,7 @@ const server = http.createServer(async (req, res) => { @@ -246,7 +278,7 @@ const server = http.createServer(async (req, res) => {
throw new ToolError('E_UNAUTHORIZED', 'invalid or missing bearer token');
}
let body = null;
if (req.method === 'POST') {
if (req.method === 'POST' || req.method === 'PUT') {
const raw = await readBody(req, 10 * 1024 * 1024);
if (raw.trim()) {
try {

3
content/content.js

@ -292,7 +292,8 @@ @@ -292,7 +292,8 @@
characterData: true
});
console.log("[dsh-memory] content.js active");
if (UI) { UI.setPhase('idle'); UI.setConnected(true); canStart = true; UI.log('active'); }
if (UI) { UI.setPhase('idle'); UI.setConnected(true); canStart = true; UI.log('active'); } __refreshStats();
});
});
function __refreshStats() { try { var SB = globalThis.STORAGE_BRIDGE; if (!SB || !UI || !UI.setStats) return; SB.getState().then(function (st) { var mN = st && st.memories ? Object.keys(st.memories).length : 0; var sN = st && st.skills && st.skills.length ? st.skills.length : 0; return SB.authHeaders().then(function (h) { return fetch(SB.BU + '/health', { headers: h }); }).then(function (r) { return r.json(); }).then(function (j) { UI.setStats((j && j.workspace) || '?', mN, sN); }); }).catch(function () { UI.setStats('?', 0, 0); }); } catch (e) { console.warn('[dsh-memory] stats ' + String(e)); } }
})();

4
content/panel.js

@ -35,7 +35,7 @@ @@ -35,7 +35,7 @@
el.start = mk('button', 'dshmem-btn primary', 'Start'); el.reset = mk('button', 'dshmem-btn', 'Reset queue');
el.stop = mk('button', 'dshmem-btn danger', 'Stop');
row1.appendChild(el.start); row1.appendChild(el.reset); row1.appendChild(el.stop);
el.body.appendChild(row1);
el.body.appendChild(row1); el.stats = mk('div','dshmem-stats'); el.stats.id='dshmem-stats'; el.body.appendChild(el.stats);
var set = mk('div', 'dshmem-settings');
var lbl = mk('div', 'dshmem-label', 'Token (save, then reload page)');
el.token = mk('input', 'dshmem-input');
@ -75,7 +75,7 @@ @@ -75,7 +75,7 @@
var API = {
setPhase: function (p) { state.phase = p; if (el.phase) el.phase.textContent = p; },
setConnected: function (b) { state.connected = !!b; if (el.dot) el.dot.className = 'dshmem-dot ' + (b ? 'ok' : 'err'); },
setStartEnabled: function (b) { if (el.start) el.start.disabled = !b; },
setStartEnabled: function (b) { if (el.start) el.start.disabled = !b; }, setStats: function (ws, memN, skillN) { if (!el.stats) return; el.stats.textContent = 'WS: ' + (ws || '?') + ' mem: ' + (memN || 0) + ' skills: ' + (skillN || 0); },
log: function (m) {
if (!el.log) return;
var t = new Date().toLocaleTimeString();

20
content/storage-bridge.js

@ -0,0 +1,20 @@ @@ -0,0 +1,20 @@
// storage-bridge.js - двухслойный клиент памяти dsh-memory
var LK="dsm_state",TK="dshmem-bridge-token",BU="http://127.0.0.1:8766";
function empty() {return {version:1,updatedAt:new Date().toISOString(),memories:{},skills:[]};}
function loadLocal() {return new Promise(function(res){chrome.storage.local.get([LK],function(o){res(o[LK] || empty())})})};
function saveLocal(s) {return new Promise(function(res){chrome.storage.local.set({dsm_state:s},function(){res(true)})})};
function authHeaders() {return new Promise(function(res){chrome.storage.local.get([TK],function(o){var h={};h["Content-Type"]="application/json";if(o[TK])h.Authorization="Bearer "+o[TK];res(h)})})};
function fetchRemote() {return authHeaders().then(function(h){return fetch(BU+"/"+"memory/state",{method:"GET",headers:h})}).then(function(r){if(!r.ok)throw new Error("GET "+r.status);return r.json()}).then(function(j){if(!j||!j.ok)throw new Error("bad payload");return j.data||empty()})};
function putRemote(s) {return authHeaders().then(function(h){return fetch(BU+"/"+"memory/state",{method:"PUT",headers:h,body:JSON.stringify(s)})}).then(function(r){if(!r.ok)throw new Error("PUT "+r.status);return r.json()}).then(function(j){return j&&j.ok})};
function newer(a,b) {return (a&&a.updatedAt?a.updatedAt:"") >= (b&&b.updatedAt?b.updatedAt:"")};
function sync() {return Promise.all([loadLocal(),fetchRemote().catch(function(){return null})]).then(function(arr){var loc=arr[0],rem=arr[1];if(!rem)return loc;if(newer(loc,rem)){putRemote(loc).catch(function(){});return loc};return saveLocal(rem).then(function(){return rem})})};
function getState() {return sync()};
function putState(s) {var v={version:1,updatedAt:new Date().toISOString(),memories:s.memories||{},skills:s.skills||[]};return saveLocal(v).then(function(){return putRemote(v).catch(function(){return false})}).then(function(){return v})};
var API={empty:empty,loadLocal:loadLocal,saveLocal:saveLocal,authHeaders:authHeaders,fetchRemote:fetchRemote,putRemote:putRemote,sync:sync,getState:getState,putState:putState,LK:LK,TK:TK,BU:BU};
if(typeof module!=="undefined"&&module.exports){module.exports=API};
if(typeof globalThis!=="undefined"){globalThis.STORAGE_BRIDGE=API};

3
manifest.json

@ -23,7 +23,8 @@ @@ -23,7 +23,8 @@
"js": [
"content/selectors.js",
"content/parser.js",
"content/bridge-client.js",
"content/storage-bridge.js",
"content/bridge-client.js",
"content/panel.js",
"content/content.js"
],

6
memory/state.json

@ -0,0 +1,6 @@ @@ -0,0 +1,6 @@
{
"version": 1,
"updatedAt": "2026-10-31T02:11:46.453Z",
"memories": {},
"skills": []
}
Loading…
Cancel
Save