@saturn-universe/runtime-host 0.0.0-stage → 0.1.1
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/LICENSE +661 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
- package/dist/command-dispatch.d.ts +10 -0
- package/dist/command-dispatch.js +65 -0
- package/dist/completion-judge.d.ts +10 -0
- package/dist/completion-judge.js +156 -0
- package/dist/composition.d.ts +108 -0
- package/dist/composition.js +1180 -0
- package/dist/configuration.d.ts +49 -0
- package/dist/configuration.js +51 -0
- package/dist/context-extensions.d.ts +681 -0
- package/dist/context-extensions.js +289 -0
- package/dist/cordis/context-core-plugin.d.ts +35 -0
- package/dist/cordis/context-core-plugin.js +296 -0
- package/dist/cordis/env-probe-plugin.d.ts +27 -0
- package/dist/cordis/env-probe-plugin.js +114 -0
- package/dist/cordis/host-context.d.ts +65 -0
- package/dist/cordis/host-context.js +199 -0
- package/dist/cordis/model-responses-plugin.d.ts +81 -0
- package/dist/cordis/model-responses-plugin.js +209 -0
- package/dist/cordis/plugin-contributions.d.ts +47 -0
- package/dist/cordis/plugin-contributions.js +119 -0
- package/dist/cordis/plugin-lifecycle.d.ts +57 -0
- package/dist/cordis/plugin-lifecycle.js +222 -0
- package/dist/cordis/plugin-loader.d.ts +18 -0
- package/dist/cordis/plugin-loader.js +310 -0
- package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
- package/dist/cordis/plugin-sdk-adapter.js +283 -0
- package/dist/cordis/required-host-plugin.d.ts +6 -0
- package/dist/cordis/required-host-plugin.js +1 -0
- package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
- package/dist/cordis/runtime-hooks-plugin.js +103 -0
- package/dist/cordis/sandbox-plugin.d.ts +18 -0
- package/dist/cordis/sandbox-plugin.js +21 -0
- package/dist/cordis/scoped-layers.d.ts +63 -0
- package/dist/cordis/scoped-layers.js +170 -0
- package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
- package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
- package/dist/cordis/tools/index.d.ts +17 -0
- package/dist/cordis/tools/index.js +40 -0
- package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
- package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
- package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
- package/dist/cordis/tools/process-manager-plugin.js +39 -0
- package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
- package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
- package/dist/cordis/tools/tool-guidance.d.ts +4 -0
- package/dist/cordis/tools/tool-guidance.js +30 -0
- package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
- package/dist/cordis/tools/tools-core-plugin.js +486 -0
- package/dist/cordis/tools/web-fetch.d.ts +17 -0
- package/dist/cordis/tools/web-fetch.js +529 -0
- package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
- package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
- package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
- package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
- package/dist/env-probe.d.ts +8 -0
- package/dist/env-probe.js +172 -0
- package/dist/host-configuration.d.ts +27 -0
- package/dist/host-configuration.js +185 -0
- package/dist/host-tools.d.ts +19 -0
- package/dist/host-tools.js +30 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +140 -0
- package/dist/ipc.d.ts +24 -0
- package/dist/ipc.js +162 -0
- package/dist/logger.d.ts +11 -0
- package/dist/logger.js +84 -0
- package/dist/mcp-configuration.d.ts +17 -0
- package/dist/mcp-configuration.js +50 -0
- package/dist/modes.d.ts +27 -0
- package/dist/modes.js +478 -0
- package/dist/ownership.d.ts +7 -0
- package/dist/ownership.js +100 -0
- package/dist/plugin-configuration.d.ts +9 -0
- package/dist/plugin-configuration.js +21 -0
- package/dist/plugin-tool-grants.d.ts +18 -0
- package/dist/plugin-tool-grants.js +21 -0
- package/dist/process-workspaces.d.ts +4 -0
- package/dist/process-workspaces.js +28 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +699 -0
- package/dist/provider-catalog.d.ts +754 -0
- package/dist/provider-catalog.js +472 -0
- package/dist/run-budget.d.ts +24 -0
- package/dist/run-budget.js +47 -0
- package/dist/run-checkpoint.d.ts +2 -0
- package/dist/run-checkpoint.js +52 -0
- package/dist/sandbox-manager.d.ts +111 -0
- package/dist/sandbox-manager.js +1519 -0
- package/dist/session-paths.d.ts +15 -0
- package/dist/session-paths.js +40 -0
- package/dist/side-question.d.ts +14 -0
- package/dist/side-question.js +89 -0
- package/dist/skills-runtime.d.ts +13 -0
- package/dist/skills-runtime.js +243 -0
- package/dist/token-estimator.d.ts +3 -0
- package/dist/token-estimator.js +73 -0
- package/dist/tool-result.d.ts +2 -0
- package/dist/tool-result.js +91 -0
- package/dist/user-config.d.ts +23 -0
- package/dist/user-config.js +36 -0
- package/package.json +28 -3
- package/README.md +0 -3
|
@@ -0,0 +1,1473 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { access, readdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createLedgerController } from './src/ledger.mjs';
|
|
5
|
+
import {
|
|
6
|
+
atomicWrite,
|
|
7
|
+
checkFile,
|
|
8
|
+
createBoard,
|
|
9
|
+
fail,
|
|
10
|
+
safeSegment,
|
|
11
|
+
scanWorkspace,
|
|
12
|
+
STATUSES,
|
|
13
|
+
} from './src/board.mjs';
|
|
14
|
+
import {
|
|
15
|
+
createInstanceLeaseManager,
|
|
16
|
+
isContainerAlreadyGoneError,
|
|
17
|
+
platformAdapter,
|
|
18
|
+
resolveRemoteChallengeId,
|
|
19
|
+
syncPlatform,
|
|
20
|
+
} from './src/platform/index.mjs';
|
|
21
|
+
import { createBoardService } from './src/server.mjs';
|
|
22
|
+
|
|
23
|
+
const source = { kind: 'plugin', sourceId: 'ctf' };
|
|
24
|
+
const string = { type: 'string', minLength: 1, maxLength: 4096 };
|
|
25
|
+
const count = { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER };
|
|
26
|
+
const strings = { type: 'array', maxItems: 128, uniqueItems: true, items: string };
|
|
27
|
+
const challengeId = { ...string, maxLength: 180 };
|
|
28
|
+
const date = { ...string, maxLength: 64 };
|
|
29
|
+
const schema = (properties, required = []) => ({
|
|
30
|
+
type: 'object',
|
|
31
|
+
additionalProperties: false,
|
|
32
|
+
properties,
|
|
33
|
+
required,
|
|
34
|
+
});
|
|
35
|
+
const mainScope = { scope: { kind: 'role', roles: ['main'] } };
|
|
36
|
+
const good = (data, effect = 'none') => ({
|
|
37
|
+
effect,
|
|
38
|
+
outcome: { status: 'success', content: [{ type: 'text', text: JSON.stringify(data) }], data },
|
|
39
|
+
});
|
|
40
|
+
const bad = (error) => ({
|
|
41
|
+
effect: 'none',
|
|
42
|
+
outcome: {
|
|
43
|
+
status: 'error',
|
|
44
|
+
error: {
|
|
45
|
+
code: typeof error.code === 'string' ? error.code : 'CTF_OPERATION_FAILED',
|
|
46
|
+
message: error.message,
|
|
47
|
+
retryable: false,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
function settingsFor(input) {
|
|
53
|
+
const values = {
|
|
54
|
+
maxActiveChallenges: input.max_active_challenges ?? 3,
|
|
55
|
+
maxHelpersPerChallenge: input.max_helpers_per_challenge ?? 2,
|
|
56
|
+
boardPort: input.board_port ?? 0,
|
|
57
|
+
submitMinIntervalMs: input.submit_min_interval_ms ?? 5_000,
|
|
58
|
+
maxRemoteInstances: input.max_remote_instances ?? 1,
|
|
59
|
+
instanceCooldownMs: input.instance_cooldown_ms ?? 30_000,
|
|
60
|
+
coordinatorPollIntervalMs: input.coordinator_poll_interval_ms ?? 600_000,
|
|
61
|
+
};
|
|
62
|
+
for (const [key, value] of Object.entries(values)) {
|
|
63
|
+
const allowingZero =
|
|
64
|
+
key === 'boardPort' ||
|
|
65
|
+
key === 'maxHelpersPerChallenge' ||
|
|
66
|
+
key === 'submitMinIntervalMs' ||
|
|
67
|
+
key === 'instanceCooldownMs' ||
|
|
68
|
+
key === 'coordinatorPollIntervalMs';
|
|
69
|
+
if (
|
|
70
|
+
!Number.isSafeInteger(value) ||
|
|
71
|
+
value < (allowingZero ? 0 : 1) ||
|
|
72
|
+
(key === 'boardPort' && value > 65535) ||
|
|
73
|
+
(key === 'maxRemoteInstances' && value > 16)
|
|
74
|
+
)
|
|
75
|
+
throw new Error(`Invalid ctf@1 setting: ${key}`);
|
|
76
|
+
}
|
|
77
|
+
const rawPerChallengeWall = input.per_challenge_wall_time_ms;
|
|
78
|
+
let perChallengeWallTimeMs;
|
|
79
|
+
if (
|
|
80
|
+
rawPerChallengeWall !== undefined &&
|
|
81
|
+
rawPerChallengeWall !== null &&
|
|
82
|
+
rawPerChallengeWall !== 'unlimited' &&
|
|
83
|
+
rawPerChallengeWall !== 0
|
|
84
|
+
) {
|
|
85
|
+
if (!Number.isSafeInteger(rawPerChallengeWall) || rawPerChallengeWall < 1) {
|
|
86
|
+
throw new Error('Invalid ctf@1 setting: perChallengeWallTimeMs');
|
|
87
|
+
}
|
|
88
|
+
perChallengeWallTimeMs = rawPerChallengeWall;
|
|
89
|
+
}
|
|
90
|
+
const autoSubmit = input.auto_submit ?? false;
|
|
91
|
+
if (typeof autoSubmit !== 'boolean') throw new Error('Invalid ctf@1 setting: auto_submit');
|
|
92
|
+
const autoStopOnSolve = input.auto_stop_on_solve ?? true;
|
|
93
|
+
if (typeof autoStopOnSolve !== 'boolean') throw new Error('Invalid ctf@1 setting: auto_stop_on_solve');
|
|
94
|
+
let boardToken;
|
|
95
|
+
if (input.board_token !== undefined) {
|
|
96
|
+
if (
|
|
97
|
+
typeof input.board_token !== 'string' ||
|
|
98
|
+
!input.board_token ||
|
|
99
|
+
/[\0\r\n;\s]/u.test(input.board_token)
|
|
100
|
+
) {
|
|
101
|
+
throw new Error('Invalid ctf@1 setting: board_token');
|
|
102
|
+
}
|
|
103
|
+
boardToken = input.board_token;
|
|
104
|
+
}
|
|
105
|
+
let boardPublicHost;
|
|
106
|
+
if (input.board_public_host !== undefined) {
|
|
107
|
+
if (
|
|
108
|
+
typeof input.board_public_host !== 'string' ||
|
|
109
|
+
!input.board_public_host.trim() ||
|
|
110
|
+
/[\0\r\n\s/?#@]/u.test(input.board_public_host.trim())
|
|
111
|
+
) {
|
|
112
|
+
throw new Error('Invalid ctf@1 setting: board_public_host');
|
|
113
|
+
}
|
|
114
|
+
const candidate = input.board_public_host.trim();
|
|
115
|
+
let parsed;
|
|
116
|
+
try {
|
|
117
|
+
parsed = new URL(`http://${candidate}`);
|
|
118
|
+
} catch {
|
|
119
|
+
throw new Error('Invalid ctf@1 setting: board_public_host');
|
|
120
|
+
}
|
|
121
|
+
if (
|
|
122
|
+
!parsed.host ||
|
|
123
|
+
parsed.host.toLowerCase() !== candidate.toLowerCase() ||
|
|
124
|
+
parsed.pathname !== '/' ||
|
|
125
|
+
parsed.username ||
|
|
126
|
+
parsed.password
|
|
127
|
+
) {
|
|
128
|
+
throw new Error('Invalid ctf@1 setting: board_public_host');
|
|
129
|
+
}
|
|
130
|
+
boardPublicHost = parsed.host.toLowerCase();
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
...values,
|
|
134
|
+
...(perChallengeWallTimeMs !== undefined ? { perChallengeWallTimeMs } : {}),
|
|
135
|
+
autoSubmit,
|
|
136
|
+
autoStopOnSolve,
|
|
137
|
+
...(boardToken ? { boardToken } : {}),
|
|
138
|
+
...(boardPublicHost ? { boardPublicHost } : {}),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function normalizeMetadata(patch) {
|
|
143
|
+
for (const key of ['startTime', 'endTime']) {
|
|
144
|
+
if (patch[key] === undefined) continue;
|
|
145
|
+
if (
|
|
146
|
+
!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/iu.test(patch[key]) ||
|
|
147
|
+
!Number.isFinite(Date.parse(patch[key]))
|
|
148
|
+
)
|
|
149
|
+
throw fail('INVALID_INPUT', 'Board times must use ISO 8601 with a timezone.');
|
|
150
|
+
patch[key] = new Date(patch[key]).toISOString();
|
|
151
|
+
}
|
|
152
|
+
return patch;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function normalizeCategorySet(categories) {
|
|
156
|
+
if (!Array.isArray(categories) || categories.length === 0) return undefined;
|
|
157
|
+
const set = new Set(categories.map((cat) => String(cat).trim().toLowerCase()).filter(Boolean));
|
|
158
|
+
return set.size > 0 ? set : undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function matchesScopeFilters(item, categorySet, idSet) {
|
|
162
|
+
const catOk =
|
|
163
|
+
!categorySet ||
|
|
164
|
+
[item.category, ...(Array.isArray(item.tags) ? item.tags : [])].some(
|
|
165
|
+
(value) => typeof value === 'string' && value.trim() && categorySet.has(value.trim().toLowerCase()),
|
|
166
|
+
);
|
|
167
|
+
const idOk =
|
|
168
|
+
!idSet || idSet.has(item.id) || (item.remoteId !== undefined && idSet.has(String(item.remoteId)));
|
|
169
|
+
return catOk && idOk;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export default {
|
|
173
|
+
id: 'ctf',
|
|
174
|
+
version: '0.1.1',
|
|
175
|
+
kind: 'saturn-registrar',
|
|
176
|
+
apiVersion: 1,
|
|
177
|
+
sdkVersion: '0.1.1',
|
|
178
|
+
async setup(api, config = {}) {
|
|
179
|
+
const { boardToken, boardPublicHost, ...boardSettings } = settingsFor(config);
|
|
180
|
+
if (boardToken) api.registerSecret?.(boardToken);
|
|
181
|
+
const redact = api.redactValue ?? ((value) => value);
|
|
182
|
+
const settings = boardSettings;
|
|
183
|
+
const sessions = new Map();
|
|
184
|
+
const pendingSessions = new Map();
|
|
185
|
+
const leasePools = new Map();
|
|
186
|
+
const sessionPlatformQueues = new Map();
|
|
187
|
+
const leasePoolQueues = new Map();
|
|
188
|
+
let lastActiveSessionId;
|
|
189
|
+
|
|
190
|
+
const ledgerSanitizeRecord = (record) => {
|
|
191
|
+
const entries = Object.entries(record).map(([key, value]) =>
|
|
192
|
+
['summary', 'evidence', 'title', 'authorRole', 'outcome', 'transition'].includes(key)
|
|
193
|
+
? [key, redact(value)]
|
|
194
|
+
: [key, value],
|
|
195
|
+
);
|
|
196
|
+
return Object.fromEntries(entries);
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
function normalizeSessionId(raw) {
|
|
200
|
+
if (typeof raw !== 'string') return 'default';
|
|
201
|
+
const trimmed = raw.trim();
|
|
202
|
+
return trimmed && trimmed !== 'legacy' ? trimmed : 'default';
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function createSessionBoard(sessionId) {
|
|
206
|
+
if (sessionId !== 'default' && api.resolveSessionPaths) {
|
|
207
|
+
const paths = api.resolveSessionPaths(sessionId);
|
|
208
|
+
return createBoard(api.workspaceRoot, boardSettings, redact, {
|
|
209
|
+
stateDir: paths.pluginDataDir,
|
|
210
|
+
assetsRoot: paths.assetsDir,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return createBoard(api.workspaceRoot, boardSettings, redact);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function getSession(rawSessionId) {
|
|
217
|
+
const sessionId = normalizeSessionId(rawSessionId);
|
|
218
|
+
if (sessionId !== 'default') lastActiveSessionId = sessionId;
|
|
219
|
+
const existing = sessions.get(sessionId);
|
|
220
|
+
if (existing) return existing;
|
|
221
|
+
const pending = pendingSessions.get(sessionId);
|
|
222
|
+
if (pending) return pending;
|
|
223
|
+
|
|
224
|
+
const task = (async () => {
|
|
225
|
+
const board = await createSessionBoard(sessionId);
|
|
226
|
+
const ledger = createLedgerController({
|
|
227
|
+
workspaceRoot: board.root,
|
|
228
|
+
logger: api.logger,
|
|
229
|
+
ledgerDir: path.join(path.dirname(board.filename), 'ledgers'),
|
|
230
|
+
filenameFor: (id) => `${id}.jsonl`,
|
|
231
|
+
keyFor: safeSegment,
|
|
232
|
+
sanitizeRecord: ledgerSanitizeRecord,
|
|
233
|
+
});
|
|
234
|
+
const ledgerHandlers = new Map();
|
|
235
|
+
ledger.register({
|
|
236
|
+
registerTool(definition, handler) {
|
|
237
|
+
ledgerHandlers.set(definition.name, handler);
|
|
238
|
+
},
|
|
239
|
+
registerContextProvider() {},
|
|
240
|
+
});
|
|
241
|
+
const scope = {
|
|
242
|
+
sessionId,
|
|
243
|
+
board,
|
|
244
|
+
ledger,
|
|
245
|
+
ledgerHandlers,
|
|
246
|
+
connection: undefined,
|
|
247
|
+
wrongAnswers: new Map(),
|
|
248
|
+
lastSubmitAt: undefined,
|
|
249
|
+
};
|
|
250
|
+
sessions.set(sessionId, scope);
|
|
251
|
+
return scope;
|
|
252
|
+
})().finally(() => {
|
|
253
|
+
pendingSessions.delete(sessionId);
|
|
254
|
+
});
|
|
255
|
+
pendingSessions.set(sessionId, task);
|
|
256
|
+
return task;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function leasePoolKey(input) {
|
|
260
|
+
const auth = input.auth ?? {};
|
|
261
|
+
const secretPart = auth.token || auth.cookie || `${auth.username ?? ''}:${auth.password ?? ''}`;
|
|
262
|
+
return createHash('sha256')
|
|
263
|
+
.update(`${input.platform}|${input.baseUrl}|${secretPart}`, 'utf8')
|
|
264
|
+
.digest('hex')
|
|
265
|
+
.slice(0, 16);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function leasePoolFor(input) {
|
|
269
|
+
const fingerprint = leasePoolKey(input);
|
|
270
|
+
let pool = leasePools.get(fingerprint);
|
|
271
|
+
if (!pool) {
|
|
272
|
+
pool = createInstanceLeaseManager({
|
|
273
|
+
maxRemoteInstances: settings.maxRemoteInstances,
|
|
274
|
+
instanceCooldownMs: settings.instanceCooldownMs,
|
|
275
|
+
});
|
|
276
|
+
leasePools.set(fingerprint, pool);
|
|
277
|
+
}
|
|
278
|
+
return pool;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function runQueued(queues, key, operation, signal) {
|
|
282
|
+
if (signal?.aborted) {
|
|
283
|
+
return Promise.reject(
|
|
284
|
+
signal.reason instanceof Error
|
|
285
|
+
? signal.reason
|
|
286
|
+
: Object.assign(new Error('Aborted'), { name: 'AbortError' }),
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
const previous = queues.get(key) ?? Promise.resolve();
|
|
290
|
+
const next = previous.then(() => {
|
|
291
|
+
if (signal?.aborted) {
|
|
292
|
+
throw signal.reason instanceof Error
|
|
293
|
+
? signal.reason
|
|
294
|
+
: Object.assign(new Error('Aborted'), { name: 'AbortError' });
|
|
295
|
+
}
|
|
296
|
+
return operation();
|
|
297
|
+
});
|
|
298
|
+
const tail = next.then(
|
|
299
|
+
() => undefined,
|
|
300
|
+
() => undefined,
|
|
301
|
+
);
|
|
302
|
+
queues.set(key, tail);
|
|
303
|
+
tail.finally(() => {
|
|
304
|
+
if (queues.get(key) === tail) queues.delete(key);
|
|
305
|
+
});
|
|
306
|
+
return next;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async function prepareLedger(session, id) {
|
|
310
|
+
await session.board.ledgerDirectory();
|
|
311
|
+
await checkFile(session.ledger.ledgerPathFor(id));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function readLedger(sessionId, id) {
|
|
315
|
+
const session = await getSession(sessionId);
|
|
316
|
+
await prepareLedger(session, id);
|
|
317
|
+
const state = await session.ledger.loadState(id);
|
|
318
|
+
return redact({ facts: [...state.facts.values()], hypotheses: [...state.hypotheses.values()] });
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function discoverDiskSessionIds() {
|
|
322
|
+
const found = new Set(sessions.keys());
|
|
323
|
+
const sessionsDir = path.join(api.workspaceRoot, '.saturn', 'sessions');
|
|
324
|
+
try {
|
|
325
|
+
for (const entry of await readdir(sessionsDir, { withFileTypes: true })) {
|
|
326
|
+
if (!entry.isDirectory()) continue;
|
|
327
|
+
const boardPath = path.join(sessionsDir, entry.name, 'plugins', 'ctf', 'board.json');
|
|
328
|
+
if (
|
|
329
|
+
await access(boardPath)
|
|
330
|
+
.then(() => true)
|
|
331
|
+
.catch(() => false)
|
|
332
|
+
) {
|
|
333
|
+
found.add(entry.name);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
} catch {
|
|
337
|
+
// No session directory yet.
|
|
338
|
+
}
|
|
339
|
+
const legacyBoardPath = path.join(api.workspaceRoot, '.saturn', 'plugins', 'ctf', 'board.json');
|
|
340
|
+
if (
|
|
341
|
+
await access(legacyBoardPath)
|
|
342
|
+
.then(() => true)
|
|
343
|
+
.catch(() => false)
|
|
344
|
+
) {
|
|
345
|
+
found.add('default');
|
|
346
|
+
}
|
|
347
|
+
if (found.size === 0) found.add('default');
|
|
348
|
+
return [...found];
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const boardProvider = {
|
|
352
|
+
getDefaultSessionId: () =>
|
|
353
|
+
lastActiveSessionId ?? [...sessions.keys()].find((id) => id !== 'default') ?? 'default',
|
|
354
|
+
listSessions: async () => {
|
|
355
|
+
const ids = await discoverDiskSessionIds();
|
|
356
|
+
const summaries = [];
|
|
357
|
+
for (const id of ids) {
|
|
358
|
+
try {
|
|
359
|
+
const scope = await getSession(id);
|
|
360
|
+
const snap = await scope.board.snapshot();
|
|
361
|
+
const total = snap.challenges.length;
|
|
362
|
+
const solved = snap.challenges.filter((c) => c.status === 'solved').length;
|
|
363
|
+
const running = snap.challenges.filter((c) => c.status === 'running').length;
|
|
364
|
+
if (total === 0 && id === 'default' && ids.length > 1) continue;
|
|
365
|
+
summaries.push({
|
|
366
|
+
id,
|
|
367
|
+
title: snap.metadata?.title ?? 'Saturn',
|
|
368
|
+
revision: snap.revision,
|
|
369
|
+
total,
|
|
370
|
+
solved,
|
|
371
|
+
running,
|
|
372
|
+
});
|
|
373
|
+
} catch {
|
|
374
|
+
// Skip unreadable session boards.
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return summaries;
|
|
378
|
+
},
|
|
379
|
+
getBoard: async (requestedSessionId) => {
|
|
380
|
+
let targetId = requestedSessionId ? normalizeSessionId(requestedSessionId) : undefined;
|
|
381
|
+
if (!targetId) {
|
|
382
|
+
const all = await boardProvider.listSessions();
|
|
383
|
+
targetId =
|
|
384
|
+
lastActiveSessionId ?? all.find((entry) => entry.id !== 'default')?.id ?? all[0]?.id ?? 'default';
|
|
385
|
+
}
|
|
386
|
+
const scope = await getSession(targetId);
|
|
387
|
+
return { sessionId: scope.sessionId, board: scope.board };
|
|
388
|
+
},
|
|
389
|
+
readLedger: (sessionId, id) => readLedger(sessionId, id),
|
|
390
|
+
watchRoot: async () => api.workspaceRoot,
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
const service = createBoardService(boardProvider, settings.boardPort, undefined, api.logger, {
|
|
394
|
+
...(boardToken ? { boardToken } : {}),
|
|
395
|
+
...(boardPublicHost ? { boardPublicHost } : {}),
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
async function ensureBoardStarted({ failOnError = false } = {}) {
|
|
399
|
+
try {
|
|
400
|
+
const url = await service.start();
|
|
401
|
+
api.reportStatus?.({ boardUrl: url });
|
|
402
|
+
return url;
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (failOnError) throw error;
|
|
405
|
+
api.logger.error(
|
|
406
|
+
{
|
|
407
|
+
code: 'CTF_BOARD_START_FAILED',
|
|
408
|
+
message: redact(error instanceof Error && error.message ? error.message : 'Board start failed.'),
|
|
409
|
+
},
|
|
410
|
+
'Could not start the CTF board WebUI service',
|
|
411
|
+
);
|
|
412
|
+
return undefined;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function accessible(session, input, context, assignment) {
|
|
417
|
+
const snapshot = await session.board.snapshot();
|
|
418
|
+
assignment ??= await api.resolveWorkspaceAssignment?.(context);
|
|
419
|
+
if (assignment?.role === 'main') {
|
|
420
|
+
if (!input) return snapshot.challenges;
|
|
421
|
+
safeSegment(input);
|
|
422
|
+
const item = snapshot.challenges.find(({ id }) => id === input);
|
|
423
|
+
if (item) return [item];
|
|
424
|
+
throw fail('CHALLENGE_NOT_FOUND', 'Unknown challenge.');
|
|
425
|
+
}
|
|
426
|
+
const workSubpath = assignment?.workSubpath?.trim().replaceAll('\\', '/').replace(/\/+$/, '');
|
|
427
|
+
const assigned =
|
|
428
|
+
workSubpath &&
|
|
429
|
+
snapshot.challenges.find(
|
|
430
|
+
(item) => workSubpath === item.workSubpath || workSubpath.startsWith(item.workSubpath + '/'),
|
|
431
|
+
);
|
|
432
|
+
if (!assigned || (input !== undefined && assigned.id !== input))
|
|
433
|
+
throw fail('CHALLENGE_SCOPE_REQUIRED', 'The calling agent must be bound to the requested challenge.');
|
|
434
|
+
return [assigned];
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function invoke(handler, effect) {
|
|
438
|
+
return {
|
|
439
|
+
async invoke(input, context) {
|
|
440
|
+
try {
|
|
441
|
+
const session = await getSession(context?.sessionId);
|
|
442
|
+
const data = redact(await handler(input, context, session));
|
|
443
|
+
const resolvedEffect =
|
|
444
|
+
typeof effect === 'function' ? effect(data) : effect === 'read' ? 'none' : 'applied';
|
|
445
|
+
return good(data, resolvedEffect);
|
|
446
|
+
} catch (error) {
|
|
447
|
+
if (typeof error.code !== 'string' || /^[A-Z0-9_]+$/u.test(error.code) === false)
|
|
448
|
+
return bad(fail('CTF_OPERATION_FAILED', 'The operation failed.'));
|
|
449
|
+
return bad(fail(error.code, redact(error.message)));
|
|
450
|
+
}
|
|
451
|
+
},
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function register(name, description, inputSchema, effects, handler, options) {
|
|
456
|
+
api.registerTool(
|
|
457
|
+
{
|
|
458
|
+
name,
|
|
459
|
+
description,
|
|
460
|
+
inputSchema,
|
|
461
|
+
effects: effects === 'read' ? 'read' : 'non_idempotent_write',
|
|
462
|
+
source,
|
|
463
|
+
version: '1',
|
|
464
|
+
supportsIdempotencyKey: false,
|
|
465
|
+
supportsReconcile: false,
|
|
466
|
+
concurrency: 'serial_per_run',
|
|
467
|
+
timeoutMs: name.startsWith('ctf_platform_') ? 120_000 : 10_000,
|
|
468
|
+
},
|
|
469
|
+
invoke(handler, effects),
|
|
470
|
+
options,
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Reuse the ledger's validation, ID allocation, append order, and query semantics per session.
|
|
475
|
+
const schemaLedger = createLedgerController({
|
|
476
|
+
workspaceRoot: api.workspaceRoot,
|
|
477
|
+
logger: api.logger,
|
|
478
|
+
filenameFor: (id) => `${id}.jsonl`,
|
|
479
|
+
keyFor: safeSegment,
|
|
480
|
+
});
|
|
481
|
+
schemaLedger.register({
|
|
482
|
+
registerTool(definition) {
|
|
483
|
+
const name = definition.name.replace(/^security_/, 'ctf_');
|
|
484
|
+
api.registerTool(
|
|
485
|
+
{
|
|
486
|
+
...definition,
|
|
487
|
+
name,
|
|
488
|
+
source,
|
|
489
|
+
description: definition.description
|
|
490
|
+
.replaceAll('current Run', 'selected challenge')
|
|
491
|
+
.replaceAll('security_query_ledger', 'ctf_query_ledger'),
|
|
492
|
+
inputSchema: {
|
|
493
|
+
...definition.inputSchema,
|
|
494
|
+
properties: { ...definition.inputSchema.properties, challengeId },
|
|
495
|
+
},
|
|
496
|
+
effects: definition.effects === 'read' ? 'read' : 'non_idempotent_write',
|
|
497
|
+
supportsIdempotencyKey: false,
|
|
498
|
+
},
|
|
499
|
+
{
|
|
500
|
+
async invoke(input, context) {
|
|
501
|
+
try {
|
|
502
|
+
const session = await getSession(context?.sessionId);
|
|
503
|
+
const { challengeId: requested, ...fields } = input;
|
|
504
|
+
const assignment = await api.resolveWorkspaceAssignment?.(context);
|
|
505
|
+
if (!requested && assignment?.role === 'main')
|
|
506
|
+
throw fail('INVALID_INPUT', 'Provide the challengeId for this ledger operation.');
|
|
507
|
+
const [{ id }] = await accessible(session, requested, context, assignment);
|
|
508
|
+
await prepareLedger(session, id);
|
|
509
|
+
const handler = session.ledgerHandlers.get(definition.name);
|
|
510
|
+
const value = await handler.invoke(fields, {
|
|
511
|
+
...context,
|
|
512
|
+
runId: id,
|
|
513
|
+
checkpointSourceRunId: undefined,
|
|
514
|
+
});
|
|
515
|
+
if (value.effect === 'applied') void service.publish(session.sessionId);
|
|
516
|
+
return redact(value);
|
|
517
|
+
} catch (error) {
|
|
518
|
+
return bad(
|
|
519
|
+
fail(error.code ?? 'CTF_LEDGER_FAILED', 'Unable to access the requested challenge ledger.'),
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
},
|
|
523
|
+
},
|
|
524
|
+
);
|
|
525
|
+
},
|
|
526
|
+
registerContextProvider() {},
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
register(
|
|
530
|
+
'ctf_scan_workspace',
|
|
531
|
+
'Index challenge directories, descriptions, and attached files.',
|
|
532
|
+
schema({}),
|
|
533
|
+
'write',
|
|
534
|
+
async (_input, _context, session) => {
|
|
535
|
+
const url = await ensureBoardStarted();
|
|
536
|
+
const scanRoot = session.board.assetsRoot ?? session.board.root;
|
|
537
|
+
const snapshot = await session.board.merge(await scanWorkspace(scanRoot, api.workspaceRoot));
|
|
538
|
+
void service.publish(session.sessionId);
|
|
539
|
+
return { ...snapshot, ...(url ? { url } : {}) };
|
|
540
|
+
},
|
|
541
|
+
mainScope,
|
|
542
|
+
);
|
|
543
|
+
register(
|
|
544
|
+
'ctf_board_init',
|
|
545
|
+
'Set event metadata and open the local task board.',
|
|
546
|
+
schema(
|
|
547
|
+
{
|
|
548
|
+
title: string,
|
|
549
|
+
subtitle: string,
|
|
550
|
+
startTime: date,
|
|
551
|
+
endTime: date,
|
|
552
|
+
categories: strings,
|
|
553
|
+
challengeIds: strings,
|
|
554
|
+
},
|
|
555
|
+
['title'],
|
|
556
|
+
),
|
|
557
|
+
'write',
|
|
558
|
+
async (input, _context, session) => {
|
|
559
|
+
const url = await ensureBoardStarted({ failOnError: true });
|
|
560
|
+
const { challengeIds, ...metadataInput } = input;
|
|
561
|
+
const categorySet = normalizeCategorySet(metadataInput.categories);
|
|
562
|
+
const idSet =
|
|
563
|
+
Array.isArray(challengeIds) && challengeIds.length > 0
|
|
564
|
+
? new Set(challengeIds.map((id) => String(id).trim()).filter(Boolean))
|
|
565
|
+
: undefined;
|
|
566
|
+
const snapshot = await session.board.change((current) => {
|
|
567
|
+
Object.assign(current.metadata, normalizeMetadata({ ...metadataInput }));
|
|
568
|
+
if (Date.parse(current.metadata.startTime) > Date.parse(current.metadata.endTime))
|
|
569
|
+
throw fail('INVALID_INPUT', 'The event cannot end before it starts.');
|
|
570
|
+
if (categorySet || idSet) {
|
|
571
|
+
current.challenges = current.challenges.filter((item) => {
|
|
572
|
+
if (item.status === 'running' || item.status === 'solved') return true;
|
|
573
|
+
return matchesScopeFilters(item, categorySet, idSet);
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
void service.publish(session.sessionId);
|
|
578
|
+
return { url, board: snapshot };
|
|
579
|
+
},
|
|
580
|
+
mainScope,
|
|
581
|
+
);
|
|
582
|
+
register(
|
|
583
|
+
'ctf_board_register',
|
|
584
|
+
'Register external/CLI challenges onto the tracking board so board tools and per-challenge ledgers work without ctf_platform_sync.',
|
|
585
|
+
schema(
|
|
586
|
+
{
|
|
587
|
+
challenges: {
|
|
588
|
+
type: 'array',
|
|
589
|
+
minItems: 1,
|
|
590
|
+
maxItems: 500,
|
|
591
|
+
items: schema(
|
|
592
|
+
{
|
|
593
|
+
id: challengeId,
|
|
594
|
+
title: string,
|
|
595
|
+
workSubpath: { type: 'string', minLength: 1, maxLength: 512 },
|
|
596
|
+
category: string,
|
|
597
|
+
points: count,
|
|
598
|
+
description: { type: 'string', minLength: 1, maxLength: 32768 },
|
|
599
|
+
hasContainer: { type: 'boolean' },
|
|
600
|
+
status: { type: 'string', enum: STATUSES },
|
|
601
|
+
},
|
|
602
|
+
['id', 'title', 'workSubpath'],
|
|
603
|
+
),
|
|
604
|
+
},
|
|
605
|
+
},
|
|
606
|
+
['challenges'],
|
|
607
|
+
),
|
|
608
|
+
'write',
|
|
609
|
+
async (input, _context, session) => {
|
|
610
|
+
const items = [];
|
|
611
|
+
const seen = new Set();
|
|
612
|
+
for (const raw of input.challenges) {
|
|
613
|
+
const id = safeSegment(String(raw.id ?? '').trim());
|
|
614
|
+
if (seen.has(id)) throw fail('INVALID_INPUT', `Duplicate challenge id: ${id}`);
|
|
615
|
+
seen.add(id);
|
|
616
|
+
const title = String(raw.title ?? '').trim();
|
|
617
|
+
if (!title) throw fail('INVALID_INPUT', `Challenge "${id}" requires a non-empty title.`);
|
|
618
|
+
const subpath = String(raw.workSubpath ?? '')
|
|
619
|
+
.trim()
|
|
620
|
+
.replaceAll('\\', '/')
|
|
621
|
+
.replace(/\/+$/, '');
|
|
622
|
+
if (
|
|
623
|
+
!subpath ||
|
|
624
|
+
subpath.startsWith('/') ||
|
|
625
|
+
/^[a-zA-Z]:/u.test(subpath) ||
|
|
626
|
+
subpath.split('/').some((seg) => seg === '.saturn' || /^\.env(?:\..*)?$/iu.test(seg))
|
|
627
|
+
) {
|
|
628
|
+
throw fail('INVALID_PATH', `Invalid workSubpath for challenge "${id}".`);
|
|
629
|
+
}
|
|
630
|
+
for (const seg of subpath.split('/')) safeSegment(seg);
|
|
631
|
+
items.push({
|
|
632
|
+
id,
|
|
633
|
+
title,
|
|
634
|
+
workSubpath: subpath,
|
|
635
|
+
source: 'external',
|
|
636
|
+
...(typeof raw.category === 'string' && raw.category.trim()
|
|
637
|
+
? { category: raw.category.trim() }
|
|
638
|
+
: {}),
|
|
639
|
+
...(raw.points !== undefined ? { points: raw.points } : {}),
|
|
640
|
+
...(typeof raw.description === 'string' && raw.description.trim()
|
|
641
|
+
? { description: raw.description }
|
|
642
|
+
: {}),
|
|
643
|
+
...(raw.hasContainer !== undefined ? { hasContainer: raw.hasContainer } : {}),
|
|
644
|
+
...(raw.status ? { status: raw.status } : {}),
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
const url = await ensureBoardStarted();
|
|
648
|
+
const snapshot = await session.board.merge(items);
|
|
649
|
+
void service.publish(session.sessionId);
|
|
650
|
+
return {
|
|
651
|
+
...(url ? { url } : {}),
|
|
652
|
+
revision: snapshot.revision,
|
|
653
|
+
registered: items.length,
|
|
654
|
+
total: snapshot.challenges.length,
|
|
655
|
+
};
|
|
656
|
+
},
|
|
657
|
+
mainScope,
|
|
658
|
+
);
|
|
659
|
+
register(
|
|
660
|
+
'ctf_board_status',
|
|
661
|
+
'Read challenge progress and available scheduling capacity.',
|
|
662
|
+
schema({
|
|
663
|
+
challengeId,
|
|
664
|
+
category: string,
|
|
665
|
+
status: { type: 'string', enum: STATUSES },
|
|
666
|
+
compact: { type: 'boolean' },
|
|
667
|
+
}),
|
|
668
|
+
'read',
|
|
669
|
+
async (input, context, session) => {
|
|
670
|
+
const accessibleChallenges = await accessible(session, input.challengeId, context);
|
|
671
|
+
const url = await ensureBoardStarted();
|
|
672
|
+
const snapshot = await session.board.snapshot();
|
|
673
|
+
const running = snapshot.challenges.filter((item) => item.status === 'running').length;
|
|
674
|
+
const categoryFilter =
|
|
675
|
+
typeof input.category === 'string' && input.category.trim()
|
|
676
|
+
? input.category.trim().toLowerCase()
|
|
677
|
+
: undefined;
|
|
678
|
+
let filtered = accessibleChallenges;
|
|
679
|
+
if (categoryFilter) {
|
|
680
|
+
filtered = filtered.filter(
|
|
681
|
+
(item) =>
|
|
682
|
+
typeof item.category === 'string' && item.category.trim().toLowerCase() === categoryFilter,
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
if (input.status) {
|
|
686
|
+
filtered = filtered.filter((item) => item.status === input.status);
|
|
687
|
+
}
|
|
688
|
+
const challenges = (
|
|
689
|
+
input.compact === true && !input.challengeId
|
|
690
|
+
? filtered.map(({ description: _description, ...rest }) => rest)
|
|
691
|
+
: filtered
|
|
692
|
+
).map((item) =>
|
|
693
|
+
(item.dispatchCount ?? 0) >= 2 && item.status !== 'solved'
|
|
694
|
+
? { ...item, retryBudgetWarning: true }
|
|
695
|
+
: item,
|
|
696
|
+
);
|
|
697
|
+
const byStatus = { queued: 0, running: 0, solved: 0, blocked: 0 };
|
|
698
|
+
const byCategory = {};
|
|
699
|
+
for (const item of snapshot.challenges) {
|
|
700
|
+
if (item.status && Object.hasOwn(byStatus, item.status)) byStatus[item.status] += 1;
|
|
701
|
+
const cat =
|
|
702
|
+
typeof item.category === 'string' && item.category.trim()
|
|
703
|
+
? item.category.trim()
|
|
704
|
+
: 'Uncategorized';
|
|
705
|
+
byCategory[cat] = (byCategory[cat] ?? 0) + 1;
|
|
706
|
+
}
|
|
707
|
+
return {
|
|
708
|
+
...snapshot,
|
|
709
|
+
...(url ? { url } : {}),
|
|
710
|
+
summary: {
|
|
711
|
+
total: snapshot.challenges.length,
|
|
712
|
+
byStatus,
|
|
713
|
+
byCategory,
|
|
714
|
+
},
|
|
715
|
+
challenges,
|
|
716
|
+
availableSlots: Math.max(0, settings.maxActiveChallenges - running),
|
|
717
|
+
remoteInstances: {
|
|
718
|
+
max: settings.maxRemoteInstances,
|
|
719
|
+
active: session.connection?.leases.list(undefined, session.sessionId) ?? [],
|
|
720
|
+
},
|
|
721
|
+
};
|
|
722
|
+
},
|
|
723
|
+
);
|
|
724
|
+
register(
|
|
725
|
+
'ctf_board_update',
|
|
726
|
+
'Update the tracking state and recorded assignment of a challenge.',
|
|
727
|
+
schema(
|
|
728
|
+
{
|
|
729
|
+
challengeId,
|
|
730
|
+
title: string,
|
|
731
|
+
status: { type: 'string', enum: STATUSES },
|
|
732
|
+
category: string,
|
|
733
|
+
points: count,
|
|
734
|
+
worker: string,
|
|
735
|
+
helpers: strings,
|
|
736
|
+
elapsedMs: count,
|
|
737
|
+
tokens: count,
|
|
738
|
+
summary: string,
|
|
739
|
+
artifacts: strings,
|
|
740
|
+
},
|
|
741
|
+
['challengeId'],
|
|
742
|
+
),
|
|
743
|
+
'write',
|
|
744
|
+
async ({ challengeId: id, ...patch }, context, session) => {
|
|
745
|
+
const [challenge] = await accessible(session, id, context);
|
|
746
|
+
if (patch.artifacts) {
|
|
747
|
+
const normalized = [];
|
|
748
|
+
const seen = new Set();
|
|
749
|
+
const subpathPrefix =
|
|
750
|
+
typeof challenge.workSubpath === 'string' && challenge.workSubpath.trim()
|
|
751
|
+
? `${challenge.workSubpath.trim().replaceAll('\\', '/').replace(/\/+$/, '')}/`
|
|
752
|
+
: undefined;
|
|
753
|
+
for (const rawFile of patch.artifacts) {
|
|
754
|
+
let file = String(rawFile ?? '')
|
|
755
|
+
.trim()
|
|
756
|
+
.replaceAll('\\', '/');
|
|
757
|
+
if (/^\/workspace(?:\/|$)/u.test(file)) {
|
|
758
|
+
file = file.replace(/^\/workspace\/+/u, '');
|
|
759
|
+
}
|
|
760
|
+
while (file.startsWith('./')) file = file.slice(2);
|
|
761
|
+
if (subpathPrefix && file.startsWith(subpathPrefix)) {
|
|
762
|
+
file = file.slice(subpathPrefix.length);
|
|
763
|
+
}
|
|
764
|
+
while (file.startsWith('./')) file = file.slice(2);
|
|
765
|
+
if (!file || file.startsWith('/')) {
|
|
766
|
+
throw fail('INVALID_PATH', 'Artifact paths must be relative to the challenge directory.');
|
|
767
|
+
}
|
|
768
|
+
try {
|
|
769
|
+
for (const segment of file.split('/')) safeSegment(segment);
|
|
770
|
+
} catch {
|
|
771
|
+
throw fail('INVALID_PATH', 'Artifact paths must be relative to the challenge directory.');
|
|
772
|
+
}
|
|
773
|
+
if (!seen.has(file)) {
|
|
774
|
+
seen.add(file);
|
|
775
|
+
normalized.push(file);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
patch.artifacts = normalized;
|
|
779
|
+
}
|
|
780
|
+
await ensureBoardStarted();
|
|
781
|
+
const snapshot = await session.board.update(id, patch);
|
|
782
|
+
void service.publish(session.sessionId);
|
|
783
|
+
return snapshot.challenges.find((item) => item.id === id);
|
|
784
|
+
},
|
|
785
|
+
);
|
|
786
|
+
|
|
787
|
+
async function withPlatform(session, operation, options = {}) {
|
|
788
|
+
return runQueued(
|
|
789
|
+
sessionPlatformQueues,
|
|
790
|
+
session.sessionId,
|
|
791
|
+
async () => {
|
|
792
|
+
const poolKey = options.poolKey ?? session.connection?.poolKey;
|
|
793
|
+
if (!poolKey) return operation();
|
|
794
|
+
return runQueued(leasePoolQueues, poolKey, operation, options.signal);
|
|
795
|
+
},
|
|
796
|
+
options.signal,
|
|
797
|
+
);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
async function connectionFilePath(session) {
|
|
801
|
+
const dir = (await session.board.directory()) ?? path.dirname(session.board.filename);
|
|
802
|
+
return path.join(dir, '.connection.json');
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
async function saveConnectionConfig(session, input) {
|
|
806
|
+
await session.board.change(() => {});
|
|
807
|
+
const filename = await connectionFilePath(session);
|
|
808
|
+
const record = {
|
|
809
|
+
version: 1,
|
|
810
|
+
platform: input.platform,
|
|
811
|
+
baseUrl: input.baseUrl,
|
|
812
|
+
...(input.portalBaseUrl ? { portalBaseUrl: input.portalBaseUrl } : {}),
|
|
813
|
+
...(input.gameId !== undefined ? { gameId: input.gameId } : {}),
|
|
814
|
+
auth: input.auth,
|
|
815
|
+
};
|
|
816
|
+
await atomicWrite(filename, `${JSON.stringify(record, null, 2)}\n`);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
async function ensureConnected(session, signal) {
|
|
820
|
+
if (session.connection) return session.connection;
|
|
821
|
+
const filename = await connectionFilePath(session);
|
|
822
|
+
let raw;
|
|
823
|
+
try {
|
|
824
|
+
raw = await readFile(filename, 'utf8');
|
|
825
|
+
} catch (error) {
|
|
826
|
+
if (error?.code === 'ENOENT') {
|
|
827
|
+
throw fail('PLATFORM_NOT_CONNECTED', 'Connect to the platform first.');
|
|
828
|
+
}
|
|
829
|
+
throw error;
|
|
830
|
+
}
|
|
831
|
+
let saved;
|
|
832
|
+
try {
|
|
833
|
+
saved = JSON.parse(raw);
|
|
834
|
+
} catch {
|
|
835
|
+
throw fail('PLATFORM_NOT_CONNECTED', 'Connect to the platform first.');
|
|
836
|
+
}
|
|
837
|
+
if (!saved || saved.version !== 1 || !saved.platform || !saved.baseUrl || !saved.auth) {
|
|
838
|
+
throw fail('PLATFORM_NOT_CONNECTED', 'Connect to the platform first.');
|
|
839
|
+
}
|
|
840
|
+
for (const value of [saved.auth.token, saved.auth.password, saved.auth.cookie]) {
|
|
841
|
+
if (value) api.registerSecret?.(value);
|
|
842
|
+
}
|
|
843
|
+
const adapter = platformAdapter(saved, api.registerSecret);
|
|
844
|
+
const pool = leasePoolFor(saved);
|
|
845
|
+
await adapter.connect(signal);
|
|
846
|
+
session.connection = {
|
|
847
|
+
adapter,
|
|
848
|
+
leases: pool,
|
|
849
|
+
poolKey: leasePoolKey(saved),
|
|
850
|
+
platform: saved.platform,
|
|
851
|
+
...(saved.gameId !== undefined ? { gameId: saved.gameId } : {}),
|
|
852
|
+
};
|
|
853
|
+
return session.connection;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
register(
|
|
857
|
+
'ctf_platform_connect',
|
|
858
|
+
'Authenticate a Host-side session for challenge metadata and attachments.',
|
|
859
|
+
schema(
|
|
860
|
+
{
|
|
861
|
+
platform: { type: 'string', enum: ['ctfd', 'gzctf', 'ctfplus'] },
|
|
862
|
+
baseUrl: string,
|
|
863
|
+
portalBaseUrl: string,
|
|
864
|
+
gameId: {
|
|
865
|
+
oneOf: [
|
|
866
|
+
{ ...count, minimum: 1 },
|
|
867
|
+
{ type: 'string', pattern: '^\\d{1,30}$' },
|
|
868
|
+
],
|
|
869
|
+
},
|
|
870
|
+
auth: schema({ token: string, cookie: string, username: string, password: string }),
|
|
871
|
+
},
|
|
872
|
+
['platform', 'baseUrl', 'auth'],
|
|
873
|
+
),
|
|
874
|
+
'write',
|
|
875
|
+
async (input, context, session) => {
|
|
876
|
+
if (!api.registerSecret)
|
|
877
|
+
throw fail('CTF_REDACTION_UNAVAILABLE', 'Host credential redaction is required.');
|
|
878
|
+
// Register credentials before any validation or request can fail.
|
|
879
|
+
for (const value of [input.auth.token, input.auth.password, input.auth.cookie])
|
|
880
|
+
if (value) api.registerSecret(value);
|
|
881
|
+
const poolKey = leasePoolKey(input);
|
|
882
|
+
return withPlatform(
|
|
883
|
+
session,
|
|
884
|
+
async () => {
|
|
885
|
+
const adapter = platformAdapter(input, api.registerSecret);
|
|
886
|
+
const pool = leasePoolFor(input);
|
|
887
|
+
await session.board.change(() => {});
|
|
888
|
+
await adapter.connect(context.signal);
|
|
889
|
+
const competition = await adapter.metadata?.(context.signal).catch(() => undefined);
|
|
890
|
+
pool.reset(session.sessionId);
|
|
891
|
+
await saveConnectionConfig(session, input);
|
|
892
|
+
session.connection = {
|
|
893
|
+
adapter,
|
|
894
|
+
leases: pool,
|
|
895
|
+
poolKey,
|
|
896
|
+
platform: input.platform,
|
|
897
|
+
...(input.gameId !== undefined ? { gameId: input.gameId } : {}),
|
|
898
|
+
};
|
|
899
|
+
return {
|
|
900
|
+
connected: true,
|
|
901
|
+
platform: input.platform,
|
|
902
|
+
...(competition ? { competition } : {}),
|
|
903
|
+
};
|
|
904
|
+
},
|
|
905
|
+
{ signal: context.signal, poolKey },
|
|
906
|
+
);
|
|
907
|
+
},
|
|
908
|
+
mainScope,
|
|
909
|
+
);
|
|
910
|
+
register(
|
|
911
|
+
'ctf_platform_sync',
|
|
912
|
+
'Import listed competition tasks and same-origin attachments into the workspace.',
|
|
913
|
+
schema({
|
|
914
|
+
downloadAttachments: { type: 'boolean' },
|
|
915
|
+
challengeIds: strings,
|
|
916
|
+
categories: strings,
|
|
917
|
+
}),
|
|
918
|
+
'write',
|
|
919
|
+
async (input, context, session) =>
|
|
920
|
+
withPlatform(
|
|
921
|
+
session,
|
|
922
|
+
async () => {
|
|
923
|
+
const connection = await ensureConnected(session, context.signal);
|
|
924
|
+
const url = await ensureBoardStarted();
|
|
925
|
+
const {
|
|
926
|
+
snapshot: mergedSnapshot,
|
|
927
|
+
syncedSubpaths,
|
|
928
|
+
downloadedAttachments,
|
|
929
|
+
} = await syncPlatform(
|
|
930
|
+
connection.adapter,
|
|
931
|
+
connection.platform,
|
|
932
|
+
session.board,
|
|
933
|
+
redact,
|
|
934
|
+
context.signal,
|
|
935
|
+
{
|
|
936
|
+
downloadAttachments: input?.downloadAttachments,
|
|
937
|
+
challengeIds: input?.challengeIds,
|
|
938
|
+
categories: input?.categories,
|
|
939
|
+
},
|
|
940
|
+
);
|
|
941
|
+
const categorySet = normalizeCategorySet(input?.categories);
|
|
942
|
+
const snapshot = categorySet
|
|
943
|
+
? await session.board.change((current) => {
|
|
944
|
+
const scopedCategories = input.categories.map((cat) => String(cat).trim()).filter(Boolean);
|
|
945
|
+
if (scopedCategories.length > 0) {
|
|
946
|
+
current.metadata.categories = [...new Set(scopedCategories)];
|
|
947
|
+
}
|
|
948
|
+
current.challenges = current.challenges.filter((item) => {
|
|
949
|
+
if (item.status === 'running' || item.status === 'solved') return true;
|
|
950
|
+
return matchesScopeFilters(item, categorySet, undefined);
|
|
951
|
+
});
|
|
952
|
+
})
|
|
953
|
+
: mergedSnapshot;
|
|
954
|
+
const sandboxSync =
|
|
955
|
+
syncedSubpaths.length > 0
|
|
956
|
+
? await api.syncWorkspaceSubpaths?.(
|
|
957
|
+
{
|
|
958
|
+
runId: context.runId,
|
|
959
|
+
agentSessionId: context.agentSessionId,
|
|
960
|
+
sessionId: session.sessionId,
|
|
961
|
+
},
|
|
962
|
+
syncedSubpaths,
|
|
963
|
+
)
|
|
964
|
+
: undefined;
|
|
965
|
+
void service.publish(session.sessionId);
|
|
966
|
+
return {
|
|
967
|
+
...(url ? { url } : {}),
|
|
968
|
+
revision: snapshot.revision,
|
|
969
|
+
imported: snapshot.challenges.filter((item) => item.platform === session.connection.platform)
|
|
970
|
+
.length,
|
|
971
|
+
synced: syncedSubpaths.length,
|
|
972
|
+
downloadedAttachments,
|
|
973
|
+
...(sandboxSync
|
|
974
|
+
? {
|
|
975
|
+
mainWorkspaceSynced: !sandboxSync.partial,
|
|
976
|
+
...(sandboxSync.partial
|
|
977
|
+
? { mainWorkspacePartial: true, mainWorkspaceSkipped: sandboxSync.skipped }
|
|
978
|
+
: {}),
|
|
979
|
+
}
|
|
980
|
+
: {}),
|
|
981
|
+
};
|
|
982
|
+
},
|
|
983
|
+
{ signal: context.signal },
|
|
984
|
+
),
|
|
985
|
+
mainScope,
|
|
986
|
+
);
|
|
987
|
+
|
|
988
|
+
async function stopChallengeInstance(session, challenge, remoteId, signal) {
|
|
989
|
+
let result;
|
|
990
|
+
try {
|
|
991
|
+
result = await session.connection.adapter.instance(remoteId, 'stop', signal);
|
|
992
|
+
} catch (error) {
|
|
993
|
+
if (!isContainerAlreadyGoneError(error)) throw error;
|
|
994
|
+
result = { supported: true, action: 'stop', active: false, alreadyStopped: true };
|
|
995
|
+
}
|
|
996
|
+
if (!result.supported) return { supported: false, result };
|
|
997
|
+
session.connection.leases.release(challenge.id, undefined, session.sessionId);
|
|
998
|
+
const connectionInfo = { active: false, updatedAt: new Date().toISOString() };
|
|
999
|
+
await session.board.update(challenge.id, { connection: connectionInfo });
|
|
1000
|
+
void service.publish(session.sessionId);
|
|
1001
|
+
return { supported: true, result, connectionInfo };
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
register(
|
|
1005
|
+
'ctf_platform_instance',
|
|
1006
|
+
'Start, renew, or stop a dynamic challenge container on the connected competition platform.',
|
|
1007
|
+
schema(
|
|
1008
|
+
{
|
|
1009
|
+
challengeId,
|
|
1010
|
+
action: { type: 'string', enum: ['start', 'stop', 'renew'] },
|
|
1011
|
+
},
|
|
1012
|
+
['challengeId', 'action'],
|
|
1013
|
+
),
|
|
1014
|
+
(data) =>
|
|
1015
|
+
data?.supported === false || data?.status === 'blocked' || data?.reused === true ? 'none' : 'applied',
|
|
1016
|
+
async (input, context, session) =>
|
|
1017
|
+
withPlatform(
|
|
1018
|
+
session,
|
|
1019
|
+
async () => {
|
|
1020
|
+
const { leases, adapter, platform } = await ensureConnected(session, context.signal);
|
|
1021
|
+
const [challenge] = await accessible(session, input.challengeId, context);
|
|
1022
|
+
const remoteId = resolveRemoteChallengeId(challenge, session.connection);
|
|
1023
|
+
|
|
1024
|
+
if (input.action === 'start') {
|
|
1025
|
+
const check = leases.checkStart(challenge.id, undefined, session.sessionId);
|
|
1026
|
+
if (check.ok && check.reused) {
|
|
1027
|
+
const info = check.lease.connection;
|
|
1028
|
+
return {
|
|
1029
|
+
status: 'ok',
|
|
1030
|
+
supported: true,
|
|
1031
|
+
reused: true,
|
|
1032
|
+
challengeId: challenge.id,
|
|
1033
|
+
platform,
|
|
1034
|
+
action: 'start',
|
|
1035
|
+
active: true,
|
|
1036
|
+
...(info.host ? { host: info.host } : {}),
|
|
1037
|
+
...(info.port !== undefined ? { port: info.port } : {}),
|
|
1038
|
+
...(info.entry ? { entry: info.entry } : {}),
|
|
1039
|
+
...(info.expiresAt ? { expiresAt: info.expiresAt } : {}),
|
|
1040
|
+
connection: info,
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
if (!check.ok && check.code === 'REMOTE_QUOTA_EXCEEDED') {
|
|
1044
|
+
return {
|
|
1045
|
+
status: 'blocked',
|
|
1046
|
+
supported: true,
|
|
1047
|
+
code: 'REMOTE_QUOTA_EXCEEDED',
|
|
1048
|
+
challengeId: challenge.id,
|
|
1049
|
+
platform,
|
|
1050
|
+
action: 'start',
|
|
1051
|
+
active: false,
|
|
1052
|
+
maxRemoteInstances: check.maxRemoteInstances,
|
|
1053
|
+
activeLeases: check.activeLeases,
|
|
1054
|
+
message: check.ownedByOtherSession
|
|
1055
|
+
? `Challenge "${challenge.id}" already has an active remote instance owned by another session.`
|
|
1056
|
+
: `Remote instance quota reached (${check.activeLeases.length}/${check.maxRemoteInstances} active). Stop an active instance or wait for lease expiry before starting another.`,
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
if (!check.ok && check.code === 'INSTANCE_COOLDOWN') {
|
|
1060
|
+
return {
|
|
1061
|
+
status: 'blocked',
|
|
1062
|
+
supported: true,
|
|
1063
|
+
code: 'INSTANCE_COOLDOWN',
|
|
1064
|
+
challengeId: challenge.id,
|
|
1065
|
+
platform,
|
|
1066
|
+
action: 'start',
|
|
1067
|
+
active: false,
|
|
1068
|
+
retryAfterMs: check.retryAfterMs,
|
|
1069
|
+
instanceCooldownMs: check.instanceCooldownMs,
|
|
1070
|
+
message: `Remote instance cooldown active; wait ${check.retryAfterMs}ms before starting a new instance.`,
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
const result = await adapter.instance(remoteId, 'start', context.signal);
|
|
1074
|
+
if (!result.supported) {
|
|
1075
|
+
return {
|
|
1076
|
+
status: 'unsupported',
|
|
1077
|
+
supported: false,
|
|
1078
|
+
code: result.code ?? 'PLATFORM_UNSUPPORTED',
|
|
1079
|
+
challengeId: challenge.id,
|
|
1080
|
+
platform,
|
|
1081
|
+
action: 'start',
|
|
1082
|
+
message: result.message,
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
const nowIso = new Date().toISOString();
|
|
1086
|
+
const connectionInfo = result.active
|
|
1087
|
+
? {
|
|
1088
|
+
active: true,
|
|
1089
|
+
...(result.host ? { host: result.host } : {}),
|
|
1090
|
+
...(result.port !== undefined ? { port: result.port } : {}),
|
|
1091
|
+
...(result.entry ? { entry: result.entry } : {}),
|
|
1092
|
+
...(result.expiresAt ? { expiresAt: result.expiresAt } : {}),
|
|
1093
|
+
updatedAt: nowIso,
|
|
1094
|
+
}
|
|
1095
|
+
: { active: false, updatedAt: nowIso };
|
|
1096
|
+
if (result.active) {
|
|
1097
|
+
leases.acquire(challenge.id, {
|
|
1098
|
+
startedAt: nowIso,
|
|
1099
|
+
expiresAt: result.expiresAt,
|
|
1100
|
+
connection: connectionInfo,
|
|
1101
|
+
ownerSessionId: session.sessionId,
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
await session.board.update(challenge.id, { connection: connectionInfo });
|
|
1105
|
+
void service.publish(session.sessionId);
|
|
1106
|
+
return {
|
|
1107
|
+
status: 'ok',
|
|
1108
|
+
supported: true,
|
|
1109
|
+
challengeId: challenge.id,
|
|
1110
|
+
platform,
|
|
1111
|
+
action: 'start',
|
|
1112
|
+
active: result.active,
|
|
1113
|
+
...(result.host ? { host: result.host } : {}),
|
|
1114
|
+
...(result.port !== undefined ? { port: result.port } : {}),
|
|
1115
|
+
...(result.entry ? { entry: result.entry } : {}),
|
|
1116
|
+
...(result.expiresAt ? { expiresAt: result.expiresAt } : {}),
|
|
1117
|
+
connection: connectionInfo,
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
if (input.action === 'renew') {
|
|
1122
|
+
const result = await adapter.instance(remoteId, 'renew', context.signal);
|
|
1123
|
+
if (!result.supported) {
|
|
1124
|
+
return {
|
|
1125
|
+
status: 'unsupported',
|
|
1126
|
+
supported: false,
|
|
1127
|
+
code: result.code ?? 'PLATFORM_UNSUPPORTED',
|
|
1128
|
+
challengeId: challenge.id,
|
|
1129
|
+
platform,
|
|
1130
|
+
action: 'renew',
|
|
1131
|
+
message: result.message,
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
const prior =
|
|
1135
|
+
leases.get(challenge.id, undefined, session.sessionId)?.connection ?? challenge.connection;
|
|
1136
|
+
const host = result.host ?? prior?.host;
|
|
1137
|
+
const port = result.port ?? prior?.port;
|
|
1138
|
+
const entry = result.entry ?? prior?.entry;
|
|
1139
|
+
const expiresAt = result.expiresAt ?? prior?.expiresAt;
|
|
1140
|
+
const connectionInfo = result.active
|
|
1141
|
+
? {
|
|
1142
|
+
active: true,
|
|
1143
|
+
...(host ? { host } : {}),
|
|
1144
|
+
...(port !== undefined ? { port } : {}),
|
|
1145
|
+
...(entry ? { entry } : {}),
|
|
1146
|
+
...(expiresAt ? { expiresAt } : {}),
|
|
1147
|
+
updatedAt: new Date().toISOString(),
|
|
1148
|
+
}
|
|
1149
|
+
: { active: false, updatedAt: new Date().toISOString() };
|
|
1150
|
+
if (result.active) {
|
|
1151
|
+
leases.renew(challenge.id, {
|
|
1152
|
+
expiresAt,
|
|
1153
|
+
connection: connectionInfo,
|
|
1154
|
+
ownerSessionId: session.sessionId,
|
|
1155
|
+
});
|
|
1156
|
+
} else {
|
|
1157
|
+
leases.release(challenge.id, undefined, session.sessionId);
|
|
1158
|
+
}
|
|
1159
|
+
await session.board.update(challenge.id, { connection: connectionInfo });
|
|
1160
|
+
void service.publish(session.sessionId);
|
|
1161
|
+
return {
|
|
1162
|
+
status: 'ok',
|
|
1163
|
+
supported: true,
|
|
1164
|
+
challengeId: challenge.id,
|
|
1165
|
+
platform,
|
|
1166
|
+
action: 'renew',
|
|
1167
|
+
active: result.active,
|
|
1168
|
+
...(host ? { host } : {}),
|
|
1169
|
+
...(port !== undefined ? { port } : {}),
|
|
1170
|
+
...(entry ? { entry } : {}),
|
|
1171
|
+
...(expiresAt ? { expiresAt } : {}),
|
|
1172
|
+
connection: connectionInfo,
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
const stopped = await stopChallengeInstance(session, challenge, remoteId, context.signal);
|
|
1177
|
+
if (!stopped.supported) {
|
|
1178
|
+
return {
|
|
1179
|
+
status: 'unsupported',
|
|
1180
|
+
supported: false,
|
|
1181
|
+
code: stopped.result.code ?? 'PLATFORM_UNSUPPORTED',
|
|
1182
|
+
challengeId: challenge.id,
|
|
1183
|
+
platform,
|
|
1184
|
+
action: 'stop',
|
|
1185
|
+
message: stopped.result.message,
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
return {
|
|
1189
|
+
status: 'ok',
|
|
1190
|
+
supported: true,
|
|
1191
|
+
challengeId: challenge.id,
|
|
1192
|
+
platform,
|
|
1193
|
+
action: 'stop',
|
|
1194
|
+
active: false,
|
|
1195
|
+
...(stopped.result?.alreadyStopped ? { alreadyStopped: true } : {}),
|
|
1196
|
+
connection: stopped.connectionInfo,
|
|
1197
|
+
};
|
|
1198
|
+
},
|
|
1199
|
+
{ signal: context.signal },
|
|
1200
|
+
),
|
|
1201
|
+
);
|
|
1202
|
+
|
|
1203
|
+
function checkSubmitRateLimit(session) {
|
|
1204
|
+
if (session.lastSubmitAt === undefined || settings.submitMinIntervalMs <= 0) return undefined;
|
|
1205
|
+
const elapsed = Date.now() - session.lastSubmitAt;
|
|
1206
|
+
if (elapsed >= settings.submitMinIntervalMs) return undefined;
|
|
1207
|
+
const retryAfterMs = settings.submitMinIntervalMs - elapsed;
|
|
1208
|
+
return { retryAfterMs };
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
register(
|
|
1212
|
+
'ctf_platform_submit',
|
|
1213
|
+
'Submit a challenge answer to the connected platform with deduplication, rate limiting, and confirmation gating.',
|
|
1214
|
+
schema(
|
|
1215
|
+
{
|
|
1216
|
+
challengeId,
|
|
1217
|
+
answer: string,
|
|
1218
|
+
confirm: { type: 'boolean' },
|
|
1219
|
+
},
|
|
1220
|
+
['challengeId', 'answer'],
|
|
1221
|
+
),
|
|
1222
|
+
(data) => (data?.submitted && data?.correct ? 'applied' : 'none'),
|
|
1223
|
+
async (input, context, session) => {
|
|
1224
|
+
const normalized = input.answer.trim();
|
|
1225
|
+
if (!normalized) throw fail('INVALID_INPUT', 'Answer must not be empty.');
|
|
1226
|
+
if (!session.connection) {
|
|
1227
|
+
await withPlatform(session, () => ensureConnected(session, context.signal), {
|
|
1228
|
+
signal: context.signal,
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
const assignment = await api.resolveWorkspaceAssignment?.(context);
|
|
1232
|
+
const [challenge] = await accessible(session, input.challengeId, context, assignment);
|
|
1233
|
+
const remoteId = resolveRemoteChallengeId(challenge, session.connection);
|
|
1234
|
+
|
|
1235
|
+
if (session.wrongAnswers.get(challenge.id)?.has(normalized)) {
|
|
1236
|
+
return {
|
|
1237
|
+
submitted: false,
|
|
1238
|
+
status: 'blocked',
|
|
1239
|
+
code: 'DUPLICATE_WRONG_ANSWER',
|
|
1240
|
+
challengeId: challenge.id,
|
|
1241
|
+
title: challenge.title,
|
|
1242
|
+
message: 'This answer was already rejected for this challenge.',
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
if (settings.autoSubmit !== true && input.confirm !== true) {
|
|
1247
|
+
return {
|
|
1248
|
+
submitted: false,
|
|
1249
|
+
status: 'confirmation_required',
|
|
1250
|
+
code: 'CONFIRMATION_REQUIRED',
|
|
1251
|
+
challengeId: challenge.id,
|
|
1252
|
+
title: challenge.title,
|
|
1253
|
+
preview: redact(normalized.length > 64 ? `${normalized.slice(0, 61)}...` : normalized),
|
|
1254
|
+
message:
|
|
1255
|
+
'Confirmation required before submitting because auto_submit is disabled. Retry with confirm: true.',
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
const earlyRateLimit = checkSubmitRateLimit(session);
|
|
1260
|
+
if (earlyRateLimit) {
|
|
1261
|
+
return {
|
|
1262
|
+
submitted: false,
|
|
1263
|
+
status: 'blocked',
|
|
1264
|
+
code: 'RATE_LIMITED',
|
|
1265
|
+
challengeId: challenge.id,
|
|
1266
|
+
title: challenge.title,
|
|
1267
|
+
retryAfterMs: earlyRateLimit.retryAfterMs,
|
|
1268
|
+
minIntervalMs: settings.submitMinIntervalMs,
|
|
1269
|
+
message: `Submission rate limited; wait ${earlyRateLimit.retryAfterMs}ms before retrying.`,
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
return withPlatform(
|
|
1274
|
+
session,
|
|
1275
|
+
async () => {
|
|
1276
|
+
const insideRateLimit = checkSubmitRateLimit(session);
|
|
1277
|
+
if (insideRateLimit) {
|
|
1278
|
+
return {
|
|
1279
|
+
submitted: false,
|
|
1280
|
+
status: 'blocked',
|
|
1281
|
+
code: 'RATE_LIMITED',
|
|
1282
|
+
challengeId: challenge.id,
|
|
1283
|
+
title: challenge.title,
|
|
1284
|
+
retryAfterMs: insideRateLimit.retryAfterMs,
|
|
1285
|
+
minIntervalMs: settings.submitMinIntervalMs,
|
|
1286
|
+
message: `Submission rate limited; wait ${insideRateLimit.retryAfterMs}ms before retrying.`,
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
const { adapter, leases, platform } = session.connection;
|
|
1290
|
+
session.lastSubmitAt = Date.now();
|
|
1291
|
+
const result = await adapter.submit(remoteId, normalized, context.signal);
|
|
1292
|
+
if (result.status === 'correct' || result.status === 'already_solved') {
|
|
1293
|
+
const solvedWorker = !challenge.worker
|
|
1294
|
+
? assignment?.role === 'main'
|
|
1295
|
+
? 'main'
|
|
1296
|
+
: (challenge.workSubpath ?? assignment?.workSubpath ?? 'worker')
|
|
1297
|
+
: undefined;
|
|
1298
|
+
await session.board.update(challenge.id, {
|
|
1299
|
+
status: 'solved',
|
|
1300
|
+
...(solvedWorker ? { worker: solvedWorker } : {}),
|
|
1301
|
+
});
|
|
1302
|
+
void service.publish(session.sessionId);
|
|
1303
|
+
const recordFactHandler = session.ledgerHandlers.get('security_record_fact');
|
|
1304
|
+
if (recordFactHandler) {
|
|
1305
|
+
await prepareLedger(session, challenge.id);
|
|
1306
|
+
await recordFactHandler.invoke(
|
|
1307
|
+
{
|
|
1308
|
+
category: 'endpoint',
|
|
1309
|
+
confidence: 'verified',
|
|
1310
|
+
summary: redact(
|
|
1311
|
+
`Platform ${platform} accepted submission for ${challenge.title} (${result.status}).`,
|
|
1312
|
+
),
|
|
1313
|
+
evidence: redact(
|
|
1314
|
+
`challengeId=${challenge.id}, platform=${platform}, status=${result.status}${
|
|
1315
|
+
result.message ? `, message=${result.message}` : ''
|
|
1316
|
+
}`,
|
|
1317
|
+
),
|
|
1318
|
+
},
|
|
1319
|
+
{
|
|
1320
|
+
...context,
|
|
1321
|
+
runId: challenge.id,
|
|
1322
|
+
checkpointSourceRunId: undefined,
|
|
1323
|
+
},
|
|
1324
|
+
);
|
|
1325
|
+
void service.publish(session.sessionId);
|
|
1326
|
+
}
|
|
1327
|
+
let autoStopped = false;
|
|
1328
|
+
let autoStopError;
|
|
1329
|
+
if (settings.autoStopOnSolve !== false) {
|
|
1330
|
+
leases.prune();
|
|
1331
|
+
if (
|
|
1332
|
+
leases.has(challenge.id, undefined, session.sessionId) ||
|
|
1333
|
+
challenge.connection?.active === true
|
|
1334
|
+
) {
|
|
1335
|
+
try {
|
|
1336
|
+
const stopped = await stopChallengeInstance(session, challenge, remoteId, context.signal);
|
|
1337
|
+
autoStopped = stopped.supported === true;
|
|
1338
|
+
} catch (error) {
|
|
1339
|
+
autoStopped = false;
|
|
1340
|
+
autoStopError = redact(
|
|
1341
|
+
error instanceof Error && error.message ? error.message : 'Auto-stop failed.',
|
|
1342
|
+
);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
return {
|
|
1347
|
+
submitted: true,
|
|
1348
|
+
correct: true,
|
|
1349
|
+
status: result.status,
|
|
1350
|
+
challengeId: challenge.id,
|
|
1351
|
+
title: challenge.title,
|
|
1352
|
+
boardStatus: 'solved',
|
|
1353
|
+
autoStopped,
|
|
1354
|
+
...(autoStopError ? { autoStopError } : {}),
|
|
1355
|
+
...(result.message ? { message: result.message } : {}),
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
if (result.status === 'incorrect') {
|
|
1359
|
+
let wrong = session.wrongAnswers.get(challenge.id);
|
|
1360
|
+
if (!wrong) session.wrongAnswers.set(challenge.id, (wrong = new Set()));
|
|
1361
|
+
wrong.add(normalized);
|
|
1362
|
+
return {
|
|
1363
|
+
submitted: true,
|
|
1364
|
+
correct: false,
|
|
1365
|
+
status: 'incorrect',
|
|
1366
|
+
challengeId: challenge.id,
|
|
1367
|
+
title: challenge.title,
|
|
1368
|
+
...(result.message ? { message: result.message } : {}),
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
return {
|
|
1372
|
+
submitted: false,
|
|
1373
|
+
correct: false,
|
|
1374
|
+
status: 'rate_limited',
|
|
1375
|
+
code: 'RATE_LIMITED',
|
|
1376
|
+
challengeId: challenge.id,
|
|
1377
|
+
title: challenge.title,
|
|
1378
|
+
...(result.message ? { message: result.message } : {}),
|
|
1379
|
+
};
|
|
1380
|
+
},
|
|
1381
|
+
{ signal: context.signal },
|
|
1382
|
+
);
|
|
1383
|
+
},
|
|
1384
|
+
);
|
|
1385
|
+
|
|
1386
|
+
api.onWorkerLifecycle?.(async (event) => {
|
|
1387
|
+
const subpath = event.workSubpath?.trim().replaceAll('\\', '/').replace(/\/+$/, '');
|
|
1388
|
+
if (!subpath) return;
|
|
1389
|
+
const session = await getSession(event.sessionId);
|
|
1390
|
+
const snapshot = await session.board.snapshot();
|
|
1391
|
+
const challenge = snapshot.challenges.find(
|
|
1392
|
+
(item) =>
|
|
1393
|
+
subpath === item.workSubpath || (item.workSubpath && subpath.startsWith(item.workSubpath + '/')),
|
|
1394
|
+
);
|
|
1395
|
+
if (!challenge) return;
|
|
1396
|
+
const isDepth1 = !event.parentMemberId || event.parentMemberId === 'main';
|
|
1397
|
+
|
|
1398
|
+
if (event.phase === 'started') {
|
|
1399
|
+
if (isDepth1) {
|
|
1400
|
+
if (challenge.status === 'queued' || challenge.status === 'blocked') {
|
|
1401
|
+
try {
|
|
1402
|
+
await session.board.update(challenge.id, { status: 'running', worker: event.memberId });
|
|
1403
|
+
void service.publish(session.sessionId);
|
|
1404
|
+
} catch {
|
|
1405
|
+
// Ignore capacity/transition races so worker startup continues cleanly.
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
return;
|
|
1409
|
+
}
|
|
1410
|
+
const existingHelpers = Array.isArray(challenge.helpers) ? challenge.helpers : [];
|
|
1411
|
+
if (
|
|
1412
|
+
!existingHelpers.includes(event.memberId) &&
|
|
1413
|
+
existingHelpers.length < settings.maxHelpersPerChallenge
|
|
1414
|
+
) {
|
|
1415
|
+
try {
|
|
1416
|
+
await session.board.update(challenge.id, { helpers: [...existingHelpers, event.memberId] });
|
|
1417
|
+
void service.publish(session.sessionId);
|
|
1418
|
+
} catch {
|
|
1419
|
+
// Ignore helper cap/transition races.
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
if (event.phase === 'completed') {
|
|
1426
|
+
const deltaTokens = event.usage
|
|
1427
|
+
? Math.max(0, (event.usage.inputTokens ?? 0) + (event.usage.outputTokens ?? 0))
|
|
1428
|
+
: 0;
|
|
1429
|
+
const patch = {};
|
|
1430
|
+
if (isDepth1) {
|
|
1431
|
+
if (challenge.status === 'running' && challenge.worker === event.memberId) {
|
|
1432
|
+
patch.status = 'queued';
|
|
1433
|
+
}
|
|
1434
|
+
} else if (Array.isArray(challenge.helpers) && challenge.helpers.includes(event.memberId)) {
|
|
1435
|
+
patch.helpers = challenge.helpers.filter((id) => id !== event.memberId);
|
|
1436
|
+
}
|
|
1437
|
+
if (deltaTokens > 0) {
|
|
1438
|
+
patch.tokens = (challenge.tokens ?? 0) + deltaTokens;
|
|
1439
|
+
}
|
|
1440
|
+
if (Object.keys(patch).length > 0) {
|
|
1441
|
+
try {
|
|
1442
|
+
await session.board.update(challenge.id, patch);
|
|
1443
|
+
void service.publish(session.sessionId);
|
|
1444
|
+
} catch {
|
|
1445
|
+
// Ignore concurrent status transition.
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
});
|
|
1450
|
+
|
|
1451
|
+
await ensureBoardStarted({ failOnError: false });
|
|
1452
|
+
|
|
1453
|
+
api.onDispose(async () => {
|
|
1454
|
+
api.reportStatus?.(undefined);
|
|
1455
|
+
await service.dispose();
|
|
1456
|
+
await Promise.allSettled([...sessionPlatformQueues.values(), ...leasePoolQueues.values()]);
|
|
1457
|
+
await Promise.all(
|
|
1458
|
+
[...sessions.values()].flatMap((session) => [session.ledger.dispose(), session.board.dispose()]),
|
|
1459
|
+
);
|
|
1460
|
+
for (const scope of sessions.values()) {
|
|
1461
|
+
scope.wrongAnswers.clear();
|
|
1462
|
+
scope.lastSubmitAt = undefined;
|
|
1463
|
+
scope.connection = undefined;
|
|
1464
|
+
}
|
|
1465
|
+
for (const pool of leasePools.values()) pool.reset();
|
|
1466
|
+
leasePools.clear();
|
|
1467
|
+
sessionPlatformQueues.clear();
|
|
1468
|
+
leasePoolQueues.clear();
|
|
1469
|
+
sessions.clear();
|
|
1470
|
+
pendingSessions.clear();
|
|
1471
|
+
});
|
|
1472
|
+
},
|
|
1473
|
+
};
|