replicas-engine 0.1.933 → 0.1.935

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.
@@ -5,13 +5,15 @@ import {
5
5
  ENGINE_ENV,
6
6
  monolithRequest,
7
7
  setAgentCredentialSnapshot
8
- } from "./chunk-3GJEQKPY.js";
8
+ } from "./chunk-SJLJNLTL.js";
9
9
  import {
10
10
  AppServerProcess,
11
+ buildCodexAgentEnv
12
+ } from "./chunk-5S4DHSVO.js";
13
+ import {
11
14
  SUBPROCESS_MAX_BUFFER,
12
- buildCodexAgentEnv,
13
15
  execFileAsync
14
- } from "./chunk-BXHF65NV.js";
16
+ } from "./chunk-4MN6PV5T.js";
15
17
  import {
16
18
  isRecord
17
19
  } from "./chunk-UZSNFLDQ.js";
@@ -25,7 +27,7 @@ import {
25
27
  listOpenAICompatibleModels,
26
28
  readOllamaAuthEnv,
27
29
  resolveOpenAICompatibleModelsUrl
28
- } from "./chunk-RVSMHQVH.js";
30
+ } from "./chunk-7AHZJSWR.js";
29
31
 
30
32
  // src/managers/codex-token-manager.ts
31
33
  import { promises as fs } from "fs";
@@ -258,7 +260,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
258
260
  await this.applyCredentialUpdate(++this.credentialGeneration, async () => {
259
261
  await this.applyCredentialsResponse(data);
260
262
  setAgentCredentialSnapshot("codex", data);
261
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-V5JMSPLS.js");
263
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-TNBLV7CZ.js");
262
264
  await restartCodexAspHostIfRunning2();
263
265
  });
264
266
  await this.start(true);
@@ -278,7 +280,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
278
280
  await this.applyCredentialUpdate(generation, async () => {
279
281
  await this.applyCredentialsResponse(data);
280
282
  if (restartOnChange && CODEX_AUTH_ENV_KEYS.some((key, index) => process.env[key] !== previousEnv[index])) {
281
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-V5JMSPLS.js");
283
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-TNBLV7CZ.js");
282
284
  await restartCodexAspHostIfRunning2();
283
285
  }
284
286
  setAgentCredentialSnapshot("codex", data);
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'node:module';
3
+ const require = __createRequire(import.meta.url);
4
+ import {
5
+ monolithRequest
6
+ } from "./chunk-SJLJNLTL.js";
7
+ import {
8
+ SUBPROCESS_MAX_BUFFER,
9
+ execFileAsync
10
+ } from "./chunk-4MN6PV5T.js";
11
+ import {
12
+ extractCommandProtectionCommandText,
13
+ findCommandProtectionGitLookups,
14
+ findGitCommitSignals,
15
+ findPrMergeSignals,
16
+ parseCommandProtectionRequest
17
+ } from "./chunk-7AHZJSWR.js";
18
+
19
+ // src/services/command-protection-service.ts
20
+ import { readFile, stat } from "fs/promises";
21
+
22
+ // src/git/commands.ts
23
+ import { readdirSync, readFileSync, statSync } from "fs";
24
+ import { join, resolve } from "path";
25
+ async function runGitCommand(args, cwd, options = {}) {
26
+ const { stdout } = await execFileAsync("git", args, {
27
+ cwd,
28
+ encoding: "utf-8",
29
+ maxBuffer: options.maxBuffer ?? SUBPROCESS_MAX_BUFFER
30
+ });
31
+ return stdout.trim();
32
+ }
33
+ function readRepoHeadBranches(repoPath) {
34
+ const branches = /* @__PURE__ */ new Set();
35
+ try {
36
+ let gitDir = join(repoPath, ".git");
37
+ if (statSync(gitDir).isFile()) {
38
+ const target = readFileSync(gitDir, "utf8").trim().match(/^gitdir: (.+)$/)?.[1];
39
+ if (!target) return branches;
40
+ gitDir = resolve(repoPath, target);
41
+ }
42
+ let commonDir = gitDir;
43
+ try {
44
+ commonDir = resolve(gitDir, readFileSync(join(gitDir, "commondir"), "utf8").trim());
45
+ } catch {
46
+ }
47
+ const headDirs = /* @__PURE__ */ new Set([gitDir, commonDir]);
48
+ try {
49
+ for (const entry of readdirSync(join(commonDir, "worktrees"))) {
50
+ headDirs.add(join(commonDir, "worktrees", entry));
51
+ }
52
+ } catch {
53
+ }
54
+ for (const dir of headDirs) {
55
+ try {
56
+ const branch = readFileSync(join(dir, "HEAD"), "utf8").trim().match(/^ref:\s+refs\/heads\/(.+)$/)?.[1];
57
+ if (branch) branches.add(branch);
58
+ } catch {
59
+ }
60
+ }
61
+ } catch {
62
+ }
63
+ return branches;
64
+ }
65
+ async function branchExists(branchName, cwd) {
66
+ try {
67
+ await runGitCommand(["rev-parse", "--verify", branchName], cwd);
68
+ return true;
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
73
+ async function getOriginDefaultBranch(repoPath) {
74
+ try {
75
+ const output = await runGitCommand(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], repoPath);
76
+ return output.match(/^origin\/(.+)$/)?.[1] ?? null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+ async function getCurrentBranch(cwd) {
82
+ try {
83
+ return await runGitCommand(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
84
+ } catch (error) {
85
+ console.error("Error getting current branch:", error);
86
+ return null;
87
+ }
88
+ }
89
+ async function resolveDiffBase(repoPath, defaultBranch) {
90
+ const baseBranch = `origin/${defaultBranch}`;
91
+ try {
92
+ return await runGitCommand(["merge-base", baseBranch, "HEAD"], repoPath);
93
+ } catch {
94
+ }
95
+ return await branchExists(baseBranch, repoPath) ? baseBranch : "HEAD";
96
+ }
97
+
98
+ // src/services/command-protection-service.ts
99
+ var DEFAULT_COMMAND_PROTECTION_BLOCK_MESSAGE = "Blocked by Replicas command protection.";
100
+ var MAX_COMMIT_MESSAGE_FILE_BYTES = 64 * 1024;
101
+ async function resolveGitContext({ repoDirs, messageFiles }) {
102
+ if (repoDirs.length === 0 && messageFiles.length === 0) return void 0;
103
+ const git = (dir, args) => runGitCommand(args, dir).then((output) => output || null, () => null);
104
+ const [repos, files] = await Promise.all([
105
+ Promise.all(repoDirs.map(async (dir) => {
106
+ const [branch, defaultBranch, pushBranch, pushConfig, headMessage, mergeHead] = await Promise.all([
107
+ git(dir, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
108
+ getOriginDefaultBranch(dir),
109
+ git(dir, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{push}"]),
110
+ git(dir, ["config", "--get-regexp", "^(push\\.default|push\\.pushoption|remote\\..+\\.push)$"]),
111
+ git(dir, ["log", "-1", "--format=%B"]),
112
+ git(dir, ["rev-parse", "--quiet", "--verify", "MERGE_HEAD"])
113
+ ]);
114
+ return [dir, { branch, defaultBranch, pushBranch: pushBranch?.replace(/^[^/]+\//, "") ?? null, pushConfig, headMessage, mergeInProgress: mergeHead !== null }];
115
+ })),
116
+ Promise.all(messageFiles.map(async (path) => {
117
+ const info = await stat(path).catch(() => null);
118
+ const content = info?.isFile() && info.size <= MAX_COMMIT_MESSAGE_FILE_BYTES ? await readFile(path, "utf8").catch(() => null) : null;
119
+ return content === null ? [] : [[path, content]];
120
+ }))
121
+ ]);
122
+ return { repos: Object.fromEntries(repos), messageFiles: Object.fromEntries(files.flat()) };
123
+ }
124
+ function asCommandProtectionResponse(value) {
125
+ if (typeof value !== "object" || value === null) return null;
126
+ const candidate = value;
127
+ return typeof candidate.allowed === "boolean" && typeof candidate.enabled === "boolean" ? candidate : null;
128
+ }
129
+ function failClosed(reason, matchedSignals) {
130
+ return {
131
+ allowed: false,
132
+ enabled: true,
133
+ reason,
134
+ matchedSignals
135
+ };
136
+ }
137
+ async function evaluateCommandProtection(request, signal) {
138
+ const parsed = parseCommandProtectionRequest(request);
139
+ const gitContext = await resolveGitContext(findCommandProtectionGitLookups(parsed));
140
+ const matchedSignals = [...findGitCommitSignals(parsed), ...findPrMergeSignals(parsed, gitContext).signals];
141
+ if (matchedSignals.length === 0) {
142
+ return { allowed: true, enabled: true };
143
+ }
144
+ let response;
145
+ try {
146
+ response = await monolithRequest("/v1/engine/command-protection/evaluate", {
147
+ body: { ...request, gitContext },
148
+ signal
149
+ });
150
+ } catch (error) {
151
+ const detail = error instanceof Error ? error.message : String(error);
152
+ return failClosed(`Command protection failed closed: ${detail}`, matchedSignals);
153
+ }
154
+ if (!response.ok) {
155
+ const detail = await response.text().catch(() => "");
156
+ return failClosed(`Command protection failed closed: ${response.status} ${detail}`, matchedSignals);
157
+ }
158
+ let payload;
159
+ try {
160
+ payload = await response.json();
161
+ } catch (error) {
162
+ const detail = error instanceof Error ? error.message : String(error);
163
+ return failClosed(`Command protection failed closed: ${detail}`, matchedSignals);
164
+ }
165
+ return asCommandProtectionResponse(payload) ?? failClosed("Command protection failed closed: invalid response from policy service", matchedSignals);
166
+ }
167
+ function extractToolCommand(input) {
168
+ return extractCommandProtectionCommandText({ toolInput: input }, { stringifyFallback: false });
169
+ }
170
+ function reportCommandProtectionBlock(options) {
171
+ const message = options.result.reason || DEFAULT_COMMAND_PROTECTION_BLOCK_MESSAGE;
172
+ console.warn(`[${options.managerName}] blocked ${options.action} by command protection: ${message}`);
173
+ options.recordHistoryEvent(options.eventType, {
174
+ type: "error",
175
+ message,
176
+ ...options.context,
177
+ command: options.command
178
+ }, options.historyFile);
179
+ return message;
180
+ }
181
+
182
+ export {
183
+ runGitCommand,
184
+ readRepoHeadBranches,
185
+ getOriginDefaultBranch,
186
+ getCurrentBranch,
187
+ resolveDiffBase,
188
+ evaluateCommandProtection,
189
+ extractToolCommand,
190
+ reportCommandProtectionBlock
191
+ };
@@ -5,7 +5,7 @@ import {
5
5
  extractCommandProtectionCommandText,
6
6
  isRecord,
7
7
  parseCodeHostPrUrl
8
- } from "./chunk-RVSMHQVH.js";
8
+ } from "./chunk-7AHZJSWR.js";
9
9
 
10
10
  // src/services/published-pull-request-urls.ts
11
11
  function publishedPullRequestUrls(result) {
@@ -15,7 +15,7 @@ import {
15
15
  isValidRelayBaseProvider,
16
16
  parsePosixEnvFile,
17
17
  readReplicasRuntimeEnv
18
- } from "./chunk-RVSMHQVH.js";
18
+ } from "./chunk-7AHZJSWR.js";
19
19
 
20
20
  // src/runtime-env-loader.ts
21
21
  import { readFileSync } from "fs";
@@ -3,12 +3,13 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  evaluateCommandProtection
6
- } from "./chunk-SY46VC2H.js";
7
- import "./chunk-3GJEQKPY.js";
6
+ } from "./chunk-H4VNL5V4.js";
7
+ import "./chunk-SJLJNLTL.js";
8
+ import "./chunk-4MN6PV5T.js";
8
9
  import {
9
10
  isRecord
10
11
  } from "./chunk-UZSNFLDQ.js";
11
- import "./chunk-RVSMHQVH.js";
12
+ import "./chunk-7AHZJSWR.js";
12
13
  import "./chunk-VEQXQN22.js";
13
14
 
14
15
  // src/command-protection-hook.ts
@@ -43,7 +44,7 @@ async function main() {
43
44
  source: `${provider}_pre_tool_use`,
44
45
  toolName,
45
46
  toolInput,
46
- cwd: typeof payload.cwd === "string" ? payload.cwd : process.cwd(),
47
+ cwd: typeof payload.cwd === "string" && payload.cwd ? payload.cwd : process.cwd(),
47
48
  toolUseId: typeof payload.tool_use_id === "string" ? payload.tool_use_id : typeof payload.call_id === "string" ? payload.call_id : null
48
49
  };
49
50
  const result = await evaluateCommandProtection(request);
@@ -8,12 +8,13 @@ import {
8
8
  import {
9
9
  AppServerProcess,
10
10
  buildCodexAgentEnv
11
- } from "./chunk-BXHF65NV.js";
11
+ } from "./chunk-5S4DHSVO.js";
12
+ import "./chunk-4MN6PV5T.js";
12
13
  import {
13
14
  AGENT,
14
15
  getMemoryOutputSafetyViolation,
15
16
  headlessAgentRequestSchema
16
- } from "./chunk-RVSMHQVH.js";
17
+ } from "./chunk-7AHZJSWR.js";
17
18
  import "./chunk-VEQXQN22.js";
18
19
 
19
20
  // src/headless-agent.ts