negotium 0.23.10 → 0.23.11
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 +1321 -396
- package/dist/agent-helpers.js.map +10 -10
- package/dist/background-bash.js +12 -12
- package/dist/background-bash.js.map +3 -3
- package/dist/browser-runtime.js +44 -42
- package/dist/browser-runtime.js.map +3 -3
- package/dist/canonical-mcp-bridge.js +9 -8
- package/dist/canonical-mcp-bridge.js.map +1 -1
- package/dist/{chunk-qvtj66y2.js → chunk-0fenxbe6.js} +5 -4
- package/dist/{chunk-qvtj66y2.js.map → chunk-0fenxbe6.js.map} +2 -2
- package/dist/chunk-2mx7fq49.js +6 -0
- package/dist/{chunk-22kg3fsw.js.map → chunk-2mx7fq49.js.map} +1 -1
- package/dist/chunk-ad7kxsaq.js +202 -0
- package/dist/chunk-ad7kxsaq.js.map +9 -0
- package/dist/{chunk-qd0vtfm2.js → chunk-da9ad838.js} +119 -115
- package/dist/{chunk-qd0vtfm2.js.map → chunk-da9ad838.js.map} +7 -7
- package/dist/{chunk-ww8a4ej4.js → chunk-f7p0h1gs.js} +5 -5
- package/dist/{chunk-ww8a4ej4.js.map → chunk-f7p0h1gs.js.map} +2 -2
- package/dist/{chunk-wf7ny8eq.js → chunk-jtv8yzy1.js} +12 -12
- package/dist/{chunk-wf7ny8eq.js.map → chunk-jtv8yzy1.js.map} +2 -2
- package/dist/{chunk-d4j77adx.js → chunk-mxxwx5mg.js} +135 -96
- package/dist/{chunk-d4j77adx.js.map → chunk-mxxwx5mg.js.map} +6 -6
- package/dist/hosted-agent.js +127 -123
- package/dist/hosted-agent.js.map +4 -4
- package/dist/main.js +4456 -3445
- package/dist/main.js.map +21 -21
- package/dist/mcp-catalog.js +4 -4
- package/dist/mcp-catalog.js.map +1 -1
- package/dist/mcp-factories.js +1587 -657
- package/dist/mcp-factories.js.map +11 -11
- 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 +2 -2
- package/dist/outbox.js +15 -15
- package/dist/outbox.js.map +2 -2
- package/dist/platform-runtime.js +7 -7
- package/dist/platform-runtime.js.map +1 -1
- package/dist/prompts.js +6 -6
- package/dist/prompts.js.map +3 -3
- package/dist/query-runtime.js +18 -16
- package/dist/query-runtime.js.map +3 -3
- package/dist/registry.js +20 -19
- package/dist/registry.js.map +2 -2
- package/dist/rollout.js +41 -41
- package/dist/rollout.js.map +2 -2
- package/dist/runtime/src/agents/archiver.ts +6 -0
- package/dist/runtime/src/agents/claude-provider.ts +5 -4
- package/dist/runtime/src/agents/idle-archiver.ts +1 -0
- package/dist/runtime/src/agents/index.ts +2 -1
- package/dist/runtime/src/mcp/wiki-server.ts +115 -64
- package/dist/runtime/src/prompts/agents/wiki-archiver.md +3 -0
- package/dist/runtime/src/runtime/turn-event-stream.ts +20 -3
- package/dist/runtime/src/topics/lifecycle.ts +1 -0
- package/dist/runtime/src/types.ts +8 -0
- 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 +54 -52
- package/dist/runtime-helpers.js.map +3 -3
- package/dist/sqlite.js +5 -3
- package/dist/sqlite.js.map +2 -2
- package/dist/storage.js +637 -666
- package/dist/storage.js.map +3 -3
- package/dist/types/packages/core/src/agents/archiver.d.ts +2 -0
- package/dist/types/packages/core/src/mcp/wiki-server.d.ts +16 -4
- package/dist/types/packages/core/src/types.d.ts +11 -0
- package/dist/types/packages/core/src/version.d.ts +1 -1
- package/dist/vault.js +22 -20
- package/dist/vault.js.map +3 -3
- package/package.json +1 -1
- package/dist/chunk-22kg3fsw.js +0 -79
package/dist/agent-helpers.js
CHANGED
|
@@ -13,18 +13,9 @@ var __export = (target, all) => {
|
|
|
13
13
|
set: __exportSetter.bind(all, name)
|
|
14
14
|
});
|
|
15
15
|
};
|
|
16
|
-
var __esm = (fn, res
|
|
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
|
-
};
|
|
16
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
27
17
|
var __promiseAll = (args) => Promise.all(args);
|
|
18
|
+
var __require = import.meta.require;
|
|
28
19
|
|
|
29
20
|
// ../../packages/core/src/platform/paths.ts
|
|
30
21
|
import { existsSync, realpathSync } from "fs";
|
|
@@ -193,6 +184,106 @@ var init_logger = __esm(() => {
|
|
|
193
184
|
});
|
|
194
185
|
|
|
195
186
|
// ../../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
|
+
});
|
|
196
287
|
import { execFileSync } from "child_process";
|
|
197
288
|
import { randomBytes } from "crypto";
|
|
198
289
|
import {
|
|
@@ -342,6 +433,9 @@ function safeWorkspaceSegment(value, fallback) {
|
|
|
342
433
|
function resolveTopicWorkspaceDir(topicId) {
|
|
343
434
|
return join(TOPIC_WORKSPACE_DIR, safeWorkspaceSegment(topicId, "topic"));
|
|
344
435
|
}
|
|
436
|
+
function isProductionEnv() {
|
|
437
|
+
return false;
|
|
438
|
+
}
|
|
345
439
|
function loadOrCreateLocalSecret(envKey, filename, options = {}) {
|
|
346
440
|
const envValue = envText(envKey);
|
|
347
441
|
const secretFile = resolve3(SECRETS_DIR, filename);
|
|
@@ -376,13 +470,18 @@ function loadOrCreateLocalSecret(envKey, filename, options = {}) {
|
|
|
376
470
|
return stored;
|
|
377
471
|
}
|
|
378
472
|
}
|
|
473
|
+
function getCleanEnv() {
|
|
474
|
+
const env = { ...process.env };
|
|
475
|
+
delete env.CLAUDECODE;
|
|
476
|
+
return env;
|
|
477
|
+
}
|
|
379
478
|
function resolveWhisperBackend() {
|
|
380
479
|
return envText("WHISPER_BACKEND") === "mlx-whisper" ? "mlx-whisper" : "faster-whisper";
|
|
381
480
|
}
|
|
382
481
|
function codexAuthFilePath() {
|
|
383
482
|
return process.env.NEGOTIUM_CODEX_AUTH_FILE || join(process.env.CODEX_HOME || join(homedir(), ".codex"), "auth.json");
|
|
384
483
|
}
|
|
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;
|
|
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, RUNTIME_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_HAIKU = "claude-haiku-4-5-20251001", MODEL_FABLE = "claude-fable-5-1", MODEL_DEEPSEEK_V4_PRO = "deepseek-v4-pro", MODEL_DEEPSEEK_V4_FLASH = "deepseek-v4-flash", 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;
|
|
386
485
|
var init_config = __esm(() => {
|
|
387
486
|
init_config_helpers();
|
|
388
487
|
init_logger();
|
|
@@ -439,6 +538,7 @@ var init_config = __esm(() => {
|
|
|
439
538
|
DEBUG_FILE = resolve3(DATA_DIR, "debug-users.json");
|
|
440
539
|
USERS_LOG_DIR = resolve3(DATA_DIR, "users");
|
|
441
540
|
RUN_DIR = resolveLocalStateDir("NEGOTIUM_RUN_DIR", "runtime");
|
|
541
|
+
RUNTIME_DIR = RUN_DIR;
|
|
442
542
|
PROGRESS_DIR = resolve3(RUN_DIR, "progress");
|
|
443
543
|
DM_CMD_DIR = resolve3(RUN_DIR, "dm-commands");
|
|
444
544
|
DM_RESP_DIR = resolve3(RUN_DIR, "dm-responses");
|
|
@@ -676,6 +776,13 @@ function validateActorTopicScope(value) {
|
|
|
676
776
|
}
|
|
677
777
|
return { ok: true, scope };
|
|
678
778
|
}
|
|
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
|
+
}
|
|
679
786
|
function intersectActorTopicScopes(scopes) {
|
|
680
787
|
if (scopes.length === 0 || scopes.some((scope) => scope === undefined))
|
|
681
788
|
return;
|
|
@@ -786,6 +893,13 @@ function validateRemoteSessionGrant(value) {
|
|
|
786
893
|
}
|
|
787
894
|
return { ok: true, grant: { hubUrl: hubUrl.url, capability } };
|
|
788
895
|
}
|
|
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
|
+
}
|
|
789
903
|
function remoteSessionGrantExpiry(grant) {
|
|
790
904
|
const payload = grant.capability.split(".")[1];
|
|
791
905
|
if (!payload)
|
|
@@ -824,7 +938,7 @@ function encodeRemoteSessionGrantArg(grant) {
|
|
|
824
938
|
throw new Error("remoteSession is required");
|
|
825
939
|
return Buffer.from(JSON.stringify(validated.grant), "utf-8").toString("base64url");
|
|
826
940
|
}
|
|
827
|
-
var REMOTE_SESSION_GRANT_LIMITS, GRANT_KEYS, LOOPBACK_HOSTS, MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH;
|
|
941
|
+
var REMOTE_SESSION_GRANT_LIMITS, GRANT_KEYS, LOOPBACK_HOSTS, REMOTE_SESSION_REPLY_TOKEN_PATTERN, MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH;
|
|
828
942
|
var init_remote_session_grant = __esm(() => {
|
|
829
943
|
REMOTE_SESSION_GRANT_LIMITS = Object.freeze({
|
|
830
944
|
maxHubUrlLength: 512,
|
|
@@ -833,6 +947,7 @@ var init_remote_session_grant = __esm(() => {
|
|
|
833
947
|
});
|
|
834
948
|
GRANT_KEYS = ["hubUrl", "capability"];
|
|
835
949
|
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_-]+$/;
|
|
836
951
|
MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH = REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength;
|
|
837
952
|
});
|
|
838
953
|
|
|
@@ -1177,12 +1292,12 @@ function createBackgroundBashManager(options = {}) {
|
|
|
1177
1292
|
usedPorts.clear();
|
|
1178
1293
|
knownContexts.clear();
|
|
1179
1294
|
const deadline = now() + 3000;
|
|
1180
|
-
await Promise.all(entries.map((instance) => new Promise((
|
|
1295
|
+
await Promise.all(entries.map((instance) => new Promise((resolve4) => {
|
|
1181
1296
|
if (instance.process.exitCode !== null || instance.process.killed)
|
|
1182
|
-
return
|
|
1183
|
-
instance.process.once("exit",
|
|
1184
|
-
instance.process.once("error",
|
|
1185
|
-
const timer = setTimeout(
|
|
1297
|
+
return resolve4();
|
|
1298
|
+
instance.process.once("exit", resolve4);
|
|
1299
|
+
instance.process.once("error", resolve4);
|
|
1300
|
+
const timer = setTimeout(resolve4, Math.max(0, deadline - now()));
|
|
1186
1301
|
timer.unref?.();
|
|
1187
1302
|
})));
|
|
1188
1303
|
}
|
|
@@ -1885,7 +2000,7 @@ var init_api_messages = __esm(async () => {
|
|
|
1885
2000
|
|
|
1886
2001
|
// ../../packages/core/src/storage/topic-link-records.ts
|
|
1887
2002
|
function topicLinkSchemaIsCurrent(database, nodeId) {
|
|
1888
|
-
const objects = new Map(database.query("SELECT name, sql FROM sqlite_master WHERE type IN ('table','index','trigger')").all().map((
|
|
2003
|
+
const objects = new Map(database.query("SELECT name, sql FROM sqlite_master WHERE type IN ('table','index','trigger')").all().map((row2) => [row2.name, row2.sql ?? ""]));
|
|
1889
2004
|
for (const name of [...SCHEMA_TABLES, ...SCHEMA_INDEXES, ...SCHEMA_INDEXES_TOMBSTONES]) {
|
|
1890
2005
|
if (!objects.has(name))
|
|
1891
2006
|
return false;
|
|
@@ -1902,7 +2017,7 @@ function topicLinkSchemaIsCurrent(database, nodeId) {
|
|
|
1902
2017
|
return false;
|
|
1903
2018
|
}
|
|
1904
2019
|
const identity = database.query("SELECT node_id, epoch_id FROM api_node_identity WHERE singleton = 1").all();
|
|
1905
|
-
if (identity.some((
|
|
2020
|
+
if (identity.some((row2) => row2.epoch_id === null))
|
|
1906
2021
|
return false;
|
|
1907
2022
|
if (nodeId && identity[0]?.node_id !== nodeId)
|
|
1908
2023
|
return false;
|
|
@@ -2741,6 +2856,9 @@ function rowToDto2(r, participants = getTopicParticipants(r.id), tellTargets) {
|
|
|
2741
2856
|
function normalizeTopicVisibility(value) {
|
|
2742
2857
|
return value === "hidden" ? "hidden" : "visible";
|
|
2743
2858
|
}
|
|
2859
|
+
function isTopicVisible(topic) {
|
|
2860
|
+
return topic.visibility !== "hidden";
|
|
2861
|
+
}
|
|
2744
2862
|
function normalizeTopicKind(value) {
|
|
2745
2863
|
return value === "channel" || value === "agent" || value === "manager" ? value : null;
|
|
2746
2864
|
}
|
|
@@ -5203,7 +5321,7 @@ var init_codex = __esm(async () => {
|
|
|
5203
5321
|
});
|
|
5204
5322
|
|
|
5205
5323
|
// ../../packages/core/src/version.ts
|
|
5206
|
-
var NEGOTIUM_VERSION = "0.23.
|
|
5324
|
+
var NEGOTIUM_VERSION = "0.23.11";
|
|
5207
5325
|
|
|
5208
5326
|
// ../../packages/core/src/agents/codex-native-multi-agent.ts
|
|
5209
5327
|
import { spawn as spawn2 } from "child_process";
|
|
@@ -5292,7 +5410,7 @@ async function bootstrapCodexModelCache(codexHome, cachePath) {
|
|
|
5292
5410
|
stdio: ["pipe", "pipe", "pipe"],
|
|
5293
5411
|
windowsHide: true
|
|
5294
5412
|
});
|
|
5295
|
-
const refreshed = new Promise((
|
|
5413
|
+
const refreshed = new Promise((resolve7, reject) => {
|
|
5296
5414
|
let settled = false;
|
|
5297
5415
|
let stdoutBuffer = "";
|
|
5298
5416
|
let stderr = "";
|
|
@@ -5311,7 +5429,7 @@ async function bootstrapCodexModelCache(codexHome, cachePath) {
|
|
|
5311
5429
|
else if (!existsSync6(cachePath))
|
|
5312
5430
|
reject(new Error("Codex did not create its model cache"));
|
|
5313
5431
|
else
|
|
5314
|
-
|
|
5432
|
+
resolve7();
|
|
5315
5433
|
};
|
|
5316
5434
|
const send = (message) => {
|
|
5317
5435
|
child.stdin.write(`${JSON.stringify(message)}
|
|
@@ -5377,12 +5495,12 @@ async function bootstrapCodexModelCache(codexHome, cachePath) {
|
|
|
5377
5495
|
function waitForChildExit(child, timeoutMs) {
|
|
5378
5496
|
if (child.exitCode !== null || child.signalCode !== null)
|
|
5379
5497
|
return Promise.resolve();
|
|
5380
|
-
return new Promise((
|
|
5381
|
-
const timer = setTimeout(
|
|
5498
|
+
return new Promise((resolve7) => {
|
|
5499
|
+
const timer = setTimeout(resolve7, timeoutMs);
|
|
5382
5500
|
timer.unref?.();
|
|
5383
5501
|
child.once("exit", () => {
|
|
5384
5502
|
clearTimeout(timer);
|
|
5385
|
-
|
|
5503
|
+
resolve7();
|
|
5386
5504
|
});
|
|
5387
5505
|
});
|
|
5388
5506
|
}
|
|
@@ -5471,11 +5589,16 @@ var init_codex_native_multi_agent = __esm(() => {
|
|
|
5471
5589
|
});
|
|
5472
5590
|
|
|
5473
5591
|
// ../../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
|
+
});
|
|
5474
5597
|
import { spawn as spawn3 } from "child_process";
|
|
5475
5598
|
function createCodexAppServerForker(host) {
|
|
5476
5599
|
return async (parentThreadId) => {
|
|
5477
5600
|
const child = host.spawnServer();
|
|
5478
|
-
return await new Promise((
|
|
5601
|
+
return await new Promise((resolve7, reject) => {
|
|
5479
5602
|
let settled = false;
|
|
5480
5603
|
let stdoutBuffer = "";
|
|
5481
5604
|
let stderr = "";
|
|
@@ -5492,7 +5615,7 @@ function createCodexAppServerForker(host) {
|
|
|
5492
5615
|
if (error)
|
|
5493
5616
|
reject(error);
|
|
5494
5617
|
else if (result)
|
|
5495
|
-
|
|
5618
|
+
resolve7(result);
|
|
5496
5619
|
else
|
|
5497
5620
|
reject(new Error("Codex thread fork returned no result"));
|
|
5498
5621
|
};
|
|
@@ -5629,8 +5752,8 @@ var init_codex_registry = __esm(async () => {
|
|
|
5629
5752
|
return { sessionId: threadId, rolloutPath };
|
|
5630
5753
|
},
|
|
5631
5754
|
async forkSession({ parentSessionId }) {
|
|
5632
|
-
await init_codex_app_server();
|
|
5633
|
-
return await
|
|
5755
|
+
const { forkCodexSession: forkCodexSession2 } = await init_codex_app_server().then(() => exports_codex_app_server);
|
|
5756
|
+
return await forkCodexSession2(parentSessionId);
|
|
5634
5757
|
},
|
|
5635
5758
|
async cleanupRollouts({ sessionIds }) {
|
|
5636
5759
|
if (sessionIds.length === 0)
|
|
@@ -5811,6 +5934,11 @@ var init_maestro_registry = __esm(() => {
|
|
|
5811
5934
|
});
|
|
5812
5935
|
|
|
5813
5936
|
// ../../packages/core/src/agents/registry.ts
|
|
5937
|
+
var exports_registry = {};
|
|
5938
|
+
__export(exports_registry, {
|
|
5939
|
+
getRegistryOperations: () => getRegistryOperations,
|
|
5940
|
+
getRegistry: () => getRegistry
|
|
5941
|
+
});
|
|
5814
5942
|
function getRegistry(agent) {
|
|
5815
5943
|
return REGISTRIES[agent];
|
|
5816
5944
|
}
|
|
@@ -6166,8 +6294,8 @@ var init_claude_notices = __esm(() => {
|
|
|
6166
6294
|
SYSTEM_NOTICES = {
|
|
6167
6295
|
api_retry: (m) => {
|
|
6168
6296
|
const reason = m.error_status === null ? "Lost connection to Claude" : API_ERROR_TEXT[m.error] ?? "Claude request failed";
|
|
6169
|
-
const
|
|
6170
|
-
const when =
|
|
6297
|
+
const delay2 = Math.round(m.retry_delay_ms / 1000);
|
|
6298
|
+
const when = delay2 > 0 ? `in ${delay2}s` : "now";
|
|
6171
6299
|
return `${reason} \xB7 retrying ${when} (${m.attempt}/${m.max_retries})`;
|
|
6172
6300
|
},
|
|
6173
6301
|
model_refusal_fallback: (m) => m.direction === "retry" ? `${modelLabel(m.original_model)} declined \xB7 ${modelLabel(m.fallback_model)} is answering instead` : m.content || undefined,
|
|
@@ -6288,11 +6416,11 @@ var DEFAULT_CONTEXT_WARNING_RATIO = 0.8;
|
|
|
6288
6416
|
// ../../packages/core/src/agents/claude-provider.ts
|
|
6289
6417
|
var exports_claude_provider = {};
|
|
6290
6418
|
__export(exports_claude_provider, {
|
|
6291
|
-
|
|
6292
|
-
claudeBuiltInTools: () => claudeBuiltInTools,
|
|
6293
|
-
claudeProvider: () => claudeProvider,
|
|
6419
|
+
substituteClaudeToolInput: () => substituteClaudeToolInput,
|
|
6294
6420
|
spawnClaudeCodeProcessWithTreeKill: () => spawnClaudeCodeProcessWithTreeKill,
|
|
6295
|
-
|
|
6421
|
+
claudeProvider: () => claudeProvider,
|
|
6422
|
+
claudeBuiltInTools: () => claudeBuiltInTools,
|
|
6423
|
+
buildClaudeDisallowedTools: () => buildClaudeDisallowedTools
|
|
6296
6424
|
});
|
|
6297
6425
|
import { spawn as spawn4 } from "child_process";
|
|
6298
6426
|
import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
|
|
@@ -6373,8 +6501,8 @@ function buildClaudePrompt(opts) {
|
|
|
6373
6501
|
}
|
|
6374
6502
|
function watchClaudeProcessExit(signal) {
|
|
6375
6503
|
let listener;
|
|
6376
|
-
const exited = new Promise((
|
|
6377
|
-
listener =
|
|
6504
|
+
const exited = new Promise((resolve8) => {
|
|
6505
|
+
listener = resolve8;
|
|
6378
6506
|
const listeners = claudeProcessExitListeners.get(signal) ?? new Set;
|
|
6379
6507
|
listeners.add(listener);
|
|
6380
6508
|
claudeProcessExitListeners.set(signal, listeners);
|
|
@@ -6669,6 +6797,7 @@ async function* claudeProvider(opts) {
|
|
|
6669
6797
|
yield beat;
|
|
6670
6798
|
} else if (delta.delta.type === "text_delta" && delta.delta.text) {
|
|
6671
6799
|
thinkingStart = null;
|
|
6800
|
+
yield { type: "text_preview", content: delta.delta.text };
|
|
6672
6801
|
} else {
|
|
6673
6802
|
thinkingStart = null;
|
|
6674
6803
|
}
|
|
@@ -6971,12 +7100,12 @@ function createCodexTreeManager(host, options = {}) {
|
|
|
6971
7100
|
const previous = spawnChain;
|
|
6972
7101
|
let release;
|
|
6973
7102
|
let released = false;
|
|
6974
|
-
spawnChain = new Promise((
|
|
7103
|
+
spawnChain = new Promise((resolve8) => {
|
|
6975
7104
|
release = () => {
|
|
6976
7105
|
if (released)
|
|
6977
7106
|
return;
|
|
6978
7107
|
released = true;
|
|
6979
|
-
|
|
7108
|
+
resolve8();
|
|
6980
7109
|
};
|
|
6981
7110
|
});
|
|
6982
7111
|
await previous;
|
|
@@ -7083,7 +7212,7 @@ function createCodexTreeManager(host, options = {}) {
|
|
|
7083
7212
|
return;
|
|
7084
7213
|
const deadline = Date.now() + Math.max(0, graceMs);
|
|
7085
7214
|
while (Date.now() < deadline && hasSurvivors(plan.targets)) {
|
|
7086
|
-
await new Promise((
|
|
7215
|
+
await new Promise((resolve8) => setTimeout(resolve8, Math.min(100, Math.max(1, deadline - Date.now()))));
|
|
7087
7216
|
}
|
|
7088
7217
|
killStragglers(plan);
|
|
7089
7218
|
}
|
|
@@ -7411,8 +7540,8 @@ async function createCodexVaultHookBridge(userId) {
|
|
|
7411
7540
|
});
|
|
7412
7541
|
restrictIpcEndpoint(socketPath);
|
|
7413
7542
|
if (IS_WINDOWS2) {
|
|
7414
|
-
await Promise.resolve().then(() => init_config());
|
|
7415
|
-
const cached = await ensureCodexWindowsWrapperExe(join13(
|
|
7543
|
+
const { BINARIES_DIR: BINARIES_DIR2 } = await Promise.resolve().then(() => (init_config(), exports_config));
|
|
7544
|
+
const cached = await ensureCodexWindowsWrapperExe(join13(BINARIES_DIR2, "codex-hook-wrapper"));
|
|
7416
7545
|
await copyFile(cached, wrapperPath);
|
|
7417
7546
|
await writeFile2(join13(root, "codex-with-hooks.cfg"), [process.execPath, codexCliScriptPath(), socketPath, token].join(`
|
|
7418
7547
|
`), { encoding: "utf8", mode: 384 });
|
|
@@ -7984,10 +8113,10 @@ var init_tool_format = __esm(() => {
|
|
|
7984
8113
|
// ../../packages/core/src/agents/codex-provider.ts
|
|
7985
8114
|
var exports_codex_provider = {};
|
|
7986
8115
|
__export(exports_codex_provider, {
|
|
7987
|
-
|
|
7988
|
-
codexProvider: () => codexProvider,
|
|
8116
|
+
toCodexMcpServers: () => toCodexMcpServers,
|
|
7989
8117
|
normalizeCodexTurnUsage: () => normalizeCodexTurnUsage,
|
|
7990
|
-
|
|
8118
|
+
codexProvider: () => codexProvider,
|
|
8119
|
+
codexNoticeStatus: () => codexNoticeStatus
|
|
7991
8120
|
});
|
|
7992
8121
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
7993
8122
|
import { existsSync as existsSync14, readFileSync as readFileSync11, realpathSync as realpathSync4, statSync as statSync5 } from "fs";
|
|
@@ -8295,9 +8424,9 @@ async function startStreamedWithTracking(thread, prompt, abortSignal, trackedPid
|
|
|
8295
8424
|
nextP.catch(() => {});
|
|
8296
8425
|
first = await Promise.race([nextP, startupTimeout]);
|
|
8297
8426
|
} catch (err) {
|
|
8298
|
-
const
|
|
8299
|
-
if (
|
|
8300
|
-
killCodexTrees(
|
|
8427
|
+
const novel2 = findNewCodexChildren(baseline);
|
|
8428
|
+
if (novel2.length > 0) {
|
|
8429
|
+
killCodexTrees(novel2);
|
|
8301
8430
|
}
|
|
8302
8431
|
await closeIterator(iter);
|
|
8303
8432
|
throw err;
|
|
@@ -8733,11 +8862,11 @@ var init_maestro_bootstrap_env = __esm(() => {
|
|
|
8733
8862
|
// ../../packages/core/src/agents/maestro-provider.ts
|
|
8734
8863
|
var exports_maestro_provider = {};
|
|
8735
8864
|
__export(exports_maestro_provider, {
|
|
8736
|
-
|
|
8737
|
-
buildMaestroToolHooks: () => buildMaestroToolHooks,
|
|
8738
|
-
buildMaestroToolResultTruncation: () => buildMaestroToolResultTruncation,
|
|
8865
|
+
resolveMaestroApiKeyOverrides: () => resolveMaestroApiKeyOverrides,
|
|
8739
8866
|
maestroProvider: () => maestroProvider,
|
|
8740
|
-
|
|
8867
|
+
buildMaestroToolResultTruncation: () => buildMaestroToolResultTruncation,
|
|
8868
|
+
buildMaestroToolHooks: () => buildMaestroToolHooks,
|
|
8869
|
+
buildMaestroDisallowedTools: () => buildMaestroDisallowedTools
|
|
8741
8870
|
});
|
|
8742
8871
|
import { resolve as resolve11 } from "path";
|
|
8743
8872
|
import { maestroProvider as sdkMaestroProvider, setMcpResolver } from "maestro-agent-sdk";
|
|
@@ -8865,18 +8994,18 @@ import { join as join15 } from "path";
|
|
|
8865
8994
|
async function* dispatchAgent(opts) {
|
|
8866
8995
|
switch (opts.agent) {
|
|
8867
8996
|
case "claude": {
|
|
8868
|
-
const { claudeProvider } = await loadClaudeProvider();
|
|
8869
|
-
yield*
|
|
8997
|
+
const { claudeProvider: claudeProvider2 } = await loadClaudeProvider();
|
|
8998
|
+
yield* claudeProvider2(opts);
|
|
8870
8999
|
return;
|
|
8871
9000
|
}
|
|
8872
9001
|
case "codex": {
|
|
8873
|
-
const { codexProvider } = await loadCodexProvider();
|
|
8874
|
-
yield*
|
|
9002
|
+
const { codexProvider: codexProvider2 } = await loadCodexProvider();
|
|
9003
|
+
yield* codexProvider2(opts);
|
|
8875
9004
|
return;
|
|
8876
9005
|
}
|
|
8877
9006
|
case "maestro": {
|
|
8878
|
-
const { maestroProvider } = await loadMaestroProvider();
|
|
8879
|
-
yield*
|
|
9007
|
+
const { maestroProvider: maestroProvider2 } = await loadMaestroProvider();
|
|
9008
|
+
yield* maestroProvider2(opts);
|
|
8880
9009
|
return;
|
|
8881
9010
|
}
|
|
8882
9011
|
default: {
|
|
@@ -8907,8 +9036,8 @@ async function resolveSessionFileMissing(agent, sessionId, cwd) {
|
|
|
8907
9036
|
return true;
|
|
8908
9037
|
}
|
|
8909
9038
|
case "maestro": {
|
|
8910
|
-
const { hasActiveMaestroSession, maestroSessionPath } = await import("maestro-agent-sdk");
|
|
8911
|
-
return !existsSync15(
|
|
9039
|
+
const { hasActiveMaestroSession, maestroSessionPath: maestroSessionPath2 } = await import("maestro-agent-sdk");
|
|
9040
|
+
return !existsSync15(maestroSessionPath2(sessionId)) && !hasActiveMaestroSession(sessionId);
|
|
8912
9041
|
}
|
|
8913
9042
|
default: {
|
|
8914
9043
|
const _exhaustive = agent;
|
|
@@ -8963,7 +9092,7 @@ async function* runAgent(opts) {
|
|
|
8963
9092
|
const taskScope = resolveTaskEventScope(dispatchOpts);
|
|
8964
9093
|
const stream = taskScope ? withTaskSnapshots(dispatchAgent(dispatchOpts), taskScope) : dispatchAgent(dispatchOpts);
|
|
8965
9094
|
for await (const event of stream) {
|
|
8966
|
-
if (recording && event.type !== "tasks") {
|
|
9095
|
+
if (recording && event.type !== "tasks" && event.type !== "text_preview") {
|
|
8967
9096
|
appendConversationEvent(opts.userId, opts.session, opts.agent, event);
|
|
8968
9097
|
}
|
|
8969
9098
|
yield event;
|
|
@@ -8987,6 +9116,24 @@ var init_agents = __esm(async () => {
|
|
|
8987
9116
|
});
|
|
8988
9117
|
|
|
8989
9118
|
// ../../packages/core/src/agents/model-catalog.ts
|
|
9119
|
+
var exports_model_catalog = {};
|
|
9120
|
+
__export(exports_model_catalog, {
|
|
9121
|
+
selectableModel: () => selectableModel,
|
|
9122
|
+
resolveWorkerModel: () => resolveWorkerModel,
|
|
9123
|
+
resolveWorkerDefaultModel: () => resolveWorkerDefaultModel,
|
|
9124
|
+
resolveModelForAgent: () => resolveModelForAgent,
|
|
9125
|
+
resolveDefaultModel: () => resolveDefaultModel,
|
|
9126
|
+
resolveCompactionExecution: () => resolveCompactionExecution,
|
|
9127
|
+
modelOwner: () => modelOwner,
|
|
9128
|
+
formatSelectableModel: () => formatSelectableModel,
|
|
9129
|
+
canonicalModelId: () => canonicalModelId,
|
|
9130
|
+
SELECTABLE_MODELS: () => SELECTABLE_MODELS,
|
|
9131
|
+
MODEL_OWNER: () => MODEL_OWNER,
|
|
9132
|
+
MODEL_COST_ROUTING_SUMMARY: () => MODEL_COST_ROUTING_SUMMARY,
|
|
9133
|
+
MODEL_COST_RESEARCHED_AT: () => MODEL_COST_RESEARCHED_AT,
|
|
9134
|
+
FALLBACK_ORDER: () => FALLBACK_ORDER,
|
|
9135
|
+
AGENT_DISPLAY_NAME: () => AGENT_DISPLAY_NAME
|
|
9136
|
+
});
|
|
8990
9137
|
function canonicalModelCasing() {
|
|
8991
9138
|
return Object.fromEntries(SELECTABLE_MODELS.map((candidate) => [candidate.model.toLowerCase(), candidate.model]));
|
|
8992
9139
|
}
|
|
@@ -8999,6 +9146,10 @@ function formatSelectableModel(candidate) {
|
|
|
8999
9146
|
const tier = `${candidate.intelligenceTier[0].toUpperCase()}${candidate.intelligenceTier.slice(1)}`;
|
|
9000
9147
|
return `${candidate.agent} / \`${candidate.model}\` [${tier}-level]: ${candidate.routingSummary}`;
|
|
9001
9148
|
}
|
|
9149
|
+
function selectableModel(value) {
|
|
9150
|
+
const canonical = canonicalModelId(value).toLowerCase();
|
|
9151
|
+
return SELECTABLE_MODELS.find((candidate) => candidate.model === canonical);
|
|
9152
|
+
}
|
|
9002
9153
|
function modelOwner(model) {
|
|
9003
9154
|
const lower = model.toLowerCase();
|
|
9004
9155
|
if (lower.startsWith("claude-"))
|
|
@@ -9051,7 +9202,7 @@ function resolveCompactionExecution(agent, registry) {
|
|
|
9051
9202
|
const effort = registry.validateEffort("medium") ? "medium" : registry.defaultEffort;
|
|
9052
9203
|
return { model, ...effort ? { effort } : {} };
|
|
9053
9204
|
}
|
|
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
|
+
var MODEL_OWNER, MODEL_COST_RESEARCHED_AT = "2026-09-05", 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, FALLBACK_ORDER, AGENT_DISPLAY_NAME;
|
|
9055
9206
|
var init_model_catalog = __esm(() => {
|
|
9056
9207
|
init_config();
|
|
9057
9208
|
MODEL_OWNER = {
|
|
@@ -9232,6 +9383,20 @@ var init_model_catalog = __esm(() => {
|
|
|
9232
9383
|
"glm-pro": "glm-5.3",
|
|
9233
9384
|
"glm-flash": "glm-5.3-flash"
|
|
9234
9385
|
};
|
|
9386
|
+
FALLBACK_ORDER = {
|
|
9387
|
+
claude: [
|
|
9388
|
+
{ agent: "maestro", model: "deepseek-pro" },
|
|
9389
|
+
{ agent: "codex", model: "luna" }
|
|
9390
|
+
],
|
|
9391
|
+
codex: [
|
|
9392
|
+
{ agent: "maestro", model: "deepseek-pro" },
|
|
9393
|
+
{ agent: "claude", model: "sonnet" }
|
|
9394
|
+
],
|
|
9395
|
+
maestro: [
|
|
9396
|
+
{ agent: "codex", model: "luna" },
|
|
9397
|
+
{ agent: "claude", model: "sonnet" }
|
|
9398
|
+
]
|
|
9399
|
+
};
|
|
9235
9400
|
AGENT_DISPLAY_NAME = {
|
|
9236
9401
|
claude: "Claude",
|
|
9237
9402
|
codex: "Codex",
|
|
@@ -9983,9 +10148,9 @@ function resolveTopicBrief(topicId, legacyTitle) {
|
|
|
9983
10148
|
const titleBrief = getTopicBrief(titleKey);
|
|
9984
10149
|
if (titleBrief)
|
|
9985
10150
|
return { brief: titleBrief, storageKey: titleKey };
|
|
9986
|
-
const
|
|
9987
|
-
if (
|
|
9988
|
-
return { brief:
|
|
10151
|
+
const current2 = getTopicBrief(topicId);
|
|
10152
|
+
if (current2)
|
|
10153
|
+
return { brief: current2, storageKey: topicId };
|
|
9989
10154
|
const legacy = titleKey === legacyTitle ? null : getTopicBrief(legacyTitle);
|
|
9990
10155
|
return legacy ? { brief: legacy, storageKey: legacyTitle } : null;
|
|
9991
10156
|
}
|
|
@@ -10277,7 +10442,8 @@ function createArchiverRuntime(host) {
|
|
|
10277
10442
|
archivePath,
|
|
10278
10443
|
rawArchivePaths = [],
|
|
10279
10444
|
messageCount,
|
|
10280
|
-
mode = "deleted-topic"
|
|
10445
|
+
mode = "deleted-topic",
|
|
10446
|
+
memoryKeyFixed = false
|
|
10281
10447
|
} = params;
|
|
10282
10448
|
const generalTopicId = host.storage.getGeneralTopicId(userId, sourceTopicId);
|
|
10283
10449
|
let definition;
|
|
@@ -10293,10 +10459,12 @@ function createArchiverRuntime(host) {
|
|
|
10293
10459
|
const model = resolveWorkerModel(agent, params.model ?? definition.model, getRegistry(agent));
|
|
10294
10460
|
const outputLanguage = resolveMemoryLanguage();
|
|
10295
10461
|
const generalReplyInstruction = `Reply with a short completion message in ${outputLanguage} for display in #General. ` + "Do not include tool-call logs or raw transcripts \u2014 just briefly name the summary / brief / articles you saved.";
|
|
10462
|
+
const memoryKeyLines = memoryKeyFixed ? [`fixed_memory_key: ${topicTitle}`] : [];
|
|
10296
10463
|
const prompt = mode === "active-topic" ? [
|
|
10297
10464
|
`Recent idle conversation snapshot of session "${topicTitle}". Extract durable memory from the archive below and save it into this topic's wiki.`,
|
|
10298
10465
|
`archive_path: ${archivePath}`,
|
|
10299
10466
|
...rawArchivePaths.map((path) => `raw_archive_path: ${path}`),
|
|
10467
|
+
...memoryKeyLines,
|
|
10300
10468
|
`wiki_dir: ${wikiDir}`,
|
|
10301
10469
|
`output_language: ${outputLanguage}`,
|
|
10302
10470
|
"",
|
|
@@ -10306,6 +10474,7 @@ function createArchiverRuntime(host) {
|
|
|
10306
10474
|
`Session "${topicTitle}" was deleted. Extract durable memory from the archive below and save it into the wiki.`,
|
|
10307
10475
|
`archive_path: ${archivePath}`,
|
|
10308
10476
|
...rawArchivePaths.map((path) => `raw_archive_path: ${path}`),
|
|
10477
|
+
...memoryKeyLines,
|
|
10309
10478
|
`wiki_dir: ${wikiDir}`,
|
|
10310
10479
|
`output_language: ${outputLanguage}`,
|
|
10311
10480
|
"",
|
|
@@ -10605,6 +10774,11 @@ var init_archiver = __esm(async () => {
|
|
|
10605
10774
|
});
|
|
10606
10775
|
|
|
10607
10776
|
// ../../packages/core/src/agents/auth-check.ts
|
|
10777
|
+
var exports_auth_check = {};
|
|
10778
|
+
__export(exports_auth_check, {
|
|
10779
|
+
checkAgentModelAuth: () => checkAgentModelAuth,
|
|
10780
|
+
checkAgentAuth: () => checkAgentAuth
|
|
10781
|
+
});
|
|
10608
10782
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
10609
10783
|
import { existsSync as existsSync17 } from "fs";
|
|
10610
10784
|
import { homedir as homedir8, platform } from "os";
|
|
@@ -10936,8 +11110,8 @@ function createRoomQueryRegistry(host) {
|
|
|
10936
11110
|
clearInterval(previousMonitor);
|
|
10937
11111
|
activeByRoom.set(roomId, control);
|
|
10938
11112
|
const monitor = setInterval(() => {
|
|
10939
|
-
const
|
|
10940
|
-
if (!
|
|
11113
|
+
const current2 = activeByRoom.get(roomId);
|
|
11114
|
+
if (!current2 || current2.queryId !== control.queryId) {
|
|
10941
11115
|
clearInterval(monitor);
|
|
10942
11116
|
if (leaseMonitors.get(roomId) === monitor)
|
|
10943
11117
|
leaseMonitors.delete(roomId);
|
|
@@ -10959,8 +11133,8 @@ function createRoomQueryRegistry(host) {
|
|
|
10959
11133
|
return true;
|
|
10960
11134
|
}
|
|
10961
11135
|
function clear(roomId, queryId) {
|
|
10962
|
-
const
|
|
10963
|
-
if (
|
|
11136
|
+
const current2 = activeByRoom.get(roomId);
|
|
11137
|
+
if (current2?.queryId === queryId) {
|
|
10964
11138
|
activeByRoom.delete(roomId);
|
|
10965
11139
|
const monitor = leaseMonitors.get(roomId);
|
|
10966
11140
|
if (monitor)
|
|
@@ -11023,12 +11197,43 @@ var init_room_query_registry = () => {};
|
|
|
11023
11197
|
var init_types2 = () => {};
|
|
11024
11198
|
|
|
11025
11199
|
// ../../packages/core/src/query/active-rooms.ts
|
|
11200
|
+
var exports_active_rooms = {};
|
|
11201
|
+
__export(exports_active_rooms, {
|
|
11202
|
+
wsAbortReason: () => wsAbortReason,
|
|
11203
|
+
takeDeferredInject: () => takeDeferredInject,
|
|
11204
|
+
setRoomQuery: () => setRoomQuery,
|
|
11205
|
+
listRunningTopicQueries: () => listRunningTopicQueries,
|
|
11206
|
+
listRunningTopicIds: () => listRunningTopicIds,
|
|
11207
|
+
isolatedTurnRoomId: () => isolatedTurnRoomId,
|
|
11208
|
+
isUserOrigin: () => isUserOrigin,
|
|
11209
|
+
isTopicRunning: () => isTopicRunning,
|
|
11210
|
+
interSessionQueue: () => interSessionQueue,
|
|
11211
|
+
getRoomQueryStatus: () => getRoomQueryStatus,
|
|
11212
|
+
getRoomQuery: () => getRoomQuery,
|
|
11213
|
+
deferInject: () => deferInject,
|
|
11214
|
+
decideNewQuery: () => decideNewQuery,
|
|
11215
|
+
clearRoomQuery: () => clearRoomQuery,
|
|
11216
|
+
cancelDeferredInject: () => cancelDeferredInject,
|
|
11217
|
+
abortRoom: () => abortRoom,
|
|
11218
|
+
abortAllRooms: () => abortAllRooms,
|
|
11219
|
+
InterSessionQueue: () => InterSessionQueue,
|
|
11220
|
+
DeferredInjectBatcher: () => DeferredInjectBatcher
|
|
11221
|
+
});
|
|
11026
11222
|
function getRoomQuery(roomId) {
|
|
11027
11223
|
return roomQueryRegistry.get(roomId);
|
|
11028
11224
|
}
|
|
11225
|
+
function listRunningTopicQueries() {
|
|
11226
|
+
return roomQueryRegistry.listRunningTopicQueries();
|
|
11227
|
+
}
|
|
11228
|
+
function listRunningTopicIds() {
|
|
11229
|
+
return roomQueryRegistry.listRunningTopicIds();
|
|
11230
|
+
}
|
|
11029
11231
|
function isTopicRunning(topicId) {
|
|
11030
11232
|
return roomQueryRegistry.isTopicRunning(topicId);
|
|
11031
11233
|
}
|
|
11234
|
+
function getRoomQueryStatus(topicId, queryId) {
|
|
11235
|
+
return roomQueryRegistry.status(topicId, queryId);
|
|
11236
|
+
}
|
|
11032
11237
|
function setRoomQuery(control) {
|
|
11033
11238
|
return roomQueryRegistry.set(control);
|
|
11034
11239
|
}
|
|
@@ -11038,6 +11243,9 @@ function clearRoomQuery(roomId, queryId) {
|
|
|
11038
11243
|
function abortRoom(roomId, reason = "external" /* External */) {
|
|
11039
11244
|
return roomQueryRegistry.abort(roomId, reason);
|
|
11040
11245
|
}
|
|
11246
|
+
function abortAllRooms(reason = "external" /* External */) {
|
|
11247
|
+
return roomQueryRegistry.abortAll(reason);
|
|
11248
|
+
}
|
|
11041
11249
|
function decideNewQuery(topicId, incomingOrigin) {
|
|
11042
11250
|
return roomQueryRegistry.decide(topicId, incomingOrigin);
|
|
11043
11251
|
}
|
|
@@ -11203,6 +11411,9 @@ function deferInject(inject) {
|
|
|
11203
11411
|
function takeDeferredInject(topicId) {
|
|
11204
11412
|
return interSessionQueue.dequeueAll(topicId);
|
|
11205
11413
|
}
|
|
11414
|
+
function cancelDeferredInject(topicId, requestId) {
|
|
11415
|
+
return interSessionQueue.remove(topicId, requestId) !== undefined;
|
|
11416
|
+
}
|
|
11206
11417
|
function wsAbortReason(reason) {
|
|
11207
11418
|
return reason === "internal" /* Internal */ ? "superseded" : "stopped";
|
|
11208
11419
|
}
|
|
@@ -11495,8 +11706,8 @@ function settleTopicArchiveJob(topicId, archivePath, success) {
|
|
|
11495
11706
|
db.query("UPDATE api_topic_archive_jobs SET status = 'pending', updated_at = ? WHERE topic_id = ? AND archive_path = ?").run(new Date().toISOString(), topicId, archivePath);
|
|
11496
11707
|
return;
|
|
11497
11708
|
}
|
|
11498
|
-
const
|
|
11499
|
-
setTopicArchiveState(topicId, Math.max(
|
|
11709
|
+
const current2 = getTopicArchiveState(topicId)?.lastArchivedRowid ?? 0;
|
|
11710
|
+
setTopicArchiveState(topicId, Math.max(current2, job.last_rowid), job.archive_path);
|
|
11500
11711
|
db.query("DELETE FROM api_topic_archive_jobs WHERE topic_id = ? AND archive_path = ?").run(topicId, archivePath);
|
|
11501
11712
|
})();
|
|
11502
11713
|
}
|
|
@@ -11657,6 +11868,7 @@ function archiveActiveTopicForMemory(topicId, userId, options) {
|
|
|
11657
11868
|
sourceTopicId: topic.id,
|
|
11658
11869
|
topicId: memoryTopic.id,
|
|
11659
11870
|
topicTitle: memoryTitle,
|
|
11871
|
+
memoryKeyFixed: Boolean(memoryTopic.memoryKey?.trim()),
|
|
11660
11872
|
archivePath: job.archivePath,
|
|
11661
11873
|
...options.rawArchivePaths ? { rawArchivePaths: options.rawArchivePaths } : {},
|
|
11662
11874
|
messageCount: job.messageCount,
|
|
@@ -12179,7 +12391,7 @@ function createAskUserRuntime(host) {
|
|
|
12179
12391
|
if (ask.expired || ask.selectedLabel) {
|
|
12180
12392
|
return { ok: false, error: "This question is no longer awaiting an answer." };
|
|
12181
12393
|
}
|
|
12182
|
-
if (!kind && !ask.choices.some((
|
|
12394
|
+
if (!kind && !ask.choices.some((choice2) => choice2.label === label)) {
|
|
12183
12395
|
return { ok: false, error: "Invalid choice." };
|
|
12184
12396
|
}
|
|
12185
12397
|
const pending = pendingAsks.get(messageId);
|
|
@@ -12339,8 +12551,8 @@ function createAskUserRuntime(host) {
|
|
|
12339
12551
|
return errorResult(`Error: failed to persist ask_user_question: ${error instanceof Error ? error.message : String(error)}`);
|
|
12340
12552
|
}
|
|
12341
12553
|
let resolveAnswer;
|
|
12342
|
-
const promise = new Promise((
|
|
12343
|
-
resolveAnswer =
|
|
12554
|
+
const promise = new Promise((resolve13) => {
|
|
12555
|
+
resolveAnswer = resolve13;
|
|
12344
12556
|
});
|
|
12345
12557
|
pendingAsks.set(message.id, {
|
|
12346
12558
|
topicId: ctx.topicId,
|
|
@@ -12542,8 +12754,8 @@ var init_self_schedules = __esm(async () => {
|
|
|
12542
12754
|
});
|
|
12543
12755
|
|
|
12544
12756
|
// ../../packages/core/src/platform/playwright/manager-utils.ts
|
|
12545
|
-
function isLiveOwnedChildProcess(
|
|
12546
|
-
return
|
|
12757
|
+
function isLiveOwnedChildProcess(current2, expected) {
|
|
12758
|
+
return current2?.process === expected && expected.exitCode === null && expected.signalCode === null && !expected.killed;
|
|
12547
12759
|
}
|
|
12548
12760
|
function matchesSpawnedBrowserHealth(health, expectedSpawnNonce) {
|
|
12549
12761
|
if (!health || typeof health !== "object")
|
|
@@ -12787,10 +12999,10 @@ function findExecutableOnPath(command, environment = process.env) {
|
|
|
12787
12999
|
return null;
|
|
12788
13000
|
}
|
|
12789
13001
|
function resolveHeadedPlaywrightSpawn(command, args, options = {}) {
|
|
12790
|
-
const
|
|
13002
|
+
const platform2 = options.platform ?? process.platform;
|
|
12791
13003
|
const environment = options.environment ?? process.env;
|
|
12792
13004
|
const hasDisplay = Boolean(environment.DISPLAY?.trim() || environment.WAYLAND_DISPLAY?.trim());
|
|
12793
|
-
if (
|
|
13005
|
+
if (platform2 !== "linux" || hasDisplay) {
|
|
12794
13006
|
return { command, args: [...args], virtualDisplay: false };
|
|
12795
13007
|
}
|
|
12796
13008
|
const xvfbRun = (options.findExecutable ?? findExecutableOnPath)("xvfb-run", environment);
|
|
@@ -12839,7 +13051,7 @@ async function probeMcpTransport(transport, options = {}) {
|
|
|
12839
13051
|
}
|
|
12840
13052
|
}
|
|
12841
13053
|
async function probePlaywrightMcpTransports(port, capability, fetchImpl = fetch) {
|
|
12842
|
-
const
|
|
13054
|
+
const query2 = new URLSearchParams({ owner: PROBE_OWNER });
|
|
12843
13055
|
const baseUrl = `http://127.0.0.1:${port}`;
|
|
12844
13056
|
const ownerCapability = browserOwnerCapability(capability, PROBE_OWNER);
|
|
12845
13057
|
const capabilityHeaders = { "X-Browser-Capability": ownerCapability };
|
|
@@ -12848,14 +13060,14 @@ async function probePlaywrightMcpTransports(port, capability, fetchImpl = fetch)
|
|
|
12848
13060
|
headers.set("X-Browser-Capability", ownerCapability);
|
|
12849
13061
|
return fetchImpl(input, { ...init, headers });
|
|
12850
13062
|
};
|
|
12851
|
-
const sseTransport = new SSEClientTransport(new URL(`${baseUrl}/sse?${
|
|
13063
|
+
const sseTransport = new SSEClientTransport(new URL(`${baseUrl}/sse?${query2}`), {
|
|
12852
13064
|
fetch: authenticatedFetch,
|
|
12853
13065
|
eventSourceInit: { fetch: authenticatedFetch },
|
|
12854
13066
|
requestInit: { headers: capabilityHeaders }
|
|
12855
13067
|
});
|
|
12856
13068
|
if (!await probeMcpTransport(sseTransport))
|
|
12857
13069
|
return false;
|
|
12858
|
-
const streamableTransport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp?${
|
|
13070
|
+
const streamableTransport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp?${query2}`), {
|
|
12859
13071
|
fetch: authenticatedFetch,
|
|
12860
13072
|
requestInit: { headers: capabilityHeaders }
|
|
12861
13073
|
});
|
|
@@ -12985,9 +13197,9 @@ async function createBrowserVaultBroker(userId) {
|
|
|
12985
13197
|
if (typeof request.tool !== "string")
|
|
12986
13198
|
return { id, ok: false, error: "invalid tool" };
|
|
12987
13199
|
const leaseCutoff = Date.now() - LEASE_TTL_MS;
|
|
12988
|
-
for (const [
|
|
13200
|
+
for (const [lease2, binding] of leases) {
|
|
12989
13201
|
if (binding.createdAt < leaseCutoff)
|
|
12990
|
-
leases.delete(
|
|
13202
|
+
leases.delete(lease2);
|
|
12991
13203
|
}
|
|
12992
13204
|
if (leases.size >= MAX_ACTIVE_LEASES) {
|
|
12993
13205
|
return { id, ok: false, error: "too many active leases" };
|
|
@@ -13548,9 +13760,9 @@ async function spawnPlaywright(instanceKey, ownerId, reservedPort, browserBin =
|
|
|
13548
13760
|
const stderrTail = captureBoundedStderr(proc);
|
|
13549
13761
|
const startup = watchChildStartup(proc, stderrTail);
|
|
13550
13762
|
const reapCrashedBrowser = () => {
|
|
13551
|
-
const
|
|
13552
|
-
managerHost.cleanupBrowserProcessesForDataDir(
|
|
13553
|
-
cleanSingletonFiles(
|
|
13763
|
+
const userDataDir2 = resolveUserDataDir(instanceKey);
|
|
13764
|
+
managerHost.cleanupBrowserProcessesForDataDir(userDataDir2);
|
|
13765
|
+
cleanSingletonFiles(userDataDir2);
|
|
13554
13766
|
};
|
|
13555
13767
|
proc.once("error", (err) => {
|
|
13556
13768
|
logger.error({ err, instanceKey, stderr: stderrTail() || undefined }, "Playwright MCP error");
|
|
@@ -13619,8 +13831,8 @@ ${stderrTail()}` : ""));
|
|
|
13619
13831
|
}
|
|
13620
13832
|
async function supportsOwnerCleanup(port, capability) {
|
|
13621
13833
|
try {
|
|
13622
|
-
const
|
|
13623
|
-
const response = await fetch(`http://127.0.0.1:${port}/owners?${
|
|
13834
|
+
const query2 = new URLSearchParams({ owner: "__negotium_capability_probe__" });
|
|
13835
|
+
const response = await fetch(`http://127.0.0.1:${port}/owners?${query2}`, {
|
|
13624
13836
|
method: "DELETE",
|
|
13625
13837
|
headers: {
|
|
13626
13838
|
"X-Browser-Capability": capability
|
|
@@ -13695,8 +13907,8 @@ async function closeBindingOwnerTabs(binding, owner) {
|
|
|
13695
13907
|
if (!instance)
|
|
13696
13908
|
return 0;
|
|
13697
13909
|
const port = instance.port;
|
|
13698
|
-
const
|
|
13699
|
-
const response = await fetch(`http://127.0.0.1:${port}/owners?${
|
|
13910
|
+
const query2 = new URLSearchParams({ owner });
|
|
13911
|
+
const response = await fetch(`http://127.0.0.1:${port}/owners?${query2}`, {
|
|
13700
13912
|
method: "DELETE",
|
|
13701
13913
|
headers: {
|
|
13702
13914
|
"X-Browser-Capability": instance.capability
|
|
@@ -14396,7 +14608,7 @@ async function runIdleCompactForTopic(topicId, userId, options = {}) {
|
|
|
14396
14608
|
return "below-threshold";
|
|
14397
14609
|
}
|
|
14398
14610
|
const compact = options.compact ?? (async (id, actorId, reason) => {
|
|
14399
|
-
await init_session();
|
|
14611
|
+
const { compactTopicSession } = await init_session().then(() => exports_session);
|
|
14400
14612
|
return compactTopicSession(id, actorId, reason, { preemptive: false });
|
|
14401
14613
|
});
|
|
14402
14614
|
try {
|
|
@@ -14596,40 +14808,40 @@ function beginTransientBackgroundSession(userId, session) {
|
|
|
14596
14808
|
update(status, step) {
|
|
14597
14809
|
if (finished)
|
|
14598
14810
|
return;
|
|
14599
|
-
const
|
|
14600
|
-
if (
|
|
14811
|
+
const current2 = transientSessions.get(record.id);
|
|
14812
|
+
if (current2 !== record)
|
|
14601
14813
|
return;
|
|
14602
14814
|
const nextStatus = text(status, 160);
|
|
14603
14815
|
if (nextStatus)
|
|
14604
|
-
|
|
14816
|
+
current2.status = nextStatus;
|
|
14605
14817
|
const nextStep = text(step);
|
|
14606
|
-
if (nextStep &&
|
|
14607
|
-
|
|
14818
|
+
if (nextStep && current2.steps.at(-1) !== nextStep) {
|
|
14819
|
+
current2.steps.push(nextStep);
|
|
14608
14820
|
}
|
|
14609
14821
|
},
|
|
14610
14822
|
setOutput(output) {
|
|
14611
14823
|
if (finished)
|
|
14612
14824
|
return;
|
|
14613
|
-
const
|
|
14614
|
-
if (
|
|
14825
|
+
const current2 = transientSessions.get(record.id);
|
|
14826
|
+
if (current2 !== record)
|
|
14615
14827
|
return;
|
|
14616
|
-
|
|
14828
|
+
current2.output = output;
|
|
14617
14829
|
},
|
|
14618
14830
|
finish(status, step) {
|
|
14619
14831
|
if (finished)
|
|
14620
14832
|
return;
|
|
14621
14833
|
this.update(status ?? record.status, step);
|
|
14622
14834
|
finished = true;
|
|
14623
|
-
const
|
|
14624
|
-
if (
|
|
14835
|
+
const current2 = transientSessions.get(record.id);
|
|
14836
|
+
if (current2 !== record)
|
|
14625
14837
|
return;
|
|
14626
|
-
|
|
14627
|
-
|
|
14628
|
-
|
|
14838
|
+
current2.active = false;
|
|
14839
|
+
current2.expiresAt = Date.now() + Math.max(0, retentionMs);
|
|
14840
|
+
current2.expiryTimer = setTimeout(() => {
|
|
14629
14841
|
if (transientSessions.get(record.id) === record)
|
|
14630
14842
|
transientSessions.delete(record.id);
|
|
14631
14843
|
}, Math.max(0, retentionMs));
|
|
14632
|
-
|
|
14844
|
+
current2.expiryTimer.unref?.();
|
|
14633
14845
|
}
|
|
14634
14846
|
};
|
|
14635
14847
|
}
|
|
@@ -14888,8 +15100,8 @@ function markRuntimeUserTurnMessagesLogged(topicId, requestId, ownerId, loggedUs
|
|
|
14888
15100
|
return false;
|
|
14889
15101
|
return db.transaction(() => {
|
|
14890
15102
|
const requests = db.query("SELECT * FROM runtime_user_turn_requests WHERE topic_id = ? ORDER BY created_at ASC, rowid ASC").all(topicId).map(rowToRequest);
|
|
14891
|
-
const hasLoggedPrefix = (
|
|
14892
|
-
const candidate =
|
|
15103
|
+
const hasLoggedPrefix = (request2) => loggedUserMessages.length <= request2.userMessages.length && loggedUserMessages.every((message, index) => {
|
|
15104
|
+
const candidate = request2.userMessages[index];
|
|
14893
15105
|
return candidate?.prompt === message.prompt && candidate.actorUserId === message.actorUserId && candidate.actorLabel === message.actorLabel && JSON.stringify(candidate.attachments ?? []) === JSON.stringify(message.attachments ?? []);
|
|
14894
15106
|
});
|
|
14895
15107
|
const request = requests.find((candidate) => candidate.requestId === requestId && candidate.claimedBy === ownerId && hasLoggedPrefix(candidate)) ?? requests.find((candidate) => candidate.execution?.supersededRequestIds?.includes(requestId) && hasLoggedPrefix(candidate));
|
|
@@ -14907,6 +15119,60 @@ function markRuntimeUserTurnMessagesLogged(topicId, requestId, ownerId, loggedUs
|
|
|
14907
15119
|
return result.changes === 1;
|
|
14908
15120
|
}).immediate();
|
|
14909
15121
|
}
|
|
15122
|
+
function claimNextRuntimeUserTurnRequest(ownerId, now = Date.now()) {
|
|
15123
|
+
return db.transaction(() => {
|
|
15124
|
+
const row = db.query(`SELECT r.*
|
|
15125
|
+
FROM runtime_user_turn_requests r
|
|
15126
|
+
LEFT JOIN runtime_turn_leases l ON l.topic_id = r.topic_id
|
|
15127
|
+
LEFT JOIN runtime_topic_state s ON s.topic_id = r.topic_id
|
|
15128
|
+
WHERE (l.topic_id IS NULL OR l.heartbeat_at < ?)
|
|
15129
|
+
AND (s.topic_id IS NULL OR s.maintenance = 0 OR s.heartbeat_at < ?)
|
|
15130
|
+
AND r.topic_epoch = COALESCE(s.epoch, 0)
|
|
15131
|
+
AND NOT EXISTS (
|
|
15132
|
+
SELECT 1
|
|
15133
|
+
FROM runtime_user_turn_requests active
|
|
15134
|
+
WHERE active.topic_id = r.topic_id
|
|
15135
|
+
AND active.request_id <> r.request_id
|
|
15136
|
+
AND active.claimed_at IS NOT NULL
|
|
15137
|
+
AND active.claimed_at >= ?
|
|
15138
|
+
)
|
|
15139
|
+
AND (
|
|
15140
|
+
(r.status = 'pending' AND (r.claimed_at IS NULL OR r.claimed_at < ?))
|
|
15141
|
+
OR (r.status = 'running' AND (r.claimed_at IS NULL OR r.claimed_at < ?))
|
|
15142
|
+
)
|
|
15143
|
+
ORDER BY r.created_at ASC, r.rowid ASC
|
|
15144
|
+
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);
|
|
15145
|
+
if (!row)
|
|
15146
|
+
return null;
|
|
15147
|
+
const updated = db.query(`UPDATE runtime_user_turn_requests
|
|
15148
|
+
SET claimed_by = ?, claimed_at = ?
|
|
15149
|
+
WHERE request_id = ? AND topic_id = ?
|
|
15150
|
+
AND (
|
|
15151
|
+
(status = 'pending' AND (claimed_at IS NULL OR claimed_at < ?))
|
|
15152
|
+
OR (status = 'running' AND (claimed_at IS NULL OR claimed_at < ?))
|
|
15153
|
+
)`).run(ownerId, now, row.request_id, row.topic_id, now - REQUEST_CLAIM_STALE_MS, now - REQUEST_CLAIM_STALE_MS);
|
|
15154
|
+
if (Number(updated.changes ?? 0) === 0)
|
|
15155
|
+
return null;
|
|
15156
|
+
return rowToRequest({ ...row, claimed_by: ownerId, claimed_at: now });
|
|
15157
|
+
}).immediate();
|
|
15158
|
+
}
|
|
15159
|
+
function markRuntimeUserTurnRunning(topicId, requestId, ownerId, queryId) {
|
|
15160
|
+
const result = db.query(`UPDATE runtime_user_turn_requests
|
|
15161
|
+
SET status = 'running', running_query_id = ?, claimed_at = ?
|
|
15162
|
+
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(queryId, Date.now(), topicId, requestId, ownerId);
|
|
15163
|
+
return Number(result.changes ?? 0) > 0;
|
|
15164
|
+
}
|
|
15165
|
+
function releaseRuntimeUserTurnClaim(topicId, requestId, ownerId) {
|
|
15166
|
+
const result = db.query(`UPDATE runtime_user_turn_requests
|
|
15167
|
+
SET status = 'pending', claimed_by = NULL, claimed_at = NULL, running_query_id = NULL
|
|
15168
|
+
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(topicId, requestId, ownerId);
|
|
15169
|
+
return Number(result.changes ?? 0) > 0;
|
|
15170
|
+
}
|
|
15171
|
+
function completeRuntimeUserTurnRequest(topicId, requestId, ownerId) {
|
|
15172
|
+
const result = db.query(`DELETE FROM runtime_user_turn_requests
|
|
15173
|
+
WHERE topic_id = ? AND request_id = ? AND claimed_by = ?`).run(topicId, requestId, ownerId);
|
|
15174
|
+
return Number(result.changes ?? 0) > 0;
|
|
15175
|
+
}
|
|
14910
15176
|
function cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, epoch) {
|
|
14911
15177
|
const rows = db.query("SELECT request_id FROM runtime_user_turn_requests WHERE topic_id = ? AND topic_epoch < ?").all(topicId, epoch);
|
|
14912
15178
|
db.query("DELETE FROM runtime_user_turn_requests WHERE topic_id = ? AND topic_epoch < ?").run(topicId, epoch);
|
|
@@ -14944,10 +15210,36 @@ var init_runtime_turn_requests = __esm(async () => {
|
|
|
14944
15210
|
});
|
|
14945
15211
|
|
|
14946
15212
|
// ../../packages/core/src/topics/session.ts
|
|
15213
|
+
var exports_session = {};
|
|
15214
|
+
__export(exports_session, {
|
|
15215
|
+
splitCompactionPairs: () => splitCompactionPairs,
|
|
15216
|
+
shouldUseCompactionLog: () => shouldUseCompactionLog,
|
|
15217
|
+
shouldCompactForkEntries: () => shouldCompactForkEntries,
|
|
15218
|
+
restartTopicSession: () => restartTopicSession,
|
|
15219
|
+
createCompactedRolloutEntries: () => createCompactedRolloutEntries,
|
|
15220
|
+
compactTopicSession: () => compactTopicSession,
|
|
15221
|
+
COMPACTION_RETAINED_TAIL_TOKENS: () => COMPACTION_RETAINED_TAIL_TOKENS,
|
|
15222
|
+
AUTO_FORK_COMPACTION_TOKENS: () => AUTO_FORK_COMPACTION_TOKENS
|
|
15223
|
+
});
|
|
14947
15224
|
import { randomUUID as randomUUID12 } from "crypto";
|
|
14948
15225
|
import { mkdtempSync as mkdtempSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "fs";
|
|
14949
15226
|
import { tmpdir as tmpdir4 } from "os";
|
|
14950
15227
|
import { join as join23 } from "path";
|
|
15228
|
+
async function waitForMemoryArchive(settled, timeoutMs) {
|
|
15229
|
+
let timer;
|
|
15230
|
+
try {
|
|
15231
|
+
return await Promise.race([
|
|
15232
|
+
settled.then(() => true),
|
|
15233
|
+
new Promise((resolve17) => {
|
|
15234
|
+
timer = setTimeout(() => resolve17(false), timeoutMs);
|
|
15235
|
+
timer.unref?.();
|
|
15236
|
+
})
|
|
15237
|
+
]);
|
|
15238
|
+
} finally {
|
|
15239
|
+
if (timer)
|
|
15240
|
+
clearTimeout(timer);
|
|
15241
|
+
}
|
|
15242
|
+
}
|
|
14951
15243
|
async function fenceTopicWork(topicId, maintenance) {
|
|
14952
15244
|
for (const queryId of cancelRuntimeUserTurnRequestsBeforeEpoch(topicId, maintenance.epoch)) {
|
|
14953
15245
|
WsHub.get().broadcastAborted(topicId, queryId, "stopped");
|
|
@@ -14972,6 +15264,97 @@ function hasTopicWorkInFlight(topicId) {
|
|
|
14972
15264
|
function topicIsQuiescedForNonPreemptiveWork(topicId) {
|
|
14973
15265
|
return !hasTopicWorkInFlight(topicId);
|
|
14974
15266
|
}
|
|
15267
|
+
async function restartTopicSession(topicId, userId, reason = "topic-session-restart", options = {}) {
|
|
15268
|
+
const topic = getTopic(topicId);
|
|
15269
|
+
if (!topic)
|
|
15270
|
+
return { text: "Topic not found.", isError: true };
|
|
15271
|
+
if (isLegacySharedGeneral(topic.id)) {
|
|
15272
|
+
return { text: "The legacy shared General session cannot be reset.", isError: true };
|
|
15273
|
+
}
|
|
15274
|
+
const owner = topic.participants.some((participant) => participant.userId === userId && participant.role === "owner");
|
|
15275
|
+
if (!owner)
|
|
15276
|
+
return { text: "Only the topic owner can reset the session.", isError: true };
|
|
15277
|
+
const maintenance = beginRuntimeTopicMaintenance(topicId);
|
|
15278
|
+
if (!maintenance)
|
|
15279
|
+
return { text: "Topic maintenance is already in progress.", isError: true };
|
|
15280
|
+
try {
|
|
15281
|
+
const fenceError = await fenceTopicWork(topicId, maintenance);
|
|
15282
|
+
if (fenceError)
|
|
15283
|
+
return { text: fenceError, isError: true };
|
|
15284
|
+
cancelIdleArchiveForTopic(topicId);
|
|
15285
|
+
cancelIdleCompactForTopic(topicId);
|
|
15286
|
+
const rawArchivePaths = [];
|
|
15287
|
+
try {
|
|
15288
|
+
for (const participantUserId of new Set([
|
|
15289
|
+
userId,
|
|
15290
|
+
...topic.participants.map((participant) => participant.userId)
|
|
15291
|
+
])) {
|
|
15292
|
+
const archived = archiveConversationEvents(topicId, topic.title, participantUserId, {
|
|
15293
|
+
reason: "reset"
|
|
15294
|
+
});
|
|
15295
|
+
if (archived)
|
|
15296
|
+
rawArchivePaths.push(archived.path);
|
|
15297
|
+
}
|
|
15298
|
+
} catch (error) {
|
|
15299
|
+
return {
|
|
15300
|
+
text: `Session reset could not archive the raw conversation: ${error instanceof Error ? error.message : String(error)}`,
|
|
15301
|
+
isError: true
|
|
15302
|
+
};
|
|
15303
|
+
}
|
|
15304
|
+
let settleMemoryArchive;
|
|
15305
|
+
const memoryArchiveSettled = new Promise((resolve17) => {
|
|
15306
|
+
settleMemoryArchive = resolve17;
|
|
15307
|
+
});
|
|
15308
|
+
const archiveStatus = (options.archiveMemory ?? archiveActiveTopicForMemory)(topicId, options.memoryUserId ?? userId, {
|
|
15309
|
+
reason: "reset",
|
|
15310
|
+
minMessages: 1,
|
|
15311
|
+
minExchanges: MIN_MEMORY_ARCHIVE_EXCHANGES,
|
|
15312
|
+
allowMentionOnly: true,
|
|
15313
|
+
skipBusyCheck: true,
|
|
15314
|
+
rawArchivePaths,
|
|
15315
|
+
onSettled: () => settleMemoryArchive?.()
|
|
15316
|
+
});
|
|
15317
|
+
if (archiveStatus === "archived") {
|
|
15318
|
+
const archiveFinished = await waitForMemoryArchive(memoryArchiveSettled, options.memoryArchiveWaitMs ?? RESET_MEMORY_ARCHIVE_WAIT_MS);
|
|
15319
|
+
if (!archiveFinished) {
|
|
15320
|
+
return {
|
|
15321
|
+
text: "Memory archiving did not finish in time. The session was not reset.",
|
|
15322
|
+
isError: true
|
|
15323
|
+
};
|
|
15324
|
+
}
|
|
15325
|
+
}
|
|
15326
|
+
if (!maintenance.isOwned()) {
|
|
15327
|
+
return { text: "Topic maintenance ownership was lost. Try again.", isError: true };
|
|
15328
|
+
}
|
|
15329
|
+
const sessionId = getTopicSessionId(topicId);
|
|
15330
|
+
const purgeLogs = options.purgeLogs ?? purgeTopicLogs;
|
|
15331
|
+
const participantUserIds = Array.from(new Set([userId, ...topic.participants.map((participant) => participant.userId)]));
|
|
15332
|
+
for (const [index, participantUserId] of participantUserIds.entries()) {
|
|
15333
|
+
let purged = false;
|
|
15334
|
+
try {
|
|
15335
|
+
purged = await purgeLogs({
|
|
15336
|
+
userId: participantUserId,
|
|
15337
|
+
topicName: topic.title,
|
|
15338
|
+
cwd: resolveTopicWorkspaceDir(topicId),
|
|
15339
|
+
extraSessions: index === 0 && topic.agent && sessionId ? [{ agent: topic.agent, sessionId }] : []
|
|
15340
|
+
});
|
|
15341
|
+
} catch (error) {
|
|
15342
|
+
logger.warn({ err: error, topicId, userId: participantUserId }, "restartTopicSession: participant context cleanup failed");
|
|
15343
|
+
}
|
|
15344
|
+
if (!purged) {
|
|
15345
|
+
return {
|
|
15346
|
+
text: "Session reset could not remove all provider context. The current session was kept.",
|
|
15347
|
+
isError: true
|
|
15348
|
+
};
|
|
15349
|
+
}
|
|
15350
|
+
}
|
|
15351
|
+
clearTopicSessionId(topicId, reason);
|
|
15352
|
+
clearQueryUsageAlert(userId, topicId);
|
|
15353
|
+
return { text: `Session reset for "${topic.title}". The next message starts fresh.` };
|
|
15354
|
+
} finally {
|
|
15355
|
+
maintenance.finish();
|
|
15356
|
+
}
|
|
15357
|
+
}
|
|
14975
15358
|
function previousCompactedSummary(entries) {
|
|
14976
15359
|
for (let index = entries.length - 2;index >= 0; index -= 1) {
|
|
14977
15360
|
const request = entries[index]?.event;
|
|
@@ -14986,9 +15369,9 @@ The assistant response is the authoritative summary of all earlier context.` &&
|
|
|
14986
15369
|
function withoutCompactionSentinels(entries) {
|
|
14987
15370
|
const filtered = [];
|
|
14988
15371
|
for (let index = 0;index < entries.length; index++) {
|
|
14989
|
-
const
|
|
15372
|
+
const current2 = entries[index]?.event;
|
|
14990
15373
|
const next = entries[index + 1]?.event;
|
|
14991
|
-
if (
|
|
15374
|
+
if (current2?.type === "user_message" && current2.synthetic === "compaction" && next?.type === "result") {
|
|
14992
15375
|
index += 1;
|
|
14993
15376
|
continue;
|
|
14994
15377
|
}
|
|
@@ -15038,18 +15421,18 @@ function retainedPairEntries(agent, pairs) {
|
|
|
15038
15421
|
}
|
|
15039
15422
|
return entries;
|
|
15040
15423
|
}
|
|
15041
|
-
function fitCompactionChunk(
|
|
15042
|
-
if (
|
|
15043
|
-
return
|
|
15424
|
+
function fitCompactionChunk(text2, limit) {
|
|
15425
|
+
if (text2.length <= limit)
|
|
15426
|
+
return text2;
|
|
15044
15427
|
const marker = `
|
|
15045
15428
|
[\u2026]
|
|
15046
15429
|
`;
|
|
15047
15430
|
if (limit <= marker.length)
|
|
15048
|
-
return
|
|
15431
|
+
return text2.slice(0, limit);
|
|
15049
15432
|
const available = limit - marker.length;
|
|
15050
15433
|
const headChars = Math.ceil(available * 0.6);
|
|
15051
15434
|
const tailChars = available - headChars;
|
|
15052
|
-
return `${
|
|
15435
|
+
return `${text2.slice(0, headChars)}${marker}${text2.slice(-tailChars)}`;
|
|
15053
15436
|
}
|
|
15054
15437
|
function buildCompactionSource(topicId, userId, entries, visibleMessages, providerPairs) {
|
|
15055
15438
|
const sections = [];
|
|
@@ -15450,9 +15833,9 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15450
15833
|
const compactionExecution = resolveCompactionExecution(agent, registry);
|
|
15451
15834
|
const cwd = resolveTopicWorkspaceDir(topicId);
|
|
15452
15835
|
const oldEntries = readConversation(userId, topic.title);
|
|
15453
|
-
let
|
|
15836
|
+
let compactEntries2;
|
|
15454
15837
|
try {
|
|
15455
|
-
|
|
15838
|
+
compactEntries2 = await createCompactedRolloutEntries({
|
|
15456
15839
|
topicId,
|
|
15457
15840
|
topicTitle: topic.title,
|
|
15458
15841
|
userId,
|
|
@@ -15478,7 +15861,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15478
15861
|
try {
|
|
15479
15862
|
replacement = getRegistryOperations(agent).writeRollout({
|
|
15480
15863
|
cwd,
|
|
15481
|
-
entries:
|
|
15864
|
+
entries: compactEntries2,
|
|
15482
15865
|
model,
|
|
15483
15866
|
...effort ? { effort } : {}
|
|
15484
15867
|
});
|
|
@@ -15508,7 +15891,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15508
15891
|
}
|
|
15509
15892
|
try {
|
|
15510
15893
|
replaceConversationStrict(userId, topic.title, [
|
|
15511
|
-
...
|
|
15894
|
+
...compactEntries2,
|
|
15512
15895
|
...priorSessionEntries,
|
|
15513
15896
|
replacementSessionEntry
|
|
15514
15897
|
]);
|
|
@@ -15545,7 +15928,7 @@ async function compactTopicSession(topicId, userId, reason = "topic-session-comp
|
|
|
15545
15928
|
} else {
|
|
15546
15929
|
try {
|
|
15547
15930
|
replaceConversationStrict(userId, topic.title, [
|
|
15548
|
-
...
|
|
15931
|
+
...compactEntries2,
|
|
15549
15932
|
replacementSessionEntry
|
|
15550
15933
|
]);
|
|
15551
15934
|
} catch (manifestError) {
|
|
@@ -15599,11 +15982,45 @@ var init_session = __esm(async () => {
|
|
|
15599
15982
|
});
|
|
15600
15983
|
|
|
15601
15984
|
// ../../packages/core/src/topics/derive.ts
|
|
15985
|
+
var exports_derive = {};
|
|
15986
|
+
__export(exports_derive, {
|
|
15987
|
+
updateTopic: () => updateTopic,
|
|
15988
|
+
isParticipant: () => isParticipant,
|
|
15989
|
+
getVisibleTopics: () => getVisibleTopics,
|
|
15990
|
+
getTopics: () => getTopics,
|
|
15991
|
+
createDerivedTopic: () => createDerivedTopic,
|
|
15992
|
+
TopicTitleConflictError: () => TopicTitleConflictError,
|
|
15993
|
+
TopicForkCompactionError: () => TopicForkCompactionError,
|
|
15994
|
+
TopicDeriveBusyError: () => TopicDeriveBusyError
|
|
15995
|
+
});
|
|
15602
15996
|
import { createHash as createHash9, randomUUID as randomUUID13 } from "crypto";
|
|
15603
15997
|
import { mkdirSync as mkdirSync14, rmSync as rmSync5, unlinkSync as unlinkSync13 } from "fs";
|
|
15604
15998
|
function getTopics(opts = {}) {
|
|
15605
15999
|
return listTopics(opts).filter((topic) => !isLegacySharedGeneral(topic.id));
|
|
15606
16000
|
}
|
|
16001
|
+
function getVisibleTopics(opts = {}) {
|
|
16002
|
+
return getTopics(opts).filter(isTopicVisible).map((topic) => {
|
|
16003
|
+
if (!topic.agent)
|
|
16004
|
+
return topic;
|
|
16005
|
+
const registry = getRegistry(topic.agent);
|
|
16006
|
+
const config = getApiTopicConfig(topic.id);
|
|
16007
|
+
const requestedEffort = config?.effort ?? topic.defaultEffort;
|
|
16008
|
+
return {
|
|
16009
|
+
...topic,
|
|
16010
|
+
effectiveModel: resolveModelForAgent(topic.agent, config?.model ?? topic.defaultModel, registry),
|
|
16011
|
+
effectiveEffort: requestedEffort && registry.validateEffort(requestedEffort) ? requestedEffort : registry.defaultEffort
|
|
16012
|
+
};
|
|
16013
|
+
});
|
|
16014
|
+
}
|
|
16015
|
+
function updateTopic(topicId, patch) {
|
|
16016
|
+
const topic = getTopic(topicId);
|
|
16017
|
+
if (!topic)
|
|
16018
|
+
return false;
|
|
16019
|
+
Object.assign(topic, patch);
|
|
16020
|
+
upsertTopic(topic);
|
|
16021
|
+
WsHub.get().broadcastTopicUpdated(topicId);
|
|
16022
|
+
return true;
|
|
16023
|
+
}
|
|
15607
16024
|
function isParticipant(topic, userId) {
|
|
15608
16025
|
return topic.participants.some((p) => p.userId === userId);
|
|
15609
16026
|
}
|
|
@@ -16019,9 +16436,9 @@ function subagentLineageTopicIds(currentTopicId) {
|
|
|
16019
16436
|
const children = new Set;
|
|
16020
16437
|
if (!currentTopicId)
|
|
16021
16438
|
return { reachable, children };
|
|
16022
|
-
const
|
|
16023
|
-
if (
|
|
16024
|
-
reachable.add(
|
|
16439
|
+
const current2 = getTopic(currentTopicId);
|
|
16440
|
+
if (current2?.isSubagent && current2.parentTopicId) {
|
|
16441
|
+
reachable.add(current2.parentTopicId);
|
|
16025
16442
|
for (const id of listSubagentTellTargetIds(currentTopicId))
|
|
16026
16443
|
reachable.add(id);
|
|
16027
16444
|
}
|
|
@@ -16147,9 +16564,9 @@ function cleanupSessionInboxFiles(userId, topicId, legacyTopicTitle) {
|
|
|
16147
16564
|
try {
|
|
16148
16565
|
unlinkSync15(path);
|
|
16149
16566
|
deleted++;
|
|
16150
|
-
} catch (
|
|
16151
|
-
if (
|
|
16152
|
-
logger.warn({ err, path, topicId, userId }, "topic cleanup: inbox unlink failed");
|
|
16567
|
+
} catch (err2) {
|
|
16568
|
+
if (err2?.code !== "ENOENT") {
|
|
16569
|
+
logger.warn({ err: err2, path, topicId, userId }, "topic cleanup: inbox unlink failed");
|
|
16153
16570
|
}
|
|
16154
16571
|
}
|
|
16155
16572
|
}
|
|
@@ -16274,9 +16691,9 @@ function hubHeaders(bearer) {
|
|
|
16274
16691
|
};
|
|
16275
16692
|
}
|
|
16276
16693
|
function errorText(status, body, fallback) {
|
|
16277
|
-
const
|
|
16278
|
-
if (typeof
|
|
16279
|
-
return
|
|
16694
|
+
const text2 = body?.error;
|
|
16695
|
+
if (typeof text2 === "string" && text2.trim())
|
|
16696
|
+
return text2.trim();
|
|
16280
16697
|
return `${fallback} (hub answered ${status})`;
|
|
16281
16698
|
}
|
|
16282
16699
|
function describeFailure(status, body) {
|
|
@@ -16372,6 +16789,19 @@ var init_actor_policy = __esm(async () => {
|
|
|
16372
16789
|
await init_actor_topic_reach();
|
|
16373
16790
|
});
|
|
16374
16791
|
// ../../packages/core/src/storage/session-asks.ts
|
|
16792
|
+
var exports_session_asks = {};
|
|
16793
|
+
__export(exports_session_asks, {
|
|
16794
|
+
releasePendingAsk: () => releasePendingAsk,
|
|
16795
|
+
markPendingAskState: () => markPendingAskState,
|
|
16796
|
+
markPendingAskSources: () => markPendingAskSources,
|
|
16797
|
+
listPendingAsksForCaller: () => listPendingAsksForCaller,
|
|
16798
|
+
describePendingAskState: () => describePendingAskState,
|
|
16799
|
+
deletePendingAsksForTopic: () => deletePendingAsksForTopic,
|
|
16800
|
+
createPendingAsk: () => createPendingAsk,
|
|
16801
|
+
clearPendingAskSources: () => clearPendingAskSources,
|
|
16802
|
+
clearPendingAsk: () => clearPendingAsk,
|
|
16803
|
+
PENDING_ASK_TTL_MS: () => PENDING_ASK_TTL_MS
|
|
16804
|
+
});
|
|
16375
16805
|
import { createHash as createHash10 } from "crypto";
|
|
16376
16806
|
import {
|
|
16377
16807
|
closeSync as closeSync2,
|
|
@@ -16393,8 +16823,8 @@ function encodeAskKey(key) {
|
|
|
16393
16823
|
return JSON.stringify([key.from, key.to]);
|
|
16394
16824
|
}
|
|
16395
16825
|
function pendingAskPath(key) {
|
|
16396
|
-
const
|
|
16397
|
-
return join28(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${
|
|
16826
|
+
const digest2 = createHash10("sha256").update(encodeAskKey(key)).digest("hex");
|
|
16827
|
+
return join28(pendingAskDir(key.userId), `${ASK_FILENAME_PREFIX}${digest2}.pending`);
|
|
16398
16828
|
}
|
|
16399
16829
|
function v2PendingAskPath(key) {
|
|
16400
16830
|
const encoded = Buffer.from(encodeAskKey(key), "utf8").toString("base64url");
|
|
@@ -16420,10 +16850,10 @@ function parsePendingAskFilename(fileName) {
|
|
|
16420
16850
|
}
|
|
16421
16851
|
} catch {}
|
|
16422
16852
|
}
|
|
16423
|
-
const
|
|
16424
|
-
if (
|
|
16853
|
+
const sep3 = raw.indexOf("___");
|
|
16854
|
+
if (sep3 < 0)
|
|
16425
16855
|
return null;
|
|
16426
|
-
return { from: raw.slice(0,
|
|
16856
|
+
return { from: raw.slice(0, sep3), to: raw.slice(sep3 + 3) };
|
|
16427
16857
|
}
|
|
16428
16858
|
function readPendingAskFile(path, fallback) {
|
|
16429
16859
|
try {
|
|
@@ -16466,6 +16896,16 @@ function readPendingAskFile(path, fallback) {
|
|
|
16466
16896
|
return null;
|
|
16467
16897
|
}
|
|
16468
16898
|
}
|
|
16899
|
+
function isStale(record, path) {
|
|
16900
|
+
const ts = record ? Date.parse(record.updatedAt || record.createdAt) : Number.NaN;
|
|
16901
|
+
if (Number.isFinite(ts))
|
|
16902
|
+
return Date.now() - ts > PENDING_ASK_TTL_MS;
|
|
16903
|
+
try {
|
|
16904
|
+
return Date.now() - statSync8(path).mtimeMs > PENDING_ASK_TTL_MS;
|
|
16905
|
+
} catch {
|
|
16906
|
+
return false;
|
|
16907
|
+
}
|
|
16908
|
+
}
|
|
16469
16909
|
function writePendingAsk(record) {
|
|
16470
16910
|
const path = pendingAskPath(record);
|
|
16471
16911
|
mkdirSync16(pendingAskDir(record.userId), { recursive: true });
|
|
@@ -16491,10 +16931,10 @@ function writePendingAskIfAbsent(record) {
|
|
|
16491
16931
|
}
|
|
16492
16932
|
}
|
|
16493
16933
|
function readPendingAsk(key) {
|
|
16494
|
-
const
|
|
16495
|
-
const canonical = readPendingAskFile(
|
|
16934
|
+
const canonicalPath2 = pendingAskPath(key);
|
|
16935
|
+
const canonical = readPendingAskFile(canonicalPath2, key);
|
|
16496
16936
|
if (canonical && canonical.from === key.from && canonical.to === key.to) {
|
|
16497
|
-
return { path:
|
|
16937
|
+
return { path: canonicalPath2, record: canonical };
|
|
16498
16938
|
}
|
|
16499
16939
|
for (const compatibilityPath of [v2PendingAskPath(key), legacyPendingAskPath(key)]) {
|
|
16500
16940
|
if (!compatibilityPath)
|
|
@@ -16503,17 +16943,67 @@ function readPendingAsk(key) {
|
|
|
16503
16943
|
if (!legacy || legacy.from !== key.from || legacy.to !== key.to)
|
|
16504
16944
|
continue;
|
|
16505
16945
|
const migrated = writePendingAskIfAbsent(legacy);
|
|
16506
|
-
const next = migrated ? legacy : readPendingAskFile(
|
|
16946
|
+
const next = migrated ? legacy : readPendingAskFile(canonicalPath2, key);
|
|
16507
16947
|
if (next && next.from === key.from && next.to === key.to) {
|
|
16508
16948
|
try {
|
|
16509
16949
|
unlinkSync16(compatibilityPath);
|
|
16510
16950
|
} catch {}
|
|
16511
|
-
return { path:
|
|
16951
|
+
return { path: canonicalPath2, record: next };
|
|
16512
16952
|
}
|
|
16513
16953
|
return { path: compatibilityPath, record: legacy };
|
|
16514
16954
|
}
|
|
16515
16955
|
return null;
|
|
16516
16956
|
}
|
|
16957
|
+
function createPendingAsk(args) {
|
|
16958
|
+
const migrated = readPendingAsk(args);
|
|
16959
|
+
if (migrated && !isStale(migrated.record, migrated.path)) {
|
|
16960
|
+
return { ok: false, existing: migrated.record, stale: false };
|
|
16961
|
+
}
|
|
16962
|
+
if (migrated) {
|
|
16963
|
+
try {
|
|
16964
|
+
unlinkSync16(migrated.path);
|
|
16965
|
+
} catch {
|
|
16966
|
+
return { ok: false, existing: migrated.record, stale: true };
|
|
16967
|
+
}
|
|
16968
|
+
}
|
|
16969
|
+
const path = pendingAskPath(args);
|
|
16970
|
+
const now = new Date().toISOString();
|
|
16971
|
+
const record = {
|
|
16972
|
+
userId: args.userId,
|
|
16973
|
+
from: args.from,
|
|
16974
|
+
to: args.to,
|
|
16975
|
+
requestId: args.requestId,
|
|
16976
|
+
contextId: args.contextId,
|
|
16977
|
+
state: "requested",
|
|
16978
|
+
createdAt: now,
|
|
16979
|
+
updatedAt: now
|
|
16980
|
+
};
|
|
16981
|
+
mkdirSync16(pendingAskDir(args.userId), { recursive: true });
|
|
16982
|
+
for (let attempt = 0;attempt < 2; attempt++) {
|
|
16983
|
+
let fd = null;
|
|
16984
|
+
try {
|
|
16985
|
+
fd = openSync2(path, "wx");
|
|
16986
|
+
writeFileSync14(fd, `${JSON.stringify(record)}
|
|
16987
|
+
`);
|
|
16988
|
+
return { ok: true, record };
|
|
16989
|
+
} catch (err2) {
|
|
16990
|
+
if (err2.code !== "EEXIST")
|
|
16991
|
+
throw err2;
|
|
16992
|
+
const existing = readPendingAskFile(path, args);
|
|
16993
|
+
if (!isStale(existing, path))
|
|
16994
|
+
return { ok: false, existing, stale: false };
|
|
16995
|
+
try {
|
|
16996
|
+
unlinkSync16(path);
|
|
16997
|
+
} catch {
|
|
16998
|
+
return { ok: false, existing, stale: true };
|
|
16999
|
+
}
|
|
17000
|
+
} finally {
|
|
17001
|
+
if (fd !== null)
|
|
17002
|
+
closeSync2(fd);
|
|
17003
|
+
}
|
|
17004
|
+
}
|
|
17005
|
+
return { ok: false, existing: readPendingAskFile(path, args), stale: true };
|
|
17006
|
+
}
|
|
16517
17007
|
function markPendingAskState(args) {
|
|
16518
17008
|
const pending = readPendingAsk(args);
|
|
16519
17009
|
if (!pending)
|
|
@@ -16547,6 +17037,83 @@ function clearPendingAsk(args) {
|
|
|
16547
17037
|
return false;
|
|
16548
17038
|
}
|
|
16549
17039
|
}
|
|
17040
|
+
function releasePendingAsk(args) {
|
|
17041
|
+
if (clearPendingAsk(args))
|
|
17042
|
+
return true;
|
|
17043
|
+
const still = readPendingAsk(args);
|
|
17044
|
+
return !still || still.record.requestId !== args.requestId;
|
|
17045
|
+
}
|
|
17046
|
+
function markPendingAskSources(args) {
|
|
17047
|
+
for (const source of args.sources ?? []) {
|
|
17048
|
+
if (!source.from)
|
|
17049
|
+
continue;
|
|
17050
|
+
markPendingAskState({
|
|
17051
|
+
userId: args.userId,
|
|
17052
|
+
from: args.callerTopic,
|
|
17053
|
+
to: source.from,
|
|
17054
|
+
requestId: source.requestId,
|
|
17055
|
+
state: args.state
|
|
17056
|
+
});
|
|
17057
|
+
}
|
|
17058
|
+
}
|
|
17059
|
+
function clearPendingAskSources(args) {
|
|
17060
|
+
for (const source of args.sources ?? []) {
|
|
17061
|
+
if (!source.from)
|
|
17062
|
+
continue;
|
|
17063
|
+
clearPendingAsk({
|
|
17064
|
+
userId: args.userId,
|
|
17065
|
+
from: args.callerTopic,
|
|
17066
|
+
to: source.from,
|
|
17067
|
+
requestId: source.requestId
|
|
17068
|
+
});
|
|
17069
|
+
}
|
|
17070
|
+
}
|
|
17071
|
+
function listPendingAsksForCaller(args) {
|
|
17072
|
+
const dir = pendingAskDir(args.userId);
|
|
17073
|
+
let files;
|
|
17074
|
+
try {
|
|
17075
|
+
files = readdirSync4(dir);
|
|
17076
|
+
} catch {
|
|
17077
|
+
return [];
|
|
17078
|
+
}
|
|
17079
|
+
const records = new Map;
|
|
17080
|
+
for (const fileName of files) {
|
|
17081
|
+
const isV3 = fileName.startsWith(ASK_FILENAME_PREFIX);
|
|
17082
|
+
const parsed = isV3 ? { from: args.from, to: "" } : parsePendingAskFilename(fileName);
|
|
17083
|
+
if (!parsed)
|
|
17084
|
+
continue;
|
|
17085
|
+
const path = join28(dir, fileName);
|
|
17086
|
+
const record = readPendingAskFile(path, {
|
|
17087
|
+
userId: args.userId,
|
|
17088
|
+
from: parsed.from,
|
|
17089
|
+
to: parsed.to
|
|
17090
|
+
});
|
|
17091
|
+
if (!record || record.from !== args.from)
|
|
17092
|
+
continue;
|
|
17093
|
+
if (isStale(record, path)) {
|
|
17094
|
+
try {
|
|
17095
|
+
unlinkSync16(path);
|
|
17096
|
+
} catch {}
|
|
17097
|
+
continue;
|
|
17098
|
+
}
|
|
17099
|
+
const canonical = readPendingAsk(record);
|
|
17100
|
+
if (!canonical || canonical.record.from !== args.from)
|
|
17101
|
+
continue;
|
|
17102
|
+
if (path !== canonical.path) {
|
|
17103
|
+
try {
|
|
17104
|
+
unlinkSync16(path);
|
|
17105
|
+
} catch {}
|
|
17106
|
+
}
|
|
17107
|
+
if (isStale(canonical.record, canonical.path)) {
|
|
17108
|
+
try {
|
|
17109
|
+
unlinkSync16(canonical.path);
|
|
17110
|
+
} catch {}
|
|
17111
|
+
continue;
|
|
17112
|
+
}
|
|
17113
|
+
records.set(encodeAskKey(canonical.record), canonical.record);
|
|
17114
|
+
}
|
|
17115
|
+
return [...records.values()];
|
|
17116
|
+
}
|
|
16550
17117
|
function deletePendingAsksForTopic(args) {
|
|
16551
17118
|
const dir = pendingAskDir(args.userId);
|
|
16552
17119
|
let files;
|
|
@@ -16575,6 +17142,18 @@ function deletePendingAsksForTopic(args) {
|
|
|
16575
17142
|
}
|
|
16576
17143
|
return deleted;
|
|
16577
17144
|
}
|
|
17145
|
+
function describePendingAskState(state) {
|
|
17146
|
+
switch (state) {
|
|
17147
|
+
case "requested":
|
|
17148
|
+
return "\uB300\uC0C1 \uC138\uC158 \uCC98\uB9AC \uC911";
|
|
17149
|
+
case "reply_ready":
|
|
17150
|
+
return "\uC751\uB2F5 \uC0DD\uC131 \uC644\uB8CC, \uC774 \uC138\uC158 \uC8FC\uC785 \uC900\uBE44 \uC911";
|
|
17151
|
+
case "queued_for_caller":
|
|
17152
|
+
return "\uC751\uB2F5 \uC0DD\uC131 \uC644\uB8CC, \uC774 \uC138\uC158 \uC2E4\uD589 \uC885\uB8CC \uD6C4 \uC8FC\uC785 \uB300\uAE30 \uC911";
|
|
17153
|
+
case "injecting_to_caller":
|
|
17154
|
+
return "\uC751\uB2F5\uC744 \uC774 \uC138\uC158\uC5D0 \uC8FC\uC785 \uC911";
|
|
17155
|
+
}
|
|
17156
|
+
}
|
|
16578
17157
|
var PENDING_ASK_TTL_MS, ASK_FILENAME_PREFIX = "v3-", V2_ASK_FILENAME_PREFIX = "v2-";
|
|
16579
17158
|
var init_session_asks = __esm(async () => {
|
|
16580
17159
|
await init_storage_host();
|
|
@@ -16676,10 +17255,10 @@ function deferRemoteSessionReplyOutbox(args) {
|
|
|
16676
17255
|
if (!row)
|
|
16677
17256
|
return;
|
|
16678
17257
|
const attempts = Number(row.attempts) + 1;
|
|
16679
|
-
const
|
|
17258
|
+
const delay2 = args.retryMs ?? remoteSessionRetryDelayMs(attempts, args.random);
|
|
16680
17259
|
db.query(`UPDATE remote_session_reply_outbox
|
|
16681
17260
|
SET attempts = ?, next_attempt_at = ?, last_error = ?
|
|
16682
|
-
WHERE request_id = ?`).run(attempts, now +
|
|
17261
|
+
WHERE request_id = ?`).run(attempts, now + delay2, args.error.slice(0, 500), args.requestId);
|
|
16683
17262
|
})();
|
|
16684
17263
|
}
|
|
16685
17264
|
function purgeExpiredRemoteSessionReplyOutbox(now = Date.now()) {
|
|
@@ -16850,9 +17429,37 @@ var init_remote_session_reply_outbox = __esm(async () => {
|
|
|
16850
17429
|
});
|
|
16851
17430
|
|
|
16852
17431
|
// ../../packages/core/src/mcp/session-comm/peer-forward.ts
|
|
17432
|
+
var exports_peer_forward = {};
|
|
17433
|
+
__export(exports_peer_forward, {
|
|
17434
|
+
registerPeerSessionBridge: () => registerPeerSessionBridge,
|
|
17435
|
+
peerSessionsForUser: () => peerSessionsForUser,
|
|
17436
|
+
parseHubRemoteReplyRoute: () => parseHubRemoteReplyRoute,
|
|
17437
|
+
isHubRemoteReplyRoute: () => isHubRemoteReplyRoute,
|
|
17438
|
+
forwardToPeer: () => forwardToPeer,
|
|
17439
|
+
deliverPeerReply: () => deliverPeerReply
|
|
17440
|
+
});
|
|
16853
17441
|
function isHubRemoteReplyRoute(route) {
|
|
16854
17442
|
return route.via === "hub";
|
|
16855
17443
|
}
|
|
17444
|
+
function parseHubRemoteReplyRoute(value) {
|
|
17445
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
17446
|
+
return null;
|
|
17447
|
+
const route = value;
|
|
17448
|
+
if (route.via !== "hub" || typeof route.hubUrl !== "string" || typeof route.token !== "string" || typeof route.nodeName !== "string" || typeof route.topicId !== "string" || typeof route.requestId !== "string") {
|
|
17449
|
+
return null;
|
|
17450
|
+
}
|
|
17451
|
+
const requestId = route.requestId.trim();
|
|
17452
|
+
const nodeName = route.nodeName.trim();
|
|
17453
|
+
const topicId = route.topicId.trim();
|
|
17454
|
+
const token = route.token.trim();
|
|
17455
|
+
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)) {
|
|
17456
|
+
return null;
|
|
17457
|
+
}
|
|
17458
|
+
const hubUrl = normalizeHubUrl(route.hubUrl.trim(), "remoteReply.hubUrl");
|
|
17459
|
+
if ("error" in hubUrl)
|
|
17460
|
+
return null;
|
|
17461
|
+
return { via: "hub", hubUrl: hubUrl.url, token, nodeName, topicId, requestId };
|
|
17462
|
+
}
|
|
16856
17463
|
function loopbackBridgeConfig() {
|
|
16857
17464
|
const rawUrl = process.env[PEER_BRIDGE_URL_ENV]?.trim();
|
|
16858
17465
|
const token = process.env[PEER_BRIDGE_TOKEN_ENV]?.trim();
|
|
@@ -16889,6 +17496,39 @@ async function callLoopbackBridge(request) {
|
|
|
16889
17496
|
return { configured: true, result: null };
|
|
16890
17497
|
}
|
|
16891
17498
|
}
|
|
17499
|
+
function registerPeerSessionBridge(bridge) {
|
|
17500
|
+
activeBridge = bridge;
|
|
17501
|
+
return () => {
|
|
17502
|
+
if (activeBridge === bridge)
|
|
17503
|
+
activeBridge = null;
|
|
17504
|
+
};
|
|
17505
|
+
}
|
|
17506
|
+
async function forwardToPeer(args) {
|
|
17507
|
+
if (activeBridge)
|
|
17508
|
+
return activeBridge.forward(args);
|
|
17509
|
+
const forwarded = await callLoopbackBridge({ action: "forward", args });
|
|
17510
|
+
if (forwarded.result)
|
|
17511
|
+
return forwarded.result;
|
|
17512
|
+
return {
|
|
17513
|
+
ok: false,
|
|
17514
|
+
error: forwarded.configured ? "remote session bridge is configured but unavailable" : "remote nodes are not connected on this negotium node (standalone mode)"
|
|
17515
|
+
};
|
|
17516
|
+
}
|
|
17517
|
+
async function peerSessionsForUser(userId, sourceQueryId, fromTopicId) {
|
|
17518
|
+
if (activeBridge)
|
|
17519
|
+
return activeBridge.sessions(userId, sourceQueryId, fromTopicId);
|
|
17520
|
+
const sessions = await callLoopbackBridge({
|
|
17521
|
+
action: "sessions",
|
|
17522
|
+
userId,
|
|
17523
|
+
sourceQueryId,
|
|
17524
|
+
fromTopicId
|
|
17525
|
+
});
|
|
17526
|
+
if (sessions.result)
|
|
17527
|
+
return sessions.result;
|
|
17528
|
+
if (sessions.configured)
|
|
17529
|
+
return { ok: false, nodes: [] };
|
|
17530
|
+
return { ok: true, nodes: [] };
|
|
17531
|
+
}
|
|
16892
17532
|
async function deliverPeerReply(route, sourceTitle, replyText, kind) {
|
|
16893
17533
|
if (isHubRemoteReplyRoute(route)) {
|
|
16894
17534
|
return deliverHubRemoteReply(route, sourceTitle, replyText, kind);
|
|
@@ -16903,13 +17543,40 @@ async function deliverPeerReply(route, sourceTitle, replyText, kind) {
|
|
|
16903
17543
|
kind
|
|
16904
17544
|
})).result ?? false;
|
|
16905
17545
|
}
|
|
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;
|
|
17546
|
+
var MAX_ROUTE_REQUEST_ID_LENGTH = 200, MAX_ROUTE_LABEL_LENGTH = 300, 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;
|
|
16907
17547
|
var init_peer_forward = __esm(async () => {
|
|
16908
17548
|
init_remote_session_grant();
|
|
16909
17549
|
await init_remote_session_reply_outbox();
|
|
16910
17550
|
});
|
|
16911
17551
|
|
|
16912
17552
|
// ../../packages/core/src/runtime/ask-callbacks.ts
|
|
17553
|
+
var exports_ask_callbacks = {};
|
|
17554
|
+
__export(exports_ask_callbacks, {
|
|
17555
|
+
resolveAskCallback: () => resolveAskCallback,
|
|
17556
|
+
registerAskCallback: () => registerAskCallback,
|
|
17557
|
+
purgeStaleAsks: () => purgeStaleAsks,
|
|
17558
|
+
failInterruptedRemoteAskCallbacks: () => failInterruptedRemoteAskCallbacks,
|
|
17559
|
+
deleteHubRemoteAskCallbackRow: () => deleteHubRemoteAskCallbackRow,
|
|
17560
|
+
cancelAskCallbacksForTopic: () => cancelAskCallbacksForTopic
|
|
17561
|
+
});
|
|
17562
|
+
function registerAskCallback(entry) {
|
|
17563
|
+
pendingAsks.set(entry.targetQueryId, entry);
|
|
17564
|
+
if (entry.remoteReply) {
|
|
17565
|
+
const route = entry.remoteReply;
|
|
17566
|
+
const hub = isHubRemoteReplyRoute(route);
|
|
17567
|
+
db.query(`INSERT INTO remote_ask_callbacks
|
|
17568
|
+
(target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, created_at, route_json)
|
|
17569
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
17570
|
+
ON CONFLICT(target_query_id) DO UPDATE SET
|
|
17571
|
+
request_id = excluded.request_id,
|
|
17572
|
+
node_name = excluded.node_name,
|
|
17573
|
+
node_cell_id = excluded.node_cell_id,
|
|
17574
|
+
topic_id = excluded.topic_id,
|
|
17575
|
+
user_id = excluded.user_id,
|
|
17576
|
+
created_at = excluded.created_at,
|
|
17577
|
+
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);
|
|
17578
|
+
}
|
|
17579
|
+
}
|
|
16913
17580
|
function resolveAskCallback(queryId) {
|
|
16914
17581
|
const entry = pendingAsks.get(queryId);
|
|
16915
17582
|
if (!entry)
|
|
@@ -16926,6 +17593,13 @@ function resolveAskCallback(queryId) {
|
|
|
16926
17593
|
function deleteHubRemoteAskCallbackRow(requestId) {
|
|
16927
17594
|
db.query("DELETE FROM remote_ask_callbacks WHERE request_id = ? AND route_json IS NOT NULL").run(requestId);
|
|
16928
17595
|
}
|
|
17596
|
+
function purgeStaleAsks(now = Date.now()) {
|
|
17597
|
+
for (const [id, entry] of pendingAsks) {
|
|
17598
|
+
if (now - entry.createdAt > MAX_ASK_AGE_MS)
|
|
17599
|
+
pendingAsks.delete(id);
|
|
17600
|
+
}
|
|
17601
|
+
db.query("DELETE FROM remote_ask_callbacks WHERE created_at < ?").run(now - MAX_ASK_AGE_MS);
|
|
17602
|
+
}
|
|
16929
17603
|
function cancelAskCallbacksForTopic(topicId) {
|
|
16930
17604
|
let cancelled = 0;
|
|
16931
17605
|
for (const [queryId, entry] of pendingAsks) {
|
|
@@ -16937,6 +17611,43 @@ function cancelAskCallbacksForTopic(topicId) {
|
|
|
16937
17611
|
}
|
|
16938
17612
|
return cancelled;
|
|
16939
17613
|
}
|
|
17614
|
+
function durableRoute(row) {
|
|
17615
|
+
if (row.route_json) {
|
|
17616
|
+
try {
|
|
17617
|
+
return parseHubRemoteReplyRoute(JSON.parse(row.route_json));
|
|
17618
|
+
} catch {
|
|
17619
|
+
return null;
|
|
17620
|
+
}
|
|
17621
|
+
}
|
|
17622
|
+
return {
|
|
17623
|
+
nodeName: row.node_name,
|
|
17624
|
+
nodeCellId: row.node_cell_id,
|
|
17625
|
+
topicId: row.topic_id,
|
|
17626
|
+
userId: row.user_id,
|
|
17627
|
+
requestId: row.request_id
|
|
17628
|
+
};
|
|
17629
|
+
}
|
|
17630
|
+
async function failInterruptedRemoteAskCallbacks(options = {}) {
|
|
17631
|
+
const rows = db.query(`SELECT target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, route_json
|
|
17632
|
+
FROM remote_ask_callbacks
|
|
17633
|
+
ORDER BY created_at ASC`).all();
|
|
17634
|
+
let failed = 0;
|
|
17635
|
+
for (const row of rows) {
|
|
17636
|
+
const route = durableRoute(row);
|
|
17637
|
+
if (!route) {
|
|
17638
|
+
db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
|
|
17639
|
+
continue;
|
|
17640
|
+
}
|
|
17641
|
+
if (options.routes === "hub" && !isHubRemoteReplyRoute(route))
|
|
17642
|
+
continue;
|
|
17643
|
+
const delivered = await deliverPeerReply(route, "peer", "The remote worker restarted before this ask completed. Please retry the request.", "error");
|
|
17644
|
+
if (!delivered)
|
|
17645
|
+
continue;
|
|
17646
|
+
db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
|
|
17647
|
+
failed++;
|
|
17648
|
+
}
|
|
17649
|
+
return failed;
|
|
17650
|
+
}
|
|
16940
17651
|
var pendingAsks, MAX_ASK_AGE_MS;
|
|
16941
17652
|
var init_ask_callbacks = __esm(async () => {
|
|
16942
17653
|
await __promiseAll([
|
|
@@ -17362,6 +18073,14 @@ var init_topic_tool_capabilities = __esm(async () => {
|
|
|
17362
18073
|
});
|
|
17363
18074
|
|
|
17364
18075
|
// ../../packages/core/src/topics/lifecycle.ts
|
|
18076
|
+
var exports_lifecycle = {};
|
|
18077
|
+
__export(exports_lifecycle, {
|
|
18078
|
+
deleteTopicCascade: () => deleteTopicCascade,
|
|
18079
|
+
TopicTurnStillActiveError: () => TopicTurnStillActiveError,
|
|
18080
|
+
TopicDeleteVetoedError: () => TopicDeleteVetoedError,
|
|
18081
|
+
TopicCleanupRequiredError: () => TopicCleanupRequiredError,
|
|
18082
|
+
TopicArchiveRequiredError: () => TopicArchiveRequiredError
|
|
18083
|
+
});
|
|
17365
18084
|
import { rmSync as rmSync6 } from "fs";
|
|
17366
18085
|
async function abortAndWaitForTopic(topicId) {
|
|
17367
18086
|
interSessionQueue.drop(topicId);
|
|
@@ -17394,8 +18113,8 @@ async function cleanupParticipantResources(topic, userIds, sessionId, cwd, purge
|
|
|
17394
18113
|
cwd,
|
|
17395
18114
|
extraSessions: index === 0 ? currentSessionRef(topic, sessionId) : []
|
|
17396
18115
|
});
|
|
17397
|
-
} catch (
|
|
17398
|
-
logger.warn({ err, topicId: topic.id, userId: participantUserId }, "deleteTopicCascade: participant rollout cleanup failed");
|
|
18116
|
+
} catch (err2) {
|
|
18117
|
+
logger.warn({ err: err2, topicId: topic.id, userId: participantUserId }, "deleteTopicCascade: participant rollout cleanup failed");
|
|
17399
18118
|
}
|
|
17400
18119
|
if (!purged)
|
|
17401
18120
|
return false;
|
|
@@ -17451,12 +18170,12 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
17451
18170
|
if (rawArchive)
|
|
17452
18171
|
rawArchives.push(rawArchive.path);
|
|
17453
18172
|
}
|
|
17454
|
-
} catch (
|
|
18173
|
+
} catch (err2) {
|
|
17455
18174
|
if (!force) {
|
|
17456
|
-
logger.warn({ err, topicId }, "deleteTopicCascade: archive failed - blocking delete unless force=true");
|
|
17457
|
-
throw new TopicArchiveRequiredError(topicId,
|
|
18175
|
+
logger.warn({ err: err2, topicId }, "deleteTopicCascade: archive failed - blocking delete unless force=true");
|
|
18176
|
+
throw new TopicArchiveRequiredError(topicId, err2);
|
|
17458
18177
|
}
|
|
17459
|
-
logger.warn({ err, topicId }, "deleteTopicCascade: archive failed but force=true - continuing with hard delete");
|
|
18178
|
+
logger.warn({ err: err2, topicId }, "deleteTopicCascade: archive failed but force=true - continuing with hard delete");
|
|
17460
18179
|
}
|
|
17461
18180
|
}
|
|
17462
18181
|
if (archived && meetsMemoryArchiveExchangeThreshold(archived.exchangeCount, MIN_MEMORY_ARCHIVE_EXCHANGES, topic)) {
|
|
@@ -17468,12 +18187,13 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
17468
18187
|
sourceTopicId: topicId,
|
|
17469
18188
|
...memoryTopic.id !== topicId && !deletingTopicIds.has(memoryTopic.id) ? { topicId: memoryTopic.id } : {},
|
|
17470
18189
|
topicTitle: memoryTitle,
|
|
18190
|
+
memoryKeyFixed: Boolean(memoryTopic.memoryKey?.trim()),
|
|
17471
18191
|
archivePath: archived.path,
|
|
17472
18192
|
...rawArchives.length > 0 ? { rawArchivePaths: rawArchives } : {},
|
|
17473
18193
|
messageCount: archived.messageCount
|
|
17474
18194
|
});
|
|
17475
|
-
} catch (
|
|
17476
|
-
logger.warn({ err, topicId, archive: archived.path }, "deleteTopicCascade: background archiver launch failed - raw archive preserved");
|
|
18195
|
+
} catch (err2) {
|
|
18196
|
+
logger.warn({ err: err2, topicId, archive: archived.path }, "deleteTopicCascade: background archiver launch failed - raw archive preserved");
|
|
17477
18197
|
}
|
|
17478
18198
|
}
|
|
17479
18199
|
const sessionId = getTopicSessionId(topicId);
|
|
@@ -17490,21 +18210,21 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
17490
18210
|
killBgBash(userId, topicId);
|
|
17491
18211
|
try {
|
|
17492
18212
|
await closeTopicBrowserTabs(userId, topicId);
|
|
17493
|
-
} catch (
|
|
17494
|
-
logger.warn({ err, topicId }, "deleteTopicCascade: browser owner cleanup failed");
|
|
18213
|
+
} catch (err2) {
|
|
18214
|
+
logger.warn({ err: err2, topicId }, "deleteTopicCascade: browser owner cleanup failed");
|
|
17495
18215
|
}
|
|
17496
18216
|
deleteTopicProfileDir(userId, topicId);
|
|
17497
18217
|
cancelAskCallbacksForTopic(topicId);
|
|
17498
18218
|
deleteSelfSchedulesForTopic(topicId);
|
|
17499
18219
|
try {
|
|
17500
18220
|
await deleteFilesForTopic(topicId);
|
|
17501
|
-
} catch (
|
|
17502
|
-
logger.warn({ err, topicId }, "deleteTopicCascade: host file cleanup failed");
|
|
18221
|
+
} catch (err2) {
|
|
18222
|
+
logger.warn({ err: err2, topicId }, "deleteTopicCascade: host file cleanup failed");
|
|
17503
18223
|
}
|
|
17504
18224
|
try {
|
|
17505
18225
|
rmSync6(cwd, { recursive: true, force: true });
|
|
17506
|
-
} catch (
|
|
17507
|
-
logger.warn({ err, topicId, cwd }, "deleteTopicCascade: workspace cleanup failed");
|
|
18226
|
+
} catch (err2) {
|
|
18227
|
+
logger.warn({ err: err2, topicId, cwd }, "deleteTopicCascade: workspace cleanup failed");
|
|
17508
18228
|
}
|
|
17509
18229
|
deleteTopicVisuals(topicId);
|
|
17510
18230
|
deleteTopicHostMcpGrant(topicId);
|
|
@@ -17546,7 +18266,7 @@ async function deleteTopicCascadeImpl(topic, userId, options, deletingAncestorId
|
|
|
17546
18266
|
}
|
|
17547
18267
|
}
|
|
17548
18268
|
}
|
|
17549
|
-
var DELETE_TURN_WAIT_MS = 5000, TopicArchiveRequiredError, TopicTurnStillActiveError, TopicCleanupRequiredError;
|
|
18269
|
+
var DELETE_TURN_WAIT_MS = 5000, TopicArchiveRequiredError, TopicTurnStillActiveError, TopicCleanupRequiredError, TopicDeleteVetoedError;
|
|
17550
18270
|
var init_lifecycle = __esm(async () => {
|
|
17551
18271
|
init_manager();
|
|
17552
18272
|
init_config();
|
|
@@ -17612,9 +18332,19 @@ var init_lifecycle = __esm(async () => {
|
|
|
17612
18332
|
this.topicId = topicId;
|
|
17613
18333
|
}
|
|
17614
18334
|
};
|
|
18335
|
+
TopicDeleteVetoedError = class TopicDeleteVetoedError extends Error {
|
|
18336
|
+
code = "TOPIC_DELETE_VETOED";
|
|
18337
|
+
topicId;
|
|
18338
|
+
constructor(topicId, reason) {
|
|
18339
|
+
super(`Topic delete was vetoed: ${reason}`);
|
|
18340
|
+
this.name = "TopicDeleteVetoedError";
|
|
18341
|
+
this.topicId = topicId;
|
|
18342
|
+
}
|
|
18343
|
+
};
|
|
17615
18344
|
});
|
|
17616
18345
|
|
|
17617
18346
|
// ../../packages/core/src/runtime/attachments.ts
|
|
18347
|
+
import { randomUUID as randomUUID16 } from "crypto";
|
|
17618
18348
|
import { copyFileSync as copyFileSync2, mkdirSync as mkdirSync17, writeFileSync as writeFileSync15 } from "fs";
|
|
17619
18349
|
import { basename as basename6, join as join29 } from "path";
|
|
17620
18350
|
function workspaceCwdFor(topicId) {
|
|
@@ -17656,8 +18386,8 @@ function materializePromptAttachments(topicId, queryId, attachmentIds) {
|
|
|
17656
18386
|
sizeBytes: attachment.sizeBytes,
|
|
17657
18387
|
path: destPath
|
|
17658
18388
|
});
|
|
17659
|
-
} catch (
|
|
17660
|
-
logger.warn({ topicId, queryId, fileId, err }, "ai: failed to materialize attachment");
|
|
18389
|
+
} catch (err2) {
|
|
18390
|
+
logger.warn({ topicId, queryId, fileId, err: err2 }, "ai: failed to materialize attachment");
|
|
17661
18391
|
}
|
|
17662
18392
|
}
|
|
17663
18393
|
return out;
|
|
@@ -17675,6 +18405,24 @@ function composeAttachmentPrompt(prompt, promptLines) {
|
|
|
17675
18405
|
function promptWithAttachments(prompt, attachments) {
|
|
17676
18406
|
return composeAttachmentPrompt(prompt, attachments.map(({ filename, path }) => attachmentPromptLine(filename, path)));
|
|
17677
18407
|
}
|
|
18408
|
+
function ingestAttachment(args) {
|
|
18409
|
+
const destDir = join29(UPLOADS_DIR, args.topicId);
|
|
18410
|
+
mkdirSync17(destDir, { recursive: true });
|
|
18411
|
+
const safeName = safeAttachmentFilename(args.filename, "upload");
|
|
18412
|
+
const destPath = join29(destDir, `${Date.now()}-${randomUUID16().slice(0, 8)}-${safeName}`);
|
|
18413
|
+
if (args.sourcePath !== undefined) {
|
|
18414
|
+
copyFileSync2(args.sourcePath, destPath);
|
|
18415
|
+
} else if (args.bytes !== undefined) {
|
|
18416
|
+
writeFileSync15(destPath, args.bytes);
|
|
18417
|
+
} else {
|
|
18418
|
+
throw new Error("ingestAttachment: provide sourcePath or bytes");
|
|
18419
|
+
}
|
|
18420
|
+
return {
|
|
18421
|
+
path: destPath,
|
|
18422
|
+
filename: args.filename,
|
|
18423
|
+
promptLine: attachmentPromptLine(args.filename, destPath)
|
|
18424
|
+
};
|
|
18425
|
+
}
|
|
17678
18426
|
function parseAttachmentNames(raw) {
|
|
17679
18427
|
if (!raw)
|
|
17680
18428
|
return [];
|
|
@@ -17715,13 +18463,13 @@ function isLikelyCurrentChannelTrigger(row, userId, prompt) {
|
|
|
17715
18463
|
return Number.isFinite(createdMs) && Date.now() - createdMs <= CHANNEL_CONTEXT_CURRENT_MESSAGE_MATCH_MS;
|
|
17716
18464
|
}
|
|
17717
18465
|
function formatChannelTranscriptLine(row) {
|
|
17718
|
-
const
|
|
18466
|
+
const text2 = row.text.trim();
|
|
17719
18467
|
const attachments = parseAttachmentNames(row.attachments);
|
|
17720
18468
|
const attachmentSuffix = attachments.length > 0 ? `
|
|
17721
18469
|
[attachments: ${attachments.join(", ")}]` : "";
|
|
17722
18470
|
const edited = row.edited_at ? " (edited)" : "";
|
|
17723
18471
|
const thread = row.thread_root_id ? ` (in thread ${threadTag(row.thread_root_id)})` : "";
|
|
17724
|
-
return `[${row.created_at}] ${channelTranscriptSpeaker(row)}${edited}${thread}: ${
|
|
18472
|
+
return `[${row.created_at}] ${channelTranscriptSpeaker(row)}${edited}${thread}: ${text2}${attachmentSuffix}`;
|
|
17725
18473
|
}
|
|
17726
18474
|
function buildMentionOnlyChannelPrompt(params) {
|
|
17727
18475
|
const rows = getAllMessagesForTopic(params.topicId).filter((row) => {
|
|
@@ -17766,6 +18514,14 @@ function buildMentionOnlyChannelPrompt(params) {
|
|
|
17766
18514
|
].filter((line) => line !== undefined).join(`
|
|
17767
18515
|
`);
|
|
17768
18516
|
}
|
|
18517
|
+
function escapeRegExp3(s) {
|
|
18518
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18519
|
+
}
|
|
18520
|
+
function mentionsAi(text2, label) {
|
|
18521
|
+
const names = ["ai", "bot", "\uBD07", label.trim()].filter(Boolean);
|
|
18522
|
+
const alt = names.map(escapeRegExp3).join("|");
|
|
18523
|
+
return new RegExp(`(^|\\s)@(${alt})(?![\\p{L}\\p{N}])`, "iu").test(text2);
|
|
18524
|
+
}
|
|
17769
18525
|
var CHANNEL_CONTEXT_CURRENT_MESSAGE_MATCH_MS, CHANNEL_CONTEXT_MAX_MESSAGES = 500, CHANNEL_CONTEXT_MAX_CHARS = 120000;
|
|
17770
18526
|
var init_channel_context = __esm(async () => {
|
|
17771
18527
|
init_attachments();
|
|
@@ -17774,13 +18530,13 @@ var init_channel_context = __esm(async () => {
|
|
|
17774
18530
|
});
|
|
17775
18531
|
|
|
17776
18532
|
// ../../packages/core/src/runtime/errors.ts
|
|
17777
|
-
function stringifyError(
|
|
17778
|
-
if (
|
|
17779
|
-
return
|
|
17780
|
-
if (typeof
|
|
17781
|
-
return
|
|
18533
|
+
function stringifyError(err2) {
|
|
18534
|
+
if (err2 instanceof Error)
|
|
18535
|
+
return err2.message;
|
|
18536
|
+
if (typeof err2 === "string")
|
|
18537
|
+
return err2;
|
|
17782
18538
|
try {
|
|
17783
|
-
return JSON.stringify(
|
|
18539
|
+
return JSON.stringify(err2) ?? String(err2);
|
|
17784
18540
|
} catch {
|
|
17785
18541
|
return "Unknown agent error";
|
|
17786
18542
|
}
|
|
@@ -17795,19 +18551,19 @@ function authRecoveryHint(agent) {
|
|
|
17795
18551
|
return "Please check the DEEPSEEK_API_KEY, MOONSHOT_API_KEY, or GLM_API_KEY environment variable";
|
|
17796
18552
|
}
|
|
17797
18553
|
}
|
|
17798
|
-
function classifyAgentError(
|
|
18554
|
+
function classifyAgentError(err2, agent) {
|
|
17799
18555
|
const name = AGENT_DISPLAY_NAME[agent];
|
|
17800
18556
|
const hint = authRecoveryHint(agent);
|
|
17801
|
-
const ctor = typeof
|
|
18557
|
+
const ctor = typeof err2 === "object" && err2 !== null ? err2.constructor?.name : undefined;
|
|
17802
18558
|
if (ctor === "AuthenticationError")
|
|
17803
18559
|
return `${name} authentication expired. ${hint}. (401)`;
|
|
17804
18560
|
if (ctor === "RateLimitError")
|
|
17805
18561
|
return `${name} request limit exceeded. Please try again in a moment. (429)`;
|
|
17806
18562
|
if (ctor === "InternalServerError") {
|
|
17807
|
-
const status =
|
|
18563
|
+
const status = err2.status;
|
|
17808
18564
|
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)`;
|
|
17809
18565
|
}
|
|
17810
|
-
const s = stringifyError(
|
|
18566
|
+
const s = stringifyError(err2);
|
|
17811
18567
|
if (/401|authentication.error|invalid.*api.key|not logged|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|MOONSHOT_API_KEY|GLM_API_KEY/i.test(s)) {
|
|
17812
18568
|
return `${name} authentication expired. ${hint}. (401)`;
|
|
17813
18569
|
}
|
|
@@ -17830,12 +18586,12 @@ var init_errors = __esm(() => {
|
|
|
17830
18586
|
|
|
17831
18587
|
// ../../packages/core/src/runtime/event-heartbeat.ts
|
|
17832
18588
|
function nextOrHeartbeat(pending, intervalMs) {
|
|
17833
|
-
return new Promise((
|
|
17834
|
-
const timer = setTimeout(() =>
|
|
18589
|
+
return new Promise((resolve17, reject) => {
|
|
18590
|
+
const timer = setTimeout(() => resolve17({ kind: "heartbeat" }), intervalMs);
|
|
17835
18591
|
timer.unref?.();
|
|
17836
18592
|
pending.then((result) => {
|
|
17837
18593
|
clearTimeout(timer);
|
|
17838
|
-
|
|
18594
|
+
resolve17({ kind: "event", result });
|
|
17839
18595
|
}, (error) => {
|
|
17840
18596
|
clearTimeout(timer);
|
|
17841
18597
|
reject(error);
|
|
@@ -18129,7 +18885,7 @@ var init_vault_request_gates = __esm(async () => {
|
|
|
18129
18885
|
});
|
|
18130
18886
|
|
|
18131
18887
|
// ../../packages/core/src/agents/mcp-tools/request-vault.ts
|
|
18132
|
-
import { createHash as createHash12, randomUUID as
|
|
18888
|
+
import { createHash as createHash12, randomUUID as randomUUID17 } from "crypto";
|
|
18133
18889
|
import { z as z4 } from "zod";
|
|
18134
18890
|
function requestBodyHash(key, description) {
|
|
18135
18891
|
return createHash12("sha256").update(JSON.stringify({ key, description })).digest("hex");
|
|
@@ -18369,8 +19125,8 @@ function createRequestVaultRuntime(host) {
|
|
|
18369
19125
|
return errorResult(`Error: failed to persist request_vault_secret: ${error instanceof Error ? error.message : String(error)}`);
|
|
18370
19126
|
}
|
|
18371
19127
|
let resolveAnswer;
|
|
18372
|
-
const promise = new Promise((
|
|
18373
|
-
resolveAnswer =
|
|
19128
|
+
const promise = new Promise((resolve17) => {
|
|
19129
|
+
resolveAnswer = resolve17;
|
|
18374
19130
|
});
|
|
18375
19131
|
pendingRequests.set(message.id, {
|
|
18376
19132
|
topicId: ctx.topicId,
|
|
@@ -18470,7 +19226,7 @@ var init_request_vault = __esm(async () => {
|
|
|
18470
19226
|
init_vault_request_gates()
|
|
18471
19227
|
]);
|
|
18472
19228
|
MAX_DESCRIPTION_CHARS = VAULT_DESCRIPTION_MAX_LENGTH;
|
|
18473
|
-
VAULT_GATE_OWNER_ID = `request-vault-${process.pid}-${
|
|
19229
|
+
VAULT_GATE_OWNER_ID = `request-vault-${process.pid}-${randomUUID17()}`;
|
|
18474
19230
|
defaultRequestVaultDurabilityHost = {
|
|
18475
19231
|
gates: {
|
|
18476
19232
|
prepare: prepareVaultRequestGate,
|
|
@@ -18512,7 +19268,7 @@ var init_request_vault = __esm(async () => {
|
|
|
18512
19268
|
durability: defaultRequestVaultDurabilityHost,
|
|
18513
19269
|
runtime: {
|
|
18514
19270
|
ownerId: VAULT_GATE_OWNER_ID,
|
|
18515
|
-
createId:
|
|
19271
|
+
createId: randomUUID17,
|
|
18516
19272
|
now: () => new Date().toISOString()
|
|
18517
19273
|
}
|
|
18518
19274
|
});
|
|
@@ -18549,24 +19305,24 @@ function taskPanelMessageId(queryId) {
|
|
|
18549
19305
|
// ../../packages/core/src/runtime/tasks.ts
|
|
18550
19306
|
function upsertTaskPanelMessage(topicId, queryId, tasks, lastRenderedText) {
|
|
18551
19307
|
if (tasks.length === 0) {
|
|
18552
|
-
const
|
|
18553
|
-
for (const
|
|
18554
|
-
|
|
19308
|
+
const hub2 = WsHub.get();
|
|
19309
|
+
for (const messageId2 of softDeleteApiMessagesByIdPrefix(topicId, "tasks-")) {
|
|
19310
|
+
hub2.broadcastMessageUpdated(topicId, messageId2, { deleted: true, text: "" });
|
|
18555
19311
|
}
|
|
18556
19312
|
return null;
|
|
18557
19313
|
}
|
|
18558
|
-
const
|
|
18559
|
-
if (
|
|
19314
|
+
const text2 = renderTaskPanel(tasks);
|
|
19315
|
+
if (text2 === lastRenderedText)
|
|
18560
19316
|
return lastRenderedText;
|
|
18561
19317
|
const hub = WsHub.get();
|
|
18562
19318
|
const messageId = taskPanelMessageId(queryId);
|
|
18563
19319
|
const existing = getApiMessage(topicId, messageId);
|
|
18564
19320
|
if (existing && !existing.deleted) {
|
|
18565
19321
|
const editedAt = new Date().toISOString();
|
|
18566
|
-
const updated = updateApiMessageText(topicId, messageId,
|
|
19322
|
+
const updated = updateApiMessageText(topicId, messageId, text2, editedAt);
|
|
18567
19323
|
if (updated) {
|
|
18568
|
-
hub.broadcastMessageUpdated(topicId, messageId, { text, editedAt });
|
|
18569
|
-
return
|
|
19324
|
+
hub.broadcastMessageUpdated(topicId, messageId, { text: text2, editedAt });
|
|
19325
|
+
return text2;
|
|
18570
19326
|
}
|
|
18571
19327
|
}
|
|
18572
19328
|
const createdAt = new Date().toISOString();
|
|
@@ -18574,12 +19330,12 @@ function upsertTaskPanelMessage(topicId, queryId, tasks, lastRenderedText) {
|
|
|
18574
19330
|
id: messageId,
|
|
18575
19331
|
topicId,
|
|
18576
19332
|
authorId: "system",
|
|
18577
|
-
text,
|
|
19333
|
+
text: text2,
|
|
18578
19334
|
createdAt
|
|
18579
19335
|
};
|
|
18580
19336
|
appendApiMessage(message, { notify: false });
|
|
18581
19337
|
hub.broadcastMessage(topicId, message);
|
|
18582
|
-
return
|
|
19338
|
+
return text2;
|
|
18583
19339
|
}
|
|
18584
19340
|
var init_tasks2 = __esm(async () => {
|
|
18585
19341
|
await __promiseAll([
|
|
@@ -18866,6 +19622,10 @@ function locateVisualMediaInput(topicId, input) {
|
|
|
18866
19622
|
}
|
|
18867
19623
|
return { kind: "file", path: realCandidate, rawPath };
|
|
18868
19624
|
}
|
|
19625
|
+
function visualMediaInputError(topicId, input) {
|
|
19626
|
+
const located = locateVisualMediaInput(topicId, input);
|
|
19627
|
+
return "error" in located ? located.error : null;
|
|
19628
|
+
}
|
|
18869
19629
|
function resolveVisualMediaInput(topicId, input) {
|
|
18870
19630
|
const located = locateVisualMediaInput(topicId, input);
|
|
18871
19631
|
if ("error" in located)
|
|
@@ -18904,7 +19664,7 @@ var init_visuals = __esm(async () => {
|
|
|
18904
19664
|
});
|
|
18905
19665
|
|
|
18906
19666
|
// ../../packages/core/src/runtime/turn-event-stream.ts
|
|
18907
|
-
import { randomUUID as
|
|
19667
|
+
import { randomUUID as randomUUID18 } from "crypto";
|
|
18908
19668
|
import { realpathSync as realpathSync6, statSync as statSync9 } from "fs";
|
|
18909
19669
|
import { isAbsolute as isAbsolute7, resolve as resolve18 } from "path";
|
|
18910
19670
|
function sessionEventMatchesCurrentExecution(topicId, queryId, agent, model) {
|
|
@@ -18931,6 +19691,7 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
18931
19691
|
let pendingSawDelta = false;
|
|
18932
19692
|
let accumulatedText = "";
|
|
18933
19693
|
let pendingText = "";
|
|
19694
|
+
let previewText = "";
|
|
18934
19695
|
let pendingMessage = null;
|
|
18935
19696
|
let previewTimer = null;
|
|
18936
19697
|
const clearPreviewTimer = () => {
|
|
@@ -18939,9 +19700,9 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
18939
19700
|
previewTimer = null;
|
|
18940
19701
|
};
|
|
18941
19702
|
const scheduleTextPreview = () => {
|
|
18942
|
-
if (silent || previewTimer || !pendingText.trim())
|
|
19703
|
+
if (silent || previewTimer || !(pendingText + previewText).trim())
|
|
18943
19704
|
return;
|
|
18944
|
-
pendingMessage ??= { id:
|
|
19705
|
+
pendingMessage ??= { id: randomUUID18(), createdAt: new Date().toISOString() };
|
|
18945
19706
|
previewTimer = setTimeout(() => {
|
|
18946
19707
|
previewTimer = null;
|
|
18947
19708
|
if (!pendingMessage || abortController.signal.aborted)
|
|
@@ -18951,7 +19712,7 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
18951
19712
|
kind: "message_stream",
|
|
18952
19713
|
queryId,
|
|
18953
19714
|
messageId: pendingMessage.id,
|
|
18954
|
-
text: pendingText,
|
|
19715
|
+
text: pendingText + previewText,
|
|
18955
19716
|
createdAt: pendingMessage.createdAt,
|
|
18956
19717
|
...execution?.threadRootId ? { threadRootId: execution.threadRootId } : {}
|
|
18957
19718
|
});
|
|
@@ -19006,9 +19767,9 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19006
19767
|
const existing = providerToolIds.get(providerId);
|
|
19007
19768
|
if (existing)
|
|
19008
19769
|
return existing;
|
|
19009
|
-
const
|
|
19010
|
-
providerToolIds.set(providerId,
|
|
19011
|
-
return
|
|
19770
|
+
const clientId2 = fallback ?? providerId;
|
|
19771
|
+
providerToolIds.set(providerId, clientId2);
|
|
19772
|
+
return clientId2;
|
|
19012
19773
|
}
|
|
19013
19774
|
const clientId = fallback ?? nextSyntheticToolUseId();
|
|
19014
19775
|
anonymousToolIds.push(clientId);
|
|
@@ -19042,15 +19803,20 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19042
19803
|
clearPreviewTimer();
|
|
19043
19804
|
const identity = pendingMessage;
|
|
19044
19805
|
pendingMessage = null;
|
|
19045
|
-
const
|
|
19806
|
+
const text2 = pendingText.trimEnd();
|
|
19046
19807
|
pendingText = "";
|
|
19047
|
-
|
|
19808
|
+
previewText = "";
|
|
19809
|
+
if (silent || !text2.trim()) {
|
|
19810
|
+
if (identity && !silent) {
|
|
19811
|
+
hub.broadcastMessageUpdated(topicId, identity.id, { deleted: true, text: "" });
|
|
19812
|
+
}
|
|
19048
19813
|
return null;
|
|
19814
|
+
}
|
|
19049
19815
|
const message = {
|
|
19050
|
-
id: identity?.id ??
|
|
19816
|
+
id: identity?.id ?? randomUUID18(),
|
|
19051
19817
|
topicId,
|
|
19052
19818
|
authorId: "ai",
|
|
19053
|
-
text,
|
|
19819
|
+
text: text2,
|
|
19054
19820
|
queryId,
|
|
19055
19821
|
agentType,
|
|
19056
19822
|
model,
|
|
@@ -19117,7 +19883,12 @@ async function runTurnEventStream(topicId, topicTitle, queryId, events, control,
|
|
|
19117
19883
|
broadcastContextProgress();
|
|
19118
19884
|
break;
|
|
19119
19885
|
}
|
|
19886
|
+
case "text_preview":
|
|
19887
|
+
previewText += event.content;
|
|
19888
|
+
scheduleTextPreview();
|
|
19889
|
+
break;
|
|
19120
19890
|
case "text":
|
|
19891
|
+
previewText = "";
|
|
19121
19892
|
if (pendingSawDelta) {
|
|
19122
19893
|
pendingSawDelta = false;
|
|
19123
19894
|
break;
|
|
@@ -19272,8 +20043,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
19272
20043
|
hub.broadcastVisual(topicId, queryId, url, vizId, title ?? null, kind);
|
|
19273
20044
|
hub.broadcastToolOutput(topicId, queryId, toolUseId, `Displayed: ${url}`);
|
|
19274
20045
|
markVisualToolResultHandled(event.toolUseId);
|
|
19275
|
-
} catch (
|
|
19276
|
-
const reason =
|
|
20046
|
+
} catch (err2) {
|
|
20047
|
+
const reason = err2 instanceof Error ? err2.message : String(err2);
|
|
19277
20048
|
failMediaVisual(reason);
|
|
19278
20049
|
}
|
|
19279
20050
|
} else {
|
|
@@ -19384,8 +20155,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
19384
20155
|
}
|
|
19385
20156
|
terminalEmitted = true;
|
|
19386
20157
|
{
|
|
19387
|
-
await init_ask_callbacks();
|
|
19388
|
-
const pending =
|
|
20158
|
+
const { resolveAskCallback: resolveAskCallback2 } = await init_ask_callbacks().then(() => exports_ask_callbacks);
|
|
20159
|
+
const pending = resolveAskCallback2(queryId);
|
|
19389
20160
|
if (pending) {
|
|
19390
20161
|
const sourceLabel = pending.sourceLabel ?? topicTitle;
|
|
19391
20162
|
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)";
|
|
@@ -19458,8 +20229,8 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
19458
20229
|
if (control.injectParams)
|
|
19459
20230
|
control.injectParams.sessionId = event.sessionId;
|
|
19460
20231
|
onSessionId(event.sessionId);
|
|
19461
|
-
} catch (
|
|
19462
|
-
logger.warn({ err, topicId, queryId, agentType }, "ai: isolated session owner rejected provider session id");
|
|
20232
|
+
} catch (err2) {
|
|
20233
|
+
logger.warn({ err: err2, topicId, queryId, agentType }, "ai: isolated session owner rejected provider session id");
|
|
19463
20234
|
}
|
|
19464
20235
|
} else if (!silent && sessionEventMatchesCurrentExecution(topicId, queryId, agentType, model)) {
|
|
19465
20236
|
setTopicSessionId(topicId, event.sessionId, {
|
|
@@ -19492,14 +20263,14 @@ ${JSON.stringify(event.input ?? {})}`);
|
|
|
19492
20263
|
settleSubagentFailure(queryId, "\uC911\uC9C0\uB428 (\uC0AC\uC6A9\uC790\uAC00 \uC2E4\uD589\uC744 \uBA48\uCDC4\uC2B5\uB2C8\uB2E4)");
|
|
19493
20264
|
} else {
|
|
19494
20265
|
if (control.abortReason === "internal" /* Internal */) {
|
|
19495
|
-
await init_ask_callbacks();
|
|
19496
|
-
|
|
20266
|
+
const { resolveAskCallback: resolveAskCallback2 } = await init_ask_callbacks().then(() => exports_ask_callbacks);
|
|
20267
|
+
resolveAskCallback2(queryId);
|
|
19497
20268
|
}
|
|
19498
20269
|
}
|
|
19499
20270
|
}
|
|
19500
|
-
} catch (
|
|
19501
|
-
const msg = stringifyError(
|
|
19502
|
-
logger.warn({ err, topicId, queryId, agentType, model, silent }, "ai: stream failed");
|
|
20271
|
+
} catch (err2) {
|
|
20272
|
+
const msg = stringifyError(err2) || "Unknown agent error";
|
|
20273
|
+
logger.warn({ err: err2, topicId, queryId, agentType, model, silent }, "ai: stream failed");
|
|
19503
20274
|
terminalEmitted = true;
|
|
19504
20275
|
if (retryableSessionExpired && isSessionExpiredError(msg)) {
|
|
19505
20276
|
outcome = { kind: "session-expired", error: msg };
|
|
@@ -19656,7 +20427,86 @@ var init_app_settings = __esm(async () => {
|
|
|
19656
20427
|
});
|
|
19657
20428
|
|
|
19658
20429
|
// ../../packages/core/src/runtime/turn-runner.ts
|
|
19659
|
-
|
|
20430
|
+
var exports_turn_runner = {};
|
|
20431
|
+
__export(exports_turn_runner, {
|
|
20432
|
+
workspaceCwdFor: () => workspaceCwdFor,
|
|
20433
|
+
withDefaultPlaywright: () => withDefaultPlaywright,
|
|
20434
|
+
wasLocallyRequeuedAfterUserPreemption: () => wasLocallyRequeuedAfterUserPreemption,
|
|
20435
|
+
visualMediaInputError: () => visualMediaInputError,
|
|
20436
|
+
userConversationPromptsToRecord: () => userConversationPromptsToRecord,
|
|
20437
|
+
upsertTaskPanelMessage: () => upsertTaskPanelMessage,
|
|
20438
|
+
tryReconstructTopicRollout: () => tryReconstructTopicRollout,
|
|
20439
|
+
triggerTopicAiTurn: () => triggerTopicAiTurn,
|
|
20440
|
+
topicAllowsVisualFileId: () => topicAllowsVisualFileId,
|
|
20441
|
+
taskPanelMessageId: () => taskPanelMessageId,
|
|
20442
|
+
stripMermaidFence: () => stripMermaidFence,
|
|
20443
|
+
stringifyError: () => stringifyError,
|
|
20444
|
+
streamAgentEvents: () => streamAgentEvents,
|
|
20445
|
+
startDurableTurnRequestWorker: () => startDurableTurnRequestWorker,
|
|
20446
|
+
startAiTurn: () => startAiTurn,
|
|
20447
|
+
selectableModel: () => selectableModel,
|
|
20448
|
+
sameTurnActor: () => sameTurnActor,
|
|
20449
|
+
safeAttachmentFilename: () => safeAttachmentFilename,
|
|
20450
|
+
resolveWorkerModel: () => resolveWorkerModel,
|
|
20451
|
+
resolveWorkerDefaultModel: () => resolveWorkerDefaultModel,
|
|
20452
|
+
resolveWikiMirrorPath: () => resolveWikiMirrorPath,
|
|
20453
|
+
resolveWikiMemoryMirror: () => resolveWikiMemoryMirror,
|
|
20454
|
+
resolveVisualMediaInput: () => resolveVisualMediaInput,
|
|
20455
|
+
resolveTurnToolCapabilities: () => resolveTurnToolCapabilities,
|
|
20456
|
+
resolveTurnHostMcpServers: () => resolveTurnHostMcpServers,
|
|
20457
|
+
resolveTopicTurnSession: () => resolveTopicTurnSession,
|
|
20458
|
+
resolveTopicTurnExecution: () => resolveTopicTurnExecution,
|
|
20459
|
+
resolveSessionRetry: () => resolveSessionRetry,
|
|
20460
|
+
resolveModelForAgent: () => resolveModelForAgent,
|
|
20461
|
+
resolveInitialTurnSessionId: () => resolveInitialTurnSessionId,
|
|
20462
|
+
resolveDefaultModel: () => resolveDefaultModel,
|
|
20463
|
+
resolveCompactionExecution: () => resolveCompactionExecution,
|
|
20464
|
+
renderUserTurnBatch: () => renderUserTurnBatch,
|
|
20465
|
+
renderUserPromptBatch: () => renderUserPromptBatch,
|
|
20466
|
+
renderTaskPanel: () => renderTaskPanel,
|
|
20467
|
+
promptWithAttachments: () => promptWithAttachments,
|
|
20468
|
+
prepareInjectReplayAfterUserPreemption: () => prepareInjectReplayAfterUserPreemption,
|
|
20469
|
+
parseAttachmentNames: () => parseAttachmentNames,
|
|
20470
|
+
normalizeToolUseId: () => normalizeToolUseId,
|
|
20471
|
+
normalizeMermaidTheme: () => normalizeMermaidTheme,
|
|
20472
|
+
modelOwner: () => modelOwner,
|
|
20473
|
+
mergeSupersedingUserTurn: () => mergeSupersedingUserTurn,
|
|
20474
|
+
mentionsAi: () => mentionsAi,
|
|
20475
|
+
materializePromptAttachments: () => materializePromptAttachments,
|
|
20476
|
+
isVisualsShowMermaidTool: () => isVisualsShowMermaidTool,
|
|
20477
|
+
isVisualsShowImageTool: () => isVisualsShowImageTool,
|
|
20478
|
+
isVisualsShowHtmlTool: () => isVisualsShowHtmlTool,
|
|
20479
|
+
isSessionExpiredError: () => isSessionExpiredError,
|
|
20480
|
+
isRuntimeTool: () => isRuntimeTool,
|
|
20481
|
+
isPathInside: () => isPathInside,
|
|
20482
|
+
isLikelyCurrentChannelTrigger: () => isLikelyCurrentChannelTrigger,
|
|
20483
|
+
ingestAttachment: () => ingestAttachment,
|
|
20484
|
+
formatSelectableModel: () => formatSelectableModel,
|
|
20485
|
+
formatChannelTranscriptLine: () => formatChannelTranscriptLine,
|
|
20486
|
+
escapeRegExp: () => escapeRegExp3,
|
|
20487
|
+
escapeHtml: () => escapeHtml2,
|
|
20488
|
+
deliverAskCallbackToCaller: () => deliverAskCallbackToCaller,
|
|
20489
|
+
composeAttachmentPrompt: () => composeAttachmentPrompt,
|
|
20490
|
+
classifyAgentError: () => classifyAgentError,
|
|
20491
|
+
channelTranscriptSpeaker: () => channelTranscriptSpeaker,
|
|
20492
|
+
canonicalModelId: () => canonicalModelId,
|
|
20493
|
+
buildVideoHtml: () => buildVideoHtml,
|
|
20494
|
+
buildTurnReminderQuery: () => buildTurnReminderQuery,
|
|
20495
|
+
buildMermaidHtml: () => buildMermaidHtml,
|
|
20496
|
+
buildMentionOnlyChannelPrompt: () => buildMentionOnlyChannelPrompt,
|
|
20497
|
+
buildImageHtml: () => buildImageHtml,
|
|
20498
|
+
authRecoveryHint: () => authRecoveryHint,
|
|
20499
|
+
attachmentPromptLine: () => attachmentPromptLine,
|
|
20500
|
+
activeVisualHtmlForPrompt: () => activeVisualHtmlForPrompt,
|
|
20501
|
+
SESSION_EXPIRED_MSG: () => SESSION_EXPIRED_MSG,
|
|
20502
|
+
SELECTABLE_MODELS: () => SELECTABLE_MODELS,
|
|
20503
|
+
MODEL_OWNER: () => MODEL_OWNER,
|
|
20504
|
+
MODEL_COST_ROUTING_SUMMARY: () => MODEL_COST_ROUTING_SUMMARY,
|
|
20505
|
+
MODEL_COST_RESEARCHED_AT: () => MODEL_COST_RESEARCHED_AT,
|
|
20506
|
+
FALLBACK_ORDER: () => FALLBACK_ORDER,
|
|
20507
|
+
AGENT_DISPLAY_NAME: () => AGENT_DISPLAY_NAME
|
|
20508
|
+
});
|
|
20509
|
+
import { randomUUID as randomUUID19 } from "crypto";
|
|
19660
20510
|
import { existsSync as existsSync22, mkdirSync as mkdirSync19, readdirSync as readdirSync5, statSync as statSync10 } from "fs";
|
|
19661
20511
|
import { join as join31 } from "path";
|
|
19662
20512
|
function withDefaultPlaywright(configuredMcp, isManager) {
|
|
@@ -19679,12 +20529,12 @@ function buildTurnReminderQuery(agent, prompt, reminders) {
|
|
|
19679
20529
|
|
|
19680
20530
|
${reminderPrompt}` };
|
|
19681
20531
|
}
|
|
19682
|
-
function appendSystemMessage(topicId,
|
|
20532
|
+
function appendSystemMessage(topicId, text2, threadRootId) {
|
|
19683
20533
|
const message = {
|
|
19684
|
-
id:
|
|
20534
|
+
id: randomUUID19(),
|
|
19685
20535
|
topicId,
|
|
19686
20536
|
authorId: "system",
|
|
19687
|
-
text,
|
|
20537
|
+
text: text2,
|
|
19688
20538
|
...threadRootId ? { threadRootId } : {},
|
|
19689
20539
|
createdAt: new Date().toISOString()
|
|
19690
20540
|
};
|
|
@@ -19701,12 +20551,12 @@ function notifyPlaywrightUnavailable(topicId) {
|
|
|
19701
20551
|
appendSystemMessage(topicId, "Playwright browser tools are unavailable this turn. Browser automation was removed from the tool catalog; retry shortly if browser interaction is required.");
|
|
19702
20552
|
WsHub.get().broadcastTopicNotice(topicId, "info", "Playwright \uC0AC\uC6A9 \uBD88\uAC00");
|
|
19703
20553
|
}
|
|
19704
|
-
function appendAskReplyMessage(topicId,
|
|
20554
|
+
function appendAskReplyMessage(topicId, text2, sourceLabel, body, kind, agentType, threadRootId) {
|
|
19705
20555
|
const message = {
|
|
19706
|
-
id:
|
|
20556
|
+
id: randomUUID19(),
|
|
19707
20557
|
topicId,
|
|
19708
20558
|
authorId: "ai",
|
|
19709
|
-
text,
|
|
20559
|
+
text: text2,
|
|
19710
20560
|
kind: "tell",
|
|
19711
20561
|
tellCard: {
|
|
19712
20562
|
fromLabel: sourceLabel,
|
|
@@ -19767,8 +20617,8 @@ function redispatchInject(inject) {
|
|
|
19767
20617
|
kind: "error",
|
|
19768
20618
|
error: "topic gone or AI no longer invited"
|
|
19769
20619
|
});
|
|
19770
|
-
} catch (
|
|
19771
|
-
logger.warn({ err, topicId: inject.topicId }, "ai: deferred settlement hook failed");
|
|
20620
|
+
} catch (err2) {
|
|
20621
|
+
logger.warn({ err: err2, topicId: inject.topicId }, "ai: deferred settlement hook failed");
|
|
19772
20622
|
}
|
|
19773
20623
|
if (inject.forkHandle)
|
|
19774
20624
|
cleanupAgentFork(inject.forkHandle);
|
|
@@ -19826,28 +20676,28 @@ async function clearPendingAskFile(pending, state) {
|
|
|
19826
20676
|
if (!pending.pendingAsk)
|
|
19827
20677
|
return;
|
|
19828
20678
|
try {
|
|
19829
|
-
await init_session_asks();
|
|
20679
|
+
const { clearPendingAsk: clearPendingAsk2, markPendingAskState: markPendingAskState2 } = await init_session_asks().then(() => exports_session_asks);
|
|
19830
20680
|
if (state)
|
|
19831
|
-
|
|
19832
|
-
|
|
19833
|
-
} catch (
|
|
19834
|
-
logger.warn({ err, pendingAsk: pending.pendingAsk }, "sessions: pending ask cleanup failed");
|
|
20681
|
+
markPendingAskState2({ ...pending.pendingAsk, state });
|
|
20682
|
+
clearPendingAsk2(pending.pendingAsk);
|
|
20683
|
+
} catch (err2) {
|
|
20684
|
+
logger.warn({ err: err2, pendingAsk: pending.pendingAsk }, "sessions: pending ask cleanup failed");
|
|
19835
20685
|
}
|
|
19836
20686
|
}
|
|
19837
20687
|
async function markPendingAskFile(pending, state) {
|
|
19838
20688
|
if (!pending.pendingAsk)
|
|
19839
20689
|
return;
|
|
19840
20690
|
try {
|
|
19841
|
-
await init_session_asks();
|
|
19842
|
-
|
|
19843
|
-
} catch (
|
|
19844
|
-
logger.warn({ err, pendingAsk: pending.pendingAsk, state }, "sessions: pending ask mark failed");
|
|
20691
|
+
const { markPendingAskState: markPendingAskState2 } = await init_session_asks().then(() => exports_session_asks);
|
|
20692
|
+
markPendingAskState2({ ...pending.pendingAsk, state });
|
|
20693
|
+
} catch (err2) {
|
|
20694
|
+
logger.warn({ err: err2, pendingAsk: pending.pendingAsk, state }, "sessions: pending ask mark failed");
|
|
19845
20695
|
}
|
|
19846
20696
|
}
|
|
19847
20697
|
async function deliverAskCallbackToCaller(pending, sourceLabel, body, kind, options = {}) {
|
|
19848
20698
|
if (pending.remoteReply) {
|
|
19849
|
-
await init_peer_forward();
|
|
19850
|
-
const delivered = await
|
|
20699
|
+
const { deliverPeerReply: deliverPeerReply2 } = await init_peer_forward().then(() => exports_peer_forward);
|
|
20700
|
+
const delivered = await deliverPeerReply2(pending.remoteReply, sourceLabel, body, kind);
|
|
19851
20701
|
if (delivered)
|
|
19852
20702
|
options.onRecorded?.();
|
|
19853
20703
|
return delivered;
|
|
@@ -19867,8 +20717,8 @@ ${body}`;
|
|
|
19867
20717
|
record(undefined);
|
|
19868
20718
|
await clearPendingAskFile(pending);
|
|
19869
20719
|
return true;
|
|
19870
|
-
} catch (
|
|
19871
|
-
logger.warn({ err, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback direct delivery failed");
|
|
20720
|
+
} catch (err2) {
|
|
20721
|
+
logger.warn({ err: err2, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback direct delivery failed");
|
|
19872
20722
|
return false;
|
|
19873
20723
|
}
|
|
19874
20724
|
}
|
|
@@ -19897,9 +20747,9 @@ ${body}`;
|
|
|
19897
20747
|
if (queued) {
|
|
19898
20748
|
try {
|
|
19899
20749
|
record(callerTopic.agent);
|
|
19900
|
-
} catch (
|
|
20750
|
+
} catch (err2) {
|
|
19901
20751
|
interSessionQueue.remove(pending.callerTopicId, pending.requestId);
|
|
19902
|
-
logger.warn({ err, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback record failed after enqueue; queue entry withdrawn");
|
|
20752
|
+
logger.warn({ err: err2, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback record failed after enqueue; queue entry withdrawn");
|
|
19903
20753
|
return false;
|
|
19904
20754
|
}
|
|
19905
20755
|
await markPendingAskFile(pending, "queued_for_caller");
|
|
@@ -19919,8 +20769,8 @@ ${body}`;
|
|
|
19919
20769
|
}
|
|
19920
20770
|
async function deliverAskError(queryId, sourceLabel, error) {
|
|
19921
20771
|
try {
|
|
19922
|
-
await init_ask_callbacks();
|
|
19923
|
-
const pending =
|
|
20772
|
+
const { resolveAskCallback: resolveAskCallback2 } = await init_ask_callbacks().then(() => exports_ask_callbacks);
|
|
20773
|
+
const pending = resolveAskCallback2(queryId);
|
|
19924
20774
|
if (pending) {
|
|
19925
20775
|
const prefix = pending.timedOut ? `\u26A0\uFE0F [Timeout - error notification was dropped]
|
|
19926
20776
|
|
|
@@ -19950,9 +20800,9 @@ function tryReconstructTopicRollout(opts) {
|
|
|
19950
20800
|
entries: entries.length
|
|
19951
20801
|
}, sessionId ? "ai: session expired \u2014 rollout reconstructed from unified log" : "ai: provider session bridged from shared conversation log");
|
|
19952
20802
|
return { kind: "rebuilt", sessionId: result.sessionId };
|
|
19953
|
-
} catch (
|
|
19954
|
-
logger.warn({ err, topicId, agent, sessionId }, "ai: session reconstruct failed");
|
|
19955
|
-
return { kind: "failed", error: stringifyError(
|
|
20803
|
+
} catch (err2) {
|
|
20804
|
+
logger.warn({ err: err2, topicId, agent, sessionId }, "ai: session reconstruct failed");
|
|
20805
|
+
return { kind: "failed", error: stringifyError(err2) };
|
|
19956
20806
|
}
|
|
19957
20807
|
}
|
|
19958
20808
|
function resolveSessionRetry(opts) {
|
|
@@ -20061,8 +20911,8 @@ function waitToStartRemoteUserTurn(params, queryId, options) {
|
|
|
20061
20911
|
function announceQueuedUserTurn(params, queryId) {
|
|
20062
20912
|
try {
|
|
20063
20913
|
params.onDispatched?.(queryId);
|
|
20064
|
-
} catch (
|
|
20065
|
-
logger.warn({ err, topicId: params.topic.id, queryId }, "ai: queued dispatch hook failed");
|
|
20914
|
+
} catch (err2) {
|
|
20915
|
+
logger.warn({ err: err2, topicId: params.topic.id, queryId }, "ai: queued dispatch hook failed");
|
|
20066
20916
|
}
|
|
20067
20917
|
if (!params.silent)
|
|
20068
20918
|
WsHub.get().broadcastAiActive(params.topic.id, queryId);
|
|
@@ -20083,6 +20933,81 @@ function waitToDrainRemoteInject(topicId) {
|
|
|
20083
20933
|
timer.unref?.();
|
|
20084
20934
|
remoteInjectWaiters.set(topicId, timer);
|
|
20085
20935
|
}
|
|
20936
|
+
async function drainOneDurableUserTurn() {
|
|
20937
|
+
if (durableTurnWorkerBusy)
|
|
20938
|
+
return;
|
|
20939
|
+
durableTurnWorkerBusy = true;
|
|
20940
|
+
try {
|
|
20941
|
+
const request = claimNextRuntimeUserTurnRequest(RUNTIME_INSTANCE_ID);
|
|
20942
|
+
if (!request)
|
|
20943
|
+
return;
|
|
20944
|
+
const topic = getTopic(request.topicId);
|
|
20945
|
+
if (!topic?.agent) {
|
|
20946
|
+
completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20947
|
+
return;
|
|
20948
|
+
}
|
|
20949
|
+
const execution = request.execution;
|
|
20950
|
+
const queryId = startAiTurn({
|
|
20951
|
+
topic,
|
|
20952
|
+
userId: request.userId,
|
|
20953
|
+
actorUserId: execution?.actorUserId,
|
|
20954
|
+
actorTopicScope: actorTopicScopeFrom(execution?.actorTopicScope),
|
|
20955
|
+
remoteSession: remoteSessionGrantFrom(execution?.remoteSession),
|
|
20956
|
+
vaultUserId: execution?.vaultUserId,
|
|
20957
|
+
prompt: request.prompt,
|
|
20958
|
+
_userMessages: request.userMessages,
|
|
20959
|
+
_conversationPrompts: execution?.conversationPrompts ?? [request.prompt],
|
|
20960
|
+
_loggedUserMessageCount: execution?.loggedUserMessageCount ?? Math.max(0, request.userMessages.length - (execution?.conversationPrompts?.length ?? 1)),
|
|
20961
|
+
_durableRequestIds: [request.requestId],
|
|
20962
|
+
attachments: request.attachments,
|
|
20963
|
+
allowAutoContinue: request.allowAutoContinue,
|
|
20964
|
+
origin: "user",
|
|
20965
|
+
requestId: execution?.sourceRequestId,
|
|
20966
|
+
agentOverride: execution?.agentOverride,
|
|
20967
|
+
modelOverride: execution?.modelOverride,
|
|
20968
|
+
effortOverride: execution?.effortOverride,
|
|
20969
|
+
...execution?.sessionIdSpecified ? { sessionId: execution.sessionId } : {},
|
|
20970
|
+
sessionScope: execution?.sessionScope,
|
|
20971
|
+
cwd: execution?.cwd,
|
|
20972
|
+
sessionName: execution?.sessionName,
|
|
20973
|
+
sessionType: execution?.sessionType,
|
|
20974
|
+
visualTools: execution?.visualTools,
|
|
20975
|
+
fileDeliveryTools: execution?.fileDeliveryTools,
|
|
20976
|
+
silent: execution?.silent,
|
|
20977
|
+
bridgeSessionFromHistory: execution?.bridgeSessionFromHistory,
|
|
20978
|
+
peerBridge: execution?.peerBridge,
|
|
20979
|
+
from: execution?.from,
|
|
20980
|
+
threadRootId: execution?.threadRootId,
|
|
20981
|
+
_queryId: request.requestId,
|
|
20982
|
+
_runtimeEpoch: execution?.runtimeEpoch ?? request.topicEpoch,
|
|
20983
|
+
onSettled: () => {
|
|
20984
|
+
completeRuntimeUserTurnRequest(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20985
|
+
}
|
|
20986
|
+
});
|
|
20987
|
+
if (!queryId) {
|
|
20988
|
+
releaseRuntimeUserTurnClaim(request.topicId, request.requestId, RUNTIME_INSTANCE_ID);
|
|
20989
|
+
return;
|
|
20990
|
+
}
|
|
20991
|
+
markRuntimeUserTurnRunning(request.topicId, request.requestId, RUNTIME_INSTANCE_ID, queryId);
|
|
20992
|
+
} finally {
|
|
20993
|
+
durableTurnWorkerBusy = false;
|
|
20994
|
+
}
|
|
20995
|
+
}
|
|
20996
|
+
function startDurableTurnRequestWorker() {
|
|
20997
|
+
if (durableTurnWorker)
|
|
20998
|
+
return () => {};
|
|
20999
|
+
durableTurnWorker = setInterval(() => {
|
|
21000
|
+
drainOneDurableUserTurn();
|
|
21001
|
+
}, 100);
|
|
21002
|
+
durableTurnWorker.unref?.();
|
|
21003
|
+
drainOneDurableUserTurn();
|
|
21004
|
+
return () => {
|
|
21005
|
+
if (!durableTurnWorker)
|
|
21006
|
+
return;
|
|
21007
|
+
clearInterval(durableTurnWorker);
|
|
21008
|
+
durableTurnWorker = null;
|
|
21009
|
+
};
|
|
21010
|
+
}
|
|
20086
21011
|
function startAiTurn(params) {
|
|
20087
21012
|
const storedTopic = getTopic(params.topic.id);
|
|
20088
21013
|
if (!storedTopic || !storedTopic.agent && !params.agentOverride) {
|
|
@@ -20094,8 +21019,8 @@ function startAiTurn(params) {
|
|
|
20094
21019
|
kind: "error",
|
|
20095
21020
|
error: storedTopic ? "topic no longer has an AI agent" : "topic no longer exists"
|
|
20096
21021
|
});
|
|
20097
|
-
} catch (
|
|
20098
|
-
logger.warn({ err, topicId: params.topic.id }, "ai: rejected-turn settlement hook failed");
|
|
21022
|
+
} catch (err2) {
|
|
21023
|
+
logger.warn({ err: err2, topicId: params.topic.id }, "ai: rejected-turn settlement hook failed");
|
|
20099
21024
|
}
|
|
20100
21025
|
return null;
|
|
20101
21026
|
}
|
|
@@ -20151,7 +21076,7 @@ function startAiTurn(params) {
|
|
|
20151
21076
|
const askReplySources = params.askReplySources;
|
|
20152
21077
|
const sessionRetried = params._sessionRetried === true;
|
|
20153
21078
|
const emptyResponseRetried = params._emptyResponseRetried === true;
|
|
20154
|
-
const queryId = asTurnId(params._queryId ??
|
|
21079
|
+
const queryId = asTurnId(params._queryId ?? randomUUID19());
|
|
20155
21080
|
const roomId = turnConcurrency === "isolated" ? isolatedTurnRoomId(topicId, queryId) : asTurnSlotKey(topicId);
|
|
20156
21081
|
const currentRuntimeEpoch = getRuntimeTopicEpoch(topic.id);
|
|
20157
21082
|
const runtimeEpoch = params._runtimeEpoch ?? currentRuntimeEpoch;
|
|
@@ -20163,8 +21088,8 @@ function startAiTurn(params) {
|
|
|
20163
21088
|
}
|
|
20164
21089
|
try {
|
|
20165
21090
|
params.onSettled?.({ queryId, kind: "aborted", abortReason: "external" /* External */ });
|
|
20166
|
-
} catch (
|
|
20167
|
-
logger.warn({ err, topicId: topic.id, queryId }, "ai: stale-turn settlement hook failed");
|
|
21091
|
+
} catch (err2) {
|
|
21092
|
+
logger.warn({ err: err2, topicId: topic.id, queryId }, "ai: stale-turn settlement hook failed");
|
|
20168
21093
|
}
|
|
20169
21094
|
logger.info({ topicId: topic.id, queryId, queuedEpoch: params._runtimeEpoch, currentRuntimeEpoch }, "ai: dropped work queued before topic reset");
|
|
20170
21095
|
return null;
|
|
@@ -20214,8 +21139,8 @@ function startAiTurn(params) {
|
|
|
20214
21139
|
cleanupAgentFork(forkHandle);
|
|
20215
21140
|
try {
|
|
20216
21141
|
onSettled?.({ queryId: "", kind: "error", error });
|
|
20217
|
-
} catch (
|
|
20218
|
-
logger.warn({ err, topicId, queryId }, "ai: isolated-turn rejection hook failed");
|
|
21142
|
+
} catch (err2) {
|
|
21143
|
+
logger.warn({ err: err2, topicId, queryId }, "ai: isolated-turn rejection hook failed");
|
|
20219
21144
|
}
|
|
20220
21145
|
return null;
|
|
20221
21146
|
};
|
|
@@ -20262,7 +21187,7 @@ function startAiTurn(params) {
|
|
|
20262
21187
|
if (decision.action === "abort-replace") {
|
|
20263
21188
|
const running = decision.running;
|
|
20264
21189
|
if (isUserOrigin(running.origin) && !sameTurnActor(running.actorUserId, params.actorUserId)) {
|
|
20265
|
-
const
|
|
21190
|
+
const queuedQueryId2 = waitToStartRemoteUserTurn({
|
|
20266
21191
|
...params,
|
|
20267
21192
|
topic,
|
|
20268
21193
|
prompt,
|
|
@@ -20274,9 +21199,9 @@ function startAiTurn(params) {
|
|
|
20274
21199
|
_durableRequestIds: durableRequestIds,
|
|
20275
21200
|
_runtimeEpoch: runtimeEpoch
|
|
20276
21201
|
}, queryId);
|
|
20277
|
-
announceQueuedUserTurn({ ...params, topic },
|
|
20278
|
-
logger.info({ topicId, queryId:
|
|
20279
|
-
return
|
|
21202
|
+
announceQueuedUserTurn({ ...params, topic }, queuedQueryId2);
|
|
21203
|
+
logger.info({ topicId, queryId: queuedQueryId2, runningQueryId: running.queryId }, "ai: user turn from another actor queued behind the running turn");
|
|
21204
|
+
return queuedQueryId2;
|
|
20280
21205
|
}
|
|
20281
21206
|
let omitRequestIds;
|
|
20282
21207
|
if (isUserOrigin(running.origin)) {
|
|
@@ -20408,14 +21333,14 @@ function startAiTurn(params) {
|
|
|
20408
21333
|
if (turnConcurrency === "topic") {
|
|
20409
21334
|
try {
|
|
20410
21335
|
writeQueryState(userId, topic.id, topic.title, prompt);
|
|
20411
|
-
} catch (
|
|
20412
|
-
logger.warn({ err, topicId, userId }, "ai: failed to write active query state");
|
|
21336
|
+
} catch (err2) {
|
|
21337
|
+
logger.warn({ err: err2, topicId, userId }, "ai: failed to write active query state");
|
|
20413
21338
|
}
|
|
20414
21339
|
}
|
|
20415
21340
|
try {
|
|
20416
21341
|
onDispatched?.(queryId);
|
|
20417
|
-
} catch (
|
|
20418
|
-
logger.warn({ err, topicId, queryId }, "ai: dispatch hook failed");
|
|
21342
|
+
} catch (err2) {
|
|
21343
|
+
logger.warn({ err: err2, topicId, queryId }, "ai: dispatch hook failed");
|
|
20419
21344
|
}
|
|
20420
21345
|
const override = getTopicConfig(topicId);
|
|
20421
21346
|
const agentKind = execution.agent;
|
|
@@ -20442,8 +21367,8 @@ function startAiTurn(params) {
|
|
|
20442
21367
|
control.injectParams.sessionId = bridge.sessionId;
|
|
20443
21368
|
try {
|
|
20444
21369
|
onSessionId?.(bridge.sessionId);
|
|
20445
|
-
} catch (
|
|
20446
|
-
logger.warn({ err, topicId, queryId, agent: agentKind }, "ai: isolated session owner rejected bridged provider session id");
|
|
21370
|
+
} catch (err2) {
|
|
21371
|
+
logger.warn({ err: err2, topicId, queryId, agent: agentKind }, "ai: isolated session owner rejected bridged provider session id");
|
|
20447
21372
|
}
|
|
20448
21373
|
} else if (bridge.kind === "failed") {
|
|
20449
21374
|
historyBridgeError = "Conversation history could not be encoded into a provider session; no fresh session was started.";
|
|
@@ -20512,8 +21437,8 @@ function startAiTurn(params) {
|
|
|
20512
21437
|
const wikiDir = getSharedWikiDir();
|
|
20513
21438
|
const { latestSummaryFile } = resolveWikiMemoryMirror(wikiDir, memoryTopic.id, memoryTitle);
|
|
20514
21439
|
hasMemoryArchive = Boolean(resolvedBrief?.brief.latestSummaryMd || latestSummaryFile);
|
|
20515
|
-
} catch (
|
|
20516
|
-
logger.warn({ topicId, err }, "ai: failed to inject topic brief");
|
|
21440
|
+
} catch (err2) {
|
|
21441
|
+
logger.warn({ topicId, err: err2 }, "ai: failed to inject topic brief");
|
|
20517
21442
|
}
|
|
20518
21443
|
systemPrompt += buildMemoryPromptSection({
|
|
20519
21444
|
topicTitle: topic.title,
|
|
@@ -20589,8 +21514,8 @@ function startAiTurn(params) {
|
|
|
20589
21514
|
control.injectParams.sessionId = prepared.forkId;
|
|
20590
21515
|
control.injectParams.forkHandle = prepared;
|
|
20591
21516
|
}
|
|
20592
|
-
} catch (
|
|
20593
|
-
throw new Error(`failed to prepare isolated session: ${stringifyError(
|
|
21517
|
+
} catch (err2) {
|
|
21518
|
+
throw new Error(`failed to prepare isolated session: ${stringifyError(err2)}`);
|
|
20594
21519
|
}
|
|
20595
21520
|
if (abortController.signal.aborted)
|
|
20596
21521
|
return;
|
|
@@ -20609,8 +21534,8 @@ function startAiTurn(params) {
|
|
|
20609
21534
|
throw new Error("browser MCP capability was not registered");
|
|
20610
21535
|
}
|
|
20611
21536
|
trackPlaywrightTurn(playwrightInstanceKey, control);
|
|
20612
|
-
} catch (
|
|
20613
|
-
logger.warn({ topicId, err }, "ai: ensurePlaywright failed \u2014 proceeding without browser tools");
|
|
21537
|
+
} catch (err2) {
|
|
21538
|
+
logger.warn({ topicId, err: err2 }, "ai: ensurePlaywright failed \u2014 proceeding without browser tools");
|
|
20614
21539
|
markPlaywrightUnavailable({
|
|
20615
21540
|
userId,
|
|
20616
21541
|
topic: topic.title,
|
|
@@ -20623,8 +21548,8 @@ function startAiTurn(params) {
|
|
|
20623
21548
|
if (wantsBgBash) {
|
|
20624
21549
|
try {
|
|
20625
21550
|
bgBashPort = await ensureBgBash(userId, topic.id);
|
|
20626
|
-
} catch (
|
|
20627
|
-
logger.warn({ topicId, err }, "ai: ensureBgBash failed \u2014 proceeding without background bash tools");
|
|
21551
|
+
} catch (err2) {
|
|
21552
|
+
logger.warn({ topicId, err: err2 }, "ai: ensureBgBash failed \u2014 proceeding without background bash tools");
|
|
20628
21553
|
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>");
|
|
20629
21554
|
}
|
|
20630
21555
|
}
|
|
@@ -20837,8 +21762,8 @@ function startAiTurn(params) {
|
|
|
20837
21762
|
await settleSubagentFailure(queryId, error);
|
|
20838
21763
|
try {
|
|
20839
21764
|
onSettled?.({ queryId, kind: "error", error });
|
|
20840
|
-
} catch (
|
|
20841
|
-
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21765
|
+
} catch (err2) {
|
|
21766
|
+
logger.warn({ err: err2, topicId, queryId }, "ai: turn settlement hook failed");
|
|
20842
21767
|
}
|
|
20843
21768
|
return;
|
|
20844
21769
|
}
|
|
@@ -20854,8 +21779,8 @@ function startAiTurn(params) {
|
|
|
20854
21779
|
await settleSubagentFailure(queryId, classifyAgentError(outcome.error, agentKind));
|
|
20855
21780
|
try {
|
|
20856
21781
|
onSettled?.({ queryId, kind: "error", error: outcome.error });
|
|
20857
|
-
} catch (
|
|
20858
|
-
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21782
|
+
} catch (err2) {
|
|
21783
|
+
logger.warn({ err: err2, topicId, queryId }, "ai: turn settlement hook failed");
|
|
20859
21784
|
}
|
|
20860
21785
|
return;
|
|
20861
21786
|
}
|
|
@@ -20868,12 +21793,12 @@ function startAiTurn(params) {
|
|
|
20868
21793
|
kind: outcome.kind === "aborted" ? "aborted" : "completed",
|
|
20869
21794
|
...outcome.kind === "aborted" ? { abortReason: control.abortReason } : {}
|
|
20870
21795
|
});
|
|
20871
|
-
} catch (
|
|
20872
|
-
logger.warn({ err, topicId, queryId }, "ai: turn settlement hook failed");
|
|
21796
|
+
} catch (err2) {
|
|
21797
|
+
logger.warn({ err: err2, topicId, queryId }, "ai: turn settlement hook failed");
|
|
20873
21798
|
}
|
|
20874
|
-
}).catch(async (
|
|
20875
|
-
const error =
|
|
20876
|
-
logger.warn({ err, topicId, queryId, agent: agentKind, model: resolvedModel, silent }, "ai: background stream task failed");
|
|
21799
|
+
}).catch(async (err2) => {
|
|
21800
|
+
const error = err2 instanceof Error ? err2.message : "Agent process crashed";
|
|
21801
|
+
logger.warn({ err: err2, topicId, queryId, agent: agentKind, model: resolvedModel, silent }, "ai: background stream task failed");
|
|
20877
21802
|
if (!silent) {
|
|
20878
21803
|
WsHub.get().broadcastError(topicId, queryId, error);
|
|
20879
21804
|
WsHub.get().broadcastTopicNotice(topicId, "error", "\uC751\uB2F5 \uC2E4\uD328");
|
|
@@ -20922,7 +21847,7 @@ function triggerTopicAiTurn(topicId, userId, prompt, agentType, opts) {
|
|
|
20922
21847
|
if (!opts?.silent && !opts?.hideInjectMessage) {
|
|
20923
21848
|
const now = new Date().toISOString();
|
|
20924
21849
|
const injectMsg = {
|
|
20925
|
-
id: opts?.requestId ? `tell-${opts.requestId}` : `tell-${
|
|
21850
|
+
id: opts?.requestId ? `tell-${opts.requestId}` : `tell-${randomUUID19()}`,
|
|
20926
21851
|
topicId,
|
|
20927
21852
|
authorId: opts?.injectAuthorId ?? userId,
|
|
20928
21853
|
sourceAdapter: opts?.injectSourceAdapter,
|
|
@@ -20979,7 +21904,7 @@ function triggerTopicAiTurn(topicId, userId, prompt, agentType, opts) {
|
|
|
20979
21904
|
from: opts?.from
|
|
20980
21905
|
});
|
|
20981
21906
|
}
|
|
20982
|
-
var PLAYWRIGHT_UNAVAILABLE_NOTICE_COOLDOWN_MS, ASK_REPLY_INJECT_BATCH_MS = 500, playwrightUnavailableNoticeAt, askReplyInjectBatcher, remoteInjectWaiters;
|
|
21907
|
+
var PLAYWRIGHT_UNAVAILABLE_NOTICE_COOLDOWN_MS, ASK_REPLY_INJECT_BATCH_MS = 500, playwrightUnavailableNoticeAt, askReplyInjectBatcher, remoteInjectWaiters, durableTurnWorker = null, durableTurnWorkerBusy = false;
|
|
20983
21908
|
var init_turn_runner = __esm(async () => {
|
|
20984
21909
|
init_manager();
|
|
20985
21910
|
init_constants();
|
|
@@ -21110,29 +22035,29 @@ function createSubagentLifecycle(host) {
|
|
|
21110
22035
|
}
|
|
21111
22036
|
function computeSubagentDepth(topicId) {
|
|
21112
22037
|
let depth = 0;
|
|
21113
|
-
let
|
|
22038
|
+
let current3 = host.storage.getTopic(topicId);
|
|
21114
22039
|
const visited = new Set;
|
|
21115
|
-
while (
|
|
21116
|
-
if (visited.has(
|
|
22040
|
+
while (current3) {
|
|
22041
|
+
if (visited.has(current3.id))
|
|
21117
22042
|
return limits.maxDepth;
|
|
21118
|
-
visited.add(
|
|
21119
|
-
if (
|
|
22043
|
+
visited.add(current3.id);
|
|
22044
|
+
if (current3.isSubagent)
|
|
21120
22045
|
depth += 1;
|
|
21121
|
-
if (!
|
|
22046
|
+
if (!current3.parentTopicId || current3.parentTopicId === current3.id)
|
|
21122
22047
|
break;
|
|
21123
|
-
|
|
22048
|
+
current3 = host.storage.getTopic(current3.parentTopicId);
|
|
21124
22049
|
}
|
|
21125
22050
|
return depth;
|
|
21126
22051
|
}
|
|
21127
|
-
function
|
|
22052
|
+
function canSpawnSubagentsFromTopic2(topicId) {
|
|
21128
22053
|
const topic = host.storage.getTopic(topicId);
|
|
21129
22054
|
return topic?.kind === "agent" && computeSubagentDepth(topicId) < limits.maxDepth;
|
|
21130
22055
|
}
|
|
21131
22056
|
function patchSubagentCard(parentTopicId, cardMessageId, patch) {
|
|
21132
|
-
const
|
|
21133
|
-
if (!
|
|
22057
|
+
const current3 = host.storage.getMessage(parentTopicId, cardMessageId)?.subagentCard;
|
|
22058
|
+
if (!current3)
|
|
21134
22059
|
return;
|
|
21135
|
-
const next = { ...
|
|
22060
|
+
const next = { ...current3, ...patch };
|
|
21136
22061
|
const editedAt = host.runtime.now();
|
|
21137
22062
|
if (!host.storage.updateSubagentCard(parentTopicId, cardMessageId, next, editedAt))
|
|
21138
22063
|
return;
|
|
@@ -21152,7 +22077,7 @@ function createSubagentLifecycle(host) {
|
|
|
21152
22077
|
patchSubagentCard(watch.parentTopicId, watch.cardMessageId, { status: "running" });
|
|
21153
22078
|
}
|
|
21154
22079
|
}
|
|
21155
|
-
function
|
|
22080
|
+
function takeSubagentWatch2(queryId) {
|
|
21156
22081
|
const childTopicId = childByQueryId.get(queryId);
|
|
21157
22082
|
if (!childTopicId)
|
|
21158
22083
|
return recoverPersistedSubagentWatch(queryId);
|
|
@@ -21196,7 +22121,7 @@ function createSubagentLifecycle(host) {
|
|
|
21196
22121
|
if (watch.queryId)
|
|
21197
22122
|
childByQueryId.delete(watch.queryId);
|
|
21198
22123
|
}
|
|
21199
|
-
function
|
|
22124
|
+
function cancelSubagentWatchForDeletedTopic2(childTopicId) {
|
|
21200
22125
|
const watch = watchesByChild.get(childTopicId);
|
|
21201
22126
|
if (!watch)
|
|
21202
22127
|
return;
|
|
@@ -21226,8 +22151,8 @@ function createSubagentLifecycle(host) {
|
|
|
21226
22151
|
if (!await host.sessionCommunication.notifyParent({ watch, prompt, requestId })) {
|
|
21227
22152
|
appendParentSystemNote(watch, prompt);
|
|
21228
22153
|
}
|
|
21229
|
-
} catch (
|
|
21230
|
-
logger.warn({ err, parentTopicId: watch.parentTopicId, childTopicId: watch.childTopicId, noteKind }, "subagent: parent AI notify failed \u2014 falling back to system message");
|
|
22154
|
+
} catch (err2) {
|
|
22155
|
+
logger.warn({ err: err2, parentTopicId: watch.parentTopicId, childTopicId: watch.childTopicId, noteKind }, "subagent: parent AI notify failed \u2014 falling back to system message");
|
|
21231
22156
|
try {
|
|
21232
22157
|
appendParentSystemNote(watch, prompt);
|
|
21233
22158
|
} catch (fallbackErr) {
|
|
@@ -21239,7 +22164,7 @@ function createSubagentLifecycle(host) {
|
|
|
21239
22164
|
}
|
|
21240
22165
|
}
|
|
21241
22166
|
}
|
|
21242
|
-
async function
|
|
22167
|
+
async function settleSubagentSuccess2(watch, finalText) {
|
|
21243
22168
|
const summary = finalText.replace(/\s+/g, " ").trim().slice(0, RESULT_SUMMARY_CHARS);
|
|
21244
22169
|
try {
|
|
21245
22170
|
patchSubagentCard(watch.parentTopicId, watch.cardMessageId, {
|
|
@@ -21247,8 +22172,8 @@ function createSubagentLifecycle(host) {
|
|
|
21247
22172
|
resultSummary: summary || "(no text response)",
|
|
21248
22173
|
finishedAt: host.runtime.now()
|
|
21249
22174
|
});
|
|
21250
|
-
} catch (
|
|
21251
|
-
logger.warn({ err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: completed-card update failed");
|
|
22175
|
+
} catch (err2) {
|
|
22176
|
+
logger.warn({ err: err2, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: completed-card update failed");
|
|
21252
22177
|
}
|
|
21253
22178
|
if (watch.reportMode === "auto") {
|
|
21254
22179
|
await notifyParent(watch, `[Subagent completed \u2190 ${watch.name}]
|
|
@@ -21257,8 +22182,8 @@ function createSubagentLifecycle(host) {
|
|
|
21257
22182
|
${finalText || "(no text response)"}`, "done");
|
|
21258
22183
|
}
|
|
21259
22184
|
}
|
|
21260
|
-
async function
|
|
21261
|
-
const watch =
|
|
22185
|
+
async function settleSubagentFailure2(queryId, reason) {
|
|
22186
|
+
const watch = takeSubagentWatch2(queryId);
|
|
21262
22187
|
if (!watch)
|
|
21263
22188
|
return;
|
|
21264
22189
|
try {
|
|
@@ -21267,8 +22192,8 @@ ${finalText || "(no text response)"}`, "done");
|
|
|
21267
22192
|
errorMessage: reason,
|
|
21268
22193
|
finishedAt: host.runtime.now()
|
|
21269
22194
|
});
|
|
21270
|
-
} catch (
|
|
21271
|
-
logger.warn({ err, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: failed-card update failed");
|
|
22195
|
+
} catch (err2) {
|
|
22196
|
+
logger.warn({ err: err2, parentTopicId: watch.parentTopicId, cardMessageId: watch.cardMessageId }, "subagent: failed-card update failed");
|
|
21272
22197
|
}
|
|
21273
22198
|
if (watch.reportMode === "auto") {
|
|
21274
22199
|
await notifyParent(watch, `[Subagent failed \u2190 ${watch.name}]
|
|
@@ -21305,7 +22230,7 @@ spawn_subagent\uB85C \uC704\uC784\uD55C \uC791\uC5C5\uC774 \uC2E4\uD328\uD588\uC
|
|
|
21305
22230
|
function findSubagentCardMessage(childTopicId) {
|
|
21306
22231
|
return host.storage.listSubagentMessages().filter((message) => message.subagentCard?.subagentTopicId === childTopicId).at(-1);
|
|
21307
22232
|
}
|
|
21308
|
-
function
|
|
22233
|
+
function subagentReportMode2(childTopicId) {
|
|
21309
22234
|
return host.storage.getTopic(childTopicId)?.subagentReportMode ?? findSubagentCardMessage(childTopicId)?.subagentCard?.reportMode ?? "auto";
|
|
21310
22235
|
}
|
|
21311
22236
|
async function startSubagentCard(ctx, cardMessage) {
|
|
@@ -21513,7 +22438,7 @@ ${card.task}${reportInstruction}`;
|
|
|
21513
22438
|
for (const siblings of byParent.values()) {
|
|
21514
22439
|
siblings.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
21515
22440
|
}
|
|
21516
|
-
const
|
|
22441
|
+
const descendants2 = [];
|
|
21517
22442
|
const visited = new Set([ctx.topicId]);
|
|
21518
22443
|
const visit = (parentId) => {
|
|
21519
22444
|
for (const child of byParent.get(parentId) ?? []) {
|
|
@@ -21523,12 +22448,12 @@ ${card.task}${reportInstruction}`;
|
|
|
21523
22448
|
if (!child.participants.some((participant) => participant.userId === rootOwnerId && participant.role === "owner")) {
|
|
21524
22449
|
continue;
|
|
21525
22450
|
}
|
|
21526
|
-
|
|
22451
|
+
descendants2.push(child);
|
|
21527
22452
|
visit(child.id);
|
|
21528
22453
|
}
|
|
21529
22454
|
};
|
|
21530
22455
|
visit(ctx.topicId);
|
|
21531
|
-
return
|
|
22456
|
+
return descendants2;
|
|
21532
22457
|
})() : [];
|
|
21533
22458
|
const children = actorScope ? descendants.filter((child) => actorScope.visible.has(child.id)) : descendants;
|
|
21534
22459
|
return {
|
|
@@ -21552,10 +22477,10 @@ ${card.task}${reportInstruction}`;
|
|
|
21552
22477
|
return card?.status ?? "unknown";
|
|
21553
22478
|
}
|
|
21554
22479
|
function listMemoryTopicNames(ctx) {
|
|
21555
|
-
const
|
|
21556
|
-
if (!
|
|
22480
|
+
const current3 = host.storage.getTopic(ctx.topicId);
|
|
22481
|
+
if (!current3)
|
|
21557
22482
|
return { error: `Error: topic '${ctx.topicId}' not found.` };
|
|
21558
|
-
if (!
|
|
22483
|
+
if (!current3.participants.some((participant) => participant.userId === ctx.userId)) {
|
|
21559
22484
|
return { error: "Error: user is not a member of this topic." };
|
|
21560
22485
|
}
|
|
21561
22486
|
const sources = new Map;
|
|
@@ -21645,8 +22570,8 @@ ${card.task}${reportInstruction}`;
|
|
|
21645
22570
|
try {
|
|
21646
22571
|
await host.topic.delete(child, ctx.userId);
|
|
21647
22572
|
return textResult(`Subagent deleted: ${child.title} (${child.id})`);
|
|
21648
|
-
} catch (
|
|
21649
|
-
const message =
|
|
22573
|
+
} catch (err2) {
|
|
22574
|
+
const message = err2 instanceof Error ? err2.message : String(err2);
|
|
21650
22575
|
return errorResult(`Error: failed to delete subagent '${child.title}': ${message}`);
|
|
21651
22576
|
}
|
|
21652
22577
|
}
|
|
@@ -21743,13 +22668,13 @@ ${card.task}${reportInstruction}`;
|
|
|
21743
22668
|
}
|
|
21744
22669
|
return {
|
|
21745
22670
|
computeSubagentDepth,
|
|
21746
|
-
canSpawnSubagentsFromTopic,
|
|
21747
|
-
takeSubagentWatch,
|
|
21748
|
-
cancelSubagentWatchForDeletedTopic,
|
|
21749
|
-
settleSubagentSuccess,
|
|
21750
|
-
settleSubagentFailure,
|
|
22671
|
+
canSpawnSubagentsFromTopic: canSpawnSubagentsFromTopic2,
|
|
22672
|
+
takeSubagentWatch: takeSubagentWatch2,
|
|
22673
|
+
cancelSubagentWatchForDeletedTopic: cancelSubagentWatchForDeletedTopic2,
|
|
22674
|
+
settleSubagentSuccess: settleSubagentSuccess2,
|
|
22675
|
+
settleSubagentFailure: settleSubagentFailure2,
|
|
21751
22676
|
sweepStaleSubagentCards,
|
|
21752
|
-
subagentReportMode,
|
|
22677
|
+
subagentReportMode: subagentReportMode2,
|
|
21753
22678
|
createSubagentManagementToolDefinitions,
|
|
21754
22679
|
createSpawnSubagentToolDefinition,
|
|
21755
22680
|
createPrepareSubagentToolDefinition
|
|
@@ -21796,9 +22721,9 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
21796
22721
|
},
|
|
21797
22722
|
topic: {
|
|
21798
22723
|
async createDerived(input) {
|
|
21799
|
-
await init_derive();
|
|
22724
|
+
const { createDerivedTopic: createDerivedTopic2, TopicDeriveBusyError: TopicDeriveBusyError2, TopicTitleConflictError: TopicTitleConflictError2 } = await init_derive().then(() => exports_derive);
|
|
21800
22725
|
try {
|
|
21801
|
-
const topic = await
|
|
22726
|
+
const topic = await createDerivedTopic2(input.parentTopicId, input.userId, false, {
|
|
21802
22727
|
name: input.name,
|
|
21803
22728
|
subagent: {
|
|
21804
22729
|
agent: input.agent,
|
|
@@ -21808,30 +22733,30 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
21808
22733
|
});
|
|
21809
22734
|
return { ok: true, topic };
|
|
21810
22735
|
} catch (error) {
|
|
21811
|
-
if (error instanceof
|
|
22736
|
+
if (error instanceof TopicTitleConflictError2) {
|
|
21812
22737
|
return { ok: false, reason: "title-conflict", message: error.message };
|
|
21813
22738
|
}
|
|
21814
|
-
if (error instanceof
|
|
22739
|
+
if (error instanceof TopicDeriveBusyError2)
|
|
21815
22740
|
return { ok: false, reason: "busy" };
|
|
21816
22741
|
throw error;
|
|
21817
22742
|
}
|
|
21818
22743
|
},
|
|
21819
22744
|
async delete(topic, userId) {
|
|
21820
|
-
await init_lifecycle();
|
|
21821
|
-
await
|
|
22745
|
+
const { deleteTopicCascade: deleteTopicCascade2 } = await init_lifecycle().then(() => exports_lifecycle);
|
|
22746
|
+
await deleteTopicCascade2(topic, userId);
|
|
21822
22747
|
}
|
|
21823
22748
|
},
|
|
21824
22749
|
task: {
|
|
21825
22750
|
async dispatch(input) {
|
|
21826
|
-
await init_turn_runner();
|
|
21827
|
-
await init_active_rooms();
|
|
21828
|
-
const queryId =
|
|
22751
|
+
const { triggerTopicAiTurn: triggerTopicAiTurn2 } = await init_turn_runner().then(() => exports_turn_runner);
|
|
22752
|
+
const { getRoomQuery: getRoomQuery2 } = await init_active_rooms().then(() => exports_active_rooms);
|
|
22753
|
+
const queryId = triggerTopicAiTurn2(input.child.id, input.userId, input.prompt, undefined, {
|
|
21829
22754
|
origin: `subagent-task:${input.parent.title}`,
|
|
21830
22755
|
requestId: input.requestId,
|
|
21831
22756
|
injectAuthorId: "ai",
|
|
21832
22757
|
onDispatched: input.onDispatched
|
|
21833
22758
|
});
|
|
21834
|
-
return { accepted: Boolean(queryId ||
|
|
22759
|
+
return { accepted: Boolean(queryId || getRoomQuery2(input.child.id)) };
|
|
21835
22760
|
}
|
|
21836
22761
|
},
|
|
21837
22762
|
sessionCommunication: {
|
|
@@ -21839,16 +22764,16 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
21839
22764
|
const parent = getTopic(watch.parentTopicId);
|
|
21840
22765
|
if (!parent)
|
|
21841
22766
|
return true;
|
|
21842
|
-
await init_turn_runner();
|
|
21843
|
-
const queryId = parent.agent ?
|
|
22767
|
+
const { triggerTopicAiTurn: triggerTopicAiTurn2 } = await init_turn_runner().then(() => exports_turn_runner);
|
|
22768
|
+
const queryId = parent.agent ? triggerTopicAiTurn2(watch.parentTopicId, watch.userId, prompt, undefined, {
|
|
21844
22769
|
origin: `subagent:${watch.name}`,
|
|
21845
22770
|
requestId,
|
|
21846
22771
|
hideInjectMessage: true
|
|
21847
22772
|
}) : null;
|
|
21848
22773
|
if (queryId)
|
|
21849
22774
|
return true;
|
|
21850
|
-
await init_active_rooms();
|
|
21851
|
-
return Boolean(parent.agent &&
|
|
22775
|
+
const { interSessionQueue: interSessionQueue2 } = await init_active_rooms().then(() => exports_active_rooms);
|
|
22776
|
+
return Boolean(parent.agent && interSessionQueue2.hasRequest(parent.id, requestId));
|
|
21852
22777
|
},
|
|
21853
22778
|
listTellTargetIds: listSubagentTellTargetIds,
|
|
21854
22779
|
grantTellTarget: grantSubagentTellTarget,
|
|
@@ -21877,19 +22802,19 @@ var init_spawn_subagent = __esm(async () => {
|
|
|
21877
22802
|
async resolveAgentModel({ context, agent, model, hasOverride }) {
|
|
21878
22803
|
let resolvedModel = model;
|
|
21879
22804
|
if (model) {
|
|
21880
|
-
await Promise.resolve().then(() => init_model_catalog());
|
|
21881
|
-
await init_registry();
|
|
21882
|
-
const registry =
|
|
22805
|
+
const { resolveModelForAgent: resolveModelForAgent2 } = await Promise.resolve().then(() => (init_model_catalog(), exports_model_catalog));
|
|
22806
|
+
const { getRegistry: getRegistry2 } = await init_registry().then(() => exports_registry);
|
|
22807
|
+
const registry = getRegistry2(agent);
|
|
21883
22808
|
if (!registry.validateModel(model)) {
|
|
21884
22809
|
return { error: `Error: model '${model}' is not valid for agent '${agent}'.` };
|
|
21885
22810
|
}
|
|
21886
|
-
resolvedModel =
|
|
22811
|
+
resolvedModel = resolveModelForAgent2(agent, model, registry);
|
|
21887
22812
|
}
|
|
21888
22813
|
if (hasOverride) {
|
|
21889
|
-
await init_auth_check();
|
|
21890
|
-
await init_registry();
|
|
21891
|
-
const targetModel = resolvedModel ??
|
|
21892
|
-
const auth =
|
|
22814
|
+
const { checkAgentModelAuth: checkAgentModelAuth2 } = await init_auth_check().then(() => exports_auth_check);
|
|
22815
|
+
const { getRegistry: getRegistry2 } = await init_registry().then(() => exports_registry);
|
|
22816
|
+
const targetModel = resolvedModel ?? getRegistry2(agent).defaultModel;
|
|
22817
|
+
const auth = checkAgentModelAuth2(agent, targetModel, undefined, context.userId);
|
|
21893
22818
|
if (!auth.ok) {
|
|
21894
22819
|
return { error: `Error: agent '${agent}' is not available: ${auth.error}` };
|
|
21895
22820
|
}
|
|
@@ -22319,11 +23244,11 @@ var DEFAULT_SELF_CONFIG_PRODUCT = {
|
|
|
22319
23244
|
derivedTopicLimit: SELF_CONFIG_DERIVED_TOPIC_LIMIT,
|
|
22320
23245
|
toolDescriptions: {}
|
|
22321
23246
|
};
|
|
22322
|
-
function ok(
|
|
22323
|
-
return { text };
|
|
23247
|
+
function ok(text2) {
|
|
23248
|
+
return { text: text2 };
|
|
22324
23249
|
}
|
|
22325
|
-
function err(
|
|
22326
|
-
return { text, isError: true };
|
|
23250
|
+
function err(text2) {
|
|
23251
|
+
return { text: text2, isError: true };
|
|
22327
23252
|
}
|
|
22328
23253
|
function errorMessage(error) {
|
|
22329
23254
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -22640,8 +23565,8 @@ var defaultSelfConfigHost = {
|
|
|
22640
23565
|
},
|
|
22641
23566
|
derivedTopics: {
|
|
22642
23567
|
async create(sourceTopicId, userId, copyHistory, options) {
|
|
22643
|
-
await init_derive();
|
|
22644
|
-
return
|
|
23568
|
+
const { createDerivedTopic: createDerivedTopic2 } = await init_derive().then(() => exports_derive);
|
|
23569
|
+
return createDerivedTopic2(sourceTopicId, userId, copyHistory, options);
|
|
22645
23570
|
},
|
|
22646
23571
|
link: topicMarkdownLink,
|
|
22647
23572
|
isTitleConflict: (error) => error instanceof Error && error.name === "TopicTitleConflictError",
|
|
@@ -22921,58 +23846,58 @@ await __promiseAll([
|
|
|
22921
23846
|
init_topic_cleanup()
|
|
22922
23847
|
]);
|
|
22923
23848
|
export {
|
|
22924
|
-
|
|
22925
|
-
MIN_MEMORY_ARCHIVE_EXCHANGES,
|
|
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,
|
|
23849
|
+
withTaskSnapshots,
|
|
22974
23850
|
withCodexSpawnSerial,
|
|
22975
|
-
|
|
23851
|
+
visualToolDefinitions,
|
|
23852
|
+
unregisterOwnedCodexPids,
|
|
23853
|
+
summarizeToolInput,
|
|
23854
|
+
summarizeShellCommand,
|
|
23855
|
+
summarizeDisplayText,
|
|
23856
|
+
snapshotCodexChildren,
|
|
23857
|
+
showPngTool,
|
|
23858
|
+
showMermaidTool,
|
|
23859
|
+
showImageTool,
|
|
23860
|
+
showHtmlTool,
|
|
23861
|
+
rotateTopicLogs,
|
|
23862
|
+
resolveTaskEventScope,
|
|
23863
|
+
registerOwnedCodexPids,
|
|
23864
|
+
purgeTopicLogs,
|
|
23865
|
+
otiumVisualToolDefinitions,
|
|
23866
|
+
normalizeAskUserQuestionInput,
|
|
23867
|
+
normalizeAskUserChoices,
|
|
23868
|
+
killOwnedCodexTreesForShutdown,
|
|
23869
|
+
killCodexTrees,
|
|
23870
|
+
isExplicitAgentSwitchTargets,
|
|
23871
|
+
hasExplicitAgentSwitchRequest,
|
|
23872
|
+
formatToolUse,
|
|
23873
|
+
forkAgentSession,
|
|
23874
|
+
findNewCodexChildren,
|
|
23875
|
+
explicitAgentSwitchTargets,
|
|
23876
|
+
defaultAskUserDurabilityHost,
|
|
23877
|
+
createTopicLogMaintenance,
|
|
23878
|
+
createSubagentLifecycle,
|
|
23879
|
+
createSelfConfigToolDefinitionsForCore,
|
|
23880
|
+
createSelfConfigRuntime,
|
|
23881
|
+
createSelfConfigCore,
|
|
23882
|
+
createPublishHtmlToolDefinitions,
|
|
23883
|
+
createCodexTreeManager,
|
|
23884
|
+
createAskUserRuntime,
|
|
23885
|
+
createArchiverRuntime,
|
|
23886
|
+
createAgentForkHelpers,
|
|
23887
|
+
cleanupTopicRolloutsFromEntries,
|
|
23888
|
+
cleanupTopicRollouts,
|
|
23889
|
+
cleanupAgentFork,
|
|
23890
|
+
classifyShellToolName,
|
|
23891
|
+
checkAgentModelAuth,
|
|
23892
|
+
checkAgentAuth,
|
|
23893
|
+
buildNumberedDiffSummary,
|
|
23894
|
+
archiveActiveTopicForMemory,
|
|
23895
|
+
applySelfConfigCapabilityFilter,
|
|
23896
|
+
acquireCodexSpawnLock,
|
|
23897
|
+
VISUALS_MCP_KEY,
|
|
23898
|
+
SELF_CONFIG_CAPABILITIES,
|
|
23899
|
+
MIN_MEMORY_ARCHIVE_EXCHANGES,
|
|
23900
|
+
DEFAULT_SELF_CONFIG_PRODUCT
|
|
22976
23901
|
};
|
|
22977
23902
|
|
|
22978
|
-
//# debugId=
|
|
23903
|
+
//# debugId=F0D0E016782B3E0564756E2164756E21
|