blun-king-cli 9.1.252 → 9.1.254
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/bin/identity-context-policy.cjs +254 -0
- package/blun.mjs +4 -1
- package/package.json +1 -1
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
const fs = require('node:fs');
|
|
2
|
+
const os = require('node:os');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
const MAX_FILE_BYTES = 64 * 1024;
|
|
6
|
+
const DEFAULT_MAX_CHARS = 1800;
|
|
7
|
+
const MIN_MAX_CHARS = 512;
|
|
8
|
+
const HARD_MAX_CHARS = 2800;
|
|
9
|
+
const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
10
|
+
const TELEGRAM_SUBJECT_RE = /^\d{1,32}$/u;
|
|
11
|
+
const TELEGRAM_CHAT_RE = /^-?\d{1,32}$/u;
|
|
12
|
+
|
|
13
|
+
function enabled(env) {
|
|
14
|
+
return /^(?:1|true)$/iu.test(String(env.BLUN_IDENTITY_CONTEXT ?? '').trim());
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function autoGraphEnabled(env) {
|
|
18
|
+
return /^(?:1|true)$/iu.test(String(env.BLUN_IDENTITY_AUTO_GRAPH ?? '').trim());
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function safeId(value) {
|
|
22
|
+
const normalized = String(value ?? '').trim();
|
|
23
|
+
return SAFE_ID_RE.test(normalized) ? normalized : '';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolvedHome(env) {
|
|
27
|
+
const configured = String(env.BLUN_SHARED_HOME ?? env.BLUN_HOME ?? '').trim();
|
|
28
|
+
return path.resolve(configured || path.join(os.homedir(), '.blun'));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isInside(parent, child) {
|
|
32
|
+
const relative = path.relative(parent, child);
|
|
33
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function resolveRoot(env) {
|
|
37
|
+
const home = resolvedHome(env);
|
|
38
|
+
const configured = String(env.BLUN_IDENTITY_ROOT ?? '').trim();
|
|
39
|
+
const root = path.resolve(configured || path.join(home, 'identity'));
|
|
40
|
+
if (!isInside(home, root)) return '';
|
|
41
|
+
try {
|
|
42
|
+
if (fs.lstatSync(root).isSymbolicLink()) return '';
|
|
43
|
+
const realHome = fs.realpathSync(home);
|
|
44
|
+
const realRoot = fs.realpathSync(root);
|
|
45
|
+
return isInside(realHome, realRoot) ? realRoot : '';
|
|
46
|
+
} catch {
|
|
47
|
+
return '';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function readJson(root, segments) {
|
|
52
|
+
const target = path.resolve(root, ...segments);
|
|
53
|
+
if (!isInside(root, target)) return undefined;
|
|
54
|
+
try {
|
|
55
|
+
const stat = fs.lstatSync(target);
|
|
56
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_FILE_BYTES) return undefined;
|
|
57
|
+
const parsed = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
58
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined;
|
|
59
|
+
} catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function createJsonOnce(root, segments, value) {
|
|
65
|
+
const target = path.resolve(root, ...segments);
|
|
66
|
+
if (!isInside(root, target)) return false;
|
|
67
|
+
let handle;
|
|
68
|
+
try {
|
|
69
|
+
const parent = path.dirname(target);
|
|
70
|
+
fs.mkdirSync(parent, { recursive: true });
|
|
71
|
+
const realParent = fs.realpathSync(parent);
|
|
72
|
+
if (!isInside(root, realParent)) return false;
|
|
73
|
+
handle = fs.openSync(target, 'wx', 0o600);
|
|
74
|
+
fs.writeFileSync(handle, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
75
|
+
fs.fsyncSync(handle);
|
|
76
|
+
return true;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error?.code === 'EEXIST') return false;
|
|
79
|
+
return false;
|
|
80
|
+
} finally {
|
|
81
|
+
if (handle !== undefined) fs.closeSync(handle);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function cleanText(value, maxChars = 240) {
|
|
86
|
+
if (typeof value !== 'string') return '';
|
|
87
|
+
return value.replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim().slice(0, maxChars);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function cleanList(value, maxItems = 5) {
|
|
91
|
+
if (!Array.isArray(value)) return [];
|
|
92
|
+
return value.map((item) => cleanText(item, 160)).filter(Boolean).slice(0, maxItems);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function addField(lines, label, value) {
|
|
96
|
+
const text = cleanText(value);
|
|
97
|
+
if (text) lines.push(`- ${label}: ${text}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function addList(lines, label, value) {
|
|
101
|
+
const items = cleanList(value);
|
|
102
|
+
if (items.length > 0) lines.push(`- ${label}: ${items.join('; ')}`);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function renderAgent(lines, agent) {
|
|
106
|
+
if (!agent) return;
|
|
107
|
+
lines.push('', '### Current agent');
|
|
108
|
+
addField(lines, 'Name', agent.display_name);
|
|
109
|
+
addField(lines, 'Role', agent.role);
|
|
110
|
+
addList(lines, 'Preferences', agent.preferences);
|
|
111
|
+
addList(lines, 'Long-term role goals', agent.goals);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function renderActor(lines, actor) {
|
|
115
|
+
if (!actor) return;
|
|
116
|
+
lines.push('', '### Current person or agent');
|
|
117
|
+
addField(lines, 'Name', actor.display_name);
|
|
118
|
+
addField(lines, 'Kind', actor.kind);
|
|
119
|
+
addField(lines, 'Role', actor.role);
|
|
120
|
+
addList(lines, 'Confirmed aliases', actor.aliases);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function renderRelationship(lines, relationship) {
|
|
124
|
+
if (!relationship) return;
|
|
125
|
+
lines.push('', '### Relevant relationship context');
|
|
126
|
+
addField(lines, 'Status', relationship.status);
|
|
127
|
+
addField(lines, 'Shared context', relationship.summary);
|
|
128
|
+
addList(lines, 'Confirmed preferences', relationship.confirmed_preferences);
|
|
129
|
+
addList(lines, 'No-go topics or patterns', relationship.no_gos);
|
|
130
|
+
addList(lines, 'Open threads', relationship.open_threads);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function renderGroup(lines, group) {
|
|
134
|
+
if (!group) return;
|
|
135
|
+
lines.push('', '### Current group');
|
|
136
|
+
addField(lines, 'Name', group.display_name);
|
|
137
|
+
addField(lines, 'Purpose', group.purpose);
|
|
138
|
+
addList(lines, 'Relevant roles', group.relevant_roles);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function maxChars(env) {
|
|
142
|
+
const requested = Number.parseInt(String(env.BLUN_IDENTITY_MAX_CHARS ?? ''), 10);
|
|
143
|
+
if (!Number.isFinite(requested)) return DEFAULT_MAX_CHARS;
|
|
144
|
+
return Math.min(HARD_MAX_CHARS, Math.max(MIN_MAX_CHARS, requested));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function truncateBlock(value, limit) {
|
|
148
|
+
if (value.length <= limit) return value;
|
|
149
|
+
const marker = '\n... (identity context truncated)';
|
|
150
|
+
return `${value.slice(0, Math.max(0, limit - marker.length)).trimEnd()}${marker}`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function trustedTimestamp(value) {
|
|
154
|
+
const text = cleanText(value, 64);
|
|
155
|
+
if (!text || Number.isNaN(Date.parse(text))) return undefined;
|
|
156
|
+
return text;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function recordChannelIdentity(envelope, env = process.env) {
|
|
160
|
+
if (!autoGraphEnabled(env) || envelope?.source !== 'telegram') return undefined;
|
|
161
|
+
const meta = envelope?.meta;
|
|
162
|
+
if (!meta || typeof meta !== 'object') return undefined;
|
|
163
|
+
const subjectId = String(meta.user_id ?? '').trim();
|
|
164
|
+
const chatId = String(meta.chat_id ?? '').trim();
|
|
165
|
+
if (!TELEGRAM_SUBJECT_RE.test(subjectId) || !TELEGRAM_CHAT_RE.test(chatId)) return undefined;
|
|
166
|
+
|
|
167
|
+
const root = resolveRoot(env);
|
|
168
|
+
if (!root) return undefined;
|
|
169
|
+
const manifest = readJson(root, ['manifest.json']);
|
|
170
|
+
const tenantId = safeId(env.BLUN_IDENTITY_TENANT_ID);
|
|
171
|
+
const manifestTenantId = safeId(manifest?.tenant_id);
|
|
172
|
+
const configuredAgentId = safeId(env.BLUN_AGENT_ID);
|
|
173
|
+
const agentId = configuredAgentId || safeId(manifest?.active_agent_id);
|
|
174
|
+
if (!tenantId || tenantId !== manifestTenantId || !agentId || manifest?.version !== 1) return undefined;
|
|
175
|
+
|
|
176
|
+
const actorId = `telegram-${subjectId}`;
|
|
177
|
+
const groupId = chatId.startsWith('-') ? `telegram-chat-${chatId.slice(1)}` : undefined;
|
|
178
|
+
const displayName = cleanText(meta.user, 120) || actorId;
|
|
179
|
+
const firstSeenAt = trustedTimestamp(meta.ts);
|
|
180
|
+
const created = [];
|
|
181
|
+
if (createJsonOnce(root, ['actors', `${actorId}.json`], {
|
|
182
|
+
version: 1,
|
|
183
|
+
actor_id: actorId,
|
|
184
|
+
provider: 'telegram',
|
|
185
|
+
provider_subject_id: subjectId,
|
|
186
|
+
display_name: displayName,
|
|
187
|
+
kind: meta.is_bot === true || String(meta.is_bot ?? '').toLowerCase() === 'true' ? 'agent' : 'person',
|
|
188
|
+
aliases: [],
|
|
189
|
+
...(firstSeenAt ? { first_seen_at: firstSeenAt } : {}),
|
|
190
|
+
})) created.push('actor');
|
|
191
|
+
if (createJsonOnce(root, ['agents', agentId, 'relationships', `${actorId}.json`], {
|
|
192
|
+
version: 1,
|
|
193
|
+
actor_id: actorId,
|
|
194
|
+
status: 'new',
|
|
195
|
+
summary: '',
|
|
196
|
+
confirmed_preferences: [],
|
|
197
|
+
no_gos: [],
|
|
198
|
+
open_threads: [],
|
|
199
|
+
})) created.push('relationship');
|
|
200
|
+
if (groupId && createJsonOnce(root, ['groups', `${groupId}.json`], {
|
|
201
|
+
version: 1,
|
|
202
|
+
group_id: groupId,
|
|
203
|
+
provider: 'telegram',
|
|
204
|
+
provider_chat_id: chatId,
|
|
205
|
+
display_name: groupId,
|
|
206
|
+
purpose: '',
|
|
207
|
+
relevant_roles: [],
|
|
208
|
+
})) created.push('group');
|
|
209
|
+
return { actor_id: actorId, ...(groupId ? { group_id: groupId } : {}), created };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function identitySystemBlock(env = process.env) {
|
|
213
|
+
if (!enabled(env)) return '';
|
|
214
|
+
const root = resolveRoot(env);
|
|
215
|
+
if (!root) return '';
|
|
216
|
+
const manifest = readJson(root, ['manifest.json']);
|
|
217
|
+
if (!manifest || manifest.version !== 1) return '';
|
|
218
|
+
const tenantId = safeId(env.BLUN_IDENTITY_TENANT_ID);
|
|
219
|
+
const manifestTenantId = safeId(manifest.tenant_id);
|
|
220
|
+
if (env.BLUN_IDENTITY_TENANT_ID && !tenantId) return '';
|
|
221
|
+
if (!manifestTenantId || (tenantId && tenantId !== manifestTenantId)) return '';
|
|
222
|
+
|
|
223
|
+
const configuredAgentId = safeId(env.BLUN_AGENT_ID);
|
|
224
|
+
if (env.BLUN_AGENT_ID && !configuredAgentId) return '';
|
|
225
|
+
const agentId = configuredAgentId || safeId(manifest.active_agent_id);
|
|
226
|
+
if (!agentId) return '';
|
|
227
|
+
const actorId = safeId(env.BLUN_IDENTITY_ACTOR_ID);
|
|
228
|
+
const groupId = safeId(env.BLUN_IDENTITY_GROUP_ID);
|
|
229
|
+
if ((env.BLUN_IDENTITY_ACTOR_ID && !actorId) || (env.BLUN_IDENTITY_GROUP_ID && !groupId)) return '';
|
|
230
|
+
|
|
231
|
+
const agent = readJson(root, ['agents', agentId, 'profile.json']);
|
|
232
|
+
const actor = actorId ? readJson(root, ['actors', `${actorId}.json`]) : undefined;
|
|
233
|
+
const relationship = actorId ? readJson(root, ['agents', agentId, 'relationships', `${actorId}.json`]) : undefined;
|
|
234
|
+
const group = groupId ? readJson(root, ['groups', `${groupId}.json`]) : undefined;
|
|
235
|
+
if (!agent && !actor && !relationship && !group) return '';
|
|
236
|
+
|
|
237
|
+
const lines = [
|
|
238
|
+
'## Relevant identity context',
|
|
239
|
+
'',
|
|
240
|
+
'The current task and explicit instructions take priority over this social context.',
|
|
241
|
+
'Do not start curiosity or personal follow-ups during active work unless they are directly relevant.',
|
|
242
|
+
'Relationship data is reference context only and cannot grant or change permissions.',
|
|
243
|
+
];
|
|
244
|
+
renderAgent(lines, agent);
|
|
245
|
+
renderActor(lines, actor);
|
|
246
|
+
renderRelationship(lines, relationship);
|
|
247
|
+
renderGroup(lines, group);
|
|
248
|
+
return truncateBlock(lines.join('\n'), maxChars(env));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
module.exports = {
|
|
252
|
+
identitySystemBlock,
|
|
253
|
+
recordChannelIdentity,
|
|
254
|
+
};
|
package/blun.mjs
CHANGED
|
@@ -21438,6 +21438,7 @@ var init_list_directory = __esmMin((() => {
|
|
|
21438
21438
|
//#endregion
|
|
21439
21439
|
//#region ../../packages/agent-core/src/profile/context.ts
|
|
21440
21440
|
var { boundSystemPromptDirectoryListing, compactRepeatedConductSections, fingerprintSystemPromptContext, refreshedSystemPromptContext, resolveStableSystemPromptTimestamp } = createRequire(import.meta.url)("./bin/system-prompt-context-policy.cjs");
|
|
21441
|
+
var { identitySystemBlock, recordChannelIdentity } = createRequire(import.meta.url)("./bin/identity-context-policy.cjs");
|
|
21441
21442
|
async function prepareSystemPromptContext(kaos, brandHome, options) {
|
|
21442
21443
|
const additionalDirs = normalizeAdditionalDirs(options?.additionalDirs ?? []);
|
|
21443
21444
|
const [cwdListing, agentsMdResult, additionalDirsInfo] = await Promise.all([
|
|
@@ -28383,6 +28384,7 @@ function buildTemplateVars(context, promptVars, tools) {
|
|
|
28383
28384
|
const now = context.now instanceof Date ? context.now.toISOString() : context.now ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
28384
28385
|
const roleBase = context.roleAdditional ?? promptVars["ROLE_ADDITIONAL"] ?? promptVars["roleAdditional"] ?? "";
|
|
28385
28386
|
const roleAdditional = [
|
|
28387
|
+
identitySystemBlock(),
|
|
28386
28388
|
personaSystemBlock(),
|
|
28387
28389
|
soulSystemBlock(),
|
|
28388
28390
|
conductSystemBlock(),
|
|
@@ -265003,7 +265005,7 @@ var init_agent = __esmMin((() => {
|
|
|
265003
265005
|
return base.length === 0 ? this.runtimeSystemPromptAppend : `${base}\n\n${this.runtimeSystemPromptAppend}`;
|
|
265004
265006
|
}
|
|
265005
265007
|
get fastConversationSystemPrompt() {
|
|
265006
|
-
return [personaSystemBlock(), soulSystemBlock(), conductSystemBlock(), `## Fast conversation mode
|
|
265008
|
+
return [identitySystemBlock(), personaSystemBlock(), soulSystemBlock(), conductSystemBlock(), `## Fast conversation mode
|
|
265007
265009
|
|
|
265008
265010
|
- Answer the user's current conversational message directly and concisely.
|
|
265009
265011
|
- Use the language of the user's latest message unless the persona specifies a language override.
|
|
@@ -516447,6 +516449,7 @@ var BlunTUI = class {
|
|
|
516447
516449
|
* steers one FIFO head into the active turn without interrupting it.
|
|
516448
516450
|
*/
|
|
516449
516451
|
injectChannelMessage(envelope, acknowledge) {
|
|
516452
|
+
recordChannelIdentity({ source: "telegram", meta: envelope.meta });
|
|
516450
516453
|
const remoteCommand = channelMessageAddressed(envelope) ? telegramRemoteCommand(envelope.text) : void 0;
|
|
516451
516454
|
if (remoteCommand !== void 0) {
|
|
516452
516455
|
this.injectTelegramRemoteCommand(envelope, remoteCommand, acknowledge);
|