negotium 0.23.9 → 0.23.10
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/dist/agent-helpers.js +434 -1299
- package/dist/agent-helpers.js.map +5 -5
- package/dist/background-bash.js +12 -12
- package/dist/background-bash.js.map +2 -2
- package/dist/browser-runtime.js +42 -44
- package/dist/browser-runtime.js.map +2 -2
- package/dist/canonical-mcp-bridge.js +8 -9
- package/dist/canonical-mcp-bridge.js.map +1 -1
- package/dist/chunk-22kg3fsw.js +79 -0
- package/dist/{chunk-2mx7fq49.js.map → chunk-22kg3fsw.js.map} +1 -1
- package/dist/{chunk-mxxwx5mg.js → chunk-d4j77adx.js} +96 -135
- package/dist/{chunk-mxxwx5mg.js.map → chunk-d4j77adx.js.map} +5 -5
- package/dist/{chunk-da9ad838.js → chunk-qd0vtfm2.js} +115 -119
- package/dist/{chunk-da9ad838.js.map → chunk-qd0vtfm2.js.map} +6 -6
- package/dist/{chunk-jsv1te9a.js → chunk-qvtj66y2.js} +4 -5
- package/dist/{chunk-jsv1te9a.js.map → chunk-qvtj66y2.js.map} +2 -2
- package/dist/{chunk-jtv8yzy1.js → chunk-wf7ny8eq.js} +12 -12
- package/dist/{chunk-jtv8yzy1.js.map → chunk-wf7ny8eq.js.map} +2 -2
- package/dist/{chunk-f7p0h1gs.js → chunk-ww8a4ej4.js} +5 -5
- package/dist/{chunk-f7p0h1gs.js.map → chunk-ww8a4ej4.js.map} +2 -2
- package/dist/hosted-agent.js +123 -126
- package/dist/hosted-agent.js.map +3 -3
- package/dist/main.js +3401 -5212
- package/dist/main.js.map +5 -5
- package/dist/mcp-catalog.js +4 -4
- package/dist/mcp-catalog.js.map +1 -1
- package/dist/mcp-factories.js +691 -1548
- package/dist/mcp-factories.js.map +5 -5
- package/dist/mcp-servers.js +5 -5
- package/dist/mcp-servers.js.map +1 -1
- package/dist/media.js +3 -3
- package/dist/media.js.map +1 -1
- package/dist/outbox.js +15 -15
- package/dist/outbox.js.map +2 -2
- package/dist/platform-runtime.js +7 -7
- package/dist/platform-runtime.js.map +1 -1
- package/dist/prompts.js +6 -6
- package/dist/prompts.js.map +2 -2
- package/dist/query-runtime.js +16 -18
- package/dist/query-runtime.js.map +2 -2
- package/dist/registry.js +19 -20
- package/dist/registry.js.map +2 -2
- package/dist/rollout.js +41 -41
- package/dist/rollout.js.map +2 -2
- package/dist/runtime/src/bus.ts +10 -0
- package/dist/runtime/src/runtime/turn-event-stream.ts +42 -3
- package/dist/runtime/src/version.ts +1 -1
- package/dist/runtime-gateway.js +12 -12
- package/dist/runtime-gateway.js.map +2 -2
- package/dist/runtime-helpers.js +52 -54
- package/dist/runtime-helpers.js.map +2 -2
- package/dist/sqlite.js +3 -5
- package/dist/sqlite.js.map +2 -2
- package/dist/storage.js +4841 -4812
- package/dist/storage.js.map +2 -2
- package/dist/types/packages/core/src/bus.d.ts +9 -0
- package/dist/types/packages/core/src/version.d.ts +1 -1
- package/dist/vault.js +20 -22
- package/dist/vault.js.map +2 -2
- package/package.json +1 -1
- package/dist/chunk-2mx7fq49.js +0 -6
- package/dist/chunk-ad7kxsaq.js +0 -202
- package/dist/chunk-ad7kxsaq.js.map +0 -9
package/dist/agent-helpers.js
CHANGED
|
@@ -13,9 +13,18 @@ var __export = (target, all) => {
|
|
|
13
13
|
set: __exportSetter.bind(all, name)
|
|
14
14
|
});
|
|
15
15
|
};
|
|
16
|
-
var __esm = (fn, res) => () =>
|
|
16
|
+
var __esm = (fn, res, err) => () => {
|
|
17
|
+
if (fn)
|
|
18
|
+
try {
|
|
19
|
+
res = fn(fn = 0);
|
|
20
|
+
} catch (e) {
|
|
21
|
+
err = [e];
|
|
22
|
+
}
|
|
23
|
+
if (err)
|
|
24
|
+
throw err[0];
|
|
25
|
+
return res;
|
|
26
|
+
};
|
|
17
27
|
var __promiseAll = (args) => Promise.all(args);
|
|
18
|
-
var __require = import.meta.require;
|
|
19
28
|
|
|
20
29
|
// ../../packages/core/src/platform/paths.ts
|
|
21
30
|
import { existsSync, realpathSync } from "fs";
|
|
@@ -184,106 +193,6 @@ var init_logger = __esm(() => {
|
|
|
184
193
|
});
|
|
185
194
|
|
|
186
195
|
// ../../packages/core/src/platform/config.ts
|
|
187
|
-
var exports_config = {};
|
|
188
|
-
__export(exports_config, {
|
|
189
|
-
resolveTopicWorkspaceDir: () => resolveTopicWorkspaceDir,
|
|
190
|
-
resolveOutputLanguage: () => resolveOutputLanguage,
|
|
191
|
-
resolveBrowserRsBin: () => resolveBrowserRsBin,
|
|
192
|
-
resolveBrowserProxy: () => resolveBrowserProxy,
|
|
193
|
-
resolveBrowserMcpBin: () => resolveBrowserMcpBin,
|
|
194
|
-
resolveBashRsBin: () => resolveBashRsBin,
|
|
195
|
-
isProductionEnv: () => isProductionEnv,
|
|
196
|
-
hostname: () => hostname,
|
|
197
|
-
getCleanEnv: () => getCleanEnv,
|
|
198
|
-
envText: () => envText,
|
|
199
|
-
codexAuthFilePath: () => codexAuthFilePath,
|
|
200
|
-
WORKSPACE_DIR: () => WORKSPACE_DIR,
|
|
201
|
-
WIKI_SERVER: () => WIKI_SERVER,
|
|
202
|
-
WHISPER_MODEL_MLX: () => WHISPER_MODEL_MLX,
|
|
203
|
-
WHISPER_MODEL: () => WHISPER_MODEL,
|
|
204
|
-
WHISPER_BACKEND: () => WHISPER_BACKEND,
|
|
205
|
-
VAULT_SERVER: () => VAULT_SERVER,
|
|
206
|
-
VAULT_MASTER_KEY: () => VAULT_MASTER_KEY,
|
|
207
|
-
VAULT_DIR: () => VAULT_DIR,
|
|
208
|
-
USERS_LOG_DIR: () => USERS_LOG_DIR,
|
|
209
|
-
UPLOADS_DIR: () => UPLOADS_DIR,
|
|
210
|
-
TSX_LOADER: () => TSX_LOADER,
|
|
211
|
-
TSX_BIN: () => TSX_BIN,
|
|
212
|
-
TSCONFIG_PATH: () => TSCONFIG_PATH,
|
|
213
|
-
TOPIC_WORKSPACE_DIR: () => TOPIC_WORKSPACE_DIR,
|
|
214
|
-
TOKEN_STATS_SERVER: () => TOKEN_STATS_SERVER,
|
|
215
|
-
TESSERACT_BIN: () => TESSERACT_BIN,
|
|
216
|
-
TASK_SERVER: () => TASK_SERVER,
|
|
217
|
-
SYSTEM_HEALTH_SERVER: () => SYSTEM_HEALTH_SERVER,
|
|
218
|
-
STATE_DIR: () => STATE_DIR,
|
|
219
|
-
SNIPPETS_API_URL: () => SNIPPETS_API_URL,
|
|
220
|
-
SHARED_WIKI_DIR: () => SHARED_WIKI_DIR,
|
|
221
|
-
SESSION_WORKSPACE_DIR: () => SESSION_WORKSPACE_DIR,
|
|
222
|
-
SESSION_INBOX_DIR: () => SESSION_INBOX_DIR,
|
|
223
|
-
SESSION_HISTORY_SERVER: () => SESSION_HISTORY_SERVER,
|
|
224
|
-
SESSION_COMM_SERVER: () => SESSION_COMM_SERVER,
|
|
225
|
-
SESSION_ASKS_DIR: () => SESSION_ASKS_DIR,
|
|
226
|
-
SESSIONS_DB: () => SESSIONS_DB,
|
|
227
|
-
SECRETS_DIR: () => SECRETS_DIR,
|
|
228
|
-
RUN_DIR: () => RUN_DIR,
|
|
229
|
-
RUNTIME_MCP_SECRET: () => RUNTIME_MCP_SECRET,
|
|
230
|
-
RUNTIME_DIR: () => RUNTIME_DIR,
|
|
231
|
-
RESOURCES_DIR: () => RESOURCES_DIR,
|
|
232
|
-
PYTHON_BIN: () => PYTHON_BIN,
|
|
233
|
-
PROJECT_ROOT: () => PROJECT_ROOT,
|
|
234
|
-
PROGRESS_DIR: () => PROGRESS_DIR,
|
|
235
|
-
PLAYWRIGHT_PORTS_DIR: () => PLAYWRIGHT_PORTS_DIR,
|
|
236
|
-
PLAYWRIGHT_MCP_BIN: () => PLAYWRIGHT_MCP_BIN,
|
|
237
|
-
PLAYWRIGHT_MAX_PORT: () => PLAYWRIGHT_MAX_PORT,
|
|
238
|
-
PLAYWRIGHT_BASE_PORT: () => PLAYWRIGHT_BASE_PORT,
|
|
239
|
-
PDFTOTEXT_BIN: () => PDFTOTEXT_BIN,
|
|
240
|
-
NODE_ID: () => NODE_ID,
|
|
241
|
-
NODE_CONTROL_TOKEN: () => NODE_CONTROL_TOKEN,
|
|
242
|
-
NEGOTIUM_PORT: () => NEGOTIUM_PORT,
|
|
243
|
-
MODEL_SONNET: () => MODEL_SONNET,
|
|
244
|
-
MODEL_OPUS: () => MODEL_OPUS,
|
|
245
|
-
MODEL_HAIKU: () => MODEL_HAIKU,
|
|
246
|
-
MODEL_FABLE: () => MODEL_FABLE,
|
|
247
|
-
MODEL_DEEPSEEK_V4_PRO: () => MODEL_DEEPSEEK_V4_PRO,
|
|
248
|
-
MODEL_DEEPSEEK_V4_FLASH: () => MODEL_DEEPSEEK_V4_FLASH,
|
|
249
|
-
MLX_WHISPER_BIN: () => MLX_WHISPER_BIN,
|
|
250
|
-
MAX_TELL_DEPTH: () => MAX_TELL_DEPTH,
|
|
251
|
-
LOG_DIR: () => LOG_DIR,
|
|
252
|
-
FILE_TAG_REGEX: () => FILE_TAG_REGEX,
|
|
253
|
-
FILE_EXTENSIONS_REGEX: () => FILE_EXTENSIONS_REGEX,
|
|
254
|
-
FFPROBE_BIN: () => FFPROBE_BIN,
|
|
255
|
-
FFMPEG_BIN: () => FFMPEG_BIN,
|
|
256
|
-
FASTER_WHISPER_WRAPPER: () => FASTER_WHISPER_WRAPPER,
|
|
257
|
-
FALLBACK_MODEL: () => FALLBACK_MODEL,
|
|
258
|
-
FALLBACK_AGENT: () => FALLBACK_AGENT,
|
|
259
|
-
DM_WORKSPACE_DIR: () => DM_WORKSPACE_DIR,
|
|
260
|
-
DM_RESP_DIR: () => DM_RESP_DIR,
|
|
261
|
-
DM_CMD_DIR: () => DM_CMD_DIR,
|
|
262
|
-
DEFAULT_TOPIC_EFFORT: () => DEFAULT_TOPIC_EFFORT,
|
|
263
|
-
DEFAULT_OUTPUT_LANGUAGE: () => DEFAULT_OUTPUT_LANGUAGE,
|
|
264
|
-
DECISION_SERVER: () => DECISION_SERVER,
|
|
265
|
-
DEBUG_FILE: () => DEBUG_FILE,
|
|
266
|
-
DATA_DIR: () => DATA_DIR,
|
|
267
|
-
CRON_WORKSPACE_DIR: () => CRON_WORKSPACE_DIR,
|
|
268
|
-
COMPACTION_LOG_SERVER: () => COMPACTION_LOG_SERVER,
|
|
269
|
-
CLAUDE_EXECUTABLE: () => CLAUDE_EXECUTABLE,
|
|
270
|
-
CANONICAL_MCP_PROXY_SERVER: () => CANONICAL_MCP_PROXY_SERVER,
|
|
271
|
-
BROWSER_RS_VERSION: () => BROWSER_RS_VERSION,
|
|
272
|
-
BROWSER_RS_MIN_SECURE_VERSION: () => BROWSER_RS_MIN_SECURE_VERSION,
|
|
273
|
-
BROWSER_RS_BIN: () => BROWSER_RS_BIN,
|
|
274
|
-
BROWSER_PROFILES_DIR: () => BROWSER_PROFILES_DIR,
|
|
275
|
-
BROWSER_DIR: () => BROWSER_DIR,
|
|
276
|
-
BINARY_EXTENSION: () => BINARY_EXTENSION,
|
|
277
|
-
BINARIES_DIR: () => BINARIES_DIR,
|
|
278
|
-
BG_BASH_MAX_PORT: () => BG_BASH_MAX_PORT,
|
|
279
|
-
BG_BASH_BASE_PORT: () => BG_BASH_BASE_PORT,
|
|
280
|
-
BASH_RS_VERSION: () => BASH_RS_VERSION,
|
|
281
|
-
BASH_RS_BIN: () => BASH_RS_BIN,
|
|
282
|
-
BASHRS_SPILL_ROOT: () => BASHRS_SPILL_ROOT,
|
|
283
|
-
AGENT_HEALTH_SERVER: () => AGENT_HEALTH_SERVER,
|
|
284
|
-
AGENTS_PROMPTS_DIR: () => AGENTS_PROMPTS_DIR,
|
|
285
|
-
ACTIVE_QUERY_STALE_MS: () => ACTIVE_QUERY_STALE_MS
|
|
286
|
-
});
|
|
287
196
|
import { execFileSync } from "child_process";
|
|
288
197
|
import { randomBytes } from "crypto";
|
|
289
198
|
import {
|
|
@@ -433,9 +342,6 @@ function safeWorkspaceSegment(value, fallback) {
|
|
|
433
342
|
function resolveTopicWorkspaceDir(topicId) {
|
|
434
343
|
return join(TOPIC_WORKSPACE_DIR, safeWorkspaceSegment(topicId, "topic"));
|
|
435
344
|
}
|
|
436
|
-
function isProductionEnv() {
|
|
437
|
-
return false;
|
|
438
|
-
}
|
|
439
345
|
function loadOrCreateLocalSecret(envKey, filename, options = {}) {
|
|
440
346
|
const envValue = envText(envKey);
|
|
441
347
|
const secretFile = resolve3(SECRETS_DIR, filename);
|
|
@@ -470,18 +376,13 @@ function loadOrCreateLocalSecret(envKey, filename, options = {}) {
|
|
|
470
376
|
return stored;
|
|
471
377
|
}
|
|
472
378
|
}
|
|
473
|
-
function getCleanEnv() {
|
|
474
|
-
const env = { ...process.env };
|
|
475
|
-
delete env.CLAUDECODE;
|
|
476
|
-
return env;
|
|
477
|
-
}
|
|
478
379
|
function resolveWhisperBackend() {
|
|
479
380
|
return envText("WHISPER_BACKEND") === "mlx-whisper" ? "mlx-whisper" : "faster-whisper";
|
|
480
381
|
}
|
|
481
382
|
function codexAuthFilePath() {
|
|
482
383
|
return process.env.NEGOTIUM_CODEX_AUTH_FILE || join(process.env.CODEX_HOME || join(homedir(), ".codex"), "auth.json");
|
|
483
384
|
}
|
|
484
|
-
var HOME, PROJECT_ROOT, STATE_DIR, WORKSPACE_DIR, TOPIC_WORKSPACE_DIR, SHARED_WIKI_DIR, CRON_WORKSPACE_DIR, BROWSER_DIR, BROWSER_PROFILES_DIR, BINARIES_DIR, SECRETS_DIR, DM_WORKSPACE_DIR, SESSION_WORKSPACE_DIR, CLAUDE_EXECUTABLE_ENV, CLAUDE_EXECUTABLE, DEFAULT_OUTPUT_LANGUAGE = "English", BINARY_EXTENSION, BROWSER_RS_VERSION = "v0.7.7", BROWSER_RS_MIN_SECURE_VERSION = "0.2.1", BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15000, SNIPPETS_API_URL, BROWSER_RS_BIN, BASH_RS_VERSION = "v0.1.10", BASH_RS_BIN, PLAYWRIGHT_MCP_BIN, TSX_BIN, TSX_LOADER_PATH, TSX_LOADER, TSCONFIG_PATH, SESSION_COMM_SERVER, TASK_SERVER, DECISION_SERVER, CANONICAL_MCP_PROXY_SERVER, WIKI_SERVER, TOKEN_STATS_SERVER, COMPACTION_LOG_SERVER, SESSION_HISTORY_SERVER, SYSTEM_HEALTH_SERVER, AGENT_HEALTH_SERVER, VAULT_SERVER, BG_BASH_BASE_PORT, BG_BASH_MAX_PORT, RUNTIME_MCP_SECRET, NODE_CONTROL_TOKEN, NODE_ID, VAULT_MASTER_KEY, NEGOTIUM_PORT, hostname, DATA_DIR, LOG_DIR, UPLOADS_DIR, VAULT_DIR, SESSIONS_DB, DEBUG_FILE, USERS_LOG_DIR, RUN_DIR,
|
|
385
|
+
var HOME, PROJECT_ROOT, STATE_DIR, WORKSPACE_DIR, TOPIC_WORKSPACE_DIR, SHARED_WIKI_DIR, CRON_WORKSPACE_DIR, BROWSER_DIR, BROWSER_PROFILES_DIR, BINARIES_DIR, SECRETS_DIR, DM_WORKSPACE_DIR, SESSION_WORKSPACE_DIR, CLAUDE_EXECUTABLE_ENV, CLAUDE_EXECUTABLE, DEFAULT_OUTPUT_LANGUAGE = "English", BINARY_EXTENSION, BROWSER_RS_VERSION = "v0.7.7", BROWSER_RS_MIN_SECURE_VERSION = "0.2.1", BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15000, SNIPPETS_API_URL, BROWSER_RS_BIN, BASH_RS_VERSION = "v0.1.10", BASH_RS_BIN, PLAYWRIGHT_MCP_BIN, TSX_BIN, TSX_LOADER_PATH, TSX_LOADER, TSCONFIG_PATH, SESSION_COMM_SERVER, TASK_SERVER, DECISION_SERVER, CANONICAL_MCP_PROXY_SERVER, WIKI_SERVER, TOKEN_STATS_SERVER, COMPACTION_LOG_SERVER, SESSION_HISTORY_SERVER, SYSTEM_HEALTH_SERVER, AGENT_HEALTH_SERVER, VAULT_SERVER, BG_BASH_BASE_PORT, BG_BASH_MAX_PORT, RUNTIME_MCP_SECRET, NODE_CONTROL_TOKEN, NODE_ID, VAULT_MASTER_KEY, NEGOTIUM_PORT, hostname, DATA_DIR, LOG_DIR, UPLOADS_DIR, VAULT_DIR, SESSIONS_DB, DEBUG_FILE, USERS_LOG_DIR, RUN_DIR, PROGRESS_DIR, DM_CMD_DIR, DM_RESP_DIR, SESSION_INBOX_DIR, SESSION_ASKS_DIR, BASHRS_SPILL_ROOT, PLAYWRIGHT_BASE_PORT, PLAYWRIGHT_MAX_PORT, PLAYWRIGHT_PORTS_DIR, ACTIVE_QUERY_STALE_MS, AGENTS_PROMPTS_DIR, RESOURCES_DIR, ABSOLUTE_PATH_PREFIX, FILE_EXTENSIONS_REGEX, FILE_TAG_REGEX, MODEL_SONNET = "claude-sonnet-5", MODEL_OPUS = "claude-opus-5-5", MODEL_FABLE = "claude-fable-5-1", FALLBACK_AGENT, FALLBACK_MODEL, DEFAULT_TOPIC_EFFORT, FFMPEG_BIN, FFPROBE_BIN, PYTHON_BIN, FASTER_WHISPER_WRAPPER, WHISPER_MODEL, TESSERACT_BIN, PDFTOTEXT_BIN, WHISPER_BACKEND, MLX_WHISPER_BIN, WHISPER_MODEL_MLX, _envMaxTellDepth, MAX_TELL_DEPTH;
|
|
485
386
|
var init_config = __esm(() => {
|
|
486
387
|
init_config_helpers();
|
|
487
388
|
init_logger();
|
|
@@ -538,7 +439,6 @@ var init_config = __esm(() => {
|
|
|
538
439
|
DEBUG_FILE = resolve3(DATA_DIR, "debug-users.json");
|
|
539
440
|
USERS_LOG_DIR = resolve3(DATA_DIR, "users");
|
|
540
441
|
RUN_DIR = resolveLocalStateDir("NEGOTIUM_RUN_DIR", "runtime");
|
|
541
|
-
RUNTIME_DIR = RUN_DIR;
|
|
542
442
|
PROGRESS_DIR = resolve3(RUN_DIR, "progress");
|
|
543
443
|
DM_CMD_DIR = resolve3(RUN_DIR, "dm-commands");
|
|
544
444
|
DM_RESP_DIR = resolve3(RUN_DIR, "dm-responses");
|
|
@@ -776,13 +676,6 @@ function validateActorTopicScope(value) {
|
|
|
776
676
|
}
|
|
777
677
|
return { ok: true, scope };
|
|
778
678
|
}
|
|
779
|
-
function parseActorTopicScope(value) {
|
|
780
|
-
const validated = validateActorTopicScope(value);
|
|
781
|
-
return validated.ok ? validated.scope : null;
|
|
782
|
-
}
|
|
783
|
-
function actorTopicScopeFrom(value) {
|
|
784
|
-
return parseActorTopicScope(value) ?? undefined;
|
|
785
|
-
}
|
|
786
679
|
function intersectActorTopicScopes(scopes) {
|
|
787
680
|
if (scopes.length === 0 || scopes.some((scope) => scope === undefined))
|
|
788
681
|
return;
|
|
@@ -893,13 +786,6 @@ function validateRemoteSessionGrant(value) {
|
|
|
893
786
|
}
|
|
894
787
|
return { ok: true, grant: { hubUrl: hubUrl.url, capability } };
|
|
895
788
|
}
|
|
896
|
-
function parseRemoteSessionGrant(value) {
|
|
897
|
-
const validated = validateRemoteSessionGrant(value);
|
|
898
|
-
return validated.ok ? validated.grant : null;
|
|
899
|
-
}
|
|
900
|
-
function remoteSessionGrantFrom(value) {
|
|
901
|
-
return parseRemoteSessionGrant(value) ?? undefined;
|
|
902
|
-
}
|
|
903
789
|
function remoteSessionGrantExpiry(grant) {
|
|
904
790
|
const payload = grant.capability.split(".")[1];
|
|
905
791
|
if (!payload)
|
|
@@ -938,7 +824,7 @@ function encodeRemoteSessionGrantArg(grant) {
|
|
|
938
824
|
throw new Error("remoteSession is required");
|
|
939
825
|
return Buffer.from(JSON.stringify(validated.grant), "utf-8").toString("base64url");
|
|
940
826
|
}
|
|
941
|
-
var REMOTE_SESSION_GRANT_LIMITS, GRANT_KEYS, LOOPBACK_HOSTS,
|
|
827
|
+
var REMOTE_SESSION_GRANT_LIMITS, GRANT_KEYS, LOOPBACK_HOSTS, MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH;
|
|
942
828
|
var init_remote_session_grant = __esm(() => {
|
|
943
829
|
REMOTE_SESSION_GRANT_LIMITS = Object.freeze({
|
|
944
830
|
maxHubUrlLength: 512,
|
|
@@ -947,7 +833,6 @@ var init_remote_session_grant = __esm(() => {
|
|
|
947
833
|
});
|
|
948
834
|
GRANT_KEYS = ["hubUrl", "capability"];
|
|
949
835
|
LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
|
|
950
|
-
REMOTE_SESSION_REPLY_TOKEN_PATTERN = /^rsr1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
951
836
|
MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH = REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength;
|
|
952
837
|
});
|
|
953
838
|
|
|
@@ -1292,12 +1177,12 @@ function createBackgroundBashManager(options = {}) {
|
|
|
1292
1177
|
usedPorts.clear();
|
|
1293
1178
|
knownContexts.clear();
|
|
1294
1179
|
const deadline = now() + 3000;
|
|
1295
|
-
await Promise.all(entries.map((instance) => new Promise((
|
|
1180
|
+
await Promise.all(entries.map((instance) => new Promise((resolve) => {
|
|
1296
1181
|
if (instance.process.exitCode !== null || instance.process.killed)
|
|
1297
|
-
return
|
|
1298
|
-
instance.process.once("exit",
|
|
1299
|
-
instance.process.once("error",
|
|
1300
|
-
const timer = setTimeout(
|
|
1182
|
+
return resolve();
|
|
1183
|
+
instance.process.once("exit", resolve);
|
|
1184
|
+
instance.process.once("error", resolve);
|
|
1185
|
+
const timer = setTimeout(resolve, Math.max(0, deadline - now()));
|
|
1301
1186
|
timer.unref?.();
|
|
1302
1187
|
})));
|
|
1303
1188
|
}
|
|
@@ -2000,7 +1885,7 @@ var init_api_messages = __esm(async () => {
|
|
|
2000
1885
|
|
|
2001
1886
|
// ../../packages/core/src/storage/topic-link-records.ts
|
|
2002
1887
|
function topicLinkSchemaIsCurrent(database, nodeId) {
|
|
2003
|
-
const objects = new Map(database.query("SELECT name, sql FROM sqlite_master WHERE type IN ('table','index','trigger')").all().map((
|
|
1888
|
+
const objects = new Map(database.query("SELECT name, sql FROM sqlite_master WHERE type IN ('table','index','trigger')").all().map((row) => [row.name, row.sql ?? ""]));
|
|
2004
1889
|
for (const name of [...SCHEMA_TABLES, ...SCHEMA_INDEXES, ...SCHEMA_INDEXES_TOMBSTONES]) {
|
|
2005
1890
|
if (!objects.has(name))
|
|
2006
1891
|
return false;
|
|
@@ -2017,7 +1902,7 @@ function topicLinkSchemaIsCurrent(database, nodeId) {
|
|
|
2017
1902
|
return false;
|
|
2018
1903
|
}
|
|
2019
1904
|
const identity = database.query("SELECT node_id, epoch_id FROM api_node_identity WHERE singleton = 1").all();
|
|
2020
|
-
if (identity.some((
|
|
1905
|
+
if (identity.some((row) => row.epoch_id === null))
|
|
2021
1906
|
return false;
|
|
2022
1907
|
if (nodeId && identity[0]?.node_id !== nodeId)
|
|
2023
1908
|
return false;
|
|
@@ -2856,9 +2741,6 @@ function rowToDto2(r, participants = getTopicParticipants(r.id), tellTargets) {
|
|
|
2856
2741
|
function normalizeTopicVisibility(value) {
|
|
2857
2742
|
return value === "hidden" ? "hidden" : "visible";
|
|
2858
2743
|
}
|
|
2859
|
-
function isTopicVisible(topic) {
|
|
2860
|
-
return topic.visibility !== "hidden";
|
|
2861
|
-
}
|
|
2862
2744
|
function normalizeTopicKind(value) {
|
|
2863
2745
|
return value === "channel" || value === "agent" || value === "manager" ? value : null;
|
|
2864
2746
|
}
|
|
@@ -5321,7 +5203,7 @@ var init_codex = __esm(async () => {
|
|
|
5321
5203
|
});
|
|
5322
5204
|
|
|
5323
5205
|
// ../../packages/core/src/version.ts
|
|
5324
|
-
var NEGOTIUM_VERSION = "0.23.
|
|
5206
|
+
var NEGOTIUM_VERSION = "0.23.10";
|
|
5325
5207
|
|
|
5326
5208
|
// ../../packages/core/src/agents/codex-native-multi-agent.ts
|
|
5327
5209
|
import { spawn as spawn2 } from "child_process";
|
|
@@ -5410,7 +5292,7 @@ async function bootstrapCodexModelCache(codexHome, cachePath) {
|
|
|
5410
5292
|
stdio: ["pipe", "pipe", "pipe"],
|
|
5411
5293
|
windowsHide: true
|
|
5412
5294
|
});
|
|
5413
|
-
const refreshed = new Promise((
|
|
5295
|
+
const refreshed = new Promise((resolve, reject) => {
|
|
5414
5296
|
let settled = false;
|
|
5415
5297
|
let stdoutBuffer = "";
|
|
5416
5298
|
let stderr = "";
|
|
@@ -5429,7 +5311,7 @@ async function bootstrapCodexModelCache(codexHome, cachePath) {
|
|
|
5429
5311
|
else if (!existsSync6(cachePath))
|
|
5430
5312
|
reject(new Error("Codex did not create its model cache"));
|
|
5431
5313
|
else
|
|
5432
|
-
|
|
5314
|
+
resolve();
|
|
5433
5315
|
};
|
|
5434
5316
|
const send = (message) => {
|
|
5435
5317
|
child.stdin.write(`${JSON.stringify(message)}
|
|
@@ -5495,12 +5377,12 @@ async function bootstrapCodexModelCache(codexHome, cachePath) {
|
|
|
5495
5377
|
function waitForChildExit(child, timeoutMs) {
|
|
5496
5378
|
if (child.exitCode !== null || child.signalCode !== null)
|
|
5497
5379
|
return Promise.resolve();
|
|
5498
|
-
return new Promise((
|
|
5499
|
-
const timer = setTimeout(
|
|
5380
|
+
return new Promise((resolve) => {
|
|
5381
|
+
const timer = setTimeout(resolve, timeoutMs);
|
|
5500
5382
|
timer.unref?.();
|
|
5501
5383
|
child.once("exit", () => {
|
|
5502
5384
|
clearTimeout(timer);
|
|
5503
|
-
|
|
5385
|
+
resolve();
|
|
5504
5386
|
});
|
|
5505
5387
|
});
|
|
5506
5388
|
}
|
|
@@ -5589,16 +5471,11 @@ var init_codex_native_multi_agent = __esm(() => {
|
|
|
5589
5471
|
});
|
|
5590
5472
|
|
|
5591
5473
|
// ../../packages/core/src/agents/codex-app-server.ts
|
|
5592
|
-
var exports_codex_app_server = {};
|
|
5593
|
-
__export(exports_codex_app_server, {
|
|
5594
|
-
forkCodexSession: () => forkCodexSession,
|
|
5595
|
-
createCodexAppServerForker: () => createCodexAppServerForker
|
|
5596
|
-
});
|
|
5597
5474
|
import { spawn as spawn3 } from "child_process";
|
|
5598
5475
|
function createCodexAppServerForker(host) {
|
|
5599
5476
|
return async (parentThreadId) => {
|
|
5600
5477
|
const child = host.spawnServer();
|
|
5601
|
-
return await new Promise((
|
|
5478
|
+
return await new Promise((resolve, reject) => {
|
|
5602
5479
|
let settled = false;
|
|
5603
5480
|
let stdoutBuffer = "";
|
|
5604
5481
|
let stderr = "";
|
|
@@ -5615,7 +5492,7 @@ function createCodexAppServerForker(host) {
|
|
|
5615
5492
|
if (error)
|
|
5616
5493
|
reject(error);
|
|
5617
5494
|
else if (result)
|
|
5618
|
-
|
|
5495
|
+
resolve(result);
|
|
5619
5496
|
else
|
|
5620
5497
|
reject(new Error("Codex thread fork returned no result"));
|
|
5621
5498
|
};
|
|
@@ -5752,8 +5629,8 @@ var init_codex_registry = __esm(async () => {
|
|
|
5752
5629
|
return { sessionId: threadId, rolloutPath };
|
|
5753
5630
|
},
|
|
5754
5631
|
async forkSession({ parentSessionId }) {
|
|
5755
|
-
|
|
5756
|
-
return await
|
|
5632
|
+
await init_codex_app_server();
|
|
5633
|
+
return await forkCodexSession(parentSessionId);
|
|
5757
5634
|
},
|
|
5758
5635
|
async cleanupRollouts({ sessionIds }) {
|
|
5759
5636
|
if (sessionIds.length === 0)
|
|
@@ -5934,11 +5811,6 @@ var init_maestro_registry = __esm(() => {
|
|
|
5934
5811
|
});
|
|
5935
5812
|
|
|
5936
5813
|
// ../../packages/core/src/agents/registry.ts
|
|
5937
|
-
var exports_registry = {};
|
|
5938
|
-
__export(exports_registry, {
|
|
5939
|
-
getRegistryOperations: () => getRegistryOperations,
|
|
5940
|
-
getRegistry: () => getRegistry
|
|
5941
|
-
});
|
|
5942
5814
|
function getRegistry(agent) {
|
|
5943
5815
|
return REGISTRIES[agent];
|
|
5944
5816
|
}
|
|
@@ -6294,8 +6166,8 @@ var init_claude_notices = __esm(() => {
|
|
|
6294
6166
|
SYSTEM_NOTICES = {
|
|
6295
6167
|
api_retry: (m) => {
|
|
6296
6168
|
const reason = m.error_status === null ? "Lost connection to Claude" : API_ERROR_TEXT[m.error] ?? "Claude request failed";
|
|
6297
|
-
const
|
|
6298
|
-
const when =
|
|
6169
|
+
const delay = Math.round(m.retry_delay_ms / 1000);
|
|
6170
|
+
const when = delay > 0 ? `in ${delay}s` : "now";
|
|
6299
6171
|
return `${reason} \xB7 retrying ${when} (${m.attempt}/${m.max_retries})`;
|
|
6300
6172
|
},
|
|
6301
6173
|
model_refusal_fallback: (m) => m.direction === "retry" ? `${modelLabel(m.original_model)} declined \xB7 ${modelLabel(m.fallback_model)} is answering instead` : m.content || undefined,
|
|
@@ -6416,11 +6288,11 @@ var DEFAULT_CONTEXT_WARNING_RATIO = 0.8;
|
|
|
6416
6288
|
// ../../packages/core/src/agents/claude-provider.ts
|
|
6417
6289
|
var exports_claude_provider = {};
|
|
6418
6290
|
__export(exports_claude_provider, {
|
|
6419
|
-
|
|
6420
|
-
spawnClaudeCodeProcessWithTreeKill: () => spawnClaudeCodeProcessWithTreeKill,
|
|
6421
|
-
claudeProvider: () => claudeProvider,
|
|
6291
|
+
buildClaudeDisallowedTools: () => buildClaudeDisallowedTools,
|
|
6422
6292
|
claudeBuiltInTools: () => claudeBuiltInTools,
|
|
6423
|
-
|
|
6293
|
+
claudeProvider: () => claudeProvider,
|
|
6294
|
+
spawnClaudeCodeProcessWithTreeKill: () => spawnClaudeCodeProcessWithTreeKill,
|
|
6295
|
+
substituteClaudeToolInput: () => substituteClaudeToolInput
|
|
6424
6296
|
});
|
|
6425
6297
|
import { spawn as spawn4 } from "child_process";
|
|
6426
6298
|
import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
|
|
@@ -6501,8 +6373,8 @@ function buildClaudePrompt(opts) {
|
|
|
6501
6373
|
}
|
|
6502
6374
|
function watchClaudeProcessExit(signal) {
|
|
6503
6375
|
let listener;
|
|
6504
|
-
const exited = new Promise((
|
|
6505
|
-
listener =
|
|
6376
|
+
const exited = new Promise((resolve) => {
|
|
6377
|
+
listener = resolve;
|
|
6506
6378
|
const listeners = claudeProcessExitListeners.get(signal) ?? new Set;
|
|
6507
6379
|
listeners.add(listener);
|
|
6508
6380
|
claudeProcessExitListeners.set(signal, listeners);
|
|
@@ -7099,12 +6971,12 @@ function createCodexTreeManager(host, options = {}) {
|
|
|
7099
6971
|
const previous = spawnChain;
|
|
7100
6972
|
let release;
|
|
7101
6973
|
let released = false;
|
|
7102
|
-
spawnChain = new Promise((
|
|
6974
|
+
spawnChain = new Promise((resolve) => {
|
|
7103
6975
|
release = () => {
|
|
7104
6976
|
if (released)
|
|
7105
6977
|
return;
|
|
7106
6978
|
released = true;
|
|
7107
|
-
|
|
6979
|
+
resolve();
|
|
7108
6980
|
};
|
|
7109
6981
|
});
|
|
7110
6982
|
await previous;
|
|
@@ -7211,7 +7083,7 @@ function createCodexTreeManager(host, options = {}) {
|
|
|
7211
7083
|
return;
|
|
7212
7084
|
const deadline = Date.now() + Math.max(0, graceMs);
|
|
7213
7085
|
while (Date.now() < deadline && hasSurvivors(plan.targets)) {
|
|
7214
|
-
await new Promise((
|
|
7086
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(100, Math.max(1, deadline - Date.now()))));
|
|
7215
7087
|
}
|
|
7216
7088
|
killStragglers(plan);
|
|
7217
7089
|
}
|
|
@@ -7539,8 +7411,8 @@ async function createCodexVaultHookBridge(userId) {
|
|
|
7539
7411
|
});
|
|
7540
7412
|
restrictIpcEndpoint(socketPath);
|
|
7541
7413
|
if (IS_WINDOWS2) {
|
|
7542
|
-
|
|
7543
|
-
const cached = await ensureCodexWindowsWrapperExe(join13(
|
|
7414
|
+
await Promise.resolve().then(() => init_config());
|
|
7415
|
+
const cached = await ensureCodexWindowsWrapperExe(join13(BINARIES_DIR, "codex-hook-wrapper"));
|
|
7544
7416
|
await copyFile(cached, wrapperPath);
|
|
7545
7417
|
await writeFile2(join13(root, "codex-with-hooks.cfg"), [process.execPath, codexCliScriptPath(), socketPath, token].join(`
|
|
7546
7418
|
`), { encoding: "utf8", mode: 384 });
|
|
@@ -8112,10 +7984,10 @@ var init_tool_format = __esm(() => {
|
|
|
8112
7984
|
// ../../packages/core/src/agents/codex-provider.ts
|
|
8113
7985
|
var exports_codex_provider = {};
|
|
8114
7986
|
__export(exports_codex_provider, {
|
|
8115
|
-
|
|
8116
|
-
normalizeCodexTurnUsage: () => normalizeCodexTurnUsage,
|
|
7987
|
+
codexNoticeStatus: () => codexNoticeStatus,
|
|
8117
7988
|
codexProvider: () => codexProvider,
|
|
8118
|
-
|
|
7989
|
+
normalizeCodexTurnUsage: () => normalizeCodexTurnUsage,
|
|
7990
|
+
toCodexMcpServers: () => toCodexMcpServers
|
|
8119
7991
|
});
|
|
8120
7992
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
8121
7993
|
import { existsSync as existsSync14, readFileSync as readFileSync11, realpathSync as realpathSync4, statSync as statSync5 } from "fs";
|
|
@@ -8423,9 +8295,9 @@ async function startStreamedWithTracking(thread, prompt, abortSignal, trackedPid
|
|
|
8423
8295
|
nextP.catch(() => {});
|
|
8424
8296
|
first = await Promise.race([nextP, startupTimeout]);
|
|
8425
8297
|
} catch (err) {
|
|
8426
|
-
const
|
|
8427
|
-
if (
|
|
8428
|
-
killCodexTrees(
|
|
8298
|
+
const novel = findNewCodexChildren(baseline);
|
|
8299
|
+
if (novel.length > 0) {
|
|
8300
|
+
killCodexTrees(novel);
|
|
8429
8301
|
}
|
|
8430
8302
|
await closeIterator(iter);
|
|
8431
8303
|
throw err;
|
|
@@ -8861,11 +8733,11 @@ var init_maestro_bootstrap_env = __esm(() => {
|
|
|
8861
8733
|
// ../../packages/core/src/agents/maestro-provider.ts
|
|
8862
8734
|
var exports_maestro_provider = {};
|
|
8863
8735
|
__export(exports_maestro_provider, {
|
|
8864
|
-
|
|
8865
|
-
maestroProvider: () => maestroProvider,
|
|
8866
|
-
buildMaestroToolResultTruncation: () => buildMaestroToolResultTruncation,
|
|
8736
|
+
buildMaestroDisallowedTools: () => buildMaestroDisallowedTools,
|
|
8867
8737
|
buildMaestroToolHooks: () => buildMaestroToolHooks,
|
|
8868
|
-
|
|
8738
|
+
buildMaestroToolResultTruncation: () => buildMaestroToolResultTruncation,
|
|
8739
|
+
maestroProvider: () => maestroProvider,
|
|
8740
|
+
resolveMaestroApiKeyOverrides: () => resolveMaestroApiKeyOverrides
|
|
8869
8741
|
});
|
|
8870
8742
|
import { resolve as resolve11 } from "path";
|
|
8871
8743
|
import { maestroProvider as sdkMaestroProvider, setMcpResolver } from "maestro-agent-sdk";
|
|
@@ -8993,18 +8865,18 @@ import { join as join15 } from "path";
|
|
|
8993
8865
|
async function* dispatchAgent(opts) {
|
|
8994
8866
|
switch (opts.agent) {
|
|
8995
8867
|
case "claude": {
|
|
8996
|
-
const { claudeProvider
|
|
8997
|
-
yield*
|
|
8868
|
+
const { claudeProvider } = await loadClaudeProvider();
|
|
8869
|
+
yield* claudeProvider(opts);
|
|
8998
8870
|
return;
|
|
8999
8871
|
}
|
|
9000
8872
|
case "codex": {
|
|
9001
|
-
const { codexProvider
|
|
9002
|
-
yield*
|
|
8873
|
+
const { codexProvider } = await loadCodexProvider();
|
|
8874
|
+
yield* codexProvider(opts);
|
|
9003
8875
|
return;
|
|
9004
8876
|
}
|
|
9005
8877
|
case "maestro": {
|
|
9006
|
-
const { maestroProvider
|
|
9007
|
-
yield*
|
|
8878
|
+
const { maestroProvider } = await loadMaestroProvider();
|
|
8879
|
+
yield* maestroProvider(opts);
|
|
9008
8880
|
return;
|
|
9009
8881
|
}
|
|
9010
8882
|
default: {
|
|
@@ -9035,8 +8907,8 @@ async function resolveSessionFileMissing(agent, sessionId, cwd) {
|
|
|
9035
8907
|
return true;
|
|
9036
8908
|
}
|
|
9037
8909
|
case "maestro": {
|
|
9038
|
-
const { hasActiveMaestroSession, maestroSessionPath
|
|
9039
|
-
return !existsSync15(
|
|
8910
|
+
const { hasActiveMaestroSession, maestroSessionPath } = await import("maestro-agent-sdk");
|
|
8911
|
+
return !existsSync15(maestroSessionPath(sessionId)) && !hasActiveMaestroSession(sessionId);
|
|
9040
8912
|
}
|
|
9041
8913
|
default: {
|
|
9042
8914
|
const _exhaustive = agent;
|
|
@@ -9115,24 +8987,6 @@ var init_agents = __esm(async () => {
|
|
|
9115
8987
|
});
|
|
9116
8988
|
|
|
9117
8989
|
// ../../packages/core/src/agents/model-catalog.ts
|
|
9118
|
-
var exports_model_catalog = {};
|
|
9119
|
-
__export(exports_model_catalog, {
|
|
9120
|
-
selectableModel: () => selectableModel,
|
|
9121
|
-
resolveWorkerModel: () => resolveWorkerModel,
|
|
9122
|
-
resolveWorkerDefaultModel: () => resolveWorkerDefaultModel,
|
|
9123
|
-
resolveModelForAgent: () => resolveModelForAgent,
|
|
9124
|
-
resolveDefaultModel: () => resolveDefaultModel,
|
|
9125
|
-
resolveCompactionExecution: () => resolveCompactionExecution,
|
|
9126
|
-
modelOwner: () => modelOwner,
|
|
9127
|
-
formatSelectableModel: () => formatSelectableModel,
|
|
9128
|
-
canonicalModelId: () => canonicalModelId,
|
|
9129
|
-
SELECTABLE_MODELS: () => SELECTABLE_MODELS,
|
|
9130
|
-
MODEL_OWNER: () => MODEL_OWNER,
|
|
9131
|
-
MODEL_COST_ROUTING_SUMMARY: () => MODEL_COST_ROUTING_SUMMARY,
|
|
9132
|
-
MODEL_COST_RESEARCHED_AT: () => MODEL_COST_RESEARCHED_AT,
|
|
9133
|
-
FALLBACK_ORDER: () => FALLBACK_ORDER,
|
|
9134
|
-
AGENT_DISPLAY_NAME: () => AGENT_DISPLAY_NAME
|
|
9135
|
-
});
|
|
9136
8990
|
function canonicalModelCasing() {
|
|
9137
8991
|
return Object.fromEntries(SELECTABLE_MODELS.map((candidate) => [candidate.model.toLowerCase(), candidate.model]));
|
|
9138
8992
|
}
|
|
@@ -9145,10 +8999,6 @@ function formatSelectableModel(candidate) {
|
|
|
9145
8999
|
const tier = `${candidate.intelligenceTier[0].toUpperCase()}${candidate.intelligenceTier.slice(1)}`;
|
|
9146
9000
|
return `${candidate.agent} / \`${candidate.model}\` [${tier}-level]: ${candidate.routingSummary}`;
|
|
9147
9001
|
}
|
|
9148
|
-
function selectableModel(value) {
|
|
9149
|
-
const canonical = canonicalModelId(value).toLowerCase();
|
|
9150
|
-
return SELECTABLE_MODELS.find((candidate) => candidate.model === canonical);
|
|
9151
|
-
}
|
|
9152
9002
|
function modelOwner(model) {
|
|
9153
9003
|
const lower = model.toLowerCase();
|
|
9154
9004
|
if (lower.startsWith("claude-"))
|
|
@@ -9201,7 +9051,7 @@ function resolveCompactionExecution(agent, registry) {
|
|
|
9201
9051
|
const effort = registry.validateEffort("medium") ? "medium" : registry.defaultEffort;
|
|
9202
9052
|
return { model, ...effort ? { effort } : {} };
|
|
9203
9053
|
}
|
|
9204
|
-
var MODEL_OWNER,
|
|
9054
|
+
var MODEL_OWNER, MODEL_COST_ROUTING_SUMMARY = "Cost basis (2026-09-05): Codex Pro 20x and Claude Max 20x are each $200/month; Maestro models are pay-per-token. DeepSeek Flash is cheapest. gpt-6-astra and Claude Fable 5.1 are the newest flagships, both priced at $10/M input / $50/M output.", CODEX_PRO_20X_COST = "ChatGPT Pro 20x subscription: $200/month", CODEX_COMMUNITY_WEEKLY = "Community plan-level observation: roughly 2\u20134B raw/cached tokens per week; fresh-input equivalent is much lower and unstable (low confidence)", CLAUDE_MAX_20X_COST = "Claude Max 20x subscription: $200/month", CLAUDE_COMMUNITY_SESSION = "Community observations vary from roughly 220\u2013250K locally displayed tokens per 5-hour session to billions of cache-heavy raw tokens per week; calibrated reports value a full weekly allowance around $680\u2013$1,900 at API rates. Recent heavy-model reports reach the weekly cap after about 4\u20135 full sessions (low confidence; not a token cap)", SELECTABLE_MODELS, SELECTABLE_MODEL_ALIASES, AGENT_DISPLAY_NAME;
|
|
9205
9055
|
var init_model_catalog = __esm(() => {
|
|
9206
9056
|
init_config();
|
|
9207
9057
|
MODEL_OWNER = {
|
|
@@ -9382,20 +9232,6 @@ var init_model_catalog = __esm(() => {
|
|
|
9382
9232
|
"glm-pro": "glm-5.3",
|
|
9383
9233
|
"glm-flash": "glm-5.3-flash"
|
|
9384
9234
|
};
|
|
9385
|
-
FALLBACK_ORDER = {
|
|
9386
|
-
claude: [
|
|
9387
|
-
{ agent: "maestro", model: "deepseek-pro" },
|
|
9388
|
-
{ agent: "codex", model: "luna" }
|
|
9389
|
-
],
|
|
9390
|
-
codex: [
|
|
9391
|
-
{ agent: "maestro", model: "deepseek-pro" },
|
|
9392
|
-
{ agent: "claude", model: "sonnet" }
|
|
9393
|
-
],
|
|
9394
|
-
maestro: [
|
|
9395
|
-
{ agent: "codex", model: "luna" },
|
|
9396
|
-
{ agent: "claude", model: "sonnet" }
|
|
9397
|
-
]
|
|
9398
|
-
};
|
|
9399
9235
|
AGENT_DISPLAY_NAME = {
|
|
9400
9236
|
claude: "Claude",
|
|
9401
9237
|
codex: "Codex",
|
|
@@ -10147,9 +9983,9 @@ function resolveTopicBrief(topicId, legacyTitle) {
|
|
|
10147
9983
|
const titleBrief = getTopicBrief(titleKey);
|
|
10148
9984
|
if (titleBrief)
|
|
10149
9985
|
return { brief: titleBrief, storageKey: titleKey };
|
|
10150
|
-
const
|
|
10151
|
-
if (
|
|
10152
|
-
return { brief:
|
|
9986
|
+
const current = getTopicBrief(topicId);
|
|
9987
|
+
if (current)
|
|
9988
|
+
return { brief: current, storageKey: topicId };
|
|
10153
9989
|
const legacy = titleKey === legacyTitle ? null : getTopicBrief(legacyTitle);
|
|
10154
9990
|
return legacy ? { brief: legacy, storageKey: legacyTitle } : null;
|
|
10155
9991
|
}
|
|
@@ -10769,11 +10605,6 @@ var init_archiver = __esm(async () => {
|
|
|
10769
10605
|
});
|
|
10770
10606
|
|
|
10771
10607
|
// ../../packages/core/src/agents/auth-check.ts
|
|
10772
|
-
var exports_auth_check = {};
|
|
10773
|
-
__export(exports_auth_check, {
|
|
10774
|
-
checkAgentModelAuth: () => checkAgentModelAuth,
|
|
10775
|
-
checkAgentAuth: () => checkAgentAuth
|
|
10776
|
-
});
|
|
10777
10608
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
10778
10609
|
import { existsSync as existsSync17 } from "fs";
|
|
10779
10610
|
import { homedir as homedir8, platform } from "os";
|
|
@@ -11105,8 +10936,8 @@ function createRoomQueryRegistry(host) {
|
|
|
11105
10936
|
clearInterval(previousMonitor);
|
|
11106
10937
|
activeByRoom.set(roomId, control);
|
|
11107
10938
|
const monitor = setInterval(() => {
|
|
11108
|
-
const
|
|
11109
|
-
if (!
|
|
10939
|
+
const current = activeByRoom.get(roomId);
|
|
10940
|
+
if (!current || current.queryId !== control.queryId) {
|
|
11110
10941
|
clearInterval(monitor);
|
|
11111
10942
|
if (leaseMonitors.get(roomId) === monitor)
|
|
11112
10943
|
leaseMonitors.delete(roomId);
|
|
@@ -11128,8 +10959,8 @@ function createRoomQueryRegistry(host) {
|
|
|
11128
10959
|
return true;
|
|
11129
10960
|
}
|
|
11130
10961
|
function clear(roomId, queryId) {
|
|
11131
|
-
const
|
|
11132
|
-
if (
|
|
10962
|
+
const current = activeByRoom.get(roomId);
|
|
10963
|
+
if (current?.queryId === queryId) {
|
|
11133
10964
|
activeByRoom.delete(roomId);
|
|
11134
10965
|
const monitor = leaseMonitors.get(roomId);
|
|
11135
10966
|
if (monitor)
|
|
@@ -11192,43 +11023,12 @@ var init_room_query_registry = () => {};
|
|
|
11192
11023
|
var init_types2 = () => {};
|
|
11193
11024
|
|
|
11194
11025
|
// ../../packages/core/src/query/active-rooms.ts
|
|
11195
|
-
var exports_active_rooms = {};
|
|
11196
|
-
__export(exports_active_rooms, {
|
|
11197
|
-
wsAbortReason: () => wsAbortReason,
|
|
11198
|
-
takeDeferredInject: () => takeDeferredInject,
|
|
11199
|
-
setRoomQuery: () => setRoomQuery,
|
|
11200
|
-
listRunningTopicQueries: () => listRunningTopicQueries,
|
|
11201
|
-
listRunningTopicIds: () => listRunningTopicIds,
|
|
11202
|
-
isolatedTurnRoomId: () => isolatedTurnRoomId,
|
|
11203
|
-
isUserOrigin: () => isUserOrigin,
|
|
11204
|
-
isTopicRunning: () => isTopicRunning,
|
|
11205
|
-
interSessionQueue: () => interSessionQueue,
|
|
11206
|
-
getRoomQueryStatus: () => getRoomQueryStatus,
|
|
11207
|
-
getRoomQuery: () => getRoomQuery,
|
|
11208
|
-
deferInject: () => deferInject,
|
|
11209
|
-
decideNewQuery: () => decideNewQuery,
|
|
11210
|
-
clearRoomQuery: () => clearRoomQuery,
|
|
11211
|
-
cancelDeferredInject: () => cancelDeferredInject,
|
|
11212
|
-
abortRoom: () => abortRoom,
|
|
11213
|
-
abortAllRooms: () => abortAllRooms,
|
|
11214
|
-
InterSessionQueue: () => InterSessionQueue,
|
|
11215
|
-
DeferredInjectBatcher: () => DeferredInjectBatcher
|
|
11216
|
-
});
|
|
11217
11026
|
function getRoomQuery(roomId) {
|
|
11218
11027
|
return roomQueryRegistry.get(roomId);
|
|
11219
11028
|
}
|
|
11220
|
-
function listRunningTopicQueries() {
|
|
11221
|
-
return roomQueryRegistry.listRunningTopicQueries();
|
|
11222
|
-
}
|
|
11223
|
-
function listRunningTopicIds() {
|
|
11224
|
-
return roomQueryRegistry.listRunningTopicIds();
|
|
11225
|
-
}
|
|
11226
11029
|
function isTopicRunning(topicId) {
|
|
11227
11030
|
return roomQueryRegistry.isTopicRunning(topicId);
|
|
11228
11031
|
}
|
|
11229
|
-
function getRoomQueryStatus(topicId, queryId) {
|
|
11230
|
-
return roomQueryRegistry.status(topicId, queryId);
|
|
11231
|
-
}
|
|
11232
11032
|
function setRoomQuery(control) {
|
|
11233
11033
|
return roomQueryRegistry.set(control);
|
|
11234
11034
|
}
|
|
@@ -11238,9 +11038,6 @@ function clearRoomQuery(roomId, queryId) {
|
|
|
11238
11038
|
function abortRoom(roomId, reason = "external" /* External */) {
|
|
11239
11039
|
return roomQueryRegistry.abort(roomId, reason);
|
|
11240
11040
|
}
|
|
11241
|
-
function abortAllRooms(reason = "external" /* External */) {
|
|
11242
|
-
return roomQueryRegistry.abortAll(reason);
|
|
11243
|
-
}
|
|
11244
11041
|
function decideNewQuery(topicId, incomingOrigin) {
|
|
11245
11042
|
return roomQueryRegistry.decide(topicId, incomingOrigin);
|
|
11246
11043
|
}
|
|
@@ -11406,9 +11203,6 @@ function deferInject(inject) {
|
|
|
11406
11203
|
function takeDeferredInject(topicId) {
|
|
11407
11204
|
return interSessionQueue.dequeueAll(topicId);
|
|
11408
11205
|
}
|
|
11409
|
-
function cancelDeferredInject(topicId, requestId) {
|
|
11410
|
-
return interSessionQueue.remove(topicId, requestId) !== undefined;
|
|
11411
|
-
}
|
|
11412
11206
|
function wsAbortReason(reason) {
|
|
11413
11207
|
return reason === "internal" /* Internal */ ? "superseded" : "stopped";
|
|
11414
11208
|
}
|
|
@@ -11701,8 +11495,8 @@ function settleTopicArchiveJob(topicId, archivePath, success) {
|
|
|
11701
11495
|
db.query("UPDATE api_topic_archive_jobs SET status = 'pending', updated_at = ? WHERE topic_id = ? AND archive_path = ?").run(new Date().toISOString(), topicId, archivePath);
|
|
11702
11496
|
return;
|
|
11703
11497
|
}
|
|
11704
|
-
const
|
|
11705
|
-
setTopicArchiveState(topicId, Math.max(
|
|
11498
|
+
const current = getTopicArchiveState(topicId)?.lastArchivedRowid ?? 0;
|
|
11499
|
+
setTopicArchiveState(topicId, Math.max(current, job.last_rowid), job.archive_path);
|
|
11706
11500
|
db.query("DELETE FROM api_topic_archive_jobs WHERE topic_id = ? AND archive_path = ?").run(topicId, archivePath);
|
|
11707
11501
|
})();
|
|
11708
11502
|
}
|
|
@@ -12385,7 +12179,7 @@ function createAskUserRuntime(host) {
|
|
|
12385
12179
|
if (ask.expired || ask.selectedLabel) {
|
|
12386
12180
|
return { ok: false, error: "This question is no longer awaiting an answer." };
|
|
12387
12181
|
}
|
|
12388
|
-
if (!kind && !ask.choices.some((
|
|
12182
|
+
if (!kind && !ask.choices.some((choice) => choice.label === label)) {
|
|
12389
12183
|
return { ok: false, error: "Invalid choice." };
|
|
12390
12184
|
}
|
|
12391
12185
|
const pending = pendingAsks.get(messageId);
|
|
@@ -12545,8 +12339,8 @@ function createAskUserRuntime(host) {
|
|
|
12545
12339
|
return errorResult(`Error: failed to persist ask_user_question: ${error instanceof Error ? error.message : String(error)}`);
|
|
12546
12340
|
}
|
|
12547
12341
|
let resolveAnswer;
|
|
12548
|
-
const promise = new Promise((
|
|
12549
|
-
resolveAnswer =
|
|
12342
|
+
const promise = new Promise((resolve) => {
|
|
12343
|
+
resolveAnswer = resolve;
|
|
12550
12344
|
});
|
|
12551
12345
|
pendingAsks.set(message.id, {
|
|
12552
12346
|
topicId: ctx.topicId,
|
|
@@ -12748,8 +12542,8 @@ var init_self_schedules = __esm(async () => {
|
|
|
12748
12542
|
});
|
|
12749
12543
|
|
|
12750
12544
|
// ../../packages/core/src/platform/playwright/manager-utils.ts
|
|
12751
|
-
function isLiveOwnedChildProcess(
|
|
12752
|
-
return
|
|
12545
|
+
function isLiveOwnedChildProcess(current, expected) {
|
|
12546
|
+
return current?.process === expected && expected.exitCode === null && expected.signalCode === null && !expected.killed;
|
|
12753
12547
|
}
|
|
12754
12548
|
function matchesSpawnedBrowserHealth(health, expectedSpawnNonce) {
|
|
12755
12549
|
if (!health || typeof health !== "object")
|
|
@@ -12993,10 +12787,10 @@ function findExecutableOnPath(command, environment = process.env) {
|
|
|
12993
12787
|
return null;
|
|
12994
12788
|
}
|
|
12995
12789
|
function resolveHeadedPlaywrightSpawn(command, args, options = {}) {
|
|
12996
|
-
const
|
|
12790
|
+
const platform = options.platform ?? process.platform;
|
|
12997
12791
|
const environment = options.environment ?? process.env;
|
|
12998
12792
|
const hasDisplay = Boolean(environment.DISPLAY?.trim() || environment.WAYLAND_DISPLAY?.trim());
|
|
12999
|
-
if (
|
|
12793
|
+
if (platform !== "linux" || hasDisplay) {
|
|
13000
12794
|
return { command, args: [...args], virtualDisplay: false };
|
|
13001
12795
|
}
|
|
13002
12796
|
const xvfbRun = (options.findExecutable ?? findExecutableOnPath)("xvfb-run", environment);
|
|
@@ -13045,7 +12839,7 @@ async function probeMcpTransport(transport, options = {}) {
|
|
|
13045
12839
|
}
|
|
13046
12840
|
}
|
|
13047
12841
|
async function probePlaywrightMcpTransports(port, capability, fetchImpl = fetch) {
|
|
13048
|
-
const
|
|
12842
|
+
const query = new URLSearchParams({ owner: PROBE_OWNER });
|
|
13049
12843
|
const baseUrl = `http://127.0.0.1:${port}`;
|
|
13050
12844
|
const ownerCapability = browserOwnerCapability(capability, PROBE_OWNER);
|
|
13051
12845
|
const capabilityHeaders = { "X-Browser-Capability": ownerCapability };
|
|
@@ -13054,14 +12848,14 @@ async function probePlaywrightMcpTransports(port, capability, fetchImpl = fetch)
|
|
|
13054
12848
|
headers.set("X-Browser-Capability", ownerCapability);
|
|
13055
12849
|
return fetchImpl(input, { ...init, headers });
|
|
13056
12850
|
};
|
|
13057
|
-
const sseTransport = new SSEClientTransport(new URL(`${baseUrl}/sse?${
|
|
12851
|
+
const sseTransport = new SSEClientTransport(new URL(`${baseUrl}/sse?${query}`), {
|
|
13058
12852
|
fetch: authenticatedFetch,
|
|
13059
12853
|
eventSourceInit: { fetch: authenticatedFetch },
|
|
13060
12854
|
requestInit: { headers: capabilityHeaders }
|
|
13061
12855
|
});
|
|
13062
12856
|
if (!await probeMcpTransport(sseTransport))
|
|
13063
12857
|
return false;
|
|
13064
|
-
const streamableTransport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp?${
|
|
12858
|
+
const streamableTransport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp?${query}`), {
|
|
13065
12859
|
fetch: authenticatedFetch,
|
|
13066
12860
|
requestInit: { headers: capabilityHeaders }
|
|
13067
12861
|
});
|
|
@@ -13191,9 +12985,9 @@ async function createBrowserVaultBroker(userId) {
|
|
|
13191
12985
|
if (typeof request.tool !== "string")
|
|
13192
12986
|
return { id, ok: false, error: "invalid tool" };
|
|
13193
12987
|
const leaseCutoff = Date.now() - LEASE_TTL_MS;
|
|
13194
|
-
for (const [
|
|
12988
|
+
for (const [lease, binding] of leases) {
|
|
13195
12989
|
if (binding.createdAt < leaseCutoff)
|
|
13196
|
-
leases.delete(
|
|
12990
|
+
leases.delete(lease);
|
|
13197
12991
|
}
|
|
13198
12992
|
if (leases.size >= MAX_ACTIVE_LEASES) {
|
|
13199
12993
|
return { id, ok: false, error: "too many active leases" };
|
|
@@ -13754,9 +13548,9 @@ async function spawnPlaywright(instanceKey, ownerId, reservedPort, browserBin =
|
|
|
13754
13548
|
const stderrTail = captureBoundedStderr(proc);
|
|
13755
13549
|
const startup = watchChildStartup(proc, stderrTail);
|
|
13756
13550
|
const reapCrashedBrowser = () => {
|
|
13757
|
-
const
|
|
13758
|
-
managerHost.cleanupBrowserProcessesForDataDir(
|
|
13759
|
-
cleanSingletonFiles(
|
|
13551
|
+
const userDataDir = resolveUserDataDir(instanceKey);
|
|
13552
|
+
managerHost.cleanupBrowserProcessesForDataDir(userDataDir);
|
|
13553
|
+
cleanSingletonFiles(userDataDir);
|
|
13760
13554
|
};
|
|
13761
13555
|
proc.once("error", (err) => {
|
|
13762
13556
|
logger.error({ err, instanceKey, stderr: stderrTail() || undefined }, "Playwright MCP error");
|
|
@@ -13825,8 +13619,8 @@ ${stderrTail()}` : ""));
|
|
|
13825
13619
|
}
|
|
13826
13620
|
async function supportsOwnerCleanup(port, capability) {
|
|
13827
13621
|
try {
|
|
13828
|
-
const
|
|
13829
|
-
const response = await fetch(`http://127.0.0.1:${port}/owners?${
|
|
13622
|
+
const query = new URLSearchParams({ owner: "__negotium_capability_probe__" });
|
|
13623
|
+
const response = await fetch(`http://127.0.0.1:${port}/owners?${query}`, {
|
|
13830
13624
|
method: "DELETE",
|
|
13831
13625
|
headers: {
|
|
13832
13626
|
"X-Browser-Capability": capability
|
|
@@ -13901,8 +13695,8 @@ async function closeBindingOwnerTabs(binding, owner) {
|
|
|
13901
13695
|
if (!instance)
|
|
13902
13696
|
return 0;
|
|
13903
13697
|
const port = instance.port;
|
|
13904
|
-
const
|
|
13905
|
-
const response = await fetch(`http://127.0.0.1:${port}/owners?${
|
|
13698
|
+
const query = new URLSearchParams({ owner });
|
|
13699
|
+
const response = await fetch(`http://127.0.0.1:${port}/owners?${query}`, {
|
|
13906
13700
|
method: "DELETE",
|
|
13907
13701
|
headers: {
|
|
13908
13702
|
"X-Browser-Capability": instance.capability
|
|
@@ -14602,7 +14396,7 @@ async function runIdleCompactForTopic(topicId, userId, options = {}) {
|
|
|
14602
14396
|
return "below-threshold";
|
|
14603
14397
|
}
|
|
14604
14398
|
const compact = options.compact ?? (async (id, actorId, reason) => {
|
|
14605
|
-
|
|
14399
|
+
await init_session();
|
|
14606
14400
|
return compactTopicSession(id, actorId, reason, { preemptive: false });
|
|
14607
14401
|
});
|
|
14608
14402
|
try {
|
|
@@ -14802,40 +14596,40 @@ function beginTransientBackgroundSession(userId, session) {
|
|
|
14802
14596
|
update(status, step) {
|
|
14803
14597
|
if (finished)
|
|
14804
14598
|
return;
|
|
14805
|
-
const
|
|
14806
|
-
if (
|
|
14599
|
+
const current = transientSessions.get(record.id);
|
|
14600
|
+
if (current !== record)
|
|
14807
14601
|
return;
|
|
14808
14602
|
const nextStatus = text(status, 160);
|
|
14809
14603
|
if (nextStatus)
|
|
14810
|
-
|
|
14604
|
+
current.status = nextStatus;
|
|
14811
14605
|
const nextStep = text(step);
|
|
14812
|
-
if (nextStep &&
|
|
14813
|
-
|
|
14606
|
+
if (nextStep && current.steps.at(-1) !== nextStep) {
|
|
14607
|
+
current.steps.push(nextStep);
|
|
14814
14608
|
}
|
|
14815
14609
|
},
|
|
14816
14610
|
setOutput(output) {
|
|
14817
14611
|
if (finished)
|
|
14818
14612
|
return;
|
|
14819
|
-
const
|
|
14820
|
-
if (
|
|
14613
|
+
const current = transientSessions.get(record.id);
|
|
14614
|
+
if (current !== record)
|
|
14821
14615
|
return;
|
|
14822
|
-
|
|
14616
|
+
current.output = output;
|
|
14823
14617
|
},
|
|
14824
14618
|
finish(status, step) {
|
|
14825
14619
|
if (finished)
|
|
14826
14620
|
return;
|
|
14827
14621
|
this.update(status ?? record.status, step);
|
|
14828
14622
|
finished = true;
|
|
14829
|
-
const
|
|
14830
|
-
if (
|
|
14623
|
+
const current = transientSessions.get(record.id);
|
|
14624
|
+
if (current !== record)
|
|
14831
14625
|
return;
|
|
14832
|
-
|
|
14833
|
-
|
|
14834
|
-
|
|
14626
|
+
current.active = false;
|
|
14627
|
+
current.expiresAt = Date.now() + Math.max(0, retentionMs);
|
|
14628
|
+
current.expiryTimer = setTimeout(() => {
|
|
14835
14629
|
if (transientSessions.get(record.id) === record)
|
|
14836
14630
|
transientSessions.delete(record.id);
|
|
14837
14631
|
}, Math.max(0, retentionMs));
|
|
14838
|
-
|
|
14632
|
+
current.expiryTimer.unref?.();
|
|
14839
14633
|
}
|
|
14840
14634
|
};
|
|
14841
14635
|
}
|
|
@@ -15094,8 +14888,8 @@ function markRuntimeUserTurnMessagesLogged(topicId, requestId, ownerId, loggedUs
|
|
|
15094
14888
|
return false;
|
|
15095
14889
|
return db.transaction(() => {
|
|
15096
14890
|
const requests = db.query("SELECT * FROM runtime_user_turn_requests WHERE topic_id = ? ORDER BY created_at ASC, rowid ASC").all(topicId).map(rowToRequest);
|
|
15097
|
-
const hasLoggedPrefix = (
|
|
15098
|
-
const candidate =
|
|
14891
|
+
const hasLoggedPrefix = (request) => loggedUserMessages.length <= request.userMessages.length && loggedUserMessages.every((message, index) => {
|
|
14892
|
+
const candidate = request.userMessages[index];
|
|
15099
14893
|
return candidate?.prompt === message.prompt && candidate.actorUserId === message.actorUserId && candidate.actorLabel === message.actorLabel && JSON.stringify(candidate.attachments ?? []) === JSON.stringify(message.attachments ?? []);
|
|
15100
14894
|
});
|
|
15101
14895
|
const request = requests.find((candidate) => candidate.requestId === requestId && candidate.claimedBy === ownerId && hasLoggedPrefix(candidate)) ?? requests.find((candidate) => candidate.execution?.supersededRequestIds?.includes(requestId) && hasLoggedPrefix(candidate));
|
|
@@ -15113,60 +14907,6 @@ function markRuntimeUserTurnMessagesLogged(topicId, requestId, ownerId, loggedUs
|
|
|
15113
14907
|
return result.changes === 1;
|
|
15114
14908
|
}).immediate();
|
|
15115
14909
|
}
|
|
15116
|
-
function claimNextRuntimeUserTurnRequest(ownerId, now = Date.now()) {
|
|
15117
|
-
return db.transaction(() => {
|
|
15118
|
-
const row = db.query(`SELECT r.*
|
|
15119
|
-
FROM runtime_user_turn_requests r
|
|
15120
|
-
LEFT JOIN runtime_turn_leases l ON l.topic_id = r.topic_id
|
|
15121
|
-
LEFT JOIN runtime_topic_state s ON s.topic_id = r.topic_id
|
|
15122
|
-
WHERE (l.topic_id IS NULL OR l.heartbeat_at < ?)
|
|
15123
|
-
AND (s.topic_id IS NULL OR s.maintenance = 0 OR s.heartbeat_at < ?)
|
|
15124
|
-
AND r.topic_epoch = COALESCE(s.epoch, 0)
|
|
15125
|
-
AND NOT EXISTS (
|
|
15126
|
-
SELECT 1
|
|
15127
|
-
FROM runtime_user_turn_requests active
|
|
15128
|
-
WHERE active.topic_id = r.topic_id
|
|
15129
|
-
AND active.request_id <> r.request_id
|
|
15130
|
-
AND active.claimed_at IS NOT NULL
|
|
15131
|
-
AND active.claimed_at >= ?
|
|
15132
|
-
)
|
|
15133
|
-
AND (
|
|
15134
|
-
(r.status = 'pending' AND (r.claimed_at IS NULL OR r.claimed_at < ?))
|
|
15135
|
-
OR (r.status = 'running' AND (r.claimed_at IS NULL OR r.claimed_at < ?))
|
|
15136
|
-
)
|
|
15137
|
-
ORDER BY r.created_at ASC, r.rowid ASC
|
|
15138
|
-
LIMIT 1`).get(now - TURN_LEASE_STALE_MS, now - TOPIC_MAINTENANCE_STALE_MS, now - REQUEST_CLAIM_STALE_MS, now - REQUEST_CLAIM_STALE_MS, now - REQUEST_CLAIM_STALE_MS);
|
|
15139
|
-
if (!row)
|
|
15140
|
-
return null;
|
|
15141
|
-
const updated = db.query(`UPDATE runtime_user_turn_requests
|
|
15142
|
-
SET claimed_by = ?, claimed_at = ?
|
|
15143
|
-
WHERE request_id = ? AND topic_id = ?
|
|
15144
|
-
AND (
|
|
15145
|
-
(status = 'pending' AND (claimed_at IS NULL OR claimed_at < ?))
|
|
15146
|
-
OR (status = 'running' AND (claimed_at IS NULL OR claimed_at < ?))
|
|
15147
|
-
)`).run(ownerId, now, row.request_id, row.topic_id, now - REQUEST_CLAIM_STALE_MS, now - REQUEST_CLAIM_STALE_MS);
|
|
15148
|
-
if (Number(updated.changes ?? 0) === 0)
|
|
15149
|
-
return null;
|
|
15150
|
-
return rowToRequest({ ...row, claimed_by: ownerId, claimed_at: now });
|
|
15151
|
-
}).immediate();
|
|
15152
|
-
}
|
|
15153
|
-
function markRuntimeUserTurnRunning(topicId, requestId, ownerId, queryId) {
|
|
15154
|
-
const result = db.query(`UPDATE runtime_user_turn_requests
|
|
15155
|
-
SET status = 'running', running_query_id = ?, claimed_at = ?
|
|
15156
|
-
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(queryId, Date.now(), topicId, requestId, ownerId);
|
|
15157
|
-
return Number(result.changes ?? 0) > 0;
|
|
15158
|
-
}
|
|
15159
|
-
function releaseRuntimeUserTurnClaim(topicId, requestId, ownerId) {
|
|
15160
|
-
const result = db.query(`UPDATE runtime_user_turn_requests
|
|
15161
|
-
SET status = 'pending', claimed_by = NULL, claimed_at = NULL, running_query_id = NULL
|
|
15162
|
-
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(topicId, requestId, ownerId);
|
|
15163
|
-
return Number(result.changes ?? 0) > 0;
|
|
15164
|
-
}
|
|
15165
|
-
function completeRuntimeUserTurnRequest(topicId, requestId, ownerId) {
|
|
15166
|
-
const result = db.query(`DELETE FROM runtime_user_turn_requests
|
|
15167
|
-
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(topicId, requestId, ownerId);
|
|
15168
|
-
return Number(result.changes ?? 0) > 0;
|
|
15169
|
-
}
|
|
15170
14910
|
function cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, epoch) {
|
|
15171
14911
|
const rows = db.query("SELECT request_id FROM runtime_user_turn_requests WHERE topic_id = ? AND topic_epoch < ?").all(topicId, epoch);
|
|
15172
14912
|
db.query("DELETE FROM runtime_user_turn_requests WHERE topic_id = ? AND topic_epoch < ?").run(topicId, epoch);
|
|
@@ -15204,36 +14944,10 @@ var init_runtime_turn_requests = __esm(async () => {
|
|
|
15204
14944
|
});
|
|
15205
14945
|
|
|
15206
14946
|
// ../../packages/core/src/topics/session.ts
|
|
15207
|
-
var exports_session = {};
|
|
15208
|
-
__export(exports_session, {
|
|
15209
|
-
splitCompactionPairs: () => splitCompactionPairs,
|
|
15210
|
-
shouldUseCompactionLog: () => shouldUseCompactionLog,
|
|
15211
|
-
shouldCompactForkEntries: () => shouldCompactForkEntries,
|
|
15212
|
-
restartTopicSession: () => restartTopicSession,
|
|
15213
|
-
createCompactedRolloutEntries: () => createCompactedRolloutEntries,
|
|
15214
|
-
compactTopicSession: () => compactTopicSession,
|
|
15215
|
-
COMPACTION_RETAINED_TAIL_TOKENS: () => COMPACTION_RETAINED_TAIL_TOKENS,
|
|
15216
|
-
AUTO_FORK_COMPACTION_TOKENS: () => AUTO_FORK_COMPACTION_TOKENS
|
|
15217
|
-
});
|
|
15218
14947
|
import { randomUUID as randomUUID12 } from "crypto";
|
|
15219
14948
|
import { mkdtempSync as mkdtempSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "fs";
|
|
15220
14949
|
import { tmpdir as tmpdir4 } from "os";
|
|
15221
14950
|
import { join as join23 } from "path";
|
|
15222
|
-
async function waitForMemoryArchive(settled, timeoutMs) {
|
|
15223
|
-
let timer;
|
|
15224
|
-
try {
|
|
15225
|
-
return await Promise.race([
|
|
15226
|
-
settled.then(() => true),
|
|
15227
|
-
new Promise((resolve17) => {
|
|
15228
|
-
timer = setTimeout(() => resolve17(false), timeoutMs);
|
|
15229
|
-
timer.unref?.();
|
|
15230
|
-
})
|
|
15231
|
-
]);
|
|
15232
|
-
} finally {
|
|
15233
|
-
if (timer)
|
|
15234
|
-
clearTimeout(timer);
|
|
15235
|
-
}
|
|
15236
|
-
}
|
|
15237
14951
|
async function fenceTopicWork(topicId, maintenance) {
|
|
15238
14952
|
for (const queryId of cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, maintenance.epoch)) {
|
|
15239
14953
|
WsHub.get().broadcastAborted(topicId, queryId, "stopped");
|
|
@@ -15258,97 +14972,6 @@ function hasTopicWorkInFlight(topicId) {
|
|
|
15258
14972
|
function topicIsQuiescedForNonPreemptiveWork(topicId) {
|
|
15259
14973
|
return !hasTopicWorkInFlight(topicId);
|
|
15260
14974
|
}
|
|
15261
|
-
async function restartTopicSession(topicId, userId, reason = "topic-session-restart", options = {}) {
|
|
15262
|
-
const topic = getTopic(topicId);
|
|
15263
|
-
if (!topic)
|
|
15264
|
-
return { text: "Topic not found.", isError: true };
|
|
15265
|
-
if (isLegacySharedGeneral(topic.id)) {
|
|
15266
|
-
return { text: "The legacy shared General session cannot be reset.", isError: true };
|
|
15267
|
-
}
|
|
15268
|
-
const owner = topic.participants.some((participant) => participant.userId === userId && participant.role === "owner");
|
|
15269
|
-
if (!owner)
|
|
15270
|
-
return { text: "Only the topic owner can reset the session.", isError: true };
|
|
15271
|
-
const maintenance = beginRuntimeTopicMaintenance(topicId);
|
|
15272
|
-
if (!maintenance)
|
|
15273
|
-
return { text: "Topic maintenance is already in progress.", isError: true };
|
|
15274
|
-
try {
|
|
15275
|
-
const fenceError = await fenceTopicWork(topicId, maintenance);
|
|
15276
|
-
if (fenceError)
|
|
15277
|
-
return { text: fenceError, isError: true };
|
|
15278
|
-
cancelIdleArchiveForTopic(topicId);
|
|
15279
|
-
cancelIdleCompactForTopic(topicId);
|
|
15280
|
-
const rawArchivePaths = [];
|
|
15281
|
-
try {
|
|
15282
|
-
for (const participantUserId of new Set([
|
|
15283
|
-
userId,
|
|
15284
|
-
...topic.participants.map((participant) => participant.userId)
|
|
15285
|
-
])) {
|
|
15286
|
-
const archived = archiveConversationEvents(topicId, topic.title, participantUserId, {
|
|
15287
|
-
reason: "reset"
|
|
15288
|
-
});
|
|
15289
|
-
if (archived)
|
|
15290
|
-
rawArchivePaths.push(archived.path);
|
|
15291
|
-
}
|
|
15292
|
-
} catch (error) {
|
|
15293
|
-
return {
|
|
15294
|
-
text: `Session reset could not archive the raw conversation: ${error instanceof Error ? error.message : String(error)}`,
|
|
15295
|
-
isError: true
|
|
15296
|
-
};
|
|
15297
|
-
}
|
|
15298
|
-
let settleMemoryArchive;
|
|
15299
|
-
const memoryArchiveSettled = new Promise((resolve17) => {
|
|
15300
|
-
settleMemoryArchive = resolve17;
|
|
15301
|
-
});
|
|
15302
|
-
const archiveStatus = (options.archiveMemory ?? archiveActiveTopicForMemory)(topicId, options.memoryUserId ?? userId, {
|
|
15303
|
-
reason: "reset",
|
|
15304
|
-
minMessages: 1,
|
|
15305
|
-
minExchanges: MIN_MEMORY_ARCHIVE_EXCHANGES,
|
|
15306
|
-
allowMentionOnly: true,
|
|
15307
|
-
skipBusyCheck: true,
|
|
15308
|
-
rawArchivePaths,
|
|
15309
|
-
onSettled: () => settleMemoryArchive?.()
|
|
15310
|
-
});
|
|
15311
|
-
if (archiveStatus === "archived") {
|
|
15312
|
-
const archiveFinished = await waitForMemoryArchive(memoryArchiveSettled, options.memoryArchiveWaitMs ?? RESET_MEMORY_ARCHIVE_WAIT_MS);
|
|
15313
|
-
if (!archiveFinished) {
|
|
15314
|
-
return {
|
|
15315
|
-
text: "Memory archiving did not finish in time. The session was not reset.",
|
|
15316
|
-
isError: true
|
|
15317
|
-
};
|
|
15318
|
-
}
|
|
15319
|
-
}
|
|
15320
|
-
if (!maintenance.isOwned()) {
|
|
15321
|
-
return { text: "Topic maintenance ownership was lost. Try again.", isError: true };
|
|
15322
|
-
}
|
|
15323
|
-
const sessionId = getTopicSessionId(topicId);
|
|
15324
|
-
const purgeLogs = options.purgeLogs ?? purgeTopicLogs;
|
|
15325
|
-
const participantUserIds = Array.from(new Set([userId, ...topic.participants.map((participant) => participant.userId)]));
|
|
15326
|
-
for (const [index, participantUserId] of participantUserIds.entries()) {
|
|
15327
|
-
let purged = false;
|
|
15328
|
-
try {
|
|
15329
|
-
purged = await purgeLogs({
|
|
15330
|
-
userId: participantUserId,
|
|
15331
|
-
topicName: topic.title,
|
|
15332
|
-
cwd: resolveTopicWorkspaceDir(topicId),
|
|
15333
|
-
extraSessions: index === 0 && topic.agent && sessionId ? [{ agent: topic.agent, sessionId }] : []
|
|
15334
|
-
});
|
|
15335
|
-
} catch (error) {
|
|
15336
|
-
logger.warn({ err: error, topicId, userId: participantUserId }, "restartTopicSession: participant context cleanup failed");
|
|
15337
|
-
}
|
|
15338
|
-
if (!purged) {
|
|
15339
|
-
return {
|
|
15340
|
-
text: "Session reset could not remove all provider context. The current session was kept.",
|
|
15341
|
-
isError: true
|
|
15342
|
-
};
|
|
15343
|
-
}
|
|
15344
|
-
}
|
|
15345
|
-
clearTopicSessionId(topicId, reason);
|
|
15346
|
-
clearQueryUsageAlert(userId, topicId);
|
|
15347
|
-
return { text: `Session reset for "${topic.title}". The next message starts fresh.` };
|
|
15348
|
-
} finally {
|
|
15349
|
-
maintenance.finish();
|
|
15350
|
-
}
|
|
15351
|
-
}
|
|
15352
14975
|
function previousCompactedSummary(entries) {
|
|
15353
14976
|
for (let index = entries.length - 2;index >= 0; index -= 1) {
|
|
15354
14977
|
const request = entries[index]?.event;
|
|
@@ -15363,9 +14986,9 @@ The assistant response is the authoritative summary of all earlier context.` &&
|
|
|
15363
14986
|
function withoutCompactionSentinels(entries) {
|
|
15364
14987
|
const filtered = [];
|
|
15365
14988
|
for (let index = 0;index < entries.length; index++) {
|
|
15366
|
-
const
|
|
14989
|
+
const current = entries[index]?.event;
|
|
15367
14990
|
const next = entries[index + 1]?.event;
|
|
15368
|
-
if (
|
|
14991
|
+
if (current?.type === "user_message" && current.synthetic === "compaction" && next?.type === "result") {
|
|
15369
14992
|
index += 1;
|
|
15370
14993
|
continue;
|
|
15371
14994
|
}
|
|
@@ -15415,18 +15038,18 @@ function retainedPairEntries(agent, pairs) {
|
|
|
15415
15038
|
}
|
|
15416
15039
|
return entries;
|
|
15417
15040
|
}
|
|
15418
|
-
function fitCompactionChunk(
|
|
15419
|
-
if (
|
|
15420
|
-
return
|
|
15041
|
+
function fitCompactionChunk(text, limit) {
|
|
15042
|
+
if (text.length <= limit)
|
|
15043
|
+
return text;
|
|
15421
15044
|
const marker = `
|
|
15422
15045
|
[\u2026]
|
|
15423
15046
|
`;
|
|
15424
15047
|
if (limit <= marker.length)
|
|
15425
|
-
return
|
|
15048
|
+
return text.slice(0, limit);
|
|
15426
15049
|
const available = limit - marker.length;
|
|
15427
15050
|
const headChars = Math.ceil(available * 0.6);
|
|
15428
15051
|
const tailChars = available - headChars;
|
|
15429
|
-
return `${
|
|
15052
|
+
return `${text.slice(0, headChars)}${marker}${text.slice(-tailChars)}`;
|
|
15430
15053
|
}
|
|
15431
15054
|
function buildCompactionSource(topicId, userId, entries, visibleMessages, providerPairs) {
|
|
15432
15055
|
const sections = [];
|
|
@@ -15827,9 +15450,9 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15827
15450
|
const compactionExecution = resolveCompactionExecution(agent, registry);
|
|
15828
15451
|
const cwd = resolveTopicWorkspaceDir(topicId);
|
|
15829
15452
|
const oldEntries = readConversation(userId, topic.title);
|
|
15830
|
-
let
|
|
15453
|
+
let compactEntries;
|
|
15831
15454
|
try {
|
|
15832
|
-
|
|
15455
|
+
compactEntries = await createCompactedRolloutEntries({
|
|
15833
15456
|
topicId,
|
|
15834
15457
|
topicTitle: topic.title,
|
|
15835
15458
|
userId,
|
|
@@ -15855,7 +15478,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15855
15478
|
try {
|
|
15856
15479
|
replacement = getRegistryOperations(agent).writeRollout({
|
|
15857
15480
|
cwd,
|
|
15858
|
-
entries:
|
|
15481
|
+
entries: compactEntries,
|
|
15859
15482
|
model,
|
|
15860
15483
|
...effort ? { effort } : {}
|
|
15861
15484
|
});
|
|
@@ -15885,7 +15508,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15885
15508
|
}
|
|
15886
15509
|
try {
|
|
15887
15510
|
replaceConversationStrict(userId, topic.title, [
|
|
15888
|
-
...
|
|
15511
|
+
...compactEntries,
|
|
15889
15512
|
...priorSessionEntries,
|
|
15890
15513
|
replacementSessionEntry
|
|
15891
15514
|
]);
|
|
@@ -15922,7 +15545,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15922
15545
|
} else {
|
|
15923
15546
|
try {
|
|
15924
15547
|
replaceConversationStrict(userId, topic.title, [
|
|
15925
|
-
...
|
|
15548
|
+
...compactEntries,
|
|
15926
15549
|
replacementSessionEntry
|
|
15927
15550
|
]);
|
|
15928
15551
|
} catch (manifestError) {
|
|
@@ -15976,45 +15599,11 @@ var init_session = __esm(async () => {
|
|
|
15976
15599
|
});
|
|
15977
15600
|
|
|
15978
15601
|
// ../../packages/core/src/topics/derive.ts
|
|
15979
|
-
var exports_derive = {};
|
|
15980
|
-
__export(exports_derive, {
|
|
15981
|
-
updateTopic: () => updateTopic,
|
|
15982
|
-
isParticipant: () => isParticipant,
|
|
15983
|
-
getVisibleTopics: () => getVisibleTopics,
|
|
15984
|
-
getTopics: () => getTopics,
|
|
15985
|
-
createDerivedTopic: () => createDerivedTopic,
|
|
15986
|
-
TopicTitleConflictError: () => TopicTitleConflictError,
|
|
15987
|
-
TopicForkCompactionError: () => TopicForkCompactionError,
|
|
15988
|
-
TopicDeriveBusyError: () => TopicDeriveBusyError
|
|
15989
|
-
});
|
|
15990
15602
|
import { createHash as createHash9, randomUUID as randomUUID13 } from "crypto";
|
|
15991
15603
|
import { mkdirSync as mkdirSync14, rmSync as rmSync5, unlinkSync as unlinkSync13 } from "fs";
|
|
15992
15604
|
function getTopics(opts = {}) {
|
|
15993
15605
|
return listTopics(opts).filter((topic) => !isLegacySharedGeneral(topic.id));
|
|
15994
15606
|
}
|
|
15995
|
-
function getVisibleTopics(opts = {}) {
|
|
15996
|
-
return getTopics(opts).filter(isTopicVisible).map((topic) => {
|
|
15997
|
-
if (!topic.agent)
|
|
15998
|
-
return topic;
|
|
15999
|
-
const registry = getRegistry(topic.agent);
|
|
16000
|
-
const config = getApiTopicConfig(topic.id);
|
|
16001
|
-
const requestedEffort = config?.effort ?? topic.defaultEffort;
|
|
16002
|
-
return {
|
|
16003
|
-
...topic,
|
|
16004
|
-
effectiveModel: resolveModelForAgent(topic.agent, config?.model ?? topic.defaultModel, registry),
|
|
16005
|
-
effectiveEffort: requestedEffort && registry.validateEffort(requestedEffort) ? requestedEffort : registry.defaultEffort
|
|
16006
|
-
};
|
|
16007
|
-
});
|
|
16008
|
-
}
|
|
16009
|
-
function updateTopic(topicId, patch) {
|
|
16010
|
-
const topic = getTopic(topicId);
|
|
16011
|
-
if (!topic)
|
|
16012
|
-
return false;
|
|
16013
|
-
Object.assign(topic, patch);
|
|
16014
|
-
upsertTopic(topic);
|
|
16015
|
-
WsHub.get().broadcastTopicUpdated(topicId);
|
|
16016
|
-
return true;
|
|
16017
|
-
}
|
|
16018
15607
|
function isParticipant(topic, userId) {
|
|
16019
15608
|
return topic.participants.some((p) => p.userId === userId);
|
|
16020
15609
|
}
|
|
@@ -16430,9 +16019,9 @@ function subagentLineageTopicIds(currentTopicId) {
|
|
|
16430
16019
|
const children = new Set;
|
|
16431
16020
|
if (!currentTopicId)
|
|
16432
16021
|
return { reachable, children };
|
|
16433
|
-
const
|
|
16434
|
-
if (
|
|
16435
|
-
reachable.add(
|
|
16022
|
+
const current = getTopic(currentTopicId);
|
|
16023
|
+
if (current?.isSubagent && current.parentTopicId) {
|
|
16024
|
+
reachable.add(current.parentTopicId);
|
|
16436
16025
|
for (const id of listSubagentTellTargetIds(currentTopicId))
|
|
16437
16026
|
reachable.add(id);
|
|
16438
16027
|
}
|
|
@@ -16558,9 +16147,9 @@ function cleanupSessionInboxFiles(userId, topicId, legacyTopicTitle) {
|
|
|
16558
16147
|
try {
|
|
16559
16148
|
unlinkSync15(path);
|
|
16560
16149
|
deleted++;
|
|
16561
|
-
} catch (
|
|
16562
|
-
if (
|
|
16563
|
-
logger.warn({ err
|
|
16150
|
+
} catch (err) {
|
|
16151
|
+
if (err?.code !== "ENOENT") {
|
|
16152
|
+
logger.warn({ err, path, topicId, userId }, "topic cleanup: inbox unlink failed");
|
|
16564
16153
|
}
|
|
16565
16154
|
}
|
|
16566
16155
|
}
|
|
@@ -16685,9 +16274,9 @@ function hubHeaders(bearer) {
|
|
|
16685
16274
|
};
|
|
16686
16275
|
}
|
|
16687
16276
|
function errorText(status, body, fallback) {
|
|
16688
|
-
const
|
|
16689
|
-
if (typeof
|
|
16690
|
-
return
|
|
16277
|
+
const text = body?.error;
|
|
16278
|
+
if (typeof text === "string" && text.trim())
|
|
16279
|
+
return text.trim();
|
|
16691
16280
|
return `${fallback} (hub answered ${status})`;
|
|
16692
16281
|
}
|
|
16693
16282
|
function describeFailure(status, body) {
|
|
@@ -16783,19 +16372,6 @@ var init_actor_policy = __esm(async () => {
|
|
|
16783
16372
|
await init_actor_topic_reach();
|
|
16784
16373
|
});
|
|
16785
16374
|
// ../../packages/core/src/storage/session-asks.ts
|
|
16786
|
-
var exports_session_asks = {};
|
|
16787
|
-
__export(exports_session_asks, {
|
|
16788
|
-
releasePendingAsk: () => releasePendingAsk,
|
|
16789
|
-
markPendingAskState: () => markPendingAskState,
|
|
16790
|
-
markPendingAskSources: () => markPendingAskSources,
|
|
16791
|
-
listPendingAsksForCaller: () => listPendingAsksForCaller,
|
|
16792
|
-
describePendingAskState: () => describePendingAskState,
|
|
16793
|
-
deletePendingAsksForTopic: () => deletePendingAsksForTopic,
|
|
16794
|
-
createPendingAsk: () => createPendingAsk,
|
|
16795
|
-
clearPendingAskSources: () => clearPendingAskSources,
|
|
16796
|
-
clearPendingAsk: () => clearPendingAsk,
|
|
16797
|
-
PENDING_ASK_TTL_MS: () => PENDING_ASK_TTL_MS
|
|
16798
|
-
});
|
|
16799
16375
|
import { createHash as createHash10 } from "crypto";
|
|
16800
16376
|
import {
|
|
16801
16377
|
closeSync as closeSync2,
|
|
@@ -16817,8 +16393,8 @@ function encodeAskKey(key) {
|
|
|
16817
16393
|
return JSON.stringify([key.from, key.to]);
|
|
16818
16394
|
}
|
|
16819
16395
|
function pendingAskPath(key) {
|
|
16820
|
-
const
|
|
16821
|
-
return join28(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${
|
|
16396
|
+
const digest = createHash10("sha256").update(encodeAskKey(key)).digest("hex");
|
|
16397
|
+
return join28(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${digest}.pending`);
|
|
16822
16398
|
}
|
|
16823
16399
|
function v2PendingAskPath(key) {
|
|
16824
16400
|
const encoded = Buffer.from(encodeAskKey(key), "utf8").toString("base64url");
|
|
@@ -16844,10 +16420,10 @@ function parsePendingAskFilename(fileName) {
|
|
|
16844
16420
|
}
|
|
16845
16421
|
} catch {}
|
|
16846
16422
|
}
|
|
16847
|
-
const
|
|
16848
|
-
if (
|
|
16423
|
+
const sep = raw.indexOf("___");
|
|
16424
|
+
if (sep < 0)
|
|
16849
16425
|
return null;
|
|
16850
|
-
return { from: raw.slice(0,
|
|
16426
|
+
return { from: raw.slice(0, sep), to: raw.slice(sep + 3) };
|
|
16851
16427
|
}
|
|
16852
16428
|
function readPendingAskFile(path, fallback) {
|
|
16853
16429
|
try {
|
|
@@ -16890,16 +16466,6 @@ function readPendingAskFile(path, fallback) {
|
|
|
16890
16466
|
return null;
|
|
16891
16467
|
}
|
|
16892
16468
|
}
|
|
16893
|
-
function isStale(record, path) {
|
|
16894
|
-
const ts = record ? Date.parse(record.updatedAt || record.createdAt) : Number.NaN;
|
|
16895
|
-
if (Number.isFinite(ts))
|
|
16896
|
-
return Date.now() - ts > PENDING_ASK_TTL_MS;
|
|
16897
|
-
try {
|
|
16898
|
-
return Date.now() - statSync8(path).mtimeMs > PENDING_ASK_TTL_MS;
|
|
16899
|
-
} catch {
|
|
16900
|
-
return false;
|
|
16901
|
-
}
|
|
16902
|
-
}
|
|
16903
16469
|
function writePendingAsk(record) {
|
|
16904
16470
|
const path = pendingAskPath(record);
|
|
16905
16471
|
mkdirSync16(pendingAskDir(record.userId), { recursive: true });
|
|
@@ -16925,10 +16491,10 @@ function writePendingAskIfAbsent(record) {
|
|
|
16925
16491
|
}
|
|
16926
16492
|
}
|
|
16927
16493
|
function readPendingAsk(key) {
|
|
16928
|
-
const
|
|
16929
|
-
const canonical = readPendingAskFile(
|
|
16494
|
+
const canonicalPath = pendingAskPath(key);
|
|
16495
|
+
const canonical = readPendingAskFile(canonicalPath, key);
|
|
16930
16496
|
if (canonical && canonical.from === key.from && canonical.to === key.to) {
|
|
16931
|
-
return { path:
|
|
16497
|
+
return { path: canonicalPath, record: canonical };
|
|
16932
16498
|
}
|
|
16933
16499
|
for (const compatibilityPath of [v2PendingAskPath(key), legacyPendingAskPath(key)]) {
|
|
16934
16500
|
if (!compatibilityPath)
|
|
@@ -16937,67 +16503,17 @@ function readPendingAsk(key) {
|
|
|
16937
16503
|
if (!legacy || legacy.from !== key.from || legacy.to !== key.to)
|
|
16938
16504
|
continue;
|
|
16939
16505
|
const migrated = writePendingAskIfAbsent(legacy);
|
|
16940
|
-
const next = migrated ? legacy : readPendingAskFile(
|
|
16506
|
+
const next = migrated ? legacy : readPendingAskFile(canonicalPath, key);
|
|
16941
16507
|
if (next && next.from === key.from && next.to === key.to) {
|
|
16942
16508
|
try {
|
|
16943
16509
|
unlinkSync16(compatibilityPath);
|
|
16944
16510
|
} catch {}
|
|
16945
|
-
return { path:
|
|
16511
|
+
return { path: canonicalPath, record: next };
|
|
16946
16512
|
}
|
|
16947
16513
|
return { path: compatibilityPath, record: legacy };
|
|
16948
16514
|
}
|
|
16949
16515
|
return null;
|
|
16950
16516
|
}
|
|
16951
|
-
function createPendingAsk(args) {
|
|
16952
|
-
const migrated = readPendingAsk(args);
|
|
16953
|
-
if (migrated && !isStale(migrated.record, migrated.path)) {
|
|
16954
|
-
return { ok: false, existing: migrated.record, stale: false };
|
|
16955
|
-
}
|
|
16956
|
-
if (migrated) {
|
|
16957
|
-
try {
|
|
16958
|
-
unlinkSync16(migrated.path);
|
|
16959
|
-
} catch {
|
|
16960
|
-
return { ok: false, existing: migrated.record, stale: true };
|
|
16961
|
-
}
|
|
16962
|
-
}
|
|
16963
|
-
const path = pendingAskPath(args);
|
|
16964
|
-
const now = new Date().toISOString();
|
|
16965
|
-
const record = {
|
|
16966
|
-
userId: args.userId,
|
|
16967
|
-
from: args.from,
|
|
16968
|
-
to: args.to,
|
|
16969
|
-
requestId: args.requestId,
|
|
16970
|
-
contextId: args.contextId,
|
|
16971
|
-
state: "requested",
|
|
16972
|
-
createdAt: now,
|
|
16973
|
-
updatedAt: now
|
|
16974
|
-
};
|
|
16975
|
-
mkdirSync16(pendingAskDir(args.userId), { recursive: true });
|
|
16976
|
-
for (let attempt = 0;attempt < 2; attempt++) {
|
|
16977
|
-
let fd = null;
|
|
16978
|
-
try {
|
|
16979
|
-
fd = openSync2(path, "wx");
|
|
16980
|
-
writeFileSync14(fd, `${JSON.stringify(record)}
|
|
16981
|
-
`);
|
|
16982
|
-
return { ok: true, record };
|
|
16983
|
-
} catch (err2) {
|
|
16984
|
-
if (err2.code !== "EEXIST")
|
|
16985
|
-
throw err2;
|
|
16986
|
-
const existing = readPendingAskFile(path, args);
|
|
16987
|
-
if (!isStale(existing, path))
|
|
16988
|
-
return { ok: false, existing, stale: false };
|
|
16989
|
-
try {
|
|
16990
|
-
unlinkSync16(path);
|
|
16991
|
-
} catch {
|
|
16992
|
-
return { ok: false, existing, stale: true };
|
|
16993
|
-
}
|
|
16994
|
-
} finally {
|
|
16995
|
-
if (fd !== null)
|
|
16996
|
-
closeSync2(fd);
|
|
16997
|
-
}
|
|
16998
|
-
}
|
|
16999
|
-
return { ok: false, existing: readPendingAskFile(path, args), stale: true };
|
|
17000
|
-
}
|
|
17001
16517
|
function markPendingAskState(args) {
|
|
17002
16518
|
const pending = readPendingAsk(args);
|
|
17003
16519
|
if (!pending)
|
|
@@ -17031,83 +16547,6 @@ function clearPendingAsk(args) {
|
|
|
17031
16547
|
return false;
|
|
17032
16548
|
}
|
|
17033
16549
|
}
|
|
17034
|
-
function releasePendingAsk(args) {
|
|
17035
|
-
if (clearPendingAsk(args))
|
|
17036
|
-
return true;
|
|
17037
|
-
const still = readPendingAsk(args);
|
|
17038
|
-
return !still || still.record.requestId !== args.requestId;
|
|
17039
|
-
}
|
|
17040
|
-
function markPendingAskSources(args) {
|
|
17041
|
-
for (const source of args.sources ?? []) {
|
|
17042
|
-
if (!source.from)
|
|
17043
|
-
continue;
|
|
17044
|
-
markPendingAskState({
|
|
17045
|
-
userId: args.userId,
|
|
17046
|
-
from: args.callerTopic,
|
|
17047
|
-
to: source.from,
|
|
17048
|
-
requestId: source.requestId,
|
|
17049
|
-
state: args.state
|
|
17050
|
-
});
|
|
17051
|
-
}
|
|
17052
|
-
}
|
|
17053
|
-
function clearPendingAskSources(args) {
|
|
17054
|
-
for (const source of args.sources ?? []) {
|
|
17055
|
-
if (!source.from)
|
|
17056
|
-
continue;
|
|
17057
|
-
clearPendingAsk({
|
|
17058
|
-
userId: args.userId,
|
|
17059
|
-
from: args.callerTopic,
|
|
17060
|
-
to: source.from,
|
|
17061
|
-
requestId: source.requestId
|
|
17062
|
-
});
|
|
17063
|
-
}
|
|
17064
|
-
}
|
|
17065
|
-
function listPendingAsksForCaller(args) {
|
|
17066
|
-
const dir = pendingAskDir(args.userId);
|
|
17067
|
-
let files;
|
|
17068
|
-
try {
|
|
17069
|
-
files = readdirSync4(dir);
|
|
17070
|
-
} catch {
|
|
17071
|
-
return [];
|
|
17072
|
-
}
|
|
17073
|
-
const records = new Map;
|
|
17074
|
-
for (const fileName of files) {
|
|
17075
|
-
const isV3 = fileName.startsWith(ASK_FILENAME_PREFIX);
|
|
17076
|
-
const parsed = isV3 ? { from: args.from, to: "" } : parsePendingAskFilename(fileName);
|
|
17077
|
-
if (!parsed)
|
|
17078
|
-
continue;
|
|
17079
|
-
const path = join28(dir, fileName);
|
|
17080
|
-
const record = readPendingAskFile(path, {
|
|
17081
|
-
userId: args.userId,
|
|
17082
|
-
from: parsed.from,
|
|
17083
|
-
to: parsed.to
|
|
17084
|
-
});
|
|
17085
|
-
if (!record || record.from !== args.from)
|
|
17086
|
-
continue;
|
|
17087
|
-
if (isStale(record, path)) {
|
|
17088
|
-
try {
|
|
17089
|
-
unlinkSync16(path);
|
|
17090
|
-
} catch {}
|
|
17091
|
-
continue;
|
|
17092
|
-
}
|
|
17093
|
-
const canonical = readPendingAsk(record);
|
|
17094
|
-
if (!canonical || canonical.record.from !== args.from)
|
|
17095
|
-
continue;
|
|
17096
|
-
if (path !== canonical.path) {
|
|
17097
|
-
try {
|
|
17098
|
-
unlinkSync16(path);
|
|
17099
|
-
} catch {}
|
|
17100
|
-
}
|
|
17101
|
-
if (isStale(canonical.record, canonical.path)) {
|
|
17102
|
-
try {
|
|
17103
|
-
unlinkSync16(canonical.path);
|
|
17104
|
-
} catch {}
|
|
17105
|
-
continue;
|
|
17106
|
-
}
|
|
17107
|
-
records.set(encodeAskKey(canonical.record), canonical.record);
|
|
17108
|
-
}
|
|
17109
|
-
return [...records.values()];
|
|
17110
|
-
}
|
|
17111
16550
|
function deletePendingAsksForTopic(args) {
|
|
17112
16551
|
const dir = pendingAskDir(args.userId);
|
|
17113
16552
|
let files;
|
|
@@ -17136,18 +16575,6 @@ function deletePendingAsksForTopic(args) {
|
|
|
17136
16575
|
}
|
|
17137
16576
|
return deleted;
|
|
17138
16577
|
}
|
|
17139
|
-
function describePendingAskState(state) {
|
|
17140
|
-
switch (state) {
|
|
17141
|
-
case "requested":
|
|
17142
|
-
return "\uB300\uC0C1 \uC138\uC158 \uCC98\uB9AC \uC911";
|
|
17143
|
-
case "reply_ready":
|
|
17144
|
-
return "\uC751\uB2F5 \uC0DD\uC131 \uC644\uB8CC, \uC774 \uC138\uC158 \uC8FC\uC785 \uC900\uBE44 \uC911";
|
|
17145
|
-
case "queued_for_caller":
|
|
17146
|
-
return "\uC751\uB2F5 \uC0DD\uC131 \uC644\uB8CC, \uC774 \uC138\uC158 \uC2E4\uD589 \uC885\uB8CC \uD6C4 \uC8FC\uC785 \uB300\uAE30 \uC911";
|
|
17147
|
-
case "injecting_to_caller":
|
|
17148
|
-
return "\uC751\uB2F5\uC744 \uC774 \uC138\uC158\uC5D0 \uC8FC\uC785 \uC911";
|
|
17149
|
-
}
|
|
17150
|
-
}
|
|
17151
16578
|
var PENDING_ASK_TTL_MS, ASK_FILENAME_PREFIX = "v3-", V2_ASK_FILENAME_PREFIX = "v2-";
|
|
17152
16579
|
var init_session_asks = __esm(async () => {
|
|
17153
16580
|
await init_storage_host();
|
|
@@ -17249,10 +16676,10 @@ function deferRemoteSessionReplyOutbox(args) {
|
|
|
17249
16676
|
if (!row)
|
|
17250
16677
|
return;
|
|
17251
16678
|
const attempts = Number(row.attempts) + 1;
|
|
17252
|
-
const
|
|
16679
|
+
const delay = args.retryMs ?? remoteSessionRetryDelayMs(attempts, args.random);
|
|
17253
16680
|
db.query(`UPDATE remote_session_reply_outbox
|
|
17254
16681
|
SET attempts = ?, next_attempt_at = ?, last_error = ?
|
|
17255
|
-
WHERE request_id = ?`).run(attempts, now +
|
|
16682
|
+
WHERE request_id = ?`).run(attempts, now + delay, args.error.slice(0, 500), args.requestId);
|
|
17256
16683
|
})();
|
|
17257
16684
|
}
|
|
17258
16685
|
function purgeExpiredRemoteSessionReplyOutbox(now = Date.now()) {
|
|
@@ -17423,37 +16850,9 @@ var init_remote_session_reply_outbox = __esm(async () => {
|
|
|
17423
16850
|
});
|
|
17424
16851
|
|
|
17425
16852
|
// ../../packages/core/src/mcp/session-comm/peer-forward.ts
|
|
17426
|
-
var exports_peer_forward = {};
|
|
17427
|
-
__export(exports_peer_forward, {
|
|
17428
|
-
registerPeerSessionBridge: () => registerPeerSessionBridge,
|
|
17429
|
-
peerSessionsForUser: () => peerSessionsForUser,
|
|
17430
|
-
parseHubRemoteReplyRoute: () => parseHubRemoteReplyRoute,
|
|
17431
|
-
isHubRemoteReplyRoute: () => isHubRemoteReplyRoute,
|
|
17432
|
-
forwardToPeer: () => forwardToPeer,
|
|
17433
|
-
deliverPeerReply: () => deliverPeerReply
|
|
17434
|
-
});
|
|
17435
16853
|
function isHubRemoteReplyRoute(route) {
|
|
17436
16854
|
return route.via === "hub";
|
|
17437
16855
|
}
|
|
17438
|
-
function parseHubRemoteReplyRoute(value) {
|
|
17439
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
17440
|
-
return null;
|
|
17441
|
-
const route = value;
|
|
17442
|
-
if (route.via !== "hub" || typeof route.hubUrl !== "string" || typeof route.token !== "string" || typeof route.nodeName !== "string" || typeof route.topicId !== "string" || typeof route.requestId !== "string") {
|
|
17443
|
-
return null;
|
|
17444
|
-
}
|
|
17445
|
-
const requestId = route.requestId.trim();
|
|
17446
|
-
const nodeName = route.nodeName.trim();
|
|
17447
|
-
const topicId = route.topicId.trim();
|
|
17448
|
-
const token = route.token.trim();
|
|
17449
|
-
if (!requestId || requestId.length > MAX_ROUTE_REQUEST_ID_LENGTH || !nodeName || nodeName.length > MAX_ROUTE_LABEL_LENGTH || !topicId || topicId.length > MAX_ROUTE_LABEL_LENGTH || token.length > MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH || !REMOTE_SESSION_REPLY_TOKEN_PATTERN.test(token)) {
|
|
17450
|
-
return null;
|
|
17451
|
-
}
|
|
17452
|
-
const hubUrl = normalizeHubUrl(route.hubUrl.trim(), "remoteReply.hubUrl");
|
|
17453
|
-
if ("error" in hubUrl)
|
|
17454
|
-
return null;
|
|
17455
|
-
return { via: "hub", hubUrl: hubUrl.url, token, nodeName, topicId, requestId };
|
|
17456
|
-
}
|
|
17457
16856
|
function loopbackBridgeConfig() {
|
|
17458
16857
|
const rawUrl = process.env[PEER_BRIDGE_URL_ENV]?.trim();
|
|
17459
16858
|
const token = process.env[PEER_BRIDGE_TOKEN_ENV]?.trim();
|
|
@@ -17490,39 +16889,6 @@ async function callLoopbackBridge(request) {
|
|
|
17490
16889
|
return { configured: true, result: null };
|
|
17491
16890
|
}
|
|
17492
16891
|
}
|
|
17493
|
-
function registerPeerSessionBridge(bridge) {
|
|
17494
|
-
activeBridge = bridge;
|
|
17495
|
-
return () => {
|
|
17496
|
-
if (activeBridge === bridge)
|
|
17497
|
-
activeBridge = null;
|
|
17498
|
-
};
|
|
17499
|
-
}
|
|
17500
|
-
async function forwardToPeer(args) {
|
|
17501
|
-
if (activeBridge)
|
|
17502
|
-
return activeBridge.forward(args);
|
|
17503
|
-
const forwarded = await callLoopbackBridge({ action: "forward", args });
|
|
17504
|
-
if (forwarded.result)
|
|
17505
|
-
return forwarded.result;
|
|
17506
|
-
return {
|
|
17507
|
-
ok: false,
|
|
17508
|
-
error: forwarded.configured ? "remote session bridge is configured but unavailable" : "remote nodes are not connected on this negotium node (standalone mode)"
|
|
17509
|
-
};
|
|
17510
|
-
}
|
|
17511
|
-
async function peerSessionsForUser(userId, sourceQueryId, fromTopicId) {
|
|
17512
|
-
if (activeBridge)
|
|
17513
|
-
return activeBridge.sessions(userId, sourceQueryId, fromTopicId);
|
|
17514
|
-
const sessions = await callLoopbackBridge({
|
|
17515
|
-
action: "sessions",
|
|
17516
|
-
userId,
|
|
17517
|
-
sourceQueryId,
|
|
17518
|
-
fromTopicId
|
|
17519
|
-
});
|
|
17520
|
-
if (sessions.result)
|
|
17521
|
-
return sessions.result;
|
|
17522
|
-
if (sessions.configured)
|
|
17523
|
-
return { ok: false, nodes: [] };
|
|
17524
|
-
return { ok: true, nodes: [] };
|
|
17525
|
-
}
|
|
17526
16892
|
async function deliverPeerReply(route, sourceTitle, replyText, kind) {
|
|
17527
16893
|
if (isHubRemoteReplyRoute(route)) {
|
|
17528
16894
|
return deliverHubRemoteReply(route, sourceTitle, replyText, kind);
|
|
@@ -17537,40 +16903,13 @@ async function deliverPeerReply(route, sourceTitle, replyText, kind) {
|
|
|
17537
16903
|
kind
|
|
17538
16904
|
})).result ?? false;
|
|
17539
16905
|
}
|
|
17540
|
-
var
|
|
16906
|
+
var activeBridge = null, PEER_BRIDGE_URL_ENV = "NEGOTIUM_PEER_SESSION_BRIDGE_URL", PEER_BRIDGE_TOKEN_ENV = "NEGOTIUM_PEER_SESSION_BRIDGE_TOKEN", PEER_BRIDGE_TIMEOUT_MS = 5000;
|
|
17541
16907
|
var init_peer_forward = __esm(async () => {
|
|
17542
16908
|
init_remote_session_grant();
|
|
17543
16909
|
await init_remote_session_reply_outbox();
|
|
17544
16910
|
});
|
|
17545
16911
|
|
|
17546
16912
|
// ../../packages/core/src/runtime/ask-callbacks.ts
|
|
17547
|
-
var exports_ask_callbacks = {};
|
|
17548
|
-
__export(exports_ask_callbacks, {
|
|
17549
|
-
resolveAskCallback: () => resolveAskCallback,
|
|
17550
|
-
registerAskCallback: () => registerAskCallback,
|
|
17551
|
-
purgeStaleAsks: () => purgeStaleAsks,
|
|
17552
|
-
failInterruptedRemoteAskCallbacks: () => failInterruptedRemoteAskCallbacks,
|
|
17553
|
-
deleteHubRemoteAskCallbackRow: () => deleteHubRemoteAskCallbackRow,
|
|
17554
|
-
cancelAskCallbacksForTopic: () => cancelAskCallbacksForTopic
|
|
17555
|
-
});
|
|
17556
|
-
function registerAskCallback(entry) {
|
|
17557
|
-
pendingAsks.set(entry.targetQueryId, entry);
|
|
17558
|
-
if (entry.remoteReply) {
|
|
17559
|
-
const route = entry.remoteReply;
|
|
17560
|
-
const hub = isHubRemoteReplyRoute(route);
|
|
17561
|
-
db.query(`INSERT INTO remote_ask_callbacks
|
|
17562
|
-
(target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, created_at, route_json)
|
|
17563
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
17564
|
-
ON CONFLICT(target_query_id) DO UPDATE SET
|
|
17565
|
-
request_id = excluded.request_id,
|
|
17566
|
-
node_name = excluded.node_name,
|
|
17567
|
-
node_cell_id = excluded.node_cell_id,
|
|
17568
|
-
topic_id = excluded.topic_id,
|
|
17569
|
-
user_id = excluded.user_id,
|
|
17570
|
-
created_at = excluded.created_at,
|
|
17571
|
-
route_json = excluded.route_json`).run(entry.targetQueryId, route.requestId, route.nodeName, hub ? "" : route.nodeCellId, route.topicId, hub ? "" : route.userId, entry.createdAt, hub ? JSON.stringify(route) : null);
|
|
17572
|
-
}
|
|
17573
|
-
}
|
|
17574
16913
|
function resolveAskCallback(queryId) {
|
|
17575
16914
|
const entry = pendingAsks.get(queryId);
|
|
17576
16915
|
if (!entry)
|
|
@@ -17587,13 +16926,6 @@ function resolveAskCallback(queryId) {
|
|
|
17587
16926
|
function deleteHubRemoteAskCallbackRow(requestId) {
|
|
17588
16927
|
db.query("DELETE FROM remote_ask_callbacks WHERE request_id = ? AND route_json IS NOT NULL").run(requestId);
|
|
17589
16928
|
}
|
|
17590
|
-
function purgeStaleAsks(now = Date.now()) {
|
|
17591
|
-
for (const [id, entry] of pendingAsks) {
|
|
17592
|
-
if (now - entry.createdAt > MAX_ASK_AGE_MS)
|
|
17593
|
-
pendingAsks.delete(id);
|
|
17594
|
-
}
|
|
17595
|
-
db.query("DELETE FROM remote_ask_callbacks WHERE created_at < ?").run(now - MAX_ASK_AGE_MS);
|
|
17596
|
-
}
|
|
17597
16929
|
function cancelAskCallbacksForTopic(topicId) {
|
|
17598
16930
|
let cancelled = 0;
|
|
17599
16931
|
for (const [queryId, entry] of pendingAsks) {
|
|
@@ -17605,43 +16937,6 @@ function cancelAskCallbacksForTopic(topicId) {
|
|
|
17605
16937
|
}
|
|
17606
16938
|
return cancelled;
|
|
17607
16939
|
}
|
|
17608
|
-
function durableRoute(row) {
|
|
17609
|
-
if (row.route_json) {
|
|
17610
|
-
try {
|
|
17611
|
-
return parseHubRemoteReplyRoute(JSON.parse(row.route_json));
|
|
17612
|
-
} catch {
|
|
17613
|
-
return null;
|
|
17614
|
-
}
|
|
17615
|
-
}
|
|
17616
|
-
return {
|
|
17617
|
-
nodeName: row.node_name,
|
|
17618
|
-
nodeCellId: row.node_cell_id,
|
|
17619
|
-
topicId: row.topic_id,
|
|
17620
|
-
userId: row.user_id,
|
|
17621
|
-
requestId: row.request_id
|
|
17622
|
-
};
|
|
17623
|
-
}
|
|
17624
|
-
async function failInterruptedRemoteAskCallbacks(options = {}) {
|
|
17625
|
-
const rows = db.query(`SELECT target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, route_json
|
|
17626
|
-
FROM remote_ask_callbacks
|
|
17627
|
-
ORDER BY created_at ASC`).all();
|
|
17628
|
-
let failed = 0;
|
|
17629
|
-
for (const row of rows) {
|
|
17630
|
-
const route = durableRoute(row);
|
|
17631
|
-
if (!route) {
|
|
17632
|
-
db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
|
|
17633
|
-
continue;
|
|
17634
|
-
}
|
|
17635
|
-
if (options.routes === "hub" && !isHubRemoteReplyRoute(route))
|
|
17636
|
-
continue;
|
|
17637
|
-
const delivered = await deliverPeerReply(route, "peer", "The remote worker restarted before this ask completed. Please retry the request.", "error");
|
|
17638
|
-
if (!delivered)
|
|
17639
|
-
continue;
|
|
17640
|
-
db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
|
|
17641
|
-
failed++;
|
|
17642
|
-
}
|
|
17643
|
-
return failed;
|
|
17644
|
-
}
|
|
17645
16940
|
var pendingAsks, MAX_ASK_AGE_MS;
|
|
17646
16941
|
var init_ask_callbacks = __esm(async () => {
|
|
17647
16942
|
await __promiseAll([
|
|
@@ -18067,14 +17362,6 @@ var init_topic_tool_capabilities = __esm(async () => {
|
|
|
18067
17362
|
});
|
|
18068
17363
|
|
|
18069
17364
|
// ../../packages/core/src/topics/lifecycle.ts
|
|
18070
|
-
var exports_lifecycle = {};
|
|
18071
|
-
__export(exports_lifecycle, {
|
|
18072
|
-
deleteTopicCascade: () => deleteTopicCascade,
|
|
18073
|
-
TopicTurnStillActiveError: () => TopicTurnStillActiveError,
|
|
18074
|
-
TopicDeleteVetoedError: () => TopicDeleteVetoedError,
|
|
18075
|
-
TopicCleanupRequiredError: () => TopicCleanupRequiredError,
|
|
18076
|
-
TopicArchiveRequiredError: () => TopicArchiveRequiredError
|
|
18077
|
-
});
|
|
18078
17365
|
import { rmSync as rmSync6 } from "fs";
|
|
18079
17366
|
async function abortAndWaitForTopic(topicId) {
|
|
18080
17367
|
interSessionQueue.drop(topicId);
|
|
@@ -18107,8 +17394,8 @@ async function cleanupParticipantResources(topic, userIds, sessionId, cwd, purge
|
|
|
18107
17394
|
cwd,
|
|
18108
17395
|
extraSessions: index === 0 ? currentSessionRef(topic, sessionId) : []
|
|
18109
17396
|
});
|
|
18110
|
-
} catch (
|
|
18111
|
-
logger.warn({ err
|
|
17397
|
+
} catch (err) {
|
|
17398
|
+
logger.warn({ err, topicId: topic.id, userId: participantUserId }, "deleteTopicCascade: participant rollout cleanup failed");
|
|
18112
17399
|
}
|
|
18113
17400
|
if (!purged)
|
|
18114
17401
|
return false;
|
|
@@ -18164,12 +17451,12 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18164
17451
|
if (rawArchive)
|
|
18165
17452
|
rawArchives.push(rawArchive.path);
|
|
18166
17453
|
}
|
|
18167
|
-
} catch (
|
|
17454
|
+
} catch (err) {
|
|
18168
17455
|
if (!force) {
|
|
18169
|
-
logger.warn({ err
|
|
18170
|
-
throw new TopicArchiveRequiredError(topicId,
|
|
17456
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: archive failed - blocking delete unless force=true");
|
|
17457
|
+
throw new TopicArchiveRequiredError(topicId, err);
|
|
18171
17458
|
}
|
|
18172
|
-
logger.warn({ err
|
|
17459
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: archive failed but force=true - continuing with hard delete");
|
|
18173
17460
|
}
|
|
18174
17461
|
}
|
|
18175
17462
|
if (archived && meetsMemoryArchiveExchangeThreshold(archived.exchangeCount, MIN_MEMORY_ARCHIVE_EXCHANGES, topic)) {
|
|
@@ -18185,8 +17472,8 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18185
17472
|
...rawArchives.length > 0 ? { rawArchivePaths: rawArchives } : {},
|
|
18186
17473
|
messageCount: archived.messageCount
|
|
18187
17474
|
});
|
|
18188
|
-
} catch (
|
|
18189
|
-
logger.warn({ err
|
|
17475
|
+
} catch (err) {
|
|
17476
|
+
logger.warn({ err, topicId, archive: archived.path }, "deleteTopicCascade: background archiver launch failed - raw archive preserved");
|
|
18190
17477
|
}
|
|
18191
17478
|
}
|
|
18192
17479
|
const sessionId = getTopicSessionId(topicId);
|
|
@@ -18203,21 +17490,21 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18203
17490
|
killBgBash(userId, topicId);
|
|
18204
17491
|
try {
|
|
18205
17492
|
await closeTopicBrowserTabs(userId, topicId);
|
|
18206
|
-
} catch (
|
|
18207
|
-
logger.warn({ err
|
|
17493
|
+
} catch (err) {
|
|
17494
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: browser owner cleanup failed");
|
|
18208
17495
|
}
|
|
18209
17496
|
deleteTopicProfileDir(userId, topicId);
|
|
18210
17497
|
cancelAskCallbacksForTopic(topicId);
|
|
18211
17498
|
deleteSelfSchedulesForTopic(topicId);
|
|
18212
17499
|
try {
|
|
18213
17500
|
await deleteFilesForTopic(topicId);
|
|
18214
|
-
} catch (
|
|
18215
|
-
logger.warn({ err
|
|
17501
|
+
} catch (err) {
|
|
17502
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: host file cleanup failed");
|
|
18216
17503
|
}
|
|
18217
17504
|
try {
|
|
18218
17505
|
rmSync6(cwd, { recursive: true, force: true });
|
|
18219
|
-
} catch (
|
|
18220
|
-
logger.warn({ err
|
|
17506
|
+
} catch (err) {
|
|
17507
|
+
logger.warn({ err, topicId, cwd }, "deleteTopicCascade: workspace cleanup failed");
|
|
18221
17508
|
}
|
|
18222
17509
|
deleteTopicVisuals(topicId);
|
|
18223
17510
|
deleteTopicHostMcpGrant(topicId);
|
|
@@ -18259,7 +17546,7 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18259
17546
|
}
|
|
18260
17547
|
}
|
|
18261
17548
|
}
|
|
18262
|
-
var DELETE_TURN_WAIT_MS = 5000, TopicArchiveRequiredError, TopicTurnStillActiveError, TopicCleanupRequiredError
|
|
17549
|
+
var DELETE_TURN_WAIT_MS = 5000, TopicArchiveRequiredError, TopicTurnStillActiveError, TopicCleanupRequiredError;
|
|
18263
17550
|
var init_lifecycle = __esm(async () => {
|
|
18264
17551
|
init_manager();
|
|
18265
17552
|
init_config();
|
|
@@ -18325,19 +17612,9 @@ var init_lifecycle = __esm(async () => {
|
|
|
18325
17612
|
this.topicId = topicId;
|
|
18326
17613
|
}
|
|
18327
17614
|
};
|
|
18328
|
-
TopicDeleteVetoedError = class TopicDeleteVetoedError extends Error {
|
|
18329
|
-
code = "TOPIC_DELETE_VETOED";
|
|
18330
|
-
topicId;
|
|
18331
|
-
constructor(topicId, reason) {
|
|
18332
|
-
super(`Topic delete was vetoed: ${reason}`);
|
|
18333
|
-
this.name = "TopicDeleteVetoedError";
|
|
18334
|
-
this.topicId = topicId;
|
|
18335
|
-
}
|
|
18336
|
-
};
|
|
18337
17615
|
});
|
|
18338
17616
|
|
|
18339
17617
|
// ../../packages/core/src/runtime/attachments.ts
|
|
18340
|
-
import { randomUUID as randomUUID16 } from "crypto";
|
|
18341
17618
|
import { copyFileSync as copyFileSync2, mkdirSync as mkdirSync17, writeFileSync as writeFileSync15 } from "fs";
|
|
18342
17619
|
import { basename as basename6, join as join29 } from "path";
|
|
18343
17620
|
function workspaceCwdFor(topicId) {
|
|
@@ -18379,8 +17656,8 @@ function materializePromptAttachments(topicId, queryId, attachmentIds) {
|
|
|
18379
17656
|
sizeBytes: attachment.sizeBytes,
|
|
18380
17657
|
path: destPath
|
|
18381
17658
|
});
|
|
18382
|
-
} catch (
|
|
18383
|
-
logger.warn({ topicId, queryId, fileId, err
|
|
17659
|
+
} catch (err) {
|
|
17660
|
+
logger.warn({ topicId, queryId, fileId, err }, "ai: failed to materialize attachment");
|
|
18384
17661
|
}
|
|
18385
17662
|
}
|
|
18386
17663
|
return out;
|
|
@@ -18398,24 +17675,6 @@ function composeAttachmentPrompt(prompt, promptLines) {
|
|
|
18398
17675
|
function promptWithAttachments(prompt, attachments) {
|
|
18399
17676
|
return composeAttachmentPrompt(prompt, attachments.map(({ filename, path }) => attachmentPromptLine(filename, path)));
|
|
18400
17677
|
}
|
|
18401
|
-
function ingestAttachment(args) {
|
|
18402
|
-
const destDir = join29(UPLOADS_DIR, args.topicId);
|
|
18403
|
-
mkdirSync17(destDir, { recursive: true });
|
|
18404
|
-
const safeName = safeAttachmentFilename(args.filename, "upload");
|
|
18405
|
-
const destPath = join29(destDir, `${Date.now()}-${randomUUID16().slice(0, 8)}-${safeName}`);
|
|
18406
|
-
if (args.sourcePath !== undefined) {
|
|
18407
|
-
copyFileSync2(args.sourcePath, destPath);
|
|
18408
|
-
} else if (args.bytes !== undefined) {
|
|
18409
|
-
writeFileSync15(destPath, args.bytes);
|
|
18410
|
-
} else {
|
|
18411
|
-
throw new Error("ingestAttachment: provide sourcePath or bytes");
|
|
18412
|
-
}
|
|
18413
|
-
return {
|
|
18414
|
-
path: destPath,
|
|
18415
|
-
filename: args.filename,
|
|
18416
|
-
promptLine: attachmentPromptLine(args.filename, destPath)
|
|
18417
|
-
};
|
|
18418
|
-
}
|
|
18419
17678
|
function parseAttachmentNames(raw) {
|
|
18420
17679
|
if (!raw)
|
|
18421
17680
|
return [];
|
|
@@ -18456,13 +17715,13 @@ function isLikelyCurrentChannelTrigger(row, userId, prompt) {
|
|
|
18456
17715
|
return Number.isFinite(createdMs) && Date.now() - createdMs <= CHANNEL_CONTEXT_CURRENT_MESSAGE_MATCH_MS;
|
|
18457
17716
|
}
|
|
18458
17717
|
function formatChannelTranscriptLine(row) {
|
|
18459
|
-
const
|
|
17718
|
+
const text = row.text.trim();
|
|
18460
17719
|
const attachments = parseAttachmentNames(row.attachments);
|
|
18461
17720
|
const attachmentSuffix = attachments.length > 0 ? `
|
|
18462
17721
|
[attachments: ${attachments.join(", ")}]` : "";
|
|
18463
17722
|
const edited = row.edited_at ? " (edited)" : "";
|
|
18464
17723
|
const thread = row.thread_root_id ? ` (in thread ${threadTag(row.thread_root_id)})` : "";
|
|
18465
|
-
return `[${row.created_at}] ${channelTranscriptSpeaker(row)}${edited}${thread}: ${
|
|
17724
|
+
return `[${row.created_at}] ${channelTranscriptSpeaker(row)}${edited}${thread}: ${text}${attachmentSuffix}`;
|
|
18466
17725
|
}
|
|
18467
17726
|
function buildMentionOnlyChannelPrompt(params) {
|
|
18468
17727
|
const rows = getAllMessagesForTopic(params.topicId).filter((row) => {
|
|
@@ -18507,14 +17766,6 @@ function buildMentionOnlyChannelPrompt(params) {
|
|
|
18507
17766
|
].filter((line) => line !== undefined).join(`
|
|
18508
17767
|
`);
|
|
18509
17768
|
}
|
|
18510
|
-
function escapeRegExp3(s) {
|
|
18511
|
-
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18512
|
-
}
|
|
18513
|
-
function mentionsAi(text2, label) {
|
|
18514
|
-
const names = ["ai", "bot", "\uBD07", label.trim()].filter(Boolean);
|
|
18515
|
-
const alt = names.map(escapeRegExp3).join("|");
|
|
18516
|
-
return new RegExp(`(^|\\s)@(${alt})(?![\\p{L}\\p{N}])`, "iu").test(text2);
|
|
18517
|
-
}
|
|
18518
17769
|
var CHANNEL_CONTEXT_CURRENT_MESSAGE_MATCH_MS, CHANNEL_CONTEXT_MAX_MESSAGES = 500, CHANNEL_CONTEXT_MAX_CHARS = 120000;
|
|
18519
17770
|
var init_channel_context = __esm(async () => {
|
|
18520
17771
|
init_attachments();
|
|
@@ -18523,13 +17774,13 @@ var init_channel_context = __esm(async () => {
|
|
|
18523
17774
|
});
|
|
18524
17775
|
|
|
18525
17776
|
// ../../packages/core/src/runtime/errors.ts
|
|
18526
|
-
function stringifyError(
|
|
18527
|
-
if (
|
|
18528
|
-
return
|
|
18529
|
-
if (typeof
|
|
18530
|
-
return
|
|
17777
|
+
function stringifyError(err) {
|
|
17778
|
+
if (err instanceof Error)
|
|
17779
|
+
return err.message;
|
|
17780
|
+
if (typeof err === "string")
|
|
17781
|
+
return err;
|
|
18531
17782
|
try {
|
|
18532
|
-
return JSON.stringify(
|
|
17783
|
+
return JSON.stringify(err) ?? String(err);
|
|
18533
17784
|
} catch {
|
|
18534
17785
|
return "Unknown agent error";
|
|
18535
17786
|
}
|
|
@@ -18544,19 +17795,19 @@ function authRecoveryHint(agent) {
|
|
|
18544
17795
|
return "Please check the DEEPSEEK_API_KEY, MOONSHOT_API_KEY, or GLM_API_KEY environment variable";
|
|
18545
17796
|
}
|
|
18546
17797
|
}
|
|
18547
|
-
function classifyAgentError(
|
|
17798
|
+
function classifyAgentError(err, agent) {
|
|
18548
17799
|
const name = AGENT_DISPLAY_NAME[agent];
|
|
18549
17800
|
const hint = authRecoveryHint(agent);
|
|
18550
|
-
const ctor = typeof
|
|
17801
|
+
const ctor = typeof err === "object" && err !== null ? err.constructor?.name : undefined;
|
|
18551
17802
|
if (ctor === "AuthenticationError")
|
|
18552
17803
|
return `${name} authentication expired. ${hint}. (401)`;
|
|
18553
17804
|
if (ctor === "RateLimitError")
|
|
18554
17805
|
return `${name} request limit exceeded. Please try again in a moment. (429)`;
|
|
18555
17806
|
if (ctor === "InternalServerError") {
|
|
18556
|
-
const status =
|
|
17807
|
+
const status = err.status;
|
|
18557
17808
|
return status === 529 ? `${name} server is overloaded. Please try again in a moment. (529)` : `${name} server error occurred. Please try again in a moment. (500)`;
|
|
18558
17809
|
}
|
|
18559
|
-
const s = stringifyError(
|
|
17810
|
+
const s = stringifyError(err);
|
|
18560
17811
|
if (/401|authentication.error|invalid.*api.key|not logged|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|MOONSHOT_API_KEY|GLM_API_KEY/i.test(s)) {
|
|
18561
17812
|
return `${name} authentication expired. ${hint}. (401)`;
|
|
18562
17813
|
}
|
|
@@ -18579,12 +17830,12 @@ var init_errors = __esm(() => {
|
|
|
18579
17830
|
|
|
18580
17831
|
// ../../packages/core/src/runtime/event-heartbeat.ts
|
|
18581
17832
|
function nextOrHeartbeat(pending, intervalMs) {
|
|
18582
|
-
return new Promise((
|
|
18583
|
-
const timer = setTimeout(() =>
|
|
17833
|
+
return new Promise((resolve, reject) => {
|
|
17834
|
+
const timer = setTimeout(() => resolve({ kind: "heartbeat" }), intervalMs);
|
|
18584
17835
|
timer.unref?.();
|
|
18585
17836
|
pending.then((result) => {
|
|
18586
17837
|
clearTimeout(timer);
|
|
18587
|
-
|
|
17838
|
+
resolve({ kind: "event", result });
|
|
18588
17839
|
}, (error) => {
|
|
18589
17840
|
clearTimeout(timer);
|
|
18590
17841
|
reject(error);
|
|
@@ -18878,7 +18129,7 @@ var init_vault_request_gates = __esm(async () => {
|
|
|
18878
18129
|
});
|
|
18879
18130
|
|
|
18880
18131
|
// ../../packages/core/src/agents/mcp-tools/request-vault.ts
|
|
18881
|
-
import { createHash as createHash12, randomUUID as
|
|
18132
|
+
import { createHash as createHash12, randomUUID as randomUUID16 } from "crypto";
|
|
18882
18133
|
import { z as z4 } from "zod";
|
|
18883
18134
|
function requestBodyHash(key, description) {
|
|
18884
18135
|
return createHash12("sha256").update(JSON.stringify({ key, description })).digest("hex");
|
|
@@ -19118,8 +18369,8 @@ function createRequestVaultRuntime(host) {
|
|
|
19118
18369
|
return errorResult(`Error: failed to persist request_vault_secret: ${error instanceof Error ? error.message : String(error)}`);
|
|
19119
18370
|
}
|
|
19120
18371
|
let resolveAnswer;
|
|
19121
|
-
const promise = new Promise((
|
|
19122
|
-
resolveAnswer =
|
|
18372
|
+
const promise = new Promise((resolve) => {
|
|
18373
|
+
resolveAnswer = resolve;
|
|
19123
18374
|
});
|
|
19124
18375
|
pendingRequests.set(message.id, {
|
|
19125
18376
|
topicId: ctx.topicId,
|
|
@@ -19219,7 +18470,7 @@ var init_request_vault = __esm(async () => {
|
|
|
19219
18470
|
init_vault_request_gates()
|
|
19220
18471
|
]);
|
|
19221
18472
|
MAX_DESCRIPTION_CHARS = VAULT_DESCRIPTION_MAX_LENGTH;
|
|
19222
|
-
VAULT_GATE_OWNER_ID = `request-vault-${process.pid}-${
|
|
18473
|
+
VAULT_GATE_OWNER_ID = `request-vault-${process.pid}-${randomUUID16()}`;
|
|
19223
18474
|
defaultRequestVaultDurabilityHost = {
|
|
19224
18475
|
gates: {
|
|
19225
18476
|
prepare: prepareVaultRequestGate,
|
|
@@ -19261,7 +18512,7 @@ var init_request_vault = __esm(async () => {
|
|
|
19261
18512
|
durability: defaultRequestVaultDurabilityHost,
|
|
19262
18513
|
runtime: {
|
|
19263
18514
|
ownerId: VAULT_GATE_OWNER_ID,
|
|
19264
|
-
createId:
|
|
18515
|
+
createId: randomUUID16,
|
|
19265
18516
|
now: () => new Date().toISOString()
|
|
19266
18517
|
}
|
|
19267
18518
|
});
|
|
@@ -19298,24 +18549,24 @@ function taskPanelMessageId(queryId) {
|
|
|
19298
18549
|
// ../../packages/core/src/runtime/tasks.ts
|
|
19299
18550
|
function upsertTaskPanelMessage(topicId, queryId, tasks, lastRenderedText) {
|
|
19300
18551
|
if (tasks.length === 0) {
|
|
19301
|
-
const
|
|
19302
|
-
for (const
|
|
19303
|
-
|
|
18552
|
+
const hub = WsHub.get();
|
|
18553
|
+
for (const messageId of softDeleteApiMessagesByIdPrefix(topicId, "tasks-")) {
|
|
18554
|
+
hub.broadcastMessageUpdated(topicId, messageId, { deleted: true, text: "" });
|
|
19304
18555
|
}
|
|
19305
18556
|
return null;
|
|
19306
18557
|
}
|
|
19307
|
-
const
|
|
19308
|
-
if (
|
|
18558
|
+
const text = renderTaskPanel(tasks);
|
|
18559
|
+
if (text === lastRenderedText)
|
|
19309
18560
|
return lastRenderedText;
|
|
19310
18561
|
const hub = WsHub.get();
|
|
19311
18562
|
const messageId = taskPanelMessageId(queryId);
|
|
19312
18563
|
const existing = getApiMessage(topicId, messageId);
|
|
19313
18564
|
if (existing && !existing.deleted) {
|
|
19314
18565
|
const editedAt = new Date().toISOString();
|
|
19315
|
-
const updated = updateApiMessageText(topicId, messageId,
|
|
18566
|
+
const updated = updateApiMessageText(topicId, messageId, text, editedAt);
|
|
19316
18567
|
if (updated) {
|
|
19317
|
-
hub.broadcastMessageUpdated(topicId, messageId, { text
|
|
19318
|
-
return
|
|
18568
|
+
hub.broadcastMessageUpdated(topicId, messageId, { text, editedAt });
|
|
18569
|
+
return text;
|
|
19319
18570
|
}
|
|
19320
18571
|
}
|
|
19321
18572
|
const createdAt = new Date().toISOString();
|
|
@@ -19323,12 +18574,12 @@ function upsertTaskPanelMessage(topicId, queryId, tasks, lastRenderedText) {
|
|
|
19323
18574
|
id: messageId,
|
|
19324
18575
|
topicId,
|
|
19325
18576
|
authorId: "system",
|
|
19326
|
-
text
|
|
18577
|
+
text,
|
|
19327
18578
|
createdAt
|
|
19328
18579
|
};
|
|
19329
18580
|
appendApiMessage(message, { notify: false });
|
|
19330
18581
|
hub.broadcastMessage(topicId, message);
|
|
19331
|
-
return
|
|
18582
|
+
return text;
|
|
19332
18583
|
}
|
|
19333
18584
|
var init_tasks2 = __esm(async () => {
|
|
19334
18585
|
await __promiseAll([
|
|
@@ -19615,10 +18866,6 @@ function locateVisualMediaInput(topicId, input) {
|
|
|
19615
18866
|
}
|
|
19616
18867
|
return { kind: "file", path: realCandidate, rawPath };
|
|
19617
18868
|
}
|
|
19618
|
-
function visualMediaInputError(topicId, input) {
|
|
19619
|
-
const located = locateVisualMediaInput(topicId, input);
|
|
19620
|
-
return "error" in located ? located.error : null;
|
|
19621
|
-
}
|
|
19622
18869
|
function resolveVisualMediaInput(topicId, input) {
|
|
19623
18870
|
const located = locateVisualMediaInput(topicId, input);
|
|
19624
18871
|
if ("error" in located)
|
|
@@ -19657,7 +18904,7 @@ var init_visuals = __esm(async () => {
|
|
|
19657
18904
|
});
|
|
19658
18905
|
|
|
19659
18906
|
// ../../packages/core/src/runtime/turn-event-stream.ts
|
|
19660
|
-
import { randomUUID as
|
|
18907
|
+
import { randomUUID as randomUUID17 } from "crypto";
|
|
19661
18908
|
import { realpathSync as realpathSync6, statSync as statSync9 } from "fs";
|
|
19662
18909
|
import { isAbsolute as isAbsolute7, resolve as resolve18 } from "path";
|
|
19663
18910
|
function sessionEventMatchesCurrentExecution(topicId, queryId, agent, model) {
|
|
@@ -19684,6 +18931,38 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19684
18931
|
let pendingSawDelta = false;
|
|
19685
18932
|
let accumulatedText = "";
|
|
19686
18933
|
let pendingText = "";
|
|
18934
|
+
let pendingMessage = null;
|
|
18935
|
+
let previewTimer = null;
|
|
18936
|
+
const clearPreviewTimer = () => {
|
|
18937
|
+
if (previewTimer)
|
|
18938
|
+
clearTimeout(previewTimer);
|
|
18939
|
+
previewTimer = null;
|
|
18940
|
+
};
|
|
18941
|
+
const scheduleTextPreview = () => {
|
|
18942
|
+
if (silent || previewTimer || !pendingText.trim())
|
|
18943
|
+
return;
|
|
18944
|
+
pendingMessage ??= { id: randomUUID17(), createdAt: new Date().toISOString() };
|
|
18945
|
+
previewTimer = setTimeout(() => {
|
|
18946
|
+
previewTimer = null;
|
|
18947
|
+
if (!pendingMessage || abortController.signal.aborted)
|
|
18948
|
+
return;
|
|
18949
|
+
try {
|
|
18950
|
+
hub.broadcastAiStatus(topicId, {
|
|
18951
|
+
kind: "message_stream",
|
|
18952
|
+
queryId,
|
|
18953
|
+
messageId: pendingMessage.id,
|
|
18954
|
+
text: pendingText,
|
|
18955
|
+
createdAt: pendingMessage.createdAt,
|
|
18956
|
+
...execution?.threadRootId ? { threadRootId: execution.threadRootId } : {}
|
|
18957
|
+
});
|
|
18958
|
+
} catch (error) {
|
|
18959
|
+
control.abortReason = "infrastructure" /* Infrastructure */;
|
|
18960
|
+
control.abortError = stringifyError(error);
|
|
18961
|
+
abortController.abort();
|
|
18962
|
+
}
|
|
18963
|
+
}, 50);
|
|
18964
|
+
previewTimer.unref?.();
|
|
18965
|
+
};
|
|
19687
18966
|
let assistantContextTokens = 0;
|
|
19688
18967
|
let toolContextTokens = 0;
|
|
19689
18968
|
let lastContextProgressAt = 0;
|
|
@@ -19727,9 +19006,9 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19727
19006
|
const existing = providerToolIds.get(providerId);
|
|
19728
19007
|
if (existing)
|
|
19729
19008
|
return existing;
|
|
19730
|
-
const
|
|
19731
|
-
providerToolIds.set(providerId,
|
|
19732
|
-
return
|
|
19009
|
+
const clientId = fallback ?? providerId;
|
|
19010
|
+
providerToolIds.set(providerId, clientId);
|
|
19011
|
+
return clientId;
|
|
19733
19012
|
}
|
|
19734
19013
|
const clientId = fallback ?? nextSyntheticToolUseId();
|
|
19735
19014
|
anonymousToolIds.push(clientId);
|
|
@@ -19760,22 +19039,25 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19760
19039
|
return providerId ? handledVisualToolResultIds.has(providerId) : false;
|
|
19761
19040
|
};
|
|
19762
19041
|
const emitPendingAssistantMessage = (usage) => {
|
|
19763
|
-
|
|
19042
|
+
clearPreviewTimer();
|
|
19043
|
+
const identity = pendingMessage;
|
|
19044
|
+
pendingMessage = null;
|
|
19045
|
+
const text = pendingText.trimEnd();
|
|
19764
19046
|
pendingText = "";
|
|
19765
|
-
if (silent || !
|
|
19047
|
+
if (silent || !text.trim())
|
|
19766
19048
|
return null;
|
|
19767
19049
|
const message = {
|
|
19768
|
-
id:
|
|
19050
|
+
id: identity?.id ?? randomUUID17(),
|
|
19769
19051
|
topicId,
|
|
19770
19052
|
authorId: "ai",
|
|
19771
|
-
text
|
|
19053
|
+
text,
|
|
19772
19054
|
queryId,
|
|
19773
19055
|
agentType,
|
|
19774
19056
|
model,
|
|
19775
19057
|
sourceNode: execution?.sourceNode,
|
|
19776
19058
|
...execution?.threadRootId ? { threadRootId: execution.threadRootId } : {},
|
|
19777
19059
|
usage,
|
|
19778
|
-
createdAt: new Date().toISOString()
|
|
19060
|
+
createdAt: identity?.createdAt ?? new Date().toISOString()
|
|
19779
19061
|
};
|
|
19780
19062
|
appendApiMessage(message, execution?.threadRootId ? { updateTopicLastMessageAt: false } : undefined);
|
|
19781
19063
|
hub.broadcastMessage(topicId, message);
|
|
@@ -19830,6 +19112,7 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19830
19112
|
const incoming = event.content;
|
|
19831
19113
|
accumulatedText += incoming;
|
|
19832
19114
|
pendingText += incoming;
|
|
19115
|
+
scheduleTextPreview();
|
|
19833
19116
|
assistantContextTokens = estimateTextTokens(accumulatedText);
|
|
19834
19117
|
broadcastContextProgress();
|
|
19835
19118
|
break;
|
|
@@ -19843,6 +19126,7 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19843
19126
|
const incoming = event.content;
|
|
19844
19127
|
accumulatedText += incoming;
|
|
19845
19128
|
pendingText += incoming;
|
|
19129
|
+
scheduleTextPreview();
|
|
19846
19130
|
assistantContextTokens = estimateTextTokens(accumulatedText);
|
|
19847
19131
|
broadcastContextProgress();
|
|
19848
19132
|
}
|
|
@@ -19988,8 +19272,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
19988
19272
|
hub.broadcastVisual(topicId, queryId, url, vizId, title ?? null, kind);
|
|
19989
19273
|
hub.broadcastToolOutput(topicId, queryId, toolUseId, `Displayed: ${url}`);
|
|
19990
19274
|
markVisualToolResultHandled(event.toolUseId);
|
|
19991
|
-
} catch (
|
|
19992
|
-
const reason =
|
|
19275
|
+
} catch (err) {
|
|
19276
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
19993
19277
|
failMediaVisual(reason);
|
|
19994
19278
|
}
|
|
19995
19279
|
} else {
|
|
@@ -20100,8 +19384,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20100
19384
|
}
|
|
20101
19385
|
terminalEmitted = true;
|
|
20102
19386
|
{
|
|
20103
|
-
|
|
20104
|
-
const pending =
|
|
19387
|
+
await init_ask_callbacks();
|
|
19388
|
+
const pending = resolveAskCallback(queryId);
|
|
20105
19389
|
if (pending) {
|
|
20106
19390
|
const sourceLabel = pending.sourceLabel ?? topicTitle;
|
|
20107
19391
|
const replyText = pending.timedOut ? `\u26A0\uFE0F [Timeout - reply from ${sourceLabel} took too long and was dropped]` : accumulatedText.trim() || "(\uCC98\uB9AC\uB428, \uBCC4\uB3C4 \uC751\uB2F5 \uC5C6\uC74C)";
|
|
@@ -20174,8 +19458,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20174
19458
|
if (control.injectParams)
|
|
20175
19459
|
control.injectParams.sessionId = event.sessionId;
|
|
20176
19460
|
onSessionId(event.sessionId);
|
|
20177
|
-
} catch (
|
|
20178
|
-
logger.warn({ err
|
|
19461
|
+
} catch (err) {
|
|
19462
|
+
logger.warn({ err, topicId, queryId, agentType }, "ai: isolated session owner rejected provider session id");
|
|
20179
19463
|
}
|
|
20180
19464
|
} else if (!silent && sessionEventMatchesCurrentExecution(topicId, queryId, agentType, model)) {
|
|
20181
19465
|
setTopicSessionId(topicId, event.sessionId, {
|
|
@@ -20208,14 +19492,14 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20208
19492
|
settleSubagentFailure(queryId, "\uC911\uC9C0\uB428 (\uC0AC\uC6A9\uC790\uAC00 \uC2E4\uD589\uC744 \uBA48\uCDC4\uC2B5\uB2C8\uB2E4)");
|
|
20209
19493
|
} else {
|
|
20210
19494
|
if (control.abortReason === "internal" /* Internal */) {
|
|
20211
|
-
|
|
20212
|
-
|
|
19495
|
+
await init_ask_callbacks();
|
|
19496
|
+
resolveAskCallback(queryId);
|
|
20213
19497
|
}
|
|
20214
19498
|
}
|
|
20215
19499
|
}
|
|
20216
|
-
} catch (
|
|
20217
|
-
const msg = stringifyError(
|
|
20218
|
-
logger.warn({ err
|
|
19500
|
+
} catch (err) {
|
|
19501
|
+
const msg = stringifyError(err) || "Unknown agent error";
|
|
19502
|
+
logger.warn({ err, topicId, queryId, agentType, model, silent }, "ai: stream failed");
|
|
20219
19503
|
terminalEmitted = true;
|
|
20220
19504
|
if (retryableSessionExpired && isSessionExpiredError(msg)) {
|
|
20221
19505
|
outcome = { kind: "session-expired", error: msg };
|
|
@@ -20225,6 +19509,11 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20225
19509
|
deliverAskError(queryId, topicTitle, msg);
|
|
20226
19510
|
}
|
|
20227
19511
|
} finally {
|
|
19512
|
+
clearPreviewTimer();
|
|
19513
|
+
if (pendingMessage) {
|
|
19514
|
+
hub.broadcastMessageUpdated(topicId, pendingMessage.id, { deleted: true, text: "" });
|
|
19515
|
+
pendingMessage = null;
|
|
19516
|
+
}
|
|
20228
19517
|
if (!terminalEmitted && !abortController.signal.aborted) {
|
|
20229
19518
|
const error = "Provider stream ended without a terminal event";
|
|
20230
19519
|
outcome = { kind: "provider-error", error };
|
|
@@ -20367,86 +19656,7 @@ var init_app_settings = __esm(async () => {
|
|
|
20367
19656
|
});
|
|
20368
19657
|
|
|
20369
19658
|
// ../../packages/core/src/runtime/turn-runner.ts
|
|
20370
|
-
|
|
20371
|
-
__export(exports_turn_runner, {
|
|
20372
|
-
workspaceCwdFor: () => workspaceCwdFor,
|
|
20373
|
-
withDefaultPlaywright: () => withDefaultPlaywright,
|
|
20374
|
-
wasLocallyRequeuedAfterUserPreemption: () => wasLocallyRequeuedAfterUserPreemption,
|
|
20375
|
-
visualMediaInputError: () => visualMediaInputError,
|
|
20376
|
-
userConversationPromptsToRecord: () => userConversationPromptsToRecord,
|
|
20377
|
-
upsertTaskPanelMessage: () => upsertTaskPanelMessage,
|
|
20378
|
-
tryReconstructTopicRollout: () => tryReconstructTopicRollout,
|
|
20379
|
-
triggerTopicAiTurn: () => triggerTopicAiTurn,
|
|
20380
|
-
topicAllowsVisualFileId: () => topicAllowsVisualFileId,
|
|
20381
|
-
taskPanelMessageId: () => taskPanelMessageId,
|
|
20382
|
-
stripMermaidFence: () => stripMermaidFence,
|
|
20383
|
-
stringifyError: () => stringifyError,
|
|
20384
|
-
streamAgentEvents: () => streamAgentEvents,
|
|
20385
|
-
startDurableTurnRequestWorker: () => startDurableTurnRequestWorker,
|
|
20386
|
-
startAiTurn: () => startAiTurn,
|
|
20387
|
-
selectableModel: () => selectableModel,
|
|
20388
|
-
sameTurnActor: () => sameTurnActor,
|
|
20389
|
-
safeAttachmentFilename: () => safeAttachmentFilename,
|
|
20390
|
-
resolveWorkerModel: () => resolveWorkerModel,
|
|
20391
|
-
resolveWorkerDefaultModel: () => resolveWorkerDefaultModel,
|
|
20392
|
-
resolveWikiMirrorPath: () => resolveWikiMirrorPath,
|
|
20393
|
-
resolveWikiMemoryMirror: () => resolveWikiMemoryMirror,
|
|
20394
|
-
resolveVisualMediaInput: () => resolveVisualMediaInput,
|
|
20395
|
-
resolveTurnToolCapabilities: () => resolveTurnToolCapabilities,
|
|
20396
|
-
resolveTurnHostMcpServers: () => resolveTurnHostMcpServers,
|
|
20397
|
-
resolveTopicTurnSession: () => resolveTopicTurnSession,
|
|
20398
|
-
resolveTopicTurnExecution: () => resolveTopicTurnExecution,
|
|
20399
|
-
resolveSessionRetry: () => resolveSessionRetry,
|
|
20400
|
-
resolveModelForAgent: () => resolveModelForAgent,
|
|
20401
|
-
resolveInitialTurnSessionId: () => resolveInitialTurnSessionId,
|
|
20402
|
-
resolveDefaultModel: () => resolveDefaultModel,
|
|
20403
|
-
resolveCompactionExecution: () => resolveCompactionExecution,
|
|
20404
|
-
renderUserTurnBatch: () => renderUserTurnBatch,
|
|
20405
|
-
renderUserPromptBatch: () => renderUserPromptBatch,
|
|
20406
|
-
renderTaskPanel: () => renderTaskPanel,
|
|
20407
|
-
promptWithAttachments: () => promptWithAttachments,
|
|
20408
|
-
prepareInjectReplayAfterUserPreemption: () => prepareInjectReplayAfterUserPreemption,
|
|
20409
|
-
parseAttachmentNames: () => parseAttachmentNames,
|
|
20410
|
-
normalizeToolUseId: () => normalizeToolUseId,
|
|
20411
|
-
normalizeMermaidTheme: () => normalizeMermaidTheme,
|
|
20412
|
-
modelOwner: () => modelOwner,
|
|
20413
|
-
mergeSupersedingUserTurn: () => mergeSupersedingUserTurn,
|
|
20414
|
-
mentionsAi: () => mentionsAi,
|
|
20415
|
-
materializePromptAttachments: () => materializePromptAttachments,
|
|
20416
|
-
isVisualsShowMermaidTool: () => isVisualsShowMermaidTool,
|
|
20417
|
-
isVisualsShowImageTool: () => isVisualsShowImageTool,
|
|
20418
|
-
isVisualsShowHtmlTool: () => isVisualsShowHtmlTool,
|
|
20419
|
-
isSessionExpiredError: () => isSessionExpiredError,
|
|
20420
|
-
isRuntimeTool: () => isRuntimeTool,
|
|
20421
|
-
isPathInside: () => isPathInside,
|
|
20422
|
-
isLikelyCurrentChannelTrigger: () => isLikelyCurrentChannelTrigger,
|
|
20423
|
-
ingestAttachment: () => ingestAttachment,
|
|
20424
|
-
formatSelectableModel: () => formatSelectableModel,
|
|
20425
|
-
formatChannelTranscriptLine: () => formatChannelTranscriptLine,
|
|
20426
|
-
escapeRegExp: () => escapeRegExp3,
|
|
20427
|
-
escapeHtml: () => escapeHtml2,
|
|
20428
|
-
deliverAskCallbackToCaller: () => deliverAskCallbackToCaller,
|
|
20429
|
-
composeAttachmentPrompt: () => composeAttachmentPrompt,
|
|
20430
|
-
classifyAgentError: () => classifyAgentError,
|
|
20431
|
-
channelTranscriptSpeaker: () => channelTranscriptSpeaker,
|
|
20432
|
-
canonicalModelId: () => canonicalModelId,
|
|
20433
|
-
buildVideoHtml: () => buildVideoHtml,
|
|
20434
|
-
buildTurnReminderQuery: () => buildTurnReminderQuery,
|
|
20435
|
-
buildMermaidHtml: () => buildMermaidHtml,
|
|
20436
|
-
buildMentionOnlyChannelPrompt: () => buildMentionOnlyChannelPrompt,
|
|
20437
|
-
buildImageHtml: () => buildImageHtml,
|
|
20438
|
-
authRecoveryHint: () => authRecoveryHint,
|
|
20439
|
-
attachmentPromptLine: () => attachmentPromptLine,
|
|
20440
|
-
activeVisualHtmlForPrompt: () => activeVisualHtmlForPrompt,
|
|
20441
|
-
SESSION_EXPIRED_MSG: () => SESSION_EXPIRED_MSG,
|
|
20442
|
-
SELECTABLE_MODELS: () => SELECTABLE_MODELS,
|
|
20443
|
-
MODEL_OWNER: () => MODEL_OWNER,
|
|
20444
|
-
MODEL_COST_ROUTING_SUMMARY: () => MODEL_COST_ROUTING_SUMMARY,
|
|
20445
|
-
MODEL_COST_RESEARCHED_AT: () => MODEL_COST_RESEARCHED_AT,
|
|
20446
|
-
FALLBACK_ORDER: () => FALLBACK_ORDER,
|
|
20447
|
-
AGENT_DISPLAY_NAME: () => AGENT_DISPLAY_NAME
|
|
20448
|
-
});
|
|
20449
|
-
import { randomUUID as randomUUID19 } from "crypto";
|
|
19659
|
+
import { randomUUID as randomUUID18 } from "crypto";
|
|
20450
19660
|
import { existsSync as existsSync22, mkdirSync as mkdirSync19, readdirSync as readdirSync5, statSync as statSync10 } from "fs";
|
|
20451
19661
|
import { join as join31 } from "path";
|
|
20452
19662
|
function withDefaultPlaywright(configuredMcp, isManager) {
|
|
@@ -20469,12 +19679,12 @@ function buildTurnReminderQuery(agent, prompt, reminders) {
|
|
|
20469
19679
|
|
|
20470
19680
|
${reminderPrompt}` };
|
|
20471
19681
|
}
|
|
20472
|
-
function appendSystemMessage(topicId,
|
|
19682
|
+
function appendSystemMessage(topicId, text, threadRootId) {
|
|
20473
19683
|
const message = {
|
|
20474
|
-
id:
|
|
19684
|
+
id: randomUUID18(),
|
|
20475
19685
|
topicId,
|
|
20476
19686
|
authorId: "system",
|
|
20477
|
-
text
|
|
19687
|
+
text,
|
|
20478
19688
|
...threadRootId ? { threadRootId } : {},
|
|
20479
19689
|
createdAt: new Date().toISOString()
|
|
20480
19690
|
};
|
|
@@ -20491,12 +19701,12 @@ function notifyPlaywrightUnavailable(topicId) {
|
|
|
20491
19701
|
appendSystemMessage(topicId, "Playwright browser tools are unavailable this turn. Browser automation was removed from the tool catalog; retry shortly if browser interaction is required.");
|
|
20492
19702
|
WsHub.get().broadcastTopicNotice(topicId, "info", "Playwright \uC0AC\uC6A9 \uBD88\uAC00");
|
|
20493
19703
|
}
|
|
20494
|
-
function appendAskReplyMessage(topicId,
|
|
19704
|
+
function appendAskReplyMessage(topicId, text, sourceLabel, body, kind, agentType, threadRootId) {
|
|
20495
19705
|
const message = {
|
|
20496
|
-
id:
|
|
19706
|
+
id: randomUUID18(),
|
|
20497
19707
|
topicId,
|
|
20498
19708
|
authorId: "ai",
|
|
20499
|
-
text
|
|
19709
|
+
text,
|
|
20500
19710
|
kind: "tell",
|
|
20501
19711
|
tellCard: {
|
|
20502
19712
|
fromLabel: sourceLabel,
|
|
@@ -20557,8 +19767,8 @@ function redispatchInject(inject) {
|
|
|
20557
19767
|
kind: "error",
|
|
20558
19768
|
error: "topic gone or AI no longer invited"
|
|
20559
19769
|
});
|
|
20560
|
-
} catch (
|
|
20561
|
-
logger.warn({ err
|
|
19770
|
+
} catch (err) {
|
|
19771
|
+
logger.warn({ err, topicId: inject.topicId }, "ai: deferred settlement hook failed");
|
|
20562
19772
|
}
|
|
20563
19773
|
if (inject.forkHandle)
|
|
20564
19774
|
cleanupAgentFork(inject.forkHandle);
|
|
@@ -20616,28 +19826,28 @@ async function clearPendingAskFile(pending, state) {
|
|
|
20616
19826
|
if (!pending.pendingAsk)
|
|
20617
19827
|
return;
|
|
20618
19828
|
try {
|
|
20619
|
-
|
|
19829
|
+
await init_session_asks();
|
|
20620
19830
|
if (state)
|
|
20621
|
-
|
|
20622
|
-
|
|
20623
|
-
} catch (
|
|
20624
|
-
logger.warn({ err
|
|
19831
|
+
markPendingAskState({ ...pending.pendingAsk, state });
|
|
19832
|
+
clearPendingAsk(pending.pendingAsk);
|
|
19833
|
+
} catch (err) {
|
|
19834
|
+
logger.warn({ err, pendingAsk: pending.pendingAsk }, "sessions: pending ask cleanup failed");
|
|
20625
19835
|
}
|
|
20626
19836
|
}
|
|
20627
19837
|
async function markPendingAskFile(pending, state) {
|
|
20628
19838
|
if (!pending.pendingAsk)
|
|
20629
19839
|
return;
|
|
20630
19840
|
try {
|
|
20631
|
-
|
|
20632
|
-
|
|
20633
|
-
} catch (
|
|
20634
|
-
logger.warn({ err
|
|
19841
|
+
await init_session_asks();
|
|
19842
|
+
markPendingAskState({ ...pending.pendingAsk, state });
|
|
19843
|
+
} catch (err) {
|
|
19844
|
+
logger.warn({ err, pendingAsk: pending.pendingAsk, state }, "sessions: pending ask mark failed");
|
|
20635
19845
|
}
|
|
20636
19846
|
}
|
|
20637
19847
|
async function deliverAskCallbackToCaller(pending, sourceLabel, body, kind, options = {}) {
|
|
20638
19848
|
if (pending.remoteReply) {
|
|
20639
|
-
|
|
20640
|
-
const delivered = await
|
|
19849
|
+
await init_peer_forward();
|
|
19850
|
+
const delivered = await deliverPeerReply(pending.remoteReply, sourceLabel, body, kind);
|
|
20641
19851
|
if (delivered)
|
|
20642
19852
|
options.onRecorded?.();
|
|
20643
19853
|
return delivered;
|
|
@@ -20657,8 +19867,8 @@ ${body}`;
|
|
|
20657
19867
|
record(undefined);
|
|
20658
19868
|
await clearPendingAskFile(pending);
|
|
20659
19869
|
return true;
|
|
20660
|
-
} catch (
|
|
20661
|
-
logger.warn({ err
|
|
19870
|
+
} catch (err) {
|
|
19871
|
+
logger.warn({ err, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback direct delivery failed");
|
|
20662
19872
|
return false;
|
|
20663
19873
|
}
|
|
20664
19874
|
}
|
|
@@ -20687,9 +19897,9 @@ ${body}`;
|
|
|
20687
19897
|
if (queued) {
|
|
20688
19898
|
try {
|
|
20689
19899
|
record(callerTopic.agent);
|
|
20690
|
-
} catch (
|
|
19900
|
+
} catch (err) {
|
|
20691
19901
|
interSessionQueue.remove(pending.callerTopicId, pending.requestId);
|
|
20692
|
-
logger.warn({ err
|
|
19902
|
+
logger.warn({ err, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback record failed after enqueue; queue entry withdrawn");
|
|
20693
19903
|
return false;
|
|
20694
19904
|
}
|
|
20695
19905
|
await markPendingAskFile(pending, "queued_for_caller");
|
|
@@ -20709,8 +19919,8 @@ ${body}`;
|
|
|
20709
19919
|
}
|
|
20710
19920
|
async function deliverAskError(queryId, sourceLabel, error) {
|
|
20711
19921
|
try {
|
|
20712
|
-
|
|
20713
|
-
const pending =
|
|
19922
|
+
await init_ask_callbacks();
|
|
19923
|
+
const pending = resolveAskCallback(queryId);
|
|
20714
19924
|
if (pending) {
|
|
20715
19925
|
const prefix = pending.timedOut ? `\u26A0\uFE0F [Timeout - error notification was dropped]
|
|
20716
19926
|
|
|
@@ -20740,9 +19950,9 @@ function tryReconstructTopicRollout(opts) {
|
|
|
20740
19950
|
entries: entries.length
|
|
20741
19951
|
}, sessionId ? "ai: session expired \u2014 rollout reconstructed from unified log" : "ai: provider session bridged from shared conversation log");
|
|
20742
19952
|
return { kind: "rebuilt", sessionId: result.sessionId };
|
|
20743
|
-
} catch (
|
|
20744
|
-
logger.warn({ err
|
|
20745
|
-
return { kind: "failed", error: stringifyError(
|
|
19953
|
+
} catch (err) {
|
|
19954
|
+
logger.warn({ err, topicId, agent, sessionId }, "ai: session reconstruct failed");
|
|
19955
|
+
return { kind: "failed", error: stringifyError(err) };
|
|
20746
19956
|
}
|
|
20747
19957
|
}
|
|
20748
19958
|
function resolveSessionRetry(opts) {
|
|
@@ -20851,8 +20061,8 @@ function waitToStartRemoteUserTurn(params, queryId, options) {
|
|
|
20851
20061
|
function announceQueuedUserTurn(params, queryId) {
|
|
20852
20062
|
try {
|
|
20853
20063
|
params.onDispatched?.(queryId);
|
|
20854
|
-
} catch (
|
|
20855
|
-
logger.warn({ err
|
|
20064
|
+
} catch (err) {
|
|
20065
|
+
logger.warn({ err, topicId: params.topic.id, queryId }, "ai: queued dispatch hook failed");
|
|
20856
20066
|
}
|
|
20857
20067
|
if (!params.silent)
|
|
20858
20068
|
WsHub.get().broadcastAiActive(params.topic.id, queryId);
|
|
@@ -20873,81 +20083,6 @@ function waitToDrainRemoteInject(topicId) {
|
|
|
20873
20083
|
timer.unref?.();
|
|
20874
20084
|
remoteInjectWaiters.set(topicId, timer);
|
|
20875
20085
|
}
|
|
20876
|
-
async function drainOneDurableUserTurn() {
|
|
20877
|
-
if (durableTurnWorkerBusy)
|
|
20878
|
-
return;
|
|
20879
|
-
durableTurnWorkerBusy = true;
|
|
20880
|
-
try {
|
|
20881
|
-
const request = claimNextRuntimeUserTurnRequest(RUNTIME_INSTANCE_ID);
|
|
20882
|
-
if (!request)
|
|
20883
|
-
return;
|
|
20884
|
-
const topic = getTopic(request.topicId);
|
|
20885
|
-
if (!topic?.agent) {
|
|
20886
|
-
completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20887
|
-
return;
|
|
20888
|
-
}
|
|
20889
|
-
const execution = request.execution;
|
|
20890
|
-
const queryId = startAiTurn({
|
|
20891
|
-
topic,
|
|
20892
|
-
userId: request.userId,
|
|
20893
|
-
actorUserId: execution?.actorUserId,
|
|
20894
|
-
actorTopicScope: actorTopicScopeFrom(execution?.actorTopicScope),
|
|
20895
|
-
remoteSession: remoteSessionGrantFrom(execution?.remoteSession),
|
|
20896
|
-
vaultUserId: execution?.vaultUserId,
|
|
20897
|
-
prompt: request.prompt,
|
|
20898
|
-
_userMessages: request.userMessages,
|
|
20899
|
-
_conversationPrompts: execution?.conversationPrompts ?? [request.prompt],
|
|
20900
|
-
_loggedUserMessageCount: execution?.loggedUserMessageCount ?? Math.max(0, request.userMessages.length - (execution?.conversationPrompts?.length ?? 1)),
|
|
20901
|
-
_durableRequestIds: [request.requestId],
|
|
20902
|
-
attachments: request.attachments,
|
|
20903
|
-
allowAutoContinue: request.allowAutoContinue,
|
|
20904
|
-
origin: "user",
|
|
20905
|
-
requestId: execution?.sourceRequestId,
|
|
20906
|
-
agentOverride: execution?.agentOverride,
|
|
20907
|
-
modelOverride: execution?.modelOverride,
|
|
20908
|
-
effortOverride: execution?.effortOverride,
|
|
20909
|
-
...execution?.sessionIdSpecified ? { sessionId: execution.sessionId } : {},
|
|
20910
|
-
sessionScope: execution?.sessionScope,
|
|
20911
|
-
cwd: execution?.cwd,
|
|
20912
|
-
sessionName: execution?.sessionName,
|
|
20913
|
-
sessionType: execution?.sessionType,
|
|
20914
|
-
visualTools: execution?.visualTools,
|
|
20915
|
-
fileDeliveryTools: execution?.fileDeliveryTools,
|
|
20916
|
-
silent: execution?.silent,
|
|
20917
|
-
bridgeSessionFromHistory: execution?.bridgeSessionFromHistory,
|
|
20918
|
-
peerBridge: execution?.peerBridge,
|
|
20919
|
-
from: execution?.from,
|
|
20920
|
-
threadRootId: execution?.threadRootId,
|
|
20921
|
-
_queryId: request.requestId,
|
|
20922
|
-
_runtimeEpoch: execution?.runtimeEpoch ?? request.topicEpoch,
|
|
20923
|
-
onSettled: () => {
|
|
20924
|
-
completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20925
|
-
}
|
|
20926
|
-
});
|
|
20927
|
-
if (!queryId) {
|
|
20928
|
-
releaseRuntimeUserTurnClaim(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20929
|
-
return;
|
|
20930
|
-
}
|
|
20931
|
-
markRuntimeUserTurnRunning(request.topicId, request.requestId, RUNTIME_INSTANCE_ID, queryId);
|
|
20932
|
-
} finally {
|
|
20933
|
-
durableTurnWorkerBusy = false;
|
|
20934
|
-
}
|
|
20935
|
-
}
|
|
20936
|
-
function startDurableTurnRequestWorker() {
|
|
20937
|
-
if (durableTurnWorker)
|
|
20938
|
-
return () => {};
|
|
20939
|
-
durableTurnWorker = setInterval(() => {
|
|
20940
|
-
drainOneDurableUserTurn();
|
|
20941
|
-
}, 100);
|
|
20942
|
-
durableTurnWorker.unref?.();
|
|
20943
|
-
drainOneDurableUserTurn();
|
|
20944
|
-
return () => {
|
|
20945
|
-
if (!durableTurnWorker)
|
|
20946
|
-
return;
|
|
20947
|
-
clearInterval(durableTurnWorker);
|
|
20948
|
-
durableTurnWorker = null;
|
|
20949
|
-
};
|
|
20950
|
-
}
|
|
20951
20086
|
function startAiTurn(params) {
|
|
20952
20087
|
const storedTopic = getTopic(params.topic.id);
|
|
20953
20088
|
if (!storedTopic || !storedTopic.agent && !params.agentOverride) {
|
|
@@ -20959,8 +20094,8 @@ function startAiTurn(params) {
|
|
|
20959
20094
|
kind: "error",
|
|
20960
20095
|
error: storedTopic ? "topic no longer has an AI agent" : "topic no longer exists"
|
|
20961
20096
|
});
|
|
20962
|
-
} catch (
|
|
20963
|
-
logger.warn({ err
|
|
20097
|
+
} catch (err) {
|
|
20098
|
+
logger.warn({ err, topicId: params.topic.id }, "ai: rejected-turn settlement hook failed");
|
|
20964
20099
|
}
|
|
20965
20100
|
return null;
|
|
20966
20101
|
}
|
|
@@ -21016,7 +20151,7 @@ function startAiTurn(params) {
|
|
|
21016
20151
|
const askReplySources = params.askReplySources;
|
|
21017
20152
|
const sessionRetried = params._sessionRetried === true;
|
|
21018
20153
|
const emptyResponseRetried = params._emptyResponseRetried === true;
|
|
21019
|
-
const queryId = asTurnId(params._queryId ??
|
|
20154
|
+
const queryId = asTurnId(params._queryId ?? randomUUID18());
|
|
21020
20155
|
const roomId = turnConcurrency === "isolated" ? isolatedTurnRoomId(topicId, queryId) : asTurnSlotKey(topicId);
|
|
21021
20156
|
const currentRuntimeEpoch = getRuntimeTopicEpoch(topic.id);
|
|
21022
20157
|
const runtimeEpoch = params._runtimeEpoch ?? currentRuntimeEpoch;
|
|
@@ -21028,8 +20163,8 @@ function startAiTurn(params) {
|
|
|
21028
20163
|
}
|
|
21029
20164
|
try {
|
|
21030
20165
|
params.onSettled?.({ queryId, kind: "aborted", abortReason: "external" /* External */ });
|
|
21031
|
-
} catch (
|
|
21032
|
-
logger.warn({ err
|
|
20166
|
+
} catch (err) {
|
|
20167
|
+
logger.warn({ err, topicId: topic.id, queryId }, "ai: stale-turn settlement hook failed");
|
|
21033
20168
|
}
|
|
21034
20169
|
logger.info({ topicId: topic.id, queryId, queuedEpoch: params._runtimeEpoch, currentRuntimeEpoch }, "ai: dropped work queued before topic reset");
|
|
21035
20170
|
return null;
|
|
@@ -21079,8 +20214,8 @@ function startAiTurn(params) {
|
|
|
21079
20214
|
cleanupAgentFork(forkHandle);
|
|
21080
20215
|
try {
|
|
21081
20216
|
onSettled?.({ queryId: "", kind: "error", error });
|
|
21082
|
-
} catch (
|
|
21083
|
-
logger.warn({ err
|
|
20217
|
+
} catch (err) {
|
|
20218
|
+
logger.warn({ err, topicId, queryId }, "ai: isolated-turn rejection hook failed");
|
|
21084
20219
|
}
|
|
21085
20220
|
return null;
|
|
21086
20221
|
};
|
|
@@ -21127,7 +20262,7 @@ function startAiTurn(params) {
|
|
|
21127
20262
|
if (decision.action === "abort-replace") {
|
|
21128
20263
|
const running = decision.running;
|
|
21129
20264
|
if (isUserOrigin(running.origin) && !sameTurnActor(running.actorUserId, params.actorUserId)) {
|
|
21130
|
-
const
|
|
20265
|
+
const queuedQueryId = waitToStartRemoteUserTurn({
|
|
21131
20266
|
...params,
|
|
21132
20267
|
topic,
|
|
21133
20268
|
prompt,
|
|
@@ -21139,9 +20274,9 @@ function startAiTurn(params) {
|
|
|
21139
20274
|
_durableRequestIds: durableRequestIds,
|
|
21140
20275
|
_runtimeEpoch: runtimeEpoch
|
|
21141
20276
|
}, queryId);
|
|
21142
|
-
announceQueuedUserTurn({ ...params, topic },
|
|
21143
|
-
logger.info({ topicId, queryId:
|
|
21144
|
-
return
|
|
20277
|
+
announceQueuedUserTurn({ ...params, topic }, queuedQueryId);
|
|
20278
|
+
logger.info({ topicId, queryId: queuedQueryId, runningQueryId: running.queryId }, "ai: user turn from another actor queued behind the running turn");
|
|
20279
|
+
return queuedQueryId;
|
|
21145
20280
|
}
|
|
21146
20281
|
let omitRequestIds;
|
|
21147
20282
|
if (isUserOrigin(running.origin)) {
|
|
@@ -21273,14 +20408,14 @@ function startAiTurn(params) {
|
|
|
21273
20408
|
if (turnConcurrency === "topic") {
|
|
21274
20409
|
try {
|
|
21275
20410
|
writeQueryState(userId, topic.id, topic.title, prompt);
|
|
21276
|
-
} catch (
|
|
21277
|
-
logger.warn({ err
|
|
20411
|
+
} catch (err) {
|
|
20412
|
+
logger.warn({ err, topicId, userId }, "ai: failed to write active query state");
|
|
21278
20413
|
}
|
|
21279
20414
|
}
|
|
21280
20415
|
try {
|
|
21281
20416
|
onDispatched?.(queryId);
|
|
21282
|
-
} catch (
|
|
21283
|
-
logger.warn({ err
|
|
20417
|
+
} catch (err) {
|
|
20418
|
+
logger.warn({ err, topicId, queryId }, "ai: dispatch hook failed");
|
|
21284
20419
|
}
|
|
21285
20420
|
const override = getTopicConfig(topicId);
|
|
21286
20421
|
const agentKind = execution.agent;
|
|
@@ -21307,8 +20442,8 @@ function startAiTurn(params) {
|
|
|
21307
20442
|
control.injectParams.sessionId = bridge.sessionId;
|
|
21308
20443
|
try {
|
|
21309
20444
|
onSessionId?.(bridge.sessionId);
|
|
21310
|
-
} catch (
|
|
21311
|
-
logger.warn({ err
|
|
20445
|
+
} catch (err) {
|
|
20446
|
+
logger.warn({ err, topicId, queryId, agent: agentKind }, "ai: isolated session owner rejected bridged provider session id");
|
|
21312
20447
|
}
|
|
21313
20448
|
} else if (bridge.kind === "failed") {
|
|
21314
20449
|
historyBridgeError = "Conversation history could not be encoded into a provider session; no fresh session was started.";
|
|
@@ -21377,8 +20512,8 @@ function startAiTurn(params) {
|
|
|
21377
20512
|
const wikiDir = getSharedWikiDir();
|
|
21378
20513
|
const { latestSummaryFile } = resolveWikiMemoryMirror(wikiDir, memoryTopic.id, memoryTitle);
|
|
21379
20514
|
hasMemoryArchive = Boolean(resolvedBrief?.brief.latestSummaryMd || latestSummaryFile);
|
|
21380
|
-
} catch (
|
|
21381
|
-
logger.warn({ topicId, err
|
|
20515
|
+
} catch (err) {
|
|
20516
|
+
logger.warn({ topicId, err }, "ai: failed to inject topic brief");
|
|
21382
20517
|
}
|
|
21383
20518
|
systemPrompt += buildMemoryPromptSection({
|
|
21384
20519
|
topicTitle: topic.title,
|
|
@@ -21454,8 +20589,8 @@ function startAiTurn(params) {
|
|
|
21454
20589
|
control.injectParams.sessionId = prepared.forkId;
|
|
21455
20590
|
control.injectParams.forkHandle = prepared;
|
|
21456
20591
|
}
|
|
21457
|
-
} catch (
|
|
21458
|
-
throw new Error(`failed to prepare isolated session: ${stringifyError(
|
|
20592
|
+
} catch (err) {
|
|
20593
|
+
throw new Error(`failed to prepare isolated session: ${stringifyError(err)}`);
|
|
21459
20594
|
}
|
|
21460
20595
|
if (abortController.signal.aborted)
|
|
21461
20596
|
return;
|
|
@@ -21474,8 +20609,8 @@ function startAiTurn(params) {
|
|
|
21474
20609
|
throw new Error("browser MCP capability was not registered");
|
|
21475
20610
|
}
|
|
21476
20611
|
trackPlaywrightTurn(playwrightInstanceKey, control);
|
|
21477
|
-
} catch (
|
|
21478
|
-
logger.warn({ topicId, err
|
|
20612
|
+
} catch (err) {
|
|
20613
|
+
logger.warn({ topicId, err }, "ai: ensurePlaywright failed \u2014 proceeding without browser tools");
|
|
21479
20614
|
markPlaywrightUnavailable({
|
|
21480
20615
|
userId,
|
|
21481
20616
|
topic: topic.title,
|
|
@@ -21488,8 +20623,8 @@ function startAiTurn(params) {
|
|
|
21488
20623
|
if (wantsBgBash) {
|
|
21489
20624
|
try {
|
|
21490
20625
|
bgBashPort = await ensureBgBash(userId, topic.id);
|
|
21491
|
-
} catch (
|
|
21492
|
-
logger.warn({ topicId, err
|
|
20626
|
+
} catch (err) {
|
|
20627
|
+
logger.warn({ topicId, err }, "ai: ensureBgBash failed \u2014 proceeding without background bash tools");
|
|
21493
20628
|
turnReminders.push("<system-reminder>Background bash tools are UNAVAILABLE this turn. The `background_bash_*` tools could not be prepared, most often because the bash-rs binary is not installed on this host. Do not attempt to call them; run short commands in the foreground instead, and tell the user if the work genuinely needs a background job.</system-reminder>");
|
|
21494
20629
|
}
|
|
21495
20630
|
}
|
|
@@ -21702,8 +20837,8 @@ function startAiTurn(params) {
|
|
|
21702
20837
|
await settleSubagentFailure(queryId, error);
|
|
21703
20838
|
try {
|
|
21704
20839
|
onSettled?.({ queryId, kind: "error", error });
|
|
21705
|
-
} catch (
|
|
21706
|
-
logger.warn({ err
|
|
20840
|
+
} catch (err) {
|
|
20841
|
+
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21707
20842
|
}
|
|
21708
20843
|
return;
|
|
21709
20844
|
}
|
|
@@ -21719,8 +20854,8 @@ function startAiTurn(params) {
|
|
|
21719
20854
|
await settleSubagentFailure(queryId, classifyAgentError(outcome.error, agentKind));
|
|
21720
20855
|
try {
|
|
21721
20856
|
onSettled?.({ queryId, kind: "error", error: outcome.error });
|
|
21722
|
-
} catch (
|
|
21723
|
-
logger.warn({ err
|
|
20857
|
+
} catch (err) {
|
|
20858
|
+
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21724
20859
|
}
|
|
21725
20860
|
return;
|
|
21726
20861
|
}
|
|
@@ -21733,12 +20868,12 @@ function startAiTurn(params) {
|
|
|
21733
20868
|
kind: outcome.kind === "aborted" ? "aborted" : "completed",
|
|
21734
20869
|
...outcome.kind === "aborted" ? { abortReason: control.abortReason } : {}
|
|
21735
20870
|
});
|
|
21736
|
-
} catch (
|
|
21737
|
-
logger.warn({ err
|
|
20871
|
+
} catch (err) {
|
|
20872
|
+
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21738
20873
|
}
|
|
21739
|
-
}).catch(async (
|
|
21740
|
-
const error =
|
|
21741
|
-
logger.warn({ err
|
|
20874
|
+
}).catch(async (err) => {
|
|
20875
|
+
const error = err instanceof Error ? err.message : "Agent process crashed";
|
|
20876
|
+
logger.warn({ err, topicId, queryId, agent: agentKind, model: resolvedModel, silent }, "ai: background stream task failed");
|
|
21742
20877
|
if (!silent) {
|
|
21743
20878
|
WsHub.get().broadcastError(topicId, queryId, error);
|
|
21744
20879
|
WsHub.get().broadcastTopicNotice(topicId, "error", "\uC751\uB2F5 \uC2E4\uD328");
|
|
@@ -21787,7 +20922,7 @@ function triggerTopicAiTurn(topicId, userId, prompt, agentType, opts) {
|
|
|
21787
20922
|
if (!opts?.silent && !opts?.hideInjectMessage) {
|
|
21788
20923
|
const now = new Date().toISOString();
|
|
21789
20924
|
const injectMsg = {
|
|
21790
|
-
id: opts?.requestId ? `tell-${opts.requestId}` : `tell-${
|
|
20925
|
+
id: opts?.requestId ? `tell-${opts.requestId}` : `tell-${randomUUID18()}`,
|
|
21791
20926
|
topicId,
|
|
21792
20927
|
authorId: opts?.injectAuthorId ?? userId,
|
|
21793
20928
|
sourceAdapter: opts?.injectSourceAdapter,
|
|
@@ -21844,7 +20979,7 @@ function triggerTopicAiTurn(topicId, userId, prompt, agentType, opts) {
|
|
|
21844
20979
|
from: opts?.from
|
|
21845
20980
|
});
|
|
21846
20981
|
}
|
|
21847
|
-
var PLAYWRIGHT_UNAVAILABLE_NOTICE_COOLDOWN_MS, ASK_REPLY_INJECT_BATCH_MS = 500, playwrightUnavailableNoticeAt, askReplyInjectBatcher, remoteInjectWaiters
|
|
20982
|
+
var PLAYWRIGHT_UNAVAILABLE_NOTICE_COOLDOWN_MS, ASK_REPLY_INJECT_BATCH_MS = 500, playwrightUnavailableNoticeAt, askReplyInjectBatcher, remoteInjectWaiters;
|
|
21848
20983
|
var init_turn_runner = __esm(async () => {
|
|
21849
20984
|
init_manager();
|
|
21850
20985
|
init_constants();
|
|
@@ -21975,29 +21110,29 @@ function createSubagentLifecycle(host) {
|
|
|
21975
21110
|
}
|
|
21976
21111
|
function computeSubagentDepth(topicId) {
|
|
21977
21112
|
let depth = 0;
|
|
21978
|
-
let
|
|
21113
|
+
let current = host.storage.getTopic(topicId);
|
|
21979
21114
|
const visited = new Set;
|
|
21980
|
-
while (
|
|
21981
|
-
if (visited.has(
|
|
21115
|
+
while (current) {
|
|
21116
|
+
if (visited.has(current.id))
|
|
21982
21117
|
return limits.maxDepth;
|
|
21983
|
-
visited.add(
|
|
21984
|
-
if (
|
|
21118
|
+
visited.add(current.id);
|
|
21119
|
+
if (current.isSubagent)
|
|
21985
21120
|
depth += 1;
|
|
21986
|
-
if (!
|
|
21121
|
+
if (!current.parentTopicId || current.parentTopicId === current.id)
|
|
21987
21122
|
break;
|
|
21988
|
-
|
|
21123
|
+
current = host.storage.getTopic(current.parentTopicId);
|
|
21989
21124
|
}
|
|
21990
21125
|
return depth;
|
|
21991
21126
|
}
|
|
21992
|
-
function
|
|
21127
|
+
function canSpawnSubagentsFromTopic(topicId) {
|
|
21993
21128
|
const topic = host.storage.getTopic(topicId);
|
|
21994
21129
|
return topic?.kind === "agent" && computeSubagentDepth(topicId) < limits.maxDepth;
|
|
21995
21130
|
}
|
|
21996
21131
|
function patchSubagentCard(parentTopicId, cardMessageId, patch) {
|
|
21997
|
-
const
|
|
21998
|
-
if (!
|
|
21132
|
+
const current = host.storage.getMessage(parentTopicId, cardMessageId)?.subagentCard;
|
|
21133
|
+
if (!current)
|
|
21999
21134
|
return;
|
|
22000
|
-
const next = { ...
|
|
21135
|
+
const next = { ...current, ...patch };
|
|
22001
21136
|
const editedAt = host.runtime.now();
|
|
22002
21137
|
if (!host.storage.updateSubagentCard(parentTopicId, cardMessageId, next, editedAt))
|
|
22003
21138
|
return;
|
|
@@ -22017,7 +21152,7 @@ function createSubagentLifecycle(host) {
|
|
|
22017
21152
|
patchSubagentCard(watch.parentTopicId, watch.cardMessageId, { status: "running" });
|
|
22018
21153
|
}
|
|
22019
21154
|
}
|
|
22020
|
-
function
|
|
21155
|
+
function takeSubagentWatch(queryId) {
|
|
22021
21156
|
const childTopicId = childByQueryId.get(queryId);
|
|
22022
21157
|
if (!childTopicId)
|
|
22023
21158
|
return recoverPersistedSubagentWatch(queryId);
|
|
@@ -22061,7 +21196,7 @@ function createSubagentLifecycle(host) {
|
|
|
22061
21196
|
if (watch.queryId)
|
|
22062
21197
|
childByQueryId.delete(watch.queryId);
|
|
22063
21198
|
}
|
|
22064
|
-
function
|
|
21199
|
+
function cancelSubagentWatchForDeletedTopic(childTopicId) {
|
|
22065
21200
|
const watch = watchesByChild.get(childTopicId);
|
|
22066
21201
|
if (!watch)
|
|
22067
21202
|
return;
|
|
@@ -22091,8 +21226,8 @@ function createSubagentLifecycle(host) {
|
|
|
22091
21226
|
if (!await host.sessionCommunication.notifyParent({ watch, prompt, requestId })) {
|
|
22092
21227
|
appendParentSystemNote(watch, prompt);
|
|
22093
21228
|
}
|
|
22094
|
-
} catch (
|
|
22095
|
-
logger.warn({ err
|
|
21229
|
+
} catch (err) {
|
|
21230
|
+
logger.warn({ err, parentTopicId: watch.parentTopicId, childTopicId: watch.childTopicId, noteKind }, "subagent: parent AI notify failed \u2014 falling back to system message");
|
|
22096
21231
|
try {
|
|
22097
21232
|
appendParentSystemNote(watch, prompt);
|
|
22098
21233
|
} catch (fallbackErr) {
|
|
@@ -22104,7 +21239,7 @@ function createSubagentLifecycle(host) {
|
|
|
22104
21239
|
}
|
|
22105
21240
|
}
|
|
22106
21241
|
}
|
|
22107
|
-
async function
|
|
21242
|
+
async function settleSubagentSuccess(watch, finalText) {
|
|
22108
21243
|
const summary = finalText.replace(/\s+/g, " ").trim().slice(0, RESULT_SUMMARY_CHARS);
|
|
22109
21244
|
try {
|
|
22110
21245
|
patchSubagentCard(watch.parentTopicId, watch.cardMessageId, {
|
|
@@ -22112,8 +21247,8 @@ function createSubagentLifecycle(host) {
|
|
|
22112
21247
|
resultSummary: summary || "(no text response)",
|
|
22113
21248
|
finishedAt: host.runtime.now()
|
|
22114
21249
|
});
|
|
22115
|
-
} catch (
|
|
22116
|
-
logger.warn({ err
|
|
21250
|
+
} catch (err) {
|
|
21251
|
+
logger.warn({ err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: completed-card update failed");
|
|
22117
21252
|
}
|
|
22118
21253
|
if (watch.reportMode === "auto") {
|
|
22119
21254
|
await notifyParent(watch, `[Subagent completed \u2190 ${watch.name}]
|
|
@@ -22122,8 +21257,8 @@ function createSubagentLifecycle(host) {
|
|
|
22122
21257
|
${finalText || "(no text response)"}`, "done");
|
|
22123
21258
|
}
|
|
22124
21259
|
}
|
|
22125
|
-
async function
|
|
22126
|
-
const watch =
|
|
21260
|
+
async function settleSubagentFailure(queryId, reason) {
|
|
21261
|
+
const watch = takeSubagentWatch(queryId);
|
|
22127
21262
|
if (!watch)
|
|
22128
21263
|
return;
|
|
22129
21264
|
try {
|
|
@@ -22132,8 +21267,8 @@ ${finalText || "(no text response)"}`, "done");
|
|
|
22132
21267
|
errorMessage: reason,
|
|
22133
21268
|
finishedAt: host.runtime.now()
|
|
22134
21269
|
});
|
|
22135
|
-
} catch (
|
|
22136
|
-
logger.warn({ err
|
|
21270
|
+
} catch (err) {
|
|
21271
|
+
logger.warn({ err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: failed-card update failed");
|
|
22137
21272
|
}
|
|
22138
21273
|
if (watch.reportMode === "auto") {
|
|
22139
21274
|
await notifyParent(watch, `[Subagent failed \u2190 ${watch.name}]
|
|
@@ -22170,7 +21305,7 @@ spawn_subagent\uB85C \uC704\uC784\uD55C \uC791\uC5C5\uC774 \uC2E4\uD328\uD588\uC
|
|
|
22170
21305
|
function findSubagentCardMessage(childTopicId) {
|
|
22171
21306
|
return host.storage.listSubagentMessages().filter((message) => message.subagentCard?.subagentTopicId === childTopicId).at(-1);
|
|
22172
21307
|
}
|
|
22173
|
-
function
|
|
21308
|
+
function subagentReportMode(childTopicId) {
|
|
22174
21309
|
return host.storage.getTopic(childTopicId)?.subagentReportMode ?? findSubagentCardMessage(childTopicId)?.subagentCard?.reportMode ?? "auto";
|
|
22175
21310
|
}
|
|
22176
21311
|
async function startSubagentCard(ctx, cardMessage) {
|
|
@@ -22378,7 +21513,7 @@ ${card.task}${reportInstruction}`;
|
|
|
22378
21513
|
for (const siblings of byParent.values()) {
|
|
22379
21514
|
siblings.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
22380
21515
|
}
|
|
22381
|
-
const
|
|
21516
|
+
const descendants = [];
|
|
22382
21517
|
const visited = new Set([ctx.topicId]);
|
|
22383
21518
|
const visit = (parentId) => {
|
|
22384
21519
|
for (const child of byParent.get(parentId) ?? []) {
|
|
@@ -22388,12 +21523,12 @@ ${card.task}${reportInstruction}`;
|
|
|
22388
21523
|
if (!child.participants.some((participant) => participant.userId === rootOwnerId && participant.role === "owner")) {
|
|
22389
21524
|
continue;
|
|
22390
21525
|
}
|
|
22391
|
-
|
|
21526
|
+
descendants.push(child);
|
|
22392
21527
|
visit(child.id);
|
|
22393
21528
|
}
|
|
22394
21529
|
};
|
|
22395
21530
|
visit(ctx.topicId);
|
|
22396
|
-
return
|
|
21531
|
+
return descendants;
|
|
22397
21532
|
})() : [];
|
|
22398
21533
|
const children = actorScope ? descendants.filter((child) => actorScope.visible.has(child.id)) : descendants;
|
|
22399
21534
|
return {
|
|
@@ -22417,10 +21552,10 @@ ${card.task}${reportInstruction}`;
|
|
|
22417
21552
|
return card?.status ?? "unknown";
|
|
22418
21553
|
}
|
|
22419
21554
|
function listMemoryTopicNames(ctx) {
|
|
22420
|
-
const
|
|
22421
|
-
if (!
|
|
21555
|
+
const current = host.storage.getTopic(ctx.topicId);
|
|
21556
|
+
if (!current)
|
|
22422
21557
|
return { error: `Error: topic '${ctx.topicId}' not found.` };
|
|
22423
|
-
if (!
|
|
21558
|
+
if (!current.participants.some((participant) => participant.userId === ctx.userId)) {
|
|
22424
21559
|
return { error: "Error: user is not a member of this topic." };
|
|
22425
21560
|
}
|
|
22426
21561
|
const sources = new Map;
|
|
@@ -22510,8 +21645,8 @@ ${card.task}${reportInstruction}`;
|
|
|
22510
21645
|
try {
|
|
22511
21646
|
await host.topic.delete(child, ctx.userId);
|
|
22512
21647
|
return textResult(`Subagent deleted: ${child.title} (${child.id})`);
|
|
22513
|
-
} catch (
|
|
22514
|
-
const message =
|
|
21648
|
+
} catch (err) {
|
|
21649
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
22515
21650
|
return errorResult(`Error: failed to delete subagent '${child.title}': ${message}`);
|
|
22516
21651
|
}
|
|
22517
21652
|
}
|
|
@@ -22608,13 +21743,13 @@ ${card.task}${reportInstruction}`;
|
|
|
22608
21743
|
}
|
|
22609
21744
|
return {
|
|
22610
21745
|
computeSubagentDepth,
|
|
22611
|
-
canSpawnSubagentsFromTopic
|
|
22612
|
-
takeSubagentWatch
|
|
22613
|
-
cancelSubagentWatchForDeletedTopic
|
|
22614
|
-
settleSubagentSuccess
|
|
22615
|
-
settleSubagentFailure
|
|
21746
|
+
canSpawnSubagentsFromTopic,
|
|
21747
|
+
takeSubagentWatch,
|
|
21748
|
+
cancelSubagentWatchForDeletedTopic,
|
|
21749
|
+
settleSubagentSuccess,
|
|
21750
|
+
settleSubagentFailure,
|
|
22616
21751
|
sweepStaleSubagentCards,
|
|
22617
|
-
subagentReportMode
|
|
21752
|
+
subagentReportMode,
|
|
22618
21753
|
createSubagentManagementToolDefinitions,
|
|
22619
21754
|
createSpawnSubagentToolDefinition,
|
|
22620
21755
|
createPrepareSubagentToolDefinition
|
|
@@ -22661,9 +21796,9 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22661
21796
|
},
|
|
22662
21797
|
topic: {
|
|
22663
21798
|
async createDerived(input) {
|
|
22664
|
-
|
|
21799
|
+
await init_derive();
|
|
22665
21800
|
try {
|
|
22666
|
-
const topic = await
|
|
21801
|
+
const topic = await createDerivedTopic(input.parentTopicId, input.userId, false, {
|
|
22667
21802
|
name: input.name,
|
|
22668
21803
|
subagent: {
|
|
22669
21804
|
agent: input.agent,
|
|
@@ -22673,30 +21808,30 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22673
21808
|
});
|
|
22674
21809
|
return { ok: true, topic };
|
|
22675
21810
|
} catch (error) {
|
|
22676
|
-
if (error instanceof
|
|
21811
|
+
if (error instanceof TopicTitleConflictError) {
|
|
22677
21812
|
return { ok: false, reason: "title-conflict", message: error.message };
|
|
22678
21813
|
}
|
|
22679
|
-
if (error instanceof
|
|
21814
|
+
if (error instanceof TopicDeriveBusyError)
|
|
22680
21815
|
return { ok: false, reason: "busy" };
|
|
22681
21816
|
throw error;
|
|
22682
21817
|
}
|
|
22683
21818
|
},
|
|
22684
21819
|
async delete(topic, userId) {
|
|
22685
|
-
|
|
22686
|
-
await
|
|
21820
|
+
await init_lifecycle();
|
|
21821
|
+
await deleteTopicCascade(topic, userId);
|
|
22687
21822
|
}
|
|
22688
21823
|
},
|
|
22689
21824
|
task: {
|
|
22690
21825
|
async dispatch(input) {
|
|
22691
|
-
|
|
22692
|
-
|
|
22693
|
-
const queryId =
|
|
21826
|
+
await init_turn_runner();
|
|
21827
|
+
await init_active_rooms();
|
|
21828
|
+
const queryId = triggerTopicAiTurn(input.child.id, input.userId, input.prompt, undefined, {
|
|
22694
21829
|
origin: `subagent-task:${input.parent.title}`,
|
|
22695
21830
|
requestId: input.requestId,
|
|
22696
21831
|
injectAuthorId: "ai",
|
|
22697
21832
|
onDispatched: input.onDispatched
|
|
22698
21833
|
});
|
|
22699
|
-
return { accepted: Boolean(queryId ||
|
|
21834
|
+
return { accepted: Boolean(queryId || getRoomQuery(input.child.id)) };
|
|
22700
21835
|
}
|
|
22701
21836
|
},
|
|
22702
21837
|
sessionCommunication: {
|
|
@@ -22704,16 +21839,16 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22704
21839
|
const parent = getTopic(watch.parentTopicId);
|
|
22705
21840
|
if (!parent)
|
|
22706
21841
|
return true;
|
|
22707
|
-
|
|
22708
|
-
const queryId = parent.agent ?
|
|
21842
|
+
await init_turn_runner();
|
|
21843
|
+
const queryId = parent.agent ? triggerTopicAiTurn(watch.parentTopicId, watch.userId, prompt, undefined, {
|
|
22709
21844
|
origin: `subagent:${watch.name}`,
|
|
22710
21845
|
requestId,
|
|
22711
21846
|
hideInjectMessage: true
|
|
22712
21847
|
}) : null;
|
|
22713
21848
|
if (queryId)
|
|
22714
21849
|
return true;
|
|
22715
|
-
|
|
22716
|
-
return Boolean(parent.agent &&
|
|
21850
|
+
await init_active_rooms();
|
|
21851
|
+
return Boolean(parent.agent && interSessionQueue.hasRequest(parent.id, requestId));
|
|
22717
21852
|
},
|
|
22718
21853
|
listTellTargetIds: listSubagentTellTargetIds,
|
|
22719
21854
|
grantTellTarget: grantSubagentTellTarget,
|
|
@@ -22742,19 +21877,19 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22742
21877
|
async resolveAgentModel({ context, agent, model, hasOverride }) {
|
|
22743
21878
|
let resolvedModel = model;
|
|
22744
21879
|
if (model) {
|
|
22745
|
-
|
|
22746
|
-
|
|
22747
|
-
const registry =
|
|
21880
|
+
await Promise.resolve().then(() => init_model_catalog());
|
|
21881
|
+
await init_registry();
|
|
21882
|
+
const registry = getRegistry(agent);
|
|
22748
21883
|
if (!registry.validateModel(model)) {
|
|
22749
21884
|
return { error: `Error: model '${model}' is not valid for agent '${agent}'.` };
|
|
22750
21885
|
}
|
|
22751
|
-
resolvedModel =
|
|
21886
|
+
resolvedModel = resolveModelForAgent(agent, model, registry);
|
|
22752
21887
|
}
|
|
22753
21888
|
if (hasOverride) {
|
|
22754
|
-
|
|
22755
|
-
|
|
22756
|
-
const targetModel = resolvedModel ??
|
|
22757
|
-
const auth =
|
|
21889
|
+
await init_auth_check();
|
|
21890
|
+
await init_registry();
|
|
21891
|
+
const targetModel = resolvedModel ?? getRegistry(agent).defaultModel;
|
|
21892
|
+
const auth = checkAgentModelAuth(agent, targetModel, undefined, context.userId);
|
|
22758
21893
|
if (!auth.ok) {
|
|
22759
21894
|
return { error: `Error: agent '${agent}' is not available: ${auth.error}` };
|
|
22760
21895
|
}
|
|
@@ -23184,11 +22319,11 @@ var DEFAULT_SELF_CONFIG_PRODUCT = {
|
|
|
23184
22319
|
derivedTopicLimit: SELF_CONFIG_DERIVED_TOPIC_LIMIT,
|
|
23185
22320
|
toolDescriptions: {}
|
|
23186
22321
|
};
|
|
23187
|
-
function ok(
|
|
23188
|
-
return { text
|
|
22322
|
+
function ok(text) {
|
|
22323
|
+
return { text };
|
|
23189
22324
|
}
|
|
23190
|
-
function err(
|
|
23191
|
-
return { text
|
|
22325
|
+
function err(text) {
|
|
22326
|
+
return { text, isError: true };
|
|
23192
22327
|
}
|
|
23193
22328
|
function errorMessage(error) {
|
|
23194
22329
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -23505,8 +22640,8 @@ var defaultSelfConfigHost = {
|
|
|
23505
22640
|
},
|
|
23506
22641
|
derivedTopics: {
|
|
23507
22642
|
async create(sourceTopicId, userId, copyHistory, options) {
|
|
23508
|
-
|
|
23509
|
-
return
|
|
22643
|
+
await init_derive();
|
|
22644
|
+
return createDerivedTopic(sourceTopicId, userId, copyHistory, options);
|
|
23510
22645
|
},
|
|
23511
22646
|
link: topicMarkdownLink,
|
|
23512
22647
|
isTitleConflict: (error) => error instanceof Error && error.name === "TopicTitleConflictError",
|
|
@@ -23786,58 +22921,58 @@ await __promiseAll([
|
|
|
23786
22921
|
init_topic_cleanup()
|
|
23787
22922
|
]);
|
|
23788
22923
|
export {
|
|
23789
|
-
|
|
23790
|
-
withCodexSpawnSerial,
|
|
23791
|
-
visualToolDefinitions,
|
|
23792
|
-
unregisterOwnedCodexPids,
|
|
23793
|
-
summarizeToolInput,
|
|
23794
|
-
summarizeShellCommand,
|
|
23795
|
-
summarizeDisplayText,
|
|
23796
|
-
snapshotCodexChildren,
|
|
23797
|
-
showPngTool,
|
|
23798
|
-
showMermaidTool,
|
|
23799
|
-
showImageTool,
|
|
23800
|
-
showHtmlTool,
|
|
23801
|
-
rotateTopicLogs,
|
|
23802
|
-
resolveTaskEventScope,
|
|
23803
|
-
registerOwnedCodexPids,
|
|
23804
|
-
purgeTopicLogs,
|
|
23805
|
-
otiumVisualToolDefinitions,
|
|
23806
|
-
normalizeAskUserQuestionInput,
|
|
23807
|
-
normalizeAskUserChoices,
|
|
23808
|
-
killOwnedCodexTreesForShutdown,
|
|
23809
|
-
killCodexTrees,
|
|
23810
|
-
isExplicitAgentSwitchTargets,
|
|
23811
|
-
hasExplicitAgentSwitchRequest,
|
|
23812
|
-
formatToolUse,
|
|
23813
|
-
forkAgentSession,
|
|
23814
|
-
findNewCodexChildren,
|
|
23815
|
-
explicitAgentSwitchTargets,
|
|
23816
|
-
defaultAskUserDurabilityHost,
|
|
23817
|
-
createTopicLogMaintenance,
|
|
23818
|
-
createSubagentLifecycle,
|
|
23819
|
-
createSelfConfigToolDefinitionsForCore,
|
|
23820
|
-
createSelfConfigRuntime,
|
|
23821
|
-
createSelfConfigCore,
|
|
23822
|
-
createPublishHtmlToolDefinitions,
|
|
23823
|
-
createCodexTreeManager,
|
|
23824
|
-
createAskUserRuntime,
|
|
23825
|
-
createArchiverRuntime,
|
|
23826
|
-
createAgentForkHelpers,
|
|
23827
|
-
cleanupTopicRolloutsFromEntries,
|
|
23828
|
-
cleanupTopicRollouts,
|
|
23829
|
-
cleanupAgentFork,
|
|
23830
|
-
classifyShellToolName,
|
|
23831
|
-
checkAgentModelAuth,
|
|
23832
|
-
checkAgentAuth,
|
|
23833
|
-
buildNumberedDiffSummary,
|
|
23834
|
-
archiveActiveTopicForMemory,
|
|
23835
|
-
applySelfConfigCapabilityFilter,
|
|
23836
|
-
acquireCodexSpawnLock,
|
|
23837
|
-
VISUALS_MCP_KEY,
|
|
23838
|
-
SELF_CONFIG_CAPABILITIES,
|
|
22924
|
+
DEFAULT_SELF_CONFIG_PRODUCT,
|
|
23839
22925
|
MIN_MEMORY_ARCHIVE_EXCHANGES,
|
|
23840
|
-
|
|
22926
|
+
SELF_CONFIG_CAPABILITIES,
|
|
22927
|
+
VISUALS_MCP_KEY,
|
|
22928
|
+
acquireCodexSpawnLock,
|
|
22929
|
+
applySelfConfigCapabilityFilter,
|
|
22930
|
+
archiveActiveTopicForMemory,
|
|
22931
|
+
buildNumberedDiffSummary,
|
|
22932
|
+
checkAgentAuth,
|
|
22933
|
+
checkAgentModelAuth,
|
|
22934
|
+
classifyShellToolName,
|
|
22935
|
+
cleanupAgentFork,
|
|
22936
|
+
cleanupTopicRollouts,
|
|
22937
|
+
cleanupTopicRolloutsFromEntries,
|
|
22938
|
+
createAgentForkHelpers,
|
|
22939
|
+
createArchiverRuntime,
|
|
22940
|
+
createAskUserRuntime,
|
|
22941
|
+
createCodexTreeManager,
|
|
22942
|
+
createPublishHtmlToolDefinitions,
|
|
22943
|
+
createSelfConfigCore,
|
|
22944
|
+
createSelfConfigRuntime,
|
|
22945
|
+
createSelfConfigToolDefinitionsForCore,
|
|
22946
|
+
createSubagentLifecycle,
|
|
22947
|
+
createTopicLogMaintenance,
|
|
22948
|
+
defaultAskUserDurabilityHost,
|
|
22949
|
+
explicitAgentSwitchTargets,
|
|
22950
|
+
findNewCodexChildren,
|
|
22951
|
+
forkAgentSession,
|
|
22952
|
+
formatToolUse,
|
|
22953
|
+
hasExplicitAgentSwitchRequest,
|
|
22954
|
+
isExplicitAgentSwitchTargets,
|
|
22955
|
+
killCodexTrees,
|
|
22956
|
+
killOwnedCodexTreesForShutdown,
|
|
22957
|
+
normalizeAskUserChoices,
|
|
22958
|
+
normalizeAskUserQuestionInput,
|
|
22959
|
+
otiumVisualToolDefinitions,
|
|
22960
|
+
purgeTopicLogs,
|
|
22961
|
+
registerOwnedCodexPids,
|
|
22962
|
+
resolveTaskEventScope,
|
|
22963
|
+
rotateTopicLogs,
|
|
22964
|
+
showHtmlTool,
|
|
22965
|
+
showImageTool,
|
|
22966
|
+
showMermaidTool,
|
|
22967
|
+
showPngTool,
|
|
22968
|
+
snapshotCodexChildren,
|
|
22969
|
+
summarizeDisplayText,
|
|
22970
|
+
summarizeShellCommand,
|
|
22971
|
+
summarizeToolInput,
|
|
22972
|
+
unregisterOwnedCodexPids,
|
|
22973
|
+
visualToolDefinitions,
|
|
22974
|
+
withCodexSpawnSerial,
|
|
22975
|
+
withTaskSnapshots
|
|
23841
22976
|
};
|
|
23842
22977
|
|
|
23843
|
-
//# debugId=
|
|
22978
|
+
//# debugId=D917583E369BC94464756E2164756E21
|