@causyne/agent 1.18.0 → 1.20.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.
Files changed (76) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +2348 -2531
  3. package/src/agentLoop.ts +2865 -0
  4. package/src/checkpoints.d.ts +4 -0
  5. package/src/cliMode.js +30 -17
  6. package/src/commands.js +307 -57
  7. package/src/config.js +22 -0
  8. package/src/contextManager.d.ts +10 -0
  9. package/src/continuum/adapters/antigravity.js +193 -0
  10. package/src/continuum/adapters/antigravity.ts +204 -0
  11. package/src/continuum/adapters/base.js +48 -0
  12. package/src/continuum/adapters/base.ts +57 -0
  13. package/src/continuum/adapters/causyne.js +66 -0
  14. package/src/continuum/adapters/causyne.ts +72 -0
  15. package/src/continuum/adapters/claudeCode.js +171 -0
  16. package/src/continuum/adapters/claudeCode.ts +179 -0
  17. package/src/continuum/adapters/codex.js +181 -0
  18. package/src/continuum/adapters/codex.ts +193 -0
  19. package/src/continuum/adapters/opencode.js +134 -0
  20. package/src/continuum/adapters/opencode.ts +153 -0
  21. package/src/continuum/compactor.js +54 -0
  22. package/src/continuum/compactor.ts +83 -0
  23. package/src/continuum/index.js +8 -0
  24. package/src/continuum/index.ts +9 -0
  25. package/src/continuum/ingest.js +63 -0
  26. package/src/continuum/ingest.ts +89 -0
  27. package/src/continuum/sanitizer.js +55 -0
  28. package/src/continuum/sanitizer.ts +59 -0
  29. package/src/continuum/scanner.js +86 -0
  30. package/src/continuum/scanner.ts +106 -0
  31. package/src/continuum/types.js +3 -0
  32. package/src/continuum/types.ts +51 -0
  33. package/src/continuum/ui/continuumPicker.js +111 -0
  34. package/src/continuum/ui/continuumPicker.ts +145 -0
  35. package/src/cortex/autoCondenser.d.ts +2 -0
  36. package/src/cortex/vectorDb.d.ts +1 -0
  37. package/src/designPalettes.d.ts +2 -0
  38. package/src/devMode.d.ts +1 -0
  39. package/src/dynamicCatalogue.js +5 -3
  40. package/src/dynamicCatalogue.ts +7 -4
  41. package/src/embodimentSession.d.ts +2 -0
  42. package/src/entrypoint.js +12 -0
  43. package/src/memory.d.ts +1 -0
  44. package/src/memoryManager.d.ts +1 -0
  45. package/src/memoryManager.js +10 -6
  46. package/src/modelIds.d.ts +2 -0
  47. package/src/outputStore.d.ts +4 -0
  48. package/src/providers/acp.js +320 -299
  49. package/src/providers/acp.ts +360 -0
  50. package/src/providers/antigravity.js +387 -278
  51. package/src/providers/antigravity.ts +450 -0
  52. package/src/providers/base.d.ts +68 -0
  53. package/src/providers/factory.d.ts +1 -0
  54. package/src/provisioning/capabilityProvisioner.d.ts +2 -0
  55. package/src/sandbox.d.ts +1 -0
  56. package/src/sessionJournal.js +14 -1
  57. package/src/sessionJournal.ts +21 -1
  58. package/src/skillsManager.d.ts +3 -0
  59. package/src/slopDetector.d.ts +3 -0
  60. package/src/taskBuffer.d.ts +1 -0
  61. package/src/tokenTracker.d.ts +1 -0
  62. package/src/toolPacks.d.ts +8 -0
  63. package/src/tools/registry.d.ts +4 -0
  64. package/src/tui/chatRenderer.js +148 -8
  65. package/src/tui/clipboardSync.js +36 -0
  66. package/src/tui/clipboardSync.ts +36 -0
  67. package/src/tui/dialogs.js +15 -2
  68. package/src/tui/home.js +2 -1
  69. package/src/tui/modelPicker.js +254 -0
  70. package/src/tui/modelPicker.ts +318 -0
  71. package/src/tui/prompt.js +90 -8
  72. package/src/tui/selectList.js +20 -0
  73. package/src/tui/sessionPicker.js +185 -0
  74. package/src/tui/sessionPicker.ts +259 -0
  75. package/src/tui/stageSurface.js +9 -0
  76. package/src/tui/statusLine.js +5 -5
@@ -0,0 +1,193 @@
1
+ // Codex Continuum Adapter: reads threads from ~/.codex/thread_history_1.sqlite.
2
+ // Authorship: Strict TypeScript (Causyne Agent).
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { BaseContinuumAdapter, isSafeIdentifier } from './base.js';
9
+ import type { ContinuumSessionSummary, ContinuumSessionDetail, ContinuumMessage } from '../types.js';
10
+ import { cleanUserText, cleanAssistantText, deriveSessionTitle } from '../sanitizer.js';
11
+
12
+ function extractCodexContent(content: unknown): string {
13
+ if (typeof content === 'string') return content;
14
+ if (Array.isArray(content)) {
15
+ return content
16
+ .map((c: unknown) => {
17
+ if (typeof c === 'string') return c;
18
+ if (c && typeof c === 'object' && 'text' in c && typeof (c as { text?: unknown }).text === 'string') {
19
+ return (c as { text: string }).text;
20
+ }
21
+ return '';
22
+ })
23
+ .filter(Boolean)
24
+ .join('\n');
25
+ }
26
+ return '';
27
+ }
28
+
29
+ export class CodexAdapter extends BaseContinuumAdapter {
30
+ readonly platform = 'codex' as const;
31
+ readonly label = 'Codex';
32
+
33
+ private readonly dbPath = path.join(os.homedir(), '.codex/thread_history_1.sqlite');
34
+
35
+ isAvailable(): boolean {
36
+ return fs.existsSync(this.dbPath);
37
+ }
38
+
39
+ async listSessions(limit = 100): Promise<ContinuumSessionSummary[]> {
40
+ if (!this.isAvailable()) return [];
41
+
42
+ let db: DatabaseSync | null = null;
43
+ try {
44
+ db = new DatabaseSync(this.dbPath, { readOnly: true });
45
+ const rows = db.prepare(`
46
+ SELECT thread_id,
47
+ MIN(created_at_ms) as first_created,
48
+ MAX(created_at_ms) as last_updated,
49
+ COUNT(*) as total_items
50
+ FROM thread_items
51
+ GROUP BY thread_id
52
+ ORDER BY last_updated DESC
53
+ LIMIT ?
54
+ `).all(limit) as Array<{
55
+ thread_id: string;
56
+ first_created: number;
57
+ last_updated: number;
58
+ total_items: number;
59
+ }>;
60
+
61
+ const summaries: ContinuumSessionSummary[] = [];
62
+
63
+ for (const row of rows) {
64
+ let title = `Codex Thread ${row.thread_id.slice(0, 8)}`;
65
+ let snippet = '';
66
+
67
+ try {
68
+ const firstMsg = db.prepare(`
69
+ SELECT item_json FROM thread_items
70
+ WHERE thread_id = ? AND item_type = 'userMessage'
71
+ ORDER BY rollout_ordinal ASC
72
+ LIMIT 1
73
+ `).get(row.thread_id) as { item_json: string } | undefined;
74
+
75
+ if (firstMsg?.item_json) {
76
+ const parsed = JSON.parse(firstMsg.item_json);
77
+ const fullText = extractCodexContent(parsed.content);
78
+ if (fullText) {
79
+ title = deriveSessionTitle(fullText, title);
80
+ snippet = fullText.slice(0, 100);
81
+ }
82
+ }
83
+ } catch {
84
+ // Use default title
85
+ }
86
+
87
+ summaries.push({
88
+ id: `codex:${row.thread_id}`,
89
+ sourcePlatform: this.platform,
90
+ sourceLabel: this.label,
91
+ title,
92
+ workspacePath: '',
93
+ updatedAt: row.last_updated || row.first_created || Date.now(),
94
+ messageCount: row.total_items,
95
+ snippet
96
+ });
97
+ }
98
+
99
+ return summaries;
100
+ } catch {
101
+ return [];
102
+ } finally {
103
+ if (db) {
104
+ try { db.close(); } catch { /* ignore */ }
105
+ }
106
+ }
107
+ }
108
+
109
+ async getSession(id: string): Promise<ContinuumSessionDetail | null> {
110
+ if (!this.isAvailable()) return null;
111
+ const rawId = id.startsWith('codex:') ? id.slice('codex:'.length) : id;
112
+ if (!isSafeIdentifier(rawId)) {
113
+ return null;
114
+ }
115
+
116
+ let db: DatabaseSync | null = null;
117
+ try {
118
+ db = new DatabaseSync(this.dbPath, { readOnly: true });
119
+ const items = db.prepare(`
120
+ SELECT item_type, created_at_ms, item_json
121
+ FROM thread_items
122
+ WHERE thread_id = ?
123
+ ORDER BY rollout_ordinal ASC, created_at_ms ASC
124
+ `).all(rawId) as Array<{
125
+ item_type: string;
126
+ created_at_ms: number;
127
+ item_json: string;
128
+ }>;
129
+
130
+ if (items.length === 0) return null;
131
+
132
+ const messages: ContinuumMessage[] = [];
133
+ let sessionTitle = `Codex Thread ${rawId.slice(0, 8)}`;
134
+
135
+ for (const item of items) {
136
+ if (!item.item_json) continue;
137
+ try {
138
+ const parsed = JSON.parse(item.item_json);
139
+ const type = item.item_type || parsed.type;
140
+ const text = extractCodexContent(parsed.content);
141
+
142
+ if (type === 'userMessage' || type === 'user') {
143
+ const cleaned = cleanUserText(text);
144
+ if (cleaned) {
145
+ if (messages.length === 0) {
146
+ sessionTitle = deriveSessionTitle(cleaned, sessionTitle);
147
+ }
148
+ messages.push({
149
+ role: 'user',
150
+ content: cleaned,
151
+ timestamp: item.created_at_ms
152
+ });
153
+ }
154
+ } else if (type === 'agentMessage' || type === 'assistantMessage' || type === 'assistant') {
155
+ const cleaned = cleanAssistantText(text);
156
+ if (cleaned) {
157
+ messages.push({
158
+ role: 'assistant',
159
+ content: cleaned,
160
+ timestamp: item.created_at_ms
161
+ });
162
+ }
163
+ }
164
+ } catch {
165
+ // Skip corrupt item
166
+ }
167
+ }
168
+
169
+ if (messages.length === 0) return null;
170
+
171
+ const firstItem = items[0];
172
+ const lastItem = items[items.length - 1];
173
+
174
+ return {
175
+ id: `codex:${rawId}`,
176
+ sourcePlatform: this.platform,
177
+ sourceLabel: this.label,
178
+ title: sessionTitle,
179
+ workspacePath: '',
180
+ updatedAt: lastItem?.created_at_ms || firstItem?.created_at_ms || Date.now(),
181
+ messageCount: messages.length,
182
+ snippet: messages[0]?.content.slice(0, 100) || '',
183
+ messages
184
+ };
185
+ } catch {
186
+ return null;
187
+ } finally {
188
+ if (db) {
189
+ try { db.close(); } catch { /* ignore */ }
190
+ }
191
+ }
192
+ }
193
+ }
@@ -0,0 +1,134 @@
1
+ // OpenCode Continuum Adapter: reads sessions from ~/.local/share/opencode/opencode.db.
2
+ // Authorship: Strict TypeScript (Causyne Agent).
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import { DatabaseSync } from 'node:sqlite';
7
+ import { BaseContinuumAdapter, isSafeIdentifier } from './base.js';
8
+ import { cleanUserText, cleanAssistantText } from '../sanitizer.js';
9
+ export class OpenCodeAdapter extends BaseContinuumAdapter {
10
+ platform = 'opencode';
11
+ label = 'OpenCode';
12
+ dbPath = path.join(os.homedir(), '.local/share/opencode/opencode.db');
13
+ isAvailable() {
14
+ return fs.existsSync(this.dbPath);
15
+ }
16
+ async listSessions(limit = 100) {
17
+ if (!this.isAvailable())
18
+ return [];
19
+ let db = null;
20
+ try {
21
+ db = new DatabaseSync(this.dbPath, { readOnly: true });
22
+ const rows = db.prepare(`
23
+ SELECT id, title, time_created, time_updated, directory
24
+ FROM session
25
+ ORDER BY time_updated DESC
26
+ LIMIT ?
27
+ `).all(limit);
28
+ return rows.map(r => ({
29
+ id: `opencode:${r.id}`,
30
+ sourcePlatform: this.platform,
31
+ sourceLabel: this.label,
32
+ title: r.title || 'Untitled Session',
33
+ workspacePath: r.directory || '',
34
+ updatedAt: r.time_updated || r.time_created || Date.now(),
35
+ messageCount: 1,
36
+ snippet: `OpenCode workspace: ${path.basename(r.directory || '')}`
37
+ }));
38
+ }
39
+ catch {
40
+ return [];
41
+ }
42
+ finally {
43
+ if (db) {
44
+ try {
45
+ db.close();
46
+ }
47
+ catch { /* ignore */ }
48
+ }
49
+ }
50
+ }
51
+ async getSession(id) {
52
+ if (!this.isAvailable())
53
+ return null;
54
+ const rawId = id.startsWith('opencode:') ? id.slice('opencode:'.length) : id;
55
+ if (!isSafeIdentifier(rawId)) {
56
+ return null;
57
+ }
58
+ let db = null;
59
+ try {
60
+ db = new DatabaseSync(this.dbPath, { readOnly: true });
61
+ const sessionRow = db.prepare(`
62
+ SELECT id, title, time_created, time_updated, directory
63
+ FROM session
64
+ WHERE id = ?
65
+ `).get(rawId);
66
+ if (!sessionRow) {
67
+ return null;
68
+ }
69
+ const messageRows = db.prepare(`
70
+ SELECT m.id, json_extract(m.data, '$.role') as role,
71
+ m.time_created,
72
+ json_extract(p.data, '$.type') as ptype,
73
+ json_extract(p.data, '$.text') as ptext
74
+ FROM message m
75
+ JOIN part p ON m.id = p.message_id
76
+ WHERE m.session_id = ? AND json_extract(p.data, '$.type') = 'text'
77
+ ORDER BY m.time_created ASC, p.id ASC
78
+ `).all(rawId);
79
+ // Group multi-part messages into unified turns
80
+ const grouped = new Map();
81
+ for (const row of messageRows) {
82
+ if (!row.ptext || !row.ptext.trim())
83
+ continue;
84
+ const existing = grouped.get(row.id);
85
+ if (existing) {
86
+ existing.texts.push(row.ptext);
87
+ }
88
+ else {
89
+ grouped.set(row.id, {
90
+ role: row.role === 'user' ? 'user' : 'assistant',
91
+ time: row.time_created,
92
+ texts: [row.ptext]
93
+ });
94
+ }
95
+ }
96
+ const messages = [];
97
+ for (const item of grouped.values()) {
98
+ const joined = item.texts.join('\n');
99
+ const cleaned = item.role === 'user' ? cleanUserText(joined) : cleanAssistantText(joined);
100
+ if (cleaned) {
101
+ messages.push({
102
+ role: item.role,
103
+ content: cleaned,
104
+ timestamp: item.time
105
+ });
106
+ }
107
+ }
108
+ if (messages.length === 0)
109
+ return null;
110
+ return {
111
+ id: `opencode:${sessionRow.id}`,
112
+ sourcePlatform: this.platform,
113
+ sourceLabel: this.label,
114
+ title: sessionRow.title || 'Untitled Session',
115
+ workspacePath: sessionRow.directory || '',
116
+ updatedAt: sessionRow.time_updated || sessionRow.time_created,
117
+ messageCount: messages.length,
118
+ snippet: messages[0]?.content.slice(0, 100) || '',
119
+ messages
120
+ };
121
+ }
122
+ catch {
123
+ return null;
124
+ }
125
+ finally {
126
+ if (db) {
127
+ try {
128
+ db.close();
129
+ }
130
+ catch { /* ignore */ }
131
+ }
132
+ }
133
+ }
134
+ }
@@ -0,0 +1,153 @@
1
+ // OpenCode Continuum Adapter: reads sessions from ~/.local/share/opencode/opencode.db.
2
+ // Authorship: Strict TypeScript (Causyne Agent).
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { BaseContinuumAdapter, isSafeIdentifier } from './base.js';
9
+ import type { ContinuumSessionSummary, ContinuumSessionDetail, ContinuumMessage } from '../types.js';
10
+ import { cleanUserText, cleanAssistantText } from '../sanitizer.js';
11
+
12
+ export class OpenCodeAdapter extends BaseContinuumAdapter {
13
+ readonly platform = 'opencode' as const;
14
+ readonly label = 'OpenCode';
15
+
16
+ private readonly dbPath = path.join(os.homedir(), '.local/share/opencode/opencode.db');
17
+
18
+ isAvailable(): boolean {
19
+ return fs.existsSync(this.dbPath);
20
+ }
21
+
22
+ async listSessions(limit = 100): Promise<ContinuumSessionSummary[]> {
23
+ if (!this.isAvailable()) return [];
24
+
25
+ let db: DatabaseSync | null = null;
26
+ try {
27
+ db = new DatabaseSync(this.dbPath, { readOnly: true });
28
+ const rows = db.prepare(`
29
+ SELECT id, title, time_created, time_updated, directory
30
+ FROM session
31
+ ORDER BY time_updated DESC
32
+ LIMIT ?
33
+ `).all(limit) as Array<{
34
+ id: string;
35
+ title: string;
36
+ time_created: number;
37
+ time_updated: number;
38
+ directory: string;
39
+ }>;
40
+
41
+ return rows.map(r => ({
42
+ id: `opencode:${r.id}`,
43
+ sourcePlatform: this.platform,
44
+ sourceLabel: this.label,
45
+ title: r.title || 'Untitled Session',
46
+ workspacePath: r.directory || '',
47
+ updatedAt: r.time_updated || r.time_created || Date.now(),
48
+ messageCount: 1,
49
+ snippet: `OpenCode workspace: ${path.basename(r.directory || '')}`
50
+ }));
51
+ } catch {
52
+ return [];
53
+ } finally {
54
+ if (db) {
55
+ try { db.close(); } catch { /* ignore */ }
56
+ }
57
+ }
58
+ }
59
+
60
+ async getSession(id: string): Promise<ContinuumSessionDetail | null> {
61
+ if (!this.isAvailable()) return null;
62
+ const rawId = id.startsWith('opencode:') ? id.slice('opencode:'.length) : id;
63
+ if (!isSafeIdentifier(rawId)) {
64
+ return null;
65
+ }
66
+
67
+ let db: DatabaseSync | null = null;
68
+ try {
69
+ db = new DatabaseSync(this.dbPath, { readOnly: true });
70
+ const sessionRow = db.prepare(`
71
+ SELECT id, title, time_created, time_updated, directory
72
+ FROM session
73
+ WHERE id = ?
74
+ `).get(rawId) as {
75
+ id: string;
76
+ title: string;
77
+ time_created: number;
78
+ time_updated: number;
79
+ directory: string;
80
+ } | undefined;
81
+
82
+ if (!sessionRow) {
83
+ return null;
84
+ }
85
+
86
+ const messageRows = db.prepare(`
87
+ SELECT m.id, json_extract(m.data, '$.role') as role,
88
+ m.time_created,
89
+ json_extract(p.data, '$.type') as ptype,
90
+ json_extract(p.data, '$.text') as ptext
91
+ FROM message m
92
+ JOIN part p ON m.id = p.message_id
93
+ WHERE m.session_id = ? AND json_extract(p.data, '$.type') = 'text'
94
+ ORDER BY m.time_created ASC, p.id ASC
95
+ `).all(rawId) as Array<{
96
+ id: string;
97
+ role: string;
98
+ time_created: number;
99
+ ptype: string;
100
+ ptext: string;
101
+ }>;
102
+
103
+ // Group multi-part messages into unified turns
104
+ const grouped = new Map<string, { role: 'user' | 'assistant'; time: number; texts: string[] }>();
105
+ for (const row of messageRows) {
106
+ if (!row.ptext || !row.ptext.trim()) continue;
107
+ const existing = grouped.get(row.id);
108
+ if (existing) {
109
+ existing.texts.push(row.ptext);
110
+ } else {
111
+ grouped.set(row.id, {
112
+ role: row.role === 'user' ? 'user' : 'assistant',
113
+ time: row.time_created,
114
+ texts: [row.ptext]
115
+ });
116
+ }
117
+ }
118
+
119
+ const messages: ContinuumMessage[] = [];
120
+ for (const item of grouped.values()) {
121
+ const joined = item.texts.join('\n');
122
+ const cleaned = item.role === 'user' ? cleanUserText(joined) : cleanAssistantText(joined);
123
+ if (cleaned) {
124
+ messages.push({
125
+ role: item.role,
126
+ content: cleaned,
127
+ timestamp: item.time
128
+ });
129
+ }
130
+ }
131
+
132
+ if (messages.length === 0) return null;
133
+
134
+ return {
135
+ id: `opencode:${sessionRow.id}`,
136
+ sourcePlatform: this.platform,
137
+ sourceLabel: this.label,
138
+ title: sessionRow.title || 'Untitled Session',
139
+ workspacePath: sessionRow.directory || '',
140
+ updatedAt: sessionRow.time_updated || sessionRow.time_created,
141
+ messageCount: messages.length,
142
+ snippet: messages[0]?.content.slice(0, 100) || '',
143
+ messages
144
+ };
145
+ } catch {
146
+ return null;
147
+ } finally {
148
+ if (db) {
149
+ try { db.close(); } catch { /* ignore */ }
150
+ }
151
+ }
152
+ }
153
+ }
@@ -0,0 +1,54 @@
1
+ // Continuum Context Compactor: protects token budgets and preserves Root Anchor Intent.
2
+ // Authorship: Strict TypeScript (Causyne Agent).
3
+ /**
4
+ * Compact a long multi-turn peer conversation into an optimal context window
5
+ * without losing root intention or recent critical decisions.
6
+ */
7
+ export function compactContinuumMessages(messages, options = {}) {
8
+ const maxTurns = options.maxTurns ?? 30;
9
+ const recentTurns = options.recentTurns ?? 12;
10
+ if (messages.length <= maxTurns) {
11
+ return prefixHandshake(messages, options);
12
+ }
13
+ // Find root anchor (first user message)
14
+ const rootIndex = messages.findIndex(m => m.role === 'user');
15
+ const rootMessage = rootIndex !== -1
16
+ ? messages[rootIndex]
17
+ : { role: 'user', content: 'Initial user turn' };
18
+ const recentStart = messages.length - recentTurns;
19
+ const recent = messages.slice(recentStart);
20
+ // If the root intent is already within the recent window, simply return recent
21
+ if (rootIndex !== -1 && rootIndex >= recentStart) {
22
+ return prefixHandshake(recent, options);
23
+ }
24
+ // Summarize middle turns between root and recent
25
+ const middleStart = rootIndex !== -1 ? rootIndex + 1 : 0;
26
+ const middleEnd = recentStart;
27
+ const middleCount = Math.max(0, middleEnd - middleStart);
28
+ const middleSummaryText = `[Continuum Context Condensation]\n` +
29
+ `Preserved initial root intent and the last ${recent.length} active turns.\n` +
30
+ `${middleCount} intermediate turns were compressed. ` +
31
+ `Original agent: ${options.platform || 'peer agent'}, topic: "${options.sourceTitle || 'Untitled'}".`;
32
+ const condensedMiddle = {
33
+ role: 'system',
34
+ content: middleSummaryText
35
+ };
36
+ const compacted = [
37
+ rootMessage,
38
+ condensedMiddle,
39
+ ...recent
40
+ ];
41
+ return prefixHandshake(compacted, options);
42
+ }
43
+ function prefixHandshake(messages, options) {
44
+ const platformLabel = options.platform ? options.platform.toUpperCase() : 'PEER AGENT';
45
+ const header = `[Continuum Handshake · Adopted from ${platformLabel}]\n` +
46
+ `Session: "${options.sourceTitle || 'Untitled'}"\n` +
47
+ `Original workspace: ${options.originalWorkspace || '(unspecified)'}\n` +
48
+ `Status: Adopted into Causyne Agent foreground session. Seamlessly continue the user's objective.`;
49
+ const anchorMessage = {
50
+ role: 'system',
51
+ content: header
52
+ };
53
+ return [anchorMessage, ...messages];
54
+ }
@@ -0,0 +1,83 @@
1
+ // Continuum Context Compactor: protects token budgets and preserves Root Anchor Intent.
2
+ // Authorship: Strict TypeScript (Causyne Agent).
3
+
4
+ import type { ContinuumMessage, AgentPlatform } from './types.js';
5
+
6
+ export interface CompactionOptions {
7
+ maxTurns?: number;
8
+ recentTurns?: number;
9
+ platform?: AgentPlatform;
10
+ sourceTitle?: string;
11
+ originalWorkspace?: string;
12
+ }
13
+
14
+ /**
15
+ * Compact a long multi-turn peer conversation into an optimal context window
16
+ * without losing root intention or recent critical decisions.
17
+ */
18
+ export function compactContinuumMessages(
19
+ messages: ContinuumMessage[],
20
+ options: CompactionOptions = {}
21
+ ): ContinuumMessage[] {
22
+ const maxTurns = options.maxTurns ?? 30;
23
+ const recentTurns = options.recentTurns ?? 12;
24
+
25
+ if (messages.length <= maxTurns) {
26
+ return prefixHandshake(messages, options);
27
+ }
28
+
29
+ // Find root anchor (first user message)
30
+ const rootIndex = messages.findIndex(m => m.role === 'user');
31
+ const rootMessage: ContinuumMessage = rootIndex !== -1
32
+ ? messages[rootIndex]!
33
+ : { role: 'user', content: 'Initial user turn' };
34
+
35
+ const recentStart = messages.length - recentTurns;
36
+ const recent = messages.slice(recentStart);
37
+
38
+ // If the root intent is already within the recent window, simply return recent
39
+ if (rootIndex !== -1 && rootIndex >= recentStart) {
40
+ return prefixHandshake(recent, options);
41
+ }
42
+
43
+ // Summarize middle turns between root and recent
44
+ const middleStart = rootIndex !== -1 ? rootIndex + 1 : 0;
45
+ const middleEnd = recentStart;
46
+ const middleCount = Math.max(0, middleEnd - middleStart);
47
+
48
+ const middleSummaryText = `[Continuum Context Condensation]\n` +
49
+ `Preserved initial root intent and the last ${recent.length} active turns.\n` +
50
+ `${middleCount} intermediate turns were compressed. ` +
51
+ `Original agent: ${options.platform || 'peer agent'}, topic: "${options.sourceTitle || 'Untitled'}".`;
52
+
53
+ const condensedMiddle: ContinuumMessage = {
54
+ role: 'system',
55
+ content: middleSummaryText
56
+ };
57
+
58
+ const compacted: ContinuumMessage[] = [
59
+ rootMessage,
60
+ condensedMiddle,
61
+ ...recent
62
+ ];
63
+
64
+ return prefixHandshake(compacted, options);
65
+ }
66
+
67
+ function prefixHandshake(
68
+ messages: ContinuumMessage[],
69
+ options: CompactionOptions
70
+ ): ContinuumMessage[] {
71
+ const platformLabel = options.platform ? options.platform.toUpperCase() : 'PEER AGENT';
72
+ const header = `[Continuum Handshake · Adopted from ${platformLabel}]\n` +
73
+ `Session: "${options.sourceTitle || 'Untitled'}"\n` +
74
+ `Original workspace: ${options.originalWorkspace || '(unspecified)'}\n` +
75
+ `Status: Adopted into Causyne Agent foreground session. Seamlessly continue the user's objective.`;
76
+
77
+ const anchorMessage: ContinuumMessage = {
78
+ role: 'system',
79
+ content: header
80
+ };
81
+
82
+ return [anchorMessage, ...messages];
83
+ }
@@ -0,0 +1,8 @@
1
+ // Causyne Continuum: Universal Cross-Agent Session Extraction, Inspection & Adoption Engine.
2
+ // Authorship: Strict TypeScript (Causyne Agent).
3
+ export * from './types.js';
4
+ export * from './sanitizer.js';
5
+ export * from './compactor.js';
6
+ export * from './scanner.js';
7
+ export * from './ingest.js';
8
+ export * from './ui/continuumPicker.js';
@@ -0,0 +1,9 @@
1
+ // Causyne Continuum: Universal Cross-Agent Session Extraction, Inspection & Adoption Engine.
2
+ // Authorship: Strict TypeScript (Causyne Agent).
3
+
4
+ export * from './types.js';
5
+ export * from './sanitizer.js';
6
+ export * from './compactor.js';
7
+ export * from './scanner.js';
8
+ export * from './ingest.js';
9
+ export * from './ui/continuumPicker.js';