Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ cccodroid 让执行回到你自己的设备上:云端只负责模型推理,
- **修复账本**:开发工具包的每次安装、校验、修复与启动时的恢复都记一笔(发现了什么、做了什么、结果如何),设置页可查。
- **已知问题**:还没查清、也没完全排除的问题,以及目前知道的情况,列在 [docs/known-issues.zh-CN.md](docs/known-issues.zh-CN.md)。
- **权限说明**:每个权限拿来干什么、什么时候问、不给会怎样,见 [docs/permissions.zh-CN.md](docs/permissions.zh-CN.md);发现安全问题请按 [SECURITY.md](SECURITY.md) 私下报告。
- **设备互联**:设置 → 设备互联。与另一台 cccodroid 在同一局域网时用 6 位码配对,之后双向同步 Claude 会话、会话名、置顶和会话引用的工作区产物;不同网络可在两端填同一个 HTTPS 公网中转。关闭互联不会删除配对和会话。
- **跨设备执行**:输入框里以 `@手机 任务`、`@电脑 任务` 或 `@shouji-设备号 任务` 开头时,这一轮交给对端执行,正文、思考、工具调用实时回传;对端已有同步会话时续跑同一会话,回复再随会话同步回来。Claude 也可以通过内置 `remote_devices` / `remote_task` MCP 工具主动派一次性任务。
- **互联权限**:远程执行默认关闭,开启后还要逐台放行;放行等于允许该设备在本机运行任意命令和读写文件。局域网会话传输是明文 HTTP,只在可信家庭 / 办公室网络开启;公网请使用 HTTPS 中转。
- **USB 调试另一台设备**:OTG 线连上后运行 `usb-adb`,就能照常 `adb devices / install / shell`。
- **自检**:`cccodroid-selftest` 逐项实测 70 多项工具与用法(含 ffmpeg 与硬件编码探测);工具说明会注入 Claude 的系统提示,让它知道手里有什么。

Expand Down
3 changes: 2 additions & 1 deletion devkit/devkit.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@ import path from "node:path";
import zlib from "node:zlib";
import crypto from "node:crypto";
import { execFileSync, execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import * as xzNs from "./vendor/xz-decompress/dist/package/xz-decompress.js";
const xz = xzNs.default ?? xzNs;

const HERE = path.dirname(new URL(import.meta.url).pathname);
const HERE = path.dirname(fileURLToPath(import.meta.url));
const MAN = JSON.parse(fs.readFileSync(path.join(HERE, "devkit.json"), "utf8"));
const args = process.argv.slice(2);
const cmd = args[0];
Expand Down
24 changes: 23 additions & 1 deletion gateway/gw/bus.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { LIVE } from "./config.mjs";
import { RUNS, runList } from "./runs.mjs";
import { NEXT, sendJson, uiTag, writePaced } from "./http.mjs";
import { NEXT, readBody, sendJson, uiTag, writePaced } from "./http.mjs";
import { flushPend, snapshot } from "./queue.mjs";
import { onTamper, tamperAck, tamperPending } from "./tamper.mjs";

Expand Down Expand Up @@ -127,6 +127,28 @@ export async function routeBus(req, res, u, p) {
req.on("close", () => BUS.clients.delete(res));
return;
}
// linkd 是独立进程:同步拉到新会话或名称/置顶变化后,用网关令牌通知这里,
// 让所有已打开的界面立即重取会话列表,而不是等下一次切页或 45 秒轮询。
if (req.method === "POST" && p === "/api/link/synced") {
let b;
try { b = JSON.parse((await readBody(req)) || "{}"); } catch { return sendJson(res, 400, { error: "bad json" }); }
const n = (v) => Math.max(0, Math.min(10000, Number(v) || 0));
const peer = b.peer && typeof b.peer === "object" ? b.peer : {};
const ev = {
type: "link_sync",
at: Number(b.at) || Date.now(),
peer: {
id: String(peer.id || "").slice(0, 64),
name: String(peer.name || "").slice(0, 60),
via: peer.via === "relay" ? "relay" : "lan",
},
pulled: n(b.pulled),
pushed: n(b.pushed),
meta: !!b.meta,
};
publish(ev);
return sendJson(res, 200, { ok: true });
}
if (req.method === "GET" && p === "/api/state") return sendJson(res, 200, snapshot());
if (req.method === "POST" && p === "/api/tamper/ack") {
tamperAck(u.searchParams.get("id"));
Expand Down
262 changes: 262 additions & 0 deletions gateway/gw/link.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { CFG, HERE, log } from "./config.mjs";
import { TOKEN } from "./access.mjs";
import { NEXT, readBodyBuf, sendJson } from "./http.mjs";

// ── 设备互联客户端 / linkd 守护 ───────────────────────────────────────
// linkd 是随 APK 安装在 files/app/link 的独立 Node 服务:
// · 9377 只给本机界面和网关用,鉴权沿用网关令牌
// · 9378 给已配对设备同步会话
// · 9379/UDP 只负责局域网发现
// 网关只负责把它拉起来、提供管理页地址,并在 @ 设备轮次里转发插话 / 产物请求。

export const LINK_API = process.env.CCAPP_LINKD || "http://127.0.0.1:9377";
const LINK_SCRIPT = path.join(HERE, "link", "linkd.mjs");
const REMOTE_MCP = path.join(HERE, "link", "remote-mcp.mjs");
const LINK_UI = path.join(HERE, "link", "ui.html");
const TOKEN_FILE = path.join(CFG.home, ".gateway-token");
const LINK_PROXY = "/api/link/proxy/";

let linkChild = null;
let linkActive = false;
let linkTimer = null;
let linkStarting = null;

function timeout(ms) {
return AbortSignal.timeout ? AbortSignal.timeout(ms) : undefined;
}

async function healthy(ms = 1500) {
try {
const r = await fetch(LINK_API + "/api/health", { signal: timeout(ms) });
if (!r.ok) return false;
const j = await r.json().catch(() => null);
return !!(j && j.ok && Number(j.v) === 1);
} catch {
return false;
}
}

function relayLine(kind, buf) {
const s = String(buf || "").trim();
if (s) for (const line of s.split(/\r?\n/)) log(`[${kind}] ${line}`.slice(0, 4000));
}

/** 拉起 linkd;已经有一个健康的实例(例如网关被 SIGKILL 后重启)就直接复用。 */
export async function ensureLinkd() {
if (await healthy()) return { ok: true, adopted: linkChild == null };
if (linkStarting) return linkStarting;
if (!fs.existsSync(LINK_SCRIPT)) throw new Error(`找不到互联服务:${LINK_SCRIPT}`);
linkStarting = (async () => {
if (linkChild && linkChild.exitCode == null) return { ok: true };
const args = [
LINK_SCRIPT,
"--home", CFG.home,
"--workspace", CFG.workspace,
"--gateway-port", String(CFG.port),
"--local-port", "9377",
"--lan-port", "9378",
"--udp-port", "9379",
];
const child = spawn(process.execPath, args, {
cwd: CFG.home,
env: { ...process.env, CCAPP_LINKD: LINK_API },
stdio: ["ignore", "pipe", "pipe"],
detached: false,
});
linkChild = child;
child.stdout?.setEncoding("utf8");
child.stderr?.setEncoding("utf8");
child.stdout?.on("data", (d) => relayLine("link", d));
child.stderr?.on("data", (d) => relayLine("link!", d));
child.on("error", (e) => log(`互联服务进程错误:${e.message}`));
child.on("exit", (code, signal) => {
if (linkChild === child) linkChild = null;
if (linkActive) log(`互联服务退出 code=${code ?? "-"} signal=${signal || "-"}`);
});
for (let i = 0; i < 30; i++) {
await new Promise((r) => setTimeout(r, 200));
if (await healthy(600)) return { ok: true };
if (child.exitCode != null) break;
}
throw new Error("互联服务没有在 9377 端口就绪,请查看 gateway.log / link.log");
})().finally(() => { linkStarting = null; });
return linkStarting;
}

/** 网关启动后调用:先立即拉一次,之后每 10 秒补拉;退出中的网关不会反复拉起。 */
export function startLinkdSupervisor() {
if (linkActive) return;
linkActive = true;
const tick = () => { if (linkActive) ensureLinkd().catch((e) => log(`互联服务:${e.message}`)); };
tick();
linkTimer = setInterval(tick, 10000);
linkTimer.unref?.();
}

/** 网关正常退出时停掉实例;SIGKILL 留下的实例会被下一任网关复用。 */
export async function stopLinkd() {
linkActive = false;
if (linkTimer) { clearInterval(linkTimer); linkTimer = null; }
const child = linkChild;
linkChild = null;
if (child && child.exitCode == null) { try { child.kill("SIGTERM"); } catch {} }
await fetch(LINK_API + "/api/shutdown", {
method: "POST",
headers: { "x-link-token": TOKEN, "content-type": "application/json" },
body: "{}",
signal: timeout(1200),
}).catch(() => {});
}

async function call(p, opts = {}, ms = 20000) {
const r = await fetch(LINK_API + p, {
...opts,
headers: {
"x-link-token": TOKEN,
"content-type": "application/json",
...(opts.headers || {}),
},
signal: timeout(ms),
});
const j = await r.json().catch(() => ({}));
if (!r.ok) {
const e = new Error(j.message || j.error || `linkd HTTP ${r.status}`);
e.status = r.status;
e.body = j;
throw e;
}
return j;
}

export function linkGet(p, ms = 20000) { return call(p, { method: "GET" }, ms); }
export function linkPost(p, body, ms = 20000) {
return call(p, { method: "POST", body: JSON.stringify(body || {}) }, ms);
}

/** 插话:投给正在对端执行的那一轮。 */
export function linkInject(taskId, text) {
return linkPost("/api/remote/inject", { id: taskId, text }, 20000);
}

/** 本机缺的工作区产物,按相对路径向正在执行的局域网对端取一份。 */
export function linkFetchArtifact(p, ms = 15000) {
return linkPost("/api/remote/fetch", { path: p }, ms);
}

/** 每次起 Claude 时随 --mcp-config 注入;不改用户自己的 .claude.json。 */
export function remoteMcpServer() {
if (!fs.existsSync(REMOTE_MCP)) return null;
return {
type: "stdio",
command: process.execPath,
args: [REMOTE_MCP],
env: {
CCAPP_LINKD: LINK_API,
CCAPP_GW_TOKEN_FILE: TOKEN_FILE,
},
};
}

/** linkd 的管理页跟主界面一起走同源代理,避免 Android WebView 的跨端口令牌 / Cookie 差异。 */
export function linkUiHtml() {
return fs.readFileSync(LINK_UI, "utf8").replaceAll('"/api/', `"${LINK_PROXY}`);
}

async function proxyLink(req, res, p) {
const sub = p.slice(LINK_PROXY.length).replace(/^\/+/, "");
if (!sub) return sendJson(res, 400, { error: "bad link path" });
const q = req.url.includes("?") ? req.url.slice(req.url.indexOf("?")) : "";
const body = req.method === "GET" || req.method === "HEAD"
? undefined
: await readBodyBuf(req, 128 * 1024);
const r = await fetch(LINK_API + "/api/" + sub + q, {
method: req.method,
headers: {
"x-link-token": TOKEN,
"content-type": String(req.headers["content-type"] || "application/json"),
},
body,
signal: timeout(20000),
});
const data = Buffer.from(await r.arrayBuffer());
res.writeHead(r.status, {
"content-type": r.headers.get("content-type") || "application/json; charset=utf-8",
"cache-control": "no-store",
"content-length": data.length,
});
res.end(data);
}

export async function routeLink(req, res, u, p) {
if (req.method === "GET" && p === "/api/link/ui") {
try {
const data = Buffer.from(linkUiHtml());
res.writeHead(200, {
"content-type": "text/html; charset=utf-8",
"cache-control": "no-store",
"content-length": data.length,
});
return res.end(data);
} catch (e) {
return sendJson(res, 500, { error: e.message });
}
}
if ((req.method === "GET" || req.method === "POST") && p.startsWith(LINK_PROXY)) {
try {
return await proxyLink(req, res, p);
} catch (e) {
return sendJson(res, e.status || 502, { error: e.message || "link proxy failed" });
}
}
if (req.method === "GET" && p === "/api/link/origins") {
try {
const j = await linkGet("/api/origins", 5000);
return sendJson(res, 200, j);
} catch {
return sendJson(res, 200, { ok: false, origins: {} });
}
}
if (req.method === "GET" && p === "/api/link/status") {
const up = await healthy();
if (!up) return sendJson(res, 200, { ok: true, running: false });
try {
const s = await linkGet("/api/status", 4000);
return sendJson(res, 200, {
ok: true, running: true,
device: s.device || null,
lan: s.lan || null,
relay: s.relay || null,
peers: s.peers || [],
});
} catch (e) {
return sendJson(res, 200, { ok: true, running: false, error: e.message });
}
}
if (req.method === "GET" && p === "/api/link/url") {
try {
await ensureLinkd();
return sendJson(res, 200, {
ok: true,
url: LINK_API + "/?t=" + encodeURIComponent(TOKEN),
embed: "/api/link/ui",
});
} catch (e) {
return sendJson(res, 503, { ok: false, error: e.message });
}
}
if (req.method === "POST" && p === "/api/link/restart") {
try {
await linkPost("/api/shutdown", {}, 2000).catch(() => {});
linkChild = null;
await new Promise((r) => setTimeout(r, 500));
await ensureLinkd();
return sendJson(res, 200, { ok: true });
} catch (e) {
return sendJson(res, 503, { ok: false, error: e.message });
}
}
return NEXT;
}
37 changes: 35 additions & 2 deletions gateway/gw/queue.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { cleanMergeFrom } from "./merge.mjs";
import { LOCAL_CMD_RE } from "./modelcmd.mjs";
import { tamperPending } from "./tamper.mjs";
import { RATE_LIMITS } from "./stream.mjs";
import { linkInject } from "./link.mjs";

// ── 生成与排队 ────────────────────────────────────────────────────────
export const QUEUE = []; // 等着跑的消息:{ id, message, sessionId, follow, model, permissionMode, addDirs, at }
Expand Down Expand Up @@ -50,6 +51,14 @@ function laneRun(lane) {
return null;
}
const sameLane = (q, run) => { const l = laneOfItem(q), sid = sidOfLane(l); return l === run.lane || (!!sid && sid === run.sessionId); };
/** 这个会话是否正有一轮在另一台设备上跑(@ 设备)。 */
function remoteRunOf(sid) {
for (const r of RUNS.values()) {
if (!r || r.ended || !r.remote || !r.remoteTaskId) continue;
if ((r.sessionId || "") === (sid || "")) return r;
}
return null;
}
let RUN_N = 0;
const newRunId = () => `r${BOOT}${(++RUN_N).toString(36)}`;

Expand Down Expand Up @@ -307,6 +316,7 @@ export function abortRun(run, { hold = true } = {}) {
if (!run || run.ended) return false;
run.aborted = true;
run.readyAbort?.abort();
if (typeof run.remoteCancel === "function") { try { run.remoteCancel(); } catch {} }
// 停止要和排队的消息严格隔开:此刻排着的一律挂起,不许这一轮一结束就自动发出去
// (以前点停止反而是"立刻发下一条")。用户点 ⚡ 才发;停止之后新发的消息不受影响,照常先跑
// 并行时只挂起这个会话自己排着的,别的会话不受影响。
Expand Down Expand Up @@ -486,14 +496,37 @@ export async function routeQueue(req, res, u, p) {
let b;
try { b = JSON.parse((await readBody(req)) || "{}"); } catch { return sendJson(res, 400, { error: "bad json" }); }
if (!String(b.message || "").trim()) return sendJson(res, 400, { error: "empty message" });
const msgText = String(b.message || "").trim();
// 远端轮次进行中:不带 @ 的消息不能在本机另起一轮,否则两边会同时写同一个会话。
const rr = remoteRunOf(b.sessionId);
if (rr && !msgText.startsWith("/")) {
const mm = /^@(shouji|手机|phone|diannao|电脑|pc)(?:[--]([^\s,,::]+))?(?:\s+([\s\S]*))?$/i.exec(msgText);
if (!mm) {
return sendJson(res, 409, {
error: "remote_busy",
message: tz("这一轮正在「{name}」上执行。要插话,请在开头写 @手机 或 @电脑。", { name: rr.remoteName || tz("另一台设备") }),
});
}
const text = (mm[3] || "").trim();
if (!text) return sendJson(res, 400, { error: "empty message", message: tz("在 @ 后面写上要插的话") });
try {
const r = await linkInject(rr.remoteTaskId, text);
if (r && r.ok === false) return sendJson(res, 409, { error: "inject_failed", message: r.error || tz("插话没送进去") });
log(`⇄ 插话 → ${rr.remoteName || "远端"}:${text.slice(0, 40)}${text.length > 40 ? "…" : ""}`);
return sendJson(res, 200, { ok: true, injected: true, id: rr.id });
} catch (e) {
return sendJson(res, 502, { error: "inject_failed", message: tz("插话没送进去:{msg}", { msg: e.message }) });
}
}
// 看这条消息要用的那家(新会话首条选的 / 会话钉的 / 全局的),不是只看全局
const q0 = { sessionId: b.sessionId ? String(b.sessionId) : null, follow: b.follow || null, projectId: b.projectId ? String(b.projectId) : null,
pin: !b.sessionId && b.pin && typeof b.pin.provider === "string" ? { provider: b.pin.provider } : null };
const pk = pickProvider(q0), bp = pk.P;
const remoteAsk = /^@(shouji|手机|phone|diannao|电脑|pc)(?:[--]|\s|$)/i.test(msgText);
// 要用的那家不在了(写错、删了):当场拒,不悄悄换成全局默认那家发出去(起跑时 startRun 还会再挡一次)
const lost = lostProvider(q0, pk.sid0, pk.pdef0);
if (lost) return sendJson(res, 409, { error: "provider_gone", message: lost });
if (!keyOf(bp) && !bp.login && !/^\/(model|models|effort|autocompact)\b/i.test(String(b.message).trim())) {
if (lost && !remoteAsk) return sendJson(res, 409, { error: "provider_gone", message: lost });
if (!keyOf(bp) && !bp.login && !remoteAsk && !/^\/(model|models|effort|autocompact)\b/i.test(msgText)) {
return sendJson(res, 503, {
error: "no_api_key",
message: tz("「{name}」还没填 Key。到 设置 → 接口 里填好保存,或换一个接口。", { name: bp.label || bp.id }),
Expand Down
Loading
Loading