@neuralnomads/codenomad-dev 0.20.0-dev-20260916-59d450c1 → 0.20.0-dev-20260917-aa51cbb9
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 +2 -2
- package/dist/api-types.js.map +1 -1
- package/dist/opencode/compatibility/contract-fixture.js +15 -0
- package/dist/opencode/compatibility/contract-fixture.js.map +1 -0
- package/dist/opencode/compatibility/events.js +9 -0
- package/dist/opencode/compatibility/events.js.map +1 -0
- package/dist/opencode/compatibility/location.js +89 -0
- package/dist/opencode/compatibility/location.js.map +1 -0
- package/dist/opencode/compatibility/location.test.js +92 -0
- package/dist/opencode/compatibility/location.test.js.map +1 -0
- package/dist/opencode/compatibility/negotiate.js +73 -0
- package/dist/opencode/compatibility/negotiate.js.map +1 -0
- package/dist/opencode/compatibility/negotiate.test.js +61 -0
- package/dist/opencode/compatibility/negotiate.test.js.map +1 -0
- package/dist/opencode/compatibility/proxy-locations.js +137 -0
- package/dist/opencode/compatibility/proxy-locations.js.map +1 -0
- package/dist/opencode/compatibility/proxy-locations.test.js +42 -0
- package/dist/opencode/compatibility/proxy-locations.test.js.map +1 -0
- package/dist/opencode/compatibility/proxy.js +60 -0
- package/dist/opencode/compatibility/proxy.js.map +1 -0
- package/dist/opencode/compatibility/proxy.test.js +47 -0
- package/dist/opencode/compatibility/proxy.test.js.map +1 -0
- package/dist/opencode/compatibility/requests.js +54 -0
- package/dist/opencode/compatibility/requests.js.map +1 -0
- package/dist/opencode/compatibility/runtime.js +26 -0
- package/dist/opencode/compatibility/runtime.js.map +1 -0
- package/dist/opencode/compatibility/transport.js +112 -0
- package/dist/opencode/compatibility/transport.js.map +1 -0
- package/dist/opencode/compatibility/transport.test.js +83 -0
- package/dist/opencode/compatibility/transport.test.js.map +1 -0
- package/dist/opencode/session-pruning/location.js +16 -0
- package/dist/opencode/session-pruning/location.js.map +1 -0
- package/dist/opencode/session-pruning/package.test.js +37 -0
- package/dist/opencode/session-pruning/package.test.js.map +1 -0
- package/dist/opencode/session-pruning/plugin.js +5 -2
- package/dist/opencode/session-pruning/plugin.js.map +1 -1
- package/dist/opencode/session-pruning/preview-store.js +3 -2
- package/dist/opencode/session-pruning/preview-store.js.map +1 -1
- package/dist/opencode/session-pruning/pruning.test.js +7 -5
- package/dist/opencode/session-pruning/pruning.test.js.map +1 -1
- package/dist/opencode/session-pruning/service.js +5 -4
- package/dist/opencode/session-pruning/service.js.map +1 -1
- package/dist/opencode/session-pruning/service.test.js +65 -53
- package/dist/opencode/session-pruning/service.test.js.map +1 -1
- package/dist/permissions/opencode-replier.js +2 -2
- package/dist/permissions/opencode-replier.js.map +1 -1
- package/dist/permissions/opencode-replier.test.js +1 -1
- package/dist/permissions/opencode-replier.test.js.map +1 -1
- package/dist/permissions/opencode-yolo-metadata.js.map +1 -1
- package/dist/permissions/opencode-yolo-metadata.test.js.map +1 -1
- package/dist/plugins/session-pruning/plugin.mjs +422 -271
- package/dist/server/__tests__/instance-proxy-legacy.test.js +111 -0
- package/dist/server/__tests__/instance-proxy-legacy.test.js.map +1 -0
- package/dist/server/__tests__/instance-proxy.test.js +44 -34
- package/dist/server/__tests__/instance-proxy.test.js.map +1 -1
- package/dist/server/http-server.js +107 -238
- package/dist/server/http-server.js.map +1 -1
- package/dist/server/routes/session-pruning.js +4 -2
- package/dist/server/routes/session-pruning.js.map +1 -1
- package/dist/server/routes/session-pruning.test.js +16 -2
- package/dist/server/routes/session-pruning.test.js.map +1 -1
- package/dist/server/routes/worktrees.js +1 -0
- package/dist/server/routes/worktrees.js.map +1 -1
- package/dist/server/routes/worktrees.test.js +54 -1
- package/dist/server/routes/worktrees.test.js.map +1 -1
- package/dist/workspaces/host-opencode-service.test.js +56 -7
- package/dist/workspaces/host-opencode-service.test.js.map +1 -1
- package/dist/workspaces/instance-client.js.map +1 -1
- package/dist/workspaces/instance-events.js +71 -57
- package/dist/workspaces/instance-events.js.map +1 -1
- package/dist/workspaces/instance-events.test.js +122 -9
- package/dist/workspaces/instance-events.test.js.map +1 -1
- package/dist/workspaces/manager.js +24 -39
- package/dist/workspaces/manager.js.map +1 -1
- package/dist/workspaces/manager.test.js +43 -7
- package/dist/workspaces/manager.test.js.map +1 -1
- package/dist/workspaces/opencode-cli-service.js +56 -29
- package/dist/workspaces/opencode-cli-service.js.map +1 -1
- package/dist/workspaces/opencode-connection-generation.test.js +57 -0
- package/dist/workspaces/opencode-connection-generation.test.js.map +1 -0
- package/dist/workspaces/opencode-service.js +70 -16
- package/dist/workspaces/opencode-service.js.map +1 -1
- package/dist/workspaces/opencode-service.test.js +3 -4
- package/dist/workspaces/opencode-service.test.js.map +1 -1
- package/dist/workspaces/worktree-session-evacuation.js +31 -11
- package/dist/workspaces/worktree-session-evacuation.js.map +1 -1
- package/dist/workspaces/worktree-session-evacuation.test.js +211 -0
- package/dist/workspaces/worktree-session-evacuation.test.js.map +1 -1
- package/dist/workspaces/wsl-opencode-service.test.js +64 -24
- package/dist/workspaces/wsl-opencode-service.test.js.map +1 -1
- package/package.json +3 -3
- package/public/assets/{App-CchaYx5f.js → App-BROhwPo9.js} +7 -7
- package/public/assets/App-BROhwPo9.js.map +1 -0
- package/public/assets/{FilesTab-D48ghuKz.js → FilesTab-DY3Vr-3r.js} +2 -2
- package/public/assets/{FilesTab-D48ghuKz.js.map → FilesTab-DY3Vr-3r.js.map} +1 -1
- package/public/assets/{GitChangesTab-CCmRJHOz.js → GitChangesTab-BD6CJngE.js} +2 -2
- package/public/assets/{GitChangesTab-CCmRJHOz.js.map → GitChangesTab-BD6CJngE.js.map} +1 -1
- package/public/assets/StatusTab-C-_2yaPa.js +2 -0
- package/public/assets/StatusTab-C-_2yaPa.js.map +1 -0
- package/public/assets/{align-justify-CGBrnO86.js → align-justify-DI8VTZ4G.js} +2 -2
- package/public/assets/{align-justify-CGBrnO86.js.map → align-justify-DI8VTZ4G.js.map} +1 -1
- package/public/assets/{diff-viewer-CmJjbHh5.js → diff-viewer-CGPsYEr3.js} +2 -2
- package/public/assets/{diff-viewer-CmJjbHh5.js.map → diff-viewer-CGPsYEr3.js.map} +1 -1
- package/public/assets/main-Cbx7KdTr.js +38 -0
- package/public/assets/main-Cbx7KdTr.js.map +1 -0
- package/public/assets/{markdown-CwQB_x0O.js → markdown-BWnjyvnX.js} +2 -2
- package/public/assets/{markdown-CwQB_x0O.js.map → markdown-BWnjyvnX.js.map} +1 -1
- package/public/assets/{startup-state-settings-card-CsVbusKE.js → startup-state-settings-card-C4E2Itop.js} +2 -2
- package/public/assets/{startup-state-settings-card-CsVbusKE.js.map → startup-state-settings-card-C4E2Itop.js.map} +1 -1
- package/public/assets/{terminal-square-C2cUF_bs.js → terminal-square-C3wutdV0.js} +2 -2
- package/public/assets/{terminal-square-C2cUF_bs.js.map → terminal-square-C3wutdV0.js.map} +1 -1
- package/public/assets/{tool-call-Cv5pDAZT.js → tool-call-DNsAQ_m4.js} +4 -4
- package/public/assets/{tool-call-Cv5pDAZT.js.map → tool-call-DNsAQ_m4.js.map} +1 -1
- package/public/assets/unified-picker-tB7y17Qz.js.map +1 -1
- package/public/assets/{wrap-text-GxclkjbF.js → wrap-text-CkBxzt04.js} +2 -2
- package/public/assets/{wrap-text-GxclkjbF.js.map → wrap-text-CkBxzt04.js.map} +1 -1
- package/public/index.html +1 -1
- package/public/sw.js +1 -1
- package/public/sw.js.map +1 -1
- package/public/assets/App-CchaYx5f.js.map +0 -1
- package/public/assets/StatusTab-D4793GJu.js +0 -2
- package/public/assets/StatusTab-D4793GJu.js.map +0 -1
- package/public/assets/main-CYyZsCqM.js +0 -38
- package/public/assets/main-CYyZsCqM.js.map +0 -1
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { readLocationRef } from "./location";
|
|
3
|
+
function object(value) {
|
|
4
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !Buffer.isBuffer(value);
|
|
5
|
+
}
|
|
6
|
+
// Call on the canonical request before route translation. Public legacy query
|
|
7
|
+
// selectors use "workspace"; stored/body locations use "workspaceID".
|
|
8
|
+
export function readRequestLocations(url, body, defaultDirectory, profile) {
|
|
9
|
+
const result = { directories: [], locations: [], invalid: false };
|
|
10
|
+
const add = (directory, workspaceID) => {
|
|
11
|
+
try {
|
|
12
|
+
const ref = readLocationRef({ directory, workspaceID });
|
|
13
|
+
if (workspaceID !== undefined && profile !== "legacy")
|
|
14
|
+
throw new Error("Unsupported workspace selector");
|
|
15
|
+
result.directories.push(ref.directory);
|
|
16
|
+
result.locations.push(ref);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
result.invalid = true;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
for (const key of ["directory", "location[directory]", "workspace", "location[workspace]"]) {
|
|
23
|
+
if (url.searchParams.getAll(key).length > 1)
|
|
24
|
+
result.invalid = true;
|
|
25
|
+
}
|
|
26
|
+
if (url.searchParams.has("workspaceID") || url.searchParams.has("location[workspaceID]"))
|
|
27
|
+
result.invalid = true;
|
|
28
|
+
for (const [directoryKey, workspaceKey] of [["directory", "workspace"], ["location[directory]", "location[workspace]"]]) {
|
|
29
|
+
const directory = url.searchParams.get(directoryKey) ?? undefined;
|
|
30
|
+
const workspaceID = url.searchParams.get(workspaceKey) ?? undefined;
|
|
31
|
+
if (workspaceID !== undefined && workspaceKey === "workspace" && url.pathname.replace(/\/$/, "") !== "/api/session")
|
|
32
|
+
result.invalid = true;
|
|
33
|
+
if (directory !== undefined || workspaceID !== undefined)
|
|
34
|
+
add(directory ?? defaultDirectory, workspaceID);
|
|
35
|
+
}
|
|
36
|
+
if (object(body)) {
|
|
37
|
+
if ("workspace" in body)
|
|
38
|
+
result.invalid = true;
|
|
39
|
+
if ("directory" in body || "workspaceID" in body)
|
|
40
|
+
add(body.directory ?? defaultDirectory, body.workspaceID);
|
|
41
|
+
if (body.location !== undefined && body.location !== null) {
|
|
42
|
+
if (!object(body.location) || "workspace" in body.location)
|
|
43
|
+
result.invalid = true;
|
|
44
|
+
else
|
|
45
|
+
add(body.location.directory ?? defaultDirectory, body.location.workspaceID);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
// Preserve the export/history identities; never rewrite every historical
|
|
51
|
+
// location to the import destination. Each is independently authorized by the
|
|
52
|
+
// caller and subsequently directory-translated at the existing proxy boundary.
|
|
53
|
+
export function prepareLocationImport(body, directory, profile) {
|
|
54
|
+
const result = { body, directories: [], locations: [], invalid: false };
|
|
55
|
+
if (!object(body))
|
|
56
|
+
return { ...result, invalid: true };
|
|
57
|
+
const addLocation = (owner, key) => {
|
|
58
|
+
const input = owner[key] ?? { directory };
|
|
59
|
+
if (!object(input) || "workspace" in input) {
|
|
60
|
+
result.invalid = true;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const location = readLocationRef({ ...input, directory: input.directory ?? directory });
|
|
65
|
+
if (location.workspaceID !== undefined && profile !== "legacy")
|
|
66
|
+
throw new Error("Unsupported workspace selector");
|
|
67
|
+
owner[key] = location;
|
|
68
|
+
result.directories.push(location.directory);
|
|
69
|
+
result.locations.push(location);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
result.invalid = true;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
// A copy keeps failed authorization from mutating the incoming request.
|
|
76
|
+
const input = { ...body };
|
|
77
|
+
result.body = input;
|
|
78
|
+
addLocation(input, "location");
|
|
79
|
+
if (object(input.info)) {
|
|
80
|
+
input.info = { ...input.info };
|
|
81
|
+
addLocation(input.info, "location");
|
|
82
|
+
}
|
|
83
|
+
if (Array.isArray(input.messages))
|
|
84
|
+
input.messages = input.messages.map((message) => {
|
|
85
|
+
if (!object(message) || message.type !== "location-switched")
|
|
86
|
+
return message;
|
|
87
|
+
const next = { ...message };
|
|
88
|
+
addLocation(next, "location");
|
|
89
|
+
if (object(next.previous)) {
|
|
90
|
+
next.previous = { ...next.previous };
|
|
91
|
+
addLocation(next.previous, "location");
|
|
92
|
+
}
|
|
93
|
+
return next;
|
|
94
|
+
});
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
export function decodeSessionListScope(cursor, profile) {
|
|
98
|
+
if (!cursor || cursor.length > 65_536 || !/^[A-Za-z0-9_-]+$/.test(cursor))
|
|
99
|
+
return null;
|
|
100
|
+
try {
|
|
101
|
+
const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
102
|
+
if (!object(value) || value.workspaceID !== undefined)
|
|
103
|
+
return null;
|
|
104
|
+
const workspaceID = value.workspace;
|
|
105
|
+
if (workspaceID !== undefined && (profile !== "legacy" || typeof workspaceID !== "string" || !workspaceID.trim()))
|
|
106
|
+
return null;
|
|
107
|
+
const anchor = value.anchor;
|
|
108
|
+
if (!object(anchor) || typeof anchor.id !== "string" || !anchor.id
|
|
109
|
+
|| typeof anchor.time !== "number" || !Number.isFinite(anchor.time)
|
|
110
|
+
|| (anchor.direction !== "previous" && anchor.direction !== "next"))
|
|
111
|
+
return null;
|
|
112
|
+
if (value.search !== undefined && typeof value.search !== "string")
|
|
113
|
+
return null;
|
|
114
|
+
if (value.order !== undefined && value.order !== "asc" && value.order !== "desc")
|
|
115
|
+
return null;
|
|
116
|
+
if (value.parentID !== undefined && value.parentID !== null && typeof value.parentID !== "string")
|
|
117
|
+
return null;
|
|
118
|
+
const legacy = workspaceID === undefined ? {} : { workspaceID: workspaceID };
|
|
119
|
+
if (typeof value.directory === "string" && value.directory.trim() && value.project === undefined && value.subpath === undefined) {
|
|
120
|
+
return { directory: value.directory, ...legacy };
|
|
121
|
+
}
|
|
122
|
+
if (typeof value.project === "string" && value.project.trim() && value.directory === undefined) {
|
|
123
|
+
if (value.subpath === undefined)
|
|
124
|
+
return { project: value.project, ...legacy };
|
|
125
|
+
if (typeof value.subpath === "string" && !path.posix.isAbsolute(value.subpath)
|
|
126
|
+
&& !path.win32.isAbsolute(value.subpath) && !value.subpath.split(/[\\/]/).includes("..")) {
|
|
127
|
+
return { project: value.project, subpath: value.subpath, ...legacy };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// Workspace-only/unscoped tokens cannot prove directory authority.
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=proxy-locations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy-locations.js","sourceRoot":"","sources":["../../../src/opencode/compatibility/proxy-locations.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAA;AAG5B,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAQ5C,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,OAAO,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;AACxG,CAAC;AAED,8EAA8E;AAC9E,sEAAsE;AACtE,MAAM,UAAU,oBAAoB,CAAC,GAAQ,EAAE,IAAa,EAAE,gBAAwB,EAAE,OAAwB;IAC9G,MAAM,MAAM,GAAqB,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAA;IACnF,MAAM,GAAG,GAAG,CAAC,SAAkB,EAAE,WAAqB,EAAE,EAAE;QACxD,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,eAAe,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC,CAAA;YACvD,IAAI,WAAW,KAAK,SAAS,IAAI,OAAO,KAAK,QAAQ;gBAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;YACxG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;Y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KAAK,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC;mBACzE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3F,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,MAAM,EAAE,CAAA;YACtE,CAAC;QACH,CAAC;QACD,mEAAmE;QACnE,OAAO,IAAI,CAAA;IACb,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,IAAI,CAAA;IAAC,CAAC;AACzB,CAAC","sourcesContent":["import path from \"node:path\"\nimport type { LocationRef } from \"@opencode/client\"\nimport type { ContractProfile } from \"./runtime\"\nimport { readLocationRef } from \"./location\"\n\nexport interface RequestLocations {\n directories: string[]\n locations: LocationRef[]\n invalid: boolean\n}\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value) && !Buffer.isBuffer(value)\n}\n\n// Call on the canonical request before route translation. Public legacy query\n// selectors use \"workspace\"; stored/body locations use \"workspaceID\".\nexport function readRequestLocations(url: URL, body: unknown, defaultDirectory: string, profile: ContractProfile): RequestLocations {\n const result: RequestLocations = { directories: [], locations: [], invalid: false }\n const add = (directory: unknown, workspaceID?: unknown) => {\n try {\n const ref = readLocationRef({ directory, workspaceID })\n if (workspaceID !== undefined && profile !== \"legacy\") throw new Error(\"Unsupported workspace selector\")\n result.directories.push(ref.directory)\n result.locations.push(ref)\n } catch { result.invalid = true }\n }\n for (const key of [\"directory\", \"location[directory]\", \"workspace\", \"location[workspace]\"]) {\n if (url.searchParams.getAll(key).length > 1) result.invalid = true\n }\n if (url.searchParams.has(\"workspaceID\") || url.searchParams.has(\"location[workspaceID]\")) result.invalid = true\n for (const [directoryKey, workspaceKey] of [[\"directory\", \"workspace\"], [\"location[directory]\", \"location[workspace]\"]]) {\n const directory = url.searchParams.get(directoryKey) ?? undefined\n const workspaceID = url.searchParams.get(workspaceKey) ?? undefined\n if (workspaceID !== undefined && workspaceKey === \"workspace\" && url.pathname.replace(/\\/$/, \"\") !== \"/api/session\") result.invalid = true\n if (directory !== undefined || workspaceID !== undefined) add(directory ?? defaultDirectory, workspaceID)\n }\n if (object(body)) {\n if (\"workspace\" in body) result.invalid = true\n if (\"directory\" in body || \"workspaceID\" in body) add(body.directory ?? defaultDirectory, body.workspaceID)\n if (body.location !== undefined && body.location !== null) {\n if (!object(body.location) || \"workspace\" in body.location) result.invalid = true\n else add(body.location.directory ?? defaultDirectory, body.location.workspaceID)\n }\n }\n return result\n}\n\n// Preserve the export/history identities; never rewrite every historical\n// location to the import destination. Each is independently authorized by the\n// caller and subsequently directory-translated at the existing proxy boundary.\nexport function prepareLocationImport(body: unknown, directory: string, profile: ContractProfile): RequestLocations & { body: unknown } {\n const result: RequestLocations & { body: unknown } = { body, directories: [], locations: [], invalid: false }\n if (!object(body)) return { ...result, invalid: true }\n const addLocation = (owner: Record<string, unknown>, key: string) => {\n const input = owner[key] ?? { directory }\n if (!object(input) || \"workspace\" in input) { result.invalid = true; return }\n try {\n const location = readLocationRef({ ...input, directory: input.directory ?? directory })\n if (location.workspaceID !== undefined && profile !== \"legacy\") throw new Error(\"Unsupported workspace selector\")\n owner[key] = location\n result.directories.push(location.directory)\n result.locations.push(location)\n } catch { result.invalid = true }\n }\n // A copy keeps failed authorization from mutating the incoming request.\n const input = { ...body }\n result.body = input\n addLocation(input, \"location\")\n if (object(input.info)) { input.info = { ...input.info }; addLocation(input.info as Record<string, unknown>, \"location\") }\n if (Array.isArray(input.messages)) input.messages = input.messages.map((message) => {\n if (!object(message) || message.type !== \"location-switched\") return message\n const next = { ...message }\n addLocation(next, \"location\")\n if (object(next.previous)) { next.previous = { ...next.previous }; addLocation(next.previous as Record<string, unknown>, \"location\") }\n return next\n })\n return result\n}\n\nexport interface SessionListScope {\n directory?: string\n project?: string\n subpath?: string\n workspaceID?: string\n}\n\nexport function decodeSessionListScope(cursor: string, profile: ContractProfile): SessionListScope | null {\n if (!cursor || cursor.length > 65_536 || !/^[A-Za-z0-9_-]+$/.test(cursor)) return null\n try {\n const value: unknown = JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf8\"))\n if (!object(value) || value.workspaceID !== undefined) return null\n const workspaceID = value.workspace\n if (workspaceID !== undefined && (profile !== \"legacy\" || typeof workspaceID !== \"string\" || !workspaceID.trim())) return null\n const anchor = value.anchor\n if (!object(anchor) || typeof anchor.id !== \"string\" || !anchor.id\n || typeof anchor.time !== \"number\" || !Number.isFinite(anchor.time)\n || (anchor.direction !== \"previous\" && anchor.direction !== \"next\")) return null\n if (value.search !== undefined && typeof value.search !== \"string\") return null\n if (value.order !== undefined && value.order !== \"asc\" && value.order !== \"desc\") return null\n if (value.parentID !== undefined && value.parentID !== null && typeof value.parentID !== \"string\") return null\n const legacy = workspaceID === undefined ? {} : { workspaceID: workspaceID as string }\n if (typeof value.directory === \"string\" && value.directory.trim() && value.project === undefined && value.subpath === undefined) {\n return { directory: value.directory, ...legacy }\n }\n if (typeof value.project === \"string\" && value.project.trim() && value.directory === undefined) {\n if (value.subpath === undefined) return { project: value.project, ...legacy }\n if (typeof value.subpath === \"string\" && !path.posix.isAbsolute(value.subpath)\n && !path.win32.isAbsolute(value.subpath) && !value.subpath.split(/[\\\\/]/).includes(\"..\")) {\n return { project: value.project, subpath: value.subpath, ...legacy }\n }\n }\n // Workspace-only/unscoped tokens cannot prove directory authority.\n return null\n } catch { return null }\n}\n"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { decodeSessionListScope, prepareLocationImport, readRequestLocations } from "./proxy-locations";
|
|
4
|
+
test("request selectors preserve legacy authority and retain modern rejection", () => {
|
|
5
|
+
const url = new URL("http://localhost/api/form?location[directory]=/repo&location[workspace]=one");
|
|
6
|
+
assert.deepEqual(readRequestLocations(url, undefined, "/root", "legacy"), {
|
|
7
|
+
directories: ["/repo"], locations: [{ directory: "/repo", workspaceID: "one" }], invalid: false,
|
|
8
|
+
});
|
|
9
|
+
assert.equal(readRequestLocations(url, undefined, "/root", "modern").invalid, true);
|
|
10
|
+
url.searchParams.append("location[workspace]", "two");
|
|
11
|
+
assert.equal(readRequestLocations(url, undefined, "/root", "legacy").invalid, true);
|
|
12
|
+
for (const body of [{ location: { directory: "/repo", workspaceID: "one" } }, { directory: "/repo", workspaceID: "one" }]) {
|
|
13
|
+
const result = readRequestLocations(new URL("http://localhost/api/session"), body, "/root", "legacy");
|
|
14
|
+
assert.deepEqual(result.locations, [{ directory: "/repo", workspaceID: "one" }]);
|
|
15
|
+
assert.equal(readRequestLocations(new URL("http://localhost/api/session"), body, "/root", "modern").invalid, true);
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
test("imports authorize each full historical identity without rewriting it", () => {
|
|
19
|
+
const body = {
|
|
20
|
+
location: { directory: "/root", workspaceID: "root" },
|
|
21
|
+
info: { location: { directory: "/repo", workspaceID: "one" } },
|
|
22
|
+
messages: [{ type: "location-switched", location: { directory: "/repo", workspaceID: "two" }, previous: { location: { directory: "/repo", workspaceID: "one" } } }],
|
|
23
|
+
};
|
|
24
|
+
const result = prepareLocationImport(body, "/default", "legacy");
|
|
25
|
+
assert.equal(result.invalid, false);
|
|
26
|
+
assert.deepEqual(result.locations.map(location => location.workspaceID), ["root", "one", "two", "one"]);
|
|
27
|
+
assert.deepEqual(result.body, body);
|
|
28
|
+
assert.notEqual(result.body, body);
|
|
29
|
+
assert.equal(prepareLocationImport(body, "/default", "modern").invalid, true);
|
|
30
|
+
});
|
|
31
|
+
test("cursor parsing preserves native scope while rejecting foreign-schema authority", () => {
|
|
32
|
+
const value = { directory: "/repo", workspace: "one", anchor: { id: "s", time: 1, direction: "next" } };
|
|
33
|
+
const cursor = Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
34
|
+
assert.deepEqual(decodeSessionListScope(cursor, "legacy"), { directory: "/repo", workspaceID: "one" });
|
|
35
|
+
assert.equal(decodeSessionListScope(cursor, "modern"), null);
|
|
36
|
+
const withFields = (fields) => Buffer.from(JSON.stringify({ ...value, ...fields })).toString("base64url");
|
|
37
|
+
assert.equal(decodeSessionListScope(withFields({ project: "other" }), "legacy"), null);
|
|
38
|
+
assert.equal(decodeSessionListScope(withFields({ workspaceID: "other" }), "legacy"), null);
|
|
39
|
+
assert.equal(decodeSessionListScope(withFields({ directory: undefined }), "legacy"), null);
|
|
40
|
+
assert.deepEqual(JSON.parse(Buffer.from(cursor, "base64url").toString()), value, "the native token is not rewritten");
|
|
41
|
+
});
|
|
42
|
+
//# sourceMappingURL=proxy-locations.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy-locations.test.js","sourceRoot":"","sources":["../../../src/opencode/compatibility/proxy-locations.test.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,oBAAoB,CAAA;AACvC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAA;AAEvG,IAAI,CAAC,yEAAyE,EAAE,GAAG,EAAE;IACnF,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,6EAA6E,CAAC,CAAA;IAClG,MAAM,CAAC,SAAS,CAAC,oBAAoB,CAAC,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE;QACxE,WAAW,EAAE,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK;KACh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MAAM,CAAC,SAAS,CAAC,sBAAsB,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,CAAA;IACtG,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAA;IAC5D,MAAM,UAAU,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,KAAK,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAA;IACjH,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAA;IACtF,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,UAAU,CAAC,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAA;IAC1F,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAA;IAC1F,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,QAAQ,EAAE,CAAC,EAAE,KAAK,EAAE,mCAAmC,CAAC,CAAA;AACvH,CAAC,CAAC,CAAA","sourcesContent":["import assert from \"node:assert/strict\"\nimport { test } from \"node:test\"\nimport { decodeSessionListScope, prepareLocationImport, readRequestLocations } from \"./proxy-locations\"\n\ntest(\"request selectors preserve legacy authority and retain modern rejection\", () => {\n const url = new URL(\"http://localhost/api/form?location[directory]=/repo&location[workspace]=one\")\n assert.deepEqual(readRequestLocations(url, undefined, \"/root\", \"legacy\"), {\n directories: [\"/repo\"], locations: [{ directory: \"/repo\", workspaceID: \"one\" }], invalid: false,\n })\n assert.equal(readRequestLocations(url, undefined, \"/root\", \"modern\").invalid, true)\n url.searchParams.append(\"location[workspace]\", \"two\")\n assert.equal(readRequestLocations(url, undefined, \"/root\", \"legacy\").invalid, true)\n for (const body of [{ location: { directory: \"/repo\", workspaceID: \"one\" } }, { directory: \"/repo\", workspaceID: \"one\" }]) {\n const result = readRequestLocations(new URL(\"http://localhost/api/session\"), body, \"/root\", \"legacy\")\n assert.deepEqual(result.locations, [{ directory: \"/repo\", workspaceID: \"one\" }])\n assert.equal(readRequestLocations(new URL(\"http://localhost/api/session\"), body, \"/root\", \"modern\").invalid, true)\n }\n})\n\ntest(\"imports authorize each full historical identity without rewriting it\", () => {\n const body = {\n location: { directory: \"/root\", workspaceID: \"root\" },\n info: { location: { directory: \"/repo\", workspaceID: \"one\" } },\n messages: [{ type: \"location-switched\", location: { directory: \"/repo\", workspaceID: \"two\" }, previous: { location: { directory: \"/repo\", workspaceID: \"one\" } } }],\n }\n const result = prepareLocationImport(body, \"/default\", \"legacy\")\n assert.equal(result.invalid, false)\n assert.deepEqual(result.locations.map(location => location.workspaceID), [\"root\", \"one\", \"two\", \"one\"])\n assert.deepEqual(result.body, body)\n assert.notEqual(result.body, body)\n assert.equal(prepareLocationImport(body, \"/default\", \"modern\").invalid, true)\n})\n\ntest(\"cursor parsing preserves native scope while rejecting foreign-schema authority\", () => {\n const value = { directory: \"/repo\", workspace: \"one\", anchor: { id: \"s\", time: 1, direction: \"next\" } }\n const cursor = Buffer.from(JSON.stringify(value)).toString(\"base64url\")\n assert.deepEqual(decodeSessionListScope(cursor, \"legacy\"), { directory: \"/repo\", workspaceID: \"one\" })\n assert.equal(decodeSessionListScope(cursor, \"modern\"), null)\n const withFields = (fields: object) => Buffer.from(JSON.stringify({ ...value, ...fields })).toString(\"base64url\")\n assert.equal(decodeSessionListScope(withFields({ project: \"other\" }), \"legacy\"), null)\n assert.equal(decodeSessionListScope(withFields({ workspaceID: \"other\" }), \"legacy\"), null)\n assert.equal(decodeSessionListScope(withFields({ directory: undefined }), \"legacy\"), null)\n assert.deepEqual(JSON.parse(Buffer.from(cursor, \"base64url\").toString()), value, \"the native token is not rewritten\")\n})\n"]}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Readable } from "node:stream";
|
|
2
|
+
export async function forwardRuntimeRequest(args) {
|
|
3
|
+
const controller = new AbortController();
|
|
4
|
+
let released = false;
|
|
5
|
+
let unauthorized = false;
|
|
6
|
+
const release = () => {
|
|
7
|
+
if (released)
|
|
8
|
+
return;
|
|
9
|
+
released = true;
|
|
10
|
+
args.release?.();
|
|
11
|
+
args.reply.raw.off("close", disconnect);
|
|
12
|
+
// Retiring the connection aborts its fetch bodies. Preserve the received
|
|
13
|
+
// native 401 envelope until its body has been consumed by the downstream.
|
|
14
|
+
if (unauthorized)
|
|
15
|
+
args.invalidate();
|
|
16
|
+
};
|
|
17
|
+
const disconnect = () => { controller.abort(); release(); };
|
|
18
|
+
args.reply.raw.once("close", disconnect);
|
|
19
|
+
if (args.reply.raw.destroyed || args.request.raw.aborted)
|
|
20
|
+
controller.abort();
|
|
21
|
+
try {
|
|
22
|
+
const headers = new Headers();
|
|
23
|
+
for (const [key, value] of Object.entries(args.headers)) {
|
|
24
|
+
if (typeof value === "string")
|
|
25
|
+
headers.set(key, value);
|
|
26
|
+
else if (Array.isArray(value))
|
|
27
|
+
for (const item of value)
|
|
28
|
+
headers.append(key, String(item));
|
|
29
|
+
}
|
|
30
|
+
headers.delete("content-length");
|
|
31
|
+
const body = args.body === undefined || args.body === null ? undefined
|
|
32
|
+
: typeof args.body === "string" ? args.body : Buffer.isBuffer(args.body) ? Uint8Array.from(args.body).buffer : JSON.stringify(args.body);
|
|
33
|
+
if (body === undefined)
|
|
34
|
+
headers.delete("content-type");
|
|
35
|
+
const response = await args.fetch(args.url, { method: args.request.method, headers, body, signal: controller.signal });
|
|
36
|
+
unauthorized = response.status === 401;
|
|
37
|
+
args.reply.code(response.status);
|
|
38
|
+
// Fetch has decompressed the body. Do not relay its original framing,
|
|
39
|
+
// cookies, redirect destinations or content-encoding/content-length.
|
|
40
|
+
for (const name of ["content-type", "cache-control", "etag", "last-modified"]) {
|
|
41
|
+
const value = response.headers.get(name);
|
|
42
|
+
if (value !== null)
|
|
43
|
+
args.reply.header(name, value);
|
|
44
|
+
}
|
|
45
|
+
if (!response.body) {
|
|
46
|
+
release();
|
|
47
|
+
return args.reply.send();
|
|
48
|
+
}
|
|
49
|
+
const stream = Readable.fromWeb(response.body);
|
|
50
|
+
stream.once("end", release).once("close", release).once("error", release);
|
|
51
|
+
return args.reply.send(stream);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
release();
|
|
55
|
+
if (!controller.signal.aborted)
|
|
56
|
+
args.invalidate();
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=proxy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../../../src/opencode/compatibility/proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAGtC,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,IAS3C;IACC,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAA;IACxC,IAAI,QAAQ,GAAG,KAAK,CAAA;IACpB,IAAI,YAAY,GAAG,KAAK,CAAA;IACxB,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,IAAI,QAAQ;YAAE,OAAM;QACpB,QAAQ,GAAG,IAAI,CAAA;QACf,IAAI,CAAC,OAAO,EAAE,EAAE,CAAA;QAChB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;QACvC,yEAAyE;QACzE,0EAA0E;Q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AC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,CAAA;QACT,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO;YAAE,IAAI,CAAC,UAAU,EAAE,CAAA;QACjD,MAAM,KAAK,CAAA;IACb,CAAC;AACH,CAAC","sourcesContent":["import { Readable } from \"node:stream\"\nimport type { FastifyReply, FastifyRequest } from \"fastify\"\n\nexport async function forwardRuntimeRequest(args: {\n request: FastifyRequest\n reply: FastifyReply\n url: string\n body: unknown\n headers: Record<string, unknown>\n fetch: typeof fetch\n release?: () => void\n invalidate: () => void\n}) {\n const controller = new AbortController()\n let released = false\n let unauthorized = false\n const release = () => {\n if (released) return\n released = true\n args.release?.()\n args.reply.raw.off(\"close\", disconnect)\n // Retiring the connection aborts its fetch bodies. Preserve the received\n // native 401 envelope until its body has been consumed by the downstream.\n if (unauthorized) args.invalidate()\n }\n const disconnect = () => { controller.abort(); release() }\n args.reply.raw.once(\"close\", disconnect)\n if (args.reply.raw.destroyed || args.request.raw.aborted) controller.abort()\n try {\n const headers = new Headers()\n for (const [key, value] of Object.entries(args.headers)) {\n if (typeof value === \"string\") headers.set(key, value)\n else if (Array.isArray(value)) for (const item of value) headers.append(key, String(item))\n }\n headers.delete(\"content-length\")\n const body = args.body === undefined || args.body === null ? undefined\n : typeof args.body === \"string\" ? args.body : Buffer.isBuffer(args.body) ? Uint8Array.from(args.body).buffer : JSON.stringify(args.body)\n if (body === undefined) headers.delete(\"content-type\")\n const response = await args.fetch(args.url, { method: args.request.method, headers, body, signal: controller.signal })\n unauthorized = response.status === 401\n args.reply.code(response.status)\n // Fetch has decompressed the body. Do not relay its original framing,\n // cookies, redirect destinations or content-encoding/content-length.\n for (const name of [\"content-type\", \"cache-control\", \"etag\", \"last-modified\"]) {\n const value = response.headers.get(name)\n if (value !== null) args.reply.header(name, value)\n }\n if (!response.body) { release(); return args.reply.send() }\n const stream = Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream)\n stream.once(\"end\", release).once(\"close\", release).once(\"error\", release)\n return args.reply.send(stream)\n } catch (error) {\n release()\n if (!controller.signal.aborted) args.invalidate()\n throw error\n }\n}\n"]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
import { setImmediate } from "node:timers/promises";
|
|
5
|
+
import Fastify from "fastify";
|
|
6
|
+
import { OpenCodeSharedService } from "../../workspaces/opencode-service";
|
|
7
|
+
import { forwardRuntimeRequest } from "./proxy";
|
|
8
|
+
test("retiring the actual connection preserves complete and streamed native 401 envelopes", async () => {
|
|
9
|
+
for (const delayed of [false, true]) {
|
|
10
|
+
const upstream = Fastify();
|
|
11
|
+
const envelope = { _tag: "UnauthorizedError", message: "fixture" };
|
|
12
|
+
upstream.get("/api/denied", async (_request, reply) => {
|
|
13
|
+
reply.code(401);
|
|
14
|
+
if (!delayed)
|
|
15
|
+
return envelope;
|
|
16
|
+
return reply.type("application/json").send(Readable.from((async function* () {
|
|
17
|
+
yield '{"_tag":"UnauthorizedError",';
|
|
18
|
+
await setImmediate();
|
|
19
|
+
yield '"message":"fixture"}';
|
|
20
|
+
})()));
|
|
21
|
+
});
|
|
22
|
+
await upstream.listen({ host: "127.0.0.1", port: 0 });
|
|
23
|
+
const endpoint = { url: `http://127.0.0.1:${upstream.server.address().port}` };
|
|
24
|
+
const service = new OpenCodeSharedService();
|
|
25
|
+
await service.client({ kind: "lifecycle", identity: "fixture", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } });
|
|
26
|
+
const connection = await service.acquire();
|
|
27
|
+
const app = Fastify();
|
|
28
|
+
let releases = 0;
|
|
29
|
+
app.get("/fixture", (request, reply) => forwardRuntimeRequest({
|
|
30
|
+
request, reply, url: `${endpoint.url}/api/denied`, body: undefined, headers: {},
|
|
31
|
+
fetch: connection.fetch, invalidate: connection.invalidate, release: () => { releases++; },
|
|
32
|
+
}));
|
|
33
|
+
try {
|
|
34
|
+
const response = await app.inject("/fixture");
|
|
35
|
+
assert.equal(response.statusCode, 401);
|
|
36
|
+
assert.deepEqual(response.json(), envelope);
|
|
37
|
+
assert.equal(releases, 1);
|
|
38
|
+
assert.throws(connection.assertCurrent, /connection changed/);
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
await service.shutdown();
|
|
42
|
+
await app.close();
|
|
43
|
+
await upstream.close();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
//# sourceMappingURL=proxy.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxy.test.js","sourceRoot":"","sources":["../../../src/opencode/compatibility/proxy.test.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,oBAAoB,CAAA;AACvC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AACnD,OAAO,OAAO,MAAM,SAAS,CAAA;AAC7B,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAA;AACzE,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAA;AAE/C,IAAI,CAAC,qFAAqF,EAAE,KAAK,IAAI,EAAE;IACrG,KAAK,MAAM,OAAO,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC;QACpC,MAAM,QAAQ,GAAG,OAAO,EAAE,CAAA;QAC1B,MAAM,QAAQ,GAAG,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,SAAS,EAAE,CAAA;QAClE,QAAQ,CAAC,GAAG,CAAC,aAAa,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE;YACpD,KAAK,CAAC,IAAI,CAAC,GAAG,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AK,EAAE,UAAU,EAAE,UAAU,CAAC,UAAU,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,QAAQ,EAAE,CAAA,CAAC,CAAC;SAC1F,CAAC,CAAC,CAAA;QACH,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAAA;YAC7C,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,EAAE,GAAG,CAAC,CAAA;YACtC,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC3C,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;YACzB,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,aAAa,EAAE,oBAAoB,CAAC,CAAA;QAC/D,CAAC;gBAAS,CAAC;YAAC,MAAM,OAAO,CAAC,QAAQ,EAAE,CAAC;YAAC,MAAM,GAAG,CAAC,KAAK,EAAE,CAAC;YAAC,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAA;QAAC,CAAC;IACnF,CAAC;AACH,CAAC,CAAC,CAAA","sourcesContent":["import assert from \"node:assert/strict\"\nimport { test } from \"node:test\"\nimport { Readable } from \"node:stream\"\nimport { setImmediate } from \"node:timers/promises\"\nimport Fastify from \"fastify\"\nimport { OpenCodeSharedService } from \"../../workspaces/opencode-service\"\nimport { forwardRuntimeRequest } from \"./proxy\"\n\ntest(\"retiring the actual connection preserves complete and streamed native 401 envelopes\", async () => {\n for (const delayed of [false, true]) {\n const upstream = Fastify()\n const envelope = { _tag: \"UnauthorizedError\", message: \"fixture\" }\n upstream.get(\"/api/denied\", async (_request, reply) => {\n reply.code(401)\n if (!delayed) return envelope\n return reply.type(\"application/json\").send(Readable.from((async function* () {\n yield '{\"_tag\":\"UnauthorizedError\",'\n await setImmediate()\n yield '\"message\":\"fixture\"}'\n })()))\n })\n await upstream.listen({ host: \"127.0.0.1\", port: 0 })\n const endpoint = { url: `http://127.0.0.1:${(upstream.server.address() as { port: number }).port}` }\n const service = new OpenCodeSharedService()\n await service.client({ kind: \"lifecycle\", identity: \"fixture\", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } })\n const connection = await service.acquire()\n const app = Fastify()\n let releases = 0\n app.get(\"/fixture\", (request, reply) => forwardRuntimeRequest({\n request, reply, url: `${endpoint.url}/api/denied`, body: undefined, headers: {},\n fetch: connection.fetch, invalidate: connection.invalidate, release: () => { releases++ },\n }))\n try {\n const response = await app.inject(\"/fixture\")\n assert.equal(response.statusCode, 401)\n assert.deepEqual(response.json(), envelope)\n assert.equal(releases, 1)\n assert.throws(connection.assertCurrent, /connection changed/)\n } finally { await service.shutdown(); await app.close(); await upstream.close() }\n }\n})\n"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Only translate consumed, reviewed operations. The external proxy allowlist is
|
|
2
|
+
// checked before reaching this module; translation never expands that allowlist.
|
|
3
|
+
export function legacyRequest(url, method, body) {
|
|
4
|
+
const original = url.pathname;
|
|
5
|
+
if (original === "/api/status" && method === "GET")
|
|
6
|
+
url.pathname = "/api/health";
|
|
7
|
+
if (/^\/api\/experimental\/session\/(?:stats|import|[^/]+\/(?:export|wait|instructions\/entries(?:\/[^/]+)?))$/.test(original)
|
|
8
|
+
|| /^\/api\/experimental\/mcp\/[^/]+\/(?:connect|disconnect)$/.test(original)) {
|
|
9
|
+
url.pathname = original.replace("/experimental", "");
|
|
10
|
+
}
|
|
11
|
+
if (original === "/api/form" && method === "GET")
|
|
12
|
+
url.pathname = "/api/form/request";
|
|
13
|
+
if (/^\/api\/session\/[^/]+$/.test(original) && method === "PATCH") {
|
|
14
|
+
if (!body || typeof body.title !== "string" || Object.keys(body).some(key => key !== "title")) {
|
|
15
|
+
throw new Error("Earlier OpenCode V2 supports title-only session updates");
|
|
16
|
+
}
|
|
17
|
+
url.pathname += "/rename";
|
|
18
|
+
method = "POST";
|
|
19
|
+
}
|
|
20
|
+
if (/^\/api\/session\/[^/]+\/fork$/.test(original) && method === "POST") {
|
|
21
|
+
if (body?.before !== undefined && typeof body.before !== "string")
|
|
22
|
+
throw new Error("Invalid fork boundary");
|
|
23
|
+
body = { boundary: body?.before === undefined ? { type: "through" } : { type: "before", messageID: body.before } };
|
|
24
|
+
}
|
|
25
|
+
if (/^\/api\/session\/[^/]+\/command$/.test(original) && method === "POST" && body) {
|
|
26
|
+
const { name, ...rest } = body;
|
|
27
|
+
body = { ...rest, command: name };
|
|
28
|
+
}
|
|
29
|
+
if (/^\/api\/session\/[^/]+\/permission\/[^/]+\/reply$/.test(original) && method === "POST" && body) {
|
|
30
|
+
const { decision, ...rest } = body;
|
|
31
|
+
body = { ...rest, reply: decision };
|
|
32
|
+
}
|
|
33
|
+
if (/^\/api\/session\/[^/]+\/interrupt$/.test(original) && method === "POST" && url.searchParams.has("resume")) {
|
|
34
|
+
url.searchParams.set("continue", url.searchParams.get("resume"));
|
|
35
|
+
url.searchParams.delete("resume");
|
|
36
|
+
}
|
|
37
|
+
if (/^\/api\/session\/[^/]+\/inbox\/[^/]+$/.test(original) && method === "PATCH") {
|
|
38
|
+
if (body?.delivery !== "steer" && body?.delivery !== "queue")
|
|
39
|
+
throw new Error("Invalid inbox delivery");
|
|
40
|
+
url.pathname += `/${body.delivery}`;
|
|
41
|
+
method = "POST";
|
|
42
|
+
body = undefined;
|
|
43
|
+
}
|
|
44
|
+
if (/^\/api\/session\/[^/]+\/revert$/.test(original) && method === "DELETE") {
|
|
45
|
+
url.pathname += "/clear";
|
|
46
|
+
method = "POST";
|
|
47
|
+
}
|
|
48
|
+
if (/^\/api\/session\/[^/]+\/form\/[^/]+$/.test(original) && method === "DELETE") {
|
|
49
|
+
url.pathname += "/cancel";
|
|
50
|
+
method = "POST";
|
|
51
|
+
}
|
|
52
|
+
return { url, method, body };
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=requests.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"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E,QAAQ,KAAK,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;QACvG,GAAG,CAAC,QAAQ,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAA;QACnC,MAAM,GAAG,MAAM,CAAA;QACf,IAAI,GAAG,SAAS,CAAA;IAClB,CAAC;IACD,IAAI,iCAAiC,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC5E,GAAG,CAAC,QAAQ,IAAI,QAAQ,CAAA;QACxB,MAAM,GAAG,MAAM,CAAA;IACjB,CAAC;IACD,IAAI,sCAAsC,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;QACjF,GAAG,CAAC,QAAQ,IAAI,SAAS,CAAA;QACzB,MAAM,GAAG,MAAM,CAAA;IACjB,CAAC;IACD,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAA;AAC9B,CAAC","sourcesContent":["// Only translate consumed, reviewed operations. The external proxy allowlist is\n// checked before reaching this module; translation never expands that allowlist.\nexport function legacyRequest(url: URL, method: string, body: Record<string, unknown> | undefined) {\n const original = url.pathname\n if (original === \"/api/status\" && method === \"GET\") url.pathname = \"/api/health\"\n if (/^\\/api\\/experimental\\/session\\/(?:stats|import|[^/]+\\/(?:export|wait|instructions\\/entries(?:\\/[^/]+)?))$/.test(original)\n || /^\\/api\\/experimental\\/mcp\\/[^/]+\\/(?:connect|disconnect)$/.test(original)) {\n url.pathname = original.replace(\"/experimental\", \"\")\n }\n if (original === \"/api/form\" && method === \"GET\") url.pathname = \"/api/form/request\"\n if (/^\\/api\\/session\\/[^/]+$/.test(original) && method === \"PATCH\") {\n if (!body || typeof body.title !== \"string\" || Object.keys(body).some(key => key !== \"title\")) {\n throw new Error(\"Earlier OpenCode V2 supports title-only session updates\")\n }\n url.pathname += \"/rename\"\n method = \"POST\"\n }\n if (/^\\/api\\/session\\/[^/]+\\/fork$/.test(original) && method === \"POST\") {\n if (body?.before !== undefined && typeof body.before !== \"string\") throw new Error(\"Invalid fork boundary\")\n body = { boundary: body?.before === undefined ? { type: \"through\" } : { type: \"before\", messageID: body.before } }\n }\n if (/^\\/api\\/session\\/[^/]+\\/command$/.test(original) && method === \"POST\" && body) {\n const { name, ...rest } = body\n body = { ...rest, command: name }\n }\n if (/^\\/api\\/session\\/[^/]+\\/permission\\/[^/]+\\/reply$/.test(original) && method === \"POST\" && body) {\n const { decision, ...rest } = body\n body = { ...rest, reply: decision }\n }\n if (/^\\/api\\/session\\/[^/]+\\/interrupt$/.test(original) && method === \"POST\" && url.searchParams.has(\"resume\")) {\n url.searchParams.set(\"continue\", url.searchParams.get(\"resume\")!)\n url.searchParams.delete(\"resume\")\n }\n if (/^\\/api\\/session\\/[^/]+\\/inbox\\/[^/]+$/.test(original) && method === \"PATCH\") {\n if (body?.delivery !== \"steer\" && body?.delivery !== \"queue\") throw new Error(\"Invalid inbox delivery\")\n url.pathname += `/${body.delivery}`\n method = \"POST\"\n body = undefined\n }\n if (/^\\/api\\/session\\/[^/]+\\/revert$/.test(original) && method === \"DELETE\") {\n url.pathname += \"/clear\"\n method = \"POST\"\n }\n if (/^\\/api\\/session\\/[^/]+\\/form\\/[^/]+$/.test(original) && method === \"DELETE\") {\n url.pathname += \"/cancel\"\n method = \"POST\"\n }\n return { url, method, body }\n}\n"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Keep authenticated daemon metadata out of public endpoints and credentials.
|
|
2
|
+
const RUNTIME_IDENTITY = Symbol.for("codenomad.opencode.runtime");
|
|
3
|
+
export function rememberRuntime(endpoint, identity) {
|
|
4
|
+
Object.defineProperty(endpoint, RUNTIME_IDENTITY, { value: Object.freeze({ ...identity, contract: {} }) });
|
|
5
|
+
}
|
|
6
|
+
export function runtimeIdentity(endpoint) {
|
|
7
|
+
return endpoint[RUNTIME_IDENTITY];
|
|
8
|
+
}
|
|
9
|
+
export function contractProfile(identity) {
|
|
10
|
+
// Custom embedded/test lifecycles that don't negotiate use the pinned contract.
|
|
11
|
+
if (!identity)
|
|
12
|
+
return "modern";
|
|
13
|
+
if (identity.contract?.profile)
|
|
14
|
+
return identity.contract.profile;
|
|
15
|
+
if (/^2\.0\.[0-3]$/.test(identity.version))
|
|
16
|
+
return "legacy";
|
|
17
|
+
if (/^2\.0\.[45]$/.test(identity.version))
|
|
18
|
+
return "modern";
|
|
19
|
+
const beta = /^0\.0\.0-beta-(\d+)$/.exec(identity.version)?.[1];
|
|
20
|
+
const audited = new Set([18866, 18955, 18965, 18985, 18992, 18999, 19059, 19086,
|
|
21
|
+
19124, 19129, 19133, 19135, 19151, 19157, 19187, 19192, 19215, 19213,
|
|
22
|
+
19228, 19234, 19242, 19266, 19271, 19275, 19278, 19283, 19288, 19289,
|
|
23
|
+
19296, 19365, 19378, 19381, 19398, 19419, 19422, 19425, 19500, 19507]);
|
|
24
|
+
return beta && audited.has(Number(beta)) ? "legacy" : "unknown";
|
|
25
|
+
}
|
|
26
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/opencode/compatibility/runtime.ts"],"names":[],"mappings":"AAUA,8EAA8E;AAC9E,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;AACjE,MAAM,UAAU,eAAe,CAAC,QAAkB,EAAE,QAAyB;IAC3E,MAAM,CAAC,cAAc,CAAC,QAAQ,EAAE,gBAAgB,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,CAAA;AAC5G,CAAC;AACD,MAAM,UAAU,eAAe,CAAC,QAAkB;IAChD,OAAQ,QAAgE,CAAC,gBAAgB,CAAC,CAAA;AAC5F,CAAC;AAGD,MAAM,UAAU,eAAe,CAAC,QAAqC;IACnE,gFAAgF;IAChF,IAAI,CAAC,QAAQ;QAAE,OAAO,QAAQ,CAAA;IAC9B,IAAI,QAAQ,CAAC,QAAQ,EAAE,OAAO;QAAE,OAAO,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAA;IAChE,IAAI,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC3D,IAAI,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,QAAQ,CAAA;IAC1D,MAAM,IAAI,GAAG,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;IAC/D,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;QAC7E,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;QACpE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;QACpE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAA;IACxE,OAAO,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAA;AACjE,CAAC","sourcesContent":["import type { Endpoint } from \"@opencode/client/service\"\n\nexport interface RuntimeIdentity {\n version: string\n pid: number\n discovery: \"status\" | \"health\"\n /** Filled only by a successful, authenticated schema negotiation. */\n contract?: { profile?: Exclude<ContractProfile, \"unknown\"> }\n}\n\n// Keep authenticated daemon metadata out of public endpoints and credentials.\nconst RUNTIME_IDENTITY = Symbol.for(\"codenomad.opencode.runtime\")\nexport function rememberRuntime(endpoint: Endpoint, identity: RuntimeIdentity): void {\n Object.defineProperty(endpoint, RUNTIME_IDENTITY, { value: Object.freeze({ ...identity, contract: {} }) })\n}\nexport function runtimeIdentity(endpoint: Endpoint): RuntimeIdentity | undefined {\n return (endpoint as Endpoint & { [RUNTIME_IDENTITY]?: RuntimeIdentity })[RUNTIME_IDENTITY]\n}\n\nexport type ContractProfile = \"modern\" | \"legacy\" | \"unknown\"\nexport function contractProfile(identity: RuntimeIdentity | undefined): ContractProfile {\n // Custom embedded/test lifecycles that don't negotiate use the pinned contract.\n if (!identity) return \"modern\"\n if (identity.contract?.profile) return identity.contract.profile\n if (/^2\\.0\\.[0-3]$/.test(identity.version)) return \"legacy\"\n if (/^2\\.0\\.[45]$/.test(identity.version)) return \"modern\"\n const beta = /^0\\.0\\.0-beta-(\\d+)$/.exec(identity.version)?.[1]\n const audited = new Set([18866, 18955, 18965, 18985, 18992, 18999, 19059, 19086,\n 19124, 19129, 19133, 19135, 19151, 19157, 19187, 19192, 19215, 19213,\n 19228, 19234, 19242, 19266, 19271, 19275, 19278, 19283, 19288, 19289,\n 19296, 19365, 19378, 19381, 19398, 19419, 19422, 19425, 19500, 19507])\n return beta && audited.has(Number(beta)) ? \"legacy\" : \"unknown\"\n}\n"]}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { Service } from "@opencode/client/service";
|
|
2
|
+
import { contractProfile, runtimeIdentity } from "./runtime";
|
|
3
|
+
import { legacyRequest } from "./requests";
|
|
4
|
+
import { negotiateRuntime } from "./negotiate";
|
|
5
|
+
import { applyLocationContext, LOCATION_CONTEXT_HEADER } from "./location";
|
|
6
|
+
function object(value) {
|
|
7
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
function normalizeInbox(value) {
|
|
10
|
+
if (!object(value))
|
|
11
|
+
throw new Error("Invalid native inbox item");
|
|
12
|
+
if (object(value.time) && typeof value.time.created === "number")
|
|
13
|
+
return value;
|
|
14
|
+
if (typeof value.timeCreated !== "number" || !Number.isFinite(value.timeCreated)) {
|
|
15
|
+
throw new Error("Invalid native inbox creation time");
|
|
16
|
+
}
|
|
17
|
+
const { timeCreated, ...rest } = value;
|
|
18
|
+
return { ...rest, time: { created: timeCreated } };
|
|
19
|
+
}
|
|
20
|
+
// Both the server's generated client and the authorized browser proxy use this
|
|
21
|
+
// transport. No error classification here retries a mutation.
|
|
22
|
+
export function createRuntimeFetch(endpoint, fetcher = globalThis.fetch) {
|
|
23
|
+
return createRuntimeTransport(endpoint, fetcher).fetch;
|
|
24
|
+
}
|
|
25
|
+
export function createRuntimeTransport(endpoint, fetcher = globalThis.fetch, lifetime = new AbortController().signal) {
|
|
26
|
+
const identity = runtimeIdentity(endpoint);
|
|
27
|
+
let profile = contractProfile(identity);
|
|
28
|
+
let negotiation;
|
|
29
|
+
const resolveProfile = async (signal) => {
|
|
30
|
+
signal?.throwIfAborted();
|
|
31
|
+
lifetime.throwIfAborted();
|
|
32
|
+
if (profile !== "unknown")
|
|
33
|
+
return profile;
|
|
34
|
+
negotiation ??= negotiateRuntime(endpoint, fetcher, lifetime).then(value => {
|
|
35
|
+
profile = value;
|
|
36
|
+
return value;
|
|
37
|
+
}).catch(error => { negotiation = undefined; throw error; });
|
|
38
|
+
return awaitLocal(negotiation, signal);
|
|
39
|
+
};
|
|
40
|
+
const adaptedFetch = async (input, init) => {
|
|
41
|
+
const request = new Request(input, init);
|
|
42
|
+
const url = new URL(request.url);
|
|
43
|
+
if (url.origin !== new URL(endpoint.url).origin)
|
|
44
|
+
throw new Error("OpenCode transport origin mismatch");
|
|
45
|
+
const profile = await resolveProfile(request.signal);
|
|
46
|
+
const headers = new Headers(request.headers);
|
|
47
|
+
for (const [name, value] of Object.entries(Service.headers(endpoint) ?? {}))
|
|
48
|
+
headers.set(name, value);
|
|
49
|
+
// Credentialed native requests must never follow a redirect to another host.
|
|
50
|
+
const options = { method: request.method, headers, signal: AbortSignal.any([request.signal, lifetime]), redirect: "error" };
|
|
51
|
+
const originalPath = url.pathname;
|
|
52
|
+
if (profile === "legacy" || headers.has(LOCATION_CONTEXT_HEADER)) {
|
|
53
|
+
const text = request.body ? await request.text() : undefined;
|
|
54
|
+
let body = text ? JSON.parse(text) : undefined;
|
|
55
|
+
body = applyLocationContext(url, request.method, body, headers, profile);
|
|
56
|
+
if (body !== undefined && !object(body))
|
|
57
|
+
throw new Error("Invalid OpenCode request body");
|
|
58
|
+
const translated = profile === "legacy" ? legacyRequest(url, request.method, body) : { method: request.method, body };
|
|
59
|
+
options.method = translated.method;
|
|
60
|
+
options.body = translated.body === undefined ? undefined : JSON.stringify(translated.body);
|
|
61
|
+
headers.delete("content-length");
|
|
62
|
+
if (options.body === undefined)
|
|
63
|
+
headers.delete("content-type");
|
|
64
|
+
}
|
|
65
|
+
else if (request.body) {
|
|
66
|
+
options.body = await request.arrayBuffer();
|
|
67
|
+
}
|
|
68
|
+
const response = await fetcher(url, options);
|
|
69
|
+
if (!response.ok && !response.headers.get("content-type")?.includes("application/json")) {
|
|
70
|
+
await response.body?.cancel();
|
|
71
|
+
return Response.json({
|
|
72
|
+
_tag: "OpenCodeContractError", message: `OpenCode ${identity?.version ?? profile}: ${request.method} ${originalPath} returned HTTP ${response.status}`,
|
|
73
|
+
status: response.status, profile, method: request.method, path: originalPath,
|
|
74
|
+
}, { status: response.status });
|
|
75
|
+
}
|
|
76
|
+
if (profile === "legacy" && response.ok && originalPath === "/api/status") {
|
|
77
|
+
const health = await response.json();
|
|
78
|
+
return Response.json({ version: health.version, pid: health.pid, urls: [endpoint.url] });
|
|
79
|
+
}
|
|
80
|
+
if (profile !== "legacy" || !response.ok || !/^\/api\/session\/[^/]+\/(?:inbox|prompt|synthetic|compact)$/.test(originalPath)
|
|
81
|
+
|| response.status === 204)
|
|
82
|
+
return response;
|
|
83
|
+
const value = await response.json();
|
|
84
|
+
if (!object(value))
|
|
85
|
+
throw new Error("Invalid native inbox response");
|
|
86
|
+
const normalized = { ...value, data: Array.isArray(value.data) ? value.data.map(normalizeInbox) : normalizeInbox(value.data) };
|
|
87
|
+
const responseHeaders = new Headers(response.headers);
|
|
88
|
+
responseHeaders.delete("content-length");
|
|
89
|
+
responseHeaders.delete("content-encoding");
|
|
90
|
+
return new Response(JSON.stringify(normalized), { status: response.status, headers: responseHeaders });
|
|
91
|
+
};
|
|
92
|
+
return { fetch: adaptedFetch, profile: resolveProfile };
|
|
93
|
+
}
|
|
94
|
+
// A cancelled subscriber must not cancel the connection's negotiation or wait
|
|
95
|
+
// for another subscriber's request to finish before observing its own abort.
|
|
96
|
+
function awaitLocal(pending, signal) {
|
|
97
|
+
if (!signal)
|
|
98
|
+
return pending;
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
const abort = () => { signal.removeEventListener("abort", abort); reject(signal.reason); };
|
|
101
|
+
if (signal.aborted) {
|
|
102
|
+
reject(signal.reason);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
106
|
+
pending.then(value => { signal.removeEventListener("abort", abort); resolve(value); }, error => {
|
|
107
|
+
signal.removeEventListener("abort", abort);
|
|
108
|
+
reject(error);
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
//# sourceMappingURL=transport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/opencode/compatibility/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAiB,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AA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IAAI,CAAC,MAAM;QAAE,OAAO,OAAO,CAAA;IAC3B,OAAO,IAAI,OAAO,CAAI,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACxC,MAAM,KAAK,GAAG,GAAG,EAAE,GAAG,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA,CAAC,CAAC,CAAA;QACzF,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;YAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAAC,OAAM;QAAC,CAAC;QACrD,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;QACvD,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE;YAC5F,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAAC,MAAM,CAAC,KAAK,CAAC,CAAA;QAC3D,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { Service, type Endpoint } from \"@opencode/client/service\"\nimport { contractProfile, runtimeIdentity } from \"./runtime\"\nimport { legacyRequest } from \"./requests\"\nimport { negotiateRuntime } from \"./negotiate\"\nimport { applyLocationContext, LOCATION_CONTEXT_HEADER } from \"./location\"\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n}\n\nfunction normalizeInbox(value: unknown): unknown {\n if (!object(value)) throw new Error(\"Invalid native inbox item\")\n if (object(value.time) && typeof value.time.created === \"number\") return value\n if (typeof value.timeCreated !== \"number\" || !Number.isFinite(value.timeCreated)) {\n throw new Error(\"Invalid native inbox creation time\")\n }\n const { timeCreated, ...rest } = value\n return { ...rest, time: { created: timeCreated } }\n}\n\n// Both the server's generated client and the authorized browser proxy use this\n// transport. No error classification here retries a mutation.\nexport function createRuntimeFetch(endpoint: Endpoint, fetcher: typeof fetch = globalThis.fetch): typeof fetch {\n return createRuntimeTransport(endpoint, fetcher).fetch\n}\n\nexport function createRuntimeTransport(endpoint: Endpoint, fetcher: typeof fetch = globalThis.fetch, lifetime = new AbortController().signal) {\n const identity = runtimeIdentity(endpoint)\n let profile = contractProfile(identity)\n let negotiation: Promise<\"modern\" | \"legacy\"> | undefined\n const resolveProfile = async (signal?: AbortSignal) => {\n signal?.throwIfAborted()\n lifetime.throwIfAborted()\n if (profile !== \"unknown\") return profile\n negotiation ??= negotiateRuntime(endpoint, fetcher, lifetime).then(value => {\n profile = value\n return value\n }).catch(error => { negotiation = undefined; throw error })\n return awaitLocal(negotiation, signal)\n }\n const adaptedFetch: typeof fetch = async (input, init) => {\n const request = new Request(input, init)\n const url = new URL(request.url)\n if (url.origin !== new URL(endpoint.url).origin) throw new Error(\"OpenCode transport origin mismatch\")\n const profile = await resolveProfile(request.signal)\n const headers = new Headers(request.headers)\n for (const [name, value] of Object.entries(Service.headers(endpoint) ?? {})) headers.set(name, value)\n // Credentialed native requests must never follow a redirect to another host.\n const options: RequestInit = { method: request.method, headers, signal: AbortSignal.any([request.signal, lifetime]), redirect: \"error\" }\n const originalPath = url.pathname\n if (profile === \"legacy\" || headers.has(LOCATION_CONTEXT_HEADER)) {\n const text = request.body ? await request.text() : undefined\n let body: unknown = text ? JSON.parse(text) : undefined\n body = applyLocationContext(url, request.method, body, headers, profile)\n if (body !== undefined && !object(body)) throw new Error(\"Invalid OpenCode request body\")\n const translated = profile === \"legacy\" ? legacyRequest(url, request.method, body) : { method: request.method, body }\n options.method = translated.method\n options.body = translated.body === undefined ? undefined : JSON.stringify(translated.body)\n headers.delete(\"content-length\")\n if (options.body === undefined) headers.delete(\"content-type\")\n } else if (request.body) {\n options.body = await request.arrayBuffer()\n }\n const response = await fetcher(url, options)\n if (!response.ok && !response.headers.get(\"content-type\")?.includes(\"application/json\")) {\n await response.body?.cancel()\n return Response.json({\n _tag: \"OpenCodeContractError\", message: `OpenCode ${identity?.version ?? profile}: ${request.method} ${originalPath} returned HTTP ${response.status}`,\n status: response.status, profile, method: request.method, path: originalPath,\n }, { status: response.status })\n }\n if (profile === \"legacy\" && response.ok && originalPath === \"/api/status\") {\n const health = await response.json() as { version: string; pid: number }\n return Response.json({ version: health.version, pid: health.pid, urls: [endpoint.url] })\n }\n if (profile !== \"legacy\" || !response.ok || !/^\\/api\\/session\\/[^/]+\\/(?:inbox|prompt|synthetic|compact)$/.test(originalPath)\n || response.status === 204) return response\n const value: unknown = await response.json()\n if (!object(value)) throw new Error(\"Invalid native inbox response\")\n const normalized = { ...value, data: Array.isArray(value.data) ? value.data.map(normalizeInbox) : normalizeInbox(value.data) }\n const responseHeaders = new Headers(response.headers)\n responseHeaders.delete(\"content-length\")\n responseHeaders.delete(\"content-encoding\")\n return new Response(JSON.stringify(normalized), { status: response.status, headers: responseHeaders })\n }\n return { fetch: adaptedFetch, profile: resolveProfile }\n}\n\n// A cancelled subscriber must not cancel the connection's negotiation or wait\n// for another subscriber's request to finish before observing its own abort.\nfunction awaitLocal<T>(pending: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return pending\n return new Promise<T>((resolve, reject) => {\n const abort = () => { signal.removeEventListener(\"abort\", abort); reject(signal.reason) }\n if (signal.aborted) { reject(signal.reason); return }\n signal.addEventListener(\"abort\", abort, { once: true })\n pending.then(value => { signal.removeEventListener(\"abort\", abort); resolve(value) }, error => {\n signal.removeEventListener(\"abort\", abort); reject(error)\n })\n })\n}\n"]}
|