@dsh-mobile/mobile-remote 0.0.0-stage → 3.2.5
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/CHANGELOG.md +1273 -0
- package/CONTRIBUTING.md +59 -0
- package/FAQ.md +115 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/cordis.patch.yml +22 -0
- package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +121 -0
- package/docs/01-PRD.md +148 -0
- package/docs/02-architecture.md +249 -0
- package/docs/03-api.md +882 -0
- package/docs/04-security.md +109 -0
- package/docs/05-test-cases.md +376 -0
- package/docs/06-install-run.md +349 -0
- package/docs/07-user-manual.md +92 -0
- package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +86 -0
- package/docs/09-compatibility.md +201 -0
- package/docs/10-remote-access-and-launch-plan.md +216 -0
- package/docs/11-remote-relay-guide.md +82 -0
- package/docs/APP-ENCRYPTION-DESCRIPTION.md +50 -0
- package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
- package/docs/ARCHITECTURE-CURRENT.md +229 -0
- package/docs/AUDIT-2026-11-node.md +181 -0
- package/docs/AUDIT-2026-11.md +167 -0
- package/docs/BRAND-ASSETS.md +142 -0
- package/docs/BUILD-ENVIRONMENT.md +180 -0
- package/docs/FEATURE-PARITY.md +195 -0
- package/docs/PRIVACY-POLICY.en.md +143 -0
- package/docs/PRIVACY-POLICY.md +143 -0
- package/docs/REA-UNDERSTANDING.md +246 -0
- package/docs/STORE-LAUNCH.md +278 -0
- package/docs/STORE-LISTING.md +150 -0
- package/docs/SUPPORT.md +43 -0
- package/docs/TERMS-OF-SERVICE.en.md +70 -0
- package/docs/TERMS-OF-SERVICE.md +70 -0
- package/docs/screenshots/01-home.png +0 -0
- package/docs/screenshots/02-notifications.png +0 -0
- package/docs/screenshots/03-sessions.png +0 -0
- package/docs/screenshots/04-chat.png +0 -0
- package/docs/screenshots/05-settings.png +0 -0
- package/docs/screenshots/06-new-session.png +0 -0
- package/docs/screenshots/07-connect.png +0 -0
- package/docs/screenshots/pgy-appstore.jpg +0 -0
- package/docs/screenshots/pgy-mobile-app.jpg +0 -0
- package/docs/screenshots/pgy-pc-client.jpg +0 -0
- package/lib/account-usage-query.js +278 -0
- package/lib/account-usage.js +145 -0
- package/lib/api-helpers.js +333 -0
- package/lib/auto-config.js +107 -0
- package/lib/client.js +586 -0
- package/lib/config.js +211 -0
- package/lib/git-read-bundled-provider.js +255 -0
- package/lib/git-read-service.js +322 -0
- package/lib/host-compat.js +133 -0
- package/lib/http-util.js +69 -0
- package/lib/index.js +5729 -0
- package/lib/push.js +73 -0
- package/lib/rate-limit.js +46 -0
- package/lib/relay/connector.js +300 -0
- package/lib/relay/crypto.js +117 -0
- package/lib/relay/devices.js +138 -0
- package/lib/relay/identity.js +60 -0
- package/lib/relay/mux.js +411 -0
- package/lib/relay/noise.js +178 -0
- package/lib/relay/pairing.js +64 -0
- package/lib/relay/phone.js +114 -0
- package/lib/relay/serve.js +105 -0
- package/lib/rpc-adapter.js +88 -0
- package/lib/session-list.js +77 -0
- package/lib/session-title-cache.js +123 -0
- package/lib/session-title-refresh.js +261 -0
- package/lib/timeline.js +476 -0
- package/lib/turn-outline.js +289 -0
- package/package.json +62 -4
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { basename, isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { realpath } from "node:fs/promises";
|
|
4
|
+
import { createBundledGitReadProvider } from "./git-read-bundled-provider.js";
|
|
5
|
+
|
|
6
|
+
const MAX_GRAPH_TIPS = 5;
|
|
7
|
+
|
|
8
|
+
function failure(code, status, message = code) {
|
|
9
|
+
const error = new Error(message);
|
|
10
|
+
error.code = code;
|
|
11
|
+
error.status = status;
|
|
12
|
+
return error;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const providerCompatible = (provider) => provider?.contractVersion === "1.0.0"
|
|
16
|
+
&& ["repositoryRoot", "branches", "resolveTip", "graph", "commit"].every((method) => typeof provider[method] === "function");
|
|
17
|
+
|
|
18
|
+
/** Session-authorized read facade over an optional external or bundled provider. */
|
|
19
|
+
export function createGitReadService(ctx, { bundledProvider, now = () => Date.now(), snapshotTtlMs = 5 * 60_000, pollIntervalMs = 30_000, onChanged } = {}) {
|
|
20
|
+
const get = (name) => { try { return ctx.get?.(name); } catch { return undefined; } };
|
|
21
|
+
const external = get("gitReadProvider");
|
|
22
|
+
let externalAvailable = false;
|
|
23
|
+
try { externalAvailable = providerCompatible(external) && external.capabilities?.().available === true; } catch {}
|
|
24
|
+
const provider = externalAvailable ? external : (bundledProvider ?? createBundledGitReadProvider(ctx));
|
|
25
|
+
const bindings = new Map();
|
|
26
|
+
const repositoryIdFor = (sessionId, root) => `repo_${createHash("sha256").update(`${sessionId}\0${root}`).digest("base64url").slice(0, 32)}`;
|
|
27
|
+
const inside = (child, parent) => {
|
|
28
|
+
const path = relative(resolve(parent), resolve(child));
|
|
29
|
+
return path === "" || (path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path));
|
|
30
|
+
};
|
|
31
|
+
const authorizedRoot = async (cwd) => {
|
|
32
|
+
if (typeof cwd !== "string" || !cwd) throw failure("repository-not-authorized", 403);
|
|
33
|
+
try {
|
|
34
|
+
const canonicalCwd = await realpath(cwd);
|
|
35
|
+
const workspacePaths = get("workspaceRegistry")?.list?.()?.map((entry) => entry?.path) ?? [];
|
|
36
|
+
const workspaces = await Promise.all(workspacePaths.filter((path) => typeof path === "string").map((path) => realpath(path).catch(() => null)));
|
|
37
|
+
if (!workspaces.some((path) => path && inside(canonicalCwd, path))) throw failure("repository-not-authorized", 403);
|
|
38
|
+
const root = await realpath(await provider.repositoryRoot(canonicalCwd));
|
|
39
|
+
if (!inside(canonicalCwd, root) || !workspaces.some((path) => path && inside(root, path))) throw failure("repository-not-authorized", 403);
|
|
40
|
+
return root;
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (["git-provider-unavailable", "not-git-repository"].includes(error?.code)) throw failure(error.code, error.status);
|
|
43
|
+
throw failure("repository-not-authorized", 403);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const session = (sessionId) => {
|
|
47
|
+
if (typeof sessionId !== "string" || sessionId === "") throw failure("session-not-found", 404);
|
|
48
|
+
const value = get("sessions")?.get?.(sessionId);
|
|
49
|
+
if (!value) throw failure("session-not-found", 404);
|
|
50
|
+
return value;
|
|
51
|
+
};
|
|
52
|
+
const binding = async (sessionId, repositoryId) => {
|
|
53
|
+
const value = bindings.get(repositoryId);
|
|
54
|
+
if (!value || value.sessionId !== sessionId) throw failure("repository-not-authorized", 403);
|
|
55
|
+
const current = session(sessionId);
|
|
56
|
+
const currentRoot = await authorizedRoot(current?.header?.cwd);
|
|
57
|
+
if (currentRoot !== value.root) throw failure("repository-not-authorized", 403);
|
|
58
|
+
return value;
|
|
59
|
+
};
|
|
60
|
+
const worktreeSnapshots = new Map();
|
|
61
|
+
const snapshots = new Map();
|
|
62
|
+
const fileCursors = new Map();
|
|
63
|
+
const refSignatures = new Map();
|
|
64
|
+
const keepBounded = (map, maximum) => {
|
|
65
|
+
while (map.size > maximum) map.delete(map.keys().next().value);
|
|
66
|
+
};
|
|
67
|
+
const prune = () => {
|
|
68
|
+
for (const [id, item] of snapshots) if (item.expiresAt <= now()) snapshots.delete(id);
|
|
69
|
+
for (const [id, item] of fileCursors) if (item.expiresAt <= now()) fileCursors.delete(id);
|
|
70
|
+
};
|
|
71
|
+
let pollTimer = null;
|
|
72
|
+
let unsubscribeProvider = null;
|
|
73
|
+
const validOid = (value) => typeof value === "string" && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(value);
|
|
74
|
+
const safeFilePath = (value) => typeof value === "string" && value !== "" && !isAbsolute(value) && !/^(?:[A-Za-z]:[\\/]|\\\\|[a-z][a-z\d+.-]*:\/\/)/i.test(value) && !value.split(/[\\/]/).includes("..") && !value.includes("\0");
|
|
75
|
+
const validRef = (value) => value === "HEAD" || (typeof value === "string" && /^refs\/(?:heads|remotes)\/[A-Za-z0-9._/-]+$/.test(value) && !value.includes("..") && !value.includes("//") && !value.includes("@{") && !/(^|\/)\.|\/$|\.lock(?:\/|$)|[/.]$/.test(value));
|
|
76
|
+
const stale = () => failure("graph-stale", 409);
|
|
77
|
+
const capabilities = () => {
|
|
78
|
+
const base = provider.capabilities?.() ?? { available: true, reason: null };
|
|
79
|
+
return {
|
|
80
|
+
contractVersion: "1.0.0", available: base.available !== false,
|
|
81
|
+
reason: ["git-provider-unavailable", "workspace-registry-unavailable"].includes(base.reason) ? base.reason : null,
|
|
82
|
+
readOnly: true, provider: provider === external ? "external" : "bundled",
|
|
83
|
+
features: { repository: true, branches: true, graph: true, commit: true, worktree: true, preview: true },
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
const service = {
|
|
87
|
+
capabilities,
|
|
88
|
+
async capabilitiesForSession(sessionId) {
|
|
89
|
+
const current = session(sessionId);
|
|
90
|
+
const base = capabilities();
|
|
91
|
+
if (!base.available) return base;
|
|
92
|
+
try {
|
|
93
|
+
await authorizedRoot(current?.header?.cwd);
|
|
94
|
+
return base;
|
|
95
|
+
} catch (error) {
|
|
96
|
+
const reason = ["not-git-repository", "git-provider-unavailable"].includes(error?.code)
|
|
97
|
+
? error.code : "repository-not-authorized";
|
|
98
|
+
return { ...base, available: false, reason };
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
async repositoryForSession(sessionId) {
|
|
102
|
+
const current = session(sessionId);
|
|
103
|
+
const root = await authorizedRoot(current?.header?.cwd);
|
|
104
|
+
const repositoryId = repositoryIdFor(sessionId, root);
|
|
105
|
+
bindings.set(repositoryId, { sessionId, root });
|
|
106
|
+
keepBounded(bindings, 256);
|
|
107
|
+
const rawInfo = typeof provider.repositoryInfo === "function" ? await provider.repositoryInfo(root) : {};
|
|
108
|
+
if (typeof provider.refSignature === "function") refSignatures.set(repositoryId, await provider.refSignature(root));
|
|
109
|
+
return {
|
|
110
|
+
repositoryId, name: basename(root) || "repository",
|
|
111
|
+
...(validOid(rawInfo.headOid) ? { headOid: rawInfo.headOid } : {}),
|
|
112
|
+
...(typeof rawInfo.currentBranch === "string" && rawInfo.currentBranch.startsWith("refs/heads/") && validRef(rawInfo.currentBranch) ? { currentBranch: rawInfo.currentBranch } : {}),
|
|
113
|
+
detached: rawInfo.detached === true, empty: rawInfo.empty === true,
|
|
114
|
+
};
|
|
115
|
+
},
|
|
116
|
+
async worktree(sessionId, repositoryId) {
|
|
117
|
+
const authorized = await binding(sessionId, repositoryId);
|
|
118
|
+
let reader = typeof provider.worktree === "function" ? provider : createBundledGitReadProvider(ctx);
|
|
119
|
+
let raw = await reader.worktree(authorized.root);
|
|
120
|
+
if (typeof raw?.signature !== "string" || raw.signature === "" || !Array.isArray(raw.entries)) {
|
|
121
|
+
reader = createBundledGitReadProvider(ctx);
|
|
122
|
+
raw = await reader.worktree(authorized.root);
|
|
123
|
+
}
|
|
124
|
+
const entries = (raw.entries ?? []).filter((entry) => safeFilePath(entry.path)).slice(0, 2000);
|
|
125
|
+
const snapshotId = createHash("sha256").update(`${repositoryId}\0${raw.signature}\0${JSON.stringify(entries)}`).digest("base64url");
|
|
126
|
+
worktreeSnapshots.set(snapshotId, { sessionId, repositoryId, root: authorized.root, signature: raw.signature, entries, reader, expiresAt: now() + snapshotTtlMs });
|
|
127
|
+
keepBounded(worktreeSnapshots, 128);
|
|
128
|
+
return { repositoryId, snapshotId, staged: entries.filter((e) => e.index).map(({ path, oldPath, status, conflicted }) => ({ path, ...(oldPath ? { oldPath } : {}), status, conflicted })), unstaged: entries.filter((e) => e.worktree).map(({ path, oldPath, status, conflicted }) => ({ path, ...(oldPath ? { oldPath } : {}), status, conflicted })), untracked: entries.filter((e) => e.status === "untracked").map(({ path, status, conflicted }) => ({ path, status, conflicted })), truncated: (raw.entries ?? []).length > 2000 };
|
|
129
|
+
},
|
|
130
|
+
async preview(sessionId, repositoryId, { kind, snapshotId, path, oid } = {}) {
|
|
131
|
+
const authorized = await binding(sessionId, repositoryId);
|
|
132
|
+
if (!safeFilePath(path) || !["staged", "unstaged", "untracked", "commit"].includes(kind)) throw failure("preview-invalid", 400);
|
|
133
|
+
const reader = createBundledGitReadProvider(ctx);
|
|
134
|
+
let raw;
|
|
135
|
+
if (kind === "commit") {
|
|
136
|
+
if (!validOid(oid)) throw failure("invalid-oid", 400);
|
|
137
|
+
const commit = typeof provider.commit === "function"
|
|
138
|
+
? await provider.commit(authorized.root, oid)
|
|
139
|
+
: await reader.commit(authorized.root, oid);
|
|
140
|
+
const commitFile = (Array.isArray(commit?.files) ? commit.files : []).find((file) => file.path === path || file.oldPath === path);
|
|
141
|
+
if (!commitFile) throw failure("preview-file-not-found", 404);
|
|
142
|
+
raw = { ...await reader.commitPreview(authorized.root, oid, path), ...(commitFile.oldPath ? { oldPath: commitFile.oldPath } : {}) };
|
|
143
|
+
} else {
|
|
144
|
+
const snap = worktreeSnapshots.get(snapshotId);
|
|
145
|
+
if (!snap || snap.sessionId !== sessionId || snap.repositoryId !== repositoryId || snap.root !== authorized.root || snap.expiresAt <= now()) throw stale();
|
|
146
|
+
const current = await snap.reader.worktree(authorized.root);
|
|
147
|
+
if (current.signature !== snap.signature) throw stale();
|
|
148
|
+
const member = snap.entries.find((entry) => entry.path === path && (kind === "untracked" ? entry.status === "untracked" : kind === "staged" ? entry.index : entry.worktree));
|
|
149
|
+
if (!member) throw failure("preview-file-not-found", 404);
|
|
150
|
+
if (member.conflicted) raw = { diff: "", binary: false, notice: "merge conflict preview omitted" };
|
|
151
|
+
else {
|
|
152
|
+
const previewReader = typeof snap.reader.worktreePreview === "function" ? snap.reader : reader;
|
|
153
|
+
const preview = await previewReader.worktreePreview(authorized.root, kind, path);
|
|
154
|
+
const afterPreview = await snap.reader.worktree(authorized.root);
|
|
155
|
+
if (afterPreview.signature !== snap.signature) throw stale();
|
|
156
|
+
raw = { ...preview, ...(member.oldPath ? { oldPath: member.oldPath } : {}) };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
let diff = String(raw.diff ?? ""); const max = 512 * 1024; const truncated = raw.truncated === true || Buffer.byteLength(diff) > max;
|
|
160
|
+
if (Buffer.byteLength(diff) > max) diff = Buffer.from(diff).subarray(0, max).toString("utf8");
|
|
161
|
+
const binary = raw.binary === true || /Binary files? .* differ/.test(diff) || diff.includes("GIT binary patch");
|
|
162
|
+
let notice = raw.notice;
|
|
163
|
+
if (!notice && binary) { notice = "binary preview omitted"; diff = ""; }
|
|
164
|
+
else if (!notice && /(?:new file mode|old mode|new mode) 120000/.test(diff)) { notice = "symlink text preview omitted"; diff = ""; }
|
|
165
|
+
else if (!notice && /^\+(?:Subproject commit )|^-(?:Subproject commit )/m.test(diff)) { notice = "submodule preview omitted"; diff = ""; }
|
|
166
|
+
else if (!notice && !/^@@/m.test(diff) && /^(?:old mode|new mode) /m.test(diff)) { notice = "file mode changed; no text changes"; diff = ""; }
|
|
167
|
+
return { repositoryId, kind, path, ...(raw.oldPath ? { oldPath: raw.oldPath } : {}), diff, truncated, binary, additions: raw.additions ?? null, deletions: raw.deletions ?? null, ...(notice ? { notice } : {}) };
|
|
168
|
+
},
|
|
169
|
+
async branches(sessionId, repositoryId) {
|
|
170
|
+
const authorized = await binding(sessionId, repositoryId);
|
|
171
|
+
if (typeof provider.branches !== "function") throw failure("provider-incompatible", 503);
|
|
172
|
+
const rows = await provider.branches(authorized.root);
|
|
173
|
+
const branches = (Array.isArray(rows) ? rows : []).filter((row) => row && row.name !== "HEAD" && validRef(row.name) && validOid(row.oid)).map((row) => ({
|
|
174
|
+
name: row.name, displayName: row.name.replace(/^refs\/(?:heads|remotes)\//, ""), oid: row.oid,
|
|
175
|
+
kind: row.name.startsWith("refs/remotes/") ? "remote" : "local", current: row.current === true,
|
|
176
|
+
tracking: typeof row.tracking === "string" && row.tracking.startsWith("refs/remotes/") && validRef(row.tracking) ? row.tracking : null,
|
|
177
|
+
ahead: Math.max(0, Number(row.ahead) || 0), behind: Math.max(0, Number(row.behind) || 0),
|
|
178
|
+
}));
|
|
179
|
+
return { repositoryId, branches };
|
|
180
|
+
},
|
|
181
|
+
async commit(sessionId, repositoryId, oid, { filesCursor, filesLimit = 100 } = {}) {
|
|
182
|
+
const authorized = await binding(sessionId, repositoryId);
|
|
183
|
+
if (!validOid(oid)) throw failure("invalid-oid", 400);
|
|
184
|
+
if (typeof provider.commit !== "function") throw failure("provider-incompatible", 503);
|
|
185
|
+
const limit = Math.max(1, Math.min(200, Number(filesLimit) || 100));
|
|
186
|
+
prune();
|
|
187
|
+
let offset = 0;
|
|
188
|
+
if (filesCursor) {
|
|
189
|
+
const saved = fileCursors.get(filesCursor);
|
|
190
|
+
if (!saved || saved.expiresAt <= now() || saved.sessionId !== sessionId || saved.repositoryId !== repositoryId || saved.oid !== String(oid).toLowerCase()) throw failure("invalid-files-cursor", 400);
|
|
191
|
+
offset = saved.offset;
|
|
192
|
+
}
|
|
193
|
+
const value = await provider.commit(authorized.root, oid);
|
|
194
|
+
const allFiles = (Array.isArray(value.files) ? value.files : []).filter((file) => safeFilePath(file?.path) && (file.oldPath == null || safeFilePath(file.oldPath))).map((file) => ({
|
|
195
|
+
path: String(file.path ?? ""), ...(typeof file.oldPath === "string" ? { oldPath: file.oldPath } : {}),
|
|
196
|
+
status: String(file.status ?? "modified"), binary: file.binary === true,
|
|
197
|
+
additions: file.additions == null ? null : Math.max(0, Number(file.additions) || 0),
|
|
198
|
+
deletions: file.deletions == null ? null : Math.max(0, Number(file.deletions) || 0),
|
|
199
|
+
}));
|
|
200
|
+
const items = allFiles.slice(offset, offset + limit);
|
|
201
|
+
let nextCursor = null;
|
|
202
|
+
if (offset + items.length < allFiles.length) {
|
|
203
|
+
nextCursor = randomUUID();
|
|
204
|
+
fileCursors.set(nextCursor, { sessionId, repositoryId, oid: value.oid.toLowerCase(), offset: offset + items.length, expiresAt: now() + snapshotTtlMs });
|
|
205
|
+
keepBounded(fileCursors, 1024);
|
|
206
|
+
}
|
|
207
|
+
const stats = allFiles.reduce((sum, file) => ({ additions: sum.additions + (file.additions ?? 0), deletions: sum.deletions + (file.deletions ?? 0), files: sum.files + 1 }), { additions: 0, deletions: 0, files: 0 });
|
|
208
|
+
return { repositoryId, oid: String(value.oid ?? ""), parents: Array.isArray(value.parents) ? value.parents.map(String) : [], author: String(value.author ?? ""), timestamp: Number(value.timestamp) || 0, message: String(value.message ?? ""), refs: Array.isArray(value.refs) ? value.refs.map(String) : [], tags: Array.isArray(value.tags) ? value.tags.map(String) : [], stats, files: { items, total: allFiles.length, nextCursor } };
|
|
209
|
+
},
|
|
210
|
+
async graph(sessionId, repositoryId, { tips, snapshotId, cursor, limit = 100 } = {}) {
|
|
211
|
+
const authorized = await binding(sessionId, repositoryId);
|
|
212
|
+
prune();
|
|
213
|
+
const pageSize = Math.max(1, Math.min(200, Number(limit) || 100));
|
|
214
|
+
let snapshot, offset = 0;
|
|
215
|
+
if (snapshotId !== undefined || cursor !== undefined) {
|
|
216
|
+
if (!snapshotId || !cursor) throw stale();
|
|
217
|
+
snapshot = snapshots.get(snapshotId);
|
|
218
|
+
if (!snapshot || snapshot.sessionId !== sessionId || snapshot.repositoryId !== repositoryId || snapshot.root !== authorized.root || snapshot.expiresAt <= now()) throw stale();
|
|
219
|
+
offset = snapshot.cursors.get(cursor);
|
|
220
|
+
if (!Number.isInteger(offset)) throw stale();
|
|
221
|
+
} else {
|
|
222
|
+
const selected = tips === undefined ? [{ name: "HEAD", tipOid: null }] : tips;
|
|
223
|
+
if (!Array.isArray(selected) || selected.length > MAX_GRAPH_TIPS) throw failure("graph-too-many-tips", 400);
|
|
224
|
+
if (selected.length === 0) throw failure("graph-tip-invalid", 400);
|
|
225
|
+
const names = selected.map((tip) => tip?.name);
|
|
226
|
+
if (new Set(names).size !== names.length || names.some((name) => !validRef(name)) || selected.some((tip) => tip?.tipOid != null && !validOid(tip.tipOid))) throw failure("graph-tip-invalid", 400);
|
|
227
|
+
const resolved = [];
|
|
228
|
+
for (const tip of selected) {
|
|
229
|
+
let oid;
|
|
230
|
+
try { oid = await provider.resolveTip(authorized.root, tip.name); }
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (tip.name === "HEAD" && error?.code === "git-command-failed") continue;
|
|
233
|
+
throw failure("graph-tip-invalid", 409);
|
|
234
|
+
}
|
|
235
|
+
if (!validOid(oid)) throw failure("graph-tip-invalid", 409);
|
|
236
|
+
if (tip.tipOid != null && tip.tipOid.toLowerCase() !== oid.toLowerCase()) throw failure("graph-tip-invalid", 409);
|
|
237
|
+
resolved.push({ name: tip.name, tipOid: oid });
|
|
238
|
+
}
|
|
239
|
+
snapshot = { id: randomUUID(), sessionId, repositoryId, root: authorized.root, tips: resolved, expiresAt: now() + snapshotTtlMs, cursors: new Map() };
|
|
240
|
+
snapshots.set(snapshot.id, snapshot);
|
|
241
|
+
keepBounded(snapshots, 128);
|
|
242
|
+
}
|
|
243
|
+
for (const tip of snapshot.tips) {
|
|
244
|
+
let current;
|
|
245
|
+
try { current = await provider.resolveTip(authorized.root, tip.name); } catch { throw stale(); }
|
|
246
|
+
if (current.toLowerCase() !== tip.tipOid.toLowerCase()) throw stale();
|
|
247
|
+
}
|
|
248
|
+
let rawCommits;
|
|
249
|
+
try { rawCommits = await provider.graph(authorized.root, { refs: snapshot.tips.map((tip) => tip.tipOid), offset, limit: pageSize }); }
|
|
250
|
+
catch (error) {
|
|
251
|
+
for (const tip of snapshot.tips) {
|
|
252
|
+
let current;
|
|
253
|
+
try { current = await provider.resolveTip(authorized.root, tip.name); } catch { snapshots.delete(snapshot.id); throw stale(); }
|
|
254
|
+
if (current.toLowerCase() !== tip.tipOid.toLowerCase()) { snapshots.delete(snapshot.id); throw stale(); }
|
|
255
|
+
}
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
for (const tip of snapshot.tips) {
|
|
259
|
+
let current;
|
|
260
|
+
try { current = await provider.resolveTip(authorized.root, tip.name); } catch { snapshots.delete(snapshot.id); throw stale(); }
|
|
261
|
+
if (current.toLowerCase() !== tip.tipOid.toLowerCase()) { snapshots.delete(snapshot.id); throw stale(); }
|
|
262
|
+
}
|
|
263
|
+
const commits = (Array.isArray(rawCommits) ? rawCommits : []).map((row) => ({
|
|
264
|
+
oid: String(row.oid ?? ""), parents: Array.isArray(row.parents) ? row.parents.map(String) : [],
|
|
265
|
+
author: String(row.author ?? ""), timestamp: Number(row.timestamp) || 0, subject: String(row.subject ?? ""),
|
|
266
|
+
refs: Array.isArray(row.refs) ? row.refs.map(String) : [],
|
|
267
|
+
}));
|
|
268
|
+
let nextCursor = null;
|
|
269
|
+
if (commits.length === pageSize) {
|
|
270
|
+
nextCursor = randomUUID();
|
|
271
|
+
snapshot.cursors.set(nextCursor, offset + commits.length);
|
|
272
|
+
keepBounded(snapshot.cursors, 128);
|
|
273
|
+
}
|
|
274
|
+
return { repositoryId, snapshotId: snapshot.id, tips: snapshot.tips, commits, nextCursor };
|
|
275
|
+
},
|
|
276
|
+
async _pollOnce() {
|
|
277
|
+
for (const [repositoryId, authorized] of bindings) {
|
|
278
|
+
try {
|
|
279
|
+
await binding(authorized.sessionId, repositoryId);
|
|
280
|
+
if (typeof provider.refSignature === "function") {
|
|
281
|
+
const signature = await provider.refSignature(authorized.root);
|
|
282
|
+
const previous = refSignatures.get(repositoryId); refSignatures.set(repositoryId, signature);
|
|
283
|
+
if (previous !== undefined && previous !== signature) onChanged?.(repositoryId, "refs");
|
|
284
|
+
}
|
|
285
|
+
} catch { bindings.delete(repositoryId); refSignatures.delete(repositoryId); }
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
start() {
|
|
289
|
+
if (unsubscribeProvider || pollTimer) return;
|
|
290
|
+
if (typeof provider.subscribeChanges === "function") {
|
|
291
|
+
try { unsubscribeProvider = provider.subscribeChanges((change) => {
|
|
292
|
+
void (async () => {
|
|
293
|
+
for (const [repositoryId, authorized] of bindings) {
|
|
294
|
+
if (change?.root !== authorized.root) continue;
|
|
295
|
+
try {
|
|
296
|
+
await binding(authorized.sessionId, repositoryId);
|
|
297
|
+
if (typeof provider.refSignature === "function") {
|
|
298
|
+
const signature = await provider.refSignature(authorized.root);
|
|
299
|
+
const previous = refSignatures.get(repositoryId);
|
|
300
|
+
refSignatures.set(repositoryId, signature);
|
|
301
|
+
if (previous === signature) continue;
|
|
302
|
+
}
|
|
303
|
+
onChanged?.(repositoryId);
|
|
304
|
+
} catch { bindings.delete(repositoryId); refSignatures.delete(repositoryId); }
|
|
305
|
+
}
|
|
306
|
+
})();
|
|
307
|
+
}); } catch { unsubscribeProvider = null; }
|
|
308
|
+
if (typeof unsubscribeProvider !== "function") unsubscribeProvider = null;
|
|
309
|
+
}
|
|
310
|
+
// Ref polling is server-side; worktree polling stays scoped to an open mobile page.
|
|
311
|
+
pollTimer = setInterval(() => { void service._pollOnce(); }, pollIntervalMs);
|
|
312
|
+
pollTimer.unref?.();
|
|
313
|
+
},
|
|
314
|
+
stop() {
|
|
315
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
316
|
+
pollTimer = null;
|
|
317
|
+
try { unsubscribeProvider?.(); } catch { /* optional provider teardown must not break host shutdown */ }
|
|
318
|
+
unsubscribeProvider = null;
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
return service;
|
|
322
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主 API 代际探测(ADR 0017):按结构特征判别任务服务 / 网关 / 设置服务属于哪一代,以及能力状态归类。
|
|
3
|
+
* 从 lib/index.js 原样拆出(行为不变)。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 任务服务的代际:0.2.0 同时带来两处差异——`list`/`kill` 改收 SessionId **字符串**
|
|
8
|
+
* (0.1.x 收 **Agent 对象**,实现内部取其 `.id`),以及事件回调
|
|
9
|
+
* `onJobsChanged`/`onJobDone` 被统一的 `events.subscribe(filter, listener)` 取代。
|
|
10
|
+
* 两处同版发生,故共用同一个结构探测(事件流是否存在),避免"用一个特征的版本
|
|
11
|
+
* 去推断另一个特征"。传错 caller 形状不报错,只是恒返回空。
|
|
12
|
+
*/
|
|
13
|
+
export const jobsNeedsSessionId = (jobs) => typeof jobs?.events?.subscribe === "function";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 事件流打开:0.2.0 在途中插入了 uplink/peer,取消信号从**第 3 位移到第 5 位**。
|
|
17
|
+
* 传错位不会报参数错误——信号落进 uplink、真正的 signal 为 undefined,
|
|
18
|
+
* 宿主在 `AbortSignal.any` 处抛错并被重试循环吞掉,表现为"该通道不可用"。
|
|
19
|
+
* 按形参个数判别(0.1.x 为 3,0.2.0 为 6)。
|
|
20
|
+
*/
|
|
21
|
+
export const wireStreamTakesControl = (gateway) =>
|
|
22
|
+
typeof gateway?.openWireStream === "function" && gateway.openWireStream.length >= 5;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 进程内网关调用的 Peer 来源(issue #34,DSH 0.2.1-rc.2)。
|
|
26
|
+
*
|
|
27
|
+
* 宿主 0.2.1 删除了 `typertGateway.operatorPeer()` / `connection.operator` 兜底,改为
|
|
28
|
+
* **每一个**网关入口(`invokeRpc` / `stream` / `openWireStream` / `dispatchRpc`)都先
|
|
29
|
+
* `assertPeerLive(peer)`——进程内调用者必须显式传一个活着的 Peer(`InvokeRemoteRequest.peer`
|
|
30
|
+
* 已是必填)。0.2.1 给进程内调用者的入口是 `connection.createPeer({ principal, interactions })`。
|
|
31
|
+
*
|
|
32
|
+
* 返回值即"插件该走哪条 peer 路径":
|
|
33
|
+
* - `createPeer` 0.2.1+:由 `ctx.connection.createPeer` 现造 owner Peer;
|
|
34
|
+
* - `operatorPeer` 0.2.0:网关自带 operator Peer 兜底,插件继续传 undefined 即可;
|
|
35
|
+
* - `none` 网关入口在、但两条 peer 来源都没有 —— 调用必失败(能力语义漂移)。
|
|
36
|
+
*
|
|
37
|
+
* 按结构特征判别,不按版本号(ADR 0017)。
|
|
38
|
+
*/
|
|
39
|
+
export const hostPeerSource = (gateway, connection) => {
|
|
40
|
+
if (typeof connection?.createPeer === "function") return "createPeer";
|
|
41
|
+
if (typeof gateway?.operatorPeer === "function") return "operatorPeer";
|
|
42
|
+
return "none";
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 0.2.1+:创建一个进程内 owner Peer(与浏览器 GUI 同主体,`interactions: "answer"` 才能开
|
|
47
|
+
* `$events` 转发流)。旧代没有 `createPeer` 时返回 undefined,让网关自己兜底。
|
|
48
|
+
*/
|
|
49
|
+
export const createInProcessPeer = (connection) => {
|
|
50
|
+
if (typeof connection?.createPeer !== "function") return undefined;
|
|
51
|
+
return connection.createPeer({ principal: { kind: "owner" }, interactions: "answer" });
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 跨代读取一个设置节:0.2.0 走 `describe()` 找同名描述符取其 `value`;
|
|
56
|
+
* 0.1.x 走 `get(ns)`。两代都取不到时返回 undefined(调用方按"无此配置"处理)。
|
|
57
|
+
*/
|
|
58
|
+
export const readSettingsSection = (settings, ns) => {
|
|
59
|
+
const result = readSettingsSectionStrict(settings, ns);
|
|
60
|
+
return result.ok ? result.value : undefined;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* **严格**读取一个设置节(issue #21 评审 WARNING 3)。
|
|
65
|
+
*
|
|
66
|
+
* `readSettingsSection` 会把"读取抛错""describe 返回形状不合法""方法缺失"全部折叠成
|
|
67
|
+
* undefined,调用方再用 `?? {}` 兜底 —— 于是**读取失败被伪装成"命名空间不存在"**。
|
|
68
|
+
* 对 Codex 代理配置而言这是致命的:插件会据此判定"用户没开代理"、静默改走直连。
|
|
69
|
+
*
|
|
70
|
+
* 本函数把三件事分开:
|
|
71
|
+
* - `{ ok: true, value }` —— 读到了(`value` 可能是 undefined,表示命名空间确实不存在);
|
|
72
|
+
* - `{ ok: false, reason }` —— **读不到**(方法缺失 / 抛错 / 描述符形状漂移)。
|
|
73
|
+
*
|
|
74
|
+
* @returns {{ok: true, value: unknown} | {ok: false, reason: string}}
|
|
75
|
+
*/
|
|
76
|
+
export const readSettingsSectionStrict = (settings, ns) => {
|
|
77
|
+
if (!settings) return { ok: false, reason: "settings-service-missing" };
|
|
78
|
+
if (typeof ns !== "string" || ns === "") return { ok: false, reason: "namespace-invalid" };
|
|
79
|
+
// 0.1.x:get(ns)
|
|
80
|
+
if (typeof settings.get === "function") {
|
|
81
|
+
try {
|
|
82
|
+
return { ok: true, value: settings.get(ns) };
|
|
83
|
+
} catch {
|
|
84
|
+
return { ok: false, reason: "settings-get-threw" };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// 0.2.x:describe() → 描述符数组
|
|
88
|
+
if (typeof settings.describe === "function") {
|
|
89
|
+
let rows;
|
|
90
|
+
try {
|
|
91
|
+
rows = settings.describe();
|
|
92
|
+
} catch {
|
|
93
|
+
return { ok: false, reason: "settings-describe-threw" };
|
|
94
|
+
}
|
|
95
|
+
// 形状漂移(返回对象而非数组、或行结构不认识)属于**读不到**,不是"不存在"
|
|
96
|
+
if (!Array.isArray(rows)) return { ok: false, reason: "settings-describe-shape-invalid" };
|
|
97
|
+
const row = rows.find((candidate) => candidate?.ns === ns);
|
|
98
|
+
if (row === undefined) return { ok: true, value: undefined }; // 命名空间确实不存在
|
|
99
|
+
if (!Object.prototype.hasOwnProperty.call(row, "value")) return { ok: false, reason: "settings-descriptor-without-value" };
|
|
100
|
+
return { ok: true, value: row.value };
|
|
101
|
+
}
|
|
102
|
+
return { ok: false, reason: "settings-has-no-read-method" };
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 任务查询 / 终止的 caller 实参:0.2.0 要 SessionId **字符串**,0.1.x 要 **Agent 对象**。
|
|
107
|
+
* 传错形状不会报参数错误:列表恒返回空(看起来像"这个会话确实没有任务"),
|
|
108
|
+
* 终止则报"任务属于另一个会话"。因此必须按代际给出正确形状。
|
|
109
|
+
* caller 缺失时两代都接受 undefined,原样传 undefined。
|
|
110
|
+
*/
|
|
111
|
+
export const jobsCallerFor = (jobs, agent, sessionId) => {
|
|
112
|
+
if (!jobsNeedsSessionId(jobs)) return agent;
|
|
113
|
+
if (typeof sessionId === "string" && sessionId !== "") return sessionId;
|
|
114
|
+
const id = agent?.session?.id ?? agent?.id;
|
|
115
|
+
return typeof id === "string" && id !== "" ? id.replace(/^session:/, "") : undefined;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 单项宿主能力的状态(ADR 0017 要求的三态报告)。仅报"服务在不在"不够:
|
|
120
|
+
* 本次四处不兼容**全部**是"服务在、调用不报错、语义已变",两分法看不见它们。
|
|
121
|
+
* · `ok` 服务与插件真正调用的成员都在;
|
|
122
|
+
* · `drift` 服务在,但成员形状不是插件认识的样子(能力语义漂移);
|
|
123
|
+
* · `missing` 服务本身不存在。
|
|
124
|
+
* 判定谓词由调用方给出——每项能力"什么算可用"的定义不同(例如 tasks 有两代合法形状)。
|
|
125
|
+
*/
|
|
126
|
+
export const capabilityState = (service, predicate) => {
|
|
127
|
+
if (!service) return "missing";
|
|
128
|
+
try {
|
|
129
|
+
return predicate(service) ? "ok" : "drift";
|
|
130
|
+
} catch {
|
|
131
|
+
return "drift"; // 探测自身抛错,同样说明形状不符预期
|
|
132
|
+
}
|
|
133
|
+
};
|
package/lib/http-util.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON 响应 / 请求体读取 / 方法检查 / 响应防崩守卫。从 lib/index.js 原样拆出(行为不变;`error` 在模块内更名为 `sendError`)。
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/** 响应防崩守卫(写已销毁响应时 error 事件有监听)。 */
|
|
6
|
+
export const guardRes = (res) => {
|
|
7
|
+
if (!res.__dshErrGuarded) {
|
|
8
|
+
res.__dshErrGuarded = true;
|
|
9
|
+
res.on("error", () => {});
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const sendJson = (res, status, body, headers = {}) => {
|
|
14
|
+
// v2.7.2 review(S2):客户端中途断开后对已销毁响应 writeHead/end 会 emit 'error',
|
|
15
|
+
// 无监听时 Node 抛未捕获异常 → 崩进程;挂一次性 noop 监听兜底
|
|
16
|
+
guardRes(res);
|
|
17
|
+
const text = JSON.stringify(body);
|
|
18
|
+
res.writeHead(status, {
|
|
19
|
+
"content-type": "application/json; charset=utf-8",
|
|
20
|
+
"cache-control": "no-store",
|
|
21
|
+
// v3.0.0(热修 04):响应即断(connection: close)——关闭 keep-alive 复用窗口:
|
|
22
|
+
// 手机 dart:io 连接池 idle 15s 与服务端 keep-alive 5s 存在半关竞态,
|
|
23
|
+
// 复用半关 socket 表现为「Connection reset by peer」:消息已送达却报失败。
|
|
24
|
+
// 移动端 API 均为一问一答短请求,无 keep-alive 收益。
|
|
25
|
+
"connection": "close",
|
|
26
|
+
"content-length": Buffer.byteLength(text),
|
|
27
|
+
...headers,
|
|
28
|
+
});
|
|
29
|
+
res.end(text);
|
|
30
|
+
};
|
|
31
|
+
export const sendError = (res, status, err, detail) => sendJson(res, status, detail ? { error: err, detail } : { error: err });
|
|
32
|
+
|
|
33
|
+
export const readBody = (req, limit = 64 * 1024) =>
|
|
34
|
+
new Promise((resolve, reject) => {
|
|
35
|
+
let size = 0;
|
|
36
|
+
const chunks = [];
|
|
37
|
+
req.on("data", (chunk) => {
|
|
38
|
+
size += chunk.length;
|
|
39
|
+
if (size > limit) {
|
|
40
|
+
reject(Object.assign(new Error("body too large"), { status: 413 }));
|
|
41
|
+
// v3.0.0 修复:超限先停读并让 handler 回 413——此前先 req.destroy()
|
|
42
|
+
// 会把连接直接掐断,客户端看到的是"连接意外关闭/连接重置"而非 413
|
|
43
|
+
// (592KB 图片上传即此症状:上游看到连接被切断 → 桥回 502 bridge-unavailable)
|
|
44
|
+
req.pause();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
chunks.push(chunk);
|
|
48
|
+
});
|
|
49
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
50
|
+
req.on("error", reject);
|
|
51
|
+
// review:客户端断开且不触发 error 时也要 settle,避免 handler 悬挂
|
|
52
|
+
req.on("close", () => reject(Object.assign(new Error("request closed"), { status: 400 })));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Phase 1(S6):方法检查收敛——不匹配时已响应 405 并返回 true,调用点 `if (requireGet(method, res)) return;`
|
|
56
|
+
export const requireGet = (method, res) => {
|
|
57
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
58
|
+
sendError(res, 405, "method-not-allowed");
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
return false;
|
|
62
|
+
};
|
|
63
|
+
export const requirePost = (method, res) => {
|
|
64
|
+
if (method !== "POST") {
|
|
65
|
+
sendError(res, 405, "method-not-allowed");
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
return false;
|
|
69
|
+
};
|