refactor: remove dead exports and orphan modules
Delete exported symbols that nothing in src/, setup/, scripts/ or runners/ references (and no test exercises), iterated to a fixed point: service-routing lease/failover helpers, paired-workspace-manager fingerprint/registration helpers, message-runtime-rules trigger helpers, utils.fetchWithTimeout, detectPnpmStorePath, isCodexMainService, isDeltaHandoffEnabledForGroup with the unused DELTA_HANDOFF config, the deprecated db/schema.applySchemaMigrations alias, unused db wrappers (memories, router state, sessions-by-agent-type, room skill override writes, recent chat/turn-output queries) and a few unused type aliases. Orphan files: src/dashboard.ts + src/dashboard-status-content.ts (only referenced each other), src/restart-context-cli.ts (never invoked) and the unused src/config/index.ts barrel. Service-handoff / channel-owner-lease code is left for a later batch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,12 +20,6 @@ import {
|
|||||||
} from './room-registration-state.js';
|
} from './room-registration-state.js';
|
||||||
import { emitStatus } from './status.js';
|
import { emitStatus } from './status.js';
|
||||||
|
|
||||||
export function detectAssignedRooms(
|
|
||||||
options?: Parameters<typeof detectRoomRegistrationState>[0],
|
|
||||||
): boolean {
|
|
||||||
return detectRoomRegistrationState(options).assignedRooms > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function run(_args: string[]): Promise<void> {
|
export async function run(_args: string[]): Promise<void> {
|
||||||
const projectRoot = process.cwd();
|
const projectRoot = process.cwd();
|
||||||
|
|
||||||
|
|||||||
@@ -55,45 +55,6 @@ export function hasSystemd(): boolean {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Open a URL in the default browser, cross-platform.
|
|
||||||
* Returns true if the command was attempted, false if no method available.
|
|
||||||
*/
|
|
||||||
export function openBrowser(url: string): boolean {
|
|
||||||
try {
|
|
||||||
const platform = getPlatform();
|
|
||||||
if (platform === 'macos') {
|
|
||||||
execSync(`open ${JSON.stringify(url)}`, { stdio: 'ignore' });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (platform === 'linux') {
|
|
||||||
// Try xdg-open first, then wslview for WSL
|
|
||||||
if (commandExists('xdg-open')) {
|
|
||||||
execSync(`xdg-open ${JSON.stringify(url)}`, { stdio: 'ignore' });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (isWSL() && commandExists('wslview')) {
|
|
||||||
execSync(`wslview ${JSON.stringify(url)}`, { stdio: 'ignore' });
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
// WSL without wslview: try cmd.exe
|
|
||||||
if (isWSL()) {
|
|
||||||
try {
|
|
||||||
execSync(`cmd.exe /c start "" ${JSON.stringify(url)}`, {
|
|
||||||
stdio: 'ignore',
|
|
||||||
});
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
// cmd.exe not available
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Command failed
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getServiceManager(): ServiceManager {
|
export function getServiceManager(): ServiceManager {
|
||||||
const platform = getPlatform();
|
const platform = getPlatform();
|
||||||
if (platform === 'macos') return 'launchd';
|
if (platform === 'macos') return 'launchd';
|
||||||
|
|||||||
@@ -186,14 +186,6 @@ export function classifyRotationTrigger(
|
|||||||
|
|
||||||
// ── Unified error classification ────────────────────────────────
|
// ── Unified error classification ────────────────────────────────
|
||||||
|
|
||||||
export type ErrorCategory =
|
|
||||||
| 'rate-limit'
|
|
||||||
| 'auth-expired'
|
|
||||||
| 'org-access-denied'
|
|
||||||
| 'overloaded'
|
|
||||||
| 'network-error'
|
|
||||||
| 'none';
|
|
||||||
|
|
||||||
export type AgentErrorClassification =
|
export type AgentErrorClassification =
|
||||||
| {
|
| {
|
||||||
category: 'none';
|
category: 'none';
|
||||||
|
|||||||
@@ -14,11 +14,7 @@ import {
|
|||||||
} from './claude-credentials-path.js';
|
} from './claude-credentials-path.js';
|
||||||
import { DATA_DIR } from './config.js';
|
import { DATA_DIR } from './config.js';
|
||||||
import { logger } from './logger.js';
|
import { logger } from './logger.js';
|
||||||
import {
|
import { getAllTokens, getConfiguredClaudeTokens } from './token-rotation.js';
|
||||||
getAllTokens,
|
|
||||||
getConfiguredClaudeTokens,
|
|
||||||
getCurrentToken,
|
|
||||||
} from './token-rotation.js';
|
|
||||||
import { readJsonFile, writeJsonFile } from './utils.js';
|
import { readJsonFile, writeJsonFile } from './utils.js';
|
||||||
|
|
||||||
const USAGE_CACHE_FILE = path.join(DATA_DIR, 'claude-usage-cache.json');
|
const USAGE_CACHE_FILE = path.join(DATA_DIR, 'claude-usage-cache.json');
|
||||||
@@ -423,27 +419,6 @@ async function fetchUsageForToken(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch Claude usage via the OAuth API.
|
|
||||||
* Uses the current active token from rotation.
|
|
||||||
*/
|
|
||||||
export async function fetchClaudeUsage(): Promise<ClaudeUsageData | null> {
|
|
||||||
// Prefer the access token in credentials.json when present. The static .env
|
|
||||||
// token (CLAUDE_CODE_OAUTH_TOKEN) was issued before the `user:profile` scope
|
|
||||||
// was required for /api/oauth/usage and so always 403s. The credentials file
|
|
||||||
// is the canonical source written by `claude auth login` and kept fresh by
|
|
||||||
// token-refresh.ts — its accessToken carries the full scope set.
|
|
||||||
const credsToken = readCredentialsAccessToken(0);
|
|
||||||
const token =
|
|
||||||
credsToken || getCurrentToken() || getConfiguredClaudeTokens()[0];
|
|
||||||
if (!token) {
|
|
||||||
logger.debug('No Claude OAuth token available for usage check');
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
// Pass accountIndex=0 so 401/403 → forceRefreshToken retry path engages.
|
|
||||||
return (await fetchUsageForToken(token, 0)).usage;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ClaudeAccountProfile {
|
export interface ClaudeAccountProfile {
|
||||||
email: string;
|
email: string;
|
||||||
planType: string; // "max", "pro", "free"
|
planType: string; // "max", "pro", "free"
|
||||||
@@ -634,6 +609,3 @@ export async function fetchAllClaudeUsage(): Promise<ClaudeAccountUsage[]> {
|
|||||||
}
|
}
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Legacy alias
|
|
||||||
export const fetchClaudeUsageViaCli = fetchClaudeUsage;
|
|
||||||
|
|||||||
@@ -1,16 +1,7 @@
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
|
|
||||||
export type CodexConfigFeature = 'fast_mode' | 'goals';
|
export type CodexConfigFeature = 'fast_mode' | 'goals';
|
||||||
|
|
||||||
export function codexConfigPath(): string {
|
|
||||||
const override = process.env.EJCLAW_CODEX_CONFIG_PATH?.trim();
|
|
||||||
if (override) return override;
|
|
||||||
const home = process.env.EJCLAW_SETTINGS_HOME || os.homedir();
|
|
||||||
return path.join(home, '.codex', 'config.toml');
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readCodexFeatureFromContent(
|
export function readCodexFeatureFromContent(
|
||||||
content: string,
|
content: string,
|
||||||
feature: CodexConfigFeature,
|
feature: CodexConfigFeature,
|
||||||
@@ -66,18 +57,3 @@ export function writeCodexFeatureInContent(
|
|||||||
}
|
}
|
||||||
return `${trimmed}\n\n[features]\n${line}\n`;
|
return `${trimmed}\n\n[features]\n${line}\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function writeCodexFeatureToFile(
|
|
||||||
filePath: string,
|
|
||||||
feature: CodexConfigFeature,
|
|
||||||
value: boolean,
|
|
||||||
): void {
|
|
||||||
const content = fs.existsSync(filePath)
|
|
||||||
? fs.readFileSync(filePath, 'utf-8')
|
|
||||||
: '';
|
|
||||||
const updated = writeCodexFeatureInContent(content, feature, value);
|
|
||||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
||||||
const tempPath = `${filePath}.tmp`;
|
|
||||||
fs.writeFileSync(tempPath, updated, { mode: 0o600 });
|
|
||||||
fs.renameSync(tempPath, filePath);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -308,26 +308,11 @@ function loadCodexState(quiet = false): void {
|
|||||||
if (restoredDeadAuth) saveCodexState();
|
if (restoredDeadAuth) saveCodexState();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Re-read the on-disk rotation state (written by any service).
|
|
||||||
* Call before dashboard renders so the renderer picks up rotations
|
|
||||||
* performed by the Codex service process.
|
|
||||||
*/
|
|
||||||
export function reloadCodexStateFromDisk(): void {
|
|
||||||
if (accounts.length <= 1) return;
|
|
||||||
loadCodexState(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Get the auth.json path for the current active account. */
|
/** Get the auth.json path for the current active account. */
|
||||||
export function getActiveCodexAuthPath(): string | null {
|
export function getActiveCodexAuthPath(): string | null {
|
||||||
return getCodexAuthPath();
|
return getCodexAuthPath();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Currently active codex account index (after rotation). */
|
|
||||||
export function getCurrentCodexAccountIndex(): number {
|
|
||||||
return accounts.length === 0 ? 0 : currentIndex;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Find the rotation-array index that owns the given auth.json path. */
|
/** Find the rotation-array index that owns the given auth.json path. */
|
||||||
export function findCodexAccountIndexByAuthPath(
|
export function findCodexAccountIndexByAuthPath(
|
||||||
authPath: string,
|
authPath: string,
|
||||||
|
|||||||
@@ -28,10 +28,6 @@ export function isClaudeService(serviceId: string = SERVICE_ID): boolean {
|
|||||||
return normalizeServiceId(serviceId) === CLAUDE_SERVICE_ID;
|
return normalizeServiceId(serviceId) === CLAUDE_SERVICE_ID;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isCodexMainService(serviceId: string = SERVICE_ID): boolean {
|
|
||||||
return normalizeServiceId(serviceId) === CODEX_MAIN_SERVICE_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isReviewService(serviceId: string = SERVICE_ID): boolean {
|
export function isReviewService(serviceId: string = SERVICE_ID): boolean {
|
||||||
return normalizeServiceId(serviceId) === CODEX_REVIEW_SERVICE_ID;
|
return normalizeServiceId(serviceId) === CODEX_REVIEW_SERVICE_ID;
|
||||||
}
|
}
|
||||||
@@ -152,16 +148,3 @@ const SESSION_COMMAND_ALLOWED_SENDERS = CONFIG.sessionCommands.allowedSenders;
|
|||||||
export function isSessionCommandSenderAllowed(sender: string): boolean {
|
export function isSessionCommandSenderAllowed(sender: string): boolean {
|
||||||
return SESSION_COMMAND_ALLOWED_SENDERS.has(sender);
|
return SESSION_COMMAND_ALLOWED_SENDERS.has(sender);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delta handoff: cross-provider session continuity with probe + fallback
|
|
||||||
export const DELTA_HANDOFF_ENABLED = CONFIG.deltaHandoff.enabled;
|
|
||||||
export const DELTA_HANDOFF_CANARY_GROUPS = CONFIG.deltaHandoff.canaryGroups;
|
|
||||||
|
|
||||||
export function isDeltaHandoffEnabledForGroup(groupFolder: string): boolean {
|
|
||||||
if (!DELTA_HANDOFF_ENABLED) return false;
|
|
||||||
// If canary groups are specified, only enable for those groups
|
|
||||||
if (DELTA_HANDOFF_CANARY_GROUPS.size > 0) {
|
|
||||||
return DELTA_HANDOFF_CANARY_GROUPS.has(groupFolder);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
export type { AppConfig, RoleModelConfig } from './schema.js';
|
|
||||||
export { loadConfig } from './load-config.js';
|
|
||||||
@@ -280,14 +280,5 @@ export function loadConfig(): AppConfig {
|
|||||||
.filter(Boolean),
|
.filter(Boolean),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
deltaHandoff: {
|
|
||||||
enabled: readText('DELTA_HANDOFF_ENABLED') === 'true',
|
|
||||||
canaryGroups: new Set(
|
|
||||||
(readText('DELTA_HANDOFF_CANARY_GROUPS') ?? '')
|
|
||||||
.split(',')
|
|
||||||
.map((value) => value.trim())
|
|
||||||
.filter(Boolean),
|
|
||||||
),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,8 +93,4 @@ export interface AppConfig {
|
|||||||
sessionCommands: {
|
sessionCommands: {
|
||||||
allowedSenders: Set<string>;
|
allowedSenders: Set<string>;
|
||||||
};
|
};
|
||||||
deltaHandoff: {
|
|
||||||
enabled: boolean;
|
|
||||||
canaryGroups: Set<string>;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { STATUS_SHOW_ROOMS } from './config.js';
|
|
||||||
import type { GroupStatus } from './group-queue.js';
|
import type { GroupStatus } from './group-queue.js';
|
||||||
|
|
||||||
export function formatElapsed(ms: number): string {
|
export function formatElapsed(ms: number): string {
|
||||||
@@ -84,7 +83,3 @@ export function composeDashboardContent(
|
|||||||
);
|
);
|
||||||
return parts.join('\n\n');
|
return parts.join('\n\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function shouldShowRoomStatus(): boolean {
|
|
||||||
return STATUS_SHOW_ROOMS;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
import { STATUS_SHOW_ROOM_DETAILS, STATUS_SHOW_ROOMS } from './config.js';
|
|
||||||
import {
|
|
||||||
composeDashboardContent,
|
|
||||||
type DashboardRoomLine,
|
|
||||||
getStatusLabel,
|
|
||||||
renderCategorizedRoomSections,
|
|
||||||
} from './dashboard-render.js';
|
|
||||||
import type { GroupQueue } from './group-queue.js';
|
|
||||||
import type { AgentType, Channel, RegisteredGroup } from './types.js';
|
|
||||||
|
|
||||||
export interface DashboardOptions {
|
|
||||||
assistantName: string;
|
|
||||||
channels: Channel[];
|
|
||||||
getSessions: () => Record<string, string>;
|
|
||||||
queue: GroupQueue;
|
|
||||||
roomBindings: () => Record<string, RegisteredGroup>;
|
|
||||||
statusChannelId: string;
|
|
||||||
statusUpdateInterval: number;
|
|
||||||
usageUpdateInterval: number;
|
|
||||||
serviceAgentType?: AgentType;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getSessionLabel(sessionId: string | undefined): string {
|
|
||||||
if (!sessionId) return '세션 없음';
|
|
||||||
const shortId = sessionId.length > 8 ? sessionId.slice(-8) : sessionId;
|
|
||||||
return `세션 ${shortId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildStatusContent(opts: DashboardOptions): string {
|
|
||||||
if (!STATUS_SHOW_ROOMS) return '';
|
|
||||||
|
|
||||||
const sessions = opts.getSessions();
|
|
||||||
const groups = opts.roomBindings();
|
|
||||||
const statuses = opts.queue.getStatuses(Object.keys(groups));
|
|
||||||
|
|
||||||
let totalActive = 0;
|
|
||||||
let totalWaiting = 0;
|
|
||||||
const roomLines: DashboardRoomLine[] = statuses
|
|
||||||
.map((status) => {
|
|
||||||
const group = groups[status.jid];
|
|
||||||
if (!group) return null;
|
|
||||||
if (status.status === 'processing') totalActive += 1;
|
|
||||||
if (status.status === 'waiting') totalWaiting += 1;
|
|
||||||
return {
|
|
||||||
category: '기타',
|
|
||||||
categoryPosition: 999,
|
|
||||||
position: 999,
|
|
||||||
line: ` **${group.name}** — ${getStatusLabel(status)} · ${getSessionLabel(sessions[group.folder])}`,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.filter((line): line is DashboardRoomLine => Boolean(line));
|
|
||||||
|
|
||||||
const header = `**에이전트 상태** (${opts.assistantName}) — 활성 ${totalActive} | 큐대기 ${totalWaiting} | 전체 ${roomLines.length}`;
|
|
||||||
if (!STATUS_SHOW_ROOM_DETAILS) {
|
|
||||||
return composeDashboardContent([header]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return composeDashboardContent([
|
|
||||||
`${header}\n\n${renderCategorizedRoomSections({
|
|
||||||
lines: roomLines,
|
|
||||||
showCategoryHeaders: false,
|
|
||||||
})}`,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
|
|
||||||
import type { DashboardOptions } from './dashboard-status-content.js';
|
|
||||||
import { formatRoomName } from './unified-dashboard.js';
|
|
||||||
|
|
||||||
function makeOptions(sessionId?: string): DashboardOptions {
|
|
||||||
const sessions: Record<string, string> = sessionId
|
|
||||||
? { 'group-folder': sessionId }
|
|
||||||
: {};
|
|
||||||
|
|
||||||
return {
|
|
||||||
assistantName: 'Test',
|
|
||||||
channels: [],
|
|
||||||
getSessions: () => sessions,
|
|
||||||
queue: {
|
|
||||||
getStatuses: () => [
|
|
||||||
{
|
|
||||||
jid: 'dc:123',
|
|
||||||
status: 'inactive',
|
|
||||||
elapsedMs: null,
|
|
||||||
pendingMessages: false,
|
|
||||||
pendingTasks: 0,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
} as unknown as DashboardOptions['queue'],
|
|
||||||
roomBindings: () => ({
|
|
||||||
'dc:123': {
|
|
||||||
name: 'clone-test',
|
|
||||||
folder: 'group-folder',
|
|
||||||
trigger: '@bot',
|
|
||||||
added_at: '2026-03-16T00:00:00.000Z',
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
statusChannelId: 'status',
|
|
||||||
statusUpdateInterval: 60000,
|
|
||||||
usageUpdateInterval: 60000,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('buildStatusContent', () => {
|
|
||||||
async function loadBuildStatusContent(
|
|
||||||
options: {
|
|
||||||
statusShowRooms?: string;
|
|
||||||
statusShowRoomDetails?: string;
|
|
||||||
} = {},
|
|
||||||
): Promise<(opts: DashboardOptions) => string> {
|
|
||||||
vi.resetModules();
|
|
||||||
process.env.STATUS_SHOW_ROOMS = options.statusShowRooms ?? 'true';
|
|
||||||
process.env.STATUS_SHOW_ROOM_DETAILS =
|
|
||||||
options.statusShowRoomDetails ?? 'true';
|
|
||||||
const mod = await import('./dashboard-status-content.js');
|
|
||||||
return mod.buildStatusContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
delete process.env.STATUS_SHOW_ROOMS;
|
|
||||||
delete process.env.STATUS_SHOW_ROOM_DETAILS;
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows cleared sessions as empty', async () => {
|
|
||||||
const buildStatusContent = await loadBuildStatusContent();
|
|
||||||
const content = buildStatusContent(makeOptions());
|
|
||||||
expect(content).toContain('세션 없음');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows a shortened session id when a session exists', async () => {
|
|
||||||
const buildStatusContent = await loadBuildStatusContent();
|
|
||||||
const content = buildStatusContent(makeOptions('session-1234567890'));
|
|
||||||
expect(content).toContain('세션 34567890');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns an empty string when room status display is disabled', async () => {
|
|
||||||
const buildStatusContent = await loadBuildStatusContent({
|
|
||||||
statusShowRooms: 'false',
|
|
||||||
});
|
|
||||||
expect(buildStatusContent(makeOptions())).toBe('');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('renders only the status header when room details are disabled', async () => {
|
|
||||||
const buildStatusContent = await loadBuildStatusContent({
|
|
||||||
statusShowRooms: 'true',
|
|
||||||
statusShowRoomDetails: 'false',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(buildStatusContent(makeOptions())).toContain('**에이전트 상태**');
|
|
||||||
expect(buildStatusContent(makeOptions())).not.toContain('**clone-test**');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('formatRoomName', () => {
|
|
||||||
it('uses the stored chat name without adding an extra Discord hash', () => {
|
|
||||||
expect(
|
|
||||||
formatRoomName(
|
|
||||||
'dc:123',
|
|
||||||
undefined,
|
|
||||||
'registered-room-name',
|
|
||||||
'My Server #bot-chat',
|
|
||||||
),
|
|
||||||
).toBe('My Server #bot-chat');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('adds a Discord hash for raw channel metadata names', () => {
|
|
||||||
expect(
|
|
||||||
formatRoomName(
|
|
||||||
'dc:123',
|
|
||||||
{
|
|
||||||
name: 'bot-chat',
|
|
||||||
position: 1,
|
|
||||||
category: 'Bots',
|
|
||||||
categoryPosition: 1,
|
|
||||||
},
|
|
||||||
'registered-room-name',
|
|
||||||
'My Server #bot-chat',
|
|
||||||
),
|
|
||||||
).toBe('#bot-chat');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import {
|
|
||||||
buildStatusContent,
|
|
||||||
type DashboardOptions,
|
|
||||||
} from './dashboard-status-content.js';
|
|
||||||
import {
|
|
||||||
purgeDashboardChannel,
|
|
||||||
startUnifiedDashboard,
|
|
||||||
} from './unified-dashboard.js';
|
|
||||||
|
|
||||||
export { buildStatusContent, purgeDashboardChannel };
|
|
||||||
export type { DashboardOptions };
|
|
||||||
|
|
||||||
export async function startStatusDashboard(
|
|
||||||
opts: DashboardOptions,
|
|
||||||
): Promise<void> {
|
|
||||||
await startUnifiedDashboard({
|
|
||||||
assistantName: opts.assistantName,
|
|
||||||
serviceId: opts.serviceAgentType === 'codex' ? 'codex-main' : 'claude',
|
|
||||||
serviceAgentType: opts.serviceAgentType || 'claude-code',
|
|
||||||
statusChannelId: opts.statusChannelId,
|
|
||||||
statusUpdateInterval: opts.statusUpdateInterval,
|
|
||||||
usageUpdateInterval: opts.usageUpdateInterval,
|
|
||||||
channels: opts.channels,
|
|
||||||
queue: opts.queue,
|
|
||||||
roomBindings: opts.roomBindings,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function startUsageDashboard(): Promise<void> {
|
|
||||||
// Usage dashboard is integrated into startStatusDashboard via unified dashboard.
|
|
||||||
}
|
|
||||||
14
src/db.ts
14
src/db.ts
@@ -6,10 +6,7 @@ export {
|
|||||||
} from './db/runtime-database.js';
|
} from './db/runtime-database.js';
|
||||||
export {
|
export {
|
||||||
_setMemoryTimestampsForTests,
|
_setMemoryTimestampsForTests,
|
||||||
archiveMemory,
|
|
||||||
createProducedWorkItem,
|
createProducedWorkItem,
|
||||||
enforceMemoryBounds,
|
|
||||||
expireStaleMemories,
|
|
||||||
getAllChats,
|
getAllChats,
|
||||||
getLastHumanMessageContent,
|
getLastHumanMessageContent,
|
||||||
getLastHumanMessageSender,
|
getLastHumanMessageSender,
|
||||||
@@ -23,8 +20,6 @@ export {
|
|||||||
getOpenWorkItemForChat,
|
getOpenWorkItemForChat,
|
||||||
getRecentDeliveredWorkItemsForChat,
|
getRecentDeliveredWorkItemsForChat,
|
||||||
getRecentChatMessages,
|
getRecentChatMessages,
|
||||||
getRecentChatMessagesBatch,
|
|
||||||
hasMessage,
|
|
||||||
hasRecentRestartAnnouncement,
|
hasRecentRestartAnnouncement,
|
||||||
markWorkItemDelivered,
|
markWorkItemDelivered,
|
||||||
markWorkItemDeliveryRetry,
|
markWorkItemDeliveryRetry,
|
||||||
@@ -32,7 +27,6 @@ export {
|
|||||||
rememberMemory,
|
rememberMemory,
|
||||||
storeChatMetadata,
|
storeChatMetadata,
|
||||||
storeMessage,
|
storeMessage,
|
||||||
touchMemories,
|
|
||||||
} from './db/runtime-memory-messages.js';
|
} from './db/runtime-memory-messages.js';
|
||||||
export {
|
export {
|
||||||
_deleteStoredRoomSettingsForTests,
|
_deleteStoredRoomSettingsForTests,
|
||||||
@@ -43,7 +37,6 @@ export {
|
|||||||
createTask,
|
createTask,
|
||||||
deleteAllSessionsForGroup,
|
deleteAllSessionsForGroup,
|
||||||
deleteSession,
|
deleteSession,
|
||||||
deleteStoredRoomSkillOverride,
|
|
||||||
deleteTask,
|
deleteTask,
|
||||||
findDuplicateCiWatcher,
|
findDuplicateCiWatcher,
|
||||||
getAllRoomBindings,
|
getAllRoomBindings,
|
||||||
@@ -58,22 +51,16 @@ export {
|
|||||||
getRegisteredAgentTypesForJid,
|
getRegisteredAgentTypesForJid,
|
||||||
getRegisteredGroup,
|
getRegisteredGroup,
|
||||||
getRouterState,
|
getRouterState,
|
||||||
getRouterStateForService,
|
|
||||||
getSession,
|
getSession,
|
||||||
getSessionForAgentType,
|
|
||||||
getStoredRoomRoleAgentPlan,
|
getStoredRoomRoleAgentPlan,
|
||||||
getStoredRoomSettings,
|
getStoredRoomSettings,
|
||||||
getStoredRoomSkillOverrides,
|
getStoredRoomSkillOverrides,
|
||||||
getTaskById,
|
getTaskById,
|
||||||
getTasksForGroup,
|
|
||||||
hasActiveCiWatcherForChat,
|
hasActiveCiWatcherForChat,
|
||||||
logTaskRun,
|
logTaskRun,
|
||||||
setExplicitRoomMode,
|
setExplicitRoomMode,
|
||||||
setRouterState,
|
setRouterState,
|
||||||
setRouterStateForService,
|
|
||||||
setSession,
|
setSession,
|
||||||
setSessionForAgentType,
|
|
||||||
upsertStoredRoomSkillOverride,
|
|
||||||
updateRegisteredGroupName,
|
updateRegisteredGroupName,
|
||||||
updateTask,
|
updateTask,
|
||||||
updateTaskAfterRun,
|
updateTaskAfterRun,
|
||||||
@@ -107,7 +94,6 @@ export {
|
|||||||
getPairedTurnAttempts,
|
getPairedTurnAttempts,
|
||||||
getPairedTurnById,
|
getPairedTurnById,
|
||||||
getPairedTurnOutputs,
|
getPairedTurnOutputs,
|
||||||
getRecentPairedTurnOutputsForChat,
|
|
||||||
getPairedTurnsForTask,
|
getPairedTurnsForTask,
|
||||||
getLatestPairedTurnForTask,
|
getLatestPairedTurnForTask,
|
||||||
updatePairedTurnProgressText,
|
updatePairedTurnProgressText,
|
||||||
|
|||||||
@@ -165,16 +165,6 @@ export function touchMemoriesInDatabase(
|
|||||||
tx();
|
tx();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function archiveMemoryInDatabase(database: Database, id: number): void {
|
|
||||||
database
|
|
||||||
.prepare(
|
|
||||||
`UPDATE memories
|
|
||||||
SET archived_at = COALESCE(archived_at, ?)
|
|
||||||
WHERE id = ?`,
|
|
||||||
)
|
|
||||||
.run(new Date().toISOString(), id);
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildCompactMemoryExpiryCutoff(nowIso: string): string {
|
function buildCompactMemoryExpiryCutoff(nowIso: string): string {
|
||||||
return new Date(
|
return new Date(
|
||||||
new Date(nowIso).getTime() - COMPACT_MEMORY_TTL_DAYS * 24 * 60 * 60 * 1000,
|
new Date(nowIso).getTime() - COMPACT_MEMORY_TTL_DAYS * 24 * 60 * 60 * 1000,
|
||||||
|
|||||||
@@ -95,17 +95,6 @@ export function getAllChatsFromDatabase(database: Database): ChatInfo[] {
|
|||||||
.all() as ChatInfo[];
|
.all() as ChatInfo[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hasMessageInDatabase(
|
|
||||||
database: Database,
|
|
||||||
chatJid: string,
|
|
||||||
id: string,
|
|
||||||
): boolean {
|
|
||||||
const row = database
|
|
||||||
.prepare('SELECT 1 FROM messages WHERE chat_jid = ? AND id = ? LIMIT 1')
|
|
||||||
.get(chatJid, id);
|
|
||||||
return !!row;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function storeMessageInDatabase(
|
export function storeMessageInDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
msg: NewMessage,
|
msg: NewMessage,
|
||||||
@@ -352,44 +341,6 @@ export function getRecentChatMessagesFromDatabase(
|
|||||||
return rows.map(normalizeMessageRow);
|
return rows.map(normalizeMessageRow);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getRecentChatMessagesBatchFromDatabase(
|
|
||||||
database: Database,
|
|
||||||
chatJids: string[],
|
|
||||||
limit: number = 8,
|
|
||||||
): Map<string, NewMessage[]> {
|
|
||||||
const out = new Map<string, NewMessage[]>();
|
|
||||||
if (chatJids.length === 0) return out;
|
|
||||||
const placeholders = chatJids.map(() => '?').join(',');
|
|
||||||
const sql = `
|
|
||||||
WITH ranked AS (
|
|
||||||
SELECT id, chat_jid, sender, sender_name, content, timestamp,
|
|
||||||
is_from_me, is_bot_message, message_source_kind,
|
|
||||||
ROW_NUMBER() OVER (PARTITION BY chat_jid ORDER BY timestamp DESC) AS rn
|
|
||||||
FROM messages
|
|
||||||
WHERE chat_jid IN (${placeholders})
|
|
||||||
AND content != '' AND content IS NOT NULL
|
|
||||||
)
|
|
||||||
SELECT id, chat_jid, sender, sender_name, content, timestamp,
|
|
||||||
is_from_me, is_bot_message, message_source_kind
|
|
||||||
FROM ranked
|
|
||||||
WHERE rn <= ?
|
|
||||||
ORDER BY chat_jid, timestamp ASC
|
|
||||||
`;
|
|
||||||
const rows = database.prepare(sql).all(...chatJids, limit) as Array<
|
|
||||||
NewMessage & {
|
|
||||||
is_from_me?: boolean | number;
|
|
||||||
is_bot_message?: boolean | number;
|
|
||||||
}
|
|
||||||
>;
|
|
||||||
for (const row of rows) {
|
|
||||||
const normalized = normalizeMessageRow(row);
|
|
||||||
const existing = out.get(normalized.chat_jid);
|
|
||||||
if (existing) existing.push(normalized);
|
|
||||||
else out.set(normalized.chat_jid, [normalized]);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getLastHumanMessageTimestampFromDatabase(
|
export function getLastHumanMessageTimestampFromDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
chatJid: string,
|
chatJid: string,
|
||||||
|
|||||||
@@ -94,32 +94,6 @@ export function getPairedTurnOutputsFromDatabase(
|
|||||||
.map((row) => hydratePairedTurnOutputRow(row as StoredPairedTurnOutputRow));
|
.map((row) => hydratePairedTurnOutputRow(row as StoredPairedTurnOutputRow));
|
||||||
}
|
}
|
||||||
|
|
||||||
const recentOutputsForChatStmtCache = new WeakMap<
|
|
||||||
Database,
|
|
||||||
ReturnType<Database['prepare']>
|
|
||||||
>();
|
|
||||||
|
|
||||||
export function getRecentPairedTurnOutputsForChatFromDatabase(
|
|
||||||
database: Database,
|
|
||||||
chatJid: string,
|
|
||||||
limit: number = 8,
|
|
||||||
): PairedTurnOutput[] {
|
|
||||||
let stmt = recentOutputsForChatStmtCache.get(database);
|
|
||||||
if (!stmt) {
|
|
||||||
stmt = database.prepare(`
|
|
||||||
SELECT o.*
|
|
||||||
FROM paired_turn_outputs o
|
|
||||||
INNER JOIN paired_tasks t ON o.task_id = t.id
|
|
||||||
WHERE t.chat_jid = ?
|
|
||||||
ORDER BY o.created_at DESC
|
|
||||||
LIMIT ?
|
|
||||||
`);
|
|
||||||
recentOutputsForChatStmtCache.set(database, stmt);
|
|
||||||
}
|
|
||||||
const rows = stmt.all(chatJid, limit) as StoredPairedTurnOutputRow[];
|
|
||||||
return rows.reverse().map(hydratePairedTurnOutputRow);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getLatestTurnNumberFromDatabase(
|
export function getLatestTurnNumberFromDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
taskId: string,
|
taskId: string,
|
||||||
|
|||||||
@@ -38,14 +38,6 @@ export interface StoredRoomSkillOverride {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StoredRoomSkillOverrideInput {
|
|
||||||
chatJid: string;
|
|
||||||
agentType: AgentType;
|
|
||||||
skillScope: string;
|
|
||||||
skillName: string;
|
|
||||||
enabled: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AssignRoomInput {
|
export interface AssignRoomInput {
|
||||||
name: string;
|
name: string;
|
||||||
roomMode?: RoomMode;
|
roomMode?: RoomMode;
|
||||||
@@ -384,56 +376,6 @@ export function getStoredRoomSkillOverridesFromDatabase(
|
|||||||
.filter((row): row is StoredRoomSkillOverride => Boolean(row));
|
.filter((row): row is StoredRoomSkillOverride => Boolean(row));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function upsertStoredRoomSkillOverrideInDatabase(
|
|
||||||
database: Database,
|
|
||||||
input: StoredRoomSkillOverrideInput,
|
|
||||||
): void {
|
|
||||||
const agentType = normalizeStoredAgentType(input.agentType);
|
|
||||||
if (!agentType) {
|
|
||||||
throw new Error(`Unsupported agent type: ${input.agentType}`);
|
|
||||||
}
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
database
|
|
||||||
.prepare(
|
|
||||||
`INSERT INTO room_skill_overrides (
|
|
||||||
chat_jid, agent_type, skill_scope, skill_name, enabled,
|
|
||||||
created_at, updated_at
|
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
||||||
ON CONFLICT(chat_jid, agent_type, skill_scope, skill_name)
|
|
||||||
DO UPDATE SET
|
|
||||||
enabled = excluded.enabled,
|
|
||||||
updated_at = excluded.updated_at`,
|
|
||||||
)
|
|
||||||
.run(
|
|
||||||
input.chatJid,
|
|
||||||
agentType,
|
|
||||||
input.skillScope,
|
|
||||||
input.skillName,
|
|
||||||
input.enabled ? 1 : 0,
|
|
||||||
now,
|
|
||||||
now,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deleteStoredRoomSkillOverrideFromDatabase(
|
|
||||||
database: Database,
|
|
||||||
input: Omit<StoredRoomSkillOverrideInput, 'enabled'>,
|
|
||||||
): void {
|
|
||||||
const agentType = normalizeStoredAgentType(input.agentType);
|
|
||||||
if (!agentType) {
|
|
||||||
throw new Error(`Unsupported agent type: ${input.agentType}`);
|
|
||||||
}
|
|
||||||
database
|
|
||||||
.prepare(
|
|
||||||
`DELETE FROM room_skill_overrides
|
|
||||||
WHERE chat_jid = ?
|
|
||||||
AND agent_type = ?
|
|
||||||
AND skill_scope = ?
|
|
||||||
AND skill_name = ?`,
|
|
||||||
)
|
|
||||||
.run(input.chatJid, agentType, input.skillScope, input.skillName);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getStoredRoomModeRowFromDatabase(
|
function getStoredRoomModeRowFromDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
chatJid: string,
|
chatJid: string,
|
||||||
|
|||||||
@@ -26,23 +26,6 @@ export function getRouterStateFromDatabase(
|
|||||||
return prefixedRow.value;
|
return prefixedRow.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getRouterStateForServiceFromDatabase(
|
|
||||||
database: Database,
|
|
||||||
key: string,
|
|
||||||
serviceId: string,
|
|
||||||
): string | undefined {
|
|
||||||
const prefixedKey = `${normalizeServiceId(serviceId)}:${key}`;
|
|
||||||
const row = database
|
|
||||||
.prepare('SELECT value FROM router_state WHERE key = ?')
|
|
||||||
.get(prefixedKey) as { value: string } | undefined;
|
|
||||||
if (row) return row.value;
|
|
||||||
|
|
||||||
const canonical = database
|
|
||||||
.prepare('SELECT value FROM router_state WHERE key = ?')
|
|
||||||
.get(key) as { value: string } | undefined;
|
|
||||||
return canonical?.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setRouterStateInDatabase(
|
export function setRouterStateInDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
key: string,
|
key: string,
|
||||||
@@ -53,18 +36,6 @@ export function setRouterStateInDatabase(
|
|||||||
.run(key, value);
|
.run(key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setRouterStateForServiceInDatabase(
|
|
||||||
database: Database,
|
|
||||||
key: string,
|
|
||||||
value: string,
|
|
||||||
serviceId: string,
|
|
||||||
): void {
|
|
||||||
const prefixedKey = `${normalizeServiceId(serviceId)}:${key}`;
|
|
||||||
database
|
|
||||||
.prepare('INSERT OR REPLACE INTO router_state (key, value) VALUES (?, ?)')
|
|
||||||
.run(prefixedKey, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getUnsupportedRouterStateKeysFromDatabase(
|
export function getUnsupportedRouterStateKeysFromDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
): string[] {
|
): string[] {
|
||||||
|
|||||||
@@ -7,12 +7,8 @@ import {
|
|||||||
type MemoryScopeKind,
|
type MemoryScopeKind,
|
||||||
type MemorySourceKind,
|
type MemorySourceKind,
|
||||||
type RecallMemoryQuery,
|
type RecallMemoryQuery,
|
||||||
archiveMemoryInDatabase,
|
|
||||||
enforceMemoryBoundsInDatabase,
|
|
||||||
expireStaleMemoriesInDatabase,
|
|
||||||
recallMemoriesFromDatabase,
|
recallMemoriesFromDatabase,
|
||||||
rememberMemoryInDatabase,
|
rememberMemoryInDatabase,
|
||||||
touchMemoriesInDatabase,
|
|
||||||
} from './memories.js';
|
} from './memories.js';
|
||||||
import {
|
import {
|
||||||
type ChatInfo,
|
type ChatInfo,
|
||||||
@@ -26,8 +22,6 @@ import {
|
|||||||
getNewMessagesBySeqFromDatabase,
|
getNewMessagesBySeqFromDatabase,
|
||||||
getNewMessagesFromDatabase,
|
getNewMessagesFromDatabase,
|
||||||
getRecentChatMessagesFromDatabase,
|
getRecentChatMessagesFromDatabase,
|
||||||
getRecentChatMessagesBatchFromDatabase,
|
|
||||||
hasMessageInDatabase,
|
|
||||||
hasRecentRestartAnnouncementInDatabase,
|
hasRecentRestartAnnouncementInDatabase,
|
||||||
storeChatMetadataInDatabase,
|
storeChatMetadataInDatabase,
|
||||||
storeMessageInDatabase,
|
storeMessageInDatabase,
|
||||||
@@ -80,29 +74,6 @@ export function _setMemoryTimestampsForTests(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function touchMemories(ids: number[]): void {
|
|
||||||
touchMemoriesInDatabase(requireDatabase(), ids);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function archiveMemory(id: number): void {
|
|
||||||
archiveMemoryInDatabase(requireDatabase(), id);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function expireStaleMemories(args?: {
|
|
||||||
scopeKind?: MemoryScopeKind;
|
|
||||||
scopeKey?: string;
|
|
||||||
now?: string;
|
|
||||||
}): number {
|
|
||||||
return expireStaleMemoriesInDatabase(requireDatabase(), args);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function enforceMemoryBounds(
|
|
||||||
scopeKind: MemoryScopeKind,
|
|
||||||
scopeKey: string,
|
|
||||||
): void {
|
|
||||||
enforceMemoryBoundsInDatabase(requireDatabase(), scopeKind, scopeKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function rememberMemory(input: {
|
export function rememberMemory(input: {
|
||||||
scopeKind: MemoryScopeKind;
|
scopeKind: MemoryScopeKind;
|
||||||
scopeKey: string;
|
scopeKey: string;
|
||||||
@@ -144,10 +115,6 @@ export function storeMessage(msg: NewMessage): void {
|
|||||||
storeMessageInDatabase(requireDatabase(), msg);
|
storeMessageInDatabase(requireDatabase(), msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hasMessage(chatJid: string, id: string): boolean {
|
|
||||||
return hasMessageInDatabase(requireDatabase(), chatJid, id);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getNewMessages(
|
export function getNewMessages(
|
||||||
jids: string[],
|
jids: string[],
|
||||||
lastTimestamp: string,
|
lastTimestamp: string,
|
||||||
@@ -226,17 +193,6 @@ export function getRecentChatMessages(
|
|||||||
return getRecentChatMessagesFromDatabase(requireDatabase(), chatJid, limit);
|
return getRecentChatMessagesFromDatabase(requireDatabase(), chatJid, limit);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getRecentChatMessagesBatch(
|
|
||||||
chatJids: string[],
|
|
||||||
limit: number = 8,
|
|
||||||
): Map<string, NewMessage[]> {
|
|
||||||
return getRecentChatMessagesBatchFromDatabase(
|
|
||||||
requireDatabase(),
|
|
||||||
chatJids,
|
|
||||||
limit,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getLastHumanMessageTimestamp(chatJid: string): string | null {
|
export function getLastHumanMessageTimestamp(chatJid: string): string | null {
|
||||||
return getLastHumanMessageTimestampFromDatabase(requireDatabase(), chatJid);
|
return getLastHumanMessageTimestampFromDatabase(requireDatabase(), chatJid);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,6 @@ import {
|
|||||||
import {
|
import {
|
||||||
getLatestTurnNumberFromDatabase,
|
getLatestTurnNumberFromDatabase,
|
||||||
getPairedTurnOutputsFromDatabase,
|
getPairedTurnOutputsFromDatabase,
|
||||||
getRecentPairedTurnOutputsForChatFromDatabase,
|
|
||||||
insertPairedTurnOutputInDatabase,
|
insertPairedTurnOutputInDatabase,
|
||||||
} from './paired-turn-outputs.js';
|
} from './paired-turn-outputs.js';
|
||||||
import {
|
import {
|
||||||
@@ -387,17 +386,6 @@ export function getPairedTurnOutputs(taskId: string): PairedTurnOutput[] {
|
|||||||
return getPairedTurnOutputsFromDatabase(requireDatabase(), taskId);
|
return getPairedTurnOutputsFromDatabase(requireDatabase(), taskId);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getRecentPairedTurnOutputsForChat(
|
|
||||||
chatJid: string,
|
|
||||||
limit: number = 8,
|
|
||||||
): PairedTurnOutput[] {
|
|
||||||
return getRecentPairedTurnOutputsForChatFromDatabase(
|
|
||||||
requireDatabase(),
|
|
||||||
chatJid,
|
|
||||||
limit,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getLatestTurnNumber(taskId: string): number {
|
export function getLatestTurnNumber(taskId: string): number {
|
||||||
return getLatestTurnNumberFromDatabase(requireDatabase(), taskId);
|
return getLatestTurnNumberFromDatabase(requireDatabase(), taskId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ import {
|
|||||||
assignRoomInDatabase,
|
assignRoomInDatabase,
|
||||||
clearExplicitRoomModeInDatabase,
|
clearExplicitRoomModeInDatabase,
|
||||||
deleteStoredRoomSettingsForTestsInDatabase,
|
deleteStoredRoomSettingsForTestsInDatabase,
|
||||||
deleteStoredRoomSkillOverrideFromDatabase,
|
|
||||||
getAllRoomBindingsFromDatabase,
|
getAllRoomBindingsFromDatabase,
|
||||||
getEffectiveRoomModeFromDatabase,
|
getEffectiveRoomModeFromDatabase,
|
||||||
getEffectiveRuntimeRoomModeFromDatabase,
|
getEffectiveRuntimeRoomModeFromDatabase,
|
||||||
@@ -42,9 +41,7 @@ import {
|
|||||||
setRegisteredGroupForTestsInDatabase,
|
setRegisteredGroupForTestsInDatabase,
|
||||||
setStoredRoomOwnerAgentTypeForTestsInDatabase,
|
setStoredRoomOwnerAgentTypeForTestsInDatabase,
|
||||||
type StoredRoomSkillOverride,
|
type StoredRoomSkillOverride,
|
||||||
type StoredRoomSkillOverrideInput,
|
|
||||||
updateRegisteredGroupNameInDatabase,
|
updateRegisteredGroupNameInDatabase,
|
||||||
upsertStoredRoomSkillOverrideInDatabase,
|
|
||||||
} from './rooms.js';
|
} from './rooms.js';
|
||||||
import { type StoredRoomSettings } from './room-registration.js';
|
import { type StoredRoomSettings } from './room-registration.js';
|
||||||
import {
|
import {
|
||||||
@@ -56,9 +53,7 @@ import {
|
|||||||
} from './sessions.js';
|
} from './sessions.js';
|
||||||
import {
|
import {
|
||||||
getLastRespondingAgentTypeFromDatabase,
|
getLastRespondingAgentTypeFromDatabase,
|
||||||
getRouterStateForServiceFromDatabase,
|
|
||||||
getRouterStateFromDatabase,
|
getRouterStateFromDatabase,
|
||||||
setRouterStateForServiceInDatabase,
|
|
||||||
setRouterStateInDatabase,
|
setRouterStateInDatabase,
|
||||||
} from './router-state.js';
|
} from './router-state.js';
|
||||||
import {
|
import {
|
||||||
@@ -75,7 +70,6 @@ import {
|
|||||||
getDueTasksFromDatabase,
|
getDueTasksFromDatabase,
|
||||||
getRecentConsecutiveErrorsFromDatabase,
|
getRecentConsecutiveErrorsFromDatabase,
|
||||||
getTaskByIdFromDatabase,
|
getTaskByIdFromDatabase,
|
||||||
getTasksForGroupFromDatabase,
|
|
||||||
hasActiveCiWatcherForChatInDatabase,
|
hasActiveCiWatcherForChatInDatabase,
|
||||||
logTaskRunInDatabase,
|
logTaskRunInDatabase,
|
||||||
updateTaskAfterRunInDatabase,
|
updateTaskAfterRunInDatabase,
|
||||||
@@ -121,17 +115,6 @@ export function findDuplicateCiWatcher(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getTasksForGroup(
|
|
||||||
groupFolder: string,
|
|
||||||
agentType?: AgentType,
|
|
||||||
): ScheduledTask[] {
|
|
||||||
return getTasksForGroupFromDatabase(
|
|
||||||
requireDatabase(),
|
|
||||||
groupFolder,
|
|
||||||
agentType,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAllTasks(agentType?: AgentType): ScheduledTask[] {
|
export function getAllTasks(agentType?: AgentType): ScheduledTask[] {
|
||||||
return getAllTasksFromDatabase(requireDatabase(), agentType);
|
return getAllTasksFromDatabase(requireDatabase(), agentType);
|
||||||
}
|
}
|
||||||
@@ -235,29 +218,10 @@ export function getRouterState(key: string): string | undefined {
|
|||||||
return getRouterStateFromDatabase(requireDatabase(), key, SERVICE_ID);
|
return getRouterStateFromDatabase(requireDatabase(), key, SERVICE_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getRouterStateForService(
|
|
||||||
key: string,
|
|
||||||
serviceId: string,
|
|
||||||
): string | undefined {
|
|
||||||
return getRouterStateForServiceFromDatabase(
|
|
||||||
requireDatabase(),
|
|
||||||
key,
|
|
||||||
serviceId,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setRouterState(key: string, value: string): void {
|
export function setRouterState(key: string, value: string): void {
|
||||||
setRouterStateInDatabase(requireDatabase(), key, value);
|
setRouterStateInDatabase(requireDatabase(), key, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setRouterStateForService(
|
|
||||||
key: string,
|
|
||||||
value: string,
|
|
||||||
serviceId: string,
|
|
||||||
): void {
|
|
||||||
setRouterStateForServiceInDatabase(requireDatabase(), key, value, serviceId);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getSession(
|
export function getSession(
|
||||||
groupFolder: string,
|
groupFolder: string,
|
||||||
agentType: AgentType = 'claude-code',
|
agentType: AgentType = 'claude-code',
|
||||||
@@ -293,21 +257,6 @@ export function getAllSessions(): Record<string, string> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getSessionForAgentType(
|
|
||||||
groupFolder: string,
|
|
||||||
agentType: string,
|
|
||||||
): string | undefined {
|
|
||||||
return getSessionFromDatabase(requireDatabase(), groupFolder, agentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setSessionForAgentType(
|
|
||||||
groupFolder: string,
|
|
||||||
agentType: string,
|
|
||||||
sessionId: string,
|
|
||||||
): void {
|
|
||||||
setSessionInDatabase(requireDatabase(), groupFolder, agentType, sessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getLastRespondingAgentType(
|
export function getLastRespondingAgentType(
|
||||||
chatJid: string,
|
chatJid: string,
|
||||||
): AgentType | undefined {
|
): AgentType | undefined {
|
||||||
@@ -376,18 +325,6 @@ export function getStoredRoomSkillOverrides(
|
|||||||
return getStoredRoomSkillOverridesFromDatabase(db, chatJid);
|
return getStoredRoomSkillOverridesFromDatabase(db, chatJid);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function upsertStoredRoomSkillOverride(
|
|
||||||
input: StoredRoomSkillOverrideInput,
|
|
||||||
): void {
|
|
||||||
upsertStoredRoomSkillOverrideInDatabase(requireDatabase(), input);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deleteStoredRoomSkillOverride(
|
|
||||||
input: Omit<StoredRoomSkillOverrideInput, 'enabled'>,
|
|
||||||
): void {
|
|
||||||
deleteStoredRoomSkillOverrideFromDatabase(requireDatabase(), input);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getExplicitRoomMode(chatJid: string): RoomMode | undefined {
|
export function getExplicitRoomMode(chatJid: string): RoomMode | undefined {
|
||||||
return getExplicitRoomModeFromDatabase(requireDatabase(), chatJid);
|
return getExplicitRoomModeFromDatabase(requireDatabase(), chatJid);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,3 @@ export function applyLegacySchemaMigrations(
|
|||||||
`ALTER TABLE work_items ADD COLUMN service_id TEXT`,
|
`ALTER TABLE work_items ADD COLUMN service_id TEXT`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated New schema changes should be added under src/db/migrations/*. */
|
|
||||||
export const applySchemaMigrations = applyLegacySchemaMigrations;
|
|
||||||
|
|||||||
@@ -107,26 +107,6 @@ export function findDuplicateCiWatcherInDatabase(
|
|||||||
.get(chatJid, ciProvider, ciMetadata) as ScheduledTask | undefined;
|
.get(chatJid, ciProvider, ciMetadata) as ScheduledTask | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getTasksForGroupFromDatabase(
|
|
||||||
database: Database,
|
|
||||||
groupFolder: string,
|
|
||||||
agentType?: AgentType,
|
|
||||||
): ScheduledTask[] {
|
|
||||||
if (agentType) {
|
|
||||||
return database
|
|
||||||
.prepare(
|
|
||||||
'SELECT * FROM scheduled_tasks WHERE group_folder = ? AND agent_type = ? ORDER BY created_at DESC',
|
|
||||||
)
|
|
||||||
.all(groupFolder, agentType) as ScheduledTask[];
|
|
||||||
}
|
|
||||||
|
|
||||||
return database
|
|
||||||
.prepare(
|
|
||||||
'SELECT * FROM scheduled_tasks WHERE group_folder = ? ORDER BY created_at DESC',
|
|
||||||
)
|
|
||||||
.all(groupFolder) as ScheduledTask[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAllTasksFromDatabase(
|
export function getAllTasksFromDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
agentType?: AgentType,
|
agentType?: AgentType,
|
||||||
|
|||||||
@@ -273,34 +273,6 @@ export function getOpenWorkItemFromDatabase(
|
|||||||
return row ? hydrateWorkItemRow(row) : undefined;
|
return row ? hydrateWorkItemRow(row) : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Recent delivered owner-side work items for a chat, newest last.
|
|
||||||
* Used by single-mode prompt building to surface the bot's own prior
|
|
||||||
* answers (which only live in work_items.result_payload) so a new turn
|
|
||||||
* can reference what it previously said.
|
|
||||||
*/
|
|
||||||
export function getRecentDeliveredOwnerWorkItemsForChatFromDatabase(
|
|
||||||
database: Database,
|
|
||||||
chatJid: string,
|
|
||||||
limit: number,
|
|
||||||
): WorkItem[] {
|
|
||||||
if (limit <= 0) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
const rows = database
|
|
||||||
.prepare(
|
|
||||||
`SELECT *
|
|
||||||
FROM work_items
|
|
||||||
WHERE chat_jid = ?
|
|
||||||
AND status = 'delivered'
|
|
||||||
AND (delivery_role = 'owner' OR delivery_role IS NULL)
|
|
||||||
ORDER BY id DESC
|
|
||||||
LIMIT ?`,
|
|
||||||
)
|
|
||||||
.all(chatJid, limit) as StoredWorkItemRow[];
|
|
||||||
return rows.map(hydrateWorkItemRow).reverse();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getOpenWorkItemForChatFromDatabase(
|
export function getOpenWorkItemForChatFromDatabase(
|
||||||
database: Database,
|
database: Database,
|
||||||
chatJid: string,
|
chatJid: string,
|
||||||
|
|||||||
@@ -170,13 +170,6 @@ export function _setRegisteredGroups(
|
|||||||
runtimeState.setRoomBindings(groups);
|
runtimeState.setRoomBindings(groups);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @internal - exported for testing */
|
|
||||||
export function _setRoomBindings(
|
|
||||||
groups: Record<string, RegisteredGroup>,
|
|
||||||
): void {
|
|
||||||
runtimeState.setRoomBindings(groups);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function tryDeliverRestartAnnouncement(
|
async function tryDeliverRestartAnnouncement(
|
||||||
chatJid: string,
|
chatJid: string,
|
||||||
rawText: string,
|
rawText: string,
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ export {
|
|||||||
resolveClaudeRetryTrigger,
|
resolveClaudeRetryTrigger,
|
||||||
resolveCodexRetryTrigger,
|
resolveCodexRetryTrigger,
|
||||||
type AttemptRetryAction,
|
type AttemptRetryAction,
|
||||||
type AttemptRetryState as ExecutorAttemptState,
|
|
||||||
type AttemptStreamedTrigger as ExecutorStreamedTrigger,
|
|
||||||
} from './agent-attempt-retry.js';
|
} from './agent-attempt-retry.js';
|
||||||
|
|
||||||
export type PairedFollowUpQueueAction = 'pending' | 'none';
|
export type PairedFollowUpQueueAction = 'pending' | 'none';
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { getLastHumanMessageTimestamp } from './db.js';
|
import { getLastHumanMessageTimestamp } from './db.js';
|
||||||
import { filterProcessableMessages } from './bot-message-filter.js';
|
import { filterProcessableMessages } from './bot-message-filter.js';
|
||||||
import { normalizeStoredSeqCursor } from './message-cursor.js';
|
import { normalizeStoredSeqCursor } from './message-cursor.js';
|
||||||
import { isTriggerAllowed, loadSenderAllowlist } from './sender-allowlist.js';
|
|
||||||
import { isTaskStatusControlMessage } from './task-watch-status.js';
|
import { isTaskStatusControlMessage } from './task-watch-status.js';
|
||||||
import { ARBITER_AGENT_TYPE, REVIEWER_AGENT_TYPE } from './config.js';
|
import { ARBITER_AGENT_TYPE, REVIEWER_AGENT_TYPE } from './config.js';
|
||||||
import type { VisibleVerdict } from './paired-verdict.js';
|
import type { VisibleVerdict } from './paired-verdict.js';
|
||||||
@@ -21,7 +20,6 @@ import {
|
|||||||
type NewMessage,
|
type NewMessage,
|
||||||
type PairedRoomRole,
|
type PairedRoomRole,
|
||||||
type PairedTaskStatus,
|
type PairedTaskStatus,
|
||||||
type RegisteredGroup,
|
|
||||||
} from './types.js';
|
} from './types.js';
|
||||||
|
|
||||||
const BOT_COLLABORATION_WINDOW_MS = 12 * 60 * 60 * 1000;
|
const BOT_COLLABORATION_WINDOW_MS = 12 * 60 * 60 * 1000;
|
||||||
@@ -346,22 +344,6 @@ export function resolveConfiguredRoleAgentPlan(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Resolve the effective agent type for a role, considering per-role overrides. */
|
|
||||||
export function resolveEffectiveAgentType(
|
|
||||||
role: 'owner' | 'reviewer' | 'arbiter',
|
|
||||||
groupAgentType: AgentType | undefined,
|
|
||||||
reviewerAgentType: AgentType = REVIEWER_AGENT_TYPE,
|
|
||||||
arbiterAgentType: AgentType | null | undefined = ARBITER_AGENT_TYPE,
|
|
||||||
): AgentType {
|
|
||||||
const plan = resolveConfiguredRoleAgentPlan(
|
|
||||||
role !== 'owner',
|
|
||||||
groupAgentType,
|
|
||||||
reviewerAgentType,
|
|
||||||
arbiterAgentType,
|
|
||||||
);
|
|
||||||
return resolveAgentTypeForRole(plan, role);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Session folder key for a role. Owner uses groupFolder, others use groupFolder:role. */
|
/** Session folder key for a role. Owner uses groupFolder, others use groupFolder:role. */
|
||||||
export function resolveSessionFolder(
|
export function resolveSessionFolder(
|
||||||
groupFolder: string,
|
groupFolder: string,
|
||||||
@@ -487,44 +469,6 @@ export function shouldSkipBotOnlyCollaboration(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hasAllowedTrigger(opts: {
|
|
||||||
chatJid: string;
|
|
||||||
messages: NewMessage[];
|
|
||||||
group: RegisteredGroup;
|
|
||||||
triggerPattern: RegExp;
|
|
||||||
hasImplicitContinuationWindow: (
|
|
||||||
chatJid: string,
|
|
||||||
messages: NewMessage[],
|
|
||||||
) => boolean;
|
|
||||||
}): boolean {
|
|
||||||
const {
|
|
||||||
chatJid,
|
|
||||||
messages,
|
|
||||||
group,
|
|
||||||
triggerPattern,
|
|
||||||
hasImplicitContinuationWindow,
|
|
||||||
} = opts;
|
|
||||||
|
|
||||||
if (group.isMain === true || group.requiresTrigger === false) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Paired rooms: bot-to-bot ping-pong doesn't need trigger patterns.
|
|
||||||
// Peer bot messages (from reviewer/owner) are always allowed.
|
|
||||||
if (hasReviewerLease(chatJid)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const allowlistCfg = loadSenderAllowlist();
|
|
||||||
const hasTrigger = messages.some(
|
|
||||||
(message) =>
|
|
||||||
triggerPattern.test(message.content.trim()) &&
|
|
||||||
(message.is_from_me ||
|
|
||||||
isTriggerAllowed(chatJid, message.sender, allowlistCfg)),
|
|
||||||
);
|
|
||||||
return hasTrigger || hasImplicitContinuationWindow(chatJid, messages);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getProcessableMessages(
|
export function getProcessableMessages(
|
||||||
chatJid: string,
|
chatJid: string,
|
||||||
messages: Parameters<typeof filterProcessableMessages>[0],
|
messages: Parameters<typeof filterProcessableMessages>[0],
|
||||||
|
|||||||
@@ -109,5 +109,3 @@ export function requestArbiterOrEscalate(args: {
|
|||||||
}
|
}
|
||||||
return transitioned;
|
return transitioned;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type RequestArbiterOrEscalateFn = typeof requestArbiterOrEscalate;
|
|
||||||
|
|||||||
@@ -449,14 +449,6 @@ export interface PreparedPairedExecutionContext {
|
|||||||
blockMessage?: string;
|
blockMessage?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PairedExecutionRecoveryPlan {
|
|
||||||
task: PairedTask;
|
|
||||||
role: RoomRoleContext['role'];
|
|
||||||
checkpointFingerprint: string | null;
|
|
||||||
recoveryKey: string;
|
|
||||||
prompt: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isOwnerContinuationTurn(
|
function isOwnerContinuationTurn(
|
||||||
turnIdentity: PairedTurnIdentity | undefined,
|
turnIdentity: PairedTurnIdentity | undefined,
|
||||||
): boolean {
|
): boolean {
|
||||||
|
|||||||
@@ -143,6 +143,3 @@ export function applyPairedTaskPatch(args: {
|
|||||||
}
|
}
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TransitionPairedTaskStatusFn = typeof transitionPairedTaskStatus;
|
|
||||||
export type ApplyPairedTaskPatchFn = typeof applyPairedTaskPatch;
|
|
||||||
|
|||||||
@@ -483,19 +483,6 @@ function listAllowedUntrackedFiles(sourceDir: string): string[] {
|
|||||||
]).filter(shouldIncludeUntrackedReviewerPath);
|
]).filter(shouldIncludeUntrackedReviewerPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
function listReviewableTrackedDiffFiles(
|
|
||||||
sourceDir: string,
|
|
||||||
sourceRef: string,
|
|
||||||
): string[] {
|
|
||||||
return listGitPaths(sourceDir, [
|
|
||||||
'diff',
|
|
||||||
'--name-only',
|
|
||||||
'-z',
|
|
||||||
sourceRef,
|
|
||||||
'--',
|
|
||||||
]).filter((relativePath) => !isReviewerSnapshotDeniedPath(relativePath));
|
|
||||||
}
|
|
||||||
|
|
||||||
function copySnapshotPaths(
|
function copySnapshotPaths(
|
||||||
sourceDir: string,
|
sourceDir: string,
|
||||||
targetDir: string,
|
targetDir: string,
|
||||||
@@ -696,76 +683,6 @@ function makeWorkspaceRecord(args: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolvePairedTaskSourceFingerprint(
|
|
||||||
taskId: string,
|
|
||||||
): string | null {
|
|
||||||
const { task } = getTaskAndProject(taskId);
|
|
||||||
const ownerWorkspace = getPairedWorkspace(taskId, 'owner');
|
|
||||||
if (!ownerWorkspace) {
|
|
||||||
return task.source_ref || null;
|
|
||||||
}
|
|
||||||
|
|
||||||
ensureGitRepository(ownerWorkspace.workspace_dir);
|
|
||||||
return buildReviewerSnapshotFingerprint({
|
|
||||||
sourceDir: ownerWorkspace.workspace_dir,
|
|
||||||
allowedTrackedFiles: listAllowedTrackedFiles(ownerWorkspace.workspace_dir),
|
|
||||||
deletedTrackedFiles: listDeletedTrackedFiles(ownerWorkspace.workspace_dir),
|
|
||||||
allowedUntrackedFiles: listAllowedUntrackedFiles(
|
|
||||||
ownerWorkspace.workspace_dir,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function hasReviewableOwnerWorkspaceChanges(taskId: string): boolean {
|
|
||||||
const { task } = getTaskAndProject(taskId);
|
|
||||||
const ownerWorkspace = getPairedWorkspace(taskId, 'owner');
|
|
||||||
if (!ownerWorkspace) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ensureGitRepository(ownerWorkspace.workspace_dir);
|
|
||||||
const reviewableTrackedDiffs = listReviewableTrackedDiffFiles(
|
|
||||||
ownerWorkspace.workspace_dir,
|
|
||||||
task.source_ref || 'HEAD',
|
|
||||||
);
|
|
||||||
if (reviewableTrackedDiffs.length > 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return listAllowedUntrackedFiles(ownerWorkspace.workspace_dir).length > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register the canonical project directory as the owner workspace.
|
|
||||||
* No worktree is created — the owner works directly on the live project.
|
|
||||||
* This preserves the Claude SDK session across tasks (same project path).
|
|
||||||
*/
|
|
||||||
export function registerOwnerCanonicalWorkspace(
|
|
||||||
taskId: string,
|
|
||||||
canonicalWorkDir: string,
|
|
||||||
): PairedWorkspace {
|
|
||||||
ensureGitRepository(canonicalWorkDir);
|
|
||||||
const installResult = ensureWorkspaceDependenciesInstalled(canonicalWorkDir);
|
|
||||||
if (installResult.installed) {
|
|
||||||
logger.info(
|
|
||||||
{
|
|
||||||
taskId,
|
|
||||||
workspaceDir: canonicalWorkDir,
|
|
||||||
packageManager: installResult.packageManager,
|
|
||||||
command: installResult.commandText ?? null,
|
|
||||||
},
|
|
||||||
'Installed owner workspace dependencies',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const workspace = makeWorkspaceRecord({
|
|
||||||
taskId,
|
|
||||||
role: 'owner',
|
|
||||||
workspaceDir: canonicalWorkDir,
|
|
||||||
});
|
|
||||||
upsertPairedWorkspace(workspace);
|
|
||||||
return workspace;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function provisionOwnerWorkspaceForPairedTask(
|
export function provisionOwnerWorkspaceForPairedTask(
|
||||||
taskId: string,
|
taskId: string,
|
||||||
): PairedWorkspace {
|
): PairedWorkspace {
|
||||||
|
|||||||
@@ -1,70 +0,0 @@
|
|||||||
import { SERVICE_ID } from './config.js';
|
|
||||||
import { writeRestartContext } from './restart-context.js';
|
|
||||||
|
|
||||||
function printUsageAndExit(): never {
|
|
||||||
console.error(
|
|
||||||
[
|
|
||||||
'Usage:',
|
|
||||||
' bun src/restart-context-cli.ts write --chat-jid <jid> --summary <text> [--verify <text> ...] [--service-id <id> ...]',
|
|
||||||
].join('\n'),
|
|
||||||
);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const [, , command, ...args] = process.argv;
|
|
||||||
if (command !== 'write') {
|
|
||||||
printUsageAndExit();
|
|
||||||
}
|
|
||||||
|
|
||||||
let chatJid = '';
|
|
||||||
let summary = '';
|
|
||||||
const verify: string[] = [];
|
|
||||||
const serviceIds: string[] = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < args.length; i += 1) {
|
|
||||||
const arg = args[i];
|
|
||||||
const value = args[i + 1];
|
|
||||||
if (!value) {
|
|
||||||
printUsageAndExit();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (arg === '--chat-jid' || arg === '--jid') {
|
|
||||||
chatJid = value;
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (arg === '--summary') {
|
|
||||||
summary = value;
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (arg === '--verify') {
|
|
||||||
verify.push(value);
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (arg === '--service-id') {
|
|
||||||
serviceIds.push(value);
|
|
||||||
i += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
printUsageAndExit();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!chatJid || !summary) {
|
|
||||||
printUsageAndExit();
|
|
||||||
}
|
|
||||||
|
|
||||||
const written = writeRestartContext(
|
|
||||||
{
|
|
||||||
chatJid,
|
|
||||||
summary,
|
|
||||||
verify,
|
|
||||||
},
|
|
||||||
serviceIds.length > 0 ? serviceIds : [SERVICE_ID],
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const filePath of written) {
|
|
||||||
console.log(filePath);
|
|
||||||
}
|
|
||||||
@@ -133,26 +133,6 @@ function getRecentCommit(processStartedAtMs: number): string | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function writeRestartContext(
|
|
||||||
context: Omit<RestartContext, 'writtenAt'>,
|
|
||||||
serviceIds: string[] = [SERVICE_ID],
|
|
||||||
): string[] {
|
|
||||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
||||||
const payload: RestartContext = {
|
|
||||||
...context,
|
|
||||||
verify: context.verify,
|
|
||||||
writtenAt: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const writtenPaths: string[] = [];
|
|
||||||
for (const serviceId of serviceIds) {
|
|
||||||
const filePath = getRestartContextPath(serviceId);
|
|
||||||
writeJsonFile(filePath, payload, true);
|
|
||||||
writtenPaths.push(filePath);
|
|
||||||
}
|
|
||||||
return writtenPaths;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function writeShutdownRestartContext(
|
export function writeShutdownRestartContext(
|
||||||
roomBindings: Record<string, RegisteredGroup>,
|
roomBindings: Record<string, RegisteredGroup>,
|
||||||
interruptedGroups: RestartInterruptedGroup[],
|
interruptedGroups: RestartInterruptedGroup[],
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
normalizeServiceId,
|
normalizeServiceId,
|
||||||
} from './config.js';
|
} from './config.js';
|
||||||
import {
|
import {
|
||||||
clearChannelOwnerLease,
|
|
||||||
getAllChannelOwnerLeases,
|
getAllChannelOwnerLeases,
|
||||||
getEffectiveRuntimeRoomMode,
|
getEffectiveRuntimeRoomMode,
|
||||||
getStoredRoomRoleAgentPlan,
|
getStoredRoomRoleAgentPlan,
|
||||||
@@ -253,26 +252,6 @@ export function resolveLeaseServiceId(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isOwnerServiceForChat(
|
|
||||||
chatJid: string,
|
|
||||||
serviceId: string = SERVICE_ID,
|
|
||||||
): boolean {
|
|
||||||
const lease = getEffectiveChannelLease(chatJid);
|
|
||||||
return (
|
|
||||||
normalizeServiceId(serviceId) === resolveLeaseServiceId(lease, 'owner')
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isReviewerServiceForChat(
|
|
||||||
chatJid: string,
|
|
||||||
serviceId: string = SERVICE_ID,
|
|
||||||
): boolean {
|
|
||||||
const lease = getEffectiveChannelLease(chatJid);
|
|
||||||
return (
|
|
||||||
normalizeServiceId(serviceId) === resolveLeaseServiceId(lease, 'reviewer')
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function hasReviewerLease(chatJid: string): boolean {
|
export function hasReviewerLease(chatJid: string): boolean {
|
||||||
return (
|
return (
|
||||||
resolveLeaseServiceId(getEffectiveChannelLease(chatJid), 'reviewer') !==
|
resolveLeaseServiceId(getEffectiveChannelLease(chatJid), 'reviewer') !==
|
||||||
@@ -280,16 +259,6 @@ export function hasReviewerLease(chatJid: string): boolean {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isArbiterServiceForChat(
|
|
||||||
chatJid: string,
|
|
||||||
serviceId: string = SERVICE_ID,
|
|
||||||
): boolean {
|
|
||||||
const lease = getEffectiveChannelLease(chatJid);
|
|
||||||
return (
|
|
||||||
normalizeServiceId(serviceId) === resolveLeaseServiceId(lease, 'arbiter')
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function shouldServiceProcessChat(
|
export function shouldServiceProcessChat(
|
||||||
_chatJid: string,
|
_chatJid: string,
|
||||||
_serviceId: string = SERVICE_ID,
|
_serviceId: string = SERVICE_ID,
|
||||||
@@ -314,10 +283,6 @@ export function activateCodexFailover(_chatJid: string, reason: string): void {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isGlobalFailoverActive(): boolean {
|
|
||||||
return globalFailoverActive;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getGlobalFailoverInfo(): {
|
export function getGlobalFailoverInfo(): {
|
||||||
active: boolean;
|
active: boolean;
|
||||||
reason: string | null;
|
reason: string | null;
|
||||||
@@ -337,27 +302,3 @@ export function clearGlobalFailover(): void {
|
|||||||
globalFailoverActivatedAt = null;
|
globalFailoverActivatedAt = null;
|
||||||
logger.info('Global failover cleared — resuming normal owner routing');
|
logger.info('Global failover cleared — resuming normal owner routing');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function restoreDefaultChannelLease(chatJid: string): void {
|
|
||||||
clearChannelOwnerLease(chatJid);
|
|
||||||
leaseCache.delete(chatJid);
|
|
||||||
lastLeaseRefreshAt = Date.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ActiveFailoverLease {
|
|
||||||
chatJid: string;
|
|
||||||
activatedAt: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getActiveCodexFailoverLeases(): ActiveFailoverLease[] {
|
|
||||||
// Global failover: report as a single pseudo-lease
|
|
||||||
if (globalFailoverActive) {
|
|
||||||
return [{ chatJid: '*', activatedAt: globalFailoverActivatedAt }];
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @deprecated Use getActiveCodexFailoverLeases() instead */
|
|
||||||
export function getActiveCodexFailoverChatJids(): string[] {
|
|
||||||
return getActiveCodexFailoverLeases().map((l) => l.chatJid);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -41,8 +41,6 @@ export type AgentOutputPhase =
|
|||||||
/** Phase as visible in the UI (mapped from AgentOutputPhase). */
|
/** Phase as visible in the UI (mapped from AgentOutputPhase). */
|
||||||
export type VisiblePhase = 'silent' | 'progress' | 'final';
|
export type VisiblePhase = 'silent' | 'progress' | 'final';
|
||||||
|
|
||||||
export type AgentVisibility = 'public' | 'silent';
|
|
||||||
|
|
||||||
export interface OutboundAttachment {
|
export interface OutboundAttachment {
|
||||||
path: string;
|
path: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -166,8 +164,6 @@ export interface PairedWorkspace {
|
|||||||
updated_at: string;
|
updated_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AgentResponsePolicy = 'normal' | 'silent-unless-addressed';
|
|
||||||
|
|
||||||
export type StructuredAgentOutput =
|
export type StructuredAgentOutput =
|
||||||
| {
|
| {
|
||||||
visibility: 'public';
|
visibility: 'public';
|
||||||
|
|||||||
@@ -219,10 +219,3 @@ export function startUsagePrimer(): void {
|
|||||||
};
|
};
|
||||||
scheduleNext();
|
scheduleNext();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function stopUsagePrimer(): void {
|
|
||||||
if (primerTimer) {
|
|
||||||
clearTimeout(primerTimer);
|
|
||||||
primerTimer = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
15
src/utils.ts
15
src/utils.ts
@@ -38,21 +38,6 @@ export function writeJsonFile(
|
|||||||
|
|
||||||
// ── Fetch with timeout ──────────────────────────────────────────
|
// ── Fetch with timeout ──────────────────────────────────────────
|
||||||
|
|
||||||
/** Wrapper around fetch() that aborts after timeoutMs. */
|
|
||||||
export async function fetchWithTimeout(
|
|
||||||
url: string,
|
|
||||||
init: RequestInit,
|
|
||||||
timeoutMs: number,
|
|
||||||
): Promise<Response> {
|
|
||||||
const controller = new AbortController();
|
|
||||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
||||||
try {
|
|
||||||
return await fetch(url, { ...init, signal: controller.signal });
|
|
||||||
} finally {
|
|
||||||
clearTimeout(timer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Time formatting ─────────────────────────────────────────────
|
// ── Time formatting ─────────────────────────────────────────────
|
||||||
|
|
||||||
/** Format milliseconds as Korean elapsed time (e.g. "1시간 2분 30초"). */
|
/** Format milliseconds as Korean elapsed time (e.g. "1시간 2분 30초"). */
|
||||||
|
|||||||
@@ -553,42 +553,3 @@ export function ensureWorkspaceDependenciesInstalled(
|
|||||||
commandText: command.commandText,
|
commandText: command.commandText,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function detectPnpmStorePath(workspaceDir: string): string | null {
|
|
||||||
if (detectWorkspacePackageManager(workspaceDir) !== 'pnpm') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (process.env.PNPM_STORE_DIR && fs.existsSync(process.env.PNPM_STORE_DIR)) {
|
|
||||||
return process.env.PNPM_STORE_DIR;
|
|
||||||
}
|
|
||||||
|
|
||||||
const candidates: Array<[string, string[]]> = [
|
|
||||||
['pnpm', ['store', 'path']],
|
|
||||||
['corepack', ['pnpm', 'store', 'path']],
|
|
||||||
];
|
|
||||||
for (const [file, args] of candidates) {
|
|
||||||
try {
|
|
||||||
const storePath = execFileSync(file, args, {
|
|
||||||
cwd: workspaceDir,
|
|
||||||
env: buildWorkspaceCommandEnvironment(workspaceDir, 'pnpm'),
|
|
||||||
encoding: 'utf-8',
|
|
||||||
stdio: ['ignore', 'pipe', 'pipe'],
|
|
||||||
timeout: 5000,
|
|
||||||
}).trim();
|
|
||||||
if (storePath && fs.existsSync(storePath)) {
|
|
||||||
return storePath;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Try the next candidate.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaultStore = path.join(
|
|
||||||
process.env.HOME || '',
|
|
||||||
'.local',
|
|
||||||
'share',
|
|
||||||
'pnpm',
|
|
||||||
'store',
|
|
||||||
);
|
|
||||||
return fs.existsSync(defaultStore) ? defaultStore : null;
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user