replicas-engine 0.1.1727 → 0.1.1730

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,13 +8,13 @@ import {
8
8
  listCodexModelsForDetails,
9
9
  restartCodexAspHost,
10
10
  restartCodexAspHostIfRunning
11
- } from "./chunk-OAFO4KYM.js";
12
- import "./chunk-M6ELG3GK.js";
13
- import "./chunk-OY6X5AUJ.js";
14
- import "./chunk-F2YDU3AP.js";
15
- import "./chunk-NTSUADYM.js";
11
+ } from "./chunk-KBE3MXTD.js";
12
+ import "./chunk-2HQP6MMR.js";
13
+ import "./chunk-BUJZF6CI.js";
14
+ import "./chunk-PIZ63O3B.js";
15
+ import "./chunk-O2BDFDEA.js";
16
16
  import "./chunk-UZSNFLDQ.js";
17
- import "./chunk-GBVHK7GR.js";
17
+ import "./chunk-J6MIIMDU.js";
18
18
  import "./chunk-VEQXQN22.js";
19
19
  export {
20
20
  CODEX_ULTRAFAST_SERVICE_TIER,
@@ -3,7 +3,7 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  SUBAGENT_MCP_TOOL_NAMES
6
- } from "./chunk-GBVHK7GR.js";
6
+ } from "./chunk-J6MIIMDU.js";
7
7
 
8
8
  // src/managers/subagent-mcp-config.ts
9
9
  import { existsSync } from "fs";
@@ -4,7 +4,7 @@ const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  SUBPROCESS_MAX_BUFFER,
6
6
  execFileAsync
7
- } from "./chunk-NTSUADYM.js";
7
+ } from "./chunk-O2BDFDEA.js";
8
8
  import {
9
9
  isRecord
10
10
  } from "./chunk-UZSNFLDQ.js";
@@ -21,7 +21,7 @@ import {
21
21
  provisionedDeviceSchema,
22
22
  readReplicasRuntimeEnv,
23
23
  serializePosixEnvFile
24
- } from "./chunk-GBVHK7GR.js";
24
+ } from "./chunk-J6MIIMDU.js";
25
25
 
26
26
  // src/runtime-env-loader.ts
27
27
  import { readFileSync } from "fs";
@@ -5,7 +5,7 @@ import {
5
5
  extractCommandProtectionCommandText,
6
6
  isRecord,
7
7
  parseCodeHostPrUrl
8
- } from "./chunk-GBVHK7GR.js";
8
+ } from "./chunk-J6MIIMDU.js";
9
9
 
10
10
  // src/services/published-pull-request-urls.ts
11
11
  function publishedPullRequestUrls(result) {
@@ -21806,6 +21806,9 @@ function percentage(tokens, maxTokens) {
21806
21806
  if (!maxTokens || maxTokens <= 0) return 0;
21807
21807
  return clampPercentage(tokens / maxTokens * 100);
21808
21808
  }
21809
+ function providerContextUsage(usage) {
21810
+ return { ...usage, source: "provider_usage", percentage: percentage(usage.totalTokens, usage.maxTokens), categories: [], updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
21811
+ }
21809
21812
  function autoCompactThresholdField(autoCompactThreshold) {
21810
21813
  return typeof autoCompactThreshold === "number" && Number.isFinite(autoCompactThreshold) ? { autoCompactThreshold } : {};
21811
21814
  }
@@ -21977,7 +21980,7 @@ async function withRetry(label, fn, options) {
21977
21980
  }
21978
21981
 
21979
21982
  // ../shared/src/tensorlake.ts
21980
- var TENSORLAKE_IMAGE_NAME = "replicas-sandbox-2026-11-22-v7918";
21983
+ var TENSORLAKE_IMAGE_NAME = "replicas-sandbox-2026-11-22-v8494";
21981
21984
  var TENSORLAKE_DISK_MB = 100 * 1024;
21982
21985
 
21983
21986
  // ../shared/src/egress.ts
@@ -24583,6 +24586,7 @@ export {
24583
24586
  canonicalizeChatTranscriptBlocks,
24584
24587
  lastUserBlockText,
24585
24588
  percentage,
24589
+ providerContextUsage,
24586
24590
  autoCompactThresholdField,
24587
24591
  normalizeAutoCompactThreshold,
24588
24592
  clampTokensToWindow,
@@ -24616,6 +24620,7 @@ export {
24616
24620
  parseProxyRouteCheck,
24617
24621
  headlessAgentRequestSchema,
24618
24622
  headlessAgentUsagePath,
24623
+ isAuthenticationErrorText,
24619
24624
  isClaudeAuthErrorText,
24620
24625
  isCodexAuthError,
24621
24626
  serializeMuseAuthFile,
@@ -3,7 +3,7 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  subagentCodexMcpConfig
6
- } from "./chunk-M6ELG3GK.js";
6
+ } from "./chunk-2HQP6MMR.js";
7
7
  import {
8
8
  ENGINE_ENV,
9
9
  UNQUOTED_PATHS_CONFIG,
@@ -15,15 +15,15 @@ import {
15
15
  resolveDiffBase,
16
16
  runGitCommand,
17
17
  setAgentCredentialSnapshot
18
- } from "./chunk-OY6X5AUJ.js";
18
+ } from "./chunk-BUJZF6CI.js";
19
19
  import {
20
20
  AppServerProcess,
21
21
  buildCodexAgentEnv
22
- } from "./chunk-F2YDU3AP.js";
22
+ } from "./chunk-PIZ63O3B.js";
23
23
  import {
24
24
  SUBPROCESS_MAX_BUFFER,
25
25
  execFileAsync
26
- } from "./chunk-NTSUADYM.js";
26
+ } from "./chunk-O2BDFDEA.js";
27
27
  import {
28
28
  isRecord
29
29
  } from "./chunk-UZSNFLDQ.js";
@@ -68,7 +68,7 @@ import {
68
68
  shrunkImageSize,
69
69
  splitManagerInstructions,
70
70
  withTimeout
71
- } from "./chunk-GBVHK7GR.js";
71
+ } from "./chunk-J6MIIMDU.js";
72
72
 
73
73
  // src/managers/codex-token-manager.ts
74
74
  import { promises as fs } from "fs";
@@ -340,7 +340,7 @@ async function withdrawAgentLogin(provider, { envKeys, files }) {
340
340
  { ...persisted.values, REPLICAS_AGENT_CREDENTIALS: JSON.stringify(remaining) },
341
341
  /* @__PURE__ */ new Set([...persisted.unsetKeys, ...envKeys])
342
342
  ));
343
- if (provider === "codex") await (await import("./asp-host-TWRX3YXW.js")).restartCodexAspHostIfRunning();
343
+ if (provider === "codex") await (await import("./asp-host-K3ISVMG6.js")).restartCodexAspHostIfRunning();
344
344
  return true;
345
345
  }
346
346
 
@@ -498,7 +498,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
498
498
  await this.applyCredentialUpdate(++this.credentialGeneration, async () => {
499
499
  await this.applyCredentialsResponse(data);
500
500
  setAgentCredentialSnapshot("codex", data);
501
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-TWRX3YXW.js");
501
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-K3ISVMG6.js");
502
502
  await restartCodexAspHostIfRunning2();
503
503
  });
504
504
  await this.start(true);
@@ -524,7 +524,7 @@ var CodexTokenManager = class extends BaseRefreshManager {
524
524
  const accountChanged = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex?.credentialId !== data.credentialId;
525
525
  await this.applyCredentialsResponse(data);
526
526
  if (restartOnChange && (accountChanged || CODEX_AUTH_ENV_KEYS.some((key, index) => process.env[key] !== previousEnv[index]))) {
527
- const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-TWRX3YXW.js");
527
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-K3ISVMG6.js");
528
528
  await restartCodexAspHostIfRunning2();
529
529
  }
530
530
  setAgentCredentialSnapshot("codex", data);
@@ -5,7 +5,7 @@ import {
5
5
  ENGINE_ENV,
6
6
  monolithRequest,
7
7
  runGitCommand
8
- } from "./chunk-OY6X5AUJ.js";
8
+ } from "./chunk-BUJZF6CI.js";
9
9
  import {
10
10
  COMMAND_PROTECTION_MAX_MESSAGE_FILE_BYTES,
11
11
  COMMAND_PROTECTION_REPO_GIT_ARGS,
@@ -18,7 +18,7 @@ import {
18
18
  parseCommandProtectionRequest,
19
19
  toCommandProtectionRepoState,
20
20
  withRetry
21
- } from "./chunk-GBVHK7GR.js";
21
+ } from "./chunk-J6MIIMDU.js";
22
22
 
23
23
  // src/services/command-protection-service.ts
24
24
  import { readFile, stat } from "fs/promises";
@@ -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-GBVHK7GR.js";
6
+ } from "./chunk-J6MIIMDU.js";
7
7
 
8
8
  // src/utils/exec.ts
9
9
  import { exec, execFile } from "child_process";
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-XCFPXSY4.js";
7
7
  import {
8
8
  engineScriptProcess
9
- } from "./chunk-M6ELG3GK.js";
9
+ } from "./chunk-2HQP6MMR.js";
10
10
  import {
11
11
  isRecord
12
12
  } from "./chunk-UZSNFLDQ.js";
@@ -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-NTSUADYM.js";
6
+ } from "./chunk-O2BDFDEA.js";
7
7
  import {
8
8
  isVersionBelow
9
- } from "./chunk-GBVHK7GR.js";
9
+ } from "./chunk-J6MIIMDU.js";
10
10
 
11
11
  // src/utils/codex-agent-env.ts
12
12
  function buildCodexAgentEnv(source = process.env) {
@@ -244,7 +244,7 @@ function getCodexModelProvider(method) {
244
244
  if (method === "foundry") return "azure";
245
245
  return method === "ollama" || method === "openai-compatible" ? "replicas_openai_compatible" : "openai";
246
246
  }
247
- var ENGINE_PACKAGE_VERSION = "0.1.1727";
247
+ var ENGINE_PACKAGE_VERSION = "0.1.1730";
248
248
  var INITIALIZE_METHOD = "initialize";
249
249
  var INITIALIZED_NOTIFICATION = "initialized";
250
250
  var ACCOUNT_LOGIN_START_METHOD = "account/login/start";
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-XCFPXSY4.js";
7
7
  import {
8
8
  AspClient
9
- } from "./chunk-F2YDU3AP.js";
9
+ } from "./chunk-PIZ63O3B.js";
10
10
  import {
11
11
  ASTER_BASE_URL,
12
12
  ASTER_PROVIDER,
@@ -18,7 +18,7 @@ import {
18
18
  isRecord,
19
19
  readOllamaAuthEnv,
20
20
  readOpenAICompatibleAuthEnv
21
- } from "./chunk-GBVHK7GR.js";
21
+ } from "./chunk-J6MIIMDU.js";
22
22
 
23
23
  // src/managers/codex-asp/notification-dispatch.ts
24
24
  var TURN_STARTED_METHOD = "turn/started";
@@ -4,15 +4,15 @@ const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  getManagedPiMcpServers,
6
6
  managedMcpServerProcess
7
- } from "./chunk-2X4SV2H7.js";
7
+ } from "./chunk-OW37FXFJ.js";
8
8
  import "./chunk-XCFPXSY4.js";
9
- import "./chunk-M6ELG3GK.js";
9
+ import "./chunk-2HQP6MMR.js";
10
10
  import {
11
11
  isRecord
12
12
  } from "./chunk-UZSNFLDQ.js";
13
13
  import {
14
14
  rankToolsByQuery
15
- } from "./chunk-GBVHK7GR.js";
15
+ } from "./chunk-J6MIIMDU.js";
16
16
  import "./chunk-VEQXQN22.js";
17
17
 
18
18
  // src/codemode-mcp.ts
@@ -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-YKUHRKKX.js";
7
- import "./chunk-OY6X5AUJ.js";
8
- import "./chunk-NTSUADYM.js";
6
+ } from "./chunk-LIX74B2Y.js";
7
+ import "./chunk-BUJZF6CI.js";
8
+ import "./chunk-O2BDFDEA.js";
9
9
  import {
10
10
  isRecord
11
11
  } from "./chunk-UZSNFLDQ.js";
12
- import "./chunk-GBVHK7GR.js";
12
+ import "./chunk-J6MIIMDU.js";
13
13
  import "./chunk-VEQXQN22.js";
14
14
 
15
15
  // src/command-protection-hook.ts
@@ -18,13 +18,13 @@ import {
18
18
  spawnMuseMsp,
19
19
  startGeminiSession,
20
20
  startMuseSession
21
- } from "./chunk-QN5PAZSN.js";
21
+ } from "./chunk-VHY4DMEA.js";
22
22
  import "./chunk-XCFPXSY4.js";
23
23
  import {
24
24
  AppServerProcess,
25
25
  buildCodexAgentEnv
26
- } from "./chunk-F2YDU3AP.js";
27
- import "./chunk-NTSUADYM.js";
26
+ } from "./chunk-PIZ63O3B.js";
27
+ import "./chunk-O2BDFDEA.js";
28
28
  import {
29
29
  AGENT,
30
30
  OPENCODE_GO_PROVIDER,
@@ -34,7 +34,7 @@ import {
34
34
  headlessAgentUsagePath,
35
35
  isRecord,
36
36
  withTimeout
37
- } from "./chunk-GBVHK7GR.js";
37
+ } from "./chunk-J6MIIMDU.js";
38
38
  import "./chunk-VEQXQN22.js";
39
39
 
40
40
  // src/headless-agent.ts
package/dist/src/index.js CHANGED
@@ -90,12 +90,12 @@ import {
90
90
  import {
91
91
  getManagedPiMcpServers,
92
92
  managedMcpServerProcess
93
- } from "./chunk-2X4SV2H7.js";
93
+ } from "./chunk-OW37FXFJ.js";
94
94
  import {
95
95
  evaluateCommandProtection,
96
96
  extractToolCommand,
97
97
  reportCommandProtectionBlock
98
- } from "./chunk-YKUHRKKX.js";
98
+ } from "./chunk-LIX74B2Y.js";
99
99
  import {
100
100
  ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
101
101
  AGENT_MESSAGE_DELTA_METHOD,
@@ -135,7 +135,7 @@ import {
135
135
  startMuseSession,
136
136
  thinkingVariant,
137
137
  uuidV7
138
- } from "./chunk-QN5PAZSN.js";
138
+ } from "./chunk-VHY4DMEA.js";
139
139
  import {
140
140
  GEMINI_AUTH_PATH,
141
141
  GEMINI_CLI_PATH,
@@ -145,7 +145,7 @@ import {
145
145
  } from "./chunk-XCFPXSY4.js";
146
146
  import {
147
147
  publishedPullRequestUrls
148
- } from "./chunk-LWHGKKNM.js";
148
+ } from "./chunk-ITJRSUSN.js";
149
149
  import {
150
150
  ACCOUNT_RATE_LIMITS_READ_METHOD,
151
151
  AsyncLock,
@@ -225,12 +225,12 @@ import {
225
225
  upsertCredentialFileLines,
226
226
  withdrawAgentLogin,
227
227
  writeSecureCredentialFile
228
- } from "./chunk-OAFO4KYM.js";
228
+ } from "./chunk-KBE3MXTD.js";
229
229
  import {
230
230
  SUBAGENT_MCP_TOOL_TIMEOUT_MS,
231
231
  engineScriptProcess,
232
232
  subagentMcpProcessConfig
233
- } from "./chunk-M6ELG3GK.js";
233
+ } from "./chunk-2HQP6MMR.js";
234
234
  import {
235
235
  ENGINE_ENV,
236
236
  UNQUOTED_PATHS_CONFIG,
@@ -241,18 +241,18 @@ import {
241
241
  resolveDiffBase,
242
242
  setAgentCredentialSnapshot,
243
243
  setLinearSessionId
244
- } from "./chunk-OY6X5AUJ.js";
244
+ } from "./chunk-BUJZF6CI.js";
245
245
  import {
246
246
  AspRequestTimeoutError,
247
247
  AspResponseError,
248
248
  buildCodexAgentEnv,
249
249
  getCodexModelProvider
250
- } from "./chunk-F2YDU3AP.js";
250
+ } from "./chunk-PIZ63O3B.js";
251
251
  import {
252
252
  SUBPROCESS_MAX_BUFFER,
253
253
  execAsync,
254
254
  execFileAsync
255
- } from "./chunk-NTSUADYM.js";
255
+ } from "./chunk-O2BDFDEA.js";
256
256
  import {
257
257
  isRecord
258
258
  } from "./chunk-UZSNFLDQ.js";
@@ -463,6 +463,7 @@ import {
463
463
  isAgentChatMcpActivityRecord,
464
464
  isAgentChatSkillActivityRecord,
465
465
  isAgentChatTurnActivityRecord,
466
+ isAuthenticationErrorText,
466
467
  isCanvasTextKind,
467
468
  isChatMessageSender,
468
469
  isClaudeAuthErrorText,
@@ -514,6 +515,7 @@ import {
514
515
  parseProxyRouteCheck,
515
516
  parseReplicasConfigString,
516
517
  percentage,
518
+ providerContextUsage,
517
519
  proxyRouteCheckScript,
518
520
  raceWithTimeout,
519
521
  readChatHistoryAppended,
@@ -554,7 +556,7 @@ import {
554
556
  workspaceTokenRequestSchema,
555
557
  workspaceTokenResponseSchema,
556
558
  wrapInTag
557
- } from "./chunk-GBVHK7GR.js";
559
+ } from "./chunk-J6MIIMDU.js";
558
560
  import {
559
561
  __commonJS,
560
562
  __export,
@@ -10121,6 +10123,7 @@ var EnvironmentDetailsService = class {
10121
10123
  details.supportsMidTurnSteering = true;
10122
10124
  details.supportsClaudeMidTurnSteering = true;
10123
10125
  details.supportsCursorMidTurnSteering = true;
10126
+ details.supportsPiMidTurnSteering = true;
10124
10127
  details.supportsSendNow = true;
10125
10128
  details.supportsClaudeGoals = true;
10126
10129
  details.supportsGoalUpdates = true;
@@ -11378,6 +11381,7 @@ function insertChronologically(existing, additions) {
11378
11381
  }
11379
11382
  function canSteerMessage(provider, request) {
11380
11383
  if (provider === "cursor") return !request.images?.length;
11384
+ if (provider === "pi") return !request.message.trimStart().startsWith("/");
11381
11385
  if (provider !== "claude" && provider !== "codex") return false;
11382
11386
  return !getGoalCommand(request.message, request.goalMode) && !(provider === "codex" && isCompactCommand(request.message));
11383
11387
  }
@@ -11462,22 +11466,23 @@ var GeminiTokenManager = class extends BaseRefreshManager {
11462
11466
  };
11463
11467
  var geminiTokenManager = new GeminiTokenManager();
11464
11468
 
11465
- // src/managers/opencode-token-manager.ts
11466
- var OPENCODE_AUTH_ENV_KEYS = [...ollamaAuthEnvKeys("opencode"), ...openAICompatibleAuthEnvKeys("opencode")];
11467
- var OpencodeTokenManager = class extends BaseRefreshManager {
11468
- constructor() {
11469
- super("OpencodeTokenManager");
11469
+ // src/managers/api-key-token-manager.ts
11470
+ var ApiKeyTokenManager = class extends BaseRefreshManager {
11471
+ constructor(agent) {
11472
+ super(`${getProviderDisplayName(agent)}TokenManager`);
11473
+ this.agent = agent;
11470
11474
  }
11475
+ agent;
11471
11476
  doRefresh() {
11472
11477
  return Promise.resolve();
11473
11478
  }
11474
- async fetchFreshCredentials(failureReason, failureKind = "exhausted", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.opencode, allowedMethods, resetsAt) {
11475
- const failedMethod = AGENT_CREDENTIAL_METHODS_IN_ORDER.opencode.find(({ method }) => method === failedCredential?.method)?.method;
11479
+ async fetchFreshCredentials(failureReason, failureKind = "exhausted", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[this.agent], allowedMethods, resetsAt) {
11480
+ const failedMethod = AGENT_CREDENTIAL_METHODS_IN_ORDER[this.agent].find(({ method }) => method === failedCredential?.method)?.method;
11476
11481
  if (!failedMethod || allowedMethods && !allowedMethods.includes(failedMethod)) {
11477
- return createErrorResult({ message: "OpenCode only switches between keys of the same provider", code: "no_credentials" });
11482
+ return createErrorResult({ message: `${getProviderDisplayName(this.agent)} only switches between keys of the same provider`, code: "no_credentials" });
11478
11483
  }
11479
11484
  return this.swapCredentials({
11480
- provider: "opencode",
11485
+ provider: this.agent,
11481
11486
  failureKind,
11482
11487
  allowedMethods: [failedMethod],
11483
11488
  refresh: async (exclusions) => {
@@ -11489,26 +11494,27 @@ var OpencodeTokenManager = class extends BaseRefreshManager {
11489
11494
  ...resetsAt ? { resetsAt } : {},
11490
11495
  ...exclusions
11491
11496
  };
11492
- const response = await monolithRequest("/v1/engine/opencode/refresh-credentials", { body: request, signal: AbortSignal.timeout(12e4) });
11497
+ const response = await monolithRequest(`/v1/engine/${this.agent}/refresh-credentials`, { body: request, signal: AbortSignal.timeout(12e4) });
11493
11498
  if (!response.ok) {
11494
11499
  const error = new Error(`Credentials refresh failed: ${response.status} ${await response.text()}`);
11495
11500
  const revocation = refreshRevocation(error);
11496
- if (revocation) await withdrawAgentLogin("opencode", revocation);
11501
+ if (revocation) await withdrawAgentLogin(this.agent, revocation);
11497
11502
  throw error;
11498
11503
  }
11499
11504
  const data = await response.json();
11500
11505
  for (const file of data.auth.files ?? []) {
11501
11506
  await writeSecureCredentialFile(file.path, file.contents, { ensureParentDir: true });
11502
11507
  }
11503
- for (const key of OPENCODE_AUTH_ENV_KEYS) delete process.env[key];
11508
+ for (const key of [...ollamaAuthEnvKeys(this.agent), ...openAICompatibleAuthEnvKeys(this.agent)]) delete process.env[key];
11504
11509
  Object.assign(process.env, data.auth.env);
11505
- setAgentCredentialSnapshot("opencode", data);
11510
+ setAgentCredentialSnapshot(this.agent, data);
11506
11511
  },
11507
11512
  keepRefreshing: () => false
11508
11513
  });
11509
11514
  }
11510
11515
  };
11511
- var opencodeTokenManager = new OpencodeTokenManager();
11516
+ var opencodeTokenManager = new ApiKeyTokenManager("opencode");
11517
+ var piTokenManager = new ApiKeyTokenManager("pi");
11512
11518
 
11513
11519
  // src/managers/auth-fallback.ts
11514
11520
  var SWAPPABLE_AGENTS = {
@@ -11516,8 +11522,10 @@ var SWAPPABLE_AGENTS = {
11516
11522
  codex: codexTokenManager,
11517
11523
  gemini: geminiTokenManager,
11518
11524
  muse: museTokenManager,
11519
- opencode: opencodeTokenManager
11525
+ opencode: opencodeTokenManager,
11526
+ pi: piTokenManager
11520
11527
  };
11528
+ var SWITCHED_CREDENTIAL_PROMPT = "Your previous turn stopped at a usage limit or a rejected credential. Continue from where you left off: first check what is already done, and do not repeat commands, edits, or messages you already completed.";
11521
11529
  var QUOTA_STOP_NEXT_STEP = {
11522
11530
  failed: "The next credential in the fallback chain could not be used. Check it in Settings \u2192 Fallbacks and try again.",
11523
11531
  not_configured: "Nothing further is configured in the fallback chain. Add a credential or harness in Settings \u2192 Fallbacks, or try again once the limit resets.",
@@ -12795,6 +12803,28 @@ function convertOpencodePart(part, linearSessionId) {
12795
12803
  }
12796
12804
  return null;
12797
12805
  }
12806
+ function convertPiEvent(event, linearSessionId) {
12807
+ if (event.type === "message_end" && event.message.role === "assistant") {
12808
+ const { content } = event.message;
12809
+ const text = content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
12810
+ const body = text || content.flatMap((block) => block.type === "thinking" ? [block.thinking] : []).join("\n").trim();
12811
+ return body ? { linearSessionId, content: { type: "thought", body } } : null;
12812
+ }
12813
+ if (event.type === "tool_execution_start" || event.type === "tool_execution_end") {
12814
+ const output = event.type === "tool_execution_end" && isRecord2(event.result) ? extractToolResultText(event.result.content) : "";
12815
+ const result = event.type !== "tool_execution_end" ? void 0 : event.isError ? `Error: ${output || "Tool failed"}` : output || "Done";
12816
+ return {
12817
+ linearSessionId,
12818
+ content: {
12819
+ type: "action",
12820
+ action: toolAction(event.toolName),
12821
+ parameter: event.type === "tool_execution_start" ? summarizeInput(event.args) : "",
12822
+ ...result ? { result } : {}
12823
+ }
12824
+ };
12825
+ }
12826
+ return null;
12827
+ }
12798
12828
  function mapTodoStatus(status) {
12799
12829
  if (status === "in_progress") {
12800
12830
  return "inProgress";
@@ -17806,16 +17836,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
17806
17836
  } else if (frame.method === "session/contextUsage") {
17807
17837
  const used = typeof frame.params.usedTokens === "number" ? frame.params.usedTokens : 0;
17808
17838
  const size = typeof frame.params.windowTokens === "number" ? frame.params.windowTokens : 0;
17809
- this.recordContextUsage({
17810
- provider: "muse",
17811
- source: "provider_usage",
17812
- model: DEFAULT_MUSE_MODEL,
17813
- totalTokens: used,
17814
- maxTokens: size,
17815
- percentage: size > 0 ? used / size * 100 : 0,
17816
- categories: [],
17817
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
17818
- });
17839
+ this.recordContextUsage(providerContextUsage({ provider: "muse", model: DEFAULT_MUSE_MODEL, totalTokens: used, maxTokens: size }));
17819
17840
  } else if (frame.method === "userInput/requested" && typeof frame.params.userInputId === "string") {
17820
17841
  const questions = Array.isArray(frame.params.questions) ? frame.params.questions.filter(isPendingQuestion) : [];
17821
17842
  this.pendingInput = {
@@ -18207,16 +18228,12 @@ var GeminiManager = class extends CodingAgentManager {
18207
18228
  return;
18208
18229
  }
18209
18230
  if (kind === "usage_update" && typeof update.used === "number" && typeof update.size === "number") {
18210
- this.recordContextUsage({
18231
+ this.recordContextUsage(providerContextUsage({
18211
18232
  provider: "gemini",
18212
- source: "provider_usage",
18213
18233
  model: this.session ? geminiSelectOption(this.session.configOptions, "model")?.currentValue ?? null : null,
18214
18234
  totalTokens: update.used,
18215
- maxTokens: update.size,
18216
- percentage: update.size > 0 ? update.used / update.size * 100 : 0,
18217
- categories: [],
18218
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
18219
- });
18235
+ maxTokens: update.size
18236
+ }));
18220
18237
  return;
18221
18238
  }
18222
18239
  if (kind === "current_mode_update" || kind === "session_info_update") return;
@@ -18457,7 +18474,6 @@ var OPENCODE_SLASH_COMMANDS_CACHE_MS = 3e4;
18457
18474
  var OPENCODE_HEARTBEAT_TIMEOUT_MS = 6e4;
18458
18475
  var OPENCODE_ABORT_TIMEOUT_MS = 5e3;
18459
18476
  var OPENCODE_SERVER_GONE = "exited or dropped its connection";
18460
- var OPENCODE_SWITCHED_CREDENTIAL_PROMPT = "Your previous turn stopped at a usage limit. Continue from where you left off: first check what is already done, and do not repeat commands, edits, or messages you already completed.";
18461
18477
  async function getDefaultOpencodeModel(provider) {
18462
18478
  const ollama = readOllamaAuthEnv("opencode", process.env);
18463
18479
  if (provider === "ollama" && ollama) {
@@ -18908,7 +18924,7 @@ var OpencodeManager = class extends CodingAgentManager {
18908
18924
  question: Boolean(request.enableInteractiveTools),
18909
18925
  ...this.subagentMcpParentChatId() ? { task: false } : {}
18910
18926
  },
18911
- parts: [{ type: "text", text: retry ? OPENCODE_SWITCHED_CREDENTIAL_PROMPT : request.message }]
18927
+ parts: [{ type: "text", text: retry ? SWITCHED_CREDENTIAL_PROMPT : request.message }]
18912
18928
  }, { signal: controller.signal, throwOnError: true });
18913
18929
  this.recordHistoryEvent("opencode-message.updated", { info: result.data.info });
18914
18930
  for (const part of result.data.parts) this.recordOpencodePart(part);
@@ -60029,16 +60045,30 @@ var PiManager = class extends CodingAgentManager {
60029
60045
  activeSessionFile = null;
60030
60046
  sessionSubagentMcpParentChatId;
60031
60047
  sessionInstructions;
60048
+ sessionCredential;
60032
60049
  providerId = "openrouter";
60033
60050
  providerApiKey = null;
60034
60051
  modelRuntime = null;
60052
+ linearForwarder = null;
60053
+ // Held until the turn ends: a call Pi retried or Replicas moved to another credential is not the turn's failure.
60054
+ failedCall = null;
60055
+ steers = [];
60035
60056
  constructor(options) {
60036
60057
  super(options);
60037
60058
  this.initializeManager(this.processMessageInternal.bind(this));
60038
60059
  }
60039
60060
  async interruptActiveTurn() {
60061
+ this.session?.clearQueue();
60040
60062
  await this.session?.abort();
60041
60063
  }
60064
+ async steerRequest(request) {
60065
+ if (!this.session?.isStreaming || !canSteerMessage("pi", request)) return false;
60066
+ const images = await this.toPiImages(request);
60067
+ if (!this.session?.isStreaming || this.isSteerWithdrawn(request)) return false;
60068
+ this.steers.push(request);
60069
+ await this.session.steer(request.message, images);
60070
+ return true;
60071
+ }
60042
60072
  async getHistory(page2 = {}) {
60043
60073
  await this.historyFile.flush();
60044
60074
  const history = await this.historyFile.loadEventsPage(page2);
@@ -60072,7 +60102,7 @@ var PiManager = class extends CodingAgentManager {
60072
60102
  const subagentMcpParentChatId = this.subagentMcpParentChatId();
60073
60103
  const instructions = this.buildCombinedInstructions(request.customInstructions) ?? "";
60074
60104
  let retainedModel;
60075
- if (this.session && (this.sessionSubagentMcpParentChatId !== subagentMcpParentChatId || this.sessionInstructions !== instructions)) {
60105
+ if (this.session && (this.sessionSubagentMcpParentChatId !== subagentMcpParentChatId || this.sessionInstructions !== instructions || this.sessionCredential !== ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.pi)) {
60076
60106
  retainedModel = this.session.model?.id;
60077
60107
  await this.dispose();
60078
60108
  }
@@ -60097,6 +60127,7 @@ var PiManager = class extends CodingAgentManager {
60097
60127
  return this.session;
60098
60128
  }
60099
60129
  const modelRuntime = await this.getModelRuntime();
60130
+ const credential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.pi;
60100
60131
  const credentialResult = await getPiProviderCredentials();
60101
60132
  if (!credentialResult.ok) throw new Error("OpenCode Go, Aster, OpenRouter, or OpenAI-compatible credentials are not configured for Pi.");
60102
60133
  const credentials = credentialResult.data;
@@ -60219,6 +60250,7 @@ var PiManager = class extends CodingAgentManager {
60219
60250
  this.session = result.session;
60220
60251
  this.sessionSubagentMcpParentChatId = subagentMcpParentChatId;
60221
60252
  this.sessionInstructions = instructions;
60253
+ this.sessionCredential = credential;
60222
60254
  if (request.thinkingLevel) {
60223
60255
  this.session.setThinkingLevel(piThinkingLevel(request.thinkingLevel));
60224
60256
  }
@@ -60233,29 +60265,97 @@ var PiManager = class extends CodingAgentManager {
60233
60265
  return this.modelRuntime;
60234
60266
  }
60235
60267
  handleEvent(event) {
60268
+ if (event.type === "agent_start") void this.deliverEarlySteers();
60269
+ if (event.type === "message_start" && event.message.role === "user" && Array.isArray(event.message.content)) {
60270
+ const [first] = event.message.content;
60271
+ const index = first?.type === "text" ? this.steers.findIndex(({ message }) => message === first.text) : -1;
60272
+ if (index !== -1) {
60273
+ const steer = this.markSteerRead(this.steers.splice(index, 1)[0].id);
60274
+ if (steer) this.recordUserMessageHistoryEvent(steer);
60275
+ }
60276
+ }
60236
60277
  if (event.type === "message_end") this.onUsageUpdate(event, (/* @__PURE__ */ new Date()).toISOString());
60237
- const payload = eventPayload(event);
60238
- this.recordHistoryEvent(`pi-${event.type}`, payload);
60278
+ const usage = event.type === "message_end" && event.message.role === "assistant" ? this.session?.getContextUsage() : void 0;
60279
+ if (usage?.tokens != null) {
60280
+ this.recordContextUsage(providerContextUsage({
60281
+ provider: "pi",
60282
+ model: this.session?.model?.id ?? null,
60283
+ totalTokens: usage.tokens,
60284
+ maxTokens: usage.contextWindow,
60285
+ compactsAutomatically: this.session?.autoCompactionEnabled
60286
+ }));
60287
+ }
60288
+ if (event.type === "message_end" && event.message.role === "assistant") {
60289
+ this.failedCall = event.message.stopReason === "error" ? event : null;
60290
+ if (this.failedCall) return;
60291
+ }
60292
+ this.recordHistoryEvent(`pi-${event.type}`, eventPayload(event));
60293
+ const linearSessionId = this.linearSessionId;
60294
+ if (linearSessionId) this.linearForwarder?.sendEvent(convertPiEvent(event, linearSessionId));
60239
60295
  }
60240
60296
  recordUserMessage(session, request) {
60241
60297
  const skillName = explicitSkillName(session, request.message);
60242
60298
  this.recordUserMessageHistoryEvent(request, skillName ? { skillName } : {}, this.turnBeganAt);
60243
60299
  }
60300
+ async toPiImages(request) {
60301
+ if (!request.images?.length) return void 0;
60302
+ return (await normalizeImages(request.images)).map((image) => ({
60303
+ type: "image",
60304
+ data: image.source.data,
60305
+ mimeType: image.source.media_type
60306
+ }));
60307
+ }
60244
60308
  async processMessageInternal(request, signal) {
60309
+ this.linearForwarder = new LinearEventForwarder(() => this.linearSessionId);
60245
60310
  try {
60246
- const session = await this.ensureSession(request);
60247
- const images = request.images && request.images.length > 0 ? (await normalizeImages(request.images)).map((image) => ({
60248
- type: "image",
60249
- data: image.source.data,
60250
- mimeType: image.source.media_type
60251
- })) : void 0;
60311
+ let session = await this.ensureSession(request);
60312
+ const images = await this.toPiImages(request);
60252
60313
  if (!this.deliver(signal)) return;
60253
60314
  this.recordUserMessage(session, request);
60254
- await session.prompt(request.message, images ? { images } : void 0);
60315
+ let retry = false;
60316
+ let limit;
60317
+ while (true) {
60318
+ const attempted = this.sessionCredential;
60319
+ const thrown = await session.prompt(retry ? SWITCHED_CREDENTIAL_PROMPT : request.message, images && !retry ? { images } : void 0).then(() => null, (error) => error);
60320
+ const failedCall = this.failedCall;
60321
+ this.failedCall = null;
60322
+ const detail = thrown ? thrown instanceof Error ? thrown.message : String(thrown) : failedCall?.message.role === "assistant" ? failedCall.message.errorMessage ?? "Pi run failed" : null;
60323
+ if (detail === null) break;
60324
+ const quota = detectAgentQuotaLimit(detail);
60325
+ const authFailed = !quota && isAuthenticationErrorText(detail, [/\b401\b/]);
60326
+ const fallback = !signal.aborted && (quota || authFailed) ? await this.fallBackCredential(quota ?? "auth_failed", detail, attempted, void 0, !!limit) : null;
60327
+ limit ??= quota ?? void 0;
60328
+ if (fallback?.outcome === "switched") {
60329
+ if (signal.aborted) break;
60330
+ const model = fallback.model ?? session.model?.id;
60331
+ await this.dispose();
60332
+ session = await this.ensureSession({ ...request, ...model ? { model } : {} });
60333
+ if (signal.aborted) break;
60334
+ retry = true;
60335
+ continue;
60336
+ }
60337
+ const notice = fallback && limit ? describeQuotaExhaustion("pi", limit, attempted, fallback) : authFailed ? describeLoginFailure("pi", attempted, void 0, false) : null;
60338
+ if (notice) this.recordHistoryEvent("pi-error", { message: notice });
60339
+ else if (failedCall) this.recordHistoryEvent("pi-message_end", eventPayload(failedCall));
60340
+ if (fallback && limit) {
60341
+ this.emitQuotaExhausted({
60342
+ provider: "pi",
60343
+ reason: limit,
60344
+ detail,
60345
+ ...fallback.outcome === "fork" ? { forkTo: fallback.target } : {}
60346
+ });
60347
+ }
60348
+ if (thrown && !notice) throw thrown;
60349
+ break;
60350
+ }
60351
+ this.linearForwarder.flushThoughtAsResponse();
60255
60352
  } catch (error) {
60256
60353
  this.recordHistoryEvent("pi-error", { message: error instanceof Error ? error.message : String(error) });
60257
60354
  throw error;
60258
60355
  } finally {
60356
+ this.linearForwarder = null;
60357
+ this.session?.clearQueue();
60358
+ this.steers = [];
60259
60359
  await this.historyFile.flush();
60260
60360
  await this.onTurnComplete();
60261
60361
  }
@@ -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-LWHGKKNM.js";
6
+ } from "./chunk-ITJRSUSN.js";
7
7
  import {
8
8
  isRecord
9
9
  } from "./chunk-UZSNFLDQ.js";
10
10
  import {
11
11
  shouldRefreshPullRequests
12
- } from "./chunk-GBVHK7GR.js";
12
+ } from "./chunk-J6MIIMDU.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-GBVHK7GR.js";
14
+ } from "./chunk-J6MIIMDU.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.1727",
3
+ "version": "0.1.1730",
4
4
  "description": "Lightweight API server for Replicas workspaces",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",