replicas-engine 0.1.1669 → 0.1.1671
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/dist/src/{asp-host-DTBU37TZ.js → asp-host-PKDNKKHF.js} +5 -5
- package/dist/src/{chunk-2LX33VLS.js → chunk-3EYNKOGU.js} +1 -1
- package/dist/src/{chunk-6VUUNM6Z.js → chunk-3RZH5OUF.js} +1 -1
- package/dist/src/{chunk-HQWUF7L5.js → chunk-4KUQJQPT.js} +2 -2
- package/dist/src/{chunk-5BDCGAEV.js → chunk-55OD2MGN.js} +2 -2
- package/dist/src/{chunk-7QJH7SD2.js → chunk-D5SSZI5B.js} +21 -7
- package/dist/src/{chunk-IH56QPAV.js → chunk-HDCQF7AQ.js} +6 -6
- package/dist/src/{chunk-LR637LW6.js → chunk-KJ6QPUJ6.js} +8 -5
- package/dist/src/{chunk-77JPD27V.js → chunk-SLFFVHAI.js} +2 -2
- package/dist/src/command-protection-hook.js +4 -4
- package/dist/src/headless-agent.js +4 -4
- package/dist/src/index.js +527 -167
- package/dist/src/post-tool-pr-hook.js +2 -2
- package/dist/src/subagent-mcp.js +1 -1
- package/package.json +1 -1
- package/scripts/opencode +5 -1
package/dist/src/index.js
CHANGED
|
@@ -91,7 +91,7 @@ import {
|
|
|
91
91
|
evaluateCommandProtection,
|
|
92
92
|
extractToolCommand,
|
|
93
93
|
reportCommandProtectionBlock
|
|
94
|
-
} from "./chunk-
|
|
94
|
+
} from "./chunk-4KUQJQPT.js";
|
|
95
95
|
import {
|
|
96
96
|
ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
|
|
97
97
|
AGENT_MESSAGE_DELTA_METHOD,
|
|
@@ -129,10 +129,10 @@ import {
|
|
|
129
129
|
spawnMuseMsp,
|
|
130
130
|
startMuseSession,
|
|
131
131
|
uuidV7
|
|
132
|
-
} from "./chunk-
|
|
132
|
+
} from "./chunk-SLFFVHAI.js";
|
|
133
133
|
import {
|
|
134
134
|
publishedPullRequestUrls
|
|
135
|
-
} from "./chunk-
|
|
135
|
+
} from "./chunk-3RZH5OUF.js";
|
|
136
136
|
import {
|
|
137
137
|
ACCOUNT_RATE_LIMITS_READ_METHOD,
|
|
138
138
|
AsyncLock,
|
|
@@ -212,7 +212,7 @@ import {
|
|
|
212
212
|
transcriptSecrets,
|
|
213
213
|
upsertCredentialFileLines,
|
|
214
214
|
writeSecureCredentialFile
|
|
215
|
-
} from "./chunk-
|
|
215
|
+
} from "./chunk-HDCQF7AQ.js";
|
|
216
216
|
import {
|
|
217
217
|
ENGINE_ENV,
|
|
218
218
|
UNQUOTED_PATHS_CONFIG,
|
|
@@ -223,16 +223,17 @@ import {
|
|
|
223
223
|
resolveDiffBase,
|
|
224
224
|
setAgentCredentialSnapshot,
|
|
225
225
|
setLinearSessionId
|
|
226
|
-
} from "./chunk-
|
|
226
|
+
} from "./chunk-55OD2MGN.js";
|
|
227
227
|
import {
|
|
228
|
+
AspRequestTimeoutError,
|
|
228
229
|
buildCodexAgentEnv,
|
|
229
230
|
getCodexModelProvider
|
|
230
|
-
} from "./chunk-
|
|
231
|
+
} from "./chunk-KJ6QPUJ6.js";
|
|
231
232
|
import {
|
|
232
233
|
SUBPROCESS_MAX_BUFFER,
|
|
233
234
|
execAsync,
|
|
234
235
|
execFileAsync
|
|
235
|
-
} from "./chunk-
|
|
236
|
+
} from "./chunk-3EYNKOGU.js";
|
|
236
237
|
import {
|
|
237
238
|
isRecord as isRecord2
|
|
238
239
|
} from "./chunk-UZSNFLDQ.js";
|
|
@@ -532,7 +533,7 @@ import {
|
|
|
532
533
|
workspaceTokenRequestSchema,
|
|
533
534
|
workspaceTokenResponseSchema,
|
|
534
535
|
wrapInTag
|
|
535
|
-
} from "./chunk-
|
|
536
|
+
} from "./chunk-D5SSZI5B.js";
|
|
536
537
|
import {
|
|
537
538
|
__commonJS,
|
|
538
539
|
__export,
|
|
@@ -11585,6 +11586,7 @@ var MessageQueueService = class {
|
|
|
11585
11586
|
acceptanceWithdrawals = /* @__PURE__ */ new WeakSet();
|
|
11586
11587
|
queueCancellationVersion = 0;
|
|
11587
11588
|
activeTurn = null;
|
|
11589
|
+
stoppedTurns = /* @__PURE__ */ new WeakSet();
|
|
11588
11590
|
// Held while an idle-path acceptance persists, so nothing else can start a turn before it.
|
|
11589
11591
|
starting = false;
|
|
11590
11592
|
constructor(processMessage, onProcessingChanged = () => {
|
|
@@ -11676,16 +11678,24 @@ var MessageQueueService = class {
|
|
|
11676
11678
|
messageId,
|
|
11677
11679
|
position: 0
|
|
11678
11680
|
};
|
|
11681
|
+
const turn = { message: queuedMessage, controller: new AbortController(), delivered: false };
|
|
11682
|
+
this.activeTurn = turn;
|
|
11679
11683
|
this.starting = true;
|
|
11680
11684
|
try {
|
|
11681
11685
|
await onAccepted(response, queuedMessage);
|
|
11682
11686
|
} catch (error) {
|
|
11687
|
+
this.activeTurn = null;
|
|
11683
11688
|
this.starting = false;
|
|
11684
11689
|
this.resumeIfIdle();
|
|
11685
11690
|
throw error;
|
|
11686
11691
|
}
|
|
11687
11692
|
this.starting = false;
|
|
11688
|
-
|
|
11693
|
+
if (turn.controller.signal.aborted) {
|
|
11694
|
+
this.activeTurn = null;
|
|
11695
|
+
this.resumeIfIdle();
|
|
11696
|
+
return response;
|
|
11697
|
+
}
|
|
11698
|
+
this.startProcessing(queuedMessage, turn).catch((error) => {
|
|
11689
11699
|
console.error("[MessageQueue] Unhandled error in startProcessing:", error);
|
|
11690
11700
|
});
|
|
11691
11701
|
return response;
|
|
@@ -11696,8 +11706,8 @@ var MessageQueueService = class {
|
|
|
11696
11706
|
if (!tail) return false;
|
|
11697
11707
|
return tail.merge === true && tail.type === request.type;
|
|
11698
11708
|
}
|
|
11699
|
-
async startProcessing(queuedMessage) {
|
|
11700
|
-
const
|
|
11709
|
+
async startProcessing(queuedMessage, turn = { message: queuedMessage, controller: new AbortController(), delivered: false }) {
|
|
11710
|
+
const { signal } = turn.controller;
|
|
11701
11711
|
this.activeTurn = turn;
|
|
11702
11712
|
this.processing = true;
|
|
11703
11713
|
this.onProcessingChanged(true);
|
|
@@ -11711,15 +11721,18 @@ var MessageQueueService = class {
|
|
|
11711
11721
|
this.acceptanceByMessage.delete(queuedMessage);
|
|
11712
11722
|
break;
|
|
11713
11723
|
}
|
|
11714
|
-
if (!
|
|
11724
|
+
if (!signal.aborted) {
|
|
11715
11725
|
if (!queuedMessage.engineTurn) await this.onMessageStarted(queuedMessage);
|
|
11716
|
-
await this.processMessage(queuedMessage,
|
|
11726
|
+
await this.processMessage(queuedMessage, signal);
|
|
11717
11727
|
}
|
|
11718
11728
|
} catch (error) {
|
|
11719
11729
|
console.error("[MessageQueue] Error processing message:", error);
|
|
11720
11730
|
} finally {
|
|
11721
11731
|
this.activeTurn = null;
|
|
11722
11732
|
this.processing = false;
|
|
11733
|
+
if (turn.requeueAfter && !this.stoppedTurns.has(signal)) {
|
|
11734
|
+
this.queue.splice(this.queue.findIndex(({ id }) => id === turn.requeueAfter) + 1, 0, queuedMessage);
|
|
11735
|
+
}
|
|
11723
11736
|
if (this.queue.length === 0) {
|
|
11724
11737
|
this.onProcessingChanged(false);
|
|
11725
11738
|
this.onQueueChanged();
|
|
@@ -11746,8 +11759,29 @@ var MessageQueueService = class {
|
|
|
11746
11759
|
this.onQueueChanged();
|
|
11747
11760
|
return drained;
|
|
11748
11761
|
}
|
|
11749
|
-
|
|
11750
|
-
|
|
11762
|
+
/** A turn a Stop has taken stays the active one while it unwinds, so it is not withdrawn or requeued a second time. */
|
|
11763
|
+
stoppedTurn() {
|
|
11764
|
+
return this.activeTurn && this.stoppedTurns.has(this.activeTurn.controller.signal) ? this.activeTurn : null;
|
|
11765
|
+
}
|
|
11766
|
+
cancelActiveTurn(stop = false) {
|
|
11767
|
+
const turn = this.activeTurn;
|
|
11768
|
+
if (!turn) return null;
|
|
11769
|
+
const taken = this.stoppedTurn();
|
|
11770
|
+
if (stop) this.stoppedTurns.add(turn.controller.signal);
|
|
11771
|
+
turn.controller.abort();
|
|
11772
|
+
return taken ? null : turn;
|
|
11773
|
+
}
|
|
11774
|
+
requeueActiveTurnAfter(messageId) {
|
|
11775
|
+
const turn = this.activeTurn;
|
|
11776
|
+
if (!turn || turn.delivered || turn.message.engineTurn || this.stoppedTurn()) return null;
|
|
11777
|
+
turn.requeueAfter ??= messageId;
|
|
11778
|
+
return { message: turn.message, afterId: turn.requeueAfter };
|
|
11779
|
+
}
|
|
11780
|
+
isStopped(signal) {
|
|
11781
|
+
return this.stoppedTurns.has(signal);
|
|
11782
|
+
}
|
|
11783
|
+
markDelivered() {
|
|
11784
|
+
if (this.activeTurn) this.activeTurn.delivered = true;
|
|
11751
11785
|
}
|
|
11752
11786
|
/**
|
|
11753
11787
|
* Get all queued messages (does not include the currently processing message)
|
|
@@ -11845,6 +11879,7 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11845
11879
|
hostOnTurnComplete;
|
|
11846
11880
|
onProcessingChanged;
|
|
11847
11881
|
onMessageStarted;
|
|
11882
|
+
onMessageRequeued;
|
|
11848
11883
|
onQueueChanged;
|
|
11849
11884
|
onModelSwitched;
|
|
11850
11885
|
authFallback;
|
|
@@ -11860,6 +11895,13 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11860
11895
|
withdrawnSteers = /* @__PURE__ */ new WeakSet();
|
|
11861
11896
|
earlySteerDelivery = new AsyncLock();
|
|
11862
11897
|
turnOpen = false;
|
|
11898
|
+
// The chat places a message and times its turn by the harness's record of it, which is written only once the agent has the message, so that record keeps this time.
|
|
11899
|
+
turnBeganAt;
|
|
11900
|
+
// As it was sent, for a harness that keeps the message for its next turn: a Stop before then hands this back.
|
|
11901
|
+
turnRequest;
|
|
11902
|
+
harnessTurns = /* @__PURE__ */ new WeakSet();
|
|
11903
|
+
// What a message's notes took as read, so they are owed again when the agent never got the message.
|
|
11904
|
+
turnNotes = /* @__PURE__ */ new WeakMap();
|
|
11863
11905
|
reportsPromptStart = false;
|
|
11864
11906
|
// A Send now waits for the turn's prompt to start, as an earlier cut cuts nothing; a command's turn has none, so it is never cut as it begins.
|
|
11865
11907
|
promptStart = null;
|
|
@@ -11893,6 +11935,8 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11893
11935
|
});
|
|
11894
11936
|
this.onMessageStarted = options.onMessageStarted ?? (async () => {
|
|
11895
11937
|
});
|
|
11938
|
+
this.onMessageRequeued = options.onMessageRequeued ?? (() => {
|
|
11939
|
+
});
|
|
11896
11940
|
this.onQueueChanged = options.onQueueChanged ?? (() => {
|
|
11897
11941
|
});
|
|
11898
11942
|
this.onModelSwitched = options.onModelSwitched ?? (async () => {
|
|
@@ -11923,7 +11967,7 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11923
11967
|
emitQuotaExhausted(payload) {
|
|
11924
11968
|
this.emitSyntheticEvent(AGENT_QUOTA_EXHAUSTED_EVENT_TYPE, { ...payload });
|
|
11925
11969
|
}
|
|
11926
|
-
recordHistoryEvent(type, payload) {
|
|
11970
|
+
recordHistoryEvent(type, payload, timestamp = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
11927
11971
|
const eventPayload2 = {};
|
|
11928
11972
|
if (payload && typeof payload === "object") {
|
|
11929
11973
|
Object.assign(eventPayload2, payload);
|
|
@@ -11931,14 +11975,14 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11931
11975
|
eventPayload2.value = payload;
|
|
11932
11976
|
}
|
|
11933
11977
|
const event = {
|
|
11934
|
-
timestamp
|
|
11978
|
+
timestamp,
|
|
11935
11979
|
type,
|
|
11936
11980
|
payload: eventPayload2
|
|
11937
11981
|
};
|
|
11938
11982
|
this.record(event);
|
|
11939
11983
|
}
|
|
11940
|
-
recordUserMessageHistoryEvent(request, extraPayload = {}) {
|
|
11941
|
-
this.recordHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, extraPayload));
|
|
11984
|
+
recordUserMessageHistoryEvent(request, extraPayload = {}, timestamp) {
|
|
11985
|
+
this.recordHistoryEvent("event_msg", this.createUserMessageHistoryPayload(request, extraPayload), timestamp);
|
|
11942
11986
|
}
|
|
11943
11987
|
createUserMessageHistoryPayload(request, extraPayload = {}) {
|
|
11944
11988
|
return {
|
|
@@ -11953,11 +11997,13 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11953
11997
|
this.messageQueue = new MessageQueueService(
|
|
11954
11998
|
async (request, signal) => {
|
|
11955
11999
|
this.openTurn(request);
|
|
12000
|
+
this.turnRequest = request;
|
|
11956
12001
|
try {
|
|
11957
12002
|
await Promise.all([this.refreshSubagentMcp(), this.refreshAutoCompactTokens()]);
|
|
11958
12003
|
const { request: delivered, senderKey } = this.withSenderLine(request);
|
|
11959
12004
|
const stopped = signal.aborted;
|
|
11960
|
-
if (stopped
|
|
12005
|
+
if (!stopped) this.harnessTurns.add(signal);
|
|
12006
|
+
if (stopped && (request.engineTurn || this.isStopped(signal) || !await this.keepStoppedRequest(delivered, signal))) return;
|
|
11961
12007
|
await this.saveLastSenderKey(senderKey);
|
|
11962
12008
|
if (stopped) return;
|
|
11963
12009
|
const takesNotes = takesTurnNotes(request);
|
|
@@ -11966,16 +12012,18 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11966
12012
|
...replicasConfigService.areHooksRunning() && (replicasConfigService.getStartHookConfig()?.commands.length ?? 0) > 0 ? [START_HOOKS_RUNNING_PROMPT] : [],
|
|
11967
12013
|
...turnInstructions ? [turnInstructions] : []
|
|
11968
12014
|
];
|
|
12015
|
+
const turnLost = takesNotes && this.previousTurnLost;
|
|
12016
|
+
this.turnNotes.set(request, { turnLost, sentTurn: this.sentTurn, customInstructions: this.lastCustomInstructions });
|
|
11969
12017
|
const instructionsChanged = takesNotes && this.sentTurn && this.lastCustomInstructions !== standardInstructions;
|
|
11970
12018
|
this.sentTurn = true;
|
|
11971
12019
|
this.lastCustomInstructions = standardInstructions;
|
|
11972
|
-
const turnLost = takesNotes && this.previousTurnLost;
|
|
11973
12020
|
if (turnLost) this.previousTurnLost = false;
|
|
11974
12021
|
const notes = takesNotes ? [
|
|
11975
12022
|
...turnLost ? [`A workspace restart cut your previous turn off, and it was not retried. The working tree may hold partial work from it.${this.restoredMessages.has(request) ? " This message was sent before the restart." : ""}`] : [],
|
|
11976
12023
|
...instructionsChanged ? ["Your instructions changed since your previous turn. Earlier turns followed the old version: follow the current instructions from here on, and leave earlier replies as they are."] : [],
|
|
11977
12024
|
...turnFacts
|
|
11978
12025
|
].map((note) => wrapInTag(note, REPLICAS_INSTRUCTIONS_TAG)) : [];
|
|
12026
|
+
this.turnBeganAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
11979
12027
|
await processMessage({
|
|
11980
12028
|
...delivered,
|
|
11981
12029
|
// A goal or a slash command is sent as written, so what its turn needs to know goes in the system prompt.
|
|
@@ -11983,6 +12031,10 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
11983
12031
|
message: [delivered.message, ...notes].join("\n\n")
|
|
11984
12032
|
}, signal);
|
|
11985
12033
|
} finally {
|
|
12034
|
+
const cut = new Promise((resolve9) => {
|
|
12035
|
+
signal.addEventListener("abort", () => resolve9(), { once: true });
|
|
12036
|
+
});
|
|
12037
|
+
while (!signal.aborted && this.steerSettlements.size > 0) await Promise.race([Promise.allSettled(this.steerSettlements), cut]);
|
|
11986
12038
|
this.closeTurn();
|
|
11987
12039
|
}
|
|
11988
12040
|
},
|
|
@@ -12003,7 +12055,31 @@ var CodingAgentManager = class _CodingAgentManager {
|
|
|
12003
12055
|
}
|
|
12004
12056
|
async initialize() {
|
|
12005
12057
|
}
|
|
12006
|
-
async keepStoppedRequest(_request) {
|
|
12058
|
+
async keepStoppedRequest(_request, _signal) {
|
|
12059
|
+
return false;
|
|
12060
|
+
}
|
|
12061
|
+
takeKeptRequests() {
|
|
12062
|
+
return { sent: Promise.resolve([]), putBack: () => {
|
|
12063
|
+
} };
|
|
12064
|
+
}
|
|
12065
|
+
oweNotes(message) {
|
|
12066
|
+
const notes = this.turnNotes.get(message);
|
|
12067
|
+
if (!notes) return;
|
|
12068
|
+
if (notes.turnLost) this.previousTurnLost = true;
|
|
12069
|
+
this.sentTurn = notes.sentTurn;
|
|
12070
|
+
this.lastCustomInstructions = notes.customInstructions;
|
|
12071
|
+
}
|
|
12072
|
+
isStopped(signal) {
|
|
12073
|
+
return !!signal && this.messageQueue.isStopped(signal);
|
|
12074
|
+
}
|
|
12075
|
+
// A harness calls this with nothing awaited before it hands the message over, or a Stop in between would still send a withdrawn message.
|
|
12076
|
+
deliver(signal) {
|
|
12077
|
+
if (signal.aborted) return false;
|
|
12078
|
+
this.messageQueue.markDelivered();
|
|
12079
|
+
return true;
|
|
12080
|
+
}
|
|
12081
|
+
/** For a harness that only learns afterwards whether it read a message sent just before a Stop. */
|
|
12082
|
+
async readStoppedMessage(_signal) {
|
|
12007
12083
|
return false;
|
|
12008
12084
|
}
|
|
12009
12085
|
// Integration turns (Slack, GitHub, Linear) carry no sender fields and name their sender in the text, so they reset the key.
|
|
@@ -12051,27 +12127,50 @@ ${request.message}` }, senderKey };
|
|
|
12051
12127
|
const stoppedAt = new Date(requested <= now && requested > now - MAX_REQUESTED_STOP_AGE_MS ? requested : now).toISOString();
|
|
12052
12128
|
const queuedMessages = this.messageQueue.drainQueue();
|
|
12053
12129
|
const unreadSteers = [...this.unreadSteers.values()];
|
|
12130
|
+
const steersInFlight = [...this.steersInFlight.values()].filter(({ read }) => !read);
|
|
12131
|
+
for (const { message } of steersInFlight) this.steersInFlight.delete(message.id);
|
|
12054
12132
|
const earlySteers = this.earlySteers.splice(0);
|
|
12055
|
-
for (const steer of earlySteers) this.withdrawnSteers.add(steer);
|
|
12133
|
+
for (const steer of [...earlySteers, ...steersInFlight.map(({ delivered }) => delivered)]) this.withdrawnSteers.add(steer);
|
|
12056
12134
|
this.unreadSteers.clear();
|
|
12057
12135
|
this.onQueueChanged();
|
|
12058
|
-
this.messageQueue.
|
|
12136
|
+
const alreadyWithdrawn = this.messageQueue.stoppedTurn()?.delivered === false;
|
|
12137
|
+
const turn = this.messageQueue.cancelActiveTurn(true);
|
|
12138
|
+
const kept = this.takeKeptRequests();
|
|
12059
12139
|
const isProcessing = this.isProcessing() || (this.hasActiveBackgroundTasks?.() ?? false);
|
|
12140
|
+
let failure = null;
|
|
12060
12141
|
if (isProcessing) {
|
|
12061
12142
|
try {
|
|
12062
12143
|
await this.interruptActiveTurn(stoppedAt);
|
|
12063
12144
|
} catch (error) {
|
|
12064
|
-
|
|
12065
|
-
|
|
12066
|
-
|
|
12067
|
-
|
|
12068
|
-
|
|
12069
|
-
|
|
12145
|
+
failure = { error };
|
|
12146
|
+
}
|
|
12147
|
+
}
|
|
12148
|
+
const keptRequests = await kept.sent;
|
|
12149
|
+
const withdrawn = turn && !turn.message.engineTurn && !turn.delivered && !await this.readStoppedMessage(turn.controller.signal) ? [turn.message] : [];
|
|
12150
|
+
if (failure && withdrawn.length === 0) {
|
|
12151
|
+
kept.putBack();
|
|
12152
|
+
for (const steer of unreadSteers) this.unreadSteers.set(steer.message.id, steer);
|
|
12153
|
+
for (const { message, delivered } of steersInFlight) {
|
|
12154
|
+
this.withdrawnSteers.delete(delivered);
|
|
12155
|
+
this.unreadSteers.set(message.id, { message, delivered, steeredAt: stoppedAt });
|
|
12070
12156
|
}
|
|
12157
|
+
for (const steer of earlySteers) this.withdrawnSteers.delete(steer);
|
|
12158
|
+
this.earlySteers.push(...earlySteers);
|
|
12159
|
+
this.onQueueChanged();
|
|
12160
|
+
this.restoreQueuedMessages(queuedMessages.map((message) => ({ message, index: 0 })));
|
|
12161
|
+
throw failure.error;
|
|
12071
12162
|
}
|
|
12072
|
-
|
|
12163
|
+
if (failure) console.error("[CodingAgentManager] Interrupt failed for a message the agent never received:", failure.error);
|
|
12164
|
+
const handedBack = [...withdrawn.length > 0 || !turn ? keptRequests : [], ...withdrawn];
|
|
12165
|
+
const removed = [...handedBack, ...[...unreadSteers, ...steersInFlight].map(({ message }) => message), ...queuedMessages];
|
|
12073
12166
|
if (removed.length > 0) await persistRemoval(removed.map(({ id }) => id));
|
|
12074
|
-
if (
|
|
12167
|
+
if (handedBack.length > 0) {
|
|
12168
|
+
await this.saveLastSenderKey(null);
|
|
12169
|
+
for (const message of [...handedBack].reverse()) this.oweNotes(message);
|
|
12170
|
+
}
|
|
12171
|
+
if (turn && withdrawn.length > 0 && !this.harnessTurns.has(turn.controller.signal)) await this.onTurnComplete();
|
|
12172
|
+
const interrupted = isProcessing && withdrawn.length === 0 && !alreadyWithdrawn;
|
|
12173
|
+
if (interrupted) this.recordInterrupted(stoppedAt);
|
|
12075
12174
|
const queue = [];
|
|
12076
12175
|
const queueSenderUserIds = [];
|
|
12077
12176
|
let queueChars = 0;
|
|
@@ -12083,7 +12182,7 @@ ${request.message}` }, senderKey };
|
|
|
12083
12182
|
}
|
|
12084
12183
|
this.emitInterruptedQueueEvent(queue);
|
|
12085
12184
|
return {
|
|
12086
|
-
interrupted:
|
|
12185
|
+
interrupted: interrupted || withdrawn.length === 0 && removed.length > 0,
|
|
12087
12186
|
queue,
|
|
12088
12187
|
queueSenderUserIds,
|
|
12089
12188
|
removedMessageIds: removed.map(({ id }) => id)
|
|
@@ -12183,7 +12282,7 @@ ${request.message}` }, senderKey };
|
|
|
12183
12282
|
this.steersInFlight.set(messageId, inFlight);
|
|
12184
12283
|
try {
|
|
12185
12284
|
steered = this.earlySteers.length === 0 && await this.steerRequest(delivered);
|
|
12186
|
-
if (!steered && !inFlight.read && this.turnOpen && !command && this.steerRequest !== _CodingAgentManager.prototype.steerRequest) {
|
|
12285
|
+
if (!steered && !inFlight.read && this.turnOpen && !command && this.steersInFlight.has(messageId) && this.steerRequest !== _CodingAgentManager.prototype.steerRequest) {
|
|
12187
12286
|
this.earlySteers.push(delivered);
|
|
12188
12287
|
steered = true;
|
|
12189
12288
|
void this.deliverEarlySteers();
|
|
@@ -12192,7 +12291,7 @@ ${request.message}` }, senderKey };
|
|
|
12192
12291
|
} catch (error) {
|
|
12193
12292
|
console.error("[CodingAgentManager] steerRequest threw, keeping message queued:", error);
|
|
12194
12293
|
}
|
|
12195
|
-
this.steersInFlight.delete(messageId);
|
|
12294
|
+
if (!this.steersInFlight.delete(messageId)) return { success: false, queue: this.getQueue() };
|
|
12196
12295
|
if (inFlight.read) return { success: true, queue: this.getQueue() };
|
|
12197
12296
|
if (steered) {
|
|
12198
12297
|
this.unreadSteers.set(messageId, { message: taken.message, delivered, steeredAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
@@ -12217,10 +12316,16 @@ ${request.message}` }, senderKey };
|
|
|
12217
12316
|
const taken = this.messageQueue.takeFromQueue(messageId);
|
|
12218
12317
|
if (!taken) return { success: true, queue: this.getQueue() };
|
|
12219
12318
|
this.messageQueue.restoreToQueue(taken.message, 0);
|
|
12220
|
-
if (this.messageQueue.isProcessing()) {
|
|
12221
|
-
this.
|
|
12319
|
+
if (this.messageQueue.isProcessing() && !this.messageQueue.stoppedTurn()) {
|
|
12320
|
+
const requeued = this.keepStoppedRequest === _CodingAgentManager.prototype.keepStoppedRequest ? this.messageQueue.requeueActiveTurnAfter(messageId) : null;
|
|
12321
|
+
if (requeued) {
|
|
12322
|
+
this.oweNotes(requeued.message);
|
|
12323
|
+
this.onMessageRequeued(requeued.message, requeued.afterId);
|
|
12324
|
+
} else {
|
|
12325
|
+
this.recordInterrupted((/* @__PURE__ */ new Date()).toISOString(), true);
|
|
12326
|
+
}
|
|
12222
12327
|
this.messageQueue.cancelActiveTurn();
|
|
12223
|
-
await this.interruptActiveTurn();
|
|
12328
|
+
await Promise.all([this.interruptActiveTurn(), requeued && this.saveLastSenderKey(null)]);
|
|
12224
12329
|
}
|
|
12225
12330
|
return { success: true, queue: this.getQueue() };
|
|
12226
12331
|
}
|
|
@@ -13484,8 +13589,10 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13484
13589
|
// The time of the press, so the stop line is dated when the person cut the reply, not when Claude Code reports it.
|
|
13485
13590
|
cutSentAt = null;
|
|
13486
13591
|
compacting = false;
|
|
13487
|
-
// Claude Code never sees a prompt
|
|
13592
|
+
// Claude Code never sees a prompt cut off before it started, so it is sent again with the next message; a Stop before then hands back `requests`, the messages in it as the user sent them.
|
|
13488
13593
|
unreadPrompt = null;
|
|
13594
|
+
sentPrompt = null;
|
|
13595
|
+
turnPromptWritten = false;
|
|
13489
13596
|
runningTools = /* @__PURE__ */ new Map();
|
|
13490
13597
|
// Claude Code tells the model the user rejected the tool calls a stop cuts off, so the next prompt corrects that.
|
|
13491
13598
|
cutOffTools = /* @__PURE__ */ new Map();
|
|
@@ -13553,18 +13660,45 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13553
13660
|
this.requestsInFlight.clear();
|
|
13554
13661
|
}
|
|
13555
13662
|
// Stop can tear a session down before its command_lifecycle event is read, so the transcript decides.
|
|
13663
|
+
async promptRecorded(promptUuid) {
|
|
13664
|
+
return !!this.sessionId && (await getSessionMessages(this.sessionId, { dir: this.workingDirectory })).some(({ uuid }) => uuid === promptUuid);
|
|
13665
|
+
}
|
|
13556
13666
|
async dropRecordedUnreadPrompt() {
|
|
13557
|
-
|
|
13558
|
-
if (unread && this.sessionId && (await getSessionMessages(this.sessionId, { dir: this.workingDirectory })).some(({ uuid }) => uuid === unread.uuid)) {
|
|
13559
|
-
this.unreadPrompt = null;
|
|
13560
|
-
}
|
|
13667
|
+
if (this.unreadPrompt && await this.promptRecorded(this.unreadPrompt.uuid)) this.unreadPrompt = null;
|
|
13561
13668
|
}
|
|
13562
|
-
async
|
|
13669
|
+
async readStoppedMessage(signal) {
|
|
13670
|
+
return this.sentPrompt?.signal === signal && this.promptRecorded(this.sentPrompt.uuid);
|
|
13671
|
+
}
|
|
13672
|
+
// The chat's own copy of a prompt is written once Claude Code has it, so a prompt stopped before then leaves nothing behind.
|
|
13673
|
+
async recordSentPrompt() {
|
|
13674
|
+
const record3 = this.sentPrompt?.record;
|
|
13675
|
+
if (!this.sentPrompt || !record3) return;
|
|
13676
|
+
this.sentPrompt.record = void 0;
|
|
13677
|
+
await record3();
|
|
13678
|
+
}
|
|
13679
|
+
async keepStoppedRequest(request, signal) {
|
|
13563
13680
|
await this.dropRecordedUnreadPrompt();
|
|
13564
13681
|
const { uuid, message } = await this.buildUserMessage(request);
|
|
13565
|
-
|
|
13682
|
+
if (this.isStopped(signal)) return false;
|
|
13683
|
+
this.keepUnreadPrompt(uuid, appendUserContent(this.unreadPrompt?.content ?? [], message.content));
|
|
13566
13684
|
return true;
|
|
13567
13685
|
}
|
|
13686
|
+
keepUnreadPrompt(uuid, content) {
|
|
13687
|
+
const requests = this.unreadPrompt?.requests ?? [];
|
|
13688
|
+
this.unreadPrompt = { uuid, content, requests: !this.turnRequest || requests.includes(this.turnRequest) ? requests : [...requests, this.turnRequest] };
|
|
13689
|
+
}
|
|
13690
|
+
takeKeptRequests() {
|
|
13691
|
+
const unread = this.unreadPrompt;
|
|
13692
|
+
this.unreadPrompt = null;
|
|
13693
|
+
return {
|
|
13694
|
+
sent: (async () => unread && !await this.promptRecorded(unread.uuid) ? unread.requests : [])(),
|
|
13695
|
+
putBack: () => {
|
|
13696
|
+
if (!unread) return;
|
|
13697
|
+
const later = this.unreadPrompt;
|
|
13698
|
+
this.unreadPrompt = later ? { ...later, content: appendUserContent(unread.content, later.content), requests: [...unread.requests, ...later.requests] } : unread;
|
|
13699
|
+
}
|
|
13700
|
+
};
|
|
13701
|
+
}
|
|
13568
13702
|
// A steer is read when the tool call in flight returns; with none, Claude Code reads it only once the whole reply is written.
|
|
13569
13703
|
// 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.
|
|
13570
13704
|
repliesInFlight() {
|
|
@@ -13609,7 +13743,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13609
13743
|
if (!pendingTurn || !promptStream) return false;
|
|
13610
13744
|
if (getGoalCommand(request.message, request.goalMode)) return false;
|
|
13611
13745
|
const userMessage = await this.buildUserMessage(request);
|
|
13612
|
-
if (this.pendingTurn !== pendingTurn || this.activePromptStream !== promptStream) return false;
|
|
13746
|
+
if (this.pendingTurn !== pendingTurn || this.activePromptStream !== promptStream || this.isSteerWithdrawn(request)) return false;
|
|
13613
13747
|
pendingTurn.userMessageUuids.add(userMessage.uuid);
|
|
13614
13748
|
pendingTurn.steers.set(userMessage.uuid, { messageId: request.id, userMessage });
|
|
13615
13749
|
promptStream.push({ ...userMessage, priority: "next" });
|
|
@@ -13910,7 +14044,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13910
14044
|
let failedCredentials = [];
|
|
13911
14045
|
let modelRejected = [];
|
|
13912
14046
|
let walkLimit;
|
|
13913
|
-
let attempt = 0;
|
|
13914
14047
|
let authRetries = 0;
|
|
13915
14048
|
let transientRetries = 0;
|
|
13916
14049
|
let midTurnContinues = 0;
|
|
@@ -13920,6 +14053,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13920
14053
|
let currentRequest = request;
|
|
13921
14054
|
let carriedSteers = /* @__PURE__ */ new Map();
|
|
13922
14055
|
this.turnLoginFailure = null;
|
|
14056
|
+
this.turnPromptWritten = false;
|
|
13923
14057
|
await this.goalClear?.catch(() => {
|
|
13924
14058
|
});
|
|
13925
14059
|
await this.stopping?.catch(() => {
|
|
@@ -13935,7 +14069,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13935
14069
|
await this.executeQuery({ ...currentRequest, message: "/compact", images: [], goalMode: false }, { skipUserMessageRecord: true, engineTurn: true, signal });
|
|
13936
14070
|
compactBeforeRetry = false;
|
|
13937
14071
|
}
|
|
13938
|
-
await this.executeQuery(currentRequest, { skipUserMessageRecord:
|
|
14072
|
+
await this.executeQuery(currentRequest, { skipUserMessageRecord: this.turnPromptWritten || request.engineTurn, engineTurn: request.engineTurn, signal, steers });
|
|
13939
14073
|
return;
|
|
13940
14074
|
} catch (error) {
|
|
13941
14075
|
lastError = error;
|
|
@@ -13947,7 +14081,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13947
14081
|
compactedForContext = compactBeforeRetry = true;
|
|
13948
14082
|
currentRequest = { ...currentRequest, message: request.message, images: request.images, goalMode: request.goalMode };
|
|
13949
14083
|
carriedSteers = steers;
|
|
13950
|
-
attempt++;
|
|
13951
14084
|
continue;
|
|
13952
14085
|
}
|
|
13953
14086
|
if (this.attemptSawActivity) failedCredentials = [];
|
|
@@ -13975,7 +14108,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13975
14108
|
if (attemptedCredential && live && !isSameCredential(attemptedCredential, live)) {
|
|
13976
14109
|
this.turnLoginFailure ??= describeLoginFailure("claude", attemptedCredential, resolveClaudeAuthMethodForMessage(), false);
|
|
13977
14110
|
}
|
|
13978
|
-
attempt++;
|
|
13979
14111
|
continue;
|
|
13980
14112
|
}
|
|
13981
14113
|
const method = attemptedCredential?.method ?? resolveClaudeAuthMethodForMessage();
|
|
@@ -13985,12 +14117,12 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
13985
14117
|
}
|
|
13986
14118
|
if (quotaKind || isAuthError || modelUnavailable) {
|
|
13987
14119
|
const reason = quotaKind ?? (modelUnavailable ? "model_unavailable" : "auth_failed");
|
|
13988
|
-
const
|
|
14120
|
+
const detail2 = error instanceof ClaudeQuotaError || error instanceof ClaudeModelUnavailableError ? error.message : extractErrorText(error);
|
|
13989
14121
|
const repeated = !!attemptedCredential && failedCredentials.some((failed) => isSameCredential(failed, attemptedCredential));
|
|
13990
14122
|
if (attemptedCredential) failedCredentials.push(attemptedCredential);
|
|
13991
14123
|
if (attemptedCredential && modelUnavailable) modelRejected.push(attemptedCredential);
|
|
13992
14124
|
const limit = quotaKind ? { kind: quotaKind, credential: attemptedCredential } : walkLimit;
|
|
13993
|
-
const fallback = repeated ? { outcome: "unavailable" } : await this.fallBackCredential(reason,
|
|
14125
|
+
const fallback = repeated ? { outcome: "unavailable" } : await this.fallBackCredential(reason, detail2, attemptedCredential, error instanceof ClaudeQuotaError ? error.resetsAt : void 0, !!walkLimit);
|
|
13994
14126
|
if (fallback.outcome === "switched") {
|
|
13995
14127
|
walkLimit = limit;
|
|
13996
14128
|
if (isAuthError) {
|
|
@@ -14001,14 +14133,13 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14001
14133
|
loginRevoked = false;
|
|
14002
14134
|
namedLogin = void 0;
|
|
14003
14135
|
await this.tearDownSession();
|
|
14004
|
-
attempt++;
|
|
14005
14136
|
continue;
|
|
14006
14137
|
}
|
|
14007
14138
|
if (limit && (quotaKind || fallback.outcome === "fork")) {
|
|
14008
14139
|
if (isAuthError) {
|
|
14009
14140
|
this.turnLoginFailure ??= describeLoginFailure("claude", attemptedCredential ?? namedLogin, resolveClaudeAuthMethodForMessage(), loginRevoked);
|
|
14010
14141
|
}
|
|
14011
|
-
await this.emitQuotaExhaustedEvent(limit.kind, fallback,
|
|
14142
|
+
await this.emitQuotaExhaustedEvent(limit.kind, fallback, detail2, limit.credential);
|
|
14012
14143
|
return;
|
|
14013
14144
|
}
|
|
14014
14145
|
if (modelUnavailable) {
|
|
@@ -14025,7 +14156,7 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14025
14156
|
provider: "claude",
|
|
14026
14157
|
reason: "model_unavailable",
|
|
14027
14158
|
status: "switched",
|
|
14028
|
-
detail,
|
|
14159
|
+
detail: detail2,
|
|
14029
14160
|
exhaustedMethod: method,
|
|
14030
14161
|
exhaustedScope: scope,
|
|
14031
14162
|
candidateMethod: method,
|
|
@@ -14039,11 +14170,10 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14039
14170
|
forgetExhaustedCredentials("claude", modelRejected);
|
|
14040
14171
|
failedCredentials = [];
|
|
14041
14172
|
modelRejected = [];
|
|
14042
|
-
attempt++;
|
|
14043
14173
|
continue;
|
|
14044
14174
|
}
|
|
14045
14175
|
const requested = normalizeClaudeModel(request.model) ?? DEFAULT_CLAUDE_MODEL;
|
|
14046
|
-
await this.emitTerminalErrorResult(
|
|
14176
|
+
await this.emitTerminalErrorResult(detail2, [describeModelUnavailable("claude", [.../* @__PURE__ */ new Set([requested, model])], attemptedCredential)]);
|
|
14047
14177
|
return;
|
|
14048
14178
|
}
|
|
14049
14179
|
failedLogin = { credential: attemptedCredential ?? namedLogin, revoked: loginRevoked };
|
|
@@ -14056,7 +14186,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14056
14186
|
carriedSteers = steers;
|
|
14057
14187
|
await this.onSaveSessionId(null);
|
|
14058
14188
|
await this.tearDownSession();
|
|
14059
|
-
attempt++;
|
|
14060
14189
|
continue;
|
|
14061
14190
|
}
|
|
14062
14191
|
if (error instanceof ClaudeTransientTurnError && error.midTurn) {
|
|
@@ -14073,7 +14202,6 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14073
14202
|
await this.tearDownSession();
|
|
14074
14203
|
await new Promise((resolve9) => setTimeout(resolve9, delayMs));
|
|
14075
14204
|
currentRequest = { ...request, message: CLAUDE_MIDTURN_CONTINUE_PROMPT, images: [], goalMode: false };
|
|
14076
|
-
attempt++;
|
|
14077
14205
|
continue;
|
|
14078
14206
|
}
|
|
14079
14207
|
if (_ClaudeManager.isTransientTurnError(error) && transientRetries < MAX_TRANSIENT_RETRIES) {
|
|
@@ -14085,9 +14213,10 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14085
14213
|
);
|
|
14086
14214
|
await this.tearDownSession();
|
|
14087
14215
|
await new Promise((resolve9) => setTimeout(resolve9, delayMs));
|
|
14088
|
-
attempt++;
|
|
14089
14216
|
continue;
|
|
14090
14217
|
}
|
|
14218
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
14219
|
+
await this.emitTerminalErrorResult(detail, [`Claude Code stopped before this turn finished (${detail}). Send a message to continue.`]);
|
|
14091
14220
|
throw error;
|
|
14092
14221
|
}
|
|
14093
14222
|
}
|
|
@@ -14160,9 +14289,11 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14160
14289
|
this.lastRequest = request;
|
|
14161
14290
|
this.pendingInterrupt = false;
|
|
14162
14291
|
const userMessage = await this.buildUserMessage(request);
|
|
14163
|
-
|
|
14164
|
-
|
|
14165
|
-
|
|
14292
|
+
const promptAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
14293
|
+
const recordPrompt = options.skipUserMessageRecord ? void 0 : async () => {
|
|
14294
|
+
this.turnPromptWritten = true;
|
|
14295
|
+
await this.recordEvent(userMessage, request.messageId, request.replacesMessageId, promptAt);
|
|
14296
|
+
};
|
|
14166
14297
|
const goalCommand = getGoalCommand(message, request.goalMode);
|
|
14167
14298
|
const goalObjective = goalCommand?.type === "set" ? goalCommand.objective : goalCommand?.type === "resume" ? this.currentGoal?.objective : void 0;
|
|
14168
14299
|
if (goalCommand && !options.skipUserMessageRecord) {
|
|
@@ -14225,8 +14356,9 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14225
14356
|
const content = appendUserContent(appendUserContent(cutOffNote, this.unreadPrompt?.content ?? []), prompt);
|
|
14226
14357
|
if (this.pendingInterrupt || options.signal?.aborted) {
|
|
14227
14358
|
this.pendingInterrupt = false;
|
|
14228
|
-
if (!options.engineTurn) {
|
|
14229
|
-
|
|
14359
|
+
if (!options.engineTurn && !this.isStopped(options.signal)) {
|
|
14360
|
+
await recordPrompt?.();
|
|
14361
|
+
this.keepUnreadPrompt(userMessage.uuid, content);
|
|
14230
14362
|
dropNotedCutOffs();
|
|
14231
14363
|
}
|
|
14232
14364
|
return;
|
|
@@ -14244,14 +14376,21 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14244
14376
|
steers,
|
|
14245
14377
|
userMessageUuids: /* @__PURE__ */ new Set([userMessage.uuid, ...steers.keys()])
|
|
14246
14378
|
};
|
|
14379
|
+
if (options.signal && !options.engineTurn) this.sentPrompt = { uuid: userMessage.uuid, signal: options.signal, record: recordPrompt };
|
|
14247
14380
|
promptStream.push({ ...userMessage, message: { role: "user", content } });
|
|
14248
14381
|
for (const { userMessage: steer } of steers.values()) promptStream.push({ ...steer, priority: "next" });
|
|
14249
14382
|
void this.deliverEarlySteers();
|
|
14250
14383
|
});
|
|
14251
14384
|
} finally {
|
|
14252
|
-
|
|
14385
|
+
const carried = options.signal?.aborted && !options.engineTurn && !this.isStopped(options.signal);
|
|
14386
|
+
if (this.turnPromptRecorded || carried) dropNotedCutOffs();
|
|
14253
14387
|
if (this.turnPromptRecorded) this.unreadPrompt = null;
|
|
14254
|
-
else if (
|
|
14388
|
+
else if (carried) this.keepUnreadPrompt(userMessage.uuid, content);
|
|
14389
|
+
else if (this.unreadPrompt && options.signal?.aborted) this.unreadPrompt = { ...this.unreadPrompt, uuid: userMessage.uuid };
|
|
14390
|
+
if (this.sentPrompt?.record) {
|
|
14391
|
+
if (!this.isStopped(options.signal) || await this.promptRecorded(userMessage.uuid)) await this.recordSentPrompt();
|
|
14392
|
+
else this.sentPrompt.record = void 0;
|
|
14393
|
+
}
|
|
14255
14394
|
}
|
|
14256
14395
|
}
|
|
14257
14396
|
async buildUserMessage({ message, images }) {
|
|
@@ -14555,6 +14694,10 @@ var ClaudeManager = class _ClaudeManager extends CodingAgentManager {
|
|
|
14555
14694
|
if (isRecord(lifecycle2) && lifecycle2.type === "command_lifecycle" && lifecycle2.state === "started" && typeof lifecycle2.command_uuid === "string") {
|
|
14556
14695
|
if (this.pendingTurn?.userMessageUuids.has(lifecycle2.command_uuid)) {
|
|
14557
14696
|
this.turnPromptRecorded = true;
|
|
14697
|
+
if (lifecycle2.command_uuid === this.sentPrompt?.uuid) {
|
|
14698
|
+
this.messageQueue.markDelivered();
|
|
14699
|
+
await this.recordSentPrompt();
|
|
14700
|
+
}
|
|
14558
14701
|
this.settlePromptStart();
|
|
14559
14702
|
} else if (!this.activePromptStream?.sentUuids.has(lifecycle2.command_uuid)) await this.recordPeerMessage(lifecycle2.command_uuid, response);
|
|
14560
14703
|
if (this.activeQuery !== response) break;
|
|
@@ -15068,8 +15211,7 @@ ${msg.result}` } : { ...msg, errors: [loginFailure, ...msg.errors] } : msg);
|
|
|
15068
15211
|
this.recordGoalChange(null);
|
|
15069
15212
|
}
|
|
15070
15213
|
}
|
|
15071
|
-
async recordEvent(event, replicasMessageId, replacesMessageId) {
|
|
15072
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
15214
|
+
async recordEvent(event, replicasMessageId, replacesMessageId, timestamp = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
15073
15215
|
const restampAmbient = event.type === "system" && "task_id" in event && this.ambientTaskIds.has(event.task_id);
|
|
15074
15216
|
const payload = { ...event };
|
|
15075
15217
|
delete payload.tool_use_result;
|
|
@@ -15194,6 +15336,7 @@ var MODEL_AT_CAPACITY_RETRY_BASE_MS = 5e3;
|
|
|
15194
15336
|
var MODEL_AT_CAPACITY_CONTINUE_PROMPT = "Your previous turn stopped because the model was at capacity. Continue from where you left off: first check what is already done, and do not repeat commands, edits, or messages you already completed.";
|
|
15195
15337
|
var CODEX_SLASH_COMMANDS_CACHE_MS = 3e4;
|
|
15196
15338
|
var POLICY_REASON_INJECTION_TIMEOUT_MS = 5e3;
|
|
15339
|
+
var CODEX_INTERRUPT_TIMEOUT_MS = 5e3;
|
|
15197
15340
|
var SUBAGENT_MCP_THREADS_DIR = join12(ENGINE_ENV.HOME_DIR, ".replicas", "codex", "subagent-mcp-threads");
|
|
15198
15341
|
async function markSubagentMcpThread(threadId) {
|
|
15199
15342
|
await mkdir8(SUBAGENT_MCP_THREADS_DIR, { recursive: true });
|
|
@@ -15244,6 +15387,8 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15244
15387
|
goalHistoryKnown = false;
|
|
15245
15388
|
goalRevision = 0;
|
|
15246
15389
|
onGoalChanged = null;
|
|
15390
|
+
lateStart = null;
|
|
15391
|
+
stopGiveUp = null;
|
|
15247
15392
|
itemUpdateCoalescer = new ItemUpdateCoalescer((itemId) => {
|
|
15248
15393
|
const item = this.liveTurn?.items.get(itemId);
|
|
15249
15394
|
if (this.liveTurn && item) this.onEvent(codexItemEvent(this.liveTurn.id, item, true));
|
|
@@ -15254,6 +15399,7 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15254
15399
|
slashCommandsRequest = null;
|
|
15255
15400
|
steeredTempImagePaths = [];
|
|
15256
15401
|
// Codex never sees a message stopped before its turn started, so it is sent again with the next one.
|
|
15402
|
+
// `sent` is that message as the user sent it, which a Stop before the next turn hands back.
|
|
15257
15403
|
unreadRequests = [];
|
|
15258
15404
|
compacting = false;
|
|
15259
15405
|
steerLock = new AsyncLock();
|
|
@@ -15287,7 +15433,9 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15287
15433
|
}
|
|
15288
15434
|
async interrupt(persistRemoval, requestedStoppedAt) {
|
|
15289
15435
|
if (this.currentGoal?.status === "active") {
|
|
15290
|
-
await this.updateGoal({ status: "paused" })
|
|
15436
|
+
await this.updateGoal({ status: "paused" }, CODEX_INTERRUPT_TIMEOUT_MS).catch((error) => {
|
|
15437
|
+
console.error("[CodexAspManager] Failed to pause the goal on Stop:", error);
|
|
15438
|
+
});
|
|
15291
15439
|
}
|
|
15292
15440
|
return super.interrupt(persistRemoval, requestedStoppedAt);
|
|
15293
15441
|
}
|
|
@@ -15295,36 +15443,61 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15295
15443
|
if (!canSteerMessage("codex", request)) return false;
|
|
15296
15444
|
this.unreadRequests.push({ ...request, message: `${request.message}
|
|
15297
15445
|
|
|
15298
|
-
|
|
15446
|
+
`, sent: this.turnRequest });
|
|
15299
15447
|
return true;
|
|
15300
15448
|
}
|
|
15301
|
-
|
|
15449
|
+
takeKeptRequests() {
|
|
15450
|
+
const command = this.turnRequest && getGoalCommand(this.turnRequest.message, this.turnRequest.goalMode)?.type;
|
|
15451
|
+
if (this.turnRequest && (isCompactCommand(this.turnRequest.message) || command && command !== "set")) return { sent: Promise.resolve([]), putBack: () => {
|
|
15452
|
+
} };
|
|
15453
|
+
const unread = this.unreadRequests;
|
|
15454
|
+
this.unreadRequests = [];
|
|
15455
|
+
return {
|
|
15456
|
+
sent: Promise.resolve(unread.flatMap(({ sent }) => sent ?? [])),
|
|
15457
|
+
putBack: () => {
|
|
15458
|
+
this.unreadRequests = [...unread, ...this.unreadRequests];
|
|
15459
|
+
}
|
|
15460
|
+
};
|
|
15461
|
+
}
|
|
15462
|
+
async interruptActiveTurn(stoppedAt) {
|
|
15302
15463
|
if (!this.currentThreadId || !this.activeTurnId) {
|
|
15303
15464
|
return;
|
|
15304
15465
|
}
|
|
15305
15466
|
const threadId = this.currentThreadId;
|
|
15306
15467
|
const expectedTurnId = this.activeTurnId;
|
|
15468
|
+
const giveUp = stoppedAt ? this.stopGiveUp : null;
|
|
15469
|
+
giveUp?.hold();
|
|
15470
|
+
let unanswered = null;
|
|
15307
15471
|
try {
|
|
15308
15472
|
await (await getCodexAspHost()).client.request(
|
|
15309
15473
|
THREAD_BACKGROUND_TERMINALS_CLEAN_METHOD,
|
|
15310
|
-
{ threadId }
|
|
15474
|
+
{ threadId },
|
|
15475
|
+
{ timeoutMs: CODEX_INTERRUPT_TIMEOUT_MS }
|
|
15311
15476
|
);
|
|
15312
15477
|
} catch (error) {
|
|
15313
15478
|
console.warn("[CodexAspManager] Failed to stop the turn's running commands:", error);
|
|
15479
|
+
if (error instanceof AspRequestTimeoutError) unanswered = error;
|
|
15314
15480
|
}
|
|
15315
|
-
const
|
|
15481
|
+
const interrupting = this.requestActiveTurnWithReconciliation(
|
|
15316
15482
|
"interrupt",
|
|
15317
15483
|
expectedTurnId,
|
|
15318
15484
|
(host, turnId) => host.client.request(
|
|
15319
15485
|
TURN_INTERRUPT_METHOD,
|
|
15320
|
-
{ threadId, turnId }
|
|
15486
|
+
{ threadId, turnId },
|
|
15487
|
+
{ timeoutMs: CODEX_INTERRUPT_TIMEOUT_MS }
|
|
15321
15488
|
)
|
|
15322
15489
|
);
|
|
15490
|
+
void interrupting.then((result2) => {
|
|
15491
|
+
if (giveUp === this.stopGiveUp && (result2.ok || !(result2.error.details instanceof AspRequestTimeoutError))) giveUp?.arm();
|
|
15492
|
+
});
|
|
15493
|
+
if (stoppedAt && unanswered) throw unanswered;
|
|
15494
|
+
const result = await interrupting;
|
|
15323
15495
|
if (result.ok) return;
|
|
15324
15496
|
console.warn(
|
|
15325
15497
|
result.error.code === "retry_failed" ? "[CodexAspManager] Failed to interrupt reconciled active turn; leaving shared Codex app-server running:" : "[CodexAspManager] Failed to interrupt active turn:",
|
|
15326
15498
|
result.error.details
|
|
15327
15499
|
);
|
|
15500
|
+
if (stoppedAt && result.error.details instanceof AspRequestTimeoutError) throw result.error.details;
|
|
15328
15501
|
}
|
|
15329
15502
|
async requestActiveTurnWithReconciliation(operation, expectedTurnId, request) {
|
|
15330
15503
|
try {
|
|
@@ -15471,9 +15644,10 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15471
15644
|
this.recordGoalChange(null, true);
|
|
15472
15645
|
return null;
|
|
15473
15646
|
}
|
|
15474
|
-
async updateGoal(request) {
|
|
15647
|
+
async updateGoal(request, timeoutMs) {
|
|
15475
15648
|
await this.initialized;
|
|
15476
15649
|
if (!this.currentThreadId) return null;
|
|
15650
|
+
if (request.status !== "paused") await this.lateStart;
|
|
15477
15651
|
const host = await getCodexAspHost();
|
|
15478
15652
|
const response = await host.client.request(
|
|
15479
15653
|
THREAD_GOAL_SET_METHOD,
|
|
@@ -15481,14 +15655,15 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15481
15655
|
threadId: this.currentThreadId,
|
|
15482
15656
|
...request.objective !== void 0 ? { objective: request.objective } : {},
|
|
15483
15657
|
...request.status !== void 0 ? { status: request.status } : {}
|
|
15484
|
-
}
|
|
15658
|
+
},
|
|
15659
|
+
{ timeoutMs }
|
|
15485
15660
|
);
|
|
15486
15661
|
this.recordGoalChange(response.goal, true);
|
|
15487
15662
|
return this.currentGoal;
|
|
15488
15663
|
}
|
|
15489
|
-
recordUserMessageEvent(request, extraPayload = {}) {
|
|
15664
|
+
recordUserMessageEvent(request, extraPayload = {}, timestamp) {
|
|
15490
15665
|
const images = imageContentToUserMessageImages(request.images);
|
|
15491
|
-
this.recordUserMessageHistoryEvent(request, { ...images ? { images } : {}, ...extraPayload });
|
|
15666
|
+
this.recordUserMessageHistoryEvent(request, { ...images ? { images } : {}, ...extraPayload }, timestamp);
|
|
15492
15667
|
}
|
|
15493
15668
|
async processMessageInternal(request, signal) {
|
|
15494
15669
|
let userMessageRecorded = false;
|
|
@@ -15496,7 +15671,7 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15496
15671
|
const recordUserMessage = (extraPayload = {}) => {
|
|
15497
15672
|
if (userMessageRecorded) return;
|
|
15498
15673
|
userMessageRecorded = true;
|
|
15499
|
-
this.recordUserMessageEvent(request, extraPayload);
|
|
15674
|
+
this.recordUserMessageEvent(request, extraPayload, this.turnBeganAt);
|
|
15500
15675
|
};
|
|
15501
15676
|
const goalCommand = getGoalCommand(request.message, request.goalMode);
|
|
15502
15677
|
const dispatch = async () => {
|
|
@@ -15514,11 +15689,11 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15514
15689
|
return;
|
|
15515
15690
|
}
|
|
15516
15691
|
if (goalCommand?.type === "clear") {
|
|
15517
|
-
await this.executeGoalClearCommand(request, recordUserMessage);
|
|
15692
|
+
await this.executeGoalClearCommand(request, recordUserMessage, signal);
|
|
15518
15693
|
return;
|
|
15519
15694
|
}
|
|
15520
15695
|
if (goalCommand?.type === "pause") {
|
|
15521
|
-
await this.executeGoalPauseCommand(request, recordUserMessage);
|
|
15696
|
+
await this.executeGoalPauseCommand(request, recordUserMessage, signal);
|
|
15522
15697
|
return;
|
|
15523
15698
|
}
|
|
15524
15699
|
if (goalCommand?.type === "resume" && this.currentGoal?.status === "complete") {
|
|
@@ -15642,41 +15817,72 @@ var CodexAspManager = class extends CodingAgentManager {
|
|
|
15642
15817
|
await this.onTurnComplete();
|
|
15643
15818
|
}
|
|
15644
15819
|
}
|
|
15645
|
-
async executeGoalClearCommand(request, recordUserMessage) {
|
|
15646
|
-
const
|
|
15820
|
+
async executeGoalClearCommand(request, recordUserMessage, signal) {
|
|
15821
|
+
const prepared = await this.prepareGoalCommand(request, recordUserMessage, signal);
|
|
15822
|
+
if (!prepared) return;
|
|
15823
|
+
const { host, threadId } = prepared;
|
|
15647
15824
|
await host.client.request(
|
|
15648
15825
|
THREAD_GOAL_CLEAR_METHOD,
|
|
15649
15826
|
{ threadId }
|
|
15650
15827
|
);
|
|
15651
15828
|
this.recordGoalChange(null, true);
|
|
15652
15829
|
}
|
|
15653
|
-
async executeGoalPauseCommand(request, recordUserMessage) {
|
|
15654
|
-
const
|
|
15830
|
+
async executeGoalPauseCommand(request, recordUserMessage, signal) {
|
|
15831
|
+
const prepared = await this.prepareGoalCommand(request, recordUserMessage, signal);
|
|
15832
|
+
if (!prepared) return;
|
|
15833
|
+
const { host, threadId } = prepared;
|
|
15655
15834
|
const response = await host.client.request(
|
|
15656
15835
|
THREAD_GOAL_SET_METHOD,
|
|
15657
15836
|
{ threadId, status: "paused" }
|
|
15658
15837
|
);
|
|
15659
15838
|
this.recordGoalChange(response.goal, true);
|
|
15660
15839
|
}
|
|
15661
|
-
async prepareGoalCommand(request, recordUserMessage) {
|
|
15840
|
+
async prepareGoalCommand(request, recordUserMessage, signal) {
|
|
15662
15841
|
const host = await getCodexAspHost();
|
|
15663
15842
|
const developerInstructions = this.buildCombinedInstructions(splitManagerInstructions(request.customInstructions).customInstructions, true);
|
|
15664
|
-
recordUserMessage({ command: "goal" });
|
|
15665
15843
|
const threadId = await this.ensureThread(host, request, developerInstructions);
|
|
15666
|
-
|
|
15844
|
+
await this.lateStartStopped(signal);
|
|
15845
|
+
const delivered = this.deliver(signal);
|
|
15846
|
+
if (delivered || !this.isStopped(signal)) recordUserMessage({ command: "goal" });
|
|
15847
|
+
return delivered ? { host, threadId } : null;
|
|
15848
|
+
}
|
|
15849
|
+
// The app-server takes a start written behind one still in flight into that one's turn, so the next one waits until that one is stopped, undelivered: a Stop meanwhile still withdraws it.
|
|
15850
|
+
async lateStartStopped(signal) {
|
|
15851
|
+
if (!this.lateStart || signal.aborted) return;
|
|
15852
|
+
await Promise.race([this.lateStart, new Promise((resolve9) => signal.addEventListener("abort", () => resolve9(), { once: true }))]);
|
|
15667
15853
|
}
|
|
15668
15854
|
async executeAspTurn(request, recordUserMessage, signal, options = {}) {
|
|
15669
15855
|
const host = await getCodexAspHost();
|
|
15670
15856
|
const developerInstructions = this.buildCombinedInstructions(splitManagerInstructions(request.customInstructions).customInstructions, true);
|
|
15671
|
-
recordUserMessage(options.userMessagePayload);
|
|
15672
15857
|
const threadId = await this.ensureThread(host, request, developerInstructions);
|
|
15673
15858
|
const serviceTier = await this.resolveRequestedServiceTier(host, request);
|
|
15674
15859
|
await this.applyThreadServiceTier(host, threadId, serviceTier);
|
|
15675
|
-
|
|
15860
|
+
let runTurn = options.runTurn;
|
|
15861
|
+
let tempImagePaths = [];
|
|
15862
|
+
if (!runTurn) {
|
|
15863
|
+
const carried = options.continuation ? [] : [...this.unreadRequests];
|
|
15864
|
+
const turnStart = await buildTurnStartParams(
|
|
15865
|
+
threadId,
|
|
15866
|
+
options.continuation ? { ...request, images: void 0 } : request,
|
|
15867
|
+
serviceTier,
|
|
15868
|
+
carried
|
|
15869
|
+
).catch((error) => {
|
|
15870
|
+
this.unreadRequests = this.unreadRequests.map((unread) => ({ ...unread, images: void 0 }));
|
|
15871
|
+
if (!signal.aborted) recordUserMessage(options.userMessagePayload);
|
|
15872
|
+
throw error;
|
|
15873
|
+
});
|
|
15874
|
+
tempImagePaths = turnStart.tempImagePaths;
|
|
15875
|
+
runTurn = (aspHost, aspThreadId) => this.runTurn(aspHost, aspThreadId, request, turnStart, signal, carried, options.continuation);
|
|
15876
|
+
}
|
|
15877
|
+
await this.lateStartStopped(signal);
|
|
15878
|
+
if (!this.deliver(signal)) {
|
|
15879
|
+
await removeTempImageFiles(tempImagePaths);
|
|
15880
|
+
if (this.isStopped(signal)) return;
|
|
15881
|
+
recordUserMessage(options.userMessagePayload);
|
|
15676
15882
|
if (!options.runTurn && !options.continuation) await this.keepStoppedRequest(request);
|
|
15677
15883
|
return;
|
|
15678
15884
|
}
|
|
15679
|
-
|
|
15885
|
+
recordUserMessage(options.userMessagePayload);
|
|
15680
15886
|
let completedTurn;
|
|
15681
15887
|
try {
|
|
15682
15888
|
completedTurn = await runTurn(host, threadId);
|
|
@@ -15826,16 +16032,7 @@ ${text.slice(-24e3)}`
|
|
|
15826
16032
|
console.warn("[CodexAspManager] Failed to apply skill registries:", error);
|
|
15827
16033
|
}
|
|
15828
16034
|
}
|
|
15829
|
-
async runTurn(host, threadId, request,
|
|
15830
|
-
const { params, tempImagePaths } = await buildTurnStartParams(
|
|
15831
|
-
threadId,
|
|
15832
|
-
continuation ? { ...request, images: void 0 } : request,
|
|
15833
|
-
serviceTier,
|
|
15834
|
-
continuation ? [] : this.unreadRequests
|
|
15835
|
-
).catch((error) => {
|
|
15836
|
-
this.unreadRequests = this.unreadRequests.map((unread) => ({ ...unread, images: void 0 }));
|
|
15837
|
-
throw error;
|
|
15838
|
-
});
|
|
16035
|
+
async runTurn(host, threadId, request, { params, tempImagePaths }, signal, carried, continuation = false) {
|
|
15839
16036
|
return this.observeTurn(host, threadId, request, signal, async () => {
|
|
15840
16037
|
const turnStartResponse = await host.client.request(
|
|
15841
16038
|
TURN_START_METHOD,
|
|
@@ -15848,13 +16045,14 @@ ${text.slice(-24e3)}`
|
|
|
15848
16045
|
}
|
|
15849
16046
|
} : params
|
|
15850
16047
|
);
|
|
15851
|
-
|
|
16048
|
+
this.unreadRequests = this.unreadRequests.filter((unread) => !carried.includes(unread));
|
|
15852
16049
|
return { turn: turnStartResponse.turn, tempImagePaths };
|
|
15853
16050
|
});
|
|
15854
16051
|
}
|
|
15855
16052
|
async runGoalTurn(host, threadId, request, objective, signal) {
|
|
15856
16053
|
const { managerInstructions } = splitManagerInstructions(request.customInstructions);
|
|
15857
|
-
const
|
|
16054
|
+
const carried = [...this.unreadRequests];
|
|
16055
|
+
const unreadContent = await Promise.all(carried.map(async (unread) => [
|
|
15858
16056
|
{ type: "input_text", text: unread.message },
|
|
15859
16057
|
...(await normalizeImages(unread.images ?? [])).map((image) => ({ type: "input_image", image_url: `data:${image.source.media_type};base64,${image.source.data}` }))
|
|
15860
16058
|
])).catch((error) => {
|
|
@@ -15873,7 +16071,7 @@ ${text.slice(-24e3)}`
|
|
|
15873
16071
|
threadId,
|
|
15874
16072
|
items: [{ type: "message", role: "user", content: unreadContent.flat() }]
|
|
15875
16073
|
});
|
|
15876
|
-
this.unreadRequests =
|
|
16074
|
+
this.unreadRequests = this.unreadRequests.filter((unread) => !carried.includes(unread));
|
|
15877
16075
|
}
|
|
15878
16076
|
const response = await host.client.request(
|
|
15879
16077
|
THREAD_GOAL_SET_METHOD,
|
|
@@ -15903,6 +16101,23 @@ ${text.slice(-24e3)}`
|
|
|
15903
16101
|
});
|
|
15904
16102
|
void disposed.catch(() => {
|
|
15905
16103
|
});
|
|
16104
|
+
let stopTimer;
|
|
16105
|
+
let rejectStopUnanswered = () => {
|
|
16106
|
+
};
|
|
16107
|
+
const stopUnanswered = new Promise((_resolve, reject) => {
|
|
16108
|
+
rejectStopUnanswered = reject;
|
|
16109
|
+
});
|
|
16110
|
+
void stopUnanswered.catch(() => {
|
|
16111
|
+
});
|
|
16112
|
+
const giveUpIfStopUnanswered = () => {
|
|
16113
|
+
clearTimeout(stopTimer);
|
|
16114
|
+
stopTimer = setTimeout(() => rejectStopUnanswered(new Error(
|
|
16115
|
+
`Codex did not stop this turn within ${CODEX_INTERRUPT_TIMEOUT_MS / 1e3} seconds of Stop, so it was ended here. Send a message to continue.`
|
|
16116
|
+
)), CODEX_INTERRUPT_TIMEOUT_MS);
|
|
16117
|
+
};
|
|
16118
|
+
if (signal.aborted) giveUpIfStopUnanswered();
|
|
16119
|
+
else signal.addEventListener("abort", giveUpIfStopUnanswered, { once: true });
|
|
16120
|
+
this.stopGiveUp = { hold: () => clearTimeout(stopTimer), arm: giveUpIfStopUnanswered };
|
|
15906
16121
|
let observedTurnId = null;
|
|
15907
16122
|
const observedTurnIds = /* @__PURE__ */ new Set();
|
|
15908
16123
|
let lastCompletedTurn = null;
|
|
@@ -16063,14 +16278,50 @@ ${text.slice(-24e3)}`
|
|
|
16063
16278
|
return;
|
|
16064
16279
|
}
|
|
16065
16280
|
const turnLabel = observedTurnId ? ` ${observedTurnId}` : "";
|
|
16066
|
-
rejectDisposed(new Error(`Codex
|
|
16281
|
+
rejectDisposed(new Error(`Codex turn${turnLabel} did not finish: ${reason.message}`));
|
|
16067
16282
|
};
|
|
16068
16283
|
host.client.on("notification", onNotification);
|
|
16069
16284
|
host.client.on("serverRequest", onServerRequest);
|
|
16070
16285
|
host.client.on("dispose", onDispose);
|
|
16071
16286
|
this.onGoalChanged = resolveIfGoalIdle;
|
|
16072
16287
|
try {
|
|
16073
|
-
const
|
|
16288
|
+
const starting = startTurn();
|
|
16289
|
+
const started = await Promise.race([starting, stopUnanswered]).catch((error) => {
|
|
16290
|
+
const announced = Promise.withResolvers();
|
|
16291
|
+
const onLateTurn = (notification) => dispatchAspNotification(notification, {
|
|
16292
|
+
[TURN_STARTED_METHOD]: ({ params }) => {
|
|
16293
|
+
if (params.threadId === threadId) announced.resolve();
|
|
16294
|
+
}
|
|
16295
|
+
});
|
|
16296
|
+
host.client.on("notification", onLateTurn);
|
|
16297
|
+
const stopped = starting.then(async (late) => {
|
|
16298
|
+
await removeTempImageFiles(late.tempImagePaths);
|
|
16299
|
+
let turnId = late.turn?.id;
|
|
16300
|
+
if (!late.turn && this.currentGoal?.status === "active") {
|
|
16301
|
+
await host.client.request(THREAD_GOAL_SET_METHOD, { threadId, status: "paused" }, { timeoutMs: CODEX_INTERRUPT_TIMEOUT_MS }).then((response) => this.recordGoalChange(response.goal, true)).catch(() => {
|
|
16302
|
+
});
|
|
16303
|
+
const { thread } = await host.client.request(THREAD_READ_METHOD, { threadId, includeTurns: true }, { timeoutMs: CODEX_INTERRUPT_TIMEOUT_MS });
|
|
16304
|
+
turnId = thread.turns.findLast((turn2) => turn2.status === "inProgress")?.id;
|
|
16305
|
+
}
|
|
16306
|
+
if (turnId) {
|
|
16307
|
+
const waited = new AbortController();
|
|
16308
|
+
await Promise.race([announced.promise, sleep(CODEX_INTERRUPT_TIMEOUT_MS, void 0, { signal: waited.signal }).catch(() => {
|
|
16309
|
+
})]);
|
|
16310
|
+
waited.abort();
|
|
16311
|
+
await host.client.request(
|
|
16312
|
+
TURN_INTERRUPT_METHOD,
|
|
16313
|
+
{ threadId, turnId },
|
|
16314
|
+
{ timeoutMs: CODEX_INTERRUPT_TIMEOUT_MS }
|
|
16315
|
+
);
|
|
16316
|
+
}
|
|
16317
|
+
}).catch(() => {
|
|
16318
|
+
}).finally(() => host.client.off("notification", onLateTurn));
|
|
16319
|
+
this.lateStart = stopped;
|
|
16320
|
+
void stopped.then(() => {
|
|
16321
|
+
if (this.lateStart === stopped) this.lateStart = null;
|
|
16322
|
+
});
|
|
16323
|
+
throw error;
|
|
16324
|
+
});
|
|
16074
16325
|
tempImagePaths = started.tempImagePaths;
|
|
16075
16326
|
if (started.turn && !observedTurnIds.has(started.turn.id)) {
|
|
16076
16327
|
observedTurnId = started.turn.id;
|
|
@@ -16081,13 +16332,16 @@ ${text.slice(-24e3)}`
|
|
|
16081
16332
|
this.startTurn(started.turn);
|
|
16082
16333
|
interruptIfStopped();
|
|
16083
16334
|
}
|
|
16084
|
-
const turn = await Promise.race([completed, disposed]);
|
|
16335
|
+
const turn = await Promise.race([completed, disposed, stopUnanswered]);
|
|
16085
16336
|
linearForwarder.flushThoughtAsResponse();
|
|
16086
16337
|
return turn;
|
|
16087
16338
|
} finally {
|
|
16088
16339
|
host.client.off("notification", onNotification);
|
|
16089
16340
|
host.client.off("serverRequest", onServerRequest);
|
|
16090
16341
|
host.client.off("dispose", onDispose);
|
|
16342
|
+
clearTimeout(stopTimer);
|
|
16343
|
+
signal.removeEventListener("abort", giveUpIfStopUnanswered);
|
|
16344
|
+
this.stopGiveUp = null;
|
|
16091
16345
|
this.onGoalChanged = null;
|
|
16092
16346
|
this.itemUpdateCoalescer.flushPending();
|
|
16093
16347
|
await removeTempImageFiles(tempImagePaths);
|
|
@@ -16991,6 +17245,7 @@ var CursorManager = class extends CodingAgentManager {
|
|
|
16991
17245
|
abortActiveTurn = null;
|
|
16992
17246
|
reconnectNoticeVisible = false;
|
|
16993
17247
|
instructionsDelivered = false;
|
|
17248
|
+
agentRequest = null;
|
|
16994
17249
|
resumeSessionId = null;
|
|
16995
17250
|
slashCommandsCache = null;
|
|
16996
17251
|
slashCommandsRequest = null;
|
|
@@ -17098,7 +17353,13 @@ var CursorManager = class extends CodingAgentManager {
|
|
|
17098
17353
|
})();
|
|
17099
17354
|
return this.slashCommandsRequest;
|
|
17100
17355
|
}
|
|
17101
|
-
|
|
17356
|
+
// A stopped turn leaves its agent starting, so the next turn waits for that one instead of starting a second thread.
|
|
17357
|
+
ensureAgent(request) {
|
|
17358
|
+
return this.agentRequest ??= this.startAgent(request).finally(() => {
|
|
17359
|
+
this.agentRequest = null;
|
|
17360
|
+
});
|
|
17361
|
+
}
|
|
17362
|
+
async startAgent(request) {
|
|
17102
17363
|
if (this.agent) return this.agent;
|
|
17103
17364
|
const apiKey = ENGINE_ENV.CURSOR_API_KEY;
|
|
17104
17365
|
if (!apiKey) {
|
|
@@ -17120,7 +17381,7 @@ var CursorManager = class extends CodingAgentManager {
|
|
|
17120
17381
|
if (resumeId) await this.onSaveSessionId(this.agent.agentId);
|
|
17121
17382
|
return this.agent;
|
|
17122
17383
|
}
|
|
17123
|
-
async processMessageInternal(request) {
|
|
17384
|
+
async processMessageInternal(request, signal) {
|
|
17124
17385
|
let run = null;
|
|
17125
17386
|
let agent = null;
|
|
17126
17387
|
let sawCursorActivity = false;
|
|
@@ -17151,9 +17412,12 @@ var CursorManager = class extends CodingAgentManager {
|
|
|
17151
17412
|
this.setReconnectNoticeVisible(true);
|
|
17152
17413
|
}
|
|
17153
17414
|
}, CURSOR_RECONNECT_NOTICE_DELAY_MS);
|
|
17154
|
-
|
|
17155
|
-
|
|
17156
|
-
|
|
17415
|
+
const ensured = await Promise.race([this.ensureAgent(request), aborted]);
|
|
17416
|
+
if (ensured === TURN_ABORTED) return;
|
|
17417
|
+
agent = ensured;
|
|
17418
|
+
if (!this.deliver(signal)) return;
|
|
17419
|
+
this.recordUserMessageHistoryEvent(request, {}, this.turnBeganAt);
|
|
17420
|
+
const sending = sendCursorRun(agent, message, {
|
|
17157
17421
|
model: { id: model },
|
|
17158
17422
|
mode: request.planMode ? "plan" : "agent",
|
|
17159
17423
|
onDelta: (args) => {
|
|
@@ -17161,6 +17425,13 @@ var CursorManager = class extends CodingAgentManager {
|
|
|
17161
17425
|
this.recordCursorContextUsage(args.update);
|
|
17162
17426
|
}
|
|
17163
17427
|
}, this.workingDirectory);
|
|
17428
|
+
const sent = await Promise.race([sending, aborted]);
|
|
17429
|
+
if (sent === TURN_ABORTED) {
|
|
17430
|
+
void sending.then((late) => this.cancelRun(late), () => {
|
|
17431
|
+
});
|
|
17432
|
+
return;
|
|
17433
|
+
}
|
|
17434
|
+
run = sent;
|
|
17164
17435
|
this.activeRun = run;
|
|
17165
17436
|
void this.deliverEarlySteers();
|
|
17166
17437
|
const events = run.stream()[Symbol.asyncIterator]();
|
|
@@ -17366,6 +17637,7 @@ ${instructions}
|
|
|
17366
17637
|
// src/managers/muse-manager.ts
|
|
17367
17638
|
var MuseQuotaError = class extends Error {
|
|
17368
17639
|
};
|
|
17640
|
+
var MUSE_INTERRUPT_TIMEOUT_MS = 5e3;
|
|
17369
17641
|
function isPendingQuestion(value) {
|
|
17370
17642
|
return isRecord(value) && typeof value.id === "string";
|
|
17371
17643
|
}
|
|
@@ -17406,7 +17678,7 @@ var MuseManager = class extends CodingAgentManager {
|
|
|
17406
17678
|
child.on("error", (error) => this.handleProcessExit(child, error));
|
|
17407
17679
|
child.on("exit", (code, signal) => this.handleProcessExit(
|
|
17408
17680
|
child,
|
|
17409
|
-
new Error(`Muse
|
|
17681
|
+
new Error(`The Muse process exited (${signal ?? `code ${code}`}) before the turn finished`)
|
|
17410
17682
|
));
|
|
17411
17683
|
await initializeMuse(client, "replicas", 0);
|
|
17412
17684
|
if (this.sessionId) {
|
|
@@ -17416,7 +17688,8 @@ var MuseManager = class extends CodingAgentManager {
|
|
|
17416
17688
|
sessionId: this.sessionId,
|
|
17417
17689
|
excludeItems: true
|
|
17418
17690
|
});
|
|
17419
|
-
} catch {
|
|
17691
|
+
} catch (error) {
|
|
17692
|
+
if (this.client !== client) throw error;
|
|
17420
17693
|
this.sessionId = null;
|
|
17421
17694
|
}
|
|
17422
17695
|
if (this.sessionId) await this.refreshPendingApprovals();
|
|
@@ -17427,9 +17700,9 @@ var MuseManager = class extends CodingAgentManager {
|
|
|
17427
17700
|
await this.onSaveSessionId(sessionId);
|
|
17428
17701
|
}
|
|
17429
17702
|
}
|
|
17430
|
-
request(method, params) {
|
|
17703
|
+
request(method, params, timeoutMs = 0) {
|
|
17431
17704
|
if (!this.client) return Promise.reject(new Error("Muse MSP is not running."));
|
|
17432
|
-
return this.client.request(method, params, { timeoutMs
|
|
17705
|
+
return this.client.request(method, params, { timeoutMs });
|
|
17433
17706
|
}
|
|
17434
17707
|
async refreshPendingApprovals() {
|
|
17435
17708
|
if (!this.sessionId) return;
|
|
@@ -17517,7 +17790,7 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
|
|
|
17517
17790
|
this.client = null;
|
|
17518
17791
|
for (const approvalId of this.pendingApprovals.keys()) this.resolveApproval(approvalId, "aborted");
|
|
17519
17792
|
this.resolvedApprovals.clear();
|
|
17520
|
-
if (this.turnComplete && !hadPendingRequest) {
|
|
17793
|
+
if ((this.turnComplete || this.compactionComplete) && !hadPendingRequest) {
|
|
17521
17794
|
this.recordHistoryEvent("muse-error", { message: error.message });
|
|
17522
17795
|
}
|
|
17523
17796
|
this.turnComplete?.resolve();
|
|
@@ -17525,14 +17798,18 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
|
|
|
17525
17798
|
this.compactionComplete?.resolve();
|
|
17526
17799
|
this.compactionComplete = null;
|
|
17527
17800
|
}
|
|
17528
|
-
stopProcess() {
|
|
17801
|
+
stopProcess(signal = "SIGTERM") {
|
|
17529
17802
|
const process10 = this.process;
|
|
17530
17803
|
this.process = null;
|
|
17531
17804
|
this.client?.dispose();
|
|
17532
17805
|
this.client = null;
|
|
17533
17806
|
for (const approvalId of this.pendingApprovals.keys()) this.resolveApproval(approvalId, "aborted");
|
|
17534
17807
|
this.resolvedApprovals.clear();
|
|
17535
|
-
|
|
17808
|
+
this.turnComplete?.resolve();
|
|
17809
|
+
this.turnComplete = null;
|
|
17810
|
+
this.compactionComplete?.resolve();
|
|
17811
|
+
this.compactionComplete = null;
|
|
17812
|
+
process10?.kill(signal);
|
|
17536
17813
|
}
|
|
17537
17814
|
createTurnInput(text, images) {
|
|
17538
17815
|
const input = [{ type: "text", text }];
|
|
@@ -17606,18 +17883,32 @@ ${typeof pending.subject.command === "string" ? pending.subject.command : JSON.s
|
|
|
17606
17883
|
}
|
|
17607
17884
|
async processMessageInternal(request, signal) {
|
|
17608
17885
|
let userMessageRecorded = false;
|
|
17886
|
+
let stopTimer;
|
|
17887
|
+
const endIfStopUnanswered = () => {
|
|
17888
|
+
stopTimer = setTimeout(() => {
|
|
17889
|
+
if (userMessageRecorded) {
|
|
17890
|
+
this.recordHistoryEvent("muse-error", {
|
|
17891
|
+
message: `Muse did not stop this turn within ${MUSE_INTERRUPT_TIMEOUT_MS / 1e3} seconds of Stop, so its process was ended. Send a message to continue.`
|
|
17892
|
+
});
|
|
17893
|
+
}
|
|
17894
|
+
this.stopProcess("SIGKILL");
|
|
17895
|
+
}, MUSE_INTERRUPT_TIMEOUT_MS);
|
|
17896
|
+
};
|
|
17897
|
+
if (signal.aborted) endIfStopUnanswered();
|
|
17898
|
+
else signal.addEventListener("abort", endIfStopUnanswered, { once: true });
|
|
17609
17899
|
const dispatch = async () => {
|
|
17610
17900
|
const model = request.model ?? DEFAULT_MUSE_MODEL;
|
|
17611
17901
|
await this.start(model);
|
|
17612
17902
|
if (!this.sessionId) throw new Error("Muse MSP failed to initialize.");
|
|
17613
|
-
|
|
17614
|
-
|
|
17615
|
-
|
|
17616
|
-
/^\/compact$/i.test(request.message.trim()) ? { command: "compact" } : {}
|
|
17617
|
-
);
|
|
17903
|
+
const compact = /^\/compact$/i.test(request.message.trim());
|
|
17904
|
+
const recordUserMessage = () => {
|
|
17905
|
+
if (userMessageRecorded) return;
|
|
17618
17906
|
userMessageRecorded = true;
|
|
17619
|
-
|
|
17620
|
-
|
|
17907
|
+
this.recordUserMessageHistoryEvent(request, compact ? { command: "compact" } : {}, this.turnBeganAt);
|
|
17908
|
+
};
|
|
17909
|
+
if (compact) {
|
|
17910
|
+
if (!this.deliver(signal)) return;
|
|
17911
|
+
recordUserMessage();
|
|
17621
17912
|
const completed2 = new Promise((resolve9) => {
|
|
17622
17913
|
this.compactionComplete = { resolve: resolve9 };
|
|
17623
17914
|
});
|
|
@@ -17649,7 +17940,8 @@ ${pending}
|
|
|
17649
17940
|
</workspace-instructions>
|
|
17650
17941
|
|
|
17651
17942
|
` : ""}${request.planMode ? "Plan the requested work without modifying files or running mutating commands.\n\n" : ""}${request.message}`;
|
|
17652
|
-
if (signal
|
|
17943
|
+
if (!this.deliver(signal)) return;
|
|
17944
|
+
recordUserMessage();
|
|
17653
17945
|
this.turnError = null;
|
|
17654
17946
|
const completed = new Promise((resolve9) => {
|
|
17655
17947
|
this.turnComplete = { resolve: resolve9 };
|
|
@@ -17686,9 +17978,12 @@ ${pending}
|
|
|
17686
17978
|
}
|
|
17687
17979
|
return;
|
|
17688
17980
|
}
|
|
17981
|
+
if (signal.aborted) return;
|
|
17689
17982
|
this.recordHistoryEvent("muse-error", { message: error instanceof Error ? error.message : String(error) });
|
|
17690
17983
|
throw error;
|
|
17691
17984
|
} finally {
|
|
17985
|
+
clearTimeout(stopTimer);
|
|
17986
|
+
signal.removeEventListener("abort", endIfStopUnanswered);
|
|
17692
17987
|
this.turnComplete?.resolve();
|
|
17693
17988
|
this.turnComplete = null;
|
|
17694
17989
|
this.activeTurnId = null;
|
|
@@ -17710,6 +18005,8 @@ ${pending}
|
|
|
17710
18005
|
commandId: uuidV7(),
|
|
17711
18006
|
sessionId: this.sessionId,
|
|
17712
18007
|
turnId: this.activeTurnId
|
|
18008
|
+
}, MUSE_INTERRUPT_TIMEOUT_MS).catch((error) => {
|
|
18009
|
+
console.error("[MuseManager] Failed to interrupt the turn:", error);
|
|
17713
18010
|
});
|
|
17714
18011
|
}
|
|
17715
18012
|
async respondToToolInput(requestId, selectionId) {
|
|
@@ -17853,6 +18150,9 @@ var OPENCODE_LEGACY_COMMAND_PROTECTION_PLUGIN_PATH = join15(ENGINE_ENV.HOME_DIR,
|
|
|
17853
18150
|
var OPENCODE_CONFIG_PATH = join15(ENGINE_ENV.HOME_DIR, ".config", "opencode", "opencode.json");
|
|
17854
18151
|
var OPENCODE_SERVER_STARTUP_TIMEOUT_MS = 3e4;
|
|
17855
18152
|
var OPENCODE_SLASH_COMMANDS_CACHE_MS = 3e4;
|
|
18153
|
+
var OPENCODE_HEARTBEAT_TIMEOUT_MS = 6e4;
|
|
18154
|
+
var OPENCODE_ABORT_TIMEOUT_MS = 5e3;
|
|
18155
|
+
var OPENCODE_SERVER_GONE = "exited or dropped its connection";
|
|
17856
18156
|
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.";
|
|
17857
18157
|
async function getDefaultOpencodeModel(provider) {
|
|
17858
18158
|
const ollama = readOllamaAuthEnv("opencode", process.env);
|
|
@@ -17984,6 +18284,8 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
17984
18284
|
dispatcher = null;
|
|
17985
18285
|
sessionId = null;
|
|
17986
18286
|
activeAbortController = null;
|
|
18287
|
+
// A stopped turn ends here before OpenCode has answered the stop, so the next turn waits for that: its server may be about to be replaced.
|
|
18288
|
+
stopping = Promise.resolve();
|
|
17987
18289
|
configuredModels = /* @__PURE__ */ new Set();
|
|
17988
18290
|
clientUpdate = Promise.resolve();
|
|
17989
18291
|
providerId = "openrouter";
|
|
@@ -18011,12 +18313,13 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18011
18313
|
this.sessionId = options.initialSessionId;
|
|
18012
18314
|
this.initializeManager(this.processMessageInternal.bind(this));
|
|
18013
18315
|
}
|
|
18014
|
-
|
|
18015
|
-
|
|
18016
|
-
|
|
18017
|
-
} catch (error) {
|
|
18316
|
+
interruptActiveTurn() {
|
|
18317
|
+
const server3 = this.server;
|
|
18318
|
+
this.stopping = this.abortActiveTurn().catch((error) => {
|
|
18018
18319
|
console.error("[OpencodeManager] Failed to abort Opencode session:", error);
|
|
18019
|
-
|
|
18320
|
+
if (this.server === server3) this.stopServer();
|
|
18321
|
+
});
|
|
18322
|
+
return this.stopping;
|
|
18020
18323
|
}
|
|
18021
18324
|
async abortActiveTurn() {
|
|
18022
18325
|
this.activeAbortController?.abort();
|
|
@@ -18025,7 +18328,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18025
18328
|
try {
|
|
18026
18329
|
await this.client.session.abort(
|
|
18027
18330
|
{ sessionID: this.sessionId, directory: this.workingDirectory },
|
|
18028
|
-
{ throwOnError: true }
|
|
18331
|
+
{ throwOnError: true, signal: AbortSignal.timeout(OPENCODE_ABORT_TIMEOUT_MS) }
|
|
18029
18332
|
);
|
|
18030
18333
|
} finally {
|
|
18031
18334
|
this.stopsInFlight -= 1;
|
|
@@ -18100,8 +18403,6 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18100
18403
|
const subagentMcpParentChatId = this.subagentMcpParentChatId();
|
|
18101
18404
|
if (this.client && (this.providerId !== providerId || this.serverSubagentMcpParentChatId !== subagentMcpParentChatId || this.serverCredential !== ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.opencode)) {
|
|
18102
18405
|
this.stopServer();
|
|
18103
|
-
this.client = null;
|
|
18104
|
-
this.configuredModels.clear();
|
|
18105
18406
|
}
|
|
18106
18407
|
this.providerId = providerId;
|
|
18107
18408
|
const configuredModel = providerId === OPENCODE_GO_PROVIDER ? getOpenCodeGoModel(model) : model;
|
|
@@ -18176,12 +18477,13 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18176
18477
|
this.eventSubscriptionReady = new Promise((resolve9) => {
|
|
18177
18478
|
this.resolveEventSubscriptionReady = resolve9;
|
|
18178
18479
|
});
|
|
18179
|
-
this.subscribeToEvents(client, eventController
|
|
18480
|
+
void this.subscribeToEvents(client, eventController, () => {
|
|
18481
|
+
this.loseServer(server3, `stopped responding (no heartbeat for ${OPENCODE_HEARTBEAT_TIMEOUT_MS / 1e3} seconds)`);
|
|
18482
|
+
}).catch((error) => {
|
|
18180
18483
|
this.resolveEventSubscriptionReady?.();
|
|
18181
18484
|
this.resolveEventSubscriptionReady = null;
|
|
18182
18485
|
console.error("[OpencodeManager] Event subscription failed:", error);
|
|
18183
|
-
|
|
18184
|
-
});
|
|
18486
|
+
}).then(() => this.loseServer(server3, OPENCODE_SERVER_GONE));
|
|
18185
18487
|
await Promise.race([
|
|
18186
18488
|
this.eventSubscriptionReady,
|
|
18187
18489
|
new Promise((resolve9) => setTimeout(resolve9, 2e3))
|
|
@@ -18197,6 +18499,19 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18197
18499
|
void this.dispatcher?.destroy();
|
|
18198
18500
|
this.server = null;
|
|
18199
18501
|
this.dispatcher = null;
|
|
18502
|
+
this.client = null;
|
|
18503
|
+
this.configuredModels.clear();
|
|
18504
|
+
}
|
|
18505
|
+
// Sessions persist on disk, so the next turn resumes this one on a fresh server.
|
|
18506
|
+
loseServer(server3, reason) {
|
|
18507
|
+
if (!server3 || this.server !== server3) return;
|
|
18508
|
+
this.stopServer();
|
|
18509
|
+
const turn = this.activeAbortController;
|
|
18510
|
+
if (!turn || turn.signal.aborted) return;
|
|
18511
|
+
this.recordHistoryEvent("opencode-error", {
|
|
18512
|
+
message: `The OpenCode server ${reason}, so this turn ended. Send a message to continue.`
|
|
18513
|
+
});
|
|
18514
|
+
turn.abort();
|
|
18200
18515
|
}
|
|
18201
18516
|
async ensureSession(client, providerID, model, agent, variant) {
|
|
18202
18517
|
if (this.sessionId) {
|
|
@@ -18258,17 +18573,23 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18258
18573
|
this.handledAccountRateLimit = false;
|
|
18259
18574
|
this.activeAbortController = controller;
|
|
18260
18575
|
if (signal.aborted) controller.abort();
|
|
18576
|
+
let server3 = null;
|
|
18261
18577
|
try {
|
|
18578
|
+
await this.stopping;
|
|
18262
18579
|
controller.signal.throwIfAborted();
|
|
18263
18580
|
const provider = await getOpencodeProvider();
|
|
18264
18581
|
const model = request.model ?? await getDefaultOpencodeModel(provider);
|
|
18265
18582
|
const client = await this.ensureClient(model, provider);
|
|
18583
|
+
server3 = this.server;
|
|
18266
18584
|
const { providerID, modelID } = opencodeModelRef(this.providerId, model);
|
|
18267
18585
|
const agent = request.planMode ? "plan" : "build";
|
|
18268
18586
|
const variant = await this.getThinkingVariant(client, providerID, modelID, request.thinkingLevel);
|
|
18269
18587
|
const sessionId = await this.ensureSession(client, providerID, modelID, agent, variant);
|
|
18270
18588
|
const system = this.buildCombinedInstructions(request.customInstructions);
|
|
18271
|
-
if (!retry)
|
|
18589
|
+
if (!retry) {
|
|
18590
|
+
if (!this.deliver(signal)) return false;
|
|
18591
|
+
this.recordUserMessageHistoryEvent(request, {}, this.turnBeganAt);
|
|
18592
|
+
}
|
|
18272
18593
|
const result = await client.session.prompt({
|
|
18273
18594
|
sessionID: sessionId,
|
|
18274
18595
|
directory: this.workingDirectory,
|
|
@@ -18295,6 +18616,7 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18295
18616
|
});
|
|
18296
18617
|
if (!signal.aborted) return true;
|
|
18297
18618
|
}
|
|
18619
|
+
if (error instanceof TypeError) this.loseServer(server3, OPENCODE_SERVER_GONE);
|
|
18298
18620
|
if (controller.signal.aborted) {
|
|
18299
18621
|
this.recordHistoryEvent("opencode-session.idle", { sessionID: this.sessionId });
|
|
18300
18622
|
} else {
|
|
@@ -18306,24 +18628,30 @@ var OpencodeManager = class extends CodingAgentManager {
|
|
|
18306
18628
|
}
|
|
18307
18629
|
return false;
|
|
18308
18630
|
}
|
|
18309
|
-
async subscribeToEvents(client, controller) {
|
|
18631
|
+
async subscribeToEvents(client, controller, onSilent) {
|
|
18310
18632
|
let streamError;
|
|
18311
|
-
const
|
|
18312
|
-
|
|
18313
|
-
|
|
18314
|
-
|
|
18315
|
-
|
|
18316
|
-
|
|
18317
|
-
|
|
18633
|
+
const silence = setTimeout(onSilent, OPENCODE_HEARTBEAT_TIMEOUT_MS);
|
|
18634
|
+
try {
|
|
18635
|
+
const result = await client.event.subscribe(
|
|
18636
|
+
{ directory: this.workingDirectory },
|
|
18637
|
+
{
|
|
18638
|
+
signal: controller.signal,
|
|
18639
|
+
sseMaxRetryAttempts: 1,
|
|
18640
|
+
onSseError: (error) => {
|
|
18641
|
+
streamError = error;
|
|
18642
|
+
}
|
|
18643
|
+
}
|
|
18644
|
+
);
|
|
18645
|
+
for await (const event of result.stream) {
|
|
18646
|
+
silence.refresh();
|
|
18647
|
+
this.resolveEventSubscriptionReady?.();
|
|
18648
|
+
this.resolveEventSubscriptionReady = null;
|
|
18649
|
+
if (isOpencodeRuntimeEvent(event)) {
|
|
18650
|
+
this.recordOpencodeEvent(event);
|
|
18318
18651
|
}
|
|
18319
18652
|
}
|
|
18320
|
-
|
|
18321
|
-
|
|
18322
|
-
this.resolveEventSubscriptionReady?.();
|
|
18323
|
-
this.resolveEventSubscriptionReady = null;
|
|
18324
|
-
if (isOpencodeRuntimeEvent(event)) {
|
|
18325
|
-
this.recordOpencodeEvent(event);
|
|
18326
|
-
}
|
|
18653
|
+
} finally {
|
|
18654
|
+
clearTimeout(silence);
|
|
18327
18655
|
}
|
|
18328
18656
|
this.resolveEventSubscriptionReady?.();
|
|
18329
18657
|
this.resolveEventSubscriptionReady = null;
|
|
@@ -59616,21 +59944,18 @@ var PiManager = class extends CodingAgentManager {
|
|
|
59616
59944
|
}
|
|
59617
59945
|
recordUserMessage(session, request) {
|
|
59618
59946
|
const skillName = explicitSkillName(session, request.message);
|
|
59619
|
-
this.recordUserMessageHistoryEvent(
|
|
59620
|
-
request,
|
|
59621
|
-
skillName ? { skillName } : {}
|
|
59622
|
-
);
|
|
59947
|
+
this.recordUserMessageHistoryEvent(request, skillName ? { skillName } : {}, this.turnBeganAt);
|
|
59623
59948
|
}
|
|
59624
59949
|
async processMessageInternal(request, signal) {
|
|
59625
59950
|
try {
|
|
59626
59951
|
const session = await this.ensureSession(request);
|
|
59627
|
-
this.recordUserMessage(session, request);
|
|
59628
59952
|
const images = request.images && request.images.length > 0 ? (await normalizeImages(request.images)).map((image) => ({
|
|
59629
59953
|
type: "image",
|
|
59630
59954
|
data: image.source.data,
|
|
59631
59955
|
mimeType: image.source.media_type
|
|
59632
59956
|
})) : void 0;
|
|
59633
|
-
if (signal
|
|
59957
|
+
if (!this.deliver(signal)) return;
|
|
59958
|
+
this.recordUserMessage(session, request);
|
|
59634
59959
|
await session.prompt(request.message, images ? { images } : void 0);
|
|
59635
59960
|
} catch (error) {
|
|
59636
59961
|
this.recordHistoryEvent("pi-error", { message: error instanceof Error ? error.message : String(error) });
|
|
@@ -60640,6 +60965,7 @@ var AgentTokenUsageTracker = class {
|
|
|
60640
60965
|
|
|
60641
60966
|
// src/services/chat/chat-service.ts
|
|
60642
60967
|
import { totalmem } from "os";
|
|
60968
|
+
import { setTimeout as sleep3 } from "timers/promises";
|
|
60643
60969
|
|
|
60644
60970
|
// src/services/keep-alive-service.ts
|
|
60645
60971
|
var KeepAliveService = class _KeepAliveService {
|
|
@@ -61506,6 +61832,7 @@ var toolInputRequestSchema = z4.object({
|
|
|
61506
61832
|
});
|
|
61507
61833
|
var toolInputResolvedSchema = z4.object({ requestId: z4.string() });
|
|
61508
61834
|
var SUBAGENT_POLL_INTERVAL_MS = 2e3;
|
|
61835
|
+
var STOP_ARRIVAL_WAIT_MS = 3e3;
|
|
61509
61836
|
var CHAT_IDLE_RELEASE_MS = 15 * 6e4;
|
|
61510
61837
|
var CHILD_CHAT_IDLE_RELEASE_MS = 2 * 6e4;
|
|
61511
61838
|
var LIVE_AGENT_PROCESS_MB = 300;
|
|
@@ -62008,13 +62335,20 @@ var ChatService = class {
|
|
|
62008
62335
|
request = sameHarnessRequest;
|
|
62009
62336
|
const nameFromMessage = !chat.persisted.displayName && !chat.persisted.fork && !chat.persisted.parentChatId && getChatKind(chat.persisted) === "standard" && hasGeneratedChatTitle(chat.persisted) && !hasChatStarted(this.toSummary(chat));
|
|
62010
62337
|
const previousAcceptance = chat.lastSendAcceptance;
|
|
62338
|
+
const previousArrival = chat.lastSendArrival;
|
|
62339
|
+
const arriving = Promise.withResolvers();
|
|
62340
|
+
const arrived = () => {
|
|
62341
|
+
arriving.resolve();
|
|
62342
|
+
chat.arrivingSends.delete(arriving.promise);
|
|
62343
|
+
};
|
|
62344
|
+
chat.arrivingSends.add(arriving.promise);
|
|
62345
|
+
chat.lastSendArrival = arriving.promise;
|
|
62011
62346
|
const accepting = (async () => {
|
|
62012
62347
|
chat.acceptingMessages += 1;
|
|
62013
62348
|
let seenBeforeSend;
|
|
62014
62349
|
let unsaidBeforeSend;
|
|
62015
62350
|
try {
|
|
62016
|
-
await
|
|
62017
|
-
});
|
|
62351
|
+
await previousArrival;
|
|
62018
62352
|
await chat.release;
|
|
62019
62353
|
this.requireChat(chatId);
|
|
62020
62354
|
seenBeforeSend = this.forkSourceSeenBlocks.get(chatId);
|
|
@@ -62077,8 +62411,10 @@ ${decisions}` };
|
|
|
62077
62411
|
result,
|
|
62078
62412
|
typedMessage
|
|
62079
62413
|
))
|
|
62080
|
-
);
|
|
62414
|
+
).finally(arrived);
|
|
62081
62415
|
if (!steer || !response.queued) return response;
|
|
62416
|
+
await previousAcceptance?.catch(() => {
|
|
62417
|
+
});
|
|
62082
62418
|
const steered = await steerQueuedInOrder(steer === "alone" ? [{ id: response.messageId }] : chat.provider.getQueue(), response.messageId, async (id) => (await this.steerFromQueue(chatId, id)).success);
|
|
62083
62419
|
return { ...response, steered };
|
|
62084
62420
|
} finally {
|
|
@@ -62091,6 +62427,7 @@ ${decisions}` };
|
|
|
62091
62427
|
throw error;
|
|
62092
62428
|
} finally {
|
|
62093
62429
|
chat.acceptingMessages -= 1;
|
|
62430
|
+
arrived();
|
|
62094
62431
|
}
|
|
62095
62432
|
})();
|
|
62096
62433
|
chat.lastSendAcceptance = accepting;
|
|
@@ -62221,6 +62558,7 @@ ${decisions}` };
|
|
|
62221
62558
|
}
|
|
62222
62559
|
async interrupt(chatId, stoppedAt) {
|
|
62223
62560
|
const chat = this.requireChat(chatId);
|
|
62561
|
+
await Promise.race([Promise.all(chat.arrivingSends), sleep3(STOP_ARRIVAL_WAIT_MS, void 0, { ref: false })]);
|
|
62224
62562
|
const result = await this.stopTurn(chat, stoppedAt);
|
|
62225
62563
|
this.touch(chat);
|
|
62226
62564
|
await this.publish({
|
|
@@ -62458,7 +62796,9 @@ ${decisions}` };
|
|
|
62458
62796
|
async saveQueueOrder(chat) {
|
|
62459
62797
|
const order = new Map(chat.provider.getQueue().map(({ id }, index) => [id, index]));
|
|
62460
62798
|
const { state } = chat.commands;
|
|
62461
|
-
|
|
62799
|
+
if (chat.requeued && order.has(chat.requeued.id)) delete chat.requeued;
|
|
62800
|
+
const rank = (id) => order.get(id) ?? (id === chat.requeued?.id ? (order.get(chat.requeued.afterId) ?? -1) + 0.5 : -1);
|
|
62801
|
+
const queue = [...state.queue].sort((a, b) => rank(a.id) - rank(b.id));
|
|
62462
62802
|
if (queue.every((message, index) => message === state.queue[index])) return;
|
|
62463
62803
|
state.queue = queue;
|
|
62464
62804
|
await chat.commands.save();
|
|
@@ -62998,6 +63338,24 @@ ${note}`;
|
|
|
62998
63338
|
this.agentTokenUsageTracker.noteUsage(persisted.id, payload, occurredAt);
|
|
62999
63339
|
};
|
|
63000
63340
|
const onMessageStarted = (message) => this.handleTurnStarted(persisted.id, message);
|
|
63341
|
+
const onMessageRequeued = (message, afterMessageId) => {
|
|
63342
|
+
const chat = this.getRuntimeChat(persisted.id);
|
|
63343
|
+
const { state } = commands;
|
|
63344
|
+
if (!chat) return;
|
|
63345
|
+
chat.requeued = { id: message.id, afterId: afterMessageId };
|
|
63346
|
+
if (state.queue.some(({ id }) => id === message.id)) return;
|
|
63347
|
+
const errorNotificationTargets = chat.activeErrorNotificationTargets;
|
|
63348
|
+
state.queue.splice(state.queue.findIndex(({ id }) => id === afterMessageId) + 1, 0, {
|
|
63349
|
+
...message,
|
|
63350
|
+
...errorNotificationTargets.length > 0 ? { errorNotificationTargets } : {}
|
|
63351
|
+
});
|
|
63352
|
+
if (errorNotificationTargets.length > 0) chat.errorNotificationTargets.set(message.id, errorNotificationTargets);
|
|
63353
|
+
if (state.running?.id === message.id) delete state.running;
|
|
63354
|
+
chat.pendingMessageIds.splice(chat.pendingMessageIds.indexOf(afterMessageId) + 1, 0, message.id);
|
|
63355
|
+
commands.save().catch((error) => {
|
|
63356
|
+
console.error("[ChatService] Failed to save a message that runs again:", { chatId: persisted.id, error });
|
|
63357
|
+
});
|
|
63358
|
+
};
|
|
63001
63359
|
const onChatCredential = (credential) => {
|
|
63002
63360
|
if (JSON.stringify(persisted.chatCredential) === JSON.stringify(credential)) return;
|
|
63003
63361
|
persisted.chatCredential = credential;
|
|
@@ -63066,6 +63424,7 @@ ${note}`;
|
|
|
63066
63424
|
onEvent: onProviderEvent,
|
|
63067
63425
|
onProcessingChanged,
|
|
63068
63426
|
onMessageStarted,
|
|
63427
|
+
onMessageRequeued,
|
|
63069
63428
|
onQueueChanged,
|
|
63070
63429
|
onUsageUpdate: onProviderUsage,
|
|
63071
63430
|
fallbackContext,
|
|
@@ -63116,6 +63475,7 @@ ${note}`;
|
|
|
63116
63475
|
commands,
|
|
63117
63476
|
acceptingSendResponses: /* @__PURE__ */ new Map(),
|
|
63118
63477
|
acceptingMessages: 0,
|
|
63478
|
+
arrivingSends: /* @__PURE__ */ new Set(),
|
|
63119
63479
|
activeMessageId: null,
|
|
63120
63480
|
hasActiveTurn: false,
|
|
63121
63481
|
observedBranchesByRepo: /* @__PURE__ */ new Map(),
|
|
@@ -66615,7 +66975,7 @@ app.post(ENGINE_ACTIVATE_PATH, async (c) => {
|
|
|
66615
66975
|
const workspaceId = isRecord(body) && typeof body.workspaceId === "string" ? body.workspaceId : void 0;
|
|
66616
66976
|
return lifecycleResponse(c, await lifecycle.transition(() => activate(workspaceId === void 0 ? void 0 : { workspaceId })));
|
|
66617
66977
|
});
|
|
66618
|
-
app.post(ENGINE_SLEEP_PATH, async (c) => lifecycleResponse(c, await lifecycle.transition(
|
|
66978
|
+
app.post(ENGINE_SLEEP_PATH, async (c) => lifecycleResponse(c, await lifecycle.transition(sleep4)));
|
|
66619
66979
|
app.get("/status", async (c) => {
|
|
66620
66980
|
try {
|
|
66621
66981
|
const [repos, hasActiveSSHSessions, desktopReady] = await Promise.all([
|
|
@@ -66887,7 +67247,7 @@ async function startBackgroundServices(signal) {
|
|
|
66887
67247
|
}
|
|
66888
67248
|
if (!signal.aborted) startStatusBroadcaster();
|
|
66889
67249
|
}
|
|
66890
|
-
async function
|
|
67250
|
+
async function sleep4() {
|
|
66891
67251
|
if (lifecycle.state === "parked") {
|
|
66892
67252
|
return createErrorResult({ message: "A parked engine has no workspace to sleep", code: 409 });
|
|
66893
67253
|
}
|