mlai-code 0.0.0-stage → 0.3.1
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,149 @@
|
|
|
1
|
+
"""Bounded repository discovery. All returned content is untrusted project data."""
|
|
2
|
+
import ast,json,os,re,shutil,subprocess,time
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
EXCLUDED={'.git','.mini','.next','node_modules','dist','build','vendor','__pycache__'}
|
|
5
|
+
|
|
6
|
+
def files(repo,suffixes=None):
|
|
7
|
+
root=Path(repo).resolve()
|
|
8
|
+
result=subprocess.run(['git','ls-files','--cached','--others','--exclude-standard','-z'],cwd=root,capture_output=True,timeout=10)
|
|
9
|
+
if result.returncode:raise ValueError('Repository discovery requires Git')
|
|
10
|
+
paths=[]
|
|
11
|
+
for name in result.stdout.decode(errors='replace').split('\0'):
|
|
12
|
+
if not name or (suffixes and Path(name).suffix not in suffixes):continue
|
|
13
|
+
p=root/name
|
|
14
|
+
if any(x in EXCLUDED or x.startswith('.env') or x.endswith(('.pem','.key','.p12')) for x in Path(name).parts):continue
|
|
15
|
+
if p.is_symlink() or not p.resolve().is_relative_to(root) or not p.is_file():continue
|
|
16
|
+
if p.stat().st_size>300000:continue
|
|
17
|
+
paths.append(p)
|
|
18
|
+
if len(paths)>=2000:break
|
|
19
|
+
return root,paths
|
|
20
|
+
|
|
21
|
+
def symbols(path,top_level=False):
|
|
22
|
+
text=path.read_text(errors='replace');found=[]
|
|
23
|
+
if path.suffix=='.py':
|
|
24
|
+
try:
|
|
25
|
+
tree=ast.parse(text)
|
|
26
|
+
for n in (tree.body if top_level else ast.walk(tree)):
|
|
27
|
+
if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef)):
|
|
28
|
+
found.append({'name':n.name,'line':n.lineno,'kind':'class' if isinstance(n,ast.ClassDef) else 'function'})
|
|
29
|
+
except SyntaxError as e:return [{'kind':'syntax_error','line':e.lineno,'name':e.msg}]
|
|
30
|
+
elif path.suffix in {'.ts','.tsx','.js','.jsx','.mjs','.cjs'}:
|
|
31
|
+
for i,line in enumerate(text.splitlines(),1):
|
|
32
|
+
if top_level and line[:1].isspace():continue
|
|
33
|
+
match=re.search(r'(?:export\s+)?(?:async\s+)?(?:function|class|interface|type|const)\s+([A-Za-z_$][\w$]*)',line)
|
|
34
|
+
if match:found.append({'name':match[1],'line':i,'kind':'declaration_candidate'})
|
|
35
|
+
return found[:80]
|
|
36
|
+
|
|
37
|
+
SOURCE_EXT={'.py','.ts','.tsx','.js','.jsx','.mjs','.cjs'}
|
|
38
|
+
_JS_IMPORT=re.compile(r"""(?:import|export)\s[^'"]*?from\s*['"]([^'"]+)['"]|import\(\s*['"]([^'"]+)['"]|require\(\s*['"]([^'"]+)['"]""")
|
|
39
|
+
_PY_IMPORT=re.compile(r'^\s*(?:from\s+(\.*[\w.]*)\s+import|import\s+([\w.]+))',re.M)
|
|
40
|
+
|
|
41
|
+
def _resolve_js(spec,src,base,index):
|
|
42
|
+
if spec.startswith('@/') or spec.startswith('~/'):cands=[base/spec[2:],base/'src'/spec[2:]]
|
|
43
|
+
elif spec.startswith('.'):cands=[(src.parent/spec)]
|
|
44
|
+
else:return None
|
|
45
|
+
for c in cands:
|
|
46
|
+
c=Path(os.path.normpath(c))
|
|
47
|
+
for option in [c]+[Path(str(c)+e) for e in ('.ts','.tsx','.js','.jsx','.mjs')]+[c/('index'+e) for e in ('.ts','.tsx','.js','.jsx')]:
|
|
48
|
+
hit=index.get(str(option))
|
|
49
|
+
if hit:return hit
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
def _resolve_py(spec,src,base,index,modules):
|
|
53
|
+
if spec.startswith('.'):
|
|
54
|
+
level=len(spec)-len(spec.lstrip('.'));parent=src.parent
|
|
55
|
+
for _ in range(level-1):parent=parent.parent
|
|
56
|
+
rest=spec.lstrip('.').replace('.','/')
|
|
57
|
+
target=parent/rest if rest else parent
|
|
58
|
+
for option in (str(target)+'.py',str(target/'__init__.py')):
|
|
59
|
+
if option in index:return index[option]
|
|
60
|
+
return None
|
|
61
|
+
return modules.get(spec)
|
|
62
|
+
|
|
63
|
+
def ranked_map(base,paths,budget=6000):
|
|
64
|
+
"""Aider-style map: rank source files by import-graph PageRank and list their top declarations within a character budget."""
|
|
65
|
+
source=[p for p in paths if p.suffix in SOURCE_EXT][:1500]
|
|
66
|
+
if len(paths)>=2000:source=files(base,SOURCE_EXT)[1][:1500]
|
|
67
|
+
index={str(p):str(p.relative_to(base)) for p in source}
|
|
68
|
+
modules={}
|
|
69
|
+
for p in source:
|
|
70
|
+
if p.suffix=='.py':
|
|
71
|
+
rel=p.relative_to(base).with_suffix('');parts=list(rel.parts)
|
|
72
|
+
if parts[-1]=='__init__':parts=parts[:-1]
|
|
73
|
+
for i in range(len(parts)):modules.setdefault('.'.join(parts[i:]),str(p.relative_to(base)))
|
|
74
|
+
edges={index[str(p)]:set() for p in source}
|
|
75
|
+
for p in source:
|
|
76
|
+
try:text=p.read_text(errors='replace')[:200000]
|
|
77
|
+
except OSError:continue
|
|
78
|
+
me=index[str(p)]
|
|
79
|
+
if p.suffix=='.py':
|
|
80
|
+
for a,b in _PY_IMPORT.findall(text):
|
|
81
|
+
hit=_resolve_py(a or b,p,base,index,modules)
|
|
82
|
+
if hit and hit!=me:edges[me].add(hit)
|
|
83
|
+
else:
|
|
84
|
+
for groups in _JS_IMPORT.findall(text):
|
|
85
|
+
spec=next((g for g in groups if g),'')
|
|
86
|
+
hit=_resolve_js(spec,p,base,index) if spec else None
|
|
87
|
+
if hit and hit!=me:edges[me].add(hit)
|
|
88
|
+
nodes=list(edges);n=len(nodes) or 1;rank={k:1/n for k in nodes}
|
|
89
|
+
for _ in range(20):
|
|
90
|
+
nxt={k:.15/n for k in nodes}
|
|
91
|
+
for k,outs in edges.items():
|
|
92
|
+
if outs:
|
|
93
|
+
share=.85*rank[k]/len(outs)
|
|
94
|
+
for o in outs:nxt[o]+=share
|
|
95
|
+
else:
|
|
96
|
+
for o in nodes:nxt[o]+=.85*rank[k]/n
|
|
97
|
+
rank=nxt
|
|
98
|
+
inbound={k:0 for k in nodes}
|
|
99
|
+
for outs in edges.values():
|
|
100
|
+
for o in outs:inbound[o]+=1
|
|
101
|
+
ordered=sorted(nodes,key=lambda k:(-rank[k],k))
|
|
102
|
+
out=[];used=0
|
|
103
|
+
for k in ordered:
|
|
104
|
+
names=[x['name']+':'+str(x['line']) for x in symbols(base/k,True) if x.get('kind')!='syntax_error'][:12]
|
|
105
|
+
entry={'path':k,'importedBy':inbound[k],'symbols':names}
|
|
106
|
+
size=len(json.dumps(entry))
|
|
107
|
+
if used+size>budget and out:break
|
|
108
|
+
out.append(entry);used+=size
|
|
109
|
+
return {'rankedFiles':out,'rankedOf':len(nodes),'rankMethod':'import-graph PageRank (Python AST imports, JS/TS relative and @/ imports); declarations are candidates, not type-resolved'}
|
|
110
|
+
|
|
111
|
+
def run(tool,args,repo,root):
|
|
112
|
+
base,paths=files(repo)
|
|
113
|
+
if tool=='repo_map':
|
|
114
|
+
counts={};manifests=[];entry=[]
|
|
115
|
+
for p in paths:
|
|
116
|
+
ext=p.suffix or '(none)';counts[ext]=counts.get(ext,0)+1
|
|
117
|
+
rel=str(p.relative_to(base))
|
|
118
|
+
if p.name in {'package.json','pyproject.toml','Cargo.toml','go.mod','requirements.txt','AGENTS.md','README.md'}:manifests.append(rel)
|
|
119
|
+
if p.stem in {'main','index','app','page','server','cli','manage'}:entry.append(rel)
|
|
120
|
+
budget=args.get('budget',6000)
|
|
121
|
+
budget=min(16000,max(1000,int(budget))) if isinstance(budget,(int,float)) and not isinstance(budget,bool) else 6000
|
|
122
|
+
summary={'filesScanned':len(paths),'truncated':len(paths)==2000,'languages':counts,'manifests':manifests[:80],'entryCandidates':entry[:80],'topDirectories':sorted({str(p.relative_to(base)).split('/')[0] for p in paths})[:80]}
|
|
123
|
+
try:summary.update(ranked_map(base,paths,budget))
|
|
124
|
+
except (OSError,ValueError,RecursionError):summary['rankedFiles']=[]
|
|
125
|
+
return summary
|
|
126
|
+
if tool=='symbols':
|
|
127
|
+
query=args.get('query','');target=args.get('path');out=[]
|
|
128
|
+
if not isinstance(query,str) or len(query)>200:raise ValueError('Symbol query must be under 200 characters')
|
|
129
|
+
for p in paths:
|
|
130
|
+
if target and str(p.relative_to(base))!=target:continue
|
|
131
|
+
for symbol in symbols(p):
|
|
132
|
+
if query.lower() in symbol['name'].lower():out.append({'path':str(p.relative_to(base)),**symbol})
|
|
133
|
+
if len(out)>=120:break
|
|
134
|
+
return {'matches':out[:120],'method':'Python AST; JS/TS declaration candidates, not LSP type resolution'}
|
|
135
|
+
if tool=='test_plan':
|
|
136
|
+
result=subprocess.run(['git','diff','--name-only','HEAD'],cwd=base,capture_output=True,text=True,timeout=10)
|
|
137
|
+
changed=result.stdout.splitlines();candidates=[];scripts={}
|
|
138
|
+
for p in paths:
|
|
139
|
+
rel=str(p.relative_to(base))
|
|
140
|
+
if p.name=='package.json':
|
|
141
|
+
try:scripts[rel]=json.loads(p.read_text()).get('scripts',{})
|
|
142
|
+
except ValueError:pass
|
|
143
|
+
if re.search(r'(^|/)(tests?|__tests__)/|[._](test|spec)\.',rel):
|
|
144
|
+
score=sum(Path(c).stem.replace('test_','') in p.stem for c in changed)
|
|
145
|
+
candidates.append({'path':rel,'relevance':score})
|
|
146
|
+
return {'changedFiles':changed[:100],'testCandidates':sorted(candidates,key=lambda x:-x['relevance'])[:60],'packageScripts':scripts,'instruction':'Suggestions only. Inspect tests and run relevant checks using verify; these checks have not run.'}
|
|
147
|
+
if tool=='capability_check':
|
|
148
|
+
return {'python':shutil.which('python3'),'node':shutil.which('node'),'git':shutil.which('git'),'shell':shutil.which('bash'),'browserConfigured':(Path(root)/'browser-ready').exists(),'repoAccessible':base.is_dir(),'checkedAt':time.time(),'note':'Browser marker does not prove browser launch or network access. Verify those when used.'}
|
|
149
|
+
raise ValueError('Unknown intelligence tool')
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Local intent classifier: routes a request to chat / research / plan / build in well under a millisecond, no model call.
|
|
2
|
+
|
|
3
|
+
A multinomial logistic regression over hashed word and character n-gram features, trained offline
|
|
4
|
+
(benchmarks/intent/train.py) by distilling the LLM router's labels. Weights live in intent_weights.json.
|
|
5
|
+
The caller uses the prediction only when it is confident; otherwise it falls back to the LLM router.
|
|
6
|
+
"""
|
|
7
|
+
import json, math, re, zlib
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
LABELS = ('chat', 'research', 'plan', 'build')
|
|
11
|
+
DIM = 1 << 15
|
|
12
|
+
_WEIGHTS = None
|
|
13
|
+
|
|
14
|
+
def _h(token):
|
|
15
|
+
return zlib.crc32(token.encode('utf-8')) & (DIM - 1)
|
|
16
|
+
|
|
17
|
+
def normalize(text):
|
|
18
|
+
text = str(text or '').lower()
|
|
19
|
+
text = re.sub(r'https?://\S+', ' URL ', text)
|
|
20
|
+
text = re.sub(r'`[^`]{0,200}`', ' CODE ', text)
|
|
21
|
+
text = re.sub(r'\b[\w./-]+\.(py|js|jsx|ts|tsx|go|rs|java|rb|json|md|css|html|yml|yaml|toml|sql)\b', ' FILE ', text)
|
|
22
|
+
text = re.sub(r'\d+', '0', text)
|
|
23
|
+
return text
|
|
24
|
+
|
|
25
|
+
def features(text, history=''):
|
|
26
|
+
"""Sparse hashed counts: words, word bigrams, char 3-5 grams of the request; words of the previous assistant turn."""
|
|
27
|
+
t = normalize(text)[:2000]
|
|
28
|
+
words = re.findall(r"[a-z\u00c0-\u024f\u0900-\u097f']+|[?!]|URL|CODE|FILE", t)
|
|
29
|
+
feats = {}
|
|
30
|
+
def add(tok, w=1.0):
|
|
31
|
+
k = _h(tok); feats[k] = feats.get(k, 0.0) + w
|
|
32
|
+
add('__bias__')
|
|
33
|
+
for i, w in enumerate(words):
|
|
34
|
+
add('w:' + w)
|
|
35
|
+
if i: add('b:' + words[i - 1] + '_' + w)
|
|
36
|
+
if i < 3: add('s:' + w) # how a request opens matters most
|
|
37
|
+
padded = ' ' + ' '.join(words[:120]) + ' '
|
|
38
|
+
for n in (3, 4, 5):
|
|
39
|
+
for i in range(len(padded) - n + 1): add('c%d:' % n + padded[i:i + n], 0.3)
|
|
40
|
+
add('len:%d' % min(6, len(words).bit_length()))
|
|
41
|
+
if '?' in t: add('has_q')
|
|
42
|
+
if re.search(r'traceback|error:|exception|failed|\bat \w+ \(', t): add('has_err')
|
|
43
|
+
for w in re.findall(r"[a-z']+", normalize(history)[-600:])[-60:]: add('h:' + w, 0.5)
|
|
44
|
+
norm = math.sqrt(sum(v * v for v in feats.values())) or 1.0
|
|
45
|
+
return {k: v / norm for k, v in feats.items()}
|
|
46
|
+
|
|
47
|
+
def load(path=None):
|
|
48
|
+
global _WEIGHTS
|
|
49
|
+
if _WEIGHTS is None or path:
|
|
50
|
+
p = Path(path) if path else Path(__file__).with_name('intent_weights.json')
|
|
51
|
+
data = json.loads(p.read_text())
|
|
52
|
+
_WEIGHTS = {lab: {int(k): v for k, v in data['weights'][lab].items()} for lab in LABELS}
|
|
53
|
+
_WEIGHTS['_meta'] = data.get('meta', {})
|
|
54
|
+
return _WEIGHTS
|
|
55
|
+
|
|
56
|
+
def softmax(scores):
|
|
57
|
+
m = max(scores.values()); ex = {k: math.exp(v - m) for k, v in scores.items()}; s = sum(ex.values())
|
|
58
|
+
return {k: v / s for k, v in ex.items()}
|
|
59
|
+
|
|
60
|
+
BUILD_START = re.compile(r"^\W*(please\s+|pls\s+|can you\s+please\s+)?(implement|fix|add|create|build|refactor|rename|install|deploy|run|write|update|remove|delete|make|set\s*up|change|migrate|upgrade|debug|wire|hook\s*up|integrate|optimi[sz]e|clean\s*up|move|replace|convert|scaffold|generate|bump|revert|start|restart|train|arregla|agrega|a[nñ]ade|crea|implementa|corrige|haz|cambia|elimina|instala|despliega)\b", re.I)
|
|
61
|
+
NOT_BUILD = re.compile(r"\?|\b(plan|planning|roadmap|architecture|design doc|proposal|propose|outline|compare|comparison|research|investigate|look\s*up|find out|pros and cons|trade-?offs?|options|don'?t (write|code|implement|change)|no code|without (coding|code|changing)|just (explain|tell|the plan)|sin c[oó]digo|explain)\b", re.I)
|
|
62
|
+
|
|
63
|
+
def rule(text):
|
|
64
|
+
"""High-precision imperative rule: a request that opens with an implementation verb and asks nothing else is build."""
|
|
65
|
+
t = str(text or '').strip()
|
|
66
|
+
if NOT_BUILD.search(t[:600]): return None
|
|
67
|
+
if BUILD_START.search(t): return 'build'
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
def predict(text, history='', weights=None):
|
|
71
|
+
"""Returns (label, probability, all probabilities)."""
|
|
72
|
+
ruled = rule(text)
|
|
73
|
+
if ruled: return ruled, 0.97, {lab: (0.97 if lab == ruled else 0.01) for lab in LABELS}
|
|
74
|
+
w = weights or load()
|
|
75
|
+
f = features(text, history)
|
|
76
|
+
probs = softmax({lab: sum(w[lab].get(k, 0.0) * v for k, v in f.items()) for lab in LABELS})
|
|
77
|
+
best = max(probs, key=probs.get)
|
|
78
|
+
return best, probs[best], probs
|