omp-superagent 0.1.9 → 0.1.10

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/src/setup.ts CHANGED
@@ -125,7 +125,8 @@ async function newConfig(terminal: Terminal, path: string): Promise<{ config: Co
125
125
  if (!selected.length || selected.some(p => !["discord", "telegram", "slack"].includes(p)))
126
126
  throw new Error("Select at least one supported messenger");
127
127
  const raw: Record<string, unknown> = { ...template, command };
128
- for (const platform of ["discord", "telegram", "slack"]) delete raw[platform];
128
+ // Kakao needs an operator-run bridge; add its block manually (docs/kakao-bridge-protocol.md).
129
+ for (const platform of ["discord", "telegram", "slack", "kakao"]) delete raw[platform];
129
130
  const list = async (label: string) => (await terminal.ask(`${label} (comma-separated; empty = deny groups / DM only): `))
130
131
  .split(",").map(s => s.trim()).filter(Boolean);
131
132
  for (const platform of selected) {
package/src/soul.ts ADDED
@@ -0,0 +1,214 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { Inbound, StorePort } from "./contracts";
3
+ import { ownerRoutingProse, transportRoutingProse } from "./topic-history";
4
+
5
+ const dimensions = {
6
+ concept: {
7
+ plain: "",
8
+ editorial: "Use an editorial presentation: distill the relevant points and make distinctions precise within the requested format.",
9
+ mentoring: "Use a mentoring presentation: make the reasoning easy to follow and use a concrete example when it fits the requested format.",
10
+ },
11
+ tone: {
12
+ direct: "Be candid and matter-of-fact without being curt.",
13
+ warm: "Sound warm and approachable without adding filler.",
14
+ neutral: "Use a calm, neutral tone.",
15
+ },
16
+ register: {
17
+ natural: "Match the operator's register.",
18
+ formal: "Use a respectful, formal register (존댓말 in Korean).",
19
+ casual: "Use a relaxed, conversational register.",
20
+ },
21
+ detail: {
22
+ balanced: "Give the context needed to use the answer.",
23
+ brief: "Keep the answer brief unless the operator asks for depth.",
24
+ detailed: "Include relevant context and explanation.",
25
+ },
26
+ structure: {
27
+ "answer-first": "Lead with the answer, result, or blocker.",
28
+ "evidence-first": "Present the key evidence before the conclusion.",
29
+ natural: "Organize the answer naturally for the question.",
30
+ },
31
+ emoji: {
32
+ none: "Do not add decorative emoji.",
33
+ light: "Use an occasional emoji only where it reads naturally.",
34
+ },
35
+ } as const;
36
+
37
+ type Voice = { [D in keyof typeof dimensions]: keyof typeof dimensions[D] };
38
+ const requests = {
39
+ concept: {
40
+ plain: /\b(?:plain|no particular) (?:concept|persona|style)\b|컨셉\s*(?:없이|빼고)|기본\s*컨셉/u,
41
+ editorial: /\b(?:like an? editor|editorial (?:voice|style|approach|concept)|editor(?:-like)? (?:voice|style|approach|concept))\b|(?:편집장|편집자|에디터)\s*(?:처럼|같이|같은|스타일|컨셉|콘셉트?|느낌|말투)/u,
42
+ mentoring: /\b(?:like (?:a|my) (?:mentor|coach)|(?:mentor|coach)(?:-like|ing)? (?:voice|style|approach|concept))\b|(?:멘토|코치|(?:옆자리|옆에 있는|일 잘하는)\s*선배|선배)\s*(?:처럼|같이|같은|스타일|컨셉|콘셉트?|느낌|말투)/u,
43
+ },
44
+ tone: {
45
+ direct: /\b(?:candid|straightforward|matter-of-fact|direct(?:ly)?|blunt(?:ly)?)\b|단도직입|직설적|담백/u,
46
+ warm: /\b(?:warm(?:er|ly)?|friendl(?:y|ier)|approachable)\b|따뜻|친근|다정/u,
47
+ neutral: /\b(?:neutral(?:ly)?|calm(?:ly)?)\b|중립적|차분/u,
48
+ },
49
+ register: {
50
+ natural: /\b(?:my|match my|mirror my) register\b|내 말투에 맞/u,
51
+ formal: /\b(?:formally|respectfully|politely|(?:formal|respectful|polite)(?=\s*(?:[,!.]|$)|\s+(?:tone|language|voice|register|style|replies|and)\b))\b|존댓말|격식\s*있게|예의\s*있게|공손(?:하게|히)/u,
52
+ casual: /\b(?:casual(?:ly)?|informal(?:ly)?|conversational)\b|반말|격식 없이/u,
53
+ },
54
+ detail: {
55
+ balanced: /\bbalanced (?:detail|length)\b|적당한 분량/u,
56
+ brief: /\b(?:brief(?:ly)?|concis(?:e|ely)|shorter|short replies)\b|짧(?:게|고)|간결하게|간단하게/u,
57
+ detailed: /\b(?:detailed|in detail|more detail|thorough(?:ly)?)\b|자세하게|상세하게/u,
58
+ },
59
+ structure: {
60
+ "answer-first": /\b(?:answer|conclusion|result) first\b|(?:결론|결과|답|핵심|요점)\s*(?:부터|을\s*먼저)/u,
61
+ "evidence-first": /\b(?:evidence|reasoning) first\b|근거부터/u,
62
+ natural: /\bnatural (?:structure|order)\b|자연스러운 순서/u,
63
+ },
64
+ emoji: {
65
+ none: /\b(?:no|without) emoji(?:s)?\b|(?:이모지|이모티콘)\s*(?:없이|빼고|금지|쓰지\s*말)/u,
66
+ light: /\b(?:occasional|light|use some) emoji(?:s)?\b|(?:가끔|가벼운)\s*(?:이모지|이모티콘)/u,
67
+ },
68
+ } satisfies { [D in keyof Voice]: Record<Voice[D], RegExp> };
69
+ const defaultVoice = {
70
+ concept: "plain", tone: "direct", register: "natural", detail: "balanced", structure: "answer-first", emoji: "none",
71
+ } satisfies Voice;
72
+ const setting = "soul:reply-voice";
73
+
74
+ export const soulUpdateSchema = Type.Object({
75
+ sourceId: Type.String({ minLength: 1, pattern: "\\S" }),
76
+ }, { additionalProperties: false });
77
+ type SoulUpdate = Partial<Voice> | "reset";
78
+ type Ledger = Pick<StorePort, "getMeta" | "setMeta">;
79
+
80
+ function object(value: unknown): value is Record<string, unknown> {
81
+ return typeof value === "object" && value !== null && !Array.isArray(value);
82
+ }
83
+
84
+ function voicePatch(value: unknown): value is Partial<Voice> {
85
+ return object(value) && Object.keys(value).length > 0 && Object.entries(value).every(([key, choice]) =>
86
+ Object.hasOwn(dimensions, key) && typeof choice === "string" && Object.hasOwn(dimensions[key as keyof Voice], choice));
87
+ }
88
+
89
+ function completeVoice(value: unknown) {
90
+ // Both persisted pre-concept profiles and the first native wire version
91
+ // have all the original fields but no concept.
92
+ if (!voicePatch(value) || Object.keys(defaultVoice).some(key => key !== "concept" && !Object.hasOwn(value, key)))
93
+ throw new Error("Invalid reply voice profile");
94
+ return { ...defaultVoice, ...value };
95
+ }
96
+
97
+ function savedVoice(store: Ledger) {
98
+ const raw = store.getMeta(setting);
99
+ if (raw === null) return { revision: 0, sourceId: null, style: defaultVoice };
100
+ const saved: unknown = JSON.parse(raw);
101
+ if (!object(saved) || Object.keys(saved).length !== 3 || typeof saved.revision !== "number"
102
+ || !Number.isSafeInteger(saved.revision) || saved.revision < 1 || typeof saved.sourceId !== "string" || !saved.sourceId)
103
+ throw new Error("Stored reply voice is invalid");
104
+ return { revision: saved.revision, sourceId: saved.sourceId, style: completeVoice(saved.style) };
105
+ }
106
+
107
+ function startsWithPresentation(text: string): boolean {
108
+ return Object.values(requests).some(choices => Object.values(choices).some(pattern => pattern.exec(text)?.index === 0));
109
+ }
110
+
111
+ function onlyPresentationGrammar(text: string): boolean {
112
+ // Every non-choice word must be reply syntax, not a task, exception, example
113
+ // or time/channel qualifier. This also prevents a negated choice from
114
+ // becoming affirmative just because its vocabulary matched a dimension.
115
+ const english = /\b(?:please|answer|answers|reply|replies|respond|response|responses|explain|use|keep|make|be|your|my|our|the|a|an|it|in|with|and|to|as|more|tone|register|length|style|voice|approach|concept|format)\b/gu;
116
+ const korean = /(?:답변|응답|말투|톤|분량|방식|스타일|컨셉|콘셉트?)(?:으로|은|는|을|를|이|가)?|(?:으로|하게|있게|해서|하고|이며|이고|면서|그리고|또|좀|더|늘|항상|기본적으로|답해|말해|설명해|알려|써|해|바꿔|변경해|설정해|정해|부탁해|부탁드려요|줘|주세요|주라|서|로|게)/gu;
117
+ return !text.replace(english, " ").replace(korean, " ").replace(/[\s,.!,。、]+/gu, "");
118
+ }
119
+
120
+ /** Only unambiguous, supported choices in the original author's own prose are saved. */
121
+ export function soulUpdateIntent(source: Inbound): SoulUpdate | null {
122
+ const headPrefix = /^ {0,3}\/head[ \t]/u;
123
+ const raw = source.text.replace(headPrefix, "");
124
+ const body = raw.trim();
125
+ const prose = transportRoutingProse(source).replace(headPrefix, "").trim();
126
+ const indented = /^[ \t]{4}|^\t/u;
127
+ const addressedText = source.discordOriginalText;
128
+ if (!body || indented.test(raw) || body !== prose || body !== ownerRoutingProse(raw) || /[\r\n??]/u.test(raw)) return null;
129
+ if (addressedText !== undefined) {
130
+ // An addressed message can be normalized by removing only the bot
131
+ // mention, but a voice draft or quoted physical line is not that prose.
132
+ const original = addressedText.replace(/<@!?(\d+)>/gu, (mention, id) => id === source.route.accountId ? " " : mention);
133
+ if (indented.test(addressedText) || /[\r\n]/u.test(addressedText)
134
+ || original.trim().replace(/\s+/gu, " ") !== source.text.trim().replace(/\s+/gu, " ")) return null;
135
+ }
136
+ const labeled = /^(?:soul|말투)\s*:\s*(\S.*)$/iu.exec(body)?.[1];
137
+ const request = labeled ?? body;
138
+ if (/^(?:please\s+)?reset(?:\s+(?:(?:the|your|our)\s+)?(?:soul|reply style|writing style))?(?:\s+to\s+(?:the\s+)?default(?:s)?)?[.!]?$/iu.test(request)
139
+ && (labeled !== undefined || /(?:soul|reply style|writing style)\b/iu.test(request))) return "reset";
140
+ if (/^(?:(?:소울|말투|응답\s*스타일)(?:을|를)?\s+)?(?:기본(?:값|값으로|으로)?\s*(?:초기화해|되돌려|돌려)|초기화(?:해)?)\s*(?:줘|주세요)?[.!]?$/u.test(request)
141
+ && (labeled !== undefined || /^(?:소울|말투|응답\s*스타일)/u.test(request))) return "reset";
142
+ const styleText = request.toLowerCase().replace(/[‘’]/gu, "'");
143
+ // A persistent change must be a direct instruction about this agent's
144
+ // replies. Questions, alternatives, scoped exceptions and examples are
145
+ // not configuration even when they contain a supported phrase.
146
+ if (/\b(?:not|don't|never|instead of|or|could|would|should|can you|if|unless|suppose|imagine|pretend|for example|example of|quote|forwarded|only when|only for|just this|(?:this|the next) (?:thread|task|reply|answer)|(?:he|she|they) (?:said|asked))\b|말고|아니[라면]|않|하지\s*마|말아|만약|가정|상상|척해|예를\s*들|예시|인용|전달받|라고\s*(?:했|하던|쓰|적)|라는\s*(?:요청|문구|말|지시)|라면|해\s*줄래|할\s*수\s*있|어떨까|어때|(?:이번|이|다음)\s*(?:한\s*번|한번|답변|작업|스레드|메시지)(?:에(?:서)?)?만|이번만/u.test(styleText)) return null;
147
+ const englishSetting = /^(?:please\s+)?(?:change|set|update)\s+(?:(?:the|your|our)\s+)?(?:soul|reply style|writing style)\b(?:\s+to)?\s+/u;
148
+ const englishReply = /^(?:please\s+)?(?:(?:answer|reply|respond|explain)\s+(?:(?:in|with|using)\s+(?:(?:a|an|the)\s+)?|(?=like\s|[a-z]+ly\b))|(?:answer|reply|respond)\s+(?=(?:answer|conclusion|result|evidence|reasoning) first\b)|use\s+(?=.*\b(?:tone|register|voice|style|length|format)\b)(?:(?:a|an|the)\s+)?)/u;
149
+ const englishFuture = /^(?:from now on|going forward|from your next reply(?: onward)?|henceforth),?\s+/u;
150
+ const koreanFuture = /^(?:(?:답변은|응답은|말투는)\s+)?(?:앞으로(?:는|도)?|이제부터(?:는)?|지금부터(?:는)?|다음(?:\s*답변)?부터(?:는)?|앞으론|항상|매번)\s+/u;
151
+ const koreanSetting = /^(?:기본\s*)?(?:소울|말투|(?:답변|응답)\s*(?:방식|스타일|말투)|답변\s*컨셉)(?:을|를|은|는)?\s+/u;
152
+ const koreanSetRequest = /(?:바꿔|변경해|설정해|정해)\s*(?:줘|주세요|주라)?[.!]?$/u;
153
+ const koreanReply = /(?:해\s*(?:줘|주세요|주라)?|알려\s*(?:줘|주세요|주라)|부탁(?:해|드려요)?)[.!]?$/u;
154
+ const koreanLead = /^(?:(?:제게|저한테|나한테|뭐든|기본적으로|답변은|응답은|말투는|답변을|응답을|말투를|답변할\s*때(?:는|마다)?|응답할\s*때(?:는|마다)?|유능한|능숙한|좋은|친절한|믿음직한)\s+)*/u;
155
+ const persistentEnglish = styleText.replace(englishFuture, "");
156
+ const persistentKorean = styleText.replace(koreanFuture, "");
157
+ let presentation: string;
158
+ if (labeled !== undefined) presentation = styleText.replace(koreanLead, "");
159
+ else if (englishSetting.test(styleText)) presentation = styleText.replace(englishSetting, "");
160
+ else if (koreanSetting.test(styleText) && koreanSetRequest.test(styleText)) presentation = styleText.replace(koreanSetting, "").replace(koreanLead, "");
161
+ else if (persistentEnglish !== styleText && englishReply.test(persistentEnglish)) presentation = persistentEnglish.replace(englishReply, "");
162
+ else if (persistentKorean !== styleText && koreanReply.test(persistentKorean)) presentation = persistentKorean.replace(koreanLead, "");
163
+ else return null;
164
+ if (labeled === undefined && !startsWithPresentation(presentation)) return null;
165
+ const patch: Record<string, string> = {};
166
+ let remainder = presentation;
167
+ for (const [dimension, choices] of Object.entries(requests)) {
168
+ const matches = Object.entries(choices).filter(([, pattern]) => pattern.test(presentation));
169
+ if (matches.length > 1) return null;
170
+ if (matches[0]) {
171
+ const [choice, pattern] = matches[0];
172
+ patch[dimension] = choice;
173
+ remainder = remainder.replace(new RegExp(pattern.source, "gu"), " ");
174
+ }
175
+ }
176
+ // Do not silently apply only the familiar half of a concept plus style
177
+ // request when the owner named an unsupported concept.
178
+ if (!patch.concept && /\b(?:concept|persona|like an?)\b|컨셉|콘셉트?|처럼|같은\s*느낌/u.test(presentation)) return null;
179
+ return onlyPresentationGrammar(remainder) && voicePatch(patch) ? patch : null;
180
+ }
181
+
182
+ export function soulSourceId(value: unknown): string {
183
+ if (object(value) && Object.keys(value).length === 1 && typeof value.sourceId === "string" && value.sourceId.trim())
184
+ return value.sourceId;
185
+ throw new Error("A reply voice update takes only its original sourceId");
186
+ }
187
+
188
+ export function applySoulUpdate(store: Ledger, sourceId: string, update: SoulUpdate) {
189
+ const current = savedVoice(store);
190
+ if (current.sourceId !== sourceId) {
191
+ const style = update === "reset" ? defaultVoice : { ...current.style, ...update };
192
+ const next = { revision: current.revision + 1, sourceId, style };
193
+ if (!Number.isSafeInteger(next.revision)) throw new Error("Reply voice revision is unavailable");
194
+ store.setMeta(setting, JSON.stringify(next));
195
+ }
196
+ const applied = savedVoice(store);
197
+ return { revision: applied.revision, style: applied.style };
198
+ }
199
+
200
+ export function replyVoiceProfile(store: Ledger, version: 1 | 2 = 2) {
201
+ const { concept, ...base } = savedVoice(store).style;
202
+ return version === 2 ? { ...base, concept } : base;
203
+ }
204
+
205
+ export function renderReplyVoice(value: unknown): string {
206
+ const style = completeVoice(value);
207
+ return [
208
+ "<superagent-reply-voice>",
209
+ "Apply this voice only to prose addressed to the operator. Use their language. Separate verified facts from inference. Task formats, role instructions, permissions and workflows are unchanged.",
210
+ dimensions.concept[style.concept], dimensions.tone[style.tone], dimensions.register[style.register], dimensions.detail[style.detail],
211
+ dimensions.structure[style.structure], dimensions.emoji[style.emoji],
212
+ "</superagent-reply-voice>",
213
+ ].filter(Boolean).join("\n");
214
+ }