noteconnection 1.8.0 → 1.9.0
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 +257 -1803
- package/dist/src/agent_workspace.contract.parity.test.js +105 -421
- package/dist/src/agent_workspace.frontend.test.js +410 -11
- package/dist/src/android.knowledgebase.picker.contract.test.js +102 -0
- package/dist/src/appimage.patchelf.test.js +113 -0
- package/dist/src/appimage.portability.test.js +156 -0
- package/dist/src/backend/FileLoader.js +18 -4
- package/dist/src/backend/FileLoader.test.js +125 -0
- package/dist/src/backend/GraphBuilder.identity.test.js +86 -0
- package/dist/src/backend/GraphBuilder.js +66 -18
- package/dist/src/backend/GraphBuilder.matching.test.js +127 -0
- package/dist/src/backend/GraphMetrics.js +0 -3
- package/dist/src/backend/ResourceIdentity.js +155 -0
- package/dist/src/backend/ResourceIdentity.test.js +113 -0
- package/dist/src/backend/algorithms/CycleDetection.js +0 -1
- package/dist/src/backend/algorithms/HybridEngine.js +0 -3
- package/dist/src/backend/algorithms/LayoutEngine.js +0 -1
- package/dist/src/backend/algorithms/StatisticalAnalyzer.js +0 -4
- package/dist/src/backend/algorithms/TopologicalSort.js +0 -2
- package/dist/src/backend/build_dag.js +0 -1
- package/dist/src/capacitor.bridge.serialization.contract.test.js +3 -0
- package/dist/src/capacitor.runtime.contract.test.js +11 -2
- package/dist/src/core/Graph.js +138 -42
- package/dist/src/core/Graph.test.js +74 -0
- package/dist/src/core/NoteConnection.js +2 -2
- package/dist/src/core/PathBridge.js +265 -2
- package/dist/src/core/ResourceReference.js +17 -0
- package/dist/src/desktop.godot.pack.test.js +142 -0
- package/dist/src/desktop.runtime.graph.test.js +66 -0
- package/dist/src/export/WorkspaceExportBundle.js +44 -0
- package/dist/src/export/WorkspaceExportBundle.test.js +61 -0
- package/dist/src/foundation.release.evidence.contract.test.js +127 -9
- package/dist/src/foundation.sqlite.runtime.contract.test.js +6 -0
- package/dist/src/frontend/README.md +257 -1803
- package/dist/src/frontend/agent_workspace.js +665 -7
- package/dist/src/frontend/index.html +31 -2
- package/dist/src/frontend/knowledge_projection_contract.js +230 -0
- package/dist/src/frontend/knowledge_projection_store.js +214 -0
- package/dist/src/frontend/libs/path_core.js +158 -42
- package/dist/src/frontend/locales/en.json +32 -0
- package/dist/src/frontend/locales/zh.json +32 -0
- package/dist/src/frontend/mobile_budget_runtime.js +33 -0
- package/dist/src/frontend/mobile_exact_analyzer.js +393 -0
- package/dist/src/frontend/mobile_identity_contract.js +221 -0
- package/dist/src/frontend/mobile_semantic_comparator.js +264 -0
- package/dist/src/frontend/path.html +6 -2
- package/dist/src/frontend/simulationWorker.js +1 -1
- package/dist/src/frontend/source_manager.js +110 -4
- package/dist/src/frontend/storage_provider.js +661 -71
- package/dist/src/frontend/styles.css +107 -13
- package/dist/src/frontend/workspace_panes.js +111 -7
- package/dist/src/frontend.runtime.assets.contract.test.js +81 -0
- package/dist/src/graph.answer.operator.contract.test.js +72 -0
- package/dist/src/index.js +6 -2
- package/dist/src/index.knowledge-root.test.js +118 -0
- package/dist/src/indexing/IndexLifecycle.js +22 -0
- package/dist/src/indexing/IndexLifecycle.test.js +24 -0
- package/dist/src/knowledge.api.contract.test.js +4 -2
- package/dist/src/knowledge_projection.contract.test.js +134 -0
- package/dist/src/knowledge_projection_store.test.js +200 -0
- package/dist/src/learning/AnswerQualityEvaluation.js +153 -0
- package/dist/src/learning/AnswerQualityEvaluation.test.js +118 -0
- package/dist/src/learning/KnowledgeLearningPlatform.js +4687 -3892
- package/dist/src/learning/KnowledgeLearningPlatform.persistence.test.js +418 -0
- package/dist/src/learning/KnowledgeLearningPlatform.test.js +243 -6
- package/dist/src/learning/KnowledgeWorkspaceConversationRegression.js +25 -1
- package/dist/src/learning/KnowledgeWorkspaceConversationRegression.test.js +13 -5
- package/dist/src/learning/MeasurementEvidenceConflicts.test.js +78 -0
- package/dist/src/learning/PublicAnswerContract.test.js +85 -0
- package/dist/src/learning/PublicEvidenceSelection.test.js +94 -0
- package/dist/src/learning/PublicMeasurementDisclosure.test.js +54 -0
- package/dist/src/learning/agentConversationExecution.js +211 -0
- package/dist/src/learning/agentConversationExecution.test.js +209 -0
- package/dist/src/learning/agentConversationSerialization.js +266 -0
- package/dist/src/learning/agentConversationSerialization.test.js +165 -0
- package/dist/src/learning/agentResponseBudget.js +179 -0
- package/dist/src/learning/agentResponseBudget.test.js +97 -0
- package/dist/src/learning/agentWorkspaceCapabilityContracts.js +65 -0
- package/dist/src/learning/answerReleaseReview.js +1191 -250
- package/dist/src/learning/answerReleaseReview.test.js +1293 -7
- package/dist/src/learning/answerTaskPlan.js +473 -0
- package/dist/src/learning/conversationComposer.js +627 -386
- package/dist/src/learning/conversationComposer.test.js +1403 -0
- package/dist/src/learning/evidenceContextAssembler.js +312 -120
- package/dist/src/learning/graphAnswerCoverage.js +37 -0
- package/dist/src/learning/graphAnswerCoverage.test.js +93 -0
- package/dist/src/learning/graphAnswerCoverageCalibration.js +59 -0
- package/dist/src/learning/graphAnswerCoverageCalibration.test.js +46 -0
- package/dist/src/learning/graphAnswerFacts.js +94 -0
- package/dist/src/learning/graphAnswerFacts.test.js +39 -0
- package/dist/src/learning/graphAnswerPlan.js +908 -0
- package/dist/src/learning/graphAnswerPlan.test.js +907 -0
- package/dist/src/learning/graphAnswerQualityCalibration.js +255 -0
- package/dist/src/learning/graphAnswerQualityCalibration.test.js +72 -0
- package/dist/src/learning/graphAnswerQualityPolicy.js +30 -0
- package/dist/src/learning/graphClaimMatcher.js +104 -0
- package/dist/src/learning/graphConditionedContext.js +109 -0
- package/dist/src/learning/graphConditionedContext.test.js +99 -0
- package/dist/src/learning/graphContextAssembler.js +3 -13
- package/dist/src/learning/graphContextAssembler.test.js +2 -2
- package/dist/src/learning/graphExpansionPolicy.js +22 -0
- package/dist/src/learning/graphExpansionPolicy.test.js +33 -0
- package/dist/src/learning/identityMetadata.test.js +26 -0
- package/dist/src/learning/index.js +1 -0
- package/dist/src/learning/mobileAnswerProjection.js +104 -0
- package/dist/src/learning/mobileAnswerProjection.test.js +102 -0
- package/dist/src/learning/queryBackend.js +34 -10
- package/dist/src/learning/queryBackend.test.js +21 -0
- package/dist/src/learning/ragContextPack.js +115 -16
- package/dist/src/learning/ragContextPack.test.js +151 -0
- package/dist/src/learning/ragEvidenceQuality.js +96 -0
- package/dist/src/learning/ragEvidenceQuality.test.js +29 -0
- package/dist/src/learning/ragPublicText.js +67 -4
- package/dist/src/learning/ragPublicText.test.js +57 -0
- package/dist/src/learning/ragSufficiencyJudge.js +11 -1
- package/dist/src/learning/ragSufficiencyProviderJudge.js +16 -26
- package/dist/src/learning/ragSufficiencyProviderJudge.test.js +51 -0
- package/dist/src/learning/requestNormalization.js +106 -0
- package/dist/src/learning/requestNormalization.test.js +101 -0
- package/dist/src/learning/store.js +116 -12
- package/dist/src/learning/store.test.js +299 -0
- package/dist/src/learning/vectorAccelerationAdapter.js +22 -6
- package/dist/src/learning/vectorAccelerationAdapter.test.js +30 -0
- package/dist/src/learning/workspaceHydration.js +168 -0
- package/dist/src/learning/workspaceHydration.test.js +30 -0
- package/dist/src/license.policy.contract.test.js +9 -4
- package/dist/src/markdown/MarkdownGateway.js +4 -0
- package/dist/src/markdown/MarkdownGateway.test.js +59 -0
- package/dist/src/middleware/SseResponseWriter.js +122 -0
- package/dist/src/middleware/SseResponseWriter.test.js +54 -0
- package/dist/src/middleware/auth.js +28 -7
- package/dist/src/middleware/auth.test.js +33 -0
- package/dist/src/middleware/index.js +2 -1
- package/dist/src/mobile.android.evidence.contract.test.js +146 -0
- package/dist/src/mobile.android.signing.contract.test.js +66 -0
- package/dist/src/mobile.artifact.contract.test.js +144 -0
- package/dist/src/mobile.budget.contract.test.js +90 -0
- package/dist/src/mobile.canonical-id.readiness.test.js +54 -0
- package/dist/src/mobile.graph.parity.contract.test.js +207 -0
- package/dist/src/mobile.identity.contract.test.js +66 -0
- package/dist/src/mobile.identity.corpus.manifest.test.js +72 -0
- package/dist/src/mobile.identity.corpus.test.js +40 -0
- package/dist/src/mobile.native.recovery.contract.test.js +64 -0
- package/dist/src/mobile.pipeline.test.js +11 -1
- package/dist/src/mobile.profile.contract.test.js +225 -0
- package/dist/src/mobile.semantic.parity.test.js +92 -0
- package/dist/src/mobile_exact_analyzer.test.js +113 -0
- package/dist/src/notemd/ContentGenerator.js +4 -9
- package/dist/src/notemd/FileProcessor.js +4 -9
- package/dist/src/notemd/NotemdService.js +12 -17
- package/dist/src/notemd/Translator.js +4 -9
- package/dist/src/notemd/progressReporter.js +9 -0
- package/dist/src/notemd.server.integration.test.js +119 -4
- package/dist/src/notemd.workflow.pipeline.test.js +1 -1
- package/dist/src/pathbridge.handshake.contract.test.js +29 -0
- package/dist/src/pathbridge.host-adapter.contract.test.js +133 -0
- package/dist/src/pathcore.bundle.contract.test.js +8 -0
- package/dist/src/platform/ExportProfile.js +28 -0
- package/dist/src/platform/MobileBudget.js +11 -0
- package/dist/src/platform/PlatformCapabilities.js +14 -0
- package/dist/src/platform/PlatformCapabilities.test.js +6 -0
- package/dist/src/query_backend.external_http.integration.test.js +2 -2
- package/dist/src/release.godot.mirror.contract.test.js +28 -4
- package/dist/src/resources/ResourceRegistry.js +40 -0
- package/dist/src/resources/ResourceRegistry.test.js +36 -0
- package/dist/src/routes/index.js +0 -4
- package/dist/src/routes/knowledge.js +46 -33
- package/dist/src/routes/knowledgePayload.js +185 -0
- package/dist/src/routes/knowledgePayload.test.js +53 -0
- package/dist/src/routes/markdown.js +8 -0
- package/dist/src/routes/notemd.js +990 -234
- package/dist/src/routes/registry.contract.test.js +5 -2
- package/dist/src/routes/registry.shadow.contract.test.js +22 -0
- package/dist/src/routes/render.js +14 -51
- package/dist/src/runtime.capabilities.test.js +18 -2
- package/dist/src/server.js +566 -1090
- package/dist/src/server.migration.test.js +417 -15
- package/dist/src/sidecar.build.lock.contract.test.js +201 -0
- package/dist/src/sidecar.freshness.contract.test.js +184 -0
- package/dist/src/sidecar.replacement.boundary.contract.test.js +6 -3
- package/dist/src/sidecar.supply.readiness.contract.test.js +11 -0
- package/dist/src/simulation.worker.offline.test.js +104 -0
- package/dist/src/storage.provider.capacitor.content.contract.test.js +4 -1
- package/dist/src/storage.provider.contract.test.js +152 -1
- package/dist/src/tauri.frontend.build.contract.test.js +8 -0
- package/dist/src/tauri.window.evidence.execution.test.js +68 -0
- package/dist/src/utils/RuntimePaths.js +6 -0
- package/dist/src/utils/RuntimePaths.test.js +27 -0
- package/dist/src/windows.installer.build.test.js +109 -0
- package/dist/src/windows.installer.payload.test.js +76 -0
- package/dist/src/windows.installer.runtime.test.js +69 -0
- package/dist/src/workspace/WorkspaceRegistry.js +13 -0
- package/package.json +32 -10
- package/dist/src/routes/data.js +0 -267
- package/dist/src/routes/diagnostics.js +0 -51
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AgentConversationSerializationError = void 0;
|
|
4
|
+
exports.measureJsonBytes = measureJsonBytes;
|
|
5
|
+
exports.serializeAgentConversationResponse = serializeAgentConversationResponse;
|
|
6
|
+
exports.serializeAgentConversationHttpResponse = serializeAgentConversationHttpResponse;
|
|
7
|
+
exports.serializeAgentConversationTurnEvent = serializeAgentConversationTurnEvent;
|
|
8
|
+
const mobileAnswerProjection_1 = require("./mobileAnswerProjection");
|
|
9
|
+
const TRUNCATION_REASON = 'runtime_serialized_bytes_limit';
|
|
10
|
+
// Covers a completed event, its validated 160-byte turn ID, timestamp and SSE framing.
|
|
11
|
+
// Every transport reserves the same space to release the same answer.
|
|
12
|
+
const TURN_WIRE_RESERVE_BYTES = 288;
|
|
13
|
+
const DEFAULT_WIRE_LIMIT = 8 * 1024 * 1024;
|
|
14
|
+
const MAX_RELEASE_CITATIONS = 64;
|
|
15
|
+
const MAX_RELEASE_CLAIMS = 128;
|
|
16
|
+
class AgentConversationSerializationError extends Error {
|
|
17
|
+
constructor() {
|
|
18
|
+
super(TRUNCATION_REASON);
|
|
19
|
+
this.code = TRUNCATION_REASON;
|
|
20
|
+
this.statusCode = 413;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.AgentConversationSerializationError = AgentConversationSerializationError;
|
|
24
|
+
/** Exact for JSON data; stops before allocating a serialized copy of an oversized response. */
|
|
25
|
+
function measureJsonBytes(value, limit) {
|
|
26
|
+
let bytes = 0;
|
|
27
|
+
const ancestors = new Set();
|
|
28
|
+
const stringBytes = (text) => {
|
|
29
|
+
bytes += 2;
|
|
30
|
+
for (let i = 0; i < text.length && bytes <= limit; i++) {
|
|
31
|
+
const code = text.charCodeAt(i);
|
|
32
|
+
if (code === 34 || code === 92 || code === 8 || code === 9 || code === 10 || code === 12 || code === 13)
|
|
33
|
+
bytes += 2;
|
|
34
|
+
else if (code < 32)
|
|
35
|
+
bytes += 6;
|
|
36
|
+
else if (code < 128)
|
|
37
|
+
bytes++;
|
|
38
|
+
else if (code < 2048)
|
|
39
|
+
bytes += 2;
|
|
40
|
+
else if (code >= 0xd800 && code <= 0xdbff) {
|
|
41
|
+
const next = text.charCodeAt(i + 1);
|
|
42
|
+
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
43
|
+
bytes += 4;
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
else
|
|
47
|
+
bytes += 6;
|
|
48
|
+
}
|
|
49
|
+
else if (code >= 0xdc00 && code <= 0xdfff)
|
|
50
|
+
bytes += 6;
|
|
51
|
+
else
|
|
52
|
+
bytes += 3;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const visit = (item, depth) => {
|
|
56
|
+
if (bytes > limit)
|
|
57
|
+
return;
|
|
58
|
+
if (item === null || item === undefined || typeof item === 'function' || typeof item === 'symbol') {
|
|
59
|
+
bytes += 4;
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (typeof item === 'string') {
|
|
63
|
+
stringBytes(item);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (typeof item === 'boolean') {
|
|
67
|
+
bytes += item ? 4 : 5;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (typeof item === 'number') {
|
|
71
|
+
bytes += Number.isFinite(item) ? String(item).length : 4;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (typeof item !== 'object')
|
|
75
|
+
throw new TypeError('Conversation responses must contain JSON data');
|
|
76
|
+
if (ancestors.has(item) || depth > 64)
|
|
77
|
+
throw new TypeError('Cyclic or excessively nested conversation response');
|
|
78
|
+
if (typeof item.toJSON === 'function')
|
|
79
|
+
throw new TypeError('Conversation responses must contain plain JSON data');
|
|
80
|
+
ancestors.add(item);
|
|
81
|
+
bytes += 2;
|
|
82
|
+
if (Array.isArray(item)) {
|
|
83
|
+
for (let i = 0; i < item.length && bytes <= limit; i++) {
|
|
84
|
+
if (i)
|
|
85
|
+
bytes++;
|
|
86
|
+
visit(item[i], depth + 1);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
let first = true;
|
|
91
|
+
for (const key in item) {
|
|
92
|
+
if (bytes > limit)
|
|
93
|
+
break;
|
|
94
|
+
if (!Object.prototype.hasOwnProperty.call(item, key))
|
|
95
|
+
continue;
|
|
96
|
+
const child = item[key];
|
|
97
|
+
if (child === undefined || typeof child === 'function' || typeof child === 'symbol')
|
|
98
|
+
continue;
|
|
99
|
+
if (!first)
|
|
100
|
+
bytes++;
|
|
101
|
+
first = false;
|
|
102
|
+
stringBytes(key);
|
|
103
|
+
bytes++;
|
|
104
|
+
visit(child, depth + 1);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
ancestors.delete(item);
|
|
108
|
+
};
|
|
109
|
+
visit(value, 0);
|
|
110
|
+
return bytes;
|
|
111
|
+
}
|
|
112
|
+
function wireLimit(result) {
|
|
113
|
+
const requested = Number(result.responseBudget?.runtimeGovernor.maxSerializedBytes);
|
|
114
|
+
return Number.isFinite(requested) && requested > 0 ? Math.floor(requested) : DEFAULT_WIRE_LIMIT;
|
|
115
|
+
}
|
|
116
|
+
function countUnescaped(value, token) {
|
|
117
|
+
const escapedToken = token.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
|
|
118
|
+
return (value.match(new RegExp(`(?<!\\\\)${escapedToken}`, 'gu')) || []).length;
|
|
119
|
+
}
|
|
120
|
+
function clipBalancedMarkdown(source, maxChars) {
|
|
121
|
+
if (source.length <= maxChars)
|
|
122
|
+
return source;
|
|
123
|
+
const marker = '\n\n[Response truncated by runtime safety governor.]';
|
|
124
|
+
if (maxChars < marker.length)
|
|
125
|
+
return '';
|
|
126
|
+
let clipped = source.slice(0, maxChars - marker.length).trimEnd();
|
|
127
|
+
// Keep whole claims when possible, and never leave an unterminated code/math block.
|
|
128
|
+
const boundary = Math.max(clipped.lastIndexOf('\n\n'), clipped.lastIndexOf('. '), clipped.lastIndexOf('。'));
|
|
129
|
+
if (boundary >= clipped.length / 2)
|
|
130
|
+
clipped = clipped.slice(0, boundary + (clipped[boundary] === '\n' ? 0 : 1)).trimEnd();
|
|
131
|
+
const fences = [...clipped.matchAll(/^\s*(`{3,}|~{3,}).*$/gm)];
|
|
132
|
+
let openFence;
|
|
133
|
+
for (const fence of fences) {
|
|
134
|
+
if (!openFence)
|
|
135
|
+
openFence = { marker: fence[1], index: fence.index };
|
|
136
|
+
else if (fence[1][0] === openFence.marker[0] && fence[1].length >= openFence.marker.length)
|
|
137
|
+
openFence = undefined;
|
|
138
|
+
}
|
|
139
|
+
if (openFence)
|
|
140
|
+
clipped = clipped.slice(0, openFence.index).trimEnd();
|
|
141
|
+
if (countUnescaped(clipped, '$$') % 2)
|
|
142
|
+
clipped = clipped.slice(0, clipped.lastIndexOf('$$')).trimEnd();
|
|
143
|
+
if (countUnescaped(clipped.replace(/(?<!\\)\$\$/gu, ''), '$') % 2)
|
|
144
|
+
clipped = clipped.slice(0, clipped.lastIndexOf('$')).trimEnd();
|
|
145
|
+
if (countUnescaped(clipped.replace(/^\s*`{3,}.*$/gm, ''), '`') % 2)
|
|
146
|
+
clipped = clipped.slice(0, clipped.lastIndexOf('`')).trimEnd();
|
|
147
|
+
if (clipped.lastIndexOf('[') > clipped.lastIndexOf(']'))
|
|
148
|
+
clipped = clipped.slice(0, clipped.lastIndexOf('[')).trimEnd();
|
|
149
|
+
if (/[\ud800-\udbff]$/.test(clipped))
|
|
150
|
+
clipped = clipped.slice(0, -1);
|
|
151
|
+
return `${clipped}${marker}`.trim();
|
|
152
|
+
}
|
|
153
|
+
function compactResponse(result, answerMaxChars) {
|
|
154
|
+
const sourceCitations = result.citations || [];
|
|
155
|
+
const sourceClaims = result.trace?.answerClaimCitations || [];
|
|
156
|
+
let answer = clipBalancedMarkdown(result.answer || '', answerMaxChars);
|
|
157
|
+
// Oversized metadata must not leave a retained claim with a dangling citation.
|
|
158
|
+
const boundedEvidence = sourceCitations.length <= MAX_RELEASE_CITATIONS && sourceClaims.length <= MAX_RELEASE_CLAIMS;
|
|
159
|
+
const citations = boundedEvidence ? sourceCitations.map(citation => ({
|
|
160
|
+
citationId: citation.citationId, atomId: citation.atomId, documentId: citation.documentId,
|
|
161
|
+
sourcePath: citation.sourcePath, title: citation.title,
|
|
162
|
+
snippet: citation.snippet.length > 1024 ? `${citation.snippet.slice(0, 1021)}...` : citation.snippet,
|
|
163
|
+
startOffset: citation.startOffset, endOffset: citation.endOffset, startLine: citation.startLine, endLine: citation.endLine,
|
|
164
|
+
score: citation.score,
|
|
165
|
+
})) : [];
|
|
166
|
+
const citationIds = new Set(citations.map(citation => citation.citationId));
|
|
167
|
+
const claims = boundedEvidence ? sourceClaims.filter(claim => answer.includes(claim.text)) : [];
|
|
168
|
+
const claimsSupported = claims.every(claim => claim.citationIds.length <= MAX_RELEASE_CITATIONS
|
|
169
|
+
&& claim.citationIds.every(id => citationIds.has(id)));
|
|
170
|
+
if (!boundedEvidence || !claimsSupported) {
|
|
171
|
+
answer = clipBalancedMarkdown('[Response truncated by runtime safety governor. Narrow the request to retain its evidence.]', answerMaxChars);
|
|
172
|
+
citations.length = 0;
|
|
173
|
+
claims.length = 0;
|
|
174
|
+
}
|
|
175
|
+
const compact = {
|
|
176
|
+
userId: result.userId,
|
|
177
|
+
sessionId: result.sessionId,
|
|
178
|
+
assistantMessage: answer,
|
|
179
|
+
answer,
|
|
180
|
+
responseMode: result.responseMode,
|
|
181
|
+
...(result.responseProfile ? { responseProfile: result.responseProfile } : {}),
|
|
182
|
+
...(result.responseBudget ? { responseBudget: result.responseBudget } : {}),
|
|
183
|
+
assistantBlocks: [], knowledgePoints: [], citations, recalledMemories: [], memoryActions: [],
|
|
184
|
+
summary: {
|
|
185
|
+
generatedAt: result.summary.generatedAt,
|
|
186
|
+
topK: result.summary.topK,
|
|
187
|
+
returnedKnowledgePoints: 0,
|
|
188
|
+
returnedCitations: citations.length,
|
|
189
|
+
recalledMemoryCount: 0,
|
|
190
|
+
appliedMemoryCount: 0,
|
|
191
|
+
queryEvidenceCoverageRatioPct: citations.length ? result.summary.queryEvidenceCoverageRatioPct : 0,
|
|
192
|
+
responseTruncated: true,
|
|
193
|
+
responseTruncationReason: TRUNCATION_REASON,
|
|
194
|
+
},
|
|
195
|
+
trace: {
|
|
196
|
+
sessionId: result.sessionId,
|
|
197
|
+
invocationId: result.trace?.invocationId || '',
|
|
198
|
+
retrieval: {},
|
|
199
|
+
recalledMemoryCount: 0,
|
|
200
|
+
appliedMemoryCount: 0,
|
|
201
|
+
usedScope: {
|
|
202
|
+
source: result.trace?.usedScope?.source || 'global',
|
|
203
|
+
workspaceId: result.trace?.usedScope?.workspaceId || null,
|
|
204
|
+
corpusId: result.trace?.usedScope?.corpusId || null,
|
|
205
|
+
documentIds: [], atomIds: [], sourcePathPrefixes: [], languages: [],
|
|
206
|
+
matchedAtomCount: result.trace?.usedScope?.matchedAtomCount || 0,
|
|
207
|
+
},
|
|
208
|
+
...(claims.length ? { answerClaimCitations: claims } : {}),
|
|
209
|
+
responseTruncated: true,
|
|
210
|
+
responseTruncationReason: TRUNCATION_REASON,
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
if (result.responseProfile === 'mobile_compact')
|
|
214
|
+
compact.mobileProjection = (0, mobileAnswerProjection_1.projectAnswerForMobile)(compact);
|
|
215
|
+
return compact;
|
|
216
|
+
}
|
|
217
|
+
function releaseWithinBudget(result, maxBytes) {
|
|
218
|
+
if (measureJsonBytes(result, maxBytes) <= maxBytes) {
|
|
219
|
+
const truncated = result.summary.responseTruncationReason === TRUNCATION_REASON;
|
|
220
|
+
return { json: JSON.stringify(result), result, truncated, ...(truncated ? { reason: TRUNCATION_REASON } : {}) };
|
|
221
|
+
}
|
|
222
|
+
let lower = 0;
|
|
223
|
+
let upper = Math.min(32000, result.answer.length, result.responseBudget?.runtimeGovernor.maxReportChars || 32000);
|
|
224
|
+
let best = compactResponse(result, 0);
|
|
225
|
+
if (measureJsonBytes(best, maxBytes) > maxBytes) {
|
|
226
|
+
// If citations cannot fit, release no scientific claims and no obsolete coverage.
|
|
227
|
+
best = compactResponse({ ...result, citations: [], answer: '', trace: { ...result.trace, answerClaimCitations: [] } }, 0);
|
|
228
|
+
delete best.responseBudget;
|
|
229
|
+
if (measureJsonBytes(best, maxBytes) > maxBytes)
|
|
230
|
+
throw new AgentConversationSerializationError();
|
|
231
|
+
return { json: JSON.stringify(best), result: best, truncated: true, reason: TRUNCATION_REASON };
|
|
232
|
+
}
|
|
233
|
+
while (lower <= upper) {
|
|
234
|
+
const chars = Math.floor((lower + upper) / 2);
|
|
235
|
+
const candidate = compactResponse(result, chars);
|
|
236
|
+
if (measureJsonBytes(candidate, maxBytes) <= maxBytes) {
|
|
237
|
+
best = candidate;
|
|
238
|
+
lower = chars + 1;
|
|
239
|
+
}
|
|
240
|
+
else
|
|
241
|
+
upper = chars - 1;
|
|
242
|
+
}
|
|
243
|
+
return { json: JSON.stringify(best), result: best, truncated: true, reason: TRUNCATION_REASON };
|
|
244
|
+
}
|
|
245
|
+
function serializeAgentConversationResponse(result) {
|
|
246
|
+
return releaseWithinBudget(result, wireLimit(result) - TURN_WIRE_RESERVE_BYTES);
|
|
247
|
+
}
|
|
248
|
+
function serializeAgentConversationHttpResponse(result) {
|
|
249
|
+
const serialized = serializeAgentConversationResponse(result);
|
|
250
|
+
return { ...serialized, json: `{"success":true,"result":${serialized.json}}` };
|
|
251
|
+
}
|
|
252
|
+
function serializeAgentConversationTurnEvent(eventType, payload) {
|
|
253
|
+
if (eventType === 'turn_completed' && payload && typeof payload === 'object' && 'result' in payload && payload.result) {
|
|
254
|
+
const event = payload;
|
|
255
|
+
const limit = wireLimit(event.result);
|
|
256
|
+
const envelope = { ...event, result: null };
|
|
257
|
+
const framingBytes = Buffer.byteLength(`event: ${eventType}\ndata: \n\n`);
|
|
258
|
+
const envelopeBytes = measureJsonBytes(envelope, limit) - 4 + framingBytes;
|
|
259
|
+
const serialized = releaseWithinBudget(event.result, limit - Math.max(TURN_WIRE_RESERVE_BYTES, envelopeBytes));
|
|
260
|
+
return { json: JSON.stringify({ ...event, result: serialized.result }), truncated: serialized.truncated };
|
|
261
|
+
}
|
|
262
|
+
const payloadLimit = DEFAULT_WIRE_LIMIT - Buffer.byteLength(`event: ${eventType}\ndata: \n\n`);
|
|
263
|
+
if (measureJsonBytes(payload, payloadLimit) > payloadLimit)
|
|
264
|
+
throw new AgentConversationSerializationError();
|
|
265
|
+
return { json: JSON.stringify(payload), truncated: false };
|
|
266
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const agentConversationSerialization_1 = require("./agentConversationSerialization");
|
|
4
|
+
function makeResponse(overrides = {}) {
|
|
5
|
+
const answer = overrides.answer || 'A bounded answer.';
|
|
6
|
+
return {
|
|
7
|
+
userId: 'serialization-user',
|
|
8
|
+
sessionId: 'serialization-session',
|
|
9
|
+
assistantMessage: answer,
|
|
10
|
+
answer,
|
|
11
|
+
responseMode: 'full',
|
|
12
|
+
responseBudget: {
|
|
13
|
+
mode: 'unbounded',
|
|
14
|
+
tier: 'unbounded',
|
|
15
|
+
productCapDisabled: true,
|
|
16
|
+
rag: {
|
|
17
|
+
maxFragments: 4096,
|
|
18
|
+
maxCharsPerFragment: 16000,
|
|
19
|
+
maxTotalChars: 320000,
|
|
20
|
+
productCapDisabled: true,
|
|
21
|
+
runtimeMaxFragments: 4096,
|
|
22
|
+
runtimeMaxCharsPerFragment: 16000,
|
|
23
|
+
runtimeMaxTotalChars: 64 * 1024 * 1024,
|
|
24
|
+
},
|
|
25
|
+
runtimeGovernor: {
|
|
26
|
+
timeoutMs: 180000,
|
|
27
|
+
maxSerializedBytes: 1200,
|
|
28
|
+
maxFragmentsProcessed: 4096,
|
|
29
|
+
maxReportChars: 320000,
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
knowledgePoints: [],
|
|
33
|
+
citations: [],
|
|
34
|
+
recalledMemories: [],
|
|
35
|
+
memoryActions: [],
|
|
36
|
+
summary: {
|
|
37
|
+
generatedAt: '2026-09-03T00:00:00.000Z',
|
|
38
|
+
topK: 6,
|
|
39
|
+
returnedKnowledgePoints: 0,
|
|
40
|
+
returnedCitations: 0,
|
|
41
|
+
recalledMemoryCount: 0,
|
|
42
|
+
appliedMemoryCount: 0,
|
|
43
|
+
queryEvidenceCoverageRatioPct: 100,
|
|
44
|
+
},
|
|
45
|
+
trace: {
|
|
46
|
+
sessionId: 'serialization-session',
|
|
47
|
+
invocationId: 'serialization-invocation',
|
|
48
|
+
retrieval: {},
|
|
49
|
+
recalledMemoryCount: 0,
|
|
50
|
+
appliedMemoryCount: 0,
|
|
51
|
+
usedScope: {
|
|
52
|
+
source: 'global',
|
|
53
|
+
workspaceId: null,
|
|
54
|
+
corpusId: null,
|
|
55
|
+
documentIds: [],
|
|
56
|
+
atomIds: [],
|
|
57
|
+
sourcePathPrefixes: [],
|
|
58
|
+
languages: [],
|
|
59
|
+
matchedAtomCount: 0,
|
|
60
|
+
},
|
|
61
|
+
responseBudget: undefined,
|
|
62
|
+
},
|
|
63
|
+
...overrides,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
describe('agent conversation serialization governor', () => {
|
|
67
|
+
test.each(['知识🧠', 'quotes " \\ \n\t', '\ud800', '\u0000', { nested: [null, undefined, 1, false] }])('measures JSON escaping and UTF-8 before allocation: %p', value => {
|
|
68
|
+
const bytes = Buffer.byteLength(JSON.stringify(value));
|
|
69
|
+
expect((0, agentConversationSerialization_1.measureJsonBytes)(value, bytes)).toBe(bytes);
|
|
70
|
+
expect((0, agentConversationSerialization_1.measureJsonBytes)(value, bytes - 1)).toBeGreaterThan(bytes - 1);
|
|
71
|
+
});
|
|
72
|
+
test('the response fits but the full SSE envelope does not', () => {
|
|
73
|
+
const response = makeResponse();
|
|
74
|
+
response.responseBudget.runtimeGovernor.maxSerializedBytes = 2000;
|
|
75
|
+
response.answer += 'x'.repeat(Math.max(0, 1998 - Buffer.byteLength(JSON.stringify(response))));
|
|
76
|
+
expect(Buffer.byteLength(JSON.stringify(response))).toBe(1998);
|
|
77
|
+
const event = (0, agentConversationSerialization_1.serializeAgentConversationTurnEvent)('turn_completed', {
|
|
78
|
+
type: 'turn_completed', turnId: 'turn_envelope', emittedAt: '2026-09-12T00:00:00.000Z', result: response,
|
|
79
|
+
});
|
|
80
|
+
expect(Buffer.byteLength(`event: turn_completed\ndata: ${event.json}\n\n`)).toBeLessThanOrEqual(2000);
|
|
81
|
+
expect(event.truncated).toBe(true);
|
|
82
|
+
expect(JSON.parse(event.json).result.summary.responseTruncated).toBe(true);
|
|
83
|
+
});
|
|
84
|
+
test('one released projection is reused for JSON, SSE and replay with surviving citations', () => {
|
|
85
|
+
const response = makeResponse({ answer: 'A supported claim. '.repeat(800), assistantMessage: 'A supported claim. '.repeat(800) });
|
|
86
|
+
response.responseBudget.runtimeGovernor.maxSerializedBytes = 4000;
|
|
87
|
+
response.citations = [{ citationId: 'cite-1', atomId: 'atom-1', documentId: 'doc-1', sourcePath: 'source.md', title: 'Source', snippet: 'A supported claim.', score: 1 }];
|
|
88
|
+
response.summary.returnedCitations = 99;
|
|
89
|
+
response.trace.answerClaimCitations = [{ claimId: 'claim-1', text: 'A supported claim.', citationIds: ['cite-1'], fragmentIds: ['fragment-1'], sourcePaths: ['source.md'], supportStatus: 'supported' }];
|
|
90
|
+
const http = (0, agentConversationSerialization_1.serializeAgentConversationHttpResponse)(response);
|
|
91
|
+
const event = { type: 'turn_completed', turnId: 'turn_citations', emittedAt: '2026-09-12T00:00:00.000Z', result: response };
|
|
92
|
+
const live = (0, agentConversationSerialization_1.serializeAgentConversationTurnEvent)('turn_completed', event);
|
|
93
|
+
const replay = (0, agentConversationSerialization_1.serializeAgentConversationTurnEvent)('turn_completed', { ...event, result: http.result });
|
|
94
|
+
expect(JSON.parse(live.json).result).toEqual(http.result);
|
|
95
|
+
expect(JSON.parse(replay.json).result).toEqual(http.result);
|
|
96
|
+
expect(http.result.answer).toContain('A supported claim.');
|
|
97
|
+
expect(http.result.citations.map(citation => citation.citationId)).toEqual(['cite-1']);
|
|
98
|
+
expect(http.result.summary.returnedCitations).toBe(http.result.citations.length);
|
|
99
|
+
expect(http.result.summary.returnedKnowledgePoints).toBe(http.result.knowledgePoints.length);
|
|
100
|
+
});
|
|
101
|
+
test('does not initially stringify oversized diagnostic collections', () => {
|
|
102
|
+
const response = makeResponse();
|
|
103
|
+
response.trace.retrieval = { hugeDiagnostics: Array.from({ length: 10000 }, () => 'diagnostic'.repeat(50)) };
|
|
104
|
+
const stringify = jest.spyOn(JSON, 'stringify');
|
|
105
|
+
try {
|
|
106
|
+
const serialized = (0, agentConversationSerialization_1.serializeAgentConversationResponse)(response);
|
|
107
|
+
expect(stringify).not.toHaveBeenCalledWith(response);
|
|
108
|
+
expect(Buffer.byteLength(serialized.json)).toBeLessThanOrEqual(1200);
|
|
109
|
+
expect(serialized.result.summary.queryEvidenceCoverageRatioPct).toBe(0);
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
stringify.mockRestore();
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
test('rejects a ceiling too small for the required response contract', () => {
|
|
116
|
+
const response = makeResponse();
|
|
117
|
+
response.responseBudget.runtimeGovernor.maxSerializedBytes = 64;
|
|
118
|
+
expect(() => (0, agentConversationSerialization_1.serializeAgentConversationHttpResponse)(response)).toThrow('runtime_serialized_bytes_limit');
|
|
119
|
+
});
|
|
120
|
+
test('keeps responses unchanged while under the runtime byte limit', () => {
|
|
121
|
+
const response = makeResponse({
|
|
122
|
+
responseBudget: {
|
|
123
|
+
...makeResponse().responseBudget,
|
|
124
|
+
runtimeGovernor: {
|
|
125
|
+
...makeResponse().responseBudget.runtimeGovernor,
|
|
126
|
+
maxSerializedBytes: 100000,
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
const serialized = (0, agentConversationSerialization_1.serializeAgentConversationResponse)(response);
|
|
131
|
+
expect(serialized.truncated).toBe(false);
|
|
132
|
+
expect(JSON.parse(serialized.json).answer).toBe(response.answer);
|
|
133
|
+
});
|
|
134
|
+
test('compacts oversized unbounded responses and preserves balanced display math', () => {
|
|
135
|
+
const response = makeResponse({
|
|
136
|
+
answer: `## Report\n\n${'Long evidence. '.repeat(2000)}\n\n$$\\frac{a}{b}$$`,
|
|
137
|
+
assistantMessage: `## Report\n\n${'Long evidence. '.repeat(2000)}\n\n$$\\frac{a}{b}$$`,
|
|
138
|
+
});
|
|
139
|
+
const serialized = (0, agentConversationSerialization_1.serializeAgentConversationResponse)(response);
|
|
140
|
+
expect(serialized.truncated).toBe(true);
|
|
141
|
+
expect(Buffer.byteLength(serialized.json, 'utf8')).toBeLessThanOrEqual(1200);
|
|
142
|
+
expect(serialized.result.summary.responseTruncated).toBe(true);
|
|
143
|
+
expect(serialized.result.summary.responseTruncationReason).toBe('runtime_serialized_bytes_limit');
|
|
144
|
+
expect((serialized.result.answer.match(/(?<!\\)\$\$/gu) || []).length % 2).toBe(0);
|
|
145
|
+
});
|
|
146
|
+
test('applies the same governor to a completed SSE event', () => {
|
|
147
|
+
const response = makeResponse({ answer: 'Event payload '.repeat(2000) });
|
|
148
|
+
const serialized = (0, agentConversationSerialization_1.serializeAgentConversationTurnEvent)('turn_completed', {
|
|
149
|
+
type: 'turn_completed',
|
|
150
|
+
turnId: 'turn_serialization',
|
|
151
|
+
emittedAt: '2026-09-03T00:00:00.000Z',
|
|
152
|
+
result: response,
|
|
153
|
+
});
|
|
154
|
+
const event = JSON.parse(serialized.json);
|
|
155
|
+
expect(serialized.truncated).toBe(true);
|
|
156
|
+
expect(event.result.summary.responseTruncated).toBe(true);
|
|
157
|
+
});
|
|
158
|
+
test('serializes the HTTP success envelope within the runtime limit', () => {
|
|
159
|
+
const response = makeResponse({ answer: 'HTTP payload '.repeat(2000) });
|
|
160
|
+
const serialized = (0, agentConversationSerialization_1.serializeAgentConversationHttpResponse)(response);
|
|
161
|
+
expect(serialized.truncated).toBe(true);
|
|
162
|
+
expect(Buffer.byteLength(serialized.json, 'utf8')).toBeLessThanOrEqual(1200);
|
|
163
|
+
expect(JSON.parse(serialized.json).success).toBe(true);
|
|
164
|
+
});
|
|
165
|
+
});
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AGENT_RESPONSE_UNBOUNDED_RUNTIME_GOVERNOR = exports.AGENT_RESPONSE_BUDGET_TIERS = void 0;
|
|
4
|
+
exports.resolveAgentResponseBudget = resolveAgentResponseBudget;
|
|
5
|
+
exports.applyRuntimeGovernor = applyRuntimeGovernor;
|
|
6
|
+
exports.resolveHostedAgentResponseBudget = resolveHostedAgentResponseBudget;
|
|
7
|
+
const STANDARD_RUNTIME_GOVERNOR = Object.freeze({
|
|
8
|
+
timeoutMs: 60000,
|
|
9
|
+
maxSerializedBytes: 8 * 1024 * 1024,
|
|
10
|
+
maxFragmentsProcessed: 512,
|
|
11
|
+
maxReportChars: 48000,
|
|
12
|
+
});
|
|
13
|
+
const EXTENDED_RUNTIME_GOVERNOR = Object.freeze({
|
|
14
|
+
timeoutMs: 90000,
|
|
15
|
+
maxSerializedBytes: 16 * 1024 * 1024,
|
|
16
|
+
maxFragmentsProcessed: 1024,
|
|
17
|
+
maxReportChars: 80000,
|
|
18
|
+
});
|
|
19
|
+
const MAX_RUNTIME_GOVERNOR = Object.freeze({
|
|
20
|
+
timeoutMs: 120000,
|
|
21
|
+
maxSerializedBytes: 32 * 1024 * 1024,
|
|
22
|
+
maxFragmentsProcessed: 2048,
|
|
23
|
+
maxReportChars: 160000,
|
|
24
|
+
});
|
|
25
|
+
const UNBOUNDED_RUNTIME_GOVERNOR = Object.freeze({
|
|
26
|
+
timeoutMs: 180000,
|
|
27
|
+
maxSerializedBytes: 64 * 1024 * 1024,
|
|
28
|
+
maxFragmentsProcessed: 4096,
|
|
29
|
+
maxReportChars: 320000,
|
|
30
|
+
});
|
|
31
|
+
function createProductBudgetDefinition(maxFragments, maxCharsPerFragment, maxTotalChars, reportMaxChars, runtimeGovernor) {
|
|
32
|
+
return Object.freeze({
|
|
33
|
+
rag: Object.freeze({
|
|
34
|
+
maxFragments,
|
|
35
|
+
maxCharsPerFragment,
|
|
36
|
+
maxTotalChars,
|
|
37
|
+
productCapDisabled: false,
|
|
38
|
+
runtimeMaxFragments: runtimeGovernor.maxFragmentsProcessed,
|
|
39
|
+
runtimeMaxCharsPerFragment: maxCharsPerFragment,
|
|
40
|
+
runtimeMaxTotalChars: reportMaxChars,
|
|
41
|
+
}),
|
|
42
|
+
reportMaxChars,
|
|
43
|
+
runtimeGovernor,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
exports.AGENT_RESPONSE_BUDGET_TIERS = Object.freeze({
|
|
47
|
+
standard: createProductBudgetDefinition(120, 8000, 64000, 48000, STANDARD_RUNTIME_GOVERNOR),
|
|
48
|
+
extended: createProductBudgetDefinition(160, 12000, 128000, 80000, EXTENDED_RUNTIME_GOVERNOR),
|
|
49
|
+
max: createProductBudgetDefinition(256, 16000, 256000, 160000, MAX_RUNTIME_GOVERNOR),
|
|
50
|
+
});
|
|
51
|
+
exports.AGENT_RESPONSE_UNBOUNDED_RUNTIME_GOVERNOR = UNBOUNDED_RUNTIME_GOVERNOR;
|
|
52
|
+
function normalizedMemoryClass(value) {
|
|
53
|
+
const normalized = String(value || '').trim().toLowerCase();
|
|
54
|
+
return normalized === 'low' || normalized === 'standard' || normalized === 'high'
|
|
55
|
+
? normalized
|
|
56
|
+
: undefined;
|
|
57
|
+
}
|
|
58
|
+
function normalizedWorkload(value) {
|
|
59
|
+
const normalized = String(value || '').trim().toLowerCase();
|
|
60
|
+
return normalized === 'normal' || normalized === 'large' || normalized === 'max'
|
|
61
|
+
? normalized
|
|
62
|
+
: undefined;
|
|
63
|
+
}
|
|
64
|
+
function normalizedCapability(value) {
|
|
65
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
66
|
+
return {};
|
|
67
|
+
}
|
|
68
|
+
const record = value;
|
|
69
|
+
const capability = {};
|
|
70
|
+
const memoryClass = normalizedMemoryClass(record.memoryClass ?? record.memory_class);
|
|
71
|
+
const workload = normalizedWorkload(record.workload ?? record.workload_class);
|
|
72
|
+
if (memoryClass) {
|
|
73
|
+
capability.memoryClass = memoryClass;
|
|
74
|
+
}
|
|
75
|
+
if (workload) {
|
|
76
|
+
capability.workload = workload;
|
|
77
|
+
}
|
|
78
|
+
return capability;
|
|
79
|
+
}
|
|
80
|
+
function resolveAdaptiveTier(capability) {
|
|
81
|
+
if (capability.memoryClass === 'low') {
|
|
82
|
+
return 'standard';
|
|
83
|
+
}
|
|
84
|
+
if (capability.memoryClass === 'high' && capability.workload === 'max') {
|
|
85
|
+
return 'max';
|
|
86
|
+
}
|
|
87
|
+
if (capability.workload === 'max' || (capability.memoryClass === 'high' && capability.workload === 'large')) {
|
|
88
|
+
return 'extended';
|
|
89
|
+
}
|
|
90
|
+
return 'standard';
|
|
91
|
+
}
|
|
92
|
+
function cloneRuntimeGovernor(governor) {
|
|
93
|
+
return {
|
|
94
|
+
timeoutMs: governor.timeoutMs,
|
|
95
|
+
maxSerializedBytes: governor.maxSerializedBytes,
|
|
96
|
+
maxFragmentsProcessed: governor.maxFragmentsProcessed,
|
|
97
|
+
maxReportChars: governor.maxReportChars,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function cloneRagBudget(rag, productCapDisabled = false) {
|
|
101
|
+
const cloned = {
|
|
102
|
+
maxFragments: rag.maxFragments,
|
|
103
|
+
maxCharsPerFragment: rag.maxCharsPerFragment,
|
|
104
|
+
maxTotalChars: rag.maxTotalChars,
|
|
105
|
+
};
|
|
106
|
+
if (productCapDisabled) {
|
|
107
|
+
cloned.productCapDisabled = true;
|
|
108
|
+
cloned.runtimeMaxFragments = rag.runtimeMaxFragments;
|
|
109
|
+
cloned.runtimeMaxCharsPerFragment = rag.runtimeMaxCharsPerFragment;
|
|
110
|
+
cloned.runtimeMaxTotalChars = rag.runtimeMaxTotalChars;
|
|
111
|
+
}
|
|
112
|
+
return cloned;
|
|
113
|
+
}
|
|
114
|
+
function resolveAgentResponseBudget(input = {}) {
|
|
115
|
+
const responseMode = input.responseMode === 'full' ? 'full' : 'slim';
|
|
116
|
+
const mobile = input.mobile === true;
|
|
117
|
+
const requestedMode = input.responseBudgetMode === 'unbounded'
|
|
118
|
+
? 'unbounded'
|
|
119
|
+
: 'adaptive';
|
|
120
|
+
if (responseMode !== 'full' || mobile) {
|
|
121
|
+
const standard = exports.AGENT_RESPONSE_BUDGET_TIERS.standard;
|
|
122
|
+
return {
|
|
123
|
+
mode: 'adaptive',
|
|
124
|
+
tier: 'standard',
|
|
125
|
+
productCapDisabled: false,
|
|
126
|
+
rag: cloneRagBudget(standard.rag),
|
|
127
|
+
reportMaxChars: standard.reportMaxChars,
|
|
128
|
+
runtimeGovernor: cloneRuntimeGovernor(standard.runtimeGovernor),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (requestedMode === 'unbounded') {
|
|
132
|
+
return {
|
|
133
|
+
mode: 'unbounded',
|
|
134
|
+
tier: 'unbounded',
|
|
135
|
+
productCapDisabled: true,
|
|
136
|
+
rag: cloneRagBudget({
|
|
137
|
+
maxFragments: UNBOUNDED_RUNTIME_GOVERNOR.maxFragmentsProcessed,
|
|
138
|
+
maxCharsPerFragment: exports.AGENT_RESPONSE_BUDGET_TIERS.max.rag.maxCharsPerFragment,
|
|
139
|
+
maxTotalChars: exports.AGENT_RESPONSE_UNBOUNDED_RUNTIME_GOVERNOR.maxReportChars,
|
|
140
|
+
runtimeMaxFragments: UNBOUNDED_RUNTIME_GOVERNOR.maxFragmentsProcessed,
|
|
141
|
+
runtimeMaxCharsPerFragment: exports.AGENT_RESPONSE_BUDGET_TIERS.max.rag.maxCharsPerFragment,
|
|
142
|
+
runtimeMaxTotalChars: UNBOUNDED_RUNTIME_GOVERNOR.maxReportChars,
|
|
143
|
+
}, true),
|
|
144
|
+
runtimeGovernor: cloneRuntimeGovernor(UNBOUNDED_RUNTIME_GOVERNOR),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const tier = resolveAdaptiveTier(normalizedCapability(input.capability));
|
|
148
|
+
const definition = exports.AGENT_RESPONSE_BUDGET_TIERS[tier];
|
|
149
|
+
return {
|
|
150
|
+
mode: 'adaptive',
|
|
151
|
+
tier,
|
|
152
|
+
productCapDisabled: false,
|
|
153
|
+
rag: cloneRagBudget(definition.rag),
|
|
154
|
+
reportMaxChars: definition.reportMaxChars,
|
|
155
|
+
runtimeGovernor: cloneRuntimeGovernor(definition.runtimeGovernor),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function applyRuntimeGovernor(input) {
|
|
159
|
+
const governor = input.budget.runtimeGovernor;
|
|
160
|
+
if (Number(input.nowMs) - Number(input.startedAtMs) > governor.timeoutMs) {
|
|
161
|
+
return { allowed: false, truncated: true, reason: 'runtime_timeout' };
|
|
162
|
+
}
|
|
163
|
+
if (Number(input.processedFragments) > governor.maxFragmentsProcessed) {
|
|
164
|
+
return { allowed: false, truncated: true, reason: 'runtime_fragment_limit' };
|
|
165
|
+
}
|
|
166
|
+
if (Number(input.serializedBytes) > governor.maxSerializedBytes) {
|
|
167
|
+
return { allowed: false, truncated: true, reason: 'runtime_serialized_bytes_limit' };
|
|
168
|
+
}
|
|
169
|
+
if (Number(input.reportChars) > governor.maxReportChars) {
|
|
170
|
+
return { allowed: false, truncated: true, reason: 'runtime_report_chars_limit' };
|
|
171
|
+
}
|
|
172
|
+
return { allowed: true, truncated: false };
|
|
173
|
+
}
|
|
174
|
+
function resolveHostedAgentResponseBudget(input, hostCapability) {
|
|
175
|
+
const requested = resolveAgentResponseBudget(input);
|
|
176
|
+
const ceiling = resolveAgentResponseBudget({ ...input, capability: hostCapability });
|
|
177
|
+
const rank = { standard: 0, extended: 1, max: 2, unbounded: 3 };
|
|
178
|
+
return rank[requested.tier] <= rank[ceiling.tier] ? requested : ceiling;
|
|
179
|
+
}
|