codesesh 1.0.4 → 1.0.5
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/README.md +4 -4
- package/dist/{chunk-MBZ4VV4C.js → chunk-FCYCBGEL.js} +3 -3
- package/dist/{chunk-W4PZHL2C.js → chunk-NBJJGH5P.js} +57 -39
- package/dist/chunk-NBJJGH5P.js.map +1 -0
- package/dist/chunk-PAP2Q3WV.js +1271 -0
- package/dist/chunk-PAP2Q3WV.js.map +1 -0
- package/dist/{chunk-BYB77UAJ.js → chunk-TS3IWH5U.js} +115 -72
- package/dist/chunk-TS3IWH5U.js.map +1 -0
- package/dist/{chunk-YCUN52HA.js → chunk-WUYSZAYR.js} +75 -114
- package/dist/chunk-WUYSZAYR.js.map +1 -0
- package/dist/{chunk-3SXCTDD6.js → chunk-XKZSX5BM.js} +4 -3
- package/dist/chunk-YQFEGFWD.js +89 -0
- package/dist/chunk-YQFEGFWD.js.map +1 -0
- package/dist/{discovery-K3GLISI6.js → discovery-D23RV7FY.js} +11 -5
- package/dist/index.js +1415 -948
- package/dist/index.js.map +1 -1
- package/dist/project-identity-worker.js +4 -4
- package/dist/scan-refresh-worker.js +17 -7
- package/dist/scan-refresh-worker.js.map +1 -1
- package/dist/search-index-worker.js +16 -8
- package/dist/search-index-worker.js.map +1 -1
- package/dist/session-detail-worker.js +79 -0
- package/dist/session-detail-worker.js.map +1 -0
- package/dist/smart-tag-worker.js +3 -3
- package/dist/web/assets/CustomTimeWindowDialog-C9XTZRm0.js +1 -0
- package/dist/web/assets/{InteractiveReceipt-Dk50TBsH.js → InteractiveReceipt-Sca1smpv.js} +1 -1
- package/dist/web/assets/OverviewScreen-Vq6BQR9_.js +1 -0
- package/dist/web/assets/{PrismHighlighter-B1a2dPJO.js → PrismHighlighter-LWITDffT.js} +1 -1
- package/dist/web/assets/Projects-CwicV3Dk.js +1 -0
- package/dist/web/assets/{SearchResultsPanel-DfheEwpz.js → SearchResultsPanel-DCO0Ak0c.js} +1 -1
- package/dist/web/assets/SessionDetail-mdmTQgo1.js +53 -0
- package/dist/web/assets/api-CXVT9XcZ.js +1 -0
- package/dist/web/assets/contract-BS78VBCV.js +2 -0
- package/dist/web/assets/{index-Bd-YkWkZ.css → index-C5cyw58A.css} +1 -1
- package/dist/web/assets/index-H2cT-6c6.js +1423 -0
- package/dist/web/assets/{session-indexes-BsgjUoc1.js → session-indexes-yyyWpKLf.js} +2 -2
- package/dist/web/index.html +6 -6
- package/package.json +1 -1
- package/dist/chunk-BYB77UAJ.js.map +0 -1
- package/dist/chunk-G4HRD3AR.js +0 -246
- package/dist/chunk-G4HRD3AR.js.map +0 -1
- package/dist/chunk-W4PZHL2C.js.map +0 -1
- package/dist/chunk-YCUN52HA.js.map +0 -1
- package/dist/web/assets/OverviewScreen-5hvQVp4H.js +0 -1
- package/dist/web/assets/Projects-Cy_v2yep.js +0 -1
- package/dist/web/assets/SessionDetail-DRI8R3st.js +0 -53
- package/dist/web/assets/api-GP9UCedC.js +0 -1
- package/dist/web/assets/contract-xJyW5u7a.js +0 -2
- package/dist/web/assets/index-DEjvzumm.js +0 -1410
- package/dist/web/assets/panel-ND0J63d3.js +0 -1
- /package/dist/{chunk-MBZ4VV4C.js.map → chunk-FCYCBGEL.js.map} +0 -0
- /package/dist/{chunk-3SXCTDD6.js.map → chunk-XKZSX5BM.js.map} +0 -0
- /package/dist/{discovery-K3GLISI6.js.map → discovery-D23RV7FY.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import "./chunk-
|
|
3
|
-
import "./chunk-
|
|
2
|
+
import "./chunk-FCYCBGEL.js";
|
|
3
|
+
import "./chunk-PAP2Q3WV.js";
|
|
4
4
|
import {
|
|
5
5
|
computeIdentityProjection
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import "./chunk-
|
|
6
|
+
} from "./chunk-XKZSX5BM.js";
|
|
7
|
+
import "./chunk-NBJJGH5P.js";
|
|
8
8
|
|
|
9
9
|
// src/project-identity-worker.ts
|
|
10
10
|
import { parentPort } from "worker_threads";
|
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
import {
|
|
3
3
|
AgentUnavailableDuringScanError
|
|
4
4
|
} from "./chunk-RF3EEWPH.js";
|
|
5
|
+
import {
|
|
6
|
+
acknowledgeWorkerLogDrain
|
|
7
|
+
} from "./chunk-YQFEGFWD.js";
|
|
5
8
|
import "./chunk-QH2HOXJH.js";
|
|
6
9
|
import {
|
|
7
10
|
appLogger
|
|
8
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-PAP2Q3WV.js";
|
|
9
12
|
import {
|
|
10
13
|
attachMissingProjectIdentities,
|
|
11
14
|
buildAgentCacheMeta,
|
|
@@ -15,14 +18,14 @@ import {
|
|
|
15
18
|
hasStaleSessionTags,
|
|
16
19
|
planAgentScan,
|
|
17
20
|
sortSessions
|
|
18
|
-
} from "./chunk-
|
|
19
|
-
import "./chunk-
|
|
21
|
+
} from "./chunk-TS3IWH5U.js";
|
|
22
|
+
import "./chunk-XKZSX5BM.js";
|
|
20
23
|
import {
|
|
21
24
|
createRegisteredAgents
|
|
22
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-WUYSZAYR.js";
|
|
23
26
|
import {
|
|
24
27
|
synchronizePricingGeneration
|
|
25
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-NBJJGH5P.js";
|
|
26
29
|
|
|
27
30
|
// src/scan-refresh-worker.ts
|
|
28
31
|
import { parentPort, workerData } from "worker_threads";
|
|
@@ -513,7 +516,12 @@ function handleCommit(data) {
|
|
|
513
516
|
}
|
|
514
517
|
}
|
|
515
518
|
function enqueueRequest(data) {
|
|
516
|
-
requestTail = requestTail.then(
|
|
519
|
+
requestTail = requestTail.then(
|
|
520
|
+
() => appLogger.restoreContext(
|
|
521
|
+
data.logContext ?? {},
|
|
522
|
+
() => data.type === "commit" ? handleCommit(data) : handleRequest(data)
|
|
523
|
+
)
|
|
524
|
+
).catch((error) => {
|
|
517
525
|
appLogger.error("scan.refresh_worker.request_error", {
|
|
518
526
|
request_id: data.requestId,
|
|
519
527
|
request_type: data.type,
|
|
@@ -525,7 +533,9 @@ var initialRequest = workerData;
|
|
|
525
533
|
if (initialRequest?.type === "run" && typeof initialRequest.requestId === "number" && typeof initialRequest.agentName === "string" && typeof initialRequest.pricingGenerationId === "number" && initialRequest.operation != null && Array.isArray(initialRequest.previousSessions) && initialRequest.meta != null) {
|
|
526
534
|
enqueueRequest(initialRequest);
|
|
527
535
|
}
|
|
528
|
-
|
|
536
|
+
var workerPort = parentPort;
|
|
537
|
+
workerPort?.on("message", (message) => {
|
|
538
|
+
if (acknowledgeWorkerLogDrain(workerPort, message, requestTail)) return;
|
|
529
539
|
enqueueRequest(message);
|
|
530
540
|
});
|
|
531
541
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/scan-refresh-worker.ts","../src/monotonic-value-sampler.ts","../src/scan-refresh-delta.ts","../src/scan-refresh-operation.ts"],"sourcesContent":["import \"./diagnostics-bridge.js\";\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport {\n attachMissingProjectIdentities,\n buildAgentCacheMeta,\n ensureSessionTagsSync,\n executeAgentScanPlan,\n hasStaleSessionTags,\n planAgentScan,\n sortSessions,\n type ScanOptions,\n type SessionHead,\n type PersistedSessionHeadChange,\n type SessionSnapshotCompleteness,\n type SessionTagTiming,\n} from \"@codesesh/core/runtime/discovery\";\nimport {\n createRegisteredAgents,\n type AgentScanProgress,\n type BaseAgent,\n type SessionCacheMeta,\n type SessionSourceFailure,\n} from \"@codesesh/core/runtime/agents\";\nimport { synchronizePricingGeneration } from \"@codesesh/core/runtime/pricing\";\nimport { appLogger } from \"./logging.js\";\nimport { MonotonicValueSampler } from \"./monotonic-value-sampler.js\";\nimport { buildScanRefreshDelta } from \"./scan-refresh-delta.js\";\nimport {\n AgentUnavailableDuringScanError,\n type ScanRefreshWorkerErrorCode,\n} from \"./scan-refresh-error.js\";\nimport {\n isBackfillOperation,\n scanIntentForOperation,\n usesDurableCheckpoints,\n type ScanRefreshOperation,\n} from \"./scan-refresh-operation.js\";\n\nexport type ScanRefreshWorkerMessage =\n | {\n type: \"progress\";\n requestId: number;\n generation: number;\n progress: AgentScanProgress;\n }\n | {\n type: \"checkpoint\";\n requestId: number;\n generation: number;\n checkpoint: ScanRefreshWorkerCheckpoint;\n }\n | {\n type: \"done\";\n requestId: number;\n generation: number;\n changes: PersistedSessionHeadChange[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n removedMetaIds: string[];\n sourceFailures: SessionSourceFailure[];\n completeness: SessionSnapshotCompleteness;\n explicitRemovedSessionIds: string[];\n durationMs: number;\n }\n | {\n type: \"error\";\n requestId: number;\n generation: number;\n error: string;\n errorCode?: ScanRefreshWorkerErrorCode;\n durationMs: number;\n };\n\nexport type ScanRefreshWorkerCheckpoint =\n | {\n stage: \"scanned\";\n sessions: SessionHead[];\n meta: Record<string, SessionCacheMeta>;\n completeness: SessionSnapshotCompleteness;\n }\n | {\n stage: \"finalizing\";\n changes: PersistedSessionHeadChange[];\n meta: Record<string, SessionCacheMeta>;\n backfillCursor?: string;\n };\n\nexport interface ScanRefreshWorkerRunRequest {\n type: \"run\";\n requestId: number;\n agentName: string;\n generation: number;\n pricingGenerationId: number;\n previousSessions?: SessionHead[];\n operation: ScanRefreshOperation;\n scanOptions: Pick<ScanOptions, \"from\" | \"to\" | \"fast\">;\n meta?: Record<string, SessionCacheMeta>;\n}\n\nexport interface ScanRefreshWorkerCommitRequest {\n type: \"commit\";\n requestId: number;\n generation: number;\n}\n\nexport type ScanRefreshWorkerRequest = ScanRefreshWorkerRunRequest | ScanRefreshWorkerCommitRequest;\n\ninterface StagedWorkerBaseline {\n requestId: number;\n generation: number;\n sessions: SessionHead[];\n meta: Record<string, SessionCacheMeta>;\n}\n\ninterface WorkerBaseline {\n agentName: string;\n agent: BaseAgent;\n generation: number;\n sessions: SessionHead[];\n meta: Record<string, SessionCacheMeta>;\n staged: StagedWorkerBaseline | null;\n}\n\ninterface BackfillSelection {\n orderedSessions: SessionHead[];\n finalizeSessionIds: ReadonlySet<string>;\n cursorIndex: number;\n}\n\nfunction selectBackfillSessions(\n sessions: SessionHead[],\n changedIds: string[],\n cursor: string | null | undefined,\n): BackfillSelection {\n const orderedSessions = sortSessions(sessions);\n const cursorIndex = cursor\n ? orderedSessions.findIndex((session) => session.reference.sessionId === cursor)\n : -1;\n const finalizeSessionIds = new Set<string>();\n const startIndex = cursorIndex >= 0 ? cursorIndex + 1 : 0;\n\n for (let index = startIndex; index < orderedSessions.length; index += 1) {\n finalizeSessionIds.add(orderedSessions[index]!.reference.sessionId);\n }\n\n for (const changedId of changedIds) finalizeSessionIds.add(changedId);\n\n // A hot session before the cursor remains stale until it settles. Keep it in\n // the next pass so it is not permanently skipped when it becomes idle.\n for (let index = 0; index <= cursorIndex; index += 1) {\n const session = orderedSessions[index]!;\n if (hasStaleSessionTags(session)) finalizeSessionIds.add(session.reference.sessionId);\n }\n\n return { orderedSessions, finalizeSessionIds, cursorIndex };\n}\n\n/**\n * A session still receiving writes will be stale again within seconds, so\n * recomputing its tags every refresh cycle is wasted work — wait for it to\n * settle before paying the getSessionData() parse cost.\n */\nconst TAG_SETTLE_MS = 60_000;\nconst TAG_CHECKPOINT_SIZE = 32;\nconst PROGRESS_INTERVAL_MS = 100;\n\ninterface SessionFinalizationTiming extends SessionTagTiming {\n batches: number;\n}\n\nfunction createSessionFinalizationTiming(): SessionFinalizationTiming {\n return {\n batches: 0,\n sessions: 0,\n cacheHits: 0,\n staleSessions: 0,\n failedSessions: 0,\n getSessionDataCalls: 0,\n getSessionDataMs: 0,\n classifySessionTagsCalls: 0,\n classifySessionTagsMs: 0,\n };\n}\n\nfunction addSessionTagTiming(target: SessionFinalizationTiming, source: SessionTagTiming): void {\n target.sessions += source.sessions;\n target.cacheHits += source.cacheHits;\n target.staleSessions += source.staleSessions;\n target.failedSessions += source.failedSessions;\n target.getSessionDataCalls += source.getSessionDataCalls;\n target.getSessionDataMs += source.getSessionDataMs;\n target.classifySessionTagsCalls += source.classifySessionTagsCalls;\n target.classifySessionTagsMs += source.classifySessionTagsMs;\n}\n\nfunction roundMilliseconds(value: number): number {\n return Math.round(value * 100) / 100;\n}\n\nfunction isSettled(session: SessionHead, now: number): boolean {\n return now - (session.time_updated ?? session.time_created) >= TAG_SETTLE_MS;\n}\n\n/**\n * Runs identity resolution (spawns git) and stale smart-tag reclassification\n * on the worker thread, off the server's main event loop.\n */\nexport function finalizeSessions(\n agent: BaseAgent,\n sessions: SessionHead[],\n onProgress?: (progress: AgentScanProgress) => void,\n onCheckpoint?: (checkpoint: ScanRefreshWorkerCheckpoint) => void,\n finalizeSessionIds?: ReadonlySet<string>,\n onTiming?: (timing: SessionTagTiming) => void,\n): SessionHead[] {\n const ordered = sortSessions(attachMissingProjectIdentities(sessions));\n\n const now = Date.now();\n const settled = ordered.filter(\n (session) =>\n (!finalizeSessionIds || finalizeSessionIds.has(session.reference.sessionId)) &&\n isSettled(session, now),\n );\n if (settled.length === 0) return ordered;\n\n let lastReportedAt = -Infinity;\n const reportProgress = (processed: number, total: number): void => {\n const now = performance.now();\n if (processed !== 0 && processed !== total && now - lastReportedAt < 100) return;\n lastReportedAt = now;\n onProgress?.({\n phase: \"finalizing\",\n total,\n processed,\n sessions: ordered.length,\n });\n };\n reportProgress(0, settled.length);\n\n const sortIndexById = new Map(\n ordered.map((session, index) => [session.reference.sessionId, index]),\n );\n const taggedById = new Map<string, SessionHead>();\n for (let start = 0; start < settled.length; start += TAG_CHECKPOINT_SIZE) {\n const batch = settled.slice(start, start + TAG_CHECKPOINT_SIZE);\n const taggedResult = ensureSessionTagsSync(agent, batch, (processed) => {\n reportProgress(start + processed, settled.length);\n });\n if (taggedResult.timing) onTiming?.(taggedResult.timing);\n const taggedBatch = taggedResult.sessions;\n for (const session of taggedBatch) taggedById.set(session.reference.sessionId, session);\n\n onCheckpoint?.({\n stage: \"finalizing\",\n changes: taggedBatch.map((session) => ({\n session,\n sortIndex: sortIndexById.get(session.reference.sessionId) ?? 0,\n })),\n meta: buildAgentCacheMeta(\n agent,\n new Set(taggedBatch.map((session) => session.reference.sessionId)),\n ),\n });\n }\n return ordered.map((session) => taggedById.get(session.reference.sessionId) ?? session);\n}\n\nlet workerBaseline: WorkerBaseline | null = null;\n\nfunction baselineFor(data: ScanRefreshWorkerRunRequest): WorkerBaseline {\n const generation = data.generation ?? 0;\n const hasSessions = Array.isArray(data.previousSessions);\n const hasMeta = data.meta != null;\n if (hasSessions !== hasMeta)\n throw new Error(\"Worker baseline requires sessions and meta together\");\n\n if (hasSessions && hasMeta) {\n if (workerBaseline) throw new Error(\"Scan refresh worker baseline is already initialized\");\n const agent = createRegisteredAgents().find((item) => item.name === data.agentName);\n if (!agent) throw new Error(`Unknown agent: ${data.agentName}`);\n workerBaseline = {\n agentName: data.agentName,\n agent,\n generation,\n sessions: data.previousSessions!,\n meta: data.meta!,\n staged: null,\n };\n }\n\n if (!workerBaseline) throw new Error(\"Scan refresh worker baseline is not initialized\");\n if (workerBaseline.agentName !== data.agentName) {\n throw new Error(`Worker Agent mismatch: expected ${workerBaseline.agentName}`);\n }\n if (workerBaseline.generation !== generation) {\n throw new Error(\n `Worker generation mismatch: expected ${workerBaseline.generation}, received ${generation}`,\n );\n }\n if (workerBaseline.staged) {\n throw new Error(`Worker result ${workerBaseline.staged.requestId} is awaiting commit`);\n }\n\n workerBaseline.agent.restoreSessionCacheMeta(workerBaseline.meta);\n return workerBaseline;\n}\n\nasync function run(\n data: ScanRefreshWorkerRunRequest,\n progressEmitter: MonotonicValueSampler<AgentScanProgress>,\n): Promise<void> {\n const startedAt = performance.now();\n const baseline = baselineFor(data);\n const { agent } = baseline;\n const previousSessions = baseline.sessions;\n const previousMeta = baseline.meta;\n const operation = data.operation;\n const backfill = isBackfillOperation(operation);\n const scanPlan = planAgentScan(agent.sessionSourceAccess, scanIntentForOperation(operation));\n const durableCheckpoints = usesDurableCheckpoints(operation);\n const backfillCursor = backfill ? operation.cursor : undefined;\n\n appLogger.debug(\"scan.refresh_worker.started\", {\n agent: data.agentName,\n operation: operation.kind,\n backfill_cursor: backfillCursor ?? undefined,\n previous_sessions: previousSessions.length,\n });\n\n const reportProgress = (progress: AgentScanProgress): void => {\n progressEmitter.push(progress, progress.phase ?? \"scanning\");\n };\n\n if (!agent.isAvailable()) {\n appLogger.warn(\"scan.refresh_worker.agent_unavailable\", {\n agent: data.agentName,\n operation: operation.kind,\n });\n throw new AgentUnavailableDuringScanError(data.agentName);\n }\n\n if (scanPlan.kind === \"check-for-changes\") {\n throw new Error(`Change checks must run before dispatching Agent ${agent.name} to the worker`);\n }\n const execution = executeAgentScanPlan(\n agent,\n scanPlan,\n { sessions: previousSessions, meta: previousMeta },\n { ...data.scanOptions, onProgress: reportProgress },\n );\n let sessions = execution.sessions;\n const changedIds = execution.changedSessionIds;\n const sourceFailures = execution.sourceFailures;\n const explicitRemovedSessionIds = execution.explicitRemovedSessionIds;\n let finalizeSessionIds: ReadonlySet<string> | undefined =\n execution.finalizeSessionIds === undefined ? undefined : new Set(execution.finalizeSessionIds);\n let backfillOrder: SessionHead[] | undefined;\n let backfillCursorIndex = -1;\n const sourceSynchronizationDetails = execution.sourceSynchronization\n ? {\n sourceCount: execution.sourceSynchronization.sourceCount,\n removedCount: execution.sourceSynchronization.removedSourceCount,\n enumerationMs: execution.sourceSynchronization.timing.enumerationMs,\n diffMs: execution.sourceSynchronization.timing.diffMs,\n parseMs: execution.sourceSynchronization.timing.parseMs,\n changedCount: execution.sourceSynchronization.timing.changedSourceCount,\n processedCount: execution.sourceSynchronization.timing.processedSourceCount,\n }\n : undefined;\n\n sessions = attachMissingProjectIdentities(sessions);\n const completeness = execution.completeness;\n if (durableCheckpoints) {\n const ordered = sortSessions(sessions);\n parentPort?.postMessage({\n type: \"checkpoint\",\n requestId: data.requestId,\n generation: baseline.generation,\n checkpoint: {\n stage: \"scanned\",\n sessions: ordered,\n meta: buildAgentCacheMeta(\n agent,\n new Set(ordered.map((session) => session.reference.sessionId)),\n ),\n completeness,\n },\n } satisfies ScanRefreshWorkerMessage);\n sessions = ordered;\n }\n\n if (backfill) {\n const selection = selectBackfillSessions(sessions, changedIds ?? [], backfillCursor);\n sessions = selection.orderedSessions;\n finalizeSessionIds = selection.finalizeSessionIds;\n backfillOrder = selection.orderedSessions;\n backfillCursorIndex = selection.cursorIndex;\n }\n\n const scanDuration = performance.now() - startedAt;\n appLogger.debug(\"scan.refresh_worker.scanned\", {\n agent: data.agentName,\n operation: operation.kind,\n backfill_cursor: backfillCursor ?? undefined,\n sessions: sessions.length,\n changed_ids: changedIds?.length ?? 0,\n source_count: sourceSynchronizationDetails?.sourceCount,\n removed_count: sourceSynchronizationDetails?.removedCount,\n source_enumeration_ms: roundMilliseconds(sourceSynchronizationDetails?.enumerationMs ?? 0),\n source_diff_ms: roundMilliseconds(sourceSynchronizationDetails?.diffMs ?? 0),\n source_parse_ms: roundMilliseconds(sourceSynchronizationDetails?.parseMs ?? 0),\n changed_sources: sourceSynchronizationDetails?.changedCount,\n processed_sources: sourceSynchronizationDetails?.processedCount,\n failed_sources: sourceFailures.length,\n duration_ms: Math.round(scanDuration),\n });\n\n const finalizeStartedAt = performance.now();\n const finalizationTiming = createSessionFinalizationTiming();\n const backfillPositionById = backfillOrder\n ? new Map(backfillOrder.map((session, index) => [session.reference.sessionId, index]))\n : undefined;\n sessions = finalizeSessions(\n agent,\n sessions,\n reportProgress,\n durableCheckpoints\n ? (checkpoint) => {\n let nextCheckpoint = checkpoint;\n if (checkpoint.stage === \"finalizing\" && backfillOrder && backfillPositionById) {\n let nextCursorIndex = backfillCursorIndex;\n for (const { session } of checkpoint.changes) {\n const index = backfillPositionById.get(session.reference.sessionId);\n if (index != null && index > nextCursorIndex) nextCursorIndex = index;\n }\n if (nextCursorIndex > backfillCursorIndex) {\n backfillCursorIndex = nextCursorIndex;\n nextCheckpoint = {\n ...checkpoint,\n backfillCursor: backfillOrder[nextCursorIndex]?.reference.sessionId,\n };\n }\n }\n parentPort?.postMessage({\n type: \"checkpoint\",\n requestId: data.requestId,\n generation: baseline.generation,\n checkpoint: nextCheckpoint,\n } satisfies ScanRefreshWorkerMessage);\n }\n : undefined,\n finalizeSessionIds,\n (batchTiming) => {\n finalizationTiming.batches += 1;\n addSessionTagTiming(finalizationTiming, batchTiming);\n appLogger.debug(\"scan.refresh_worker.finalization_batch\", {\n agent: data.agentName,\n batch: finalizationTiming.batches,\n sessions: batchTiming.sessions,\n cache_hits: batchTiming.cacheHits,\n stale_sessions: batchTiming.staleSessions,\n failed_sessions: batchTiming.failedSessions,\n get_session_data_calls: batchTiming.getSessionDataCalls,\n get_session_data_ms: roundMilliseconds(batchTiming.getSessionDataMs),\n classify_session_tags_calls: batchTiming.classifySessionTagsCalls,\n classify_session_tags_ms: roundMilliseconds(batchTiming.classifySessionTagsMs),\n });\n },\n );\n const finalizationDuration = performance.now() - finalizeStartedAt;\n const otherFinalizationMs = Math.max(\n 0,\n finalizationDuration -\n finalizationTiming.getSessionDataMs -\n finalizationTiming.classifySessionTagsMs,\n );\n appLogger.debug(\"scan.refresh_worker.finalized\", {\n agent: data.agentName,\n operation: operation.kind,\n backfill_cursor: backfillOrder?.[backfillCursorIndex]?.reference.sessionId,\n sessions: sessions.length,\n finalized_sessions: finalizationTiming.sessions,\n batches: finalizationTiming.batches,\n cache_hits: finalizationTiming.cacheHits,\n stale_sessions: finalizationTiming.staleSessions,\n failed_sessions: finalizationTiming.failedSessions,\n get_session_data_calls: finalizationTiming.getSessionDataCalls,\n get_session_data_ms: roundMilliseconds(finalizationTiming.getSessionDataMs),\n get_session_data_avg_ms: roundMilliseconds(\n finalizationTiming.getSessionDataCalls > 0\n ? finalizationTiming.getSessionDataMs / finalizationTiming.getSessionDataCalls\n : 0,\n ),\n classify_session_tags_calls: finalizationTiming.classifySessionTagsCalls,\n classify_session_tags_ms: roundMilliseconds(finalizationTiming.classifySessionTagsMs),\n classify_session_tags_avg_ms: roundMilliseconds(\n finalizationTiming.classifySessionTagsCalls > 0\n ? finalizationTiming.classifySessionTagsMs / finalizationTiming.classifySessionTagsCalls\n : 0,\n ),\n other_finalization_ms: roundMilliseconds(otherFinalizationMs),\n duration_ms: roundMilliseconds(finalizationDuration),\n total_duration_ms: Math.round(performance.now() - startedAt),\n });\n const nextMeta = buildAgentCacheMeta(\n agent,\n new Set(sessions.map((session) => session.reference.sessionId)),\n );\n const delta = buildScanRefreshDelta({\n previousSessions,\n sessions,\n previousMeta,\n nextMeta,\n changedIds,\n completeness,\n explicitRemovedSessionIds,\n });\n\n baseline.staged = {\n requestId: data.requestId,\n generation: baseline.generation,\n sessions,\n meta: nextMeta,\n };\n progressEmitter.flush();\n parentPort?.postMessage({\n type: \"done\",\n requestId: data.requestId,\n generation: baseline.generation,\n ...delta,\n sourceFailures,\n completeness,\n explicitRemovedSessionIds,\n durationMs: performance.now() - startedAt,\n } satisfies ScanRefreshWorkerMessage);\n}\n\nasync function handleRequest(data: ScanRefreshWorkerRunRequest): Promise<void> {\n const startedAt = performance.now();\n const progressEmitter = new MonotonicValueSampler<AgentScanProgress>(\n PROGRESS_INTERVAL_MS,\n (progress) => {\n parentPort?.postMessage({\n type: \"progress\",\n requestId: data.requestId,\n generation: data.generation ?? 0,\n progress,\n } satisfies ScanRefreshWorkerMessage);\n },\n );\n try {\n synchronizePricingGeneration(data.pricingGenerationId);\n await run(data, progressEmitter);\n } catch (error) {\n progressEmitter.flush();\n postRequestError(data, error, startedAt);\n } finally {\n progressEmitter.cancel();\n }\n}\n\nlet requestTail = Promise.resolve();\n\nfunction commitBaseline(data: ScanRefreshWorkerCommitRequest): void {\n if (!workerBaseline) throw new Error(\"Cannot commit an uninitialized worker baseline\");\n const staged = workerBaseline.staged;\n if (!staged || staged.requestId !== data.requestId) {\n throw new Error(`Worker result ${data.requestId} is not awaiting commit`);\n }\n if (workerBaseline.generation !== data.generation || staged.generation !== data.generation) {\n throw new Error(\n `Worker commit generation mismatch: expected ${workerBaseline.generation}, received ${data.generation}`,\n );\n }\n workerBaseline.sessions = staged.sessions;\n workerBaseline.meta = staged.meta;\n workerBaseline.generation += 1;\n workerBaseline.staged = null;\n}\n\nfunction postRequestError(data: ScanRefreshWorkerRequest, error: unknown, startedAt: number): void {\n const errorCode = error instanceof AgentUnavailableDuringScanError ? error.code : undefined;\n parentPort?.postMessage({\n type: \"error\",\n requestId: data.requestId,\n generation: data.generation,\n error: error instanceof Error ? error.message : String(error),\n ...(errorCode ? { errorCode } : {}),\n durationMs: performance.now() - startedAt,\n } satisfies ScanRefreshWorkerMessage);\n}\n\nfunction handleCommit(data: ScanRefreshWorkerCommitRequest): void {\n const startedAt = performance.now();\n try {\n commitBaseline(data);\n } catch (error) {\n postRequestError(data, error, startedAt);\n }\n}\n\nfunction enqueueRequest(data: ScanRefreshWorkerRequest): void {\n requestTail = requestTail\n .then(() => (data.type === \"commit\" ? handleCommit(data) : handleRequest(data)))\n .catch((error) => {\n appLogger.error(\"scan.refresh_worker.request_error\", {\n request_id: data.requestId,\n request_type: data.type,\n error,\n });\n });\n}\n\nconst initialRequest = workerData as Partial<ScanRefreshWorkerRequest> | undefined;\nif (\n initialRequest?.type === \"run\" &&\n typeof initialRequest.requestId === \"number\" &&\n typeof initialRequest.agentName === \"string\" &&\n typeof initialRequest.pricingGenerationId === \"number\" &&\n initialRequest.operation != null &&\n Array.isArray(initialRequest.previousSessions) &&\n initialRequest.meta != null\n) {\n enqueueRequest(initialRequest as ScanRefreshWorkerRunRequest);\n}\n\nparentPort?.on(\"message\", (message: ScanRefreshWorkerRequest) => {\n enqueueRequest(message);\n});\n","export class MonotonicValueSampler<Value> {\n private phase: string | null = null;\n private lastEmittedAt = -Infinity;\n private pending: Value | undefined;\n private hasPending = false;\n\n constructor(\n private readonly intervalMs: number,\n private readonly emit: (value: Value) => void,\n private readonly now: () => number = () => performance.now(),\n ) {}\n\n push(value: Value, phase: string): void {\n if (this.phase !== phase) {\n this.flush();\n this.phase = phase;\n this.emitNow(value);\n return;\n }\n\n if (this.now() - this.lastEmittedAt >= this.intervalMs) {\n this.pending = undefined;\n this.hasPending = false;\n this.emitNow(value);\n return;\n }\n\n this.pending = value;\n this.hasPending = true;\n }\n\n flush(): void {\n if (!this.hasPending) return;\n const pending = this.pending as Value;\n this.pending = undefined;\n this.hasPending = false;\n this.emitNow(pending);\n }\n\n cancel(): void {\n this.phase = null;\n this.lastEmittedAt = -Infinity;\n this.pending = undefined;\n this.hasPending = false;\n }\n\n private emitNow(value: Value): void {\n this.lastEmittedAt = this.now();\n this.emit(value);\n }\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport {\n buildSessionPersistenceDiff,\n type PersistedSessionHeadChange,\n type SessionHead,\n type SessionSnapshotCompleteness,\n} from \"@codesesh/core/runtime/discovery\";\nimport { type SessionCacheMeta } from \"@codesesh/core/runtime/agents\";\n\ninterface ScanRefreshDeltaInput {\n previousSessions: SessionHead[];\n sessions: SessionHead[];\n previousMeta: Record<string, SessionCacheMeta>;\n nextMeta: Record<string, SessionCacheMeta>;\n changedIds?: string[];\n completeness: SessionSnapshotCompleteness;\n explicitRemovedSessionIds: string[];\n}\n\nexport interface ScanRefreshDelta {\n changes: PersistedSessionHeadChange[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n removedMetaIds: string[];\n}\n\nexport function buildScanRefreshDelta(input: ScanRefreshDeltaInput): ScanRefreshDelta {\n const meta: Record<string, SessionCacheMeta> = {};\n const removedMetaIds: string[] = [];\n for (const [id, value] of Object.entries(input.nextMeta)) {\n if (!isDeepStrictEqual(input.previousMeta[id], value)) meta[id] = value;\n }\n for (const id of Object.keys(input.previousMeta)) {\n if (!Object.hasOwn(input.nextMeta, id)) removedMetaIds.push(id);\n }\n\n const diff = buildSessionPersistenceDiff(input.previousSessions, input.sessions, {\n candidateChangedIds: [...(input.changedIds ?? []), ...Object.keys(meta), ...removedMetaIds],\n completeness: input.completeness,\n explicitRemovedSessionIds: input.explicitRemovedSessionIds,\n });\n return {\n changes: diff.changedSessions,\n removedSessionIds: diff.removedSessionIds,\n meta,\n removedMetaIds,\n };\n}\n","import type { AgentScanIntent } from \"@codesesh/core/runtime/discovery\";\n\ntype DurableCheckpoint = { checkpoint?: \"durable\" };\n\nexport type ScanRefreshOperation =\n | ({ kind: \"full-scan\" } & DurableCheckpoint)\n | ({ kind: \"source-refresh\" } & DurableCheckpoint)\n | { kind: \"recompute-derived\" }\n | ({ kind: \"backfill\"; cursor?: string | null } & DurableCheckpoint);\n\nexport type BackfillScanRefreshOperation = Extract<ScanRefreshOperation, { kind: \"backfill\" }>;\n\nexport function isBackfillOperation(\n operation: ScanRefreshOperation,\n): operation is BackfillScanRefreshOperation {\n return operation.kind === \"backfill\";\n}\n\nexport function usesDurableCheckpoints(operation: ScanRefreshOperation): boolean {\n return \"checkpoint\" in operation && operation.checkpoint === \"durable\";\n}\n\nexport function scanIntentForOperation(operation: ScanRefreshOperation): AgentScanIntent {\n switch (operation.kind) {\n case \"full-scan\":\n return \"reload\";\n case \"source-refresh\":\n return \"refresh\";\n case \"recompute-derived\":\n return \"recompute-derived\";\n case \"backfill\":\n return \"backfill\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,YAAY,kBAAkB;;;ACDhC,IAAM,wBAAN,MAAmC;AAAA,EAMxC,YACmB,YACA,MACA,MAAoB,MAAM,YAAY,IAAI,GAC3D;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAHgB;AAAA,EACA;AAAA,EACA;AAAA,EARX,QAAuB;AAAA,EACvB,gBAAgB;AAAA,EAChB;AAAA,EACA,aAAa;AAAA,EAQrB,KAAK,OAAc,OAAqB;AACtC,QAAI,KAAK,UAAU,OAAO;AACxB,WAAK,MAAM;AACX,WAAK,QAAQ;AACb,WAAK,QAAQ,KAAK;AAClB;AAAA,IACF;AAEA,QAAI,KAAK,IAAI,IAAI,KAAK,iBAAiB,KAA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AAAA,MACnD,YAAY,KAAK;AAAA,MACjB,cAAc,KAAK;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACL;AAEA,IAAM,iBAAiB;AACvB,IACE,gBAAgB,SAAS,SACzB,OAAO,eAAe,cAAc,YACpC,OAAO,eAAe,cAAc,YACpC,OAAO,eAAe,wBAAwB,YAC9C,eAAe,aAAa,QAC5B,MAAM,QAAQ,eAAe,gBAAgB,KAC7C,eAAe,QAAQ,MACvB;AACA,iBAAe,cAA6C;AAC9D;AAEA,YAAY,GAAG,WAAW,CAAC,YAAsC;AAC/D,iBAAe,OAAO;AACxB,CAAC;","names":["now"]}
|
|
1
|
+
{"version":3,"sources":["../src/scan-refresh-worker.ts","../src/monotonic-value-sampler.ts","../src/scan-refresh-delta.ts","../src/scan-refresh-operation.ts"],"sourcesContent":["import \"./diagnostics-bridge.js\";\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport {\n attachMissingProjectIdentities,\n buildAgentCacheMeta,\n ensureSessionTagsSync,\n executeAgentScanPlan,\n hasStaleSessionTags,\n planAgentScan,\n sortSessions,\n type ScanOptions,\n type SessionHead,\n type PersistedSessionHeadChange,\n type SessionSnapshotCompleteness,\n type SessionTagTiming,\n} from \"@codesesh/core/runtime/discovery\";\nimport {\n createRegisteredAgents,\n type AgentScanProgress,\n type BaseAgent,\n type SessionCacheMeta,\n type SessionSourceFailure,\n} from \"@codesesh/core/runtime/agents\";\nimport { synchronizePricingGeneration } from \"@codesesh/core/runtime/pricing\";\nimport { appLogger, type LogContext } from \"./logging.js\";\nimport { acknowledgeWorkerLogDrain } from \"./worker-log-drain.js\";\nimport { MonotonicValueSampler } from \"./monotonic-value-sampler.js\";\nimport { buildScanRefreshDelta } from \"./scan-refresh-delta.js\";\nimport {\n AgentUnavailableDuringScanError,\n type ScanRefreshWorkerErrorCode,\n} from \"./scan-refresh-error.js\";\nimport {\n isBackfillOperation,\n scanIntentForOperation,\n usesDurableCheckpoints,\n type ScanRefreshOperation,\n} from \"./scan-refresh-operation.js\";\n\nexport type ScanRefreshWorkerMessage =\n | {\n type: \"progress\";\n requestId: number;\n generation: number;\n progress: AgentScanProgress;\n }\n | {\n type: \"checkpoint\";\n requestId: number;\n generation: number;\n checkpoint: ScanRefreshWorkerCheckpoint;\n }\n | {\n type: \"done\";\n requestId: number;\n generation: number;\n changes: PersistedSessionHeadChange[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n removedMetaIds: string[];\n sourceFailures: SessionSourceFailure[];\n completeness: SessionSnapshotCompleteness;\n explicitRemovedSessionIds: string[];\n durationMs: number;\n }\n | {\n type: \"error\";\n requestId: number;\n generation: number;\n error: string;\n errorCode?: ScanRefreshWorkerErrorCode;\n durationMs: number;\n };\n\nexport type ScanRefreshWorkerCheckpoint =\n | {\n stage: \"scanned\";\n sessions: SessionHead[];\n meta: Record<string, SessionCacheMeta>;\n completeness: SessionSnapshotCompleteness;\n }\n | {\n stage: \"finalizing\";\n changes: PersistedSessionHeadChange[];\n meta: Record<string, SessionCacheMeta>;\n backfillCursor?: string;\n };\n\nexport interface ScanRefreshWorkerRunRequest {\n type: \"run\";\n requestId: number;\n agentName: string;\n generation: number;\n pricingGenerationId: number;\n previousSessions?: SessionHead[];\n operation: ScanRefreshOperation;\n scanOptions: Pick<ScanOptions, \"from\" | \"to\" | \"fast\">;\n meta?: Record<string, SessionCacheMeta>;\n logContext?: LogContext;\n}\n\nexport interface ScanRefreshWorkerCommitRequest {\n type: \"commit\";\n requestId: number;\n generation: number;\n logContext?: LogContext;\n}\n\nexport type ScanRefreshWorkerRequest = ScanRefreshWorkerRunRequest | ScanRefreshWorkerCommitRequest;\n\ninterface StagedWorkerBaseline {\n requestId: number;\n generation: number;\n sessions: SessionHead[];\n meta: Record<string, SessionCacheMeta>;\n}\n\ninterface WorkerBaseline {\n agentName: string;\n agent: BaseAgent;\n generation: number;\n sessions: SessionHead[];\n meta: Record<string, SessionCacheMeta>;\n staged: StagedWorkerBaseline | null;\n}\n\ninterface BackfillSelection {\n orderedSessions: SessionHead[];\n finalizeSessionIds: ReadonlySet<string>;\n cursorIndex: number;\n}\n\nfunction selectBackfillSessions(\n sessions: SessionHead[],\n changedIds: string[],\n cursor: string | null | undefined,\n): BackfillSelection {\n const orderedSessions = sortSessions(sessions);\n const cursorIndex = cursor\n ? orderedSessions.findIndex((session) => session.reference.sessionId === cursor)\n : -1;\n const finalizeSessionIds = new Set<string>();\n const startIndex = cursorIndex >= 0 ? cursorIndex + 1 : 0;\n\n for (let index = startIndex; index < orderedSessions.length; index += 1) {\n finalizeSessionIds.add(orderedSessions[index]!.reference.sessionId);\n }\n\n for (const changedId of changedIds) finalizeSessionIds.add(changedId);\n\n // A hot session before the cursor remains stale until it settles. Keep it in\n // the next pass so it is not permanently skipped when it becomes idle.\n for (let index = 0; index <= cursorIndex; index += 1) {\n const session = orderedSessions[index]!;\n if (hasStaleSessionTags(session)) finalizeSessionIds.add(session.reference.sessionId);\n }\n\n return { orderedSessions, finalizeSessionIds, cursorIndex };\n}\n\n/**\n * A session still receiving writes will be stale again within seconds, so\n * recomputing its tags every refresh cycle is wasted work — wait for it to\n * settle before paying the getSessionData() parse cost.\n */\nconst TAG_SETTLE_MS = 60_000;\nconst TAG_CHECKPOINT_SIZE = 32;\nconst PROGRESS_INTERVAL_MS = 100;\n\ninterface SessionFinalizationTiming extends SessionTagTiming {\n batches: number;\n}\n\nfunction createSessionFinalizationTiming(): SessionFinalizationTiming {\n return {\n batches: 0,\n sessions: 0,\n cacheHits: 0,\n staleSessions: 0,\n failedSessions: 0,\n getSessionDataCalls: 0,\n getSessionDataMs: 0,\n classifySessionTagsCalls: 0,\n classifySessionTagsMs: 0,\n };\n}\n\nfunction addSessionTagTiming(target: SessionFinalizationTiming, source: SessionTagTiming): void {\n target.sessions += source.sessions;\n target.cacheHits += source.cacheHits;\n target.staleSessions += source.staleSessions;\n target.failedSessions += source.failedSessions;\n target.getSessionDataCalls += source.getSessionDataCalls;\n target.getSessionDataMs += source.getSessionDataMs;\n target.classifySessionTagsCalls += source.classifySessionTagsCalls;\n target.classifySessionTagsMs += source.classifySessionTagsMs;\n}\n\nfunction roundMilliseconds(value: number): number {\n return Math.round(value * 100) / 100;\n}\n\nfunction isSettled(session: SessionHead, now: number): boolean {\n return now - (session.time_updated ?? session.time_created) >= TAG_SETTLE_MS;\n}\n\n/**\n * Runs identity resolution (spawns git) and stale smart-tag reclassification\n * on the worker thread, off the server's main event loop.\n */\nexport function finalizeSessions(\n agent: BaseAgent,\n sessions: SessionHead[],\n onProgress?: (progress: AgentScanProgress) => void,\n onCheckpoint?: (checkpoint: ScanRefreshWorkerCheckpoint) => void,\n finalizeSessionIds?: ReadonlySet<string>,\n onTiming?: (timing: SessionTagTiming) => void,\n): SessionHead[] {\n const ordered = sortSessions(attachMissingProjectIdentities(sessions));\n\n const now = Date.now();\n const settled = ordered.filter(\n (session) =>\n (!finalizeSessionIds || finalizeSessionIds.has(session.reference.sessionId)) &&\n isSettled(session, now),\n );\n if (settled.length === 0) return ordered;\n\n let lastReportedAt = -Infinity;\n const reportProgress = (processed: number, total: number): void => {\n const now = performance.now();\n if (processed !== 0 && processed !== total && now - lastReportedAt < 100) return;\n lastReportedAt = now;\n onProgress?.({\n phase: \"finalizing\",\n total,\n processed,\n sessions: ordered.length,\n });\n };\n reportProgress(0, settled.length);\n\n const sortIndexById = new Map(\n ordered.map((session, index) => [session.reference.sessionId, index]),\n );\n const taggedById = new Map<string, SessionHead>();\n for (let start = 0; start < settled.length; start += TAG_CHECKPOINT_SIZE) {\n const batch = settled.slice(start, start + TAG_CHECKPOINT_SIZE);\n const taggedResult = ensureSessionTagsSync(agent, batch, (processed) => {\n reportProgress(start + processed, settled.length);\n });\n if (taggedResult.timing) onTiming?.(taggedResult.timing);\n const taggedBatch = taggedResult.sessions;\n for (const session of taggedBatch) taggedById.set(session.reference.sessionId, session);\n\n onCheckpoint?.({\n stage: \"finalizing\",\n changes: taggedBatch.map((session) => ({\n session,\n sortIndex: sortIndexById.get(session.reference.sessionId) ?? 0,\n })),\n meta: buildAgentCacheMeta(\n agent,\n new Set(taggedBatch.map((session) => session.reference.sessionId)),\n ),\n });\n }\n return ordered.map((session) => taggedById.get(session.reference.sessionId) ?? session);\n}\n\nlet workerBaseline: WorkerBaseline | null = null;\n\nfunction baselineFor(data: ScanRefreshWorkerRunRequest): WorkerBaseline {\n const generation = data.generation ?? 0;\n const hasSessions = Array.isArray(data.previousSessions);\n const hasMeta = data.meta != null;\n if (hasSessions !== hasMeta)\n throw new Error(\"Worker baseline requires sessions and meta together\");\n\n if (hasSessions && hasMeta) {\n if (workerBaseline) throw new Error(\"Scan refresh worker baseline is already initialized\");\n const agent = createRegisteredAgents().find((item) => item.name === data.agentName);\n if (!agent) throw new Error(`Unknown agent: ${data.agentName}`);\n workerBaseline = {\n agentName: data.agentName,\n agent,\n generation,\n sessions: data.previousSessions!,\n meta: data.meta!,\n staged: null,\n };\n }\n\n if (!workerBaseline) throw new Error(\"Scan refresh worker baseline is not initialized\");\n if (workerBaseline.agentName !== data.agentName) {\n throw new Error(`Worker Agent mismatch: expected ${workerBaseline.agentName}`);\n }\n if (workerBaseline.generation !== generation) {\n throw new Error(\n `Worker generation mismatch: expected ${workerBaseline.generation}, received ${generation}`,\n );\n }\n if (workerBaseline.staged) {\n throw new Error(`Worker result ${workerBaseline.staged.requestId} is awaiting commit`);\n }\n\n workerBaseline.agent.restoreSessionCacheMeta(workerBaseline.meta);\n return workerBaseline;\n}\n\nasync function run(\n data: ScanRefreshWorkerRunRequest,\n progressEmitter: MonotonicValueSampler<AgentScanProgress>,\n): Promise<void> {\n const startedAt = performance.now();\n const baseline = baselineFor(data);\n const { agent } = baseline;\n const previousSessions = baseline.sessions;\n const previousMeta = baseline.meta;\n const operation = data.operation;\n const backfill = isBackfillOperation(operation);\n const scanPlan = planAgentScan(agent.sessionSourceAccess, scanIntentForOperation(operation));\n const durableCheckpoints = usesDurableCheckpoints(operation);\n const backfillCursor = backfill ? operation.cursor : undefined;\n\n appLogger.debug(\"scan.refresh_worker.started\", {\n agent: data.agentName,\n operation: operation.kind,\n backfill_cursor: backfillCursor ?? undefined,\n previous_sessions: previousSessions.length,\n });\n\n const reportProgress = (progress: AgentScanProgress): void => {\n progressEmitter.push(progress, progress.phase ?? \"scanning\");\n };\n\n if (!agent.isAvailable()) {\n appLogger.warn(\"scan.refresh_worker.agent_unavailable\", {\n agent: data.agentName,\n operation: operation.kind,\n });\n throw new AgentUnavailableDuringScanError(data.agentName);\n }\n\n if (scanPlan.kind === \"check-for-changes\") {\n throw new Error(`Change checks must run before dispatching Agent ${agent.name} to the worker`);\n }\n const execution = executeAgentScanPlan(\n agent,\n scanPlan,\n { sessions: previousSessions, meta: previousMeta },\n { ...data.scanOptions, onProgress: reportProgress },\n );\n let sessions = execution.sessions;\n const changedIds = execution.changedSessionIds;\n const sourceFailures = execution.sourceFailures;\n const explicitRemovedSessionIds = execution.explicitRemovedSessionIds;\n let finalizeSessionIds: ReadonlySet<string> | undefined =\n execution.finalizeSessionIds === undefined ? undefined : new Set(execution.finalizeSessionIds);\n let backfillOrder: SessionHead[] | undefined;\n let backfillCursorIndex = -1;\n const sourceSynchronizationDetails = execution.sourceSynchronization\n ? {\n sourceCount: execution.sourceSynchronization.sourceCount,\n removedCount: execution.sourceSynchronization.removedSourceCount,\n enumerationMs: execution.sourceSynchronization.timing.enumerationMs,\n diffMs: execution.sourceSynchronization.timing.diffMs,\n parseMs: execution.sourceSynchronization.timing.parseMs,\n changedCount: execution.sourceSynchronization.timing.changedSourceCount,\n processedCount: execution.sourceSynchronization.timing.processedSourceCount,\n }\n : undefined;\n\n sessions = attachMissingProjectIdentities(sessions);\n const completeness = execution.completeness;\n if (durableCheckpoints) {\n const ordered = sortSessions(sessions);\n parentPort?.postMessage({\n type: \"checkpoint\",\n requestId: data.requestId,\n generation: baseline.generation,\n checkpoint: {\n stage: \"scanned\",\n sessions: ordered,\n meta: buildAgentCacheMeta(\n agent,\n new Set(ordered.map((session) => session.reference.sessionId)),\n ),\n completeness,\n },\n } satisfies ScanRefreshWorkerMessage);\n sessions = ordered;\n }\n\n if (backfill) {\n const selection = selectBackfillSessions(sessions, changedIds ?? [], backfillCursor);\n sessions = selection.orderedSessions;\n finalizeSessionIds = selection.finalizeSessionIds;\n backfillOrder = selection.orderedSessions;\n backfillCursorIndex = selection.cursorIndex;\n }\n\n const scanDuration = performance.now() - startedAt;\n appLogger.debug(\"scan.refresh_worker.scanned\", {\n agent: data.agentName,\n operation: operation.kind,\n backfill_cursor: backfillCursor ?? undefined,\n sessions: sessions.length,\n changed_ids: changedIds?.length ?? 0,\n source_count: sourceSynchronizationDetails?.sourceCount,\n removed_count: sourceSynchronizationDetails?.removedCount,\n source_enumeration_ms: roundMilliseconds(sourceSynchronizationDetails?.enumerationMs ?? 0),\n source_diff_ms: roundMilliseconds(sourceSynchronizationDetails?.diffMs ?? 0),\n source_parse_ms: roundMilliseconds(sourceSynchronizationDetails?.parseMs ?? 0),\n changed_sources: sourceSynchronizationDetails?.changedCount,\n processed_sources: sourceSynchronizationDetails?.processedCount,\n failed_sources: sourceFailures.length,\n duration_ms: Math.round(scanDuration),\n });\n\n const finalizeStartedAt = performance.now();\n const finalizationTiming = createSessionFinalizationTiming();\n const backfillPositionById = backfillOrder\n ? new Map(backfillOrder.map((session, index) => [session.reference.sessionId, index]))\n : undefined;\n sessions = finalizeSessions(\n agent,\n sessions,\n reportProgress,\n durableCheckpoints\n ? (checkpoint) => {\n let nextCheckpoint = checkpoint;\n if (checkpoint.stage === \"finalizing\" && backfillOrder && backfillPositionById) {\n let nextCursorIndex = backfillCursorIndex;\n for (const { session } of checkpoint.changes) {\n const index = backfillPositionById.get(session.reference.sessionId);\n if (index != null && index > nextCursorIndex) nextCursorIndex = index;\n }\n if (nextCursorIndex > backfillCursorIndex) {\n backfillCursorIndex = nextCursorIndex;\n nextCheckpoint = {\n ...checkpoint,\n backfillCursor: backfillOrder[nextCursorIndex]?.reference.sessionId,\n };\n }\n }\n parentPort?.postMessage({\n type: \"checkpoint\",\n requestId: data.requestId,\n generation: baseline.generation,\n checkpoint: nextCheckpoint,\n } satisfies ScanRefreshWorkerMessage);\n }\n : undefined,\n finalizeSessionIds,\n (batchTiming) => {\n finalizationTiming.batches += 1;\n addSessionTagTiming(finalizationTiming, batchTiming);\n appLogger.debug(\"scan.refresh_worker.finalization_batch\", {\n agent: data.agentName,\n batch: finalizationTiming.batches,\n sessions: batchTiming.sessions,\n cache_hits: batchTiming.cacheHits,\n stale_sessions: batchTiming.staleSessions,\n failed_sessions: batchTiming.failedSessions,\n get_session_data_calls: batchTiming.getSessionDataCalls,\n get_session_data_ms: roundMilliseconds(batchTiming.getSessionDataMs),\n classify_session_tags_calls: batchTiming.classifySessionTagsCalls,\n classify_session_tags_ms: roundMilliseconds(batchTiming.classifySessionTagsMs),\n });\n },\n );\n const finalizationDuration = performance.now() - finalizeStartedAt;\n const otherFinalizationMs = Math.max(\n 0,\n finalizationDuration -\n finalizationTiming.getSessionDataMs -\n finalizationTiming.classifySessionTagsMs,\n );\n appLogger.debug(\"scan.refresh_worker.finalized\", {\n agent: data.agentName,\n operation: operation.kind,\n backfill_cursor: backfillOrder?.[backfillCursorIndex]?.reference.sessionId,\n sessions: sessions.length,\n finalized_sessions: finalizationTiming.sessions,\n batches: finalizationTiming.batches,\n cache_hits: finalizationTiming.cacheHits,\n stale_sessions: finalizationTiming.staleSessions,\n failed_sessions: finalizationTiming.failedSessions,\n get_session_data_calls: finalizationTiming.getSessionDataCalls,\n get_session_data_ms: roundMilliseconds(finalizationTiming.getSessionDataMs),\n get_session_data_avg_ms: roundMilliseconds(\n finalizationTiming.getSessionDataCalls > 0\n ? finalizationTiming.getSessionDataMs / finalizationTiming.getSessionDataCalls\n : 0,\n ),\n classify_session_tags_calls: finalizationTiming.classifySessionTagsCalls,\n classify_session_tags_ms: roundMilliseconds(finalizationTiming.classifySessionTagsMs),\n classify_session_tags_avg_ms: roundMilliseconds(\n finalizationTiming.classifySessionTagsCalls > 0\n ? finalizationTiming.classifySessionTagsMs / finalizationTiming.classifySessionTagsCalls\n : 0,\n ),\n other_finalization_ms: roundMilliseconds(otherFinalizationMs),\n duration_ms: roundMilliseconds(finalizationDuration),\n total_duration_ms: Math.round(performance.now() - startedAt),\n });\n const nextMeta = buildAgentCacheMeta(\n agent,\n new Set(sessions.map((session) => session.reference.sessionId)),\n );\n const delta = buildScanRefreshDelta({\n previousSessions,\n sessions,\n previousMeta,\n nextMeta,\n changedIds,\n completeness,\n explicitRemovedSessionIds,\n });\n\n baseline.staged = {\n requestId: data.requestId,\n generation: baseline.generation,\n sessions,\n meta: nextMeta,\n };\n progressEmitter.flush();\n parentPort?.postMessage({\n type: \"done\",\n requestId: data.requestId,\n generation: baseline.generation,\n ...delta,\n sourceFailures,\n completeness,\n explicitRemovedSessionIds,\n durationMs: performance.now() - startedAt,\n } satisfies ScanRefreshWorkerMessage);\n}\n\nasync function handleRequest(data: ScanRefreshWorkerRunRequest): Promise<void> {\n const startedAt = performance.now();\n const progressEmitter = new MonotonicValueSampler<AgentScanProgress>(\n PROGRESS_INTERVAL_MS,\n (progress) => {\n parentPort?.postMessage({\n type: \"progress\",\n requestId: data.requestId,\n generation: data.generation ?? 0,\n progress,\n } satisfies ScanRefreshWorkerMessage);\n },\n );\n try {\n synchronizePricingGeneration(data.pricingGenerationId);\n await run(data, progressEmitter);\n } catch (error) {\n progressEmitter.flush();\n postRequestError(data, error, startedAt);\n } finally {\n progressEmitter.cancel();\n }\n}\n\nlet requestTail = Promise.resolve();\n\nfunction commitBaseline(data: ScanRefreshWorkerCommitRequest): void {\n if (!workerBaseline) throw new Error(\"Cannot commit an uninitialized worker baseline\");\n const staged = workerBaseline.staged;\n if (!staged || staged.requestId !== data.requestId) {\n throw new Error(`Worker result ${data.requestId} is not awaiting commit`);\n }\n if (workerBaseline.generation !== data.generation || staged.generation !== data.generation) {\n throw new Error(\n `Worker commit generation mismatch: expected ${workerBaseline.generation}, received ${data.generation}`,\n );\n }\n workerBaseline.sessions = staged.sessions;\n workerBaseline.meta = staged.meta;\n workerBaseline.generation += 1;\n workerBaseline.staged = null;\n}\n\nfunction postRequestError(data: ScanRefreshWorkerRequest, error: unknown, startedAt: number): void {\n const errorCode = error instanceof AgentUnavailableDuringScanError ? error.code : undefined;\n parentPort?.postMessage({\n type: \"error\",\n requestId: data.requestId,\n generation: data.generation,\n error: error instanceof Error ? error.message : String(error),\n ...(errorCode ? { errorCode } : {}),\n durationMs: performance.now() - startedAt,\n } satisfies ScanRefreshWorkerMessage);\n}\n\nfunction handleCommit(data: ScanRefreshWorkerCommitRequest): void {\n const startedAt = performance.now();\n try {\n commitBaseline(data);\n } catch (error) {\n postRequestError(data, error, startedAt);\n }\n}\n\nfunction enqueueRequest(data: ScanRefreshWorkerRequest): void {\n requestTail = requestTail\n .then(() =>\n appLogger.restoreContext(data.logContext ?? {}, () =>\n data.type === \"commit\" ? handleCommit(data) : handleRequest(data),\n ),\n )\n .catch((error) => {\n appLogger.error(\"scan.refresh_worker.request_error\", {\n request_id: data.requestId,\n request_type: data.type,\n error,\n });\n });\n}\n\nconst initialRequest = workerData as Partial<ScanRefreshWorkerRequest> | undefined;\nif (\n initialRequest?.type === \"run\" &&\n typeof initialRequest.requestId === \"number\" &&\n typeof initialRequest.agentName === \"string\" &&\n typeof initialRequest.pricingGenerationId === \"number\" &&\n initialRequest.operation != null &&\n Array.isArray(initialRequest.previousSessions) &&\n initialRequest.meta != null\n) {\n enqueueRequest(initialRequest as ScanRefreshWorkerRunRequest);\n}\n\nconst workerPort = parentPort;\nworkerPort?.on(\"message\", (message: unknown) => {\n if (acknowledgeWorkerLogDrain(workerPort, message, requestTail)) return;\n enqueueRequest(message as ScanRefreshWorkerRequest);\n});\n","export class MonotonicValueSampler<Value> {\n private phase: string | null = null;\n private lastEmittedAt = -Infinity;\n private pending: Value | undefined;\n private hasPending = false;\n\n constructor(\n private readonly intervalMs: number,\n private readonly emit: (value: Value) => void,\n private readonly now: () => number = () => performance.now(),\n ) {}\n\n push(value: Value, phase: string): void {\n if (this.phase !== phase) {\n this.flush();\n this.phase = phase;\n this.emitNow(value);\n return;\n }\n\n if (this.now() - this.lastEmittedAt >= this.intervalMs) {\n this.pending = undefined;\n this.hasPending = false;\n this.emitNow(value);\n return;\n }\n\n this.pending = value;\n this.hasPending = true;\n }\n\n flush(): void {\n if (!this.hasPending) return;\n const pending = this.pending as Value;\n this.pending = undefined;\n this.hasPending = false;\n this.emitNow(pending);\n }\n\n cancel(): void {\n this.phase = null;\n this.lastEmittedAt = -Infinity;\n this.pending = undefined;\n this.hasPending = false;\n }\n\n private emitNow(value: Value): void {\n this.lastEmittedAt = this.now();\n this.emit(value);\n }\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport {\n buildSessionPersistenceDiff,\n type PersistedSessionHeadChange,\n type SessionHead,\n type SessionSnapshotCompleteness,\n} from \"@codesesh/core/runtime/discovery\";\nimport { type SessionCacheMeta } from \"@codesesh/core/runtime/agents\";\n\ninterface ScanRefreshDeltaInput {\n previousSessions: SessionHead[];\n sessions: SessionHead[];\n previousMeta: Record<string, SessionCacheMeta>;\n nextMeta: Record<string, SessionCacheMeta>;\n changedIds?: string[];\n completeness: SessionSnapshotCompleteness;\n explicitRemovedSessionIds: string[];\n}\n\nexport interface ScanRefreshDelta {\n changes: PersistedSessionHeadChange[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n removedMetaIds: string[];\n}\n\nexport function buildScanRefreshDelta(input: ScanRefreshDeltaInput): ScanRefreshDelta {\n const meta: Record<string, SessionCacheMeta> = {};\n const removedMetaIds: string[] = [];\n for (const [id, value] of Object.entries(input.nextMeta)) {\n if (!isDeepStrictEqual(input.previousMeta[id], value)) meta[id] = value;\n }\n for (const id of Object.keys(input.previousMeta)) {\n if (!Object.hasOwn(input.nextMeta, id)) removedMetaIds.push(id);\n }\n\n const diff = buildSessionPersistenceDiff(input.previousSessions, input.sessions, {\n candidateChangedIds: [...(input.changedIds ?? []), ...Object.keys(meta), ...removedMetaIds],\n completeness: input.completeness,\n explicitRemovedSessionIds: input.explicitRemovedSessionIds,\n });\n return {\n changes: diff.changedSessions,\n removedSessionIds: diff.removedSessionIds,\n meta,\n removedMetaIds,\n };\n}\n","import type { AgentScanIntent } from \"@codesesh/core/runtime/discovery\";\n\ntype DurableCheckpoint = { checkpoint?: \"durable\" };\n\nexport type ScanRefreshOperation =\n | ({ kind: \"full-scan\" } & DurableCheckpoint)\n | ({ kind: \"source-refresh\" } & DurableCheckpoint)\n | { kind: \"recompute-derived\" }\n | ({ kind: \"backfill\"; cursor?: string | null } & DurableCheckpoint);\n\nexport type BackfillScanRefreshOperation = Extract<ScanRefreshOperation, { kind: \"backfill\" }>;\n\nexport function isBackfillOperation(\n operation: ScanRefreshOperation,\n): operation is BackfillScanRefreshOperation {\n return operation.kind === \"backfill\";\n}\n\nexport function usesDurableCheckpoints(operation: ScanRefreshOperation): boolean {\n return \"checkpoint\" in operation && operation.checkpoint === \"durable\";\n}\n\nexport function scanIntentForOperation(operation: ScanRefreshOperation): AgentScanIntent {\n switch (operation.kind) {\n case \"full-scan\":\n return \"reload\";\n case \"source-refresh\":\n return \"refresh\";\n case \"recompute-derived\":\n return \"recompute-derived\";\n case \"backfill\":\n return \"backfill\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,YAAY,kBAAkB;;;ACDhC,IAAM,wBAAN,MAAmC;AAAA,EAMxC,YACmB,YACA,MACA,MAAoB,MAAM,YAAY,IAAI,GAC3D;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAHgB;AAAA,EACA;AAAA,EACA;AAAA,EARX,QAAuB;AAAA,EACvB,gBAAgB;AAAA,EAChB;AAAA,EACA,aAAa;AAAA,EAQrB,KAAK,OAAc,OAAqB;AACtC,QAAI,KAAK,UAAU,OAAO;AACxB,WAAK,MAAM;AACX,WAAK,QAAQ;AACb,WAAK,QAAQ,KAAK;AAClB;AAAA,I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MAC9C,KAAK,SAAS,WAAW,aAAa,IAAI,IAAI,cAAc,IAAI;AAAA,IAClE;AAAA,EACF,EACC,MAAM,CAAC,UAAU;AAChB,cAAU,MAAM,qCAAqC;AAAA,MACnD,YAAY,KAAK;AAAA,MACjB,cAAc,KAAK;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACL;AAEA,IAAM,iBAAiB;AACvB,IACE,gBAAgB,SAAS,SACzB,OAAO,eAAe,cAAc,YACpC,OAAO,eAAe,cAAc,YACpC,OAAO,eAAe,wBAAwB,YAC9C,eAAe,aAAa,QAC5B,MAAM,QAAQ,eAAe,gBAAgB,KAC7C,eAAe,QAAQ,MACvB;AACA,iBAAe,cAA6C;AAC9D;AAEA,IAAM,aAAa;AACnB,YAAY,GAAG,WAAW,CAAC,YAAqB;AAC9C,MAAI,0BAA0B,YAAY,SAAS,WAAW,EAAG;AACjE,iBAAe,OAAmC;AACpD,CAAC;","names":["now"]}
|
|
@@ -1,22 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
acknowledgeWorkerLogDrain
|
|
4
|
+
} from "./chunk-YQFEGFWD.js";
|
|
2
5
|
import "./chunk-QH2HOXJH.js";
|
|
3
6
|
import {
|
|
4
7
|
appLogger
|
|
5
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-PAP2Q3WV.js";
|
|
6
9
|
import {
|
|
7
10
|
commitDurableSessionPublication,
|
|
8
11
|
markAgentCacheInitialized,
|
|
9
12
|
sessionDetailVersion,
|
|
10
13
|
syncSessionSearchIndex,
|
|
11
14
|
syncSessionSearchIndexChanges
|
|
12
|
-
} from "./chunk-
|
|
13
|
-
import "./chunk-
|
|
15
|
+
} from "./chunk-TS3IWH5U.js";
|
|
16
|
+
import "./chunk-XKZSX5BM.js";
|
|
14
17
|
import {
|
|
15
18
|
createRegisteredAgents
|
|
16
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-WUYSZAYR.js";
|
|
17
20
|
import {
|
|
18
21
|
synchronizePricingGeneration
|
|
19
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-NBJJGH5P.js";
|
|
20
23
|
|
|
21
24
|
// src/search-index-worker.ts
|
|
22
25
|
import { randomUUID } from "crypto";
|
|
@@ -192,8 +195,13 @@ function runBatch(request) {
|
|
|
192
195
|
failedAgents: [...failedAgents]
|
|
193
196
|
});
|
|
194
197
|
}
|
|
195
|
-
|
|
196
|
-
|
|
198
|
+
var workerPort = parentPort;
|
|
199
|
+
workerPort?.on("message", (message) => {
|
|
200
|
+
if (acknowledgeWorkerLogDrain(workerPort, message)) return;
|
|
201
|
+
if (message.type === "run") {
|
|
202
|
+
appLogger.restoreContext(message.logContext ?? {}, () => runBatch(message));
|
|
203
|
+
}
|
|
197
204
|
});
|
|
198
|
-
|
|
205
|
+
var initialRequest = workerData;
|
|
206
|
+
appLogger.restoreContext(initialRequest.logContext ?? {}, () => runBatch(initialRequest));
|
|
199
207
|
//# sourceMappingURL=search-index-worker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/search-index-worker.ts"],"sourcesContent":["import \"./diagnostics-bridge.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport {\n commitDurableSessionPublication,\n markAgentCacheInitialized,\n sessionDetailVersion,\n syncSessionSearchIndex,\n syncSessionSearchIndexChanges,\n type IdentifiedSessionHead,\n type SearchIndexSyncResult,\n type SearchIndexSyncOptions,\n type SearchIndexPublicationStage,\n type PersistedSessionHeadChange,\n type SessionSnapshotCompleteness,\n type DurableSessionPublicationFailureStage,\n} from \"@codesesh/core/runtime/discovery\";\nimport { createRegisteredAgents, type SessionCacheMeta } from \"@codesesh/core/runtime/agents\";\nimport { synchronizePricingGeneration } from \"@codesesh/core/runtime/pricing\";\nimport { appLogger } from \"./logging.js\";\n\nexport type SearchIndexPersistStage = DurableSessionPublicationFailureStage;\n\nexport interface SearchIndexPublicationProgress {\n agentName: string;\n stage: SearchIndexPublicationStage;\n}\n\nexport type SearchIndexWorkerOptions = Omit<SearchIndexSyncOptions, \"onPublicationStage\">;\n\nexport type SearchIndexWorkerMessage =\n | {\n type: \"sync-result\";\n context: string;\n result: SearchIndexSyncResult | null;\n }\n | {\n type: \"persist-failed\";\n context: string;\n stage: SearchIndexPersistStage;\n publicationId: string;\n agentName: string;\n sessions: number;\n /** True when the job carries a durable publication whose staged state must be rolled back. */\n fatal: boolean;\n }\n | ({ type: \"publication-progress\" } & SearchIndexPublicationProgress)\n | {\n type: \"done\";\n context: string;\n durationMs: number;\n sessions: number;\n failedAgents: string[];\n };\n\nexport type SearchIndexWorkerJob =\n | {\n kind: \"full\";\n context: string;\n agentName: string;\n sessions: IdentifiedSessionHead[];\n meta: Record<string, SessionCacheMeta>;\n completeness: SessionSnapshotCompleteness;\n removedSessionIds: string[];\n publicationId?: string;\n saveCache?: boolean;\n searchIndexOptions?: SearchIndexWorkerOptions;\n }\n | {\n kind: \"changes\";\n context: string;\n agentName: string;\n changes: PersistedSessionHeadChange<IdentifiedSessionHead>[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n publicationId?: string;\n searchIndexOptions?: SearchIndexWorkerOptions;\n }\n | {\n kind: \"maintenance\";\n context: string;\n agentName: string;\n changes: PersistedSessionHeadChange<IdentifiedSessionHead>[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n searchIndexOptions?: SearchIndexWorkerOptions;\n };\n\nexport interface SearchIndexWorkerRunRequest {\n type: \"run\";\n pricingGenerationId: number;\n jobs?: SearchIndexWorkerJob[];\n context: string;\n agentNames?: string[];\n sessionsByAgent?: Record<string, IdentifiedSessionHead[]>;\n metaByAgent?: Record<string, Record<string, SessionCacheMeta>>;\n}\n\ntype WorkerAgent = ReturnType<typeof createRegisteredAgents>[number];\n\nfunction jobSessionCount(job: SearchIndexWorkerJob): number {\n return job.kind === \"full\" ? job.sessions.length : job.changes.length;\n}\n\nfunction searchIndexOptions(job: SearchIndexWorkerJob): SearchIndexSyncOptions {\n return {\n ...job.searchIndexOptions,\n ...(job.kind === \"full\"\n ? { completeness: job.completeness, removedSessionIds: job.removedSessionIds }\n : {}),\n detailVersions: Object.fromEntries(\n Object.entries(job.meta).map(([sessionId, meta]) => [sessionId, sessionDetailVersion(meta)]),\n ),\n };\n}\n\n/**\n * Reports a persistence failure so the batch is rejected instead of settling as\n * `done`; the caller keeps its previously published snapshot and can retry.\n */\nfunction reportPersistFailure(\n job: SearchIndexWorkerJob,\n failure: { stage: SearchIndexPersistStage; publicationId: string },\n): void {\n appLogger.error(\"search_index.persist_failed\", {\n context: job.context,\n stage: failure.stage,\n agent: job.agentName,\n sessions: jobSessionCount(job),\n publication_id: failure.publicationId,\n });\n parentPort?.postMessage({\n type: \"persist-failed\",\n context: job.context,\n stage: failure.stage,\n publicationId: failure.publicationId,\n agentName: job.agentName,\n sessions: jobSessionCount(job),\n fatal: jobIsDurablePublication(job),\n } satisfies SearchIndexWorkerMessage);\n}\n\nfunction runJob(\n job: SearchIndexWorkerJob,\n agent: WorkerAgent,\n): { stage: SearchIndexPersistStage; publicationId: string } | null {\n if (job.kind === \"maintenance\") {\n const result = syncSessionSearchIndexChanges(\n job.agentName,\n job.changes,\n job.removedSessionIds,\n (sessionId) => agent.getSessionData(sessionId),\n searchIndexOptions(job),\n );\n if (!result) {\n return { stage: \"search_index\", publicationId: randomUUID() };\n }\n postSyncResult(job.context, result);\n return null;\n }\n\n if (job.kind === \"changes\") {\n const publication = commitDurableSessionPublication(\n {\n kind: \"changes\",\n agentName: job.agentName,\n changes: job.changes,\n removedSessionIds: job.removedSessionIds,\n meta: job.meta,\n ...(job.publicationId ? { publicationId: job.publicationId } : {}),\n },\n (sessionId) => agent.getSessionData(sessionId),\n publicationSearchIndexOptions(job),\n );\n if (publication.status === \"rolled-back\") return publication;\n postSyncResult(job.context, publication.searchIndex);\n return null;\n }\n\n if (job.saveCache) {\n const publication = commitDurableSessionPublication(\n {\n kind: \"snapshot\",\n agentName: job.agentName,\n sessions: job.sessions,\n meta: job.meta,\n completeness: job.completeness,\n removedSessionIds: job.removedSessionIds,\n ...(job.publicationId ? { publicationId: job.publicationId } : {}),\n },\n (sessionId) => agent.getSessionData(sessionId),\n publicationSearchIndexOptions(job),\n );\n if (publication.status === \"rolled-back\") return publication;\n const result = publication.searchIndex;\n // Head cache init is decoupled from search-index completeness (CS-73): a\n // session that fails to load must not permanently block future incremental scans.\n markAgentCacheInitialized(job.agentName);\n if (result.skipped > 0) {\n appLogger.warn(\"search_index.sync_incomplete\", {\n agent: job.agentName,\n skipped: result.skipped,\n });\n }\n postSyncResult(job.context, result);\n return null;\n }\n\n const publicationId = job.publicationId ?? randomUUID();\n const result = syncSessionSearchIndex(\n job.agentName,\n job.sessions,\n (sessionId) => agent.getSessionData(sessionId),\n searchIndexOptions(job),\n );\n if (!result) return { stage: \"search_index\", publicationId };\n postSyncResult(job.context, result);\n return null;\n}\n\nfunction publicationSearchIndexOptions(job: SearchIndexWorkerJob): SearchIndexSyncOptions {\n return {\n ...job.searchIndexOptions,\n onPublicationStage: (stage) => {\n parentPort?.postMessage({\n type: \"publication-progress\",\n agentName: job.agentName,\n stage,\n } satisfies SearchIndexWorkerMessage);\n },\n };\n}\n\nfunction postSyncResult(context: string, result: SearchIndexSyncResult): void {\n parentPort?.postMessage({\n type: \"sync-result\",\n context,\n result,\n } satisfies SearchIndexWorkerMessage);\n}\n\nlet pricingGenerationId: number | null = null;\n\nfunction jobIsDurablePublication(job: SearchIndexWorkerJob): boolean {\n return job.kind !== \"maintenance\" && job.publicationId != null;\n}\n\nfunction jobsFromRequest(request: SearchIndexWorkerRunRequest): SearchIndexWorkerJob[] {\n if (request.jobs) return request.jobs;\n return (request.agentNames ?? []).map((agentName): SearchIndexWorkerJob => ({\n kind: \"full\",\n context: request.context,\n agentName,\n sessions: request.sessionsByAgent?.[agentName] ?? [],\n meta: request.metaByAgent?.[agentName] ?? {},\n completeness: \"complete\",\n removedSessionIds: [],\n }));\n}\n\nfunction runBatch(request: SearchIndexWorkerRunRequest): void {\n const startedAt = performance.now();\n if (pricingGenerationId !== request.pricingGenerationId) {\n synchronizePricingGeneration(request.pricingGenerationId);\n pricingGenerationId = request.pricingGenerationId;\n }\n const agents = createRegisteredAgents();\n const jobs = jobsFromRequest(request);\n\n const failedAgents = new Set<string>();\n for (const job of jobs) {\n // Later chunks for an agent whose earlier job failed would commit on top\n // of unknown state; other agents' jobs are independent and keep going.\n if (failedAgents.has(job.agentName)) continue;\n const agent = agents.find((item) => item.name === job.agentName);\n if (!agent) {\n reportPersistFailure(job, {\n stage: \"prepare\",\n publicationId:\n job.kind === \"maintenance\" ? randomUUID() : (job.publicationId ?? randomUUID()),\n });\n // A session publication must reject the whole batch so its staged\n // state gets rolled back by the caller.\n if (jobIsDurablePublication(job)) return;\n failedAgents.add(job.agentName);\n continue;\n }\n\n agent.restoreSessionCacheMeta(job.meta);\n\n const failure = runJob(job, agent);\n if (failure) {\n reportPersistFailure(job, failure);\n if (jobIsDurablePublication(job)) return;\n failedAgents.add(job.agentName);\n }\n }\n\n parentPort?.postMessage({\n type: \"done\",\n context: request.context,\n durationMs: performance.now() - startedAt,\n sessions: jobs.reduce((total, job) => total + jobSessionCount(job), 0),\n failedAgents: [...failedAgents],\n } satisfies SearchIndexWorkerMessage);\n}\n\nparentPort?.on(\"message\", (message: SearchIndexWorkerRunRequest) => {\n if (message.type === \"run\") runBatch(message);\n});\nrunBatch(workerData as SearchIndexWorkerRunRequest);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,kBAAkB;AAkGvC,SAAS,gBAAgB,KAAmC;AAC1D,SAAO,IAAI,SAAS,SAAS,IAAI,SAAS,SAAS,IAAI,QAAQ;AACjE;AAEA,SAAS,mBAAmB,KAAmD;AAC7E,SAAO;AAAA,IACL,GAAG,IAAI;AAAA,IACP,GAAI,IAAI,SAAS,SACb,EAAE,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AAI,IAAI,SAAS;AAC9B;AAAA,IACF;AAEA,UAAM,wBAAwB,IAAI,IAAI;AAEtC,UAAM,UAAU,OAAO,KAAK,KAAK;AACjC,QAAI,SAAS;AACX,2BAAqB,KAAK,OAAO;AACjC,UAAI,wBAAwB,GAAG,EAAG;AAClC,mBAAa,IAAI,IAAI,SAAS;AAAA,IAChC;AAAA,EACF;AAEA,cAAY,YAAY;AAAA,IACtB,MAAM;AAAA,IACN,SAAS,QAAQ;AAAA,IACjB,YAAY,YAAY,IAAI,IAAI;AAAA,IAChC,UAAU,KAAK,OAAO,CAAC,OAAO,QAAQ,QAAQ,gBAAgB,GAAG,GAAG,CAAC;AAAA,IACrE,cAAc,CAAC,GAAG,YAAY;AAAA,EAChC,CAAoC;AACtC;AAEA,YAAY,GAAG,WAAW,CAAC,YAAyC;AAClE,MAAI,QAAQ,SAAS,MAAO,UAAS,OAAO;AAC9C,CAAC;AACD,SAAS,UAAyC;","names":["result"]}
|
|
1
|
+
{"version":3,"sources":["../src/search-index-worker.ts"],"sourcesContent":["import \"./diagnostics-bridge.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport {\n commitDurableSessionPublication,\n markAgentCacheInitialized,\n sessionDetailVersion,\n syncSessionSearchIndex,\n syncSessionSearchIndexChanges,\n type IdentifiedSessionHead,\n type SearchIndexSyncResult,\n type SearchIndexSyncOptions,\n type SearchIndexPublicationStage,\n type PersistedSessionHeadChange,\n type SessionSnapshotCompleteness,\n type DurableSessionPublicationFailureStage,\n} from \"@codesesh/core/runtime/discovery\";\nimport { createRegisteredAgents, type SessionCacheMeta } from \"@codesesh/core/runtime/agents\";\nimport { synchronizePricingGeneration } from \"@codesesh/core/runtime/pricing\";\nimport { appLogger, type LogContext } from \"./logging.js\";\nimport { acknowledgeWorkerLogDrain } from \"./worker-log-drain.js\";\n\nexport type SearchIndexPersistStage = DurableSessionPublicationFailureStage;\n\nexport interface SearchIndexPublicationProgress {\n agentName: string;\n stage: SearchIndexPublicationStage;\n}\n\nexport type SearchIndexWorkerOptions = Omit<SearchIndexSyncOptions, \"onPublicationStage\">;\n\nexport type SearchIndexWorkerMessage =\n | {\n type: \"sync-result\";\n context: string;\n result: SearchIndexSyncResult | null;\n }\n | {\n type: \"persist-failed\";\n context: string;\n stage: SearchIndexPersistStage;\n publicationId: string;\n agentName: string;\n sessions: number;\n /** True when the job carries a durable publication whose staged state must be rolled back. */\n fatal: boolean;\n }\n | ({ type: \"publication-progress\" } & SearchIndexPublicationProgress)\n | {\n type: \"done\";\n context: string;\n durationMs: number;\n sessions: number;\n failedAgents: string[];\n };\n\nexport type SearchIndexWorkerJob =\n | {\n kind: \"full\";\n context: string;\n agentName: string;\n sessions: IdentifiedSessionHead[];\n meta: Record<string, SessionCacheMeta>;\n completeness: SessionSnapshotCompleteness;\n removedSessionIds: string[];\n publicationId?: string;\n saveCache?: boolean;\n searchIndexOptions?: SearchIndexWorkerOptions;\n }\n | {\n kind: \"changes\";\n context: string;\n agentName: string;\n changes: PersistedSessionHeadChange<IdentifiedSessionHead>[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n publicationId?: string;\n searchIndexOptions?: SearchIndexWorkerOptions;\n }\n | {\n kind: \"maintenance\";\n context: string;\n agentName: string;\n changes: PersistedSessionHeadChange<IdentifiedSessionHead>[];\n removedSessionIds: string[];\n meta: Record<string, SessionCacheMeta>;\n searchIndexOptions?: SearchIndexWorkerOptions;\n };\n\nexport interface SearchIndexWorkerRunRequest {\n type: \"run\";\n pricingGenerationId: number;\n logContext?: LogContext;\n jobs?: SearchIndexWorkerJob[];\n context: string;\n agentNames?: string[];\n sessionsByAgent?: Record<string, IdentifiedSessionHead[]>;\n metaByAgent?: Record<string, Record<string, SessionCacheMeta>>;\n}\n\ntype WorkerAgent = ReturnType<typeof createRegisteredAgents>[number];\n\nfunction jobSessionCount(job: SearchIndexWorkerJob): number {\n return job.kind === \"full\" ? job.sessions.length : job.changes.length;\n}\n\nfunction searchIndexOptions(job: SearchIndexWorkerJob): SearchIndexSyncOptions {\n return {\n ...job.searchIndexOptions,\n ...(job.kind === \"full\"\n ? { completeness: job.completeness, removedSessionIds: job.removedSessionIds }\n : {}),\n detailVersions: Object.fromEntries(\n Object.entries(job.meta).map(([sessionId, meta]) => [sessionId, sessionDetailVersion(meta)]),\n ),\n };\n}\n\n/**\n * Reports a persistence failure so the batch is rejected instead of settling as\n * `done`; the caller keeps its previously published snapshot and can retry.\n */\nfunction reportPersistFailure(\n job: SearchIndexWorkerJob,\n failure: { stage: SearchIndexPersistStage; publicationId: string },\n): void {\n appLogger.error(\"search_index.persist_failed\", {\n context: job.context,\n stage: failure.stage,\n agent: job.agentName,\n sessions: jobSessionCount(job),\n publication_id: failure.publicationId,\n });\n parentPort?.postMessage({\n type: \"persist-failed\",\n context: job.context,\n stage: failure.stage,\n publicationId: failure.publicationId,\n agentName: job.agentName,\n sessions: jobSessionCount(job),\n fatal: jobIsDurablePublication(job),\n } satisfies SearchIndexWorkerMessage);\n}\n\nfunction runJob(\n job: SearchIndexWorkerJob,\n agent: WorkerAgent,\n): { stage: SearchIndexPersistStage; publicationId: string } | null {\n if (job.kind === \"maintenance\") {\n const result = syncSessionSearchIndexChanges(\n job.agentName,\n job.changes,\n job.removedSessionIds,\n (sessionId) => agent.getSessionData(sessionId),\n searchIndexOptions(job),\n );\n if (!result) {\n return { stage: \"search_index\", publicationId: randomUUID() };\n }\n postSyncResult(job.context, result);\n return null;\n }\n\n if (job.kind === \"changes\") {\n const publication = commitDurableSessionPublication(\n {\n kind: \"changes\",\n agentName: job.agentName,\n changes: job.changes,\n removedSessionIds: job.removedSessionIds,\n meta: job.meta,\n ...(job.publicationId ? { publicationId: job.publicationId } : {}),\n },\n (sessionId) => agent.getSessionData(sessionId),\n publicationSearchIndexOptions(job),\n );\n if (publication.status === \"rolled-back\") return publication;\n postSyncResult(job.context, publication.searchIndex);\n return null;\n }\n\n if (job.saveCache) {\n const publication = commitDurableSessionPublication(\n {\n kind: \"snapshot\",\n agentName: job.agentName,\n sessions: job.sessions,\n meta: job.meta,\n completeness: job.completeness,\n removedSessionIds: job.removedSessionIds,\n ...(job.publicationId ? { publicationId: job.publicationId } : {}),\n },\n (sessionId) => agent.getSessionData(sessionId),\n publicationSearchIndexOptions(job),\n );\n if (publication.status === \"rolled-back\") return publication;\n const result = publication.searchIndex;\n // Head cache init is decoupled from search-index completeness (CS-73): a\n // session that fails to load must not permanently block future incremental scans.\n markAgentCacheInitialized(job.agentName);\n if (result.skipped > 0) {\n appLogger.warn(\"search_index.sync_incomplete\", {\n agent: job.agentName,\n skipped: result.skipped,\n });\n }\n postSyncResult(job.context, result);\n return null;\n }\n\n const publicationId = job.publicationId ?? randomUUID();\n const result = syncSessionSearchIndex(\n job.agentName,\n job.sessions,\n (sessionId) => agent.getSessionData(sessionId),\n searchIndexOptions(job),\n );\n if (!result) return { stage: \"search_index\", publicationId };\n postSyncResult(job.context, result);\n return null;\n}\n\nfunction publicationSearchIndexOptions(job: SearchIndexWorkerJob): SearchIndexSyncOptions {\n return {\n ...job.searchIndexOptions,\n onPublicationStage: (stage) => {\n parentPort?.postMessage({\n type: \"publication-progress\",\n agentName: job.agentName,\n stage,\n } satisfies SearchIndexWorkerMessage);\n },\n };\n}\n\nfunction postSyncResult(context: string, result: SearchIndexSyncResult): void {\n parentPort?.postMessage({\n type: \"sync-result\",\n context,\n result,\n } satisfies SearchIndexWorkerMessage);\n}\n\nlet pricingGenerationId: number | null = null;\n\nfunction jobIsDurablePublication(job: SearchIndexWorkerJob): boolean {\n return job.kind !== \"maintenance\" && job.publicationId != null;\n}\n\nfunction jobsFromRequest(request: SearchIndexWorkerRunRequest): SearchIndexWorkerJob[] {\n if (request.jobs) return request.jobs;\n return (request.agentNames ?? []).map((agentName): SearchIndexWorkerJob => ({\n kind: \"full\",\n context: request.context,\n agentName,\n sessions: request.sessionsByAgent?.[agentName] ?? [],\n meta: request.metaByAgent?.[agentName] ?? {},\n completeness: \"complete\",\n removedSessionIds: [],\n }));\n}\n\nfunction runBatch(request: SearchIndexWorkerRunRequest): void {\n const startedAt = performance.now();\n if (pricingGenerationId !== request.pricingGenerationId) {\n synchronizePricingGeneration(request.pricingGenerationId);\n pricingGenerationId = request.pricingGenerationId;\n }\n const agents = createRegisteredAgents();\n const jobs = jobsFromRequest(request);\n\n const failedAgents = new Set<string>();\n for (const job of jobs) {\n // Later chunks for an agent whose earlier job failed would commit on top\n // of unknown state; other agents' jobs are independent and keep going.\n if (failedAgents.has(job.agentName)) continue;\n const agent = agents.find((item) => item.name === job.agentName);\n if (!agent) {\n reportPersistFailure(job, {\n stage: \"prepare\",\n publicationId:\n job.kind === \"maintenance\" ? randomUUID() : (job.publicationId ?? randomUUID()),\n });\n // A session publication must reject the whole batch so its staged\n // state gets rolled back by the caller.\n if (jobIsDurablePublication(job)) return;\n failedAgents.add(job.agentName);\n continue;\n }\n\n agent.restoreSessionCacheMeta(job.meta);\n\n const failure = runJob(job, agent);\n if (failure) {\n reportPersistFailure(job, failure);\n if (jobIsDurablePublication(job)) return;\n failedAgents.add(job.agentName);\n }\n }\n\n parentPort?.postMessage({\n type: \"done\",\n context: request.context,\n durationMs: performance.now() - startedAt,\n sessions: jobs.reduce((total, job) => total + jobSessionCount(job), 0),\n failedAgents: [...failedAgents],\n } satisfies SearchIndexWorkerMessage);\n}\n\nconst workerPort = parentPort;\nworkerPort?.on(\"message\", (message: SearchIndexWorkerRunRequest) => {\n if (acknowledgeWorkerLogDrain(workerPort, message)) return;\n if (message.type === \"run\") {\n appLogger.restoreContext(message.logContext ?? {}, () => runBatch(message));\n }\n});\nconst initialRequest = workerData as SearchIndexWorkerRunRequest;\nappLogger.restoreContext(initialRequest.logContext ?? {}, () => runBatch(initialRequest));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,kBAAkB;AAoGvC,SAAS,gBAAgB,KAAmC;AAC1D,SAAO,IAAI,SAA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AA,QACxB,OAAO;AAAA,QACP,eACE,IAAI,SAAS,gBAAgB,WAAW,IAAK,IAAI,iBAAiB,WAAW;AAAA,MACjF,CAAC;AAGD,UAAI,wBAAwB,GAAG,EAAG;AAClC,mBAAa,IAAI,IAAI,SAAS;AAC9B;AAAA,IACF;AAEA,UAAM,wBAAwB,IAAI,IAAI;AAEtC,UAAM,UAAU,OAAO,KAAK,KAAK;AACjC,QAAI,SAAS;AACX,2BAAqB,KAAK,OAAO;AACjC,UAAI,wBAAwB,GAAG,EAAG;AAClC,mBAAa,IAAI,IAAI,SAAS;AAAA,IAChC;AAAA,EACF;AAEA,cAAY,YAAY;AAAA,IACtB,MAAM;AAAA,IACN,SAAS,QAAQ;AAAA,IACjB,YAAY,YAAY,IAAI,IAAI;AAAA,IAChC,UAAU,KAAK,OAAO,CAAC,OAAO,QAAQ,QAAQ,gBAAgB,GAAG,GAAG,CAAC;AAAA,IACrE,cAAc,CAAC,GAAG,YAAY;AAAA,EAChC,CAAoC;AACtC;AAEA,IAAM,aAAa;AACnB,YAAY,GAAG,WAAW,CAAC,YAAyC;AAClE,MAAI,0BAA0B,YAAY,OAAO,EAAG;AACpD,MAAI,QAAQ,SAAS,OAAO;AAC1B,cAAU,eAAe,QAAQ,cAAc,CAAC,GAAG,MAAM,SAAS,OAAO,CAAC;AAAA,EAC5E;AACF,CAAC;AACD,IAAM,iBAAiB;AACvB,UAAU,eAAe,eAAe,cAAc,CAAC,GAAG,MAAM,SAAS,cAAc,CAAC;","names":["result"]}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
acknowledgeWorkerLogDrain
|
|
4
|
+
} from "./chunk-YQFEGFWD.js";
|
|
5
|
+
import "./chunk-QH2HOXJH.js";
|
|
6
|
+
import {
|
|
7
|
+
appLogger
|
|
8
|
+
} from "./chunk-PAP2Q3WV.js";
|
|
9
|
+
import {
|
|
10
|
+
closeCacheStorage,
|
|
11
|
+
materializeSessionDetailResponse
|
|
12
|
+
} from "./chunk-TS3IWH5U.js";
|
|
13
|
+
import "./chunk-XKZSX5BM.js";
|
|
14
|
+
import {
|
|
15
|
+
createRegisteredAgents
|
|
16
|
+
} from "./chunk-WUYSZAYR.js";
|
|
17
|
+
import {
|
|
18
|
+
synchronizePricingGeneration
|
|
19
|
+
} from "./chunk-NBJJGH5P.js";
|
|
20
|
+
|
|
21
|
+
// src/session-detail-worker.ts
|
|
22
|
+
import { parentPort, workerData } from "worker_threads";
|
|
23
|
+
var workerPort = parentPort;
|
|
24
|
+
workerPort?.on("message", (message) => {
|
|
25
|
+
acknowledgeWorkerLogDrain(workerPort, message);
|
|
26
|
+
});
|
|
27
|
+
var request = workerData;
|
|
28
|
+
var terminalMessage = appLogger.restoreContext(
|
|
29
|
+
request.logContext ?? {},
|
|
30
|
+
() => {
|
|
31
|
+
try {
|
|
32
|
+
synchronizePricingGeneration(request.pricingGenerationId);
|
|
33
|
+
const agent = createRegisteredAgents().find(
|
|
34
|
+
(item) => item.name === request.reference.agentName
|
|
35
|
+
);
|
|
36
|
+
const sessions = request.head ? [request.head] : [];
|
|
37
|
+
agent?.restoreSessionCacheMeta(request.meta);
|
|
38
|
+
const result = materializeSessionDetailResponse(
|
|
39
|
+
{
|
|
40
|
+
agents: agent ? [agent] : [],
|
|
41
|
+
sessions,
|
|
42
|
+
byAgent: { [request.reference.agentName]: sessions }
|
|
43
|
+
},
|
|
44
|
+
request.reference,
|
|
45
|
+
{ messageCursor: request.messageCursor }
|
|
46
|
+
);
|
|
47
|
+
if (result.status === "found") {
|
|
48
|
+
const { messages, ...data } = result.data;
|
|
49
|
+
return {
|
|
50
|
+
type: "result",
|
|
51
|
+
result: {
|
|
52
|
+
status: "found-json",
|
|
53
|
+
data,
|
|
54
|
+
messages: messages.map((message) => JSON.stringify(message)),
|
|
55
|
+
messageCount: messages.length,
|
|
56
|
+
sentMessageCount: messages.length
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
type: "result",
|
|
62
|
+
result: result.status === "found-json" ? { ...result, messages: [...result.messages] } : result
|
|
63
|
+
};
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return {
|
|
66
|
+
type: "error",
|
|
67
|
+
error: error instanceof Error ? error.message : String(error)
|
|
68
|
+
};
|
|
69
|
+
} finally {
|
|
70
|
+
try {
|
|
71
|
+
closeCacheStorage();
|
|
72
|
+
} catch (error) {
|
|
73
|
+
appLogger.error("session_detail.worker.close_failed", { error });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
);
|
|
78
|
+
parentPort?.postMessage(terminalMessage);
|
|
79
|
+
//# sourceMappingURL=session-detail-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/session-detail-worker.ts"],"sourcesContent":["import \"./diagnostics-bridge.js\";\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport { createRegisteredAgents, type SessionCacheMeta } from \"@codesesh/core/runtime/agents\";\nimport {\n closeCacheStorage,\n materializeSessionDetailResponse,\n type IdentifiedSessionHead,\n type SessionDetailResponseResult,\n type SessionReference,\n} from \"@codesesh/core/runtime/discovery\";\nimport { synchronizePricingGeneration } from \"@codesesh/core/runtime/pricing\";\nimport { appLogger, type LogContext } from \"./logging.js\";\nimport { acknowledgeWorkerLogDrain } from \"./worker-log-drain.js\";\n\nexport interface SessionDetailWorkerRequest {\n reference: SessionReference;\n head?: IdentifiedSessionHead;\n meta: Record<string, SessionCacheMeta>;\n messageCursor?: string;\n pricingGenerationId: number;\n logContext?: LogContext;\n}\n\nexport type SessionDetailWorkerMessage =\n | { type: \"result\"; result: SessionDetailResponseResult }\n | { type: \"error\"; error: string };\n\nconst workerPort = parentPort;\nworkerPort?.on(\"message\", (message: unknown) => {\n acknowledgeWorkerLogDrain(workerPort, message);\n});\n\nconst request = workerData as SessionDetailWorkerRequest;\nconst terminalMessage = appLogger.restoreContext(\n request.logContext ?? {},\n (): SessionDetailWorkerMessage => {\n try {\n synchronizePricingGeneration(request.pricingGenerationId);\n const agent = createRegisteredAgents().find(\n (item) => item.name === request.reference.agentName,\n );\n const sessions = request.head ? [request.head] : [];\n agent?.restoreSessionCacheMeta(request.meta);\n const result = materializeSessionDetailResponse(\n {\n agents: agent ? [agent] : [],\n sessions,\n byAgent: { [request.reference.agentName]: sessions },\n },\n request.reference,\n { messageCursor: request.messageCursor },\n );\n if (result.status === \"found\") {\n const { messages, ...data } = result.data;\n return {\n type: \"result\",\n result: {\n status: \"found-json\",\n data,\n messages: messages.map((message) => JSON.stringify(message)),\n messageCount: messages.length,\n sentMessageCount: messages.length,\n },\n };\n }\n return {\n type: \"result\",\n result:\n result.status === \"found-json\" ? { ...result, messages: [...result.messages] } : result,\n };\n } catch (error) {\n return {\n type: \"error\",\n error: error instanceof Error ? error.message : String(error),\n };\n } finally {\n try {\n closeCacheStorage();\n } catch (error) {\n appLogger.error(\"session_detail.worker.close_failed\", { error });\n }\n }\n },\n);\nparentPort?.postMessage(terminalMessage);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA,SAAS,YAAY,kBAAkB;AA0BvC,IAAM,aAAa;AACnB,YAAY,GAAG,WAAW,CAAC,YAAqB;AAC9C,4BAA0B,YAAY,OAAO;AAC/C,CAAC;AAED,IAAM,UAAU;AAChB,IAAM,kBAAkB,UAAU;AAAA,EAChC,QAAQ,cAAc,CAAC;AAAA,EACvB,MAAkC;AAChC,QAAI;AACF,mCAA6B,QAAQ,mBAAmB;AACxD,YAAM,QAAQ,uBAAuB,EAAE;AAAA,QACrC,CAAC,SAAS,KAAK,SAAS,QAAQ,UAAU;AAAA,MAC5C;AACA,YAAM,WAAW,QAAQ,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC;AAClD,aAAO,wBAAwB,QAAQ,IAAI;AAC3C,YAAM,SAAS;AAAA,QACb;AAAA,UACE,QAAQ,QAAQ,CAAC,KAAK,IAAI,CAAC;AAAA,UAC3B;AAAA,UACA,SAAS,EAAE,CAAC,QAAQ,UAAU,SAAS,GAAG,SAAS;AAAA,QACrD;AAAA,QACA,QAAQ;AAAA,QACR,EAAE,eAAe,QAAQ,cAAc;AAAA,MACzC;AACA,UAAI,OAAO,WAAW,SAAS;AAC7B,cAAM,EAAE,UAAU,GAAG,KAAK,IAAI,OAAO;AACrC,eAAO;AAAA,UACL,MAAM;AAAA,UACN,QAAQ;AAAA,YACN,QAAQ;AAAA,YACR;AAAA,YACA,UAAU,SAAS,IAAI,CAAC,YAAY,KAAK,UAAU,OAAO,CAAC;AAAA,YAC3D,cAAc,SAAS;AAAA,YACvB,kBAAkB,SAAS;AAAA,UAC7B;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,QACL,MAAM;AAAA,QACN,QACE,OAAO,WAAW,eAAe,EAAE,GAAG,QAAQ,UAAU,CAAC,GAAG,OAAO,QAAQ,EAAE,IAAI;AAAA,MACrF;AAAA,IACF,SAAS,OAAO;AACd,aAAO;AAAA,QACL,MAAM;AAAA,QACN,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MAC9D;AAAA,IACF,UAAE;AACA,UAAI;AACF,0BAAkB;AAAA,MACpB,SAAS,OAAO;AACd,kBAAU,MAAM,sCAAsC,EAAE,MAAM,CAAC;AAAA,MACjE;AAAA,IACF;AAAA,EACF;AACF;AACA,YAAY,YAAY,eAAe;","names":[]}
|
package/dist/smart-tag-worker.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "./chunk-QH2HOXJH.js";
|
|
3
|
-
import "./chunk-
|
|
3
|
+
import "./chunk-PAP2Q3WV.js";
|
|
4
4
|
import {
|
|
5
5
|
createRegisteredAgents
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-WUYSZAYR.js";
|
|
7
7
|
import {
|
|
8
8
|
classifySessionTags,
|
|
9
9
|
getSmartTagSourceTimestamp,
|
|
10
10
|
synchronizePricingGeneration
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-NBJJGH5P.js";
|
|
12
12
|
|
|
13
13
|
// src/smart-tag-worker.ts
|
|
14
14
|
import { parentPort, workerData } from "worker_threads";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,n as t,t as n}from"./jsx-runtime-B-hcVAMW.js";import{Kt as r,On as i,t as a,v as o,w as s,x as c,y as l}from"./utils-C7BqyxxV.js";import{o as u}from"./api-CXVT9XcZ.js";var d=e(t(),1),f=n(),p=d.createContext(void 0),m=e=>{let t=d.useContext(p);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},h=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,f.jsx)(p.Provider,{value:e,children:t})),g={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_=new class{#e=g;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function v(e){setTimeout(e,0)}var y=typeof window>`u`||`Deno`in globalThis;function b(){}function ee(e,t){return typeof e==`function`?e(t):e}function x(e){return typeof e==`number`&&e>=0&&e!==1/0}function S(e,t){return Math.max(e+(t||0)-Date.now(),0)}function C(e,t){return typeof e==`function`?e(t):e}function w(e,t){return typeof e==`function`?e(t):e}function te(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==T(o,t.options))return!1}else if(!D(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function ne(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(E(t.options.mutationKey)!==E(a))return!1}else if(!D(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function T(e,t){return(t?.queryKeyHashFn||E)(e)}function E(e){return JSON.stringify(e,(e,t)=>j(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function D(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n<t.length;n++)if(!D(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!D(e[r],t[r]))return!1;return!0}return!1}var re=Object.prototype.hasOwnProperty;function O(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=A(e)&&A(t);if(!r&&!(j(e)&&j(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:re.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=O(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function k(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function A(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function j(e){if(!M(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!M(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function M(e){return Object.prototype.toString.call(e)===`[object Object]`}function ie(e){return new Promise(t=>{_.setTimeout(t,e)})}function N(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:O(e,t)}function ae(e){return e}function oe(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function se(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var P=Symbol();function ce(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===P?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function F(e,t){return typeof e==`function`?e(...t):!!e}function le(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var I=(()=>{let e=()=>y;return{isServer(){return e()},setIsServer(t){e=t}}})(),L=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},R=new class extends L{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},ue=v;function de(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=ue,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var z=de(),B=new class extends L{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function fe(e){return Math.min(1e3*2**e,3e4)}function V(e){return(e??`online`)!==`online`||B.isOnline()}var H=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function U(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(b);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new H(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>R.isFocused()&&(e.networkMode===`always`||B.isOnline())&&e.canRun(),p=()=>V(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(I.isServer()?0:3),a=e.retryDelay??fe,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){h(r);return}n++,e.onFail?.(n,r),ie(o).then(()=>f()?void 0:g()).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var W=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),x(this.gcTime)&&(this.#e=_.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(I.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(_.clearTimeout(this.#e),this.#e=void 0)}};function pe(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{le(e,()=>t.signal,()=>n=!0)},u=ce(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?se:oe;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?me:G,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:G(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function G(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function me(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var he=class extends W{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=J(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=J(this.options);e.data!==void 0&&(this.setState(q(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=N(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(b).catch(b):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>w(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===P||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>C(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!S(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=ce(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?pe(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=U({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof H&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof H){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...K(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...q(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),z.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function K(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:V(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function q(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function J(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var ge=class extends L{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Y(this.#t,this.options)?this.#m():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return X(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return X(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#y(),this.#b(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof w(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#x(),this.#t.setOptions(this.options),t._defaulted&&!k(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&ve(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||w(this.options.enabled,this.#t)!==w(t.enabled,this.#t)||C(this.options.staleTime,this.#t)!==C(t.staleTime,this.#t))&&this.#h();let i=this.#g();r&&(this.#t!==n||w(this.options.enabled,this.#t)!==w(t.enabled,this.#t)||i!==this.#f)&&this.#_(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return ye(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(b)),t}#h(){this.#y();let e=C(this.options.staleTime,this.#t);if(I.isServer()||this.#r.isStale||!x(e))return;let t=S(this.#r.dataUpdatedAt,e)+1;this.#u=_.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#g(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#_(e){this.#b(),this.#f=e,!(I.isServer()||w(this.options.enabled,this.#t)===!1||!x(this.#f)||this.#f===0)&&(this.#d=_.setInterval(()=>{(this.options.refetchIntervalInBackground||R.isFocused())&&this.#m()},this.#f))}#v(){this.#h(),this.#_(this.#g())}#y(){this.#u!==void 0&&(_.clearTimeout(this.#u),this.#u=void 0)}#b(){this.#d!==void 0&&(_.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Y(e,t),o=i&&ve(e,n,t,r);(a||o)&&(l={...l,...K(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=N(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=N(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Z(e,t),refetch:this.refetch,isEnabled:w(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),!k(t,e)&&(this.#r=t,this.#S({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#x(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#S(e){z.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function _e(e,t){return w(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||w(t.retryOnMount,e)!==!1)}function Y(e,t){return _e(e,t)||e.state.data!==void 0&&X(e,t,t.refetchOnMount)}function X(e,t,n){if(w(t.enabled,e)!==!1&&C(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Z(e,t)}return!1}function ve(e,t,n,r){return(e!==t||w(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Z(e,n)}function Z(e,t){return w(t.enabled,e)!==!1&&e.isStaleByTime(C(t.staleTime,e))}function ye(e,t){return!k(e.getCurrentResult(),t)}var be=d.createContext(!1),xe=()=>d.useContext(be);be.Provider;function Se(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ce=d.createContext(Se()),we=()=>d.useContext(Ce),Te=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?F(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Ee=e=>{d.useEffect(()=>{e.clearReset()},[e])},De=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||F(n,[e.error,r])),Oe=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},ke=(e,t)=>e?.suspense&&t.isPending,Ae=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function je(e,t,n){let r=xe(),i=we(),a=m(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Oe(o),Te(o,i,s),Ee(i);let[l]=d.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),f=!r&&c;if(d.useSyncExternalStore(d.useCallback(e=>{let t=f?l.subscribe(z.batchCalls(e)):b;return l.updateResult(),t},[l,f]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(o)},[o,l]),ke(o,u))throw Ae(o,l,i);if(De({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function Me(e,t){return je(e,ge,t)}function Ne(e){return e}function Q(e){return{days:e.days,from:e.from,to:e.to}}function Pe(e){return{...e.project?{project:e.project}:{},...e.agent?{agent:e.agent}:{}}}var Fe={bookmarks:[`bookmarks`],config:[`config`],dashboards:[`dashboard`],dashboard:(e,t)=>[`dashboard`,Q(e),Pe(t)],agentCatalogs:[`agent-catalog`],agentCatalog:e=>[`agent-catalog`,Q(e)],projects:[`projects`],projectWindow:e=>[`projects`,Q(e)],projectPage:(e,t)=>[`projects`,Q(e),`page`,t??null],projectDetail:(e,t)=>[`projects`,Q(e),`detail`,t],search:(e,t)=>[`search`,e,t],searches:[`search`],sessionDetails:[`session-detail`],sessionDetail:(e,t)=>[`session-detail`,e,t],sessionProjections:[`session-projection`],sessionProjection:e=>[`session-projection`,Q(e)]},Ie=2e3;function Le(e,t){return Ne({queryKey:Fe.dashboard(e,t),staleTime:Ie,queryFn:async({signal:n})=>{try{return await u(e,t,{signal:n})}catch(e){throw n.aborted||console.error(`Failed to load dashboard:`,e),e}}})}var Re=(0,d.createContext)(`light`),ze=`(prefers-color-scheme: dark)`;function Be(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(ze).matches}function Ve(e){let[t,n]=(0,d.useState)(Be);(0,d.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(ze),t=e=>n(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let r=e===`system`?t?`dark`:`light`:e;return(0,d.useEffect)(()=>{document.documentElement.classList.toggle(`dark`,r===`dark`)},[r]),r}function He({title:e,message:t,onRetry:n,className:r=``}){return(0,f.jsxs)(`div`,{role:`alert`,className:`rounded-sm border border-[var(--console-error-border)] bg-[var(--console-error-bg)] p-4 text-[var(--console-error)] ${r}`,children:[(0,f.jsx)(`p`,{className:`text-sm font-medium`,children:e}),(0,f.jsx)(`p`,{className:`console-mono mt-1 break-words text-[11px]`,children:t}),(0,f.jsx)(`button`,{type:`button`,onClick:n,className:`console-mono mt-3 rounded-sm border border-[var(--console-error-border)] bg-[var(--console-surface)] px-2.5 py-1 text-[11px] font-semibold motion-hover hover:bg-[var(--console-error-bg)] focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:outline-none`,children:`Retry`})]})}function Ue({className:e,children:t,...n}){return(0,f.jsx)(`section`,{className:a(`rounded-lg border border-[var(--console-border)] bg-[var(--console-surface)] shadow-[var(--shadow-raised)]`,e),...n,children:t})}function We({title:e,meta:t,action:n}){return(0,f.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,f.jsx)(`h3`,{className:`console-display min-w-0 truncate text-[15px] font-semibold text-[var(--console-text)]`,children:e}),(0,f.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-3`,children:[t===void 0?null:(0,f.jsx)(`span`,{className:`console-mono text-[10.5px] text-[var(--console-muted)]`,children:t}),n]})]})}function Ge(e){let t=e.sourceFailureCount;return[t==null?null:`${t} source${t===1?``:`s`} failed`,e.sourceFailureSummary].filter(e=>e!=null).join(` · `)}function Ke(e){return(e.sourceFailureCount??0)>0||e.sourceFailureSummary!=null}function $(e){let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`}function qe(e){if(!e)return null;let{from:t,to:n,days:r}=e.window;if(r===0||t==null)return`All time`;let i=$(t),a=$(n??Date.now());return r?`Last ${r}d · ${i} → ${a}`:`${i} → ${a}`}function Je(e,t,n){return t?e?`Searching for "${e}"`:`Loading recent sessions`:e?`${n} matches for "${e}"`:`${n} recent sessions`}function Ye(e){if(!e)return null;if(e.backfill?.active){let t=e.backfill.currentAgent,n=e.backfill.pendingAgents.length,r=e.backfill.progress,i=(r?.phase==null||r.phase===`scanning`||r.phase===`finalizing`)&&r?.total&&r.processed!=null?` · ${r.processed}/${r.total}`:``,a=r?.phase===`publish-queued`?`Full-history publication queued`:r?.phase===`committing`?`Committing full-history publication`:r?.phase===`indexing`?`Writing full-history search index`:r?.phase===`publishing`?`Preparing full-history publication`:r?.phase===`finalizing`?`Finalizing full-history metadata`:`Scanning full session history`;return t?`${a} · ${t}${i}${n>0?` · ${n} history scan queued`:``}`:`${a}${i}`}if(e.backfill?.failedAgents.length)return`Full-history refresh failed · ${e.backfill.failedAgents.join(`, `)}`;let t=Object.values(e.agentStatuses??{}).find(e=>e.status===`failed`);if(t)return`Session refresh failed · ${t.agentName}${t.error?` · ${t.error}`:``}`;if(e.active){let t=e.completedAgents.length,n=e.totalAgents,r=e.scanningAgents[0],i=r?e.agentStatuses[r]:null,a=(i?.status===`scanning`||i?.status===`finalizing`)&&i.total&&i.processed!=null?` · ${i.processed}/${i.total}`:``,o=n>0?r?` · ${r}${a} · ${t}/${n} agents ready`:` · ${t}/${n} agents ready`:``,s=i?.status===`publish-queued`?`Session publication queued`:i?.status===`finalizing`?`Finalizing session metadata`:i?.status===`publishing`||i?.status===`indexing`||e.phase===`publishing`||e.phase===`indexing`?`Publishing session updates`:`Checking for new or changed sessions`;return e.phase===`initializing`?`Initializing recent sessions${o}`:e.phase===`publishing`||e.phase===`indexing`?`${s}${o}`:n>0?r?`${s} · ${r}${a} · ${t}/${n} agents ready`:`Checking for new or changed sessions · ${t}/${n} agents ready`:`Checking for new or changed sessions`}let n=Object.entries(e.backfill?.partialAgents??{}).find(([,e])=>e.completeness===`partial`&&Ke(e));if(n){let[e,t]=n,r=Ge(t);return`Full-history refresh completed with partial data · ${e}${r?` · ${r}`:``}`}let r=Object.values(e.agentStatuses??{}).find(e=>e.status===`complete`&&e.completeness===`partial`&&Ke(e));if(r){let e=Ge(r);return`Session refresh completed with partial data · ${r.agentName}${e?` · ${e}`:``}`}if(e.searchIndexMaintenance?.active){let t=e.searchIndexMaintenance.currentAgent,n=e.searchIndexMaintenance.remaining;return`Updating search index in background${t?` · ${t}`:``}${n==null?``:` · ${n} remaining`}`}return e.searchIndexMaintenance?.failedAgents.length?`Background search index maintenance paused · ${e.searchIndexMaintenance.failedAgents.join(`, `)}`:null}function Xe({open:e,onOpenChange:t,window:n,customFrom:r,customTo:i,onSelectCustom:a}){let o=r??(n?.from==null?``:$(n.from)),s=i??(n?.to==null?null:$(n.to));return(0,f.jsx)(l,{open:e,onOpenChange:t,children:e?(0,f.jsx)(Ze,{initialFrom:o,initialTo:s,onOpenChange:t,onSelectCustom:a}):null})}function Ze({initialFrom:e,initialTo:t,onOpenChange:n,onSelectCustom:a}){let[l,u]=(0,d.useState)(e),[p,m]=(0,d.useState)(()=>t??$(Date.now()));return(0,f.jsxs)(c,{children:[(0,f.jsx)(i,{className:`motion-backdrop fixed inset-0 z-50 bg-[var(--scrim)]`}),(0,f.jsxs)(s,{className:`motion-modal fixed top-1/2 left-1/2 z-50 w-[calc(100%-2rem)] max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-lg border border-[var(--console-border)] bg-[var(--console-surface)] p-5 shadow-[var(--shadow-overlay)] outline-none`,children:[(0,f.jsx)(o,{className:`console-mono text-sm font-semibold text-[var(--console-text)]`,children:`Custom time range`}),(0,f.jsx)(`p`,{className:`mt-1 text-xs text-[var(--console-muted)]`,children:`Both dates are included.`}),(0,f.jsxs)(`div`,{className:`mt-4 grid grid-cols-2 gap-3`,children:[(0,f.jsxs)(`label`,{className:`console-mono text-[11px] uppercase tracking-wide text-[var(--console-muted)]`,children:[`From`,(0,f.jsx)(`input`,{type:`date`,value:l,max:p||void 0,onChange:e=>u(e.target.value),className:`mt-1.5 w-full rounded-sm border border-[var(--console-border-strong)] bg-[var(--console-surface)] px-2 py-2 text-xs normal-case tracking-normal text-[var(--console-text)] outline-none focus:border-[var(--brand)] focus:ring-2 focus:ring-[var(--brand)]/25`})]}),(0,f.jsxs)(`label`,{className:`console-mono text-[11px] uppercase tracking-wide text-[var(--console-muted)]`,children:[`To`,(0,f.jsx)(`input`,{type:`date`,value:p,min:l||void 0,onChange:e=>m(e.target.value),className:`mt-1.5 w-full rounded-sm border border-[var(--console-border-strong)] bg-[var(--console-surface)] px-2 py-2 text-xs normal-case tracking-normal text-[var(--console-text)] outline-none focus:border-[var(--brand)] focus:ring-2 focus:ring-[var(--brand)]/25`})]})]}),(0,f.jsxs)(`div`,{className:`mt-5 flex justify-end gap-2`,children:[(0,f.jsx)(r,{className:`rounded-sm border border-[var(--console-border)] px-3 py-1.5 text-xs text-[var(--console-text)] hover:bg-[var(--console-surface-muted)]`,children:`Cancel`}),(0,f.jsx)(`button`,{type:`button`,disabled:!l||!p||l>p,onClick:()=>{a(l,p),n(!1)},className:`rounded-sm border border-[var(--console-accent)] bg-[var(--console-accent)] px-3 py-1.5 text-xs text-[var(--console-accent-fg)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40`,children:`Apply range`})]})]})]})}export{O as A,E as C,te as D,ne as E,h as F,m as I,k as M,F as N,b as O,P,ee as S,ae as T,U as _,Ue as a,R as b,Re as c,Le as d,Fe as f,W as g,he as h,qe as i,C as j,D as k,Ve as l,Me as m,Ye as n,We as o,Ne as p,Je as r,He as s,Xe as t,Ie as u,B as v,T as w,L as x,z as y};
|