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.
Files changed (182) hide show
  1. package/README.md +12 -2
  2. package/bin/mlai.mjs +3 -0
  3. package/package.json +18 -3
  4. package/src/browser-setup.mjs +77 -0
  5. package/src/cli-ext.mjs +146 -0
  6. package/src/cli.mjs +534 -0
  7. package/src/cloud.mjs +29 -0
  8. package/src/completion.mjs +159 -0
  9. package/src/credentials.mjs +54 -0
  10. package/src/deploy.mjs +134 -0
  11. package/src/distribution.mjs +373 -0
  12. package/src/engine-key.mjs +4 -0
  13. package/src/engine.mjs +167 -0
  14. package/src/headless.mjs +196 -0
  15. package/src/home.mjs +22 -0
  16. package/src/host.mjs +123 -0
  17. package/src/local-models.mjs +64 -0
  18. package/src/modes.mjs +38 -0
  19. package/src/netbox.mjs +97 -0
  20. package/src/netjail.py +59 -0
  21. package/src/offline.mjs +98 -0
  22. package/src/parity.mjs +86 -0
  23. package/src/project.mjs +68 -0
  24. package/src/relay.mjs +140 -0
  25. package/src/render.mjs +73 -0
  26. package/src/restricted.mjs +47 -0
  27. package/src/review.mjs +70 -0
  28. package/src/runner.mjs +127 -0
  29. package/src/runtime.mjs +75 -0
  30. package/src/sandbox.mjs +135 -0
  31. package/src/sdk.mjs +11 -0
  32. package/src/server.mjs +110 -0
  33. package/src/session.mjs +290 -0
  34. package/src/settings.mjs +135 -0
  35. package/src/shared-data.mjs +3 -0
  36. package/src/tui/acp.mjs +145 -0
  37. package/src/tui/agents-cli.mjs +114 -0
  38. package/src/tui/agents-local.mjs +65 -0
  39. package/src/tui/ansi.mjs +123 -0
  40. package/src/tui/app.mjs +710 -0
  41. package/src/tui/approval.mjs +88 -0
  42. package/src/tui/bg.mjs +172 -0
  43. package/src/tui/bgterm.mjs +79 -0
  44. package/src/tui/chat.mjs +230 -0
  45. package/src/tui/clipboard.mjs +74 -0
  46. package/src/tui/cloud-cli.mjs +57 -0
  47. package/src/tui/cloud-run.mjs +123 -0
  48. package/src/tui/cmd-agents.mjs +130 -0
  49. package/src/tui/cmd-auto-review.mjs +94 -0
  50. package/src/tui/cmd-cloud.mjs +17 -0
  51. package/src/tui/cmd-config.mjs +104 -0
  52. package/src/tui/cmd-core.mjs +160 -0
  53. package/src/tui/cmd-distribution.mjs +15 -0
  54. package/src/tui/cmd-ecosystem.mjs +169 -0
  55. package/src/tui/cmd-extensibility.mjs +333 -0
  56. package/src/tui/cmd-remote.mjs +18 -0
  57. package/src/tui/cmd-review.mjs +58 -0
  58. package/src/tui/cmd-session-extra.mjs +152 -0
  59. package/src/tui/cmd-tui.mjs +200 -0
  60. package/src/tui/commands.mjs +160 -0
  61. package/src/tui/custom-commands.mjs +98 -0
  62. package/src/tui/diff.mjs +60 -0
  63. package/src/tui/editor.mjs +190 -0
  64. package/src/tui/ext-state.mjs +16 -0
  65. package/src/tui/extensions-local.mjs +140 -0
  66. package/src/tui/files.mjs +72 -0
  67. package/src/tui/handoff.mjs +110 -0
  68. package/src/tui/import-setups.mjs +151 -0
  69. package/src/tui/init.mjs +104 -0
  70. package/src/tui/keymap.mjs +70 -0
  71. package/src/tui/keys.mjs +101 -0
  72. package/src/tui/loop.mjs +75 -0
  73. package/src/tui/markdown.mjs +118 -0
  74. package/src/tui/mcp-config.mjs +225 -0
  75. package/src/tui/mcp-oauth.mjs +162 -0
  76. package/src/tui/permissions.mjs +189 -0
  77. package/src/tui/plain.mjs +32 -0
  78. package/src/tui/plugins-local.mjs +103 -0
  79. package/src/tui/remote.mjs +125 -0
  80. package/src/tui/review-cli.mjs +332 -0
  81. package/src/tui/review-github.mjs +59 -0
  82. package/src/tui/screen.mjs +60 -0
  83. package/src/tui/session-ops.mjs +104 -0
  84. package/src/tui/skills-local.mjs +92 -0
  85. package/src/tui/snapshots.mjs +87 -0
  86. package/src/tui/statusline.mjs +98 -0
  87. package/src/tui/transcript.mjs +116 -0
  88. package/src/two-words.mjs +36 -0
  89. package/src/wakeups.mjs +53 -0
  90. package/src/winenv.mjs +94 -0
  91. package/src/winsandbox.py +351 -0
  92. package/src/workspace-api.mjs +621 -0
  93. package/src/worktree.mjs +128 -0
  94. package/vendor/client-sdk/controller.cjs +115 -0
  95. package/vendor/client-sdk/files.cjs +38 -0
  96. package/vendor/client-sdk/index.cjs +133 -0
  97. package/vendor/client-sdk/login.cjs +52 -0
  98. package/vendor/client-sdk/updates.cjs +41 -0
  99. package/vendor/cloud-cli/mlai.mjs +394 -0
  100. package/worker/architecture_parse.cjs +23 -0
  101. package/worker/architecture_worker.py +394 -0
  102. package/worker/ask_first.py +96 -0
  103. package/worker/attachment_reader.py +66 -0
  104. package/worker/background_jobs.py +111 -0
  105. package/worker/brief_questions.py +56 -0
  106. package/worker/browser_local.py +49 -0
  107. package/worker/browser_pane.py +89 -0
  108. package/worker/browser_tool.py +101 -0
  109. package/worker/build_planner.py +187 -0
  110. package/worker/chat_fork.py +277 -0
  111. package/worker/checkpoints.py +133 -0
  112. package/worker/cloud_pty.py +351 -0
  113. package/worker/command_policy.py +39 -0
  114. package/worker/command_safety.py +717 -0
  115. package/worker/computer_card.sh +23 -0
  116. package/worker/computer_setup.sh +86 -0
  117. package/worker/computer_use.py +221 -0
  118. package/worker/connector_search.py +43 -0
  119. package/worker/context_manager.py +60 -0
  120. package/worker/conversation.py +144 -0
  121. package/worker/deploy_pack.py +116 -0
  122. package/worker/design_director.py +240 -0
  123. package/worker/dev_jobs.py +166 -0
  124. package/worker/edit_guard.py +99 -0
  125. package/worker/env_setup.py +129 -0
  126. package/worker/evidence.py +109 -0
  127. package/worker/fast_search.py +24 -0
  128. package/worker/git_sync.py +333 -0
  129. package/worker/goals.py +156 -0
  130. package/worker/handover.py +98 -0
  131. package/worker/harness_memory.py +194 -0
  132. package/worker/image_generation.py +173 -0
  133. package/worker/intelligence.py +149 -0
  134. package/worker/intent_model.py +78 -0
  135. package/worker/intent_weights.json +1 -0
  136. package/worker/ios_simulator.py +87 -0
  137. package/worker/kimi_bridge.py +997 -0
  138. package/worker/kimi_compact.py +93 -0
  139. package/worker/kimi_gates.py +304 -0
  140. package/worker/kimi_hook.py +617 -0
  141. package/worker/lifecycle.py +95 -0
  142. package/worker/lsp.py +77 -0
  143. package/worker/mcp_local.py +293 -0
  144. package/worker/memory.py +99 -0
  145. package/worker/mlai_auto_review.py +177 -0
  146. package/worker/mlai_hooks.py +966 -0
  147. package/worker/mlai_mcp.py +441 -0
  148. package/worker/mlai_permissions.py +283 -0
  149. package/worker/model_stream.py +75 -0
  150. package/worker/nested_repos.py +76 -0
  151. package/worker/offline_guard.py +17 -0
  152. package/worker/preview.py +806 -0
  153. package/worker/proc_watch.py +124 -0
  154. package/worker/project_context.py +72 -0
  155. package/worker/project_rules.py +99 -0
  156. package/worker/quality.py +180 -0
  157. package/worker/reply_language.py +56 -0
  158. package/worker/repo_hygiene.py +132 -0
  159. package/worker/repo_memory.py +101 -0
  160. package/worker/repo_policy.py +269 -0
  161. package/worker/roles.json +3173 -0
  162. package/worker/roles.py +303 -0
  163. package/worker/runner.py +1795 -0
  164. package/worker/runtime_control.py +205 -0
  165. package/worker/secret_scan.py +168 -0
  166. package/worker/session_hub.py +80 -0
  167. package/worker/skill_library.py +129 -0
  168. package/worker/skill_pack.py +533 -0
  169. package/worker/subagents.py +91 -0
  170. package/worker/task_controller.py +139 -0
  171. package/worker/task_skills.py +159 -0
  172. package/worker/team_checkpoint.py +33 -0
  173. package/worker/token_count.py +32 -0
  174. package/worker/tool_catalog.py +38 -0
  175. package/worker/upload_storage.py +531 -0
  176. package/worker/verification.py +725 -0
  177. package/worker/vision.py +84 -0
  178. package/worker/wakeups.py +63 -0
  179. package/worker/web_tools.py +203 -0
  180. package/worker/winproc.py +135 -0
  181. package/worker/work_ledger.py +117 -0
  182. package/worker/worktrees.py +79 -0
@@ -0,0 +1,283 @@
1
+ """Permission rules for both engines (built-in runner and the Kimi bridge), set with /permissions in the CLI.
2
+
3
+ request.json `extensions.permissions` = {"allow": [...], "deny": [...], "ask": [...], "bypass": false}
4
+
5
+ Rules (the same syntax other coding CLIs use):
6
+ Bash every shell command
7
+ Bash(npm test) exactly this command
8
+ Bash(npm test:*) this command and anything after it (word boundary): npm test, npm test -- --watch
9
+ Bash(git * main) a glob over the whole command
10
+ Edit(src/**) file edits (Edit, Write, MultiEdit, edit_file, write_file) matching a project glob
11
+ Read(.env*) file reads (Read, Grep, Glob, read_file, list_files, search_text)
12
+ WebFetch(domain:x.com) fetching x.com or any subdomain
13
+ WebSearch web searches
14
+ mcp__github every tool of the MCP server "github"; mcp__github__create_issue one tool
15
+ Connector(gmail_send) a connected-app tool by name
16
+ Agent starting helper agents
17
+
18
+ Paths: `src/**` and `./src/**` are relative to the project, a bare name without a slash (`*.pem`, `.env`) matches at
19
+ any depth, `/x` is relative to the project too, `//abs/path` is absolute and `~/` is the home folder.
20
+
21
+ Decisions, strongest first:
22
+ deny -> the call never runs, in every mode, Auto included. Edit and Read deny rules also refuse shell commands
23
+ that name a matching path.
24
+ ask -> the user is asked first, even in Auto mode or for commands the engine would run without asking.
25
+ allow -> the call runs without a prompt. A compound shell command is allowed only when every segment matches an
26
+ allow rule, and never when it writes through a shell redirection.
27
+ `bypass` (--dangerously-skip-permissions) approves every prompt; deny rules, hard-deny rules and the credential
28
+ block still apply.
29
+ """
30
+ import fnmatch, json, os, re, sys, time, urllib.parse
31
+ from pathlib import Path
32
+
33
+ ROOT = Path(os.getenv('MINI_ROOT', '/vercel/sandbox/.mini'))
34
+ REPO = os.getenv('MINI_REPO', '/vercel/sandbox/repo')
35
+ MAX_RULES = 300
36
+ RULE = re.compile(r'^\s*([A-Za-z][A-Za-z0-9_-]*)\s*(?:\((.*)\))?\s*$', re.S)
37
+ ALIASES = {'bash': 'Bash', 'shell': 'Bash', 'edit': 'Edit', 'write': 'Edit', 'multiedit': 'Edit', 'notebookedit': 'Edit',
38
+ 'read': 'Read', 'grep': 'Read', 'glob': 'Read', 'ls': 'Read', 'webfetch': 'WebFetch', 'fetch': 'WebFetch',
39
+ 'websearch': 'WebSearch', 'connector': 'Connector', 'agent': 'Agent', 'task': 'Agent'}
40
+ EDIT_TOOLS = ('Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'edit_file', 'write_file', 'agent_integrate', 'skill_create')
41
+ READ_TOOLS = ('Read', 'Grep', 'Glob', 'LS', 'read_file', 'read_files', 'parallel_reads', 'list_files', 'search_text', 'context_read')
42
+ FETCH_TOOLS = ('web_fetch', 'FetchURL', 'WebFetch', 'mcp__mlai__web_fetch')
43
+ SEARCH_TOOLS = ('web_search', 'SearchWeb', 'WebSearch', 'mcp__mlai__web_search')
44
+ SHELL_TOOLS = ('run_command', 'Bash', 'shell', 'verify')
45
+ AGENT_TOOLS = ('Agent', 'AgentSwarm', 'subagents', 'delegate_changes')
46
+ HARMLESS_REDIRECT = re.compile(r'\s*(?:\d*>&\d+|&>\s*/dev/null|\d*>>?\s*/dev/null)')
47
+ WRITE_REDIRECT = re.compile(r'>|\btee\b')
48
+
49
+
50
+ def parse(rule):
51
+ """'Bash(npm test:*)' -> ('Bash', 'npm test:*'); unknown names keep their spelling (MCP tools). None if invalid."""
52
+ if not isinstance(rule, str) or not rule.strip() or len(rule) > 500: return None
53
+ m = RULE.match(rule)
54
+ if not m: return None
55
+ name, spec = m.group(1), m.group(2)
56
+ if name.lower().startswith('mcp__'): return ('mcp', name[5:] + ('__' + spec if spec else ''))
57
+ tool = ALIASES.get(name.lower())
58
+ if not tool: return None
59
+ spec = spec.strip() if isinstance(spec, str) else None
60
+ if spec in ('', '*', '**'): spec = None
61
+ if tool == 'WebFetch' and spec and not spec.startswith('domain:'): spec = 'domain:' + (urllib.parse.urlparse(spec).hostname or spec)
62
+ return (tool, spec)
63
+
64
+
65
+ def config(raw):
66
+ """Clean {'allow','deny','ask','bypass'} from request.extensions.permissions (invalid rules are dropped)."""
67
+ raw = raw if isinstance(raw, dict) else {}
68
+ out = {'bypass': raw.get('bypass') is True}
69
+ for k in ('allow', 'deny', 'ask'):
70
+ rules = []
71
+ for r in (raw.get(k) if isinstance(raw.get(k), list) else [])[:MAX_RULES]:
72
+ p = parse(r)
73
+ if p and r not in [x[0] for x in rules]: rules.append((r.strip(), p))
74
+ out[k] = rules
75
+ return out
76
+
77
+
78
+ def active(perms):
79
+ return bool(perms and (perms.get('bypass') or perms.get('allow') or perms.get('deny') or perms.get('ask')))
80
+
81
+
82
+ # ------------------------------------------------------------------ what a tool call touches
83
+ def subjects(tool, args, command=None, paths=None):
84
+ """[(kind, value)] for one call: ('Bash', segment-joined command), ('Edit'|'Read', path), ('WebFetch', url),
85
+ ('WebSearch', query), ('mcp', 'server__tool'), ('Connector', name), ('Agent', '')."""
86
+ tool = str(tool or ''); args = args if isinstance(args, dict) else {}
87
+ paths = [p for p in ([paths] if isinstance(paths, str) else list(paths or [])) if p]
88
+ if tool in SHELL_TOOLS or (command and tool not in EDIT_TOOLS + READ_TOOLS):
89
+ c = command if command is not None else args.get('command')
90
+ return [('Bash', str(c))] if isinstance(c, str) and c.strip() else []
91
+ if tool in EDIT_TOOLS: return [('Edit', p) for p in paths]
92
+ if tool in READ_TOOLS: return [('Read', p) for p in paths] or [('Read', '.')]
93
+ if tool in FETCH_TOOLS:
94
+ urls = [args['url']] if isinstance(args.get('url'), str) else []
95
+ urls += [u for u in args.get('urls') or [] if isinstance(u, str)] if isinstance(args.get('urls'), list) else []
96
+ return [('WebFetch', u) for u in urls[:20]]
97
+ if tool in SEARCH_TOOLS: return [('WebSearch', str(args.get('query') or ''))]
98
+ if tool in AGENT_TOOLS: return [('Agent', '')]
99
+ if tool == 'mcp': # the runner's workspace tool for the user's MCP servers; listing tools is a read
100
+ if args.get('action') == 'list' or not args.get('tool'): return []
101
+ return [('mcp', str(args.get('server') or '') + '__' + str(args.get('tool')))]
102
+ if tool.startswith('connector:'): return [('Connector', tool[10:])]
103
+ if tool.startswith('mcp__') and not tool.startswith('mcp__mlai__'): return [('mcp', tool[5:])]
104
+ return []
105
+
106
+
107
+ # ------------------------------------------------------------------ matching
108
+ def _norm(s): return ' '.join(str(s).split())
109
+
110
+
111
+ def _segments(command):
112
+ try:
113
+ from mlai_hooks import segments
114
+ return segments(command)
115
+ except Exception:
116
+ return [s.strip() for s in re.split(r'&&|\|\||;|\n|\|', str(command)) if s.strip()]
117
+
118
+
119
+ def command_match(command, spec):
120
+ """One command (or segment) against a Bash spec."""
121
+ c = _norm(command)
122
+ if spec is None: return True
123
+ s = _norm(spec)
124
+ if s.endswith(':*'):
125
+ prefix = s[:-2].rstrip()
126
+ return c == prefix or c.startswith(prefix + ' ')
127
+ if any(ch in s for ch in '*?['): return fnmatch.fnmatchcase(c, s)
128
+ return c == s
129
+
130
+
131
+ def path_globs(spec):
132
+ """Rule path -> patterns for mlai_hooks.path_match (repo-relative or absolute)."""
133
+ s = str(spec or '').strip()
134
+ if not s: return []
135
+ if s.startswith('//'): base = [s[1:]]
136
+ elif s.startswith('~'): base = [s]
137
+ elif s.startswith('/'): base = [s[1:]]
138
+ elif s.startswith('./'): base = [s[2:]]
139
+ elif '/' not in s.rstrip('/'): base = [s.rstrip('/'), '**/' + s.rstrip('/')]
140
+ else: base = [s.rstrip('/')]
141
+ out = []
142
+ for b in base:
143
+ out.append(b)
144
+ if not b.endswith('**'): out.append(b + '/**') # a folder rule covers what is inside it
145
+ return out
146
+
147
+
148
+ def path_hit(path, spec, repo=None):
149
+ try:
150
+ from mlai_hooks import path_match
151
+ return bool(path_match(path, path_globs(spec), repo or REPO))
152
+ except Exception:
153
+ return any(fnmatch.fnmatchcase(str(path), g) for g in path_globs(spec))
154
+
155
+
156
+ def host_hit(url, spec):
157
+ if not spec: return True
158
+ want = spec[7:].lower().strip().lstrip('.') if spec.startswith('domain:') else spec.lower()
159
+ try: host = (urllib.parse.urlparse(url if '//' in str(url) else 'https://' + str(url)).hostname or '').lower()
160
+ except ValueError: return False
161
+ if want.startswith('*.'): want = want[2:]
162
+ return bool(host) and (host == want or host.endswith('.' + want))
163
+
164
+
165
+ def mcp_hit(name, spec):
166
+ name = str(name)
167
+ if spec.endswith('__*'): spec = spec[:-3]
168
+ return name == spec or name.startswith(spec + '__') or fnmatch.fnmatchcase(name, spec)
169
+
170
+
171
+ def rule_hit(kind, value, parsed, repo=None, whole=False):
172
+ """Does one subject match one parsed rule. `whole`: shell commands match on any segment (deny/ask) instead of
173
+ all segments (allow), handled by the caller."""
174
+ tool, spec = parsed
175
+ if tool == 'mcp': return kind == 'mcp' and mcp_hit(value, spec)
176
+ if tool != kind: return False
177
+ if kind == 'Bash': return command_match(value, spec)
178
+ if kind in ('Edit', 'Read'): return spec is None or path_hit(value, spec, repo)
179
+ if kind == 'WebFetch': return host_hit(value, spec)
180
+ if kind == 'Connector': return spec is None or fnmatch.fnmatchcase(str(value), spec)
181
+ return spec is None # WebSearch, Agent
182
+
183
+
184
+ def _any(kind, value, rules, repo=None):
185
+ if kind == 'Bash':
186
+ segs = [value] + _segments(value)
187
+ for text, p in rules:
188
+ if p[0] == 'Bash' and any(command_match(s, p[1]) for s in segs): return text
189
+ if p[0] in ('Edit', 'Read') and p[1]: # deny/ask path rules also see paths named in commands
190
+ try:
191
+ from mlai_hooks import command_paths
192
+ if command_paths(value, path_globs(p[1]), repo or REPO)[0]: return text
193
+ except Exception: pass
194
+ return None
195
+ for text, p in rules:
196
+ if rule_hit(kind, value, p, repo): return text
197
+ return None
198
+
199
+
200
+ def _all_allowed(kind, value, rules, repo=None):
201
+ if kind == 'Bash':
202
+ every = next((text for text, p in rules if p == ('Bash', None)), None)
203
+ if every: return every
204
+ value = HARMLESS_REDIRECT.sub('', str(value)) # 2>&1 and >/dev/null write nothing
205
+ if WRITE_REDIRECT.search(value): return None
206
+ segs = _segments(value) or [value]
207
+ hits = []
208
+ for s in segs:
209
+ hit = next((text for text, p in rules if p[0] == 'Bash' and command_match(s, p[1])), None)
210
+ if not hit: return None
211
+ hits.append(hit)
212
+ return hits[0]
213
+ return next((text for text, p in rules if rule_hit(kind, value, p, repo)), None)
214
+
215
+
216
+ def decide(perms, subs, repo=None):
217
+ """('deny'|'ask'|'allow', rule) or (None, None)."""
218
+ if not perms or not subs: return None, None
219
+ for kind, value in subs:
220
+ hit = _any(kind, value, perms.get('deny') or [], repo)
221
+ if hit: return 'deny', hit
222
+ for kind, value in subs:
223
+ hit = _any(kind, value, perms.get('ask') or [], repo)
224
+ if hit: return 'ask', hit
225
+ allow = perms.get('allow') or []
226
+ if allow:
227
+ hits = [_all_allowed(kind, value, allow, repo) for kind, value in subs]
228
+ if all(hits): return 'allow', hits[0]
229
+ return None, None
230
+
231
+
232
+ def describe(subs):
233
+ kind, value = subs[0]
234
+ if kind == 'Bash': return str(value)[:6000]
235
+ if kind == 'mcp': return 'MCP tool ' + str(value).replace('__', ' ', 1)
236
+ label = {'Edit': 'Edit ', 'Read': 'Read ', 'WebFetch': 'Fetch ', 'WebSearch': 'Search the web: ', 'Connector': 'Connected tool: ', 'Agent': 'Start a helper agent'}[kind]
237
+ return label + ', '.join(str(v) for _k, v in subs[:5])[:6000]
238
+
239
+
240
+ def deny_reason(rule): return 'Blocked by your permission rule "' + rule + '" (deny). Choose another approach, or ask the user to change the rule with /permissions.'
241
+
242
+
243
+ # ------------------------------------------------------------------ asking (ask rules)
244
+ def ask_user(description, rule, root=None, timeout=600, reason=None):
245
+ """Ask the user directly (approval card kind "permission"). True when approved."""
246
+ root = Path(root or ROOT); ident = os.urandom(8).hex()
247
+ pending = {'id': ident, 'kind': 'command', 'effect': 'permission', 'rule': rule[:200],
248
+ 'reason': reason or ('Your permission rule "' + rule[:200] + '" asks before this runs'), 'command': description[:20000]}
249
+ tmp = root / 'pending.json.tmp'; tmp.write_text(json.dumps(pending)); tmp.replace(root / 'pending.json')
250
+ try:
251
+ with (root / 'events.jsonl').open('a') as f: f.write(json.dumps({'type': 'approval', 'time': time.time(), **pending}) + '\n')
252
+ except OSError: pass
253
+ decision = root / ('decision-' + ident); deadline = time.monotonic() + timeout
254
+ try:
255
+ while not decision.exists():
256
+ if (root / 'cancel').exists() or time.monotonic() > deadline: return False
257
+ time.sleep(0.2)
258
+ return decision.read_text().strip() in ('approve', 'approve_all')
259
+ finally:
260
+ decision.unlink(missing_ok=True); (root / 'pending.json').unlink(missing_ok=True)
261
+
262
+
263
+ def guidance(perms):
264
+ if not active(perms): return ''
265
+ parts = []
266
+ for k, label in (('deny', 'never allowed'), ('ask', 'the user is asked first'), ('allow', 'run without asking')):
267
+ if perms.get(k): parts.append(label + ': ' + ', '.join(t for t, _p in perms[k][:20]))
268
+ text = 'Permission rules set by the user (' + '; '.join(parts) + ').' if parts else ''
269
+ if perms.get('bypass'): text += ' Prompts are skipped for this session; deny rules still apply.'
270
+ return text.strip()
271
+
272
+
273
+ def main(argv):
274
+ """python3 mlai_permissions.py check (stdin {"rules": {...}, "tool": ..., "args": {...}, "command": ...})"""
275
+ msg = json.loads(sys.stdin.read() or '{}')
276
+ perms = config(msg.get('rules'))
277
+ subs = subjects(msg.get('tool'), msg.get('args'), msg.get('command'), msg.get('paths'))
278
+ verdict, rule = decide(perms, subs, msg.get('repo'))
279
+ print(json.dumps({'decision': verdict, 'rule': rule, 'subjects': subs}))
280
+
281
+
282
+ if __name__ == '__main__':
283
+ main(sys.argv[1:])
@@ -0,0 +1,75 @@
1
+ """OpenAI-compatible SSE assembly. Partial tool arguments are never executable."""
2
+ import json,queue,threading,time,urllib.request
3
+
4
+ def read_stream(response,on_text):
5
+ content=[];calls={};usage={};finished=False;total=0;reason=None
6
+ for raw in response:
7
+ total+=len(raw)
8
+ if total>4000000 or len(raw)>500000:raise ValueError('Model stream exceeded size limit')
9
+ line=raw.decode('utf-8').strip()
10
+ if not line or line.startswith(':') or not line.startswith('data:'):continue
11
+ payload=line[5:].strip()
12
+ if payload=='[DONE]':finished=True;break
13
+ chunk=json.loads(payload)
14
+ if chunk.get('error'):raise ValueError('Provider stream returned an error')
15
+ if isinstance(chunk.get('usage'),dict):usage=chunk['usage']
16
+ for choice in chunk.get('choices',[]):
17
+ if choice.get('index',0)!=0:continue
18
+ if choice.get('finish_reason'):reason=choice['finish_reason']
19
+ delta=choice.get('delta',{})
20
+ text=delta.get('content')
21
+ if isinstance(text,str):content.append(text);on_text(text)
22
+ # Deliberately discard reasoning_content and other hidden reasoning fields.
23
+ for item in delta.get('tool_calls',[]):
24
+ index=item.get('index',0)
25
+ if type(index)!=int or not 0<=index<8:raise ValueError('Invalid streamed tool index')
26
+ call=calls.setdefault(index,{'id':'','type':'function','function':{'name':'','arguments':''}})
27
+ if item.get('id'):call['id']=item['id']
28
+ for key in ('name','arguments'):
29
+ fragment=item.get('function',{}).get(key)
30
+ if isinstance(fragment,str):call['function'][key]+=fragment
31
+ if not finished or reason not in ('stop','tool_calls'):raise ValueError('Incomplete model stream; no actions were executed')
32
+ return {'choices':[{'message':{'content':''.join(content),'tool_calls':[calls[i] for i in sorted(calls)]},'finish_reason':reason}],'usage':usage}
33
+
34
+ def request_stream(request,cancelled,on_progress,timeout=240):
35
+ events=queue.Queue(maxsize=128);stop=threading.Event();response_holder=[]
36
+ def send(kind,value):
37
+ while not stop.is_set():
38
+ try:events.put((kind,value),timeout=.1);return
39
+ except queue.Full:pass
40
+ def fetch():
41
+ try:
42
+ with urllib.request.urlopen(request,timeout=timeout) as response:
43
+ response_holder.append(response)
44
+ # Some providers ignore stream=true. Accept a complete JSON response honestly.
45
+ if 'text/event-stream' not in response.headers.get('Content-Type',''):
46
+ raw=response.read(4000001)
47
+ if len(raw)>4000000:raise ValueError('Model response exceeded size limit')
48
+ result=json.loads(raw)
49
+ else:result=read_stream(response,lambda text:send('text',text))
50
+ send('result',result)
51
+ except Exception as exc:send('error',exc)
52
+ threading.Thread(target=fetch,daemon=True).start()
53
+ start=time.monotonic();last=0;parts=[];first=None
54
+ try:
55
+ while True:
56
+ cancelled();now=time.monotonic()
57
+ if now-start>timeout:raise TimeoutError('Model stream timed out')
58
+ try:kind,value=events.get(timeout=.1)
59
+ except queue.Empty:
60
+ if now-last>=2:
61
+ on_progress(''.join(parts),now-start,first);last=now
62
+ continue
63
+ if kind=='text':
64
+ if first is None:first=time.monotonic()-start
65
+ parts.append(value)
66
+ if now-last>=.5:on_progress(''.join(parts),now-start,first);last=now
67
+ elif kind=='error':raise value
68
+ else:
69
+ on_progress(''.join(parts),time.monotonic()-start,first)
70
+ return value
71
+ finally:
72
+ stop.set()
73
+ # Close a live transport on a daemon thread so cancellation never waits on socket I/O.
74
+ if response_holder:
75
+ threading.Thread(target=response_holder[0].close,daemon=True).start()
@@ -0,0 +1,76 @@
1
+ """Repair nested git repositories that have no commits.
2
+
3
+ Scaffolders such as `forge init`, `cargo new` or `git init` inside the project
4
+ create `<dir>/.git` with no commits. Git cannot index that folder ("unable to
5
+ index file 'contracts/'" or "does not have a commit checked out"), so every
6
+ `git add -A` fails: task checkpoints, step snapshots and GitHub sync all break.
7
+
8
+ An empty nested repository holds no history, so its `.git` folder is moved
9
+ (never deleted) into the parent's `.git/mini-nested-git/` and the files become ordinary project
10
+ files. Nested repositories that do have commits are left untouched.
11
+
12
+ CLI: python3 nested_repos.py <repo> [backup_dir] -> prints one moved path per line.
13
+ """
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+
21
+ SKIP = {'.git', 'node_modules', '.next', '.venv', 'venv', '__pycache__', '.turbo', '.vercel', 'dist', 'build', 'target', '.cache'}
22
+ MAX_DIRS = 20000
23
+
24
+
25
+ def _has_commit(path):
26
+ r = subprocess.run(['git', 'rev-parse', '-q', '--verify', 'HEAD'], cwd=path, capture_output=True, text=True, timeout=15,
27
+ env={**os.environ, 'GIT_DIR': str(Path(path) / '.git'), 'GIT_WORK_TREE': str(path)})
28
+ return r.returncode == 0
29
+
30
+
31
+ def _submodule_paths(repo):
32
+ r = subprocess.run(['git', 'config', '--file', '.gitmodules', '--get-regexp', r'\.path$'], cwd=repo, capture_output=True, text=True, timeout=15)
33
+ return {line.split(' ', 1)[1].strip().strip('/') for line in r.stdout.splitlines() if ' ' in line}
34
+
35
+
36
+ def empty_nested_repos(repo):
37
+ """Relative paths of folders inside `repo` that contain a `.git` folder with no commits."""
38
+ repo = Path(repo)
39
+ subs = _submodule_paths(repo) if (repo / '.gitmodules').exists() else set()
40
+ found, seen = [], 0
41
+ for root, dirs, _files in os.walk(repo):
42
+ seen += 1
43
+ if seen > MAX_DIRS:
44
+ break
45
+ here = Path(root)
46
+ if here != repo and (here / '.git').is_dir():
47
+ rel = here.relative_to(repo).as_posix()
48
+ if rel not in subs and not _has_commit(here):
49
+ found.append(rel)
50
+ dirs[:] = [] # never look inside another repository
51
+ continue
52
+ dirs[:] = [d for d in dirs if d not in SKIP]
53
+ return found
54
+
55
+
56
+ def absorb(repo, backup=None):
57
+ """Move the `.git` folder of each empty nested repository into `backup`. Returns the moved relative paths."""
58
+ repo = Path(repo)
59
+ backup = Path(backup) if backup else repo / '.git' / 'mini-nested-git'
60
+ moved = []
61
+ for rel in empty_nested_repos(repo):
62
+ target = backup / (rel.replace('/', '__') + '-' + str(int(time.time() * 1000)))
63
+ target.parent.mkdir(parents=True, exist_ok=True)
64
+ try:
65
+ shutil.move(str(repo / rel / '.git'), str(target))
66
+ moved.append(rel)
67
+ except OSError:
68
+ continue
69
+ return moved
70
+
71
+
72
+ if __name__ == '__main__':
73
+ if len(sys.argv) < 2:
74
+ sys.exit('usage: nested_repos.py <repo> [backup_dir]')
75
+ for path in absorb(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None):
76
+ print(path)
@@ -0,0 +1,17 @@
1
+ """Features that need ML AI Code's servers, refused cleanly when a laptop run is offline (MINI_OFFLINE=1, set by
2
+ apps/laptop/src/offline.mjs). The task keeps going; the agent is told to continue without the feature."""
3
+ import os
4
+
5
+ FEATURES = {'images': 'Image generation', 'research': 'Web research', 'connectors': 'Connected apps', 'deploy': 'Deploys'}
6
+
7
+
8
+ def offline():
9
+ return os.getenv('MINI_OFFLINE') == '1'
10
+
11
+
12
+ def message(feature):
13
+ return FEATURES.get(feature, 'This feature') + ' is not available offline. Continue the task without it and mention what was skipped; do not retry it.'
14
+
15
+
16
+ def check(feature):
17
+ if offline(): raise ValueError(message(feature))