mlai-code 0.0.0-stage → 0.3.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.md +12 -2
- package/bin/mlai.mjs +3 -0
- package/package.json +18 -3
- package/src/browser-setup.mjs +77 -0
- package/src/cli-ext.mjs +146 -0
- package/src/cli.mjs +534 -0
- package/src/cloud.mjs +29 -0
- package/src/completion.mjs +159 -0
- package/src/credentials.mjs +54 -0
- package/src/deploy.mjs +134 -0
- package/src/distribution.mjs +373 -0
- package/src/engine-key.mjs +4 -0
- package/src/engine.mjs +167 -0
- package/src/headless.mjs +196 -0
- package/src/home.mjs +22 -0
- package/src/host.mjs +123 -0
- package/src/local-models.mjs +64 -0
- package/src/modes.mjs +38 -0
- package/src/netbox.mjs +97 -0
- package/src/netjail.py +59 -0
- package/src/offline.mjs +98 -0
- package/src/parity.mjs +86 -0
- package/src/project.mjs +68 -0
- package/src/relay.mjs +140 -0
- package/src/render.mjs +73 -0
- package/src/restricted.mjs +47 -0
- package/src/review.mjs +70 -0
- package/src/runner.mjs +127 -0
- package/src/runtime.mjs +75 -0
- package/src/sandbox.mjs +135 -0
- package/src/sdk.mjs +11 -0
- package/src/server.mjs +110 -0
- package/src/session.mjs +290 -0
- package/src/settings.mjs +135 -0
- package/src/shared-data.mjs +3 -0
- package/src/tui/acp.mjs +145 -0
- package/src/tui/agents-cli.mjs +114 -0
- package/src/tui/agents-local.mjs +65 -0
- package/src/tui/ansi.mjs +123 -0
- package/src/tui/app.mjs +710 -0
- package/src/tui/approval.mjs +88 -0
- package/src/tui/bg.mjs +172 -0
- package/src/tui/bgterm.mjs +79 -0
- package/src/tui/chat.mjs +230 -0
- package/src/tui/clipboard.mjs +74 -0
- package/src/tui/cloud-cli.mjs +57 -0
- package/src/tui/cloud-run.mjs +123 -0
- package/src/tui/cmd-agents.mjs +130 -0
- package/src/tui/cmd-auto-review.mjs +94 -0
- package/src/tui/cmd-cloud.mjs +17 -0
- package/src/tui/cmd-config.mjs +104 -0
- package/src/tui/cmd-core.mjs +160 -0
- package/src/tui/cmd-distribution.mjs +15 -0
- package/src/tui/cmd-ecosystem.mjs +169 -0
- package/src/tui/cmd-extensibility.mjs +333 -0
- package/src/tui/cmd-remote.mjs +18 -0
- package/src/tui/cmd-review.mjs +58 -0
- package/src/tui/cmd-session-extra.mjs +152 -0
- package/src/tui/cmd-tui.mjs +200 -0
- package/src/tui/commands.mjs +160 -0
- package/src/tui/custom-commands.mjs +98 -0
- package/src/tui/diff.mjs +60 -0
- package/src/tui/editor.mjs +190 -0
- package/src/tui/ext-state.mjs +16 -0
- package/src/tui/extensions-local.mjs +140 -0
- package/src/tui/files.mjs +72 -0
- package/src/tui/handoff.mjs +110 -0
- package/src/tui/import-setups.mjs +151 -0
- package/src/tui/init.mjs +104 -0
- package/src/tui/keymap.mjs +70 -0
- package/src/tui/keys.mjs +101 -0
- package/src/tui/loop.mjs +75 -0
- package/src/tui/markdown.mjs +118 -0
- package/src/tui/mcp-config.mjs +225 -0
- package/src/tui/mcp-oauth.mjs +162 -0
- package/src/tui/permissions.mjs +189 -0
- package/src/tui/plain.mjs +32 -0
- package/src/tui/plugins-local.mjs +103 -0
- package/src/tui/remote.mjs +125 -0
- package/src/tui/review-cli.mjs +332 -0
- package/src/tui/review-github.mjs +59 -0
- package/src/tui/screen.mjs +60 -0
- package/src/tui/session-ops.mjs +104 -0
- package/src/tui/skills-local.mjs +92 -0
- package/src/tui/snapshots.mjs +87 -0
- package/src/tui/statusline.mjs +98 -0
- package/src/tui/transcript.mjs +116 -0
- package/src/two-words.mjs +36 -0
- package/src/wakeups.mjs +53 -0
- package/src/winenv.mjs +94 -0
- package/src/winsandbox.py +351 -0
- package/src/workspace-api.mjs +621 -0
- package/src/worktree.mjs +128 -0
- package/vendor/client-sdk/controller.cjs +115 -0
- package/vendor/client-sdk/files.cjs +38 -0
- package/vendor/client-sdk/index.cjs +133 -0
- package/vendor/client-sdk/login.cjs +52 -0
- package/vendor/client-sdk/updates.cjs +41 -0
- package/vendor/cloud-cli/mlai.mjs +394 -0
- package/worker/architecture_parse.cjs +23 -0
- package/worker/architecture_worker.py +394 -0
- package/worker/ask_first.py +96 -0
- package/worker/attachment_reader.py +66 -0
- package/worker/background_jobs.py +111 -0
- package/worker/brief_questions.py +56 -0
- package/worker/browser_local.py +49 -0
- package/worker/browser_pane.py +89 -0
- package/worker/browser_tool.py +101 -0
- package/worker/build_planner.py +187 -0
- package/worker/chat_fork.py +277 -0
- package/worker/checkpoints.py +133 -0
- package/worker/cloud_pty.py +351 -0
- package/worker/command_policy.py +39 -0
- package/worker/command_safety.py +717 -0
- package/worker/computer_card.sh +23 -0
- package/worker/computer_setup.sh +86 -0
- package/worker/computer_use.py +221 -0
- package/worker/connector_search.py +43 -0
- package/worker/context_manager.py +60 -0
- package/worker/conversation.py +144 -0
- package/worker/deploy_pack.py +116 -0
- package/worker/design_director.py +240 -0
- package/worker/dev_jobs.py +166 -0
- package/worker/edit_guard.py +99 -0
- package/worker/env_setup.py +129 -0
- package/worker/evidence.py +109 -0
- package/worker/fast_search.py +24 -0
- package/worker/git_sync.py +333 -0
- package/worker/goals.py +156 -0
- package/worker/handover.py +98 -0
- package/worker/harness_memory.py +194 -0
- package/worker/image_generation.py +173 -0
- package/worker/intelligence.py +149 -0
- package/worker/intent_model.py +78 -0
- package/worker/intent_weights.json +1 -0
- package/worker/ios_simulator.py +87 -0
- package/worker/kimi_bridge.py +997 -0
- package/worker/kimi_compact.py +93 -0
- package/worker/kimi_gates.py +304 -0
- package/worker/kimi_hook.py +617 -0
- package/worker/lifecycle.py +95 -0
- package/worker/lsp.py +77 -0
- package/worker/mcp_local.py +293 -0
- package/worker/memory.py +99 -0
- package/worker/mlai_auto_review.py +177 -0
- package/worker/mlai_hooks.py +966 -0
- package/worker/mlai_mcp.py +441 -0
- package/worker/mlai_permissions.py +283 -0
- package/worker/model_stream.py +75 -0
- package/worker/nested_repos.py +76 -0
- package/worker/offline_guard.py +17 -0
- package/worker/preview.py +806 -0
- package/worker/proc_watch.py +124 -0
- package/worker/project_context.py +72 -0
- package/worker/project_rules.py +99 -0
- package/worker/quality.py +180 -0
- package/worker/reply_language.py +56 -0
- package/worker/repo_hygiene.py +132 -0
- package/worker/repo_memory.py +101 -0
- package/worker/repo_policy.py +269 -0
- package/worker/roles.json +3173 -0
- package/worker/roles.py +303 -0
- package/worker/runner.py +1795 -0
- package/worker/runtime_control.py +205 -0
- package/worker/secret_scan.py +168 -0
- package/worker/session_hub.py +80 -0
- package/worker/skill_library.py +129 -0
- package/worker/skill_pack.py +533 -0
- package/worker/subagents.py +91 -0
- package/worker/task_controller.py +139 -0
- package/worker/task_skills.py +159 -0
- package/worker/team_checkpoint.py +33 -0
- package/worker/token_count.py +32 -0
- package/worker/tool_catalog.py +38 -0
- package/worker/upload_storage.py +531 -0
- package/worker/verification.py +725 -0
- package/worker/vision.py +84 -0
- package/worker/wakeups.py +63 -0
- package/worker/web_tools.py +203 -0
- package/worker/winproc.py +135 -0
- package/worker/work_ledger.py +117 -0
- package/worker/worktrees.py +79 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Process identity checks. A PID alone is never enough to recover or terminate a run."""
|
|
2
|
+
import json, os, signal, time
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
def boot_id():
|
|
6
|
+
try:return Path('/proc/sys/kernel/random/boot_id').read_text().strip()
|
|
7
|
+
except OSError:
|
|
8
|
+
import sys,subprocess
|
|
9
|
+
if sys.platform=='darwin':return subprocess.check_output(['sysctl','-n','kern.boottime'],text=True).strip()
|
|
10
|
+
if sys.platform=='win32':
|
|
11
|
+
import winproc;return winproc.boot_id()
|
|
12
|
+
raise RuntimeError('This runtime requires macOS or Linux (WSL2 on Windows)')
|
|
13
|
+
|
|
14
|
+
def identity(pid):
|
|
15
|
+
import sys,subprocess
|
|
16
|
+
if sys.platform=='win32':
|
|
17
|
+
import winproc
|
|
18
|
+
try:
|
|
19
|
+
pid=int(pid)
|
|
20
|
+
start=winproc.start_time(pid) if pid>0 else None
|
|
21
|
+
return {'pid':pid,'start':start,'boot':boot_id()} if start else None
|
|
22
|
+
except (OSError,ValueError,TypeError):return None
|
|
23
|
+
if sys.platform=='darwin':
|
|
24
|
+
try:
|
|
25
|
+
pid=int(pid)
|
|
26
|
+
if pid<=0:return None
|
|
27
|
+
result=subprocess.check_output(['ps','-p',str(pid),'-o','lstart=','-o','stat='],text=True).strip()
|
|
28
|
+
if not result or result.split()[-1].startswith('Z'):return None
|
|
29
|
+
return {'pid':pid,'start':result,'boot':boot_id()}
|
|
30
|
+
except (OSError,ValueError,subprocess.CalledProcessError):return None
|
|
31
|
+
try:
|
|
32
|
+
stat=Path(f'/proc/{int(pid)}/stat').read_text().rsplit(')',1)[1].split()
|
|
33
|
+
if stat[0]=='Z':return None
|
|
34
|
+
return {'pid':int(pid),'start':stat[19],'boot':boot_id()}
|
|
35
|
+
except (OSError,ValueError,IndexError,TypeError):return None
|
|
36
|
+
|
|
37
|
+
def alive(record):
|
|
38
|
+
return bool(record and record.get('start') and identity(record.get('pid'))=={k:record.get(k) for k in ('pid','start','boot')})
|
|
39
|
+
|
|
40
|
+
def load(root,name,default=None):
|
|
41
|
+
try:return json.loads((Path(root)/name).read_text())
|
|
42
|
+
except (OSError,ValueError):return default
|
|
43
|
+
|
|
44
|
+
def inspect_run(root):
|
|
45
|
+
status=load(root,'status.json',{'state':'idle'})
|
|
46
|
+
if status.get('state')=='starting' and status.get('started') and time.time()-status['started']>360:
|
|
47
|
+
return {**status,'state':'interrupted','error':'Startup did not finish within six minutes. Continue to recover; the previous task will not be replayed automatically.'}
|
|
48
|
+
if status.get('state')=='running':
|
|
49
|
+
proc=status.get('process')
|
|
50
|
+
boot=boot_id()
|
|
51
|
+
if status.get('boot')!=boot or (proc and not alive(proc)):
|
|
52
|
+
return {**status,'state':'interrupted','error':'The worker stopped before finishing. Continue to inspect the workspace and recover safely.'}
|
|
53
|
+
return status
|
|
54
|
+
|
|
55
|
+
def recover(root):
|
|
56
|
+
root=Path(root);status=inspect_run(root)
|
|
57
|
+
if alive(status.get('process')):raise ValueError('The task is still running. Stop it before continuing.')
|
|
58
|
+
if status.get('state')=='starting':raise ValueError('The task is still starting. Wait for startup to finish.')
|
|
59
|
+
if status.get('state')=='running' and not status.get('process') and (not status.get('boot') or status.get('boot')==boot_id()):raise ValueError('Cannot confirm that this older worker stopped. Stop the environment first.')
|
|
60
|
+
child=load(root,'child.json')
|
|
61
|
+
if child and alive(child):
|
|
62
|
+
os.killpg(child['pid'],signal.SIGKILL)
|
|
63
|
+
deadline=time.monotonic()+3
|
|
64
|
+
while alive(child) and time.monotonic()<deadline:time.sleep(.05)
|
|
65
|
+
if alive(child):raise ValueError('Previous command is still stopping; try again shortly.')
|
|
66
|
+
for filename in ('run.lock','pending.json','child.json'):(root/filename).unlink(missing_ok=True)
|
|
67
|
+
(root/'status.json').write_text(json.dumps({**status,'state':'interrupted','error':'Previous run ended. Inspect files and external state before continuing.'}))
|
|
68
|
+
return load(root,'request.json',{}).get('task','')
|
|
69
|
+
|
|
70
|
+
def nested_guidance(repo,target):
|
|
71
|
+
base=Path(repo).resolve();parent=Path(target).resolve().parent
|
|
72
|
+
if not parent.is_relative_to(base):raise ValueError('Target outside repository')
|
|
73
|
+
sections=[];budget=6000
|
|
74
|
+
for directory in reversed([parent,*parent.parents]):
|
|
75
|
+
if directory==base or not directory.is_relative_to(base):continue
|
|
76
|
+
file=directory/'AGENTS.md'
|
|
77
|
+
if file.is_file() and not file.is_symlink() and budget>0:
|
|
78
|
+
with file.open(errors='replace') as stream:text=stream.read(min(3000,budget))
|
|
79
|
+
budget-=len(text)
|
|
80
|
+
sections.append(str(file.relative_to(base))+':\n'+text)
|
|
81
|
+
return '\n\n'.join(sections)
|
|
82
|
+
|
|
83
|
+
def claim_run(root,run_id,fingerprint):
|
|
84
|
+
"""Call under setup.lock. A request receipt survives completion and crashes."""
|
|
85
|
+
import re
|
|
86
|
+
if not re.fullmatch(r'[a-f0-9-]{36}',run_id):raise ValueError('Invalid run request ID')
|
|
87
|
+
root=Path(root);directory=root/'run-receipts';directory.mkdir(exist_ok=True)
|
|
88
|
+
target=directory/(run_id+'.json')
|
|
89
|
+
if target.exists():
|
|
90
|
+
receipt=json.loads(target.read_text())
|
|
91
|
+
if receipt.get('fingerprint')!=fingerprint:raise ValueError('Run request ID was reused with different input')
|
|
92
|
+
return False
|
|
93
|
+
if (root/'run.lock').exists():raise ValueError('A task is already running; stop it before starting another.')
|
|
94
|
+
with target.open('x') as stream:json.dump({'fingerprint':fingerprint,'created':time.time()},stream)
|
|
95
|
+
return True
|
package/worker/lsp.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Bounded, read-only LSP queries for TypeScript/JavaScript and Python."""
|
|
2
|
+
import json,os,queue,signal,subprocess,threading,time
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from intelligence import files
|
|
5
|
+
|
|
6
|
+
def query(repo,root,args,cancelled=lambda:None):
|
|
7
|
+
base,eligible=files(repo);relative=args.get('path','');target=(base/relative).resolve()
|
|
8
|
+
if target not in eligible:raise ValueError('Choose an eligible repository source file')
|
|
9
|
+
operation=args.get('operation','definition')
|
|
10
|
+
if operation not in ('definition','references','hover','diagnostics'):raise ValueError('Unsupported LSP operation')
|
|
11
|
+
line=args.get('line',1);column=args.get('column',1)
|
|
12
|
+
if type(line)!=int or type(column)!=int or min(line,column)<1:raise ValueError('Use one-based line and column')
|
|
13
|
+
python=target.suffix=='.py';language='python' if python else 'typescriptreact' if target.suffix=='.tsx' else 'javascriptreact' if target.suffix=='.jsx' else 'typescript' if target.suffix=='.ts' else 'javascript'
|
|
14
|
+
if target.suffix not in ('.py','.ts','.tsx','.js','.jsx','.mjs','.cjs'):raise ValueError('Supported languages: Python, TypeScript, JavaScript')
|
|
15
|
+
binary=Path(root)/'lsp/node_modules/.bin'/('pyright-langserver' if python else 'typescript-language-server')
|
|
16
|
+
if not binary.is_file():raise ValueError('Language servers are not installed. Use Tools > code intelligence > Install language servers.')
|
|
17
|
+
env={k:v for k,v in os.environ.items() if k not in ('MODEL_API_KEY','VERCEL_OIDC_TOKEN')}
|
|
18
|
+
process=subprocess.Popen([str(binary),'--stdio'],cwd=base,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,start_new_session=True)
|
|
19
|
+
messages=queue.Queue();seq=0;diagnostics=[];uri=target.as_uri();deadline=time.monotonic()+35
|
|
20
|
+
def reader():
|
|
21
|
+
try:
|
|
22
|
+
while True:
|
|
23
|
+
headers={}
|
|
24
|
+
while True:
|
|
25
|
+
row=process.stdout.readline()
|
|
26
|
+
if not row:return
|
|
27
|
+
if row in (b'\r\n',b'\n'):break
|
|
28
|
+
k,v=row.decode().split(':',1);headers[k.lower()]=v.strip()
|
|
29
|
+
size=int(headers.get('content-length','0'))
|
|
30
|
+
if size>2000000:return
|
|
31
|
+
data=process.stdout.read(size)
|
|
32
|
+
messages.put(json.loads(data))
|
|
33
|
+
except Exception:return
|
|
34
|
+
threading.Thread(target=reader,daemon=True).start()
|
|
35
|
+
def send(message):
|
|
36
|
+
data=json.dumps({'jsonrpc':'2.0',**message}).encode();process.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode()+data);process.stdin.flush()
|
|
37
|
+
def wait(ident=None,diagnostic=False):
|
|
38
|
+
while time.monotonic()<deadline:
|
|
39
|
+
cancelled()
|
|
40
|
+
try:message=messages.get(timeout=.15)
|
|
41
|
+
except queue.Empty:
|
|
42
|
+
if process.poll() is not None:raise ValueError('Language server exited')
|
|
43
|
+
continue
|
|
44
|
+
if message.get('method')=='textDocument/publishDiagnostics' and message.get('params',{}).get('uri')==uri:
|
|
45
|
+
diagnostics[:]=message['params'].get('diagnostics',[])
|
|
46
|
+
if diagnostic:return diagnostics
|
|
47
|
+
if 'method' in message and 'id' in message:
|
|
48
|
+
# Acknowledge registration/configuration requests; never apply edits or execute commands.
|
|
49
|
+
method=message['method'];result=[None for _ in message.get('params',{}).get('items',[])] if method=='workspace/configuration' else {'applied':False} if method=='workspace/applyEdit' else None
|
|
50
|
+
send({'id':message['id'],'result':result})
|
|
51
|
+
elif ident is not None and message.get('id')==ident:
|
|
52
|
+
if 'error' in message:raise ValueError(str(message['error'])[:1000])
|
|
53
|
+
return message.get('result')
|
|
54
|
+
raise ValueError('Language server timed out after 35 seconds')
|
|
55
|
+
def request(method,params):
|
|
56
|
+
nonlocal seq
|
|
57
|
+
seq+=1;send({'id':seq,'method':method,'params':params});return wait(seq)
|
|
58
|
+
try:
|
|
59
|
+
request('initialize',{'processId':None,'rootUri':base.as_uri(),'workspaceFolders':[{'uri':base.as_uri(),'name':base.name}],'initializationOptions':{'tsserver':{'path':str(Path(root)/'lsp/node_modules/typescript/lib/tsserver.js')}},'capabilities':{'textDocument':{'publishDiagnostics':{}},'general':{'positionEncodings':['utf-16']}}})
|
|
60
|
+
send({'method':'initialized','params':{}})
|
|
61
|
+
send({'method':'textDocument/didOpen','params':{'textDocument':{'uri':uri,'languageId':language,'version':1,'text':target.read_text()}}})
|
|
62
|
+
if operation=='diagnostics':result=wait(diagnostic=True)
|
|
63
|
+
else:
|
|
64
|
+
params={'textDocument':{'uri':uri},'position':{'line':line-1,'character':column-1}}
|
|
65
|
+
if operation=='references':params['context']={'includeDeclaration':True}
|
|
66
|
+
result=request('textDocument/'+operation,params)
|
|
67
|
+
# Paths outside this repository are never returned as navigable source locations.
|
|
68
|
+
def sanitize(value):
|
|
69
|
+
if isinstance(value,list):return [sanitize(v) for v in value[:100]]
|
|
70
|
+
if isinstance(value,dict):return {k:('[external library]' if k in ('uri','targetUri') and isinstance(v,str) and not v.startswith(base.as_uri()+'/') else sanitize(v)) for k,v in value.items()}
|
|
71
|
+
return value[:12000] if isinstance(value,str) else value
|
|
72
|
+
return {'operation':operation,'path':relative,'positionEncoding':'utf-16','result':sanitize(result)}
|
|
73
|
+
finally:
|
|
74
|
+
try:os.killpg(process.pid,signal.SIGKILL)
|
|
75
|
+
except ProcessLookupError:pass
|
|
76
|
+
process.wait(timeout=5)
|
|
77
|
+
process.stdin.close();process.stdout.close()
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""The user's own MCP servers on This Mac (CLI /mcp), for both engines.
|
|
2
|
+
|
|
3
|
+
The CLI merges .mlai/mcp.json, .mcp.json, .cursor/mcp.json, ~/.mlai/mcp.json and the `mcpServers` setting and sends
|
|
4
|
+
them in request.json `extensions.mcpServers`: name -> {"command", "args", "env", "cwd"} (stdio) or
|
|
5
|
+
{"url", "headers"} (streamable HTTP; "transport": "sse" for older HTTP+SSE servers). Environment values that came from ${VAR} references are not written to
|
|
6
|
+
request.json; the CLI passes them in MINI_MCP_ENV (JSON name -> {VAR: value}), the way Vault secrets travel.
|
|
7
|
+
|
|
8
|
+
Kimi engine: the servers are added to Kimi's mcp.json next to the built-in "mlai" server (tools mcp__<name>__<tool>).
|
|
9
|
+
Built-in runner: `tools(config)` lists them and `call(config, server, tool, arguments)` runs one call; the runner
|
|
10
|
+
exposes them as the workspace tool "mcp". Read-only turns (Plan, Ask) only get servers marked "readOnly": true.
|
|
11
|
+
Permission rules (mlai_permissions) apply to every call: mcp__<server> or mcp__<server>__<tool>.
|
|
12
|
+
|
|
13
|
+
CLI: python3 mcp_local.py tools <name> (stdin: the server JSON; prints {"tools": [...]} or {"error": "..."})
|
|
14
|
+
"""
|
|
15
|
+
import json, os, re, subprocess, sys, threading, time, urllib.parse, urllib.request, urllib.error
|
|
16
|
+
|
|
17
|
+
NAME = re.compile(r'^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$')
|
|
18
|
+
PROTOCOL = '2025-03-26'
|
|
19
|
+
MAX_SERVERS = 20
|
|
20
|
+
CLIENT = {'name': 'mlai-code', 'version': '1'}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _ext(config):
|
|
24
|
+
ext = (config or {}).get('extensions')
|
|
25
|
+
return ext if isinstance(ext, dict) else {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Taken out of the environment when the engine starts (runner.py imports this module), so agent commands never see it.
|
|
29
|
+
_SECRET = os.environ.pop('MINI_MCP_ENV', None)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _secret_env():
|
|
33
|
+
raw = os.environ.get('MINI_MCP_ENV') or _SECRET or '{}'
|
|
34
|
+
try: v = json.loads(raw)
|
|
35
|
+
except ValueError: v = {}
|
|
36
|
+
return v if isinstance(v, dict) else {}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def clean(name, raw):
|
|
40
|
+
"""A runnable server spec or None."""
|
|
41
|
+
if not isinstance(name, str) or not NAME.match(name) or name == 'mlai' or not isinstance(raw, dict): return None
|
|
42
|
+
if raw.get('disabled') is True or raw.get('enabled') is False: return None
|
|
43
|
+
out = {'readOnly': raw.get('readOnly') is True}
|
|
44
|
+
if isinstance(raw.get('url'), str) and raw['url'].startswith(('https://', 'http://')):
|
|
45
|
+
out['url'] = raw['url'][:2000]
|
|
46
|
+
h = raw.get('headers') if isinstance(raw.get('headers'), dict) else {}
|
|
47
|
+
out['headers'] = {str(k)[:100]: str(v)[:4000] for k, v in list(h.items())[:20]}
|
|
48
|
+
if str(raw.get('transport') or raw.get('type') or '').lower() == 'sse': out['transport'] = 'sse'
|
|
49
|
+
return out
|
|
50
|
+
cmd = raw.get('command')
|
|
51
|
+
if not isinstance(cmd, str) or not cmd.strip(): return None
|
|
52
|
+
out['command'] = cmd[:1000]
|
|
53
|
+
out['args'] = [str(a)[:4000] for a in (raw.get('args') if isinstance(raw.get('args'), list) else [])][:60]
|
|
54
|
+
env = raw.get('env') if isinstance(raw.get('env'), dict) else {}
|
|
55
|
+
out['env'] = {str(k)[:100]: str(v)[:8000] for k, v in list(env.items())[:60]}
|
|
56
|
+
if isinstance(raw.get('cwd'), str): out['cwd'] = raw['cwd'][:1000]
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def servers(config, readonly=False):
|
|
61
|
+
raw = _ext(config).get('mcpServers')
|
|
62
|
+
if not isinstance(raw, dict): return {}
|
|
63
|
+
secret = _secret_env(); out = {}
|
|
64
|
+
for name, spec in list(raw.items())[:MAX_SERVERS]:
|
|
65
|
+
s = clean(name, spec)
|
|
66
|
+
if not s or (readonly and not s['readOnly']): continue
|
|
67
|
+
extra = secret.get(name) if isinstance(secret.get(name), dict) else {}
|
|
68
|
+
if 'url' in s: s['headers'] = {**s['headers'], **{k: str(v) for k, v in (extra.get('headers') or {}).items()}} if isinstance(extra.get('headers'), dict) else s['headers']
|
|
69
|
+
else: s['env'] = {**s['env'], **{k: str(v) for k, v in extra.items() if k != 'headers'}}
|
|
70
|
+
out[name] = s
|
|
71
|
+
return out
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def kimi_servers(config, readonly=False):
|
|
75
|
+
"""Entries for Kimi's mcp.json."""
|
|
76
|
+
out = {}
|
|
77
|
+
for name, s in servers(config, readonly).items():
|
|
78
|
+
if 'url' in s: out[name] = {'url': s['url'], 'transport': s.get('transport') or 'http', **({'headers': s['headers']} if s['headers'] else {}), 'toolTimeoutMs': 120000}
|
|
79
|
+
else: out[name] = {'command': s['command'], 'args': s['args'], **({'env': s['env']} if s['env'] else {}), **({'cwd': s['cwd']} if s.get('cwd') else {}), 'toolTimeoutMs': 120000}
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def guidance(config, readonly=False):
|
|
84
|
+
names = sorted(servers(config, readonly))
|
|
85
|
+
if not names: return ''
|
|
86
|
+
return ('The user connected MCP servers on this computer: ' + ', '.join(names) + '. List a server\'s tools with the workspace tool mcp '
|
|
87
|
+
'{"server": "<name>", "action": "list"} and call one with {"server": "<name>", "tool": "<tool>", "arguments": {...}}.')
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------ minimal MCP client (stdio and streamable HTTP)
|
|
91
|
+
class McpError(Exception): pass
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class Stdio:
|
|
95
|
+
def __init__(self, spec, cwd=None, timeout=30):
|
|
96
|
+
env = {**{k: v for k, v in os.environ.items() if not k.startswith('MINI_') and k != 'MODEL_API_KEY'}, **spec.get('env', {})}
|
|
97
|
+
try:
|
|
98
|
+
self.p = subprocess.Popen([spec['command'], *spec.get('args', [])], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
99
|
+
cwd=spec.get('cwd') or cwd, env=env, text=True, bufsize=1)
|
|
100
|
+
except OSError as e: raise McpError('Could not start ' + spec['command'] + ': ' + str(e)[:200])
|
|
101
|
+
self.timeout = timeout; self.next = 0
|
|
102
|
+
|
|
103
|
+
def request(self, method, params=None, notify=False):
|
|
104
|
+
msg = {'jsonrpc': '2.0', 'method': method, **({'params': params} if params is not None else {})}
|
|
105
|
+
if not notify: self.next += 1; msg['id'] = self.next
|
|
106
|
+
try: self.p.stdin.write(json.dumps(msg) + '\n'); self.p.stdin.flush()
|
|
107
|
+
except (OSError, ValueError): raise McpError('The server closed its input')
|
|
108
|
+
if notify: return None
|
|
109
|
+
box = {}
|
|
110
|
+
|
|
111
|
+
def read():
|
|
112
|
+
for line in self.p.stdout:
|
|
113
|
+
try: m = json.loads(line)
|
|
114
|
+
except ValueError: continue
|
|
115
|
+
if isinstance(m, dict) and m.get('id') == msg['id'] and ('result' in m or 'error' in m): box['m'] = m; return
|
|
116
|
+
t = threading.Thread(target=read, daemon=True); t.start(); t.join(self.timeout)
|
|
117
|
+
if 'm' not in box: raise McpError('No answer from the server within ' + str(self.timeout) + ' seconds')
|
|
118
|
+
if box['m'].get('error'): raise McpError(str(box['m']['error'].get('message') or box['m']['error'])[:400])
|
|
119
|
+
return box['m'].get('result')
|
|
120
|
+
|
|
121
|
+
def close(self):
|
|
122
|
+
try: self.p.stdin.close(); self.p.terminate(); self.p.wait(3)
|
|
123
|
+
except Exception:
|
|
124
|
+
try: self.p.kill()
|
|
125
|
+
except Exception: pass
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class Http:
|
|
129
|
+
def __init__(self, spec, timeout=30):
|
|
130
|
+
self.url = spec['url']; self.headers = dict(spec.get('headers') or {}); self.timeout = timeout; self.next = 0; self.session = None
|
|
131
|
+
|
|
132
|
+
def request(self, method, params=None, notify=False):
|
|
133
|
+
msg = {'jsonrpc': '2.0', 'method': method, **({'params': params} if params is not None else {})}
|
|
134
|
+
if not notify: self.next += 1; msg['id'] = self.next
|
|
135
|
+
h = {'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream', **self.headers}
|
|
136
|
+
if self.session: h['Mcp-Session-Id'] = self.session
|
|
137
|
+
req = urllib.request.Request(self.url, data=json.dumps(msg).encode(), headers=h, method='POST')
|
|
138
|
+
try:
|
|
139
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
140
|
+
self.session = r.headers.get('Mcp-Session-Id') or self.session
|
|
141
|
+
body = r.read(4_000_000).decode('utf-8', 'replace'); kind = r.headers.get('Content-Type', '')
|
|
142
|
+
except urllib.error.HTTPError as e: raise McpError(_http_error(e.code))
|
|
143
|
+
except (urllib.error.URLError, OSError) as e: raise McpError('Could not reach the server: ' + str(getattr(e, 'reason', e))[:200])
|
|
144
|
+
if notify: return None
|
|
145
|
+
found = []
|
|
146
|
+
if 'text/event-stream' in kind:
|
|
147
|
+
for line in body.splitlines():
|
|
148
|
+
if line.startswith('data:'):
|
|
149
|
+
try: found.append(json.loads(line[5:].strip()))
|
|
150
|
+
except ValueError: pass
|
|
151
|
+
else:
|
|
152
|
+
try: found.append(json.loads(body))
|
|
153
|
+
except ValueError: raise McpError('The server did not answer with JSON')
|
|
154
|
+
for m in found:
|
|
155
|
+
if isinstance(m, dict) and m.get('id') == msg['id']:
|
|
156
|
+
if m.get('error'): raise McpError(str(m['error'].get('message') or m['error'])[:400])
|
|
157
|
+
return m.get('result')
|
|
158
|
+
raise McpError('The server did not answer the request')
|
|
159
|
+
|
|
160
|
+
def close(self): pass
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _http_error(code):
|
|
164
|
+
if code == 401: return 'HTTP 401 from the server: it needs a sign-in. Ask the user to run mlai mcp login <server> in a terminal.'
|
|
165
|
+
return 'HTTP ' + str(code) + ' from the server'
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class Sse:
|
|
169
|
+
"""The older HTTP+SSE transport: GET opens an event stream whose first "endpoint" event names the URL to POST
|
|
170
|
+
messages to; answers arrive as "message" events on the stream."""
|
|
171
|
+
def __init__(self, spec, timeout=30):
|
|
172
|
+
self.url = spec['url']; self.headers = dict(spec.get('headers') or {}); self.timeout = timeout; self.next = 0
|
|
173
|
+
self.endpoint = None; self.answers = {}; self.cv = threading.Condition(); self.error = None
|
|
174
|
+
req = urllib.request.Request(self.url, headers={'Accept': 'text/event-stream', **self.headers})
|
|
175
|
+
try: self.stream = urllib.request.urlopen(req, timeout=timeout)
|
|
176
|
+
except urllib.error.HTTPError as e: raise McpError(_http_error(e.code))
|
|
177
|
+
except (urllib.error.URLError, OSError) as e: raise McpError('Could not reach the server: ' + str(getattr(e, 'reason', e))[:200])
|
|
178
|
+
threading.Thread(target=self._read, daemon=True).start()
|
|
179
|
+
with self.cv:
|
|
180
|
+
self.cv.wait_for(lambda: self.endpoint or self.error, timeout)
|
|
181
|
+
if not self.endpoint: self.close(); raise McpError(self.error or 'The server sent no endpoint within ' + str(timeout) + ' seconds')
|
|
182
|
+
|
|
183
|
+
def _read(self):
|
|
184
|
+
event, data = 'message', []
|
|
185
|
+
try:
|
|
186
|
+
for raw in self.stream:
|
|
187
|
+
line = raw.decode('utf-8', 'replace').rstrip('\r\n')
|
|
188
|
+
if line.startswith('event:'): event = line[6:].strip()
|
|
189
|
+
elif line.startswith('data:'): data.append(line[5:][1:] if line[5:].startswith(' ') else line[5:])
|
|
190
|
+
elif not line:
|
|
191
|
+
text = '\n'.join(data); data = []
|
|
192
|
+
with self.cv:
|
|
193
|
+
if event == 'endpoint': self.endpoint = urllib.parse.urljoin(self.url, text.strip())
|
|
194
|
+
elif text:
|
|
195
|
+
try: m = json.loads(text)
|
|
196
|
+
except ValueError: m = None
|
|
197
|
+
if isinstance(m, dict) and 'id' in m: self.answers[m['id']] = m
|
|
198
|
+
self.cv.notify_all()
|
|
199
|
+
event = 'message'
|
|
200
|
+
except Exception as e: self.error = 'The event stream failed: ' + str(e)[:200]
|
|
201
|
+
with self.cv:
|
|
202
|
+
self.error = self.error or 'The server closed the event stream'; self.cv.notify_all()
|
|
203
|
+
|
|
204
|
+
def request(self, method, params=None, notify=False):
|
|
205
|
+
msg = {'jsonrpc': '2.0', 'method': method, **({'params': params} if params is not None else {})}
|
|
206
|
+
if not notify: self.next += 1; msg['id'] = self.next
|
|
207
|
+
req = urllib.request.Request(self.endpoint, data=json.dumps(msg).encode(), headers={'Content-Type': 'application/json', **self.headers}, method='POST')
|
|
208
|
+
try:
|
|
209
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r: r.read(1_000_000)
|
|
210
|
+
except urllib.error.HTTPError as e: raise McpError(_http_error(e.code))
|
|
211
|
+
except (urllib.error.URLError, OSError) as e: raise McpError('Could not reach the server: ' + str(getattr(e, 'reason', e))[:200])
|
|
212
|
+
if notify: return None
|
|
213
|
+
with self.cv:
|
|
214
|
+
self.cv.wait_for(lambda: msg['id'] in self.answers or self.error, self.timeout)
|
|
215
|
+
m = self.answers.pop(msg['id'], None)
|
|
216
|
+
if m is None: raise McpError(self.error if self.error and self.error != 'The server closed the event stream' else 'No answer from the server within ' + str(self.timeout) + ' seconds')
|
|
217
|
+
if m.get('error'): raise McpError(str(m['error'].get('message') or m['error'])[:400])
|
|
218
|
+
return m.get('result')
|
|
219
|
+
|
|
220
|
+
def close(self):
|
|
221
|
+
try: self.stream.close()
|
|
222
|
+
except Exception: pass
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def connect(spec, cwd=None, timeout=30):
|
|
226
|
+
c = (Sse(spec, timeout) if spec.get('transport') == 'sse' else Http(spec, timeout)) if 'url' in spec else Stdio(spec, cwd, timeout)
|
|
227
|
+
try:
|
|
228
|
+
c.request('initialize', {'protocolVersion': PROTOCOL, 'capabilities': {}, 'clientInfo': CLIENT})
|
|
229
|
+
c.request('notifications/initialized', None, notify=True)
|
|
230
|
+
except Exception:
|
|
231
|
+
c.close(); raise
|
|
232
|
+
return c
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def list_tools(spec, cwd=None, timeout=30):
|
|
236
|
+
c = connect(spec, cwd, timeout)
|
|
237
|
+
try:
|
|
238
|
+
tools, cursor = [], None
|
|
239
|
+
for _ in range(10):
|
|
240
|
+
r = c.request('tools/list', {'cursor': cursor} if cursor else {}) or {}
|
|
241
|
+
tools += [t for t in r.get('tools') or [] if isinstance(t, dict) and isinstance(t.get('name'), str)]
|
|
242
|
+
cursor = r.get('nextCursor')
|
|
243
|
+
if not cursor: break
|
|
244
|
+
return [{'name': t['name'], 'description': str(t.get('description') or '')[:600], 'inputSchema': t.get('inputSchema') or {'type': 'object'},
|
|
245
|
+
'readOnly': bool((t.get('annotations') or {}).get('readOnlyHint'))} for t in tools[:200]]
|
|
246
|
+
finally: c.close()
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def call_tool(spec, tool, arguments, cwd=None, timeout=120):
|
|
250
|
+
c = connect(spec, cwd, timeout)
|
|
251
|
+
try:
|
|
252
|
+
r = c.request('tools/call', {'name': tool, 'arguments': arguments if isinstance(arguments, dict) else {}}) or {}
|
|
253
|
+
finally: c.close()
|
|
254
|
+
parts = []
|
|
255
|
+
for item in r.get('content') or []:
|
|
256
|
+
if not isinstance(item, dict): continue
|
|
257
|
+
if item.get('type') == 'text': parts.append(str(item.get('text') or ''))
|
|
258
|
+
elif item.get('type') == 'resource' and isinstance(item.get('resource'), dict): parts.append(str(item['resource'].get('text') or item['resource'].get('uri') or ''))
|
|
259
|
+
else: parts.append('[' + str(item.get('type')) + ' content]')
|
|
260
|
+
if r.get('structuredContent') is not None and not parts: parts.append(json.dumps(r['structuredContent'])[:20000])
|
|
261
|
+
return {'returncode': 1 if r.get('isError') else 0, 'output': '\n'.join(parts)[:24000] or '(no output)'}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def run_tool(config, args, repo=None, readonly=False):
|
|
265
|
+
"""The runner's workspace tool "mcp": {server, action: list} or {server, tool, arguments}."""
|
|
266
|
+
avail = servers(config, readonly)
|
|
267
|
+
name = args.get('server') if isinstance(args, dict) else None
|
|
268
|
+
if not avail: return {'returncode': 1, 'output': 'No MCP servers are connected for this task.'}
|
|
269
|
+
if name not in avail: return {'returncode': 1, 'output': 'Unknown MCP server. Connected: ' + ', '.join(sorted(avail))}
|
|
270
|
+
try:
|
|
271
|
+
if args.get('action') == 'list' or not args.get('tool'):
|
|
272
|
+
tools = list_tools(avail[name], repo)
|
|
273
|
+
return {'returncode': 0, 'output': json.dumps([{k: t[k] for k in ('name', 'description', 'inputSchema')} for t in tools])[:24000]}
|
|
274
|
+
return call_tool(avail[name], str(args['tool']), args.get('arguments') or {}, repo)
|
|
275
|
+
except McpError as e: return {'returncode': 1, 'output': 'MCP server ' + name + ': ' + str(e)}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
TOOL = {'name': 'mcp', 'description': 'Call a tool of an MCP server the user connected on this computer. {"server", "action": "list"} lists its tools; {"server", "tool", "arguments"} calls one.',
|
|
279
|
+
'inputSchema': {'type': 'object', 'properties': {'server': {'type': 'string'}, 'action': {'type': 'string', 'enum': ['list', 'call']}, 'tool': {'type': 'string'}, 'arguments': {'type': 'object'}}, 'required': ['server']}}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def main(argv):
|
|
283
|
+
if argv[:1] == ['tools'] and len(argv) > 1:
|
|
284
|
+
spec = clean(argv[1], json.loads(sys.stdin.read() or '{}'))
|
|
285
|
+
if not spec: print(json.dumps({'error': 'Invalid server configuration'})); return
|
|
286
|
+
try: print(json.dumps({'tools': list_tools(spec, os.getcwd(), timeout=float(os.environ.get('MCP_TIMEOUT') or 20))}))
|
|
287
|
+
except McpError as e: print(json.dumps({'error': str(e)}))
|
|
288
|
+
return
|
|
289
|
+
print(json.dumps({'error': 'usage: mcp_local.py tools <name>'}))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
if __name__ == '__main__':
|
|
293
|
+
main(sys.argv[1:])
|
package/worker/memory.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Project memory (port of the Pixis L4 memory store): one markdown fact per file under <root>/memory/ plus MEMORY.md,
|
|
2
|
+
an index with one line per fact. The index goes into the agent's system context every run; a fact is read on demand.
|
|
3
|
+
|
|
4
|
+
Types: project (how this repository works), user (preferences of the person), feedback (corrections they gave),
|
|
5
|
+
reference (where things live: URLs, hosts, dashboards). Facts are plain text, never secrets.
|
|
6
|
+
"""
|
|
7
|
+
import json, re, time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
TYPES = ('project', 'user', 'feedback', 'reference')
|
|
11
|
+
SECRET = re.compile(r'(sk-[A-Za-z0-9]{16,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}|(?i:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S{8,})')
|
|
12
|
+
MAX_FACTS = 200
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MemoryStore:
|
|
16
|
+
def __init__(self, root):
|
|
17
|
+
self.dir = Path(root) / 'memory'
|
|
18
|
+
self.index = self.dir / 'MEMORY.md'
|
|
19
|
+
|
|
20
|
+
def _slug(self, name):
|
|
21
|
+
slug = re.sub(r'[^a-z0-9]+', '-', str(name or '').lower()).strip('-')[:60]
|
|
22
|
+
if not slug: raise ValueError('name is required')
|
|
23
|
+
return slug
|
|
24
|
+
|
|
25
|
+
def save(self, name, content, kind='project', description=''):
|
|
26
|
+
"""Create or replace one fact. Returns its index line."""
|
|
27
|
+
kind = kind if kind in TYPES else 'project'
|
|
28
|
+
content = str(content or '').strip()
|
|
29
|
+
if not content: raise ValueError('content is required')
|
|
30
|
+
if len(content) > 4000: raise ValueError('a fact must stay under 4000 characters; split it')
|
|
31
|
+
if SECRET.search(content) or SECRET.search(str(description or '')): raise ValueError('memory never stores credentials; keep secrets in the Vault')
|
|
32
|
+
slug = self._slug(name)
|
|
33
|
+
description = re.sub(r'\s+', ' ', str(description or content.splitlines()[0])).strip()[:160]
|
|
34
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
35
|
+
existing = self.list()
|
|
36
|
+
if slug not in {f['name'] for f in existing} and len(existing) >= MAX_FACTS: raise ValueError('memory is full (%d facts); forget something first' % MAX_FACTS)
|
|
37
|
+
body = '---\nname: ' + slug + '\ntype: ' + kind + '\ndescription: ' + description + '\nupdated: ' + time.strftime('%Y-%m-%d') + '\n---\n' + content + '\n'
|
|
38
|
+
(self.dir / (slug + '.md')).write_text(body)
|
|
39
|
+
self._rebuild()
|
|
40
|
+
return '- [' + kind + '] ' + slug + ' — ' + description
|
|
41
|
+
|
|
42
|
+
def read(self, name):
|
|
43
|
+
path = self.dir / (self._slug(name) + '.md')
|
|
44
|
+
if not path.is_file(): raise ValueError('no memory named ' + name)
|
|
45
|
+
text = path.read_text()
|
|
46
|
+
m = re.match(r'---\n(.*?)\n---\n', text, re.S)
|
|
47
|
+
return text[m.end():].strip() if m else text.strip()
|
|
48
|
+
|
|
49
|
+
def forget(self, name):
|
|
50
|
+
path = self.dir / (self._slug(name) + '.md')
|
|
51
|
+
if not path.is_file(): return False
|
|
52
|
+
path.unlink(); self._rebuild(); return True
|
|
53
|
+
|
|
54
|
+
def list(self):
|
|
55
|
+
out = []
|
|
56
|
+
if not self.dir.is_dir(): return out
|
|
57
|
+
for path in sorted(self.dir.glob('*.md')):
|
|
58
|
+
if path.name == 'MEMORY.md': continue
|
|
59
|
+
try: head = path.read_text()[:2000]
|
|
60
|
+
except OSError: continue
|
|
61
|
+
m = re.match(r'---\n(.*?)\n---', head, re.S)
|
|
62
|
+
meta = {}
|
|
63
|
+
if m:
|
|
64
|
+
for line in m.group(1).splitlines():
|
|
65
|
+
k, _, v = line.partition(':'); meta[k.strip()] = v.strip()
|
|
66
|
+
out.append({'name': path.stem, 'type': meta.get('type', 'project'), 'description': meta.get('description', ''), 'updated': meta.get('updated', '')})
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
def _rebuild(self):
|
|
70
|
+
facts = self.list()
|
|
71
|
+
lines = ['# Project memory', '', 'One line per fact. Read a fact with mcp__mlai__memory {"action":"read","name":"<name>"}.', '']
|
|
72
|
+
for kind in TYPES:
|
|
73
|
+
rows = [f for f in facts if f['type'] == kind]
|
|
74
|
+
if not rows: continue
|
|
75
|
+
lines.append('## ' + kind)
|
|
76
|
+
lines += ['- ' + f['name'] + ' — ' + f['description'] for f in rows]
|
|
77
|
+
lines.append('')
|
|
78
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
self.index.write_text('\n'.join(lines).rstrip() + '\n')
|
|
80
|
+
|
|
81
|
+
def index_text(self, limit=6000):
|
|
82
|
+
facts = self.list()
|
|
83
|
+
if not facts:
|
|
84
|
+
return ('Project memory: empty. This workspace keeps durable facts across tasks in mcp__mlai__memory. When you learn something that will matter next time '
|
|
85
|
+
'(how to run or test this project, a convention, a preference the user stated, a correction they gave, where something lives), save it with '
|
|
86
|
+
'mcp__mlai__memory {"action":"save","name":"short-name","type":"project|user|feedback|reference","description":"one line","content":"the fact"}. Never store secrets.')
|
|
87
|
+
text = 'Project memory (facts saved in earlier tasks; read one with mcp__mlai__memory {"action":"read","name":"<name>"}; save new durable facts with action "save", correct wrong ones by saving the same name, drop them with "forget"):\n'
|
|
88
|
+
body = self.index.read_text() if self.index.is_file() else ''
|
|
89
|
+
body = '\n'.join(l for l in body.splitlines() if l.startswith('- ') or l.startswith('## '))
|
|
90
|
+
return (text + body)[:limit]
|
|
91
|
+
|
|
92
|
+
def run(self, args):
|
|
93
|
+
"""MCP tool entry: {action: save|read|list|forget, name?, type?, description?, content?}."""
|
|
94
|
+
action = str(args.get('action') or 'list')
|
|
95
|
+
if action == 'save': return {'saved': self.save(args.get('name'), args.get('content'), args.get('type') or 'project', args.get('description') or ''), 'facts': len(self.list())}
|
|
96
|
+
if action == 'read': return {'name': self._slug(args.get('name')), 'content': self.read(args.get('name'))}
|
|
97
|
+
if action == 'forget': return {'forgotten': self.forget(args.get('name'))}
|
|
98
|
+
if action == 'list': return {'facts': self.list()}
|
|
99
|
+
raise ValueError('action must be save, read, list or forget')
|