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,966 @@
|
|
|
1
|
+
"""Hooks, hard-deny rules and credential blocking for both engines (built-in runner and the Kimi bridge).
|
|
2
|
+
|
|
3
|
+
Hooks come from three places, merged in this order:
|
|
4
|
+
- account and project settings (Settings > Hooks), sent by the server in request.json `extensions.hooks`
|
|
5
|
+
- enabled plugins, also in `extensions.hooks` with source "plugin:<id>"
|
|
6
|
+
- the repository file .mlai/hooks.json (reviewed like code). On This Mac it runs only when the user turned on
|
|
7
|
+
"Run repository hooks on This Mac" (`extensions.localRepoHooks`); in the cloud sandbox it always runs.
|
|
8
|
+
|
|
9
|
+
.mlai/hooks.json:
|
|
10
|
+
{
|
|
11
|
+
"version": 1,
|
|
12
|
+
"hooks": [
|
|
13
|
+
{"name": "Lint on edit", "event": "after_edit", "matcher": "*.ts|*.tsx", "type": "command",
|
|
14
|
+
"command": "npx --no-install eslint \"$MLAI_HOOK_PATH\"", "blocking": true, "timeout": 60},
|
|
15
|
+
{"name": "No lockfile edits", "event": "before_tool", "matcher": "edit", "type": "command",
|
|
16
|
+
"command": "case \"$MLAI_HOOK_PATH\" in *lock*) echo 'Lockfiles change through the package manager' >&2; exit 2;; esac"},
|
|
17
|
+
{"name": "Notify", "event": "run_end", "type": "webhook", "url": "https://hooks.example.com/mlai", "secret": "HOOK_SECRET"}
|
|
18
|
+
],
|
|
19
|
+
"deny": {"commands": ["terraform apply*"], "paths": ["infra/prod/**"], "hosts": ["*.internal.example.com"]}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
Events: before_tool, after_tool, before_command, after_edit, run_end, approval.
|
|
23
|
+
`matcher` (globs, `|` separated) is checked against: the tool (before_tool/after_tool: canonical name such as shell,
|
|
24
|
+
edit, read, web, agent, connector:<name>, or the engine's own tool name), the command (before_command), the edited
|
|
25
|
+
path (after_edit) or the approval kind (approval: command, edit, integration, plan, scope, ...). run_end ignores it.
|
|
26
|
+
|
|
27
|
+
Command hooks get the event JSON on stdin and MLAI_HOOK_* variables. Exit 2 blocks with stderr as the reason; stdout
|
|
28
|
+
may also be JSON {"decision": "block"|"allow", "reason": "..."}. Webhooks receive the same JSON as a POST (signed with
|
|
29
|
+
X-MLAI-Signature: sha256=<hmac> when `secret` names a Vault secret) and may answer with the same decision JSON.
|
|
30
|
+
Blocking means: before_* -> the call does not run; after_* -> the reason is fed back to the agent; run_end -> the
|
|
31
|
+
agent keeps working (at most twice per run); approval -> the request is denied. "allow" on an approval skips the
|
|
32
|
+
prompt, but only for hooks from account or project settings, never from the repository file or a plugin.
|
|
33
|
+
Hook failures (crash, timeout, unreachable URL) never block unless the hook sets "onError": "block".
|
|
34
|
+
|
|
35
|
+
Hard-deny rules (commands, paths, hosts) apply in every mode, Auto included, to every engine and helper agent.
|
|
36
|
+
Credential blocking is always on: commands that read credential stores or dump the environment never run.
|
|
37
|
+
|
|
38
|
+
CLI: python3 mlai_hooks.py show | validate [file] | fire (JSON on stdout)
|
|
39
|
+
"""
|
|
40
|
+
import fnmatch, hashlib, hmac, ipaddress, json, os, re, shlex, socket, subprocess, sys, threading, time, urllib.request, urllib.error, urllib.parse
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
|
|
43
|
+
ROOT = Path(os.getenv('MINI_ROOT', '/vercel/sandbox/.mini'))
|
|
44
|
+
REPO = os.getenv('MINI_REPO', '/vercel/sandbox/repo')
|
|
45
|
+
EVENTS = ('before_tool', 'after_tool', 'before_command', 'after_edit', 'run_end', 'approval')
|
|
46
|
+
TRUSTED = ('account', 'project', 'local') # local: the user's own CLI settings on this computer
|
|
47
|
+
MAX_HOOKS = 40
|
|
48
|
+
MAX_RUN_END_BLOCKS = 2
|
|
49
|
+
FILE = '.mlai/hooks.json'
|
|
50
|
+
_ID = re.compile(r'^[a-z0-9][a-z0-9-]{0,59}$')
|
|
51
|
+
_VAULT_NAME = re.compile(r'^[A-Z][A-Z0-9_]{1,63}$')
|
|
52
|
+
|
|
53
|
+
# ------------------------------------------------------------------ credential blocking (always on)
|
|
54
|
+
CREDENTIAL_PATHS = ['~/.ssh/**', '~/.aws/**', '~/.gnupg/**', '~/.config/gcloud/**', '~/.kube/**', '~/.docker/config.json',
|
|
55
|
+
'~/.azure/**', '~/.netrc', '~/.npmrc', '~/.pypirc', '~/.git-credentials', '~/.config/gh/**', '~/.config/hub',
|
|
56
|
+
'~/Library/Keychains/**', '~/.vault-token', '~/.config/op/**', '~/.terraform.d/credentials.tfrc.json',
|
|
57
|
+
'~/.cargo/credentials', '~/.cargo/credentials.toml', '~/.gem/credentials', '~/.config/doctl/**', '~/.oci/**',
|
|
58
|
+
'~/.mlai/auth.json', '~/.mlai/.device-token', '~/.mlai/vault/**', '/proc/*/environ', '/proc/self/environ']
|
|
59
|
+
CREDENTIAL_COMMANDS = ['gh auth token*', 'gh auth status --show-token*', 'gh auth status -t*', 'gcloud auth print-access-token*',
|
|
60
|
+
'gcloud auth print-identity-token*', 'gcloud auth application-default print-access-token*',
|
|
61
|
+
'aws configure get *', 'aws configure export-credentials*', 'az account get-access-token*',
|
|
62
|
+
'security find-generic-password*', 'security find-internet-password*', 'security dump-keychain*',
|
|
63
|
+
'security export*', 'git credential fill*', 'git credential-osxkeychain*', 'git credential-store*',
|
|
64
|
+
'git config --get-regexp *credential*', 'op read *', 'op item get *', 'vault print token*', 'cat /proc/*/environ*']
|
|
65
|
+
# Whole-environment dumps: refused only as a complete segment (`env FOO=1 cmd`, `set -e` and `printenv PATH` still run).
|
|
66
|
+
ENV_DUMPS = ('printenv', 'env', 'export', 'export -p', 'declare -x', 'declare -px', 'declare -p', 'set', 'compgen -e', 'typeset -x')
|
|
67
|
+
CREDENTIAL_REASON = ('Blocked: this command reads stored credentials or dumps the environment, which agent commands never do. '
|
|
68
|
+
'Use a secret the user shared through the Vault by its environment variable name instead (for example "$GITHUB_TOKEN" inside the command).')
|
|
69
|
+
# Environment names that look like credentials; hook commands never receive them (Vault secrets are passed explicitly).
|
|
70
|
+
SECRET_ENV = re.compile(r'(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIAL|SESSION|COOKIE|AUTH)', re.I)
|
|
71
|
+
SAFE_ENV = ('PATH', 'HOME', 'LANG', 'LC_ALL', 'TMPDIR', 'TERM', 'SHELL', 'USER', 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy',
|
|
72
|
+
'https_proxy', 'no_proxy', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'npm_config_cache', 'XDG_CACHE_HOME', 'PNPM_HOME', 'COREPACK_HOME')
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def clip(v, n): return str(v if v is not None else '')[:n]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ------------------------------------------------------------------ normalization (mirrors lib/hooks.ts)
|
|
79
|
+
def _globs(v):
|
|
80
|
+
if isinstance(v, list): v = '|'.join(str(x) for x in v if isinstance(x, (str, int)))
|
|
81
|
+
return [p.strip() for p in str(v or '').split('|') if p.strip()][:20]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _strs(v, limit=100, each=300):
|
|
85
|
+
return [str(x).strip()[:each] for x in v if isinstance(x, (str, int)) and str(x).strip()][:limit] if isinstance(v, list) else []
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def is_local_host(host):
|
|
89
|
+
return (host or '').lower() in ('localhost', '127.0.0.1', '::1', '[::1]')
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def normalize_hook(raw, source='account', errors=None, index=0):
|
|
93
|
+
"""A clean hook dict, or None (with a plain-English error) when it cannot run."""
|
|
94
|
+
errors = errors if errors is not None else []
|
|
95
|
+
label = 'Hook ' + str(index + 1)
|
|
96
|
+
if not isinstance(raw, dict): errors.append(label + ' must be an object'); return None
|
|
97
|
+
name = ' '.join(str(raw.get('name') or '').split())[:80]
|
|
98
|
+
label = name or label
|
|
99
|
+
event = raw.get('event')
|
|
100
|
+
if event not in EVENTS: errors.append(label + ': event must be one of ' + ', '.join(EVENTS)); return None
|
|
101
|
+
kind = raw.get('type') or ('webhook' if raw.get('url') else 'command')
|
|
102
|
+
if kind not in ('command', 'webhook'): errors.append(label + ': type must be "command" or "webhook"'); return None
|
|
103
|
+
hook = {'id': str(raw.get('id')) if isinstance(raw.get('id'), str) and _ID.match(raw.get('id')) else hashlib.sha1((source + json.dumps(raw, sort_keys=True, default=str)).encode()).hexdigest()[:12],
|
|
104
|
+
'name': name or (event.replace('_', ' ').capitalize() + ' ' + kind), 'event': event, 'type': kind, 'matcher': '|'.join(_globs(raw.get('matcher'))),
|
|
105
|
+
'blocking': raw.get('blocking') is not False, 'enabled': raw.get('enabled') is not False, 'source': str(source)[:80],
|
|
106
|
+
'onError': 'block' if raw.get('onError') == 'block' else 'allow'}
|
|
107
|
+
try: timeout = int(raw.get('timeout') or 30)
|
|
108
|
+
except (TypeError, ValueError): timeout = 30
|
|
109
|
+
hook['timeout'] = max(1, min(120, timeout))
|
|
110
|
+
if kind == 'command':
|
|
111
|
+
command = raw.get('command')
|
|
112
|
+
if not isinstance(command, str) or not command.strip() or len(command) > 4000: errors.append(label + ': add a command (up to 4,000 characters)'); return None
|
|
113
|
+
hook['command'] = command.strip()
|
|
114
|
+
else:
|
|
115
|
+
url = raw.get('url')
|
|
116
|
+
try: u = urllib.parse.urlparse(str(url or ''))
|
|
117
|
+
except ValueError: u = None
|
|
118
|
+
if not u or u.scheme not in ('https', 'http') or not u.hostname or u.username or u.password:
|
|
119
|
+
errors.append(label + ': add an https:// webhook URL without credentials'); return None
|
|
120
|
+
if u.scheme == 'http' and not is_local_host(u.hostname): errors.append(label + ': webhooks use https:// (http:// only for localhost)'); return None
|
|
121
|
+
if any(re.search(r'token|secret|key|password|signature', k, re.I) for k in urllib.parse.parse_qs(u.query)): errors.append(label + ': put credentials in the signing secret, not the URL'); return None
|
|
122
|
+
hook['url'] = str(url)[:2000]
|
|
123
|
+
secret = raw.get('secret')
|
|
124
|
+
if secret not in (None, ''):
|
|
125
|
+
if not isinstance(secret, str) or not _VAULT_NAME.match(secret): errors.append(label + ': secret must be the NAME of a Vault secret (for example HOOK_SECRET), never the value'); return None
|
|
126
|
+
hook['secret'] = secret
|
|
127
|
+
if raw.get('plugin') and isinstance(raw.get('plugin'), str): hook['plugin'] = raw['plugin'][:60]
|
|
128
|
+
return hook
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def normalize_deny(raw, errors=None):
|
|
132
|
+
errors = errors if errors is not None else []
|
|
133
|
+
if raw in (None, ''): return {'commands': [], 'paths': [], 'hosts': []}
|
|
134
|
+
if not isinstance(raw, dict): errors.append('deny must be an object with commands, paths and hosts lists'); return {'commands': [], 'paths': [], 'hosts': []}
|
|
135
|
+
for k in raw:
|
|
136
|
+
if k not in ('commands', 'paths', 'hosts'): errors.append('Unknown deny list "' + str(k) + '" (use commands, paths, hosts)')
|
|
137
|
+
hosts = []
|
|
138
|
+
for h in _strs(raw.get('hosts'), 100, 200):
|
|
139
|
+
h = h.lower().strip().rstrip('.')
|
|
140
|
+
if '/' in h or ' ' in h: errors.append('Host "' + h + '" should be a host name or pattern like *.example.com'); continue
|
|
141
|
+
hosts.append(h)
|
|
142
|
+
return {'commands': _strs(raw.get('commands')), 'paths': _strs(raw.get('paths')), 'hosts': hosts}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def merge_deny(*lists):
|
|
146
|
+
out = {'commands': [], 'paths': [], 'hosts': []}
|
|
147
|
+
for d in lists:
|
|
148
|
+
for k in out:
|
|
149
|
+
for v in (d or {}).get(k) or []:
|
|
150
|
+
if v not in out[k]: out[k].append(v)
|
|
151
|
+
return out
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def parse_file(text):
|
|
155
|
+
"""Parse .mlai/hooks.json text -> (hooks, deny, errors)."""
|
|
156
|
+
errors = []
|
|
157
|
+
if len(text) > 100000: return [], merge_deny(), ['hooks.json is over 100,000 characters']
|
|
158
|
+
try: data = json.loads(text) if text.strip() else {}
|
|
159
|
+
except ValueError as e: return [], merge_deny(), ['hooks.json is not valid JSON: ' + str(e)[:200]]
|
|
160
|
+
if not isinstance(data, dict): return [], merge_deny(), ['hooks.json must be an object with a "hooks" list']
|
|
161
|
+
for k in data:
|
|
162
|
+
if k not in ('version', 'hooks', 'deny', '$schema'): errors.append('Unknown key "' + str(k) + '"')
|
|
163
|
+
raw = data.get('hooks') or []
|
|
164
|
+
if not isinstance(raw, list): errors.append('"hooks" must be a list'); raw = []
|
|
165
|
+
if len(raw) > MAX_HOOKS: errors.append('At most ' + str(MAX_HOOKS) + ' hooks'); raw = raw[:MAX_HOOKS]
|
|
166
|
+
hooks = [h for h in (normalize_hook(r, 'repo', errors, i) for i, r in enumerate(raw)) if h]
|
|
167
|
+
return hooks, normalize_deny(data.get('deny'), errors), errors
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# Network off (CLI /sandbox network off): web tools, remote hosts in commands and commands that need the network.
|
|
171
|
+
OFFLINE_REASON = ('Network access is off for this session, so this was not run. Work offline (local files, installed packages, '
|
|
172
|
+
'localhost), or ask the user to turn it on with /sandbox network on.')
|
|
173
|
+
OFFLINE_COMMANDS = ['npm install*', 'npm i', 'npm i *', 'npm ci*', 'npm add*', 'npm update*', 'npm publish*', 'npx *', 'pnpm install*', 'pnpm add*', 'pnpm i',
|
|
174
|
+
'pnpm i *', 'pnpm dlx*', 'yarn add*', 'yarn install*', 'yarn', 'bun install*', 'bun add*', 'pip install*', 'pip3 install*',
|
|
175
|
+
'python -m pip install*', 'python3 -m pip install*', 'uv pip install*', 'uv add*', 'uv sync*', 'poetry install*', 'poetry add*',
|
|
176
|
+
'cargo install*', 'cargo add*', 'cargo fetch*', 'go get*', 'go install*', 'go mod download*', 'gem install*', 'bundle install*',
|
|
177
|
+
'brew install*', 'brew upgrade*', 'apt install*', 'apt-get install*', 'git push*', 'git pull*', 'git fetch*', 'git clone*',
|
|
178
|
+
'git ls-remote*', 'git submodule update*', 'ssh *', 'scp *', 'rsync *', 'gh *', 'docker pull*', 'docker push*']
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# Restricted mode (CLI --restricted, for shared computers): no shell commands, file tools inside the project only.
|
|
182
|
+
RESTRICTED_COMMAND = ('Restricted mode is on for this computer, so shell commands are off and this was not run. Use the file '
|
|
183
|
+
'tools, and tell the user which command they could run themselves.')
|
|
184
|
+
RESTRICTED_PATH = 'Restricted mode is on for this computer: file tools work inside the project only, so {path} was not touched.'
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def outside_repo(p, repo=None):
|
|
188
|
+
"""True when a tool path resolves (symlinks included) outside the project folder."""
|
|
189
|
+
base = os.path.realpath(str(repo or REPO))
|
|
190
|
+
s = os.path.expanduser(str(p))
|
|
191
|
+
full = os.path.realpath(s if os.path.isabs(s) else os.path.join(base, s))
|
|
192
|
+
return not (full == base or full.startswith(base.rstrip(os.sep) + os.sep))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def restricted_block(tool, command, path, cfg, root=None):
|
|
196
|
+
if not cfg.get('restricted'): return None
|
|
197
|
+
if command or canonical(tool) in ('shell', 'agent'):
|
|
198
|
+
deny_event('restricted', RESTRICTED_COMMAND, root, **({'command': command} if command else {})); return RESTRICTED_COMMAND
|
|
199
|
+
for p in ([path] if isinstance(path, str) else list(path or [])):
|
|
200
|
+
if p and outside_repo(p):
|
|
201
|
+
reason = RESTRICTED_PATH.format(path=clip(p, 200)); deny_event('restricted', reason, root, path=p); return reason
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# ------------------------------------------------------------------ configuration for this run
|
|
206
|
+
_CACHE = {}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _request(root):
|
|
210
|
+
try: return json.loads((Path(root) / 'request.json').read_text())
|
|
211
|
+
except (OSError, ValueError): return {}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _repo_file(repo):
|
|
215
|
+
f = Path(repo) / FILE
|
|
216
|
+
if not f.is_file() or f.is_symlink(): return None
|
|
217
|
+
try: return f.read_text(errors='replace')[:100001]
|
|
218
|
+
except OSError: return None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def settings(root=None, repo=None, config=None):
|
|
222
|
+
"""{'hooks': [...], 'deny': {...}, 'errors': [...], 'repoSkipped': bool, 'laptop': bool} for this run (cached on file mtimes)."""
|
|
223
|
+
root, repo = Path(root or ROOT), str(repo or REPO)
|
|
224
|
+
try: stamp = (Path(repo) / FILE).stat().st_mtime
|
|
225
|
+
except OSError: stamp = 0
|
|
226
|
+
try: rstamp = (root / 'request.json').stat().st_mtime
|
|
227
|
+
except OSError: rstamp = 0
|
|
228
|
+
key = (str(root), repo, stamp, rstamp, id(config))
|
|
229
|
+
if key in _CACHE: return _CACHE[key]
|
|
230
|
+
config = config if config is not None else _request(root)
|
|
231
|
+
ext = config.get('extensions') if isinstance(config.get('extensions'), dict) else {}
|
|
232
|
+
laptop = bool(config.get('laptop')) or os.getenv('MINI_LAPTOP') == '1'
|
|
233
|
+
errors, hooks = [], []
|
|
234
|
+
for i, raw in enumerate((ext.get('hooks') if isinstance(ext.get('hooks'), list) else [])[:MAX_HOOKS * 2]):
|
|
235
|
+
src = raw.get('source') if isinstance(raw, dict) and isinstance(raw.get('source'), str) else 'account'
|
|
236
|
+
if src == 'repo': src = 'account' # the server never sends repo hooks; refuse to let a payload claim it
|
|
237
|
+
h = normalize_hook(raw, src, errors, i)
|
|
238
|
+
if h: hooks.append(h)
|
|
239
|
+
text = _repo_file(repo)
|
|
240
|
+
repo_hooks, repo_deny, repo_errors = parse_file(text) if text is not None else ([], merge_deny(), [])
|
|
241
|
+
skipped = bool(repo_hooks) and laptop and ext.get('localRepoHooks') is not True
|
|
242
|
+
if not skipped: hooks += repo_hooks
|
|
243
|
+
deny = merge_deny(normalize_deny(ext.get('hardDeny')), repo_deny) # the repo file can only add deny rules
|
|
244
|
+
out = {'hooks': [h for h in hooks if h['enabled']], 'deny': deny, 'errors': errors + repo_errors, 'repoSkipped': skipped, 'laptop': laptop,
|
|
245
|
+
'vault': {}, 'plugins': {p['id']: p for p in (ext.get('plugins') or []) if isinstance(p, dict) and isinstance(p.get('id'), str)},
|
|
246
|
+
'files': ext.get('files') if isinstance(ext.get('files'), dict) else {}, 'perms': _perms_config(ext.get('permissions')),
|
|
247
|
+
'offline': isinstance(ext.get('network'), dict) and ext['network'].get('enabled') is False,
|
|
248
|
+
'restricted': isinstance(ext.get('restricted'), dict) and ext['restricted'].get('enabled') is True}
|
|
249
|
+
_CACHE.clear(); _CACHE[key] = out
|
|
250
|
+
return out
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ------------------------------------------------------------------ permission rules (worker/mlai_permissions.py)
|
|
254
|
+
# The decision for the call in progress: before() sets it, approval() uses it (same process in both engines).
|
|
255
|
+
_PERM = {'grant': None, 'rule': None}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _perms_config(raw):
|
|
259
|
+
try:
|
|
260
|
+
import mlai_permissions
|
|
261
|
+
return mlai_permissions.config(raw)
|
|
262
|
+
except Exception: return {'bypass': False, 'allow': [], 'deny': [], 'ask': []}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def permission(tool, args, command=None, path=None, cfg=None, root=None, ask=True, mode=None):
|
|
266
|
+
"""Permission rules for one call: returns a block message or None, and records an allow/ask grant for approval().
|
|
267
|
+
Tools of the user's own MCP servers ask in Guided mode unless an allow rule covers them (they can change anything)."""
|
|
268
|
+
cfg = cfg or settings(root)
|
|
269
|
+
perms = cfg.get('perms') or {}
|
|
270
|
+
_PERM.update(grant=None, rule=None)
|
|
271
|
+
import mlai_permissions as mp
|
|
272
|
+
subs = mp.subjects(tool, args, command, path)
|
|
273
|
+
mcp_call = bool(subs) and subs[0][0] == 'mcp'
|
|
274
|
+
if not mp.active(perms) and not mcp_call: return None
|
|
275
|
+
if perms.get('bypass'): _PERM.update(grant='bypass')
|
|
276
|
+
verdict, rule = mp.decide(perms, subs, REPO)
|
|
277
|
+
guided = mode not in ('auto', 'plan') and not (Path(root or ROOT) / 'kimi-approve-all').exists()
|
|
278
|
+
if verdict is None and mcp_call and guided and ask and not perms.get('bypass'):
|
|
279
|
+
if not mp.ask_user(mp.describe(subs), 'mcp__' + subs[0][1], root or ROOT, reason='MCP tools ask before they run in Guided mode'):
|
|
280
|
+
return 'The user did not approve this MCP tool call. Choose another approach or explain what you need.'
|
|
281
|
+
_PERM.update(grant='asked', rule='MCP tools ask in Guided mode')
|
|
282
|
+
return None
|
|
283
|
+
if verdict == 'deny':
|
|
284
|
+
reason = mp.deny_reason(rule)
|
|
285
|
+
emit('policy', root, rule=str(rule)[:200], decision='deny', content=reason[:600], permission=True, command=clip(command or mp.describe(subs), 300))
|
|
286
|
+
return reason
|
|
287
|
+
if verdict == 'ask' and ask and not perms.get('bypass'):
|
|
288
|
+
if not mp.ask_user(mp.describe(subs), rule, root or ROOT):
|
|
289
|
+
return 'The user did not approve this call (permission rule "' + rule + '" asks first). Choose another approach or explain what you need.'
|
|
290
|
+
_PERM.update(grant='asked', rule=rule)
|
|
291
|
+
elif verdict == 'allow':
|
|
292
|
+
_PERM.update(grant='allow', rule=rule)
|
|
293
|
+
return None
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def wants(event, cfg=None):
|
|
297
|
+
cfg = cfg or settings()
|
|
298
|
+
return any(h['event'] == event for h in cfg['hooks'])
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
# ------------------------------------------------------------------ matching
|
|
302
|
+
def _cmd_match(command, pat):
|
|
303
|
+
c = ' '.join(str(command).split()); p = ' '.join(str(pat).split())
|
|
304
|
+
return fnmatch.fnmatchcase(c, p) or (not any(ch in p for ch in '*?[') and (c == p or c.startswith(p + ' ')))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def segments(command):
|
|
308
|
+
"""Shell segments, including the bodies of $(...) and `...` and bash -c strings, so wrapping cannot hide a command."""
|
|
309
|
+
text = str(command or '')
|
|
310
|
+
inner = re.findall(r'\$\(([^()]*)\)', text) + re.findall(r'`([^`]*)`', text)
|
|
311
|
+
for m in re.finditer(r'\b(?:ba|z|da)?sh\s+-c\s+([\'"])(.*?)\1', text, re.S): inner.append(m.group(2))
|
|
312
|
+
parts = []
|
|
313
|
+
for chunk in [text] + inner:
|
|
314
|
+
for s in re.split(r'&&|\|\||;|\n|\|(?!\|)|&(?!&)', chunk):
|
|
315
|
+
s = s.strip().lstrip('(').rstrip(')').strip()
|
|
316
|
+
s = re.sub(r'^(?:sudo|command|exec|nohup|time|xargs)\s+', '', s)
|
|
317
|
+
s = re.sub(r'^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+', '', s) # FOO=1 cmd
|
|
318
|
+
if s: parts.append(s)
|
|
319
|
+
return parts
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def match_command(command, patterns):
|
|
323
|
+
whole = ' '.join(str(command).split())
|
|
324
|
+
segs = segments(command)
|
|
325
|
+
for pat in patterns:
|
|
326
|
+
if _cmd_match(whole, pat) or any(_cmd_match(s, pat) for s in segs): return pat
|
|
327
|
+
return None
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _expand(p):
|
|
331
|
+
p = str(p).replace('$HOME', '~').replace('${HOME}', '~')
|
|
332
|
+
return os.path.expanduser(p)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _glob_hit(c, q):
|
|
336
|
+
if fnmatch.fnmatchcase(c, q): return True
|
|
337
|
+
if q.endswith('/**') and (c == q[:-3] or c.startswith(q[:-2])): return True
|
|
338
|
+
if '/**/' in q and fnmatch.fnmatchcase(c, q.replace('/**/', '/')): return True
|
|
339
|
+
if q.startswith('**/') and (fnmatch.fnmatchcase(c, q[3:]) or fnmatch.fnmatchcase(os.path.basename(c), q[3:])): return True
|
|
340
|
+
return False
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def path_match(path, patterns, repo=None):
|
|
344
|
+
"""Glob match for repo-relative patterns (src/**, **/*.pem) and absolute or ~ patterns (~/.aws/**)."""
|
|
345
|
+
repo = os.path.normpath(str(repo or REPO))
|
|
346
|
+
raw = _expand(str(path or '').strip().strip('"\''))
|
|
347
|
+
if not raw: return None
|
|
348
|
+
absolute = os.path.normpath(raw if os.path.isabs(raw) else os.path.join(repo, raw))
|
|
349
|
+
rel = os.path.relpath(absolute, repo) if absolute == repo or absolute.startswith(repo + os.sep) else None
|
|
350
|
+
for pat in patterns:
|
|
351
|
+
q = os.path.normpath(_expand(pat)) + ('/**' if str(pat).endswith('/**') and not os.path.normpath(_expand(pat)).endswith('**') else '')
|
|
352
|
+
if os.path.isabs(q):
|
|
353
|
+
if _glob_hit(absolute, q): return pat
|
|
354
|
+
elif rel is not None and _glob_hit(rel, q[2:] if q.startswith('./') else q): return pat
|
|
355
|
+
return None
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _tokens(command):
|
|
359
|
+
try: toks = shlex.split(str(command), posix=True)
|
|
360
|
+
except ValueError: toks = str(command).split()
|
|
361
|
+
out = []
|
|
362
|
+
for t in toks + [w for t in toks if ' ' in t for w in t.split()]: # quoted strings (bash -c "...") are split too
|
|
363
|
+
for piece in re.split(r'[=<>]', t):
|
|
364
|
+
piece = piece.strip()
|
|
365
|
+
if piece: out.append(piece)
|
|
366
|
+
return out
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def command_paths(command, patterns, repo=None):
|
|
370
|
+
for tok in _tokens(command):
|
|
371
|
+
if '/' not in tok and '~' not in tok and '.' not in tok: continue
|
|
372
|
+
hit = path_match(tok, patterns, repo)
|
|
373
|
+
if hit: return hit, tok
|
|
374
|
+
return None, None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
HOST = re.compile(r'\b(?:https?|wss?|ftp|ssh|git)://(?:[^@/\s]+@)?(\[[0-9a-fA-F:]+\]|[A-Za-z0-9.-]+)', re.I)
|
|
378
|
+
SCP = re.compile(r'(?:^|\s)[A-Za-z0-9._-]+@([A-Za-z0-9.-]+\.[A-Za-z]{2,}):')
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def hosts_in(text):
|
|
382
|
+
found = [h.strip('[]').lower().rstrip('.') for h in HOST.findall(str(text))] + [h.lower() for h in SCP.findall(str(text))]
|
|
383
|
+
for tok in _tokens(text):
|
|
384
|
+
if re.fullmatch(r'[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+(?::\d+)?', tok) and not re.search(r'\.(?:js|ts|tsx|jsx|py|json|md|txt|sh|lock|yml|yaml|toml|css|html|log|csv)$', tok, re.I):
|
|
385
|
+
found.append(tok.split(':')[0].lower())
|
|
386
|
+
out = []
|
|
387
|
+
for h in found:
|
|
388
|
+
if h and h not in out: out.append(h)
|
|
389
|
+
return out
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def host_match(host, patterns):
|
|
393
|
+
host = str(host or '').lower().strip('[]').rstrip('.')
|
|
394
|
+
for pat in patterns:
|
|
395
|
+
p = pat.lower()
|
|
396
|
+
if host == p or fnmatch.fnmatchcase(host, p) or (p.startswith('*.') and host == p[2:]): return pat
|
|
397
|
+
if p.startswith('.') and host.endswith(p): return pat
|
|
398
|
+
try:
|
|
399
|
+
if '/' in p and ipaddress.ip_address(host) in ipaddress.ip_network(p, strict=False): return pat
|
|
400
|
+
except ValueError: pass
|
|
401
|
+
return None
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
# ------------------------------------------------------------------ hard deny + credential checks
|
|
405
|
+
def credential_reason(command, repo=None):
|
|
406
|
+
if match_command(command, CREDENTIAL_COMMANDS): return CREDENTIAL_REASON
|
|
407
|
+
if any(' '.join(seg.split()) in ENV_DUMPS for seg in segments(command)): return CREDENTIAL_REASON
|
|
408
|
+
hit, _tok = command_paths(command, CREDENTIAL_PATHS, repo)
|
|
409
|
+
if hit: return CREDENTIAL_REASON
|
|
410
|
+
if re.search(r'/proc/(?:\d+|self|\*)/environ', str(command)): return CREDENTIAL_REASON
|
|
411
|
+
return None
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def deny_command(command, cfg=None, repo=None):
|
|
415
|
+
"""(rule, reason) when the command may never run, else (None, None)."""
|
|
416
|
+
cfg = cfg or settings(repo=repo)
|
|
417
|
+
reason = credential_reason(command, repo)
|
|
418
|
+
if reason: return 'credentials', reason
|
|
419
|
+
d = cfg['deny']
|
|
420
|
+
pat = match_command(command, d['commands'])
|
|
421
|
+
if pat: return pat, 'Refused by a hard-deny rule ("' + pat + '"). This command never runs here, in any mode, including Auto. Use a different approach or ask the user.'
|
|
422
|
+
pat, tok = command_paths(command, d['paths'], repo)
|
|
423
|
+
if pat: return pat, 'Refused by a hard-deny rule: ' + tok + ' matches the protected path "' + pat + '", which agent commands never touch.'
|
|
424
|
+
for h in hosts_in(command):
|
|
425
|
+
pat = host_match(h, d['hosts'])
|
|
426
|
+
if pat: return pat, 'Refused by a hard-deny rule: ' + h + ' matches the blocked host "' + pat + '".'
|
|
427
|
+
if cfg.get('offline'):
|
|
428
|
+
urls = [h.strip('[]').lower() for h in HOST.findall(str(command))] + [h.lower() for h in SCP.findall(str(command))]
|
|
429
|
+
urls += [h for seg in segments(command) if re.match(r'(?:curl|wget|http|xh)\s', seg) for h in hosts_in(seg)] # curl example.com
|
|
430
|
+
remote = next((h for h in urls if not is_local_host(h) and h != '0.0.0.0'), None)
|
|
431
|
+
if remote or match_command(command, OFFLINE_COMMANDS): return 'network', OFFLINE_REASON
|
|
432
|
+
return None, None
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def deny_path(path, cfg=None, repo=None):
|
|
436
|
+
cfg = cfg or settings(repo=repo)
|
|
437
|
+
if path_match(path, CREDENTIAL_PATHS, repo): return 'credentials', 'Blocked: ' + str(path)[:200] + ' holds stored credentials, which agents never read or change.'
|
|
438
|
+
pat = path_match(path, cfg['deny']['paths'], repo)
|
|
439
|
+
if pat: return pat, 'Refused by a hard-deny rule: ' + str(path)[:200] + ' matches the protected path "' + pat + '". It is never read or changed here, in any mode.'
|
|
440
|
+
return None, None
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def deny_url(url, cfg=None):
|
|
444
|
+
cfg = cfg or settings()
|
|
445
|
+
try: host = urllib.parse.urlparse(str(url)).hostname or ''
|
|
446
|
+
except ValueError: host = ''
|
|
447
|
+
pat = host_match(host, cfg['deny']['hosts']) if host else None
|
|
448
|
+
if pat: return pat, 'Refused by a hard-deny rule: ' + host + ' matches the blocked host "' + pat + '".'
|
|
449
|
+
if cfg.get('offline') and host and not is_local_host(host): return 'network', OFFLINE_REASON
|
|
450
|
+
return None, None
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
# ------------------------------------------------------------------ events and payloads
|
|
454
|
+
def emit(kind, root=None, **data):
|
|
455
|
+
try:
|
|
456
|
+
with (Path(root or ROOT) / 'events.jsonl').open('a') as f: f.write(json.dumps({'type': kind, 'time': time.time(), **data}) + '\n')
|
|
457
|
+
except OSError: pass
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def deny_event(rule, reason, root=None, **data):
|
|
461
|
+
emit('policy', root, rule=str(rule)[:200], decision='deny', content=reason[:600], hardDeny=True, **{k: clip(v, 300) for k, v in data.items()})
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def canonical(name, args=None):
|
|
465
|
+
"""Engine-neutral tool names for matchers."""
|
|
466
|
+
n = str(name or '')
|
|
467
|
+
if n in ('run_command', 'Bash', 'shell', 'verify'): return 'shell'
|
|
468
|
+
if n in ('edit_file', 'Write', 'Edit', 'write_file', 'agent_integrate', 'skill_create'): return 'edit'
|
|
469
|
+
if n in ('read_file', 'read_files', 'parallel_reads', 'list_files', 'search_text', 'Read', 'Glob', 'Grep', 'context_read'): return 'read'
|
|
470
|
+
if n in ('web_search', 'web_fetch', 'FetchURL', 'SearchWeb', 'WebSearch', 'WebFetch'): return 'web'
|
|
471
|
+
if n in ('Agent', 'AgentSwarm', 'subagents', 'delegate_changes'): return 'agent'
|
|
472
|
+
if n.startswith('mcp__') and not n.startswith('mcp__mlai__'): return 'connector:' + n.split('__', 2)[-1]
|
|
473
|
+
if n.startswith('connector:'): return n
|
|
474
|
+
return n
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _match_hook(h, subject, extra=()):
|
|
478
|
+
pats = _globs(h.get('matcher'))
|
|
479
|
+
if not pats or h['event'] == 'run_end': return True
|
|
480
|
+
subjects = [str(s) for s in (subject,) + tuple(extra) if s]
|
|
481
|
+
for p in pats:
|
|
482
|
+
for s in subjects:
|
|
483
|
+
if h['event'] == 'before_command':
|
|
484
|
+
if match_command(s, [p]): return True
|
|
485
|
+
elif h['event'] == 'after_edit':
|
|
486
|
+
if path_match(s, [p]) or fnmatch.fnmatchcase(os.path.basename(s), p): return True
|
|
487
|
+
elif fnmatch.fnmatchcase(s, p): return True
|
|
488
|
+
return False
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _bounded(v, n=8000):
|
|
492
|
+
try: text = json.dumps(v, default=str)
|
|
493
|
+
except (TypeError, ValueError): text = json.dumps(str(v))
|
|
494
|
+
return v if len(text) <= n else {'truncated': True, 'preview': text[:n]}
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def payload(event, run=None, **data):
|
|
498
|
+
run = run or {}
|
|
499
|
+
out = {'event': event, 'time': time.time(), 'run': {'id': clip(run.get('runId'), 80), 'mode': clip(run.get('mode'), 20), 'task': clip(run.get('task'), 500),
|
|
500
|
+
'engine': 'cloud' if not run.get('laptop') else 'this-mac', 'subagent': bool(run.get('subagent'))},
|
|
501
|
+
'repo': str(REPO)}
|
|
502
|
+
for k, v in data.items():
|
|
503
|
+
if v is not None: out[k] = _bounded(v) if isinstance(v, (dict, list)) else clip(v, 8000)
|
|
504
|
+
return out
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
# ------------------------------------------------------------------ running hooks
|
|
508
|
+
def _vault():
|
|
509
|
+
try: raw = json.loads(os.environ.get('MINI_VAULT') or '{}')
|
|
510
|
+
except ValueError: return {}
|
|
511
|
+
return {k: v for k, v in raw.items() if isinstance(k, str) and _VAULT_NAME.match(k) and isinstance(v, str)} if isinstance(raw, dict) else {}
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _plugin_root(h, cfg, root):
|
|
515
|
+
pid = h.get('plugin') or (h['source'][7:] if h['source'].startswith('plugin:') else '')
|
|
516
|
+
if not pid or not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,59}', pid): return None
|
|
517
|
+
target = Path(root) / 'plugins' / pid
|
|
518
|
+
files = (cfg.get('files') or {}).get(pid) if isinstance(cfg.get('files'), dict) else None
|
|
519
|
+
if isinstance(files, dict):
|
|
520
|
+
stamp = hashlib.sha1(json.dumps(files, sort_keys=True).encode()).hexdigest()[:16]
|
|
521
|
+
marker = target / '.mlai-plugin-sha'
|
|
522
|
+
if not marker.is_file() or marker.read_text().strip() != stamp:
|
|
523
|
+
for rel, content in list(files.items())[:40]:
|
|
524
|
+
rel = str(rel).replace('\\', '/')
|
|
525
|
+
if not isinstance(content, str) or rel.startswith('/') or '..' in rel.split('/') or not re.fullmatch(r'[\w./-]{1,160}', rel): continue
|
|
526
|
+
p = target / rel; p.parent.mkdir(parents=True, exist_ok=True); p.write_text(content[:200000])
|
|
527
|
+
if rel.startswith(('scripts/', 'hooks/', 'bin/')) and rel.endswith(('.sh', '.py', '.mjs', '.js')): p.chmod(0o755)
|
|
528
|
+
target.mkdir(parents=True, exist_ok=True); marker.write_text(stamp)
|
|
529
|
+
return target
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def hook_env(h, data, cfg, root):
|
|
533
|
+
env = {k: v for k, v in os.environ.items() if k in SAFE_ENV or (k.startswith('LC_'))}
|
|
534
|
+
env.update({'MLAI_HOOK_EVENT': h['event'], 'MLAI_HOOK_NAME': h['name'][:80], 'MLAI_HOOK_SOURCE': h['source'],
|
|
535
|
+
'MLAI_HOOK_TOOL': clip((data.get('tool') or {}).get('canonical') if isinstance(data.get('tool'), dict) else '', 200),
|
|
536
|
+
'MLAI_HOOK_PATH': clip(data.get('path'), 1000), 'MLAI_HOOK_COMMAND': clip(data.get('command'), 4000), 'MINI_REPO': str(REPO)})
|
|
537
|
+
if h['source'] in TRUSTED: env.update(_vault()) # only the user's own settings hooks see Vault secrets
|
|
538
|
+
proot = _plugin_root(h, cfg, root)
|
|
539
|
+
if proot: env['MLAI_PLUGIN_ROOT'] = str(proot)
|
|
540
|
+
return env
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _decision(text):
|
|
544
|
+
text = (text or '').strip()
|
|
545
|
+
if not text.startswith('{'): return None, ''
|
|
546
|
+
try: d = json.loads(text.splitlines()[0] if text.count('\n') and not text.endswith('}') else text)
|
|
547
|
+
except ValueError: return None, ''
|
|
548
|
+
if not isinstance(d, dict): return None, ''
|
|
549
|
+
dec = str(d.get('decision') or '').lower()
|
|
550
|
+
dec = {'deny': 'block', 'reject': 'block', 'approve': 'allow'}.get(dec, dec)
|
|
551
|
+
return (dec if dec in ('block', 'allow') else None), clip(d.get('reason') or d.get('message'), 2000)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def run_command_hook(h, data, cfg, root):
|
|
555
|
+
env = hook_env(h, data, cfg, root)
|
|
556
|
+
try:
|
|
557
|
+
p = subprocess.run(['bash', '-c', h['command']], input=json.dumps(data), capture_output=True, text=True, cwd=str(REPO) if Path(REPO).is_dir() else None,
|
|
558
|
+
env=env, timeout=h['timeout'], start_new_session=True)
|
|
559
|
+
except subprocess.TimeoutExpired: return {'state': 'error', 'error': 'timed out after ' + str(h['timeout']) + ' s'}
|
|
560
|
+
except OSError as e: return {'state': 'error', 'error': str(e)[:200]}
|
|
561
|
+
out, err = (p.stdout or '')[-8000:], (p.stderr or '')[-4000:]
|
|
562
|
+
if p.returncode == 2: return {'state': 'block', 'reason': (err.strip() or out.strip() or 'Blocked by hook ' + h['name'])[:2000]}
|
|
563
|
+
dec, reason = _decision(out)
|
|
564
|
+
if p.returncode != 0: return {'state': 'error', 'error': ('exit ' + str(p.returncode) + ': ' + (err.strip() or out.strip())[:300]).strip()}
|
|
565
|
+
if dec: return {'state': dec, 'reason': reason, 'output': out[:2000]}
|
|
566
|
+
return {'state': 'ok', 'output': out.strip()[:2000]}
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
570
|
+
def redirect_request(self, *a, **k): return None
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _public(host, laptop):
|
|
574
|
+
if is_local_host(host): return laptop
|
|
575
|
+
try: infos = socket.getaddrinfo(host, None)
|
|
576
|
+
except OSError: return False
|
|
577
|
+
for info in infos:
|
|
578
|
+
ip = ipaddress.ip_address(info[4][0].split('%')[0])
|
|
579
|
+
if ip.is_link_local or ip.is_multicast or ip.is_unspecified or ip.is_reserved: return False
|
|
580
|
+
if (ip.is_private or ip.is_loopback) and not laptop: return False
|
|
581
|
+
return True
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def run_webhook(h, data, cfg, root):
|
|
585
|
+
url = h['url']; host = urllib.parse.urlparse(url).hostname or ''
|
|
586
|
+
pat, reason = deny_url(url, cfg)
|
|
587
|
+
if pat: return {'state': 'error', 'error': reason}
|
|
588
|
+
if not _public(host, cfg.get('laptop')): return {'state': 'error', 'error': 'private or reserved address refused for ' + host}
|
|
589
|
+
body = json.dumps(data).encode()
|
|
590
|
+
headers = {'Content-Type': 'application/json', 'User-Agent': 'ML-AI-Code-Hooks/1', 'X-MLAI-Event': h['event'], 'X-MLAI-Hook': h['id'],
|
|
591
|
+
'X-MLAI-Delivery': hashlib.sha1(body + str(time.time()).encode()).hexdigest()[:20]}
|
|
592
|
+
if h.get('secret'):
|
|
593
|
+
secret = _vault().get(h['secret'])
|
|
594
|
+
if not secret: return {'state': 'error', 'error': 'Vault secret ' + h['secret'] + ' is not shared with the agent'}
|
|
595
|
+
headers['X-MLAI-Signature'] = 'sha256=' + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
|
596
|
+
req = urllib.request.Request(url, data=body, headers=headers, method='POST')
|
|
597
|
+
try:
|
|
598
|
+
with urllib.request.build_opener(_NoRedirect).open(req, timeout=h['timeout']) as r:
|
|
599
|
+
text = r.read(64000).decode('utf-8', 'replace')
|
|
600
|
+
status = r.status
|
|
601
|
+
except urllib.error.HTTPError as e:
|
|
602
|
+
return {'state': 'error', 'error': 'HTTP ' + str(e.code)}
|
|
603
|
+
except (urllib.error.URLError, OSError, ValueError) as e:
|
|
604
|
+
return {'state': 'error', 'error': str(getattr(e, 'reason', e))[:200]}
|
|
605
|
+
if status >= 300: return {'state': 'error', 'error': 'HTTP ' + str(status)}
|
|
606
|
+
dec, reason = _decision(text)
|
|
607
|
+
return {'state': dec or 'ok', 'reason': reason, 'output': text[:2000]}
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def run_hook(h, data, cfg=None, root=None):
|
|
611
|
+
cfg = cfg or settings(root)
|
|
612
|
+
start = time.time()
|
|
613
|
+
result = (run_webhook if h['type'] == 'webhook' else run_command_hook)(h, data, cfg, root or ROOT)
|
|
614
|
+
result['seconds'] = round(time.time() - start, 2)
|
|
615
|
+
return result
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def fire_detached(h, data, root=None):
|
|
619
|
+
"""Non-blocking hooks run in a separate process so a slow notifier never holds up the agent."""
|
|
620
|
+
try:
|
|
621
|
+
p = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), 'fire'], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
622
|
+
start_new_session=True, env={**os.environ, 'MINI_ROOT': str(root or ROOT), 'MINI_REPO': str(REPO)})
|
|
623
|
+
p.stdin.write(json.dumps({'hook': h, 'payload': data}).encode()); p.stdin.close()
|
|
624
|
+
return True
|
|
625
|
+
except OSError: return False
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def dispatch(event, data, subject='', extra=(), cfg=None, root=None, wait=True):
|
|
629
|
+
"""Run matching hooks for one event. Returns {'decision': 'block'|'allow'|None, 'reason', 'hook'}.
|
|
630
|
+
The first blocking hook that blocks wins; 'allow' (approval only) counts from trusted sources."""
|
|
631
|
+
cfg = cfg or settings(root)
|
|
632
|
+
hooks = [h for h in cfg['hooks'] if h['event'] == event and _match_hook(h, subject, extra)]
|
|
633
|
+
allow = None
|
|
634
|
+
for h in hooks:
|
|
635
|
+
if not h['blocking'] and event != 'approval':
|
|
636
|
+
fire_detached(h, data, root); emit('hook', root, hook=h['name'], hookEvent=event, source=h['source'], decision='sent', content='Hook ' + h['name'] + ' notified')
|
|
637
|
+
continue
|
|
638
|
+
r = run_hook(h, data, cfg, root)
|
|
639
|
+
state = r.get('state')
|
|
640
|
+
if state == 'error':
|
|
641
|
+
emit('hook', root, hook=h['name'], hookEvent=event, source=h['source'], decision='error', content='Hook ' + h['name'] + ' failed: ' + clip(r.get('error'), 300))
|
|
642
|
+
if h['onError'] == 'block':
|
|
643
|
+
return {'decision': 'block', 'reason': 'Hook "' + h['name'] + '" could not run (' + clip(r.get('error'), 200) + ') and is set to block on errors.', 'hook': h}
|
|
644
|
+
continue
|
|
645
|
+
if state == 'block':
|
|
646
|
+
reason = r.get('reason') or ('Blocked by hook ' + h['name'])
|
|
647
|
+
emit('hook', root, hook=h['name'], hookEvent=event, source=h['source'], decision='block', content=reason[:600])
|
|
648
|
+
return {'decision': 'block', 'reason': reason, 'hook': h}
|
|
649
|
+
if state == 'allow' and event == 'approval' and h['source'] in TRUSTED and allow is None:
|
|
650
|
+
allow = {'decision': 'allow', 'reason': r.get('reason') or ('Approved by hook ' + h['name']), 'hook': h}
|
|
651
|
+
continue
|
|
652
|
+
emit('hook', root, hook=h['name'], hookEvent=event, source=h['source'], decision='ok', content='Hook ' + h['name'] + ' passed' + (': ' + clip(r.get('output'), 200) if r.get('output') else ''))
|
|
653
|
+
if allow: emit('hook', root, hook=allow['hook']['name'], hookEvent=event, source=allow['hook']['source'], decision='allow', content=allow['reason'][:600])
|
|
654
|
+
return allow or {'decision': None, 'reason': '', 'hook': None}
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def block_text(result, phase):
|
|
658
|
+
h = result.get('hook') or {}
|
|
659
|
+
who = 'Hook "' + h.get('name', 'hook') + '"' + (' (' + h['source'] + ')' if h.get('source') else '')
|
|
660
|
+
if phase == 'before': return who + ' blocked this call; it did not run. Reason: ' + result['reason'] + '\nAdjust your approach to satisfy the hook, or explain to the user why you cannot.'
|
|
661
|
+
if phase == 'after': return who + ' reported a problem after this step: ' + result['reason'] + '\nAddress it before continuing.'
|
|
662
|
+
if phase == 'run_end': return who + ' did not accept finishing yet: ' + result['reason'] + '\nFix this, verify, then finish again.'
|
|
663
|
+
return who + ' denied this request: ' + result['reason']
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
# ------------------------------------------------------------------ engine-neutral entry points
|
|
667
|
+
def before(tool, args, run=None, command=None, path=None, cfg=None, root=None):
|
|
668
|
+
"""Hard deny, credential block, then before_tool/before_command hooks. Returns a block message or None."""
|
|
669
|
+
cfg = cfg or settings(root)
|
|
670
|
+
blocked = restricted_block(tool, command, path, cfg, root)
|
|
671
|
+
if blocked: return blocked
|
|
672
|
+
if command:
|
|
673
|
+
rule, reason = deny_command(command, cfg)
|
|
674
|
+
if rule: deny_event(rule, reason, root, command=command); return reason
|
|
675
|
+
for p in ([path] if isinstance(path, str) else list(path or [])):
|
|
676
|
+
if not p: continue
|
|
677
|
+
rule, reason = deny_path(p, cfg)
|
|
678
|
+
if rule: deny_event(rule, reason, root, path=p); return reason
|
|
679
|
+
for u in _urls(args):
|
|
680
|
+
rule, reason = deny_url(u, cfg)
|
|
681
|
+
if rule: deny_event(rule, reason, root, url=u); return reason
|
|
682
|
+
if cfg.get('offline') and (canonical(tool) == 'web' or tool in ('mcp__mlai__web_search', 'mcp__mlai__web_fetch')): deny_event('network', OFFLINE_REASON, root); return OFFLINE_REASON
|
|
683
|
+
if cfg.get('perms') and (cfg['perms'].get('deny')):
|
|
684
|
+
blocked = permission(tool, args, command, path, cfg, root, ask=False)
|
|
685
|
+
if blocked: return blocked
|
|
686
|
+
name = canonical(tool)
|
|
687
|
+
if wants('before_tool', cfg):
|
|
688
|
+
r = dispatch('before_tool', payload('before_tool', run, tool={'name': tool, 'canonical': name, 'arguments': args}, command=command, path=_first(path)), name, (tool,), cfg, root)
|
|
689
|
+
if r['decision'] == 'block': return block_text(r, 'before')
|
|
690
|
+
if command and wants('before_command', cfg):
|
|
691
|
+
r = dispatch('before_command', payload('before_command', run, tool={'name': tool, 'canonical': name}, command=command), command, (), cfg, root)
|
|
692
|
+
if r['decision'] == 'block': return block_text(r, 'before')
|
|
693
|
+
blocked = permission(tool, args, command, path, cfg, root, mode=(run or {}).get('mode'))
|
|
694
|
+
if blocked or (run or {}).get('mode') != 'auto' or _PERM.get('grant') in ('allow', 'bypass'): return blocked
|
|
695
|
+
try: import mlai_auto_review
|
|
696
|
+
except ImportError: return None
|
|
697
|
+
return mlai_auto_review.gate(tool, args, command, path, run, root or ROOT, REPO) # auto mode: reviewer pass on risky actions
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
def after(tool, args, result, run=None, command=None, path=None, cfg=None, root=None):
|
|
701
|
+
"""after_tool and after_edit hooks. Returns feedback text for the agent or None."""
|
|
702
|
+
cfg = cfg or settings(root)
|
|
703
|
+
name = canonical(tool); notes = []
|
|
704
|
+
res = {'returncode': result.get('returncode'), 'output': clip(result.get('output'), 4000)} if isinstance(result, dict) else {'output': clip(result, 4000)}
|
|
705
|
+
if wants('after_tool', cfg):
|
|
706
|
+
r = dispatch('after_tool', payload('after_tool', run, tool={'name': tool, 'canonical': name, 'arguments': args}, command=command, path=_first(path), result=res), name, (tool,), cfg, root)
|
|
707
|
+
if r['decision'] == 'block': notes.append(block_text(r, 'after'))
|
|
708
|
+
if name == 'edit' and wants('after_edit', cfg) and not (isinstance(result, dict) and result.get('returncode')):
|
|
709
|
+
for p in ([path] if isinstance(path, str) else list(path or []))[:10]:
|
|
710
|
+
if not p: continue
|
|
711
|
+
r = dispatch('after_edit', payload('after_edit', run, tool={'name': tool, 'canonical': name}, path=p), p, (), cfg, root)
|
|
712
|
+
if r['decision'] == 'block': notes.append(block_text(r, 'after'))
|
|
713
|
+
return '\n'.join(notes) or None
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def run_end(run=None, summary='', cfg=None, root=None):
|
|
717
|
+
"""run_end hooks when the agent is about to finish. Returns a message that keeps it working, or None."""
|
|
718
|
+
cfg = cfg or settings(root); root = Path(root or ROOT)
|
|
719
|
+
if not wants('run_end', cfg): return None
|
|
720
|
+
count_file = root / 'hooks-run-end.json'
|
|
721
|
+
try: count = json.loads(count_file.read_text()).get(str((run or {}).get('runId') or ''), 0)
|
|
722
|
+
except (OSError, ValueError, AttributeError): count = 0
|
|
723
|
+
r = dispatch('run_end', payload('run_end', run, summary=clip(summary, 4000)), '', (), cfg, root)
|
|
724
|
+
if r['decision'] != 'block': return None
|
|
725
|
+
if count >= MAX_RUN_END_BLOCKS:
|
|
726
|
+
emit('hook', root, hook=r['hook']['name'], hookEvent='run_end', source=r['hook']['source'], decision='noted', content='Finished after ' + str(count) + ' hook reviews: ' + r['reason'][:400])
|
|
727
|
+
return None
|
|
728
|
+
try: count_file.write_text(json.dumps({str((run or {}).get('runId') or ''): count + 1}))
|
|
729
|
+
except OSError: pass
|
|
730
|
+
return block_text(r, 'run_end')
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def approval(request, run=None, cfg=None, root=None):
|
|
734
|
+
"""approval hooks for a pending request. Returns ('deny', message) | ('allow', reason) | (None, '')."""
|
|
735
|
+
cfg = cfg or settings(root)
|
|
736
|
+
if not isinstance(request, dict): return None, ''
|
|
737
|
+
grant = _PERM.get('grant')
|
|
738
|
+
if grant == 'bypass' or (cfg.get('perms') or {}).get('bypass'): return 'allow', 'Prompts are skipped for this session'
|
|
739
|
+
if grant in ('allow', 'asked') and request.get('kind') != 'operation':
|
|
740
|
+
emit('policy', root, rule=str(_PERM.get('rule'))[:200], decision='allow', permission=True, content='Allowed by your permission rule "' + str(_PERM.get('rule'))[:200] + '"')
|
|
741
|
+
return 'allow', 'Allowed by your permission rule "' + str(_PERM.get('rule')) + '"'
|
|
742
|
+
if not wants('approval', cfg): return None, ''
|
|
743
|
+
kind = str(request.get('kind') or ('edit' if str(request.get('command', '')).startswith(('Edit ', 'Write ')) else 'command'))
|
|
744
|
+
r = dispatch('approval', payload('approval', run, approval={'kind': kind, 'command': clip(request.get('command'), 6000), 'name': clip(request.get('name'), 200),
|
|
745
|
+
'connection': clip(request.get('connection'), 200), 'effect': clip(request.get('effect'), 40)}), kind, (str(request.get('name') or ''),), cfg, root)
|
|
746
|
+
if r['decision'] == 'block': return 'deny', block_text(r, 'approval')
|
|
747
|
+
if r['decision'] == 'allow': return 'allow', r['reason']
|
|
748
|
+
return None, ''
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def _first(path):
|
|
752
|
+
if isinstance(path, str): return path
|
|
753
|
+
for p in path or []: return p
|
|
754
|
+
return None
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _urls(args):
|
|
758
|
+
if not isinstance(args, dict): return []
|
|
759
|
+
out = [args['url']] if isinstance(args.get('url'), str) else []
|
|
760
|
+
if isinstance(args.get('urls'), list): out += [u for u in args['urls'] if isinstance(u, str)]
|
|
761
|
+
return out[:20]
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
def tool_paths(args):
|
|
765
|
+
if not isinstance(args, dict): return []
|
|
766
|
+
out = [str(args[k]) for k in ('path', 'file_path', 'filePath', 'target') if isinstance(args.get(k), str)]
|
|
767
|
+
for k in ('paths', 'files'):
|
|
768
|
+
for v in args.get(k) or [] if isinstance(args.get(k), list) else []:
|
|
769
|
+
if isinstance(v, str): out.append(v)
|
|
770
|
+
elif isinstance(v, dict) and isinstance(v.get('path'), str): out.append(v['path'])
|
|
771
|
+
return out[:20]
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
# ------------------------------------------------------------------ built-in runner (worker/runner.py)
|
|
775
|
+
class _Globals:
|
|
776
|
+
"""Attribute access over a module's globals() dict."""
|
|
777
|
+
def __init__(self, g): object.__setattr__(self, '_g', g)
|
|
778
|
+
def __getattr__(self, k):
|
|
779
|
+
try: return self._g[k]
|
|
780
|
+
except KeyError: raise AttributeError(k) from None
|
|
781
|
+
def __setattr__(self, k, v): self._g[k] = v
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def install_runner(module, env_cls):
|
|
785
|
+
"""Wrap Environment.execute and the pending-approval writer of the built-in runner. Hard-deny and credential checks
|
|
786
|
+
run at every depth (nested verify calls too); hooks run for top-level actions only. `module` may be the runner's
|
|
787
|
+
globals() (tests load runner.py under other names without registering it in sys.modules)."""
|
|
788
|
+
if isinstance(module, dict): module = _Globals(module)
|
|
789
|
+
inner_execute = env_cls.execute
|
|
790
|
+
inner_write = module.write
|
|
791
|
+
state = {'approval_note': None}
|
|
792
|
+
|
|
793
|
+
def run_info(self):
|
|
794
|
+
c = getattr(self, 'agent_config', {}) or {}
|
|
795
|
+
return {'runId': c.get('runId'), 'mode': getattr(self, 'mode', c.get('mode')), 'task': c.get('task'), 'laptop': c.get('laptop'), 'subagent': c.get('subagent')}
|
|
796
|
+
|
|
797
|
+
def describe(action):
|
|
798
|
+
kind = action.get('kind'); args = action.get('arguments') if isinstance(action.get('arguments'), dict) else {}
|
|
799
|
+
if kind == 'workspace':
|
|
800
|
+
name = str(action.get('name') or '')
|
|
801
|
+
command = args.get('command') if name == 'verify' and isinstance(args.get('command'), str) else None
|
|
802
|
+
return name, args, command, tool_paths(args)
|
|
803
|
+
if kind == 'integration': return 'connector:' + str(action.get('name') or ''), args, None, []
|
|
804
|
+
if kind == 'answer': return None, args, None, []
|
|
805
|
+
command = str(action.get('command') or '')
|
|
806
|
+
return ('run_command' if command.strip() else None), {'command': command}, command or None, []
|
|
807
|
+
|
|
808
|
+
def execute(self, action, **kwargs):
|
|
809
|
+
if not isinstance(action, dict): return inner_execute(self, action, **kwargs)
|
|
810
|
+
top = getattr(self, 'plan_depth', 0) == 0
|
|
811
|
+
try: cfg = settings()
|
|
812
|
+
except Exception: cfg = None # hooks never crash a run
|
|
813
|
+
tool, args, command, paths = describe(action)
|
|
814
|
+
finishing = action.get('kind') == 'answer' or str(action.get('command', '')).strip() == 'echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT'
|
|
815
|
+
if cfg and tool and not finishing:
|
|
816
|
+
if not top:
|
|
817
|
+
blocked = restricted_block(tool, command, paths, cfg)
|
|
818
|
+
if blocked: return {'returncode': 1, 'output': blocked, 'executed': False}
|
|
819
|
+
rule, reason = deny_command(command, cfg) if command else (None, None)
|
|
820
|
+
if rule: deny_event(rule, reason, command=command); return {'returncode': 1, 'output': reason, 'executed': False}
|
|
821
|
+
if cfg.get('perms') and cfg['perms'].get('deny'):
|
|
822
|
+
saved = dict(_PERM); blocked = permission(tool, args, command, paths, cfg, ask=False); _PERM.update(saved)
|
|
823
|
+
if blocked: return {'returncode': 1, 'output': blocked, 'executed': False}
|
|
824
|
+
else:
|
|
825
|
+
blocked = before(tool, args, run_info(self), command=command, path=paths, cfg=cfg)
|
|
826
|
+
if blocked: return {'returncode': 1, 'output': blocked, 'executed': False}
|
|
827
|
+
state['approval_note'] = None
|
|
828
|
+
try: result = inner_execute(self, action, **kwargs)
|
|
829
|
+
except Exception as exc:
|
|
830
|
+
if top: _PERM.update(grant=None, rule=None)
|
|
831
|
+
if cfg and top and finishing and type(exc).__name__ == 'Submitted':
|
|
832
|
+
summary = ''
|
|
833
|
+
try: summary = str(exc.args[0].get('content', ''))
|
|
834
|
+
except (IndexError, AttributeError): pass
|
|
835
|
+
note = run_end(run_info(self), summary, cfg)
|
|
836
|
+
if note: return {'returncode': 1, 'output': note}
|
|
837
|
+
raise
|
|
838
|
+
if top: _PERM.update(grant=None, rule=None) # a grant covers the approvals of this one call only
|
|
839
|
+
if cfg and top and tool and not finishing and isinstance(result, dict):
|
|
840
|
+
feedback = after(tool, args, result, run_info(self), command=command, path=paths, cfg=cfg)
|
|
841
|
+
if state['approval_note']: feedback = state['approval_note'] + ('\n' + feedback if feedback else '')
|
|
842
|
+
if feedback: result = dict(result, output=str(result.get('output', '')) + '\n' + feedback)
|
|
843
|
+
return result
|
|
844
|
+
|
|
845
|
+
def write(name, data):
|
|
846
|
+
# Plan reviews and auto-allowed calls are not approvals of an action, so hooks leave them to the user.
|
|
847
|
+
if name == 'pending.json' and isinstance(data, dict) and data.get('id') and not any(data.get(k) for k in ('plan', 'brief', 'autoAllowed', 'items')):
|
|
848
|
+
try: verdict, text = approval(data, {'runId': None, 'mode': None})
|
|
849
|
+
except Exception: verdict, text = None, ''
|
|
850
|
+
if verdict == 'deny':
|
|
851
|
+
state['approval_note'] = text; state['answered'] = str(data['id'])
|
|
852
|
+
(ROOT / ('decision-' + str(data['id']))).write_text('reject'); return
|
|
853
|
+
if verdict == 'allow':
|
|
854
|
+
state['answered'] = str(data['id'])
|
|
855
|
+
(ROOT / ('decision-' + str(data['id']))).write_text('approve'); return
|
|
856
|
+
return inner_write(name, data)
|
|
857
|
+
|
|
858
|
+
inner_event = getattr(module, 'event', None)
|
|
859
|
+
|
|
860
|
+
def event(event_type, **data):
|
|
861
|
+
# The runner announces every approval right after writing pending.json; one a rule or hook already answered
|
|
862
|
+
# is not shown to the user as a prompt.
|
|
863
|
+
if event_type == 'approval' and state.get('answered') and str(data.get('id')) == state['answered']:
|
|
864
|
+
state['answered'] = None; return None
|
|
865
|
+
return inner_event(event_type, **data)
|
|
866
|
+
|
|
867
|
+
inner_operation = getattr(module, 'approve_operation', None)
|
|
868
|
+
|
|
869
|
+
def approve_operation(root, mode, description, cancelled, emit_fn):
|
|
870
|
+
if mode not in ('plan', 'auto'):
|
|
871
|
+
try: verdict, text = approval({'id': 'operation', 'kind': 'operation', 'command': description})
|
|
872
|
+
except Exception: verdict, text = None, ''
|
|
873
|
+
if verdict == 'deny': raise ValueError(text)
|
|
874
|
+
if verdict == 'allow': return 'approve'
|
|
875
|
+
return inner_operation(root, mode, description, cancelled, emit_fn)
|
|
876
|
+
|
|
877
|
+
env_cls.execute = execute
|
|
878
|
+
module.write = write
|
|
879
|
+
if inner_event: module.event = event
|
|
880
|
+
if inner_operation: module.approve_operation = approve_operation
|
|
881
|
+
return env_cls
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
# ------------------------------------------------------------------ Kimi bridge (worker/kimi_hook.py)
|
|
885
|
+
def kimi_target(name, args):
|
|
886
|
+
command = str(args.get('command') or '') if name == 'Bash' else None
|
|
887
|
+
return command, tool_paths(args)
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def kimi_run(st):
|
|
891
|
+
req = _request(ROOT)
|
|
892
|
+
return {k: st.get(k, req.get(k)) for k in ('runId', 'mode', 'task', 'laptop')}
|
|
893
|
+
|
|
894
|
+
|
|
895
|
+
def kimi_pre(name, args, st):
|
|
896
|
+
command, paths = kimi_target(name, args)
|
|
897
|
+
return before(name, args, kimi_run(st), command=command, path=paths)
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def kimi_post(payload_in, st):
|
|
901
|
+
name = str(payload_in.get('tool_name') or '')
|
|
902
|
+
args = payload_in.get('tool_input') if isinstance(payload_in.get('tool_input'), dict) else {}
|
|
903
|
+
out = payload_in.get('tool_response', payload_in.get('tool_output', payload_in.get('output')))
|
|
904
|
+
result = {'output': clip(out if isinstance(out, str) else json.dumps(out, default=str), 4000), 'returncode': 1 if payload_in.get('is_error') else 0}
|
|
905
|
+
command, paths = kimi_target(name, args)
|
|
906
|
+
return after(name, args, result, kimi_run(st), command=command, path=paths)
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def wants_post(config):
|
|
910
|
+
cfg = settings(config=config)
|
|
911
|
+
return any(h['event'] in ('after_tool', 'after_edit') for h in cfg['hooks'])
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
# ------------------------------------------------------------------ plugin skills (worker/skill_library.py)
|
|
915
|
+
def plugin_skills(root=None):
|
|
916
|
+
ext = _request(root or ROOT).get('extensions') or {}
|
|
917
|
+
return [s for s in (ext.get('skills') or []) if isinstance(s, dict)][:60] if isinstance(ext, dict) else []
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
def active(cfg=None):
|
|
921
|
+
cfg = cfg or settings()
|
|
922
|
+
perms = cfg.get('perms') or {}
|
|
923
|
+
return bool(cfg['hooks'] or any(cfg['deny'].values()) or cfg.get('offline') or cfg.get('restricted') or perms.get('allow') or perms.get('deny') or perms.get('ask') or perms.get('bypass'))
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
def guidance(cfg=None):
|
|
927
|
+
"""One short paragraph for the agent's instructions, so blocks are not a surprise."""
|
|
928
|
+
cfg = cfg or settings()
|
|
929
|
+
lines = []
|
|
930
|
+
if cfg['hooks']:
|
|
931
|
+
names = ', '.join(sorted({h['name'] + ' (' + h['event'].replace('_', ' ') + ')' for h in cfg['hooks']}))[:600]
|
|
932
|
+
lines.append('Project hooks run on this task: ' + names + '. When a hook blocks a call, its reason is the project\'s rule: follow it instead of working around it.')
|
|
933
|
+
d = cfg['deny']
|
|
934
|
+
if any(d.values()):
|
|
935
|
+
lines.append('Hard-deny rules (never allowed, in any mode): ' + '; '.join(k + ': ' + ', '.join(v[:12]) for k, v in d.items() if v)[:800] + '.')
|
|
936
|
+
try:
|
|
937
|
+
import mlai_permissions
|
|
938
|
+
text = mlai_permissions.guidance(cfg.get('perms'))
|
|
939
|
+
if text: lines.append(text)
|
|
940
|
+
except Exception: pass
|
|
941
|
+
if cfg.get('offline'): lines.append('Network access is off for this session: no web tools, remote hosts, package installs or git remotes. Localhost works.')
|
|
942
|
+
if cfg.get('restricted'): lines.append('Restricted mode (shared computer): shell commands, verify commands and helper agents are off, and file tools work inside the project only. Do the work with the file tools and list any command the user should run.')
|
|
943
|
+
lines.append('Commands that read stored credentials (SSH keys, cloud CLI tokens, keychains, /proc environ) or dump the environment are always refused.')
|
|
944
|
+
return '\n'.join(lines) + '\n'
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
# ------------------------------------------------------------------ CLI
|
|
948
|
+
def main(argv):
|
|
949
|
+
if argv[:1] == ['fire']:
|
|
950
|
+
try:
|
|
951
|
+
msg = json.loads(sys.stdin.read() or '{}'); h = normalize_hook(msg.get('hook') or {}, (msg.get('hook') or {}).get('source', 'account'))
|
|
952
|
+
if h: run_hook(h, msg.get('payload') or {}, settings())
|
|
953
|
+
except Exception: pass
|
|
954
|
+
return
|
|
955
|
+
if argv[:1] == ['validate']:
|
|
956
|
+
text = Path(argv[1]).read_text()[:100001] if len(argv) > 1 else sys.stdin.read()[:100001]
|
|
957
|
+
hooks, deny, errors = parse_file(text)
|
|
958
|
+
print(json.dumps({'ok': not errors, 'errors': errors, 'hooks': hooks, 'deny': deny})); return
|
|
959
|
+
text = _repo_file(REPO)
|
|
960
|
+
hooks, deny, errors = parse_file(text) if text is not None else ([], merge_deny(), [])
|
|
961
|
+
print(json.dumps({'file': FILE, 'exists': text is not None, 'text': text or '', 'hooks': hooks, 'deny': deny, 'errors': errors,
|
|
962
|
+
'events': list(EVENTS), 'credentialPaths': CREDENTIAL_PATHS, 'credentialCommands': CREDENTIAL_COMMANDS}))
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
if __name__ == '__main__':
|
|
966
|
+
main(sys.argv[1:])
|