negotium 0.23.8 → 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 +436 -1300
- package/dist/agent-helpers.js.map +6 -6
- 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-g5etvfj3.js → chunk-qvtj66y2.js} +4 -5
- package/dist/{chunk-g5etvfj3.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 +3750 -5422
- package/dist/main.js.map +14 -10
- package/dist/mcp-catalog.js +4 -4
- package/dist/mcp-catalog.js.map +1 -1
- package/dist/mcp-factories.js +967 -1769
- package/dist/mcp-factories.js.map +12 -9
- 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 +8 -7
- package/dist/prompts.js.map +3 -3
- 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/mcp/factories/session-comm.ts +16 -2
- package/dist/runtime/src/mcp/factories/session-history.ts +21 -306
- package/dist/runtime/src/mcp/session-comm/default-host.ts +14 -0
- package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
- package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/server.ts +16 -2
- package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
- package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
- package/dist/runtime/src/mcp/session-history-server.ts +2 -10
- package/dist/runtime/src/prompts/builders.ts +2 -1
- 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/mcp/factories/session-comm.d.ts +6 -0
- package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
- package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -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",
|
|
@@ -9849,8 +9685,9 @@ function buildRuntimeToolSection(opts, extensions) {
|
|
|
9849
9685
|
"The session-comm MCP server is the only cross-topic messaging surface. Its canonical tools are `list_sessions`, `peek_session`, `tell_session`, `ask_session`, and `abort_session`.",
|
|
9850
9686
|
"`list_sessions` inspects topics; `ask_session` is for read-only questions whose answer must return here; `tell_session` is one-way delegation/handoff with no reply back. Do not call `tell_session` bidirectional, and do not claim `ask_session` is unavailable without first checking the session-comm tools."
|
|
9851
9687
|
],
|
|
9688
|
+
"To hand over context, point instead of pasting: in `tell_session`/`ask_session`, state the instruction and cite the relevant part of your own history (an entry range from `list_session_boundaries`, or a `sessionId`) rather than copying long transcripts. A session that receives such a message (`[from <topic>]`) reads the sender's history with `read_session_history_of`/`search_session_history_of` (`to` = the sender as `list_sessions` shows it). Only sessions listed by `list_sessions` are readable; if the sender is not listed, ask for the details instead.",
|
|
9852
9689
|
...agentKind === "maestro" ? [
|
|
9853
|
-
subagentParentTitle ? "Session-comm schemas may initially be deferred. Activate `mcp__session-comm__list_sessions` and `mcp__session-comm__tell_session` with ToolSearch before use." : 'Session-comm schemas may initially be deferred. Before using or judging availability, call ToolSearch("select:mcp__session-comm__list_sessions,mcp__session-comm__peek_session,mcp__session-comm__tell_session,mcp__session-comm__ask_session,mcp__session-comm__abort_session") to activate the exact tools. Never substitute a similarly described runtime tool.'
|
|
9690
|
+
subagentParentTitle ? "Session-comm schemas may initially be deferred. Activate `mcp__session-comm__list_sessions` and `mcp__session-comm__tell_session` with ToolSearch before use." : 'Session-comm schemas may initially be deferred. Before using or judging availability, call ToolSearch("select:mcp__session-comm__list_sessions,mcp__session-comm__peek_session,mcp__session-comm__tell_session,mcp__session-comm__ask_session,mcp__session-comm__abort_session,mcp__session-comm__read_session_history_of,mcp__session-comm__search_session_history_of") to activate the exact tools. Never substitute a similarly described runtime tool.'
|
|
9854
9691
|
] : [],
|
|
9855
9692
|
"Do not use session communication to make another topic perform destructive changes without the user's clear intent.",
|
|
9856
9693
|
...spawnSubagentSection,
|
|
@@ -10146,9 +9983,9 @@ function resolveTopicBrief(topicId, legacyTitle) {
|
|
|
10146
9983
|
const titleBrief = getTopicBrief(titleKey);
|
|
10147
9984
|
if (titleBrief)
|
|
10148
9985
|
return { brief: titleBrief, storageKey: titleKey };
|
|
10149
|
-
const
|
|
10150
|
-
if (
|
|
10151
|
-
return { brief:
|
|
9986
|
+
const current = getTopicBrief(topicId);
|
|
9987
|
+
if (current)
|
|
9988
|
+
return { brief: current, storageKey: topicId };
|
|
10152
9989
|
const legacy = titleKey === legacyTitle ? null : getTopicBrief(legacyTitle);
|
|
10153
9990
|
return legacy ? { brief: legacy, storageKey: legacyTitle } : null;
|
|
10154
9991
|
}
|
|
@@ -10768,11 +10605,6 @@ var init_archiver = __esm(async () => {
|
|
|
10768
10605
|
});
|
|
10769
10606
|
|
|
10770
10607
|
// ../../packages/core/src/agents/auth-check.ts
|
|
10771
|
-
var exports_auth_check = {};
|
|
10772
|
-
__export(exports_auth_check, {
|
|
10773
|
-
checkAgentModelAuth: () => checkAgentModelAuth,
|
|
10774
|
-
checkAgentAuth: () => checkAgentAuth
|
|
10775
|
-
});
|
|
10776
10608
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
10777
10609
|
import { existsSync as existsSync17 } from "fs";
|
|
10778
10610
|
import { homedir as homedir8, platform } from "os";
|
|
@@ -11104,8 +10936,8 @@ function createRoomQueryRegistry(host) {
|
|
|
11104
10936
|
clearInterval(previousMonitor);
|
|
11105
10937
|
activeByRoom.set(roomId, control);
|
|
11106
10938
|
const monitor = setInterval(() => {
|
|
11107
|
-
const
|
|
11108
|
-
if (!
|
|
10939
|
+
const current = activeByRoom.get(roomId);
|
|
10940
|
+
if (!current || current.queryId !== control.queryId) {
|
|
11109
10941
|
clearInterval(monitor);
|
|
11110
10942
|
if (leaseMonitors.get(roomId) === monitor)
|
|
11111
10943
|
leaseMonitors.delete(roomId);
|
|
@@ -11127,8 +10959,8 @@ function createRoomQueryRegistry(host) {
|
|
|
11127
10959
|
return true;
|
|
11128
10960
|
}
|
|
11129
10961
|
function clear(roomId, queryId) {
|
|
11130
|
-
const
|
|
11131
|
-
if (
|
|
10962
|
+
const current = activeByRoom.get(roomId);
|
|
10963
|
+
if (current?.queryId === queryId) {
|
|
11132
10964
|
activeByRoom.delete(roomId);
|
|
11133
10965
|
const monitor = leaseMonitors.get(roomId);
|
|
11134
10966
|
if (monitor)
|
|
@@ -11191,43 +11023,12 @@ var init_room_query_registry = () => {};
|
|
|
11191
11023
|
var init_types2 = () => {};
|
|
11192
11024
|
|
|
11193
11025
|
// ../../packages/core/src/query/active-rooms.ts
|
|
11194
|
-
var exports_active_rooms = {};
|
|
11195
|
-
__export(exports_active_rooms, {
|
|
11196
|
-
wsAbortReason: () => wsAbortReason,
|
|
11197
|
-
takeDeferredInject: () => takeDeferredInject,
|
|
11198
|
-
setRoomQuery: () => setRoomQuery,
|
|
11199
|
-
listRunningTopicQueries: () => listRunningTopicQueries,
|
|
11200
|
-
listRunningTopicIds: () => listRunningTopicIds,
|
|
11201
|
-
isolatedTurnRoomId: () => isolatedTurnRoomId,
|
|
11202
|
-
isUserOrigin: () => isUserOrigin,
|
|
11203
|
-
isTopicRunning: () => isTopicRunning,
|
|
11204
|
-
interSessionQueue: () => interSessionQueue,
|
|
11205
|
-
getRoomQueryStatus: () => getRoomQueryStatus,
|
|
11206
|
-
getRoomQuery: () => getRoomQuery,
|
|
11207
|
-
deferInject: () => deferInject,
|
|
11208
|
-
decideNewQuery: () => decideNewQuery,
|
|
11209
|
-
clearRoomQuery: () => clearRoomQuery,
|
|
11210
|
-
cancelDeferredInject: () => cancelDeferredInject,
|
|
11211
|
-
abortRoom: () => abortRoom,
|
|
11212
|
-
abortAllRooms: () => abortAllRooms,
|
|
11213
|
-
InterSessionQueue: () => InterSessionQueue,
|
|
11214
|
-
DeferredInjectBatcher: () => DeferredInjectBatcher
|
|
11215
|
-
});
|
|
11216
11026
|
function getRoomQuery(roomId) {
|
|
11217
11027
|
return roomQueryRegistry.get(roomId);
|
|
11218
11028
|
}
|
|
11219
|
-
function listRunningTopicQueries() {
|
|
11220
|
-
return roomQueryRegistry.listRunningTopicQueries();
|
|
11221
|
-
}
|
|
11222
|
-
function listRunningTopicIds() {
|
|
11223
|
-
return roomQueryRegistry.listRunningTopicIds();
|
|
11224
|
-
}
|
|
11225
11029
|
function isTopicRunning(topicId) {
|
|
11226
11030
|
return roomQueryRegistry.isTopicRunning(topicId);
|
|
11227
11031
|
}
|
|
11228
|
-
function getRoomQueryStatus(topicId, queryId) {
|
|
11229
|
-
return roomQueryRegistry.status(topicId, queryId);
|
|
11230
|
-
}
|
|
11231
11032
|
function setRoomQuery(control) {
|
|
11232
11033
|
return roomQueryRegistry.set(control);
|
|
11233
11034
|
}
|
|
@@ -11237,9 +11038,6 @@ function clearRoomQuery(roomId, queryId) {
|
|
|
11237
11038
|
function abortRoom(roomId, reason = "external" /* External */) {
|
|
11238
11039
|
return roomQueryRegistry.abort(roomId, reason);
|
|
11239
11040
|
}
|
|
11240
|
-
function abortAllRooms(reason = "external" /* External */) {
|
|
11241
|
-
return roomQueryRegistry.abortAll(reason);
|
|
11242
|
-
}
|
|
11243
11041
|
function decideNewQuery(topicId, incomingOrigin) {
|
|
11244
11042
|
return roomQueryRegistry.decide(topicId, incomingOrigin);
|
|
11245
11043
|
}
|
|
@@ -11405,9 +11203,6 @@ function deferInject(inject) {
|
|
|
11405
11203
|
function takeDeferredInject(topicId) {
|
|
11406
11204
|
return interSessionQueue.dequeueAll(topicId);
|
|
11407
11205
|
}
|
|
11408
|
-
function cancelDeferredInject(topicId, requestId) {
|
|
11409
|
-
return interSessionQueue.remove(topicId, requestId) !== undefined;
|
|
11410
|
-
}
|
|
11411
11206
|
function wsAbortReason(reason) {
|
|
11412
11207
|
return reason === "internal" /* Internal */ ? "superseded" : "stopped";
|
|
11413
11208
|
}
|
|
@@ -11700,8 +11495,8 @@ function settleTopicArchiveJob(topicId, archivePath, success) {
|
|
|
11700
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);
|
|
11701
11496
|
return;
|
|
11702
11497
|
}
|
|
11703
|
-
const
|
|
11704
|
-
setTopicArchiveState(topicId, Math.max(
|
|
11498
|
+
const current = getTopicArchiveState(topicId)?.lastArchivedRowid ?? 0;
|
|
11499
|
+
setTopicArchiveState(topicId, Math.max(current, job.last_rowid), job.archive_path);
|
|
11705
11500
|
db.query("DELETE FROM api_topic_archive_jobs WHERE topic_id = ? AND archive_path = ?").run(topicId, archivePath);
|
|
11706
11501
|
})();
|
|
11707
11502
|
}
|
|
@@ -12384,7 +12179,7 @@ function createAskUserRuntime(host) {
|
|
|
12384
12179
|
if (ask.expired || ask.selectedLabel) {
|
|
12385
12180
|
return { ok: false, error: "This question is no longer awaiting an answer." };
|
|
12386
12181
|
}
|
|
12387
|
-
if (!kind && !ask.choices.some((
|
|
12182
|
+
if (!kind && !ask.choices.some((choice) => choice.label === label)) {
|
|
12388
12183
|
return { ok: false, error: "Invalid choice." };
|
|
12389
12184
|
}
|
|
12390
12185
|
const pending = pendingAsks.get(messageId);
|
|
@@ -12544,8 +12339,8 @@ function createAskUserRuntime(host) {
|
|
|
12544
12339
|
return errorResult(`Error: failed to persist ask_user_question: ${error instanceof Error ? error.message : String(error)}`);
|
|
12545
12340
|
}
|
|
12546
12341
|
let resolveAnswer;
|
|
12547
|
-
const promise = new Promise((
|
|
12548
|
-
resolveAnswer =
|
|
12342
|
+
const promise = new Promise((resolve) => {
|
|
12343
|
+
resolveAnswer = resolve;
|
|
12549
12344
|
});
|
|
12550
12345
|
pendingAsks.set(message.id, {
|
|
12551
12346
|
topicId: ctx.topicId,
|
|
@@ -12747,8 +12542,8 @@ var init_self_schedules = __esm(async () => {
|
|
|
12747
12542
|
});
|
|
12748
12543
|
|
|
12749
12544
|
// ../../packages/core/src/platform/playwright/manager-utils.ts
|
|
12750
|
-
function isLiveOwnedChildProcess(
|
|
12751
|
-
return
|
|
12545
|
+
function isLiveOwnedChildProcess(current, expected) {
|
|
12546
|
+
return current?.process === expected && expected.exitCode === null && expected.signalCode === null && !expected.killed;
|
|
12752
12547
|
}
|
|
12753
12548
|
function matchesSpawnedBrowserHealth(health, expectedSpawnNonce) {
|
|
12754
12549
|
if (!health || typeof health !== "object")
|
|
@@ -12992,10 +12787,10 @@ function findExecutableOnPath(command, environment = process.env) {
|
|
|
12992
12787
|
return null;
|
|
12993
12788
|
}
|
|
12994
12789
|
function resolveHeadedPlaywrightSpawn(command, args, options = {}) {
|
|
12995
|
-
const
|
|
12790
|
+
const platform = options.platform ?? process.platform;
|
|
12996
12791
|
const environment = options.environment ?? process.env;
|
|
12997
12792
|
const hasDisplay = Boolean(environment.DISPLAY?.trim() || environment.WAYLAND_DISPLAY?.trim());
|
|
12998
|
-
if (
|
|
12793
|
+
if (platform !== "linux" || hasDisplay) {
|
|
12999
12794
|
return { command, args: [...args], virtualDisplay: false };
|
|
13000
12795
|
}
|
|
13001
12796
|
const xvfbRun = (options.findExecutable ?? findExecutableOnPath)("xvfb-run", environment);
|
|
@@ -13044,7 +12839,7 @@ async function probeMcpTransport(transport, options = {}) {
|
|
|
13044
12839
|
}
|
|
13045
12840
|
}
|
|
13046
12841
|
async function probePlaywrightMcpTransports(port, capability, fetchImpl = fetch) {
|
|
13047
|
-
const
|
|
12842
|
+
const query = new URLSearchParams({ owner: PROBE_OWNER });
|
|
13048
12843
|
const baseUrl = `http://127.0.0.1:${port}`;
|
|
13049
12844
|
const ownerCapability = browserOwnerCapability(capability, PROBE_OWNER);
|
|
13050
12845
|
const capabilityHeaders = { "X-Browser-Capability": ownerCapability };
|
|
@@ -13053,14 +12848,14 @@ async function probePlaywrightMcpTransports(port, capability, fetchImpl = fetch)
|
|
|
13053
12848
|
headers.set("X-Browser-Capability", ownerCapability);
|
|
13054
12849
|
return fetchImpl(input, { ...init, headers });
|
|
13055
12850
|
};
|
|
13056
|
-
const sseTransport = new SSEClientTransport(new URL(`${baseUrl}/sse?${
|
|
12851
|
+
const sseTransport = new SSEClientTransport(new URL(`${baseUrl}/sse?${query}`), {
|
|
13057
12852
|
fetch: authenticatedFetch,
|
|
13058
12853
|
eventSourceInit: { fetch: authenticatedFetch },
|
|
13059
12854
|
requestInit: { headers: capabilityHeaders }
|
|
13060
12855
|
});
|
|
13061
12856
|
if (!await probeMcpTransport(sseTransport))
|
|
13062
12857
|
return false;
|
|
13063
|
-
const streamableTransport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp?${
|
|
12858
|
+
const streamableTransport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp?${query}`), {
|
|
13064
12859
|
fetch: authenticatedFetch,
|
|
13065
12860
|
requestInit: { headers: capabilityHeaders }
|
|
13066
12861
|
});
|
|
@@ -13190,9 +12985,9 @@ async function createBrowserVaultBroker(userId) {
|
|
|
13190
12985
|
if (typeof request.tool !== "string")
|
|
13191
12986
|
return { id, ok: false, error: "invalid tool" };
|
|
13192
12987
|
const leaseCutoff = Date.now() - LEASE_TTL_MS;
|
|
13193
|
-
for (const [
|
|
12988
|
+
for (const [lease, binding] of leases) {
|
|
13194
12989
|
if (binding.createdAt < leaseCutoff)
|
|
13195
|
-
leases.delete(
|
|
12990
|
+
leases.delete(lease);
|
|
13196
12991
|
}
|
|
13197
12992
|
if (leases.size >= MAX_ACTIVE_LEASES) {
|
|
13198
12993
|
return { id, ok: false, error: "too many active leases" };
|
|
@@ -13753,9 +13548,9 @@ async function spawnPlaywright(instanceKey, ownerId, reservedPort, browserBin =
|
|
|
13753
13548
|
const stderrTail = captureBoundedStderr(proc);
|
|
13754
13549
|
const startup = watchChildStartup(proc, stderrTail);
|
|
13755
13550
|
const reapCrashedBrowser = () => {
|
|
13756
|
-
const
|
|
13757
|
-
managerHost.cleanupBrowserProcessesForDataDir(
|
|
13758
|
-
cleanSingletonFiles(
|
|
13551
|
+
const userDataDir = resolveUserDataDir(instanceKey);
|
|
13552
|
+
managerHost.cleanupBrowserProcessesForDataDir(userDataDir);
|
|
13553
|
+
cleanSingletonFiles(userDataDir);
|
|
13759
13554
|
};
|
|
13760
13555
|
proc.once("error", (err) => {
|
|
13761
13556
|
logger.error({ err, instanceKey, stderr: stderrTail() || undefined }, "Playwright MCP error");
|
|
@@ -13824,8 +13619,8 @@ ${stderrTail()}` : ""));
|
|
|
13824
13619
|
}
|
|
13825
13620
|
async function supportsOwnerCleanup(port, capability) {
|
|
13826
13621
|
try {
|
|
13827
|
-
const
|
|
13828
|
-
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}`, {
|
|
13829
13624
|
method: "DELETE",
|
|
13830
13625
|
headers: {
|
|
13831
13626
|
"X-Browser-Capability": capability
|
|
@@ -13900,8 +13695,8 @@ async function closeBindingOwnerTabs(binding, owner) {
|
|
|
13900
13695
|
if (!instance)
|
|
13901
13696
|
return 0;
|
|
13902
13697
|
const port = instance.port;
|
|
13903
|
-
const
|
|
13904
|
-
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}`, {
|
|
13905
13700
|
method: "DELETE",
|
|
13906
13701
|
headers: {
|
|
13907
13702
|
"X-Browser-Capability": instance.capability
|
|
@@ -14601,7 +14396,7 @@ async function runIdleCompactForTopic(topicId, userId, options = {}) {
|
|
|
14601
14396
|
return "below-threshold";
|
|
14602
14397
|
}
|
|
14603
14398
|
const compact = options.compact ?? (async (id, actorId, reason) => {
|
|
14604
|
-
|
|
14399
|
+
await init_session();
|
|
14605
14400
|
return compactTopicSession(id, actorId, reason, { preemptive: false });
|
|
14606
14401
|
});
|
|
14607
14402
|
try {
|
|
@@ -14801,40 +14596,40 @@ function beginTransientBackgroundSession(userId, session) {
|
|
|
14801
14596
|
update(status, step) {
|
|
14802
14597
|
if (finished)
|
|
14803
14598
|
return;
|
|
14804
|
-
const
|
|
14805
|
-
if (
|
|
14599
|
+
const current = transientSessions.get(record.id);
|
|
14600
|
+
if (current !== record)
|
|
14806
14601
|
return;
|
|
14807
14602
|
const nextStatus = text(status, 160);
|
|
14808
14603
|
if (nextStatus)
|
|
14809
|
-
|
|
14604
|
+
current.status = nextStatus;
|
|
14810
14605
|
const nextStep = text(step);
|
|
14811
|
-
if (nextStep &&
|
|
14812
|
-
|
|
14606
|
+
if (nextStep && current.steps.at(-1) !== nextStep) {
|
|
14607
|
+
current.steps.push(nextStep);
|
|
14813
14608
|
}
|
|
14814
14609
|
},
|
|
14815
14610
|
setOutput(output) {
|
|
14816
14611
|
if (finished)
|
|
14817
14612
|
return;
|
|
14818
|
-
const
|
|
14819
|
-
if (
|
|
14613
|
+
const current = transientSessions.get(record.id);
|
|
14614
|
+
if (current !== record)
|
|
14820
14615
|
return;
|
|
14821
|
-
|
|
14616
|
+
current.output = output;
|
|
14822
14617
|
},
|
|
14823
14618
|
finish(status, step) {
|
|
14824
14619
|
if (finished)
|
|
14825
14620
|
return;
|
|
14826
14621
|
this.update(status ?? record.status, step);
|
|
14827
14622
|
finished = true;
|
|
14828
|
-
const
|
|
14829
|
-
if (
|
|
14623
|
+
const current = transientSessions.get(record.id);
|
|
14624
|
+
if (current !== record)
|
|
14830
14625
|
return;
|
|
14831
|
-
|
|
14832
|
-
|
|
14833
|
-
|
|
14626
|
+
current.active = false;
|
|
14627
|
+
current.expiresAt = Date.now() + Math.max(0, retentionMs);
|
|
14628
|
+
current.expiryTimer = setTimeout(() => {
|
|
14834
14629
|
if (transientSessions.get(record.id) === record)
|
|
14835
14630
|
transientSessions.delete(record.id);
|
|
14836
14631
|
}, Math.max(0, retentionMs));
|
|
14837
|
-
|
|
14632
|
+
current.expiryTimer.unref?.();
|
|
14838
14633
|
}
|
|
14839
14634
|
};
|
|
14840
14635
|
}
|
|
@@ -15093,8 +14888,8 @@ function markRuntimeUserTurnMessagesLogged(topicId, requestId, ownerId, loggedUs
|
|
|
15093
14888
|
return false;
|
|
15094
14889
|
return db.transaction(() => {
|
|
15095
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);
|
|
15096
|
-
const hasLoggedPrefix = (
|
|
15097
|
-
const candidate =
|
|
14891
|
+
const hasLoggedPrefix = (request) => loggedUserMessages.length <= request.userMessages.length && loggedUserMessages.every((message, index) => {
|
|
14892
|
+
const candidate = request.userMessages[index];
|
|
15098
14893
|
return candidate?.prompt === message.prompt && candidate.actorUserId === message.actorUserId && candidate.actorLabel === message.actorLabel && JSON.stringify(candidate.attachments ?? []) === JSON.stringify(message.attachments ?? []);
|
|
15099
14894
|
});
|
|
15100
14895
|
const request = requests.find((candidate) => candidate.requestId === requestId && candidate.claimedBy === ownerId && hasLoggedPrefix(candidate)) ?? requests.find((candidate) => candidate.execution?.supersededRequestIds?.includes(requestId) && hasLoggedPrefix(candidate));
|
|
@@ -15112,60 +14907,6 @@ function markRuntimeUserTurnMessagesLogged(topicId, requestId, ownerId, loggedUs
|
|
|
15112
14907
|
return result.changes === 1;
|
|
15113
14908
|
}).immediate();
|
|
15114
14909
|
}
|
|
15115
|
-
function claimNextRuntimeUserTurnRequest(ownerId, now = Date.now()) {
|
|
15116
|
-
return db.transaction(() => {
|
|
15117
|
-
const row = db.query(`SELECT r.*
|
|
15118
|
-
FROM runtime_user_turn_requests r
|
|
15119
|
-
LEFT JOIN runtime_turn_leases l ON l.topic_id = r.topic_id
|
|
15120
|
-
LEFT JOIN runtime_topic_state s ON s.topic_id = r.topic_id
|
|
15121
|
-
WHERE (l.topic_id IS NULL OR l.heartbeat_at < ?)
|
|
15122
|
-
AND (s.topic_id IS NULL OR s.maintenance = 0 OR s.heartbeat_at < ?)
|
|
15123
|
-
AND r.topic_epoch = COALESCE(s.epoch, 0)
|
|
15124
|
-
AND NOT EXISTS (
|
|
15125
|
-
SELECT 1
|
|
15126
|
-
FROM runtime_user_turn_requests active
|
|
15127
|
-
WHERE active.topic_id = r.topic_id
|
|
15128
|
-
AND active.request_id <> r.request_id
|
|
15129
|
-
AND active.claimed_at IS NOT NULL
|
|
15130
|
-
AND active.claimed_at >= ?
|
|
15131
|
-
)
|
|
15132
|
-
AND (
|
|
15133
|
-
(r.status = 'pending' AND (r.claimed_at IS NULL OR r.claimed_at < ?))
|
|
15134
|
-
OR (r.status = 'running' AND (r.claimed_at IS NULL OR r.claimed_at < ?))
|
|
15135
|
-
)
|
|
15136
|
-
ORDER BY r.created_at ASC, r.rowid ASC
|
|
15137
|
-
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);
|
|
15138
|
-
if (!row)
|
|
15139
|
-
return null;
|
|
15140
|
-
const updated = db.query(`UPDATE runtime_user_turn_requests
|
|
15141
|
-
SET claimed_by = ?, claimed_at = ?
|
|
15142
|
-
WHERE request_id = ? AND topic_id = ?
|
|
15143
|
-
AND (
|
|
15144
|
-
(status = 'pending' AND (claimed_at IS NULL OR claimed_at < ?))
|
|
15145
|
-
OR (status = 'running' AND (claimed_at IS NULL OR claimed_at < ?))
|
|
15146
|
-
)`).run(ownerId, now, row.request_id, row.topic_id, now - REQUEST_CLAIM_STALE_MS, now - REQUEST_CLAIM_STALE_MS);
|
|
15147
|
-
if (Number(updated.changes ?? 0) === 0)
|
|
15148
|
-
return null;
|
|
15149
|
-
return rowToRequest({ ...row, claimed_by: ownerId, claimed_at: now });
|
|
15150
|
-
}).immediate();
|
|
15151
|
-
}
|
|
15152
|
-
function markRuntimeUserTurnRunning(topicId, requestId, ownerId, queryId) {
|
|
15153
|
-
const result = db.query(`UPDATE runtime_user_turn_requests
|
|
15154
|
-
SET status = 'running', running_query_id = ?, claimed_at = ?
|
|
15155
|
-
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(queryId, Date.now(), topicId, requestId, ownerId);
|
|
15156
|
-
return Number(result.changes ?? 0) > 0;
|
|
15157
|
-
}
|
|
15158
|
-
function releaseRuntimeUserTurnClaim(topicId, requestId, ownerId) {
|
|
15159
|
-
const result = db.query(`UPDATE runtime_user_turn_requests
|
|
15160
|
-
SET status = 'pending', claimed_by = NULL, claimed_at = NULL, running_query_id = NULL
|
|
15161
|
-
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(topicId, requestId, ownerId);
|
|
15162
|
-
return Number(result.changes ?? 0) > 0;
|
|
15163
|
-
}
|
|
15164
|
-
function completeRuntimeUserTurnRequest(topicId, requestId, ownerId) {
|
|
15165
|
-
const result = db.query(`DELETE FROM runtime_user_turn_requests
|
|
15166
|
-
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(topicId, requestId, ownerId);
|
|
15167
|
-
return Number(result.changes ?? 0) > 0;
|
|
15168
|
-
}
|
|
15169
14910
|
function cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, epoch) {
|
|
15170
14911
|
const rows = db.query("SELECT request_id FROM runtime_user_turn_requests WHERE topic_id = ? AND topic_epoch < ?").all(topicId, epoch);
|
|
15171
14912
|
db.query("DELETE FROM runtime_user_turn_requests WHERE topic_id = ? AND topic_epoch < ?").run(topicId, epoch);
|
|
@@ -15203,36 +14944,10 @@ var init_runtime_turn_requests = __esm(async () => {
|
|
|
15203
14944
|
});
|
|
15204
14945
|
|
|
15205
14946
|
// ../../packages/core/src/topics/session.ts
|
|
15206
|
-
var exports_session = {};
|
|
15207
|
-
__export(exports_session, {
|
|
15208
|
-
splitCompactionPairs: () => splitCompactionPairs,
|
|
15209
|
-
shouldUseCompactionLog: () => shouldUseCompactionLog,
|
|
15210
|
-
shouldCompactForkEntries: () => shouldCompactForkEntries,
|
|
15211
|
-
restartTopicSession: () => restartTopicSession,
|
|
15212
|
-
createCompactedRolloutEntries: () => createCompactedRolloutEntries,
|
|
15213
|
-
compactTopicSession: () => compactTopicSession,
|
|
15214
|
-
COMPACTION_RETAINED_TAIL_TOKENS: () => COMPACTION_RETAINED_TAIL_TOKENS,
|
|
15215
|
-
AUTO_FORK_COMPACTION_TOKENS: () => AUTO_FORK_COMPACTION_TOKENS
|
|
15216
|
-
});
|
|
15217
14947
|
import { randomUUID as randomUUID12 } from "crypto";
|
|
15218
14948
|
import { mkdtempSync as mkdtempSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "fs";
|
|
15219
14949
|
import { tmpdir as tmpdir4 } from "os";
|
|
15220
14950
|
import { join as join23 } from "path";
|
|
15221
|
-
async function waitForMemoryArchive(settled, timeoutMs) {
|
|
15222
|
-
let timer;
|
|
15223
|
-
try {
|
|
15224
|
-
return await Promise.race([
|
|
15225
|
-
settled.then(() => true),
|
|
15226
|
-
new Promise((resolve17) => {
|
|
15227
|
-
timer = setTimeout(() => resolve17(false), timeoutMs);
|
|
15228
|
-
timer.unref?.();
|
|
15229
|
-
})
|
|
15230
|
-
]);
|
|
15231
|
-
} finally {
|
|
15232
|
-
if (timer)
|
|
15233
|
-
clearTimeout(timer);
|
|
15234
|
-
}
|
|
15235
|
-
}
|
|
15236
14951
|
async function fenceTopicWork(topicId, maintenance) {
|
|
15237
14952
|
for (const queryId of cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, maintenance.epoch)) {
|
|
15238
14953
|
WsHub.get().broadcastAborted(topicId, queryId, "stopped");
|
|
@@ -15257,97 +14972,6 @@ function hasTopicWorkInFlight(topicId) {
|
|
|
15257
14972
|
function topicIsQuiescedForNonPreemptiveWork(topicId) {
|
|
15258
14973
|
return !hasTopicWorkInFlight(topicId);
|
|
15259
14974
|
}
|
|
15260
|
-
async function restartTopicSession(topicId, userId, reason = "topic-session-restart", options = {}) {
|
|
15261
|
-
const topic = getTopic(topicId);
|
|
15262
|
-
if (!topic)
|
|
15263
|
-
return { text: "Topic not found.", isError: true };
|
|
15264
|
-
if (isLegacySharedGeneral(topic.id)) {
|
|
15265
|
-
return { text: "The legacy shared General session cannot be reset.", isError: true };
|
|
15266
|
-
}
|
|
15267
|
-
const owner = topic.participants.some((participant) => participant.userId === userId && participant.role === "owner");
|
|
15268
|
-
if (!owner)
|
|
15269
|
-
return { text: "Only the topic owner can reset the session.", isError: true };
|
|
15270
|
-
const maintenance = beginRuntimeTopicMaintenance(topicId);
|
|
15271
|
-
if (!maintenance)
|
|
15272
|
-
return { text: "Topic maintenance is already in progress.", isError: true };
|
|
15273
|
-
try {
|
|
15274
|
-
const fenceError = await fenceTopicWork(topicId, maintenance);
|
|
15275
|
-
if (fenceError)
|
|
15276
|
-
return { text: fenceError, isError: true };
|
|
15277
|
-
cancelIdleArchiveForTopic(topicId);
|
|
15278
|
-
cancelIdleCompactForTopic(topicId);
|
|
15279
|
-
const rawArchivePaths = [];
|
|
15280
|
-
try {
|
|
15281
|
-
for (const participantUserId of new Set([
|
|
15282
|
-
userId,
|
|
15283
|
-
...topic.participants.map((participant) => participant.userId)
|
|
15284
|
-
])) {
|
|
15285
|
-
const archived = archiveConversationEvents(topicId, topic.title, participantUserId, {
|
|
15286
|
-
reason: "reset"
|
|
15287
|
-
});
|
|
15288
|
-
if (archived)
|
|
15289
|
-
rawArchivePaths.push(archived.path);
|
|
15290
|
-
}
|
|
15291
|
-
} catch (error) {
|
|
15292
|
-
return {
|
|
15293
|
-
text: `Session reset could not archive the raw conversation: ${error instanceof Error ? error.message : String(error)}`,
|
|
15294
|
-
isError: true
|
|
15295
|
-
};
|
|
15296
|
-
}
|
|
15297
|
-
let settleMemoryArchive;
|
|
15298
|
-
const memoryArchiveSettled = new Promise((resolve17) => {
|
|
15299
|
-
settleMemoryArchive = resolve17;
|
|
15300
|
-
});
|
|
15301
|
-
const archiveStatus = (options.archiveMemory ?? archiveActiveTopicForMemory)(topicId, options.memoryUserId ?? userId, {
|
|
15302
|
-
reason: "reset",
|
|
15303
|
-
minMessages: 1,
|
|
15304
|
-
minExchanges: MIN_MEMORY_ARCHIVE_EXCHANGES,
|
|
15305
|
-
allowMentionOnly: true,
|
|
15306
|
-
skipBusyCheck: true,
|
|
15307
|
-
rawArchivePaths,
|
|
15308
|
-
onSettled: () => settleMemoryArchive?.()
|
|
15309
|
-
});
|
|
15310
|
-
if (archiveStatus === "archived") {
|
|
15311
|
-
const archiveFinished = await waitForMemoryArchive(memoryArchiveSettled, options.memoryArchiveWaitMs ?? RESET_MEMORY_ARCHIVE_WAIT_MS);
|
|
15312
|
-
if (!archiveFinished) {
|
|
15313
|
-
return {
|
|
15314
|
-
text: "Memory archiving did not finish in time. The session was not reset.",
|
|
15315
|
-
isError: true
|
|
15316
|
-
};
|
|
15317
|
-
}
|
|
15318
|
-
}
|
|
15319
|
-
if (!maintenance.isOwned()) {
|
|
15320
|
-
return { text: "Topic maintenance ownership was lost. Try again.", isError: true };
|
|
15321
|
-
}
|
|
15322
|
-
const sessionId = getTopicSessionId(topicId);
|
|
15323
|
-
const purgeLogs = options.purgeLogs ?? purgeTopicLogs;
|
|
15324
|
-
const participantUserIds = Array.from(new Set([userId, ...topic.participants.map((participant) => participant.userId)]));
|
|
15325
|
-
for (const [index, participantUserId] of participantUserIds.entries()) {
|
|
15326
|
-
let purged = false;
|
|
15327
|
-
try {
|
|
15328
|
-
purged = await purgeLogs({
|
|
15329
|
-
userId: participantUserId,
|
|
15330
|
-
topicName: topic.title,
|
|
15331
|
-
cwd: resolveTopicWorkspaceDir(topicId),
|
|
15332
|
-
extraSessions: index === 0 && topic.agent && sessionId ? [{ agent: topic.agent, sessionId }] : []
|
|
15333
|
-
});
|
|
15334
|
-
} catch (error) {
|
|
15335
|
-
logger.warn({ err: error, topicId, userId: participantUserId }, "restartTopicSession: participant context cleanup failed");
|
|
15336
|
-
}
|
|
15337
|
-
if (!purged) {
|
|
15338
|
-
return {
|
|
15339
|
-
text: "Session reset could not remove all provider context. The current session was kept.",
|
|
15340
|
-
isError: true
|
|
15341
|
-
};
|
|
15342
|
-
}
|
|
15343
|
-
}
|
|
15344
|
-
clearTopicSessionId(topicId, reason);
|
|
15345
|
-
clearQueryUsageAlert(userId, topicId);
|
|
15346
|
-
return { text: `Session reset for "${topic.title}". The next message starts fresh.` };
|
|
15347
|
-
} finally {
|
|
15348
|
-
maintenance.finish();
|
|
15349
|
-
}
|
|
15350
|
-
}
|
|
15351
14975
|
function previousCompactedSummary(entries) {
|
|
15352
14976
|
for (let index = entries.length - 2;index >= 0; index -= 1) {
|
|
15353
14977
|
const request = entries[index]?.event;
|
|
@@ -15362,9 +14986,9 @@ The assistant response is the authoritative summary of all earlier context.` &&
|
|
|
15362
14986
|
function withoutCompactionSentinels(entries) {
|
|
15363
14987
|
const filtered = [];
|
|
15364
14988
|
for (let index = 0;index < entries.length; index++) {
|
|
15365
|
-
const
|
|
14989
|
+
const current = entries[index]?.event;
|
|
15366
14990
|
const next = entries[index + 1]?.event;
|
|
15367
|
-
if (
|
|
14991
|
+
if (current?.type === "user_message" && current.synthetic === "compaction" && next?.type === "result") {
|
|
15368
14992
|
index += 1;
|
|
15369
14993
|
continue;
|
|
15370
14994
|
}
|
|
@@ -15414,18 +15038,18 @@ function retainedPairEntries(agent, pairs) {
|
|
|
15414
15038
|
}
|
|
15415
15039
|
return entries;
|
|
15416
15040
|
}
|
|
15417
|
-
function fitCompactionChunk(
|
|
15418
|
-
if (
|
|
15419
|
-
return
|
|
15041
|
+
function fitCompactionChunk(text, limit) {
|
|
15042
|
+
if (text.length <= limit)
|
|
15043
|
+
return text;
|
|
15420
15044
|
const marker = `
|
|
15421
15045
|
[\u2026]
|
|
15422
15046
|
`;
|
|
15423
15047
|
if (limit <= marker.length)
|
|
15424
|
-
return
|
|
15048
|
+
return text.slice(0, limit);
|
|
15425
15049
|
const available = limit - marker.length;
|
|
15426
15050
|
const headChars = Math.ceil(available * 0.6);
|
|
15427
15051
|
const tailChars = available - headChars;
|
|
15428
|
-
return `${
|
|
15052
|
+
return `${text.slice(0, headChars)}${marker}${text.slice(-tailChars)}`;
|
|
15429
15053
|
}
|
|
15430
15054
|
function buildCompactionSource(topicId, userId, entries, visibleMessages, providerPairs) {
|
|
15431
15055
|
const sections = [];
|
|
@@ -15826,9 +15450,9 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15826
15450
|
const compactionExecution = resolveCompactionExecution(agent, registry);
|
|
15827
15451
|
const cwd = resolveTopicWorkspaceDir(topicId);
|
|
15828
15452
|
const oldEntries = readConversation(userId, topic.title);
|
|
15829
|
-
let
|
|
15453
|
+
let compactEntries;
|
|
15830
15454
|
try {
|
|
15831
|
-
|
|
15455
|
+
compactEntries = await createCompactedRolloutEntries({
|
|
15832
15456
|
topicId,
|
|
15833
15457
|
topicTitle: topic.title,
|
|
15834
15458
|
userId,
|
|
@@ -15854,7 +15478,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15854
15478
|
try {
|
|
15855
15479
|
replacement = getRegistryOperations(agent).writeRollout({
|
|
15856
15480
|
cwd,
|
|
15857
|
-
entries:
|
|
15481
|
+
entries: compactEntries,
|
|
15858
15482
|
model,
|
|
15859
15483
|
...effort ? { effort } : {}
|
|
15860
15484
|
});
|
|
@@ -15884,7 +15508,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15884
15508
|
}
|
|
15885
15509
|
try {
|
|
15886
15510
|
replaceConversationStrict(userId, topic.title, [
|
|
15887
|
-
...
|
|
15511
|
+
...compactEntries,
|
|
15888
15512
|
...priorSessionEntries,
|
|
15889
15513
|
replacementSessionEntry
|
|
15890
15514
|
]);
|
|
@@ -15921,7 +15545,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15921
15545
|
} else {
|
|
15922
15546
|
try {
|
|
15923
15547
|
replaceConversationStrict(userId, topic.title, [
|
|
15924
|
-
...
|
|
15548
|
+
...compactEntries,
|
|
15925
15549
|
replacementSessionEntry
|
|
15926
15550
|
]);
|
|
15927
15551
|
} catch (manifestError) {
|
|
@@ -15975,45 +15599,11 @@ var init_session = __esm(async () => {
|
|
|
15975
15599
|
});
|
|
15976
15600
|
|
|
15977
15601
|
// ../../packages/core/src/topics/derive.ts
|
|
15978
|
-
var exports_derive = {};
|
|
15979
|
-
__export(exports_derive, {
|
|
15980
|
-
updateTopic: () => updateTopic,
|
|
15981
|
-
isParticipant: () => isParticipant,
|
|
15982
|
-
getVisibleTopics: () => getVisibleTopics,
|
|
15983
|
-
getTopics: () => getTopics,
|
|
15984
|
-
createDerivedTopic: () => createDerivedTopic,
|
|
15985
|
-
TopicTitleConflictError: () => TopicTitleConflictError,
|
|
15986
|
-
TopicForkCompactionError: () => TopicForkCompactionError,
|
|
15987
|
-
TopicDeriveBusyError: () => TopicDeriveBusyError
|
|
15988
|
-
});
|
|
15989
15602
|
import { createHash as createHash9, randomUUID as randomUUID13 } from "crypto";
|
|
15990
15603
|
import { mkdirSync as mkdirSync14, rmSync as rmSync5, unlinkSync as unlinkSync13 } from "fs";
|
|
15991
15604
|
function getTopics(opts = {}) {
|
|
15992
15605
|
return listTopics(opts).filter((topic) => !isLegacySharedGeneral(topic.id));
|
|
15993
15606
|
}
|
|
15994
|
-
function getVisibleTopics(opts = {}) {
|
|
15995
|
-
return getTopics(opts).filter(isTopicVisible).map((topic) => {
|
|
15996
|
-
if (!topic.agent)
|
|
15997
|
-
return topic;
|
|
15998
|
-
const registry = getRegistry(topic.agent);
|
|
15999
|
-
const config = getApiTopicConfig(topic.id);
|
|
16000
|
-
const requestedEffort = config?.effort ?? topic.defaultEffort;
|
|
16001
|
-
return {
|
|
16002
|
-
...topic,
|
|
16003
|
-
effectiveModel: resolveModelForAgent(topic.agent, config?.model ?? topic.defaultModel, registry),
|
|
16004
|
-
effectiveEffort: requestedEffort && registry.validateEffort(requestedEffort) ? requestedEffort : registry.defaultEffort
|
|
16005
|
-
};
|
|
16006
|
-
});
|
|
16007
|
-
}
|
|
16008
|
-
function updateTopic(topicId, patch) {
|
|
16009
|
-
const topic = getTopic(topicId);
|
|
16010
|
-
if (!topic)
|
|
16011
|
-
return false;
|
|
16012
|
-
Object.assign(topic, patch);
|
|
16013
|
-
upsertTopic(topic);
|
|
16014
|
-
WsHub.get().broadcastTopicUpdated(topicId);
|
|
16015
|
-
return true;
|
|
16016
|
-
}
|
|
16017
15607
|
function isParticipant(topic, userId) {
|
|
16018
15608
|
return topic.participants.some((p) => p.userId === userId);
|
|
16019
15609
|
}
|
|
@@ -16429,9 +16019,9 @@ function subagentLineageTopicIds(currentTopicId) {
|
|
|
16429
16019
|
const children = new Set;
|
|
16430
16020
|
if (!currentTopicId)
|
|
16431
16021
|
return { reachable, children };
|
|
16432
|
-
const
|
|
16433
|
-
if (
|
|
16434
|
-
reachable.add(
|
|
16022
|
+
const current = getTopic(currentTopicId);
|
|
16023
|
+
if (current?.isSubagent && current.parentTopicId) {
|
|
16024
|
+
reachable.add(current.parentTopicId);
|
|
16435
16025
|
for (const id of listSubagentTellTargetIds(currentTopicId))
|
|
16436
16026
|
reachable.add(id);
|
|
16437
16027
|
}
|
|
@@ -16557,9 +16147,9 @@ function cleanupSessionInboxFiles(userId, topicId, legacyTopicTitle) {
|
|
|
16557
16147
|
try {
|
|
16558
16148
|
unlinkSync15(path);
|
|
16559
16149
|
deleted++;
|
|
16560
|
-
} catch (
|
|
16561
|
-
if (
|
|
16562
|
-
logger.warn({ err
|
|
16150
|
+
} catch (err) {
|
|
16151
|
+
if (err?.code !== "ENOENT") {
|
|
16152
|
+
logger.warn({ err, path, topicId, userId }, "topic cleanup: inbox unlink failed");
|
|
16563
16153
|
}
|
|
16564
16154
|
}
|
|
16565
16155
|
}
|
|
@@ -16684,9 +16274,9 @@ function hubHeaders(bearer) {
|
|
|
16684
16274
|
};
|
|
16685
16275
|
}
|
|
16686
16276
|
function errorText(status, body, fallback) {
|
|
16687
|
-
const
|
|
16688
|
-
if (typeof
|
|
16689
|
-
return
|
|
16277
|
+
const text = body?.error;
|
|
16278
|
+
if (typeof text === "string" && text.trim())
|
|
16279
|
+
return text.trim();
|
|
16690
16280
|
return `${fallback} (hub answered ${status})`;
|
|
16691
16281
|
}
|
|
16692
16282
|
function describeFailure(status, body) {
|
|
@@ -16782,19 +16372,6 @@ var init_actor_policy = __esm(async () => {
|
|
|
16782
16372
|
await init_actor_topic_reach();
|
|
16783
16373
|
});
|
|
16784
16374
|
// ../../packages/core/src/storage/session-asks.ts
|
|
16785
|
-
var exports_session_asks = {};
|
|
16786
|
-
__export(exports_session_asks, {
|
|
16787
|
-
releasePendingAsk: () => releasePendingAsk,
|
|
16788
|
-
markPendingAskState: () => markPendingAskState,
|
|
16789
|
-
markPendingAskSources: () => markPendingAskSources,
|
|
16790
|
-
listPendingAsksForCaller: () => listPendingAsksForCaller,
|
|
16791
|
-
describePendingAskState: () => describePendingAskState,
|
|
16792
|
-
deletePendingAsksForTopic: () => deletePendingAsksForTopic,
|
|
16793
|
-
createPendingAsk: () => createPendingAsk,
|
|
16794
|
-
clearPendingAskSources: () => clearPendingAskSources,
|
|
16795
|
-
clearPendingAsk: () => clearPendingAsk,
|
|
16796
|
-
PENDING_ASK_TTL_MS: () => PENDING_ASK_TTL_MS
|
|
16797
|
-
});
|
|
16798
16375
|
import { createHash as createHash10 } from "crypto";
|
|
16799
16376
|
import {
|
|
16800
16377
|
closeSync as closeSync2,
|
|
@@ -16816,8 +16393,8 @@ function encodeAskKey(key) {
|
|
|
16816
16393
|
return JSON.stringify([key.from, key.to]);
|
|
16817
16394
|
}
|
|
16818
16395
|
function pendingAskPath(key) {
|
|
16819
|
-
const
|
|
16820
|
-
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`);
|
|
16821
16398
|
}
|
|
16822
16399
|
function v2PendingAskPath(key) {
|
|
16823
16400
|
const encoded = Buffer.from(encodeAskKey(key), "utf8").toString("base64url");
|
|
@@ -16843,10 +16420,10 @@ function parsePendingAskFilename(fileName) {
|
|
|
16843
16420
|
}
|
|
16844
16421
|
} catch {}
|
|
16845
16422
|
}
|
|
16846
|
-
const
|
|
16847
|
-
if (
|
|
16423
|
+
const sep = raw.indexOf("___");
|
|
16424
|
+
if (sep < 0)
|
|
16848
16425
|
return null;
|
|
16849
|
-
return { from: raw.slice(0,
|
|
16426
|
+
return { from: raw.slice(0, sep), to: raw.slice(sep + 3) };
|
|
16850
16427
|
}
|
|
16851
16428
|
function readPendingAskFile(path, fallback) {
|
|
16852
16429
|
try {
|
|
@@ -16889,16 +16466,6 @@ function readPendingAskFile(path, fallback) {
|
|
|
16889
16466
|
return null;
|
|
16890
16467
|
}
|
|
16891
16468
|
}
|
|
16892
|
-
function isStale(record, path) {
|
|
16893
|
-
const ts = record ? Date.parse(record.updatedAt || record.createdAt) : Number.NaN;
|
|
16894
|
-
if (Number.isFinite(ts))
|
|
16895
|
-
return Date.now() - ts > PENDING_ASK_TTL_MS;
|
|
16896
|
-
try {
|
|
16897
|
-
return Date.now() - statSync8(path).mtimeMs > PENDING_ASK_TTL_MS;
|
|
16898
|
-
} catch {
|
|
16899
|
-
return false;
|
|
16900
|
-
}
|
|
16901
|
-
}
|
|
16902
16469
|
function writePendingAsk(record) {
|
|
16903
16470
|
const path = pendingAskPath(record);
|
|
16904
16471
|
mkdirSync16(pendingAskDir(record.userId), { recursive: true });
|
|
@@ -16924,10 +16491,10 @@ function writePendingAskIfAbsent(record) {
|
|
|
16924
16491
|
}
|
|
16925
16492
|
}
|
|
16926
16493
|
function readPendingAsk(key) {
|
|
16927
|
-
const
|
|
16928
|
-
const canonical = readPendingAskFile(
|
|
16494
|
+
const canonicalPath = pendingAskPath(key);
|
|
16495
|
+
const canonical = readPendingAskFile(canonicalPath, key);
|
|
16929
16496
|
if (canonical && canonical.from === key.from && canonical.to === key.to) {
|
|
16930
|
-
return { path:
|
|
16497
|
+
return { path: canonicalPath, record: canonical };
|
|
16931
16498
|
}
|
|
16932
16499
|
for (const compatibilityPath of [v2PendingAskPath(key), legacyPendingAskPath(key)]) {
|
|
16933
16500
|
if (!compatibilityPath)
|
|
@@ -16936,67 +16503,17 @@ function readPendingAsk(key) {
|
|
|
16936
16503
|
if (!legacy || legacy.from !== key.from || legacy.to !== key.to)
|
|
16937
16504
|
continue;
|
|
16938
16505
|
const migrated = writePendingAskIfAbsent(legacy);
|
|
16939
|
-
const next = migrated ? legacy : readPendingAskFile(
|
|
16506
|
+
const next = migrated ? legacy : readPendingAskFile(canonicalPath, key);
|
|
16940
16507
|
if (next && next.from === key.from && next.to === key.to) {
|
|
16941
16508
|
try {
|
|
16942
16509
|
unlinkSync16(compatibilityPath);
|
|
16943
16510
|
} catch {}
|
|
16944
|
-
return { path:
|
|
16511
|
+
return { path: canonicalPath, record: next };
|
|
16945
16512
|
}
|
|
16946
16513
|
return { path: compatibilityPath, record: legacy };
|
|
16947
16514
|
}
|
|
16948
16515
|
return null;
|
|
16949
16516
|
}
|
|
16950
|
-
function createPendingAsk(args) {
|
|
16951
|
-
const migrated = readPendingAsk(args);
|
|
16952
|
-
if (migrated && !isStale(migrated.record, migrated.path)) {
|
|
16953
|
-
return { ok: false, existing: migrated.record, stale: false };
|
|
16954
|
-
}
|
|
16955
|
-
if (migrated) {
|
|
16956
|
-
try {
|
|
16957
|
-
unlinkSync16(migrated.path);
|
|
16958
|
-
} catch {
|
|
16959
|
-
return { ok: false, existing: migrated.record, stale: true };
|
|
16960
|
-
}
|
|
16961
|
-
}
|
|
16962
|
-
const path = pendingAskPath(args);
|
|
16963
|
-
const now = new Date().toISOString();
|
|
16964
|
-
const record = {
|
|
16965
|
-
userId: args.userId,
|
|
16966
|
-
from: args.from,
|
|
16967
|
-
to: args.to,
|
|
16968
|
-
requestId: args.requestId,
|
|
16969
|
-
contextId: args.contextId,
|
|
16970
|
-
state: "requested",
|
|
16971
|
-
createdAt: now,
|
|
16972
|
-
updatedAt: now
|
|
16973
|
-
};
|
|
16974
|
-
mkdirSync16(pendingAskDir(args.userId), { recursive: true });
|
|
16975
|
-
for (let attempt = 0;attempt < 2; attempt++) {
|
|
16976
|
-
let fd = null;
|
|
16977
|
-
try {
|
|
16978
|
-
fd = openSync2(path, "wx");
|
|
16979
|
-
writeFileSync14(fd, `${JSON.stringify(record)}
|
|
16980
|
-
`);
|
|
16981
|
-
return { ok: true, record };
|
|
16982
|
-
} catch (err2) {
|
|
16983
|
-
if (err2.code !== "EEXIST")
|
|
16984
|
-
throw err2;
|
|
16985
|
-
const existing = readPendingAskFile(path, args);
|
|
16986
|
-
if (!isStale(existing, path))
|
|
16987
|
-
return { ok: false, existing, stale: false };
|
|
16988
|
-
try {
|
|
16989
|
-
unlinkSync16(path);
|
|
16990
|
-
} catch {
|
|
16991
|
-
return { ok: false, existing, stale: true };
|
|
16992
|
-
}
|
|
16993
|
-
} finally {
|
|
16994
|
-
if (fd !== null)
|
|
16995
|
-
closeSync2(fd);
|
|
16996
|
-
}
|
|
16997
|
-
}
|
|
16998
|
-
return { ok: false, existing: readPendingAskFile(path, args), stale: true };
|
|
16999
|
-
}
|
|
17000
16517
|
function markPendingAskState(args) {
|
|
17001
16518
|
const pending = readPendingAsk(args);
|
|
17002
16519
|
if (!pending)
|
|
@@ -17030,83 +16547,6 @@ function clearPendingAsk(args) {
|
|
|
17030
16547
|
return false;
|
|
17031
16548
|
}
|
|
17032
16549
|
}
|
|
17033
|
-
function releasePendingAsk(args) {
|
|
17034
|
-
if (clearPendingAsk(args))
|
|
17035
|
-
return true;
|
|
17036
|
-
const still = readPendingAsk(args);
|
|
17037
|
-
return !still || still.record.requestId !== args.requestId;
|
|
17038
|
-
}
|
|
17039
|
-
function markPendingAskSources(args) {
|
|
17040
|
-
for (const source of args.sources ?? []) {
|
|
17041
|
-
if (!source.from)
|
|
17042
|
-
continue;
|
|
17043
|
-
markPendingAskState({
|
|
17044
|
-
userId: args.userId,
|
|
17045
|
-
from: args.callerTopic,
|
|
17046
|
-
to: source.from,
|
|
17047
|
-
requestId: source.requestId,
|
|
17048
|
-
state: args.state
|
|
17049
|
-
});
|
|
17050
|
-
}
|
|
17051
|
-
}
|
|
17052
|
-
function clearPendingAskSources(args) {
|
|
17053
|
-
for (const source of args.sources ?? []) {
|
|
17054
|
-
if (!source.from)
|
|
17055
|
-
continue;
|
|
17056
|
-
clearPendingAsk({
|
|
17057
|
-
userId: args.userId,
|
|
17058
|
-
from: args.callerTopic,
|
|
17059
|
-
to: source.from,
|
|
17060
|
-
requestId: source.requestId
|
|
17061
|
-
});
|
|
17062
|
-
}
|
|
17063
|
-
}
|
|
17064
|
-
function listPendingAsksForCaller(args) {
|
|
17065
|
-
const dir = pendingAskDir(args.userId);
|
|
17066
|
-
let files;
|
|
17067
|
-
try {
|
|
17068
|
-
files = readdirSync4(dir);
|
|
17069
|
-
} catch {
|
|
17070
|
-
return [];
|
|
17071
|
-
}
|
|
17072
|
-
const records = new Map;
|
|
17073
|
-
for (const fileName of files) {
|
|
17074
|
-
const isV3 = fileName.startsWith(ASK_FILENAME_PREFIX);
|
|
17075
|
-
const parsed = isV3 ? { from: args.from, to: "" } : parsePendingAskFilename(fileName);
|
|
17076
|
-
if (!parsed)
|
|
17077
|
-
continue;
|
|
17078
|
-
const path = join28(dir, fileName);
|
|
17079
|
-
const record = readPendingAskFile(path, {
|
|
17080
|
-
userId: args.userId,
|
|
17081
|
-
from: parsed.from,
|
|
17082
|
-
to: parsed.to
|
|
17083
|
-
});
|
|
17084
|
-
if (!record || record.from !== args.from)
|
|
17085
|
-
continue;
|
|
17086
|
-
if (isStale(record, path)) {
|
|
17087
|
-
try {
|
|
17088
|
-
unlinkSync16(path);
|
|
17089
|
-
} catch {}
|
|
17090
|
-
continue;
|
|
17091
|
-
}
|
|
17092
|
-
const canonical = readPendingAsk(record);
|
|
17093
|
-
if (!canonical || canonical.record.from !== args.from)
|
|
17094
|
-
continue;
|
|
17095
|
-
if (path !== canonical.path) {
|
|
17096
|
-
try {
|
|
17097
|
-
unlinkSync16(path);
|
|
17098
|
-
} catch {}
|
|
17099
|
-
}
|
|
17100
|
-
if (isStale(canonical.record, canonical.path)) {
|
|
17101
|
-
try {
|
|
17102
|
-
unlinkSync16(canonical.path);
|
|
17103
|
-
} catch {}
|
|
17104
|
-
continue;
|
|
17105
|
-
}
|
|
17106
|
-
records.set(encodeAskKey(canonical.record), canonical.record);
|
|
17107
|
-
}
|
|
17108
|
-
return [...records.values()];
|
|
17109
|
-
}
|
|
17110
16550
|
function deletePendingAsksForTopic(args) {
|
|
17111
16551
|
const dir = pendingAskDir(args.userId);
|
|
17112
16552
|
let files;
|
|
@@ -17135,18 +16575,6 @@ function deletePendingAsksForTopic(args) {
|
|
|
17135
16575
|
}
|
|
17136
16576
|
return deleted;
|
|
17137
16577
|
}
|
|
17138
|
-
function describePendingAskState(state) {
|
|
17139
|
-
switch (state) {
|
|
17140
|
-
case "requested":
|
|
17141
|
-
return "\uB300\uC0C1 \uC138\uC158 \uCC98\uB9AC \uC911";
|
|
17142
|
-
case "reply_ready":
|
|
17143
|
-
return "\uC751\uB2F5 \uC0DD\uC131 \uC644\uB8CC, \uC774 \uC138\uC158 \uC8FC\uC785 \uC900\uBE44 \uC911";
|
|
17144
|
-
case "queued_for_caller":
|
|
17145
|
-
return "\uC751\uB2F5 \uC0DD\uC131 \uC644\uB8CC, \uC774 \uC138\uC158 \uC2E4\uD589 \uC885\uB8CC \uD6C4 \uC8FC\uC785 \uB300\uAE30 \uC911";
|
|
17146
|
-
case "injecting_to_caller":
|
|
17147
|
-
return "\uC751\uB2F5\uC744 \uC774 \uC138\uC158\uC5D0 \uC8FC\uC785 \uC911";
|
|
17148
|
-
}
|
|
17149
|
-
}
|
|
17150
16578
|
var PENDING_ASK_TTL_MS, ASK_FILENAME_PREFIX = "v3-", V2_ASK_FILENAME_PREFIX = "v2-";
|
|
17151
16579
|
var init_session_asks = __esm(async () => {
|
|
17152
16580
|
await init_storage_host();
|
|
@@ -17248,10 +16676,10 @@ function deferRemoteSessionReplyOutbox(args) {
|
|
|
17248
16676
|
if (!row)
|
|
17249
16677
|
return;
|
|
17250
16678
|
const attempts = Number(row.attempts) + 1;
|
|
17251
|
-
const
|
|
16679
|
+
const delay = args.retryMs ?? remoteSessionRetryDelayMs(attempts, args.random);
|
|
17252
16680
|
db.query(`UPDATE remote_session_reply_outbox
|
|
17253
16681
|
SET attempts = ?, next_attempt_at = ?, last_error = ?
|
|
17254
|
-
WHERE request_id = ?`).run(attempts, now +
|
|
16682
|
+
WHERE request_id = ?`).run(attempts, now + delay, args.error.slice(0, 500), args.requestId);
|
|
17255
16683
|
})();
|
|
17256
16684
|
}
|
|
17257
16685
|
function purgeExpiredRemoteSessionReplyOutbox(now = Date.now()) {
|
|
@@ -17422,37 +16850,9 @@ var init_remote_session_reply_outbox = __esm(async () => {
|
|
|
17422
16850
|
});
|
|
17423
16851
|
|
|
17424
16852
|
// ../../packages/core/src/mcp/session-comm/peer-forward.ts
|
|
17425
|
-
var exports_peer_forward = {};
|
|
17426
|
-
__export(exports_peer_forward, {
|
|
17427
|
-
registerPeerSessionBridge: () => registerPeerSessionBridge,
|
|
17428
|
-
peerSessionsForUser: () => peerSessionsForUser,
|
|
17429
|
-
parseHubRemoteReplyRoute: () => parseHubRemoteReplyRoute,
|
|
17430
|
-
isHubRemoteReplyRoute: () => isHubRemoteReplyRoute,
|
|
17431
|
-
forwardToPeer: () => forwardToPeer,
|
|
17432
|
-
deliverPeerReply: () => deliverPeerReply
|
|
17433
|
-
});
|
|
17434
16853
|
function isHubRemoteReplyRoute(route) {
|
|
17435
16854
|
return route.via === "hub";
|
|
17436
16855
|
}
|
|
17437
|
-
function parseHubRemoteReplyRoute(value) {
|
|
17438
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
17439
|
-
return null;
|
|
17440
|
-
const route = value;
|
|
17441
|
-
if (route.via !== "hub" || typeof route.hubUrl !== "string" || typeof route.token !== "string" || typeof route.nodeName !== "string" || typeof route.topicId !== "string" || typeof route.requestId !== "string") {
|
|
17442
|
-
return null;
|
|
17443
|
-
}
|
|
17444
|
-
const requestId = route.requestId.trim();
|
|
17445
|
-
const nodeName = route.nodeName.trim();
|
|
17446
|
-
const topicId = route.topicId.trim();
|
|
17447
|
-
const token = route.token.trim();
|
|
17448
|
-
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)) {
|
|
17449
|
-
return null;
|
|
17450
|
-
}
|
|
17451
|
-
const hubUrl = normalizeHubUrl(route.hubUrl.trim(), "remoteReply.hubUrl");
|
|
17452
|
-
if ("error" in hubUrl)
|
|
17453
|
-
return null;
|
|
17454
|
-
return { via: "hub", hubUrl: hubUrl.url, token, nodeName, topicId, requestId };
|
|
17455
|
-
}
|
|
17456
16856
|
function loopbackBridgeConfig() {
|
|
17457
16857
|
const rawUrl = process.env[PEER_BRIDGE_URL_ENV]?.trim();
|
|
17458
16858
|
const token = process.env[PEER_BRIDGE_TOKEN_ENV]?.trim();
|
|
@@ -17489,39 +16889,6 @@ async function callLoopbackBridge(request) {
|
|
|
17489
16889
|
return { configured: true, result: null };
|
|
17490
16890
|
}
|
|
17491
16891
|
}
|
|
17492
|
-
function registerPeerSessionBridge(bridge) {
|
|
17493
|
-
activeBridge = bridge;
|
|
17494
|
-
return () => {
|
|
17495
|
-
if (activeBridge === bridge)
|
|
17496
|
-
activeBridge = null;
|
|
17497
|
-
};
|
|
17498
|
-
}
|
|
17499
|
-
async function forwardToPeer(args) {
|
|
17500
|
-
if (activeBridge)
|
|
17501
|
-
return activeBridge.forward(args);
|
|
17502
|
-
const forwarded = await callLoopbackBridge({ action: "forward", args });
|
|
17503
|
-
if (forwarded.result)
|
|
17504
|
-
return forwarded.result;
|
|
17505
|
-
return {
|
|
17506
|
-
ok: false,
|
|
17507
|
-
error: forwarded.configured ? "remote session bridge is configured but unavailable" : "remote nodes are not connected on this negotium node (standalone mode)"
|
|
17508
|
-
};
|
|
17509
|
-
}
|
|
17510
|
-
async function peerSessionsForUser(userId, sourceQueryId, fromTopicId) {
|
|
17511
|
-
if (activeBridge)
|
|
17512
|
-
return activeBridge.sessions(userId, sourceQueryId, fromTopicId);
|
|
17513
|
-
const sessions = await callLoopbackBridge({
|
|
17514
|
-
action: "sessions",
|
|
17515
|
-
userId,
|
|
17516
|
-
sourceQueryId,
|
|
17517
|
-
fromTopicId
|
|
17518
|
-
});
|
|
17519
|
-
if (sessions.result)
|
|
17520
|
-
return sessions.result;
|
|
17521
|
-
if (sessions.configured)
|
|
17522
|
-
return { ok: false, nodes: [] };
|
|
17523
|
-
return { ok: true, nodes: [] };
|
|
17524
|
-
}
|
|
17525
16892
|
async function deliverPeerReply(route, sourceTitle, replyText, kind) {
|
|
17526
16893
|
if (isHubRemoteReplyRoute(route)) {
|
|
17527
16894
|
return deliverHubRemoteReply(route, sourceTitle, replyText, kind);
|
|
@@ -17536,40 +16903,13 @@ async function deliverPeerReply(route, sourceTitle, replyText, kind) {
|
|
|
17536
16903
|
kind
|
|
17537
16904
|
})).result ?? false;
|
|
17538
16905
|
}
|
|
17539
|
-
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;
|
|
17540
16907
|
var init_peer_forward = __esm(async () => {
|
|
17541
16908
|
init_remote_session_grant();
|
|
17542
16909
|
await init_remote_session_reply_outbox();
|
|
17543
16910
|
});
|
|
17544
16911
|
|
|
17545
16912
|
// ../../packages/core/src/runtime/ask-callbacks.ts
|
|
17546
|
-
var exports_ask_callbacks = {};
|
|
17547
|
-
__export(exports_ask_callbacks, {
|
|
17548
|
-
resolveAskCallback: () => resolveAskCallback,
|
|
17549
|
-
registerAskCallback: () => registerAskCallback,
|
|
17550
|
-
purgeStaleAsks: () => purgeStaleAsks,
|
|
17551
|
-
failInterruptedRemoteAskCallbacks: () => failInterruptedRemoteAskCallbacks,
|
|
17552
|
-
deleteHubRemoteAskCallbackRow: () => deleteHubRemoteAskCallbackRow,
|
|
17553
|
-
cancelAskCallbacksForTopic: () => cancelAskCallbacksForTopic
|
|
17554
|
-
});
|
|
17555
|
-
function registerAskCallback(entry) {
|
|
17556
|
-
pendingAsks.set(entry.targetQueryId, entry);
|
|
17557
|
-
if (entry.remoteReply) {
|
|
17558
|
-
const route = entry.remoteReply;
|
|
17559
|
-
const hub = isHubRemoteReplyRoute(route);
|
|
17560
|
-
db.query(`INSERT INTO remote_ask_callbacks
|
|
17561
|
-
(target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, created_at, route_json)
|
|
17562
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
17563
|
-
ON CONFLICT(target_query_id) DO UPDATE SET
|
|
17564
|
-
request_id = excluded.request_id,
|
|
17565
|
-
node_name = excluded.node_name,
|
|
17566
|
-
node_cell_id = excluded.node_cell_id,
|
|
17567
|
-
topic_id = excluded.topic_id,
|
|
17568
|
-
user_id = excluded.user_id,
|
|
17569
|
-
created_at = excluded.created_at,
|
|
17570
|
-
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);
|
|
17571
|
-
}
|
|
17572
|
-
}
|
|
17573
16913
|
function resolveAskCallback(queryId) {
|
|
17574
16914
|
const entry = pendingAsks.get(queryId);
|
|
17575
16915
|
if (!entry)
|
|
@@ -17586,13 +16926,6 @@ function resolveAskCallback(queryId) {
|
|
|
17586
16926
|
function deleteHubRemoteAskCallbackRow(requestId) {
|
|
17587
16927
|
db.query("DELETE FROM remote_ask_callbacks WHERE request_id = ? AND route_json IS NOT NULL").run(requestId);
|
|
17588
16928
|
}
|
|
17589
|
-
function purgeStaleAsks(now = Date.now()) {
|
|
17590
|
-
for (const [id, entry] of pendingAsks) {
|
|
17591
|
-
if (now - entry.createdAt > MAX_ASK_AGE_MS)
|
|
17592
|
-
pendingAsks.delete(id);
|
|
17593
|
-
}
|
|
17594
|
-
db.query("DELETE FROM remote_ask_callbacks WHERE created_at < ?").run(now - MAX_ASK_AGE_MS);
|
|
17595
|
-
}
|
|
17596
16929
|
function cancelAskCallbacksForTopic(topicId) {
|
|
17597
16930
|
let cancelled = 0;
|
|
17598
16931
|
for (const [queryId, entry] of pendingAsks) {
|
|
@@ -17604,43 +16937,6 @@ function cancelAskCallbacksForTopic(topicId) {
|
|
|
17604
16937
|
}
|
|
17605
16938
|
return cancelled;
|
|
17606
16939
|
}
|
|
17607
|
-
function durableRoute(row) {
|
|
17608
|
-
if (row.route_json) {
|
|
17609
|
-
try {
|
|
17610
|
-
return parseHubRemoteReplyRoute(JSON.parse(row.route_json));
|
|
17611
|
-
} catch {
|
|
17612
|
-
return null;
|
|
17613
|
-
}
|
|
17614
|
-
}
|
|
17615
|
-
return {
|
|
17616
|
-
nodeName: row.node_name,
|
|
17617
|
-
nodeCellId: row.node_cell_id,
|
|
17618
|
-
topicId: row.topic_id,
|
|
17619
|
-
userId: row.user_id,
|
|
17620
|
-
requestId: row.request_id
|
|
17621
|
-
};
|
|
17622
|
-
}
|
|
17623
|
-
async function failInterruptedRemoteAskCallbacks(options = {}) {
|
|
17624
|
-
const rows = db.query(`SELECT target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, route_json
|
|
17625
|
-
FROM remote_ask_callbacks
|
|
17626
|
-
ORDER BY created_at ASC`).all();
|
|
17627
|
-
let failed = 0;
|
|
17628
|
-
for (const row of rows) {
|
|
17629
|
-
const route = durableRoute(row);
|
|
17630
|
-
if (!route) {
|
|
17631
|
-
db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
|
|
17632
|
-
continue;
|
|
17633
|
-
}
|
|
17634
|
-
if (options.routes === "hub" && !isHubRemoteReplyRoute(route))
|
|
17635
|
-
continue;
|
|
17636
|
-
const delivered = await deliverPeerReply(route, "peer", "The remote worker restarted before this ask completed. Please retry the request.", "error");
|
|
17637
|
-
if (!delivered)
|
|
17638
|
-
continue;
|
|
17639
|
-
db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
|
|
17640
|
-
failed++;
|
|
17641
|
-
}
|
|
17642
|
-
return failed;
|
|
17643
|
-
}
|
|
17644
16940
|
var pendingAsks, MAX_ASK_AGE_MS;
|
|
17645
16941
|
var init_ask_callbacks = __esm(async () => {
|
|
17646
16942
|
await __promiseAll([
|
|
@@ -18066,14 +17362,6 @@ var init_topic_tool_capabilities = __esm(async () => {
|
|
|
18066
17362
|
});
|
|
18067
17363
|
|
|
18068
17364
|
// ../../packages/core/src/topics/lifecycle.ts
|
|
18069
|
-
var exports_lifecycle = {};
|
|
18070
|
-
__export(exports_lifecycle, {
|
|
18071
|
-
deleteTopicCascade: () => deleteTopicCascade,
|
|
18072
|
-
TopicTurnStillActiveError: () => TopicTurnStillActiveError,
|
|
18073
|
-
TopicDeleteVetoedError: () => TopicDeleteVetoedError,
|
|
18074
|
-
TopicCleanupRequiredError: () => TopicCleanupRequiredError,
|
|
18075
|
-
TopicArchiveRequiredError: () => TopicArchiveRequiredError
|
|
18076
|
-
});
|
|
18077
17365
|
import { rmSync as rmSync6 } from "fs";
|
|
18078
17366
|
async function abortAndWaitForTopic(topicId) {
|
|
18079
17367
|
interSessionQueue.drop(topicId);
|
|
@@ -18106,8 +17394,8 @@ async function cleanupParticipantResources(topic, userIds, sessionId, cwd, purge
|
|
|
18106
17394
|
cwd,
|
|
18107
17395
|
extraSessions: index === 0 ? currentSessionRef(topic, sessionId) : []
|
|
18108
17396
|
});
|
|
18109
|
-
} catch (
|
|
18110
|
-
logger.warn({ err
|
|
17397
|
+
} catch (err) {
|
|
17398
|
+
logger.warn({ err, topicId: topic.id, userId: participantUserId }, "deleteTopicCascade: participant rollout cleanup failed");
|
|
18111
17399
|
}
|
|
18112
17400
|
if (!purged)
|
|
18113
17401
|
return false;
|
|
@@ -18163,12 +17451,12 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18163
17451
|
if (rawArchive)
|
|
18164
17452
|
rawArchives.push(rawArchive.path);
|
|
18165
17453
|
}
|
|
18166
|
-
} catch (
|
|
17454
|
+
} catch (err) {
|
|
18167
17455
|
if (!force) {
|
|
18168
|
-
logger.warn({ err
|
|
18169
|
-
throw new TopicArchiveRequiredError(topicId,
|
|
17456
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: archive failed - blocking delete unless force=true");
|
|
17457
|
+
throw new TopicArchiveRequiredError(topicId, err);
|
|
18170
17458
|
}
|
|
18171
|
-
logger.warn({ err
|
|
17459
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: archive failed but force=true - continuing with hard delete");
|
|
18172
17460
|
}
|
|
18173
17461
|
}
|
|
18174
17462
|
if (archived && meetsMemoryArchiveExchangeThreshold(archived.exchangeCount, MIN_MEMORY_ARCHIVE_EXCHANGES, topic)) {
|
|
@@ -18184,8 +17472,8 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18184
17472
|
...rawArchives.length > 0 ? { rawArchivePaths: rawArchives } : {},
|
|
18185
17473
|
messageCount: archived.messageCount
|
|
18186
17474
|
});
|
|
18187
|
-
} catch (
|
|
18188
|
-
logger.warn({ err
|
|
17475
|
+
} catch (err) {
|
|
17476
|
+
logger.warn({ err, topicId, archive: archived.path }, "deleteTopicCascade: background archiver launch failed - raw archive preserved");
|
|
18189
17477
|
}
|
|
18190
17478
|
}
|
|
18191
17479
|
const sessionId = getTopicSessionId(topicId);
|
|
@@ -18202,21 +17490,21 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18202
17490
|
killBgBash(userId, topicId);
|
|
18203
17491
|
try {
|
|
18204
17492
|
await closeTopicBrowserTabs(userId, topicId);
|
|
18205
|
-
} catch (
|
|
18206
|
-
logger.warn({ err
|
|
17493
|
+
} catch (err) {
|
|
17494
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: browser owner cleanup failed");
|
|
18207
17495
|
}
|
|
18208
17496
|
deleteTopicProfileDir(userId, topicId);
|
|
18209
17497
|
cancelAskCallbacksForTopic(topicId);
|
|
18210
17498
|
deleteSelfSchedulesForTopic(topicId);
|
|
18211
17499
|
try {
|
|
18212
17500
|
await deleteFilesForTopic(topicId);
|
|
18213
|
-
} catch (
|
|
18214
|
-
logger.warn({ err
|
|
17501
|
+
} catch (err) {
|
|
17502
|
+
logger.warn({ err, topicId }, "deleteTopicCascade: host file cleanup failed");
|
|
18215
17503
|
}
|
|
18216
17504
|
try {
|
|
18217
17505
|
rmSync6(cwd, { recursive: true, force: true });
|
|
18218
|
-
} catch (
|
|
18219
|
-
logger.warn({ err
|
|
17506
|
+
} catch (err) {
|
|
17507
|
+
logger.warn({ err, topicId, cwd }, "deleteTopicCascade: workspace cleanup failed");
|
|
18220
17508
|
}
|
|
18221
17509
|
deleteTopicVisuals(topicId);
|
|
18222
17510
|
deleteTopicHostMcpGrant(topicId);
|
|
@@ -18258,7 +17546,7 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
18258
17546
|
}
|
|
18259
17547
|
}
|
|
18260
17548
|
}
|
|
18261
|
-
var DELETE_TURN_WAIT_MS = 5000, TopicArchiveRequiredError, TopicTurnStillActiveError, TopicCleanupRequiredError
|
|
17549
|
+
var DELETE_TURN_WAIT_MS = 5000, TopicArchiveRequiredError, TopicTurnStillActiveError, TopicCleanupRequiredError;
|
|
18262
17550
|
var init_lifecycle = __esm(async () => {
|
|
18263
17551
|
init_manager();
|
|
18264
17552
|
init_config();
|
|
@@ -18324,19 +17612,9 @@ var init_lifecycle = __esm(async () => {
|
|
|
18324
17612
|
this.topicId = topicId;
|
|
18325
17613
|
}
|
|
18326
17614
|
};
|
|
18327
|
-
TopicDeleteVetoedError = class TopicDeleteVetoedError extends Error {
|
|
18328
|
-
code = "TOPIC_DELETE_VETOED";
|
|
18329
|
-
topicId;
|
|
18330
|
-
constructor(topicId, reason) {
|
|
18331
|
-
super(`Topic delete was vetoed: ${reason}`);
|
|
18332
|
-
this.name = "TopicDeleteVetoedError";
|
|
18333
|
-
this.topicId = topicId;
|
|
18334
|
-
}
|
|
18335
|
-
};
|
|
18336
17615
|
});
|
|
18337
17616
|
|
|
18338
17617
|
// ../../packages/core/src/runtime/attachments.ts
|
|
18339
|
-
import { randomUUID as randomUUID16 } from "crypto";
|
|
18340
17618
|
import { copyFileSync as copyFileSync2, mkdirSync as mkdirSync17, writeFileSync as writeFileSync15 } from "fs";
|
|
18341
17619
|
import { basename as basename6, join as join29 } from "path";
|
|
18342
17620
|
function workspaceCwdFor(topicId) {
|
|
@@ -18378,8 +17656,8 @@ function materializePromptAttachments(topicId, queryId, attachmentIds) {
|
|
|
18378
17656
|
sizeBytes: attachment.sizeBytes,
|
|
18379
17657
|
path: destPath
|
|
18380
17658
|
});
|
|
18381
|
-
} catch (
|
|
18382
|
-
logger.warn({ topicId, queryId, fileId, err
|
|
17659
|
+
} catch (err) {
|
|
17660
|
+
logger.warn({ topicId, queryId, fileId, err }, "ai: failed to materialize attachment");
|
|
18383
17661
|
}
|
|
18384
17662
|
}
|
|
18385
17663
|
return out;
|
|
@@ -18397,24 +17675,6 @@ function composeAttachmentPrompt(prompt, promptLines) {
|
|
|
18397
17675
|
function promptWithAttachments(prompt, attachments) {
|
|
18398
17676
|
return composeAttachmentPrompt(prompt, attachments.map(({ filename, path }) => attachmentPromptLine(filename, path)));
|
|
18399
17677
|
}
|
|
18400
|
-
function ingestAttachment(args) {
|
|
18401
|
-
const destDir = join29(UPLOADS_DIR, args.topicId);
|
|
18402
|
-
mkdirSync17(destDir, { recursive: true });
|
|
18403
|
-
const safeName = safeAttachmentFilename(args.filename, "upload");
|
|
18404
|
-
const destPath = join29(destDir, `${Date.now()}-${randomUUID16().slice(0, 8)}-${safeName}`);
|
|
18405
|
-
if (args.sourcePath !== undefined) {
|
|
18406
|
-
copyFileSync2(args.sourcePath, destPath);
|
|
18407
|
-
} else if (args.bytes !== undefined) {
|
|
18408
|
-
writeFileSync15(destPath, args.bytes);
|
|
18409
|
-
} else {
|
|
18410
|
-
throw new Error("ingestAttachment: provide sourcePath or bytes");
|
|
18411
|
-
}
|
|
18412
|
-
return {
|
|
18413
|
-
path: destPath,
|
|
18414
|
-
filename: args.filename,
|
|
18415
|
-
promptLine: attachmentPromptLine(args.filename, destPath)
|
|
18416
|
-
};
|
|
18417
|
-
}
|
|
18418
17678
|
function parseAttachmentNames(raw) {
|
|
18419
17679
|
if (!raw)
|
|
18420
17680
|
return [];
|
|
@@ -18455,13 +17715,13 @@ function isLikelyCurrentChannelTrigger(row, userId, prompt) {
|
|
|
18455
17715
|
return Number.isFinite(createdMs) && Date.now() - createdMs <= CHANNEL_CONTEXT_CURRENT_MESSAGE_MATCH_MS;
|
|
18456
17716
|
}
|
|
18457
17717
|
function formatChannelTranscriptLine(row) {
|
|
18458
|
-
const
|
|
17718
|
+
const text = row.text.trim();
|
|
18459
17719
|
const attachments = parseAttachmentNames(row.attachments);
|
|
18460
17720
|
const attachmentSuffix = attachments.length > 0 ? `
|
|
18461
17721
|
[attachments: ${attachments.join(", ")}]` : "";
|
|
18462
17722
|
const edited = row.edited_at ? " (edited)" : "";
|
|
18463
17723
|
const thread = row.thread_root_id ? ` (in thread ${threadTag(row.thread_root_id)})` : "";
|
|
18464
|
-
return `[${row.created_at}] ${channelTranscriptSpeaker(row)}${edited}${thread}: ${
|
|
17724
|
+
return `[${row.created_at}] ${channelTranscriptSpeaker(row)}${edited}${thread}: ${text}${attachmentSuffix}`;
|
|
18465
17725
|
}
|
|
18466
17726
|
function buildMentionOnlyChannelPrompt(params) {
|
|
18467
17727
|
const rows = getAllMessagesForTopic(params.topicId).filter((row) => {
|
|
@@ -18506,14 +17766,6 @@ function buildMentionOnlyChannelPrompt(params) {
|
|
|
18506
17766
|
].filter((line) => line !== undefined).join(`
|
|
18507
17767
|
`);
|
|
18508
17768
|
}
|
|
18509
|
-
function escapeRegExp3(s) {
|
|
18510
|
-
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18511
|
-
}
|
|
18512
|
-
function mentionsAi(text2, label) {
|
|
18513
|
-
const names = ["ai", "bot", "\uBD07", label.trim()].filter(Boolean);
|
|
18514
|
-
const alt = names.map(escapeRegExp3).join("|");
|
|
18515
|
-
return new RegExp(`(^|\\s)@(${alt})(?![\\p{L}\\p{N}])`, "iu").test(text2);
|
|
18516
|
-
}
|
|
18517
17769
|
var CHANNEL_CONTEXT_CURRENT_MESSAGE_MATCH_MS, CHANNEL_CONTEXT_MAX_MESSAGES = 500, CHANNEL_CONTEXT_MAX_CHARS = 120000;
|
|
18518
17770
|
var init_channel_context = __esm(async () => {
|
|
18519
17771
|
init_attachments();
|
|
@@ -18522,13 +17774,13 @@ var init_channel_context = __esm(async () => {
|
|
|
18522
17774
|
});
|
|
18523
17775
|
|
|
18524
17776
|
// ../../packages/core/src/runtime/errors.ts
|
|
18525
|
-
function stringifyError(
|
|
18526
|
-
if (
|
|
18527
|
-
return
|
|
18528
|
-
if (typeof
|
|
18529
|
-
return
|
|
17777
|
+
function stringifyError(err) {
|
|
17778
|
+
if (err instanceof Error)
|
|
17779
|
+
return err.message;
|
|
17780
|
+
if (typeof err === "string")
|
|
17781
|
+
return err;
|
|
18530
17782
|
try {
|
|
18531
|
-
return JSON.stringify(
|
|
17783
|
+
return JSON.stringify(err) ?? String(err);
|
|
18532
17784
|
} catch {
|
|
18533
17785
|
return "Unknown agent error";
|
|
18534
17786
|
}
|
|
@@ -18543,19 +17795,19 @@ function authRecoveryHint(agent) {
|
|
|
18543
17795
|
return "Please check the DEEPSEEK_API_KEY, MOONSHOT_API_KEY, or GLM_API_KEY environment variable";
|
|
18544
17796
|
}
|
|
18545
17797
|
}
|
|
18546
|
-
function classifyAgentError(
|
|
17798
|
+
function classifyAgentError(err, agent) {
|
|
18547
17799
|
const name = AGENT_DISPLAY_NAME[agent];
|
|
18548
17800
|
const hint = authRecoveryHint(agent);
|
|
18549
|
-
const ctor = typeof
|
|
17801
|
+
const ctor = typeof err === "object" && err !== null ? err.constructor?.name : undefined;
|
|
18550
17802
|
if (ctor === "AuthenticationError")
|
|
18551
17803
|
return `${name} authentication expired. ${hint}. (401)`;
|
|
18552
17804
|
if (ctor === "RateLimitError")
|
|
18553
17805
|
return `${name} request limit exceeded. Please try again in a moment. (429)`;
|
|
18554
17806
|
if (ctor === "InternalServerError") {
|
|
18555
|
-
const status =
|
|
17807
|
+
const status = err.status;
|
|
18556
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)`;
|
|
18557
17809
|
}
|
|
18558
|
-
const s = stringifyError(
|
|
17810
|
+
const s = stringifyError(err);
|
|
18559
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)) {
|
|
18560
17812
|
return `${name} authentication expired. ${hint}. (401)`;
|
|
18561
17813
|
}
|
|
@@ -18578,12 +17830,12 @@ var init_errors = __esm(() => {
|
|
|
18578
17830
|
|
|
18579
17831
|
// ../../packages/core/src/runtime/event-heartbeat.ts
|
|
18580
17832
|
function nextOrHeartbeat(pending, intervalMs) {
|
|
18581
|
-
return new Promise((
|
|
18582
|
-
const timer = setTimeout(() =>
|
|
17833
|
+
return new Promise((resolve, reject) => {
|
|
17834
|
+
const timer = setTimeout(() => resolve({ kind: "heartbeat" }), intervalMs);
|
|
18583
17835
|
timer.unref?.();
|
|
18584
17836
|
pending.then((result) => {
|
|
18585
17837
|
clearTimeout(timer);
|
|
18586
|
-
|
|
17838
|
+
resolve({ kind: "event", result });
|
|
18587
17839
|
}, (error) => {
|
|
18588
17840
|
clearTimeout(timer);
|
|
18589
17841
|
reject(error);
|
|
@@ -18877,7 +18129,7 @@ var init_vault_request_gates = __esm(async () => {
|
|
|
18877
18129
|
});
|
|
18878
18130
|
|
|
18879
18131
|
// ../../packages/core/src/agents/mcp-tools/request-vault.ts
|
|
18880
|
-
import { createHash as createHash12, randomUUID as
|
|
18132
|
+
import { createHash as createHash12, randomUUID as randomUUID16 } from "crypto";
|
|
18881
18133
|
import { z as z4 } from "zod";
|
|
18882
18134
|
function requestBodyHash(key, description) {
|
|
18883
18135
|
return createHash12("sha256").update(JSON.stringify({ key, description })).digest("hex");
|
|
@@ -19117,8 +18369,8 @@ function createRequestVaultRuntime(host) {
|
|
|
19117
18369
|
return errorResult(`Error: failed to persist request_vault_secret: ${error instanceof Error ? error.message : String(error)}`);
|
|
19118
18370
|
}
|
|
19119
18371
|
let resolveAnswer;
|
|
19120
|
-
const promise = new Promise((
|
|
19121
|
-
resolveAnswer =
|
|
18372
|
+
const promise = new Promise((resolve) => {
|
|
18373
|
+
resolveAnswer = resolve;
|
|
19122
18374
|
});
|
|
19123
18375
|
pendingRequests.set(message.id, {
|
|
19124
18376
|
topicId: ctx.topicId,
|
|
@@ -19218,7 +18470,7 @@ var init_request_vault = __esm(async () => {
|
|
|
19218
18470
|
init_vault_request_gates()
|
|
19219
18471
|
]);
|
|
19220
18472
|
MAX_DESCRIPTION_CHARS = VAULT_DESCRIPTION_MAX_LENGTH;
|
|
19221
|
-
VAULT_GATE_OWNER_ID = `request-vault-${process.pid}-${
|
|
18473
|
+
VAULT_GATE_OWNER_ID = `request-vault-${process.pid}-${randomUUID16()}`;
|
|
19222
18474
|
defaultRequestVaultDurabilityHost = {
|
|
19223
18475
|
gates: {
|
|
19224
18476
|
prepare: prepareVaultRequestGate,
|
|
@@ -19260,7 +18512,7 @@ var init_request_vault = __esm(async () => {
|
|
|
19260
18512
|
durability: defaultRequestVaultDurabilityHost,
|
|
19261
18513
|
runtime: {
|
|
19262
18514
|
ownerId: VAULT_GATE_OWNER_ID,
|
|
19263
|
-
createId:
|
|
18515
|
+
createId: randomUUID16,
|
|
19264
18516
|
now: () => new Date().toISOString()
|
|
19265
18517
|
}
|
|
19266
18518
|
});
|
|
@@ -19297,24 +18549,24 @@ function taskPanelMessageId(queryId) {
|
|
|
19297
18549
|
// ../../packages/core/src/runtime/tasks.ts
|
|
19298
18550
|
function upsertTaskPanelMessage(topicId, queryId, tasks, lastRenderedText) {
|
|
19299
18551
|
if (tasks.length === 0) {
|
|
19300
|
-
const
|
|
19301
|
-
for (const
|
|
19302
|
-
|
|
18552
|
+
const hub = WsHub.get();
|
|
18553
|
+
for (const messageId of softDeleteApiMessagesByIdPrefix(topicId, "tasks-")) {
|
|
18554
|
+
hub.broadcastMessageUpdated(topicId, messageId, { deleted: true, text: "" });
|
|
19303
18555
|
}
|
|
19304
18556
|
return null;
|
|
19305
18557
|
}
|
|
19306
|
-
const
|
|
19307
|
-
if (
|
|
18558
|
+
const text = renderTaskPanel(tasks);
|
|
18559
|
+
if (text === lastRenderedText)
|
|
19308
18560
|
return lastRenderedText;
|
|
19309
18561
|
const hub = WsHub.get();
|
|
19310
18562
|
const messageId = taskPanelMessageId(queryId);
|
|
19311
18563
|
const existing = getApiMessage(topicId, messageId);
|
|
19312
18564
|
if (existing && !existing.deleted) {
|
|
19313
18565
|
const editedAt = new Date().toISOString();
|
|
19314
|
-
const updated = updateApiMessageText(topicId, messageId,
|
|
18566
|
+
const updated = updateApiMessageText(topicId, messageId, text, editedAt);
|
|
19315
18567
|
if (updated) {
|
|
19316
|
-
hub.broadcastMessageUpdated(topicId, messageId, { text
|
|
19317
|
-
return
|
|
18568
|
+
hub.broadcastMessageUpdated(topicId, messageId, { text, editedAt });
|
|
18569
|
+
return text;
|
|
19318
18570
|
}
|
|
19319
18571
|
}
|
|
19320
18572
|
const createdAt = new Date().toISOString();
|
|
@@ -19322,12 +18574,12 @@ function upsertTaskPanelMessage(topicId, queryId, tasks, lastRenderedText) {
|
|
|
19322
18574
|
id: messageId,
|
|
19323
18575
|
topicId,
|
|
19324
18576
|
authorId: "system",
|
|
19325
|
-
text
|
|
18577
|
+
text,
|
|
19326
18578
|
createdAt
|
|
19327
18579
|
};
|
|
19328
18580
|
appendApiMessage(message, { notify: false });
|
|
19329
18581
|
hub.broadcastMessage(topicId, message);
|
|
19330
|
-
return
|
|
18582
|
+
return text;
|
|
19331
18583
|
}
|
|
19332
18584
|
var init_tasks2 = __esm(async () => {
|
|
19333
18585
|
await __promiseAll([
|
|
@@ -19614,10 +18866,6 @@ function locateVisualMediaInput(topicId, input) {
|
|
|
19614
18866
|
}
|
|
19615
18867
|
return { kind: "file", path: realCandidate, rawPath };
|
|
19616
18868
|
}
|
|
19617
|
-
function visualMediaInputError(topicId, input) {
|
|
19618
|
-
const located = locateVisualMediaInput(topicId, input);
|
|
19619
|
-
return "error" in located ? located.error : null;
|
|
19620
|
-
}
|
|
19621
18869
|
function resolveVisualMediaInput(topicId, input) {
|
|
19622
18870
|
const located = locateVisualMediaInput(topicId, input);
|
|
19623
18871
|
if ("error" in located)
|
|
@@ -19656,7 +18904,7 @@ var init_visuals = __esm(async () => {
|
|
|
19656
18904
|
});
|
|
19657
18905
|
|
|
19658
18906
|
// ../../packages/core/src/runtime/turn-event-stream.ts
|
|
19659
|
-
import { randomUUID as
|
|
18907
|
+
import { randomUUID as randomUUID17 } from "crypto";
|
|
19660
18908
|
import { realpathSync as realpathSync6, statSync as statSync9 } from "fs";
|
|
19661
18909
|
import { isAbsolute as isAbsolute7, resolve as resolve18 } from "path";
|
|
19662
18910
|
function sessionEventMatchesCurrentExecution(topicId, queryId, agent, model) {
|
|
@@ -19683,6 +18931,38 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19683
18931
|
let pendingSawDelta = false;
|
|
19684
18932
|
let accumulatedText = "";
|
|
19685
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
|
+
};
|
|
19686
18966
|
let assistantContextTokens = 0;
|
|
19687
18967
|
let toolContextTokens = 0;
|
|
19688
18968
|
let lastContextProgressAt = 0;
|
|
@@ -19726,9 +19006,9 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19726
19006
|
const existing = providerToolIds.get(providerId);
|
|
19727
19007
|
if (existing)
|
|
19728
19008
|
return existing;
|
|
19729
|
-
const
|
|
19730
|
-
providerToolIds.set(providerId,
|
|
19731
|
-
return
|
|
19009
|
+
const clientId = fallback ?? providerId;
|
|
19010
|
+
providerToolIds.set(providerId, clientId);
|
|
19011
|
+
return clientId;
|
|
19732
19012
|
}
|
|
19733
19013
|
const clientId = fallback ?? nextSyntheticToolUseId();
|
|
19734
19014
|
anonymousToolIds.push(clientId);
|
|
@@ -19759,22 +19039,25 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19759
19039
|
return providerId ? handledVisualToolResultIds.has(providerId) : false;
|
|
19760
19040
|
};
|
|
19761
19041
|
const emitPendingAssistantMessage = (usage) => {
|
|
19762
|
-
|
|
19042
|
+
clearPreviewTimer();
|
|
19043
|
+
const identity = pendingMessage;
|
|
19044
|
+
pendingMessage = null;
|
|
19045
|
+
const text = pendingText.trimEnd();
|
|
19763
19046
|
pendingText = "";
|
|
19764
|
-
if (silent || !
|
|
19047
|
+
if (silent || !text.trim())
|
|
19765
19048
|
return null;
|
|
19766
19049
|
const message = {
|
|
19767
|
-
id:
|
|
19050
|
+
id: identity?.id ?? randomUUID17(),
|
|
19768
19051
|
topicId,
|
|
19769
19052
|
authorId: "ai",
|
|
19770
|
-
text
|
|
19053
|
+
text,
|
|
19771
19054
|
queryId,
|
|
19772
19055
|
agentType,
|
|
19773
19056
|
model,
|
|
19774
19057
|
sourceNode: execution?.sourceNode,
|
|
19775
19058
|
...execution?.threadRootId ? { threadRootId: execution.threadRootId } : {},
|
|
19776
19059
|
usage,
|
|
19777
|
-
createdAt: new Date().toISOString()
|
|
19060
|
+
createdAt: identity?.createdAt ?? new Date().toISOString()
|
|
19778
19061
|
};
|
|
19779
19062
|
appendApiMessage(message, execution?.threadRootId ? { updateTopicLastMessageAt: false } : undefined);
|
|
19780
19063
|
hub.broadcastMessage(topicId, message);
|
|
@@ -19829,6 +19112,7 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19829
19112
|
const incoming = event.content;
|
|
19830
19113
|
accumulatedText += incoming;
|
|
19831
19114
|
pendingText += incoming;
|
|
19115
|
+
scheduleTextPreview();
|
|
19832
19116
|
assistantContextTokens = estimateTextTokens(accumulatedText);
|
|
19833
19117
|
broadcastContextProgress();
|
|
19834
19118
|
break;
|
|
@@ -19842,6 +19126,7 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19842
19126
|
const incoming = event.content;
|
|
19843
19127
|
accumulatedText += incoming;
|
|
19844
19128
|
pendingText += incoming;
|
|
19129
|
+
scheduleTextPreview();
|
|
19845
19130
|
assistantContextTokens = estimateTextTokens(accumulatedText);
|
|
19846
19131
|
broadcastContextProgress();
|
|
19847
19132
|
}
|
|
@@ -19987,8 +19272,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
19987
19272
|
hub.broadcastVisual(topicId, queryId, url, vizId, title ?? null, kind);
|
|
19988
19273
|
hub.broadcastToolOutput(topicId, queryId, toolUseId, `Displayed: ${url}`);
|
|
19989
19274
|
markVisualToolResultHandled(event.toolUseId);
|
|
19990
|
-
} catch (
|
|
19991
|
-
const reason =
|
|
19275
|
+
} catch (err) {
|
|
19276
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
19992
19277
|
failMediaVisual(reason);
|
|
19993
19278
|
}
|
|
19994
19279
|
} else {
|
|
@@ -20099,8 +19384,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20099
19384
|
}
|
|
20100
19385
|
terminalEmitted = true;
|
|
20101
19386
|
{
|
|
20102
|
-
|
|
20103
|
-
const pending =
|
|
19387
|
+
await init_ask_callbacks();
|
|
19388
|
+
const pending = resolveAskCallback(queryId);
|
|
20104
19389
|
if (pending) {
|
|
20105
19390
|
const sourceLabel = pending.sourceLabel ?? topicTitle;
|
|
20106
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)";
|
|
@@ -20173,8 +19458,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20173
19458
|
if (control.injectParams)
|
|
20174
19459
|
control.injectParams.sessionId = event.sessionId;
|
|
20175
19460
|
onSessionId(event.sessionId);
|
|
20176
|
-
} catch (
|
|
20177
|
-
logger.warn({ err
|
|
19461
|
+
} catch (err) {
|
|
19462
|
+
logger.warn({ err, topicId, queryId, agentType }, "ai: isolated session owner rejected provider session id");
|
|
20178
19463
|
}
|
|
20179
19464
|
} else if (!silent && sessionEventMatchesCurrentExecution(topicId, queryId, agentType, model)) {
|
|
20180
19465
|
setTopicSessionId(topicId, event.sessionId, {
|
|
@@ -20207,14 +19492,14 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20207
19492
|
settleSubagentFailure(queryId, "\uC911\uC9C0\uB428 (\uC0AC\uC6A9\uC790\uAC00 \uC2E4\uD589\uC744 \uBA48\uCDC4\uC2B5\uB2C8\uB2E4)");
|
|
20208
19493
|
} else {
|
|
20209
19494
|
if (control.abortReason === "internal" /* Internal */) {
|
|
20210
|
-
|
|
20211
|
-
|
|
19495
|
+
await init_ask_callbacks();
|
|
19496
|
+
resolveAskCallback(queryId);
|
|
20212
19497
|
}
|
|
20213
19498
|
}
|
|
20214
19499
|
}
|
|
20215
|
-
} catch (
|
|
20216
|
-
const msg = stringifyError(
|
|
20217
|
-
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");
|
|
20218
19503
|
terminalEmitted = true;
|
|
20219
19504
|
if (retryableSessionExpired && isSessionExpiredError(msg)) {
|
|
20220
19505
|
outcome = { kind: "session-expired", error: msg };
|
|
@@ -20224,6 +19509,11 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
20224
19509
|
deliverAskError(queryId, topicTitle, msg);
|
|
20225
19510
|
}
|
|
20226
19511
|
} finally {
|
|
19512
|
+
clearPreviewTimer();
|
|
19513
|
+
if (pendingMessage) {
|
|
19514
|
+
hub.broadcastMessageUpdated(topicId, pendingMessage.id, { deleted: true, text: "" });
|
|
19515
|
+
pendingMessage = null;
|
|
19516
|
+
}
|
|
20227
19517
|
if (!terminalEmitted && !abortController.signal.aborted) {
|
|
20228
19518
|
const error = "Provider stream ended without a terminal event";
|
|
20229
19519
|
outcome = { kind: "provider-error", error };
|
|
@@ -20366,86 +19656,7 @@ var init_app_settings = __esm(async () => {
|
|
|
20366
19656
|
});
|
|
20367
19657
|
|
|
20368
19658
|
// ../../packages/core/src/runtime/turn-runner.ts
|
|
20369
|
-
|
|
20370
|
-
__export(exports_turn_runner, {
|
|
20371
|
-
workspaceCwdFor: () => workspaceCwdFor,
|
|
20372
|
-
withDefaultPlaywright: () => withDefaultPlaywright,
|
|
20373
|
-
wasLocallyRequeuedAfterUserPreemption: () => wasLocallyRequeuedAfterUserPreemption,
|
|
20374
|
-
visualMediaInputError: () => visualMediaInputError,
|
|
20375
|
-
userConversationPromptsToRecord: () => userConversationPromptsToRecord,
|
|
20376
|
-
upsertTaskPanelMessage: () => upsertTaskPanelMessage,
|
|
20377
|
-
tryReconstructTopicRollout: () => tryReconstructTopicRollout,
|
|
20378
|
-
triggerTopicAiTurn: () => triggerTopicAiTurn,
|
|
20379
|
-
topicAllowsVisualFileId: () => topicAllowsVisualFileId,
|
|
20380
|
-
taskPanelMessageId: () => taskPanelMessageId,
|
|
20381
|
-
stripMermaidFence: () => stripMermaidFence,
|
|
20382
|
-
stringifyError: () => stringifyError,
|
|
20383
|
-
streamAgentEvents: () => streamAgentEvents,
|
|
20384
|
-
startDurableTurnRequestWorker: () => startDurableTurnRequestWorker,
|
|
20385
|
-
startAiTurn: () => startAiTurn,
|
|
20386
|
-
selectableModel: () => selectableModel,
|
|
20387
|
-
sameTurnActor: () => sameTurnActor,
|
|
20388
|
-
safeAttachmentFilename: () => safeAttachmentFilename,
|
|
20389
|
-
resolveWorkerModel: () => resolveWorkerModel,
|
|
20390
|
-
resolveWorkerDefaultModel: () => resolveWorkerDefaultModel,
|
|
20391
|
-
resolveWikiMirrorPath: () => resolveWikiMirrorPath,
|
|
20392
|
-
resolveWikiMemoryMirror: () => resolveWikiMemoryMirror,
|
|
20393
|
-
resolveVisualMediaInput: () => resolveVisualMediaInput,
|
|
20394
|
-
resolveTurnToolCapabilities: () => resolveTurnToolCapabilities,
|
|
20395
|
-
resolveTurnHostMcpServers: () => resolveTurnHostMcpServers,
|
|
20396
|
-
resolveTopicTurnSession: () => resolveTopicTurnSession,
|
|
20397
|
-
resolveTopicTurnExecution: () => resolveTopicTurnExecution,
|
|
20398
|
-
resolveSessionRetry: () => resolveSessionRetry,
|
|
20399
|
-
resolveModelForAgent: () => resolveModelForAgent,
|
|
20400
|
-
resolveInitialTurnSessionId: () => resolveInitialTurnSessionId,
|
|
20401
|
-
resolveDefaultModel: () => resolveDefaultModel,
|
|
20402
|
-
resolveCompactionExecution: () => resolveCompactionExecution,
|
|
20403
|
-
renderUserTurnBatch: () => renderUserTurnBatch,
|
|
20404
|
-
renderUserPromptBatch: () => renderUserPromptBatch,
|
|
20405
|
-
renderTaskPanel: () => renderTaskPanel,
|
|
20406
|
-
promptWithAttachments: () => promptWithAttachments,
|
|
20407
|
-
prepareInjectReplayAfterUserPreemption: () => prepareInjectReplayAfterUserPreemption,
|
|
20408
|
-
parseAttachmentNames: () => parseAttachmentNames,
|
|
20409
|
-
normalizeToolUseId: () => normalizeToolUseId,
|
|
20410
|
-
normalizeMermaidTheme: () => normalizeMermaidTheme,
|
|
20411
|
-
modelOwner: () => modelOwner,
|
|
20412
|
-
mergeSupersedingUserTurn: () => mergeSupersedingUserTurn,
|
|
20413
|
-
mentionsAi: () => mentionsAi,
|
|
20414
|
-
materializePromptAttachments: () => materializePromptAttachments,
|
|
20415
|
-
isVisualsShowMermaidTool: () => isVisualsShowMermaidTool,
|
|
20416
|
-
isVisualsShowImageTool: () => isVisualsShowImageTool,
|
|
20417
|
-
isVisualsShowHtmlTool: () => isVisualsShowHtmlTool,
|
|
20418
|
-
isSessionExpiredError: () => isSessionExpiredError,
|
|
20419
|
-
isRuntimeTool: () => isRuntimeTool,
|
|
20420
|
-
isPathInside: () => isPathInside,
|
|
20421
|
-
isLikelyCurrentChannelTrigger: () => isLikelyCurrentChannelTrigger,
|
|
20422
|
-
ingestAttachment: () => ingestAttachment,
|
|
20423
|
-
formatSelectableModel: () => formatSelectableModel,
|
|
20424
|
-
formatChannelTranscriptLine: () => formatChannelTranscriptLine,
|
|
20425
|
-
escapeRegExp: () => escapeRegExp3,
|
|
20426
|
-
escapeHtml: () => escapeHtml2,
|
|
20427
|
-
deliverAskCallbackToCaller: () => deliverAskCallbackToCaller,
|
|
20428
|
-
composeAttachmentPrompt: () => composeAttachmentPrompt,
|
|
20429
|
-
classifyAgentError: () => classifyAgentError,
|
|
20430
|
-
channelTranscriptSpeaker: () => channelTranscriptSpeaker,
|
|
20431
|
-
canonicalModelId: () => canonicalModelId,
|
|
20432
|
-
buildVideoHtml: () => buildVideoHtml,
|
|
20433
|
-
buildTurnReminderQuery: () => buildTurnReminderQuery,
|
|
20434
|
-
buildMermaidHtml: () => buildMermaidHtml,
|
|
20435
|
-
buildMentionOnlyChannelPrompt: () => buildMentionOnlyChannelPrompt,
|
|
20436
|
-
buildImageHtml: () => buildImageHtml,
|
|
20437
|
-
authRecoveryHint: () => authRecoveryHint,
|
|
20438
|
-
attachmentPromptLine: () => attachmentPromptLine,
|
|
20439
|
-
activeVisualHtmlForPrompt: () => activeVisualHtmlForPrompt,
|
|
20440
|
-
SESSION_EXPIRED_MSG: () => SESSION_EXPIRED_MSG,
|
|
20441
|
-
SELECTABLE_MODELS: () => SELECTABLE_MODELS,
|
|
20442
|
-
MODEL_OWNER: () => MODEL_OWNER,
|
|
20443
|
-
MODEL_COST_ROUTING_SUMMARY: () => MODEL_COST_ROUTING_SUMMARY,
|
|
20444
|
-
MODEL_COST_RESEARCHED_AT: () => MODEL_COST_RESEARCHED_AT,
|
|
20445
|
-
FALLBACK_ORDER: () => FALLBACK_ORDER,
|
|
20446
|
-
AGENT_DISPLAY_NAME: () => AGENT_DISPLAY_NAME
|
|
20447
|
-
});
|
|
20448
|
-
import { randomUUID as randomUUID19 } from "crypto";
|
|
19659
|
+
import { randomUUID as randomUUID18 } from "crypto";
|
|
20449
19660
|
import { existsSync as existsSync22, mkdirSync as mkdirSync19, readdirSync as readdirSync5, statSync as statSync10 } from "fs";
|
|
20450
19661
|
import { join as join31 } from "path";
|
|
20451
19662
|
function withDefaultPlaywright(configuredMcp, isManager) {
|
|
@@ -20468,12 +19679,12 @@ function buildTurnReminderQuery(agent, prompt, reminders) {
|
|
|
20468
19679
|
|
|
20469
19680
|
${reminderPrompt}` };
|
|
20470
19681
|
}
|
|
20471
|
-
function appendSystemMessage(topicId,
|
|
19682
|
+
function appendSystemMessage(topicId, text, threadRootId) {
|
|
20472
19683
|
const message = {
|
|
20473
|
-
id:
|
|
19684
|
+
id: randomUUID18(),
|
|
20474
19685
|
topicId,
|
|
20475
19686
|
authorId: "system",
|
|
20476
|
-
text
|
|
19687
|
+
text,
|
|
20477
19688
|
...threadRootId ? { threadRootId } : {},
|
|
20478
19689
|
createdAt: new Date().toISOString()
|
|
20479
19690
|
};
|
|
@@ -20490,12 +19701,12 @@ function notifyPlaywrightUnavailable(topicId) {
|
|
|
20490
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.");
|
|
20491
19702
|
WsHub.get().broadcastTopicNotice(topicId, "info", "Playwright \uC0AC\uC6A9 \uBD88\uAC00");
|
|
20492
19703
|
}
|
|
20493
|
-
function appendAskReplyMessage(topicId,
|
|
19704
|
+
function appendAskReplyMessage(topicId, text, sourceLabel, body, kind, agentType, threadRootId) {
|
|
20494
19705
|
const message = {
|
|
20495
|
-
id:
|
|
19706
|
+
id: randomUUID18(),
|
|
20496
19707
|
topicId,
|
|
20497
19708
|
authorId: "ai",
|
|
20498
|
-
text
|
|
19709
|
+
text,
|
|
20499
19710
|
kind: "tell",
|
|
20500
19711
|
tellCard: {
|
|
20501
19712
|
fromLabel: sourceLabel,
|
|
@@ -20556,8 +19767,8 @@ function redispatchInject(inject) {
|
|
|
20556
19767
|
kind: "error",
|
|
20557
19768
|
error: "topic gone or AI no longer invited"
|
|
20558
19769
|
});
|
|
20559
|
-
} catch (
|
|
20560
|
-
logger.warn({ err
|
|
19770
|
+
} catch (err) {
|
|
19771
|
+
logger.warn({ err, topicId: inject.topicId }, "ai: deferred settlement hook failed");
|
|
20561
19772
|
}
|
|
20562
19773
|
if (inject.forkHandle)
|
|
20563
19774
|
cleanupAgentFork(inject.forkHandle);
|
|
@@ -20615,28 +19826,28 @@ async function clearPendingAskFile(pending, state) {
|
|
|
20615
19826
|
if (!pending.pendingAsk)
|
|
20616
19827
|
return;
|
|
20617
19828
|
try {
|
|
20618
|
-
|
|
19829
|
+
await init_session_asks();
|
|
20619
19830
|
if (state)
|
|
20620
|
-
|
|
20621
|
-
|
|
20622
|
-
} catch (
|
|
20623
|
-
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");
|
|
20624
19835
|
}
|
|
20625
19836
|
}
|
|
20626
19837
|
async function markPendingAskFile(pending, state) {
|
|
20627
19838
|
if (!pending.pendingAsk)
|
|
20628
19839
|
return;
|
|
20629
19840
|
try {
|
|
20630
|
-
|
|
20631
|
-
|
|
20632
|
-
} catch (
|
|
20633
|
-
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");
|
|
20634
19845
|
}
|
|
20635
19846
|
}
|
|
20636
19847
|
async function deliverAskCallbackToCaller(pending, sourceLabel, body, kind, options = {}) {
|
|
20637
19848
|
if (pending.remoteReply) {
|
|
20638
|
-
|
|
20639
|
-
const delivered = await
|
|
19849
|
+
await init_peer_forward();
|
|
19850
|
+
const delivered = await deliverPeerReply(pending.remoteReply, sourceLabel, body, kind);
|
|
20640
19851
|
if (delivered)
|
|
20641
19852
|
options.onRecorded?.();
|
|
20642
19853
|
return delivered;
|
|
@@ -20656,8 +19867,8 @@ ${body}`;
|
|
|
20656
19867
|
record(undefined);
|
|
20657
19868
|
await clearPendingAskFile(pending);
|
|
20658
19869
|
return true;
|
|
20659
|
-
} catch (
|
|
20660
|
-
logger.warn({ err
|
|
19870
|
+
} catch (err) {
|
|
19871
|
+
logger.warn({ err, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback direct delivery failed");
|
|
20661
19872
|
return false;
|
|
20662
19873
|
}
|
|
20663
19874
|
}
|
|
@@ -20686,9 +19897,9 @@ ${body}`;
|
|
|
20686
19897
|
if (queued) {
|
|
20687
19898
|
try {
|
|
20688
19899
|
record(callerTopic.agent);
|
|
20689
|
-
} catch (
|
|
19900
|
+
} catch (err) {
|
|
20690
19901
|
interSessionQueue.remove(pending.callerTopicId, pending.requestId);
|
|
20691
|
-
logger.warn({ err
|
|
19902
|
+
logger.warn({ err, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback record failed after enqueue; queue entry withdrawn");
|
|
20692
19903
|
return false;
|
|
20693
19904
|
}
|
|
20694
19905
|
await markPendingAskFile(pending, "queued_for_caller");
|
|
@@ -20708,8 +19919,8 @@ ${body}`;
|
|
|
20708
19919
|
}
|
|
20709
19920
|
async function deliverAskError(queryId, sourceLabel, error) {
|
|
20710
19921
|
try {
|
|
20711
|
-
|
|
20712
|
-
const pending =
|
|
19922
|
+
await init_ask_callbacks();
|
|
19923
|
+
const pending = resolveAskCallback(queryId);
|
|
20713
19924
|
if (pending) {
|
|
20714
19925
|
const prefix = pending.timedOut ? `\u26A0\uFE0F [Timeout - error notification was dropped]
|
|
20715
19926
|
|
|
@@ -20739,9 +19950,9 @@ function tryReconstructTopicRollout(opts) {
|
|
|
20739
19950
|
entries: entries.length
|
|
20740
19951
|
}, sessionId ? "ai: session expired \u2014 rollout reconstructed from unified log" : "ai: provider session bridged from shared conversation log");
|
|
20741
19952
|
return { kind: "rebuilt", sessionId: result.sessionId };
|
|
20742
|
-
} catch (
|
|
20743
|
-
logger.warn({ err
|
|
20744
|
-
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) };
|
|
20745
19956
|
}
|
|
20746
19957
|
}
|
|
20747
19958
|
function resolveSessionRetry(opts) {
|
|
@@ -20850,8 +20061,8 @@ function waitToStartRemoteUserTurn(params, queryId, options) {
|
|
|
20850
20061
|
function announceQueuedUserTurn(params, queryId) {
|
|
20851
20062
|
try {
|
|
20852
20063
|
params.onDispatched?.(queryId);
|
|
20853
|
-
} catch (
|
|
20854
|
-
logger.warn({ err
|
|
20064
|
+
} catch (err) {
|
|
20065
|
+
logger.warn({ err, topicId: params.topic.id, queryId }, "ai: queued dispatch hook failed");
|
|
20855
20066
|
}
|
|
20856
20067
|
if (!params.silent)
|
|
20857
20068
|
WsHub.get().broadcastAiActive(params.topic.id, queryId);
|
|
@@ -20872,81 +20083,6 @@ function waitToDrainRemoteInject(topicId) {
|
|
|
20872
20083
|
timer.unref?.();
|
|
20873
20084
|
remoteInjectWaiters.set(topicId, timer);
|
|
20874
20085
|
}
|
|
20875
|
-
async function drainOneDurableUserTurn() {
|
|
20876
|
-
if (durableTurnWorkerBusy)
|
|
20877
|
-
return;
|
|
20878
|
-
durableTurnWorkerBusy = true;
|
|
20879
|
-
try {
|
|
20880
|
-
const request = claimNextRuntimeUserTurnRequest(RUNTIME_INSTANCE_ID);
|
|
20881
|
-
if (!request)
|
|
20882
|
-
return;
|
|
20883
|
-
const topic = getTopic(request.topicId);
|
|
20884
|
-
if (!topic?.agent) {
|
|
20885
|
-
completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20886
|
-
return;
|
|
20887
|
-
}
|
|
20888
|
-
const execution = request.execution;
|
|
20889
|
-
const queryId = startAiTurn({
|
|
20890
|
-
topic,
|
|
20891
|
-
userId: request.userId,
|
|
20892
|
-
actorUserId: execution?.actorUserId,
|
|
20893
|
-
actorTopicScope: actorTopicScopeFrom(execution?.actorTopicScope),
|
|
20894
|
-
remoteSession: remoteSessionGrantFrom(execution?.remoteSession),
|
|
20895
|
-
vaultUserId: execution?.vaultUserId,
|
|
20896
|
-
prompt: request.prompt,
|
|
20897
|
-
_userMessages: request.userMessages,
|
|
20898
|
-
_conversationPrompts: execution?.conversationPrompts ?? [request.prompt],
|
|
20899
|
-
_loggedUserMessageCount: execution?.loggedUserMessageCount ?? Math.max(0, request.userMessages.length - (execution?.conversationPrompts?.length ?? 1)),
|
|
20900
|
-
_durableRequestIds: [request.requestId],
|
|
20901
|
-
attachments: request.attachments,
|
|
20902
|
-
allowAutoContinue: request.allowAutoContinue,
|
|
20903
|
-
origin: "user",
|
|
20904
|
-
requestId: execution?.sourceRequestId,
|
|
20905
|
-
agentOverride: execution?.agentOverride,
|
|
20906
|
-
modelOverride: execution?.modelOverride,
|
|
20907
|
-
effortOverride: execution?.effortOverride,
|
|
20908
|
-
...execution?.sessionIdSpecified ? { sessionId: execution.sessionId } : {},
|
|
20909
|
-
sessionScope: execution?.sessionScope,
|
|
20910
|
-
cwd: execution?.cwd,
|
|
20911
|
-
sessionName: execution?.sessionName,
|
|
20912
|
-
sessionType: execution?.sessionType,
|
|
20913
|
-
visualTools: execution?.visualTools,
|
|
20914
|
-
fileDeliveryTools: execution?.fileDeliveryTools,
|
|
20915
|
-
silent: execution?.silent,
|
|
20916
|
-
bridgeSessionFromHistory: execution?.bridgeSessionFromHistory,
|
|
20917
|
-
peerBridge: execution?.peerBridge,
|
|
20918
|
-
from: execution?.from,
|
|
20919
|
-
threadRootId: execution?.threadRootId,
|
|
20920
|
-
_queryId: request.requestId,
|
|
20921
|
-
_runtimeEpoch: execution?.runtimeEpoch ?? request.topicEpoch,
|
|
20922
|
-
onSettled: () => {
|
|
20923
|
-
completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20924
|
-
}
|
|
20925
|
-
});
|
|
20926
|
-
if (!queryId) {
|
|
20927
|
-
releaseRuntimeUserTurnClaim(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20928
|
-
return;
|
|
20929
|
-
}
|
|
20930
|
-
markRuntimeUserTurnRunning(request.topicId, request.requestId, RUNTIME_INSTANCE_ID, queryId);
|
|
20931
|
-
} finally {
|
|
20932
|
-
durableTurnWorkerBusy = false;
|
|
20933
|
-
}
|
|
20934
|
-
}
|
|
20935
|
-
function startDurableTurnRequestWorker() {
|
|
20936
|
-
if (durableTurnWorker)
|
|
20937
|
-
return () => {};
|
|
20938
|
-
durableTurnWorker = setInterval(() => {
|
|
20939
|
-
drainOneDurableUserTurn();
|
|
20940
|
-
}, 100);
|
|
20941
|
-
durableTurnWorker.unref?.();
|
|
20942
|
-
drainOneDurableUserTurn();
|
|
20943
|
-
return () => {
|
|
20944
|
-
if (!durableTurnWorker)
|
|
20945
|
-
return;
|
|
20946
|
-
clearInterval(durableTurnWorker);
|
|
20947
|
-
durableTurnWorker = null;
|
|
20948
|
-
};
|
|
20949
|
-
}
|
|
20950
20086
|
function startAiTurn(params) {
|
|
20951
20087
|
const storedTopic = getTopic(params.topic.id);
|
|
20952
20088
|
if (!storedTopic || !storedTopic.agent && !params.agentOverride) {
|
|
@@ -20958,8 +20094,8 @@ function startAiTurn(params) {
|
|
|
20958
20094
|
kind: "error",
|
|
20959
20095
|
error: storedTopic ? "topic no longer has an AI agent" : "topic no longer exists"
|
|
20960
20096
|
});
|
|
20961
|
-
} catch (
|
|
20962
|
-
logger.warn({ err
|
|
20097
|
+
} catch (err) {
|
|
20098
|
+
logger.warn({ err, topicId: params.topic.id }, "ai: rejected-turn settlement hook failed");
|
|
20963
20099
|
}
|
|
20964
20100
|
return null;
|
|
20965
20101
|
}
|
|
@@ -21015,7 +20151,7 @@ function startAiTurn(params) {
|
|
|
21015
20151
|
const askReplySources = params.askReplySources;
|
|
21016
20152
|
const sessionRetried = params._sessionRetried === true;
|
|
21017
20153
|
const emptyResponseRetried = params._emptyResponseRetried === true;
|
|
21018
|
-
const queryId = asTurnId(params._queryId ??
|
|
20154
|
+
const queryId = asTurnId(params._queryId ?? randomUUID18());
|
|
21019
20155
|
const roomId = turnConcurrency === "isolated" ? isolatedTurnRoomId(topicId, queryId) : asTurnSlotKey(topicId);
|
|
21020
20156
|
const currentRuntimeEpoch = getRuntimeTopicEpoch(topic.id);
|
|
21021
20157
|
const runtimeEpoch = params._runtimeEpoch ?? currentRuntimeEpoch;
|
|
@@ -21027,8 +20163,8 @@ function startAiTurn(params) {
|
|
|
21027
20163
|
}
|
|
21028
20164
|
try {
|
|
21029
20165
|
params.onSettled?.({ queryId, kind: "aborted", abortReason: "external" /* External */ });
|
|
21030
|
-
} catch (
|
|
21031
|
-
logger.warn({ err
|
|
20166
|
+
} catch (err) {
|
|
20167
|
+
logger.warn({ err, topicId: topic.id, queryId }, "ai: stale-turn settlement hook failed");
|
|
21032
20168
|
}
|
|
21033
20169
|
logger.info({ topicId: topic.id, queryId, queuedEpoch: params._runtimeEpoch, currentRuntimeEpoch }, "ai: dropped work queued before topic reset");
|
|
21034
20170
|
return null;
|
|
@@ -21078,8 +20214,8 @@ function startAiTurn(params) {
|
|
|
21078
20214
|
cleanupAgentFork(forkHandle);
|
|
21079
20215
|
try {
|
|
21080
20216
|
onSettled?.({ queryId: "", kind: "error", error });
|
|
21081
|
-
} catch (
|
|
21082
|
-
logger.warn({ err
|
|
20217
|
+
} catch (err) {
|
|
20218
|
+
logger.warn({ err, topicId, queryId }, "ai: isolated-turn rejection hook failed");
|
|
21083
20219
|
}
|
|
21084
20220
|
return null;
|
|
21085
20221
|
};
|
|
@@ -21126,7 +20262,7 @@ function startAiTurn(params) {
|
|
|
21126
20262
|
if (decision.action === "abort-replace") {
|
|
21127
20263
|
const running = decision.running;
|
|
21128
20264
|
if (isUserOrigin(running.origin) && !sameTurnActor(running.actorUserId, params.actorUserId)) {
|
|
21129
|
-
const
|
|
20265
|
+
const queuedQueryId = waitToStartRemoteUserTurn({
|
|
21130
20266
|
...params,
|
|
21131
20267
|
topic,
|
|
21132
20268
|
prompt,
|
|
@@ -21138,9 +20274,9 @@ function startAiTurn(params) {
|
|
|
21138
20274
|
_durableRequestIds: durableRequestIds,
|
|
21139
20275
|
_runtimeEpoch: runtimeEpoch
|
|
21140
20276
|
}, queryId);
|
|
21141
|
-
announceQueuedUserTurn({ ...params, topic },
|
|
21142
|
-
logger.info({ topicId, queryId:
|
|
21143
|
-
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;
|
|
21144
20280
|
}
|
|
21145
20281
|
let omitRequestIds;
|
|
21146
20282
|
if (isUserOrigin(running.origin)) {
|
|
@@ -21272,14 +20408,14 @@ function startAiTurn(params) {
|
|
|
21272
20408
|
if (turnConcurrency === "topic") {
|
|
21273
20409
|
try {
|
|
21274
20410
|
writeQueryState(userId, topic.id, topic.title, prompt);
|
|
21275
|
-
} catch (
|
|
21276
|
-
logger.warn({ err
|
|
20411
|
+
} catch (err) {
|
|
20412
|
+
logger.warn({ err, topicId, userId }, "ai: failed to write active query state");
|
|
21277
20413
|
}
|
|
21278
20414
|
}
|
|
21279
20415
|
try {
|
|
21280
20416
|
onDispatched?.(queryId);
|
|
21281
|
-
} catch (
|
|
21282
|
-
logger.warn({ err
|
|
20417
|
+
} catch (err) {
|
|
20418
|
+
logger.warn({ err, topicId, queryId }, "ai: dispatch hook failed");
|
|
21283
20419
|
}
|
|
21284
20420
|
const override = getTopicConfig(topicId);
|
|
21285
20421
|
const agentKind = execution.agent;
|
|
@@ -21306,8 +20442,8 @@ function startAiTurn(params) {
|
|
|
21306
20442
|
control.injectParams.sessionId = bridge.sessionId;
|
|
21307
20443
|
try {
|
|
21308
20444
|
onSessionId?.(bridge.sessionId);
|
|
21309
|
-
} catch (
|
|
21310
|
-
logger.warn({ err
|
|
20445
|
+
} catch (err) {
|
|
20446
|
+
logger.warn({ err, topicId, queryId, agent: agentKind }, "ai: isolated session owner rejected bridged provider session id");
|
|
21311
20447
|
}
|
|
21312
20448
|
} else if (bridge.kind === "failed") {
|
|
21313
20449
|
historyBridgeError = "Conversation history could not be encoded into a provider session; no fresh session was started.";
|
|
@@ -21376,8 +20512,8 @@ function startAiTurn(params) {
|
|
|
21376
20512
|
const wikiDir = getSharedWikiDir();
|
|
21377
20513
|
const { latestSummaryFile } = resolveWikiMemoryMirror(wikiDir, memoryTopic.id, memoryTitle);
|
|
21378
20514
|
hasMemoryArchive = Boolean(resolvedBrief?.brief.latestSummaryMd || latestSummaryFile);
|
|
21379
|
-
} catch (
|
|
21380
|
-
logger.warn({ topicId, err
|
|
20515
|
+
} catch (err) {
|
|
20516
|
+
logger.warn({ topicId, err }, "ai: failed to inject topic brief");
|
|
21381
20517
|
}
|
|
21382
20518
|
systemPrompt += buildMemoryPromptSection({
|
|
21383
20519
|
topicTitle: topic.title,
|
|
@@ -21453,8 +20589,8 @@ function startAiTurn(params) {
|
|
|
21453
20589
|
control.injectParams.sessionId = prepared.forkId;
|
|
21454
20590
|
control.injectParams.forkHandle = prepared;
|
|
21455
20591
|
}
|
|
21456
|
-
} catch (
|
|
21457
|
-
throw new Error(`failed to prepare isolated session: ${stringifyError(
|
|
20592
|
+
} catch (err) {
|
|
20593
|
+
throw new Error(`failed to prepare isolated session: ${stringifyError(err)}`);
|
|
21458
20594
|
}
|
|
21459
20595
|
if (abortController.signal.aborted)
|
|
21460
20596
|
return;
|
|
@@ -21473,8 +20609,8 @@ function startAiTurn(params) {
|
|
|
21473
20609
|
throw new Error("browser MCP capability was not registered");
|
|
21474
20610
|
}
|
|
21475
20611
|
trackPlaywrightTurn(playwrightInstanceKey, control);
|
|
21476
|
-
} catch (
|
|
21477
|
-
logger.warn({ topicId, err
|
|
20612
|
+
} catch (err) {
|
|
20613
|
+
logger.warn({ topicId, err }, "ai: ensurePlaywright failed \u2014 proceeding without browser tools");
|
|
21478
20614
|
markPlaywrightUnavailable({
|
|
21479
20615
|
userId,
|
|
21480
20616
|
topic: topic.title,
|
|
@@ -21487,8 +20623,8 @@ function startAiTurn(params) {
|
|
|
21487
20623
|
if (wantsBgBash) {
|
|
21488
20624
|
try {
|
|
21489
20625
|
bgBashPort = await ensureBgBash(userId, topic.id);
|
|
21490
|
-
} catch (
|
|
21491
|
-
logger.warn({ topicId, err
|
|
20626
|
+
} catch (err) {
|
|
20627
|
+
logger.warn({ topicId, err }, "ai: ensureBgBash failed \u2014 proceeding without background bash tools");
|
|
21492
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>");
|
|
21493
20629
|
}
|
|
21494
20630
|
}
|
|
@@ -21701,8 +20837,8 @@ function startAiTurn(params) {
|
|
|
21701
20837
|
await settleSubagentFailure(queryId, error);
|
|
21702
20838
|
try {
|
|
21703
20839
|
onSettled?.({ queryId, kind: "error", error });
|
|
21704
|
-
} catch (
|
|
21705
|
-
logger.warn({ err
|
|
20840
|
+
} catch (err) {
|
|
20841
|
+
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21706
20842
|
}
|
|
21707
20843
|
return;
|
|
21708
20844
|
}
|
|
@@ -21718,8 +20854,8 @@ function startAiTurn(params) {
|
|
|
21718
20854
|
await settleSubagentFailure(queryId, classifyAgentError(outcome.error, agentKind));
|
|
21719
20855
|
try {
|
|
21720
20856
|
onSettled?.({ queryId, kind: "error", error: outcome.error });
|
|
21721
|
-
} catch (
|
|
21722
|
-
logger.warn({ err
|
|
20857
|
+
} catch (err) {
|
|
20858
|
+
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21723
20859
|
}
|
|
21724
20860
|
return;
|
|
21725
20861
|
}
|
|
@@ -21732,12 +20868,12 @@ function startAiTurn(params) {
|
|
|
21732
20868
|
kind: outcome.kind === "aborted" ? "aborted" : "completed",
|
|
21733
20869
|
...outcome.kind === "aborted" ? { abortReason: control.abortReason } : {}
|
|
21734
20870
|
});
|
|
21735
|
-
} catch (
|
|
21736
|
-
logger.warn({ err
|
|
20871
|
+
} catch (err) {
|
|
20872
|
+
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21737
20873
|
}
|
|
21738
|
-
}).catch(async (
|
|
21739
|
-
const error =
|
|
21740
|
-
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");
|
|
21741
20877
|
if (!silent) {
|
|
21742
20878
|
WsHub.get().broadcastError(topicId, queryId, error);
|
|
21743
20879
|
WsHub.get().broadcastTopicNotice(topicId, "error", "\uC751\uB2F5 \uC2E4\uD328");
|
|
@@ -21786,7 +20922,7 @@ function triggerTopicAiTurn(topicId, userId, prompt, agentType, opts) {
|
|
|
21786
20922
|
if (!opts?.silent && !opts?.hideInjectMessage) {
|
|
21787
20923
|
const now = new Date().toISOString();
|
|
21788
20924
|
const injectMsg = {
|
|
21789
|
-
id: opts?.requestId ? `tell-${opts.requestId}` : `tell-${
|
|
20925
|
+
id: opts?.requestId ? `tell-${opts.requestId}` : `tell-${randomUUID18()}`,
|
|
21790
20926
|
topicId,
|
|
21791
20927
|
authorId: opts?.injectAuthorId ?? userId,
|
|
21792
20928
|
sourceAdapter: opts?.injectSourceAdapter,
|
|
@@ -21843,7 +20979,7 @@ function triggerTopicAiTurn(topicId, userId, prompt, agentType, opts) {
|
|
|
21843
20979
|
from: opts?.from
|
|
21844
20980
|
});
|
|
21845
20981
|
}
|
|
21846
|
-
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;
|
|
21847
20983
|
var init_turn_runner = __esm(async () => {
|
|
21848
20984
|
init_manager();
|
|
21849
20985
|
init_constants();
|
|
@@ -21974,29 +21110,29 @@ function createSubagentLifecycle(host) {
|
|
|
21974
21110
|
}
|
|
21975
21111
|
function computeSubagentDepth(topicId) {
|
|
21976
21112
|
let depth = 0;
|
|
21977
|
-
let
|
|
21113
|
+
let current = host.storage.getTopic(topicId);
|
|
21978
21114
|
const visited = new Set;
|
|
21979
|
-
while (
|
|
21980
|
-
if (visited.has(
|
|
21115
|
+
while (current) {
|
|
21116
|
+
if (visited.has(current.id))
|
|
21981
21117
|
return limits.maxDepth;
|
|
21982
|
-
visited.add(
|
|
21983
|
-
if (
|
|
21118
|
+
visited.add(current.id);
|
|
21119
|
+
if (current.isSubagent)
|
|
21984
21120
|
depth += 1;
|
|
21985
|
-
if (!
|
|
21121
|
+
if (!current.parentTopicId || current.parentTopicId === current.id)
|
|
21986
21122
|
break;
|
|
21987
|
-
|
|
21123
|
+
current = host.storage.getTopic(current.parentTopicId);
|
|
21988
21124
|
}
|
|
21989
21125
|
return depth;
|
|
21990
21126
|
}
|
|
21991
|
-
function
|
|
21127
|
+
function canSpawnSubagentsFromTopic(topicId) {
|
|
21992
21128
|
const topic = host.storage.getTopic(topicId);
|
|
21993
21129
|
return topic?.kind === "agent" && computeSubagentDepth(topicId) < limits.maxDepth;
|
|
21994
21130
|
}
|
|
21995
21131
|
function patchSubagentCard(parentTopicId, cardMessageId, patch) {
|
|
21996
|
-
const
|
|
21997
|
-
if (!
|
|
21132
|
+
const current = host.storage.getMessage(parentTopicId, cardMessageId)?.subagentCard;
|
|
21133
|
+
if (!current)
|
|
21998
21134
|
return;
|
|
21999
|
-
const next = { ...
|
|
21135
|
+
const next = { ...current, ...patch };
|
|
22000
21136
|
const editedAt = host.runtime.now();
|
|
22001
21137
|
if (!host.storage.updateSubagentCard(parentTopicId, cardMessageId, next, editedAt))
|
|
22002
21138
|
return;
|
|
@@ -22016,7 +21152,7 @@ function createSubagentLifecycle(host) {
|
|
|
22016
21152
|
patchSubagentCard(watch.parentTopicId, watch.cardMessageId, { status: "running" });
|
|
22017
21153
|
}
|
|
22018
21154
|
}
|
|
22019
|
-
function
|
|
21155
|
+
function takeSubagentWatch(queryId) {
|
|
22020
21156
|
const childTopicId = childByQueryId.get(queryId);
|
|
22021
21157
|
if (!childTopicId)
|
|
22022
21158
|
return recoverPersistedSubagentWatch(queryId);
|
|
@@ -22060,7 +21196,7 @@ function createSubagentLifecycle(host) {
|
|
|
22060
21196
|
if (watch.queryId)
|
|
22061
21197
|
childByQueryId.delete(watch.queryId);
|
|
22062
21198
|
}
|
|
22063
|
-
function
|
|
21199
|
+
function cancelSubagentWatchForDeletedTopic(childTopicId) {
|
|
22064
21200
|
const watch = watchesByChild.get(childTopicId);
|
|
22065
21201
|
if (!watch)
|
|
22066
21202
|
return;
|
|
@@ -22090,8 +21226,8 @@ function createSubagentLifecycle(host) {
|
|
|
22090
21226
|
if (!await host.sessionCommunication.notifyParent({ watch, prompt, requestId })) {
|
|
22091
21227
|
appendParentSystemNote(watch, prompt);
|
|
22092
21228
|
}
|
|
22093
|
-
} catch (
|
|
22094
|
-
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");
|
|
22095
21231
|
try {
|
|
22096
21232
|
appendParentSystemNote(watch, prompt);
|
|
22097
21233
|
} catch (fallbackErr) {
|
|
@@ -22103,7 +21239,7 @@ function createSubagentLifecycle(host) {
|
|
|
22103
21239
|
}
|
|
22104
21240
|
}
|
|
22105
21241
|
}
|
|
22106
|
-
async function
|
|
21242
|
+
async function settleSubagentSuccess(watch, finalText) {
|
|
22107
21243
|
const summary = finalText.replace(/\s+/g, " ").trim().slice(0, RESULT_SUMMARY_CHARS);
|
|
22108
21244
|
try {
|
|
22109
21245
|
patchSubagentCard(watch.parentTopicId, watch.cardMessageId, {
|
|
@@ -22111,8 +21247,8 @@ function createSubagentLifecycle(host) {
|
|
|
22111
21247
|
resultSummary: summary || "(no text response)",
|
|
22112
21248
|
finishedAt: host.runtime.now()
|
|
22113
21249
|
});
|
|
22114
|
-
} catch (
|
|
22115
|
-
logger.warn({ err
|
|
21250
|
+
} catch (err) {
|
|
21251
|
+
logger.warn({ err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: completed-card update failed");
|
|
22116
21252
|
}
|
|
22117
21253
|
if (watch.reportMode === "auto") {
|
|
22118
21254
|
await notifyParent(watch, `[Subagent completed \u2190 ${watch.name}]
|
|
@@ -22121,8 +21257,8 @@ function createSubagentLifecycle(host) {
|
|
|
22121
21257
|
${finalText || "(no text response)"}`, "done");
|
|
22122
21258
|
}
|
|
22123
21259
|
}
|
|
22124
|
-
async function
|
|
22125
|
-
const watch =
|
|
21260
|
+
async function settleSubagentFailure(queryId, reason) {
|
|
21261
|
+
const watch = takeSubagentWatch(queryId);
|
|
22126
21262
|
if (!watch)
|
|
22127
21263
|
return;
|
|
22128
21264
|
try {
|
|
@@ -22131,8 +21267,8 @@ ${finalText || "(no text response)"}`, "done");
|
|
|
22131
21267
|
errorMessage: reason,
|
|
22132
21268
|
finishedAt: host.runtime.now()
|
|
22133
21269
|
});
|
|
22134
|
-
} catch (
|
|
22135
|
-
logger.warn({ err
|
|
21270
|
+
} catch (err) {
|
|
21271
|
+
logger.warn({ err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: failed-card update failed");
|
|
22136
21272
|
}
|
|
22137
21273
|
if (watch.reportMode === "auto") {
|
|
22138
21274
|
await notifyParent(watch, `[Subagent failed \u2190 ${watch.name}]
|
|
@@ -22169,7 +21305,7 @@ spawn_subagent\uB85C \uC704\uC784\uD55C \uC791\uC5C5\uC774 \uC2E4\uD328\uD588\uC
|
|
|
22169
21305
|
function findSubagentCardMessage(childTopicId) {
|
|
22170
21306
|
return host.storage.listSubagentMessages().filter((message) => message.subagentCard?.subagentTopicId === childTopicId).at(-1);
|
|
22171
21307
|
}
|
|
22172
|
-
function
|
|
21308
|
+
function subagentReportMode(childTopicId) {
|
|
22173
21309
|
return host.storage.getTopic(childTopicId)?.subagentReportMode ?? findSubagentCardMessage(childTopicId)?.subagentCard?.reportMode ?? "auto";
|
|
22174
21310
|
}
|
|
22175
21311
|
async function startSubagentCard(ctx, cardMessage) {
|
|
@@ -22377,7 +21513,7 @@ ${card.task}${reportInstruction}`;
|
|
|
22377
21513
|
for (const siblings of byParent.values()) {
|
|
22378
21514
|
siblings.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
22379
21515
|
}
|
|
22380
|
-
const
|
|
21516
|
+
const descendants = [];
|
|
22381
21517
|
const visited = new Set([ctx.topicId]);
|
|
22382
21518
|
const visit = (parentId) => {
|
|
22383
21519
|
for (const child of byParent.get(parentId) ?? []) {
|
|
@@ -22387,12 +21523,12 @@ ${card.task}${reportInstruction}`;
|
|
|
22387
21523
|
if (!child.participants.some((participant) => participant.userId === rootOwnerId && participant.role === "owner")) {
|
|
22388
21524
|
continue;
|
|
22389
21525
|
}
|
|
22390
|
-
|
|
21526
|
+
descendants.push(child);
|
|
22391
21527
|
visit(child.id);
|
|
22392
21528
|
}
|
|
22393
21529
|
};
|
|
22394
21530
|
visit(ctx.topicId);
|
|
22395
|
-
return
|
|
21531
|
+
return descendants;
|
|
22396
21532
|
})() : [];
|
|
22397
21533
|
const children = actorScope ? descendants.filter((child) => actorScope.visible.has(child.id)) : descendants;
|
|
22398
21534
|
return {
|
|
@@ -22416,10 +21552,10 @@ ${card.task}${reportInstruction}`;
|
|
|
22416
21552
|
return card?.status ?? "unknown";
|
|
22417
21553
|
}
|
|
22418
21554
|
function listMemoryTopicNames(ctx) {
|
|
22419
|
-
const
|
|
22420
|
-
if (!
|
|
21555
|
+
const current = host.storage.getTopic(ctx.topicId);
|
|
21556
|
+
if (!current)
|
|
22421
21557
|
return { error: `Error: topic '${ctx.topicId}' not found.` };
|
|
22422
|
-
if (!
|
|
21558
|
+
if (!current.participants.some((participant) => participant.userId === ctx.userId)) {
|
|
22423
21559
|
return { error: "Error: user is not a member of this topic." };
|
|
22424
21560
|
}
|
|
22425
21561
|
const sources = new Map;
|
|
@@ -22509,8 +21645,8 @@ ${card.task}${reportInstruction}`;
|
|
|
22509
21645
|
try {
|
|
22510
21646
|
await host.topic.delete(child, ctx.userId);
|
|
22511
21647
|
return textResult(`Subagent deleted: ${child.title} (${child.id})`);
|
|
22512
|
-
} catch (
|
|
22513
|
-
const message =
|
|
21648
|
+
} catch (err) {
|
|
21649
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
22514
21650
|
return errorResult(`Error: failed to delete subagent '${child.title}': ${message}`);
|
|
22515
21651
|
}
|
|
22516
21652
|
}
|
|
@@ -22607,13 +21743,13 @@ ${card.task}${reportInstruction}`;
|
|
|
22607
21743
|
}
|
|
22608
21744
|
return {
|
|
22609
21745
|
computeSubagentDepth,
|
|
22610
|
-
canSpawnSubagentsFromTopic
|
|
22611
|
-
takeSubagentWatch
|
|
22612
|
-
cancelSubagentWatchForDeletedTopic
|
|
22613
|
-
settleSubagentSuccess
|
|
22614
|
-
settleSubagentFailure
|
|
21746
|
+
canSpawnSubagentsFromTopic,
|
|
21747
|
+
takeSubagentWatch,
|
|
21748
|
+
cancelSubagentWatchForDeletedTopic,
|
|
21749
|
+
settleSubagentSuccess,
|
|
21750
|
+
settleSubagentFailure,
|
|
22615
21751
|
sweepStaleSubagentCards,
|
|
22616
|
-
subagentReportMode
|
|
21752
|
+
subagentReportMode,
|
|
22617
21753
|
createSubagentManagementToolDefinitions,
|
|
22618
21754
|
createSpawnSubagentToolDefinition,
|
|
22619
21755
|
createPrepareSubagentToolDefinition
|
|
@@ -22660,9 +21796,9 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22660
21796
|
},
|
|
22661
21797
|
topic: {
|
|
22662
21798
|
async createDerived(input) {
|
|
22663
|
-
|
|
21799
|
+
await init_derive();
|
|
22664
21800
|
try {
|
|
22665
|
-
const topic = await
|
|
21801
|
+
const topic = await createDerivedTopic(input.parentTopicId, input.userId, false, {
|
|
22666
21802
|
name: input.name,
|
|
22667
21803
|
subagent: {
|
|
22668
21804
|
agent: input.agent,
|
|
@@ -22672,30 +21808,30 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22672
21808
|
});
|
|
22673
21809
|
return { ok: true, topic };
|
|
22674
21810
|
} catch (error) {
|
|
22675
|
-
if (error instanceof
|
|
21811
|
+
if (error instanceof TopicTitleConflictError) {
|
|
22676
21812
|
return { ok: false, reason: "title-conflict", message: error.message };
|
|
22677
21813
|
}
|
|
22678
|
-
if (error instanceof
|
|
21814
|
+
if (error instanceof TopicDeriveBusyError)
|
|
22679
21815
|
return { ok: false, reason: "busy" };
|
|
22680
21816
|
throw error;
|
|
22681
21817
|
}
|
|
22682
21818
|
},
|
|
22683
21819
|
async delete(topic, userId) {
|
|
22684
|
-
|
|
22685
|
-
await
|
|
21820
|
+
await init_lifecycle();
|
|
21821
|
+
await deleteTopicCascade(topic, userId);
|
|
22686
21822
|
}
|
|
22687
21823
|
},
|
|
22688
21824
|
task: {
|
|
22689
21825
|
async dispatch(input) {
|
|
22690
|
-
|
|
22691
|
-
|
|
22692
|
-
const queryId =
|
|
21826
|
+
await init_turn_runner();
|
|
21827
|
+
await init_active_rooms();
|
|
21828
|
+
const queryId = triggerTopicAiTurn(input.child.id, input.userId, input.prompt, undefined, {
|
|
22693
21829
|
origin: `subagent-task:${input.parent.title}`,
|
|
22694
21830
|
requestId: input.requestId,
|
|
22695
21831
|
injectAuthorId: "ai",
|
|
22696
21832
|
onDispatched: input.onDispatched
|
|
22697
21833
|
});
|
|
22698
|
-
return { accepted: Boolean(queryId ||
|
|
21834
|
+
return { accepted: Boolean(queryId || getRoomQuery(input.child.id)) };
|
|
22699
21835
|
}
|
|
22700
21836
|
},
|
|
22701
21837
|
sessionCommunication: {
|
|
@@ -22703,16 +21839,16 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22703
21839
|
const parent = getTopic(watch.parentTopicId);
|
|
22704
21840
|
if (!parent)
|
|
22705
21841
|
return true;
|
|
22706
|
-
|
|
22707
|
-
const queryId = parent.agent ?
|
|
21842
|
+
await init_turn_runner();
|
|
21843
|
+
const queryId = parent.agent ? triggerTopicAiTurn(watch.parentTopicId, watch.userId, prompt, undefined, {
|
|
22708
21844
|
origin: `subagent:${watch.name}`,
|
|
22709
21845
|
requestId,
|
|
22710
21846
|
hideInjectMessage: true
|
|
22711
21847
|
}) : null;
|
|
22712
21848
|
if (queryId)
|
|
22713
21849
|
return true;
|
|
22714
|
-
|
|
22715
|
-
return Boolean(parent.agent &&
|
|
21850
|
+
await init_active_rooms();
|
|
21851
|
+
return Boolean(parent.agent && interSessionQueue.hasRequest(parent.id, requestId));
|
|
22716
21852
|
},
|
|
22717
21853
|
listTellTargetIds: listSubagentTellTargetIds,
|
|
22718
21854
|
grantTellTarget: grantSubagentTellTarget,
|
|
@@ -22741,19 +21877,19 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
22741
21877
|
async resolveAgentModel({ context, agent, model, hasOverride }) {
|
|
22742
21878
|
let resolvedModel = model;
|
|
22743
21879
|
if (model) {
|
|
22744
|
-
|
|
22745
|
-
|
|
22746
|
-
const registry =
|
|
21880
|
+
await Promise.resolve().then(() => init_model_catalog());
|
|
21881
|
+
await init_registry();
|
|
21882
|
+
const registry = getRegistry(agent);
|
|
22747
21883
|
if (!registry.validateModel(model)) {
|
|
22748
21884
|
return { error: `Error: model '${model}' is not valid for agent '${agent}'.` };
|
|
22749
21885
|
}
|
|
22750
|
-
resolvedModel =
|
|
21886
|
+
resolvedModel = resolveModelForAgent(agent, model, registry);
|
|
22751
21887
|
}
|
|
22752
21888
|
if (hasOverride) {
|
|
22753
|
-
|
|
22754
|
-
|
|
22755
|
-
const targetModel = resolvedModel ??
|
|
22756
|
-
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);
|
|
22757
21893
|
if (!auth.ok) {
|
|
22758
21894
|
return { error: `Error: agent '${agent}' is not available: ${auth.error}` };
|
|
22759
21895
|
}
|
|
@@ -23183,11 +22319,11 @@ var DEFAULT_SELF_CONFIG_PRODUCT = {
|
|
|
23183
22319
|
derivedTopicLimit: SELF_CONFIG_DERIVED_TOPIC_LIMIT,
|
|
23184
22320
|
toolDescriptions: {}
|
|
23185
22321
|
};
|
|
23186
|
-
function ok(
|
|
23187
|
-
return { text
|
|
22322
|
+
function ok(text) {
|
|
22323
|
+
return { text };
|
|
23188
22324
|
}
|
|
23189
|
-
function err(
|
|
23190
|
-
return { text
|
|
22325
|
+
function err(text) {
|
|
22326
|
+
return { text, isError: true };
|
|
23191
22327
|
}
|
|
23192
22328
|
function errorMessage(error) {
|
|
23193
22329
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -23504,8 +22640,8 @@ var defaultSelfConfigHost = {
|
|
|
23504
22640
|
},
|
|
23505
22641
|
derivedTopics: {
|
|
23506
22642
|
async create(sourceTopicId, userId, copyHistory, options) {
|
|
23507
|
-
|
|
23508
|
-
return
|
|
22643
|
+
await init_derive();
|
|
22644
|
+
return createDerivedTopic(sourceTopicId, userId, copyHistory, options);
|
|
23509
22645
|
},
|
|
23510
22646
|
link: topicMarkdownLink,
|
|
23511
22647
|
isTitleConflict: (error) => error instanceof Error && error.name === "TopicTitleConflictError",
|
|
@@ -23785,58 +22921,58 @@ await __promiseAll([
|
|
|
23785
22921
|
init_topic_cleanup()
|
|
23786
22922
|
]);
|
|
23787
22923
|
export {
|
|
23788
|
-
|
|
23789
|
-
withCodexSpawnSerial,
|
|
23790
|
-
visualToolDefinitions,
|
|
23791
|
-
unregisterOwnedCodexPids,
|
|
23792
|
-
summarizeToolInput,
|
|
23793
|
-
summarizeShellCommand,
|
|
23794
|
-
summarizeDisplayText,
|
|
23795
|
-
snapshotCodexChildren,
|
|
23796
|
-
showPngTool,
|
|
23797
|
-
showMermaidTool,
|
|
23798
|
-
showImageTool,
|
|
23799
|
-
showHtmlTool,
|
|
23800
|
-
rotateTopicLogs,
|
|
23801
|
-
resolveTaskEventScope,
|
|
23802
|
-
registerOwnedCodexPids,
|
|
23803
|
-
purgeTopicLogs,
|
|
23804
|
-
otiumVisualToolDefinitions,
|
|
23805
|
-
normalizeAskUserQuestionInput,
|
|
23806
|
-
normalizeAskUserChoices,
|
|
23807
|
-
killOwnedCodexTreesForShutdown,
|
|
23808
|
-
killCodexTrees,
|
|
23809
|
-
isExplicitAgentSwitchTargets,
|
|
23810
|
-
hasExplicitAgentSwitchRequest,
|
|
23811
|
-
formatToolUse,
|
|
23812
|
-
forkAgentSession,
|
|
23813
|
-
findNewCodexChildren,
|
|
23814
|
-
explicitAgentSwitchTargets,
|
|
23815
|
-
defaultAskUserDurabilityHost,
|
|
23816
|
-
createTopicLogMaintenance,
|
|
23817
|
-
createSubagentLifecycle,
|
|
23818
|
-
createSelfConfigToolDefinitionsForCore,
|
|
23819
|
-
createSelfConfigRuntime,
|
|
23820
|
-
createSelfConfigCore,
|
|
23821
|
-
createPublishHtmlToolDefinitions,
|
|
23822
|
-
createCodexTreeManager,
|
|
23823
|
-
createAskUserRuntime,
|
|
23824
|
-
createArchiverRuntime,
|
|
23825
|
-
createAgentForkHelpers,
|
|
23826
|
-
cleanupTopicRolloutsFromEntries,
|
|
23827
|
-
cleanupTopicRollouts,
|
|
23828
|
-
cleanupAgentFork,
|
|
23829
|
-
classifyShellToolName,
|
|
23830
|
-
checkAgentModelAuth,
|
|
23831
|
-
checkAgentAuth,
|
|
23832
|
-
buildNumberedDiffSummary,
|
|
23833
|
-
archiveActiveTopicForMemory,
|
|
23834
|
-
applySelfConfigCapabilityFilter,
|
|
23835
|
-
acquireCodexSpawnLock,
|
|
23836
|
-
VISUALS_MCP_KEY,
|
|
23837
|
-
SELF_CONFIG_CAPABILITIES,
|
|
22924
|
+
DEFAULT_SELF_CONFIG_PRODUCT,
|
|
23838
22925
|
MIN_MEMORY_ARCHIVE_EXCHANGES,
|
|
23839
|
-
|
|
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
|
|
23840
22976
|
};
|
|
23841
22977
|
|
|
23842
|
-
//# debugId=
|
|
22978
|
+
//# debugId=D917583E369BC94464756E2164756E21
|