@piagent/platform 1.46.4 → 1.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +16 -3
- package/README.vi.md +16 -3
- package/docs/command-reference-vietnamese.md +4 -4
- package/docs/company-dev-commands.md +6 -5
- package/docs/distribution-standard.md +6 -6
- package/docs/languages.json +2 -2
- package/docs/mcp-and-tools.md +21 -1
- package/docs/operator-manual-vietnamese.md +7 -7
- package/docs/publishing-for-teams.md +2 -0
- package/docs/release-install-policy.md +2 -2
- package/docs/security-threat-model.md +3 -1
- package/docs/team-onboarding.md +2 -2
- package/docs-site/architecture.html +1 -1
- package/docs-site/assets/search-en.json +1 -1
- package/docs-site/assets/search-vi.json +1 -1
- package/docs-site/benchmark.html +1 -1
- package/docs-site/commands.html +1 -1
- package/docs-site/content/en/mcp.html +8 -0
- package/docs-site/content/mcp.html +8 -0
- package/docs-site/context-engine.html +1 -1
- package/docs-site/ecosystem.html +1 -1
- package/docs-site/en/architecture.html +1 -1
- package/docs-site/en/benchmark.html +1 -1
- package/docs-site/en/commands.html +1 -1
- package/docs-site/en/context-engine.html +1 -1
- package/docs-site/en/ecosystem.html +1 -1
- package/docs-site/en/index.html +15 -15
- package/docs-site/en/mcp-approval.html +1 -1
- package/docs-site/en/mcp-auth.html +1 -1
- package/docs-site/en/mcp-servers.html +1 -1
- package/docs-site/en/mcp.html +9 -1
- package/docs-site/en/permissions.html +1 -1
- package/docs-site/en/profiles.html +1 -1
- package/docs-site/en/quickstart.html +1 -1
- package/docs-site/en/runtime.html +1 -1
- package/docs-site/en/scope.html +1 -1
- package/docs-site/en/security.html +1 -1
- package/docs-site/en/team.html +1 -1
- package/docs-site/en/update.html +3 -3
- package/docs-site/en/whats-new.html +59 -32
- package/docs-site/en/windows.html +1 -1
- package/docs-site/en/workflows.html +1 -1
- package/docs-site/index.html +15 -15
- package/docs-site/mcp-approval.html +1 -1
- package/docs-site/mcp-auth.html +1 -1
- package/docs-site/mcp-servers.html +1 -1
- package/docs-site/mcp.html +9 -1
- package/docs-site/permissions.html +1 -1
- package/docs-site/profiles.html +1 -1
- package/docs-site/quickstart.html +1 -1
- package/docs-site/releases.json +87 -0
- package/docs-site/runtime.html +1 -1
- package/docs-site/scope.html +1 -1
- package/docs-site/security.html +1 -1
- package/docs-site/team.html +1 -1
- package/docs-site/update.html +3 -3
- package/docs-site/whats-new.html +59 -32
- package/docs-site/windows.html +1 -1
- package/docs-site/workflows.html +1 -1
- package/evals/private-holdout-v1/public-exposure.v2.json +2 -2
- package/package.json +2 -1
- package/packages/piagent-core/extensions/guard-types.ts +10 -2
- package/packages/piagent-core/extensions/piagent-guard.ts +106 -169
- package/packages/piagent-core/extensions/policy-core.js +7 -7
- package/packages/piagent-core/extensions/shell-ast.js +85 -0
- package/packages/piagent-core/extensions/shell-command-words.js +19 -0
- package/packages/piagent-core/managed/command-tools.mjs +70 -26
- package/packages/piagent-core/managed/fetch-guard.mjs +3 -3
- package/packages/piagent-core/managed/host-command.mjs +15 -7
- package/packages/piagent-core/managed/member-mcp.mjs +96 -0
- package/packages/piagent-core/managed/memory-lessons.mjs +1 -1
- package/packages/piagent-core/managed/permission.mjs +19 -12
- package/packages/piagent-core/managed/repository-operation.mjs +1 -1
- package/packages/piagent-core/managed/resource-loader.mjs +19 -7
- package/packages/piagent-core/managed/sandbox-diagnostic.mjs +4 -0
- package/packages/piagent-core/managed/session.mjs +4 -4
- package/packages/piagent-core/managed/simulator-commands.mjs +117 -0
- package/packages/piagent-core/mcp/mcp-server-catalog.js +18 -1
- package/packages/piagent-core/package.json +1 -1
- package/packages/piagent-core/runtime/hooks/session-start-hook.ts +1 -1
- package/packages/piagent-core/runtime/inspection/approval-broker.ts +33 -16
- package/packages/piagent-core/runtime/mcp-repository-gate.d.mts +10 -0
- package/packages/piagent-core/runtime/mcp-repository-gate.mjs +150 -0
- package/packages/piagent-core/runtime/policy/handoff-policy.mjs +144 -0
- package/packages/piagent-core/runtime/registration/permission-commands.ts +2 -2
- package/packages/piagent-webui/dist/client/assets/{App-CiwY9VpU.js → App-fZeIRoaD.js} +1 -1
- package/packages/piagent-webui/dist/client/assets/{GatewayApp-DrNJW3v_.js → GatewayApp-CpC4lgYK.js} +17 -15
- package/packages/piagent-webui/dist/client/assets/{InspectionApp-BBiwSaV0.js → InspectionApp-pD-BqBXm.js} +1 -1
- package/packages/piagent-webui/dist/client/assets/{SessionAgentWorkspace-DwyPebIX.js → SessionAgentWorkspace-3tM7Q6HH.js} +1 -1
- package/packages/piagent-webui/dist/client/assets/{SessionInspectorDrawer-CpVzaf_G.js → SessionInspectorDrawer-BJ94aQ6y.js} +2 -2
- package/packages/piagent-webui/dist/client/assets/SettingsNavigation-BFfqMcuL.js +3 -0
- package/packages/piagent-webui/dist/client/assets/SettingsPage-CxpZ7cdM.js +1 -0
- package/packages/piagent-webui/dist/client/assets/{TerminalPanel-B8j_r6-y.js → TerminalPanel-CtZyb0tj.js} +1 -1
- package/packages/piagent-webui/dist/client/assets/{WorkspaceCodeEditor-BDTPvq-0.js → WorkspaceCodeEditor-BS_ZrjPN.js} +1 -1
- package/packages/piagent-webui/dist/client/assets/{WorkspaceExplorer-DVsNU0eu.js → WorkspaceExplorer-CkFBpcM7.js} +3 -3
- package/packages/piagent-webui/dist/client/assets/{index-uhJMXxqD.js → index-CNdhIouM.js} +2 -2
- package/packages/piagent-webui/dist/client/assets/{index-Dqb2hNan.css → index-CjM70M7D.css} +1 -1
- package/packages/piagent-webui/dist/client/assets/transcript-view-model-CpEMY1xb.js +3 -0
- package/packages/piagent-webui/dist/client/index.html +2 -2
- package/packages/piagent-webui/gateway/gateway-events.ts +5 -1
- package/packages/piagent-webui/server/gateway-websocket.ts +5 -1
- package/schemas/piagent-webui/approval-v1.schema.json +3 -1
- package/schemas/project-profile.schema.json +16 -0
- package/scripts/company-terminal.mjs +5 -5
- package/scripts/setup.sh +1 -1
- package/scripts/verify-release-identity.mjs +1 -1
- package/packages/piagent-core/runtime/policy/bypass-policy.mjs +0 -42
- package/packages/piagent-webui/dist/client/assets/SettingsNavigation-C-tO5iXn.js +0 -3
- package/packages/piagent-webui/dist/client/assets/SettingsPage-Ca-qRSZa.js +0 -1
- package/packages/piagent-webui/dist/client/assets/transcript-view-model-Bq0nkxyu.js +0 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { excludedFindSelectorValue, findSelectorOption, SEARCH_COMMANDS, SEARCH_FILE_OPTIONS, SEARCH_GLOB_OPTIONS,
|
|
2
|
-
|
|
1
|
+
import { excludedFindSelectorValue, findSelectorOption, SEARCH_COMMANDS, SEARCH_FILE_OPTIONS, SEARCH_GLOB_OPTIONS, SEARCH_PATTERN_OPTIONS, searchSelectorIsExclusion, searchSelectorWithinToken } from "./shell-selector-policy.js";
|
|
2
|
+
import { CONTROL_PREFIXES, gitSubcommandWords } from "./shell-command-words.js";
|
|
3
3
|
|
|
4
4
|
const PATH_REDIRECT_OPERATORS = new Set(["<", ">", ">>", "1>", "1>>", "2>", "2>>", "&>", "&>>"]);
|
|
5
5
|
const DATA_ONLY_COMMANDS = new Set(["echo", "printf"]);
|
|
@@ -35,7 +35,7 @@ const INLINE_CODE_FLAGS = new Map([
|
|
|
35
35
|
["perl", new Set(["-e", "-E"])],
|
|
36
36
|
["php", new Set(["-r"])]
|
|
37
37
|
]);
|
|
38
|
-
const SIMPLE_WRAPPERS = new Set(["sudo", "nohup", "time", "nice", "ionice", "command"]);
|
|
38
|
+
const SIMPLE_WRAPPERS = new Set(["sudo", "doas", "nohup", "time", "nice", "ionice", "command", "exec"]);
|
|
39
39
|
|
|
40
40
|
function escapeRegex(value) {
|
|
41
41
|
return value.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
@@ -703,13 +703,13 @@ function isLeadingRedirection(word) {
|
|
|
703
703
|
return /^[0-9]*(?:>>?\|?|<>?|>&|<&)/.test(word);
|
|
704
704
|
}
|
|
705
705
|
|
|
706
|
-
function stripWrapper(words) {
|
|
706
|
+
export function stripWrapper(words) {
|
|
707
707
|
let current = [...words];
|
|
708
708
|
let changed = true;
|
|
709
709
|
|
|
710
710
|
while (changed && current.length > 0) {
|
|
711
711
|
changed = false;
|
|
712
|
-
while (current.length > 0 && isAssignment(current[0])) {
|
|
712
|
+
while (current.length > 0 && (isAssignment(current[0]) || CONTROL_PREFIXES.has(current[0]))) {
|
|
713
713
|
current = current.slice(1);
|
|
714
714
|
changed = true;
|
|
715
715
|
}
|
|
@@ -1186,7 +1186,7 @@ export function evaluateExecPolicyCore(command, options) {
|
|
|
1186
1186
|
|
|
1187
1187
|
for (const rule of execPolicy.rules) {
|
|
1188
1188
|
if (!commandRuleMatches(rule, text, words)) continue;
|
|
1189
|
-
matches.push(`${rule.action}:${rule.id}`);
|
|
1189
|
+
matches.push(`${rule.action}:${rule.id}`, ...(rule.action === "forbid" && rule.terminate ? [`terminate:${rule.id}`] : []));
|
|
1190
1190
|
if (rule.action === "forbid") reasons.push(`Forbidden by exec policy ${rule.id}: ${rule.reason}`);
|
|
1191
1191
|
if (rule.action === "prompt") reasons.push(`Prompt required by exec policy ${rule.id}: ${rule.reason}`);
|
|
1192
1192
|
}
|
|
@@ -1229,7 +1229,7 @@ export function evaluateExecPolicyCore(command, options) {
|
|
|
1229
1229
|
const confirmationPatternMatches = (pattern, words) => {
|
|
1230
1230
|
const expected = shellWords(String(pattern ?? ""));
|
|
1231
1231
|
if (expected.length === 0) return false;
|
|
1232
|
-
const executableWords = stripWrapper(words);
|
|
1232
|
+
const executableWords = gitSubcommandWords(stripWrapper(words));
|
|
1233
1233
|
if (arrayStartsWith(executableWords, expected)) return true;
|
|
1234
1234
|
if (expected.length !== 1) return false;
|
|
1235
1235
|
const action = expected[0];
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// The simple commands a shell line runs, read from a real shell syntax tree.
|
|
2
|
+
//
|
|
3
|
+
// policy-core.js splits a line into segments with its own scanner; this reads
|
|
4
|
+
// the same line through a POSIX/Bash parser and walks every place a command
|
|
5
|
+
// can sit: pipelines, && and ||, if/while/for/case bodies, functions, ( … ),
|
|
6
|
+
// { … }, $( … ), backticks and <( … ). `bash -c '…'`, `sh -c` and `eval` are
|
|
7
|
+
// parsed again, so the text they run is read as commands too. A check that
|
|
8
|
+
// reads both lists sees a command whichever reader finds it.
|
|
9
|
+
//
|
|
10
|
+
// Words come back as text. A word built from an expansion the shell decides
|
|
11
|
+
// at run time ($VAR, $(…), `…`) keeps it as written and is flagged dynamic;
|
|
12
|
+
// nothing is evaluated here. A line the parser rejects gives null: callers
|
|
13
|
+
// keep the scanner's answer, which is never weakened by this module.
|
|
14
|
+
import { parse } from "@aliou/sh";
|
|
15
|
+
|
|
16
|
+
const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "mksh"]);
|
|
17
|
+
const MAX_DEPTH = 8;
|
|
18
|
+
|
|
19
|
+
function wordText(word) {
|
|
20
|
+
let text = "", dynamic = false;
|
|
21
|
+
const visit = (parts) => {
|
|
22
|
+
for (const part of parts ?? []) {
|
|
23
|
+
if (part.type === "Literal" || part.type === "SglQuoted") text += part.value;
|
|
24
|
+
else if (part.type === "DblQuoted") visit(part.parts);
|
|
25
|
+
else if (part.type === "ParamExp") { text += `$${part.param?.value ?? ""}`; dynamic = true; }
|
|
26
|
+
else { text += "$(…)"; dynamic = true; }
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
visit(word?.parts);
|
|
30
|
+
return { text, dynamic };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The $( … ) and ` … ` an unquoted heredoc body runs: the parser keeps the
|
|
34
|
+
// body as text, and the shell expands it.
|
|
35
|
+
function substitutions(text) {
|
|
36
|
+
const found = [];
|
|
37
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
38
|
+
if (text[index] === "`") {
|
|
39
|
+
const close = text.indexOf("`", index + 1);
|
|
40
|
+
if (close < 0) break;
|
|
41
|
+
found.push(text.slice(index + 1, close)); index = close;
|
|
42
|
+
} else if (text.startsWith("$(", index) && text[index + 2] !== "(") {
|
|
43
|
+
let depth = 0, close = -1;
|
|
44
|
+
for (let at = index + 1; at < text.length; at += 1) {
|
|
45
|
+
if (text[at] === "(") depth += 1;
|
|
46
|
+
else if (text[at] === ")" && --depth === 0) { close = at; break; }
|
|
47
|
+
}
|
|
48
|
+
if (close < 0) break;
|
|
49
|
+
found.push(text.slice(index + 2, close)); index = close;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return found;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function collect(node, found, depth) {
|
|
56
|
+
if (!node || typeof node !== "object") return;
|
|
57
|
+
if (Array.isArray(node)) { for (const item of node) collect(item, found, depth); return; }
|
|
58
|
+
if (node.type === "Redirect" && node.heredoc && node.target?.parts?.every((part) => part.type === "Literal") && depth < MAX_DEPTH) {
|
|
59
|
+
for (const source of substitutions(wordText(node.heredoc).text)) collectSource(source, found, depth + 1);
|
|
60
|
+
}
|
|
61
|
+
if (node.type === "SimpleCommand" && node.words?.length) {
|
|
62
|
+
const words = node.words.map(wordText);
|
|
63
|
+
found.push({ words: words.map((word) => word.text), dynamic: words.some((word) => word.dynamic) });
|
|
64
|
+
const name = String(words[0]?.text ?? "").split("/").pop();
|
|
65
|
+
const inline = SHELLS.has(name) ? words.findIndex((word, index) => index > 0 && /^-[a-z]*c[a-z]*$/.test(word.text)) + 1 : name === "eval" ? 1 : 0;
|
|
66
|
+
if (inline > 0 && depth < MAX_DEPTH) {
|
|
67
|
+
const source = name === "eval" ? words.slice(1).map((word) => word.text).join(" ") : words[inline]?.text;
|
|
68
|
+
if (source) collectSource(source, found, depth + 1);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
for (const [key, value] of Object.entries(node)) {
|
|
72
|
+
if (key !== "pos" && key !== "end" && value && typeof value === "object") collect(value, found, depth);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function collectSource(source, found, depth) {
|
|
77
|
+
try { collect(parse(String(source), { dialect: "bash" }).ast, found, depth); } catch { /* the scanner still reads it */ }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// [{ words, dynamic }] for every simple command, or null when the line does not parse.
|
|
81
|
+
export function astCommands(command) {
|
|
82
|
+
const found = [];
|
|
83
|
+
try { collect(parse(String(command), { dialect: "bash" }).ast, found, 0); } catch { return null; }
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// How a simple command's words name what runs, shared by policy-core.js and
|
|
2
|
+
// the handoff policy (runtime/policy/handoff-policy.mjs).
|
|
3
|
+
|
|
4
|
+
// Shell words that open a compound statement: the command follows them.
|
|
5
|
+
// `if true; then rm -rf /; fi` splits into `then rm -rf /`, which runs rm.
|
|
6
|
+
export const CONTROL_PREFIXES = new Set(["!", "{", "(", "if", "then", "do", "elif", "else", "while", "until"]);
|
|
7
|
+
|
|
8
|
+
// Git's global options come before the subcommand: `git -C api push` and
|
|
9
|
+
// `git -c core.hooksPath=x --no-pager push` push as `git push` does. Without
|
|
10
|
+
// this a rule written as "git push" matched only the plain spelling.
|
|
11
|
+
const GIT_OPTIONS_WITH_VALUE = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path", "--list-cmds"]);
|
|
12
|
+
export function gitSubcommandWords(words) {
|
|
13
|
+
if (String(words[0] ?? "").split("/").pop() !== "git") return words;
|
|
14
|
+
let index = 1;
|
|
15
|
+
while (index < words.length && words[index].startsWith("-")) {
|
|
16
|
+
index += GIT_OPTIONS_WITH_VALUE.has(words[index]) ? 2 : 1;
|
|
17
|
+
}
|
|
18
|
+
return ["git", ...words.slice(index)];
|
|
19
|
+
}
|
|
@@ -1,44 +1,61 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { asksOnlyHandoff, broadAccess, effectivePermission, networkConfirmation } from './permission.mjs';
|
|
3
|
+
import { handoffReason } from '../runtime/policy/handoff-policy.mjs';
|
|
3
4
|
import { engineAlive, engineLauncher } from './container-engine.mjs';
|
|
4
5
|
import { MEMBER_ONLY, memberOnlyReason, credentialReason, runHostCommand } from './host-command.mjs';
|
|
5
6
|
import { processTools } from './background-process.mjs';
|
|
6
7
|
import { checkpointsOf } from './checkpoints.mjs';
|
|
8
|
+
import { detachedEmulator, simulatorCommandReason } from './simulator-commands.mjs';
|
|
7
9
|
|
|
8
|
-
// Commands that leave the plain sandbox
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
10
|
+
// Commands that leave the plain sandbox: run_with_network (internet, a local
|
|
11
|
+
// server or browser), run_with_docker when this machine has Docker (the same
|
|
12
|
+
// plus the engine's socket), run_on_host (on the member's machine, outside the
|
|
13
|
+
// sandbox) and run_on_simulator. What each mode asks (permission.mjs):
|
|
14
|
+
// - Ask first: every command.
|
|
15
|
+
// - Full access: run_with_network, run_with_docker and run_on_simulator run,
|
|
16
|
+
// except the handoff and destructive steps (mustConfirm); run_on_host asks
|
|
17
|
+
// every command.
|
|
18
|
+
// - Bypass: all four run, except the handoff (handoffReason: push, PR,
|
|
19
|
+
// publish, deploy, remote and cloud tools, uploads) and, on the host, a
|
|
20
|
+
// command that reaches credentials.
|
|
16
21
|
const PARAMETERS = { type: 'object', properties: { command: { type: 'string', minLength: 1, maxLength: 4000 }, reason: { type: 'string', minLength: 1, maxLength: 300 }, timeout: { type: 'number', minimum: 1, maximum: 1800 } }, required: ['command', 'reason'], additionalProperties: false };
|
|
17
22
|
|
|
18
23
|
const KINDS = {
|
|
19
24
|
network: {
|
|
20
25
|
name: 'run_with_network', label: 'Run with network', scope: 'network-command-once', provider: 'network', riskClass: 'medium',
|
|
21
|
-
description: 'Run one shell command that needs the internet beyond the package registries bash already reaches (a download site or registry the package proxy refuses), or that starts a local server or a browser (end-to-end tests with Playwright\'s Chromium against a server on 127.0.0.1), after the user approves that exact command. Normal bash has no internet; on macOS it reaches servers on this Mac and runs Playwright\'s Chromium against them, except while a local proxy listens. Credentials (.npmrc, SSH keys, Keychain) stay unavailable, so private registries and git push are not possible here.',
|
|
26
|
+
description: 'Run one shell command that needs the internet beyond the package registries bash already reaches (a download site or registry the package proxy refuses), or that starts a local server or a browser (end-to-end tests with Playwright\'s Chromium against a server on 127.0.0.1), after the user approves that exact command (Full access and Bypass run it without asking, but a push, publish, deploy or upload is always asked). Normal bash has no internet; on macOS it reaches servers on this Mac and runs Playwright\'s Chromium against them, except while a local proxy listens. Credentials (.npmrc, SSH keys, Keychain) stay unavailable, so private registries and git push are not possible here.',
|
|
22
27
|
allow: 'Run this exact command once, with internet access; a server it starts accepts connections while it runs.',
|
|
23
28
|
title: 'Chạy lệnh có internet', allowText: 'chạy đúng lệnh này một lần, có internet; server nó mở nhận kết nối trong lúc chạy.',
|
|
24
29
|
confirm: (self, command) => networkConfirmation(self, command),
|
|
25
30
|
},
|
|
26
31
|
docker: {
|
|
27
32
|
name: 'run_with_docker', label: 'Run with Docker', scope: 'docker-command-once', provider: 'docker', riskClass: 'high',
|
|
28
|
-
description: 'Run one shell command that needs the Docker engine of this machine: docker, docker compose (a database or service for tests), docker build, or tests that start containers themselves (Testcontainers), after the user approves that exact command. It has internet access too. Normal bash and run_with_network cannot reach Docker. Mount only folders inside the project. Registry credentials are unavailable: public images pull, private registries and docker push do not. Containers started in the background (-d, compose up -d) keep running after the command: stop them (docker compose down) when the work is done unless the member wants them kept.',
|
|
33
|
+
description: 'Run one shell command that needs the Docker engine of this machine: docker, docker compose (a database or service for tests), docker build, or tests that start containers themselves (Testcontainers), after the user approves that exact command (Full access and Bypass run it without asking, but docker push or login and any other handoff is always asked). It has internet access too. Normal bash and run_with_network cannot reach Docker. Mount only folders inside the project. Registry credentials are unavailable: public images pull, private registries and docker push do not. Containers started in the background (-d, compose up -d) keep running after the command: stop them (docker compose down) when the work is done unless the member wants them kept.',
|
|
29
34
|
allow: 'Run this exact command once, with internet access and the Docker engine; a container it starts can read folders Docker shares from this machine and may keep running.',
|
|
30
35
|
title: 'Chạy lệnh dùng Docker', allowText: 'chạy đúng lệnh này một lần, có internet và Docker; container nó tạo có thể đọc thư mục Docker được chia sẻ trên máy và có thể tiếp tục chạy.',
|
|
31
36
|
confirm: (self, command) => networkConfirmation(self, command),
|
|
32
37
|
},
|
|
33
38
|
host: {
|
|
34
39
|
name: 'run_on_host', label: 'Run on this machine', scope: 'host-command-once', provider: 'host', riskClass: 'high',
|
|
35
|
-
description: 'Run one shell command on the member\'s machine, outside the sandbox, as the member, after they approve that exact command. Use it when the sandbox blocks what the task needs and no other tool covers it: install a runtime or tool the project needs (brew install openjdk@21, brew install node@22, sdk install java…), git pull
|
|
40
|
+
description: 'Run one shell command on the member\'s machine, outside the sandbox, as the member, after they approve that exact command (only Bypass runs it without asking, and even there a push, PR, publish, deploy or a command that reaches credentials is asked). Use it when the sandbox blocks what the task needs and no other tool covers it: install a runtime or tool the project needs (brew install openjdk@21, brew install node@22, sdk install java…), git pull with the member\'s sign-in, git push only when the member asked for it, a private registry, a file outside the project. It has the member\'s files, Keychain and sign-ins, so ask only for what the task needs and say why in reason. No input can be typed: commands that need the member\'s password (sudo, a .pkg installer) or an interactive sign-in are refused; ask the member with ask_user for those.',
|
|
36
41
|
allow: 'Run this exact command once on this machine, outside the sandbox, as you: it can read and change your files and use your sign-ins.',
|
|
37
42
|
title: 'Chạy lệnh trên máy (ngoài sandbox)', allowText: 'chạy đúng lệnh này một lần trên máy bạn, ngoài sandbox, bằng quyền của bạn: lệnh đọc/sửa được file và dùng được tài khoản đã đăng nhập trên máy.',
|
|
38
43
|
// Full access does not cover it: the member approves each command (with
|
|
39
|
-
// what Full access would still have asked about). Bypass asks
|
|
40
|
-
// credentials: a prompt injection's "cat ~/.ssh/id_rsa"
|
|
41
|
-
|
|
44
|
+
// what Full access would still have asked about). Bypass asks about the
|
|
45
|
+
// handoff and about credentials: a prompt injection's "cat ~/.ssh/id_rsa"
|
|
46
|
+
// or "git push --force" is never silent.
|
|
47
|
+
confirm: async (self, command) => asksOnlyHandoff(self) ? credentialReason(command) ?? await handoffReason(command) : await networkConfirmation(self, command) ?? 'ask',
|
|
48
|
+
},
|
|
49
|
+
// The sandbox reaches neither CoreSimulator nor adb. Simulator and app build
|
|
50
|
+
// commands only (simulator-commands.mjs), asked about as network commands:
|
|
51
|
+
// Full access and Bypass run them, except what reaches credentials and what
|
|
52
|
+
// either mode asks about any command.
|
|
53
|
+
simulator: {
|
|
54
|
+
name: 'run_on_simulator', label: 'Run on simulator', scope: 'simulator-command-once', provider: 'host', riskClass: 'medium',
|
|
55
|
+
description: 'Run one iOS Simulator or Android emulator command on the member\'s machine, outside the sandbox. iOS: xcrun simctl (list, boot, bootstatus -b, install, launch, terminate, openurl, io <device> screenshot <file>, ui appearance, status_bar, spawn <device> log show --info --last 5m --predicate \'process == "<App>"\'), xcodebuild with a simulator destination (build, test: XCUITest is the reliable way to tap, type and answer system dialogs), xcodegen generate, axe (describe-ui reads the screen\'s elements; tap, type, swipe where this Xcode accepts them), open -a Simulator (some Xcode versions run simulators without that window; the device works without it). Android: adb (devices, install, shell am start, shell input tap/text/swipe, exec-out screencap -p > <file>, logcat -d), emulator -avd <name> (started in the background), avdmanager, ./gradlew installDebug. Also flutter, pod install, npx expo/react-native/cap, mkdir -p and cd inside the project. Parts may be joined by && or || and piped into grep, head, tail, xcbeautify or jq; files may be written only inside the project or to /dev/null. Read a screenshot you saved with read to see the screen. Other commands: run_on_host.',
|
|
56
|
+
allow: 'Run this exact simulator or app build command once on this machine, outside the sandbox: a build can run the project\'s build scripts as you.',
|
|
57
|
+
title: 'Chạy lệnh simulator', allowText: 'chạy đúng lệnh simulator/build app này một lần trên máy bạn, ngoài sandbox: build có thể chạy script build của project bằng quyền của bạn.',
|
|
58
|
+
confirm: async (self, command) => credentialReason(command) ?? await networkConfirmation(self, command),
|
|
42
59
|
},
|
|
43
60
|
};
|
|
44
61
|
|
|
@@ -49,14 +66,34 @@ async function engineReady(boundary) {
|
|
|
49
66
|
}
|
|
50
67
|
const DOCKER_STOPPED = 'managed-docker-unreachable: Docker engine trên máy không chạy. Gọi start_docker để xin member duyệt mở Docker, rồi chạy lại đúng lệnh này bằng run_with_docker.';
|
|
51
68
|
|
|
52
|
-
//
|
|
69
|
+
// Why a mode that runs commands without asking asks about this one, as the
|
|
70
|
+
// card says it: the mode named as it is.
|
|
71
|
+
export function stillAsks(self, reason) {
|
|
72
|
+
return effectivePermission(self) === 'bypass' ? { en: `Bypass still asks: ${reason}`, vi: `Bypass vẫn hỏi: ${reason}` }
|
|
73
|
+
: { en: `Full access still asks: ${reason}`, vi: `Full access vẫn hỏi: ${reason}` };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// One approval of the member (the dashboard card, else the Terminal). The
|
|
77
|
+
// member may allow it once, allow the same exact action for the rest of the
|
|
78
|
+
// conversation (never a handoff: its scope names it), deny it, or deny it and
|
|
79
|
+
// stop the turn so the agent does not try again.
|
|
80
|
+
const CHOICES = { once: 'Đồng ý một lần', session: 'Đồng ý cho cả cuộc trò chuyện (đúng lệnh này)', deny: 'Từ chối', stop: 'Từ chối và dừng lượt này' };
|
|
53
81
|
export async function approve(self, id, signal, ctx, action, { title, body }) {
|
|
82
|
+
const grantable = !/handoff/.test(String(action.requestedScope ?? '')), key = `${action.toolName}\u0000${action.commandPreview ?? JSON.stringify(action.rawAction ?? {})}`;
|
|
83
|
+
if (grantable && self.sessionApprovals?.has(key)) return;
|
|
54
84
|
const { piApprovalBroker } = await import('../runtime/inspection/approval-broker.ts');
|
|
85
|
+
const choices = ['once', ...(grantable ? ['session'] : []), 'deny', 'stop'];
|
|
55
86
|
const decision = await piApprovalBroker.request({ cwd: self.cwd, rawSessionId: self.session.sessionManager.getSessionId(), toolCallId: id,
|
|
56
87
|
action: { kind: 'external-provider-action', preconditionClass: 'runtime-only', targetPaths: [self.cwd], urlOrigin: null, ...action },
|
|
57
88
|
terminalConfirm: () => ctx?.ui?.confirm?.(title, body) ?? Promise.resolve(false),
|
|
89
|
+
...(ctx?.mode === 'tui' && ctx?.hasUI && typeof ctx.ui?.select === 'function' ? { terminalChoose: async () => {
|
|
90
|
+
const picked = await ctx.ui.select(`${title}\n\n${body}`, choices.map(choice => CHOICES[choice]));
|
|
91
|
+
return choices.find(choice => CHOICES[choice] === picked) ?? 'deny';
|
|
92
|
+
} } : {}),
|
|
58
93
|
unavailableFallback: 'terminal-confirm', recheck: () => !signal?.aborted && Boolean(self.grant) });
|
|
94
|
+
if (!decision.allowed && decision.choice === 'stop') { try { ctx?.abort?.(); } catch { /* the denial below still stands */ } throw Error('managed-operation-denied-stop: bạn đã từ chối và dừng lượt này; không thử lại, chờ member.'); }
|
|
59
95
|
if (!decision.allowed || !decision.consume() || signal?.aborted) throw Error('managed-operation-denied');
|
|
96
|
+
if (decision.choice === 'session' && grantable) (self.sessionApprovals ??= new Set()).add(key);
|
|
60
97
|
}
|
|
61
98
|
|
|
62
99
|
function commandTool(self, kind) {
|
|
@@ -66,16 +103,22 @@ function commandTool(self, kind) {
|
|
|
66
103
|
if (kind === 'docker' && !await engineReady(self.boundary)) throw Error(DOCKER_STOPPED);
|
|
67
104
|
const memberOnly = kind === 'host' ? memberOnlyReason(args.command) : null;
|
|
68
105
|
if (memberOnly) throw Error(MEMBER_ONLY(memberOnly));
|
|
106
|
+
const notSimulator = kind === 'simulator' ? simulatorCommandReason(args.command, self.cwd) : null;
|
|
107
|
+
if (notSimulator) throw Error(`managed-simulator-command: ${notSimulator}.`);
|
|
69
108
|
const confirm = await spec.confirm(self, args.command);
|
|
70
|
-
if (confirm !== null)
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
109
|
+
if (confirm !== null) {
|
|
110
|
+
const why = confirm === 'ask' ? null : stillAsks(self, confirm), handoff = await handoffReason(args.command);
|
|
111
|
+
await approve(self, id, signal, ctx, { toolName: spec.name, rawAction: { command: args.command }, commandPreview: String(args.command),
|
|
112
|
+
provider: spec.provider, requestedScope: handoff ? 'handoff-once' : spec.scope, reason: (why ? `${why.en}. ${args.reason}` : String(args.reason)).slice(0, 300), riskClass: spec.riskClass,
|
|
113
|
+
allowConsequence: spec.allow, denyConsequence: 'The command does not run; the agent is told you declined.' },
|
|
114
|
+
{ title: spec.title, body: `${args.command}\n\nLý do: ${args.reason}${why ? `\n${why.vi}` : ''}\n\nĐồng ý: ${spec.allowText}\nTừ chối: lệnh không chạy, agent được báo bạn đã từ chối.` });
|
|
115
|
+
}
|
|
74
116
|
let ok = false;
|
|
75
117
|
if (self.run) await checkpointsOf(self).take();
|
|
76
118
|
const before = await self.changedFiles();
|
|
77
119
|
try {
|
|
78
|
-
const result = kind === '
|
|
120
|
+
const result = kind === 'simulator' && detachedEmulator(args.command) ? await runHostCommand({ command: `nohup ${args.command} >/dev/null 2>&1 & sleep 3; echo "Emulator started in the background; wait for it with: adb wait-for-device"`, cwd: self.cwd, userHome: self.boundary.userHome, timeout: 60, signal, onUpdate })
|
|
121
|
+
: kind === 'host' || kind === 'simulator' ? await runHostCommand({ command: args.command, cwd: self.cwd, userHome: self.boundary.userHome, timeout: args.timeout, signal, onUpdate })
|
|
79
122
|
: await self.boundary.invoke('bash', { command: args.command, ...(args.timeout ? { timeout: args.timeout } : {}) }, signal, onUpdate, ctx?.model, kind === 'docker' ? { docker: true } : { network: true });
|
|
80
123
|
ok = !result?.isError; return result;
|
|
81
124
|
} finally {
|
|
@@ -87,7 +130,8 @@ function commandTool(self, kind) {
|
|
|
87
130
|
}
|
|
88
131
|
|
|
89
132
|
// start_docker: the engine the member installed, started after they approve
|
|
90
|
-
// (Bypass
|
|
133
|
+
// (Full access and Bypass start it without asking: local and reversible),
|
|
134
|
+
// then waited for.
|
|
91
135
|
const textResult = text => ({ content: [{ type: 'text', text }], details: {} });
|
|
92
136
|
function startDockerTool(self, { wait = 180_000, every = 2000, launcher: found = engineLauncher, spawnImpl = spawn } = {}) {
|
|
93
137
|
return { name: 'start_docker', label: 'Start Docker',
|
|
@@ -115,15 +159,15 @@ function startDockerTool(self, { wait = 180_000, every = 2000, launcher: found =
|
|
|
115
159
|
|
|
116
160
|
export function commandTools(self, options) {
|
|
117
161
|
const docker = self.boundary.engine || self.boundary.dockerCli;
|
|
118
|
-
return [commandTool(self, 'network'), ...(docker ? [commandTool(self, 'docker')] : []), startDockerTool(self, options), commandTool(self, 'host'), ...processTools(self)];
|
|
162
|
+
return [commandTool(self, 'network'), ...(docker ? [commandTool(self, 'docker')] : []), startDockerTool(self, options), commandTool(self, 'host'), commandTool(self, 'simulator'), ...processTools(self)];
|
|
119
163
|
}
|
|
120
164
|
|
|
121
165
|
// What the system prompt says about services and what the sandbox blocks: it
|
|
122
166
|
// is read for every request, so a Docker started since shows up.
|
|
123
|
-
const HOST_PROMPT = ' When the sandbox blocks something the task needs (a missing runtime such as a JDK or a Node version, the member\'s sign-in for git pull or
|
|
167
|
+
const HOST_PROMPT = ' When the sandbox blocks something the task needs (a missing runtime such as a JDK or a Node version, the member\'s sign-in for git pull or a private registry, a file outside the project), do not stop and do not tell the member to run it: request run_on_host with the exact command; it runs on the member\'s machine once they approve. The work ends at the handoff: commit locally, then report what is ready; push, open or merge a pull request, publish or deploy only when the member asked for it in this conversation, and each of those steps is asked about in every access mode. Only what needs the member themselves (their password for sudo or an installer, an interactive sign-in, a window to click) goes to ask_user, with the exact steps and the options to continue or skip; after their answer, check and carry on.';
|
|
124
168
|
export function servicesPrompt(boundary) {
|
|
125
|
-
const simulator = ' The iOS Simulator
|
|
126
|
-
if (boundary.engine) return ' Docker is available through run_with_docker (the member approves each command): a database or service for tests (docker compose up -d, then the tests through bash or run_with_network), docker build, or Testcontainers tests. If the engine stops answering, start_docker asks the member to start it. Stop what you started when done unless the member wants it kept.' + simulator + HOST_PROMPT;
|
|
169
|
+
const simulator = ' The iOS Simulator and Android emulator are not reachable from bash: boot them, build and install the app, launch it, tap and type, and take screenshots with run_on_simulator (save the screenshot in the project, then read it to see the screen). Do not ask the member to run simulator steps you can run.';
|
|
170
|
+
if (boundary.engine) return ' Docker is available through run_with_docker (in Ask first the member approves each command): a database or service for tests (docker compose up -d, then the tests through bash or run_with_network), docker build, or Testcontainers tests. If the engine stops answering, start_docker asks the member to start it. Stop what you started when done unless the member wants it kept.' + simulator + HOST_PROMPT;
|
|
127
171
|
if (boundary.dockerCli) return ' Docker is installed but not running: when the task needs it, call start_docker (the member approves), then run_with_docker.' + simulator + HOST_PROMPT;
|
|
128
172
|
return ' Docker is not installed on this machine: when the task needs it, ask the member with ask_user (install it, or check another way).' + simulator + HOST_PROMPT;
|
|
129
173
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { asksOnlyHandoff } from './permission.mjs';
|
|
2
2
|
import { approve } from './command-tools.mjs';
|
|
3
3
|
|
|
4
4
|
// web_fetch is a request to any public https address: a page that tells the
|
|
@@ -6,7 +6,7 @@ import { approve } from './command-tools.mjs';
|
|
|
6
6
|
// Documentation and package registries are read freely. Another host is asked
|
|
7
7
|
// about once per conversation; an address there that carries a query or a
|
|
8
8
|
// fragment (where data rides along) is asked about every time. Bypass asks
|
|
9
|
-
// only about the latter. A helper cannot ask the member: it is told to hand
|
|
9
|
+
// only about the latter: data sent out is a handoff. A helper cannot ask the member: it is told to hand
|
|
10
10
|
// the address to the main agent.
|
|
11
11
|
const TRUSTED = ['github.com', 'raw.githubusercontent.com', 'docs.github.com', 'npmjs.com', 'www.npmjs.com', 'registry.npmjs.org', 'pypi.org', 'docs.python.org',
|
|
12
12
|
'developer.mozilla.org', 'nodejs.org', 'go.dev', 'pkg.go.dev', 'crates.io', 'docs.rs', 'doc.rust-lang.org', 'learn.microsoft.com', 'developer.apple.com',
|
|
@@ -21,7 +21,7 @@ export function fetchDecision(owner, role, raw) {
|
|
|
21
21
|
if (trustedHost(host)) return null;
|
|
22
22
|
const carries = Boolean(url.search || url.hash), known = owner.fetchHosts?.has(host);
|
|
23
23
|
if (role !== 'main') return carries || !known ? 'refuse' : null;
|
|
24
|
-
if (
|
|
24
|
+
if (asksOnlyHandoff(owner)) return carries ? 'ask' : null;
|
|
25
25
|
return carries || !known ? 'ask' : null;
|
|
26
26
|
}
|
|
27
27
|
export async function guardFetch(owner, role, raw, id, signal, ctx) {
|
|
@@ -2,6 +2,7 @@ import fs from 'node:fs';
|
|
|
2
2
|
import os from 'node:os';
|
|
3
3
|
import { spawn } from 'node:child_process';
|
|
4
4
|
import { redactedText } from '../runtime/managed-failure.mjs';
|
|
5
|
+
import { commandSegments, stripWrapper } from '../runtime/policy/handoff-policy.mjs';
|
|
5
6
|
|
|
6
7
|
// Commands the member approved to run on their machine, outside the sandbox
|
|
7
8
|
// (run_on_host, start_docker): installing a runtime the project needs, git
|
|
@@ -13,12 +14,14 @@ import { redactedText } from '../runtime/managed-failure.mjs';
|
|
|
13
14
|
const PASSWORD = new Set(['sudo', 'doas', 'su', 'pkexec', 'passwd']);
|
|
14
15
|
const SIGN_IN = [/^gh auth (login|refresh)\b/, /^(npm|pnpm) (login|adduser)\b/, /^yarn npm login\b/, /^docker login\b(?!.*--password-stdin)/, /^az login\b/,
|
|
15
16
|
/^gcloud auth (login|application-default login)\b/, /^aws (configure\s*$|sso login\b)/, /^(firebase|vercel|wrangler|heroku|netlify) login\b/];
|
|
16
|
-
|
|
17
|
+
// Read through the shared shell parser (policy-core.js): `(sudo ls)`,
|
|
18
|
+
// `echo x & sudo ls` and `if …; then sudo …` are each a sudo.
|
|
17
19
|
export function memberOnlyReason(command) {
|
|
18
|
-
for (const
|
|
19
|
-
const words =
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
for (const { words } of commandSegments(command)) {
|
|
21
|
+
const run = stripWrapper(words), prefix = words.slice(0, words.length - run.length).map(word => word.split('/').pop());
|
|
22
|
+
const elevated = prefix.find(word => PASSWORD.has(word));
|
|
23
|
+
if (elevated) return `${elevated} needs the member's password`;
|
|
24
|
+
const name = run[0], rest = run.join(' ');
|
|
22
25
|
if (PASSWORD.has(name)) return `${name} needs the member's password`;
|
|
23
26
|
if (name === 'installer' || name === 'softwareupdate') return `${name} needs the member's password`;
|
|
24
27
|
if (SIGN_IN.some(rule => rule.test(rest))) return 'an interactive sign-in needs the member';
|
|
@@ -26,8 +29,13 @@ export function memberOnlyReason(command) {
|
|
|
26
29
|
return null;
|
|
27
30
|
}
|
|
28
31
|
// Where credentials live on the member's machine. A command that names one
|
|
29
|
-
// reads or moves secrets, so it is asked about even in Bypass.
|
|
30
|
-
|
|
32
|
+
// reads or moves secrets, so it is asked about even in Bypass. A text check,
|
|
33
|
+
// not a boundary: it catches the usual spellings (~/.ssh, $HOME/.ssh,
|
|
34
|
+
// /Users/me/.ssh, `tar -C ~ .ssh`); the sandbox is what keeps secrets out of
|
|
35
|
+
// plain bash. Folders whose names projects also use (.docker, .pi) count only
|
|
36
|
+
// under a home directory.
|
|
37
|
+
const HOME = String.raw`(?:~|\$HOME|\$\{HOME\}|/Users/[^/\s'"]+|/home/[^/\s'"]+|/root)/`;
|
|
38
|
+
const CREDENTIALS = [/(^|[\s'"=:/])\.(ssh|aws|gnupg|kube|azure|npmrc|netrc|pypirc|git-credentials)(\b|\/|$)/, new RegExp(String.raw`${HOME}\.(docker|pi|codex|claude|piagent|config/gh|config/gcloud)\b`),
|
|
31
39
|
/(^|[\s'"/])\.env(\.[\w-]+)?\b/, /\bauth\.json\b/, /\bcredentials(\.json)?\b/, /\bid_(rsa|ed25519|ecdsa|dsa)\b/, /\.(pem|p12|pfx|key)\b/,
|
|
32
40
|
/\bsecurity\s+(find-(generic|internet)-password|dump-keychain|export)\b/, /Library\/Keychains\b/, /\bprintenv\b|(^|[;&|]\s*)env\s*($|[|;&>])/];
|
|
33
41
|
export function credentialReason(command) {
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { evaluateMcpApproval } from '../runtime/mcp-repository-gate.mjs';
|
|
5
|
+
import { mcpWriteAction } from '../runtime/policy/handoff-policy.mjs';
|
|
6
|
+
import { userToolchains } from './toolchain.mjs';
|
|
7
|
+
import { fenced } from './untrusted.mjs';
|
|
8
|
+
|
|
9
|
+
// The member's MCP servers in company sessions. Company sessions load no Pi
|
|
10
|
+
// extension of the member's, with one exception: the MCP adapter Piagent
|
|
11
|
+
// installs (pi-mcp-adapter in Piagent's own Pi home). It reads the same
|
|
12
|
+
// configuration as personal Piagent (piagent-mcp add, ~/.config/mcp/mcp.json,
|
|
13
|
+
// a project's .mcp.json, /mcp) and the same logins (/mcp-auth), so a server the
|
|
14
|
+
// member added once works in both. The member decides which servers exist;
|
|
15
|
+
// company sessions keep the protections personal Piagent has: a server a
|
|
16
|
+
// repository defines runs only once someone on this machine approved it, a
|
|
17
|
+
// tool that writes to the server's system (create, update, push, merge,
|
|
18
|
+
// publish, send… in its name) is asked about in every access mode, Bypass
|
|
19
|
+
// included, since it hands work to the outside, and what a server returns
|
|
20
|
+
// reaches the agent as data, not instructions.
|
|
21
|
+
|
|
22
|
+
const ADAPTER = 'pi-mcp-adapter';
|
|
23
|
+
const readJson = file => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } };
|
|
24
|
+
const inside = (file, dir) => { const relative = path.relative(dir, file); return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative); };
|
|
25
|
+
|
|
26
|
+
// The adapter the member installed in Piagent's Pi home and still lists among
|
|
27
|
+
// its packages, or null. `piagent studio` starts from a cleared environment, so
|
|
28
|
+
// the home is the default one (~/.piagent/agent) unless a caller names another.
|
|
29
|
+
export function memberMcpAdapter(home = os.homedir(), agentDir = path.join(home, '.piagent', 'agent')) {
|
|
30
|
+
const packages = readJson(path.join(agentDir, 'settings.json'))?.packages;
|
|
31
|
+
const listed = Array.isArray(packages) && packages.some(entry => new RegExp(`(^|[:/])${ADAPTER}(@|$)`).test(String(typeof entry === 'string' ? entry : entry?.source ?? '')));
|
|
32
|
+
const dir = path.join(agentDir, 'npm', 'node_modules', ADAPTER);
|
|
33
|
+
if (!listed || !fs.existsSync(path.join(dir, 'package.json'))) return null;
|
|
34
|
+
return { agentDir, dir: fs.realpathSync(dir) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// What the adapter and the servers it starts need from a cleared environment:
|
|
38
|
+
// Piagent's Pi home (its mcp.json, logins and caches, shared with personal
|
|
39
|
+
// Piagent) and a PATH that finds npx, uvx, docker… as in the member's
|
|
40
|
+
// Terminal. Nothing else of the member's shell is passed, as for host commands.
|
|
41
|
+
export function memberMcpEnvironment(adapter, home = os.homedir(), env = process.env) {
|
|
42
|
+
env.PI_CODING_AGENT_DIR ||= adapter.agentDir;
|
|
43
|
+
const toolchains = userToolchains(home);
|
|
44
|
+
const dirs = [...toolchains.bins, path.dirname(process.execPath), '/opt/homebrew/bin', '/usr/local/bin', ...(env.PATH ?? '/usr/bin:/bin').split(':')];
|
|
45
|
+
env.PATH = [...new Set(dirs.filter(Boolean))].join(':');
|
|
46
|
+
for (const [name, value] of Object.entries(toolchains.env)) env[name] ||= value;
|
|
47
|
+
return env;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The MCP tool a call runs: the proxy's `tool` (`mcp` with tool and server),
|
|
51
|
+
// or a direct tool the adapter registered. null for anything else.
|
|
52
|
+
export function mcpToolCalled(toolName, input, fromAdapter) {
|
|
53
|
+
if (toolName === 'mcp') return typeof input?.tool === 'string' && input.tool.trim() ? { tool: input.tool.trim(), server: String(input.server ?? '').trim() } : null;
|
|
54
|
+
return fromAdapter(toolName) ? { tool: toolName, server: '' } : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The repository approval gate on every tool call (as personal Piagent's
|
|
58
|
+
// guard), the member's approval of an MCP write, and the adapter's results
|
|
59
|
+
// fenced as data. Without an owner (no conversation to ask in) a write is refused.
|
|
60
|
+
export function memberMcpGuard(cwd, adapterDir, owner = null) {
|
|
61
|
+
return pi => {
|
|
62
|
+
const fromAdapter = name => { const source = pi.getAllTools().find(tool => tool.name === name)?.sourceInfo?.path; return !!source && (source === adapterDir || inside(source, adapterDir)); };
|
|
63
|
+
pi.on('tool_call', async (event, ctx) => {
|
|
64
|
+
const decision = evaluateMcpApproval(cwd, event.toolName, event.input ?? {});
|
|
65
|
+
if (decision.block) return { block: true, reason: decision.reason };
|
|
66
|
+
const called = mcpToolCalled(event.toolName, event.input, fromAdapter);
|
|
67
|
+
const action = called && await mcpWriteAction(called.tool);
|
|
68
|
+
if (!action) return undefined;
|
|
69
|
+
if (!owner) return { block: true, reason: `MCP tool ${called.tool} writes outside (${action}) and no member can approve it here.` };
|
|
70
|
+
const { approve } = await import('./command-tools.mjs');
|
|
71
|
+
const name = called.server ? `${called.server} → ${called.tool}` : called.tool, args = JSON.stringify(event.input?.args ?? event.input ?? {}).slice(0, 600);
|
|
72
|
+
try {
|
|
73
|
+
await approve(owner, event.toolCallId, ctx?.signal, ctx, { toolName: event.toolName, rawAction: { tool: called.tool, server: called.server, input: event.input ?? {} }, commandPreview: name,
|
|
74
|
+
provider: called.server || 'mcp', requestedScope: 'mcp-handoff-once', reason: `The MCP tool ${name} writes outside this machine (${action}); every access mode asks before a handoff.`, riskClass: 'high',
|
|
75
|
+
allowConsequence: 'Run this exact MCP call once; it changes the system behind that server.', denyConsequence: 'The call does not run; the agent is told you declined.' },
|
|
76
|
+
{ title: 'Công cụ MCP ghi ra ngoài', body: `${name}\n${args}\n\nCông cụ này ${action} trên hệ thống của server MCP. Mọi chế độ truy cập, kể cả Bypass, đều hỏi trước việc bàn giao ra ngoài.\n\nĐồng ý: chạy đúng lệnh gọi này một lần.\nTừ chối: không chạy, agent được báo bạn đã từ chối.` });
|
|
77
|
+
} catch { return { block: true, reason: `User denied MCP tool ${name}.` }; }
|
|
78
|
+
return undefined;
|
|
79
|
+
});
|
|
80
|
+
pi.on('tool_result', event => {
|
|
81
|
+
if (!fromAdapter(event.toolName)) return undefined;
|
|
82
|
+
const text = (event.content ?? []).filter(part => part?.type === 'text').map(part => part.text).join('\n');
|
|
83
|
+
const images = (event.content ?? []).filter(part => part?.type === 'image');
|
|
84
|
+
return { content: [{ type: 'text', text: fenced(`Result of MCP tool ${event.toolName}`, text) }, ...images] };
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// The company session's own extension factories, with the member's MCP added
|
|
90
|
+
// when the adapter is installed: [factories, extension paths] for inlineExtensions.
|
|
91
|
+
export function withMemberMcp(cwd, factories, home = os.homedir(), owner = null) {
|
|
92
|
+
const adapter = memberMcpAdapter(home);
|
|
93
|
+
if (!adapter) return [factories, []];
|
|
94
|
+
memberMcpEnvironment(adapter, home);
|
|
95
|
+
return [[...factories, memberMcpGuard(cwd, adapter.dir, owner)], [adapter.dir]];
|
|
96
|
+
}
|
|
@@ -8,7 +8,7 @@ import { createHash } from 'node:crypto';
|
|
|
8
8
|
import { redactedText } from '../runtime/managed-failure.mjs';
|
|
9
9
|
import { isCheckCommand } from './workflow.mjs';
|
|
10
10
|
|
|
11
|
-
const COMMAND_TOOLS = new Set(['bash','run_with_network','run_with_docker','run_on_host']);
|
|
11
|
+
const COMMAND_TOOLS = new Set(['bash','run_with_network','run_with_docker','run_on_host','run_on_simulator']);
|
|
12
12
|
const textOf = result => (result?.content ?? []).filter(p => p?.type === 'text').map(p => p.text ?? '').join('\n');
|
|
13
13
|
const clean = (value, max) => redactedText(String(value ?? '')).replace(/\bas_(?:live|run)_[A-Za-z0-9_-]{8,}/g,'[REDACTED_SECRET]').split(os.homedir()).join('~').replace(/\s+/g,' ').trim().slice(0,max);
|
|
14
14
|
const hash = s => createHash('sha256').update(s).digest('hex').slice(0,20);
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// A company conversation's access, chosen by the member and kept with the
|
|
2
|
-
// conversation
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
2
|
+
// conversation (runtime/policy/handoff-policy.mjs has both lists):
|
|
3
|
+
// "workspace-write" (Ask first) asks before every command that leaves the
|
|
4
|
+
// sandbox; "trusted-full-access" (Full access) asks only about the handoff and
|
|
5
|
+
// what is destructive (mustConfirm); "bypass" runs the work and asks only about
|
|
6
|
+
// the handoff (handoffReason: push, PR, publish, deploy, remote and cloud
|
|
7
|
+
// tools, uploads), where the team's Harness allows it
|
|
6
8
|
// (harness.configuration.bypass_mode, an administrator's switch in Studio).
|
|
7
|
-
// The sandbox itself stays: bypass removes
|
|
8
|
-
import { mustConfirm } from '../runtime/policy/
|
|
9
|
+
// The sandbox itself stays: bypass removes questions, not the boundary.
|
|
10
|
+
import { handoffReason, mustConfirm } from '../runtime/policy/handoff-policy.mjs';
|
|
9
11
|
|
|
10
12
|
export const PERMISSIONS = ['workspace-write', 'trusted-full-access', 'bypass'];
|
|
11
13
|
const ENTRY = 'agent-watch-permission';
|
|
@@ -36,10 +38,15 @@ export function recordBypass(owner, manager) {
|
|
|
36
38
|
const last = manager.getEntries().filter(e => e.type === 'custom' && e.customType === ALLOWANCE).at(-1)?.data;
|
|
37
39
|
if ((last?.allowed === true) !== allowed) manager.appendCustomEntry(ALLOWANCE, { allowed, at: new Date().toISOString() });
|
|
38
40
|
}
|
|
39
|
-
// Whether this conversation
|
|
40
|
-
|
|
41
|
+
// Whether this conversation skips the questions Full access still asks
|
|
42
|
+
// (everything but the handoff).
|
|
43
|
+
export const asksOnlyHandoff = owner => effectivePermission(owner) === 'bypass';
|
|
41
44
|
export const broadAccess = owner => ['trusted-full-access', 'bypass'].includes(effectivePermission(owner));
|
|
42
|
-
// Why a
|
|
43
|
-
//
|
|
44
|
-
export const networkConfirmation = async (owner, command) =>
|
|
45
|
-
|
|
45
|
+
// Why a command that leaves the sandbox must be asked about: the reason, or
|
|
46
|
+
// 'ask' in Ask first, or null to run it. Every mode asks about the handoff.
|
|
47
|
+
export const networkConfirmation = async (owner, command) => {
|
|
48
|
+
const mode = effectivePermission(owner);
|
|
49
|
+
if (mode === 'bypass') return handoffReason(command);
|
|
50
|
+
if (mode === 'trusted-full-access') return mustConfirm(command);
|
|
51
|
+
return 'ask';
|
|
52
|
+
};
|
|
@@ -107,7 +107,7 @@ export async function executeRepositoryFetch(boundary,plan,signal,{transport=fet
|
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
// The fetch_origin tool of a company conversation: one approved fetch of the
|
|
110
|
-
// GitHub origin (Bypass
|
|
110
|
+
// GitHub origin (Full access and Bypass fetch without asking: it only downloads).
|
|
111
111
|
export function fetchOriginTool(self) {
|
|
112
112
|
return {name:'fetch_origin',label:'Fetch origin',description:'Request one approved GitHub origin fetch. Refreshes origin branches without changing working files. Does not expose credentials or allow arbitrary network commands. When the conversation folder holds several repositories, pass path: the repository folder inside it. Use this instead of git fetch, which has no GitHub sign-in here.',
|
|
113
113
|
parameters:{type:'object',properties:{path:{type:'string',maxLength:500,description:'Repository folder inside the conversation folder, such as "api"; omit when the conversation folder is the repository.'}},additionalProperties:false},
|