@neuralnomads/codenomad-dev 0.18.0-dev-20260715-07e8ce68 → 0.18.0-dev-20260718-8f6aa44b
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/README.md +12 -0
- package/THIRD_PARTY_NOTICES.md +26 -0
- package/dist/auth/manager.js +1 -1
- package/dist/events/bus.js +13 -0
- package/dist/events/bus.test.js +37 -0
- package/dist/filesystem/__tests__/search-cache.test.js +5 -5
- package/dist/filesystem/search-cache.js +1 -1
- package/dist/index.js +58 -56
- package/dist/index.test.js +62 -0
- package/dist/opencode-update/service.js +150 -0
- package/dist/opencode-update/service.test.js +107 -0
- package/dist/server/__tests__/remote-proxy.test.js +151 -47
- package/dist/server/http-server.js +9 -1
- package/dist/server/remote-proxy.js +91 -34
- package/dist/server/routes/opencode-update.js +37 -0
- package/dist/server/routes/opencode-update.test.js +34 -0
- package/dist/server/routes/remote-servers.js +1 -1
- package/dist/server/routes/usage.js +18 -0
- package/dist/server/routes/usage.test.js +26 -0
- package/dist/server/routes/workspaces.js +32 -1
- package/dist/server/routes/workspaces.test.js +113 -0
- package/dist/server/tls.js +2 -2
- package/dist/settings/binaries.js +4 -1
- package/dist/settings/binaries.test.js +19 -0
- package/dist/shutdown.js +83 -0
- package/dist/shutdown.test.js +148 -0
- package/dist/ui/remote-ui.js +2 -2
- package/dist/usage/providers/api-key.js +171 -0
- package/dist/usage/providers/google.js +171 -0
- package/dist/usage/providers/minimax.js +109 -0
- package/dist/usage/providers/oauth.js +111 -0
- package/dist/usage/providers/special.js +148 -0
- package/dist/usage/service.js +83 -0
- package/dist/usage/service.test.js +59 -0
- package/dist/usage/shared.js +130 -0
- package/dist/usage/shared.test.js +33 -0
- package/dist/usage/types.js +1 -0
- package/dist/workspaces/__tests__/spawn.test.js +64 -7
- package/dist/workspaces/__tests__/workspace-identity.test.js +99 -139
- package/dist/workspaces/binary-path.test.js +10 -0
- package/dist/workspaces/instance-client.js +4 -3
- package/dist/workspaces/launch-cleanup.test.js +29 -0
- package/dist/workspaces/manager.js +399 -192
- package/dist/workspaces/manager.test.js +290 -0
- package/dist/workspaces/process-identity.darwin.test.js +88 -0
- package/dist/workspaces/process-identity.js +431 -0
- package/dist/workspaces/process-identity.test.js +111 -0
- package/dist/workspaces/runtime.js +471 -138
- package/dist/workspaces/runtime.test.js +278 -0
- package/dist/workspaces/spawn.js +86 -15
- package/package.json +1 -1
- package/public/assets/{FilesTab-EPvldvn1.js → FilesTab-B0-DlSCT.js} +2 -2
- package/public/assets/{GitChangesTab-ofjovmv2.js → GitChangesTab-CxjbNBVr.js} +2 -2
- package/public/assets/{SplitFilePanel-CyoPkcLd.js → SplitFilePanel-CLQb-6uX.js} +1 -1
- package/public/assets/StatusTab-CBGAuhmp.js +1 -0
- package/public/assets/{align-justify-Bcf1-ZOl.js → align-justify-s5mnjsP0.js} +1 -1
- package/public/assets/{bundle-full-D5dzvToA.js → bundle-full-lwIMY5om.js} +1 -1
- package/public/assets/{diff-viewer-DViXCI-4.js → diff-viewer-CDtmFe6e.js} +1 -1
- package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
- package/public/assets/index-6ABz_Izb.js +1 -0
- package/public/assets/index-BPdjM9ZI.css +1 -0
- package/public/assets/index-BQK8um1r.js +1 -0
- package/public/assets/index-BkUAI4ZY.js +1 -0
- package/public/assets/index-D8bkUvEd.js +2 -0
- package/public/assets/index-DY_sbCt9.js +1 -0
- package/public/assets/index-DhmUOdAI.js +1 -0
- package/public/assets/{index-UbL8tz_V.js → index-DupnEKCQ.js} +1 -1
- package/public/assets/index-HhZzWWha.js +1 -0
- package/public/assets/{index-lf4nUOU1.js → index-lBAEWdAF.js} +1 -1
- package/public/assets/index-nVII4VJz.js +1 -0
- package/public/assets/index-p1Sble5V.js +1 -0
- package/public/assets/{loading-CZ_tt3h0.js → loading-h8DvUqqc.js} +1 -1
- package/public/assets/main-BxUSjoWA.js +68 -0
- package/public/assets/{markdown-G11aN6hz.js → markdown-Djug_spc.js} +55 -44
- package/public/assets/monaco-viewer-lkUcsK65.js +26 -0
- package/public/assets/{tool-call-BsSXWErm.js → tool-call-C4YH896w.js} +32 -32
- package/public/assets/{unified-picker-BRNI3UvE.js → unified-picker-DwNZOVlY.js} +1 -1
- package/public/assets/{wrap-text-B7up-uv7.js → wrap-text-BLVYxvcj.js} +1 -1
- package/public/index.html +5 -5
- package/public/loading.html +5 -5
- package/public/sw.js +1 -1
- package/public/assets/StatusTab-Bgu1Fh24.js +0 -1
- package/public/assets/index-3KsjbWGP.js +0 -1
- package/public/assets/index-B0WK8-cF.js +0 -1
- package/public/assets/index-BDv_iVtj.js +0 -1
- package/public/assets/index-BMvFMsuy.css +0 -1
- package/public/assets/index-BjxZvyb9.js +0 -2
- package/public/assets/index-BleKf9Nj.js +0 -1
- package/public/assets/index-CiIQ43NW.js +0 -1
- package/public/assets/index-DBquqL6Q.js +0 -1
- package/public/assets/index-yf9zolv4.js +0 -1
- package/public/assets/index-ypaL7i_s.js +0 -1
- package/public/assets/main-CAkg_fp_.js +0 -68
- package/public/assets/monaco-viewer-CZefBfct.js +0 -26
|
@@ -7,6 +7,8 @@ import { resolveWorktreeDirectory } from "../../workspaces/worktree-directory";
|
|
|
7
7
|
const WorkspaceCreateSchema = z.object({
|
|
8
8
|
path: z.string(),
|
|
9
9
|
name: z.string().optional(),
|
|
10
|
+
binaryPath: z.string().trim().min(1).max(4096).optional(),
|
|
11
|
+
requestId: z.string().trim().min(1).max(128).optional(),
|
|
10
12
|
forceNew: z.boolean().optional(),
|
|
11
13
|
});
|
|
12
14
|
const WorkspaceCloneSchema = z.object({
|
|
@@ -14,6 +16,9 @@ const WorkspaceCloneSchema = z.object({
|
|
|
14
16
|
destinationPath: z.string().trim().min(1, "Destination path is required"),
|
|
15
17
|
cleanup: z.boolean().optional(),
|
|
16
18
|
});
|
|
19
|
+
const WorkspaceCreationReleaseSchema = z.object({
|
|
20
|
+
requestId: z.string().trim().min(1).max(128),
|
|
21
|
+
});
|
|
17
22
|
const WorkspaceFilesQuerySchema = z.object({
|
|
18
23
|
path: z.string().optional(),
|
|
19
24
|
});
|
|
@@ -52,7 +57,11 @@ export function registerWorkspaceRoutes(app, deps) {
|
|
|
52
57
|
app.post("/api/workspaces", async (request, reply) => {
|
|
53
58
|
try {
|
|
54
59
|
const body = WorkspaceCreateSchema.parse(request.body ?? {});
|
|
55
|
-
const result = await deps.workspaceManager.create(body.path, body.name, {
|
|
60
|
+
const result = await deps.workspaceManager.create(body.path, body.name, {
|
|
61
|
+
binaryPath: body.binaryPath,
|
|
62
|
+
requestId: body.requestId,
|
|
63
|
+
forceNew: body.forceNew,
|
|
64
|
+
});
|
|
56
65
|
reply.code(201);
|
|
57
66
|
return result.created ? result.workspace : { ...result.workspace, reused: true };
|
|
58
67
|
}
|
|
@@ -85,6 +94,28 @@ export function registerWorkspaceRoutes(app, deps) {
|
|
|
85
94
|
await deps.workspaceManager.delete(request.params.id);
|
|
86
95
|
reply.code(204);
|
|
87
96
|
});
|
|
97
|
+
app.post("/api/workspaces/creation/cancel", async (request, reply) => {
|
|
98
|
+
const parsed = WorkspaceCreationReleaseSchema.safeParse(request.body ?? {});
|
|
99
|
+
if (!parsed.success) {
|
|
100
|
+
reply.code(400).type("text/plain").send("Invalid workspace creation request");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
await deps.workspaceManager.cancelCreationRequest(parsed.data.requestId);
|
|
104
|
+
reply.code(204);
|
|
105
|
+
});
|
|
106
|
+
app.post("/api/workspaces/:id/creation/release", async (request, reply) => {
|
|
107
|
+
const parsed = WorkspaceCreationReleaseSchema.safeParse(request.body ?? {});
|
|
108
|
+
if (!parsed.success) {
|
|
109
|
+
reply.code(400).type("text/plain").send("Invalid workspace creation request");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const body = parsed.data;
|
|
113
|
+
if (!deps.workspaceManager.releaseCreationRequest(request.params.id, body.requestId)) {
|
|
114
|
+
reply.code(404).type("text/plain").send("Workspace creation request not found");
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
reply.code(204);
|
|
118
|
+
});
|
|
88
119
|
app.get("/api/workspaces/:id/files", async (request, reply) => {
|
|
89
120
|
try {
|
|
90
121
|
const query = WorkspaceFilesQuerySchema.parse(request.query ?? {});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { describe, it } from "node:test";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
import { registerWorkspaceRoutes } from "./workspaces";
|
|
5
|
+
describe("workspace routes", () => {
|
|
6
|
+
it("forwards a validated explicit binary path when creating a workspace", async () => {
|
|
7
|
+
const calls = [];
|
|
8
|
+
const app = Fastify({ logger: false });
|
|
9
|
+
const descriptor = {
|
|
10
|
+
id: "workspace",
|
|
11
|
+
path: "C:/work",
|
|
12
|
+
status: "ready",
|
|
13
|
+
proxyPath: "/workspaces/workspace/instance",
|
|
14
|
+
binaryId: "C:/tools/opencode.exe",
|
|
15
|
+
binaryLabel: "opencode.exe",
|
|
16
|
+
createdAt: "2026-01-01T00:00:00.000Z",
|
|
17
|
+
updatedAt: "2026-01-01T00:00:00.000Z",
|
|
18
|
+
};
|
|
19
|
+
const workspaceManager = {
|
|
20
|
+
create: async (...args) => {
|
|
21
|
+
calls.push(args);
|
|
22
|
+
return { workspace: descriptor, created: true };
|
|
23
|
+
},
|
|
24
|
+
releaseCreationRequest: (workspaceId, requestId) => workspaceId === descriptor.id && requestId === "restore-request",
|
|
25
|
+
cancelCreationRequest: async (requestId) => {
|
|
26
|
+
calls.push(["cancel", requestId]);
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
registerWorkspaceRoutes(app, { workspaceManager });
|
|
30
|
+
const response = await app.inject({
|
|
31
|
+
method: "POST",
|
|
32
|
+
url: "/api/workspaces",
|
|
33
|
+
payload: {
|
|
34
|
+
path: "C:/work",
|
|
35
|
+
name: "Work",
|
|
36
|
+
binaryPath: " C:/tools/opencode.exe ",
|
|
37
|
+
requestId: " restore-request ",
|
|
38
|
+
forceNew: true,
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
assert.equal(response.statusCode, 201);
|
|
42
|
+
assert.deepEqual(calls, [["C:/work", "Work", {
|
|
43
|
+
binaryPath: "C:/tools/opencode.exe",
|
|
44
|
+
requestId: "restore-request",
|
|
45
|
+
forceNew: true,
|
|
46
|
+
}]]);
|
|
47
|
+
const released = await app.inject({
|
|
48
|
+
method: "POST",
|
|
49
|
+
url: "/api/workspaces/workspace/creation/release",
|
|
50
|
+
payload: { requestId: "restore-request" },
|
|
51
|
+
});
|
|
52
|
+
assert.equal(released.statusCode, 204);
|
|
53
|
+
const wrongRelease = await app.inject({
|
|
54
|
+
method: "POST",
|
|
55
|
+
url: "/api/workspaces/workspace/creation/release",
|
|
56
|
+
payload: { requestId: "other-request" },
|
|
57
|
+
});
|
|
58
|
+
assert.equal(wrongRelease.statusCode, 404);
|
|
59
|
+
const cancelled = await app.inject({
|
|
60
|
+
method: "POST",
|
|
61
|
+
url: "/api/workspaces/creation/cancel",
|
|
62
|
+
payload: { requestId: "restore-request" },
|
|
63
|
+
});
|
|
64
|
+
assert.equal(cancelled.statusCode, 204);
|
|
65
|
+
assert.deepEqual(calls.at(-1), ["cancel", "restore-request"]);
|
|
66
|
+
const invalid = await app.inject({
|
|
67
|
+
method: "POST",
|
|
68
|
+
url: "/api/workspaces",
|
|
69
|
+
payload: { path: "C:/work", binaryPath: "x".repeat(4097) },
|
|
70
|
+
});
|
|
71
|
+
assert.equal(invalid.statusCode, 400);
|
|
72
|
+
assert.equal(calls.length, 2);
|
|
73
|
+
await app.close();
|
|
74
|
+
});
|
|
75
|
+
it("rejects release after cancellation wins while deletion is still pending", async () => {
|
|
76
|
+
const app = Fastify({ logger: false });
|
|
77
|
+
let state = "active";
|
|
78
|
+
let cancellationStarted;
|
|
79
|
+
let finishDeletion;
|
|
80
|
+
const started = new Promise((resolve) => { cancellationStarted = resolve; });
|
|
81
|
+
const deletion = new Promise((resolve) => { finishDeletion = resolve; });
|
|
82
|
+
const workspaceManager = {
|
|
83
|
+
cancelCreationRequest: async () => {
|
|
84
|
+
state = "cancelled";
|
|
85
|
+
cancellationStarted();
|
|
86
|
+
await deletion;
|
|
87
|
+
},
|
|
88
|
+
releaseCreationRequest: () => {
|
|
89
|
+
if (state === "cancelled")
|
|
90
|
+
return false;
|
|
91
|
+
state = "released";
|
|
92
|
+
return true;
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
registerWorkspaceRoutes(app, { workspaceManager });
|
|
96
|
+
const cancellation = app.inject({
|
|
97
|
+
method: "POST",
|
|
98
|
+
url: "/api/workspaces/creation/cancel",
|
|
99
|
+
payload: { requestId: "restore-request" },
|
|
100
|
+
});
|
|
101
|
+
await started;
|
|
102
|
+
const release = await app.inject({
|
|
103
|
+
method: "POST",
|
|
104
|
+
url: "/api/workspaces/workspace/creation/release",
|
|
105
|
+
payload: { requestId: "restore-request" },
|
|
106
|
+
});
|
|
107
|
+
assert.equal(release.statusCode, 404);
|
|
108
|
+
assert.equal(release.body, "Workspace creation request not found");
|
|
109
|
+
finishDeletion();
|
|
110
|
+
assert.equal((await cancellation).statusCode, 204);
|
|
111
|
+
await app.close();
|
|
112
|
+
});
|
|
113
|
+
});
|
package/dist/server/tls.js
CHANGED
|
@@ -115,7 +115,7 @@ function generateCaCertificate() {
|
|
|
115
115
|
cert.publicKey = keys.publicKey;
|
|
116
116
|
cert.serialNumber = crypto.randomBytes(16).toString("hex");
|
|
117
117
|
const now = new Date();
|
|
118
|
-
const notBefore = new Date(now.getTime() -
|
|
118
|
+
const notBefore = new Date(now.getTime() - 60_000);
|
|
119
119
|
const notAfter = new Date(now.getTime() + CA_VALIDITY_DAYS * 24 * 60 * 60 * 1000);
|
|
120
120
|
cert.validity.notBefore = notBefore;
|
|
121
121
|
cert.validity.notAfter = notAfter;
|
|
@@ -142,7 +142,7 @@ function generateServerCertificate(args) {
|
|
|
142
142
|
cert.publicKey = keys.publicKey;
|
|
143
143
|
cert.serialNumber = crypto.randomBytes(16).toString("hex");
|
|
144
144
|
const now = new Date();
|
|
145
|
-
const notBefore = new Date(now.getTime() -
|
|
145
|
+
const notBefore = new Date(now.getTime() - 60_000);
|
|
146
146
|
const notAfter = new Date(now.getTime() + LEAF_VALIDITY_DAYS * 24 * 60 * 60 * 1000);
|
|
147
147
|
cert.validity.notBefore = notBefore;
|
|
148
148
|
cert.validity.notAfter = notAfter;
|
|
@@ -23,10 +23,13 @@ export class BinaryResolver {
|
|
|
23
23
|
return readUiBinaries(this.settings);
|
|
24
24
|
}
|
|
25
25
|
resolveDefault() {
|
|
26
|
+
return this.resolve();
|
|
27
|
+
}
|
|
28
|
+
resolve(explicitPath) {
|
|
26
29
|
const binaries = this.list();
|
|
27
30
|
const configuredDefault = readDefaultBinaryPath(this.settings);
|
|
28
31
|
const fallback = binaries[0]?.path;
|
|
29
|
-
const path = configuredDefault
|
|
32
|
+
const path = explicitPath?.trim() || configuredDefault || fallback || "opencode";
|
|
30
33
|
const entry = binaries.find((b) => b.path === path);
|
|
31
34
|
return {
|
|
32
35
|
path,
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { describe, it } from "node:test";
|
|
3
|
+
import { BinaryResolver } from "./binaries";
|
|
4
|
+
describe("BinaryResolver", () => {
|
|
5
|
+
it("uses an explicit workspace binary without changing the configured default", () => {
|
|
6
|
+
const settings = {
|
|
7
|
+
getOwner(scope, owner) {
|
|
8
|
+
if (scope === "config" && owner === "server")
|
|
9
|
+
return { opencodeBinary: "default-opencode" };
|
|
10
|
+
if (scope === "state" && owner === "ui")
|
|
11
|
+
return { opencodeBinaries: [{ path: "saved-opencode", label: "Saved", version: "1.2.3" }] };
|
|
12
|
+
return {};
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
const resolver = new BinaryResolver(settings);
|
|
16
|
+
assert.deepEqual(resolver.resolve("saved-opencode"), { path: "saved-opencode", label: "Saved", version: "1.2.3" });
|
|
17
|
+
assert.equal(resolver.resolveDefault().path, "default-opencode");
|
|
18
|
+
});
|
|
19
|
+
});
|
package/dist/shutdown.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export const SERVER_SHUTDOWN_COMPLETE = "CODENOMAD_SHUTDOWN_STATUS:complete";
|
|
2
|
+
export const SERVER_SHUTDOWN_INCOMPLETE = "CODENOMAD_SHUTDOWN_STATUS:incomplete";
|
|
3
|
+
export function createServerShutdownHandler(options) {
|
|
4
|
+
const forceExit = options.forceExit ?? process.exit;
|
|
5
|
+
const setExitCode = options.setExitCode ?? ((code) => { process.exitCode = code; });
|
|
6
|
+
const reportStatus = options.reportStatus ?? ((status) => console.log(status));
|
|
7
|
+
let pending;
|
|
8
|
+
return (signal) => {
|
|
9
|
+
if (pending) {
|
|
10
|
+
options.logger.error({ signal }, "Additional shutdown signal received; forcing nonzero exit");
|
|
11
|
+
forceExit(1);
|
|
12
|
+
return pending;
|
|
13
|
+
}
|
|
14
|
+
options.logger.info({ signal }, "Received shutdown signal, stopping workspaces and server");
|
|
15
|
+
pending = Promise.resolve().then(options.shutdown).then(() => {
|
|
16
|
+
options.logger.info({}, "Shutdown complete");
|
|
17
|
+
reportStatus(SERVER_SHUTDOWN_COMPLETE);
|
|
18
|
+
setExitCode(0);
|
|
19
|
+
}, async (error) => {
|
|
20
|
+
options.logger.error({ err: error }, "Server shutdown incomplete; retrying cleanup");
|
|
21
|
+
const retryAttempts = Math.max(0, Math.floor(options.retryAttempts ?? 3));
|
|
22
|
+
for (let attempt = 1; attempt <= retryAttempts; attempt += 1) {
|
|
23
|
+
await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs ?? 250));
|
|
24
|
+
try {
|
|
25
|
+
await options.shutdown();
|
|
26
|
+
options.logger.info({}, "Shutdown cleanup retry completed");
|
|
27
|
+
reportStatus(SERVER_SHUTDOWN_COMPLETE);
|
|
28
|
+
setExitCode(0);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
catch (retryError) {
|
|
32
|
+
options.logger.warn({ err: retryError, attempt, attempts: retryAttempts }, "Shutdown cleanup retry remains incomplete");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
options.logger.error({ attempts: retryAttempts }, "Shutdown cleanup retries exhausted; preserving process-tree containment");
|
|
36
|
+
reportStatus(SERVER_SHUTDOWN_INCOMPLETE);
|
|
37
|
+
setExitCode(1);
|
|
38
|
+
if (options.holdAfterFailure)
|
|
39
|
+
await options.holdAfterFailure();
|
|
40
|
+
});
|
|
41
|
+
return pending;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export async function orchestrateServerShutdown(operations, logger, workspaceAttempts = 2) {
|
|
45
|
+
const errors = [];
|
|
46
|
+
const namedError = (name, cause) => Object.assign(new Error(`${name} failed: ${cause instanceof Error ? cause.message : String(cause)}`), { cause });
|
|
47
|
+
const settle = async (pending) => {
|
|
48
|
+
const results = await Promise.allSettled(pending.map(([, run]) => Promise.resolve().then(run)));
|
|
49
|
+
for (let index = 0; index < results.length; index += 1) {
|
|
50
|
+
const result = results[index];
|
|
51
|
+
if (result.status !== "rejected")
|
|
52
|
+
continue;
|
|
53
|
+
const error = namedError(pending[index][0], result.reason);
|
|
54
|
+
errors.push(error);
|
|
55
|
+
logger.error({ err: error }, "Server resource shutdown failed");
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
const workspaceShutdown = (async () => {
|
|
59
|
+
const attempts = Math.max(1, Math.floor(workspaceAttempts));
|
|
60
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
61
|
+
const [result] = await Promise.allSettled([Promise.resolve().then(operations.stopWorkspaces)]);
|
|
62
|
+
if (result.status === "fulfilled")
|
|
63
|
+
break;
|
|
64
|
+
if (attempt < attempts) {
|
|
65
|
+
logger.warn({ err: result.reason, attempt, attempts }, "Workspace manager shutdown failed; retrying cleanup");
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const error = namedError("stopWorkspaces", result.reason);
|
|
69
|
+
errors.push(error);
|
|
70
|
+
logger.error({ err: error, attempts }, "Workspace manager shutdown failed");
|
|
71
|
+
}
|
|
72
|
+
})();
|
|
73
|
+
await Promise.all([
|
|
74
|
+
settle([
|
|
75
|
+
["stopInstanceEventBridge", operations.stopInstanceEventBridge], ["stopSidecars", operations.stopSidecars],
|
|
76
|
+
["stopClientConnections", operations.stopClientConnections], ["stopRemoteProxySessions", operations.stopRemoteProxySessions],
|
|
77
|
+
]),
|
|
78
|
+
workspaceShutdown,
|
|
79
|
+
]);
|
|
80
|
+
await settle([["stopHttpServers", operations.stopHttpServers], ["stopReleaseMonitor", operations.stopReleaseMonitor]]);
|
|
81
|
+
if (errors.length)
|
|
82
|
+
throw new AggregateError(errors, "Server shutdown failed");
|
|
83
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { describe, it } from "node:test";
|
|
3
|
+
import { createServerShutdownHandler, orchestrateServerShutdown, SERVER_SHUTDOWN_COMPLETE, SERVER_SHUTDOWN_INCOMPLETE, } from "./shutdown";
|
|
4
|
+
const logger = { info() { }, warn() { }, error() { } };
|
|
5
|
+
const operations = (overrides = {}) => ({
|
|
6
|
+
stopInstanceEventBridge() { }, stopSidecars() { }, stopClientConnections() { },
|
|
7
|
+
stopRemoteProxySessions() { }, stopWorkspaces() { }, stopHttpServers() { }, stopReleaseMonitor() { },
|
|
8
|
+
...overrides,
|
|
9
|
+
});
|
|
10
|
+
describe("server shutdown orchestration", () => {
|
|
11
|
+
it("retries workspace cleanup and preserves shutdown order", async () => {
|
|
12
|
+
const calls = [];
|
|
13
|
+
let attempts = 0;
|
|
14
|
+
await orchestrateServerShutdown(operations({
|
|
15
|
+
stopRemoteProxySessions: () => { calls.push("remote-proxy"); },
|
|
16
|
+
stopWorkspaces: () => { calls.push(`workspaces-${++attempts}`); if (attempts === 1)
|
|
17
|
+
throw new Error("still alive"); },
|
|
18
|
+
stopHttpServers: () => { calls.push("http"); },
|
|
19
|
+
}), logger);
|
|
20
|
+
assert.deepEqual(calls, ["workspaces-1", "remote-proxy", "workspaces-2", "http"]);
|
|
21
|
+
});
|
|
22
|
+
it("closes remaining resources and aggregates the concrete current error", async () => {
|
|
23
|
+
const failure = new Error("workspace abc POSIX process group is still alive");
|
|
24
|
+
const closed = [];
|
|
25
|
+
let attempts = 0;
|
|
26
|
+
await assert.rejects(orchestrateServerShutdown(operations({
|
|
27
|
+
stopWorkspaces: () => { attempts++; throw failure; },
|
|
28
|
+
stopHttpServers: () => { closed.push("http"); },
|
|
29
|
+
stopReleaseMonitor: () => { closed.push("release-monitor"); },
|
|
30
|
+
}), logger), (error) => {
|
|
31
|
+
assert.ok(error instanceof AggregateError);
|
|
32
|
+
assert.equal(error.errors.length, 1);
|
|
33
|
+
assert.match(error.errors[0].message, /^stopWorkspaces failed:/);
|
|
34
|
+
assert.strictEqual(error.errors[0].cause, failure);
|
|
35
|
+
return true;
|
|
36
|
+
});
|
|
37
|
+
assert.deepEqual([attempts, closed], [2, ["http", "release-monitor"]]);
|
|
38
|
+
});
|
|
39
|
+
it("starts workspace cleanup without waiting for preliminary shutdown", async () => {
|
|
40
|
+
let releasePreliminary;
|
|
41
|
+
const preliminary = new Promise((resolve) => { releasePreliminary = resolve; });
|
|
42
|
+
let workspaceStarted = false;
|
|
43
|
+
const shutdown = orchestrateServerShutdown(operations({
|
|
44
|
+
stopRemoteProxySessions: () => preliminary,
|
|
45
|
+
stopWorkspaces: () => { workspaceStarted = true; },
|
|
46
|
+
}), logger);
|
|
47
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
48
|
+
assert.equal(workspaceStarted, true);
|
|
49
|
+
releasePreliminary();
|
|
50
|
+
await shutdown;
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
describe("server shutdown signal boundary", () => {
|
|
54
|
+
it("reports incomplete cleanup and holds for final tree enforcement", async () => {
|
|
55
|
+
const calls = [];
|
|
56
|
+
const exits = [];
|
|
57
|
+
const statuses = [];
|
|
58
|
+
let releaseHold;
|
|
59
|
+
const hold = new Promise((resolve) => { releaseHold = resolve; });
|
|
60
|
+
const handler = createServerShutdownHandler({
|
|
61
|
+
shutdown: async () => { calls.push("cleanup"); throw new Error("retained child survived"); },
|
|
62
|
+
logger: { info: () => calls.push("info"), warn() { }, error: () => calls.push("error") },
|
|
63
|
+
forceExit: (code) => { calls.push("force-exit"); exits.push(code); },
|
|
64
|
+
setExitCode: () => undefined,
|
|
65
|
+
reportStatus: (status) => statuses.push(status),
|
|
66
|
+
holdAfterFailure: () => hold,
|
|
67
|
+
retryAttempts: 0,
|
|
68
|
+
});
|
|
69
|
+
const pending = handler("SIGTERM");
|
|
70
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
71
|
+
assert.deepEqual([exits, statuses, calls], [[], [SERVER_SHUTDOWN_INCOMPLETE], ["info", "cleanup", "error", "error"]]);
|
|
72
|
+
handler("SIGTERM");
|
|
73
|
+
assert.deepEqual(exits, [1]);
|
|
74
|
+
releaseHold();
|
|
75
|
+
await pending;
|
|
76
|
+
});
|
|
77
|
+
it("reports complete cleanup before allowing natural exit", async () => {
|
|
78
|
+
const statuses = [], exitCodes = [];
|
|
79
|
+
const handler = createServerShutdownHandler({
|
|
80
|
+
shutdown: async () => undefined,
|
|
81
|
+
logger,
|
|
82
|
+
reportStatus: (status) => statuses.push(status),
|
|
83
|
+
setExitCode: (code) => exitCodes.push(code),
|
|
84
|
+
});
|
|
85
|
+
await handler("stdin");
|
|
86
|
+
assert.deepEqual(statuses, [SERVER_SHUTDOWN_COMPLETE]);
|
|
87
|
+
assert.deepEqual(exitCodes, [0]);
|
|
88
|
+
});
|
|
89
|
+
it("keeps retrying identity-aware cleanup during the final enforcement budget", async () => {
|
|
90
|
+
let attempts = 0;
|
|
91
|
+
const statuses = [], exitCodes = [];
|
|
92
|
+
const handler = createServerShutdownHandler({
|
|
93
|
+
shutdown: async () => {
|
|
94
|
+
attempts++;
|
|
95
|
+
if (attempts === 1)
|
|
96
|
+
throw new Error("detached group still alive");
|
|
97
|
+
},
|
|
98
|
+
logger,
|
|
99
|
+
reportStatus: (status) => statuses.push(status),
|
|
100
|
+
setExitCode: (code) => exitCodes.push(code),
|
|
101
|
+
retryDelayMs: 0,
|
|
102
|
+
});
|
|
103
|
+
await handler("stdin");
|
|
104
|
+
assert.equal(attempts, 2);
|
|
105
|
+
assert.deepEqual(statuses, [SERVER_SHUTDOWN_COMPLETE]);
|
|
106
|
+
assert.deepEqual(exitCodes, [0]);
|
|
107
|
+
});
|
|
108
|
+
it("preserves containment after the standalone cleanup retry budget", async () => {
|
|
109
|
+
let attempts = 0;
|
|
110
|
+
const statuses = [], exitCodes = [], forcedExits = [];
|
|
111
|
+
let releaseHold;
|
|
112
|
+
const hold = new Promise((resolve) => { releaseHold = resolve; });
|
|
113
|
+
const handler = createServerShutdownHandler({
|
|
114
|
+
shutdown: async () => { attempts++; throw new Error("process tree remains alive"); },
|
|
115
|
+
logger,
|
|
116
|
+
reportStatus: (status) => statuses.push(status),
|
|
117
|
+
setExitCode: (code) => exitCodes.push(code),
|
|
118
|
+
forceExit: (code) => forcedExits.push(code),
|
|
119
|
+
holdAfterFailure: () => hold,
|
|
120
|
+
retryDelayMs: 0,
|
|
121
|
+
retryAttempts: 2,
|
|
122
|
+
});
|
|
123
|
+
const pending = handler("stdin");
|
|
124
|
+
while (attempts < 3)
|
|
125
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
126
|
+
assert.equal(attempts, 3);
|
|
127
|
+
assert.deepEqual(statuses, [SERVER_SHUTDOWN_INCOMPLETE]);
|
|
128
|
+
assert.deepEqual(exitCodes, [1]);
|
|
129
|
+
assert.deepEqual(forcedExits, []);
|
|
130
|
+
handler("SIGTERM");
|
|
131
|
+
assert.deepEqual(forcedExits, [1]);
|
|
132
|
+
releaseHold();
|
|
133
|
+
await pending;
|
|
134
|
+
});
|
|
135
|
+
it("escalates a second signal while sharing first-signal cleanup", async () => {
|
|
136
|
+
let finish;
|
|
137
|
+
const cleanup = new Promise((resolve) => { finish = resolve; });
|
|
138
|
+
const exits = [], exitCodes = [];
|
|
139
|
+
const handler = createServerShutdownHandler({ shutdown: () => cleanup, logger,
|
|
140
|
+
forceExit: (code) => exits.push(code), setExitCode: (code) => exitCodes.push(code), reportStatus: () => undefined });
|
|
141
|
+
const first = handler("SIGINT"), second = handler("SIGTERM");
|
|
142
|
+
assert.strictEqual(first, second);
|
|
143
|
+
assert.deepEqual(exits, [1]);
|
|
144
|
+
finish();
|
|
145
|
+
await first;
|
|
146
|
+
assert.deepEqual(exitCodes, [0]);
|
|
147
|
+
});
|
|
148
|
+
});
|
package/dist/ui/remote-ui.js
CHANGED
|
@@ -7,8 +7,8 @@ import { Readable } from "stream";
|
|
|
7
7
|
import { fetch } from "undici";
|
|
8
8
|
import yauzl from "yauzl";
|
|
9
9
|
const DEFAULT_MANIFEST_URL = "https://ui.codenomad.neuralnomads.ai/version.json";
|
|
10
|
-
const MANIFEST_TIMEOUT_MS =
|
|
11
|
-
const ZIP_TIMEOUT_MS =
|
|
10
|
+
const MANIFEST_TIMEOUT_MS = 5_000;
|
|
11
|
+
const ZIP_TIMEOUT_MS = 30_000;
|
|
12
12
|
export async function resolveUi(options) {
|
|
13
13
|
const manifestUrl = options.manifestUrl ?? DEFAULT_MANIFEST_URL;
|
|
14
14
|
if (options.uiDevServerUrl) {
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { fetchJson, getCredential, notConfigured, resolveWindowLabel, safeFetch, toNumber, toTimestamp, toUsageWindow, } from "../shared";
|
|
2
|
+
const kimiAliases = ["kimi-for-coding", "kimi"];
|
|
3
|
+
const kimi = {
|
|
4
|
+
id: "kimi-for-coding",
|
|
5
|
+
name: "Kimi for Coding",
|
|
6
|
+
aliases: kimiAliases,
|
|
7
|
+
async fetchQuota() {
|
|
8
|
+
const key = getCredential(kimiAliases, ["key", "token"]);
|
|
9
|
+
if (!key)
|
|
10
|
+
return notConfigured(this.id, this.name);
|
|
11
|
+
return safeFetch(this.id, this.name, async () => {
|
|
12
|
+
const payload = await fetchJson("https://api.kimi.com/coding/v1/usages", {
|
|
13
|
+
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
|
|
14
|
+
});
|
|
15
|
+
const windows = {};
|
|
16
|
+
const usage = payload?.usage;
|
|
17
|
+
if (usage) {
|
|
18
|
+
const limit = toNumber(usage.limit);
|
|
19
|
+
const remaining = toNumber(usage.remaining);
|
|
20
|
+
windows.weekly = toUsageWindow({
|
|
21
|
+
usedPercent: limit && remaining !== null ? 100 - (remaining / limit) * 100 : null,
|
|
22
|
+
resetAt: toTimestamp(usage.resetTime),
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
for (const item of Array.isArray(payload?.limits) ? payload.limits : []) {
|
|
26
|
+
const duration = toNumber(item?.window?.duration);
|
|
27
|
+
const unit = item?.window?.timeUnit;
|
|
28
|
+
const multiplier = unit === "TIME_UNIT_MINUTE" ? 60 : unit === "TIME_UNIT_HOUR" ? 3600 : unit === "TIME_UNIT_DAY" ? 86_400 : null;
|
|
29
|
+
const seconds = duration !== null && multiplier ? duration * multiplier : null;
|
|
30
|
+
const limit = toNumber(item?.detail?.limit);
|
|
31
|
+
const remaining = toNumber(item?.detail?.remaining);
|
|
32
|
+
windows[resolveWindowLabel(seconds)] = toUsageWindow({
|
|
33
|
+
usedPercent: limit && remaining !== null ? 100 - (remaining / limit) * 100 : null,
|
|
34
|
+
windowSeconds: seconds,
|
|
35
|
+
resetAt: toTimestamp(item?.detail?.resetTime),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return { windows };
|
|
39
|
+
});
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
const nanoAliases = ["nano-gpt", "nanogpt", "nano_gpt"];
|
|
43
|
+
const nanoGpt = {
|
|
44
|
+
id: "nano-gpt",
|
|
45
|
+
name: "NanoGPT",
|
|
46
|
+
aliases: nanoAliases,
|
|
47
|
+
async fetchQuota() {
|
|
48
|
+
const key = getCredential(nanoAliases, ["key", "token"]);
|
|
49
|
+
if (!key)
|
|
50
|
+
return notConfigured(this.id, this.name);
|
|
51
|
+
return safeFetch(this.id, this.name, async () => {
|
|
52
|
+
const payload = await fetchJson("https://nano-gpt.com/api/subscription/v1/usage", {
|
|
53
|
+
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
|
|
54
|
+
});
|
|
55
|
+
const windows = {};
|
|
56
|
+
for (const [label, source] of [["daily", payload?.daily], ["monthly", payload?.monthly]]) {
|
|
57
|
+
if (!source)
|
|
58
|
+
continue;
|
|
59
|
+
const fraction = toNumber(source.percentUsed);
|
|
60
|
+
const used = toNumber(source.used);
|
|
61
|
+
const limit = toNumber(source.limit ?? source.limits?.[label]);
|
|
62
|
+
windows[label] = toUsageWindow({
|
|
63
|
+
usedPercent: fraction !== null ? fraction * 100 : used !== null && limit ? (used / limit) * 100 : null,
|
|
64
|
+
windowSeconds: label === "daily" ? 86_400 : null,
|
|
65
|
+
resetAt: toTimestamp(source.resetAt ?? payload?.period?.currentPeriodEnd),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return { windows };
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
const openRouterAliases = ["openrouter"];
|
|
73
|
+
const openRouter = {
|
|
74
|
+
id: "openrouter",
|
|
75
|
+
name: "OpenRouter",
|
|
76
|
+
aliases: openRouterAliases,
|
|
77
|
+
async fetchQuota() {
|
|
78
|
+
const key = getCredential(openRouterAliases, ["key", "token"]);
|
|
79
|
+
if (!key)
|
|
80
|
+
return notConfigured(this.id, this.name);
|
|
81
|
+
return safeFetch(this.id, this.name, async () => {
|
|
82
|
+
const payload = await fetchJson("https://openrouter.ai/api/v1/credits", {
|
|
83
|
+
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
|
|
84
|
+
});
|
|
85
|
+
const total = toNumber(payload?.data?.total_credits);
|
|
86
|
+
const used = toNumber(payload?.data?.total_usage);
|
|
87
|
+
const remaining = total !== null && used !== null ? Math.max(0, total - used) : null;
|
|
88
|
+
return {
|
|
89
|
+
windows: {
|
|
90
|
+
credits: toUsageWindow({
|
|
91
|
+
usedPercent: total && used !== null ? (used / total) * 100 : null,
|
|
92
|
+
valueLabel: remaining !== null && total !== null ? `$${remaining.toFixed(2)} / $${total.toFixed(2)}` : null,
|
|
93
|
+
}),
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
});
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
function createTokenLimitProvider(input) {
|
|
100
|
+
return {
|
|
101
|
+
id: input.id,
|
|
102
|
+
name: input.name,
|
|
103
|
+
aliases: input.aliases,
|
|
104
|
+
async fetchQuota() {
|
|
105
|
+
const key = getCredential(input.aliases, ["key", "token"]);
|
|
106
|
+
if (!key)
|
|
107
|
+
return notConfigured(this.id, this.name);
|
|
108
|
+
return safeFetch(this.id, this.name, async () => {
|
|
109
|
+
const payload = await fetchJson(input.url, { headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" } });
|
|
110
|
+
const windows = {};
|
|
111
|
+
for (const limit of Array.isArray(payload?.data?.limits) ? payload.data.limits : []) {
|
|
112
|
+
if (limit?.type !== "TOKENS_LIMIT" && limit?.type !== "TIME_LIMIT")
|
|
113
|
+
continue;
|
|
114
|
+
const duration = toNumber(limit.number);
|
|
115
|
+
const seconds = limit.type === "TIME_LIMIT" ? 30 * 86_400 : limit.unit === 3 && duration ? duration * 3600 : null;
|
|
116
|
+
const label = limit.type === "TIME_LIMIT" ? "mcp-tools" : resolveWindowLabel(seconds);
|
|
117
|
+
windows[label] = toUsageWindow({
|
|
118
|
+
usedPercent: toNumber(limit.percentage),
|
|
119
|
+
windowSeconds: seconds,
|
|
120
|
+
resetAt: toTimestamp(limit.nextResetTime),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return { windows };
|
|
124
|
+
});
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
const zai = createTokenLimitProvider({
|
|
129
|
+
id: "zai-coding-plan",
|
|
130
|
+
name: "z.ai",
|
|
131
|
+
aliases: ["zai-coding-plan", "zai", "z.ai"],
|
|
132
|
+
url: "https://api.z.ai/api/monitor/usage/quota/limit",
|
|
133
|
+
});
|
|
134
|
+
const zhipu = createTokenLimitProvider({
|
|
135
|
+
id: "zhipuai-coding-plan",
|
|
136
|
+
name: "Zhipu AI Coding Plan",
|
|
137
|
+
aliases: ["zhipuai-coding-plan", "zhipuai", "zhipu"],
|
|
138
|
+
url: "https://open.bigmodel.cn/api/monitor/usage/quota/limit",
|
|
139
|
+
});
|
|
140
|
+
const waferAliases = ["wafer", "wafer-ai", "wafer_ai", "wafer.ai"];
|
|
141
|
+
const wafer = {
|
|
142
|
+
id: "wafer",
|
|
143
|
+
name: "Wafer.ai",
|
|
144
|
+
aliases: waferAliases,
|
|
145
|
+
async fetchQuota() {
|
|
146
|
+
const key = getCredential(waferAliases, ["key", "token"]);
|
|
147
|
+
if (!key)
|
|
148
|
+
return notConfigured(this.id, this.name);
|
|
149
|
+
return safeFetch(this.id, this.name, async () => {
|
|
150
|
+
const payload = await fetchJson("https://pass.wafer.ai/v1/inference/quota", {
|
|
151
|
+
headers: { Authorization: `Bearer ${key}`, "Accept-Encoding": "identity" },
|
|
152
|
+
});
|
|
153
|
+
const remaining = toNumber(payload?.remaining_included_requests);
|
|
154
|
+
const limit = toNumber(payload?.included_request_limit);
|
|
155
|
+
const startAt = toTimestamp(payload?.window_start);
|
|
156
|
+
const resetAt = toTimestamp(payload?.window_end);
|
|
157
|
+
const seconds = startAt !== null && resetAt !== null ? Math.round((resetAt - startAt) / 1000) : 5 * 3600;
|
|
158
|
+
return {
|
|
159
|
+
windows: {
|
|
160
|
+
[resolveWindowLabel(seconds)]: toUsageWindow({
|
|
161
|
+
usedPercent: toNumber(payload?.current_period_used_percent),
|
|
162
|
+
windowSeconds: seconds,
|
|
163
|
+
resetAt,
|
|
164
|
+
valueLabel: remaining !== null && limit !== null ? `${remaining} / ${limit}` : null,
|
|
165
|
+
}),
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
export const apiKeyProviders = [kimi, nanoGpt, openRouter, zai, zhipu, wafer];
|