replicas-engine 0.1.1568 → 0.1.1570

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.
@@ -8,12 +8,12 @@ import {
8
8
  listCodexModelsForDetails,
9
9
  restartCodexAspHost,
10
10
  restartCodexAspHostIfRunning
11
- } from "./chunk-ZWEREWXJ.js";
12
- import "./chunk-7FVNF42B.js";
13
- import "./chunk-EBBW3C3P.js";
14
- import "./chunk-ESMEMGKJ.js";
11
+ } from "./chunk-3YA2C54Q.js";
12
+ import "./chunk-PBLPGIS2.js";
13
+ import "./chunk-YYZKHJUU.js";
14
+ import "./chunk-6XMZQCK4.js";
15
15
  import "./chunk-UZSNFLDQ.js";
16
- import "./chunk-7TTATCCE.js";
16
+ import "./chunk-DX6ZXVYZ.js";
17
17
  import "./chunk-VEQXQN22.js";
18
18
  export {
19
19
  CODEX_ULTRAFAST_SERVICE_TIER,
@@ -6,7 +6,7 @@ import {
6
6
  getOriginDefaultBranch,
7
7
  monolithRequest,
8
8
  runGitCommand
9
- } from "./chunk-7FVNF42B.js";
9
+ } from "./chunk-PBLPGIS2.js";
10
10
  import {
11
11
  extractCommandProtectionCommandText,
12
12
  findCommandProtectionGitLookups,
@@ -15,7 +15,7 @@ import {
15
15
  findScoutRepoWriteSignals,
16
16
  parseCommandProtectionRequest,
17
17
  withE2BRetry
18
- } from "./chunk-7TTATCCE.js";
18
+ } from "./chunk-DX6ZXVYZ.js";
19
19
 
20
20
  // src/services/command-protection-service.ts
21
21
  import { readFile, stat } from "fs/promises";
@@ -8,18 +8,19 @@ import {
8
8
  getOriginDefaultBranch,
9
9
  monolithRequest,
10
10
  readRepoHeadBranches,
11
+ readRuntimeEnvFile,
11
12
  resolveDiffBase,
12
13
  runGitCommand,
13
14
  setAgentCredentialSnapshot
14
- } from "./chunk-7FVNF42B.js";
15
+ } from "./chunk-PBLPGIS2.js";
15
16
  import {
16
17
  AppServerProcess,
17
18
  buildCodexAgentEnv
18
- } from "./chunk-EBBW3C3P.js";
19
+ } from "./chunk-YYZKHJUU.js";
19
20
  import {
20
21
  SUBPROCESS_MAX_BUFFER,
21
22
  execFileAsync
22
- } from "./chunk-ESMEMGKJ.js";
23
+ } from "./chunk-6XMZQCK4.js";
23
24
  import {
24
25
  isRecord
25
26
  } from "./chunk-UZSNFLDQ.js";
@@ -57,7 +58,7 @@ import {
57
58
  resolveOpenAICompatibleModelsUrl,
58
59
  splitMothershipInstructions,
59
60
  withTimeout
60
- } from "./chunk-7TTATCCE.js";
61
+ } from "./chunk-DX6ZXVYZ.js";
61
62
 
62
63
  // src/managers/codex-token-manager.ts
63
64
  import { promises as fs } from "fs";
@@ -299,6 +300,139 @@ var BaseRefreshManager = class {
299
300
  }
300
301
  };
301
302
 
303
+ // src/utils/transcript-secrets.ts
304
+ var BACKSLASH = 92;
305
+ var FILLER = 42;
306
+ var SECRET_NAME = /KEY|TOKEN|SECRET|PASSWORD|PASSWD|PASSCODE|CREDENTIAL|PRIVATE|DSN|TOTP|COOKIE/i;
307
+ var PASSWORD_NAME = /SECRET|PASSWORD|PASSWD|PASSCODE/i;
308
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
309
+ var WHOLE_WORD_BELOW = 16;
310
+ var KEPT_REPLACEMENTS = 8;
311
+ var REPLACED_KEPT_MS = 24 * 60 * 60 * 1e3;
312
+ var currentBySource = /* @__PURE__ */ new Map();
313
+ var replacedBySource = /* @__PURE__ */ new Map();
314
+ var found = /* @__PURE__ */ new Set();
315
+ var variablesVersion = 0;
316
+ function remember(source, values) {
317
+ const previous = currentBySource.get(source) ?? [];
318
+ if (previous.join("\n") === values.join("\n")) return;
319
+ if (!source.startsWith("credential:")) variablesVersion++;
320
+ currentBySource.set(source, values);
321
+ if (previous.length > 0) replacedBySource.set(source, [{ values: previous, at: Date.now() }, ...replacedBySource.get(source) ?? []]);
322
+ }
323
+ function looksLikeCredential(value) {
324
+ return value.length >= 16 && /[A-Za-z]/.test(value) && /\d/.test(value) && (/[A-Z_]/.test(value) || value.length >= 32) && !value.startsWith("/") && !value.includes("://") && !UUID.test(value) && !/^[0-9a-f]{40}$/.test(value) && !/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(value);
325
+ }
326
+ function isNamedSecret(value, password = false) {
327
+ return value.length >= 8 && !/^(true|false|yes|no|on|off|\d+)$/i.test(value) && !value.startsWith("/") && (/[^A-Za-z]/.test(value) || value.length >= (password ? 12 : 16));
328
+ }
329
+ function credentialTokens(text) {
330
+ return text.split(/[^A-Za-z0-9._~+/=-]+/).filter(looksLikeCredential);
331
+ }
332
+ function urlCredentials(value) {
333
+ if (!/^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(value)) return null;
334
+ try {
335
+ const url = new URL(value);
336
+ const query = [...url.searchParams].flatMap(([name, part]) => SECRET_NAME.test(name) && isNamedSecret(part) ? [part, encodeURIComponent(part)] : []);
337
+ if (url.password) return [...query, ...[url.password, decodeURIComponent(url.password)].filter((part) => isNamedSecret(part, true))];
338
+ return [...query, ...[url.username, decodeURIComponent(url.username)].filter(looksLikeCredential)];
339
+ } catch {
340
+ return null;
341
+ }
342
+ }
343
+ function variableSecrets(key, value) {
344
+ if (!value) return [];
345
+ const fromUrl = urlCredentials(value);
346
+ if (fromUrl) return fromUrl;
347
+ if (SECRET_NAME.test(key)) return value.includes("\n") ? credentialTokens(value) : isNamedSecret(value, PASSWORD_NAME.test(key)) ? [value] : [];
348
+ return !key.startsWith("REPLICAS_") && !/\s/.test(value) && looksLikeCredential(value) ? [value] : [];
349
+ }
350
+ function rememberCredentials(source, text) {
351
+ remember(`credential:${source}`, credentialTokens(text));
352
+ }
353
+ function rememberSecret(source, value) {
354
+ remember(`credential:${source}`, value.length >= 8 ? [value] : []);
355
+ }
356
+ function transcriptSecrets() {
357
+ for (const [key, value] of Object.entries(process.env)) remember(`env:${key}`, variableSecrets(key, value));
358
+ for (const [key, value] of Object.entries(readRuntimeEnvFile()?.values ?? {})) remember(`runtime:${key}`, variableSecrets(key, value));
359
+ for (const [source, replaced2] of replacedBySource) {
360
+ replacedBySource.set(source, replaced2.filter(({ at }, index) => index < KEPT_REPLACEMENTS || Date.now() - at <= REPLACED_KEPT_MS));
361
+ }
362
+ const replaced = [...replacedBySource.values()].flatMap((entries) => entries.flatMap(({ values }) => values));
363
+ return { secrets: [.../* @__PURE__ */ new Set([...[...currentBySource.values()].flat(), ...replaced, ...found])], variablesVersion };
364
+ }
365
+ function needlesFor(secrets) {
366
+ const escape = (value) => JSON.stringify(value).slice(1, -1);
367
+ const bySecretForm = new Map(secrets.flatMap((secret) => [[escape(secret), secret], [escape(escape(secret)), secret]]));
368
+ return [...bySecretForm].map(([form, secret]) => ({ needle: Buffer.from(form), secret })).sort((a, b) => b.needle.length - a.needle.length);
369
+ }
370
+ function wordAt(buffer, at) {
371
+ return buffer[at] | buffer[at + 1] << 8 | buffer[at + 2] << 16 | buffer[at + 3] << 24;
372
+ }
373
+ function prefixSlot(prefix) {
374
+ return Math.imul(prefix, 2654435761) >>> 16;
375
+ }
376
+ function isWordByte(byte) {
377
+ return byte !== void 0 && (byte >= 48 && byte <= 57 || (byte | 32) >= 97 && (byte | 32) <= 122);
378
+ }
379
+ async function* scrubSecrets(chunks, secrets) {
380
+ const needles = needlesFor(secrets);
381
+ if (needles.length === 0) {
382
+ yield* chunks;
383
+ return;
384
+ }
385
+ let tail = Buffer.alloc(0);
386
+ let carriedBackslashes = 0;
387
+ const byteAt = (buffer, index) => index >= 0 ? buffer[index] : tail[tail.length + index];
388
+ const backslashesBefore = (buffer, position) => {
389
+ let start = position;
390
+ while (start > 0 && buffer[start - 1] === BACKSLASH) start--;
391
+ return position - start + (start === 0 ? carriedBackslashes : 0);
392
+ };
393
+ const standsAlone = (buffer, at, needle) => {
394
+ if (backslashesBefore(buffer, at) % 2 === 1) return false;
395
+ if (needle.length >= WHOLE_WORD_BELOW) return true;
396
+ const joinsWordBefore = isWordByte(byteAt(buffer, at - 1)) && byteAt(buffer, at - 2) !== BACKSLASH;
397
+ return !joinsWordBefore && !isWordByte(buffer[at + needle.length]);
398
+ };
399
+ const byPrefix = /* @__PURE__ */ new Map();
400
+ const prefixes = new Uint8Array(1 << 16);
401
+ for (const entry of needles) {
402
+ const prefix = wordAt(entry.needle, 0);
403
+ byPrefix.set(prefix, [...byPrefix.get(prefix) ?? [], entry]);
404
+ prefixes[prefixSlot(prefix)] = 1;
405
+ }
406
+ const scrub = (buffer, end) => {
407
+ const parts = [];
408
+ let at = 0;
409
+ for (let index = 0; index < end && index + 4 <= buffer.length; index++) {
410
+ const prefix = wordAt(buffer, index);
411
+ if (prefixes[prefixSlot(prefix)] === 0) continue;
412
+ const match = byPrefix.get(prefix)?.find(({ needle }) => index + needle.length <= buffer.length && buffer.compare(needle, 0, needle.length, index, index + needle.length) === 0 && standsAlone(buffer, index, needle));
413
+ if (!match) continue;
414
+ found.add(match.secret);
415
+ parts.push(buffer.subarray(at, index), Buffer.alloc(match.needle.length, FILLER));
416
+ at = index + match.needle.length;
417
+ index = at - 1;
418
+ }
419
+ const stop = Math.max(at, end);
420
+ parts.push(buffer.subarray(at, stop));
421
+ carriedBackslashes = backslashesBefore(buffer, stop);
422
+ tail = stop >= 2 ? Buffer.from(buffer.subarray(stop - 2, stop)) : Buffer.concat([tail, buffer.subarray(0, stop)]).subarray(-2);
423
+ return { scrubbed: Buffer.concat(parts), rest: buffer.subarray(stop) };
424
+ };
425
+ let rest = Buffer.alloc(0);
426
+ for await (const chunk of chunks) {
427
+ const buffer = rest.length > 0 ? Buffer.concat([rest, chunk]) : chunk;
428
+ const result = scrub(buffer, buffer.length - needles[0].needle.length);
429
+ rest = result.rest;
430
+ if (result.scrubbed.length > 0) yield result.scrubbed;
431
+ }
432
+ const last = scrub(rest, rest.length);
433
+ if (last.scrubbed.length > 0) yield last.scrubbed;
434
+ }
435
+
302
436
  // src/managers/codex-token-manager.ts
303
437
  var CodexAspAuthMethodChangedError = class extends Error {
304
438
  name = "CodexAspAuthMethodChangedError";
@@ -320,7 +454,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
320
454
  await this.applyCredentialUpdate(++this.credentialGeneration, async () => {
321
455
  await this.applyCredentialsResponse(data);
322
456
  setAgentCredentialSnapshot("codex", data);
323
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-6XRYGQA5.js");
457
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-3S4FME54.js");
324
458
  await restartCodexAspHostIfRunning2();
325
459
  });
326
460
  await this.start(true);
@@ -342,7 +476,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
342
476
  const accountChanged = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex?.credentialId !== data.credentialId;
343
477
  await this.applyCredentialsResponse(data);
344
478
  if (restartOnChange && (accountChanged || CODEX_AUTH_ENV_KEYS.some((key, index) => process.env[key] !== previousEnv[index]))) {
345
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-6XRYGQA5.js");
479
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-3S4FME54.js");
346
480
  await restartCodexAspHostIfRunning2();
347
481
  }
348
482
  setAgentCredentialSnapshot("codex", data);
@@ -433,6 +567,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
433
567
  }
434
568
  buildAspOauthLogin(response) {
435
569
  const credential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex;
570
+ rememberSecret("codex", response.accessToken);
436
571
  return {
437
572
  tokens: {
438
573
  accessToken: response.accessToken,
@@ -519,6 +654,7 @@ async function writeSecureCredentialFile(filePath, content, options) {
519
654
  if (options?.ensureParentDir) {
520
655
  await mkdir(dirname(filePath), { recursive: true, mode: 448 });
521
656
  }
657
+ rememberCredentials(filePath, content);
522
658
  await atomicWriteFile(filePath, content, { mode: 384 });
523
659
  }
524
660
  async function configureManagedGitCredentialHelper(homeDir) {
@@ -2116,6 +2252,9 @@ export {
2116
2252
  refreshDelayMs,
2117
2253
  BaseRefreshManager,
2118
2254
  AsyncLock,
2255
+ rememberSecret,
2256
+ transcriptSecrets,
2257
+ scrubSecrets,
2119
2258
  atomicWriteFile,
2120
2259
  writeSecureCredentialFile,
2121
2260
  configureManagedGitCredentialHelper,
@@ -3,7 +3,7 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  HOOK_EXEC_MAX_BUFFER_BYTES
6
- } from "./chunk-7TTATCCE.js";
6
+ } from "./chunk-DX6ZXVYZ.js";
7
7
 
8
8
  // src/utils/exec.ts
9
9
  import { exec, execFile } from "child_process";
@@ -20156,7 +20156,7 @@ var VOICE_WAVEFORM = {
20156
20156
  };
20157
20157
 
20158
20158
  // ../shared/src/e2b.ts
20159
- var E2B_TEMPLATE_NAME = "replicas-sandbox-2026-11-14-v23";
20159
+ var E2B_TEMPLATE_NAME = "replicas-sandbox-2026-11-14-v25";
20160
20160
 
20161
20161
  // ../shared/src/e2b-retry.ts
20162
20162
  var DEFAULT_BACKOFFS_MS = [2e3, 5e3];
@@ -22656,6 +22656,7 @@ export {
22656
22656
  formatChatForkHandoffMessage,
22657
22657
  formatChatForkUpdateMessage,
22658
22658
  threadHandoffText,
22659
+ INTERRUPTED_MESSAGE_REGEX,
22659
22660
  isToolInputQuestion,
22660
22661
  fileContentDiff,
22661
22662
  skillNamesFromCommand,
@@ -4,7 +4,7 @@ const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  SUBPROCESS_MAX_BUFFER,
6
6
  execFileAsync
7
- } from "./chunk-ESMEMGKJ.js";
7
+ } from "./chunk-6XMZQCK4.js";
8
8
  import {
9
9
  isRecord as isRecord2
10
10
  } from "./chunk-UZSNFLDQ.js";
@@ -21,7 +21,7 @@ import {
21
21
  provisionedDeviceSchema,
22
22
  readReplicasRuntimeEnv,
23
23
  serializePosixEnvFile
24
- } from "./chunk-7TTATCCE.js";
24
+ } from "./chunk-DX6ZXVYZ.js";
25
25
 
26
26
  // src/runtime-env-loader.ts
27
27
  import { readFileSync } from "fs";
@@ -3,7 +3,7 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  AspClient
6
- } from "./chunk-EBBW3C3P.js";
6
+ } from "./chunk-YYZKHJUU.js";
7
7
  import {
8
8
  ASTER_BASE_URL,
9
9
  ASTER_PROVIDER,
@@ -15,7 +15,7 @@ import {
15
15
  isRecord,
16
16
  readOllamaAuthEnv,
17
17
  readOpenAICompatibleAuthEnv
18
- } from "./chunk-7TTATCCE.js";
18
+ } from "./chunk-DX6ZXVYZ.js";
19
19
 
20
20
  // src/managers/codex-asp/notification-dispatch.ts
21
21
  var TURN_STARTED_METHOD = "turn/started";
@@ -5,7 +5,7 @@ import {
5
5
  extractCommandProtectionCommandText,
6
6
  isRecord,
7
7
  parseCodeHostPrUrl
8
- } from "./chunk-7TTATCCE.js";
8
+ } from "./chunk-DX6ZXVYZ.js";
9
9
 
10
10
  // src/services/published-pull-request-urls.ts
11
11
  function publishedPullRequestUrls(result) {
@@ -3,10 +3,10 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  execFileAsync
6
- } from "./chunk-ESMEMGKJ.js";
6
+ } from "./chunk-6XMZQCK4.js";
7
7
  import {
8
8
  isVersionBelow
9
- } from "./chunk-7TTATCCE.js";
9
+ } from "./chunk-DX6ZXVYZ.js";
10
10
 
11
11
  // src/utils/codex-agent-env.ts
12
12
  function buildCodexAgentEnv(source = process.env) {
@@ -240,7 +240,7 @@ function getCodexModelProvider(method) {
240
240
  if (method === "foundry") return "azure";
241
241
  return method === "ollama" || method === "openai-compatible" ? "replicas_openai_compatible" : "openai";
242
242
  }
243
- var ENGINE_PACKAGE_VERSION = "0.1.1568";
243
+ var ENGINE_PACKAGE_VERSION = "0.1.1570";
244
244
  var INITIALIZE_METHOD = "initialize";
245
245
  var INITIALIZED_NOTIFICATION = "initialized";
246
246
  var ACCOUNT_LOGIN_START_METHOD = "account/login/start";
@@ -3,13 +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-PNCQ6TO3.js";
7
- import "./chunk-7FVNF42B.js";
8
- import "./chunk-ESMEMGKJ.js";
6
+ } from "./chunk-2NMHGUPB.js";
7
+ import "./chunk-PBLPGIS2.js";
8
+ import "./chunk-6XMZQCK4.js";
9
9
  import {
10
10
  isRecord
11
11
  } from "./chunk-UZSNFLDQ.js";
12
- import "./chunk-7TTATCCE.js";
12
+ import "./chunk-DX6ZXVYZ.js";
13
13
  import "./chunk-VEQXQN22.js";
14
14
 
15
15
  // src/command-protection-hook.ts
@@ -14,12 +14,12 @@ import {
14
14
  recoverCompletedTurn,
15
15
  spawnMuseMsp,
16
16
  startMuseSession
17
- } from "./chunk-JPF2AS7Z.js";
17
+ } from "./chunk-REWJIHF5.js";
18
18
  import {
19
19
  AppServerProcess,
20
20
  buildCodexAgentEnv
21
- } from "./chunk-EBBW3C3P.js";
22
- import "./chunk-ESMEMGKJ.js";
21
+ } from "./chunk-YYZKHJUU.js";
22
+ import "./chunk-6XMZQCK4.js";
23
23
  import {
24
24
  AGENT,
25
25
  OPENCODE_GO_PROVIDER,
@@ -29,7 +29,7 @@ import {
29
29
  headlessAgentUsagePath,
30
30
  isRecord,
31
31
  withTimeout
32
- } from "./chunk-7TTATCCE.js";
32
+ } from "./chunk-DX6ZXVYZ.js";
33
33
  import "./chunk-VEQXQN22.js";
34
34
 
35
35
  // src/headless-agent.ts
package/dist/src/index.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  evaluateCommandProtection,
28
28
  extractToolCommand,
29
29
  reportCommandProtectionBlock
30
- } from "./chunk-PNCQ6TO3.js";
30
+ } from "./chunk-2NMHGUPB.js";
31
31
  import {
32
32
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
33
33
  AGENT_MESSAGE_DELTA_METHOD,
@@ -65,10 +65,10 @@ import {
65
65
  spawnMuseMsp,
66
66
  startMuseSession,
67
67
  uuidV7
68
- } from "./chunk-JPF2AS7Z.js";
68
+ } from "./chunk-REWJIHF5.js";
69
69
  import {
70
70
  publishedPullRequestUrls
71
- } from "./chunk-IB2AB57H.js";
71
+ } from "./chunk-XUBGPHNS.js";
72
72
  import {
73
73
  ACCOUNT_RATE_LIMITS_READ_METHOD,
74
74
  AsyncLock,
@@ -132,18 +132,21 @@ import {
132
132
  recordExhaustedCredential,
133
133
  recordFallbackModel,
134
134
  refreshDelayMs,
135
+ rememberSecret,
135
136
  removeCredentialFileLines,
136
137
  removeTempImageFiles,
137
138
  restartCodexAspHost,
138
139
  routineRefreshRequest,
139
140
  saveRepoState,
141
+ scrubSecrets,
140
142
  subagentMcpProcessConfig,
141
143
  threadToAspTranscript,
142
144
  timestampFromMilliseconds,
143
145
  timestampFromSeconds,
146
+ transcriptSecrets,
144
147
  upsertCredentialFileLines,
145
148
  writeSecureCredentialFile
146
- } from "./chunk-ZWEREWXJ.js";
149
+ } from "./chunk-3YA2C54Q.js";
147
150
  import {
148
151
  ENGINE_ENV,
149
152
  UNQUOTED_PATHS_CONFIG,
@@ -154,15 +157,15 @@ import {
154
157
  resolveDiffBase,
155
158
  setAgentCredentialSnapshot,
156
159
  setLinearSessionId
157
- } from "./chunk-7FVNF42B.js";
160
+ } from "./chunk-PBLPGIS2.js";
158
161
  import {
159
162
  getCodexModelProvider
160
- } from "./chunk-EBBW3C3P.js";
163
+ } from "./chunk-YYZKHJUU.js";
161
164
  import {
162
165
  SUBPROCESS_MAX_BUFFER,
163
166
  execAsync,
164
167
  execFileAsync
165
- } from "./chunk-ESMEMGKJ.js";
168
+ } from "./chunk-6XMZQCK4.js";
166
169
  import {
167
170
  isRecord as isRecord2
168
171
  } from "./chunk-UZSNFLDQ.js";
@@ -234,6 +237,7 @@ import {
234
237
  HOOK_EXEC_MAX_BUFFER_BYTES,
235
238
  IDENTITY_PROXY_PORT,
236
239
  IDENTITY_TOKEN_PATH,
240
+ INTERRUPTED_MESSAGE_REGEX,
237
241
  InFlightMap,
238
242
  LEARNED_SKILLS_MANIFEST_PATH,
239
243
  LEARNED_SKILL_DIR_PREFIX,
@@ -443,7 +447,7 @@ import {
443
447
  workspaceTokenRequestSchema,
444
448
  workspaceTokenResponseSchema,
445
449
  wrapInTag
446
- } from "./chunk-7TTATCCE.js";
450
+ } from "./chunk-DX6ZXVYZ.js";
447
451
  import {
448
452
  cloneMcpConfig,
449
453
  ensureCompatibilityImports,
@@ -9503,6 +9507,7 @@ var WorkspaceIdentityTokens = class {
9503
9507
  return createErrorResult({ message: "AWS source identity is unavailable from this Replicas version", code: 503 });
9504
9508
  }
9505
9509
  }
9510
+ rememberSecret(`identity:${audience}:${awsSourceIdentity}`, token.token);
9506
9511
  return createSuccessResult({ token, refreshAt: Date.parse(token.expires_at) - MIN_REMAINING_MS });
9507
9512
  }
9508
9513
  };
@@ -9683,6 +9688,7 @@ var McpOAuthTokens = class {
9683
9688
  const message = isRecord(data) && typeof data.error === "string" ? data.error : `MCP OAuth token request failed: ${response.status}`;
9684
9689
  return createErrorResult({ message, code: response.ok ? 502 : response.status });
9685
9690
  }
9691
+ rememberSecret(`mcp:${environmentMcpId}`, parsed.data.access_token);
9686
9692
  const remaining = parsed.data.expires_at ? Date.parse(parsed.data.expires_at) - Date.now() : Infinity;
9687
9693
  return createSuccessResult({
9688
9694
  token: parsed.data,
@@ -12096,8 +12102,11 @@ ${request.message}` }, senderKey };
12096
12102
  return this.messageQueue.isProcessing();
12097
12103
  }
12098
12104
  // A steer still in flight either reaches the agent or goes back on the queue, so it is read once it settles.
12099
- async queuedRequests() {
12105
+ async steersSettled() {
12100
12106
  while (this.steerSettlements.size > 0) await Promise.allSettled(this.steerSettlements);
12107
+ }
12108
+ async queuedRequests() {
12109
+ await this.steersSettled();
12101
12110
  return [...[...this.unreadSteers.values()].map(({ message }) => message), ...this.messageQueue.getQueue()];
12102
12111
  }
12103
12112
  getQueue() {
@@ -12197,11 +12206,12 @@ ${note}` };
12197
12206
  }
12198
12207
  async sendNow(messageId) {
12199
12208
  await this.initialized;
12209
+ await this.steersSettled();
12200
12210
  const queued = this.messageQueue.getQueue().some(({ id }) => id === messageId);
12201
12211
  if (!queued && !this.unreadSteers.has(messageId)) return { success: false, queue: this.getQueue() };
12202
12212
  if (this.messageQueue.isProcessing() && (!queued || (await this.steerFromQueue(messageId)).success)) {
12203
- if (this.unreadSteers.has(messageId) && this.canDeliverSteersNow()) await this.deliverSteersNow();
12204
- return { success: true, queue: this.getQueue() };
12213
+ const delivered = !this.unreadSteers.has(messageId) || !this.canDeliverSteersNow() || await this.deliverSteersNow();
12214
+ return { success: delivered, queue: this.getQueue() };
12205
12215
  }
12206
12216
  this.requeueUnreadSteers();
12207
12217
  const taken = this.messageQueue.takeFromQueue(messageId);
@@ -12244,7 +12254,7 @@ ${note}` };
12244
12254
  return false;
12245
12255
  }
12246
12256
  deliverSteersNow() {
12247
- return Promise.resolve();
12257
+ return Promise.resolve(true);
12248
12258
  }
12249
12259
  steerRequest(_request) {
12250
12260
  return Promise.resolve(false);
@@ -13201,6 +13211,8 @@ function isClaudeSessionActive(activity) {
13201
13211
  // src/managers/claude-background-tasks.ts
13202
13212
  var ClaudeBackgroundTasks = class {
13203
13213
  active = /* @__PURE__ */ new Set();
13214
+ // Background agents and workflows end on an interrupt; shell commands keep running.
13215
+ runsAgents = false;
13204
13216
  // The main agent's blocking tasks, by tool_use id; a subagent's own commands are its to wait on.
13205
13217
  foreground = /* @__PURE__ */ new Map();
13206
13218
  // A task counts as the main agent's only when its tool call is one the main agent made, so a task
@@ -13208,6 +13220,7 @@ var ClaudeBackgroundTasks = class {
13208
13220
  mainToolUses = /* @__PURE__ */ new Set();
13209
13221
  reset() {
13210
13222
  this.active.clear();
13223
+ this.runsAgents = false;
13211
13224
  this.foreground.clear();
13212
13225
  this.mainToolUses.clear();
13213
13226
  }
@@ -13227,6 +13240,7 @@ var ClaudeBackgroundTasks = class {
13227
13240
  }
13228
13241
  if (message.subtype !== "background_tasks_changed") return;
13229
13242
  this.active.clear();
13243
+ this.runsAgents = message.tasks.some((task) => task.task_type !== "local_bash");
13230
13244
  for (const task of message.tasks) {
13231
13245
  if (!task.ambient) this.active.add(task.task_id);
13232
13246
  }
@@ -13499,6 +13513,12 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13499
13513
  stoppedTurnEnded = null;
13500
13514
  // Claude Code writes a started prompt to the session transcript even when the turn then fails, so a retry must not resend it.
13501
13515
  turnPromptRecorded = false;
13516
+ endedReplies = /* @__PURE__ */ new Set();
13517
+ // Whether the cut landed in time; kept until Claude Code answers the interrupt, however late.
13518
+ pendingCut = null;
13519
+ // The time of the press, so the stop line is dated when the person cut the reply, not when Claude Code reports it.
13520
+ cutSentAt = null;
13521
+ compacting = false;
13502
13522
  // Claude Code never sees a prompt stopped before it started, so it is sent again with the next message.
13503
13523
  unreadPrompt = null;
13504
13524
  runningTools = /* @__PURE__ */ new Map();
@@ -13574,12 +13594,42 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
13574
13594
  this.unreadPrompt = { uuid, content: appendUserContent(this.unreadPrompt?.content ?? [], message.content) };
13575
13595
  return true;
13576
13596
  }
13597
+ // A steer is read when the tool call in flight returns; with none, Claude Code reads it only once the whole reply is written.
13598
+ // An interrupt would also end background agents and make a compaction start over, and one sent once the reply is cut or over would cut the reply to the steer itself.
13599
+ repliesInFlight() {
13600
+ const turn = this.pendingTurn;
13601
+ if (!turn || !this.turnPromptRecorded || this.compacting || this.runningTools.size > 0 || this.backgroundTasks.runsAgents) return [];
13602
+ return [...turn.userMessageUuids].filter((uuid) => !turn.steers.has(uuid) && !this.endedReplies.has(uuid));
13603
+ }
13577
13604
  canDeliverSteersNow() {
13578
- return this.activeQuery !== null && this.backgroundTasks.foreground.size > 0;
13605
+ return this.activeQuery !== null && (this.backgroundTasks.foreground.size > 0 || this.pendingCut !== null || this.repliesInFlight().length > 0);
13579
13606
  }
13580
13607
  async deliverSteersNow() {
13581
13608
  const query2 = this.activeQuery;
13582
- if (query2) await Promise.all([...this.backgroundTasks.foreground.values()].map((toolUseId) => query2.backgroundTasks(toolUseId)));
13609
+ if (!query2) return true;
13610
+ const foreground = [...this.backgroundTasks.foreground.values()];
13611
+ if (foreground.length > 0) {
13612
+ await Promise.all(foreground.map((toolUseId) => query2.backgroundTasks(toolUseId)));
13613
+ return true;
13614
+ }
13615
+ if (this.pendingCut) return this.pendingCut;
13616
+ const cut = this.repliesInFlight();
13617
+ for (const uuid of cut) this.endedReplies.add(uuid);
13618
+ this.cutSentAt = (/* @__PURE__ */ new Date()).toISOString();
13619
+ const answered = query2.interrupt().then(
13620
+ () => true,
13621
+ () => {
13622
+ for (const uuid of cut) this.endedReplies.delete(uuid);
13623
+ this.cutSentAt = null;
13624
+ return false;
13625
+ }
13626
+ );
13627
+ const pending = raceWithTimeout(answered, CLAUDE_INTERRUPT_TIMEOUT_MS).then((landed) => landed === true);
13628
+ this.pendingCut = pending;
13629
+ void answered.then(() => {
13630
+ if (this.pendingCut === pending) this.pendingCut = null;
13631
+ });
13632
+ return pending;
13583
13633
  }
13584
13634
  // Claude Code folds a `next`-priority prompt into the running turn at its next tool boundary.
13585
13635
  async steerRequest(request) {
@@ -14183,6 +14233,8 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14183
14233
  return;
14184
14234
  }
14185
14235
  this.turnPromptRecorded = false;
14236
+ this.endedReplies.clear();
14237
+ this.cutSentAt = null;
14186
14238
  try {
14187
14239
  await new Promise((resolve7, reject) => {
14188
14240
  const steers = options.steers ?? /* @__PURE__ */ new Map();
@@ -14439,6 +14491,8 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14439
14491
  if (name && this.pendingInterrupt && block.is_error && extractToolResultText(block.content, "").startsWith(CLAUDE_STOPPED_TOOL_RESULT)) this.cutOffTools.set(block.tool_use_id, name);
14440
14492
  }
14441
14493
  }
14494
+ if (msg.type === "result" && msg.user_message_uuid) for (const uuid of msg.user_message_uuids ?? [msg.user_message_uuid]) this.endedReplies.add(uuid);
14495
+ if (msg.type === "system" && msg.subtype === "status") this.compacting = msg.status === "compacting";
14442
14496
  if (this.pendingInterrupt) {
14443
14497
  if (msg.type === "user") await this.recordEvent(msg);
14444
14498
  else if (msg.type === "assistant") {
@@ -14454,6 +14508,11 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
14454
14508
  } else if (msg.type === "result") this.stoppedTurnEnded?.resolve();
14455
14509
  continue;
14456
14510
  }
14511
+ if (this.cutSentAt && (msg.type === "result" ? msg.terminal_reason === "aborted_streaming" || msg.terminal_reason === "aborted_tools" : msg.type === "user" && msg.parent_tool_use_id === null && Array.isArray(msg.message.content) && msg.message.content.some((block) => block.type === "text" && INTERRUPTED_MESSAGE_REGEX.test(block.text)))) {
14512
+ this.recordInterrupted(this.cutSentAt, true);
14513
+ this.cutSentAt = null;
14514
+ }
14515
+ if (msg.type === "result") this.cutSentAt = null;
14457
14516
  if (msg.type === "assistant" && msg.error === "invalid_request" && msg.message.model === "<synthetic>") {
14458
14517
  heldRefusal = msg;
14459
14518
  continue;
@@ -14595,6 +14654,8 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
14595
14654
  this.partialMessageFlushTimers.clear();
14596
14655
  this.partialMessageStreams.clear();
14597
14656
  this.runningTools.clear();
14657
+ this.pendingCut = null;
14658
+ this.compacting = false;
14598
14659
  if (hadBackgroundTasks && !this.isProcessing()) this.onProcessingChanged(false);
14599
14660
  }
14600
14661
  resolvePendingTurn() {
@@ -61035,14 +61096,16 @@ async function uploadOpenedTranscript(chatId, opened, historyVersion, chat, capt
61035
61096
  };
61036
61097
  const settled = Date.now() - mtimeMs > 1e3;
61037
61098
  const target = `${chatId}:${capture ? "capture" : "canonical"}`;
61038
- const fingerprint = JSON.stringify({ size, mtimeMs, metadata });
61099
+ const { secrets, variablesVersion } = transcriptSecrets();
61100
+ const fingerprint = JSON.stringify({ size, mtimeMs, metadata, variablesVersion });
61039
61101
  const last = lastUploadByTarget.get(target);
61040
61102
  if (last?.fingerprint === fingerprint) {
61041
61103
  return capture ? { ...last.artifact, metadata: { ...last.artifact.metadata, captureId: capture.captureId } } : null;
61042
61104
  }
61105
+ const scrubbedBytes = () => scrubSecrets(logBytes(opened), secrets);
61043
61106
  if (capture) {
61044
61107
  const hash = createHash8("sha256");
61045
- for await (const chunk of logBytes(opened)) hash.update(chunk);
61108
+ for await (const chunk of scrubbedBytes()) hash.update(chunk);
61046
61109
  metadata.captureId = capture.captureId;
61047
61110
  metadata.captureReason = capture.reason;
61048
61111
  metadata.sha256 = hash.digest("hex");
@@ -61059,7 +61122,7 @@ async function uploadOpenedTranscript(chatId, opened, historyVersion, chat, capt
61059
61122
  throw new Error("prepare failed: invalid response");
61060
61123
  }
61061
61124
  if (prepareBody.uploadUrl === null) return null;
61062
- await putPresignedFile(prepareBody.uploadUrl, Readable.from(logBytes(opened)), size, "application/x-ndjson");
61125
+ await putPresignedFile(prepareBody.uploadUrl, Readable.from(scrubbedBytes()), size, "application/x-ndjson");
61063
61126
  const finalizeResponse = await monolithRequest("/v1/engine/chat-transcripts/finalize", {
61064
61127
  body: uploadRequest
61065
61128
  });
@@ -62342,7 +62405,8 @@ ${decisions}` };
62342
62405
  async sendNow(chatId, messageId) {
62343
62406
  const chat = this.requireChat(chatId);
62344
62407
  const result = await chat.provider.sendNow(messageId);
62345
- if (result.success && !result.queue.some(({ id, steeredAt }) => id === messageId && !steeredAt)) {
62408
+ const waiting = result.queue.find(({ id }) => id === messageId);
62409
+ if (waiting ? waiting.steeredAt : result.success) {
62346
62410
  chat.pendingMessageIds = chat.pendingMessageIds.filter((pendingMessageId) => pendingMessageId !== messageId);
62347
62411
  this.publishQueueIfChanged(chatId);
62348
62412
  }
@@ -3,13 +3,13 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  publishedPullRequestUrls
6
- } from "./chunk-IB2AB57H.js";
6
+ } from "./chunk-XUBGPHNS.js";
7
7
  import {
8
8
  isRecord
9
9
  } from "./chunk-UZSNFLDQ.js";
10
10
  import {
11
11
  shouldRefreshPullRequests
12
- } from "./chunk-7TTATCCE.js";
12
+ } from "./chunk-DX6ZXVYZ.js";
13
13
  import "./chunk-VEQXQN22.js";
14
14
 
15
15
  // src/services/post-tool-pr-notifier.ts
@@ -11,7 +11,7 @@ import {
11
11
  spawnSubagentRequestSchema,
12
12
  subagentResponseSchema,
13
13
  waitSubagentRequestSchema
14
- } from "./chunk-7TTATCCE.js";
14
+ } from "./chunk-DX6ZXVYZ.js";
15
15
  import "./chunk-VEQXQN22.js";
16
16
 
17
17
  // src/subagent-mcp.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replicas-engine",
3
- "version": "0.1.1568",
3
+ "version": "0.1.1570",
4
4
  "description": "Lightweight API server for Replicas workspaces",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",