dsh-taskbridge 0.0.0-stage → 1.3.2
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 +763 -0
- package/LICENSE +21 -0
- package/README.md +622 -3
- package/bin/dsh-delegate-codex-agent.js +115 -0
- package/bin/dsh-delegate-control.d.ts +90 -0
- package/bin/dsh-delegate-control.js +450 -0
- package/bin/dsh-delegate-mcp.d.ts +121 -0
- package/bin/dsh-delegate-mcp.js +273 -0
- package/codex/dsh-taskbridge.toml +247 -0
- package/cordis.patch.yml +6 -0
- package/docs/INTRODUCTION.md +15 -0
- package/docs/INTRODUCTION.zh.md +34 -0
- package/docs/auth-contract.md +138 -0
- package/docs/claude-code.md +31 -0
- package/docs/codex-integration.md +937 -0
- package/docs/contracts-stage-b.md +443 -0
- package/docs/conversation-placement.md +304 -0
- package/docs/plugin-market.md +30 -0
- package/docs/redaction-contract.md +127 -0
- package/docs/runtime-compatibility.md +223 -0
- package/docs/silent-wait.md +191 -0
- package/docs/taskbridge-upgrade.md +28 -0
- package/docs/taskdispatch-upgrade.md +25 -0
- package/docs/worker-permissions.md +347 -0
- package/docs/workspace-contract.md +538 -0
- package/icon.svg +1 -0
- package/lib/client.d.ts +118 -0
- package/lib/client.js +3232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +138 -4
- package/src/auth/fence.js +361 -0
- package/src/auth/grants.js +789 -0
- package/src/client/api.js +2322 -0
- package/src/client/index.jsx +2333 -0
- package/src/client/styles.js +251 -0
- package/src/codex/installer.js +3299 -0
- package/src/codex/seam.js +429 -0
- package/src/codex/toml.js +784 -0
- package/src/config/defaults.js +164 -0
- package/src/config/redact.js +184 -0
- package/src/config/settings.js +629 -0
- package/src/config/store.js +186 -0
- package/src/config/validate.js +763 -0
- package/src/credentials/seam.js +202 -0
- package/src/http/execution-plane.js +456 -0
- package/src/http/respond.js +175 -0
- package/src/http/user-plane.js +1122 -0
- package/src/index.d.ts +332 -0
- package/src/index.js +657 -0
- package/src/jobs/activity.js +1008 -0
- package/src/jobs/engine.js +3614 -0
- package/src/jobs/history.js +1467 -0
- package/src/jobs/title.js +17 -0
- package/src/mcp/server.js +1821 -0
- package/src/mcp/wait.js +536 -0
- package/src/model/connectivity.js +371 -0
- package/src/model/discovery.js +582 -0
- package/src/model/native-catalog.js +68 -0
- package/src/model/openai-adapter.js +671 -0
- package/src/model/probe.js +264 -0
- package/src/model/providers.js +756 -0
- package/src/model/routing.js +321 -0
- package/src/review/preset.js +868 -0
- package/src/review/prompts.js +126 -0
- package/src/review/reviewer.js +933 -0
- package/src/runtime/agent-runner.js +1740 -0
- package/src/runtime/endpoint-discovery.js +118 -0
- package/src/runtime/permissions.js +1429 -0
- package/src/runtime/sandbox.js +358 -0
- package/src/runtime/session-placement.js +1121 -0
- package/src/workspace/audit.js +775 -0
- package/src/workspace/locks.js +167 -0
- package/src/workspace/preflight.js +424 -0
- package/src/workspace/worktrees.js +613 -0
|
@@ -0,0 +1,2322 @@
|
|
|
1
|
+
// dsh-delegate settings UI — user-plane client, shared vocabulary and store.
|
|
2
|
+
//
|
|
3
|
+
// This module is deliberately framework-free: it is the part of the browser
|
|
4
|
+
// half that can be reasoned about (and tested) without React. It owns
|
|
5
|
+
//
|
|
6
|
+
// 1. the transport to the authenticated user plane (`/api/dsh-delegate/*`),
|
|
7
|
+
// 2. the operator-facing vocabulary (Chinese labels, state/effort names),
|
|
8
|
+
// 3. the editable settings draft and its non-secret projections, and
|
|
9
|
+
// 4. a small observable store the React page subscribes to.
|
|
10
|
+
//
|
|
11
|
+
// Two rules shape everything here, and both are security properties rather than
|
|
12
|
+
// style preferences:
|
|
13
|
+
//
|
|
14
|
+
// * A credential value and a connection token are *never* part of persisted or
|
|
15
|
+
// rendered state. The credential value travels from a controlled input
|
|
16
|
+
// straight into one request and is dropped. The connection token lives in
|
|
17
|
+
// this in-memory store only until the operator dismisses it; it is not
|
|
18
|
+
// written to a URL, storage, log or clipboard unless the operator explicitly
|
|
19
|
+
// presses copy.
|
|
20
|
+
// * The user plane's authentication is the native browser-session carrier, not
|
|
21
|
+
// something this client adds. Requests therefore carry no `Authorization`
|
|
22
|
+
// header; they rely on `credentials: 'same-origin'`.
|
|
23
|
+
//
|
|
24
|
+
// Nothing here decides whether a provider/model/effort combination is legal:
|
|
25
|
+
// the settings service on the host is the authority, and its refusals are shown
|
|
26
|
+
// verbatim. The few checks below exist to keep the operator from submitting an
|
|
27
|
+
// obviously broken form, and every one of them is re-checked server-side.
|
|
28
|
+
|
|
29
|
+
/** User-plane prefix. Mirrors `USER_PLANE_PREFIX` in `src/http/user-plane.js`. */
|
|
30
|
+
export const USER_PLANE_PREFIX = '/api/dsh-delegate';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Exact user-plane routes the page drives.
|
|
34
|
+
*
|
|
35
|
+
* Every route here is served by `src/http/user-plane.js`; the list is the client
|
|
36
|
+
* half of one contract, not a wish list. The page still degrades explicitly when
|
|
37
|
+
* a host predates a route (a 404 becomes "the host does not serve this yet"
|
|
38
|
+
* rather than a fabricated success), because an older plugin version can be
|
|
39
|
+
* mounted against a newer page.
|
|
40
|
+
*/
|
|
41
|
+
export const ROUTES = Object.freeze({
|
|
42
|
+
status: `${USER_PLANE_PREFIX}/status`,
|
|
43
|
+
delegation: `${USER_PLANE_PREFIX}/delegation`,
|
|
44
|
+
nativeProviders: `${USER_PLANE_PREFIX}/native-providers`,
|
|
45
|
+
settings: `${USER_PLANE_PREFIX}/settings`,
|
|
46
|
+
// One narrow, authenticated operator route for the two silence thresholds. It is
|
|
47
|
+
// a browser-plane write only: the MCP surface never gains a settings write.
|
|
48
|
+
monitoring: `${USER_PLANE_PREFIX}/monitoring`,
|
|
49
|
+
catalog: `${USER_PLANE_PREFIX}/catalog`,
|
|
50
|
+
connections: `${USER_PLANE_PREFIX}/connections`,
|
|
51
|
+
connectionsRevoke: `${USER_PLANE_PREFIX}/connections/revoke`,
|
|
52
|
+
grants: `${USER_PLANE_PREFIX}/grants`,
|
|
53
|
+
grantsRevoke: `${USER_PLANE_PREFIX}/grants/revoke`,
|
|
54
|
+
revokeAll: `${USER_PLANE_PREFIX}/authorization/revoke-all`,
|
|
55
|
+
tasks: `${USER_PLANE_PREFIX}/tasks`,
|
|
56
|
+
tasksGet: `${USER_PLANE_PREFIX}/tasks/get`,
|
|
57
|
+
tasksCancel: `${USER_PLANE_PREFIX}/tasks/cancel`,
|
|
58
|
+
models: `${USER_PLANE_PREFIX}/models`,
|
|
59
|
+
credentialsStatus: `${USER_PLANE_PREFIX}/credentials/status`,
|
|
60
|
+
credentialsSet: `${USER_PLANE_PREFIX}/credentials/set`,
|
|
61
|
+
credentialsUnset: `${USER_PLANE_PREFIX}/credentials/unset`,
|
|
62
|
+
connectivity: `${USER_PLANE_PREFIX}/connectivity`,
|
|
63
|
+
// One path, two methods: `GET` diagnoses, `POST` performs one explicit action.
|
|
64
|
+
codex: `${USER_PLANE_PREFIX}/codex`,
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/** A refusal or transport failure carrying the contract's stable code. */
|
|
68
|
+
export class ApiError extends Error {
|
|
69
|
+
/**
|
|
70
|
+
* @param {string} code - stable machine code (`SETTINGS_INVALID`, `HTTP_404`, ...).
|
|
71
|
+
* @param {string} message - short English diagnostic from the host.
|
|
72
|
+
* @param {object} [options] - `status`, `details`.
|
|
73
|
+
*/
|
|
74
|
+
constructor(code, message, options = {}) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.name = 'ApiError';
|
|
77
|
+
this.code = code;
|
|
78
|
+
this.status = options.status ?? 0;
|
|
79
|
+
this.details = options.details ?? {};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Create the user-plane transport.
|
|
85
|
+
*
|
|
86
|
+
* URLs are document-relative (`api/dsh-delegate/...`, not `/api/...`) for the
|
|
87
|
+
* same reason the native change routes are: the web app may be mounted under a
|
|
88
|
+
* sub-path, and an absolute path would escape the mount.
|
|
89
|
+
* @param {object} [options] - `fetchImpl` for tests, `base` for a fixed prefix.
|
|
90
|
+
* @returns {object} one method per user-plane route.
|
|
91
|
+
*/
|
|
92
|
+
export function createApi(options = {}) {
|
|
93
|
+
const fetchImpl = options.fetchImpl ?? ((url, init) => globalThis.fetch(url, init));
|
|
94
|
+
const base = typeof options.base === 'string' ? options.base : '';
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Send one request and unwrap the contract envelope.
|
|
98
|
+
* @param {string} method - `GET` or `POST`.
|
|
99
|
+
* @param {string} route - route from {@link ROUTES}.
|
|
100
|
+
* @param {object} [body] - JSON body; omitted for a body-less `GET`.
|
|
101
|
+
* @returns {Promise<object>} the parsed `ok:true` body.
|
|
102
|
+
* @throws {ApiError} on transport failure, non-2xx, or `ok:false`.
|
|
103
|
+
*/
|
|
104
|
+
async function request(method, route, body) {
|
|
105
|
+
const url = `${base}${route.replace(/^\//, '')}`;
|
|
106
|
+
let response;
|
|
107
|
+
try {
|
|
108
|
+
response = await fetchImpl(url, {
|
|
109
|
+
method,
|
|
110
|
+
// The browser session cookie is the user plane's credential. Sending it
|
|
111
|
+
// cross-origin is impossible here, and the native carrier fences Host and
|
|
112
|
+
// Origin before any handler runs.
|
|
113
|
+
credentials: 'same-origin',
|
|
114
|
+
cache: 'no-store',
|
|
115
|
+
headers: body === undefined
|
|
116
|
+
? { accept: 'application/json' }
|
|
117
|
+
: { accept: 'application/json', 'content-type': 'application/json' },
|
|
118
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
119
|
+
});
|
|
120
|
+
} catch (error) {
|
|
121
|
+
throw new ApiError('USER_PLANE_UNREACHABLE', 'the delegation settings service could not be reached', {
|
|
122
|
+
details: { detail: String(error?.message ?? error).slice(0, 200) },
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
let text = '';
|
|
127
|
+
try {
|
|
128
|
+
text = typeof response.text === 'function' ? await response.text() : '';
|
|
129
|
+
} catch {
|
|
130
|
+
text = '';
|
|
131
|
+
}
|
|
132
|
+
let parsed = null;
|
|
133
|
+
try {
|
|
134
|
+
parsed = text === '' ? null : JSON.parse(text);
|
|
135
|
+
} catch {
|
|
136
|
+
parsed = null;
|
|
137
|
+
}
|
|
138
|
+
if (!response.ok || parsed === null || parsed.ok !== true) {
|
|
139
|
+
const failure = parsed !== null && typeof parsed === 'object' ? parsed.error : undefined;
|
|
140
|
+
const code = typeof failure?.code === 'string'
|
|
141
|
+
? failure.code
|
|
142
|
+
: (response.ok ? 'USER_PLANE_MALFORMED' : `HTTP_${response.status}`);
|
|
143
|
+
const message = typeof failure?.message === 'string'
|
|
144
|
+
? failure.message
|
|
145
|
+
: `the settings service answered HTTP ${response.status}`;
|
|
146
|
+
throw new ApiError(code, message, {
|
|
147
|
+
status: response.status,
|
|
148
|
+
details: typeof failure?.details === 'object' && failure.details !== null ? failure.details : {},
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
return parsed;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
/** @returns {Promise<object>} plugin/delegation posture. */
|
|
156
|
+
async getStatus() {
|
|
157
|
+
return await request('GET', ROUTES.status);
|
|
158
|
+
},
|
|
159
|
+
/** @param {boolean} enabled - master dispatch switch. */
|
|
160
|
+
async setDelegationEnabled(enabled) {
|
|
161
|
+
return await request('POST', ROUTES.delegation, { enabled });
|
|
162
|
+
},
|
|
163
|
+
/** @returns {Promise<object>} DSH's already registered providers and models. */
|
|
164
|
+
async getNativeProviders() {
|
|
165
|
+
return await request('GET', ROUTES.nativeProviders);
|
|
166
|
+
},
|
|
167
|
+
/** @returns {Promise<object>} `{ settings, secrets }`. */
|
|
168
|
+
async getSettings() {
|
|
169
|
+
return await request('GET', ROUTES.settings);
|
|
170
|
+
},
|
|
171
|
+
/**
|
|
172
|
+
* Replace the whole settings document.
|
|
173
|
+
* @param {object} settings - full document (never carrying a secret).
|
|
174
|
+
* @returns {Promise<object>} `{ settings }`.
|
|
175
|
+
*/
|
|
176
|
+
async putSettings(settings) {
|
|
177
|
+
return await request('POST', ROUTES.settings, { settings });
|
|
178
|
+
},
|
|
179
|
+
/**
|
|
180
|
+
* Replace only the two silence thresholds.
|
|
181
|
+
*
|
|
182
|
+
* This is the narrow route the advanced monitoring controls use, so a operator
|
|
183
|
+
* adjusting a timer cannot accidentally rewrite a provider list. The host
|
|
184
|
+
* re-validates: whole seconds, each in range, and the attention threshold strictly
|
|
185
|
+
* greater than the self-check one.
|
|
186
|
+
* @param {{ selfCheckSeconds: number, attentionSeconds: number }} monitoring - thresholds in seconds.
|
|
187
|
+
* @returns {Promise<object>} `{ monitoring, settings }`.
|
|
188
|
+
*/
|
|
189
|
+
async putMonitoring(monitoring) {
|
|
190
|
+
return await request('POST', ROUTES.monitoring, { monitoring });
|
|
191
|
+
},
|
|
192
|
+
/**
|
|
193
|
+
* Resolve provider models/efforts plus the composed effective config.
|
|
194
|
+
* @param {object} [body] - `{ projectPath }`.
|
|
195
|
+
* @returns {Promise<object>} `{ catalog, effective }`.
|
|
196
|
+
*/
|
|
197
|
+
async getCatalog(body = {}) {
|
|
198
|
+
return await request('POST', ROUTES.catalog, body);
|
|
199
|
+
},
|
|
200
|
+
/** @returns {Promise<object>} `{ connections }`. */
|
|
201
|
+
async listConnections() {
|
|
202
|
+
return await request('GET', ROUTES.connections);
|
|
203
|
+
},
|
|
204
|
+
/**
|
|
205
|
+
* Issue a connection. The response is the only place a token is ever visible.
|
|
206
|
+
* @param {string} label - display label.
|
|
207
|
+
* @returns {Promise<object>} `{ connection, token, tokenReturnedOnce }`.
|
|
208
|
+
*/
|
|
209
|
+
async issueConnection(label) {
|
|
210
|
+
return await request('POST', ROUTES.connections, { label });
|
|
211
|
+
},
|
|
212
|
+
/**
|
|
213
|
+
* Revoke one connection and its grants.
|
|
214
|
+
* @param {string} connectionId - server-issued identity.
|
|
215
|
+
* @returns {Promise<object>} `{ grantsRevoked }`.
|
|
216
|
+
*/
|
|
217
|
+
async revokeConnection(connectionId) {
|
|
218
|
+
return await request('POST', ROUTES.connectionsRevoke, { connectionId });
|
|
219
|
+
},
|
|
220
|
+
/**
|
|
221
|
+
* List one connection's grants.
|
|
222
|
+
* @param {string} connectionId - server-issued identity.
|
|
223
|
+
* @returns {Promise<object>} `{ grants }`.
|
|
224
|
+
*/
|
|
225
|
+
async listGrants(connectionId) {
|
|
226
|
+
return await request('GET', `${ROUTES.grants}?${new URLSearchParams({ connectionId })}`);
|
|
227
|
+
},
|
|
228
|
+
/**
|
|
229
|
+
* Issue one grant.
|
|
230
|
+
* @param {object} body - `{ connectionId, kind, workspacePath, ttlSeconds? }`.
|
|
231
|
+
* @returns {Promise<object>} `{ grant }`.
|
|
232
|
+
*/
|
|
233
|
+
async issueGrant(body) {
|
|
234
|
+
return await request('POST', ROUTES.grants, body);
|
|
235
|
+
},
|
|
236
|
+
/**
|
|
237
|
+
* Revoke one grant.
|
|
238
|
+
* @param {string} grantId - grant identity.
|
|
239
|
+
* @returns {Promise<object>} `{ grant }`.
|
|
240
|
+
*/
|
|
241
|
+
async revokeGrant(grantId) {
|
|
242
|
+
return await request('POST', ROUTES.grantsRevoke, { grantId });
|
|
243
|
+
},
|
|
244
|
+
/** @returns {Promise<object>} `{ grantsRevoked }`. */
|
|
245
|
+
async revokeAll() {
|
|
246
|
+
return await request('POST', ROUTES.revokeAll, {});
|
|
247
|
+
},
|
|
248
|
+
/**
|
|
249
|
+
* List tasks (never carrying a prompt).
|
|
250
|
+
* @param {string | null} [connectionId] - optional filter.
|
|
251
|
+
* @returns {Promise<object>} `{ tasks }`.
|
|
252
|
+
*/
|
|
253
|
+
async listTasks(connectionId = null) {
|
|
254
|
+
const suffix = connectionId === null ? '' : `?${new URLSearchParams({ connectionId })}`;
|
|
255
|
+
return await request('GET', `${ROUTES.tasks}${suffix}`);
|
|
256
|
+
},
|
|
257
|
+
/**
|
|
258
|
+
* Read one task including its prompt.
|
|
259
|
+
* @param {string} taskId - task identity.
|
|
260
|
+
* @returns {Promise<object>} `{ task }`.
|
|
261
|
+
*/
|
|
262
|
+
async getTask(taskId) {
|
|
263
|
+
return await request('POST', ROUTES.tasksGet, { taskId });
|
|
264
|
+
},
|
|
265
|
+
/**
|
|
266
|
+
* Cancel a task as the operator.
|
|
267
|
+
* @param {string} taskId - task identity.
|
|
268
|
+
* @returns {Promise<object>} `{ task }`.
|
|
269
|
+
*/
|
|
270
|
+
async cancelTask(taskId) {
|
|
271
|
+
return await request('POST', ROUTES.tasksCancel, { taskId });
|
|
272
|
+
},
|
|
273
|
+
/**
|
|
274
|
+
* Discover one provider's model list from its own API (remote discovery).
|
|
275
|
+
*
|
|
276
|
+
* The host performs one authenticated request to the provider's configured
|
|
277
|
+
* base URL with *that profile's* credential reference, so this answers "what
|
|
278
|
+
* does the endpoint say it serves" — not "what can the harness resolve" (that
|
|
279
|
+
* is `getCatalog`). A failed discovery still answers `ok: true` with
|
|
280
|
+
* `models: []` and a `discovery` diagnosis, so a caller must read
|
|
281
|
+
* `body.discovery?.failed` and `body.error` rather than treating an empty list
|
|
282
|
+
* as "the provider has no models".
|
|
283
|
+
* @param {string} providerId - configured provider id.
|
|
284
|
+
* @returns {Promise<object>} `{ models: [{ id, efforts }], source, discovery, error }`.
|
|
285
|
+
*/
|
|
286
|
+
async fetchModels(providerId) {
|
|
287
|
+
return await request('POST', ROUTES.models, { providerId });
|
|
288
|
+
},
|
|
289
|
+
/**
|
|
290
|
+
* Read whether a provider's credential is configured (target route).
|
|
291
|
+
* @param {string} providerId - configured provider id.
|
|
292
|
+
* @returns {Promise<object>} `{ credential: { configured, source?, writable? } }`.
|
|
293
|
+
*/
|
|
294
|
+
async credentialStatus(providerId) {
|
|
295
|
+
return await request('POST', ROUTES.credentialsStatus, { providerId });
|
|
296
|
+
},
|
|
297
|
+
/**
|
|
298
|
+
* Store a credential value through the separate authenticated seam.
|
|
299
|
+
* @param {string} providerId - configured provider id.
|
|
300
|
+
* @param {string} value - the literal value; never retained by the caller.
|
|
301
|
+
* @returns {Promise<object>} `{ credential }`.
|
|
302
|
+
*/
|
|
303
|
+
async setCredential(providerId, value) {
|
|
304
|
+
return await request('POST', ROUTES.credentialsSet, { providerId, value });
|
|
305
|
+
},
|
|
306
|
+
/**
|
|
307
|
+
* Remove a stored credential value.
|
|
308
|
+
* @param {string} providerId - configured provider id.
|
|
309
|
+
* @returns {Promise<object>} `{ credential }`.
|
|
310
|
+
*/
|
|
311
|
+
async unsetCredential(providerId) {
|
|
312
|
+
return await request('POST', ROUTES.credentialsUnset, { providerId });
|
|
313
|
+
},
|
|
314
|
+
/**
|
|
315
|
+
* Run the layered connectivity check.
|
|
316
|
+
* @param {object} body - `{ providerId, model?, reasoningEffort? }`.
|
|
317
|
+
* @returns {Promise<object>} `{ report }`.
|
|
318
|
+
*/
|
|
319
|
+
async checkConnectivity(body) {
|
|
320
|
+
return await request('POST', ROUTES.connectivity, body);
|
|
321
|
+
},
|
|
322
|
+
/**
|
|
323
|
+
* Diagnose the Codex integration. Read-only on the host.
|
|
324
|
+
* @returns {Promise<object>} `{ codex, switch }`.
|
|
325
|
+
*/
|
|
326
|
+
async getCodexStatus() {
|
|
327
|
+
return await request('GET', ROUTES.codex);
|
|
328
|
+
},
|
|
329
|
+
/**
|
|
330
|
+
* Perform one explicit Codex action.
|
|
331
|
+
*
|
|
332
|
+
* Only an operator click reaches this: there is no load-time or save-time
|
|
333
|
+
* caller, so visiting the page never writes into the Codex home.
|
|
334
|
+
* @param {'install'|'repair'|'remove'} action - the action to perform.
|
|
335
|
+
* @returns {Promise<object>} `{ action, changed, refused, codex, switch }`.
|
|
336
|
+
*/
|
|
337
|
+
async runCodexAction(action) {
|
|
338
|
+
return await request('POST', ROUTES.codex, { action });
|
|
339
|
+
},
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ---------------------------------------------------------------------------
|
|
344
|
+
// Vocabulary
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Reasoning-effort ids this build understands, weakest first.
|
|
349
|
+
*
|
|
350
|
+
* This is a *display* mirror of `KNOWN_EFFORTS` in `src/config/defaults.js`; the
|
|
351
|
+
* authority for what a particular model supports is the catalog the host serves,
|
|
352
|
+
* and the authority for what a document may contain is the host's validator.
|
|
353
|
+
*/
|
|
354
|
+
export const KNOWN_EFFORTS = Object.freeze(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
|
|
355
|
+
|
|
356
|
+
/** Chinese labels for effort ids. */
|
|
357
|
+
export const EFFORT_LABELS = Object.freeze({
|
|
358
|
+
off: '关闭推理',
|
|
359
|
+
minimal: '最少',
|
|
360
|
+
low: '低',
|
|
361
|
+
medium: '中',
|
|
362
|
+
high: '高',
|
|
363
|
+
xhigh: '很高',
|
|
364
|
+
max: '最高',
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
/** Sentinel used by a `<select>` for "no explicit effort". */
|
|
368
|
+
export const EFFORT_UNSET = '';
|
|
369
|
+
|
|
370
|
+
/** Workspace isolation modes, strongest first. */
|
|
371
|
+
export const ISOLATION_MODES = Object.freeze(['worktree', 'shared']);
|
|
372
|
+
|
|
373
|
+
/** Chinese labels for isolation modes. */
|
|
374
|
+
export const ISOLATION_LABELS = Object.freeze({
|
|
375
|
+
worktree: '独立工作树(临时 git worktree,不碰当前检出)',
|
|
376
|
+
shared: '共享工作区(直接修改所选目录)',
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* The retired directory-level conversation modes, kept for display compatibility.
|
|
381
|
+
*
|
|
382
|
+
* They are no longer a choice. A new submission always starts a new DSH
|
|
383
|
+
* conversation, and a follow-up continues only the task thread named by
|
|
384
|
+
* `continueFromTaskId`. The values remain here so a page can still render a task
|
|
385
|
+
* record or a stored document written by an earlier build, and so the migration
|
|
386
|
+
* note can name what went away.
|
|
387
|
+
*/
|
|
388
|
+
export const CONVERSATION_MODES = Object.freeze(['new', 'reuse']);
|
|
389
|
+
|
|
390
|
+
/** Chinese labels for the retired conversation modes. */
|
|
391
|
+
export const CONVERSATION_LABELS = Object.freeze({
|
|
392
|
+
new: '每个任务新开对话',
|
|
393
|
+
reuse: '复用同一执行目录最近的对话(已移除)',
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
/** Chinese explanation of the conversation policy that replaced the mode setting. */
|
|
397
|
+
export const CONVERSATION_POLICY_LABEL = '每次提交默认新开对话;只有带上 continueFromTaskId 的跟进任务才续接同一条对话';
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* The conversation block a draft/request should carry.
|
|
401
|
+
*
|
|
402
|
+
* The value is inert: it is preserved so saving a page never rewrites an operator's
|
|
403
|
+
* stored document into a state it did not choose, and it never influences what a
|
|
404
|
+
* run does. A stored `reuse` is kept verbatim and still means nothing on dispatch.
|
|
405
|
+
* @param {object} [draft] - editable document.
|
|
406
|
+
* @returns {{ mode: string }} conversation block.
|
|
407
|
+
*/
|
|
408
|
+
export function conversationOf(draft) {
|
|
409
|
+
const requested = draft?.conversation?.mode;
|
|
410
|
+
return { mode: CONVERSATION_MODES.includes(requested) ? requested : CONVERSATION_MODES[0] };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Chinese label for one conversation mode.
|
|
415
|
+
* @param {string} mode - mode id.
|
|
416
|
+
* @returns {string} label, falling back to the raw id.
|
|
417
|
+
*/
|
|
418
|
+
export function conversationModeLabel(mode) {
|
|
419
|
+
return CONVERSATION_LABELS[mode] ?? String(mode ?? '未设置');
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* The monitoring block a draft carries, normalized to whole seconds.
|
|
424
|
+
*
|
|
425
|
+
* This is a *display/normalization* helper, not the validator: an out-of-range or
|
|
426
|
+
* inconsistent pair is passed through so the operator sees what they typed and the
|
|
427
|
+
* precheck can explain it. Only a missing block, a non-object, or a non-finite value
|
|
428
|
+
* falls back to the documented default — an older stored document (no `monitoring`
|
|
429
|
+
* key) therefore opens at 300/600 s, i.e. 5/10 minutes.
|
|
430
|
+
* @param {object | null} source - served document, draft, or raw block.
|
|
431
|
+
* @returns {{ selfCheckSeconds: number, attentionSeconds: number }} normalized block.
|
|
432
|
+
*/
|
|
433
|
+
export function monitoringOf(source) {
|
|
434
|
+
const block = source?.monitoring;
|
|
435
|
+
if (block === null || typeof block !== 'object' || Array.isArray(block)) return { ...MONITORING_DEFAULTS };
|
|
436
|
+
const whole = (value, fallback) => (Number.isFinite(value) ? Math.trunc(value) : fallback);
|
|
437
|
+
return {
|
|
438
|
+
selfCheckSeconds: whole(block.selfCheckSeconds, MONITORING_DEFAULTS.selfCheckSeconds),
|
|
439
|
+
attentionSeconds: whole(block.attentionSeconds, MONITORING_DEFAULTS.attentionSeconds),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Convert whole seconds to minutes, for display only.
|
|
445
|
+
*
|
|
446
|
+
* A threshold that is not a whole number of minutes is returned as a fraction so the
|
|
447
|
+
* field shows the stored value instead of a rounded one that would not round-trip.
|
|
448
|
+
* @param {number} seconds - stored threshold.
|
|
449
|
+
* @returns {number} minutes.
|
|
450
|
+
*/
|
|
451
|
+
export function secondsToMinutes(seconds) {
|
|
452
|
+
if (!Number.isFinite(seconds)) return 0;
|
|
453
|
+
return seconds / 60;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Convert a minutes input back to whole seconds.
|
|
458
|
+
*
|
|
459
|
+
* The stored unit is seconds: a fractional minute is converted and rounded, because
|
|
460
|
+
* the host accepts integers only. A non-numeric input yields `NaN`, which the local
|
|
461
|
+
* precheck reports rather than silently becoming a zero.
|
|
462
|
+
* @param {unknown} minutes - operator input.
|
|
463
|
+
* @returns {number} whole seconds, or NaN.
|
|
464
|
+
*/
|
|
465
|
+
export function minutesToSeconds(minutes) {
|
|
466
|
+
// An empty or blank field is NOT zero: `Number('')` is `0`, which would silently
|
|
467
|
+
// persist a threshold of 0 s instead of letting the precheck report the blank.
|
|
468
|
+
if (typeof minutes === 'string' && minutes.trim() === '') return Number.NaN;
|
|
469
|
+
if (minutes === null || minutes === undefined) return Number.NaN;
|
|
470
|
+
const value = typeof minutes === 'number' ? minutes : Number(String(minutes).trim());
|
|
471
|
+
if (!Number.isFinite(value)) return Number.NaN;
|
|
472
|
+
return Math.round(value * 60);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Grant scopes. */
|
|
476
|
+
export const GRANT_KINDS = Object.freeze(['task', 'session']);
|
|
477
|
+
|
|
478
|
+
/** Chinese labels for grant scopes. */
|
|
479
|
+
export const GRANT_KIND_LABELS = Object.freeze({
|
|
480
|
+
task: '单次任务(用掉即失效)',
|
|
481
|
+
session: '本连接会话(限时、可撤销)',
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Chinese labels for the per-call permission states a task can report.
|
|
486
|
+
*
|
|
487
|
+
* The wording is deliberately about ONE call: a decision here never grants a
|
|
488
|
+
* standing permission, and the panel must not read like an approval workflow.
|
|
489
|
+
*/
|
|
490
|
+
export const PERMISSION_STATE_LABELS = Object.freeze({
|
|
491
|
+
pending: '等待本机指挥官决定(仅这一次调用)',
|
|
492
|
+
decided: '已决定',
|
|
493
|
+
expired: '已超时(未决定即为拒绝)',
|
|
494
|
+
cancelled: '已撤回',
|
|
495
|
+
unavailable: '无法建立请求身份(已按拒绝处理)',
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
/** Chinese labels for the two decisions the commander may take. */
|
|
499
|
+
export const PERMISSION_DECISION_LABELS = Object.freeze({
|
|
500
|
+
'allow-once': '仅本次允许',
|
|
501
|
+
reject: '拒绝',
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
/** Chinese labels for the four closed native approval outcomes. */
|
|
505
|
+
export const PERMISSION_OUTCOME_LABELS = Object.freeze({
|
|
506
|
+
'allowed-once': '仅本次允许',
|
|
507
|
+
rejected: '已拒绝',
|
|
508
|
+
cancelled: '已撤回',
|
|
509
|
+
unavailable: '无可用审批通道',
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
/** Chinese label for a task phase, falling back to the raw phase. */
|
|
513
|
+
export const TASK_PHASE_LABELS = Object.freeze({
|
|
514
|
+
created: '已创建',
|
|
515
|
+
workspace: '解析工作区',
|
|
516
|
+
authorization: '校验授权',
|
|
517
|
+
settings: '读取设置',
|
|
518
|
+
providers: '确认提供方',
|
|
519
|
+
worktree: '准备工作树',
|
|
520
|
+
audit: '记录基线',
|
|
521
|
+
'before-create': '即将创建执行器',
|
|
522
|
+
execute: '执行中',
|
|
523
|
+
'awaiting-permission': '等待本次调用授权决定',
|
|
524
|
+
review: '附加审查中',
|
|
525
|
+
'awaiting-host-review': '等待宿主审查',
|
|
526
|
+
failed: '已失败',
|
|
527
|
+
cancelled: '已取消',
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
/** Task states, exactly as the engine reports them. */
|
|
531
|
+
export const TASK_STATES = Object.freeze(['pending', 'running', 'awaiting-host-review', 'failed', 'cancelled']);
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Chinese labels for task states.
|
|
535
|
+
*
|
|
536
|
+
* `awaiting-host-review` is deliberately *not* "已完成" or "已接受": execution
|
|
537
|
+
* finished, and acceptance belongs to the host.
|
|
538
|
+
*/
|
|
539
|
+
export const TASK_STATE_LABELS = Object.freeze({
|
|
540
|
+
pending: '排队中',
|
|
541
|
+
running: '执行中',
|
|
542
|
+
'awaiting-host-review': '等待宿主审查',
|
|
543
|
+
failed: '执行失败',
|
|
544
|
+
cancelled: '已取消',
|
|
545
|
+
// A task persisted by a restart is stored with this state. It is NOT "still
|
|
546
|
+
// running": the execution does not resume, so the panel says exactly that. The
|
|
547
|
+
// engine never sets it for a live run — the same word is also the reason an
|
|
548
|
+
// OBSERVATION was interrupted, and that is a different thing (see
|
|
549
|
+
// `WAIT_REASON_LABELS.interrupted`).
|
|
550
|
+
interrupted: '已中断(进程重启后不会继续执行)',
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
/** Chinese labels for task review states. */
|
|
554
|
+
export const REVIEW_STATE_LABELS = Object.freeze({
|
|
555
|
+
disabled: '未启用附加审查',
|
|
556
|
+
not_run: '未运行',
|
|
557
|
+
completed: '已完成',
|
|
558
|
+
failed: '审查失败(与任务成败无关)',
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
/** Chinese labels for review verdicts. */
|
|
562
|
+
export const REVIEW_VERDICT_LABELS = Object.freeze({
|
|
563
|
+
approve: '建议通过',
|
|
564
|
+
'changes-requested': '建议修改',
|
|
565
|
+
unknown: '未给出结论',
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
/** Chinese labels for the four connectivity layers. */
|
|
569
|
+
export const CONNECTIVITY_LAYERS = Object.freeze([
|
|
570
|
+
{ key: 'transport', label: '传输(地址可达)' },
|
|
571
|
+
{ key: 'authentication', label: '认证(凭据可用)' },
|
|
572
|
+
{ key: 'catalog', label: '模型目录' },
|
|
573
|
+
{ key: 'modelResponse', label: '模型实际响应' },
|
|
574
|
+
]);
|
|
575
|
+
|
|
576
|
+
/** Bounds mirrored from the host validator, used for input attributes only. */
|
|
577
|
+
export const LIMITS = Object.freeze({
|
|
578
|
+
timeoutSecondsMin: 30,
|
|
579
|
+
timeoutSecondsMax: 7200,
|
|
580
|
+
maxParallelismMin: 1,
|
|
581
|
+
maxParallelismMax: 8,
|
|
582
|
+
taskGrantTtlSecondsMin: 30,
|
|
583
|
+
taskGrantTtlSecondsMax: 3600,
|
|
584
|
+
sessionGrantTtlSecondsMin: 60,
|
|
585
|
+
sessionGrantTtlSecondsMax: 43200,
|
|
586
|
+
providers: 32,
|
|
587
|
+
// Silence thresholds. Mirrors `LIMITS` in `src/config/defaults.js`; the host is
|
|
588
|
+
// still the authority, these only drive input attributes and the local precheck.
|
|
589
|
+
selfCheckSecondsMin: 30,
|
|
590
|
+
selfCheckSecondsMax: 3600,
|
|
591
|
+
attentionSecondsMin: 31,
|
|
592
|
+
attentionSecondsMax: 7200,
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Default silence thresholds, mirroring `MONITORING_DEFAULTS`.
|
|
597
|
+
*
|
|
598
|
+
* Stored as whole SECONDS (300 / 600). The panel presents them as minutes because
|
|
599
|
+
* that is how an operator thinks about them; a value that is not a whole number of
|
|
600
|
+
* minutes is still editable and is shown exactly.
|
|
601
|
+
*/
|
|
602
|
+
export const MONITORING_DEFAULTS = Object.freeze({
|
|
603
|
+
selfCheckSeconds: 300,
|
|
604
|
+
attentionSeconds: 600,
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
/** Chinese labels for the self-check verdicts the host publishes. */
|
|
608
|
+
export const SELF_CHECK_LABELS = Object.freeze({
|
|
609
|
+
'executor-alive-silent': '执行器健在,这段时间没有新输出',
|
|
610
|
+
'executor-not-started': '执行器尚未开始',
|
|
611
|
+
'idle-between-steps': '两步之间,执行器已停止输出',
|
|
612
|
+
'tool-running': '某个工具调用仍在运行',
|
|
613
|
+
'waiting-for-permission': '正在等待本次调用授权决定',
|
|
614
|
+
settled: '任务已经结束',
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
/** Chinese labels for the reasons a wait returns. */
|
|
618
|
+
export const WAIT_REASON_LABELS = Object.freeze({
|
|
619
|
+
heartbeat: '没有需要处理的事(内部心跳)',
|
|
620
|
+
attention: '长时间没有任何新进展,需要你判断',
|
|
621
|
+
permission: '有一次工具调用在等待授权决定',
|
|
622
|
+
ready: '执行已结束,等待宿主审查(不等于已接受)',
|
|
623
|
+
failed: '执行失败',
|
|
624
|
+
cancelled: '已取消',
|
|
625
|
+
// The reason describes the WAIT, and only a TERMINAL answer means the task record is
|
|
626
|
+
// itself interrupted. Both readings are named, because a serialised host reads this
|
|
627
|
+
// through `delegate_wait`'s answer: a live task stays live (`wait-limit`, below), a
|
|
628
|
+
// restart history does not resume.
|
|
629
|
+
interrupted: '这次等待被中断;任务是否仍在运行要看答案里的 terminal/state(任务记录本身中断才是重启历史,不会继续执行)',
|
|
630
|
+
'wait-limit': '本轮等待时间用完,任务仍在运行',
|
|
631
|
+
});
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Actions the Codex panel may send.
|
|
635
|
+
*
|
|
636
|
+
* `status` is deliberately absent: it is a `GET`, so a page that only renders the
|
|
637
|
+
* panel can never be mistaken for one that changes files.
|
|
638
|
+
*/
|
|
639
|
+
export const CODEX_ACTIONS = Object.freeze(['install', 'repair', 'remove']);
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* The three states the panel reports separately.
|
|
643
|
+
*
|
|
644
|
+
* They are independent on purpose: an agent can be installed while MCP is not
|
|
645
|
+
* configured, and both can be ready while the local-call switch is still off.
|
|
646
|
+
*/
|
|
647
|
+
export const CODEX_TARGETS = Object.freeze([
|
|
648
|
+
{ key: 'agent', label: 'Codex 子智能体文件' },
|
|
649
|
+
{ key: 'mcp', label: 'Codex MCP 条目' },
|
|
650
|
+
{ key: 'switch', label: 'DSH 本机调用开关' },
|
|
651
|
+
]);
|
|
652
|
+
|
|
653
|
+
/** Chinese labels for the managed-file states the host reports. */
|
|
654
|
+
export const CODEX_STATE_LABELS = Object.freeze({
|
|
655
|
+
'not-installed': '未安装',
|
|
656
|
+
installed: '已安装',
|
|
657
|
+
outdated: '旧版本,可更新',
|
|
658
|
+
modified: '不属于已知版本(插件不会改动)',
|
|
659
|
+
conflict: '存在冲突(插件不会改动)',
|
|
660
|
+
'not-configured': '未配置',
|
|
661
|
+
configured: '已配置',
|
|
662
|
+
unreadable: '无法读取(不会写入)',
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Read one target's status out of a served Codex document, in the panel's terms.
|
|
667
|
+
*
|
|
668
|
+
* Kept as a pure function so the UI and its tests agree on exactly one mapping,
|
|
669
|
+
* and so an older/newer host that omits a block yields "未知" instead of a crash.
|
|
670
|
+
* @param {object | null} codex - served `codex` document.
|
|
671
|
+
* @param {object | null} switchState - served `switch` block, when present.
|
|
672
|
+
* @param {'agent'|'mcp'|'switch'} target - which state to describe.
|
|
673
|
+
* @returns {{ key: string, label: string, state: string, tone: string, detail: string }} description.
|
|
674
|
+
*/
|
|
675
|
+
export function codexTargetView(codex, switchState, target) {
|
|
676
|
+
const label = CODEX_TARGETS.find((entry) => entry.key === target)?.label ?? target;
|
|
677
|
+
if (target === 'switch') {
|
|
678
|
+
const authorized = switchState?.authorized === true;
|
|
679
|
+
return {
|
|
680
|
+
key: 'switch',
|
|
681
|
+
label,
|
|
682
|
+
state: authorized ? 'on' : 'off',
|
|
683
|
+
tone: authorized ? 'on' : 'off',
|
|
684
|
+
detail: authorized
|
|
685
|
+
? '已开启:Codex 可以通过 MCP 提交任务。'
|
|
686
|
+
: '已关闭:Codex 可以查询状态,但新任务会被拒绝;本页不会替你打开它。',
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
const block = target === 'agent' ? codex?.agent : codex?.mcp;
|
|
690
|
+
if (block === null || block === undefined || typeof block !== 'object') {
|
|
691
|
+
return { key: target, label, state: 'unknown', tone: 'off', detail: '宿主尚未回报该状态。' };
|
|
692
|
+
}
|
|
693
|
+
const state = String(block.state ?? 'unknown');
|
|
694
|
+
const done = target === 'agent' ? block.installed === true : block.configured === true;
|
|
695
|
+
const detailParts = [];
|
|
696
|
+
if (typeof block.path === 'string' && block.path !== '') detailParts.push(block.path);
|
|
697
|
+
if (target === 'mcp' && typeof block.script === 'string' && block.script !== '') {
|
|
698
|
+
detailParts.push(`入口:${block.script}`);
|
|
699
|
+
}
|
|
700
|
+
// The executable Codex will launch. `node === null` means this host could not prove
|
|
701
|
+
// one — a desktop application executable is never used and a bare `node` is never
|
|
702
|
+
// written — so the row states the missing fact instead of showing a blank.
|
|
703
|
+
if (target === 'mcp') {
|
|
704
|
+
if (typeof block.node === 'string' && block.node !== '') detailParts.push(`Node:${block.node}`);
|
|
705
|
+
else if (block.nodeResolved === false) detailParts.push('Node:未确定(不会写入桌面应用自身的 exe)');
|
|
706
|
+
}
|
|
707
|
+
return {
|
|
708
|
+
key: target,
|
|
709
|
+
label,
|
|
710
|
+
state,
|
|
711
|
+
tone: done ? 'on' : (state === 'conflict' || state === 'unreadable' || state === 'modified') ? 'warn' : 'off',
|
|
712
|
+
detail: CODEX_STATE_LABELS[state] ?? state,
|
|
713
|
+
path: typeof block.path === 'string' ? block.path : '',
|
|
714
|
+
paths: detailParts,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* One-line summary of an action outcome, for the notice strip.
|
|
720
|
+
* @param {object | null} outcome - `{ action, changed, refused }` from the host.
|
|
721
|
+
* @returns {string} Chinese summary; empty when there was no action.
|
|
722
|
+
*/
|
|
723
|
+
export function describeCodexOutcome(outcome) {
|
|
724
|
+
if (outcome === null || outcome === undefined) return '';
|
|
725
|
+
const names = { agent: '子智能体文件', mcp: 'MCP 条目' };
|
|
726
|
+
const changed = Array.isArray(outcome.changed) ? outcome.changed.map((key) => names[key] ?? key) : [];
|
|
727
|
+
const refused = Array.isArray(outcome.refused) ? outcome.refused : [];
|
|
728
|
+
const parts = [];
|
|
729
|
+
if (changed.length > 0) parts.push(`已写入:${changed.join('、')}`);
|
|
730
|
+
if (refused.length > 0) parts.push(`未改动:${refused.map((entry) => names[entry?.target] ?? entry?.target ?? '未知').join('、')}`);
|
|
731
|
+
if (parts.length === 0) {
|
|
732
|
+
return outcome.action === 'remove' ? '没有需要移除的插件托管文件。' : '已是最新,没有需要写入的内容。';
|
|
733
|
+
}
|
|
734
|
+
return parts.join(';') + '。';
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Provider protocols this stage supports. */
|
|
738
|
+
export const SUPPORTED_PROTOCOLS = Object.freeze(['openai-chat']);
|
|
739
|
+
|
|
740
|
+
// ---------------------------------------------------------------------------
|
|
741
|
+
// Settings draft
|
|
742
|
+
// ---------------------------------------------------------------------------
|
|
743
|
+
|
|
744
|
+
/** @param {unknown} value @returns {object} deep JSON clone. */
|
|
745
|
+
export function clone(value) {
|
|
746
|
+
return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* The document shape a fresh install stores.
|
|
751
|
+
* @returns {object} default editable document.
|
|
752
|
+
*/
|
|
753
|
+
export function defaultDraft() {
|
|
754
|
+
return {
|
|
755
|
+
schemaVersion: 1,
|
|
756
|
+
delegationEnabled: false,
|
|
757
|
+
providers: [],
|
|
758
|
+
worker: {
|
|
759
|
+
providerId: null,
|
|
760
|
+
model: null,
|
|
761
|
+
reasoningEffort: null,
|
|
762
|
+
timeoutSeconds: 1800,
|
|
763
|
+
maxParallelism: 1,
|
|
764
|
+
isolation: 'worktree',
|
|
765
|
+
},
|
|
766
|
+
review: { enabled: false, providerId: null, model: null, reasoningEffort: null },
|
|
767
|
+
authorization: { taskGrantTtlSeconds: 900, sessionGrantTtlSeconds: 14400 },
|
|
768
|
+
// Silence thresholds. Present in a fresh draft so the controls render without a
|
|
769
|
+
// second load, and normalized from the served document below so an older host
|
|
770
|
+
// (or an older stored file) still opens with the documented defaults.
|
|
771
|
+
monitoring: { ...MONITORING_DEFAULTS },
|
|
772
|
+
projectOverrides: {},
|
|
773
|
+
presets: [],
|
|
774
|
+
// Deprecated and inert, kept only so a save round-trips the stored document
|
|
775
|
+
// instead of rewriting it. There is no conversation-mode control: a submission
|
|
776
|
+
// starts a new DSH conversation unless it names `continueFromTaskId`.
|
|
777
|
+
conversation: { mode: CONVERSATION_MODES[0] },
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* Turn a served public settings document into an editable draft.
|
|
783
|
+
*
|
|
784
|
+
* The `secrets` block the host adds is documentation, not settings, and is
|
|
785
|
+
* dropped here so it can never be echoed back in a write.
|
|
786
|
+
* @param {object | null} document - `settings` from `GET /settings`.
|
|
787
|
+
* @returns {object} editable document.
|
|
788
|
+
*/
|
|
789
|
+
export function draftFromSettings(document) {
|
|
790
|
+
const source = document ?? {};
|
|
791
|
+
const base = defaultDraft();
|
|
792
|
+
return {
|
|
793
|
+
schemaVersion: typeof source.schemaVersion === 'number' ? source.schemaVersion : base.schemaVersion,
|
|
794
|
+
delegationEnabled: source.delegationEnabled === true,
|
|
795
|
+
providers: Array.isArray(source.providers)
|
|
796
|
+
? source.providers.map((provider) => ({
|
|
797
|
+
id: String(provider.id ?? ''),
|
|
798
|
+
name: String(provider.name ?? ''),
|
|
799
|
+
source: provider.source ?? 'custom',
|
|
800
|
+
protocol: provider.source === 'native' ? null : String(provider.protocol ?? 'openai-chat'),
|
|
801
|
+
baseUrl: provider.source === 'native' ? null : String(provider.baseUrl ?? ''),
|
|
802
|
+
credentialRef: provider.source === 'native' ? null : (provider.credentialRef ?? null),
|
|
803
|
+
models: Array.isArray(provider.models)
|
|
804
|
+
? provider.models.map((model) => ({
|
|
805
|
+
id: String(model.id ?? ''),
|
|
806
|
+
efforts: Array.isArray(model.efforts) ? [...model.efforts] : [],
|
|
807
|
+
}))
|
|
808
|
+
: [],
|
|
809
|
+
}))
|
|
810
|
+
: [],
|
|
811
|
+
worker: { ...base.worker, ...(source.worker ?? {}) },
|
|
812
|
+
review: { ...base.review, ...(source.review ?? {}) },
|
|
813
|
+
authorization: { ...base.authorization, ...(source.authorization ?? {}) },
|
|
814
|
+
// A document written before this block existed has no `monitoring` key at all,
|
|
815
|
+
// and a host that predates it never serves one. Both open with the documented
|
|
816
|
+
// defaults instead of a blank control, and the values are coerced to whole
|
|
817
|
+
// seconds because that is the only shape the host accepts.
|
|
818
|
+
monitoring: monitoringOf(source),
|
|
819
|
+
projectOverrides: clone(source.projectOverrides ?? {}),
|
|
820
|
+
presets: Array.isArray(source.presets)
|
|
821
|
+
? source.presets.map((preset) => ({
|
|
822
|
+
id: String(preset.id ?? ''),
|
|
823
|
+
name: String(preset.name ?? preset.id ?? ''),
|
|
824
|
+
worker: preset.worker === null || preset.worker === undefined ? null : { ...preset.worker },
|
|
825
|
+
review: preset.review === null || preset.review === undefined ? null : { ...preset.review },
|
|
826
|
+
}))
|
|
827
|
+
: [],
|
|
828
|
+
// Read back through the same resolver the save path uses, so a document written
|
|
829
|
+
// before this field existed opens with the default and an inert stored `reuse`
|
|
830
|
+
// is preserved verbatim rather than silently rewritten.
|
|
831
|
+
conversation: conversationOf(source),
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* Project a draft onto the exact document `POST /settings` accepts.
|
|
837
|
+
* @param {object} draft - editable document.
|
|
838
|
+
* @returns {object} write body value (no `secrets`, no UI-only fields).
|
|
839
|
+
*/
|
|
840
|
+
export function documentFromDraft(draft) {
|
|
841
|
+
const source = draft ?? defaultDraft();
|
|
842
|
+
return {
|
|
843
|
+
schemaVersion: source.schemaVersion ?? 1,
|
|
844
|
+
delegationEnabled: source.delegationEnabled === true,
|
|
845
|
+
providers: (source.providers ?? []).map((provider) => {
|
|
846
|
+
const common = {
|
|
847
|
+
id: provider.id,
|
|
848
|
+
name: provider.name,
|
|
849
|
+
source: provider.source ?? 'custom',
|
|
850
|
+
models: (provider.models ?? []).map((model) => ({ id: model.id, efforts: [...(model.efforts ?? [])] })),
|
|
851
|
+
};
|
|
852
|
+
if (common.source === 'native') return common;
|
|
853
|
+
return {
|
|
854
|
+
...common,
|
|
855
|
+
protocol: provider.protocol,
|
|
856
|
+
baseUrl: provider.baseUrl,
|
|
857
|
+
credentialRef: provider.credentialRef === '' ? null : (provider.credentialRef ?? null),
|
|
858
|
+
};
|
|
859
|
+
}),
|
|
860
|
+
worker: { ...source.worker },
|
|
861
|
+
review: { ...source.review },
|
|
862
|
+
authorization: { ...source.authorization },
|
|
863
|
+
// Sent on every save, normalized to whole seconds: the host refuses anything
|
|
864
|
+
// else, and a document that omitted the block would store the defaults.
|
|
865
|
+
monitoring: monitoringOf(source),
|
|
866
|
+
projectOverrides: clone(source.projectOverrides ?? {}),
|
|
867
|
+
presets: (source.presets ?? []).map((preset) => ({
|
|
868
|
+
id: preset.id,
|
|
869
|
+
name: preset.name,
|
|
870
|
+
...(preset.worker === null ? {} : { worker: { ...preset.worker } }),
|
|
871
|
+
...(preset.review === null ? {} : { review: { ...preset.review } }),
|
|
872
|
+
})),
|
|
873
|
+
// Sent on every save only so the round-trip is faithful. It is inert: the host
|
|
874
|
+
// validates it as a retired value and no run consults it.
|
|
875
|
+
conversation: conversationOf(source),
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/**
|
|
880
|
+
* Nonsecret export text: exactly the public document, formatted for reading.
|
|
881
|
+
*
|
|
882
|
+
* There is no credential value anywhere in a settings document, so an export is
|
|
883
|
+
* safe by construction; the label says so to stop anyone assuming otherwise.
|
|
884
|
+
* @param {object} draft - editable document.
|
|
885
|
+
* @returns {string} JSON text with a trailing newline.
|
|
886
|
+
*/
|
|
887
|
+
export function exportDocument(draft) {
|
|
888
|
+
return `${JSON.stringify(documentFromDraft(draft), null, 2)}\n`;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/**
|
|
892
|
+
* Compose the effective execution snapshot for display.
|
|
893
|
+
*
|
|
894
|
+
* This mirrors `resolveEffectiveConfig` closely enough to show the operator what
|
|
895
|
+
* a save will produce. It is a *preview*: the host composes the snapshot it
|
|
896
|
+
* actually runs with, `catalog.effective` shows that, and job details show the
|
|
897
|
+
* immutable snapshot a running job took.
|
|
898
|
+
* @param {object} draft - editable document.
|
|
899
|
+
* @param {string | null} [projectPath] - optional project layer.
|
|
900
|
+
* @returns {{ worker: object, review: object, applied: string[] }} preview.
|
|
901
|
+
*/
|
|
902
|
+
export function previewEffective(draft, projectPath = null) {
|
|
903
|
+
const applied = [];
|
|
904
|
+
let worker = { ...(draft?.worker ?? {}) };
|
|
905
|
+
let review = { ...(draft?.review ?? {}) };
|
|
906
|
+
const overrides = draft?.projectOverrides ?? {};
|
|
907
|
+
if (typeof projectPath === 'string' && projectPath.trim() !== '') {
|
|
908
|
+
const wanted = projectPath.trim().replace(/[\\/]+$/, '');
|
|
909
|
+
const key = Object.keys(overrides).find((candidate) => (
|
|
910
|
+
candidate === wanted || candidate.toLowerCase() === wanted.toLowerCase()
|
|
911
|
+
));
|
|
912
|
+
if (key !== undefined) {
|
|
913
|
+
const block = overrides[key] ?? {};
|
|
914
|
+
if (block.worker !== undefined && block.worker !== null) {
|
|
915
|
+
worker = { ...worker, ...block.worker };
|
|
916
|
+
applied.push('项目覆盖:执行设置');
|
|
917
|
+
}
|
|
918
|
+
if (block.review !== undefined && block.review !== null) {
|
|
919
|
+
review = { ...review, ...block.review };
|
|
920
|
+
applied.push('项目覆盖:附加审查');
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
if (review.enabled !== true) review = { enabled: false, providerId: null, model: null, reasoningEffort: null };
|
|
925
|
+
return {
|
|
926
|
+
worker: { ...worker, providerRoute: worker.providerId ?? null },
|
|
927
|
+
review: { ...review, providerRoute: review.providerId ?? null },
|
|
928
|
+
// Global-only, like the host's own snapshot: no project or per-job layer can
|
|
929
|
+
// retime a task, so the preview reports the same pair the task would freeze.
|
|
930
|
+
monitoring: monitoringOf(draft),
|
|
931
|
+
applied,
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* Reusable presets and project overrides live inside the same settings document,
|
|
937
|
+
* so the export above already carries them.
|
|
938
|
+
|
|
939
|
+
* @param {object} draft - editable document.
|
|
940
|
+
* @returns {string[]} duplicate provider ids.
|
|
941
|
+
*/
|
|
942
|
+
export function duplicateProviderIds(draft) {
|
|
943
|
+
const seen = new Set();
|
|
944
|
+
const duplicates = new Set();
|
|
945
|
+
for (const provider of draft?.providers ?? []) {
|
|
946
|
+
if (seen.has(provider.id)) duplicates.add(provider.id);
|
|
947
|
+
seen.add(provider.id);
|
|
948
|
+
}
|
|
949
|
+
return [...duplicates];
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Pre-flight checks for the write button.
|
|
954
|
+
*
|
|
955
|
+
* These are *operator convenience*: they catch a blank field or a numeric field
|
|
956
|
+
* that is not a number before a round trip. They are not the authority — the
|
|
957
|
+
* host re-validates everything and its refusal is what the page reports.
|
|
958
|
+
* @param {object} draft - editable document.
|
|
959
|
+
* @returns {string[]} Chinese problem descriptions; empty when plausible.
|
|
960
|
+
*/
|
|
961
|
+
export function precheckDraft(draft) {
|
|
962
|
+
const problems = [];
|
|
963
|
+
const providers = draft?.providers ?? [];
|
|
964
|
+
const ids = new Set();
|
|
965
|
+
for (const provider of providers) {
|
|
966
|
+
if (!/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(String(provider.id ?? ''))) {
|
|
967
|
+
problems.push(`提供方标识「${provider.id || '(空)'}」需为 3–40 位小写字母、数字或连字符`);
|
|
968
|
+
}
|
|
969
|
+
if (ids.has(provider.id)) problems.push(`提供方标识「${provider.id}」重复`);
|
|
970
|
+
ids.add(provider.id);
|
|
971
|
+
if (!String(provider.name ?? '').trim()) problems.push(`提供方「${provider.id}」缺少显示名称`);
|
|
972
|
+
if (provider.source !== 'native' && !String(provider.baseUrl ?? '').trim()) {
|
|
973
|
+
problems.push(`提供方「${provider.id}」缺少接口地址`);
|
|
974
|
+
}
|
|
975
|
+
const modelIds = new Set();
|
|
976
|
+
for (const model of provider.models ?? []) {
|
|
977
|
+
if (!String(model.id ?? '').trim()) problems.push(`提供方「${provider.id}」存在空的模型 ID`);
|
|
978
|
+
if (modelIds.has(model.id)) problems.push(`提供方「${provider.id}」的模型「${model.id}」重复`);
|
|
979
|
+
modelIds.add(model.id);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
for (const [role, block] of [['执行设置', draft?.worker], ['附加审查', draft?.review]]) {
|
|
983
|
+
if (role === '附加审查' && block?.enabled !== true) continue;
|
|
984
|
+
if (block?.providerId === null || block?.providerId === undefined) {
|
|
985
|
+
if (role === '执行设置' && providers.length > 0) problems.push('执行设置尚未选择提供方');
|
|
986
|
+
continue;
|
|
987
|
+
}
|
|
988
|
+
const provider = providers.find((entry) => entry.id === block.providerId);
|
|
989
|
+
if (provider === undefined) {
|
|
990
|
+
problems.push(`${role}选择了未配置的提供方「${block.providerId}」`);
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
const model = (provider.models ?? []).find((entry) => entry.id === block.model);
|
|
994
|
+
if (model === undefined) {
|
|
995
|
+
problems.push(`${role}的模型「${block.model ?? '(空)'}」不在提供方「${provider.id}」的模型列表中`);
|
|
996
|
+
} else if (block.reasoningEffort !== null && block.reasoningEffort !== undefined
|
|
997
|
+
&& !(model.efforts ?? []).includes(block.reasoningEffort)) {
|
|
998
|
+
problems.push(`${role}的推理强度「${block.reasoningEffort}」不是模型「${model.id}」声明的能力`);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
const timeout = Number(draft?.worker?.timeoutSeconds);
|
|
1002
|
+
if (!Number.isInteger(timeout) || timeout < LIMITS.timeoutSecondsMin || timeout > LIMITS.timeoutSecondsMax) {
|
|
1003
|
+
problems.push(`超时需为 ${LIMITS.timeoutSecondsMin}–${LIMITS.timeoutSecondsMax} 秒之间的整数`);
|
|
1004
|
+
}
|
|
1005
|
+
const parallelism = Number(draft?.worker?.maxParallelism);
|
|
1006
|
+
if (!Number.isInteger(parallelism) || parallelism < LIMITS.maxParallelismMin || parallelism > LIMITS.maxParallelismMax) {
|
|
1007
|
+
problems.push(`最大并发需为 ${LIMITS.maxParallelismMin}–${LIMITS.maxParallelismMax} 之间的整数`);
|
|
1008
|
+
}
|
|
1009
|
+
const monitoring = monitoringOf(draft);
|
|
1010
|
+
for (const [field, label] of [
|
|
1011
|
+
['selfCheckSeconds', '程序自检间隔'],
|
|
1012
|
+
['attentionSeconds', '提醒你的间隔'],
|
|
1013
|
+
]) {
|
|
1014
|
+
const value = monitoring[field];
|
|
1015
|
+
const min = field === 'selfCheckSeconds' ? LIMITS.selfCheckSecondsMin : LIMITS.attentionSecondsMin;
|
|
1016
|
+
const max = field === 'selfCheckSeconds' ? LIMITS.selfCheckSecondsMax : LIMITS.attentionSecondsMax;
|
|
1017
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
1018
|
+
problems.push(`${label}需为 ${min}–${max} 秒之间的整数`);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
// The ordering rule mirrors `validateMonitoringSettings`: an attention threshold at
|
|
1022
|
+
// or below the self-check one would alert about something the self-check has not
|
|
1023
|
+
// even examined yet.
|
|
1024
|
+
if (Number.isInteger(monitoring.selfCheckSeconds) && Number.isInteger(monitoring.attentionSeconds)
|
|
1025
|
+
&& monitoring.attentionSeconds <= monitoring.selfCheckSeconds) {
|
|
1026
|
+
problems.push('提醒你的间隔必须大于程序自检间隔');
|
|
1027
|
+
}
|
|
1028
|
+
return problems;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// ---------------------------------------------------------------------------
|
|
1032
|
+
// Task helpers
|
|
1033
|
+
// ---------------------------------------------------------------------------
|
|
1034
|
+
|
|
1035
|
+
/**
|
|
1036
|
+
* Chinese label for a task state, falling back to the raw state.
|
|
1037
|
+
* @param {string} state - engine state.
|
|
1038
|
+
* @returns {string} label.
|
|
1039
|
+
*/
|
|
1040
|
+
export function taskStateLabel(state) {
|
|
1041
|
+
return TASK_STATE_LABELS[state] ?? String(state ?? '未知状态');
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/**
|
|
1045
|
+
* Whether a task may still be cancelled.
|
|
1046
|
+
* @param {string} state - engine state.
|
|
1047
|
+
* @returns {boolean} true for non-terminal states.
|
|
1048
|
+
*/
|
|
1049
|
+
export function isCancellable(state) {
|
|
1050
|
+
return state === 'pending' || state === 'running';
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/**
|
|
1054
|
+
* Chinese label for a task phase, falling back to the raw value.
|
|
1055
|
+
* @param {string} phase - engine phase.
|
|
1056
|
+
* @returns {string} label.
|
|
1057
|
+
*/
|
|
1058
|
+
export function taskPhaseLabel(phase) {
|
|
1059
|
+
if (typeof phase !== 'string' || phase === '') return '—';
|
|
1060
|
+
return TASK_PHASE_LABELS[phase] ?? phase;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* Whether a task is currently waiting for a per-call permission decision.
|
|
1065
|
+
*
|
|
1066
|
+
* Read from the task's own permission block when it is present and from the phase
|
|
1067
|
+
* otherwise (an older host reports only the phase). It is a WAIT, not a failure and
|
|
1068
|
+
* not an execution result, which is what the panel has to say.
|
|
1069
|
+
* @param {object} task - task view.
|
|
1070
|
+
* @returns {boolean} true when a decision is outstanding.
|
|
1071
|
+
*/
|
|
1072
|
+
export function isAwaitingPermission(task) {
|
|
1073
|
+
if (task?.permission?.waiting === true) return true;
|
|
1074
|
+
return task?.phase === 'awaiting-permission';
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* The pending per-call permission request of one task, or `null`.
|
|
1079
|
+
* @param {object} task - task view.
|
|
1080
|
+
* @returns {object | null} the pending request.
|
|
1081
|
+
*/
|
|
1082
|
+
export function pendingPermission(task) {
|
|
1083
|
+
const pending = task?.permission?.pending ?? null;
|
|
1084
|
+
return pending !== null && typeof pending === 'object' ? pending : null;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* One-line, plain-Chinese summary of what a task's permission state means.
|
|
1089
|
+
*
|
|
1090
|
+
* It never says "已批准" for a task, because a decision covers one call and not the
|
|
1091
|
+
* task: an `allow-once` is reported as "仅本次调用可继续", and a rejection as "该调用
|
|
1092
|
+
* 被拒绝", with the task itself still running.
|
|
1093
|
+
* @param {object} task - task view.
|
|
1094
|
+
* @returns {{ waiting: boolean, label: string, note: string, detail: string }} summary.
|
|
1095
|
+
*/
|
|
1096
|
+
export function permissionSummary(task) {
|
|
1097
|
+
const permission = task?.permission ?? null;
|
|
1098
|
+
const waiting = isAwaitingPermission(task);
|
|
1099
|
+
if (waiting) {
|
|
1100
|
+
const pending = pendingPermission(task);
|
|
1101
|
+
const tool = pending?.toolName ?? '未知工具';
|
|
1102
|
+
const access = pending?.requestedAccess?.mode;
|
|
1103
|
+
return {
|
|
1104
|
+
waiting: true,
|
|
1105
|
+
label: '等待本次调用授权决定',
|
|
1106
|
+
note: access === null || access === undefined
|
|
1107
|
+
? `工作进程暂停在 ${tool} 这一次调用上,等待本机指挥官决定。任务仍在运行,未失败,也未完成。`
|
|
1108
|
+
: `工作进程暂停在 ${tool} 这一次调用上,请求把该次调用的沙箱权限提升到 ${access},等待本机指挥官决定。`
|
|
1109
|
+
+ '无论是否允许,会话的常规权限(workspace-write)保持不变。',
|
|
1110
|
+
detail: `请求编号 ${pending?.requestId ?? '—'} · 调用 ${pending?.callId ?? '—'}`,
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
if (permission === null || permission === undefined) {
|
|
1114
|
+
return { waiting: false, label: '未使用逐次授权桥', note: '本次任务未挂载逐次授权桥:工作进程的提权请求会被直接拒绝,不会等待。', detail: '' };
|
|
1115
|
+
}
|
|
1116
|
+
const evidence = Array.isArray(permission.evidence) ? permission.evidence : [];
|
|
1117
|
+
if (evidence.length === 0) {
|
|
1118
|
+
return { waiting: false, label: '本次任务尚无授权请求', note: '暂无。请求出现时,该次调用会暂停,并在这里显示。', detail: '' };
|
|
1119
|
+
}
|
|
1120
|
+
const last = evidence[evidence.length - 1];
|
|
1121
|
+
const outcome = PERMISSION_OUTCOME_LABELS[last?.outcome] ?? last?.outcome ?? '未知结果';
|
|
1122
|
+
return {
|
|
1123
|
+
waiting: false,
|
|
1124
|
+
label: '最近一次决定',
|
|
1125
|
+
note: `最近一次调用授权请求:${outcome}。该决定只对那一次调用有效,不构成常规权限,也不会被后续调用复用。`,
|
|
1126
|
+
detail: `请求编号 ${last?.requestId ?? '—'}(共 ${evidence.length} 条记录)`,
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/**
|
|
1131
|
+
* Human duration in plain Chinese, bounded to two units.
|
|
1132
|
+
*
|
|
1133
|
+
* Used for every elapsed span the task panels show ("12 秒", "4 分 12 秒",
|
|
1134
|
+
* "2 小时 5 分"). A negative or non-finite value is reported as unknown rather than
|
|
1135
|
+
* as a plausible-looking zero.
|
|
1136
|
+
* @param {number | null | undefined} ms - milliseconds.
|
|
1137
|
+
* @returns {string} Chinese duration, or `—`.
|
|
1138
|
+
*/
|
|
1139
|
+
export function formatDuration(ms) {
|
|
1140
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return '—';
|
|
1141
|
+
const totalSeconds = Math.floor(ms / 1000);
|
|
1142
|
+
if (totalSeconds < 60) return `${totalSeconds} 秒`;
|
|
1143
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
1144
|
+
if (minutes < 60) return `${minutes} 分 ${totalSeconds % 60} 秒`;
|
|
1145
|
+
const hours = Math.floor(minutes / 60);
|
|
1146
|
+
return `${hours} 小时 ${minutes % 60} 分`;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/**
|
|
1150
|
+
* The bounded activity block of a task, normalized for display.
|
|
1151
|
+
*
|
|
1152
|
+
* Returns `null` for a record that genuinely has none — including every task stored
|
|
1153
|
+
* before this feature existed. A caller must render "没有采集到" for `null` rather than
|
|
1154
|
+
* inventing a zero, because "no data" and "no activity" are different facts.
|
|
1155
|
+
* @param {object} task - task view (list or detail).
|
|
1156
|
+
* @returns {object | null} normalized activity, or null when the record has none.
|
|
1157
|
+
*/
|
|
1158
|
+
export function taskActivity(task) {
|
|
1159
|
+
const activity = task?.activity;
|
|
1160
|
+
if (activity === null || typeof activity !== 'object' || Array.isArray(activity)) return null;
|
|
1161
|
+
const tool = activity.currentTool;
|
|
1162
|
+
const selfCheck = activity.selfCheck;
|
|
1163
|
+
return {
|
|
1164
|
+
lastActivityAt: Number.isFinite(activity.lastActivityAt) ? activity.lastActivityAt : null,
|
|
1165
|
+
idleForMs: Number.isFinite(activity.idleForMs) ? activity.idleForMs : null,
|
|
1166
|
+
waitingOn: activity.waitingOn === 'tool' ? 'tool' : 'idle',
|
|
1167
|
+
currentTool: tool === null || typeof tool !== 'object'
|
|
1168
|
+
? null
|
|
1169
|
+
: {
|
|
1170
|
+
name: typeof tool.name === 'string' && tool.name !== '' ? tool.name : '未知工具',
|
|
1171
|
+
callId: typeof tool.callId === 'string' ? tool.callId : null,
|
|
1172
|
+
startedAt: Number.isFinite(tool.startedAt) ? tool.startedAt : null,
|
|
1173
|
+
elapsedMs: Number.isFinite(tool.elapsedMs) ? tool.elapsedMs : null,
|
|
1174
|
+
},
|
|
1175
|
+
lastTool: activity.lastTool !== null && typeof activity.lastTool === 'object'
|
|
1176
|
+
? { name: activity.lastTool.name ?? null, durationMs: Number.isFinite(activity.lastTool.durationMs) ? activity.lastTool.durationMs : null }
|
|
1177
|
+
: null,
|
|
1178
|
+
events: Number.isFinite(activity.events) ? activity.events : null,
|
|
1179
|
+
activityEvents: Number.isFinite(activity.activityEvents) ? activity.activityEvents : null,
|
|
1180
|
+
toolCallsStarted: Number.isFinite(activity.toolCallsStarted) ? activity.toolCallsStarted : null,
|
|
1181
|
+
toolCallsFinished: Number.isFinite(activity.toolCallsFinished) ? activity.toolCallsFinished : null,
|
|
1182
|
+
selfCheckSeconds: Number.isFinite(activity.selfCheckSeconds) ? activity.selfCheckSeconds : null,
|
|
1183
|
+
attentionSeconds: Number.isFinite(activity.attentionSeconds) ? activity.attentionSeconds : null,
|
|
1184
|
+
selfCheck: selfCheck === null || typeof selfCheck !== 'object'
|
|
1185
|
+
? null
|
|
1186
|
+
: {
|
|
1187
|
+
episode: Number.isFinite(selfCheck.episode) ? selfCheck.episode : null,
|
|
1188
|
+
checkedAt: Number.isFinite(selfCheck.checkedAt) ? selfCheck.checkedAt : null,
|
|
1189
|
+
verdict: typeof selfCheck.verdict === 'string' ? selfCheck.verdict : null,
|
|
1190
|
+
},
|
|
1191
|
+
finalizedAt: Number.isFinite(activity.finalizedAt) ? activity.finalizedAt : null,
|
|
1192
|
+
interrupted: activity.interrupted === true,
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
/**
|
|
1197
|
+
* One plain-Chinese line describing what a running task is doing, from its activity.
|
|
1198
|
+
*
|
|
1199
|
+
* Rules the wording obeys:
|
|
1200
|
+
*
|
|
1201
|
+
* * it never claims a percentage of completion — the plugin does not measure one;
|
|
1202
|
+
* * an open tool call is described as a running tool with its OWN elapsed span,
|
|
1203
|
+
* and the silence is stated separately, because a tool that emits nothing is
|
|
1204
|
+
* still silence and may be reported as needing attention;
|
|
1205
|
+
* * a task with no activity block (an older record, or one that never ran) is
|
|
1206
|
+
* described as "未采集到进展信息", never as "空闲" or "正常".
|
|
1207
|
+
* @param {object} task - task view.
|
|
1208
|
+
* @returns {{ available: boolean, headline: string, detail: string, tone: 'off'|'on'|'warn' }} progress description.
|
|
1209
|
+
*/
|
|
1210
|
+
export function taskProgress(task) {
|
|
1211
|
+
const activity = taskActivity(task);
|
|
1212
|
+
const phase = taskPhaseLabel(task?.phase);
|
|
1213
|
+
if (activity === null) {
|
|
1214
|
+
return {
|
|
1215
|
+
available: false,
|
|
1216
|
+
headline: `${phase} · 未采集到进展信息`,
|
|
1217
|
+
detail: '这条记录没有进展信息(可能是旧版本写入的记录,或任务尚未进入执行)。没有信息不等于没有进展,也不代表失败。',
|
|
1218
|
+
tone: 'off',
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
const settled = typeof activity.finalizedAt === 'number';
|
|
1222
|
+
const idle = formatDuration(activity.idleForMs);
|
|
1223
|
+
const parts = [phase, `距上次进展 ${idle}`];
|
|
1224
|
+
if (activity.currentTool !== null) {
|
|
1225
|
+
parts.push(`正在运行 ${activity.currentTool.name}(已 ${formatDuration(activity.currentTool.elapsedMs)})`);
|
|
1226
|
+
}
|
|
1227
|
+
const headline = parts.join(' · ');
|
|
1228
|
+
const detailParts = [];
|
|
1229
|
+
if (activity.currentTool !== null) {
|
|
1230
|
+
detailParts.push('有一个工具调用正在运行;它本身耗时较长不算失败,也不会让插件结束任务。');
|
|
1231
|
+
}
|
|
1232
|
+
if (activity.selfCheck !== null && activity.selfCheck.verdict !== null) {
|
|
1233
|
+
detailParts.push(`程序自检结论:${SELF_CHECK_LABELS[activity.selfCheck.verdict] ?? activity.selfCheck.verdict}`);
|
|
1234
|
+
}
|
|
1235
|
+
if (settled) {
|
|
1236
|
+
detailParts.push('任务已结束,这些时间不再变化。');
|
|
1237
|
+
} else if (task?.state === 'interrupted') {
|
|
1238
|
+
// A restart history: the record has no `finalizedAt` (it was written by a process
|
|
1239
|
+
// that then restarted), but the run will NOT resume. This branch exists because the
|
|
1240
|
+
// generic wording would otherwise promise progress that can never happen.
|
|
1241
|
+
detailParts.push('这条记录来自一次进程重启:任务已经中断,不会继续执行,也不会再有新的进展。');
|
|
1242
|
+
} else if (activity.attentionSeconds !== null) {
|
|
1243
|
+
detailParts.push(`超过 ${formatDuration(activity.attentionSeconds * 1000)} 没有新进展时会提醒你;提醒只是提示,不会自动判失败。`);
|
|
1244
|
+
}
|
|
1245
|
+
if (activity.activityEvents !== null && activity.events !== null) {
|
|
1246
|
+
detailParts.push(`已记录 ${activity.events} 个执行事件,其中 ${activity.activityEvents} 个是真正的进展。`);
|
|
1247
|
+
}
|
|
1248
|
+
return {
|
|
1249
|
+
available: true,
|
|
1250
|
+
headline,
|
|
1251
|
+
detail: detailParts.join(' '),
|
|
1252
|
+
tone: activity.currentTool !== null ? 'on' : (settled ? 'off' : 'on'),
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/**
|
|
1257
|
+
* Chinese labels for the managed MCP entry's stale owned facts (`mcp.drift`).
|
|
1258
|
+
*
|
|
1259
|
+
* A state name ("outdated") does not tell an operator what would change, so the panel
|
|
1260
|
+
* names each fact. An unknown one falls back to its own name rather than being hidden.
|
|
1261
|
+
*/
|
|
1262
|
+
export const CODEX_MCP_DRIFT_LABELS = Object.freeze({
|
|
1263
|
+
tool_timeout_sec: '缺少工具超时(部分客户端可能因此提前中断长时间等待)',
|
|
1264
|
+
args: '入口脚本路径已变化(插件已升级或移动)',
|
|
1265
|
+
command: 'command 仍是旧版写下的路径',
|
|
1266
|
+
env: '发现文件的环境变量与当前不一致',
|
|
1267
|
+
});
|
|
1268
|
+
|
|
1269
|
+
/**
|
|
1270
|
+
* Describe an `outdated` MCP entry in the panel's terms.
|
|
1271
|
+
*/
|
|
1272
|
+
export function codexMcpDriftText(mcp) {
|
|
1273
|
+
const drift = Array.isArray(mcp?.drift) ? mcp.drift : [];
|
|
1274
|
+
if (drift.length === 0) return '托管 MCP 条目需要更新';
|
|
1275
|
+
return drift.map((key) => CODEX_MCP_DRIFT_LABELS[key] ?? key).join(';');
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* Whether a task is still live, i.e. a bounded auto-refresh may still learn something.
|
|
1280
|
+
*
|
|
1281
|
+
* `pending` and `running` are the only states that can change on their own; every
|
|
1282
|
+
* other state is terminal and a refresh would only repeat the same bytes.
|
|
1283
|
+
* @param {object} task - task view.
|
|
1284
|
+
* @returns {boolean} true while the task may still progress.
|
|
1285
|
+
*/
|
|
1286
|
+
export function isLiveTask(task) {
|
|
1287
|
+
return task?.state === 'pending' || task?.state === 'running';
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
/**
|
|
1291
|
+
* Whether a task list contains any live task.
|
|
1292
|
+
* @param {object[]} tasks - task views.
|
|
1293
|
+
* @returns {boolean} true when at least one is pending or running.
|
|
1294
|
+
*/
|
|
1295
|
+
export function hasLiveTasks(tasks) {
|
|
1296
|
+
return Array.isArray(tasks) && tasks.some(isLiveTask);
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
/**
|
|
1300
|
+
* Pre-flight checks for the two silence thresholds.
|
|
1301
|
+
*
|
|
1302
|
+
* Mirrors `validateMonitoringSettings`. Kept separate because the monitoring save has
|
|
1303
|
+
* its own narrow button: a bad timer must not block saving the rest of the settings,
|
|
1304
|
+
* and a bad provider block must not block saving a timer.
|
|
1305
|
+
* @param {{ selfCheckSeconds: number, attentionSeconds: number }} monitoring - normalized block.
|
|
1306
|
+
* @returns {string[]} Chinese problem descriptions; empty when plausible.
|
|
1307
|
+
*/
|
|
1308
|
+
export function precheckMonitoring(monitoring) {
|
|
1309
|
+
const problems = [];
|
|
1310
|
+
const self = monitoring?.selfCheckSeconds;
|
|
1311
|
+
const attention = monitoring?.attentionSeconds;
|
|
1312
|
+
if (!Number.isInteger(self) || self < LIMITS.selfCheckSecondsMin || self > LIMITS.selfCheckSecondsMax) {
|
|
1313
|
+
problems.push(`程序自检间隔需为 ${LIMITS.selfCheckSecondsMin}–${LIMITS.selfCheckSecondsMax} 秒之间的整数`);
|
|
1314
|
+
}
|
|
1315
|
+
if (!Number.isInteger(attention) || attention < LIMITS.attentionSecondsMin || attention > LIMITS.attentionSecondsMax) {
|
|
1316
|
+
problems.push(`提醒你的间隔需为 ${LIMITS.attentionSecondsMin}–${LIMITS.attentionSecondsMax} 秒之间的整数`);
|
|
1317
|
+
}
|
|
1318
|
+
if (Number.isInteger(self) && Number.isInteger(attention) && attention <= self) {
|
|
1319
|
+
problems.push('提醒你的间隔必须大于程序自检间隔');
|
|
1320
|
+
}
|
|
1321
|
+
return problems;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
/**
|
|
1325
|
+
* Honest execution/acceptance summary for one task.
|
|
1326
|
+
*
|
|
1327
|
+
* The engine reports `awaiting-host-review` after successful execution. That is
|
|
1328
|
+
* not acceptance: `selfApproved` is always false and `hostAcceptance` is null
|
|
1329
|
+
* until the host records its own decision, so the summary never says "验收通过".
|
|
1330
|
+
* @param {object} task - task view.
|
|
1331
|
+
* @returns {{ label: string, executed: boolean, accepted: boolean, note: string }} summary.
|
|
1332
|
+
*/
|
|
1333
|
+
export function taskOutcome(task) {
|
|
1334
|
+
const state = String(task?.state ?? '');
|
|
1335
|
+
const accepted = task?.hostAcceptance !== null && task?.hostAcceptance !== undefined;
|
|
1336
|
+
const executed = state === 'awaiting-host-review' || accepted === true;
|
|
1337
|
+
const note = state === 'awaiting-host-review'
|
|
1338
|
+
? '执行已完成,等待宿主(Codex)审查;插件不会自行验收。'
|
|
1339
|
+
: accepted === true
|
|
1340
|
+
? '宿主已记录验收结论。'
|
|
1341
|
+
: state === 'failed'
|
|
1342
|
+
? '执行失败;错误详情见下方证据。'
|
|
1343
|
+
: state === 'cancelled'
|
|
1344
|
+
? '任务已取消,未产生验收结论。'
|
|
1345
|
+
: '任务尚未产生结果。';
|
|
1346
|
+
return { label: taskStateLabel(state), executed, accepted, note };
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
/**
|
|
1350
|
+
* Discoverable changed-file list in a task's diff payload.
|
|
1351
|
+
*
|
|
1352
|
+
* The engine's `diff.files` entries carry `{ code, path, from, status, sensitive }`;
|
|
1353
|
+
* older or partial payloads may carry plain strings instead. Anything else
|
|
1354
|
+
* returns `null`, and the page then shows the bounded raw diff rather than
|
|
1355
|
+
* inventing a summary.
|
|
1356
|
+
* @param {object} task - task view.
|
|
1357
|
+
* @returns {string[] | null} one display line per changed file, or null.
|
|
1358
|
+
*/
|
|
1359
|
+
export function changedFiles(task) {
|
|
1360
|
+
const candidates = [task?.diff?.files, task?.diff?.changedFiles, task?.changedFiles];
|
|
1361
|
+
for (const candidate of candidates) {
|
|
1362
|
+
if (!Array.isArray(candidate)) continue;
|
|
1363
|
+
const files = [];
|
|
1364
|
+
for (const entry of candidate) {
|
|
1365
|
+
if (typeof entry === 'string') {
|
|
1366
|
+
if (entry !== '') files.push(entry);
|
|
1367
|
+
continue;
|
|
1368
|
+
}
|
|
1369
|
+
const path = entry?.path ?? entry?.file;
|
|
1370
|
+
if (typeof path !== 'string' || path === '') continue;
|
|
1371
|
+
const code = typeof entry?.status === 'string' && entry.status !== ''
|
|
1372
|
+
? entry.status
|
|
1373
|
+
: (typeof entry?.code === 'string' && entry.code !== '' ? entry.code : null);
|
|
1374
|
+
const from = typeof entry?.from === 'string' && entry.from !== '' ? entry.from : null;
|
|
1375
|
+
const label = from === null ? path : `${from} → ${path}`;
|
|
1376
|
+
// A withheld file is flagged rather than hidden: the operator must be able
|
|
1377
|
+
// to see that something changed without seeing its content.
|
|
1378
|
+
const mark = entry?.sensitive === true ? '(内容已扣留)' : '';
|
|
1379
|
+
files.push(code === null ? `${label}${mark}` : `${code} ${label}${mark}`);
|
|
1380
|
+
}
|
|
1381
|
+
if (files.length > 0) return files;
|
|
1382
|
+
}
|
|
1383
|
+
return null;
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
/**
|
|
1387
|
+
* Bounded, single-line-safe text for a monospace block.
|
|
1388
|
+
* @param {unknown} value - any server text.
|
|
1389
|
+
* @param {number} [max] - maximum characters kept.
|
|
1390
|
+
* @returns {string} text.
|
|
1391
|
+
*/
|
|
1392
|
+
export function boundedText(value, max = 20_000) {
|
|
1393
|
+
if (value === null || value === undefined) return '';
|
|
1394
|
+
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
|
|
1395
|
+
return text.length > max ? `${text.slice(0, max)}\n…(已截断)` : text;
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
/**
|
|
1399
|
+
* Format a millisecond timestamp for display.
|
|
1400
|
+
* @param {number | null | undefined} value - epoch milliseconds.
|
|
1401
|
+
* @returns {string} local time, or an em dash.
|
|
1402
|
+
*/
|
|
1403
|
+
export function formatTime(value) {
|
|
1404
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return '—';
|
|
1405
|
+
try {
|
|
1406
|
+
return new Date(value).toLocaleString('zh-CN', { hour12: false });
|
|
1407
|
+
} catch {
|
|
1408
|
+
return new Date(value).toISOString();
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* State of one grant, derived from its four timestamps.
|
|
1414
|
+
* @param {object} grant - grant view.
|
|
1415
|
+
* @param {number} now - current epoch milliseconds.
|
|
1416
|
+
* @returns {{ key: string, label: string }} state.
|
|
1417
|
+
*/
|
|
1418
|
+
export function grantState(grant, now = Date.now()) {
|
|
1419
|
+
if (grant?.revokedAt !== null && grant?.revokedAt !== undefined) return { key: 'revoked', label: '已撤销' };
|
|
1420
|
+
if (grant?.consumedAt !== null && grant?.consumedAt !== undefined) return { key: 'consumed', label: '已使用(单次授权已用完)' };
|
|
1421
|
+
if (typeof grant?.expiresAt === 'number' && grant.expiresAt <= now) return { key: 'expired', label: '已过期' };
|
|
1422
|
+
return { key: 'live', label: '有效' };
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
/**
|
|
1426
|
+
* Chinese, actionable description of one failure.
|
|
1427
|
+
* @param {unknown} error - `ApiError` or anything else.
|
|
1428
|
+
* @returns {string} message with the stable code appended for support purposes.
|
|
1429
|
+
*/
|
|
1430
|
+
export function describeError(error) {
|
|
1431
|
+
const code = typeof error?.code === 'string' ? error.code : '';
|
|
1432
|
+
const messages = {
|
|
1433
|
+
USER_PLANE_UNREACHABLE: '无法连接宿主设置接口:请确认 DSH 网页仍在运行,并刷新页面后重试。',
|
|
1434
|
+
USER_PLANE_MALFORMED: '宿主返回了无法识别的内容。',
|
|
1435
|
+
SETTINGS_MISSING: '请求中没有设置文档。',
|
|
1436
|
+
SETTINGS_INVALID: '设置内容不合法,已保留你的草稿。',
|
|
1437
|
+
SETTINGS_NO_PROVIDERS: '至少需要配置一个提供方。',
|
|
1438
|
+
SETTINGS_SCHEMA_UNSUPPORTED: '设置文档版本不被当前插件支持。',
|
|
1439
|
+
PROVIDER_ID_INVALID: '提供方标识格式不合法。',
|
|
1440
|
+
PROVIDER_NAME_INVALID: '提供方显示名称不合法。',
|
|
1441
|
+
PROVIDER_BASE_URL_INVALID: '接口地址不合法(需为 http/https,且不得包含账号密码、查询串或片段)。',
|
|
1442
|
+
PROVIDER_CREDENTIAL_REF_INVALID: '凭据引用名不合法(需为环境变量风格名称)。',
|
|
1443
|
+
PROVIDER_PROTOCOL_UNSUPPORTED: '该协议当前不受支持。',
|
|
1444
|
+
PROVIDER_SECRET_IN_SETTINGS: '设置文档中不能包含密钥;请使用单独的凭据输入框。',
|
|
1445
|
+
PROVIDER_DUPLICATE: '提供方标识重复。',
|
|
1446
|
+
PROVIDER_IN_USE: '该提供方仍被当前设置引用,无法删除。',
|
|
1447
|
+
MODEL_INVALID: '模型条目不合法。',
|
|
1448
|
+
MODEL_DUPLICATE: '模型 ID 重复。',
|
|
1449
|
+
MODEL_EFFORTS_INVALID: '模型的推理强度声明不合法。',
|
|
1450
|
+
SELECTION_PROVIDER_REQUIRED: '请选择提供方。',
|
|
1451
|
+
SELECTION_PROVIDER_UNKNOWN: '所选提供方未配置。',
|
|
1452
|
+
SELECTION_MODEL_REQUIRED: '请选择模型。',
|
|
1453
|
+
SELECTION_MODEL_UNKNOWN: '所选模型不在该提供方的模型列表中。',
|
|
1454
|
+
SELECTION_EFFORT_UNKNOWN: '推理强度取值不存在。',
|
|
1455
|
+
SELECTION_EFFORT_UNSUPPORTED: '该模型未声明此推理强度。',
|
|
1456
|
+
WORKER_TIMEOUT_INVALID: '超时时间超出允许范围。',
|
|
1457
|
+
WORKER_PARALLELISM_INVALID: '最大并发超出允许范围。',
|
|
1458
|
+
WORKER_ISOLATION_INVALID: '工作区隔离方式不受支持。',
|
|
1459
|
+
AUTHORIZATION_INVALID: '授权有效期取值不合法。',
|
|
1460
|
+
PRESET_INVALID: '预设内容不合法。',
|
|
1461
|
+
PRESET_DUPLICATE: '预设标识重复。',
|
|
1462
|
+
PROJECT_OVERRIDE_INVALID: '项目覆盖内容不合法。',
|
|
1463
|
+
PROJECT_OVERRIDE_DUPLICATE: '同一项目存在重复覆盖。',
|
|
1464
|
+
CONNECTION_ID_REQUIRED: '缺少连接标识。',
|
|
1465
|
+
CONNECTION_UNKNOWN: '该连接不存在或已失效。',
|
|
1466
|
+
CONNECTION_LIMIT: '连接数量已达上限,请先撤销不用的连接。',
|
|
1467
|
+
GRANT_ID_REQUIRED: '缺少授权标识。',
|
|
1468
|
+
GRANT_UNKNOWN: '该授权不存在。',
|
|
1469
|
+
GRANT_KIND_INVALID: '授权范围不合法。',
|
|
1470
|
+
GRANT_TTL_INVALID: '授权有效期不合法。',
|
|
1471
|
+
GRANT_LIMIT: '授权数量已达上限。',
|
|
1472
|
+
GRANT_MISMATCH: '该授权不适用于当前连接或工作区。',
|
|
1473
|
+
JOB_TASK_NOT_FOUND: '任务不存在或已被清理。',
|
|
1474
|
+
PROVIDER_ID_REQUIRED: '请选择一个提供方。',
|
|
1475
|
+
PROVIDER_UNKNOWN: '该提供方不在当前设置中,请先保存配置文件。',
|
|
1476
|
+
PROVIDER_CREDENTIAL_REF_MISSING: '该提供方未声明凭据引用名,无法保存密钥;请先在提供方设置中填写引用名。',
|
|
1477
|
+
CREDENTIAL_EMPTY: '请先输入密钥内容。',
|
|
1478
|
+
CREDENTIAL_VALUE_REQUIRED: '请先输入密钥内容;如需删除请使用「清除密钥」。',
|
|
1479
|
+
CREDENTIAL_VALUE_TOO_LARGE: '密钥内容超出长度上限。',
|
|
1480
|
+
CREDENTIAL_OPERATION_FAILED: '宿主凭据服务拒绝了本次操作。',
|
|
1481
|
+
CREDENTIAL_READ_ONLY: '该凭据引用为只读(由外部环境提供),无法在此修改。',
|
|
1482
|
+
CREDENTIAL_REF_INVALID: '凭据引用名不合法。',
|
|
1483
|
+
CREDENTIAL_SEAM_UNAVAILABLE: '当前宿主尚未提供凭据写入接口,密钥无法保存。',
|
|
1484
|
+
ROUTING_PROVIDER_NOT_REGISTERED: '该提供方尚未注册到宿主模型路由中。',
|
|
1485
|
+
ROUTING_MODEL_UNRESOLVED: '该模型无法在宿主模型路由中解析。',
|
|
1486
|
+
ROUTING_EFFORT_UNSUPPORTED: '该模型不支持所选推理强度。',
|
|
1487
|
+
ROUTING_SERVICE_UNAVAILABLE: '宿主模型服务当前不可用。',
|
|
1488
|
+
// Remote model discovery: each code is a different fix, so each gets its own
|
|
1489
|
+
// sentence. None of them can quote the endpoint, the credential or the body.
|
|
1490
|
+
DISCOVERY_PROVIDER_UNKNOWN: '未找到该提供方配置。',
|
|
1491
|
+
DISCOVERY_BASE_URL_INVALID: '接口地址不可用于获取模型列表(需为 http/https,且不含账号密码、查询串或片段)。',
|
|
1492
|
+
DISCOVERY_CREDENTIAL_REF_MISSING: '该提供方未设置凭据引用名,无法向提供方取模型;请先填写引用名并保存。',
|
|
1493
|
+
DISCOVERY_CREDENTIAL_SEAM_UNAVAILABLE: '当前宿主未提供凭据服务,无法带上密钥向提供方取模型。',
|
|
1494
|
+
DISCOVERY_CREDENTIAL_UNAVAILABLE: '宿主凭据服务无法读取该引用名对应的密钥。',
|
|
1495
|
+
DISCOVERY_CREDENTIAL_NOT_CONFIGURED: '该凭据引用名尚未保存密钥,请先在「密钥」处保存。',
|
|
1496
|
+
DISCOVERY_CREDENTIAL_EMPTY: '该凭据引用名的密钥内容为空,请重新保存。',
|
|
1497
|
+
DISCOVERY_AUTH_REFUSED: '提供方拒绝了该密钥(401/403):请确认密钥是否有效、是否属于该接口地址。',
|
|
1498
|
+
DISCOVERY_HTTP_ERROR: '提供方返回了错误状态码;详情见上方诊断。',
|
|
1499
|
+
DISCOVERY_REDIRECT_REFUSED: '提供方返回了重定向,为保护密钥没有跟随;请直接填写最终接口地址。',
|
|
1500
|
+
DISCOVERY_NETWORK_FAILED: '无法连接提供方接口地址:请检查地址、端口与网络。',
|
|
1501
|
+
DISCOVERY_TIMEOUT: '提供方在规定时间内没有响应,请稍后重试。',
|
|
1502
|
+
DISCOVERY_CANCELLED: '获取模型的请求已被取消。',
|
|
1503
|
+
DISCOVERY_MALFORMED_RESPONSE: '提供方返回的内容不是可识别的模型列表(需要 OpenAI 兼容的 {"data":[{"id":...}]})。',
|
|
1504
|
+
DISCOVERY_BODY_TOO_LARGE: '提供方返回的内容超过大小上限,已中止读取。',
|
|
1505
|
+
USER_PLANE_METHOD_NOT_ALLOWED: '该请求方法不被允许。',
|
|
1506
|
+
};
|
|
1507
|
+
const known = messages[code];
|
|
1508
|
+
if (known !== undefined) return `${known}(${code})`;
|
|
1509
|
+
if (code.startsWith('HTTP_')) return `宿主返回 ${code.slice(5)},请刷新后重试。`;
|
|
1510
|
+
const detail = typeof error?.message === 'string' && error.message !== '' ? error.message.slice(0, 200) : '未知错误';
|
|
1511
|
+
return code === '' ? detail : `${detail}(${code})`;
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
// ---------------------------------------------------------------------------
|
|
1515
|
+
// Store
|
|
1516
|
+
// ---------------------------------------------------------------------------
|
|
1517
|
+
|
|
1518
|
+
/**
|
|
1519
|
+
* Create the page store.
|
|
1520
|
+
*
|
|
1521
|
+
* The store owns the served data, the editable draft, and the transients an
|
|
1522
|
+
* operator asked for (a model catalog, a connectivity report, a one-time token).
|
|
1523
|
+
* It never owns a credential value: {@link DelegateStore#setCredential} forwards
|
|
1524
|
+
* one and forgets it.
|
|
1525
|
+
* @param {object} options - `api` transport, `now` clock.
|
|
1526
|
+
* @returns {object} store with `subscribe`, `getSnapshot` and action methods.
|
|
1527
|
+
*/
|
|
1528
|
+
export function createStore(options = {}) {
|
|
1529
|
+
const api = options.api ?? createApi();
|
|
1530
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
1531
|
+
|
|
1532
|
+
let state = {
|
|
1533
|
+
revision: 0,
|
|
1534
|
+
loading: {},
|
|
1535
|
+
notices: [],
|
|
1536
|
+
status: null,
|
|
1537
|
+
nativeProviders: [],
|
|
1538
|
+
nativeProvidersError: null,
|
|
1539
|
+
settings: null,
|
|
1540
|
+
draft: null,
|
|
1541
|
+
dirty: false,
|
|
1542
|
+
catalog: null,
|
|
1543
|
+
catalogError: null,
|
|
1544
|
+
modelCatalog: {},
|
|
1545
|
+
connections: [],
|
|
1546
|
+
selectedConnectionId: null,
|
|
1547
|
+
grants: [],
|
|
1548
|
+
tasks: [],
|
|
1549
|
+
taskDetail: null,
|
|
1550
|
+
token: null,
|
|
1551
|
+
tokenConnectionId: null,
|
|
1552
|
+
credentials: {},
|
|
1553
|
+
connectivity: {},
|
|
1554
|
+
// Codex integration. `codex` holds the last served status document,
|
|
1555
|
+
// `codexError` its last refusal, `codexOutcome` the last action's result. None
|
|
1556
|
+
// of them is a credential: the status document is a file/config diagnosis.
|
|
1557
|
+
codex: null,
|
|
1558
|
+
codexError: null,
|
|
1559
|
+
codexOutcome: null,
|
|
1560
|
+
};
|
|
1561
|
+
/** @type {Set<() => void>} */
|
|
1562
|
+
const listeners = new Set();
|
|
1563
|
+
let disposed = false;
|
|
1564
|
+
|
|
1565
|
+
function emit() {
|
|
1566
|
+
for (const listener of [...listeners]) {
|
|
1567
|
+
try {
|
|
1568
|
+
listener();
|
|
1569
|
+
} catch {
|
|
1570
|
+
// A subscriber's own render error must not break the store.
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
function patch(next) {
|
|
1576
|
+
if (disposed) return;
|
|
1577
|
+
state = { ...state, ...next, revision: state.revision + 1 };
|
|
1578
|
+
emit();
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
/**
|
|
1582
|
+
* Append one operator-facing message.
|
|
1583
|
+
* @param {'info'|'error'|'success'} level - severity.
|
|
1584
|
+
* @param {string} text - Chinese text.
|
|
1585
|
+
* @returns {number} notice id.
|
|
1586
|
+
*/
|
|
1587
|
+
function notify(level, text) {
|
|
1588
|
+
const id = state.revision + 1 + Math.random();
|
|
1589
|
+
patch({ notices: [...state.notices, { id, level, text }].slice(-6) });
|
|
1590
|
+
return id;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
function dismissNotice(id) {
|
|
1594
|
+
patch({ notices: state.notices.filter((notice) => notice.id !== id) });
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
async function track(key, work) {
|
|
1598
|
+
patch({ loading: { ...state.loading, [key]: true } });
|
|
1599
|
+
try {
|
|
1600
|
+
return await work();
|
|
1601
|
+
} finally {
|
|
1602
|
+
if (!disposed) patch({ loading: { ...state.loading, [key]: false } });
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
const store = {
|
|
1607
|
+
subscribe(listener) {
|
|
1608
|
+
listeners.add(listener);
|
|
1609
|
+
return () => listeners.delete(listener);
|
|
1610
|
+
},
|
|
1611
|
+
getSnapshot() {
|
|
1612
|
+
return state;
|
|
1613
|
+
},
|
|
1614
|
+
notify,
|
|
1615
|
+
dismissNotice,
|
|
1616
|
+
|
|
1617
|
+
/** Read the delegation posture. */
|
|
1618
|
+
async refreshStatus() {
|
|
1619
|
+
return await track('status', async () => {
|
|
1620
|
+
try {
|
|
1621
|
+
const body = await api.getStatus();
|
|
1622
|
+
patch({ status: body });
|
|
1623
|
+
return { ok: true, body };
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
notify('error', describeError(error));
|
|
1626
|
+
return { ok: false, error };
|
|
1627
|
+
}
|
|
1628
|
+
});
|
|
1629
|
+
},
|
|
1630
|
+
|
|
1631
|
+
/** Load configured provider connections from the native DSH registry. */
|
|
1632
|
+
async loadNativeProviders() {
|
|
1633
|
+
return await track('nativeProviders', async () => {
|
|
1634
|
+
try {
|
|
1635
|
+
const body = await api.getNativeProviders();
|
|
1636
|
+
patch({ nativeProviders: Array.isArray(body.providers) ? body.providers : [], nativeProvidersError: body.error ?? null });
|
|
1637
|
+
return { ok: true, providers: body.providers ?? [], error: body.error ?? null };
|
|
1638
|
+
} catch (error) {
|
|
1639
|
+
patch({ nativeProvidersError: describeError(error) });
|
|
1640
|
+
notify('error', describeError(error));
|
|
1641
|
+
return { ok: false, error };
|
|
1642
|
+
}
|
|
1643
|
+
});
|
|
1644
|
+
},
|
|
1645
|
+
|
|
1646
|
+
/** Persist and immediately apply the single authorization switch. */
|
|
1647
|
+
async setDelegationEnabled(enabled) {
|
|
1648
|
+
if (typeof enabled !== 'boolean') return { ok: false };
|
|
1649
|
+
return await track('delegationSwitch', async () => {
|
|
1650
|
+
try {
|
|
1651
|
+
const body = await api.setDelegationEnabled(enabled);
|
|
1652
|
+
const settings = state.settings === null ? null : { ...state.settings, delegationEnabled: enabled };
|
|
1653
|
+
const draft = state.draft === null ? null : { ...state.draft, delegationEnabled: enabled };
|
|
1654
|
+
patch({ status: { ...(state.status ?? {}), delegation: body.delegation }, settings, draft });
|
|
1655
|
+
notify('success', enabled ? '本机 DSH 委派已开启。' : '本机 DSH 委派已关闭,运行中的任务已请求停止。');
|
|
1656
|
+
return { ok: true, delegation: body.delegation };
|
|
1657
|
+
} catch (error) {
|
|
1658
|
+
notify('error', describeError(error));
|
|
1659
|
+
return { ok: false, error };
|
|
1660
|
+
}
|
|
1661
|
+
});
|
|
1662
|
+
},
|
|
1663
|
+
|
|
1664
|
+
/** Read the committed document (and reset the draft unless it is dirty). */
|
|
1665
|
+
async loadSettings() {
|
|
1666
|
+
return await track('settings', async () => {
|
|
1667
|
+
try {
|
|
1668
|
+
const body = await api.getSettings();
|
|
1669
|
+
patch({
|
|
1670
|
+
settings: body.settings ?? null,
|
|
1671
|
+
draft: state.dirty && state.draft !== null ? state.draft : draftFromSettings(body.settings),
|
|
1672
|
+
...(state.dirty && state.draft !== null ? {} : { dirty: false }),
|
|
1673
|
+
});
|
|
1674
|
+
return { ok: true, settings: body.settings ?? null };
|
|
1675
|
+
} catch (error) {
|
|
1676
|
+
notify('error', describeError(error));
|
|
1677
|
+
return { ok: false, error };
|
|
1678
|
+
}
|
|
1679
|
+
});
|
|
1680
|
+
},
|
|
1681
|
+
|
|
1682
|
+
/** Read the served catalog (models, effort capabilities, effective config). */
|
|
1683
|
+
async loadCatalog(projectPath = null) {
|
|
1684
|
+
return await track('catalog', async () => {
|
|
1685
|
+
try {
|
|
1686
|
+
const body = await api.getCatalog(projectPath === null ? {} : { projectPath });
|
|
1687
|
+
patch({ catalog: body, catalogError: null });
|
|
1688
|
+
return { ok: true, catalog: body };
|
|
1689
|
+
} catch (error) {
|
|
1690
|
+
patch({ catalogError: { code: error?.code ?? '', text: describeError(error) } });
|
|
1691
|
+
return { ok: false, error };
|
|
1692
|
+
}
|
|
1693
|
+
});
|
|
1694
|
+
},
|
|
1695
|
+
|
|
1696
|
+
/** Read the connection list. */
|
|
1697
|
+
async loadConnections() {
|
|
1698
|
+
return await track('connections', async () => {
|
|
1699
|
+
try {
|
|
1700
|
+
const body = await api.listConnections();
|
|
1701
|
+
const connections = Array.isArray(body.connections) ? body.connections : [];
|
|
1702
|
+
const live = connections.filter((entry) => entry.revoked !== true);
|
|
1703
|
+
const selected = connections.some((entry) => entry.connectionId === state.selectedConnectionId && entry.revoked !== true)
|
|
1704
|
+
? state.selectedConnectionId
|
|
1705
|
+
: (live[0]?.connectionId ?? null);
|
|
1706
|
+
patch({ connections, selectedConnectionId: selected });
|
|
1707
|
+
if (selected !== null && selected !== state.selectedConnectionId) await store.loadGrants(selected);
|
|
1708
|
+
return { ok: true, connections };
|
|
1709
|
+
} catch (error) {
|
|
1710
|
+
notify('error', describeError(error));
|
|
1711
|
+
return { ok: false, error };
|
|
1712
|
+
}
|
|
1713
|
+
});
|
|
1714
|
+
},
|
|
1715
|
+
|
|
1716
|
+
/**
|
|
1717
|
+
* Issue a connection. The token is kept in memory, tied to its connection id.
|
|
1718
|
+
* @param {string} label - display label.
|
|
1719
|
+
*/
|
|
1720
|
+
async issueConnection(label) {
|
|
1721
|
+
return await track('issueConnection', async () => {
|
|
1722
|
+
try {
|
|
1723
|
+
const body = await api.issueConnection(String(label ?? '').trim() || 'codex');
|
|
1724
|
+
patch({
|
|
1725
|
+
token: typeof body.token === 'string' ? body.token : null,
|
|
1726
|
+
tokenConnectionId: body.connection?.connectionId ?? null,
|
|
1727
|
+
selectedConnectionId: body.connection?.connectionId ?? state.selectedConnectionId,
|
|
1728
|
+
});
|
|
1729
|
+
await store.loadConnections();
|
|
1730
|
+
notify('success', '连接已签发。授权令牌只显示这一次,请立即复制到 MCP 宿主配置。');
|
|
1731
|
+
return { ok: true, connection: body.connection, token: body.token };
|
|
1732
|
+
} catch (error) {
|
|
1733
|
+
notify('error', describeError(error));
|
|
1734
|
+
return { ok: false, error };
|
|
1735
|
+
}
|
|
1736
|
+
});
|
|
1737
|
+
},
|
|
1738
|
+
|
|
1739
|
+
/** Drop the one-time token from memory. */
|
|
1740
|
+
clearToken() {
|
|
1741
|
+
patch({ token: null, tokenConnectionId: null });
|
|
1742
|
+
},
|
|
1743
|
+
|
|
1744
|
+
/**
|
|
1745
|
+
* Revoke one connection (and every grant it holds).
|
|
1746
|
+
* @param {string} connectionId - server-issued identity.
|
|
1747
|
+
*/
|
|
1748
|
+
async revokeConnection(connectionId) {
|
|
1749
|
+
return await track('revokeConnection', async () => {
|
|
1750
|
+
try {
|
|
1751
|
+
const body = await api.revokeConnection(connectionId);
|
|
1752
|
+
if (state.tokenConnectionId === connectionId) patch({ token: null, tokenConnectionId: null });
|
|
1753
|
+
await store.loadConnections();
|
|
1754
|
+
await store.refreshStatus();
|
|
1755
|
+
notify('success', `已撤销该连接及其授权(${body.grantsRevoked ?? 0} 条授权)。`);
|
|
1756
|
+
return { ok: true, grantsRevoked: body.grantsRevoked ?? 0 };
|
|
1757
|
+
} catch (error) {
|
|
1758
|
+
notify('error', describeError(error));
|
|
1759
|
+
return { ok: false, error };
|
|
1760
|
+
}
|
|
1761
|
+
});
|
|
1762
|
+
},
|
|
1763
|
+
|
|
1764
|
+
/** Revoke every grant and connection ("stop everything now"). */
|
|
1765
|
+
async revokeAll() {
|
|
1766
|
+
return await track('revokeAll', async () => {
|
|
1767
|
+
try {
|
|
1768
|
+
const body = await api.revokeAll();
|
|
1769
|
+
patch({ token: null, tokenConnectionId: null, grants: [] });
|
|
1770
|
+
await store.loadConnections();
|
|
1771
|
+
await store.refreshStatus();
|
|
1772
|
+
notify('success', `已撤销全部授权与连接(${body.grantsRevoked ?? 0} 条授权)。当前委托已关闭。`);
|
|
1773
|
+
return { ok: true, grantsRevoked: body.grantsRevoked ?? 0 };
|
|
1774
|
+
} catch (error) {
|
|
1775
|
+
notify('error', describeError(error));
|
|
1776
|
+
return { ok: false, error };
|
|
1777
|
+
}
|
|
1778
|
+
});
|
|
1779
|
+
},
|
|
1780
|
+
|
|
1781
|
+
/**
|
|
1782
|
+
* Select a server-issued connection identity and load its grants.
|
|
1783
|
+
* @param {string} connectionId - connection id from the served list.
|
|
1784
|
+
*/
|
|
1785
|
+
async selectConnection(connectionId) {
|
|
1786
|
+
patch({ selectedConnectionId: connectionId, grants: [] });
|
|
1787
|
+
return await store.loadGrants(connectionId);
|
|
1788
|
+
},
|
|
1789
|
+
|
|
1790
|
+
/**
|
|
1791
|
+
* Load the grants of one connection.
|
|
1792
|
+
* @param {string} connectionId - connection id.
|
|
1793
|
+
*/
|
|
1794
|
+
async loadGrants(connectionId) {
|
|
1795
|
+
return await track('grants', async () => {
|
|
1796
|
+
try {
|
|
1797
|
+
const body = await api.listGrants(connectionId);
|
|
1798
|
+
patch({ grants: Array.isArray(body.grants) ? body.grants : [] });
|
|
1799
|
+
return { ok: true, grants: body.grants ?? [] };
|
|
1800
|
+
} catch (error) {
|
|
1801
|
+
notify('error', describeError(error));
|
|
1802
|
+
return { ok: false, error };
|
|
1803
|
+
}
|
|
1804
|
+
});
|
|
1805
|
+
},
|
|
1806
|
+
|
|
1807
|
+
/**
|
|
1808
|
+
* Issue one grant for the selected connection.
|
|
1809
|
+
* @param {object} form - `{ connectionId, kind, workspacePath, ttlSeconds }`.
|
|
1810
|
+
*/
|
|
1811
|
+
async issueGrant(form) {
|
|
1812
|
+
const connectionId = form?.connectionId ?? state.selectedConnectionId;
|
|
1813
|
+
const workspacePath = String(form?.workspacePath ?? '').trim();
|
|
1814
|
+
const kind = form?.kind === 'session' ? 'session' : 'task';
|
|
1815
|
+
if (typeof connectionId !== 'string' || connectionId === '') {
|
|
1816
|
+
notify('error', '请先签发并选择一个连接,授权只能绑定到宿主签发的连接身份。');
|
|
1817
|
+
return { ok: false };
|
|
1818
|
+
}
|
|
1819
|
+
if (workspacePath === '') {
|
|
1820
|
+
notify('error', '请填写授权的绝对工作区路径。');
|
|
1821
|
+
return { ok: false };
|
|
1822
|
+
}
|
|
1823
|
+
return await track('issueGrant', async () => {
|
|
1824
|
+
try {
|
|
1825
|
+
const body = {
|
|
1826
|
+
connectionId,
|
|
1827
|
+
kind,
|
|
1828
|
+
workspacePath,
|
|
1829
|
+
};
|
|
1830
|
+
const ttl = Number(form?.ttlSeconds);
|
|
1831
|
+
if (Number.isInteger(ttl) && ttl > 0) body.ttlSeconds = ttl;
|
|
1832
|
+
const answer = await api.issueGrant(body);
|
|
1833
|
+
await store.loadGrants(connectionId);
|
|
1834
|
+
await store.refreshStatus();
|
|
1835
|
+
notify('success', kind === 'task' ? '已签发单次任务授权(用掉即失效)。' : '已签发本连接会话授权(限时、可撤销)。');
|
|
1836
|
+
return { ok: true, grant: answer.grant };
|
|
1837
|
+
} catch (error) {
|
|
1838
|
+
notify('error', describeError(error));
|
|
1839
|
+
return { ok: false, error };
|
|
1840
|
+
}
|
|
1841
|
+
});
|
|
1842
|
+
},
|
|
1843
|
+
|
|
1844
|
+
/**
|
|
1845
|
+
* Revoke one grant.
|
|
1846
|
+
* @param {string} grantId - grant identity.
|
|
1847
|
+
*/
|
|
1848
|
+
async revokeGrant(grantId) {
|
|
1849
|
+
return await track('revokeGrant', async () => {
|
|
1850
|
+
try {
|
|
1851
|
+
await api.revokeGrant(grantId);
|
|
1852
|
+
if (state.selectedConnectionId !== null) await store.loadGrants(state.selectedConnectionId);
|
|
1853
|
+
await store.refreshStatus();
|
|
1854
|
+
notify('success', '已撤销该授权。');
|
|
1855
|
+
return { ok: true };
|
|
1856
|
+
} catch (error) {
|
|
1857
|
+
notify('error', describeError(error));
|
|
1858
|
+
return { ok: false, error };
|
|
1859
|
+
}
|
|
1860
|
+
});
|
|
1861
|
+
},
|
|
1862
|
+
|
|
1863
|
+
/**
|
|
1864
|
+
* Apply an edit to the draft.
|
|
1865
|
+
* @param {(draft: object) => void} mutate - edits the cloned draft in place.
|
|
1866
|
+
*/
|
|
1867
|
+
editDraft(mutate) {
|
|
1868
|
+
const draft = clone(state.draft ?? defaultDraft());
|
|
1869
|
+
mutate(draft);
|
|
1870
|
+
patch({ draft, dirty: true });
|
|
1871
|
+
},
|
|
1872
|
+
|
|
1873
|
+
/** Discard uncommitted edits. */
|
|
1874
|
+
resetDraft() {
|
|
1875
|
+
patch({ draft: draftFromSettings(state.settings), dirty: false });
|
|
1876
|
+
},
|
|
1877
|
+
|
|
1878
|
+
/**
|
|
1879
|
+
* Validate the draft locally, then replace the stored document.
|
|
1880
|
+
* @returns {Promise<{ ok: boolean, error?: unknown }>} outcome.
|
|
1881
|
+
*/
|
|
1882
|
+
async saveSettings() {
|
|
1883
|
+
if (state.draft === null) return { ok: false };
|
|
1884
|
+
const problems = precheckDraft(state.draft);
|
|
1885
|
+
if (problems.length > 0) {
|
|
1886
|
+
notify('error', `未保存:${problems.slice(0, 4).join(';')}`);
|
|
1887
|
+
return { ok: false, problems };
|
|
1888
|
+
}
|
|
1889
|
+
return await track('save', async () => {
|
|
1890
|
+
try {
|
|
1891
|
+
const body = await api.putSettings(documentFromDraft(state.draft));
|
|
1892
|
+
patch({ settings: body.settings ?? null, draft: draftFromSettings(body.settings), dirty: false });
|
|
1893
|
+
notify('success', '设置已保存。');
|
|
1894
|
+
return { ok: true };
|
|
1895
|
+
} catch (error) {
|
|
1896
|
+
notify('error', describeError(error));
|
|
1897
|
+
return { ok: false, error };
|
|
1898
|
+
}
|
|
1899
|
+
});
|
|
1900
|
+
},
|
|
1901
|
+
|
|
1902
|
+
/**
|
|
1903
|
+
* Discover one provider's models from its own API, then keep the result.
|
|
1904
|
+
*
|
|
1905
|
+
* This is remote discovery, not a catalog read: the host calls the provider's
|
|
1906
|
+
* configured endpoint with that provider's credential reference. Consequences
|
|
1907
|
+
* this function has to honour:
|
|
1908
|
+
*
|
|
1909
|
+
* * an empty list plus a `discovery` diagnosis is a *failure*, not "the
|
|
1910
|
+
* provider serves nothing", so it is reported as one and no merge is
|
|
1911
|
+
* attempted;
|
|
1912
|
+
* * discovery never returns capabilities. New ids arrive with `efforts: []`,
|
|
1913
|
+
* so the operator still has to declare what a model supports;
|
|
1914
|
+
* * a host that predates the route (a carrier 404) gets the old fallback,
|
|
1915
|
+
* which is then labelled honestly as a catalog read rather than as
|
|
1916
|
+
* discovery.
|
|
1917
|
+
* @param {string} providerId - provider id.
|
|
1918
|
+
*/
|
|
1919
|
+
async fetchModels(providerId) {
|
|
1920
|
+
patch({ loading: { ...state.loading, [`models:${providerId}`]: true } });
|
|
1921
|
+
try {
|
|
1922
|
+
let models = [];
|
|
1923
|
+
let source = 'remote';
|
|
1924
|
+
let providerError = null;
|
|
1925
|
+
let discovery = null;
|
|
1926
|
+
try {
|
|
1927
|
+
const body = await api.fetchModels(providerId);
|
|
1928
|
+
models = Array.isArray(body.models) ? body.models : [];
|
|
1929
|
+
providerError = body.error ?? null;
|
|
1930
|
+
discovery = body.discovery ?? null;
|
|
1931
|
+
source = typeof body.source === 'string' ? body.source : 'remote';
|
|
1932
|
+
} catch (error) {
|
|
1933
|
+
// Only a carrier-level 404 means "this host does not serve the route".
|
|
1934
|
+
// Our own handler answers 404 with a JSON `PROVIDER_UNKNOWN` code, and
|
|
1935
|
+
// that is a real refusal to report, not a reason to fall back.
|
|
1936
|
+
const routeMissing = error?.code === 'HTTP_404' || error?.code === 'USER_PLANE_UNKNOWN_ROUTE';
|
|
1937
|
+
if (!routeMissing) throw error;
|
|
1938
|
+
const body = await api.getCatalog({});
|
|
1939
|
+
const entry = (body.catalog ?? []).find((candidate) => candidate.providerId === providerId);
|
|
1940
|
+
models = Array.isArray(entry?.models) ? entry.models : [];
|
|
1941
|
+
providerError = entry?.error ?? null;
|
|
1942
|
+
source = 'catalog';
|
|
1943
|
+
discovery = {
|
|
1944
|
+
attempted: false,
|
|
1945
|
+
failed: providerError !== null,
|
|
1946
|
+
code: providerError?.code ?? null,
|
|
1947
|
+
message: 'this host does not serve model discovery yet; the configured catalog was read instead',
|
|
1948
|
+
};
|
|
1949
|
+
}
|
|
1950
|
+
const failed = source === 'remote' && discovery?.failed === true;
|
|
1951
|
+
patch({
|
|
1952
|
+
modelCatalog: {
|
|
1953
|
+
...state.modelCatalog,
|
|
1954
|
+
[providerId]: { models, source, error: providerError, discovery, fetchedAt: now() },
|
|
1955
|
+
},
|
|
1956
|
+
});
|
|
1957
|
+
if (source === 'catalog') {
|
|
1958
|
+
notify('info', '宿主尚未提供从提供方获取模型的接口,已改用模型目录结果(不是远程模型列表)。');
|
|
1959
|
+
}
|
|
1960
|
+
if (source === 'remote' && discovery?.failed !== true && providerError !== null) {
|
|
1961
|
+
notify('error', `提供方「${providerId}」无法解析模型:${providerError.message ?? providerError.code ?? ''}`);
|
|
1962
|
+
}
|
|
1963
|
+
if (failed) {
|
|
1964
|
+
notify('error', `从提供方「${providerId}」获取模型失败:${describeError(providerError ?? discovery)}`);
|
|
1965
|
+
return { ok: false, models: [], source, error: providerError };
|
|
1966
|
+
}
|
|
1967
|
+
return { ok: true, models, source, discovery };
|
|
1968
|
+
} catch (error) {
|
|
1969
|
+
patch({
|
|
1970
|
+
modelCatalog: {
|
|
1971
|
+
...state.modelCatalog,
|
|
1972
|
+
[providerId]: {
|
|
1973
|
+
models: [],
|
|
1974
|
+
source: 'error',
|
|
1975
|
+
error: { code: error?.code ?? '', message: describeError(error) },
|
|
1976
|
+
discovery: { attempted: true, failed: true, code: error?.code ?? '' },
|
|
1977
|
+
fetchedAt: now(),
|
|
1978
|
+
},
|
|
1979
|
+
},
|
|
1980
|
+
});
|
|
1981
|
+
notify('error', describeError(error));
|
|
1982
|
+
return { ok: false, error };
|
|
1983
|
+
} finally {
|
|
1984
|
+
if (!disposed) patch({ loading: { ...state.loading, [`models:${providerId}`]: false } });
|
|
1985
|
+
}
|
|
1986
|
+
},
|
|
1987
|
+
|
|
1988
|
+
/**
|
|
1989
|
+
* Merge discovered models into the draft provider, keeping manual-only entries.
|
|
1990
|
+
*
|
|
1991
|
+
* The asymmetry is the point: a model the operator already declared keeps its
|
|
1992
|
+
* declared `efforts` (discovery cannot lend or revoke a capability), a newly
|
|
1993
|
+
* discovered id arrives with no efforts at all, and an id the endpoint did not
|
|
1994
|
+
* list is never removed — a manual entry stays configured.
|
|
1995
|
+
* @param {string} providerId - provider id.
|
|
1996
|
+
* @param {object[]} models - `[{ id, efforts }]`.
|
|
1997
|
+
*/
|
|
1998
|
+
mergeModelsIntoDraft(providerId, models) {
|
|
1999
|
+
store.editDraft((draft) => {
|
|
2000
|
+
const provider = draft.providers.find((entry) => entry.id === providerId);
|
|
2001
|
+
if (provider === undefined) return;
|
|
2002
|
+
for (const model of models) {
|
|
2003
|
+
if (typeof model?.id !== 'string' || model.id === '') continue;
|
|
2004
|
+
const existing = provider.models.find((entry) => entry.id === model.id);
|
|
2005
|
+
if (existing !== undefined) {
|
|
2006
|
+
// Nothing to do: the operator's own declaration wins, and discovery
|
|
2007
|
+
// never returns a capability to fill in.
|
|
2008
|
+
continue;
|
|
2009
|
+
}
|
|
2010
|
+
const served = Array.isArray(model.efforts) ? [...model.efforts] : [];
|
|
2011
|
+
provider.models.push({ id: model.id, efforts: served });
|
|
2012
|
+
}
|
|
2013
|
+
});
|
|
2014
|
+
},
|
|
2015
|
+
|
|
2016
|
+
/**
|
|
2017
|
+
* Read whether one provider's credential is configured.
|
|
2018
|
+
* @param {string} providerId - provider id.
|
|
2019
|
+
*/
|
|
2020
|
+
async credentialStatus(providerId) {
|
|
2021
|
+
patch({ loading: { ...state.loading, [`credential:${providerId}`]: true } });
|
|
2022
|
+
try {
|
|
2023
|
+
const body = await api.credentialStatus(providerId);
|
|
2024
|
+
patch({
|
|
2025
|
+
credentials: {
|
|
2026
|
+
...state.credentials,
|
|
2027
|
+
[providerId]: { ...(body.credential ?? {}), loaded: true },
|
|
2028
|
+
},
|
|
2029
|
+
});
|
|
2030
|
+
return { ok: true, credential: body.credential };
|
|
2031
|
+
} catch (error) {
|
|
2032
|
+
patch({
|
|
2033
|
+
credentials: {
|
|
2034
|
+
...state.credentials,
|
|
2035
|
+
[providerId]: {
|
|
2036
|
+
configured: null,
|
|
2037
|
+
loaded: true,
|
|
2038
|
+
unavailable: true,
|
|
2039
|
+
reason: describeError(error),
|
|
2040
|
+
},
|
|
2041
|
+
},
|
|
2042
|
+
});
|
|
2043
|
+
return { ok: false, error };
|
|
2044
|
+
} finally {
|
|
2045
|
+
if (!disposed) patch({ loading: { ...state.loading, [`credential:${providerId}`]: false } });
|
|
2046
|
+
}
|
|
2047
|
+
},
|
|
2048
|
+
|
|
2049
|
+
/**
|
|
2050
|
+
* Forward a credential value to the host and forget it.
|
|
2051
|
+
* @param {string} providerId - provider id.
|
|
2052
|
+
* @param {string} value - the literal; discarded immediately after the call.
|
|
2053
|
+
*/
|
|
2054
|
+
async setCredential(providerId, value) {
|
|
2055
|
+
const literal = typeof value === 'string' ? value : '';
|
|
2056
|
+
if (literal.trim() === '') {
|
|
2057
|
+
notify('error', describeError(new ApiError('CREDENTIAL_EMPTY', 'no value was entered')));
|
|
2058
|
+
return { ok: false };
|
|
2059
|
+
}
|
|
2060
|
+
return await track(`credential:${providerId}`, async () => {
|
|
2061
|
+
try {
|
|
2062
|
+
const body = await api.setCredential(providerId, literal);
|
|
2063
|
+
patch({
|
|
2064
|
+
credentials: { ...state.credentials, [providerId]: { ...(body.credential ?? {}), loaded: true } },
|
|
2065
|
+
});
|
|
2066
|
+
notify('success', `已保存提供方「${providerId}」的密钥(值不会回显)。`);
|
|
2067
|
+
return { ok: true, credential: body.credential };
|
|
2068
|
+
} catch (error) {
|
|
2069
|
+
// A carrier-level 404 is "this host has no credential route"; a JSON
|
|
2070
|
+
// refusal with its own code is a real answer and is shown as such.
|
|
2071
|
+
notify('error', error?.code === 'HTTP_404' || error?.code === 'USER_PLANE_UNKNOWN_ROUTE'
|
|
2072
|
+
? describeError(new ApiError('CREDENTIAL_SEAM_UNAVAILABLE', 'credential route unavailable'))
|
|
2073
|
+
: describeError(error));
|
|
2074
|
+
return { ok: false, error };
|
|
2075
|
+
}
|
|
2076
|
+
});
|
|
2077
|
+
},
|
|
2078
|
+
|
|
2079
|
+
/**
|
|
2080
|
+
* Remove one provider's stored credential.
|
|
2081
|
+
* @param {string} providerId - provider id.
|
|
2082
|
+
*/
|
|
2083
|
+
async unsetCredential(providerId) {
|
|
2084
|
+
return await track(`credential:${providerId}`, async () => {
|
|
2085
|
+
try {
|
|
2086
|
+
const body = await api.unsetCredential(providerId);
|
|
2087
|
+
patch({
|
|
2088
|
+
credentials: { ...state.credentials, [providerId]: { ...(body.credential ?? {}), loaded: true } },
|
|
2089
|
+
});
|
|
2090
|
+
notify('success', `已清除提供方「${providerId}」的密钥。`);
|
|
2091
|
+
return { ok: true, credential: body.credential };
|
|
2092
|
+
} catch (error) {
|
|
2093
|
+
notify('error', describeError(error));
|
|
2094
|
+
return { ok: false, error };
|
|
2095
|
+
}
|
|
2096
|
+
});
|
|
2097
|
+
},
|
|
2098
|
+
|
|
2099
|
+
/**
|
|
2100
|
+
* Run one provider's layered connectivity check.
|
|
2101
|
+
* @param {object} form - `{ providerId, model, reasoningEffort }`.
|
|
2102
|
+
*/
|
|
2103
|
+
async checkConnectivity(form) {
|
|
2104
|
+
const providerId = String(form?.providerId ?? '');
|
|
2105
|
+
if (providerId === '') {
|
|
2106
|
+
notify('error', '请先选择提供方。');
|
|
2107
|
+
return { ok: false };
|
|
2108
|
+
}
|
|
2109
|
+
return await track(`connectivity:${providerId}`, async () => {
|
|
2110
|
+
try {
|
|
2111
|
+
const body = { providerId };
|
|
2112
|
+
if (typeof form.model === 'string' && form.model !== '') body.model = form.model;
|
|
2113
|
+
if (typeof form.reasoningEffort === 'string' && form.reasoningEffort !== '') body.reasoningEffort = form.reasoningEffort;
|
|
2114
|
+
const answer = await api.checkConnectivity(body);
|
|
2115
|
+
patch({ connectivity: { ...state.connectivity, [providerId]: answer.report ?? null } });
|
|
2116
|
+
return { ok: true, report: answer.report };
|
|
2117
|
+
} catch (error) {
|
|
2118
|
+
patch({ connectivity: { ...state.connectivity, [providerId]: null } });
|
|
2119
|
+
notify('error', describeError(error));
|
|
2120
|
+
return { ok: false, error };
|
|
2121
|
+
}
|
|
2122
|
+
});
|
|
2123
|
+
},
|
|
2124
|
+
|
|
2125
|
+
/**
|
|
2126
|
+
* Read the Codex integration status. Read-only: this is what `init()` calls,
|
|
2127
|
+
* so opening the page never writes to the Codex home.
|
|
2128
|
+
*/
|
|
2129
|
+
async refreshCodexStatus() {
|
|
2130
|
+
return await track('codexStatus', async () => {
|
|
2131
|
+
try {
|
|
2132
|
+
const body = await api.getCodexStatus();
|
|
2133
|
+
patch({ codex: body.codex ?? null, codexError: null });
|
|
2134
|
+
return { ok: true, codex: body.codex ?? null, switch: body.switch ?? null };
|
|
2135
|
+
} catch (error) {
|
|
2136
|
+
// A host that predates this route answers 404: that is "not served
|
|
2137
|
+
// here", not "Codex is not installed", so it is shown as unavailable.
|
|
2138
|
+
const unavailable = error?.code === 'HTTP_404' || error?.code === 'USER_PLANE_UNKNOWN_ROUTE';
|
|
2139
|
+
patch({
|
|
2140
|
+
codex: null,
|
|
2141
|
+
codexError: unavailable
|
|
2142
|
+
? '当前宿主未提供 Codex 集成接口(插件版本可能较旧)。'
|
|
2143
|
+
: describeError(error),
|
|
2144
|
+
});
|
|
2145
|
+
return { ok: false, error };
|
|
2146
|
+
}
|
|
2147
|
+
});
|
|
2148
|
+
},
|
|
2149
|
+
|
|
2150
|
+
/**
|
|
2151
|
+
* Perform one explicit Codex action and keep its outcome.
|
|
2152
|
+
*
|
|
2153
|
+
* This is only reachable from a button click: nothing calls it from `init()`,
|
|
2154
|
+
* from `saveSettings()` or from a render pass. Installed files are therefore
|
|
2155
|
+
* always the result of an operator decision.
|
|
2156
|
+
* @param {'install'|'repair'|'remove'} action - action to perform.
|
|
2157
|
+
*/
|
|
2158
|
+
async runCodexAction(action) {
|
|
2159
|
+
if (!CODEX_ACTIONS.includes(action)) {
|
|
2160
|
+
notify('error', `未知的 Codex 操作:${String(action)}`);
|
|
2161
|
+
return { ok: false };
|
|
2162
|
+
}
|
|
2163
|
+
return await track('codexAction', async () => {
|
|
2164
|
+
try {
|
|
2165
|
+
const body = await api.runCodexAction(action);
|
|
2166
|
+
const outcome = {
|
|
2167
|
+
action: body.action ?? action,
|
|
2168
|
+
changed: Array.isArray(body.changed) ? body.changed : [],
|
|
2169
|
+
refused: Array.isArray(body.refused) ? body.refused : [],
|
|
2170
|
+
};
|
|
2171
|
+
const codex = body.codex ?? state.codex;
|
|
2172
|
+
patch({ codex, codexError: null, codexOutcome: outcome });
|
|
2173
|
+
const summary = describeCodexOutcome(outcome);
|
|
2174
|
+
const failed = outcome.refused.length > 0;
|
|
2175
|
+
notify(failed ? 'error' : 'success', summary === '' ? '操作完成。' : summary);
|
|
2176
|
+
return { ok: !failed, outcome, codex };
|
|
2177
|
+
} catch (error) {
|
|
2178
|
+
patch({ codexOutcome: null });
|
|
2179
|
+
notify('error', describeError(error));
|
|
2180
|
+
return { ok: false, error };
|
|
2181
|
+
}
|
|
2182
|
+
});
|
|
2183
|
+
},
|
|
2184
|
+
|
|
2185
|
+
/**
|
|
2186
|
+
* Replace only the two silence thresholds.
|
|
2187
|
+
*
|
|
2188
|
+
* The narrow route exists so an operator adjusting a timer cannot rewrite a
|
|
2189
|
+
* provider list. On success the committed document is adopted for `settings` and
|
|
2190
|
+
* the draft's monitoring block, and OTHER unsaved draft edits are left alone —
|
|
2191
|
+
* a timer save must never discard a half-finished provider edit.
|
|
2192
|
+
* @param {{ selfCheckSeconds: number, attentionSeconds: number }} monitoring - already-validated block.
|
|
2193
|
+
* @returns {Promise<{ ok: boolean, error?: unknown }>} outcome.
|
|
2194
|
+
*/
|
|
2195
|
+
async saveMonitoring(monitoring) {
|
|
2196
|
+
const normalized = monitoringOf({ monitoring });
|
|
2197
|
+
const problems = precheckMonitoring(normalized);
|
|
2198
|
+
if (problems.length > 0) {
|
|
2199
|
+
notify('error', `未保存:${problems.join(';')}`);
|
|
2200
|
+
return { ok: false, problems };
|
|
2201
|
+
}
|
|
2202
|
+
return await track('monitoring', async () => {
|
|
2203
|
+
try {
|
|
2204
|
+
const body = await api.putMonitoring(normalized);
|
|
2205
|
+
const committed = body.settings ?? null;
|
|
2206
|
+
const draft = state.draft === null
|
|
2207
|
+
? draftFromSettings(committed)
|
|
2208
|
+
: { ...state.draft, monitoring: monitoringOf(committed ?? { monitoring: normalized }) };
|
|
2209
|
+
patch({ settings: committed, draft });
|
|
2210
|
+
notify('success', '监控间隔已保存。已开始运行的任务保留它自己的快照,新任务使用新值。');
|
|
2211
|
+
return { ok: true, monitoring: body.monitoring ?? normalized };
|
|
2212
|
+
} catch (error) {
|
|
2213
|
+
notify('error', describeError(error));
|
|
2214
|
+
return { ok: false, error };
|
|
2215
|
+
}
|
|
2216
|
+
});
|
|
2217
|
+
},
|
|
2218
|
+
|
|
2219
|
+
/**
|
|
2220
|
+
* Refresh the task list without operator-facing noise.
|
|
2221
|
+
*
|
|
2222
|
+
* Used by the bounded auto-refresh only. It differs from {@link store.loadTasks}
|
|
2223
|
+
* in three ways that matter for a background read: it never notifies on failure
|
|
2224
|
+
* (a transient blip must not spam the page), it never clears a previously loaded
|
|
2225
|
+
* list on error, and it is a pure read — no model call, no task action — so a
|
|
2226
|
+
* visible page cannot cause work by being visible.
|
|
2227
|
+
* @param {string} [reason] - `auto` for the timer, `manual` for an explicit click.
|
|
2228
|
+
* @returns {Promise<{ ok: boolean, tasks?: object[] }>} outcome.
|
|
2229
|
+
*/
|
|
2230
|
+
async refreshTasks(reason = 'auto') {
|
|
2231
|
+
if (state.loading?.tasks === true) return { ok: false, skipped: 'in-flight' };
|
|
2232
|
+
patch({ loading: { ...state.loading, tasks: true } });
|
|
2233
|
+
try {
|
|
2234
|
+
const body = await api.listTasks();
|
|
2235
|
+
const tasks = Array.isArray(body.tasks) ? body.tasks : [];
|
|
2236
|
+
// The selected detail is refreshed from the SAME list snapshot rather than a
|
|
2237
|
+
// second request, so the panel never shows a detail older than its row, and
|
|
2238
|
+
// the operator's selection is never changed by a background read.
|
|
2239
|
+
const detail = state.taskDetail === null
|
|
2240
|
+
? null
|
|
2241
|
+
: tasks.find((task) => task.taskId === state.taskDetail.taskId) ?? state.taskDetail;
|
|
2242
|
+
patch({ tasks, taskDetail: detail });
|
|
2243
|
+
return { ok: true, tasks, reason };
|
|
2244
|
+
} catch (error) {
|
|
2245
|
+
if (reason === 'manual') notify('error', describeError(error));
|
|
2246
|
+
return { ok: false, error };
|
|
2247
|
+
} finally {
|
|
2248
|
+
if (!disposed) patch({ loading: { ...state.loading, tasks: false } });
|
|
2249
|
+
}
|
|
2250
|
+
},
|
|
2251
|
+
|
|
2252
|
+
/** Read the task list. */
|
|
2253
|
+
async loadTasks() {
|
|
2254
|
+
return await track('tasks', async () => {
|
|
2255
|
+
try {
|
|
2256
|
+
const body = await api.listTasks();
|
|
2257
|
+
patch({ tasks: Array.isArray(body.tasks) ? body.tasks : [] });
|
|
2258
|
+
return { ok: true, tasks: body.tasks ?? [] };
|
|
2259
|
+
} catch (error) {
|
|
2260
|
+
notify('error', describeError(error));
|
|
2261
|
+
return { ok: false, error };
|
|
2262
|
+
}
|
|
2263
|
+
});
|
|
2264
|
+
},
|
|
2265
|
+
|
|
2266
|
+
/**
|
|
2267
|
+
* Read one task with its prompt and evidence.
|
|
2268
|
+
* @param {string} taskId - task identity.
|
|
2269
|
+
*/
|
|
2270
|
+
async openTask(taskId) {
|
|
2271
|
+
return await track('taskDetail', async () => {
|
|
2272
|
+
try {
|
|
2273
|
+
const body = await api.getTask(taskId);
|
|
2274
|
+
patch({ taskDetail: body.task ?? null });
|
|
2275
|
+
return { ok: true, task: body.task };
|
|
2276
|
+
} catch (error) {
|
|
2277
|
+
notify('error', describeError(error));
|
|
2278
|
+
return { ok: false, error };
|
|
2279
|
+
}
|
|
2280
|
+
});
|
|
2281
|
+
},
|
|
2282
|
+
|
|
2283
|
+
/**
|
|
2284
|
+
* Cancel one task as the operator.
|
|
2285
|
+
* @param {string} taskId - task identity.
|
|
2286
|
+
*/
|
|
2287
|
+
async cancelTask(taskId) {
|
|
2288
|
+
return await track('cancelTask', async () => {
|
|
2289
|
+
try {
|
|
2290
|
+
const body = await api.cancelTask(taskId);
|
|
2291
|
+
patch({
|
|
2292
|
+
tasks: state.tasks.map((task) => (task.taskId === taskId ? { ...task, ...body.task } : task)),
|
|
2293
|
+
taskDetail: state.taskDetail?.taskId === taskId ? { ...state.taskDetail, ...body.task } : state.taskDetail,
|
|
2294
|
+
});
|
|
2295
|
+
notify('success', '已请求取消。');
|
|
2296
|
+
return { ok: true, task: body.task };
|
|
2297
|
+
} catch (error) {
|
|
2298
|
+
notify('error', describeError(error));
|
|
2299
|
+
return { ok: false, error };
|
|
2300
|
+
}
|
|
2301
|
+
});
|
|
2302
|
+
},
|
|
2303
|
+
|
|
2304
|
+
/** Load everything the page needs; the catalog is loaded but not awaited. */
|
|
2305
|
+
async init() {
|
|
2306
|
+
await Promise.all([store.refreshStatus(), store.loadSettings(), store.loadNativeProviders(), store.loadTasks()]);
|
|
2307
|
+
// Diagnostic read only. `init` must never perform a Codex write: installing
|
|
2308
|
+
// files is an explicit operator action, not a side effect of opening a page.
|
|
2309
|
+
void store.refreshCodexStatus();
|
|
2310
|
+
void store.loadCatalog();
|
|
2311
|
+
},
|
|
2312
|
+
|
|
2313
|
+
/** Release subscriptions and drop the one-time token. */
|
|
2314
|
+
dispose() {
|
|
2315
|
+
disposed = true;
|
|
2316
|
+
state = { ...state, token: null, tokenConnectionId: null };
|
|
2317
|
+
listeners.clear();
|
|
2318
|
+
},
|
|
2319
|
+
};
|
|
2320
|
+
|
|
2321
|
+
return store;
|
|
2322
|
+
}
|