gemus-dsh-plugin 0.0.0-stage → 0.2.12
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 +112 -2
- package/cordis.patch.yml +4 -0
- package/dist/client.js +489 -0
- package/dist/host.js +639 -0
- package/icon.png +0 -0
- package/package.json +62 -4
package/dist/host.js
ADDED
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
|
|
5
|
+
var __typeError = (msg) => {
|
|
6
|
+
throw TypeError(msg);
|
|
7
|
+
};
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
9
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
10
|
+
var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
|
|
11
|
+
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
|
|
12
|
+
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
|
|
13
|
+
var __decoratorContext = (kind, name, done, metadata2, fns) => ({ kind: __decoratorStrings[kind], name, metadata: metadata2, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
|
|
14
|
+
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
|
|
15
|
+
var __runInitializers = (array, flags, self, value) => {
|
|
16
|
+
for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
|
|
17
|
+
return value;
|
|
18
|
+
};
|
|
19
|
+
var __decorateElement = (array, flags, name, decorators, target, extra) => {
|
|
20
|
+
var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
|
|
21
|
+
var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
|
|
22
|
+
var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
|
|
23
|
+
var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
|
|
24
|
+
return __privateGet(this, extra);
|
|
25
|
+
}, set [name](x) {
|
|
26
|
+
return __privateSet(this, extra, x);
|
|
27
|
+
} }, name));
|
|
28
|
+
k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
|
|
29
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
30
|
+
ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
|
|
31
|
+
if (k) {
|
|
32
|
+
ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
|
|
33
|
+
if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
|
|
34
|
+
if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
|
|
35
|
+
}
|
|
36
|
+
it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
|
|
37
|
+
if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
|
|
38
|
+
else if (typeof it !== "object" || it === null) __typeError("Object expected");
|
|
39
|
+
else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
|
|
40
|
+
}
|
|
41
|
+
return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
|
|
42
|
+
};
|
|
43
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
44
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
45
|
+
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
|
|
46
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
47
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
48
|
+
var __privateMethod = (obj, member, method2) => (__accessCheck(obj, member, "access private method"), method2);
|
|
49
|
+
|
|
50
|
+
// src/skill.ts
|
|
51
|
+
import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
|
|
52
|
+
|
|
53
|
+
// ../../skills/gemus-getting-started/SKILL.md
|
|
54
|
+
var SKILL_default = '---\nname: gemus-getting-started\ndescription: Use when building, editing, running, or opening an AI design workflow on the Gemus canvas through the Gemus MCP connection.\n---\n\n# Working With Gemus\n\nUse the installed MCP tools to operate the user\'s live Gemus canvas. If the host provides `tool_search`, load a missing tool by its exact name. Other hosts expose connected MCP tools directly; use their tool inventory and report a missing connection instead of requiring an unavailable discovery tool.\n\n## Delivery Surface\n\nWhen the requested deliverable is a Gemus workflow, keep planning and implementation on the Gemus MCP surface. MCP mutations are the implementation: use `edit` with `op: "planCreate" / "planUpdate" / "planDecide"` for durable decisions, `op: "graph"` for multi-node phases, and structure operations for focused changes, `execute` for generation, and `publish_workflow` for a confirmed direct publish.\n\nDo not create local implementation plans, specs, apps, or documents as substitutes for those canvas operations. Local filesystem work is limited to reading user-provided files or preparing assets for upload unless the user explicitly asks for a local code or document deliverable.\n\nBrowser control after `open_canvas` is for opening the returned one-time URL and visual inspection only. It does not replace MCP reads, mutations, execution, or publishing.\n\n## Workflow Contract\n\n1. Resolve the connection mode and target before the first mutation. In Bridge mode, the platform session\'s active workflow is authoritative: edit it in place and omit workflowId, or pass that exact ID. The user must open another workflow to change targets. In standalone MCP clients (Codex, DSH, and other harnesses), there is no current-canvas binding. Reuse an explicit workflowId; when the user names an existing workflow, call `workflow_list` with its exact `name`, reuse the ID only when exactly one match is returned, and ask the user to disambiguate zero or multiple matches. If a new canvas is needed, call `workflow_create` with explicit `workspaceTarget` (`personal` or `active`), `name`, and `idempotencyKey`; keep the returned `workflowId` and use `edit` afterward. Edit does not create workflows. Never guess a target.\n2. For a workflow with three or more connected nodes, load `edit` and use `op: "graph"`; use focused structure operations for small changes. Name each new zone for its design purpose. Declare deliverables in the graph or create the plan first; follow returned node and zone IDs.\n3. Call `edit` with one graph per phase. Reuse the same workflowId on later calls. For phase 2+, read actual prior outputs and connect existingNodeId to the new nodes; extend an existing zone with `zone: { id }`.\n4. Give every analyzer, brainstorm, and generated-text node its own dedicated prompt written for that node. Connect research or other generated material to its `reference` port, never its `prompt` port.\n5. Run `execute` as a dry run first and show any platform-credit estimate before requesting confirmation. In Codex, also load `gemus-codex-imagen` for local image generation and canvas backfill. Other hosts use the providers available through `execute`; they do not require the Codex companion skill.\n6. Call `open_canvas` once after obtaining the workflow ID. In Codex, load and follow `browser:control-in-app-browser`, navigating the one-time URL in its selected user-visible browser. Do not use `browser_navigate`, `browser_snapshot`, standalone Playwright MCP, chrome-devtools, or other external/headless browser surfaces in this Codex flow: they can consume the link outside the visible Browser. The Browser skill\'s own runtime is allowed. In DSH and other MCP hosts, use the host\'s available user-visible browser capability. If the host cannot open it, provide `url` and `fallbackEditorUrl` and say that the user must open it; never claim the canvas opened without evidence.\n\nUse `read` with `requests: [{ target: "contract" }]` for node/model discovery and `target: "workspace" / "node"` for current IDs, outputs, ports, and status. Every write requires idempotencyKey (8\u2013128 safe characters): keep it for retries of the same request, use a new key for a changed operation. Read receipts item by item; an accepted execute item is not proof of completion\u2014check its matching wait handle or read the canvas.\n\n### Minimal graph request\n\nReplace the workflow ID with the returned ID. Graph deliverable references are zero-based: `new:0` is the first entry. Use returned node IDs in later calls; discover node/model contracts before filling their config.\n\n```json\n{\n "workflowId": "workflow-id",\n "idempotencyKey": "getting-started-graph-01",\n "requests": [{\n "op": "graph",\n "deliverables": [{ "title": "Launch poster", "kind": "image-set" }],\n "groups": [{\n "zone": { "name": "Launch poster" },\n "deliverableIds": ["new:0"],\n "nodes": [\n { "bind": "brief", "nodeType": "text-prompt", "config": { "text": "A minimal ceramic studio launch poster" } },\n { "bind": "poster", "nodeType": "gen-image-generation", "deliverableId": "new:0", "config": { "model": "gemini-2.5-flash-image", "mode": "text-to-image" } }\n ],\n "edges": [{ "from": "brief", "fromPort": "text", "to": "poster", "toPort": "prompt" }]\n }]\n }]\n}\n```\n\n## Presentation decks\n\nA workflow carries **at most one `gen-ppt` node**. It is the deck\'s identity: its node ID owns the revision, the plan and the slide bindings. Creating a second one abandons that state instead of repairing it.\n\nPick one authoring mode per node and stay in it:\n\n| Mode | When | What runs | What is forbidden |\n| --- | --- | --- | --- |\n| Direct authoring | You are designing and filling the deck (the default when the user asks Codex to make the PPT) | `html_edit` init/plan/write/finalize | Never `execute` the `gen-ppt` node \u2014 it overwrites the deck output with model-generated content |\n| Model pipeline | The user explicitly asks for the node\'s own generation model to produce the deck | `execute` on the `gen-ppt` node | Do not also author the same node with `html_edit` in the same pass |\n\nModel constraints are scoped to what they name. "Use `gpt-image-2` for all image generation" applies to `gen-image-generation` nodes only; never propagate an image model onto `gen-ppt`, text, or analysis nodes. `edit` returns `completions` when it auto-corrects an incompatible model \u2014 read them and tell the user what changed.\n\nWhen the canvas already holds real design imagery, plan an image-led deck: every page names its visual protagonist and each asset\'s evidence role. Support a technical claim with the technical artefact \u2014 a plan, section, exploded view or detail \u2014 because an aerial or hero render does not stand in for one. Caption each asset with what THAT asset shows, mark annotated assets and give them `contain`, and do not make one image the protagonist of several pages. `read` with `target: "ppt-plan-check"` and the current revision reports all of this deterministically before any slide exists; fix the plan there rather than meeting the same defects as critique findings afterwards.\n\nWhen the user wants Codex to design and fill a presentation directly on the Gemus canvas, use the MCP PPT editor instead of executing the `gen-ppt` node\'s configured generation model:\n\n1. Find the workflow\'s existing `gen-ppt` node with `read` target `workspace` and reuse it. Create one with `edit` op `add` **only when the canvas has none**; when one already exists you may not create a second. Search for `html_edit` with `tool_search` if it is not already loaded.\n2. Read the selected `ppt-style` profile to discover its skeleton catalog before outlining or writing slides. Use only a returned `skeletonId`; never guess one. Read the selected style resource, such as `skill://corporate`, for visual guidance.\n3. Every PPT `html_edit` write uses `{ idempotencyKey, request: { documentType: "ppt", operation: { op, nodeId, ... } } }`. Call `html_edit` with `request: { documentType: "ppt", operation: { op: "init_deck", nodeId, title } }` once. Keep the returned revision, starting at `0` for a new deck.\n4. Call `write_slide_html` once per slide and pass the revision returned by the previous write. Omit `slideId` to create a new slide. Pass `slideId` to update an existing slide. Call `get_layout_seed` for the row first and act on its `assetHints` \u2014 natural aspect ratio, image-box aspect ratio, predicted `object-fit:cover` crop, whether the asset is annotated, and the recommended fit. None of that is computable from the canvas or the seed alone.\n5. Read the optional `critique` returned by each persisted `write_slide_html` or `patch_slide`. If `critique.pass` is false and `critique.correctionAllowed` is true, apply exactly one corrective round, routed by `critique.repairClass`: `local-style` \u2192 `patch_slide`; `structural-layout` \u2192 rewrite the slide with `write_slide_html`; `asset-semantic` \u2192 rebind the right evidence (replan first when the plan is what is wrong) and rewrite; `invalid-source` \u2192 swap the unusable asset or drop it to a lesser role. The correction is re-evaluated automatically. If `correctionAllowed` is false, `critique` is absent, or it passes, continue; never poll or retry the evaluator.\n6. For later edits, call `read` with `requests: [{ target: "node", address: "node://<nodeId>" }]` to get `deckSummary`, then `read` target `ppt-slide` with that address and `slideId` to read the target HTML before patching or rewriting it.\n\nOutline `assets` contains objects with a canvas asset `label` and optional `role` (`hero`, `evidence`, `background`, or `decoration`), never bare strings. For example, with the existing deck node and actual canvas asset label:\n\n```json\n{\n "workflowId": "workflow-id",\n "idempotencyKey": "getting-started-outline-01",\n "request": {\n "documentType": "ppt",\n "operation": {\n "op": "create_outline",\n "nodeId": "deck-node-id",\n "rows": [{ "title": "The proposal", "intent": "Introduce the concept", "assets": [{ "label": "Hero render", "role": "hero" }] }]\n }\n }\n}\n```\n\nFor PPT HTML, use `read` target `ppt-slide`: `{ workflowId, requests: [{ target: "ppt-slide", address: "node://<deckNodeId>", slideId: "<slideId>" }] }`. A `gen-webpage` document is read with target `webpage-section` (address and `sectionId`) or `webpage-source` (address only).\n\n### Recovering the same node\n\nEvery failure below is repaired **on the original nodeId**. Exhaust this table before even considering a new node; a second `gen-ppt` node is not a recovery step.\n\n| Symptom | Recovery |\n| --- | --- |\n| `code: \'PPT_REVISION_CONFLICT\'` | Retry the same call with the returned `currentRevision` |\n| `code: \'PPT_DECK_MALFORMED\'` | `init_deck` with `force: true` on that same node |\n| `init_deck` failed or the node holds model-generated, non-deck output | `read` with `requests: [{ target: "node", address: "node://<nodeId>" }]` for `deckSummary`, then `init_deck` with `force: true` on that same node |\n| Transport/HTTP error with unknown outcome | `read` with `requests: [{ target: "node", address: "node://<nodeId>" }]` to learn the persisted revision, then continue from it |\n\nRoute a failed `critique` by `repairClass` \u2014 what is actually wrong \u2014 not by how cheap the fix looks. The corrective round happens once, so do not spend it on a patch that cannot reach the cause.\n\nDo not call a retired structured slide-rendering action. Direct `html_edit` mutations do not use the `execute` dry-run/credit flow; only run the `gen-ppt` node when the user explicitly asks for its model-driven generation pipeline.\n\n## HTML authoring boundary\n\n`edit` changes canvas structure, node configuration and project plans. `html_edit` authors HTML on existing `gen-ppt` and `gen-webpage` nodes; it does not edit arbitrary URLs, code files, or Word previews. Use `request: { documentType: "webpage", operation: { op, nodeId, revision, ... } }` for webpages. Read source and the latest revision with `read` before writing. Every webpage operation requires a business key, revision and workflow owner permission. PPT `get_layout_seed` is view-only and requires no key; keep all other PPT lifecycle and revision rules.\n\nRetry an identical effective request with the same key, including after reconnect. A changed request requires a new key. Keys are scoped to the caller, workflow and document domain; generate a fresh key for each new operation. Unknown outcomes require reading persisted state before continuing. The unified entry does not create cross-domain transactions. Future structured Word editing is a separate document-authoring capability.\n\n## Bridge questions\n\nIn Bridge mode, ask_user_question accepts `{ idempotencyKey, request: { kind: "question", questions: [...] } }`. Ask all independent questions together (1\u20138), with optional context, image options and multiSelect. Answers return in the same call as ordered strings or arrays. Respect decline/cancel. Retrying a finalized key replays the answer; after a disconnection an unfinished question may be asked again. Other connection modes do not expose this tool.\n\n## Domain skills\n\nBefore planning or creating a domain-specific workflow, check whether a matching Gemus Skill exists; if it does and would improve output quality, read it first with `ReadMcpResourceTool({ uri: "skill://..." })`. **Skip it for simple tasks, or when you already have sufficient context.** Reading a skill is an optional quality boost, not a gate \u2014 never block or stall on it.\n\n| Trigger | Skill |\n| --- | --- |\n| video, animation, storyboard, film | `skill://film-production` |\n| interior, room, space | `skill://interior-design` |\n| brand, logo, visual identity | `skill://brand-visual` |\n| product, packaging, industrial | `skill://product-design` |\n\n`ListMcpResourcesTool()` lists everything available, including `knowledge://model-guide` (model selection) and `knowledge://design-principles` (visual consistency across multiple assets).\n\nCodex-generated images without a corresponding node remain on the local machine and do not land on the canvas.\n\n## Written guides and reports\n\nIn Codex and DSH, follow the `document_edit` description advertised for this session. When available, place or reuse one `gen-document`, read its current revision and write and finalize the manuscript there. For an illustrated guide on an image-capable session, use `edit` to connect the requested images to `material`. Read the document node and copy the target beside each chosen image into its own paragraph as ``. On a conflict, read the document again before retrying. Return its node reference in chat. Word and PDF download the same revision, so changing formats needs no edit.\n';
|
|
55
|
+
|
|
56
|
+
// src/skill.ts
|
|
57
|
+
var frontmatter = /^---\r?\nname: ([^\r\n]+)\r?\ndescription: ([^\r\n]+)\r?\n---\r?\n/;
|
|
58
|
+
var metadata = SKILL_default.match(frontmatter);
|
|
59
|
+
if (!metadata) throw new Error("Gemus canonical skill metadata is missing");
|
|
60
|
+
var candidate = {
|
|
61
|
+
name: metadata[1],
|
|
62
|
+
description: metadata[2],
|
|
63
|
+
provider: "gemus",
|
|
64
|
+
source: "bundled",
|
|
65
|
+
invocation: { modelInvocable: true, userInvocable: true },
|
|
66
|
+
rank: BUNDLED_SKILL_RANK,
|
|
67
|
+
locator: "gemus-getting-started"
|
|
68
|
+
};
|
|
69
|
+
var provider = {
|
|
70
|
+
name: candidate.provider,
|
|
71
|
+
list: async () => [candidate],
|
|
72
|
+
get: async () => ({ ...candidate, content: SKILL_default.replace(frontmatter, "").trim() })
|
|
73
|
+
};
|
|
74
|
+
function installGemusSkill(ctx) {
|
|
75
|
+
ctx.skills.registerProvider(() => provider);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/recovery.ts
|
|
79
|
+
import { expandAssistantStream } from "@deepseek-ai/dsh-llm";
|
|
80
|
+
import { randomUUID } from "node:crypto";
|
|
81
|
+
import { z } from "zod";
|
|
82
|
+
var POLICY = "gemus/tool-json/v1";
|
|
83
|
+
var MAX_RETRIES = 2;
|
|
84
|
+
var stateSchema = z.object({
|
|
85
|
+
turn: z.number().int().nonnegative(),
|
|
86
|
+
step: z.number().int().nonnegative(),
|
|
87
|
+
provider: z.string(),
|
|
88
|
+
requestSeq: z.number().int().nullable(),
|
|
89
|
+
attemptRequestSeq: z.number().int().nullable(),
|
|
90
|
+
attemptSeq: z.number().int().nullable(),
|
|
91
|
+
handledSeq: z.number().int().nullable(),
|
|
92
|
+
names: z.array(z.string()),
|
|
93
|
+
eligible: z.boolean(),
|
|
94
|
+
retries: z.number().int().nonnegative(),
|
|
95
|
+
retryId: z.string().nullable()
|
|
96
|
+
});
|
|
97
|
+
function empty() {
|
|
98
|
+
return { turn: 0, step: 0, provider: "", requestSeq: null, attemptRequestSeq: null, attemptSeq: null, handledSeq: null, names: [], eligible: false, retries: 0, retryId: null };
|
|
99
|
+
}
|
|
100
|
+
function inspect(stream) {
|
|
101
|
+
try {
|
|
102
|
+
const chunks = expandAssistantStream(stream).map((value) => value.chunk);
|
|
103
|
+
const last = chunks.at(-1);
|
|
104
|
+
if (last?.type !== "finish" || last.reason.kind !== "error" || last.reason.failure.code !== "MALFORMED_RESPONSE") return { eligible: false, names: [] };
|
|
105
|
+
const starts = chunks.flatMap((chunk) => chunk.type === "block-start" && chunk.blockType === "tool-call" ? [chunk.index] : []);
|
|
106
|
+
const tools = chunks.flatMap((chunk) => chunk.type === "block-end" && chunk.block.type === "tool-call" ? [{ index: chunk.index, block: chunk.block }] : []);
|
|
107
|
+
const names = tools.map((tool) => tool.block.name);
|
|
108
|
+
let malformed = false;
|
|
109
|
+
for (const { block } of tools) {
|
|
110
|
+
try {
|
|
111
|
+
JSON.parse(block.arguments);
|
|
112
|
+
} catch {
|
|
113
|
+
malformed = true;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return { names, eligible: malformed && tools.length > 0 && starts.length === tools.length && starts.every((start) => tools.some((tool) => tool.index === start)) && names.every((name) => name.startsWith("mcp__gemus__")) };
|
|
117
|
+
} catch {
|
|
118
|
+
return { eligible: false, names: [] };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
var recoveryProjection = {
|
|
122
|
+
key: "gemusToolJsonRecovery",
|
|
123
|
+
stateVersion: 1,
|
|
124
|
+
stateSchema,
|
|
125
|
+
init: empty,
|
|
126
|
+
apply(state, event) {
|
|
127
|
+
if (event.type === "request/header") return { ...state, provider: event.data.header.config.provider, requestSeq: event.seq };
|
|
128
|
+
if (event.type === "request/context") return { ...state, provider: event.data.provider, requestSeq: event.seq };
|
|
129
|
+
if (event.type === "step/start") return { ...empty(), turn: event.data.turn, step: event.data.step, provider: state.provider, requestSeq: state.requestSeq };
|
|
130
|
+
if (event.type === "turn/end") return { ...empty(), provider: state.provider, requestSeq: state.requestSeq };
|
|
131
|
+
if (event.type === "assistant/attempt") {
|
|
132
|
+
if (event.data.turn !== state.turn || event.data.step !== state.step || state.attemptSeq !== null && event.seq <= state.attemptSeq) return state;
|
|
133
|
+
return { ...state, ...inspect(event.data.stream), attemptSeq: event.seq, attemptRequestSeq: state.requestSeq };
|
|
134
|
+
}
|
|
135
|
+
if (event.type === "llm/retry" && event.data.policyKey === POLICY && event.data.turn === state.turn && event.data.step === state.step && event.data.provider === state.provider && state.attemptSeq !== null && event.seq > state.attemptSeq && state.handledSeq !== state.attemptSeq && event.data.retry === state.retries + 1 && event.data.retry <= MAX_RETRIES && (state.retryId === null || state.retryId === event.data.retryId)) {
|
|
136
|
+
return { ...state, handledSeq: state.attemptSeq, retries: state.retries + 1, retryId: event.data.retryId };
|
|
137
|
+
}
|
|
138
|
+
return state;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
async function installGemusRecovery(ctx, connectionToken) {
|
|
142
|
+
const recovery = await ctx.sessionProjections.register(recoveryProjection);
|
|
143
|
+
let active = true;
|
|
144
|
+
ctx.effect(() => () => {
|
|
145
|
+
active = false;
|
|
146
|
+
});
|
|
147
|
+
ctx.on("agent/request-error", async (payload, next) => {
|
|
148
|
+
const { agent, turn, step, provider: provider2, failure, retryPolicy, signal } = payload;
|
|
149
|
+
if (!active || signal.aborted) return;
|
|
150
|
+
if (failure.code !== "MALFORMED_RESPONSE" || retryPolicy?.mode === "always" || retryPolicy?.mode === "normal" && (retryPolicy.maxRetries === 0 || retryPolicy.retryableCodes.includes(failure.code))) return next();
|
|
151
|
+
const token = connectionToken();
|
|
152
|
+
const before = recovery.stateOf(agent.session);
|
|
153
|
+
if (token === void 0 || !before.eligible || before.turn !== turn || before.step !== step || before.provider !== provider2 || before.requestSeq === null || before.requestSeq !== before.attemptRequestSeq || before.handledSeq === before.attemptSeq || before.retries >= MAX_RETRIES || !before.names.every((name) => ctx.tools.get(name))) return next();
|
|
154
|
+
const downstream = await next();
|
|
155
|
+
if (signal.aborted) return;
|
|
156
|
+
if (downstream?.kind === "retry") return downstream;
|
|
157
|
+
if (!active || connectionToken() !== token) return downstream;
|
|
158
|
+
const current = recovery.stateOf(agent.session);
|
|
159
|
+
if (current.attemptSeq !== before.attemptSeq || current.requestSeq !== before.requestSeq || current.handledSeq === current.attemptSeq || current.retries >= MAX_RETRIES) return downstream;
|
|
160
|
+
const retryId = current.retryId ?? randomUUID();
|
|
161
|
+
const retry = current.retries + 1;
|
|
162
|
+
agent.session.append("llm/retry", {
|
|
163
|
+
retryId,
|
|
164
|
+
turn,
|
|
165
|
+
step,
|
|
166
|
+
provider: provider2,
|
|
167
|
+
mode: "normal",
|
|
168
|
+
policyKey: POLICY,
|
|
169
|
+
retry,
|
|
170
|
+
maxRetries: MAX_RETRIES,
|
|
171
|
+
delayMs: 0,
|
|
172
|
+
failure
|
|
173
|
+
});
|
|
174
|
+
if (!active || signal.aborted || connectionToken() !== token) return;
|
|
175
|
+
agent.session.append("llm/retry-started", { retryId, turn, step, retry });
|
|
176
|
+
return { kind: "retry" };
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// src/host.ts
|
|
181
|
+
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
182
|
+
|
|
183
|
+
// src/credentials.ts
|
|
184
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
185
|
+
import { credentialKey } from "@deepseek-ai/dsh-credentials";
|
|
186
|
+
|
|
187
|
+
// src/contracts.ts
|
|
188
|
+
var DEFAULT_ENDPOINT = "https://gemus.ai/api/mcp";
|
|
189
|
+
|
|
190
|
+
// ../codex-backfill-core/src/mcpIdentity.ts
|
|
191
|
+
function getMcpKeyIssuer(token) {
|
|
192
|
+
const tagged = /^mak_(cn|global)_[0-9a-f]{48}$/.exec(token);
|
|
193
|
+
if (tagged?.[0] === token) return tagged[1];
|
|
194
|
+
return token.length === 52 && /^mak_[0-9a-f]{48}$/.test(token) ? "global" : null;
|
|
195
|
+
}
|
|
196
|
+
function resolveMcpEndpoint(endpoint) {
|
|
197
|
+
const syntax = /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\]|(?:www\.)?gemus\.(?:ai|cn))(?::[0-9]+)?\/api\/mcp$/i.exec(endpoint);
|
|
198
|
+
if (!syntax || syntax[0] !== endpoint) return null;
|
|
199
|
+
try {
|
|
200
|
+
const url = new URL(endpoint);
|
|
201
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== "/api/mcp") return null;
|
|
202
|
+
const host = url.hostname;
|
|
203
|
+
if (host === "localhost" || host === "127.0.0.1" || host === "[::1]") {
|
|
204
|
+
return { endpoint: url.href, issuer: "global" };
|
|
205
|
+
}
|
|
206
|
+
if (url.protocol !== "https:" || url.port) return null;
|
|
207
|
+
if (host === "gemus.cn" || host === "www.gemus.cn") return { endpoint: url.href, issuer: "cn" };
|
|
208
|
+
if (host === "gemus.ai" || host === "www.gemus.ai") return { endpoint: url.href, issuer: "global" };
|
|
209
|
+
return null;
|
|
210
|
+
} catch {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/identity.ts
|
|
216
|
+
function validateEndpoint(input) {
|
|
217
|
+
const target = resolveMcpEndpoint(input.trim());
|
|
218
|
+
if (!target) throw new Error("invalid-endpoint");
|
|
219
|
+
return target.endpoint;
|
|
220
|
+
}
|
|
221
|
+
function validateConnectionTarget(config) {
|
|
222
|
+
const target = resolveMcpEndpoint(config.endpoint.trim());
|
|
223
|
+
if (!target) throw new Error("invalid-endpoint");
|
|
224
|
+
const issuer = getMcpKeyIssuer(config.apiKey ?? "");
|
|
225
|
+
if (!issuer) throw new Error("auth-required");
|
|
226
|
+
if (issuer !== target.issuer) throw new Error("identity-mismatch");
|
|
227
|
+
return target;
|
|
228
|
+
}
|
|
229
|
+
function isObject(value) {
|
|
230
|
+
return typeof value === "object" && value !== null;
|
|
231
|
+
}
|
|
232
|
+
function validateIdentity(config, identity2) {
|
|
233
|
+
const target = validateConnectionTarget(config);
|
|
234
|
+
const actual = resolveMcpEndpoint(identity2.endpoint);
|
|
235
|
+
const official = (endpoint) => ["gemus.ai", "www.gemus.ai", "gemus.cn", "www.gemus.cn"].includes(new URL(endpoint).hostname);
|
|
236
|
+
if (identity2.instance !== target.issuer || !actual || actual.issuer !== target.issuer || actual.endpoint !== target.endpoint && !(official(actual.endpoint) && official(target.endpoint)) || config.expectedUserId && config.expectedUserId !== identity2.user.id) throw new Error("identity-mismatch");
|
|
237
|
+
}
|
|
238
|
+
async function identify(config, signal) {
|
|
239
|
+
const target = validateConnectionTarget(config);
|
|
240
|
+
try {
|
|
241
|
+
const response = await fetch(`${target.endpoint}/connection`, {
|
|
242
|
+
headers: { Authorization: `Bearer ${config.apiKey}` },
|
|
243
|
+
redirect: "error",
|
|
244
|
+
cache: "no-store",
|
|
245
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(1e4)])
|
|
246
|
+
});
|
|
247
|
+
if (response.status === 401) throw new Error("auth-required");
|
|
248
|
+
if (response.status === 404 || response.status === 405) throw new Error("server-incompatible");
|
|
249
|
+
if (!response.ok) throw new Error("network-error");
|
|
250
|
+
const body = await response.json();
|
|
251
|
+
if (!isObject(body) || !isObject(body.user) || typeof body.user.id !== "string" || !body.user.id || typeof body.user.displayName !== "string" || body.user.username !== null && typeof body.user.username !== "string" || body.personalWorkspace !== null && (!isObject(body.personalWorkspace) || typeof body.personalWorkspace.id !== "string" || typeof body.personalWorkspace.name !== "string")) throw new Error("server-incompatible");
|
|
252
|
+
const legacy = /^mak_[0-9a-f]{48}$/.test(config.apiKey ?? "") && ["gemus.ai", "www.gemus.ai"].includes(new URL(target.endpoint).hostname) && body.instance === void 0 && body.endpoint === void 0;
|
|
253
|
+
const identity2 = {
|
|
254
|
+
instance: legacy ? "global" : body.instance,
|
|
255
|
+
endpoint: legacy ? target.endpoint : typeof body.endpoint === "string" ? body.endpoint : "",
|
|
256
|
+
user: { id: body.user.id, username: body.user.username, displayName: body.user.displayName },
|
|
257
|
+
personalWorkspace: body.personalWorkspace === null ? null : { id: body.personalWorkspace.id, name: body.personalWorkspace.name }
|
|
258
|
+
};
|
|
259
|
+
validateIdentity(config, identity2);
|
|
260
|
+
return identity2;
|
|
261
|
+
} catch (error) {
|
|
262
|
+
throw new Error(error instanceof Error && ["auth-required", "server-incompatible", "identity-mismatch"].includes(error.message) ? error.message : "network-error");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// src/credentials.ts
|
|
267
|
+
var CONNECTION_KEY = credentialKey("gemus-dsh-plugin", "connection");
|
|
268
|
+
function decode(record, environment) {
|
|
269
|
+
if (!record) return {
|
|
270
|
+
revision: "none",
|
|
271
|
+
enabled: Boolean(environment.GEMUS_KEY),
|
|
272
|
+
apiKey: environment.GEMUS_KEY,
|
|
273
|
+
endpoint: environment.GEMUS_URL || DEFAULT_ENDPOINT,
|
|
274
|
+
source: environment.GEMUS_KEY ? "environment" : "none"
|
|
275
|
+
};
|
|
276
|
+
if (record.kind !== "api-key") throw new Error("storage-error");
|
|
277
|
+
return {
|
|
278
|
+
revision: record.env?.GEMUS_CONNECTION_REVISION ?? "none",
|
|
279
|
+
expectedUserId: record.env?.GEMUS_EXPECTED_USER_ID,
|
|
280
|
+
enabled: record.env?.GEMUS_CONNECTION_ENABLED === "true",
|
|
281
|
+
apiKey: record.key,
|
|
282
|
+
endpoint: record.env?.GEMUS_ENDPOINT || DEFAULT_ENDPOINT,
|
|
283
|
+
source: "saved"
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
function createCredentials(store, environment = process.env) {
|
|
287
|
+
return {
|
|
288
|
+
read: async () => {
|
|
289
|
+
try {
|
|
290
|
+
return decode(await store.readRecord(CONNECTION_KEY), environment);
|
|
291
|
+
} catch {
|
|
292
|
+
throw new Error("storage-error");
|
|
293
|
+
}
|
|
294
|
+
},
|
|
295
|
+
write: async (next, expectedRevision) => {
|
|
296
|
+
const result = await store.modifyRecord(CONNECTION_KEY, async (current) => {
|
|
297
|
+
if (decode(current, environment).revision !== expectedRevision) throw new Error("conflict");
|
|
298
|
+
return { kind: "api-key", ...next.enabled ? { key: next.apiKey } : {}, env: {
|
|
299
|
+
...next.expectedUserId ? { GEMUS_EXPECTED_USER_ID: next.expectedUserId } : {},
|
|
300
|
+
GEMUS_ENDPOINT: validateEndpoint(next.endpoint),
|
|
301
|
+
GEMUS_CONNECTION_REVISION: randomUUID2(),
|
|
302
|
+
GEMUS_CONNECTION_ENABLED: String(next.enabled)
|
|
303
|
+
} };
|
|
304
|
+
});
|
|
305
|
+
return decode(result, environment);
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/connection.ts
|
|
311
|
+
var ConnectionOwner = class {
|
|
312
|
+
constructor(deps) {
|
|
313
|
+
this.deps = deps;
|
|
314
|
+
}
|
|
315
|
+
queue = Promise.resolve();
|
|
316
|
+
generation = 0;
|
|
317
|
+
abort = new AbortController();
|
|
318
|
+
disposed = false;
|
|
319
|
+
lastWrite;
|
|
320
|
+
child;
|
|
321
|
+
view = {
|
|
322
|
+
status: "disconnected",
|
|
323
|
+
revision: "none",
|
|
324
|
+
operationId: 0,
|
|
325
|
+
endpoint: DEFAULT_ENDPOINT,
|
|
326
|
+
source: "none",
|
|
327
|
+
saved: false,
|
|
328
|
+
identity: null,
|
|
329
|
+
toolCount: 0,
|
|
330
|
+
checkedAt: null,
|
|
331
|
+
identityCheckedAt: null,
|
|
332
|
+
toolsCheckedAt: null,
|
|
333
|
+
error: null
|
|
334
|
+
};
|
|
335
|
+
getStatus() {
|
|
336
|
+
return structuredClone(this.view);
|
|
337
|
+
}
|
|
338
|
+
/** A foreground connection change immediately fences an in-flight recovery. */
|
|
339
|
+
get recoveryToken() {
|
|
340
|
+
return !this.disposed && this.child && this.view.status === "verified" && this.view.operationId === this.generation ? this.generation : void 0;
|
|
341
|
+
}
|
|
342
|
+
start(intent) {
|
|
343
|
+
return this.run(async (check) => {
|
|
344
|
+
if (!intent) return this.restore(check);
|
|
345
|
+
await this.clearChild();
|
|
346
|
+
check();
|
|
347
|
+
const current = await this.deps.read();
|
|
348
|
+
check();
|
|
349
|
+
this.acceptRecord(current);
|
|
350
|
+
this.view.identity = null;
|
|
351
|
+
this.view.identityCheckedAt = null;
|
|
352
|
+
if (intent.version !== "connect-v1" || !intent.apiKey || !intent.endpoint || !intent.expectedUserId || intent.expectedUserId !== intent.expectedUserId.trim() || intent.expectedUserId.length > 128 || /[\x00-\x1f\x7f]/.test(intent.expectedUserId)) throw new Error("identity-mismatch");
|
|
353
|
+
await this.connectRecord(current, { apiKey: intent.apiKey, endpoint: intent.endpoint, expectedUserId: intent.expectedUserId, expectedRevision: current.revision }, check);
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/** Observe after the active operation, so own notifications are cheap and foreign updates cannot be lost. */
|
|
357
|
+
recordUpdated() {
|
|
358
|
+
if (this.disposed) return;
|
|
359
|
+
this.queue = this.queue.then(async () => {
|
|
360
|
+
if (this.disposed) return;
|
|
361
|
+
const generation = this.generation;
|
|
362
|
+
const current = await this.deps.read();
|
|
363
|
+
if (generation !== this.generation) {
|
|
364
|
+
this.recordUpdated();
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (!this.disposed && (current.revision !== this.view.revision || current.enabled && !this.child)) void this.start();
|
|
368
|
+
}).catch(() => {
|
|
369
|
+
if (!this.disposed) {
|
|
370
|
+
this.view.status = "storage-error";
|
|
371
|
+
this.view.error = "storage-error";
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
connect(input) {
|
|
376
|
+
return this.run(async (check) => {
|
|
377
|
+
const current = await this.deps.read();
|
|
378
|
+
check();
|
|
379
|
+
await this.connectRecord(current, input, check);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
async connectRecord(current, input, check) {
|
|
383
|
+
this.expectRevision(current, input.expectedRevision);
|
|
384
|
+
const endpoint = validateEndpoint(input.endpoint);
|
|
385
|
+
const candidate2 = { ...current, endpoint, apiKey: input.apiKey.trim(), enabled: true, expectedUserId: input.expectedUserId?.trim() || void 0 };
|
|
386
|
+
validateConnectionTarget(candidate2);
|
|
387
|
+
const identity2 = await this.deps.identify(candidate2, this.abort.signal);
|
|
388
|
+
check();
|
|
389
|
+
validateIdentity(candidate2, identity2);
|
|
390
|
+
candidate2.expectedUserId = identity2.user.id;
|
|
391
|
+
candidate2.endpoint = identity2.endpoint;
|
|
392
|
+
const identityCheckedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
393
|
+
const saved = await this.write(candidate2, input.expectedRevision);
|
|
394
|
+
check();
|
|
395
|
+
await this.clearChild();
|
|
396
|
+
check();
|
|
397
|
+
this.acceptRecord(saved);
|
|
398
|
+
this.view.identity = identity2;
|
|
399
|
+
this.view.identityCheckedAt = identityCheckedAt;
|
|
400
|
+
if (!await this.replace(saved, check)) return;
|
|
401
|
+
this.finishCheck();
|
|
402
|
+
}
|
|
403
|
+
recheck(_expectedRevision) {
|
|
404
|
+
return this.run(async (check) => this.restore(check));
|
|
405
|
+
}
|
|
406
|
+
disconnect(expectedRevision) {
|
|
407
|
+
return this.run(async (check) => {
|
|
408
|
+
const current = await this.deps.read();
|
|
409
|
+
check();
|
|
410
|
+
const expected = this.lastWrite?.superseded && this.lastWrite.before === expectedRevision && this.lastWrite.after === current.revision ? current.revision : expectedRevision;
|
|
411
|
+
this.expectRevision(current, expected);
|
|
412
|
+
const disabled = { ...current, enabled: false };
|
|
413
|
+
delete disabled.apiKey;
|
|
414
|
+
const saved = await this.write(disabled, expected);
|
|
415
|
+
check();
|
|
416
|
+
this.acceptRecord(saved);
|
|
417
|
+
await this.clearChild();
|
|
418
|
+
check();
|
|
419
|
+
this.view = { ...this.view, status: "disconnected", identity: null, toolCount: 0, error: null, checkedAt: null, identityCheckedAt: null, toolsCheckedAt: null };
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
async dispose() {
|
|
423
|
+
this.disposed = true;
|
|
424
|
+
this.generation++;
|
|
425
|
+
this.abort.abort();
|
|
426
|
+
await this.queue;
|
|
427
|
+
await this.clearChild();
|
|
428
|
+
}
|
|
429
|
+
async restore(check) {
|
|
430
|
+
await this.clearChild();
|
|
431
|
+
check();
|
|
432
|
+
const current = await this.deps.read();
|
|
433
|
+
check();
|
|
434
|
+
this.acceptRecord(current);
|
|
435
|
+
this.view.identity = null;
|
|
436
|
+
this.view.identityCheckedAt = null;
|
|
437
|
+
if (!current.enabled || !current.apiKey) {
|
|
438
|
+
await this.clearChild();
|
|
439
|
+
check();
|
|
440
|
+
this.view.status = "disconnected";
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
validateConnectionTarget(current);
|
|
444
|
+
const identity2 = await this.deps.identify(current, this.abort.signal);
|
|
445
|
+
check();
|
|
446
|
+
validateIdentity(current, identity2);
|
|
447
|
+
this.view.identity = identity2;
|
|
448
|
+
this.view.identityCheckedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
449
|
+
if (!await this.replace(current, check)) return;
|
|
450
|
+
this.finishCheck();
|
|
451
|
+
}
|
|
452
|
+
async replace(config, check) {
|
|
453
|
+
await this.clearChild();
|
|
454
|
+
check();
|
|
455
|
+
const latest = await this.deps.read();
|
|
456
|
+
check();
|
|
457
|
+
this.expectRevision(latest, config.revision);
|
|
458
|
+
if (!latest.enabled || !latest.apiKey) throw new Error("cancelled");
|
|
459
|
+
this.child = this.deps.mount(latest);
|
|
460
|
+
await this.child.ready;
|
|
461
|
+
check();
|
|
462
|
+
const afterReady = await this.deps.read();
|
|
463
|
+
check();
|
|
464
|
+
if (afterReady.revision !== latest.revision) {
|
|
465
|
+
await this.clearChild();
|
|
466
|
+
check();
|
|
467
|
+
this.acceptRecord(afterReady);
|
|
468
|
+
this.view.identity = null;
|
|
469
|
+
this.view.identityCheckedAt = null;
|
|
470
|
+
this.view.status = afterReady.enabled ? "needs-check" : "disconnected";
|
|
471
|
+
this.view.error = afterReady.enabled ? "conflict" : null;
|
|
472
|
+
return false;
|
|
473
|
+
}
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
finishCheck() {
|
|
477
|
+
const names = this.child?.tools() ?? [];
|
|
478
|
+
this.view.toolCount = names.length;
|
|
479
|
+
this.view.toolsCheckedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
480
|
+
this.view.checkedAt = this.view.toolsCheckedAt;
|
|
481
|
+
this.view.status = this.view.identity && names.includes("mcp__gemus__workflow_list") ? "verified" : "needs-check";
|
|
482
|
+
this.view.error = null;
|
|
483
|
+
}
|
|
484
|
+
acceptRecord(record) {
|
|
485
|
+
this.view = { ...this.view, revision: record.revision, endpoint: record.endpoint, source: record.source, saved: record.source === "saved" && record.enabled && Boolean(record.apiKey), toolCount: 0, checkedAt: null, toolsCheckedAt: null };
|
|
486
|
+
}
|
|
487
|
+
expectRevision(record, expected) {
|
|
488
|
+
if (record.revision !== expected) throw new Error("conflict");
|
|
489
|
+
}
|
|
490
|
+
async write(next, expected) {
|
|
491
|
+
const generation = this.generation;
|
|
492
|
+
try {
|
|
493
|
+
const saved = await this.deps.write(next, expected);
|
|
494
|
+
this.lastWrite = { before: expected, after: saved.revision, superseded: generation !== this.generation };
|
|
495
|
+
return saved;
|
|
496
|
+
} catch (error) {
|
|
497
|
+
throw new Error(error instanceof Error && error.message === "conflict" ? "conflict" : "storage-error");
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
async clearChild() {
|
|
501
|
+
const child = this.child;
|
|
502
|
+
if (child) {
|
|
503
|
+
await child.dispose();
|
|
504
|
+
this.child = void 0;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
run(operation) {
|
|
508
|
+
const generation = ++this.generation;
|
|
509
|
+
this.abort.abort();
|
|
510
|
+
this.abort = new AbortController();
|
|
511
|
+
const check = () => {
|
|
512
|
+
if (this.disposed || generation !== this.generation) throw new Error("cancelled");
|
|
513
|
+
};
|
|
514
|
+
const task = this.queue.then(async () => {
|
|
515
|
+
const previousStatus = this.view.status === "checking" ? "needs-check" : this.view.status;
|
|
516
|
+
try {
|
|
517
|
+
check();
|
|
518
|
+
this.view = { ...this.view, status: "checking", operationId: generation, error: null };
|
|
519
|
+
await operation(check);
|
|
520
|
+
} catch (error) {
|
|
521
|
+
if (this.disposed || generation !== this.generation) return this.getStatus();
|
|
522
|
+
const safe = error instanceof Error && ["auth-required", "network-error", "server-incompatible", "storage-error", "conflict", "invalid-endpoint", "host-incompatible", "cancelled", "identity-mismatch"].includes(error.message) ? error.message : "host-incompatible";
|
|
523
|
+
this.view.error = safe;
|
|
524
|
+
this.view.status = this.child && this.view.identity ? previousStatus : safe === "auth-required" || safe === "network-error" || safe === "server-incompatible" || safe === "storage-error" ? safe : "needs-check";
|
|
525
|
+
}
|
|
526
|
+
return this.getStatus();
|
|
527
|
+
});
|
|
528
|
+
this.queue = task.catch(() => void 0);
|
|
529
|
+
return task;
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
|
|
533
|
+
// src/mcp.ts
|
|
534
|
+
import * as mcpClient from "@deepseek-ai/dsh-mcp-client";
|
|
535
|
+
function mountOfficialClient(ctx, config) {
|
|
536
|
+
const child = ctx.plugin(mcpClient, {
|
|
537
|
+
transport: "streamable-http",
|
|
538
|
+
serverName: "gemus",
|
|
539
|
+
url: config.endpoint,
|
|
540
|
+
headers: { Authorization: `Bearer ${config.apiKey}` },
|
|
541
|
+
toolCallTimeoutMs: 6e5,
|
|
542
|
+
failOnStartupError: false
|
|
543
|
+
});
|
|
544
|
+
return {
|
|
545
|
+
ready: child,
|
|
546
|
+
tools: () => ctx.tools.schemas().map((tool) => tool.name).filter((name) => name.startsWith("mcp__gemus__")),
|
|
547
|
+
dispose: () => child.dispose()
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// src/remote.ts
|
|
552
|
+
import { z as z2 } from "zod";
|
|
553
|
+
import { createTypertRemoteInfo } from "@deepseek-ai/dsh-typert-protocol/remote-info";
|
|
554
|
+
var identity = z2.object({ instance: z2.enum(["cn", "global"]), endpoint: z2.string(), user: z2.object({ id: z2.string(), username: z2.string().nullable(), displayName: z2.string() }), personalWorkspace: z2.object({ id: z2.string(), name: z2.string() }).nullable() });
|
|
555
|
+
var view = z2.object({
|
|
556
|
+
status: z2.enum(["disconnected", "checking", "verified", "needs-check", "auth-required", "network-error", "server-incompatible", "host-incompatible", "storage-error"]),
|
|
557
|
+
revision: z2.string(),
|
|
558
|
+
operationId: z2.number(),
|
|
559
|
+
endpoint: z2.string(),
|
|
560
|
+
source: z2.enum(["none", "saved", "environment"]),
|
|
561
|
+
saved: z2.boolean(),
|
|
562
|
+
identity: identity.nullable(),
|
|
563
|
+
toolCount: z2.number(),
|
|
564
|
+
checkedAt: z2.string().nullable(),
|
|
565
|
+
identityCheckedAt: z2.string().nullable(),
|
|
566
|
+
toolsCheckedAt: z2.string().nullable(),
|
|
567
|
+
error: z2.enum(["auth-required", "network-error", "server-incompatible", "storage-error", "conflict", "invalid-endpoint", "host-incompatible", "cancelled", "identity-mismatch"]).nullable()
|
|
568
|
+
});
|
|
569
|
+
function codec(schema, name) {
|
|
570
|
+
return { mode: "strict", typeSymbol: `gemus/${name}`, create: () => schema };
|
|
571
|
+
}
|
|
572
|
+
function method(name, schema) {
|
|
573
|
+
return {
|
|
574
|
+
service: "gemusConnection",
|
|
575
|
+
invocation: { kind: "direct" },
|
|
576
|
+
parameters: name && schema ? [{ name, source: "json", codec: codec(schema, name), strictCodec: codec(schema, name) }] : [],
|
|
577
|
+
result: codec(view, "ConnectionView")
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
var GEMUS_REMOTE = createTypertRemoteInfo({ package: "gemus-dsh-plugin", methods: {
|
|
581
|
+
"gemusConnection/getStatus": method(),
|
|
582
|
+
"gemusConnection/connect": method("input", z2.strictObject({ apiKey: z2.string().max(512), endpoint: z2.string().max(2048), expectedRevision: z2.string().max(128), expectedUserId: z2.string().max(128).optional() })),
|
|
583
|
+
"gemusConnection/recheck": method("expectedRevision", z2.string().max(128)),
|
|
584
|
+
"gemusConnection/disconnect": method("expectedRevision", z2.string().max(128))
|
|
585
|
+
} }, z2);
|
|
586
|
+
|
|
587
|
+
// src/host.ts
|
|
588
|
+
var _disconnect_dec, _recheck_dec, _connect_dec, _getStatus_dec, _a, _init;
|
|
589
|
+
var GemusConnection = class extends (_a = TypertRemoteService, _getStatus_dec = [Remote], _connect_dec = [Remote], _recheck_dec = [Remote], _disconnect_dec = [Remote], _a) {
|
|
590
|
+
constructor(ctx) {
|
|
591
|
+
super(ctx, "gemusConnection");
|
|
592
|
+
__runInitializers(_init, 5, this);
|
|
593
|
+
__publicField(this, "owner");
|
|
594
|
+
__publicField(this, "initialized");
|
|
595
|
+
this.owner = new ConnectionOwner({ ...createCredentials(ctx.credentials), identify, mount: (config) => mountOfficialClient(ctx, config) });
|
|
596
|
+
ctx.inject(["skills"], installGemusSkill);
|
|
597
|
+
ctx.inject(["sessionProjections", "tools"], (recoveryCtx) => installGemusRecovery(recoveryCtx, () => this.owner.recoveryToken));
|
|
598
|
+
ctx.effect(() => ctx.typert.remotes.register(GEMUS_REMOTE));
|
|
599
|
+
ctx.on("credentials/record-updated", (key) => {
|
|
600
|
+
if (key === CONNECTION_KEY) this.owner.recordUpdated();
|
|
601
|
+
});
|
|
602
|
+
const environment = process.env;
|
|
603
|
+
const intent = environment.GEMUS_SETUP_INTENT !== void 0 || environment.GEMUS_SETUP_EXPECTED_USER_ID !== void 0 ? { version: environment.GEMUS_SETUP_INTENT, apiKey: environment.GEMUS_KEY, endpoint: environment.GEMUS_URL, expectedUserId: environment.GEMUS_SETUP_EXPECTED_USER_ID } : void 0;
|
|
604
|
+
delete environment.GEMUS_SETUP_INTENT;
|
|
605
|
+
delete environment.GEMUS_SETUP_EXPECTED_USER_ID;
|
|
606
|
+
this.initialized = this.owner.start(intent);
|
|
607
|
+
ctx.effect(() => () => this.owner.dispose());
|
|
608
|
+
}
|
|
609
|
+
assertOwner() {
|
|
610
|
+
if (this.ctx.invocation?.peer.principal.kind !== "owner") throw new Error("Gemus configuration requires the Host owner");
|
|
611
|
+
}
|
|
612
|
+
async getStatus() {
|
|
613
|
+
this.assertOwner();
|
|
614
|
+
await this.initialized;
|
|
615
|
+
return this.owner.getStatus();
|
|
616
|
+
}
|
|
617
|
+
async connect(input) {
|
|
618
|
+
this.assertOwner();
|
|
619
|
+
return this.owner.connect(input);
|
|
620
|
+
}
|
|
621
|
+
async recheck(expectedRevision) {
|
|
622
|
+
this.assertOwner();
|
|
623
|
+
return this.owner.recheck(expectedRevision);
|
|
624
|
+
}
|
|
625
|
+
async disconnect(expectedRevision) {
|
|
626
|
+
this.assertOwner();
|
|
627
|
+
return this.owner.disconnect(expectedRevision);
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
_init = __decoratorStart(_a);
|
|
631
|
+
__decorateElement(_init, 1, "getStatus", _getStatus_dec, GemusConnection);
|
|
632
|
+
__decorateElement(_init, 1, "connect", _connect_dec, GemusConnection);
|
|
633
|
+
__decorateElement(_init, 1, "recheck", _recheck_dec, GemusConnection);
|
|
634
|
+
__decorateElement(_init, 1, "disconnect", _disconnect_dec, GemusConnection);
|
|
635
|
+
__decoratorMetadata(_init, GemusConnection);
|
|
636
|
+
__publicField(GemusConnection, "inject", ["credentials", "tools", "typert", "systemPrompt"]);
|
|
637
|
+
export {
|
|
638
|
+
GemusConnection as default
|
|
639
|
+
};
|
package/icon.png
ADDED
|
Binary file
|