@peer-agent/runtime-core 0.0.1-beta.43

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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/dist/capability-registry.d.ts +15 -0
  4. package/dist/capability-registry.js +88 -0
  5. package/dist/compaction-progress.d.ts +51 -0
  6. package/dist/compaction-progress.js +83 -0
  7. package/dist/context-accounting-lifecycle.d.ts +41 -0
  8. package/dist/context-accounting-lifecycle.js +90 -0
  9. package/dist/context-accounting-pipeline.d.ts +98 -0
  10. package/dist/context-accounting-pipeline.js +561 -0
  11. package/dist/context-compaction.d.ts +70 -0
  12. package/dist/context-compaction.js +192 -0
  13. package/dist/context-projection-lifecycle.d.ts +32 -0
  14. package/dist/context-projection-lifecycle.js +65 -0
  15. package/dist/context-projection.d.ts +74 -0
  16. package/dist/context-projection.js +183 -0
  17. package/dist/contracts.d.ts +218 -0
  18. package/dist/contracts.js +1 -0
  19. package/dist/conversation-history-projector.d.ts +52 -0
  20. package/dist/conversation-history-projector.js +472 -0
  21. package/dist/decision.d.ts +4 -0
  22. package/dist/decision.js +23 -0
  23. package/dist/evidence.d.ts +64 -0
  24. package/dist/evidence.js +127 -0
  25. package/dist/hooks.d.ts +5 -0
  26. package/dist/hooks.js +4 -0
  27. package/dist/index.d.ts +18 -0
  28. package/dist/index.js +18 -0
  29. package/dist/local-tool-contracts.d.ts +60 -0
  30. package/dist/local-tool-contracts.js +64 -0
  31. package/dist/microcompact.d.ts +38 -0
  32. package/dist/microcompact.js +354 -0
  33. package/dist/permission.d.ts +18 -0
  34. package/dist/permission.js +50 -0
  35. package/dist/projection-materializers.d.ts +18 -0
  36. package/dist/projection-materializers.js +34 -0
  37. package/dist/projection.d.ts +15 -0
  38. package/dist/projection.js +78 -0
  39. package/dist/runtime-usage-accounting.d.ts +19 -0
  40. package/dist/runtime-usage-accounting.js +79 -0
  41. package/package.json +47 -0
package/dist/hooks.js ADDED
@@ -0,0 +1,4 @@
1
+ import { mostRestrictiveDecision } from "./decision.js";
2
+ export function mostRestrictiveHookDecision(records = []) {
3
+ return mostRestrictiveDecision(records.map((record) => record?.decision));
4
+ }
@@ -0,0 +1,18 @@
1
+ export * from './contracts.ts';
2
+ export * from './decision.ts';
3
+ export * from './evidence.ts';
4
+ export * from './hooks.ts';
5
+ export * from './permission.ts';
6
+ export * from './capability-registry.ts';
7
+ export * from './projection.ts';
8
+ export * from './projection-materializers.ts';
9
+ export * from './local-tool-contracts.ts';
10
+ export * from './context-compaction.ts';
11
+ export * from './compaction-progress.ts';
12
+ export * from './microcompact.ts';
13
+ export * from './context-projection.ts';
14
+ export * from './context-projection-lifecycle.ts';
15
+ export * from './context-accounting-pipeline.ts';
16
+ export * from './context-accounting-lifecycle.ts';
17
+ export * from './conversation-history-projector.ts';
18
+ export * from './runtime-usage-accounting.ts';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ export * from "./contracts.js";
2
+ export * from "./decision.js";
3
+ export * from "./evidence.js";
4
+ export * from "./hooks.js";
5
+ export * from "./permission.js";
6
+ export * from "./capability-registry.js";
7
+ export * from "./projection.js";
8
+ export * from "./projection-materializers.js";
9
+ export * from "./local-tool-contracts.js";
10
+ export * from "./context-compaction.js";
11
+ export * from "./compaction-progress.js";
12
+ export * from "./microcompact.js";
13
+ export * from "./context-projection.js";
14
+ export * from "./context-projection-lifecycle.js";
15
+ export * from "./context-accounting-pipeline.js";
16
+ export * from "./context-accounting-lifecycle.js";
17
+ export * from "./conversation-history-projector.js";
18
+ export * from "./runtime-usage-accounting.js";
@@ -0,0 +1,60 @@
1
+ export interface LocalToolContract<TToolName extends string = string, TCapabilityId extends string = string> {
2
+ readonly toolName: TToolName;
3
+ readonly capabilityId: TCapabilityId;
4
+ }
5
+ /**
6
+ * Canonical model-visible contracts shared by Desktop and CLI/TUI.
7
+ *
8
+ * Provider implementations and input schemas remain owned by their capability
9
+ * modules. This registry only defines the stable public name/ID boundary.
10
+ */
11
+ export declare const SHARED_LOCAL_TOOL_CONTRACTS: Readonly<{
12
+ readFile: Readonly<LocalToolContract<"read_file", "local.file.read">>;
13
+ listFiles: Readonly<LocalToolContract<"list_files", "local.file.list">>;
14
+ searchFiles: Readonly<LocalToolContract<"search_files", "local.file.search">>;
15
+ editFile: Readonly<LocalToolContract<"edit_file", "local.file.edit">>;
16
+ writeFile: Readonly<LocalToolContract<"write_file", "local.file.write">>;
17
+ shellExec: Readonly<LocalToolContract<"bash", "local.shell.exec">>;
18
+ shellStop: Readonly<LocalToolContract<"shell_stop", "local.shell.stop">>;
19
+ batchSearch: Readonly<LocalToolContract<"batch_search", "local.search.aggregate">>;
20
+ webFetch: Readonly<LocalToolContract<"web_fetch", "local.web.fetch">>;
21
+ requestUserInput: Readonly<LocalToolContract<"request_user_input", "local.interaction.request_user_input">>;
22
+ goalCreatePlan: Readonly<LocalToolContract<"goal_create_plan", "local.goal.create_plan">>;
23
+ goalUpdateTask: Readonly<LocalToolContract<"goal_update_task", "local.goal.update_task">>;
24
+ goalGetPlan: Readonly<LocalToolContract<"goal_get_plan", "local.goal.get_plan">>;
25
+ requestExplorer: Readonly<LocalToolContract<"request_explorer", "local.goal.explore">>;
26
+ }>;
27
+ export type SharedLocalToolContractKey = keyof typeof SHARED_LOCAL_TOOL_CONTRACTS;
28
+ export type SharedLocalToolName = (typeof SHARED_LOCAL_TOOL_CONTRACTS)[SharedLocalToolContractKey]['toolName'];
29
+ export type SharedLocalCapabilityId = (typeof SHARED_LOCAL_TOOL_CONTRACTS)[SharedLocalToolContractKey]['capabilityId'];
30
+ export declare const SHARED_LOCAL_TOOL_CONTRACT_LIST: readonly (Readonly<LocalToolContract<"read_file", "local.file.read">> | Readonly<LocalToolContract<"list_files", "local.file.list">> | Readonly<LocalToolContract<"search_files", "local.file.search">> | Readonly<LocalToolContract<"edit_file", "local.file.edit">> | Readonly<LocalToolContract<"write_file", "local.file.write">> | Readonly<LocalToolContract<"bash", "local.shell.exec">> | Readonly<LocalToolContract<"shell_stop", "local.shell.stop">> | Readonly<LocalToolContract<"batch_search", "local.search.aggregate">> | Readonly<LocalToolContract<"web_fetch", "local.web.fetch">> | Readonly<LocalToolContract<"request_user_input", "local.interaction.request_user_input">> | Readonly<LocalToolContract<"goal_create_plan", "local.goal.create_plan">> | Readonly<LocalToolContract<"goal_update_task", "local.goal.update_task">> | Readonly<LocalToolContract<"goal_get_plan", "local.goal.get_plan">> | Readonly<LocalToolContract<"request_explorer", "local.goal.explore">>)[];
31
+ /**
32
+ * Explicit Desktop-only capabilities. Parity assertions must exclude exactly
33
+ * these contracts instead of ignoring arbitrary browser-prefixed additions.
34
+ */
35
+ export declare const DESKTOP_ONLY_LOCAL_TOOL_CONTRACTS: Readonly<{
36
+ browserNavigate: Readonly<LocalToolContract<"browser_navigate", "local.web.control.navigate">>;
37
+ browserClick: Readonly<LocalToolContract<"browser_click", "local.web.control.click">>;
38
+ browserType: Readonly<LocalToolContract<"browser_type", "local.web.control.type">>;
39
+ browserScreenshot: Readonly<LocalToolContract<"browser_screenshot", "local.web.control.screenshot">>;
40
+ browserReadDom: Readonly<LocalToolContract<"browser_read_dom", "local.web.control.readDom">>;
41
+ }>;
42
+ export declare const DESKTOP_ONLY_LOCAL_TOOL_CONTRACT_LIST: readonly (Readonly<LocalToolContract<"browser_navigate", "local.web.control.navigate">> | Readonly<LocalToolContract<"browser_click", "local.web.control.click">> | Readonly<LocalToolContract<"browser_type", "local.web.control.type">> | Readonly<LocalToolContract<"browser_screenshot", "local.web.control.screenshot">> | Readonly<LocalToolContract<"browser_read_dom", "local.web.control.readDom">>)[];
43
+ /**
44
+ * Read-time/inbound compatibility only. New Runtime Projections must never
45
+ * expose these legacy capability IDs.
46
+ */
47
+ export declare const LEGACY_LOCAL_CAPABILITY_ID_ALIASES: Readonly<{
48
+ 'local.goal.create': "local.goal.create_plan";
49
+ 'local.goal.update': "local.goal.update_task";
50
+ 'local.goal.read': "local.goal.get_plan";
51
+ 'local.search.content': "local.file.search";
52
+ }>;
53
+ /** Historical model-tool names accepted while replaying old turns. */
54
+ export declare const LEGACY_LOCAL_MODEL_TOOL_NAME_ALIASES: Readonly<{
55
+ local_shell_exec: "bash";
56
+ }>;
57
+ export declare function canonicalizeLocalCapabilityId(capabilityId: string): string;
58
+ export declare function canonicalizeLocalModelToolName(toolName: string): string;
59
+ export declare function isSharedLocalCapabilityId(capabilityId: string): capabilityId is SharedLocalCapabilityId;
60
+ export declare function isSharedLocalToolName(toolName: string): toolName is SharedLocalToolName;
@@ -0,0 +1,64 @@
1
+ function defineToolContract(toolName, capabilityId) {
2
+ return Object.freeze({ toolName, capabilityId });
3
+ }
4
+ /**
5
+ * Canonical model-visible contracts shared by Desktop and CLI/TUI.
6
+ *
7
+ * Provider implementations and input schemas remain owned by their capability
8
+ * modules. This registry only defines the stable public name/ID boundary.
9
+ */
10
+ export const SHARED_LOCAL_TOOL_CONTRACTS = Object.freeze({
11
+ readFile: defineToolContract('read_file', 'local.file.read'),
12
+ listFiles: defineToolContract('list_files', 'local.file.list'),
13
+ searchFiles: defineToolContract('search_files', 'local.file.search'),
14
+ editFile: defineToolContract('edit_file', 'local.file.edit'),
15
+ writeFile: defineToolContract('write_file', 'local.file.write'),
16
+ shellExec: defineToolContract('bash', 'local.shell.exec'),
17
+ shellStop: defineToolContract('shell_stop', 'local.shell.stop'),
18
+ batchSearch: defineToolContract('batch_search', 'local.search.aggregate'),
19
+ webFetch: defineToolContract('web_fetch', 'local.web.fetch'),
20
+ requestUserInput: defineToolContract('request_user_input', 'local.interaction.request_user_input'),
21
+ goalCreatePlan: defineToolContract('goal_create_plan', 'local.goal.create_plan'),
22
+ goalUpdateTask: defineToolContract('goal_update_task', 'local.goal.update_task'),
23
+ goalGetPlan: defineToolContract('goal_get_plan', 'local.goal.get_plan'),
24
+ requestExplorer: defineToolContract('request_explorer', 'local.goal.explore'),
25
+ });
26
+ export const SHARED_LOCAL_TOOL_CONTRACT_LIST = Object.freeze(Object.values(SHARED_LOCAL_TOOL_CONTRACTS));
27
+ /**
28
+ * Explicit Desktop-only capabilities. Parity assertions must exclude exactly
29
+ * these contracts instead of ignoring arbitrary browser-prefixed additions.
30
+ */
31
+ export const DESKTOP_ONLY_LOCAL_TOOL_CONTRACTS = Object.freeze({
32
+ browserNavigate: defineToolContract('browser_navigate', 'local.web.control.navigate'),
33
+ browserClick: defineToolContract('browser_click', 'local.web.control.click'),
34
+ browserType: defineToolContract('browser_type', 'local.web.control.type'),
35
+ browserScreenshot: defineToolContract('browser_screenshot', 'local.web.control.screenshot'),
36
+ browserReadDom: defineToolContract('browser_read_dom', 'local.web.control.readDom'),
37
+ });
38
+ export const DESKTOP_ONLY_LOCAL_TOOL_CONTRACT_LIST = Object.freeze(Object.values(DESKTOP_ONLY_LOCAL_TOOL_CONTRACTS));
39
+ /**
40
+ * Read-time/inbound compatibility only. New Runtime Projections must never
41
+ * expose these legacy capability IDs.
42
+ */
43
+ export const LEGACY_LOCAL_CAPABILITY_ID_ALIASES = Object.freeze({
44
+ 'local.goal.create': SHARED_LOCAL_TOOL_CONTRACTS.goalCreatePlan.capabilityId,
45
+ 'local.goal.update': SHARED_LOCAL_TOOL_CONTRACTS.goalUpdateTask.capabilityId,
46
+ 'local.goal.read': SHARED_LOCAL_TOOL_CONTRACTS.goalGetPlan.capabilityId,
47
+ 'local.search.content': SHARED_LOCAL_TOOL_CONTRACTS.searchFiles.capabilityId,
48
+ });
49
+ /** Historical model-tool names accepted while replaying old turns. */
50
+ export const LEGACY_LOCAL_MODEL_TOOL_NAME_ALIASES = Object.freeze({
51
+ local_shell_exec: SHARED_LOCAL_TOOL_CONTRACTS.shellExec.toolName,
52
+ });
53
+ export function canonicalizeLocalCapabilityId(capabilityId) {
54
+ return LEGACY_LOCAL_CAPABILITY_ID_ALIASES[capabilityId] ?? capabilityId;
55
+ }
56
+ export function canonicalizeLocalModelToolName(toolName) {
57
+ return LEGACY_LOCAL_MODEL_TOOL_NAME_ALIASES[toolName] ?? toolName;
58
+ }
59
+ export function isSharedLocalCapabilityId(capabilityId) {
60
+ return SHARED_LOCAL_TOOL_CONTRACT_LIST.some((contract) => contract.capabilityId === capabilityId);
61
+ }
62
+ export function isSharedLocalToolName(toolName) {
63
+ return SHARED_LOCAL_TOOL_CONTRACT_LIST.some((contract) => contract.toolName === toolName);
64
+ }
@@ -0,0 +1,38 @@
1
+ export declare const MICROCOMPACTION_CONFIG: Readonly<{
2
+ keepRecentCount: 8;
3
+ triggerChars: 6000;
4
+ previewChars: 800;
5
+ }>;
6
+ /** 宽松消息形状:兼容 Desktop apiMessages 与 TUI ModelMessage(无索引签名接口)。 */
7
+ export type MicrocompactMessage = {
8
+ readonly role?: string;
9
+ readonly content?: unknown;
10
+ readonly _compaction?: unknown;
11
+ };
12
+ export interface MicrocompactStats {
13
+ readonly compactedCount: number;
14
+ readonly beforeChars: number;
15
+ readonly afterChars: number;
16
+ readonly savedChars: number;
17
+ }
18
+ export interface MicrocompactResult<TMessage> {
19
+ readonly messages: readonly TMessage[];
20
+ readonly stats: MicrocompactStats;
21
+ }
22
+ export declare function previewHistoricalText(text: unknown, maxChars?: number): string;
23
+ /**
24
+ * 从将被裁掉的历史正文中抽取可回捞线索(artifact / path / retrieval command)。
25
+ * 目标:即使原文没有结构化 local_*_ref,压缩后仍留下可再读入口。
26
+ */
27
+ export declare function extractRecoverableClues(text: unknown, { limit }?: {
28
+ limit?: number;
29
+ }): {
30
+ artifactRefs: string[];
31
+ paths: string[];
32
+ suggestedRetrieval: string[];
33
+ };
34
+ /**
35
+ * 对「最近 keepRecentCount 条非 system 消息之外」的历史消息做证据引用化/预览化。
36
+ * system 与 `_compaction` handoff 不参与;已是 local_*_ref 的结果保留骨架不重复截断。
37
+ */
38
+ export declare function microcompactMessagesForContext<TMessage extends MicrocompactMessage>(messages: readonly TMessage[], options?: Partial<typeof MICROCOMPACTION_CONFIG>): MicrocompactResult<TMessage>;
@@ -0,0 +1,354 @@
1
+ // Layer 1 microcompaction — host-neutral (Desktop + CLI/TUI share one implementation).
2
+ //
3
+ // 从 Desktop context-compactor.mjs 平移下沉(23 号治理文档阶段 E):
4
+ // 对「最近窗口之外」的历史工具结果做证据引用化/预览化,而不是让大全文进 provider 请求。
5
+ // 结构化 ref(local_tool_result_ref / local_file_ref / local_capability_result_ref)
6
+ // 保留骨架与检索路径;无结构的长文本抽取可回捞线索(artifact/path/retrieval)后再预览化。
7
+ //
8
+ // 原则(17 号文档):It moves evidence out of prompt and keeps the route back.
9
+ export const MICROCOMPACTION_CONFIG = Object.freeze({
10
+ keepRecentCount: 8,
11
+ triggerChars: 6_000,
12
+ previewChars: 800,
13
+ });
14
+ export function previewHistoricalText(text, maxChars = MICROCOMPACTION_CONFIG.previewChars) {
15
+ const value = String(text ?? '');
16
+ if (value.length <= maxChars)
17
+ return value;
18
+ const headChars = Math.max(200, Math.floor(maxChars * 0.55));
19
+ const tailChars = Math.max(160, maxChars - headChars - 80);
20
+ return `${value.slice(0, headChars)}\n...[historical context preview truncated: ${value.length} chars]...\n${value.slice(-tailChars)}`;
21
+ }
22
+ function tryParseJsonObject(text) {
23
+ if (typeof text !== 'string')
24
+ return null;
25
+ const trimmed = text.trim();
26
+ if (!trimmed.startsWith('{') || !trimmed.endsWith('}'))
27
+ return null;
28
+ try {
29
+ const parsed = JSON.parse(trimmed);
30
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ function pickDefined(source, fields) {
37
+ const result = {};
38
+ for (const field of fields) {
39
+ if (source?.[field] !== undefined)
40
+ result[field] = source[field];
41
+ }
42
+ return result;
43
+ }
44
+ function compactLocalRefPayload(payload, previewChars) {
45
+ if (payload?.kind === 'local_tool_result_ref') {
46
+ const compacted = {
47
+ kind: payload.kind,
48
+ microCompacted: true,
49
+ note: 'Historical local tool result compacted; use artifact paths or suggestedRetrieval for full output.',
50
+ ...pickDefined(payload, [
51
+ 'tool', 'command', 'cwd', 'status', 'exitCode',
52
+ 'stdoutPath', 'stderrPath', 'metadataPath',
53
+ 'artifactRef', 'artifactRefs',
54
+ 'stdoutChars', 'stderrChars', 'stdoutLines', 'stderrLines',
55
+ 'originalChars', 'originalLines', 'keyFindings',
56
+ 'contextPreviewTruncated', 'suggestedRetrieval',
57
+ ]),
58
+ };
59
+ if (payload.stdoutPreview) {
60
+ compacted.stdoutPreview = previewHistoricalText(payload.stdoutPreview, previewChars);
61
+ }
62
+ if (payload.stderrPreview) {
63
+ compacted.stderrPreview = previewHistoricalText(payload.stderrPreview, Math.min(previewChars, 400));
64
+ }
65
+ return compacted;
66
+ }
67
+ if (payload?.kind === 'local_file_ref') {
68
+ return {
69
+ kind: payload.kind,
70
+ microCompacted: true,
71
+ note: 'Historical local file read compacted; use path or suggestedRetrieval for full content.',
72
+ ...pickDefined(payload, [
73
+ 'tool', 'path', 'chars', 'lines', 'mtimeMs', 'sizeBytes',
74
+ 'contentHash', 'fullRead', 'contextPreviewTruncated', 'suggestedRetrieval',
75
+ ]),
76
+ preview: previewHistoricalText(payload.preview ?? '', previewChars),
77
+ };
78
+ }
79
+ if (payload?.kind === 'local_capability_result_ref') {
80
+ const outputPreview = payload.outputPreview && typeof payload.outputPreview === 'object'
81
+ ? compactCapabilityOutputPreview(payload.outputPreview, previewChars)
82
+ : payload.outputPreview;
83
+ return {
84
+ kind: payload.kind,
85
+ microCompacted: true,
86
+ note: 'Historical local capability result compacted; use artifact paths or suggestedRetrieval for full output.',
87
+ ...pickDefined(payload, [
88
+ 'tool', 'capabilityId', 'status', 'artifactRef', 'artifactRefs', 'suggestedRetrieval',
89
+ ]),
90
+ outputPreview,
91
+ };
92
+ }
93
+ return null;
94
+ }
95
+ function compactCapabilityOutputPreview(preview, previewChars) {
96
+ const next = {
97
+ ...pickDefined(preview, [
98
+ 'status', 'tool', 'capabilityId', 'cwd', 'exitCode',
99
+ 'stdoutPath', 'stderrPath', 'metadataPath',
100
+ 'artifactRef', 'artifactRefs',
101
+ 'stdoutChars', 'stderrChars', 'stdoutLines', 'stderrLines',
102
+ 'contextPreviewTruncated', 'suggestedRetrieval',
103
+ ]),
104
+ };
105
+ // nested shell/file refs inside capability output
106
+ if (preview.localToolResultRef && typeof preview.localToolResultRef === 'object') {
107
+ next.localToolResultRef = compactLocalRefPayload({ kind: 'local_tool_result_ref', ...preview.localToolResultRef }, previewChars) || {
108
+ ...pickDefined(preview.localToolResultRef, [
109
+ 'tool', 'command', 'cwd', 'status', 'exitCode',
110
+ 'stdoutPath', 'stderrPath', 'metadataPath',
111
+ 'artifactRef', 'artifactRefs', 'suggestedRetrieval',
112
+ ]),
113
+ microCompacted: true,
114
+ };
115
+ }
116
+ if (typeof preview.preview === 'string') {
117
+ next.preview = previewHistoricalText(preview.preview, previewChars);
118
+ }
119
+ if (typeof preview.stdoutPreview === 'string') {
120
+ next.stdoutPreview = previewHistoricalText(preview.stdoutPreview, previewChars);
121
+ }
122
+ if (typeof preview.stderrPreview === 'string') {
123
+ next.stderrPreview = previewHistoricalText(preview.stderrPreview, Math.min(previewChars, 400));
124
+ }
125
+ // Drop large unstructured blobs that are recoverable via artifact refs.
126
+ if (preview.aggregated && typeof preview.aggregated === 'object') {
127
+ next.aggregated = {
128
+ ...pickDefined(preview.aggregated, ['matchCount', 'truncated', 'laneCount']),
129
+ note: 'Aggregated match details dropped by microcompact; use artifactRefs/suggestedRetrieval.',
130
+ };
131
+ }
132
+ return next;
133
+ }
134
+ function uniqueNonEmptyStrings(values, limit = 12) {
135
+ const seen = new Set();
136
+ const result = [];
137
+ for (const value of values) {
138
+ const text = String(value ?? '').trim();
139
+ if (!text || seen.has(text))
140
+ continue;
141
+ seen.add(text);
142
+ result.push(text);
143
+ if (result.length >= limit)
144
+ break;
145
+ }
146
+ return result;
147
+ }
148
+ /**
149
+ * 从将被裁掉的历史正文中抽取可回捞线索(artifact / path / retrieval command)。
150
+ * 目标:即使原文没有结构化 local_*_ref,压缩后仍留下可再读入口。
151
+ */
152
+ export function extractRecoverableClues(text, { limit = 12 } = {}) {
153
+ const value = String(text ?? '');
154
+ if (!value) {
155
+ return { artifactRefs: [], paths: [], suggestedRetrieval: [] };
156
+ }
157
+ const artifactRefs = uniqueNonEmptyStrings([
158
+ ...(value.match(/local-[a-z0-9-]+-artifact:\/\/[^\s"'`\]]+/gi) || []),
159
+ ...(value.match(/tool-result:\/\/[^\s"'`\]]+/gi) || []),
160
+ ...(value.match(/goal-plan:\/\/[^\s"'`\]]+/gi) || []),
161
+ ], limit);
162
+ const pathPatterns = [
163
+ /(?:stdoutPath|stderrPath|metadataPath|path)\s*[:=]\s*["']([^"']+)["']/g,
164
+ /(?:^|\s)(\/(?:Users|home|tmp|var|private|Volumes)\/[^\s"'`\]]+)/g,
165
+ /(?:^|\s)([A-Za-z]:\\[^\s"'`\]]+)/g,
166
+ ];
167
+ const paths = [];
168
+ for (const pattern of pathPatterns) {
169
+ for (const match of value.matchAll(pattern)) {
170
+ const candidate = match[1] || match[0];
171
+ if (candidate)
172
+ paths.push(candidate.trim());
173
+ }
174
+ }
175
+ const retrievalPatterns = [
176
+ /(?:^|\n)\s*((?:rg|tail|sed|cat|head|read_file)\b[^\n]{0,240})/g,
177
+ ];
178
+ const suggestedRetrieval = [];
179
+ for (const pattern of retrievalPatterns) {
180
+ for (const match of value.matchAll(pattern)) {
181
+ const cmd = String(match[1] || '').trim();
182
+ if (cmd.length >= 8)
183
+ suggestedRetrieval.push(cmd);
184
+ }
185
+ }
186
+ // If we only have artifact paths, synthesize cheap retrieval commands.
187
+ for (const ref of artifactRefs) {
188
+ if (ref.startsWith('local-shell-artifact://') || ref.includes('/stdout')) {
189
+ suggestedRetrieval.push(`tail -n 120 "${ref}"`);
190
+ }
191
+ }
192
+ for (const filePath of uniqueNonEmptyStrings(paths, 6)) {
193
+ if (filePath.includes('stdout') || filePath.endsWith('.txt') || filePath.endsWith('.log')) {
194
+ suggestedRetrieval.push(`tail -n 120 "${filePath}"`);
195
+ }
196
+ else {
197
+ suggestedRetrieval.push(`sed -n '1,120p' "${filePath}"`);
198
+ }
199
+ }
200
+ return {
201
+ artifactRefs: uniqueNonEmptyStrings(artifactRefs, limit),
202
+ paths: uniqueNonEmptyStrings(paths, limit),
203
+ suggestedRetrieval: uniqueNonEmptyStrings(suggestedRetrieval, limit),
204
+ };
205
+ }
206
+ function compactLongHistoricalString(text, previewChars) {
207
+ const clues = extractRecoverableClues(text);
208
+ const hasClues = clues.artifactRefs.length > 0
209
+ || clues.paths.length > 0
210
+ || clues.suggestedRetrieval.length > 0;
211
+ const lines = [
212
+ hasClues
213
+ ? '[历史长文本已从活跃上下文压缩为预览;请用下方可回捞线索按需读取原文]'
214
+ : '[历史长文本已从活跃上下文压缩为预览;原文没有可恢复的本地 artifact ref]',
215
+ `originalChars: ${text.length}`,
216
+ ];
217
+ if (clues.artifactRefs.length > 0) {
218
+ lines.push(`artifactRefs: ${JSON.stringify(clues.artifactRefs)}`);
219
+ }
220
+ if (clues.paths.length > 0) {
221
+ lines.push(`paths: ${JSON.stringify(clues.paths)}`);
222
+ }
223
+ if (clues.suggestedRetrieval.length > 0) {
224
+ lines.push('suggestedRetrieval:');
225
+ for (const cmd of clues.suggestedRetrieval) {
226
+ lines.push(` - ${cmd}`);
227
+ }
228
+ }
229
+ lines.push('', previewHistoricalText(text, previewChars));
230
+ return lines.join('\n');
231
+ }
232
+ function microcompactStringContent(content, config) {
233
+ const parsed = tryParseJsonObject(content);
234
+ if (parsed) {
235
+ const compactedRef = compactLocalRefPayload(parsed, config.previewChars);
236
+ if (compactedRef) {
237
+ const nextContent = JSON.stringify(compactedRef, null, 2);
238
+ if (nextContent.length < content.length) {
239
+ return {
240
+ content: nextContent,
241
+ compacted: true,
242
+ beforeChars: content.length,
243
+ afterChars: nextContent.length,
244
+ };
245
+ }
246
+ }
247
+ }
248
+ if (content.length <= config.triggerChars) {
249
+ return { content, compacted: false, beforeChars: content.length, afterChars: content.length };
250
+ }
251
+ const nextContent = compactLongHistoricalString(content, config.previewChars);
252
+ return {
253
+ content: nextContent,
254
+ compacted: true,
255
+ beforeChars: content.length,
256
+ afterChars: nextContent.length,
257
+ };
258
+ }
259
+ function microcompactBlockContent(block, config) {
260
+ if (block?.type === 'tool_result' && typeof block.content === 'string') {
261
+ const result = microcompactStringContent(block.content, config);
262
+ if (result.compacted) {
263
+ return {
264
+ block: { ...block, content: result.content },
265
+ compacted: true,
266
+ beforeChars: result.beforeChars,
267
+ afterChars: result.afterChars,
268
+ };
269
+ }
270
+ }
271
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text.length > config.triggerChars) {
272
+ const result = microcompactStringContent(block.text, config);
273
+ if (result.compacted) {
274
+ return {
275
+ block: { ...block, text: result.content },
276
+ compacted: true,
277
+ beforeChars: result.beforeChars,
278
+ afterChars: result.afterChars,
279
+ };
280
+ }
281
+ }
282
+ return { block, compacted: false, beforeChars: 0, afterChars: 0 };
283
+ }
284
+ function microcompactMessageContent(content, config) {
285
+ if (typeof content === 'string') {
286
+ const result = microcompactStringContent(content, config);
287
+ return { content: result.content, compacted: result.compacted, beforeChars: result.beforeChars, afterChars: result.afterChars };
288
+ }
289
+ if (Array.isArray(content)) {
290
+ let compacted = false;
291
+ let beforeChars = 0;
292
+ let afterChars = 0;
293
+ const blocks = content.map((block) => {
294
+ const result = microcompactBlockContent(block, config);
295
+ if (result.compacted) {
296
+ compacted = true;
297
+ beforeChars += result.beforeChars;
298
+ afterChars += result.afterChars;
299
+ }
300
+ return result.block;
301
+ });
302
+ return { content: blocks, compacted, beforeChars, afterChars };
303
+ }
304
+ return { content, compacted: false, beforeChars: 0, afterChars: 0 };
305
+ }
306
+ /**
307
+ * 对「最近 keepRecentCount 条非 system 消息之外」的历史消息做证据引用化/预览化。
308
+ * system 与 `_compaction` handoff 不参与;已是 local_*_ref 的结果保留骨架不重复截断。
309
+ */
310
+ export function microcompactMessagesForContext(messages, options = {}) {
311
+ const config = { ...MICROCOMPACTION_CONFIG, ...options };
312
+ let recentNonSystemSeen = 0;
313
+ const compactableIndexes = new Set();
314
+ for (let index = messages.length - 1; index >= 0; index--) {
315
+ const message = messages[index];
316
+ if (message?.role === 'system' || message?._compaction)
317
+ continue;
318
+ recentNonSystemSeen++;
319
+ if (recentNonSystemSeen > config.keepRecentCount) {
320
+ compactableIndexes.add(index);
321
+ }
322
+ }
323
+ let compactedCount = 0;
324
+ let beforeChars = 0;
325
+ let afterChars = 0;
326
+ const nextMessages = messages.map((message, index) => {
327
+ if (!compactableIndexes.has(index))
328
+ return message;
329
+ const result = microcompactMessageContent(message.content, config);
330
+ if (!result.compacted)
331
+ return message;
332
+ compactedCount++;
333
+ beforeChars += result.beforeChars;
334
+ afterChars += result.afterChars;
335
+ return {
336
+ ...message,
337
+ content: result.content,
338
+ _microCompaction: {
339
+ method: 'historical_context_preview',
340
+ beforeChars: result.beforeChars,
341
+ afterChars: result.afterChars,
342
+ },
343
+ };
344
+ });
345
+ return {
346
+ messages: compactedCount > 0 ? nextMessages : messages,
347
+ stats: {
348
+ compactedCount,
349
+ beforeChars,
350
+ afterChars,
351
+ savedChars: Math.max(0, beforeChars - afterChars),
352
+ },
353
+ };
354
+ }
@@ -0,0 +1,18 @@
1
+ import type { EvidenceRef, PermissionDecision, PermissionGrant, PermissionRequest, RuntimeDecision, RuntimeJsonObject } from './contracts.ts';
2
+ export type PermissionDecisionLike = RuntimeDecision | PermissionDecision | null | undefined;
3
+ export interface MergePermissionDecisionsOptions {
4
+ readonly defaultSource?: string;
5
+ readonly defaultReason?: string;
6
+ }
7
+ export interface CreatePermissionGrantDraftOptions {
8
+ readonly grantId: string;
9
+ readonly grantedAt: string;
10
+ readonly evidenceRefs?: readonly EvidenceRef[];
11
+ readonly metadata?: RuntimeJsonObject;
12
+ }
13
+ export declare function mostRestrictivePermissionDecision(decisions?: readonly PermissionDecisionLike[]): RuntimeDecision;
14
+ export declare function mergePermissionDecisions(decisions?: readonly (PermissionDecision | null | undefined)[], options?: MergePermissionDecisionsOptions): PermissionDecision;
15
+ export declare function isPermissionAllowed(decision: PermissionDecisionLike): boolean;
16
+ export declare function isPermissionAsking(decision: PermissionDecisionLike): boolean;
17
+ export declare function isPermissionDenied(decision: PermissionDecisionLike): boolean;
18
+ export declare function createPermissionGrantDraft(decision: PermissionDecision, request: Pick<PermissionRequest, 'capabilityId'>, options: CreatePermissionGrantDraftOptions): PermissionGrant;
@@ -0,0 +1,50 @@
1
+ import { mostRestrictiveDecision } from "./decision.js";
2
+ function decisionValue(decision) {
3
+ if (!decision) {
4
+ return undefined;
5
+ }
6
+ if (typeof decision === 'string') {
7
+ return decision;
8
+ }
9
+ return decision.decision;
10
+ }
11
+ export function mostRestrictivePermissionDecision(decisions = []) {
12
+ return mostRestrictiveDecision(decisions.map(decisionValue));
13
+ }
14
+ export function mergePermissionDecisions(decisions = [], options = {}) {
15
+ const validDecisions = decisions.filter((decision) => Boolean(decision));
16
+ const finalDecision = mostRestrictivePermissionDecision(validDecisions);
17
+ const sourceDecision = validDecisions.find((decision) => decision.decision === finalDecision);
18
+ const reason = sourceDecision?.reason ?? options.defaultReason;
19
+ const metadata = sourceDecision?.metadata;
20
+ return {
21
+ decision: finalDecision,
22
+ source: sourceDecision?.source ?? options.defaultSource ?? 'runtime_core_default',
23
+ ...(reason !== undefined ? { reason } : {}),
24
+ ...(metadata !== undefined ? { metadata } : {}),
25
+ };
26
+ }
27
+ export function isPermissionAllowed(decision) {
28
+ return decisionValue(decision) === 'allow';
29
+ }
30
+ export function isPermissionAsking(decision) {
31
+ return decisionValue(decision) === 'ask';
32
+ }
33
+ export function isPermissionDenied(decision) {
34
+ return decisionValue(decision) === 'deny';
35
+ }
36
+ export function createPermissionGrantDraft(decision, request, options) {
37
+ return {
38
+ grantId: options.grantId,
39
+ capabilityId: request.capabilityId,
40
+ decision: decision.decision,
41
+ grantedAt: options.grantedAt,
42
+ source: decision.source,
43
+ reason: decision.reason,
44
+ evidenceRefs: options.evidenceRefs,
45
+ metadata: {
46
+ ...decision.metadata,
47
+ ...options.metadata,
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,18 @@
1
+ import type { ProjectionMaterializer, RuntimeProjection } from './contracts.ts';
2
+ export interface OpenAIFunctionToolSchema {
3
+ readonly type: 'function';
4
+ readonly function: {
5
+ readonly name: string;
6
+ readonly description: string;
7
+ readonly parameters: unknown;
8
+ };
9
+ }
10
+ export interface AnthropicToolSchema {
11
+ readonly name: string;
12
+ readonly description: string;
13
+ readonly input_schema: unknown;
14
+ }
15
+ export declare function materializeOpenAITools(projection: RuntimeProjection): readonly OpenAIFunctionToolSchema[];
16
+ export declare function materializeAnthropicTools(projection: RuntimeProjection): readonly AnthropicToolSchema[];
17
+ export declare const openAIProjectionMaterializer: ProjectionMaterializer<OpenAIFunctionToolSchema>;
18
+ export declare const anthropicProjectionMaterializer: ProjectionMaterializer<AnthropicToolSchema>;