@moxt-ai/cli 0.9.0-beta.3 → 0.9.1
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/index.cjs +2684 -294
- package/dist/index.cjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1628,16 +1628,16 @@ var require_command = __commonJS({
|
|
|
1628
1628
|
* @param {Function} listener
|
|
1629
1629
|
* @return {Command} `this` command for chaining
|
|
1630
1630
|
*/
|
|
1631
|
-
hook(
|
|
1631
|
+
hook(event2, listener) {
|
|
1632
1632
|
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1633
|
-
if (!allowedValues.includes(
|
|
1634
|
-
throw new Error(`Unexpected value for event passed to hook : '${
|
|
1633
|
+
if (!allowedValues.includes(event2)) {
|
|
1634
|
+
throw new Error(`Unexpected value for event passed to hook : '${event2}'.
|
|
1635
1635
|
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1636
1636
|
}
|
|
1637
|
-
if (this._lifeCycleHooks[
|
|
1638
|
-
this._lifeCycleHooks[
|
|
1637
|
+
if (this._lifeCycleHooks[event2]) {
|
|
1638
|
+
this._lifeCycleHooks[event2].push(listener);
|
|
1639
1639
|
} else {
|
|
1640
|
-
this._lifeCycleHooks[
|
|
1640
|
+
this._lifeCycleHooks[event2] = [listener];
|
|
1641
1641
|
}
|
|
1642
1642
|
return this;
|
|
1643
1643
|
}
|
|
@@ -2472,15 +2472,15 @@ Expecting one of '${allowedValues.join("', '")}'`);
|
|
|
2472
2472
|
* @return {(Promise|undefined)}
|
|
2473
2473
|
* @private
|
|
2474
2474
|
*/
|
|
2475
|
-
_chainOrCallHooks(promise,
|
|
2475
|
+
_chainOrCallHooks(promise, event2) {
|
|
2476
2476
|
let result = promise;
|
|
2477
2477
|
const hooks = [];
|
|
2478
|
-
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[
|
|
2479
|
-
hookedCommand._lifeCycleHooks[
|
|
2478
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event2] !== void 0).forEach((hookedCommand) => {
|
|
2479
|
+
hookedCommand._lifeCycleHooks[event2].forEach((callback) => {
|
|
2480
2480
|
hooks.push({ hookedCommand, callback });
|
|
2481
2481
|
});
|
|
2482
2482
|
});
|
|
2483
|
-
if (
|
|
2483
|
+
if (event2 === "postAction") {
|
|
2484
2484
|
hooks.reverse();
|
|
2485
2485
|
}
|
|
2486
2486
|
hooks.forEach((hookDetail) => {
|
|
@@ -2498,10 +2498,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
|
|
|
2498
2498
|
* @return {(Promise|undefined)}
|
|
2499
2499
|
* @private
|
|
2500
2500
|
*/
|
|
2501
|
-
_chainOrCallSubCommandHook(promise, subCommand,
|
|
2501
|
+
_chainOrCallSubCommandHook(promise, subCommand, event2) {
|
|
2502
2502
|
let result = promise;
|
|
2503
|
-
if (this._lifeCycleHooks[
|
|
2504
|
-
this._lifeCycleHooks[
|
|
2503
|
+
if (this._lifeCycleHooks[event2] !== void 0) {
|
|
2504
|
+
this._lifeCycleHooks[event2].forEach((hook) => {
|
|
2505
2505
|
result = this._chainOrCall(result, () => {
|
|
2506
2506
|
return hook(this, subCommand);
|
|
2507
2507
|
});
|
|
@@ -4243,7 +4243,7 @@ var init_contracts = __esm({
|
|
|
4243
4243
|
});
|
|
4244
4244
|
|
|
4245
4245
|
// ../machine-connector/dist/protocol/v1/enums.js
|
|
4246
|
-
var MachineOperatingSystem, MachineConnectionTargetKind, MachineConnectionStatus, MachinePairingStatus, MachinePairingDecision, MachineJobKind, MachineJobStatus, MachineJobWakeReason, MachineJobEventKind, MachineJobOutputStream, MachineControlCommandKind, MachineCodexPermissionMode, MachineClaudePermissionMode, MachineProtocolErrorCode;
|
|
4246
|
+
var MachineOperatingSystem, MachineConnectionTargetKind, MachineConnectionStatus, MachineConnectionPurpose, MachinePairingStatus, MachinePairingDecision, MachineJobKind, MachineJobStatus, MachineJobWakeReason, MachineJobEventKind, MachineJobOutputStream, MachineControlCommandKind, MachineCodexPermissionMode, MachineClaudePermissionMode, MachineProtocolErrorCode;
|
|
4247
4247
|
var init_enums = __esm({
|
|
4248
4248
|
"../machine-connector/dist/protocol/v1/enums.js"() {
|
|
4249
4249
|
"use strict";
|
|
@@ -4262,6 +4262,10 @@ var init_enums = __esm({
|
|
|
4262
4262
|
MachineConnectionStatus2["Offline"] = "offline";
|
|
4263
4263
|
MachineConnectionStatus2["Revoked"] = "revoked";
|
|
4264
4264
|
})(MachineConnectionStatus || (MachineConnectionStatus = {}));
|
|
4265
|
+
(function(MachineConnectionPurpose2) {
|
|
4266
|
+
MachineConnectionPurpose2[MachineConnectionPurpose2["AsTool"] = 1] = "AsTool";
|
|
4267
|
+
MachineConnectionPurpose2[MachineConnectionPurpose2["LocalCodexRuntime"] = 2] = "LocalCodexRuntime";
|
|
4268
|
+
})(MachineConnectionPurpose || (MachineConnectionPurpose = {}));
|
|
4265
4269
|
(function(MachinePairingStatus2) {
|
|
4266
4270
|
MachinePairingStatus2["Connected"] = "connected";
|
|
4267
4271
|
MachinePairingStatus2["Expired"] = "expired";
|
|
@@ -4403,8 +4407,8 @@ function assertContiguousJobEvents(events, acknowledgedSequence) {
|
|
|
4403
4407
|
}
|
|
4404
4408
|
const firstEvent = events[0];
|
|
4405
4409
|
let expectedSequence = acknowledgedSequence + 1;
|
|
4406
|
-
for (const
|
|
4407
|
-
if (
|
|
4410
|
+
for (const event2 of events) {
|
|
4411
|
+
if (event2.jobId !== firstEvent.jobId || event2.generation !== firstEvent.generation || event2.sequence !== expectedSequence) {
|
|
4408
4412
|
throwEventSequenceConflict(`Expected sequence ${expectedSequence} for Job ${firstEvent.jobId}`);
|
|
4409
4413
|
}
|
|
4410
4414
|
expectedSequence += 1;
|
|
@@ -4805,19 +4809,19 @@ async function executeClaude(workingDirectory, environment, argumentsList, promp
|
|
|
4805
4809
|
};
|
|
4806
4810
|
}
|
|
4807
4811
|
async function processClaudeLine(line, metadata, callbacks) {
|
|
4808
|
-
const
|
|
4809
|
-
if (
|
|
4812
|
+
const event2 = parseClaudeEvent(line).value;
|
|
4813
|
+
if (event2 === void 0) {
|
|
4810
4814
|
return;
|
|
4811
4815
|
}
|
|
4812
|
-
if (isRecord(
|
|
4813
|
-
if (typeof
|
|
4814
|
-
metadata.threadId =
|
|
4816
|
+
if (isRecord(event2)) {
|
|
4817
|
+
if (typeof event2.session_id === "string") {
|
|
4818
|
+
metadata.threadId = event2.session_id;
|
|
4815
4819
|
}
|
|
4816
|
-
if (
|
|
4817
|
-
metadata.finalMessage =
|
|
4820
|
+
if (event2.type === "result" && typeof event2.result === "string") {
|
|
4821
|
+
metadata.finalMessage = event2.result;
|
|
4818
4822
|
}
|
|
4819
4823
|
}
|
|
4820
|
-
await callbacks.onEvent(
|
|
4824
|
+
await callbacks.onEvent(event2);
|
|
4821
4825
|
}
|
|
4822
4826
|
function parseClaudeEvent(line) {
|
|
4823
4827
|
const trimmed = line.trim();
|
|
@@ -5003,16 +5007,16 @@ async function executeCodex(workingDirectory, outputPath, environment, arguments
|
|
|
5003
5007
|
const lines = bufferedStdout.split("\n");
|
|
5004
5008
|
bufferedStdout = lines.pop() ?? "";
|
|
5005
5009
|
for (const line of lines) {
|
|
5006
|
-
const
|
|
5007
|
-
if (
|
|
5010
|
+
const event2 = parseCodexEvent(line).value;
|
|
5011
|
+
if (event2 === void 0) {
|
|
5008
5012
|
continue;
|
|
5009
5013
|
}
|
|
5010
|
-
const eventThreadId = extractThreadId(
|
|
5014
|
+
const eventThreadId = extractThreadId(event2).value;
|
|
5011
5015
|
if (eventThreadId) {
|
|
5012
5016
|
executionMetadata.value = eventThreadId;
|
|
5013
5017
|
}
|
|
5014
|
-
turnCompletion.observe(
|
|
5015
|
-
await callbacks.onEvent(
|
|
5018
|
+
turnCompletion.observe(event2);
|
|
5019
|
+
await callbacks.onEvent(event2);
|
|
5016
5020
|
}
|
|
5017
5021
|
},
|
|
5018
5022
|
onSpawn: callbacks.onSpawn,
|
|
@@ -5023,14 +5027,14 @@ async function executeCodex(workingDirectory, outputPath, environment, arguments
|
|
|
5023
5027
|
};
|
|
5024
5028
|
const result = await executeProcess(process.env.MOXT_CODEX_PATH ?? "codex", argumentsList, workingDirectory, environment, prompt, 43200, processCallbacks);
|
|
5025
5029
|
if (bufferedStdout.trim().length > 0) {
|
|
5026
|
-
const
|
|
5027
|
-
if (
|
|
5028
|
-
const eventThreadId = extractThreadId(
|
|
5030
|
+
const event2 = parseCodexEvent(bufferedStdout).value;
|
|
5031
|
+
if (event2 !== void 0) {
|
|
5032
|
+
const eventThreadId = extractThreadId(event2).value;
|
|
5029
5033
|
if (eventThreadId) {
|
|
5030
5034
|
executionMetadata.value = eventThreadId;
|
|
5031
5035
|
}
|
|
5032
|
-
turnCompletion.observe(
|
|
5033
|
-
await callbacks.onEvent(
|
|
5036
|
+
turnCompletion.observe(event2);
|
|
5037
|
+
await callbacks.onEvent(event2);
|
|
5034
5038
|
}
|
|
5035
5039
|
}
|
|
5036
5040
|
const finalMessage = (await readOptionalOutput(outputPath)).value;
|
|
@@ -5063,25 +5067,25 @@ function createCodexTurnCompletion() {
|
|
|
5063
5067
|
});
|
|
5064
5068
|
};
|
|
5065
5069
|
return {
|
|
5066
|
-
observe: (
|
|
5067
|
-
if (!isRecord2(
|
|
5070
|
+
observe: (event2) => {
|
|
5071
|
+
if (!isRecord2(event2)) {
|
|
5068
5072
|
return;
|
|
5069
5073
|
}
|
|
5070
|
-
const item =
|
|
5074
|
+
const item = event2.item;
|
|
5071
5075
|
if (isRecord2(item) && item.type === "command_execution" && typeof item.id === "string") {
|
|
5072
|
-
if (
|
|
5076
|
+
if (event2.type === "item.completed") {
|
|
5073
5077
|
completedCommandIds.add(item.id);
|
|
5074
5078
|
activeCommandIds.delete(item.id);
|
|
5075
|
-
} else if (
|
|
5079
|
+
} else if (event2.type === "item.started" && !completedCommandIds.has(item.id)) {
|
|
5076
5080
|
activeCommandIds.add(item.id);
|
|
5077
5081
|
}
|
|
5078
5082
|
}
|
|
5079
|
-
if (terminal === void 0 &&
|
|
5083
|
+
if (terminal === void 0 && event2.type === "turn.completed") {
|
|
5080
5084
|
terminal = { status: MachineJobStatus.Succeeded };
|
|
5081
5085
|
}
|
|
5082
|
-
if (terminal === void 0 &&
|
|
5086
|
+
if (terminal === void 0 && event2.type === "turn.failed") {
|
|
5083
5087
|
terminal = {
|
|
5084
|
-
failureMessage: extractCodexFailureMessage(
|
|
5088
|
+
failureMessage: extractCodexFailureMessage(event2).value,
|
|
5085
5089
|
status: MachineJobStatus.Failed
|
|
5086
5090
|
};
|
|
5087
5091
|
}
|
|
@@ -5090,12 +5094,12 @@ function createCodexTurnCompletion() {
|
|
|
5090
5094
|
result
|
|
5091
5095
|
};
|
|
5092
5096
|
}
|
|
5093
|
-
function extractCodexFailureMessage(
|
|
5094
|
-
if (typeof
|
|
5095
|
-
return { value:
|
|
5097
|
+
function extractCodexFailureMessage(event2) {
|
|
5098
|
+
if (typeof event2.message === "string") {
|
|
5099
|
+
return { value: event2.message };
|
|
5096
5100
|
}
|
|
5097
|
-
if (isRecord2(
|
|
5098
|
-
return { value:
|
|
5101
|
+
if (isRecord2(event2.error) && typeof event2.error.message === "string") {
|
|
5102
|
+
return { value: event2.error.message };
|
|
5099
5103
|
}
|
|
5100
5104
|
return {};
|
|
5101
5105
|
}
|
|
@@ -5118,15 +5122,15 @@ function parseCodexEvent(line) {
|
|
|
5118
5122
|
};
|
|
5119
5123
|
}
|
|
5120
5124
|
}
|
|
5121
|
-
function extractThreadId(
|
|
5122
|
-
if (!isRecord2(
|
|
5125
|
+
function extractThreadId(event2) {
|
|
5126
|
+
if (!isRecord2(event2)) {
|
|
5123
5127
|
return {};
|
|
5124
5128
|
}
|
|
5125
|
-
const directThreadId =
|
|
5129
|
+
const directThreadId = event2.thread_id;
|
|
5126
5130
|
if (typeof directThreadId === "string") {
|
|
5127
5131
|
return { value: directThreadId };
|
|
5128
5132
|
}
|
|
5129
|
-
const thread =
|
|
5133
|
+
const thread = event2.thread;
|
|
5130
5134
|
if (isRecord2(thread) && typeof thread.id === "string") {
|
|
5131
5135
|
return { value: thread.id };
|
|
5132
5136
|
}
|
|
@@ -5290,10 +5294,10 @@ var init_durable_job = __esm({
|
|
|
5290
5294
|
});
|
|
5291
5295
|
}
|
|
5292
5296
|
pendingEvents(limit = 100) {
|
|
5293
|
-
return this.job.events.filter((
|
|
5297
|
+
return this.job.events.filter((event2) => event2.sequence > this.job.acknowledgedSequence).slice(0, limit);
|
|
5294
5298
|
}
|
|
5295
5299
|
addEvent(kind, payload, options) {
|
|
5296
|
-
const
|
|
5300
|
+
const event2 = {
|
|
5297
5301
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5298
5302
|
eventId: (0, import_node_crypto3.randomUUID)(),
|
|
5299
5303
|
generation: this.job.claim.generation,
|
|
@@ -5303,9 +5307,9 @@ var init_durable_job = __esm({
|
|
|
5303
5307
|
sequence: this.job.nextSequence
|
|
5304
5308
|
};
|
|
5305
5309
|
if (options.outputStream) {
|
|
5306
|
-
|
|
5310
|
+
event2.outputStream = options.outputStream;
|
|
5307
5311
|
}
|
|
5308
|
-
this.job.events.push(
|
|
5312
|
+
this.job.events.push(event2);
|
|
5309
5313
|
this.job.nextSequence += 1;
|
|
5310
5314
|
}
|
|
5311
5315
|
async update(operation) {
|
|
@@ -6678,7 +6682,7 @@ var init_version = __esm({
|
|
|
6678
6682
|
});
|
|
6679
6683
|
|
|
6680
6684
|
// ../machine-connector/dist/runtime/relay-client.js
|
|
6681
|
-
async function postJson(url, body, accessToken) {
|
|
6685
|
+
async function postJson(url, body, accessToken, externalSignal) {
|
|
6682
6686
|
const headers = {
|
|
6683
6687
|
"Content-Type": "application/json",
|
|
6684
6688
|
"User-Agent": `moxt-machine-connector/${connectorVersion}`
|
|
@@ -6690,7 +6694,7 @@ async function postJson(url, body, accessToken) {
|
|
|
6690
6694
|
body: JSON.stringify(body),
|
|
6691
6695
|
headers,
|
|
6692
6696
|
method: "POST",
|
|
6693
|
-
signal:
|
|
6697
|
+
signal: requestSignal(externalSignal)
|
|
6694
6698
|
});
|
|
6695
6699
|
const responseText = await response.text();
|
|
6696
6700
|
if (!response.ok) {
|
|
@@ -6701,24 +6705,49 @@ async function postJson(url, body, accessToken) {
|
|
|
6701
6705
|
}
|
|
6702
6706
|
return JSON.parse(responseText);
|
|
6703
6707
|
}
|
|
6704
|
-
function
|
|
6708
|
+
async function getJson(url, accessToken, extraHeaders, externalSignal) {
|
|
6709
|
+
const response = await fetch(url, {
|
|
6710
|
+
headers: {
|
|
6711
|
+
...extraHeaders,
|
|
6712
|
+
Authorization: `Bearer ${accessToken}`,
|
|
6713
|
+
"User-Agent": `moxt-machine-connector/${connectorVersion}`
|
|
6714
|
+
},
|
|
6715
|
+
method: "GET",
|
|
6716
|
+
signal: requestSignal(externalSignal)
|
|
6717
|
+
});
|
|
6718
|
+
const responseText = await response.text();
|
|
6719
|
+
if (!response.ok) {
|
|
6720
|
+
throw new RelayHttpError(response.status, responseText);
|
|
6721
|
+
}
|
|
6722
|
+
return JSON.parse(responseText);
|
|
6723
|
+
}
|
|
6724
|
+
function requestSignal(externalSignal) {
|
|
6725
|
+
if (externalSignal === void 0) {
|
|
6726
|
+
return AbortSignal.timeout(requestTimeoutMilliseconds);
|
|
6727
|
+
}
|
|
6728
|
+
return AbortSignal.any([
|
|
6729
|
+
externalSignal,
|
|
6730
|
+
AbortSignal.timeout(requestTimeoutMilliseconds)
|
|
6731
|
+
]);
|
|
6732
|
+
}
|
|
6733
|
+
function toRelayEvent(event2) {
|
|
6705
6734
|
let payload = {};
|
|
6706
|
-
if (
|
|
6707
|
-
payload = JSON.parse(
|
|
6735
|
+
if (event2.payloadJson) {
|
|
6736
|
+
payload = JSON.parse(event2.payloadJson);
|
|
6708
6737
|
} else {
|
|
6709
6738
|
payload = {
|
|
6710
|
-
message:
|
|
6711
|
-
status:
|
|
6712
|
-
truncated:
|
|
6739
|
+
message: event2.message,
|
|
6740
|
+
status: event2.status,
|
|
6741
|
+
truncated: event2.truncated
|
|
6713
6742
|
};
|
|
6714
6743
|
}
|
|
6715
6744
|
return {
|
|
6716
|
-
createdAt:
|
|
6717
|
-
eventId:
|
|
6718
|
-
kind:
|
|
6719
|
-
outputStream:
|
|
6745
|
+
createdAt: event2.createdAt,
|
|
6746
|
+
eventId: event2.eventId,
|
|
6747
|
+
kind: event2.kind,
|
|
6748
|
+
outputStream: event2.outputStream,
|
|
6720
6749
|
payload,
|
|
6721
|
-
sequence:
|
|
6750
|
+
sequence: event2.sequence
|
|
6722
6751
|
};
|
|
6723
6752
|
}
|
|
6724
6753
|
function normalizeOrigin(relayOrigin) {
|
|
@@ -6806,20 +6835,66 @@ var init_relay_client = __esm({
|
|
|
6806
6835
|
async acknowledgeControl(request2) {
|
|
6807
6836
|
await this.authenticatedPost("controls/acknowledge", request2);
|
|
6808
6837
|
}
|
|
6809
|
-
async
|
|
6838
|
+
async heartbeatCodexRuntime(request2) {
|
|
6839
|
+
return await this.authenticatedPost("codex-runtime/heartbeat", request2);
|
|
6840
|
+
}
|
|
6841
|
+
async claimCodexRuntime(request2, signal) {
|
|
6842
|
+
return await this.authenticatedPost("codex-runtime/turns/claim", request2, signal);
|
|
6843
|
+
}
|
|
6844
|
+
async renewCodexRuntimeLease(attemptId, fence, signal) {
|
|
6845
|
+
return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/lease`, fence, signal);
|
|
6846
|
+
}
|
|
6847
|
+
async appendCodexRuntimeEvents(attemptId, fence, firstSequence, events) {
|
|
6848
|
+
return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/events`, { ...fence, events, firstSequence });
|
|
6849
|
+
}
|
|
6850
|
+
async updateCodexRuntimeState(attemptId, fence, state) {
|
|
6851
|
+
await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/state`, { ...fence, ...state });
|
|
6852
|
+
}
|
|
6853
|
+
async pollCodexRuntimeControls(attemptId, fence, after, waitSeconds, signal) {
|
|
6854
|
+
return await this.authenticatedGet(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/controls`, { after: String(after), waitSeconds: String(waitSeconds) }, {
|
|
6855
|
+
"x-moxt-local-codex-attempt-generation": String(fence.attemptGeneration),
|
|
6856
|
+
"x-moxt-local-codex-connector-instance-id": fence.connectorInstanceId,
|
|
6857
|
+
"x-moxt-local-codex-lease-token": fence.leaseToken,
|
|
6858
|
+
"x-moxt-local-codex-process-generation": String(fence.processGeneration),
|
|
6859
|
+
"x-moxt-local-codex-protocol-version": fence.protocolVersion,
|
|
6860
|
+
"x-moxt-local-codex-run-token": fence.runToken
|
|
6861
|
+
}, signal);
|
|
6862
|
+
}
|
|
6863
|
+
async acknowledgeCodexRuntimeControl(attemptId, fence, controlId, outcome) {
|
|
6864
|
+
await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/controls/acknowledge`, { ...fence, controlId, outcome });
|
|
6865
|
+
}
|
|
6866
|
+
async authenticatedPost(path4, body, signal) {
|
|
6810
6867
|
if (this.revoked) {
|
|
6811
6868
|
throw new MachineConnectionRevokedError(this.connection.connectionId);
|
|
6812
6869
|
}
|
|
6813
6870
|
const url = `${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/${path4}`;
|
|
6814
6871
|
try {
|
|
6815
|
-
return await postJson(url, body, this.connection.accessToken);
|
|
6872
|
+
return await postJson(url, body, this.connection.accessToken, signal);
|
|
6873
|
+
} catch (error) {
|
|
6874
|
+
if (!(error instanceof RelayHttpError) || error.status !== 401) {
|
|
6875
|
+
throw error;
|
|
6876
|
+
}
|
|
6877
|
+
}
|
|
6878
|
+
await this.refreshAccessTokenOnce();
|
|
6879
|
+
return await postJson(url, body, this.connection.accessToken, signal);
|
|
6880
|
+
}
|
|
6881
|
+
async authenticatedGet(path4, query, headers, signal) {
|
|
6882
|
+
if (this.revoked) {
|
|
6883
|
+
throw new MachineConnectionRevokedError(this.connection.connectionId);
|
|
6884
|
+
}
|
|
6885
|
+
const url = new URL(`${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/${path4}`);
|
|
6886
|
+
for (const [name, value] of Object.entries(query)) {
|
|
6887
|
+
url.searchParams.set(name, value);
|
|
6888
|
+
}
|
|
6889
|
+
try {
|
|
6890
|
+
return await getJson(url.toString(), this.connection.accessToken, headers, signal);
|
|
6816
6891
|
} catch (error) {
|
|
6817
6892
|
if (!(error instanceof RelayHttpError) || error.status !== 401) {
|
|
6818
6893
|
throw error;
|
|
6819
6894
|
}
|
|
6820
6895
|
}
|
|
6821
6896
|
await this.refreshAccessTokenOnce();
|
|
6822
|
-
return await
|
|
6897
|
+
return await getJson(url.toString(), this.connection.accessToken, headers, signal);
|
|
6823
6898
|
}
|
|
6824
6899
|
async refreshAccessTokenOnce() {
|
|
6825
6900
|
if (!this.refreshState.promise) {
|
|
@@ -6907,18 +6982,21 @@ function isNodeErrorCode3(error, expectedCode) {
|
|
|
6907
6982
|
}
|
|
6908
6983
|
return error.code === expectedCode;
|
|
6909
6984
|
}
|
|
6910
|
-
var import_promises11, import_node_os4, import_node_path8, privateFileMode, privateDirectoryMode, MachineRuntimeStore;
|
|
6985
|
+
var import_promises11, import_node_crypto5, import_node_os4, import_node_path8, privateFileMode, privateDirectoryMode, maximumProcessGeneration, MachineRuntimeStore;
|
|
6911
6986
|
var init_store = __esm({
|
|
6912
6987
|
"../machine-connector/dist/runtime/store.js"() {
|
|
6913
6988
|
"use strict";
|
|
6914
6989
|
init_cjs_shims();
|
|
6915
6990
|
import_promises11 = require("fs/promises");
|
|
6991
|
+
import_node_crypto5 = require("crypto");
|
|
6916
6992
|
import_node_os4 = require("os");
|
|
6917
6993
|
import_node_path8 = require("path");
|
|
6918
6994
|
privateFileMode = 384;
|
|
6919
6995
|
privateDirectoryMode = 448;
|
|
6996
|
+
maximumProcessGeneration = 2147483647;
|
|
6920
6997
|
MachineRuntimeStore = class {
|
|
6921
6998
|
baseDirectory;
|
|
6999
|
+
localCodexProcessGenerationQueue = Promise.resolve();
|
|
6922
7000
|
constructor(baseDirectory = defaultRuntimeDirectory()) {
|
|
6923
7001
|
this.baseDirectory = baseDirectory;
|
|
6924
7002
|
}
|
|
@@ -6931,9 +7009,19 @@ var init_store = __esm({
|
|
|
6931
7009
|
mode: privateDirectoryMode,
|
|
6932
7010
|
recursive: true
|
|
6933
7011
|
});
|
|
7012
|
+
await (0, import_promises11.mkdir)(this.localCodexAttemptsDirectory(), {
|
|
7013
|
+
mode: privateDirectoryMode,
|
|
7014
|
+
recursive: true
|
|
7015
|
+
});
|
|
7016
|
+
await (0, import_promises11.mkdir)(this.localCodexProcessGenerationsDirectory(), {
|
|
7017
|
+
mode: privateDirectoryMode,
|
|
7018
|
+
recursive: true
|
|
7019
|
+
});
|
|
6934
7020
|
await (0, import_promises11.chmod)(this.baseDirectory, privateDirectoryMode);
|
|
6935
7021
|
await (0, import_promises11.chmod)(this.jobsDirectory(), privateDirectoryMode);
|
|
6936
7022
|
await (0, import_promises11.chmod)(this.detachedProcessesDirectory(), privateDirectoryMode);
|
|
7023
|
+
await (0, import_promises11.chmod)(this.localCodexAttemptsDirectory(), privateDirectoryMode);
|
|
7024
|
+
await (0, import_promises11.chmod)(this.localCodexProcessGenerationsDirectory(), privateDirectoryMode);
|
|
6937
7025
|
}
|
|
6938
7026
|
async getCanonicalRoot(rootPath) {
|
|
6939
7027
|
return await (0, import_promises11.realpath)(rootPath);
|
|
@@ -6987,131 +7075,2385 @@ var init_store = __esm({
|
|
|
6987
7075
|
async writeJob(job) {
|
|
6988
7076
|
await this.writePrivateJson(this.jobPath(job.claim.jobId), job);
|
|
6989
7077
|
}
|
|
6990
|
-
async listJobs() {
|
|
6991
|
-
let names = [];
|
|
7078
|
+
async listJobs() {
|
|
7079
|
+
let names = [];
|
|
7080
|
+
try {
|
|
7081
|
+
names = await (0, import_promises11.readdir)(this.jobsDirectory());
|
|
7082
|
+
} catch (error) {
|
|
7083
|
+
if (isNodeErrorCode3(error, "ENOENT")) {
|
|
7084
|
+
return [];
|
|
7085
|
+
}
|
|
7086
|
+
throw error;
|
|
7087
|
+
}
|
|
7088
|
+
const jobs = [];
|
|
7089
|
+
for (const name of names.filter((entry) => entry.endsWith(".json"))) {
|
|
7090
|
+
const job = await this.readOptionalJson((0, import_node_path8.join)(this.jobsDirectory(), name));
|
|
7091
|
+
if (job.value) {
|
|
7092
|
+
jobs.push(job.value);
|
|
7093
|
+
}
|
|
7094
|
+
}
|
|
7095
|
+
return jobs;
|
|
7096
|
+
}
|
|
7097
|
+
async deleteJob(jobId) {
|
|
7098
|
+
await (0, import_promises11.rm)(this.jobPath(jobId), { force: true });
|
|
7099
|
+
}
|
|
7100
|
+
async writeDetachedProcess(resource) {
|
|
7101
|
+
await this.writePrivateJson(this.detachedProcessPath(resource.jobId), resource);
|
|
7102
|
+
}
|
|
7103
|
+
async listDetachedProcesses() {
|
|
7104
|
+
let names = [];
|
|
7105
|
+
try {
|
|
7106
|
+
names = await (0, import_promises11.readdir)(this.detachedProcessesDirectory());
|
|
7107
|
+
} catch (error) {
|
|
7108
|
+
if (isNodeErrorCode3(error, "ENOENT")) {
|
|
7109
|
+
return [];
|
|
7110
|
+
}
|
|
7111
|
+
throw error;
|
|
7112
|
+
}
|
|
7113
|
+
const resources = [];
|
|
7114
|
+
for (const name of names.filter((entry) => entry.endsWith(".json"))) {
|
|
7115
|
+
const resource = await this.readOptionalJson((0, import_node_path8.join)(this.detachedProcessesDirectory(), name));
|
|
7116
|
+
if (resource.value) {
|
|
7117
|
+
resources.push(resource.value);
|
|
7118
|
+
}
|
|
7119
|
+
}
|
|
7120
|
+
return resources;
|
|
7121
|
+
}
|
|
7122
|
+
async deleteDetachedProcess(jobId) {
|
|
7123
|
+
await (0, import_promises11.rm)(this.detachedProcessPath(jobId), { force: true });
|
|
7124
|
+
}
|
|
7125
|
+
async readLocalCodexAttempt(attemptId) {
|
|
7126
|
+
return await this.readOptionalJson(this.localCodexAttemptPath(attemptId));
|
|
7127
|
+
}
|
|
7128
|
+
async writeLocalCodexAttempt(attempt) {
|
|
7129
|
+
await this.writePrivateJson(this.localCodexAttemptPath(attempt.claim.attemptId), attempt);
|
|
7130
|
+
}
|
|
7131
|
+
async listLocalCodexAttempts() {
|
|
7132
|
+
let names = [];
|
|
7133
|
+
try {
|
|
7134
|
+
names = await (0, import_promises11.readdir)(this.localCodexAttemptsDirectory());
|
|
7135
|
+
} catch (error) {
|
|
7136
|
+
if (isNodeErrorCode3(error, "ENOENT")) {
|
|
7137
|
+
return [];
|
|
7138
|
+
}
|
|
7139
|
+
throw error;
|
|
7140
|
+
}
|
|
7141
|
+
const attempts = [];
|
|
7142
|
+
for (const name of names.filter((entry) => entry.endsWith(".json"))) {
|
|
7143
|
+
const attempt = await this.readOptionalJson((0, import_node_path8.join)(this.localCodexAttemptsDirectory(), name));
|
|
7144
|
+
if (attempt.value !== void 0) {
|
|
7145
|
+
attempts.push(attempt.value);
|
|
7146
|
+
}
|
|
7147
|
+
}
|
|
7148
|
+
return attempts;
|
|
7149
|
+
}
|
|
7150
|
+
async deleteLocalCodexAttempt(attemptId) {
|
|
7151
|
+
await (0, import_promises11.rm)(this.localCodexAttemptPath(attemptId), { force: true });
|
|
7152
|
+
}
|
|
7153
|
+
async allocateLocalCodexProcessGeneration(poolKey) {
|
|
7154
|
+
if (!/^[a-f0-9]{64}$/.test(poolKey)) {
|
|
7155
|
+
throw new Error("Local Codex Runtime process pool key is invalid");
|
|
7156
|
+
}
|
|
7157
|
+
let allocated = 0;
|
|
7158
|
+
const allocation = this.localCodexProcessGenerationQueue.then(async () => {
|
|
7159
|
+
const path4 = this.localCodexProcessGenerationPath(poolKey);
|
|
7160
|
+
const persisted = (await this.readOptionalJson(path4)).value;
|
|
7161
|
+
if (persisted !== void 0 && (persisted.version !== 1 || persisted.poolKey !== poolKey)) {
|
|
7162
|
+
throw new Error("Local Codex Runtime process generation is incompatible");
|
|
7163
|
+
}
|
|
7164
|
+
const previous2 = persisted?.lastAllocatedGeneration ?? 0;
|
|
7165
|
+
if (!Number.isSafeInteger(previous2) || previous2 < 0 || previous2 >= maximumProcessGeneration) {
|
|
7166
|
+
throw new Error("Local Codex Runtime process generation is exhausted");
|
|
7167
|
+
}
|
|
7168
|
+
allocated = previous2 + 1;
|
|
7169
|
+
await this.writePrivateJson(path4, {
|
|
7170
|
+
lastAllocatedGeneration: allocated,
|
|
7171
|
+
poolKey,
|
|
7172
|
+
version: 1
|
|
7173
|
+
});
|
|
7174
|
+
});
|
|
7175
|
+
this.localCodexProcessGenerationQueue = allocation.catch(() => void 0);
|
|
7176
|
+
await allocation;
|
|
7177
|
+
return allocated;
|
|
7178
|
+
}
|
|
7179
|
+
runtimeLogPath() {
|
|
7180
|
+
return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.log");
|
|
7181
|
+
}
|
|
7182
|
+
runtimeErrorLogPath() {
|
|
7183
|
+
return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.error.log");
|
|
7184
|
+
}
|
|
7185
|
+
runtimeStatusPath() {
|
|
7186
|
+
return (0, import_node_path8.join)(this.baseDirectory, "runtime-status.json");
|
|
7187
|
+
}
|
|
7188
|
+
runtimeSocketPath() {
|
|
7189
|
+
if ((0, import_node_os4.platform)() === "win32") {
|
|
7190
|
+
return String.raw`\\.\pipe\moxt-machine-connector`;
|
|
7191
|
+
}
|
|
7192
|
+
return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.sock");
|
|
7193
|
+
}
|
|
7194
|
+
daemonLockPath() {
|
|
7195
|
+
return (0, import_node_path8.join)(this.baseDirectory, "daemon.lock");
|
|
7196
|
+
}
|
|
7197
|
+
reconcileLockPath() {
|
|
7198
|
+
return (0, import_node_path8.join)(this.baseDirectory, "daemon-reconcile.lock");
|
|
7199
|
+
}
|
|
7200
|
+
connectionsPath() {
|
|
7201
|
+
return (0, import_node_path8.join)(this.baseDirectory, "connections.json");
|
|
7202
|
+
}
|
|
7203
|
+
detachedProcessesDirectory() {
|
|
7204
|
+
return (0, import_node_path8.join)(this.baseDirectory, "detached-processes");
|
|
7205
|
+
}
|
|
7206
|
+
detachedProcessPath(jobId) {
|
|
7207
|
+
return (0, import_node_path8.join)(this.detachedProcessesDirectory(), `${jobId}.json`);
|
|
7208
|
+
}
|
|
7209
|
+
identityPath() {
|
|
7210
|
+
return (0, import_node_path8.join)(this.baseDirectory, "identity.json");
|
|
7211
|
+
}
|
|
7212
|
+
serviceManagerPath() {
|
|
7213
|
+
return (0, import_node_path8.join)(this.baseDirectory, "service-manager.json");
|
|
7214
|
+
}
|
|
7215
|
+
privateKeyPath() {
|
|
7216
|
+
return (0, import_node_path8.join)(this.baseDirectory, "device-private-key.pem");
|
|
7217
|
+
}
|
|
7218
|
+
jobsDirectory() {
|
|
7219
|
+
return (0, import_node_path8.join)(this.baseDirectory, "jobs");
|
|
7220
|
+
}
|
|
7221
|
+
localCodexAttemptsDirectory() {
|
|
7222
|
+
return (0, import_node_path8.join)(this.baseDirectory, "local-codex-runtime-attempts");
|
|
7223
|
+
}
|
|
7224
|
+
localCodexAttemptPath(attemptId) {
|
|
7225
|
+
return (0, import_node_path8.join)(this.localCodexAttemptsDirectory(), `${attemptId}.json`);
|
|
7226
|
+
}
|
|
7227
|
+
localCodexProcessGenerationsDirectory() {
|
|
7228
|
+
return (0, import_node_path8.join)(this.baseDirectory, "local-codex-runtime-process-generations");
|
|
7229
|
+
}
|
|
7230
|
+
localCodexProcessGenerationPath(poolKey) {
|
|
7231
|
+
const key = (0, import_node_crypto5.createHash)("sha256").update(poolKey).digest("hex");
|
|
7232
|
+
return (0, import_node_path8.join)(this.localCodexProcessGenerationsDirectory(), `${key}.json`);
|
|
7233
|
+
}
|
|
7234
|
+
jobPath(jobId) {
|
|
7235
|
+
return (0, import_node_path8.join)(this.jobsDirectory(), `${jobId}.json`);
|
|
7236
|
+
}
|
|
7237
|
+
async readOptionalJson(path4) {
|
|
7238
|
+
const content3 = await this.readOptionalText(path4);
|
|
7239
|
+
if (content3.value === void 0) {
|
|
7240
|
+
return {};
|
|
7241
|
+
}
|
|
7242
|
+
return { value: JSON.parse(content3.value) };
|
|
7243
|
+
}
|
|
7244
|
+
async readOptionalText(path4) {
|
|
7245
|
+
try {
|
|
7246
|
+
return { value: await (0, import_promises11.readFile)(path4, "utf8") };
|
|
7247
|
+
} catch (error) {
|
|
7248
|
+
if (isNodeErrorCode3(error, "ENOENT")) {
|
|
7249
|
+
return {};
|
|
7250
|
+
}
|
|
7251
|
+
throw error;
|
|
7252
|
+
}
|
|
7253
|
+
}
|
|
7254
|
+
async writePrivateJson(path4, value) {
|
|
7255
|
+
await this.writePrivateText(path4, `${JSON.stringify(value, void 0, 2)}
|
|
7256
|
+
`);
|
|
7257
|
+
}
|
|
7258
|
+
async writePrivateText(path4, value) {
|
|
7259
|
+
await (0, import_promises11.mkdir)((0, import_node_path8.dirname)(path4), {
|
|
7260
|
+
mode: privateDirectoryMode,
|
|
7261
|
+
recursive: true
|
|
7262
|
+
});
|
|
7263
|
+
const temporaryPath = `${path4}.${process.pid}.tmp`;
|
|
7264
|
+
await (0, import_promises11.writeFile)(temporaryPath, value, {
|
|
7265
|
+
encoding: "utf8",
|
|
7266
|
+
mode: privateFileMode
|
|
7267
|
+
});
|
|
7268
|
+
await (0, import_promises11.chmod)(temporaryPath, privateFileMode);
|
|
7269
|
+
await (0, import_promises11.rename)(temporaryPath, path4);
|
|
7270
|
+
}
|
|
7271
|
+
};
|
|
7272
|
+
}
|
|
7273
|
+
});
|
|
7274
|
+
|
|
7275
|
+
// ../machine-connector/dist/runtime/local-codex-runtime/contracts.js
|
|
7276
|
+
var localCodexRuntimeProtocolVersion, localCodexRuntimeEventSchemaVersion, localCodexRuntimeEventRedactionVersion, LocalCodexComponentStatusWire, LocalCodexTurnStatusWire, LocalCodexControlKindWire, LocalCodexControlOutcomeWire, LocalCodexAttemptPhase, LocalCodexControlApplyPhase;
|
|
7277
|
+
var init_contracts2 = __esm({
|
|
7278
|
+
"../machine-connector/dist/runtime/local-codex-runtime/contracts.js"() {
|
|
7279
|
+
"use strict";
|
|
7280
|
+
init_cjs_shims();
|
|
7281
|
+
localCodexRuntimeProtocolVersion = "1.0";
|
|
7282
|
+
localCodexRuntimeEventSchemaVersion = 1;
|
|
7283
|
+
localCodexRuntimeEventRedactionVersion = 1;
|
|
7284
|
+
(function(LocalCodexComponentStatusWire2) {
|
|
7285
|
+
LocalCodexComponentStatusWire2["AuthenticationRequired"] = "authentication_required";
|
|
7286
|
+
LocalCodexComponentStatusWire2["Error"] = "error";
|
|
7287
|
+
LocalCodexComponentStatusWire2["Incompatible"] = "incompatible";
|
|
7288
|
+
LocalCodexComponentStatusWire2["Missing"] = "missing";
|
|
7289
|
+
LocalCodexComponentStatusWire2["Ready"] = "ready";
|
|
7290
|
+
LocalCodexComponentStatusWire2["Unknown"] = "unknown";
|
|
7291
|
+
})(LocalCodexComponentStatusWire || (LocalCodexComponentStatusWire = {}));
|
|
7292
|
+
(function(LocalCodexTurnStatusWire2) {
|
|
7293
|
+
LocalCodexTurnStatusWire2["Cancelled"] = "cancelled";
|
|
7294
|
+
LocalCodexTurnStatusWire2["Failed"] = "failed";
|
|
7295
|
+
LocalCodexTurnStatusWire2["Interrupted"] = "interrupted";
|
|
7296
|
+
LocalCodexTurnStatusWire2["Running"] = "running";
|
|
7297
|
+
LocalCodexTurnStatusWire2["RuntimeLost"] = "runtime_lost";
|
|
7298
|
+
LocalCodexTurnStatusWire2["Succeeded"] = "succeeded";
|
|
7299
|
+
})(LocalCodexTurnStatusWire || (LocalCodexTurnStatusWire = {}));
|
|
7300
|
+
(function(LocalCodexControlKindWire2) {
|
|
7301
|
+
LocalCodexControlKindWire2["Abort"] = "abort";
|
|
7302
|
+
LocalCodexControlKindWire2["InteractionResponse"] = "interaction_response";
|
|
7303
|
+
LocalCodexControlKindWire2["Steer"] = "steer";
|
|
7304
|
+
})(LocalCodexControlKindWire || (LocalCodexControlKindWire = {}));
|
|
7305
|
+
(function(LocalCodexControlOutcomeWire2) {
|
|
7306
|
+
LocalCodexControlOutcomeWire2["Applied"] = "applied";
|
|
7307
|
+
LocalCodexControlOutcomeWire2["Rejected"] = "rejected";
|
|
7308
|
+
LocalCodexControlOutcomeWire2["Stale"] = "stale";
|
|
7309
|
+
})(LocalCodexControlOutcomeWire || (LocalCodexControlOutcomeWire = {}));
|
|
7310
|
+
(function(LocalCodexAttemptPhase2) {
|
|
7311
|
+
LocalCodexAttemptPhase2["Claimed"] = "claimed";
|
|
7312
|
+
LocalCodexAttemptPhase2["Running"] = "running";
|
|
7313
|
+
LocalCodexAttemptPhase2["TerminalPendingUpload"] = "terminal_pending_upload";
|
|
7314
|
+
LocalCodexAttemptPhase2["Uploaded"] = "uploaded";
|
|
7315
|
+
})(LocalCodexAttemptPhase || (LocalCodexAttemptPhase = {}));
|
|
7316
|
+
(function(LocalCodexControlApplyPhase2) {
|
|
7317
|
+
LocalCodexControlApplyPhase2["Applied"] = "applied";
|
|
7318
|
+
LocalCodexControlApplyPhase2["Recorded"] = "recorded";
|
|
7319
|
+
})(LocalCodexControlApplyPhase || (LocalCodexControlApplyPhase = {}));
|
|
7320
|
+
}
|
|
7321
|
+
});
|
|
7322
|
+
|
|
7323
|
+
// ../machine-connector/dist/runtime/local-codex-runtime/app-server-client.js
|
|
7324
|
+
function rpcIdentifier(value) {
|
|
7325
|
+
if (typeof value === "string") {
|
|
7326
|
+
return { value };
|
|
7327
|
+
}
|
|
7328
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
7329
|
+
return { value: String(value) };
|
|
7330
|
+
}
|
|
7331
|
+
return {};
|
|
7332
|
+
}
|
|
7333
|
+
function createAppServerEnvironment(environment) {
|
|
7334
|
+
const result = {};
|
|
7335
|
+
for (const [name, value] of Object.entries(environment)) {
|
|
7336
|
+
const normalized = name.toUpperCase();
|
|
7337
|
+
if (normalized.startsWith("MOXT_MACHINE_") || normalized.startsWith("MACHINE_RELAY_") || normalized.startsWith("LOCAL_MACHINE_CONNECTOR_")) {
|
|
7338
|
+
continue;
|
|
7339
|
+
}
|
|
7340
|
+
result[name] = value;
|
|
7341
|
+
}
|
|
7342
|
+
return result;
|
|
7343
|
+
}
|
|
7344
|
+
function digestOpaque(value) {
|
|
7345
|
+
return (0, import_node_crypto6.createHash)("sha256").update(value).digest("hex");
|
|
7346
|
+
}
|
|
7347
|
+
function extractCodexVersion(userAgent) {
|
|
7348
|
+
const matched = /(?:codex_cli_rs|codex-cli|codex(?: desktop)?)\/([0-9][^\s/]*)/i.exec(userAgent);
|
|
7349
|
+
return matched?.[1] ?? userAgent.slice(0, 64);
|
|
7350
|
+
}
|
|
7351
|
+
async function completionWithinExit(child, milliseconds) {
|
|
7352
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
7353
|
+
return;
|
|
7354
|
+
}
|
|
7355
|
+
await new Promise((resolve9) => {
|
|
7356
|
+
const timeout = setTimeout(resolve9, milliseconds);
|
|
7357
|
+
timeout.unref();
|
|
7358
|
+
child.once("close", () => {
|
|
7359
|
+
clearTimeout(timeout);
|
|
7360
|
+
resolve9();
|
|
7361
|
+
});
|
|
7362
|
+
});
|
|
7363
|
+
}
|
|
7364
|
+
function terminateAppServerProcess(child) {
|
|
7365
|
+
if ((0, import_node_os5.platform)() === "win32" || child.pid === void 0) {
|
|
7366
|
+
child.kill("SIGTERM");
|
|
7367
|
+
return;
|
|
7368
|
+
}
|
|
7369
|
+
try {
|
|
7370
|
+
process.kill(-child.pid, "SIGTERM");
|
|
7371
|
+
} catch {
|
|
7372
|
+
child.kill("SIGTERM");
|
|
7373
|
+
}
|
|
7374
|
+
}
|
|
7375
|
+
function killAppServerProcess(child) {
|
|
7376
|
+
if ((0, import_node_os5.platform)() === "win32" || child.pid === void 0) {
|
|
7377
|
+
child.kill("SIGKILL");
|
|
7378
|
+
return;
|
|
7379
|
+
}
|
|
7380
|
+
try {
|
|
7381
|
+
process.kill(-child.pid, "SIGKILL");
|
|
7382
|
+
} catch {
|
|
7383
|
+
child.kill("SIGKILL");
|
|
7384
|
+
}
|
|
7385
|
+
}
|
|
7386
|
+
var import_node_child_process3, import_node_crypto6, import_node_os5, maximumFrameBytes, requestTimeoutMilliseconds2, AppServerProcessLostError, AppServerProtocolError, AppServerRequestTimeoutError, AppServerClient, LocalCodexAppServerSupervisor;
|
|
7387
|
+
var init_app_server_client = __esm({
|
|
7388
|
+
"../machine-connector/dist/runtime/local-codex-runtime/app-server-client.js"() {
|
|
7389
|
+
"use strict";
|
|
7390
|
+
init_cjs_shims();
|
|
7391
|
+
import_node_child_process3 = require("child_process");
|
|
7392
|
+
import_node_crypto6 = require("crypto");
|
|
7393
|
+
import_node_os5 = require("os");
|
|
7394
|
+
init_version();
|
|
7395
|
+
init_contracts2();
|
|
7396
|
+
maximumFrameBytes = 8e6;
|
|
7397
|
+
requestTimeoutMilliseconds2 = 3e4;
|
|
7398
|
+
AppServerProcessLostError = class extends Error {
|
|
7399
|
+
constructor(message) {
|
|
7400
|
+
super(message);
|
|
7401
|
+
this.name = "AppServerProcessLostError";
|
|
7402
|
+
}
|
|
7403
|
+
};
|
|
7404
|
+
AppServerProtocolError = class extends Error {
|
|
7405
|
+
constructor(message) {
|
|
7406
|
+
super(message);
|
|
7407
|
+
this.name = "AppServerProtocolError";
|
|
7408
|
+
}
|
|
7409
|
+
};
|
|
7410
|
+
AppServerRequestTimeoutError = class extends AppServerProtocolError {
|
|
7411
|
+
method;
|
|
7412
|
+
constructor(method) {
|
|
7413
|
+
super(`Codex App Server request ${method} timed out`);
|
|
7414
|
+
this.method = method;
|
|
7415
|
+
this.name = "AppServerRequestTimeoutError";
|
|
7416
|
+
}
|
|
7417
|
+
};
|
|
7418
|
+
AppServerClient = class _AppServerClient {
|
|
7419
|
+
child;
|
|
7420
|
+
handlers;
|
|
7421
|
+
processGeneration;
|
|
7422
|
+
buffer = Buffer.alloc(0);
|
|
7423
|
+
closed = false;
|
|
7424
|
+
handlerQueue = Promise.resolve();
|
|
7425
|
+
intentionalStop = false;
|
|
7426
|
+
nextRequestId = 1;
|
|
7427
|
+
pending = /* @__PURE__ */ new Map();
|
|
7428
|
+
writeQueue = Promise.resolve();
|
|
7429
|
+
constructor(child, handlers, processGeneration) {
|
|
7430
|
+
this.child = child;
|
|
7431
|
+
this.handlers = handlers;
|
|
7432
|
+
this.processGeneration = processGeneration;
|
|
7433
|
+
child.stdout.on("data", (chunk) => this.receive(chunk));
|
|
7434
|
+
child.stderr.setEncoding("utf8");
|
|
7435
|
+
child.stderr.on("data", (text3) => {
|
|
7436
|
+
this.enqueueHandler(async () => await handlers.onStderr(text3), "stderr");
|
|
7437
|
+
});
|
|
7438
|
+
child.once("error", (error) => {
|
|
7439
|
+
this.closeWithError(new AppServerProcessLostError(`Codex App Server process failed: ${error.message}`));
|
|
7440
|
+
});
|
|
7441
|
+
child.once("close", (code, signal) => {
|
|
7442
|
+
this.closeWithError(new AppServerProcessLostError(`Codex App Server process exited with code ${String(code)} and signal ${String(signal)}`));
|
|
7443
|
+
});
|
|
7444
|
+
}
|
|
7445
|
+
static async start(options) {
|
|
7446
|
+
const environment = createAppServerEnvironment(options.environment);
|
|
7447
|
+
const executable = process.env.MOXT_CODEX_PATH ?? "codex";
|
|
7448
|
+
const child = (0, import_node_child_process3.spawn)(executable, ["app-server", "--listen", "stdio://"], {
|
|
7449
|
+
cwd: options.processBaseDirectory,
|
|
7450
|
+
detached: (0, import_node_os5.platform)() !== "win32",
|
|
7451
|
+
env: environment,
|
|
7452
|
+
shell: false,
|
|
7453
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
7454
|
+
windowsHide: true
|
|
7455
|
+
});
|
|
7456
|
+
const client = new _AppServerClient(child, options.handlers, options.processGeneration);
|
|
7457
|
+
try {
|
|
7458
|
+
const initialized = await client.request("initialize", {
|
|
7459
|
+
capabilities: {
|
|
7460
|
+
experimentalApi: true,
|
|
7461
|
+
requestAttestation: false
|
|
7462
|
+
},
|
|
7463
|
+
clientInfo: {
|
|
7464
|
+
name: "moxt-machine-connector",
|
|
7465
|
+
title: "Moxt Machine Connector",
|
|
7466
|
+
version: connectorVersion
|
|
7467
|
+
}
|
|
7468
|
+
});
|
|
7469
|
+
await client.notify("initialized");
|
|
7470
|
+
const account = await client.request("account/read", { refreshToken: false });
|
|
7471
|
+
await client.request("thread/loaded/list", {
|
|
7472
|
+
cursor: null,
|
|
7473
|
+
limit: 1
|
|
7474
|
+
});
|
|
7475
|
+
const authenticated = account.requiresOpenaiAuth !== true || account.account !== void 0;
|
|
7476
|
+
return {
|
|
7477
|
+
capability: {
|
|
7478
|
+
appServerStatus: LocalCodexComponentStatusWire.Ready,
|
|
7479
|
+
codexAuthStatus: authenticated ? LocalCodexComponentStatusWire.Ready : LocalCodexComponentStatusWire.AuthenticationRequired,
|
|
7480
|
+
codexBinaryStatus: LocalCodexComponentStatusWire.Ready,
|
|
7481
|
+
codexVersion: extractCodexVersion(initialized.userAgent),
|
|
7482
|
+
nativeStoreIdentity: digestOpaque(`${options.nativeStoreIdentitySeed}\0${initialized.codexHome}`),
|
|
7483
|
+
processGeneration: options.processGeneration
|
|
7484
|
+
},
|
|
7485
|
+
client
|
|
7486
|
+
};
|
|
7487
|
+
} catch (error) {
|
|
7488
|
+
await client.stop();
|
|
7489
|
+
throw error;
|
|
7490
|
+
}
|
|
7491
|
+
}
|
|
7492
|
+
isClosed() {
|
|
7493
|
+
return this.closed;
|
|
7494
|
+
}
|
|
7495
|
+
async request(method, params) {
|
|
7496
|
+
if (this.closed) {
|
|
7497
|
+
throw new AppServerProcessLostError("Codex App Server process is closed");
|
|
7498
|
+
}
|
|
7499
|
+
const id = this.nextRequestId;
|
|
7500
|
+
this.nextRequestId += 1;
|
|
7501
|
+
const key = String(id);
|
|
7502
|
+
const response = new Promise((resolve9, reject) => {
|
|
7503
|
+
const timeout = setTimeout(() => {
|
|
7504
|
+
this.pending.delete(key);
|
|
7505
|
+
reject(new AppServerRequestTimeoutError(method));
|
|
7506
|
+
}, requestTimeoutMilliseconds2);
|
|
7507
|
+
timeout.unref();
|
|
7508
|
+
this.pending.set(key, { reject, resolve: resolve9, timeout });
|
|
7509
|
+
});
|
|
7510
|
+
await this.write({ id, method, params });
|
|
7511
|
+
return await response;
|
|
7512
|
+
}
|
|
7513
|
+
async notify(method, params) {
|
|
7514
|
+
await this.write({
|
|
7515
|
+
method,
|
|
7516
|
+
...params === void 0 ? {} : { params }
|
|
7517
|
+
});
|
|
7518
|
+
}
|
|
7519
|
+
async respond(id, result) {
|
|
7520
|
+
await this.write({ id, result });
|
|
7521
|
+
}
|
|
7522
|
+
async respondWithError(id, code, message) {
|
|
7523
|
+
await this.write({ error: { code, message }, id });
|
|
7524
|
+
}
|
|
7525
|
+
async stop() {
|
|
7526
|
+
if (this.closed) {
|
|
7527
|
+
return;
|
|
7528
|
+
}
|
|
7529
|
+
this.intentionalStop = true;
|
|
7530
|
+
this.child.stdin.end();
|
|
7531
|
+
await completionWithinExit(this.child, 2e3);
|
|
7532
|
+
if (!this.closed) {
|
|
7533
|
+
terminateAppServerProcess(this.child);
|
|
7534
|
+
await completionWithinExit(this.child, 2e3);
|
|
7535
|
+
}
|
|
7536
|
+
if (!this.closed) {
|
|
7537
|
+
killAppServerProcess(this.child);
|
|
7538
|
+
await completionWithinExit(this.child, 2e3);
|
|
7539
|
+
}
|
|
7540
|
+
}
|
|
7541
|
+
receive(chunk) {
|
|
7542
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
7543
|
+
if (this.buffer.length > maximumFrameBytes) {
|
|
7544
|
+
this.closeWithError(new AppServerProtocolError("Codex App Server frame exceeds the size limit"));
|
|
7545
|
+
return;
|
|
7546
|
+
}
|
|
7547
|
+
while (true) {
|
|
7548
|
+
const newline = this.buffer.indexOf(10);
|
|
7549
|
+
if (newline < 0) {
|
|
7550
|
+
return;
|
|
7551
|
+
}
|
|
7552
|
+
const frame = this.buffer.subarray(0, newline).toString("utf8");
|
|
7553
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
7554
|
+
if (frame.trim() === "") {
|
|
7555
|
+
continue;
|
|
7556
|
+
}
|
|
7557
|
+
let message;
|
|
7558
|
+
try {
|
|
7559
|
+
message = JSON.parse(frame);
|
|
7560
|
+
} catch {
|
|
7561
|
+
this.closeWithError(new AppServerProtocolError("Codex App Server returned invalid JSON"));
|
|
7562
|
+
return;
|
|
7563
|
+
}
|
|
7564
|
+
this.route(message);
|
|
7565
|
+
}
|
|
7566
|
+
}
|
|
7567
|
+
route(message) {
|
|
7568
|
+
const responseId = rpcIdentifier(message.id).value;
|
|
7569
|
+
if (responseId !== void 0 && message.method === void 0) {
|
|
7570
|
+
const pending = this.pending.get(responseId);
|
|
7571
|
+
if (pending === void 0) {
|
|
7572
|
+
return;
|
|
7573
|
+
}
|
|
7574
|
+
this.pending.delete(responseId);
|
|
7575
|
+
clearTimeout(pending.timeout);
|
|
7576
|
+
if (message.error !== void 0) {
|
|
7577
|
+
pending.reject(new AppServerProtocolError(`Codex App Server rejected request: ${JSON.stringify(message.error)}`));
|
|
7578
|
+
} else {
|
|
7579
|
+
pending.resolve(message.result);
|
|
7580
|
+
}
|
|
7581
|
+
return;
|
|
7582
|
+
}
|
|
7583
|
+
if (message.method === void 0) {
|
|
7584
|
+
return;
|
|
7585
|
+
}
|
|
7586
|
+
this.enqueueHandler(async () => {
|
|
7587
|
+
if (message.id === void 0) {
|
|
7588
|
+
await this.handlers.onNotification(message);
|
|
7589
|
+
} else {
|
|
7590
|
+
await this.handlers.onServerRequest(message);
|
|
7591
|
+
}
|
|
7592
|
+
}, message.method);
|
|
7593
|
+
}
|
|
7594
|
+
enqueueHandler(action, description) {
|
|
7595
|
+
this.handlerQueue = this.handlerQueue.then(action).catch(async (error) => {
|
|
7596
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
7597
|
+
await this.handlers.onStderr(`Local Codex ${description} handler failed: ${message}`);
|
|
7598
|
+
});
|
|
7599
|
+
}
|
|
7600
|
+
async write(message) {
|
|
7601
|
+
if (this.closed) {
|
|
7602
|
+
throw new AppServerProcessLostError("Codex App Server process is closed");
|
|
7603
|
+
}
|
|
7604
|
+
const frame = `${JSON.stringify(message)}
|
|
7605
|
+
`;
|
|
7606
|
+
if (Buffer.byteLength(frame, "utf8") > maximumFrameBytes) {
|
|
7607
|
+
throw new AppServerProtocolError("Codex App Server request exceeds the size limit");
|
|
7608
|
+
}
|
|
7609
|
+
const operation = this.writeQueue.then(async () => await new Promise((resolve9, reject) => {
|
|
7610
|
+
this.child.stdin.write(frame, (error) => {
|
|
7611
|
+
if (error) {
|
|
7612
|
+
reject(error);
|
|
7613
|
+
} else {
|
|
7614
|
+
resolve9();
|
|
7615
|
+
}
|
|
7616
|
+
});
|
|
7617
|
+
}));
|
|
7618
|
+
this.writeQueue = operation.catch(() => void 0);
|
|
7619
|
+
await operation;
|
|
7620
|
+
}
|
|
7621
|
+
closeWithError(error) {
|
|
7622
|
+
if (this.closed) {
|
|
7623
|
+
return;
|
|
7624
|
+
}
|
|
7625
|
+
this.closed = true;
|
|
7626
|
+
for (const pending of this.pending.values()) {
|
|
7627
|
+
clearTimeout(pending.timeout);
|
|
7628
|
+
pending.reject(error);
|
|
7629
|
+
}
|
|
7630
|
+
this.pending.clear();
|
|
7631
|
+
if (!this.intentionalStop) {
|
|
7632
|
+
this.enqueueHandler(async () => await this.handlers.onProcessExit(error, this.processGeneration), "process exit");
|
|
7633
|
+
}
|
|
7634
|
+
}
|
|
7635
|
+
};
|
|
7636
|
+
LocalCodexAppServerSupervisor = class {
|
|
7637
|
+
processBaseDirectory;
|
|
7638
|
+
environment;
|
|
7639
|
+
nativeStoreIdentitySeed;
|
|
7640
|
+
handlers;
|
|
7641
|
+
allocateProcessGeneration;
|
|
7642
|
+
capability;
|
|
7643
|
+
client = {};
|
|
7644
|
+
quarantinePromise;
|
|
7645
|
+
startPromise;
|
|
7646
|
+
constructor(processBaseDirectory, environment, nativeStoreIdentitySeed, handlers, allocateProcessGeneration) {
|
|
7647
|
+
this.processBaseDirectory = processBaseDirectory;
|
|
7648
|
+
this.environment = environment;
|
|
7649
|
+
this.nativeStoreIdentitySeed = nativeStoreIdentitySeed;
|
|
7650
|
+
this.handlers = handlers;
|
|
7651
|
+
this.allocateProcessGeneration = allocateProcessGeneration;
|
|
7652
|
+
this.capability = {
|
|
7653
|
+
appServerStatus: LocalCodexComponentStatusWire.Unknown,
|
|
7654
|
+
codexAuthStatus: LocalCodexComponentStatusWire.Unknown,
|
|
7655
|
+
codexBinaryStatus: LocalCodexComponentStatusWire.Unknown,
|
|
7656
|
+
nativeStoreIdentity: digestOpaque(`${nativeStoreIdentitySeed}\0${environment.CODEX_HOME ?? `${environment.HOME ?? processBaseDirectory}/.codex`}`),
|
|
7657
|
+
processGeneration: 0
|
|
7658
|
+
};
|
|
7659
|
+
}
|
|
7660
|
+
status() {
|
|
7661
|
+
return { ...this.capability };
|
|
7662
|
+
}
|
|
7663
|
+
currentClient() {
|
|
7664
|
+
return this.client;
|
|
7665
|
+
}
|
|
7666
|
+
async ensureStarted() {
|
|
7667
|
+
await this.quarantinePromise;
|
|
7668
|
+
if (this.client.value !== void 0 && !this.client.value.isClosed()) {
|
|
7669
|
+
return this.client.value;
|
|
7670
|
+
}
|
|
7671
|
+
if (this.startPromise === void 0) {
|
|
7672
|
+
this.startPromise = this.start().finally(() => {
|
|
7673
|
+
this.startPromise = void 0;
|
|
7674
|
+
});
|
|
7675
|
+
}
|
|
7676
|
+
return await this.startPromise;
|
|
7677
|
+
}
|
|
7678
|
+
markProcessLost(processGeneration) {
|
|
7679
|
+
if (this.capability.processGeneration !== processGeneration) {
|
|
7680
|
+
return false;
|
|
7681
|
+
}
|
|
7682
|
+
this.client = {};
|
|
7683
|
+
this.capability = {
|
|
7684
|
+
...this.capability,
|
|
7685
|
+
appServerStatus: LocalCodexComponentStatusWire.Error
|
|
7686
|
+
};
|
|
7687
|
+
return true;
|
|
7688
|
+
}
|
|
7689
|
+
async stop() {
|
|
7690
|
+
await this.client.value?.stop();
|
|
7691
|
+
this.client = {};
|
|
7692
|
+
}
|
|
7693
|
+
async quarantineCurrentProcess() {
|
|
7694
|
+
if (this.quarantinePromise !== void 0) {
|
|
7695
|
+
await this.quarantinePromise;
|
|
7696
|
+
return;
|
|
7697
|
+
}
|
|
7698
|
+
const client = this.client.value;
|
|
7699
|
+
this.client = {};
|
|
7700
|
+
this.capability = {
|
|
7701
|
+
...this.capability,
|
|
7702
|
+
appServerStatus: LocalCodexComponentStatusWire.Error
|
|
7703
|
+
};
|
|
7704
|
+
const operation = (async () => {
|
|
7705
|
+
await client?.stop();
|
|
7706
|
+
})();
|
|
7707
|
+
this.quarantinePromise = operation;
|
|
7708
|
+
try {
|
|
7709
|
+
await operation;
|
|
7710
|
+
} finally {
|
|
7711
|
+
if (this.quarantinePromise === operation) {
|
|
7712
|
+
this.quarantinePromise = void 0;
|
|
7713
|
+
}
|
|
7714
|
+
}
|
|
7715
|
+
}
|
|
7716
|
+
async start() {
|
|
7717
|
+
const processGeneration = await this.allocateProcessGeneration();
|
|
7718
|
+
try {
|
|
7719
|
+
const started = await AppServerClient.start({
|
|
7720
|
+
environment: this.environment,
|
|
7721
|
+
handlers: this.handlers,
|
|
7722
|
+
nativeStoreIdentitySeed: this.nativeStoreIdentitySeed,
|
|
7723
|
+
processBaseDirectory: this.processBaseDirectory,
|
|
7724
|
+
processGeneration
|
|
7725
|
+
});
|
|
7726
|
+
this.capability = started.capability;
|
|
7727
|
+
this.client = { value: started.client };
|
|
7728
|
+
return started.client;
|
|
7729
|
+
} catch (error) {
|
|
7730
|
+
const missing = error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
7731
|
+
this.capability = {
|
|
7732
|
+
...this.capability,
|
|
7733
|
+
appServerStatus: missing ? LocalCodexComponentStatusWire.Missing : LocalCodexComponentStatusWire.Error,
|
|
7734
|
+
codexBinaryStatus: missing ? LocalCodexComponentStatusWire.Missing : LocalCodexComponentStatusWire.Error,
|
|
7735
|
+
processGeneration
|
|
7736
|
+
};
|
|
7737
|
+
throw error;
|
|
7738
|
+
}
|
|
7739
|
+
}
|
|
7740
|
+
};
|
|
7741
|
+
}
|
|
7742
|
+
});
|
|
7743
|
+
|
|
7744
|
+
// ../machine-connector/dist/runtime/local-codex-runtime/durable-attempt.js
|
|
7745
|
+
function assertCompatibleClaim(persisted, connectionId, claim) {
|
|
7746
|
+
if (persisted.connectionId !== connectionId || persisted.claim.attemptId !== claim.attemptId || persisted.claim.attemptGeneration !== claim.attemptGeneration || persisted.claim.conversationId !== claim.conversationId || persisted.claim.turnId !== claim.turnId || persisted.claim.expectedNativeStoreIdentity !== claim.expectedNativeStoreIdentity) {
|
|
7747
|
+
throw new Error(`Local Codex Runtime attempt ${claim.attemptId} conflicts with its durable spool`);
|
|
7748
|
+
}
|
|
7749
|
+
if (persisted.phase !== LocalCodexAttemptPhase.Claimed && (persisted.claim.leaseToken !== claim.leaseToken || persisted.claim.runToken !== claim.runToken)) {
|
|
7750
|
+
throw new Error(`Running Local Codex Runtime attempt ${claim.attemptId} changed its fence`);
|
|
7751
|
+
}
|
|
7752
|
+
}
|
|
7753
|
+
function boundedPayload(kind, payload) {
|
|
7754
|
+
const serialized = Buffer.from(JSON.stringify(payload), "utf8");
|
|
7755
|
+
if (serialized.length <= maximumEventBytes) {
|
|
7756
|
+
return payload;
|
|
7757
|
+
}
|
|
7758
|
+
return {
|
|
7759
|
+
kind,
|
|
7760
|
+
originalBytes: serialized.length,
|
|
7761
|
+
preview: serialized.subarray(0, maximumEventBytes).toString("utf8"),
|
|
7762
|
+
truncated: true
|
|
7763
|
+
};
|
|
7764
|
+
}
|
|
7765
|
+
var import_node_crypto7, maximumEventBytes, maximumSpoolBytes, DurableLocalCodexAttempt;
|
|
7766
|
+
var init_durable_attempt = __esm({
|
|
7767
|
+
"../machine-connector/dist/runtime/local-codex-runtime/durable-attempt.js"() {
|
|
7768
|
+
"use strict";
|
|
7769
|
+
init_cjs_shims();
|
|
7770
|
+
import_node_crypto7 = require("crypto");
|
|
7771
|
+
init_contracts2();
|
|
7772
|
+
maximumEventBytes = 512e3;
|
|
7773
|
+
maximumSpoolBytes = 64e6;
|
|
7774
|
+
DurableLocalCodexAttempt = class _DurableLocalCodexAttempt {
|
|
7775
|
+
store;
|
|
7776
|
+
state;
|
|
7777
|
+
mutationQueue = Promise.resolve();
|
|
7778
|
+
constructor(store, state) {
|
|
7779
|
+
this.store = store;
|
|
7780
|
+
this.state = state;
|
|
7781
|
+
}
|
|
7782
|
+
static async create(store, connectionId, connectorInstanceId, claim) {
|
|
7783
|
+
const persisted = (await store.readLocalCodexAttempt(claim.attemptId)).value;
|
|
7784
|
+
if (persisted !== void 0) {
|
|
7785
|
+
assertCompatibleClaim(persisted, connectionId, claim);
|
|
7786
|
+
if (persisted.phase === LocalCodexAttemptPhase.Claimed) {
|
|
7787
|
+
persisted.claim = claim;
|
|
7788
|
+
persisted.connectorInstanceId = connectorInstanceId;
|
|
7789
|
+
persisted.acknowledgedSequence = claim.lastAcknowledgedEventSequence;
|
|
7790
|
+
persisted.nextSequence = Math.max(persisted.nextSequence, claim.lastAcknowledgedEventSequence + 1);
|
|
7791
|
+
persisted.events = persisted.events.filter((event2) => event2.sequence > claim.lastAcknowledgedEventSequence);
|
|
7792
|
+
persisted.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7793
|
+
await store.writeLocalCodexAttempt(persisted);
|
|
7794
|
+
}
|
|
7795
|
+
return new _DurableLocalCodexAttempt(store, persisted);
|
|
7796
|
+
}
|
|
7797
|
+
const state = {
|
|
7798
|
+
acknowledgedSequence: claim.lastAcknowledgedEventSequence,
|
|
7799
|
+
appliedControls: [],
|
|
7800
|
+
claim,
|
|
7801
|
+
connectionId,
|
|
7802
|
+
connectorInstanceId,
|
|
7803
|
+
events: [],
|
|
7804
|
+
interactions: [],
|
|
7805
|
+
nextSequence: claim.lastAcknowledgedEventSequence + 1,
|
|
7806
|
+
phase: LocalCodexAttemptPhase.Claimed,
|
|
7807
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
7808
|
+
};
|
|
7809
|
+
await store.writeLocalCodexAttempt(state);
|
|
7810
|
+
return new _DurableLocalCodexAttempt(store, state);
|
|
7811
|
+
}
|
|
7812
|
+
static fromPersisted(store, state) {
|
|
7813
|
+
return new _DurableLocalCodexAttempt(store, state);
|
|
7814
|
+
}
|
|
7815
|
+
snapshot() {
|
|
7816
|
+
return structuredClone(this.state);
|
|
7817
|
+
}
|
|
7818
|
+
async markRunning(nativeThreadId, nativeTurnId) {
|
|
7819
|
+
await this.mutate(async () => {
|
|
7820
|
+
this.state.nativeThreadId = nativeThreadId;
|
|
7821
|
+
this.state.nativeTurnId = nativeTurnId;
|
|
7822
|
+
this.state.phase = LocalCodexAttemptPhase.Running;
|
|
7823
|
+
await this.persist();
|
|
7824
|
+
});
|
|
7825
|
+
}
|
|
7826
|
+
async markThreadPrepared(nativeThreadId) {
|
|
7827
|
+
await this.mutate(async () => {
|
|
7828
|
+
if (this.state.nativeThreadId !== void 0 && this.state.nativeThreadId !== nativeThreadId) {
|
|
7829
|
+
throw new Error("Local Codex native thread changed before turn acceptance");
|
|
7830
|
+
}
|
|
7831
|
+
this.state.nativeThreadId = nativeThreadId;
|
|
7832
|
+
await this.persist();
|
|
7833
|
+
});
|
|
7834
|
+
}
|
|
7835
|
+
async appendEvent(kind, payload, correlation = {}, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
7836
|
+
const holder = {};
|
|
7837
|
+
await this.mutate(async () => {
|
|
7838
|
+
const safePayload = boundedPayload(kind, payload);
|
|
7839
|
+
const event2 = {
|
|
7840
|
+
eventId: (0, import_node_crypto7.randomUUID)(),
|
|
7841
|
+
kind,
|
|
7842
|
+
occurredAt,
|
|
7843
|
+
payload: safePayload,
|
|
7844
|
+
redactionVersion: localCodexRuntimeEventRedactionVersion,
|
|
7845
|
+
schemaVersion: localCodexRuntimeEventSchemaVersion,
|
|
7846
|
+
sequence: this.state.nextSequence,
|
|
7847
|
+
...correlation.nativeItemId ? { nativeItemId: correlation.nativeItemId } : {},
|
|
7848
|
+
...correlation.nativeThreadId ? { nativeThreadId: correlation.nativeThreadId } : {},
|
|
7849
|
+
...correlation.nativeTurnId ? { nativeTurnId: correlation.nativeTurnId } : {},
|
|
7850
|
+
...correlation.requestId ? { requestId: correlation.requestId } : {}
|
|
7851
|
+
};
|
|
7852
|
+
const pendingBytes = Buffer.byteLength(JSON.stringify([...this.state.events, event2]), "utf8");
|
|
7853
|
+
if (pendingBytes > maximumSpoolBytes) {
|
|
7854
|
+
throw new Error("Local Codex Runtime spool limit exceeded");
|
|
7855
|
+
}
|
|
7856
|
+
this.state.events.push(event2);
|
|
7857
|
+
this.state.nextSequence += 1;
|
|
7858
|
+
holder.value = event2;
|
|
7859
|
+
await this.persist();
|
|
7860
|
+
});
|
|
7861
|
+
if (holder.value === void 0) {
|
|
7862
|
+
throw new Error("Local Codex Runtime event was not persisted");
|
|
7863
|
+
}
|
|
7864
|
+
return structuredClone(holder.value);
|
|
7865
|
+
}
|
|
7866
|
+
pendingEvents() {
|
|
7867
|
+
return structuredClone(this.state.events.filter((event2) => event2.sequence > this.state.acknowledgedSequence));
|
|
7868
|
+
}
|
|
7869
|
+
async acknowledgeEvents(sequence) {
|
|
7870
|
+
await this.mutate(async () => {
|
|
7871
|
+
if (!Number.isSafeInteger(sequence) || sequence < this.state.acknowledgedSequence || sequence >= this.state.nextSequence) {
|
|
7872
|
+
throw new Error(`Invalid Local Codex Runtime ACK ${sequence}`);
|
|
7873
|
+
}
|
|
7874
|
+
this.state.acknowledgedSequence = sequence;
|
|
7875
|
+
this.state.events = this.state.events.filter((event2) => event2.sequence > sequence);
|
|
7876
|
+
await this.persist();
|
|
7877
|
+
});
|
|
7878
|
+
}
|
|
7879
|
+
async recordInteraction(interaction) {
|
|
7880
|
+
await this.mutate(async () => {
|
|
7881
|
+
if (this.state.interactions.some((candidate) => candidate.requestId === interaction.requestId)) {
|
|
7882
|
+
return;
|
|
7883
|
+
}
|
|
7884
|
+
this.state.interactions.push(interaction);
|
|
7885
|
+
await this.persist();
|
|
7886
|
+
});
|
|
7887
|
+
}
|
|
7888
|
+
pendingInteraction(requestId) {
|
|
7889
|
+
const value = this.state.interactions.find((candidate) => candidate.requestId === requestId && candidate.resolvedAt === void 0);
|
|
7890
|
+
return value === void 0 ? {} : { value: structuredClone(value) };
|
|
7891
|
+
}
|
|
7892
|
+
async resolveInteraction(requestId) {
|
|
7893
|
+
await this.mutate(async () => {
|
|
7894
|
+
const interaction = this.state.interactions.find((candidate) => candidate.requestId === requestId);
|
|
7895
|
+
if (interaction === void 0) {
|
|
7896
|
+
throw new Error(`Unknown Local Codex interaction ${requestId}`);
|
|
7897
|
+
}
|
|
7898
|
+
interaction.resolvedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7899
|
+
await this.persist();
|
|
7900
|
+
});
|
|
7901
|
+
}
|
|
7902
|
+
async recordControl(controlId) {
|
|
7903
|
+
await this.mutate(async () => {
|
|
7904
|
+
const existing = this.state.appliedControls.find((control) => control.controlId === controlId);
|
|
7905
|
+
if (existing !== void 0) {
|
|
7906
|
+
return;
|
|
7907
|
+
}
|
|
7908
|
+
this.state.appliedControls.push({
|
|
7909
|
+
controlId,
|
|
7910
|
+
phase: LocalCodexControlApplyPhase.Recorded,
|
|
7911
|
+
recordedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
7912
|
+
});
|
|
7913
|
+
await this.persist();
|
|
7914
|
+
});
|
|
7915
|
+
}
|
|
7916
|
+
appliedControlOutcome(controlId) {
|
|
7917
|
+
const control = this.state.appliedControls.find((candidate) => candidate.controlId === controlId && candidate.phase === LocalCodexControlApplyPhase.Applied);
|
|
7918
|
+
return control?.outcome === void 0 ? {} : { value: control.outcome };
|
|
7919
|
+
}
|
|
7920
|
+
async markControlApplied(controlId, outcome) {
|
|
7921
|
+
await this.mutate(async () => {
|
|
7922
|
+
const control = this.state.appliedControls.find((candidate) => candidate.controlId === controlId);
|
|
7923
|
+
if (control === void 0) {
|
|
7924
|
+
throw new Error(`Unknown Local Codex control ${controlId}`);
|
|
7925
|
+
}
|
|
7926
|
+
control.outcome = outcome;
|
|
7927
|
+
control.phase = LocalCodexControlApplyPhase.Applied;
|
|
7928
|
+
await this.persist();
|
|
7929
|
+
});
|
|
7930
|
+
}
|
|
7931
|
+
async markTerminal(result) {
|
|
7932
|
+
await this.mutate(async () => {
|
|
7933
|
+
this.state.finalStatus = result.status;
|
|
7934
|
+
this.state.finalSequence = result.finalSequence;
|
|
7935
|
+
this.state.finalErrorCode = result.errorCode;
|
|
7936
|
+
this.state.finalErrorMessage = result.errorMessage;
|
|
7937
|
+
this.state.phase = LocalCodexAttemptPhase.TerminalPendingUpload;
|
|
7938
|
+
await this.persist();
|
|
7939
|
+
});
|
|
7940
|
+
}
|
|
7941
|
+
async markUploaded() {
|
|
7942
|
+
await this.mutate(async () => {
|
|
7943
|
+
this.state.phase = LocalCodexAttemptPhase.Uploaded;
|
|
7944
|
+
await this.persist();
|
|
7945
|
+
});
|
|
7946
|
+
}
|
|
7947
|
+
async mutate(action) {
|
|
7948
|
+
const operation = this.mutationQueue.then(action);
|
|
7949
|
+
this.mutationQueue = operation.catch(() => void 0);
|
|
7950
|
+
await operation;
|
|
7951
|
+
}
|
|
7952
|
+
async persist() {
|
|
7953
|
+
this.state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7954
|
+
await this.store.writeLocalCodexAttempt(this.state);
|
|
7955
|
+
}
|
|
7956
|
+
};
|
|
7957
|
+
}
|
|
7958
|
+
});
|
|
7959
|
+
|
|
7960
|
+
// ../machine-connector/dist/runtime/local-codex-runtime/event-normalizer.js
|
|
7961
|
+
function normalizeAppServerNotification(message, canonicalRoot) {
|
|
7962
|
+
const method = message.method;
|
|
7963
|
+
if (method === void 0) {
|
|
7964
|
+
return {};
|
|
7965
|
+
}
|
|
7966
|
+
const params = recordValue(message.params);
|
|
7967
|
+
const correlation = eventCorrelation(params);
|
|
7968
|
+
if (method === "thread/started") {
|
|
7969
|
+
const thread = recordValue(params.thread);
|
|
7970
|
+
return {
|
|
7971
|
+
value: {
|
|
7972
|
+
correlation: {
|
|
7973
|
+
...correlation,
|
|
7974
|
+
nativeThreadId: optionalString(thread.id).value
|
|
7975
|
+
},
|
|
7976
|
+
kind: "thread_started",
|
|
7977
|
+
payload: {}
|
|
7978
|
+
}
|
|
7979
|
+
};
|
|
7980
|
+
}
|
|
7981
|
+
if (method === "thread/name/updated") {
|
|
7982
|
+
const title = optionalString(params.threadName).value;
|
|
7983
|
+
if (title === void 0) {
|
|
7984
|
+
return {};
|
|
7985
|
+
}
|
|
7986
|
+
return {
|
|
7987
|
+
value: {
|
|
7988
|
+
correlation,
|
|
7989
|
+
kind: "thread_title_updated",
|
|
7990
|
+
payload: { title }
|
|
7991
|
+
}
|
|
7992
|
+
};
|
|
7993
|
+
}
|
|
7994
|
+
if (method === "turn/started") {
|
|
7995
|
+
const turn = recordValue(params.turn);
|
|
7996
|
+
return {
|
|
7997
|
+
value: {
|
|
7998
|
+
correlation: {
|
|
7999
|
+
...correlation,
|
|
8000
|
+
nativeTurnId: optionalString(turn.id).value ?? correlation.nativeTurnId
|
|
8001
|
+
},
|
|
8002
|
+
kind: "turn_started",
|
|
8003
|
+
payload: { status: turn.status }
|
|
8004
|
+
}
|
|
8005
|
+
};
|
|
8006
|
+
}
|
|
8007
|
+
if (method === "turn/completed") {
|
|
8008
|
+
const turn = recordValue(params.turn);
|
|
8009
|
+
const terminalStatus = terminalStatusFor(turn.status);
|
|
8010
|
+
return {
|
|
8011
|
+
value: {
|
|
8012
|
+
correlation: {
|
|
8013
|
+
...correlation,
|
|
8014
|
+
nativeTurnId: optionalString(turn.id).value ?? correlation.nativeTurnId
|
|
8015
|
+
},
|
|
8016
|
+
kind: terminalStatus === LocalCodexTurnStatusWire.Succeeded ? "turn_completed" : "turn_failed",
|
|
8017
|
+
payload: {
|
|
8018
|
+
error: safeTurnError(turn.error),
|
|
8019
|
+
status: turn.status
|
|
8020
|
+
},
|
|
8021
|
+
terminalStatus
|
|
8022
|
+
}
|
|
8023
|
+
};
|
|
8024
|
+
}
|
|
8025
|
+
if (method === "item/agentMessage/delta") {
|
|
8026
|
+
return event("assistant_message_delta", { delta: params.delta }, correlation, canonicalRoot);
|
|
8027
|
+
}
|
|
8028
|
+
if (method === "item/reasoning/summaryTextDelta") {
|
|
8029
|
+
return event("reasoning_summary_delta", { delta: params.delta, summaryIndex: params.summaryIndex }, correlation, canonicalRoot);
|
|
8030
|
+
}
|
|
8031
|
+
if (method === "item/commandExecution/outputDelta" || method === "command/exec/outputDelta" || method === "process/outputDelta") {
|
|
8032
|
+
return event("command_output", { delta: params.delta }, correlation, canonicalRoot);
|
|
8033
|
+
}
|
|
8034
|
+
if (method === "item/fileChange/outputDelta") {
|
|
8035
|
+
return event("file_change_started", { delta: params.delta }, correlation, canonicalRoot);
|
|
8036
|
+
}
|
|
8037
|
+
if (method === "item/fileChange/patchUpdated") {
|
|
8038
|
+
return event("file_change_started", { changes: params.changes }, correlation, canonicalRoot);
|
|
8039
|
+
}
|
|
8040
|
+
if (method === "thread/tokenUsage/updated") {
|
|
8041
|
+
return event("usage_updated", { tokenUsage: params.tokenUsage }, correlation, canonicalRoot);
|
|
8042
|
+
}
|
|
8043
|
+
if (method === "item/started" || method === "item/completed") {
|
|
8044
|
+
return normalizeItem(recordValue(params.item), method === "item/completed", correlation, canonicalRoot);
|
|
8045
|
+
}
|
|
8046
|
+
if (method === "item/mcpToolCall/progress") {
|
|
8047
|
+
return event("tool_started", { message: params.message }, correlation, canonicalRoot);
|
|
8048
|
+
}
|
|
8049
|
+
if (method === "error" || method === "warning") {
|
|
8050
|
+
return event("runtime_error", sanitizeRecord(params, canonicalRoot), correlation, canonicalRoot);
|
|
8051
|
+
}
|
|
8052
|
+
return {};
|
|
8053
|
+
}
|
|
8054
|
+
function sanitizeAppServerPayload(value, canonicalRoot) {
|
|
8055
|
+
return sanitizeRecord(recordValue(value), canonicalRoot);
|
|
8056
|
+
}
|
|
8057
|
+
function normalizeItem(item, completed, baseCorrelation, canonicalRoot) {
|
|
8058
|
+
const itemType = optionalString(item.type).value;
|
|
8059
|
+
const correlation = {
|
|
8060
|
+
...baseCorrelation,
|
|
8061
|
+
nativeItemId: optionalString(item.id).value ?? baseCorrelation.nativeItemId
|
|
8062
|
+
};
|
|
8063
|
+
if (itemType === "userMessage") {
|
|
8064
|
+
const clientMessageId = optionalString(item.clientId).value;
|
|
8065
|
+
if (!completed || clientMessageId === void 0) {
|
|
8066
|
+
return {};
|
|
8067
|
+
}
|
|
8068
|
+
return event("user_message", {
|
|
8069
|
+
clientMessageId,
|
|
8070
|
+
inputItems: userMessageInputItems(item.content)
|
|
8071
|
+
}, correlation, canonicalRoot);
|
|
8072
|
+
}
|
|
8073
|
+
if (itemType === "agentMessage") {
|
|
8074
|
+
return event(completed ? "assistant_message_completed" : "assistant_message_delta", completed ? { text: item.text, phase: item.phase } : {}, correlation, canonicalRoot);
|
|
8075
|
+
}
|
|
8076
|
+
if (itemType === "reasoning") {
|
|
8077
|
+
return event(completed ? "reasoning_summary_completed" : "reasoning_summary_delta", { summary: safeStringArray(item.summary) }, correlation, canonicalRoot);
|
|
8078
|
+
}
|
|
8079
|
+
if (itemType === "commandExecution") {
|
|
8080
|
+
return event(completed ? "command_completed" : "command_started", {
|
|
8081
|
+
command: item.command,
|
|
8082
|
+
cwd: item.cwd,
|
|
8083
|
+
durationMs: item.durationMs,
|
|
8084
|
+
exitCode: item.exitCode,
|
|
8085
|
+
output: completed ? item.aggregatedOutput : void 0,
|
|
8086
|
+
status: item.status
|
|
8087
|
+
}, correlation, canonicalRoot);
|
|
8088
|
+
}
|
|
8089
|
+
if (itemType === "fileChange") {
|
|
8090
|
+
return event(completed ? "file_change_completed" : "file_change_started", { changes: item.changes, status: item.status }, correlation, canonicalRoot);
|
|
8091
|
+
}
|
|
8092
|
+
if (itemType === "mcpToolCall" || itemType === "dynamicToolCall" || itemType === "collabAgentToolCall" || itemType === "webSearch" || itemType === "imageGeneration" || itemType === "imageView") {
|
|
8093
|
+
return event(completed ? "tool_completed" : "tool_started", sanitizeThreadItem(item), correlation, canonicalRoot);
|
|
8094
|
+
}
|
|
8095
|
+
return {};
|
|
8096
|
+
}
|
|
8097
|
+
function userMessageInputItems(value) {
|
|
8098
|
+
if (!Array.isArray(value)) {
|
|
8099
|
+
return [];
|
|
8100
|
+
}
|
|
8101
|
+
const result = [];
|
|
8102
|
+
for (const entry of value) {
|
|
8103
|
+
const content3 = recordValue(entry);
|
|
8104
|
+
const contentType = optionalString(content3.type).value;
|
|
8105
|
+
if (contentType === "text" || contentType === "inputText") {
|
|
8106
|
+
result.push({
|
|
8107
|
+
itemType: "text",
|
|
8108
|
+
payload: { text: optionalString(content3.text).value ?? "" }
|
|
8109
|
+
});
|
|
8110
|
+
} else if (contentType === "image") {
|
|
8111
|
+
result.push({
|
|
8112
|
+
itemType: "image",
|
|
8113
|
+
payload: { url: optionalString(content3.url).value ?? "" }
|
|
8114
|
+
});
|
|
8115
|
+
} else if (contentType === "localImage") {
|
|
8116
|
+
result.push({
|
|
8117
|
+
itemType: "local_image",
|
|
8118
|
+
payload: { path: optionalString(content3.path).value ?? "" }
|
|
8119
|
+
});
|
|
8120
|
+
}
|
|
8121
|
+
}
|
|
8122
|
+
return result;
|
|
8123
|
+
}
|
|
8124
|
+
function event(kind, payload, correlation, canonicalRoot) {
|
|
8125
|
+
return {
|
|
8126
|
+
value: {
|
|
8127
|
+
correlation,
|
|
8128
|
+
kind,
|
|
8129
|
+
payload: sanitizeRecord(payload, canonicalRoot)
|
|
8130
|
+
}
|
|
8131
|
+
};
|
|
8132
|
+
}
|
|
8133
|
+
function eventCorrelation(params) {
|
|
8134
|
+
const thread = recordValue(params.thread);
|
|
8135
|
+
const turn = recordValue(params.turn);
|
|
8136
|
+
const item = recordValue(params.item);
|
|
8137
|
+
return {
|
|
8138
|
+
nativeThreadId: optionalString(params.threadId).value ?? optionalString(thread.id).value,
|
|
8139
|
+
nativeTurnId: optionalString(params.turnId).value ?? optionalString(turn.id).value,
|
|
8140
|
+
nativeItemId: optionalString(params.itemId).value ?? optionalString(item.id).value
|
|
8141
|
+
};
|
|
8142
|
+
}
|
|
8143
|
+
function terminalStatusFor(value) {
|
|
8144
|
+
if (value === "completed") {
|
|
8145
|
+
return LocalCodexTurnStatusWire.Succeeded;
|
|
8146
|
+
}
|
|
8147
|
+
if (value === "interrupted") {
|
|
8148
|
+
return LocalCodexTurnStatusWire.Interrupted;
|
|
8149
|
+
}
|
|
8150
|
+
if (value === "cancelled") {
|
|
8151
|
+
return LocalCodexTurnStatusWire.Cancelled;
|
|
8152
|
+
}
|
|
8153
|
+
return LocalCodexTurnStatusWire.Failed;
|
|
8154
|
+
}
|
|
8155
|
+
function sanitizeThreadItem(item) {
|
|
8156
|
+
const safe = { ...item };
|
|
8157
|
+
delete safe.prompt;
|
|
8158
|
+
delete safe.agentsStates;
|
|
8159
|
+
return safe;
|
|
8160
|
+
}
|
|
8161
|
+
function safeTurnError(value) {
|
|
8162
|
+
const error = recordValue(value);
|
|
8163
|
+
return {
|
|
8164
|
+
message: optionalString(error.message).value
|
|
8165
|
+
};
|
|
8166
|
+
}
|
|
8167
|
+
function sanitizeRecord(value, canonicalRoot) {
|
|
8168
|
+
return recordValue(redactValue(value, canonicalRoot, "payload"));
|
|
8169
|
+
}
|
|
8170
|
+
function redactValue(value, canonicalRoot, fieldName) {
|
|
8171
|
+
if (isSensitiveField(fieldName)) {
|
|
8172
|
+
return "[redacted]";
|
|
8173
|
+
}
|
|
8174
|
+
if (typeof value === "string") {
|
|
8175
|
+
if (isPathField(fieldName)) {
|
|
8176
|
+
return redactPath(value, canonicalRoot);
|
|
8177
|
+
}
|
|
8178
|
+
return redactSensitiveString(value);
|
|
8179
|
+
}
|
|
8180
|
+
if (Array.isArray(value)) {
|
|
8181
|
+
return value.map((entry) => redactValue(entry, canonicalRoot, fieldName));
|
|
8182
|
+
}
|
|
8183
|
+
if (!isRecord3(value)) {
|
|
8184
|
+
return value;
|
|
8185
|
+
}
|
|
8186
|
+
const result = {};
|
|
8187
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
8188
|
+
result[key] = redactValue(entry, canonicalRoot, key);
|
|
8189
|
+
}
|
|
8190
|
+
return result;
|
|
8191
|
+
}
|
|
8192
|
+
function redactPath(value, canonicalRoot) {
|
|
8193
|
+
if (value === canonicalRoot) {
|
|
8194
|
+
return ".";
|
|
8195
|
+
}
|
|
8196
|
+
if (value.startsWith(`${canonicalRoot}${import_node_path9.sep}`)) {
|
|
8197
|
+
return (0, import_node_path9.relative)(canonicalRoot, value);
|
|
8198
|
+
}
|
|
8199
|
+
if ((0, import_node_path9.isAbsolute)(value) || /^[A-Za-z]:[\\/]/.test(value)) {
|
|
8200
|
+
return "[redacted-absolute-path]";
|
|
8201
|
+
}
|
|
8202
|
+
return value;
|
|
8203
|
+
}
|
|
8204
|
+
function isSensitiveField(fieldName) {
|
|
8205
|
+
const normalized = normalizeFieldName(fieldName);
|
|
8206
|
+
if (isUsageField(normalized)) {
|
|
8207
|
+
return false;
|
|
8208
|
+
}
|
|
8209
|
+
const words = normalized.split("_");
|
|
8210
|
+
if (words.some((word) => [
|
|
8211
|
+
"authorization",
|
|
8212
|
+
"cookie",
|
|
8213
|
+
"credential",
|
|
8214
|
+
"environment",
|
|
8215
|
+
"password",
|
|
8216
|
+
"secret",
|
|
8217
|
+
"token"
|
|
8218
|
+
].includes(word))) {
|
|
8219
|
+
return true;
|
|
8220
|
+
}
|
|
8221
|
+
return words.includes("key") && (words.includes("api") || words.includes("private"));
|
|
8222
|
+
}
|
|
8223
|
+
function isPathField(fieldName) {
|
|
8224
|
+
const normalized = normalizeFieldName(fieldName);
|
|
8225
|
+
return ["cwd", "directory", "file", "path", "root"].includes(normalized) || /_(?:cwd|directory|path|root)$/.test(normalized);
|
|
8226
|
+
}
|
|
8227
|
+
function isUsageField(value) {
|
|
8228
|
+
return value === "token_usage" || /^(?:(?:cached_)?input|completion|output|prompt|reasoning_output|total)_tokens?$/.test(value);
|
|
8229
|
+
}
|
|
8230
|
+
function normalizeFieldName(value) {
|
|
8231
|
+
return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
|
|
8232
|
+
}
|
|
8233
|
+
function redactSensitiveString(value) {
|
|
8234
|
+
return value.replace(/-----BEGIN [^-\r\n]*PRIVATE KEY-----[\s\S]*?-----END [^-\r\n]*PRIVATE KEY-----/g, "[redacted-private-key]").replace(/\b(authorization|proxy-authorization)\s*:\s*(?:bearer|basic)\s+[^\s,;]+/gi, "$1: [redacted]").replace(/\b(cookie|set-cookie)\s*:\s*[^\r\n]*/gi, "$1: [redacted]").replace(/\b((?:MOXT_API_KEY|[A-Z][A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|CREDENTIAL|PRIVATE_KEY)))\s*=\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/g, "$1=[redacted]").replace(/\b(?:sk|moxt)_[A-Za-z0-9_-]{16,}\b/g, "[redacted-api-key]");
|
|
8235
|
+
}
|
|
8236
|
+
function safeStringArray(value) {
|
|
8237
|
+
return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
|
|
8238
|
+
}
|
|
8239
|
+
function optionalString(value) {
|
|
8240
|
+
return typeof value === "string" ? { value } : {};
|
|
8241
|
+
}
|
|
8242
|
+
function recordValue(value) {
|
|
8243
|
+
return isRecord3(value) ? value : {};
|
|
8244
|
+
}
|
|
8245
|
+
function isRecord3(value) {
|
|
8246
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8247
|
+
}
|
|
8248
|
+
var import_node_path9;
|
|
8249
|
+
var init_event_normalizer = __esm({
|
|
8250
|
+
"../machine-connector/dist/runtime/local-codex-runtime/event-normalizer.js"() {
|
|
8251
|
+
"use strict";
|
|
8252
|
+
init_cjs_shims();
|
|
8253
|
+
import_node_path9 = require("path");
|
|
8254
|
+
init_contracts2();
|
|
8255
|
+
}
|
|
8256
|
+
});
|
|
8257
|
+
|
|
8258
|
+
// ../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js
|
|
8259
|
+
function createActiveAttempt(claim, durable, workingDirectory) {
|
|
8260
|
+
let resolveTerminal = (_value) => void 0;
|
|
8261
|
+
const terminal = new Promise((resolve9) => {
|
|
8262
|
+
resolveTerminal = resolve9;
|
|
8263
|
+
});
|
|
8264
|
+
let resolveFatal = (_error) => void 0;
|
|
8265
|
+
const fatal = new Promise((resolve9) => {
|
|
8266
|
+
resolveFatal = resolve9;
|
|
8267
|
+
});
|
|
8268
|
+
return {
|
|
8269
|
+
acceptedByAppServer: false,
|
|
8270
|
+
abortRequested: false,
|
|
8271
|
+
abortSent: false,
|
|
8272
|
+
claim,
|
|
8273
|
+
controlCursor: 0,
|
|
8274
|
+
durable,
|
|
8275
|
+
eventUploadScheduled: false,
|
|
8276
|
+
eventUploadQueue: Promise.resolve(),
|
|
8277
|
+
fatal,
|
|
8278
|
+
finished: new AbortController(),
|
|
8279
|
+
leaseDeadlineMilliseconds: parseLeaseDeadline(claim.leaseExpiresAt),
|
|
8280
|
+
nativeThreadId: durable.snapshot().nativeThreadId ?? claim.nativeThreadId,
|
|
8281
|
+
spoolQueue: Promise.resolve(),
|
|
8282
|
+
terminal,
|
|
8283
|
+
resolveFatal,
|
|
8284
|
+
resolveTerminal,
|
|
8285
|
+
workingDirectory
|
|
8286
|
+
};
|
|
8287
|
+
}
|
|
8288
|
+
function fenceFor(claim, connectorInstanceId) {
|
|
8289
|
+
return {
|
|
8290
|
+
attemptGeneration: claim.attemptGeneration,
|
|
8291
|
+
connectorInstanceId,
|
|
8292
|
+
leaseToken: claim.leaseToken,
|
|
8293
|
+
processGeneration: claim.processGeneration,
|
|
8294
|
+
protocolVersion: localCodexRuntimeProtocolVersion,
|
|
8295
|
+
runToken: claim.runToken
|
|
8296
|
+
};
|
|
8297
|
+
}
|
|
8298
|
+
function persistedFence(persisted) {
|
|
8299
|
+
return {
|
|
8300
|
+
attemptGeneration: persisted.claim.attemptGeneration,
|
|
8301
|
+
connectorInstanceId: persisted.connectorInstanceId,
|
|
8302
|
+
leaseToken: persisted.claim.leaseToken,
|
|
8303
|
+
processGeneration: persisted.claim.processGeneration,
|
|
8304
|
+
protocolVersion: localCodexRuntimeProtocolVersion,
|
|
8305
|
+
runToken: persisted.claim.runToken
|
|
8306
|
+
};
|
|
8307
|
+
}
|
|
8308
|
+
function requireThreadId(response) {
|
|
8309
|
+
const id = response.thread?.id;
|
|
8310
|
+
if (id === void 0 || id === "") {
|
|
8311
|
+
throw new AppServerProtocolError("Codex App Server did not return a native thread ID");
|
|
8312
|
+
}
|
|
8313
|
+
return id;
|
|
8314
|
+
}
|
|
8315
|
+
function requireTurnId(response) {
|
|
8316
|
+
const id = response.turn?.id;
|
|
8317
|
+
if (id === void 0 || id === "") {
|
|
8318
|
+
throw new AppServerProtocolError("Codex App Server did not return a native turn ID");
|
|
8319
|
+
}
|
|
8320
|
+
return id;
|
|
8321
|
+
}
|
|
8322
|
+
function toCodexInput(items) {
|
|
8323
|
+
return items.map((item) => {
|
|
8324
|
+
const payload = safeRecord(item.payload);
|
|
8325
|
+
if (item.itemType === "text") {
|
|
8326
|
+
return {
|
|
8327
|
+
type: "text",
|
|
8328
|
+
text: optionalString2(payload.text).value ?? "",
|
|
8329
|
+
text_elements: []
|
|
8330
|
+
};
|
|
8331
|
+
}
|
|
8332
|
+
if (item.itemType === "image") {
|
|
8333
|
+
return {
|
|
8334
|
+
type: "image",
|
|
8335
|
+
url: optionalString2(payload.url).value ?? ""
|
|
8336
|
+
};
|
|
8337
|
+
}
|
|
8338
|
+
if (item.itemType === "local_image") {
|
|
8339
|
+
return {
|
|
8340
|
+
type: "localImage",
|
|
8341
|
+
path: optionalString2(payload.path).value ?? ""
|
|
8342
|
+
};
|
|
8343
|
+
}
|
|
8344
|
+
throw new Error(`Unsupported Local Codex input ${item.itemType}`);
|
|
8345
|
+
});
|
|
8346
|
+
}
|
|
8347
|
+
function localCodexInputItems(value) {
|
|
8348
|
+
if (!Array.isArray(value)) {
|
|
8349
|
+
return [];
|
|
8350
|
+
}
|
|
8351
|
+
const inputItems = [];
|
|
8352
|
+
for (const candidate of value) {
|
|
8353
|
+
const item = safeRecord(candidate);
|
|
8354
|
+
const itemType = optionalString2(item.itemType).value;
|
|
8355
|
+
if (itemType === void 0) {
|
|
8356
|
+
continue;
|
|
8357
|
+
}
|
|
8358
|
+
inputItems.push({
|
|
8359
|
+
itemType,
|
|
8360
|
+
payload: safeRecord(item.payload)
|
|
8361
|
+
});
|
|
8362
|
+
}
|
|
8363
|
+
return inputItems;
|
|
8364
|
+
}
|
|
8365
|
+
function toSandboxPolicy(policy, workingDirectory) {
|
|
8366
|
+
if (policy === "danger-full-access") {
|
|
8367
|
+
return { type: "dangerFullAccess" };
|
|
8368
|
+
}
|
|
8369
|
+
if (policy === "workspace-write") {
|
|
8370
|
+
return {
|
|
8371
|
+
type: "workspaceWrite",
|
|
8372
|
+
excludeSlashTmp: false,
|
|
8373
|
+
excludeTmpdirEnvVar: false,
|
|
8374
|
+
networkAccess: false,
|
|
8375
|
+
writableRoots: [workingDirectory]
|
|
8376
|
+
};
|
|
8377
|
+
}
|
|
8378
|
+
return { type: "readOnly", networkAccess: false };
|
|
8379
|
+
}
|
|
8380
|
+
function interactionKindFor(method, params) {
|
|
8381
|
+
if (method === "item/commandExecution/requestApproval") {
|
|
8382
|
+
return {
|
|
8383
|
+
value: Object.keys(safeRecord(safeRecord(params).networkApprovalContext)).length > 0 ? "network_approval" : "command_approval"
|
|
8384
|
+
};
|
|
8385
|
+
}
|
|
8386
|
+
if (method === "item/fileChange/requestApproval") {
|
|
8387
|
+
return { value: "file_change_approval" };
|
|
8388
|
+
}
|
|
8389
|
+
if (method === "item/permissions/requestApproval") {
|
|
8390
|
+
return { value: "permissions_approval" };
|
|
8391
|
+
}
|
|
8392
|
+
if (method === "item/tool/requestUserInput") {
|
|
8393
|
+
return { value: "user_input" };
|
|
8394
|
+
}
|
|
8395
|
+
if (method === "mcpServer/elicitation/request") {
|
|
8396
|
+
return { value: "mcp_elicitation" };
|
|
8397
|
+
}
|
|
8398
|
+
if (method === "item/tool/call") {
|
|
8399
|
+
return { value: "dynamic_tool_call" };
|
|
8400
|
+
}
|
|
8401
|
+
return {};
|
|
8402
|
+
}
|
|
8403
|
+
function appServerInteractionResponse(interaction, response) {
|
|
8404
|
+
if (interaction.method !== "item/permissions/requestApproval") {
|
|
8405
|
+
return response;
|
|
8406
|
+
}
|
|
8407
|
+
const decision = optionalString2(response.decision).value;
|
|
8408
|
+
if (decision === "decline") {
|
|
8409
|
+
return { permissions: {}, scope: "turn" };
|
|
8410
|
+
}
|
|
8411
|
+
if (decision !== "accept") {
|
|
8412
|
+
throw new Error("Local Codex permission response has no valid decision");
|
|
8413
|
+
}
|
|
8414
|
+
if (interaction.requestPayload === void 0) {
|
|
8415
|
+
throw new Error("Local Codex permission request payload is unavailable locally");
|
|
8416
|
+
}
|
|
8417
|
+
const requested = safeRecord(interaction.requestPayload.permissions);
|
|
8418
|
+
const permissions = {};
|
|
8419
|
+
if (requested.network !== void 0 && requested.network !== null) {
|
|
8420
|
+
permissions.network = requested.network;
|
|
8421
|
+
}
|
|
8422
|
+
if (requested.fileSystem !== void 0 && requested.fileSystem !== null) {
|
|
8423
|
+
permissions.fileSystem = requested.fileSystem;
|
|
8424
|
+
}
|
|
8425
|
+
return { permissions, scope: "turn" };
|
|
8426
|
+
}
|
|
8427
|
+
function firstTextInput(claim) {
|
|
8428
|
+
for (const item of claim.inputItems) {
|
|
8429
|
+
if (item.itemType === "text") {
|
|
8430
|
+
const text3 = safeRecord(item.payload).text;
|
|
8431
|
+
if (typeof text3 === "string") {
|
|
8432
|
+
return { value: text3 };
|
|
8433
|
+
}
|
|
8434
|
+
}
|
|
8435
|
+
}
|
|
8436
|
+
return {};
|
|
8437
|
+
}
|
|
8438
|
+
function terminalErrorMessage(payload) {
|
|
8439
|
+
const message = safeRecord(payload.error).message;
|
|
8440
|
+
return typeof message === "string" ? { value: message } : {};
|
|
8441
|
+
}
|
|
8442
|
+
function safeRecord(value) {
|
|
8443
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
8444
|
+
}
|
|
8445
|
+
function optionalString2(value) {
|
|
8446
|
+
return typeof value === "string" ? { value } : {};
|
|
8447
|
+
}
|
|
8448
|
+
function rpcIdentifier2(value) {
|
|
8449
|
+
if (typeof value === "string") {
|
|
8450
|
+
return { value };
|
|
8451
|
+
}
|
|
8452
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
8453
|
+
return { value: String(value) };
|
|
8454
|
+
}
|
|
8455
|
+
return {};
|
|
8456
|
+
}
|
|
8457
|
+
function errorMessage2(error) {
|
|
8458
|
+
return error instanceof Error ? error.message : String(error);
|
|
8459
|
+
}
|
|
8460
|
+
async function probeExecutable(executable, environment) {
|
|
8461
|
+
const child = (0, import_node_child_process4.spawn)(executable, ["--version"], {
|
|
8462
|
+
env: { ...environment },
|
|
8463
|
+
shell: false,
|
|
8464
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
8465
|
+
windowsHide: true
|
|
8466
|
+
});
|
|
8467
|
+
const output = [];
|
|
8468
|
+
child.stdout?.on("data", (chunk) => output.push(chunk));
|
|
8469
|
+
try {
|
|
8470
|
+
const code = await new Promise((resolve9, reject) => {
|
|
8471
|
+
const timeout = setTimeout(() => {
|
|
8472
|
+
child.kill("SIGTERM");
|
|
8473
|
+
reject(new Error("Executable probe timed out"));
|
|
8474
|
+
}, executableProbeTimeoutMilliseconds);
|
|
8475
|
+
timeout.unref();
|
|
8476
|
+
child.once("error", (error) => {
|
|
8477
|
+
clearTimeout(timeout);
|
|
8478
|
+
reject(error);
|
|
8479
|
+
});
|
|
8480
|
+
child.once("close", (exitCode) => {
|
|
8481
|
+
clearTimeout(timeout);
|
|
8482
|
+
resolve9(exitCode ?? 1);
|
|
8483
|
+
});
|
|
8484
|
+
});
|
|
8485
|
+
if (code !== 0) {
|
|
8486
|
+
return { status: LocalCodexComponentStatusWire.Error };
|
|
8487
|
+
}
|
|
8488
|
+
return {
|
|
8489
|
+
status: LocalCodexComponentStatusWire.Ready,
|
|
8490
|
+
version: Buffer.concat(output).toString("utf8").trim().slice(0, 64)
|
|
8491
|
+
};
|
|
8492
|
+
} catch (error) {
|
|
8493
|
+
const missing = error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
8494
|
+
return {
|
|
8495
|
+
status: missing ? LocalCodexComponentStatusWire.Missing : LocalCodexComponentStatusWire.Error
|
|
8496
|
+
};
|
|
8497
|
+
}
|
|
8498
|
+
}
|
|
8499
|
+
async function waitForAbort(signal, milliseconds) {
|
|
8500
|
+
if (signal.aborted) {
|
|
8501
|
+
return;
|
|
8502
|
+
}
|
|
8503
|
+
await new Promise((resolve9) => {
|
|
8504
|
+
const complete = () => {
|
|
8505
|
+
clearTimeout(timeout);
|
|
8506
|
+
signal.removeEventListener("abort", complete);
|
|
8507
|
+
resolve9();
|
|
8508
|
+
};
|
|
8509
|
+
const timeout = setTimeout(complete, milliseconds);
|
|
8510
|
+
timeout.unref();
|
|
8511
|
+
signal.addEventListener("abort", complete, { once: true });
|
|
8512
|
+
});
|
|
8513
|
+
}
|
|
8514
|
+
function parseLeaseDeadline(value) {
|
|
8515
|
+
const parsed = Date.parse(value);
|
|
8516
|
+
if (!Number.isFinite(parsed)) {
|
|
8517
|
+
throw new Error(`Invalid Local Codex lease expiry ${value}`);
|
|
8518
|
+
}
|
|
8519
|
+
return parsed;
|
|
8520
|
+
}
|
|
8521
|
+
var import_node_child_process4, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, LocalCodexRuntimeConnectionWorker;
|
|
8522
|
+
var init_runtime_worker = __esm({
|
|
8523
|
+
"../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
|
|
8524
|
+
"use strict";
|
|
8525
|
+
init_cjs_shims();
|
|
8526
|
+
import_node_child_process4 = require("child_process");
|
|
8527
|
+
init_process_executor();
|
|
8528
|
+
init_relay_client();
|
|
8529
|
+
init_app_server_client();
|
|
8530
|
+
init_contracts2();
|
|
8531
|
+
init_durable_attempt();
|
|
8532
|
+
init_event_normalizer();
|
|
8533
|
+
heartbeatIntervalMilliseconds = 2e4;
|
|
8534
|
+
claimRetryMilliseconds = 250;
|
|
8535
|
+
claimWaitSeconds = 25;
|
|
8536
|
+
eventUploadCoalesceMilliseconds = 500;
|
|
8537
|
+
eventUploadRetryMilliseconds = 1e3;
|
|
8538
|
+
leaseRenewIntervalMilliseconds = 1e4;
|
|
8539
|
+
leaseRenewRetryMilliseconds = 1e3;
|
|
8540
|
+
interactionTimeoutMilliseconds = 10 * 60 * 1e3;
|
|
8541
|
+
executableProbeTimeoutMilliseconds = 5e3;
|
|
8542
|
+
recoveryRetryMilliseconds = 1e3;
|
|
8543
|
+
ThreadUnavailableError = class extends Error {
|
|
8544
|
+
constructor(message) {
|
|
8545
|
+
super(message);
|
|
8546
|
+
this.name = "ThreadUnavailableError";
|
|
8547
|
+
}
|
|
8548
|
+
};
|
|
8549
|
+
LeaseLostError = class extends Error {
|
|
8550
|
+
constructor(message) {
|
|
8551
|
+
super(message);
|
|
8552
|
+
this.name = "LeaseLostError";
|
|
8553
|
+
}
|
|
8554
|
+
};
|
|
8555
|
+
SpoolPersistenceError = class extends Error {
|
|
8556
|
+
constructor(message, options) {
|
|
8557
|
+
super(message, options);
|
|
8558
|
+
this.name = "SpoolPersistenceError";
|
|
8559
|
+
}
|
|
8560
|
+
};
|
|
8561
|
+
UnknownTurnStartResultError = class extends Error {
|
|
8562
|
+
constructor(message, options) {
|
|
8563
|
+
super(message, options);
|
|
8564
|
+
this.name = "UnknownTurnStartResultError";
|
|
8565
|
+
}
|
|
8566
|
+
};
|
|
8567
|
+
LocalCodexRuntimeConnectionWorker = class {
|
|
8568
|
+
connection;
|
|
8569
|
+
relay;
|
|
8570
|
+
store;
|
|
8571
|
+
processPool;
|
|
8572
|
+
environment;
|
|
8573
|
+
connectorInstanceId;
|
|
8574
|
+
logger;
|
|
8575
|
+
active = {};
|
|
8576
|
+
configured = false;
|
|
8577
|
+
enabled = false;
|
|
8578
|
+
lifetimeAbort = new AbortController();
|
|
8579
|
+
registered = true;
|
|
8580
|
+
unrecoverableAttemptIds = /* @__PURE__ */ new Set();
|
|
8581
|
+
running;
|
|
8582
|
+
constructor(connection, relay, store, processPool, environment, connectorInstanceId, logger) {
|
|
8583
|
+
this.connection = connection;
|
|
8584
|
+
this.relay = relay;
|
|
8585
|
+
this.store = store;
|
|
8586
|
+
this.processPool = processPool;
|
|
8587
|
+
this.environment = environment;
|
|
8588
|
+
this.connectorInstanceId = connectorInstanceId;
|
|
8589
|
+
this.logger = logger;
|
|
8590
|
+
this.processPool.register(connection.connectionId, this);
|
|
8591
|
+
}
|
|
8592
|
+
async run() {
|
|
8593
|
+
if (this.running !== void 0) {
|
|
8594
|
+
return await this.running;
|
|
8595
|
+
}
|
|
8596
|
+
this.running = this.runLoops();
|
|
8597
|
+
return await this.running;
|
|
8598
|
+
}
|
|
8599
|
+
async stop() {
|
|
8600
|
+
this.revoke();
|
|
8601
|
+
await this.running;
|
|
8602
|
+
}
|
|
8603
|
+
revoke() {
|
|
8604
|
+
this.lifetimeAbort.abort();
|
|
8605
|
+
this.active.value?.finished.abort();
|
|
8606
|
+
}
|
|
8607
|
+
status() {
|
|
8608
|
+
return this.processPool.status();
|
|
8609
|
+
}
|
|
8610
|
+
async onNotification(message) {
|
|
8611
|
+
const active = this.active.value;
|
|
8612
|
+
if (active === void 0 || active.finished.signal.aborted) {
|
|
8613
|
+
return;
|
|
8614
|
+
}
|
|
8615
|
+
const normalized = normalizeAppServerNotification(message, active.workingDirectory).value;
|
|
8616
|
+
if (normalized === void 0) {
|
|
8617
|
+
return;
|
|
8618
|
+
}
|
|
8619
|
+
if (normalized.correlation.nativeThreadId !== void 0 && active.nativeThreadId !== void 0 && normalized.correlation.nativeThreadId !== active.nativeThreadId) {
|
|
8620
|
+
return;
|
|
8621
|
+
}
|
|
8622
|
+
const notificationTurnId = normalized.correlation.nativeTurnId;
|
|
8623
|
+
if (notificationTurnId !== void 0) {
|
|
8624
|
+
if (this.processPool.isRetiredTurn(notificationTurnId)) {
|
|
8625
|
+
return;
|
|
8626
|
+
}
|
|
8627
|
+
if (active.nativeTurnId === void 0) {
|
|
8628
|
+
if (normalized.kind !== "turn_started") {
|
|
8629
|
+
return;
|
|
8630
|
+
}
|
|
8631
|
+
active.nativeTurnId = notificationTurnId;
|
|
8632
|
+
} else if (notificationTurnId !== active.nativeTurnId) {
|
|
8633
|
+
return;
|
|
8634
|
+
}
|
|
8635
|
+
}
|
|
8636
|
+
void this.enqueueSpool(active, async () => {
|
|
8637
|
+
const persisted = await active.durable.appendEvent(normalized.kind, normalized.payload, normalized.correlation);
|
|
8638
|
+
if (normalized.correlation.nativeThreadId !== void 0 && active.nativeThreadId === void 0) {
|
|
8639
|
+
active.nativeThreadId = normalized.correlation.nativeThreadId;
|
|
8640
|
+
}
|
|
8641
|
+
if (normalized.terminalStatus !== void 0) {
|
|
8642
|
+
const terminal = {
|
|
8643
|
+
errorMessage: terminalErrorMessage(normalized.payload).value,
|
|
8644
|
+
finalSequence: persisted.sequence,
|
|
8645
|
+
status: normalized.terminalStatus
|
|
8646
|
+
};
|
|
8647
|
+
await active.durable.markTerminal(terminal);
|
|
8648
|
+
this.settleTerminal(active, terminal);
|
|
8649
|
+
}
|
|
8650
|
+
}).catch(() => void 0);
|
|
8651
|
+
void this.enqueueEventFlush(active).catch(() => void 0);
|
|
8652
|
+
}
|
|
8653
|
+
async onServerRequest(message) {
|
|
8654
|
+
const active = this.active.value;
|
|
8655
|
+
const client = this.processPool.currentClient().value;
|
|
8656
|
+
const requestId = rpcIdentifier2(message.id).value;
|
|
8657
|
+
if (active === void 0 || client === void 0 || requestId === void 0 || message.method === void 0) {
|
|
8658
|
+
if (client !== void 0 && message.id !== void 0) {
|
|
8659
|
+
await client.respondWithError(message.id, -32e3, "No owning Local Codex Runtime turn");
|
|
8660
|
+
}
|
|
8661
|
+
return;
|
|
8662
|
+
}
|
|
8663
|
+
const interactionKind = interactionKindFor(message.method, message.params).value;
|
|
8664
|
+
if (interactionKind === void 0) {
|
|
8665
|
+
await client.respondWithError(message.id, -32601, `Unsupported Local Codex interaction ${message.method}`);
|
|
8666
|
+
return;
|
|
8667
|
+
}
|
|
8668
|
+
const now = /* @__PURE__ */ new Date();
|
|
8669
|
+
const expiresAt = new Date(now.getTime() + interactionTimeoutMilliseconds).toISOString();
|
|
8670
|
+
await active.durable.recordInteraction({
|
|
8671
|
+
appServerRequestId: message.id,
|
|
8672
|
+
expiresAt,
|
|
8673
|
+
method: message.method,
|
|
8674
|
+
requestPayload: safeRecord(message.params),
|
|
8675
|
+
requestId
|
|
8676
|
+
});
|
|
8677
|
+
await this.enqueueSpool(active, async () => {
|
|
8678
|
+
await active.durable.appendEvent("interaction_requested", {
|
|
8679
|
+
expiresAt,
|
|
8680
|
+
interactionKind,
|
|
8681
|
+
request: sanitizeAppServerPayload(message.params, active.workingDirectory)
|
|
8682
|
+
}, {
|
|
8683
|
+
nativeThreadId: active.nativeThreadId,
|
|
8684
|
+
nativeTurnId: active.nativeTurnId,
|
|
8685
|
+
requestId
|
|
8686
|
+
}, now.toISOString());
|
|
8687
|
+
});
|
|
8688
|
+
await this.enqueueEventFlush(active);
|
|
8689
|
+
}
|
|
8690
|
+
async onProcessExit(error) {
|
|
8691
|
+
const active = this.active.value;
|
|
8692
|
+
if (active === void 0 || !active.acceptedByAppServer) {
|
|
8693
|
+
return;
|
|
8694
|
+
}
|
|
8695
|
+
await this.enqueueSpool(active, async () => {
|
|
8696
|
+
await active.durable.appendEvent("runtime_error", { message: error.message }, {
|
|
8697
|
+
nativeThreadId: active.nativeThreadId,
|
|
8698
|
+
nativeTurnId: active.nativeTurnId
|
|
8699
|
+
});
|
|
8700
|
+
const terminal = await active.durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
|
|
8701
|
+
nativeThreadId: active.nativeThreadId,
|
|
8702
|
+
nativeTurnId: active.nativeTurnId
|
|
8703
|
+
});
|
|
8704
|
+
const result = {
|
|
8705
|
+
errorCode: "runtime_lost",
|
|
8706
|
+
errorMessage: error.message,
|
|
8707
|
+
finalSequence: terminal.sequence,
|
|
8708
|
+
status: LocalCodexTurnStatusWire.RuntimeLost
|
|
8709
|
+
};
|
|
8710
|
+
await active.durable.markTerminal(result);
|
|
8711
|
+
this.settleTerminal(active, result);
|
|
8712
|
+
});
|
|
8713
|
+
}
|
|
8714
|
+
async runLoops() {
|
|
8715
|
+
try {
|
|
8716
|
+
await Promise.all([
|
|
8717
|
+
this.runHeartbeatLoop(),
|
|
8718
|
+
this.runClaimLoop(),
|
|
8719
|
+
this.runRecoveryLoop()
|
|
8720
|
+
]);
|
|
8721
|
+
} finally {
|
|
8722
|
+
this.active.value?.finished.abort();
|
|
8723
|
+
this.unregisterRoute();
|
|
8724
|
+
}
|
|
8725
|
+
}
|
|
8726
|
+
async runHeartbeatLoop() {
|
|
8727
|
+
while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
|
|
8728
|
+
try {
|
|
8729
|
+
await this.ensureCapability();
|
|
8730
|
+
const response = await this.sendHeartbeat();
|
|
8731
|
+
this.applyHeartbeatResponse(response);
|
|
8732
|
+
} catch (error) {
|
|
8733
|
+
if (!this.lifetimeAbort.signal.aborted) {
|
|
8734
|
+
await this.logger.error(`Local Codex Runtime heartbeat failed for connection ${this.connection.connectionId}`, error);
|
|
8735
|
+
}
|
|
8736
|
+
}
|
|
8737
|
+
await waitForAbort(this.lifetimeAbort.signal, heartbeatIntervalMilliseconds);
|
|
8738
|
+
}
|
|
8739
|
+
}
|
|
8740
|
+
async runClaimLoop() {
|
|
8741
|
+
while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
|
|
8742
|
+
if (!this.configured || !this.enabled || !this.runtimeReady()) {
|
|
8743
|
+
await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
|
|
8744
|
+
continue;
|
|
8745
|
+
}
|
|
8746
|
+
if (!this.processPool.tryAcquire(this.connection.connectionId)) {
|
|
8747
|
+
await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
|
|
8748
|
+
continue;
|
|
8749
|
+
}
|
|
8750
|
+
try {
|
|
8751
|
+
const capability = this.processPool.status();
|
|
8752
|
+
const response = await this.relay.claimCodexRuntime({
|
|
8753
|
+
connectorInstanceId: this.connectorInstanceId,
|
|
8754
|
+
nativeStoreIdentity: capability.nativeStoreIdentity,
|
|
8755
|
+
processGeneration: capability.processGeneration,
|
|
8756
|
+
protocolVersion: localCodexRuntimeProtocolVersion,
|
|
8757
|
+
waitSeconds: claimWaitSeconds
|
|
8758
|
+
}, this.lifetimeAbort.signal);
|
|
8759
|
+
if (response.attempt === void 0) {
|
|
8760
|
+
this.processPool.release(this.connection.connectionId);
|
|
8761
|
+
continue;
|
|
8762
|
+
}
|
|
8763
|
+
await this.executeAttempt(response.attempt);
|
|
8764
|
+
} catch (error) {
|
|
8765
|
+
if (!this.lifetimeAbort.signal.aborted) {
|
|
8766
|
+
await this.logger.error(`Local Codex Runtime claim loop failed for connection ${this.connection.connectionId}`, error);
|
|
8767
|
+
await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
|
|
8768
|
+
}
|
|
8769
|
+
} finally {
|
|
8770
|
+
this.active = {};
|
|
8771
|
+
this.processPool.release(this.connection.connectionId);
|
|
8772
|
+
}
|
|
8773
|
+
}
|
|
8774
|
+
}
|
|
8775
|
+
async executeAttempt(claim) {
|
|
8776
|
+
const durable = await DurableLocalCodexAttempt.create(this.store, this.connection.connectionId, this.connectorInstanceId, claim);
|
|
8777
|
+
const active = createActiveAttempt(claim, durable, this.connection.rootPath);
|
|
8778
|
+
this.active = { value: active };
|
|
8779
|
+
const leaseLoop = this.runLeaseLoop(active);
|
|
8780
|
+
const controlLoop = this.runControlLoop(active);
|
|
8781
|
+
try {
|
|
8782
|
+
active.workingDirectory = await resolveCanonicalWorkingDirectory(this.connection.rootPath, claim.relativeWorkingDirectory);
|
|
8783
|
+
const client = await this.processPool.ensureStarted();
|
|
8784
|
+
const isNewThread = active.nativeThreadId === void 0;
|
|
8785
|
+
const nativeThreadId = await this.prepareThread(client, active);
|
|
8786
|
+
active.nativeThreadId = nativeThreadId;
|
|
8787
|
+
await durable.markThreadPrepared(nativeThreadId);
|
|
8788
|
+
await active.spoolQueue;
|
|
8789
|
+
if (isNewThread && !active.durable.snapshot().events.some((event2) => event2.kind === "thread_started")) {
|
|
8790
|
+
await active.durable.appendEvent("thread_started", {}, { nativeThreadId });
|
|
8791
|
+
}
|
|
8792
|
+
let response;
|
|
8793
|
+
try {
|
|
8794
|
+
response = await client.request("turn/start", {
|
|
8795
|
+
approvalPolicy: claim.approvalPolicy,
|
|
8796
|
+
cwd: active.workingDirectory,
|
|
8797
|
+
effort: claim.reasoningEffort,
|
|
8798
|
+
input: toCodexInput(claim.inputItems),
|
|
8799
|
+
...claim.model === void 0 ? {} : { model: claim.model },
|
|
8800
|
+
sandboxPolicy: toSandboxPolicy(claim.sandboxPolicy, active.workingDirectory),
|
|
8801
|
+
threadId: nativeThreadId
|
|
8802
|
+
});
|
|
8803
|
+
} catch (error) {
|
|
8804
|
+
if (error instanceof AppServerRequestTimeoutError && error.method === "turn/start") {
|
|
8805
|
+
await this.processPool.quarantineCurrentProcess();
|
|
8806
|
+
throw new UnknownTurnStartResultError("Codex App Server turn/start result is unknown; the process generation was quarantined", { cause: error });
|
|
8807
|
+
}
|
|
8808
|
+
throw error;
|
|
8809
|
+
}
|
|
8810
|
+
const nativeTurnId = requireTurnId(response);
|
|
8811
|
+
if (active.nativeTurnId !== void 0 && active.nativeTurnId !== nativeTurnId) {
|
|
8812
|
+
throw new AppServerProtocolError("turn/start crossed the active turn boundary");
|
|
8813
|
+
}
|
|
8814
|
+
active.nativeTurnId = nativeTurnId;
|
|
8815
|
+
active.acceptedByAppServer = true;
|
|
8816
|
+
await durable.markRunning(nativeThreadId, nativeTurnId);
|
|
8817
|
+
await this.retryStateUpdate(active, {
|
|
8818
|
+
nativeTurnId,
|
|
8819
|
+
status: LocalCodexTurnStatusWire.Running
|
|
8820
|
+
});
|
|
8821
|
+
await this.interruptActiveTurnIfRequested(active, client);
|
|
8822
|
+
if (isNewThread) {
|
|
8823
|
+
await this.setInitialThreadName(client, claim, nativeThreadId);
|
|
8824
|
+
}
|
|
8825
|
+
const terminal = await Promise.race([
|
|
8826
|
+
active.terminal,
|
|
8827
|
+
active.fatal.then((error) => {
|
|
8828
|
+
throw error;
|
|
8829
|
+
})
|
|
8830
|
+
]);
|
|
8831
|
+
await active.spoolQueue;
|
|
8832
|
+
await this.flushAllEvents(active);
|
|
8833
|
+
await durable.markTerminal(terminal);
|
|
8834
|
+
await this.retryStateUpdate(active, {
|
|
8835
|
+
errorCode: terminal.errorCode,
|
|
8836
|
+
errorMessage: terminal.errorMessage,
|
|
8837
|
+
finalSequence: terminal.finalSequence,
|
|
8838
|
+
nativeTurnId,
|
|
8839
|
+
status: terminal.status
|
|
8840
|
+
});
|
|
8841
|
+
await durable.markUploaded();
|
|
8842
|
+
await this.store.deleteLocalCodexAttempt(claim.attemptId);
|
|
8843
|
+
await this.unsubscribe(client, nativeThreadId);
|
|
8844
|
+
} catch (error) {
|
|
8845
|
+
if (error instanceof LeaseLostError) {
|
|
8846
|
+
await this.logger.error(`Local Codex attempt ${claim.attemptId} stopped after losing its execution lease`, error);
|
|
8847
|
+
} else if (error instanceof SpoolPersistenceError) {
|
|
8848
|
+
await this.processPool.quarantineCurrentProcess();
|
|
8849
|
+
await this.logger.error(`Local Codex attempt ${claim.attemptId} stopped after its durable spool failed`, error);
|
|
8850
|
+
} else if (!active.acceptedByAppServer && error instanceof AppServerProcessLostError) {
|
|
8851
|
+
await this.logger.error(`Local Codex attempt ${claim.attemptId} failed before App Server accepted the turn; it remains reclaimable`, error);
|
|
8852
|
+
} else {
|
|
8853
|
+
await this.failAttempt(active, error);
|
|
8854
|
+
}
|
|
8855
|
+
} finally {
|
|
8856
|
+
if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
|
|
8857
|
+
this.processPool.retireTurn(active.nativeTurnId);
|
|
8858
|
+
}
|
|
8859
|
+
active.finished.abort();
|
|
8860
|
+
await Promise.all([leaseLoop, controlLoop]);
|
|
8861
|
+
}
|
|
8862
|
+
}
|
|
8863
|
+
async prepareThread(client, active) {
|
|
8864
|
+
const claim = active.claim;
|
|
8865
|
+
const parameters = {
|
|
8866
|
+
approvalPolicy: claim.approvalPolicy,
|
|
8867
|
+
config: { model_reasoning_effort: claim.reasoningEffort },
|
|
8868
|
+
cwd: active.workingDirectory,
|
|
8869
|
+
ephemeral: false,
|
|
8870
|
+
...claim.model === void 0 ? {} : { model: claim.model },
|
|
8871
|
+
sandbox: claim.sandboxPolicy
|
|
8872
|
+
};
|
|
8873
|
+
const preparedThreadId = active.nativeThreadId;
|
|
8874
|
+
if (preparedThreadId === void 0) {
|
|
8875
|
+
return requireThreadId(await client.request("thread/start", parameters));
|
|
8876
|
+
}
|
|
8877
|
+
try {
|
|
8878
|
+
const resumed = await client.request("thread/resume", {
|
|
8879
|
+
...parameters,
|
|
8880
|
+
threadId: preparedThreadId
|
|
8881
|
+
});
|
|
8882
|
+
const resumedId = requireThreadId(resumed);
|
|
8883
|
+
if (resumedId !== preparedThreadId) {
|
|
8884
|
+
throw new AppServerProtocolError("thread/resume returned another native thread");
|
|
8885
|
+
}
|
|
8886
|
+
return resumedId;
|
|
8887
|
+
} catch (error) {
|
|
8888
|
+
if (error instanceof AppServerProcessLostError) {
|
|
8889
|
+
throw error;
|
|
8890
|
+
}
|
|
8891
|
+
throw new ThreadUnavailableError(errorMessage2(error));
|
|
8892
|
+
}
|
|
8893
|
+
}
|
|
8894
|
+
async failAttempt(active, error) {
|
|
8895
|
+
const phase = active.durable.snapshot().phase;
|
|
8896
|
+
if (phase === LocalCodexAttemptPhase.Uploaded || phase === LocalCodexAttemptPhase.TerminalPendingUpload) {
|
|
8897
|
+
return;
|
|
8898
|
+
}
|
|
8899
|
+
const threadUnavailable = error instanceof ThreadUnavailableError;
|
|
8900
|
+
const runtimeLost = active.acceptedByAppServer && error instanceof AppServerProcessLostError || error instanceof UnknownTurnStartResultError;
|
|
8901
|
+
const status = runtimeLost ? LocalCodexTurnStatusWire.RuntimeLost : LocalCodexTurnStatusWire.Failed;
|
|
8902
|
+
const errorCode2 = threadUnavailable ? "thread_unavailable" : runtimeLost ? "runtime_lost" : "local_runtime_failed";
|
|
8903
|
+
try {
|
|
8904
|
+
const createdResult = {};
|
|
8905
|
+
await this.enqueueSpool(active, async () => {
|
|
8906
|
+
const terminal = await active.durable.appendEvent("turn_failed", { message: errorMessage2(error), status: errorCode2 }, {
|
|
8907
|
+
nativeThreadId: active.nativeThreadId,
|
|
8908
|
+
nativeTurnId: active.nativeTurnId
|
|
8909
|
+
});
|
|
8910
|
+
const result2 = {
|
|
8911
|
+
errorCode: errorCode2,
|
|
8912
|
+
errorMessage: errorMessage2(error),
|
|
8913
|
+
finalSequence: terminal.sequence,
|
|
8914
|
+
status
|
|
8915
|
+
};
|
|
8916
|
+
await active.durable.markTerminal(result2);
|
|
8917
|
+
createdResult.value = result2;
|
|
8918
|
+
this.settleTerminal(active, result2);
|
|
8919
|
+
});
|
|
8920
|
+
const result = createdResult.value ?? active.terminalValue;
|
|
8921
|
+
if (result === void 0) {
|
|
8922
|
+
return;
|
|
8923
|
+
}
|
|
8924
|
+
await this.flushAllEvents(active);
|
|
8925
|
+
await this.retryStateUpdate(active, result);
|
|
8926
|
+
await active.durable.markUploaded();
|
|
8927
|
+
await this.store.deleteLocalCodexAttempt(active.claim.attemptId);
|
|
8928
|
+
} catch (terminalError) {
|
|
8929
|
+
await this.logger.error(`Failed to terminalize Local Codex attempt ${active.claim.attemptId}`, terminalError);
|
|
8930
|
+
}
|
|
8931
|
+
}
|
|
8932
|
+
async runRecoveryLoop() {
|
|
8933
|
+
while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
|
|
8934
|
+
try {
|
|
8935
|
+
await this.recoverPersistedAttempts();
|
|
8936
|
+
} catch (error) {
|
|
8937
|
+
if (!this.lifetimeAbort.signal.aborted) {
|
|
8938
|
+
await this.logger.error(`Failed to scan persisted Local Codex attempts for connection ${this.connection.connectionId}`, error);
|
|
8939
|
+
}
|
|
8940
|
+
}
|
|
8941
|
+
await waitForAbort(this.lifetimeAbort.signal, recoveryRetryMilliseconds);
|
|
8942
|
+
}
|
|
8943
|
+
}
|
|
8944
|
+
async recoverPersistedAttempts() {
|
|
8945
|
+
const attempts = await this.store.listLocalCodexAttempts();
|
|
8946
|
+
for (const persisted of attempts) {
|
|
8947
|
+
if (persisted.connectionId !== this.connection.connectionId || typeof persisted.connectorInstanceId !== "string" || persisted.connectorInstanceId === this.connectorInstanceId || this.unrecoverableAttemptIds.has(persisted.claim.attemptId)) {
|
|
8948
|
+
continue;
|
|
8949
|
+
}
|
|
8950
|
+
try {
|
|
8951
|
+
await this.recoverPersistedAttempt(persisted);
|
|
8952
|
+
} catch (error) {
|
|
8953
|
+
if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
|
|
8954
|
+
this.unrecoverableAttemptIds.add(persisted.claim.attemptId);
|
|
8955
|
+
}
|
|
8956
|
+
await this.logger.error(`Failed to recover Local Codex attempt ${persisted.claim.attemptId}`, error);
|
|
8957
|
+
}
|
|
8958
|
+
}
|
|
8959
|
+
}
|
|
8960
|
+
async recoverPersistedAttempt(persisted) {
|
|
8961
|
+
if (persisted.phase === LocalCodexAttemptPhase.Uploaded) {
|
|
8962
|
+
await this.store.deleteLocalCodexAttempt(persisted.claim.attemptId);
|
|
8963
|
+
return;
|
|
8964
|
+
}
|
|
8965
|
+
if (persisted.phase === LocalCodexAttemptPhase.Claimed) {
|
|
8966
|
+
return;
|
|
8967
|
+
}
|
|
8968
|
+
const durable = DurableLocalCodexAttempt.fromPersisted(this.store, persisted);
|
|
8969
|
+
if (persisted.phase === LocalCodexAttemptPhase.Running) {
|
|
8970
|
+
await durable.appendEvent("runtime_error", { message: "Machine Connector restarted during the turn" }, {
|
|
8971
|
+
nativeThreadId: persisted.nativeThreadId,
|
|
8972
|
+
nativeTurnId: persisted.nativeTurnId
|
|
8973
|
+
});
|
|
8974
|
+
const terminal = await durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
|
|
8975
|
+
nativeThreadId: persisted.nativeThreadId,
|
|
8976
|
+
nativeTurnId: persisted.nativeTurnId
|
|
8977
|
+
});
|
|
8978
|
+
await durable.markTerminal({
|
|
8979
|
+
errorCode: "runtime_lost",
|
|
8980
|
+
errorMessage: "Machine Connector restarted during the turn",
|
|
8981
|
+
finalSequence: terminal.sequence,
|
|
8982
|
+
status: LocalCodexTurnStatusWire.RuntimeLost
|
|
8983
|
+
});
|
|
8984
|
+
}
|
|
8985
|
+
await this.uploadRecoveredAttempt(durable);
|
|
8986
|
+
}
|
|
8987
|
+
async uploadRecoveredAttempt(durable) {
|
|
8988
|
+
let snapshot = durable.snapshot();
|
|
8989
|
+
const fence = persistedFence(snapshot);
|
|
8990
|
+
while (durable.pendingEvents().length > 0) {
|
|
8991
|
+
const events = durable.pendingEvents().slice(0, 500);
|
|
8992
|
+
const response = await this.relay.appendCodexRuntimeEvents(snapshot.claim.attemptId, fence, events[0].sequence, events);
|
|
8993
|
+
await durable.acknowledgeEvents(response.acknowledgedSequence);
|
|
8994
|
+
snapshot = durable.snapshot();
|
|
8995
|
+
}
|
|
8996
|
+
if (snapshot.phase !== LocalCodexAttemptPhase.TerminalPendingUpload || snapshot.finalSequence === void 0 || snapshot.finalStatus === void 0) {
|
|
8997
|
+
return;
|
|
8998
|
+
}
|
|
8999
|
+
await this.relay.updateCodexRuntimeState(snapshot.claim.attemptId, fence, {
|
|
9000
|
+
errorCode: snapshot.finalErrorCode,
|
|
9001
|
+
errorMessage: snapshot.finalErrorMessage,
|
|
9002
|
+
finalSequence: snapshot.finalSequence,
|
|
9003
|
+
nativeTurnId: snapshot.nativeTurnId,
|
|
9004
|
+
status: snapshot.finalStatus
|
|
9005
|
+
});
|
|
9006
|
+
await durable.markUploaded();
|
|
9007
|
+
await this.store.deleteLocalCodexAttempt(snapshot.claim.attemptId);
|
|
9008
|
+
}
|
|
9009
|
+
async runLeaseLoop(active) {
|
|
9010
|
+
while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
|
|
9011
|
+
const remaining = active.leaseDeadlineMilliseconds - Date.now();
|
|
9012
|
+
if (remaining <= 0) {
|
|
9013
|
+
await this.loseLease(active, "Local Codex execution lease expired");
|
|
9014
|
+
return;
|
|
9015
|
+
}
|
|
9016
|
+
await waitForAbort(active.finished.signal, Math.min(leaseRenewIntervalMilliseconds, remaining));
|
|
9017
|
+
if (active.finished.signal.aborted) {
|
|
9018
|
+
return;
|
|
9019
|
+
}
|
|
9020
|
+
if (Date.now() >= active.leaseDeadlineMilliseconds) {
|
|
9021
|
+
await this.loseLease(active, "Local Codex execution lease expired");
|
|
9022
|
+
return;
|
|
9023
|
+
}
|
|
9024
|
+
try {
|
|
9025
|
+
const response = await this.renewLeaseBeforeDeadline(active);
|
|
9026
|
+
active.leaseDeadlineMilliseconds = parseLeaseDeadline(response.leaseExpiresAt);
|
|
9027
|
+
} catch (error) {
|
|
9028
|
+
if (active.finished.signal.aborted) {
|
|
9029
|
+
return;
|
|
9030
|
+
}
|
|
9031
|
+
await this.logger.error(`Failed to renew Local Codex attempt ${active.claim.attemptId}`, error);
|
|
9032
|
+
if (error instanceof LeaseLostError || error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
|
|
9033
|
+
await this.loseLease(active, errorMessage2(error));
|
|
9034
|
+
return;
|
|
9035
|
+
}
|
|
9036
|
+
const retryRemaining = active.leaseDeadlineMilliseconds - Date.now();
|
|
9037
|
+
if (retryRemaining <= 0) {
|
|
9038
|
+
await this.loseLease(active, "Local Codex execution lease expired");
|
|
9039
|
+
return;
|
|
9040
|
+
}
|
|
9041
|
+
await waitForAbort(active.finished.signal, Math.min(leaseRenewRetryMilliseconds, retryRemaining));
|
|
9042
|
+
}
|
|
9043
|
+
}
|
|
9044
|
+
}
|
|
9045
|
+
async renewLeaseBeforeDeadline(active) {
|
|
9046
|
+
const controller = new AbortController();
|
|
9047
|
+
let deadlineElapsed = false;
|
|
9048
|
+
const onFinished = () => controller.abort();
|
|
9049
|
+
active.finished.signal.addEventListener("abort", onFinished, {
|
|
9050
|
+
once: true
|
|
9051
|
+
});
|
|
9052
|
+
const remaining = Math.max(0, active.leaseDeadlineMilliseconds - Date.now());
|
|
9053
|
+
const timeout = setTimeout(() => {
|
|
9054
|
+
deadlineElapsed = true;
|
|
9055
|
+
controller.abort();
|
|
9056
|
+
}, remaining);
|
|
9057
|
+
timeout.unref();
|
|
6992
9058
|
try {
|
|
6993
|
-
|
|
9059
|
+
return await this.relay.renewCodexRuntimeLease(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), controller.signal);
|
|
6994
9060
|
} catch (error) {
|
|
6995
|
-
if (
|
|
6996
|
-
|
|
9061
|
+
if (deadlineElapsed) {
|
|
9062
|
+
throw new LeaseLostError("Local Codex execution lease expired while renewal was pending");
|
|
6997
9063
|
}
|
|
6998
9064
|
throw error;
|
|
9065
|
+
} finally {
|
|
9066
|
+
clearTimeout(timeout);
|
|
9067
|
+
active.finished.signal.removeEventListener("abort", onFinished);
|
|
6999
9068
|
}
|
|
7000
|
-
|
|
7001
|
-
|
|
7002
|
-
|
|
7003
|
-
|
|
7004
|
-
|
|
9069
|
+
}
|
|
9070
|
+
async loseLease(active, message) {
|
|
9071
|
+
const error = new LeaseLostError(message);
|
|
9072
|
+
this.signalFatal(active, error);
|
|
9073
|
+
await this.processPool.quarantineCurrentProcess();
|
|
9074
|
+
}
|
|
9075
|
+
async runControlLoop(active) {
|
|
9076
|
+
while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
|
|
9077
|
+
try {
|
|
9078
|
+
const page = await this.relay.pollCodexRuntimeControls(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), active.controlCursor, 25, active.finished.signal);
|
|
9079
|
+
for (const control of page.controls) {
|
|
9080
|
+
await this.applyControl(active, control);
|
|
9081
|
+
active.controlCursor = Math.max(active.controlCursor, control.cursor);
|
|
9082
|
+
}
|
|
9083
|
+
} catch (error) {
|
|
9084
|
+
if (!active.finished.signal.aborted) {
|
|
9085
|
+
if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
|
|
9086
|
+
await this.loseLease(active, errorMessage2(error));
|
|
9087
|
+
return;
|
|
9088
|
+
}
|
|
9089
|
+
await this.logger.error(`Failed to poll Local Codex controls for ${active.claim.attemptId}`, error);
|
|
9090
|
+
await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
|
|
9091
|
+
}
|
|
7005
9092
|
}
|
|
7006
9093
|
}
|
|
7007
|
-
return jobs;
|
|
7008
9094
|
}
|
|
7009
|
-
async
|
|
7010
|
-
await
|
|
9095
|
+
async applyControl(active, control) {
|
|
9096
|
+
await active.durable.recordControl(control.controlId);
|
|
9097
|
+
const previouslyApplied = active.durable.appliedControlOutcome(control.controlId).value;
|
|
9098
|
+
if (previouslyApplied !== void 0) {
|
|
9099
|
+
await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, previouslyApplied);
|
|
9100
|
+
return;
|
|
9101
|
+
}
|
|
9102
|
+
const client = this.processPool.currentClient().value;
|
|
9103
|
+
let outcome = LocalCodexControlOutcomeWire.Stale;
|
|
9104
|
+
if (client !== void 0 && control.kind === LocalCodexControlKindWire.Abort) {
|
|
9105
|
+
active.abortRequested = true;
|
|
9106
|
+
await this.interruptActiveTurnIfRequested(active, client);
|
|
9107
|
+
outcome = LocalCodexControlOutcomeWire.Applied;
|
|
9108
|
+
} else if (client !== void 0 && control.kind === LocalCodexControlKindWire.InteractionResponse) {
|
|
9109
|
+
const payload = safeRecord(control.payload);
|
|
9110
|
+
const requestId = optionalString2(payload.requestId).value;
|
|
9111
|
+
if (requestId !== void 0) {
|
|
9112
|
+
const interaction = active.durable.pendingInteraction(requestId).value;
|
|
9113
|
+
if (interaction !== void 0) {
|
|
9114
|
+
await client.respond(interaction.appServerRequestId, appServerInteractionResponse(interaction, safeRecord(payload.response)));
|
|
9115
|
+
await active.durable.resolveInteraction(requestId);
|
|
9116
|
+
outcome = LocalCodexControlOutcomeWire.Applied;
|
|
9117
|
+
}
|
|
9118
|
+
}
|
|
9119
|
+
} else if (control.kind === LocalCodexControlKindWire.Steer) {
|
|
9120
|
+
outcome = await this.applySteerControl(active, control);
|
|
9121
|
+
}
|
|
9122
|
+
await active.durable.markControlApplied(control.controlId, outcome);
|
|
9123
|
+
await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, outcome);
|
|
9124
|
+
}
|
|
9125
|
+
async applySteerControl(active, control) {
|
|
9126
|
+
while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
|
|
9127
|
+
const client = this.processPool.currentClient().value;
|
|
9128
|
+
if (active.acceptedByAppServer && active.nativeThreadId !== void 0 && active.nativeTurnId !== void 0 && client !== void 0) {
|
|
9129
|
+
const payload = safeRecord(control.payload);
|
|
9130
|
+
const clientMessageId = optionalString2(payload.clientMessageId).value;
|
|
9131
|
+
const inputItems = localCodexInputItems(payload.inputItems);
|
|
9132
|
+
if (clientMessageId === void 0 || inputItems.length === 0) {
|
|
9133
|
+
return LocalCodexControlOutcomeWire.Rejected;
|
|
9134
|
+
}
|
|
9135
|
+
try {
|
|
9136
|
+
const response = await client.request("turn/steer", {
|
|
9137
|
+
clientUserMessageId: clientMessageId,
|
|
9138
|
+
expectedTurnId: active.nativeTurnId,
|
|
9139
|
+
input: toCodexInput(inputItems),
|
|
9140
|
+
threadId: active.nativeThreadId
|
|
9141
|
+
});
|
|
9142
|
+
if (response.turnId !== active.nativeTurnId) {
|
|
9143
|
+
throw new AppServerProtocolError("turn/steer crossed the active turn boundary");
|
|
9144
|
+
}
|
|
9145
|
+
return LocalCodexControlOutcomeWire.Applied;
|
|
9146
|
+
} catch (error) {
|
|
9147
|
+
await this.logger.error(`Failed to steer Local Codex turn ${active.claim.turnId}`, error);
|
|
9148
|
+
return LocalCodexControlOutcomeWire.Rejected;
|
|
9149
|
+
}
|
|
9150
|
+
}
|
|
9151
|
+
await waitForAbort(active.finished.signal, 25);
|
|
9152
|
+
}
|
|
9153
|
+
return LocalCodexControlOutcomeWire.Stale;
|
|
7011
9154
|
}
|
|
7012
|
-
async
|
|
7013
|
-
|
|
9155
|
+
async interruptActiveTurnIfRequested(active, client) {
|
|
9156
|
+
if (!active.abortRequested || active.abortSent || active.nativeThreadId === void 0 || active.nativeTurnId === void 0) {
|
|
9157
|
+
return;
|
|
9158
|
+
}
|
|
9159
|
+
await client.request("turn/interrupt", {
|
|
9160
|
+
threadId: active.nativeThreadId,
|
|
9161
|
+
turnId: active.nativeTurnId
|
|
9162
|
+
});
|
|
9163
|
+
active.abortSent = true;
|
|
7014
9164
|
}
|
|
7015
|
-
async
|
|
7016
|
-
|
|
7017
|
-
|
|
7018
|
-
|
|
7019
|
-
|
|
7020
|
-
if (isNodeErrorCode3(error, "ENOENT")) {
|
|
7021
|
-
return [];
|
|
7022
|
-
}
|
|
7023
|
-
throw error;
|
|
9165
|
+
async flushEvents(active) {
|
|
9166
|
+
await active.spoolQueue;
|
|
9167
|
+
const events = active.durable.pendingEvents().slice(0, 500);
|
|
9168
|
+
if (events.length === 0) {
|
|
9169
|
+
return;
|
|
7024
9170
|
}
|
|
7025
|
-
const
|
|
7026
|
-
|
|
7027
|
-
|
|
7028
|
-
|
|
7029
|
-
|
|
9171
|
+
const response = await this.relay.appendCodexRuntimeEvents(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), events[0].sequence, events);
|
|
9172
|
+
await active.durable.acknowledgeEvents(response.acknowledgedSequence);
|
|
9173
|
+
}
|
|
9174
|
+
enqueueEventFlush(active) {
|
|
9175
|
+
if (active.eventUploadScheduled) {
|
|
9176
|
+
return active.eventUploadQueue;
|
|
9177
|
+
}
|
|
9178
|
+
active.eventUploadScheduled = true;
|
|
9179
|
+
const next = active.eventUploadQueue.catch(() => void 0).then(async () => {
|
|
9180
|
+
try {
|
|
9181
|
+
await waitForAbort(active.finished.signal, eventUploadCoalesceMilliseconds);
|
|
9182
|
+
await active.spoolQueue;
|
|
9183
|
+
while (active.durable.pendingEvents().length > 0) {
|
|
9184
|
+
await this.flushEvents(active);
|
|
9185
|
+
await active.spoolQueue;
|
|
9186
|
+
}
|
|
9187
|
+
} finally {
|
|
9188
|
+
active.eventUploadScheduled = false;
|
|
9189
|
+
}
|
|
9190
|
+
});
|
|
9191
|
+
active.eventUploadQueue = next;
|
|
9192
|
+
return next;
|
|
9193
|
+
}
|
|
9194
|
+
async flushAllEvents(active) {
|
|
9195
|
+
await active.eventUploadQueue.catch(() => void 0);
|
|
9196
|
+
while (active.durable.pendingEvents().length > 0) {
|
|
9197
|
+
if (active.fatalError !== void 0) {
|
|
9198
|
+
throw active.fatalError;
|
|
9199
|
+
}
|
|
9200
|
+
try {
|
|
9201
|
+
await this.flushEvents(active);
|
|
9202
|
+
} catch (error) {
|
|
9203
|
+
if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
|
|
9204
|
+
throw error;
|
|
9205
|
+
}
|
|
9206
|
+
if (active.finished.signal.aborted || this.lifetimeAbort.signal.aborted) {
|
|
9207
|
+
throw error;
|
|
9208
|
+
}
|
|
9209
|
+
await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
|
|
7030
9210
|
}
|
|
7031
9211
|
}
|
|
7032
|
-
return resources;
|
|
7033
9212
|
}
|
|
7034
|
-
async
|
|
7035
|
-
|
|
9213
|
+
async retryStateUpdate(active, state) {
|
|
9214
|
+
while (!this.lifetimeAbort.signal.aborted) {
|
|
9215
|
+
if (active.fatalError !== void 0) {
|
|
9216
|
+
throw active.fatalError;
|
|
9217
|
+
}
|
|
9218
|
+
try {
|
|
9219
|
+
await this.relay.updateCodexRuntimeState(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), state);
|
|
9220
|
+
return;
|
|
9221
|
+
} catch (error) {
|
|
9222
|
+
if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
|
|
9223
|
+
throw error;
|
|
9224
|
+
}
|
|
9225
|
+
await this.logger.error(`Failed to update Local Codex state for ${active.claim.attemptId}`, error);
|
|
9226
|
+
await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
|
|
9227
|
+
}
|
|
9228
|
+
}
|
|
9229
|
+
throw new Error("Local Codex Runtime stopped before state ACK");
|
|
7036
9230
|
}
|
|
7037
|
-
|
|
7038
|
-
|
|
9231
|
+
settleTerminal(active, terminal) {
|
|
9232
|
+
if (active.terminalValue !== void 0) {
|
|
9233
|
+
return;
|
|
9234
|
+
}
|
|
9235
|
+
active.terminalValue = terminal;
|
|
9236
|
+
active.resolveTerminal(terminal);
|
|
7039
9237
|
}
|
|
7040
|
-
|
|
7041
|
-
|
|
9238
|
+
enqueueSpool(active, action) {
|
|
9239
|
+
const operation = active.spoolQueue.catch(() => void 0).then(async () => {
|
|
9240
|
+
if (active.fatalError !== void 0 || active.terminalValue !== void 0) {
|
|
9241
|
+
return;
|
|
9242
|
+
}
|
|
9243
|
+
await action();
|
|
9244
|
+
});
|
|
9245
|
+
active.spoolQueue = operation.catch((error) => {
|
|
9246
|
+
const failure = new SpoolPersistenceError(`Durable Local Codex spool failed: ${errorMessage2(error)}`, { cause: error });
|
|
9247
|
+
this.signalFatal(active, failure);
|
|
9248
|
+
});
|
|
9249
|
+
return operation;
|
|
7042
9250
|
}
|
|
7043
|
-
|
|
7044
|
-
|
|
9251
|
+
signalFatal(active, error) {
|
|
9252
|
+
if (active.fatalError !== void 0) {
|
|
9253
|
+
return;
|
|
9254
|
+
}
|
|
9255
|
+
active.fatalError = error;
|
|
9256
|
+
active.resolveFatal(error);
|
|
7045
9257
|
}
|
|
7046
|
-
|
|
7047
|
-
|
|
7048
|
-
|
|
9258
|
+
async ensureCapability() {
|
|
9259
|
+
try {
|
|
9260
|
+
await this.processPool.ensureStarted();
|
|
9261
|
+
} catch {
|
|
9262
|
+
return;
|
|
7049
9263
|
}
|
|
7050
|
-
return (0, import_node_path8.join)(this.baseDirectory, "machine-connector.sock");
|
|
7051
9264
|
}
|
|
7052
|
-
|
|
7053
|
-
|
|
9265
|
+
async sendHeartbeat() {
|
|
9266
|
+
const capability = this.processPool.status();
|
|
9267
|
+
const moxt = await probeExecutable(process.env.MOXT_CLI_PATH ?? "moxt", this.environment);
|
|
9268
|
+
return await this.relay.heartbeatCodexRuntime({
|
|
9269
|
+
...capability,
|
|
9270
|
+
connectorInstanceId: this.connectorInstanceId,
|
|
9271
|
+
moxtCliStatus: moxt.status,
|
|
9272
|
+
moxtCliVersion: moxt.version,
|
|
9273
|
+
protocolVersion: localCodexRuntimeProtocolVersion
|
|
9274
|
+
});
|
|
7054
9275
|
}
|
|
7055
|
-
|
|
7056
|
-
|
|
9276
|
+
applyHeartbeatResponse(response) {
|
|
9277
|
+
this.configured = response.configured;
|
|
9278
|
+
this.enabled = response.enabled === true;
|
|
7057
9279
|
}
|
|
7058
|
-
|
|
7059
|
-
|
|
9280
|
+
runtimeReady() {
|
|
9281
|
+
const status = this.processPool.status();
|
|
9282
|
+
return status.appServerStatus === LocalCodexComponentStatusWire.Ready && status.codexAuthStatus === LocalCodexComponentStatusWire.Ready && status.codexBinaryStatus === LocalCodexComponentStatusWire.Ready;
|
|
7060
9283
|
}
|
|
7061
|
-
|
|
7062
|
-
|
|
9284
|
+
async setInitialThreadName(client, claim, threadId) {
|
|
9285
|
+
if (claim.executionContext.workflowTaskId !== void 0 || claim.executionContext.workflowWatcherId !== void 0) {
|
|
9286
|
+
return;
|
|
9287
|
+
}
|
|
9288
|
+
const text3 = firstTextInput(claim).value;
|
|
9289
|
+
if (text3 === void 0) {
|
|
9290
|
+
return;
|
|
9291
|
+
}
|
|
9292
|
+
const name = Array.from(text3.trim().replace(/\s+/g, " ")).slice(0, 40).join("");
|
|
9293
|
+
if (name === "") {
|
|
9294
|
+
return;
|
|
9295
|
+
}
|
|
9296
|
+
try {
|
|
9297
|
+
await client.request("thread/name/set", {
|
|
9298
|
+
name,
|
|
9299
|
+
threadId
|
|
9300
|
+
});
|
|
9301
|
+
} catch (error) {
|
|
9302
|
+
await this.logger.error(`Failed to name Local Codex thread ${threadId}`, error);
|
|
9303
|
+
}
|
|
7063
9304
|
}
|
|
7064
|
-
|
|
7065
|
-
|
|
9305
|
+
async unsubscribe(client, threadId) {
|
|
9306
|
+
try {
|
|
9307
|
+
await client.request("thread/unsubscribe", { threadId });
|
|
9308
|
+
} catch {
|
|
9309
|
+
return;
|
|
9310
|
+
}
|
|
7066
9311
|
}
|
|
7067
|
-
|
|
7068
|
-
|
|
9312
|
+
unregisterRoute() {
|
|
9313
|
+
if (!this.registered) {
|
|
9314
|
+
return;
|
|
9315
|
+
}
|
|
9316
|
+
this.processPool.release(this.connection.connectionId);
|
|
9317
|
+
this.processPool.unregister(this.connection.connectionId);
|
|
9318
|
+
this.registered = false;
|
|
7069
9319
|
}
|
|
7070
|
-
|
|
7071
|
-
|
|
9320
|
+
};
|
|
9321
|
+
}
|
|
9322
|
+
});
|
|
9323
|
+
|
|
9324
|
+
// ../machine-connector/dist/runtime/local-codex-runtime/process-pool.js
|
|
9325
|
+
function localCodexProcessPoolKey(environment, nativeStoreIdentitySeed) {
|
|
9326
|
+
return (0, import_node_crypto8.createHash)("sha256").update([
|
|
9327
|
+
String(process.getuid?.() ?? process.pid),
|
|
9328
|
+
environment.CODEX_HOME ?? "",
|
|
9329
|
+
environment.HOME ?? "",
|
|
9330
|
+
process.env.MOXT_CODEX_PATH ?? "codex",
|
|
9331
|
+
nativeStoreIdentitySeed,
|
|
9332
|
+
"connector-owned-app-server-stdio-v1"
|
|
9333
|
+
].join("\0")).digest("hex");
|
|
9334
|
+
}
|
|
9335
|
+
var import_node_crypto8, LocalCodexProcessPool;
|
|
9336
|
+
var init_process_pool = __esm({
|
|
9337
|
+
"../machine-connector/dist/runtime/local-codex-runtime/process-pool.js"() {
|
|
9338
|
+
"use strict";
|
|
9339
|
+
init_cjs_shims();
|
|
9340
|
+
import_node_crypto8 = require("crypto");
|
|
9341
|
+
init_app_server_client();
|
|
9342
|
+
LocalCodexProcessPool = class {
|
|
9343
|
+
poolKey;
|
|
9344
|
+
logger;
|
|
9345
|
+
activeOwner = {};
|
|
9346
|
+
routes = /* @__PURE__ */ new Map();
|
|
9347
|
+
retiredTurnIds = /* @__PURE__ */ new Set();
|
|
9348
|
+
supervisor;
|
|
9349
|
+
waitingOwners = [];
|
|
9350
|
+
constructor(poolKey, environment, nativeStoreIdentitySeed, store, logger) {
|
|
9351
|
+
this.poolKey = poolKey;
|
|
9352
|
+
this.logger = logger;
|
|
9353
|
+
this.supervisor = new LocalCodexAppServerSupervisor(environment.HOME ?? process.cwd(), environment, nativeStoreIdentitySeed, {
|
|
9354
|
+
onNotification: async (message) => {
|
|
9355
|
+
await this.activeRoute().value?.onNotification(message);
|
|
9356
|
+
},
|
|
9357
|
+
onProcessExit: async (error, processGeneration) => {
|
|
9358
|
+
if (!this.supervisor.markProcessLost(processGeneration)) {
|
|
9359
|
+
return;
|
|
9360
|
+
}
|
|
9361
|
+
await this.logger.error(`Shared Codex App Server generation ${processGeneration} exited`, error);
|
|
9362
|
+
await this.activeRoute().value?.onProcessExit(error);
|
|
9363
|
+
},
|
|
9364
|
+
onServerRequest: async (message) => {
|
|
9365
|
+
const route = this.activeRoute().value;
|
|
9366
|
+
if (route !== void 0) {
|
|
9367
|
+
await route.onServerRequest(message);
|
|
9368
|
+
return;
|
|
9369
|
+
}
|
|
9370
|
+
const client = this.supervisor.currentClient().value;
|
|
9371
|
+
if (client !== void 0 && message.id !== void 0) {
|
|
9372
|
+
await client.respondWithError(message.id, -32e3, "No owning Local Codex Runtime turn");
|
|
9373
|
+
}
|
|
9374
|
+
},
|
|
9375
|
+
onStderr: async (text3) => {
|
|
9376
|
+
await this.logger.info("Codex App Server stderr", {
|
|
9377
|
+
poolKey,
|
|
9378
|
+
text: text3.slice(0, 4e3),
|
|
9379
|
+
truncated: text3.length > 4e3
|
|
9380
|
+
});
|
|
9381
|
+
}
|
|
9382
|
+
}, async () => await store.allocateLocalCodexProcessGeneration(poolKey));
|
|
7072
9383
|
}
|
|
7073
|
-
|
|
7074
|
-
|
|
9384
|
+
register(ownerId, route) {
|
|
9385
|
+
if (this.routes.has(ownerId)) {
|
|
9386
|
+
throw new Error(`Local Codex route ${ownerId} already exists`);
|
|
9387
|
+
}
|
|
9388
|
+
this.routes.set(ownerId, route);
|
|
7075
9389
|
}
|
|
7076
|
-
|
|
7077
|
-
|
|
9390
|
+
unregister(ownerId) {
|
|
9391
|
+
if (this.activeOwner.value === ownerId) {
|
|
9392
|
+
throw new Error(`Local Codex route ${ownerId} still owns capacity`);
|
|
9393
|
+
}
|
|
9394
|
+
this.routes.delete(ownerId);
|
|
9395
|
+
const index2 = this.waitingOwners.indexOf(ownerId);
|
|
9396
|
+
if (index2 >= 0) {
|
|
9397
|
+
this.waitingOwners.splice(index2, 1);
|
|
9398
|
+
}
|
|
7078
9399
|
}
|
|
7079
|
-
|
|
7080
|
-
|
|
9400
|
+
tryAcquire(ownerId) {
|
|
9401
|
+
if (!this.routes.has(ownerId)) {
|
|
9402
|
+
throw new Error(`Local Codex route ${ownerId} is not registered`);
|
|
9403
|
+
}
|
|
9404
|
+
if (this.activeOwner.value === ownerId) {
|
|
9405
|
+
return true;
|
|
9406
|
+
}
|
|
9407
|
+
if (!this.waitingOwners.includes(ownerId)) {
|
|
9408
|
+
this.waitingOwners.push(ownerId);
|
|
9409
|
+
}
|
|
9410
|
+
if (this.activeOwner.value !== void 0 || this.waitingOwners[0] !== ownerId) {
|
|
9411
|
+
return false;
|
|
9412
|
+
}
|
|
9413
|
+
this.waitingOwners.shift();
|
|
9414
|
+
this.activeOwner = { value: ownerId };
|
|
9415
|
+
return true;
|
|
7081
9416
|
}
|
|
7082
|
-
|
|
7083
|
-
|
|
7084
|
-
|
|
7085
|
-
return {};
|
|
9417
|
+
release(ownerId) {
|
|
9418
|
+
if (this.activeOwner.value === ownerId) {
|
|
9419
|
+
this.activeOwner = {};
|
|
7086
9420
|
}
|
|
7087
|
-
return { value: JSON.parse(content3.value) };
|
|
7088
9421
|
}
|
|
7089
|
-
|
|
7090
|
-
|
|
7091
|
-
|
|
7092
|
-
|
|
7093
|
-
|
|
7094
|
-
|
|
7095
|
-
|
|
7096
|
-
|
|
9422
|
+
retireTurn(nativeTurnId) {
|
|
9423
|
+
this.retiredTurnIds.add(nativeTurnId);
|
|
9424
|
+
if (this.retiredTurnIds.size <= 4096) {
|
|
9425
|
+
return;
|
|
9426
|
+
}
|
|
9427
|
+
const oldest = this.retiredTurnIds.values().next().value;
|
|
9428
|
+
if (typeof oldest === "string") {
|
|
9429
|
+
this.retiredTurnIds.delete(oldest);
|
|
7097
9430
|
}
|
|
7098
9431
|
}
|
|
7099
|
-
|
|
7100
|
-
|
|
7101
|
-
`);
|
|
9432
|
+
isRetiredTurn(nativeTurnId) {
|
|
9433
|
+
return this.retiredTurnIds.has(nativeTurnId);
|
|
7102
9434
|
}
|
|
7103
|
-
|
|
7104
|
-
|
|
7105
|
-
|
|
7106
|
-
|
|
7107
|
-
|
|
7108
|
-
|
|
7109
|
-
|
|
7110
|
-
|
|
7111
|
-
|
|
7112
|
-
|
|
7113
|
-
await
|
|
7114
|
-
|
|
9435
|
+
status() {
|
|
9436
|
+
return this.supervisor.status();
|
|
9437
|
+
}
|
|
9438
|
+
currentClient() {
|
|
9439
|
+
return this.supervisor.currentClient();
|
|
9440
|
+
}
|
|
9441
|
+
async ensureStarted() {
|
|
9442
|
+
return await this.supervisor.ensureStarted();
|
|
9443
|
+
}
|
|
9444
|
+
async quarantineCurrentProcess() {
|
|
9445
|
+
await this.supervisor.quarantineCurrentProcess();
|
|
9446
|
+
}
|
|
9447
|
+
async stop() {
|
|
9448
|
+
await this.supervisor.stop();
|
|
9449
|
+
}
|
|
9450
|
+
activeRoute() {
|
|
9451
|
+
const owner = this.activeOwner.value;
|
|
9452
|
+
if (owner === void 0) {
|
|
9453
|
+
return {};
|
|
9454
|
+
}
|
|
9455
|
+
const value = this.routes.get(owner);
|
|
9456
|
+
return value === void 0 ? {} : { value };
|
|
7115
9457
|
}
|
|
7116
9458
|
};
|
|
7117
9459
|
}
|
|
@@ -7141,13 +9483,13 @@ function delay4(milliseconds) {
|
|
|
7141
9483
|
setTimeout(resolvePromise, milliseconds);
|
|
7142
9484
|
});
|
|
7143
9485
|
}
|
|
7144
|
-
var
|
|
9486
|
+
var import_node_os6, import_node_crypto9, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
|
|
7145
9487
|
var init_daemon = __esm({
|
|
7146
9488
|
"../machine-connector/dist/runtime/daemon.js"() {
|
|
7147
9489
|
"use strict";
|
|
7148
9490
|
init_cjs_shims();
|
|
7149
|
-
|
|
7150
|
-
|
|
9491
|
+
import_node_os6 = require("os");
|
|
9492
|
+
import_node_crypto9 = require("crypto");
|
|
7151
9493
|
init_enums();
|
|
7152
9494
|
init_contracts();
|
|
7153
9495
|
init_claude_executor();
|
|
@@ -7166,6 +9508,8 @@ var init_daemon = __esm({
|
|
|
7166
9508
|
init_runtime_types();
|
|
7167
9509
|
init_store();
|
|
7168
9510
|
init_version();
|
|
9511
|
+
init_runtime_worker();
|
|
9512
|
+
init_process_pool();
|
|
7169
9513
|
claimTimeoutSeconds = 30;
|
|
7170
9514
|
controlTimeoutSeconds = 30;
|
|
7171
9515
|
eventUploadIntervalMilliseconds = 500;
|
|
@@ -7190,10 +9534,12 @@ var init_daemon = __esm({
|
|
|
7190
9534
|
MachineConnectorDaemon = class {
|
|
7191
9535
|
store;
|
|
7192
9536
|
activeJobs = /* @__PURE__ */ new Map();
|
|
7193
|
-
connectorInstanceId = (0,
|
|
9537
|
+
connectorInstanceId = (0, import_node_crypto9.randomUUID)();
|
|
7194
9538
|
executionTasks = /* @__PURE__ */ new Set();
|
|
7195
9539
|
logger;
|
|
7196
9540
|
relayClients = /* @__PURE__ */ new Map();
|
|
9541
|
+
localCodexWorkers = /* @__PURE__ */ new Map();
|
|
9542
|
+
localCodexProcessPools = /* @__PURE__ */ new Map();
|
|
7197
9543
|
startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7198
9544
|
connections = [];
|
|
7199
9545
|
daemonLock;
|
|
@@ -7259,7 +9605,7 @@ var init_daemon = __esm({
|
|
|
7259
9605
|
this.throwIfStopping();
|
|
7260
9606
|
await this.logger.info("Moxt Machine Connector started", {
|
|
7261
9607
|
connectorInstanceId: this.connectorInstanceId,
|
|
7262
|
-
hostname: (0,
|
|
9608
|
+
hostname: (0, import_node_os6.hostname)(),
|
|
7263
9609
|
version: connectorVersion
|
|
7264
9610
|
});
|
|
7265
9611
|
this.connections = await this.store.listConnections();
|
|
@@ -7293,6 +9639,8 @@ var init_daemon = __esm({
|
|
|
7293
9639
|
await Promise.all([...this.activeJobs.values()].map(async (activeJob) => {
|
|
7294
9640
|
await activeJob.cancellation.request(ExecutionCancellationReason.Stopping);
|
|
7295
9641
|
}));
|
|
9642
|
+
await Promise.all([...this.localCodexWorkers.values()].map(async (worker) => await worker.stop()));
|
|
9643
|
+
await Promise.all([...this.localCodexProcessPools.values()].map(async (pool) => await pool.stop()));
|
|
7296
9644
|
await this.startupSettled;
|
|
7297
9645
|
await this.ipcServer?.close();
|
|
7298
9646
|
this.ipcServer = void 0;
|
|
@@ -7318,11 +9666,16 @@ var init_daemon = __esm({
|
|
|
7318
9666
|
connections: this.connections.map((connection) => ({
|
|
7319
9667
|
connectionId: connection.connectionId,
|
|
7320
9668
|
machineName: connection.machineName,
|
|
9669
|
+
purpose: connection.purpose,
|
|
7321
9670
|
relayOrigin: connection.relayOrigin,
|
|
7322
9671
|
rootDisplayName: connection.rootDisplayName,
|
|
7323
9672
|
rootPath: connection.rootPath
|
|
7324
9673
|
})),
|
|
7325
9674
|
connectorInstanceId: this.connectorInstanceId,
|
|
9675
|
+
localCodexRuntimes: [...this.localCodexWorkers.entries()].map(([connectionId, worker]) => ({
|
|
9676
|
+
connectionId,
|
|
9677
|
+
...worker.status()
|
|
9678
|
+
})),
|
|
7326
9679
|
pid: process.pid,
|
|
7327
9680
|
startedAt: this.startedAt,
|
|
7328
9681
|
shellEnvironment: this.shellEnvironmentManager.status(),
|
|
@@ -7331,12 +9684,44 @@ var init_daemon = __esm({
|
|
|
7331
9684
|
}
|
|
7332
9685
|
async runConnection(connection) {
|
|
7333
9686
|
const relay = this.relayForConnection(connection);
|
|
9687
|
+
if (connection.purpose === MachineConnectionPurpose.LocalCodexRuntime) {
|
|
9688
|
+
await Promise.all([
|
|
9689
|
+
this.runHeartbeatLoop(connection, relay),
|
|
9690
|
+
this.runLocalCodexRuntime(connection, relay)
|
|
9691
|
+
]);
|
|
9692
|
+
return;
|
|
9693
|
+
}
|
|
7334
9694
|
await Promise.all([
|
|
7335
9695
|
this.runHeartbeatLoop(connection, relay),
|
|
7336
9696
|
this.runClaimLoop(connection, relay),
|
|
7337
9697
|
this.runControlLoop(connection, relay)
|
|
7338
9698
|
]);
|
|
7339
9699
|
}
|
|
9700
|
+
async runLocalCodexRuntime(connection, relay) {
|
|
9701
|
+
const worker = new LocalCodexRuntimeConnectionWorker(connection, relay, this.store, this.localCodexProcessPool(connection.machineId), this.shellEnvironmentManager.snapshot(), this.connectorInstanceId, this.logger);
|
|
9702
|
+
this.localCodexWorkers.set(connection.connectionId, worker);
|
|
9703
|
+
if (this.stopping) {
|
|
9704
|
+
await worker.stop();
|
|
9705
|
+
}
|
|
9706
|
+
try {
|
|
9707
|
+
await worker.run();
|
|
9708
|
+
} finally {
|
|
9709
|
+
if (this.localCodexWorkers.get(connection.connectionId) === worker) {
|
|
9710
|
+
this.localCodexWorkers.delete(connection.connectionId);
|
|
9711
|
+
}
|
|
9712
|
+
}
|
|
9713
|
+
}
|
|
9714
|
+
localCodexProcessPool(nativeStoreIdentitySeed) {
|
|
9715
|
+
const environment = this.shellEnvironmentManager.snapshot();
|
|
9716
|
+
const poolKey = localCodexProcessPoolKey(environment, nativeStoreIdentitySeed);
|
|
9717
|
+
const existing = this.localCodexProcessPools.get(poolKey);
|
|
9718
|
+
if (existing !== void 0) {
|
|
9719
|
+
return existing;
|
|
9720
|
+
}
|
|
9721
|
+
const pool = new LocalCodexProcessPool(poolKey, environment, nativeStoreIdentitySeed, this.store, this.logger);
|
|
9722
|
+
this.localCodexProcessPools.set(poolKey, pool);
|
|
9723
|
+
return pool;
|
|
9724
|
+
}
|
|
7340
9725
|
relayForConnection(connection) {
|
|
7341
9726
|
const existing = this.relayClients.get(connection.connectionId);
|
|
7342
9727
|
if (existing) {
|
|
@@ -7364,6 +9749,7 @@ var init_daemon = __esm({
|
|
|
7364
9749
|
await Promise.all([...this.activeJobs.values()].filter((activeJob) => activeJob.connection.connectionId === connection.connectionId).map(async (activeJob) => {
|
|
7365
9750
|
await activeJob.cancellation.request(ExecutionCancellationReason.LeaseLost);
|
|
7366
9751
|
}));
|
|
9752
|
+
this.localCodexWorkers.get(connection.connectionId)?.revoke();
|
|
7367
9753
|
}
|
|
7368
9754
|
async runHeartbeatLoop(connection, relay) {
|
|
7369
9755
|
while (!this.stopping && !relay.isRevoked()) {
|
|
@@ -7616,11 +10002,11 @@ var init_daemon = __esm({
|
|
|
7616
10002
|
}
|
|
7617
10003
|
const callbacks = {
|
|
7618
10004
|
canSpawn,
|
|
7619
|
-
onEvent: async (
|
|
10005
|
+
onEvent: async (event2) => {
|
|
7620
10006
|
if (activeJob.cancellation.currentReason() !== void 0) {
|
|
7621
10007
|
return;
|
|
7622
10008
|
}
|
|
7623
|
-
await durableJob.appendProgress(
|
|
10009
|
+
await durableJob.appendProgress(event2);
|
|
7624
10010
|
},
|
|
7625
10011
|
onOutput: async (stream, text3) => {
|
|
7626
10012
|
if (activeJob.cancellation.currentReason() !== void 0) {
|
|
@@ -7691,7 +10077,7 @@ var init_daemon = __esm({
|
|
|
7691
10077
|
threadId: result.threadId ?? request2.threadId
|
|
7692
10078
|
};
|
|
7693
10079
|
}
|
|
7694
|
-
throw new Error(
|
|
10080
|
+
throw new Error("Unsupported Local Machine Job kind");
|
|
7695
10081
|
}
|
|
7696
10082
|
async runEventUploadLoop(activeJob) {
|
|
7697
10083
|
const durableJob = this.requireDurableJob(activeJob);
|
|
@@ -8152,12 +10538,12 @@ async function installUserService(store, request2, runtime = defaultServiceManag
|
|
|
8152
10538
|
}
|
|
8153
10539
|
function createServiceEnvironment(options) {
|
|
8154
10540
|
const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
|
|
8155
|
-
const nodeDirectory = (0,
|
|
8156
|
-
const pathEntries = [nodeDirectory, ...inheritedPath.split(
|
|
10541
|
+
const nodeDirectory = (0, import_node_path10.dirname)(options.nodePath);
|
|
10542
|
+
const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path10.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
|
|
8157
10543
|
return {
|
|
8158
10544
|
...options.environment,
|
|
8159
|
-
HOME: options.environment.HOME ?? process.env.HOME ?? (0,
|
|
8160
|
-
PATH: pathEntries.join(
|
|
10545
|
+
HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os7.homedir)(),
|
|
10546
|
+
PATH: pathEntries.join(import_node_path10.delimiter)
|
|
8161
10547
|
};
|
|
8162
10548
|
}
|
|
8163
10549
|
async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
|
|
@@ -8194,7 +10580,7 @@ async function refreshManagedUserService(store, options, runtime = defaultServic
|
|
|
8194
10580
|
try {
|
|
8195
10581
|
await rollback();
|
|
8196
10582
|
} catch (rollbackError) {
|
|
8197
|
-
throw new Error(`${
|
|
10583
|
+
throw new Error(`${errorMessage3(error)}; restoring the previous ${manager} definition also failed: ${errorMessage3(rollbackError)}`, { cause: error });
|
|
8198
10584
|
}
|
|
8199
10585
|
throw error;
|
|
8200
10586
|
}
|
|
@@ -8400,7 +10786,7 @@ async function readManagedServiceDefinition(manager, store) {
|
|
|
8400
10786
|
}
|
|
8401
10787
|
async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
|
|
8402
10788
|
const path4 = managedServiceDefinitionPath(manager, store);
|
|
8403
|
-
await (0, import_promises12.mkdir)((0,
|
|
10789
|
+
await (0, import_promises12.mkdir)((0, import_node_path10.dirname)(path4), { recursive: true });
|
|
8404
10790
|
await (0, import_promises12.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
|
|
8405
10791
|
if (manager === UserServiceManager.Launchd) {
|
|
8406
10792
|
const domain = `gui/${process.getuid?.() ?? 0}`;
|
|
@@ -8449,7 +10835,7 @@ function parseProcessId(value) {
|
|
|
8449
10835
|
}
|
|
8450
10836
|
async function persistServiceManager(store, manager, managedEntrypointPath) {
|
|
8451
10837
|
await store.writeServiceManager({
|
|
8452
|
-
...managedEntrypointPath ? { managedEntrypointPath: (0,
|
|
10838
|
+
...managedEntrypointPath ? { managedEntrypointPath: (0, import_node_path10.resolve)(managedEntrypointPath) } : {},
|
|
8453
10839
|
manager,
|
|
8454
10840
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
8455
10841
|
});
|
|
@@ -8458,9 +10844,9 @@ async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
|
|
|
8458
10844
|
const stored = (await store.readServiceManager()).value;
|
|
8459
10845
|
if (!stored || stored.manager === UserServiceManager.None)
|
|
8460
10846
|
return;
|
|
8461
|
-
const candidate = (0,
|
|
10847
|
+
const candidate = (0, import_node_path10.resolve)(candidateEntrypointPath);
|
|
8462
10848
|
if (stored.managedEntrypointPath) {
|
|
8463
|
-
if ((0,
|
|
10849
|
+
if ((0, import_node_path10.resolve)(stored.managedEntrypointPath) !== candidate) {
|
|
8464
10850
|
throw new Error("The managed Connector belongs to a different CLI installation. Run service install from the owning CLI to transfer management.");
|
|
8465
10851
|
}
|
|
8466
10852
|
return;
|
|
@@ -8470,16 +10856,16 @@ async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
|
|
|
8470
10856
|
}
|
|
8471
10857
|
}
|
|
8472
10858
|
async function isInsideSourceCheckout(path4) {
|
|
8473
|
-
let directory = (0,
|
|
10859
|
+
let directory = (0, import_node_path10.dirname)(path4);
|
|
8474
10860
|
while (true) {
|
|
8475
10861
|
try {
|
|
8476
|
-
await (0, import_promises12.stat)((0,
|
|
10862
|
+
await (0, import_promises12.stat)((0, import_node_path10.join)(directory, ".git"));
|
|
8477
10863
|
return true;
|
|
8478
10864
|
} catch (error) {
|
|
8479
10865
|
if (!isNodeErrorCode4(error, "ENOENT"))
|
|
8480
10866
|
throw error;
|
|
8481
10867
|
}
|
|
8482
|
-
const parent = (0,
|
|
10868
|
+
const parent = (0, import_node_path10.dirname)(directory);
|
|
8483
10869
|
if (parent === directory)
|
|
8484
10870
|
return false;
|
|
8485
10871
|
directory = parent;
|
|
@@ -8508,10 +10894,10 @@ function automaticSelectionDetail(manager) {
|
|
|
8508
10894
|
}
|
|
8509
10895
|
async function installLaunchAgent(store, options, runtime) {
|
|
8510
10896
|
const path4 = launchAgentPath();
|
|
8511
|
-
await (0, import_promises12.mkdir)((0,
|
|
10897
|
+
await (0, import_promises12.mkdir)((0, import_node_path10.dirname)(path4), { recursive: true });
|
|
8512
10898
|
const programArguments = [
|
|
8513
10899
|
options.nodePath,
|
|
8514
|
-
(0,
|
|
10900
|
+
(0, import_node_path10.resolve)(options.entrypointPath),
|
|
8515
10901
|
...options.commandArguments
|
|
8516
10902
|
];
|
|
8517
10903
|
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
@@ -8558,10 +10944,10 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
|
|
|
8558
10944
|
}
|
|
8559
10945
|
async function installSystemdUserService(store, options, runtime) {
|
|
8560
10946
|
const path4 = systemdUnitPath();
|
|
8561
|
-
await (0, import_promises12.mkdir)((0,
|
|
10947
|
+
await (0, import_promises12.mkdir)((0, import_node_path10.dirname)(path4), { recursive: true });
|
|
8562
10948
|
const command = [
|
|
8563
10949
|
options.nodePath,
|
|
8564
|
-
(0,
|
|
10950
|
+
(0, import_node_path10.resolve)(options.entrypointPath),
|
|
8565
10951
|
...options.commandArguments
|
|
8566
10952
|
].map(escapeSystemdArgument).join(" ");
|
|
8567
10953
|
const unit = `[Unit]
|
|
@@ -8590,7 +10976,7 @@ WantedBy=default.target
|
|
|
8590
10976
|
]);
|
|
8591
10977
|
await runCommandIgnoringFailure(runtime, "loginctl", [
|
|
8592
10978
|
"enable-linger",
|
|
8593
|
-
(0,
|
|
10979
|
+
(0, import_node_os7.userInfo)().username
|
|
8594
10980
|
]);
|
|
8595
10981
|
}
|
|
8596
10982
|
async function installSupervisorUserService(store, options, runtime) {
|
|
@@ -8611,7 +10997,7 @@ async function installSupervisorUserService(store, options, runtime) {
|
|
|
8611
10997
|
function createSupervisorConfiguration(store, options) {
|
|
8612
10998
|
const command = [
|
|
8613
10999
|
options.nodePath,
|
|
8614
|
-
(0,
|
|
11000
|
+
(0, import_node_path10.resolve)(options.entrypointPath),
|
|
8615
11001
|
...options.commandArguments
|
|
8616
11002
|
].map(escapeSupervisorArgument).join(" ");
|
|
8617
11003
|
const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
|
|
@@ -8635,7 +11021,7 @@ serverurl=unix://${supervisorSocketPath(store)}
|
|
|
8635
11021
|
|
|
8636
11022
|
[program:${supervisorProgramName}]
|
|
8637
11023
|
command=${command}
|
|
8638
|
-
directory=${escapeSupervisorPath((0,
|
|
11024
|
+
directory=${escapeSupervisorPath((0, import_node_path10.dirname)((0, import_node_path10.resolve)(options.entrypointPath)))}
|
|
8639
11025
|
environment=${environment}
|
|
8640
11026
|
autostart=true
|
|
8641
11027
|
autorestart=true
|
|
@@ -8798,26 +11184,26 @@ async function currentSupervisorProgramProcessId(store, runtime) {
|
|
|
8798
11184
|
}
|
|
8799
11185
|
}
|
|
8800
11186
|
function launchAgentPath() {
|
|
8801
|
-
return (0,
|
|
11187
|
+
return (0, import_node_path10.join)(process.env.HOME ?? (0, import_node_os7.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
|
|
8802
11188
|
}
|
|
8803
11189
|
function systemdUnitPath() {
|
|
8804
|
-
const configHome = process.env.XDG_CONFIG_HOME ?? (0,
|
|
8805
|
-
return (0,
|
|
11190
|
+
const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path10.join)(process.env.HOME ?? (0, import_node_os7.homedir)(), ".config");
|
|
11191
|
+
return (0, import_node_path10.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
|
|
8806
11192
|
}
|
|
8807
11193
|
function supervisorDirectory(store) {
|
|
8808
|
-
return (0,
|
|
11194
|
+
return (0, import_node_path10.join)(store.baseDirectory, "supervisor");
|
|
8809
11195
|
}
|
|
8810
11196
|
function supervisorConfigPath(store) {
|
|
8811
|
-
return (0,
|
|
11197
|
+
return (0, import_node_path10.join)(supervisorDirectory(store), "supervisord.conf");
|
|
8812
11198
|
}
|
|
8813
11199
|
function supervisorSocketPath(store) {
|
|
8814
|
-
return (0,
|
|
11200
|
+
return (0, import_node_path10.join)(supervisorDirectory(store), "supervisor.sock");
|
|
8815
11201
|
}
|
|
8816
11202
|
function supervisorPidPath(store) {
|
|
8817
|
-
return (0,
|
|
11203
|
+
return (0, import_node_path10.join)(supervisorDirectory(store), "supervisord.pid");
|
|
8818
11204
|
}
|
|
8819
11205
|
function supervisorLogPath(store) {
|
|
8820
|
-
return (0,
|
|
11206
|
+
return (0, import_node_path10.join)(supervisorDirectory(store), "supervisord.log");
|
|
8821
11207
|
}
|
|
8822
11208
|
async function commandSucceeds(runtime, command, argumentsList) {
|
|
8823
11209
|
try {
|
|
@@ -8867,7 +11253,7 @@ function escapeSupervisorPath(value) {
|
|
|
8867
11253
|
function escapeSupervisorValue(value) {
|
|
8868
11254
|
return value.replaceAll("%", "%%").replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
|
|
8869
11255
|
}
|
|
8870
|
-
function
|
|
11256
|
+
function errorMessage3(error) {
|
|
8871
11257
|
return error instanceof Error ? error.message : String(error);
|
|
8872
11258
|
}
|
|
8873
11259
|
function isNodeErrorCode4(error, expectedCode) {
|
|
@@ -8884,18 +11270,18 @@ function serviceManagerCurrentTime(runtime) {
|
|
|
8884
11270
|
async function serviceManagerDelay(runtime, milliseconds) {
|
|
8885
11271
|
await (runtime.delay?.(milliseconds) ?? delay5(milliseconds));
|
|
8886
11272
|
}
|
|
8887
|
-
var
|
|
11273
|
+
var import_node_child_process5, import_promises12, import_node_os7, import_node_path10, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, supervisorControlTimeoutMilliseconds, supervisorProgramStartSeconds, supervisorProgramStartRetries, supervisorProgramStopWaitSeconds, supervisorLifecycleBufferMilliseconds, supervisorExitTimeoutMilliseconds, supervisorProgramStartTimeoutMilliseconds, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
|
|
8888
11274
|
var init_service_manager = __esm({
|
|
8889
11275
|
"../machine-connector/dist/runtime/service-manager.js"() {
|
|
8890
11276
|
"use strict";
|
|
8891
11277
|
init_cjs_shims();
|
|
8892
|
-
|
|
11278
|
+
import_node_child_process5 = require("child_process");
|
|
8893
11279
|
import_promises12 = require("fs/promises");
|
|
8894
|
-
|
|
8895
|
-
|
|
11280
|
+
import_node_os7 = require("os");
|
|
11281
|
+
import_node_path10 = require("path");
|
|
8896
11282
|
import_node_util2 = require("util");
|
|
8897
11283
|
init_shell_environment();
|
|
8898
|
-
execFileAsync = (0, import_node_util2.promisify)(
|
|
11284
|
+
execFileAsync = (0, import_node_util2.promisify)(import_node_child_process5.execFile);
|
|
8899
11285
|
launchAgentLabel = "ai.moxt.machine-connector";
|
|
8900
11286
|
serviceManagerProbeTimeoutMilliseconds = 5e3;
|
|
8901
11287
|
serviceManagerMutationTimeoutMilliseconds = 3e4;
|
|
@@ -8920,7 +11306,7 @@ var init_service_manager = __esm({
|
|
|
8920
11306
|
UserServiceManager2["Systemd"] = "systemd";
|
|
8921
11307
|
})(UserServiceManager || (UserServiceManager = {}));
|
|
8922
11308
|
defaultServiceManagerRuntime = {
|
|
8923
|
-
operatingSystem: (0,
|
|
11309
|
+
operatingSystem: (0, import_node_os7.platform)(),
|
|
8924
11310
|
processIsRunning(processId) {
|
|
8925
11311
|
return localProcessIsRunning(processId);
|
|
8926
11312
|
},
|
|
@@ -8963,7 +11349,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
|
|
|
8963
11349
|
try {
|
|
8964
11350
|
managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
|
|
8965
11351
|
} catch (error) {
|
|
8966
|
-
throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${
|
|
11352
|
+
throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage4(error)}`, { cause: error });
|
|
8967
11353
|
}
|
|
8968
11354
|
if (!managerOwnsProcess) {
|
|
8969
11355
|
return { outcome: DaemonReconcileOutcome.Skipped };
|
|
@@ -8971,7 +11357,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
|
|
|
8971
11357
|
try {
|
|
8972
11358
|
await validateCliEntrypoint(options, store);
|
|
8973
11359
|
} catch (error) {
|
|
8974
|
-
throw new DaemonRefreshError("validation",
|
|
11360
|
+
throw new DaemonRefreshError("validation", errorMessage4(error), {
|
|
8975
11361
|
cause: error
|
|
8976
11362
|
});
|
|
8977
11363
|
}
|
|
@@ -8982,9 +11368,9 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
|
|
|
8982
11368
|
try {
|
|
8983
11369
|
refresh = await refreshManagedUserService(store, {
|
|
8984
11370
|
commandArguments: [...options.commandArguments],
|
|
8985
|
-
entrypointPath: (0,
|
|
11371
|
+
entrypointPath: (0, import_node_path11.resolve)(options.entrypointPath),
|
|
8986
11372
|
environment: { ...options.environment },
|
|
8987
|
-
nodePath: (0,
|
|
11373
|
+
nodePath: (0, import_node_path11.resolve)(options.nodePath)
|
|
8988
11374
|
});
|
|
8989
11375
|
if (!refresh) {
|
|
8990
11376
|
throw new Error("The Connector service is no longer managed by Moxt");
|
|
@@ -9004,7 +11390,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
|
|
|
9004
11390
|
try {
|
|
9005
11391
|
await refresh.rollback();
|
|
9006
11392
|
} catch (error) {
|
|
9007
|
-
throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${
|
|
11393
|
+
throw new DaemonRefreshError("verification", `${verificationMessage}; restoring the previous service definition also failed: ${errorMessage4(error)}`, { cause: error });
|
|
9008
11394
|
}
|
|
9009
11395
|
throw new DaemonRefreshError("verification", verificationMessage);
|
|
9010
11396
|
} finally {
|
|
@@ -9016,8 +11402,8 @@ async function validateCliEntrypoint(options, store) {
|
|
|
9016
11402
|
if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
|
|
9017
11403
|
throw new Error("The managed daemon command must be `machine daemon`");
|
|
9018
11404
|
}
|
|
9019
|
-
const nodePath = await (0, import_promises13.realpath)((0,
|
|
9020
|
-
const entrypointPath = await (0, import_promises13.realpath)((0,
|
|
11405
|
+
const nodePath = await (0, import_promises13.realpath)((0, import_node_path11.resolve)(options.nodePath));
|
|
11406
|
+
const entrypointPath = await (0, import_promises13.realpath)((0, import_node_path11.resolve)(options.entrypointPath));
|
|
9021
11407
|
await (0, import_promises13.access)(nodePath, import_promises13.constants.X_OK);
|
|
9022
11408
|
await (0, import_promises13.access)(entrypointPath, import_promises13.constants.R_OK);
|
|
9023
11409
|
const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
|
|
@@ -9049,24 +11435,24 @@ async function reachableRuntimeStatus(store) {
|
|
|
9049
11435
|
function delay6(milliseconds) {
|
|
9050
11436
|
return new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
|
|
9051
11437
|
}
|
|
9052
|
-
function
|
|
11438
|
+
function errorMessage4(error) {
|
|
9053
11439
|
return error instanceof Error ? error.message : String(error);
|
|
9054
11440
|
}
|
|
9055
|
-
var
|
|
11441
|
+
var import_node_child_process6, import_promises13, import_node_path11, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshError;
|
|
9056
11442
|
var init_daemon_reconcile = __esm({
|
|
9057
11443
|
"../machine-connector/dist/runtime/daemon-reconcile.js"() {
|
|
9058
11444
|
"use strict";
|
|
9059
11445
|
init_cjs_shims();
|
|
9060
|
-
|
|
11446
|
+
import_node_child_process6 = require("child_process");
|
|
9061
11447
|
import_promises13 = require("fs/promises");
|
|
9062
|
-
|
|
11448
|
+
import_node_path11 = require("path");
|
|
9063
11449
|
import_node_util3 = require("util");
|
|
9064
11450
|
init_local_ipc();
|
|
9065
11451
|
init_process_lock();
|
|
9066
11452
|
init_service_manager();
|
|
9067
11453
|
init_store();
|
|
9068
11454
|
reconcileTimeoutMilliseconds = 12e3;
|
|
9069
|
-
execFileAsync2 = (0, import_node_util3.promisify)(
|
|
11455
|
+
execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process6.execFile);
|
|
9070
11456
|
(function(DaemonReconcileOutcome2) {
|
|
9071
11457
|
DaemonReconcileOutcome2["Restarted"] = "restarted";
|
|
9072
11458
|
DaemonReconcileOutcome2["Skipped"] = "skipped";
|
|
@@ -9108,7 +11494,7 @@ async function runMachineDoctor(store) {
|
|
|
9108
11494
|
}
|
|
9109
11495
|
} catch (error) {
|
|
9110
11496
|
checks.push({
|
|
9111
|
-
detail:
|
|
11497
|
+
detail: errorMessage5(error),
|
|
9112
11498
|
name: "daemon",
|
|
9113
11499
|
status: DoctorCheckStatus.Failed
|
|
9114
11500
|
});
|
|
@@ -9123,7 +11509,7 @@ async function runMachineDoctor(store) {
|
|
|
9123
11509
|
});
|
|
9124
11510
|
} catch (error) {
|
|
9125
11511
|
checks.push({
|
|
9126
|
-
detail:
|
|
11512
|
+
detail: errorMessage5(error),
|
|
9127
11513
|
name: `root:${connection.connectionId}`,
|
|
9128
11514
|
status: DoctorCheckStatus.Failed
|
|
9129
11515
|
});
|
|
@@ -9138,7 +11524,7 @@ async function runMachineDoctor(store) {
|
|
|
9138
11524
|
});
|
|
9139
11525
|
} catch (error) {
|
|
9140
11526
|
checks.push({
|
|
9141
|
-
detail:
|
|
11527
|
+
detail: errorMessage5(error),
|
|
9142
11528
|
name: `dns:${connection.connectionId}`,
|
|
9143
11529
|
status: DoctorCheckStatus.Failed
|
|
9144
11530
|
});
|
|
@@ -9162,7 +11548,7 @@ async function runMachineDoctor(store) {
|
|
|
9162
11548
|
});
|
|
9163
11549
|
} catch (error) {
|
|
9164
11550
|
checks.push({
|
|
9165
|
-
detail:
|
|
11551
|
+
detail: errorMessage5(error),
|
|
9166
11552
|
name: `tls:${connection.connectionId}`,
|
|
9167
11553
|
status: DoctorCheckStatus.Failed
|
|
9168
11554
|
});
|
|
@@ -9188,7 +11574,7 @@ async function runMachineDoctor(store) {
|
|
|
9188
11574
|
});
|
|
9189
11575
|
} catch (error) {
|
|
9190
11576
|
checks.push({
|
|
9191
|
-
detail:
|
|
11577
|
+
detail: errorMessage5(error),
|
|
9192
11578
|
name: "codex",
|
|
9193
11579
|
status: DoctorCheckStatus.Warning
|
|
9194
11580
|
});
|
|
@@ -9202,28 +11588,28 @@ async function runMachineDoctor(store) {
|
|
|
9202
11588
|
});
|
|
9203
11589
|
} catch (error) {
|
|
9204
11590
|
checks.push({
|
|
9205
|
-
detail:
|
|
11591
|
+
detail: errorMessage5(error),
|
|
9206
11592
|
name: "claude",
|
|
9207
11593
|
status: DoctorCheckStatus.Warning
|
|
9208
11594
|
});
|
|
9209
11595
|
}
|
|
9210
11596
|
return checks;
|
|
9211
11597
|
}
|
|
9212
|
-
function
|
|
11598
|
+
function errorMessage5(error) {
|
|
9213
11599
|
return error instanceof Error ? error.message : String(error);
|
|
9214
11600
|
}
|
|
9215
|
-
var
|
|
11601
|
+
var import_node_child_process7, import_promises14, import_node_fs, import_promises15, import_node_util4, execFileAsync3, DoctorCheckStatus;
|
|
9216
11602
|
var init_doctor = __esm({
|
|
9217
11603
|
"../machine-connector/dist/runtime/doctor.js"() {
|
|
9218
11604
|
"use strict";
|
|
9219
11605
|
init_cjs_shims();
|
|
9220
|
-
|
|
11606
|
+
import_node_child_process7 = require("child_process");
|
|
9221
11607
|
import_promises14 = require("fs/promises");
|
|
9222
11608
|
import_node_fs = require("fs");
|
|
9223
11609
|
import_promises15 = require("dns/promises");
|
|
9224
11610
|
import_node_util4 = require("util");
|
|
9225
11611
|
init_local_ipc();
|
|
9226
|
-
execFileAsync3 = (0, import_node_util4.promisify)(
|
|
11612
|
+
execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process7.execFile);
|
|
9227
11613
|
(function(DoctorCheckStatus2) {
|
|
9228
11614
|
DoctorCheckStatus2["Failed"] = "failed";
|
|
9229
11615
|
DoctorCheckStatus2["Passed"] = "passed";
|
|
@@ -9443,6 +11829,7 @@ function toManagerConnection(connection) {
|
|
|
9443
11829
|
return {
|
|
9444
11830
|
connectionId: connection.connectionId,
|
|
9445
11831
|
machineName: connection.machineName,
|
|
11832
|
+
purpose: connection.purpose,
|
|
9446
11833
|
relayOrigin: connection.relayOrigin,
|
|
9447
11834
|
rootDisplayName: connection.rootDisplayName,
|
|
9448
11835
|
rootPath: connection.rootPath,
|
|
@@ -9467,7 +11854,7 @@ function formatPersistedCommand(job) {
|
|
|
9467
11854
|
if (job.claim.kind !== "command") {
|
|
9468
11855
|
return {};
|
|
9469
11856
|
}
|
|
9470
|
-
if (!
|
|
11857
|
+
if (!isRecord4(job.claim.requestPayload)) {
|
|
9471
11858
|
return {};
|
|
9472
11859
|
}
|
|
9473
11860
|
const executable = job.claim.requestPayload.executable;
|
|
@@ -9539,13 +11926,13 @@ function formatTimestamp(value) {
|
|
|
9539
11926
|
}
|
|
9540
11927
|
return new Date(timestamp).toLocaleString();
|
|
9541
11928
|
}
|
|
9542
|
-
function
|
|
11929
|
+
function isRecord4(value) {
|
|
9543
11930
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9544
11931
|
}
|
|
9545
11932
|
function isMissingFile(error) {
|
|
9546
11933
|
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
9547
11934
|
}
|
|
9548
|
-
function
|
|
11935
|
+
function errorMessage6(error) {
|
|
9549
11936
|
return error instanceof Error ? error.message : String(error);
|
|
9550
11937
|
}
|
|
9551
11938
|
var import_promises16, import_promises17, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
|
|
@@ -9751,7 +12138,7 @@ var init_machine_manager = __esm({
|
|
|
9751
12138
|
};
|
|
9752
12139
|
this.state.message = void 0;
|
|
9753
12140
|
} catch (error) {
|
|
9754
|
-
this.state.message =
|
|
12141
|
+
this.state.message = errorMessage6(error);
|
|
9755
12142
|
} finally {
|
|
9756
12143
|
this.refreshing = false;
|
|
9757
12144
|
this.render();
|
|
@@ -9799,7 +12186,7 @@ var init_machine_manager = __esm({
|
|
|
9799
12186
|
}
|
|
9800
12187
|
} catch (error) {
|
|
9801
12188
|
process.stdout.write(`
|
|
9802
|
-
Error: ${
|
|
12189
|
+
Error: ${errorMessage6(error)}
|
|
9803
12190
|
`);
|
|
9804
12191
|
}
|
|
9805
12192
|
await reader.question("\nPress Enter to return to the manager...");
|
|
@@ -9922,7 +12309,7 @@ async function ensureMachineIdentity(store) {
|
|
|
9922
12309
|
});
|
|
9923
12310
|
const identity = {
|
|
9924
12311
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
9925
|
-
deviceKeyFingerprint: (0,
|
|
12312
|
+
deviceKeyFingerprint: (0, import_node_crypto10.createHash)("sha256").update(keyPair.publicKey, "utf8").digest("hex"),
|
|
9926
12313
|
publicKeyPem: keyPair.publicKey
|
|
9927
12314
|
};
|
|
9928
12315
|
await store.writePrivateKey(keyPair.privateKey);
|
|
@@ -9938,12 +12325,12 @@ function decryptPairingCredentials(privateKeyPem, encryptedCredentials) {
|
|
|
9938
12325
|
if (envelope.version !== 1 || envelope.algorithm !== "RSA-OAEP-256+A256GCM") {
|
|
9939
12326
|
throw new Error("Unsupported Local Machine credentials envelope");
|
|
9940
12327
|
}
|
|
9941
|
-
const encryptionKey = (0,
|
|
12328
|
+
const encryptionKey = (0, import_node_crypto10.privateDecrypt)({
|
|
9942
12329
|
key: privateKeyPem,
|
|
9943
12330
|
oaepHash: "sha256",
|
|
9944
|
-
padding:
|
|
12331
|
+
padding: import_node_crypto10.constants.RSA_PKCS1_OAEP_PADDING
|
|
9945
12332
|
}, Buffer.from(envelope.encryptedKey, "base64url"));
|
|
9946
|
-
const decipher = (0,
|
|
12333
|
+
const decipher = (0, import_node_crypto10.createDecipheriv)("aes-256-gcm", encryptionKey, Buffer.from(envelope.initializationVector, "base64url"));
|
|
9947
12334
|
decipher.setAuthTag(Buffer.from(envelope.authenticationTag, "base64url"));
|
|
9948
12335
|
const decrypted = Buffer.concat([
|
|
9949
12336
|
decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
|
|
@@ -9951,14 +12338,14 @@ function decryptPairingCredentials(privateKeyPem, encryptedCredentials) {
|
|
|
9951
12338
|
]);
|
|
9952
12339
|
return JSON.parse(decrypted.toString("utf8"));
|
|
9953
12340
|
}
|
|
9954
|
-
var
|
|
12341
|
+
var import_node_crypto10, import_node_util5, generateKeyPairAsync;
|
|
9955
12342
|
var init_device_identity = __esm({
|
|
9956
12343
|
"../machine-connector/dist/runtime/device-identity.js"() {
|
|
9957
12344
|
"use strict";
|
|
9958
12345
|
init_cjs_shims();
|
|
9959
|
-
|
|
12346
|
+
import_node_crypto10 = require("crypto");
|
|
9960
12347
|
import_node_util5 = require("util");
|
|
9961
|
-
generateKeyPairAsync = (0, import_node_util5.promisify)(
|
|
12348
|
+
generateKeyPairAsync = (0, import_node_util5.promisify)(import_node_crypto10.generateKeyPair);
|
|
9962
12349
|
}
|
|
9963
12350
|
});
|
|
9964
12351
|
|
|
@@ -9967,9 +12354,9 @@ async function pairMachine(store, options) {
|
|
|
9967
12354
|
await store.initialize();
|
|
9968
12355
|
const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
|
|
9969
12356
|
const identity = await ensureMachineIdentity(store);
|
|
9970
|
-
const machineName = options.machineName ?? (0,
|
|
12357
|
+
const machineName = options.machineName ?? (0, import_node_os8.hostname)();
|
|
9971
12358
|
const operatingSystem = getOperatingSystem();
|
|
9972
|
-
const rootHandle = (0,
|
|
12359
|
+
const rootHandle = (0, import_node_crypto11.createHash)("sha256").update(identity.identity.deviceKeyFingerprint, "utf8").update("\0").update(canonicalRoot, "utf8").digest("base64url");
|
|
9973
12360
|
const client = new PairingRelayClient(options.relayOrigin);
|
|
9974
12361
|
const proposal = await client.propose({
|
|
9975
12362
|
connectionCode: options.connectionCode,
|
|
@@ -9978,7 +12365,7 @@ async function pairMachine(store, options) {
|
|
|
9978
12365
|
machineName,
|
|
9979
12366
|
operatingSystem,
|
|
9980
12367
|
protocolVersion: machineProtocolVersion,
|
|
9981
|
-
rootDisplayName: (0,
|
|
12368
|
+
rootDisplayName: (0, import_node_path12.basename)(canonicalRoot),
|
|
9982
12369
|
rootHandle
|
|
9983
12370
|
});
|
|
9984
12371
|
options.onConfirmation?.(proposal.confirmationUrl);
|
|
@@ -10004,9 +12391,10 @@ async function pairMachine(store, options) {
|
|
|
10004
12391
|
machineId: credentials.machineId,
|
|
10005
12392
|
machineName,
|
|
10006
12393
|
operatingSystem,
|
|
12394
|
+
purpose: credentials.purpose,
|
|
10007
12395
|
refreshToken: credentials.refreshToken,
|
|
10008
12396
|
relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
|
|
10009
|
-
rootDisplayName: (0,
|
|
12397
|
+
rootDisplayName: (0, import_node_path12.basename)(canonicalRoot),
|
|
10010
12398
|
rootHandle,
|
|
10011
12399
|
rootPath: canonicalRoot,
|
|
10012
12400
|
targetId: credentials.targetId,
|
|
@@ -10027,17 +12415,17 @@ async function pairMachine(store, options) {
|
|
|
10027
12415
|
throw new Error("Local Machine pairing expired");
|
|
10028
12416
|
}
|
|
10029
12417
|
function getOperatingSystem() {
|
|
10030
|
-
if ((0,
|
|
12418
|
+
if ((0, import_node_os8.platform)() === "darwin") {
|
|
10031
12419
|
return MachineOperatingSystem.MacOS;
|
|
10032
12420
|
}
|
|
10033
|
-
if ((0,
|
|
12421
|
+
if ((0, import_node_os8.platform)() === "linux") {
|
|
10034
12422
|
return MachineOperatingSystem.Linux;
|
|
10035
12423
|
}
|
|
10036
12424
|
return MachineOperatingSystem.Windows;
|
|
10037
12425
|
}
|
|
10038
12426
|
function openBrowser(url) {
|
|
10039
|
-
const command = (0,
|
|
10040
|
-
const child = (0,
|
|
12427
|
+
const command = (0, import_node_os8.platform)() === "darwin" ? "open" : "xdg-open";
|
|
12428
|
+
const child = (0, import_node_child_process8.execFile)(command, [url], () => void 0);
|
|
10041
12429
|
child.unref();
|
|
10042
12430
|
}
|
|
10043
12431
|
function delay7(milliseconds) {
|
|
@@ -10045,15 +12433,15 @@ function delay7(milliseconds) {
|
|
|
10045
12433
|
setTimeout(resolvePromise, milliseconds);
|
|
10046
12434
|
});
|
|
10047
12435
|
}
|
|
10048
|
-
var
|
|
12436
|
+
var import_node_child_process8, import_node_crypto11, import_node_os8, import_node_path12, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
|
|
10049
12437
|
var init_pairing = __esm({
|
|
10050
12438
|
"../machine-connector/dist/runtime/pairing.js"() {
|
|
10051
12439
|
"use strict";
|
|
10052
12440
|
init_cjs_shims();
|
|
10053
|
-
|
|
10054
|
-
|
|
10055
|
-
|
|
10056
|
-
|
|
12441
|
+
import_node_child_process8 = require("child_process");
|
|
12442
|
+
import_node_crypto11 = require("crypto");
|
|
12443
|
+
import_node_os8 = require("os");
|
|
12444
|
+
import_node_path12 = require("path");
|
|
10057
12445
|
init_contracts();
|
|
10058
12446
|
init_version();
|
|
10059
12447
|
init_enums();
|
|
@@ -10141,7 +12529,7 @@ function isMachineLifecycleMutation(command, commandArguments) {
|
|
|
10141
12529
|
async function connectCommand(store, argumentsList, entrypoint) {
|
|
10142
12530
|
const options = parseOptions(argumentsList);
|
|
10143
12531
|
const connectionCode = requiredOption(options, "code");
|
|
10144
|
-
const rootPath = (0,
|
|
12532
|
+
const rootPath = (0, import_node_path13.resolve)(options.root ?? process.cwd());
|
|
10145
12533
|
const serviceManagerPreference = requestedServiceManagerPreference(options);
|
|
10146
12534
|
await validateExplicitServiceManagerPreference(serviceManagerPreference);
|
|
10147
12535
|
writeLine("Internal Full Host Access: enabled");
|
|
@@ -10209,6 +12597,7 @@ async function statusCommand(store, argumentsList) {
|
|
|
10209
12597
|
connections: connections.map((connection) => ({
|
|
10210
12598
|
connectionId: connection.connectionId,
|
|
10211
12599
|
machineName: connection.machineName,
|
|
12600
|
+
purpose: connection.purpose,
|
|
10212
12601
|
relayOrigin: connection.relayOrigin,
|
|
10213
12602
|
rootDisplayName: connection.rootDisplayName,
|
|
10214
12603
|
rootPath: connection.rootPath,
|
|
@@ -10455,13 +12844,13 @@ function delay8(milliseconds) {
|
|
|
10455
12844
|
setTimeout(resolvePromise, milliseconds);
|
|
10456
12845
|
});
|
|
10457
12846
|
}
|
|
10458
|
-
var import_promises18,
|
|
12847
|
+
var import_promises18, import_node_path13, defaultRelayOrigin;
|
|
10459
12848
|
var init_cli = __esm({
|
|
10460
12849
|
"../machine-connector/dist/cli.js"() {
|
|
10461
12850
|
"use strict";
|
|
10462
12851
|
init_cjs_shims();
|
|
10463
12852
|
import_promises18 = require("fs/promises");
|
|
10464
|
-
|
|
12853
|
+
import_node_path13 = require("path");
|
|
10465
12854
|
init_daemon();
|
|
10466
12855
|
init_daemon_reconcile();
|
|
10467
12856
|
init_doctor();
|
|
@@ -10485,6 +12874,7 @@ __export(dist_exports, {
|
|
|
10485
12874
|
LocalIpcServer: () => LocalIpcServer,
|
|
10486
12875
|
MachineClaudePermissionMode: () => MachineClaudePermissionMode,
|
|
10487
12876
|
MachineCodexPermissionMode: () => MachineCodexPermissionMode,
|
|
12877
|
+
MachineConnectionPurpose: () => MachineConnectionPurpose,
|
|
10488
12878
|
MachineConnectionRevokedError: () => MachineConnectionRevokedError,
|
|
10489
12879
|
MachineConnectionStatus: () => MachineConnectionStatus,
|
|
10490
12880
|
MachineConnectionTargetKind: () => MachineConnectionTargetKind,
|
|
@@ -10751,7 +13141,7 @@ function getApiKeyOrUndefined() {
|
|
|
10751
13141
|
|
|
10752
13142
|
// src/utils/http.ts
|
|
10753
13143
|
function getUserAgent() {
|
|
10754
|
-
return `moxt-cli/${"0.9.
|
|
13144
|
+
return `moxt-cli/${"0.9.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
|
|
10755
13145
|
}
|
|
10756
13146
|
async function sendRequest(method, path4, init) {
|
|
10757
13147
|
return await fetch(`${getApiBaseUrl()}${path4}`, {
|
|
@@ -18139,7 +20529,7 @@ function chunkedPush(list2, right) {
|
|
|
18139
20529
|
function subtokenize(eventsArray) {
|
|
18140
20530
|
const jumps = {};
|
|
18141
20531
|
let index2 = -1;
|
|
18142
|
-
let
|
|
20532
|
+
let event2;
|
|
18143
20533
|
let lineIndex;
|
|
18144
20534
|
let otherIndex;
|
|
18145
20535
|
let otherEvent;
|
|
@@ -18151,9 +20541,9 @@ function subtokenize(eventsArray) {
|
|
|
18151
20541
|
while (index2 in jumps) {
|
|
18152
20542
|
index2 = jumps[index2];
|
|
18153
20543
|
}
|
|
18154
|
-
|
|
18155
|
-
if (index2 &&
|
|
18156
|
-
subevents =
|
|
20544
|
+
event2 = events.get(index2);
|
|
20545
|
+
if (index2 && event2[1].type === "chunkFlow" && events.get(index2 - 1)[1].type === "listItemPrefix") {
|
|
20546
|
+
subevents = event2[1]._tokenizer.events;
|
|
18157
20547
|
otherIndex = 0;
|
|
18158
20548
|
if (otherIndex < subevents.length && subevents[otherIndex][1].type === "lineEndingBlank") {
|
|
18159
20549
|
otherIndex += 2;
|
|
@@ -18170,13 +20560,13 @@ function subtokenize(eventsArray) {
|
|
|
18170
20560
|
}
|
|
18171
20561
|
}
|
|
18172
20562
|
}
|
|
18173
|
-
if (
|
|
18174
|
-
if (
|
|
20563
|
+
if (event2[0] === "enter") {
|
|
20564
|
+
if (event2[1].contentType) {
|
|
18175
20565
|
Object.assign(jumps, subcontent(events, index2));
|
|
18176
20566
|
index2 = jumps[index2];
|
|
18177
20567
|
more = true;
|
|
18178
20568
|
}
|
|
18179
|
-
} else if (
|
|
20569
|
+
} else if (event2[1]._container) {
|
|
18180
20570
|
otherIndex = index2;
|
|
18181
20571
|
lineIndex = void 0;
|
|
18182
20572
|
while (otherIndex--) {
|
|
@@ -18195,11 +20585,11 @@ function subtokenize(eventsArray) {
|
|
|
18195
20585
|
}
|
|
18196
20586
|
}
|
|
18197
20587
|
if (lineIndex) {
|
|
18198
|
-
|
|
20588
|
+
event2[1].end = {
|
|
18199
20589
|
...events.get(lineIndex)[1].start
|
|
18200
20590
|
};
|
|
18201
20591
|
parameters = events.slice(lineIndex, index2);
|
|
18202
|
-
parameters.unshift(
|
|
20592
|
+
parameters.unshift(event2);
|
|
18203
20593
|
events.splice(lineIndex, index2 - lineIndex + 1, parameters);
|
|
18204
20594
|
}
|
|
18205
20595
|
}
|
|
@@ -21041,12 +23431,12 @@ function compiler(options) {
|
|
|
21041
23431
|
let firstBlankLineIndex;
|
|
21042
23432
|
let atMarker;
|
|
21043
23433
|
while (++index2 <= length) {
|
|
21044
|
-
const
|
|
21045
|
-
switch (
|
|
23434
|
+
const event2 = events[index2];
|
|
23435
|
+
switch (event2[1].type) {
|
|
21046
23436
|
case "listUnordered":
|
|
21047
23437
|
case "listOrdered":
|
|
21048
23438
|
case "blockQuote": {
|
|
21049
|
-
if (
|
|
23439
|
+
if (event2[0] === "enter") {
|
|
21050
23440
|
containerBalance++;
|
|
21051
23441
|
} else {
|
|
21052
23442
|
containerBalance--;
|
|
@@ -21055,7 +23445,7 @@ function compiler(options) {
|
|
|
21055
23445
|
break;
|
|
21056
23446
|
}
|
|
21057
23447
|
case "lineEndingBlank": {
|
|
21058
|
-
if (
|
|
23448
|
+
if (event2[0] === "enter") {
|
|
21059
23449
|
if (listItem2 && !atMarker && !containerBalance && !firstBlankLineIndex) {
|
|
21060
23450
|
firstBlankLineIndex = index2;
|
|
21061
23451
|
}
|
|
@@ -21074,7 +23464,7 @@ function compiler(options) {
|
|
|
21074
23464
|
atMarker = void 0;
|
|
21075
23465
|
}
|
|
21076
23466
|
}
|
|
21077
|
-
if (!containerBalance &&
|
|
23467
|
+
if (!containerBalance && event2[0] === "enter" && event2[1].type === "listItemPrefix" || containerBalance === -1 && event2[0] === "exit" && (event2[1].type === "listUnordered" || event2[1].type === "listOrdered")) {
|
|
21078
23468
|
if (listItem2) {
|
|
21079
23469
|
let tailIndex = index2;
|
|
21080
23470
|
lineIndex = void 0;
|
|
@@ -21096,21 +23486,21 @@ function compiler(options) {
|
|
|
21096
23486
|
if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) {
|
|
21097
23487
|
listItem2._spread = true;
|
|
21098
23488
|
}
|
|
21099
|
-
listItem2.end = Object.assign({}, lineIndex ? events[lineIndex][1].start :
|
|
21100
|
-
events.splice(lineIndex || index2, 0, ["exit", listItem2,
|
|
23489
|
+
listItem2.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event2[1].end);
|
|
23490
|
+
events.splice(lineIndex || index2, 0, ["exit", listItem2, event2[2]]);
|
|
21101
23491
|
index2++;
|
|
21102
23492
|
length++;
|
|
21103
23493
|
}
|
|
21104
|
-
if (
|
|
23494
|
+
if (event2[1].type === "listItemPrefix") {
|
|
21105
23495
|
const item = {
|
|
21106
23496
|
type: "listItem",
|
|
21107
23497
|
_spread: false,
|
|
21108
|
-
start: Object.assign({},
|
|
23498
|
+
start: Object.assign({}, event2[1].start),
|
|
21109
23499
|
// @ts-expect-error: we’ll add `end` in a second.
|
|
21110
23500
|
end: void 0
|
|
21111
23501
|
};
|
|
21112
23502
|
listItem2 = item;
|
|
21113
|
-
events.splice(index2, 0, ["enter", item,
|
|
23503
|
+
events.splice(index2, 0, ["enter", item, event2[2]]);
|
|
21114
23504
|
index2++;
|
|
21115
23505
|
length++;
|
|
21116
23506
|
firstBlankLineIndex = void 0;
|
|
@@ -22753,7 +25143,7 @@ var path2 = __toESM(require("path"), 1);
|
|
|
22753
25143
|
function readCliConfig() {
|
|
22754
25144
|
try {
|
|
22755
25145
|
const parsed = JSON.parse(fs4.readFileSync(getConfigPath(), "utf8"));
|
|
22756
|
-
return
|
|
25146
|
+
return isRecord5(parsed) ? parsed : {};
|
|
22757
25147
|
} catch {
|
|
22758
25148
|
return {};
|
|
22759
25149
|
}
|
|
@@ -22766,7 +25156,7 @@ function writeCliConfig(config) {
|
|
|
22766
25156
|
function getConfigPath() {
|
|
22767
25157
|
return path2.join(os.homedir(), ".moxt", "config.json");
|
|
22768
25158
|
}
|
|
22769
|
-
function
|
|
25159
|
+
function isRecord5(value) {
|
|
22770
25160
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22771
25161
|
}
|
|
22772
25162
|
|
|
@@ -22828,7 +25218,7 @@ init_cjs_shims();
|
|
|
22828
25218
|
|
|
22829
25219
|
// src/update/install.ts
|
|
22830
25220
|
init_cjs_shims();
|
|
22831
|
-
var
|
|
25221
|
+
var import_node_child_process9 = require("child_process");
|
|
22832
25222
|
var import_node_fs2 = require("fs");
|
|
22833
25223
|
var path3 = __toESM(require("path"), 1);
|
|
22834
25224
|
|
|
@@ -22944,7 +25334,7 @@ function runUpgrade(channel, targetVersion) {
|
|
|
22944
25334
|
}
|
|
22945
25335
|
process.stderr.write(`Updating via \`${display}\`...
|
|
22946
25336
|
`);
|
|
22947
|
-
const installation = (0,
|
|
25337
|
+
const installation = (0, import_node_child_process9.spawnSync)(plan.command, plan.args, {
|
|
22948
25338
|
encoding: "utf8",
|
|
22949
25339
|
env: process.env,
|
|
22950
25340
|
maxBuffer: 10 * 1024 * 1024,
|
|
@@ -22959,7 +25349,7 @@ function runUpgrade(channel, targetVersion) {
|
|
|
22959
25349
|
success: false
|
|
22960
25350
|
};
|
|
22961
25351
|
}
|
|
22962
|
-
const verification = (0,
|
|
25352
|
+
const verification = (0, import_node_child_process9.spawnSync)("moxt", ["--version"], {
|
|
22963
25353
|
encoding: "utf8",
|
|
22964
25354
|
env: process.env,
|
|
22965
25355
|
maxBuffer: 1024 * 1024,
|
|
@@ -22973,7 +25363,7 @@ function runUpgrade(channel, targetVersion) {
|
|
|
22973
25363
|
success: false
|
|
22974
25364
|
};
|
|
22975
25365
|
}
|
|
22976
|
-
const daemonRefresh = (0,
|
|
25366
|
+
const daemonRefresh = (0, import_node_child_process9.spawnSync)(
|
|
22977
25367
|
"moxt",
|
|
22978
25368
|
["machine", "daemon-reconcile", "--report"],
|
|
22979
25369
|
{
|
|
@@ -23042,7 +25432,7 @@ init_cjs_shims();
|
|
|
23042
25432
|
init_cjs_shims();
|
|
23043
25433
|
function readUpdateConfig() {
|
|
23044
25434
|
const update = readCliConfig().update;
|
|
23045
|
-
if (!
|
|
25435
|
+
if (!isRecord6(update)) return {};
|
|
23046
25436
|
return {
|
|
23047
25437
|
...update.channel === "latest" || update.channel === "beta" ? { channel: update.channel } : {},
|
|
23048
25438
|
...typeof update.disabled === "boolean" ? { disabled: update.disabled } : {},
|
|
@@ -23055,7 +25445,7 @@ function writeUpdateConfig(update) {
|
|
|
23055
25445
|
const existing = readCliConfig();
|
|
23056
25446
|
writeCliConfig({ ...existing, update });
|
|
23057
25447
|
}
|
|
23058
|
-
function
|
|
25448
|
+
function isRecord6(value) {
|
|
23059
25449
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
23060
25450
|
}
|
|
23061
25451
|
|
|
@@ -23953,7 +26343,7 @@ function registerTaskCommands(workflow) {
|
|
|
23953
26343
|
})
|
|
23954
26344
|
);
|
|
23955
26345
|
startSpinner("Fetching workflow tasks...");
|
|
23956
|
-
const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-
|
|
26346
|
+
const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v4${query}`);
|
|
23957
26347
|
if (!response.ok) {
|
|
23958
26348
|
stopSpinner(false, "Failed");
|
|
23959
26349
|
failResponse(response);
|
|
@@ -24328,16 +26718,16 @@ function createProgram(version) {
|
|
|
24328
26718
|
|
|
24329
26719
|
// src/telemetry/client.ts
|
|
24330
26720
|
init_cjs_shims();
|
|
24331
|
-
var
|
|
26721
|
+
var import_node_os9 = require("os");
|
|
24332
26722
|
var buffer = [];
|
|
24333
26723
|
var FLUSH_TIMEOUT_MS = 3e3;
|
|
24334
26724
|
var MAX_BATCH_SIZE = 100;
|
|
24335
26725
|
function commonLabels() {
|
|
24336
26726
|
return {
|
|
24337
|
-
cli_version: "0.9.
|
|
26727
|
+
cli_version: "0.9.1",
|
|
24338
26728
|
node_version: process.versions.node,
|
|
24339
|
-
os: (0,
|
|
24340
|
-
arch: (0,
|
|
26729
|
+
os: (0, import_node_os9.platform)(),
|
|
26730
|
+
arch: (0, import_node_os9.arch)(),
|
|
24341
26731
|
is_ci: isCiEnvironment() ? "true" : "false"
|
|
24342
26732
|
};
|
|
24343
26733
|
}
|
|
@@ -24380,7 +26770,7 @@ async function flush() {
|
|
|
24380
26770
|
}
|
|
24381
26771
|
const batch = buffer.splice(0, MAX_BATCH_SIZE);
|
|
24382
26772
|
const payload = {
|
|
24383
|
-
release_id: "0.9.
|
|
26773
|
+
release_id: "0.9.1",
|
|
24384
26774
|
client_type: "cli",
|
|
24385
26775
|
metric_data_list: batch.map((m) => ({
|
|
24386
26776
|
profile: "cli",
|
|
@@ -24697,7 +27087,7 @@ function commandPath2(command) {
|
|
|
24697
27087
|
|
|
24698
27088
|
// src/update/daemon-reconcile-hook.ts
|
|
24699
27089
|
init_cjs_shims();
|
|
24700
|
-
var
|
|
27090
|
+
var import_node_path14 = require("path");
|
|
24701
27091
|
function installDaemonReconcileHook(program3, cliVersion) {
|
|
24702
27092
|
program3.hook("preAction", async (_thisCommand, actionCommand) => {
|
|
24703
27093
|
if (!isEligible2(actionCommand)) return;
|
|
@@ -24719,9 +27109,9 @@ function installDaemonReconcileHook(program3, cliVersion) {
|
|
|
24719
27109
|
await reconcileManagedDaemon2({
|
|
24720
27110
|
cliVersion,
|
|
24721
27111
|
commandArguments: ["machine", "daemon"],
|
|
24722
|
-
entrypointPath: (0,
|
|
27112
|
+
entrypointPath: (0, import_node_path14.resolve)(entrypointPath),
|
|
24723
27113
|
environment: {},
|
|
24724
|
-
nodePath: (0,
|
|
27114
|
+
nodePath: (0, import_node_path14.resolve)(process.execPath),
|
|
24725
27115
|
onActiveJobs: (count) => {
|
|
24726
27116
|
process.stderr.write(
|
|
24727
27117
|
`Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
|
|
@@ -24763,9 +27153,9 @@ function commandPath3(command) {
|
|
|
24763
27153
|
}
|
|
24764
27154
|
|
|
24765
27155
|
// src/index.ts
|
|
24766
|
-
var program2 = createProgram("0.9.
|
|
24767
|
-
installDaemonReconcileHook(program2, "0.9.
|
|
24768
|
-
installUpdateHook(program2, "0.9.
|
|
27156
|
+
var program2 = createProgram("0.9.1");
|
|
27157
|
+
installDaemonReconcileHook(program2, "0.9.1");
|
|
27158
|
+
installUpdateHook(program2, "0.9.1");
|
|
24769
27159
|
instrumentProgram(program2);
|
|
24770
27160
|
installExitHandler();
|
|
24771
27161
|
program2.parseAsync(process.argv).then(async () => {
|