sisyo 1.5.0 → 1.6.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/LICENSE +16 -16
- package/README.md +161 -139
- package/bin/sisyo.js +186 -78
- package/package.json +1 -1
- package/templates/.claude/rules/docs.md +19 -19
- package/templates/.claude/skills/gemini-integration/GENERATE.md +111 -0
- package/templates/.claude/skills/gemini-integration/LIVE-VOICE.md +156 -0
- package/templates/.claude/skills/gemini-integration/RAG-EMBEDDING.md +83 -0
- package/templates/.claude/skills/gemini-integration/SKILL.md +149 -0
- package/templates/.claude/skills/gemini-integration/TEXT-CHAT.md +133 -0
- package/templates/.claude/skills/gemini-integration/TROUBLESHOOTING.md +53 -0
- package/templates/.claude/skills/html-docs/SKILL.md +207 -160
- package/templates/.claude/skills/terraform-best-practices/SKILL.md +341 -341
- package/templates/.claude/skills/vibe-docs/SKILL.md +242 -242
- package/templates/SISYO.md +37 -37
- package/templates/docs/99_progress/features.md +7 -7
- package/templates/docs/99_progress/handoff.md +19 -19
- package/templates/docs/99_progress/todo.md +15 -15
- package/templates/docs/MAP.md +26 -26
package/bin/sisyo.js
CHANGED
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
const fs = require("fs");
|
|
4
4
|
const path = require("path");
|
|
5
|
+
const crypto = require("crypto");
|
|
5
6
|
|
|
6
7
|
const RESET = "\x1b[0m";
|
|
7
8
|
const GREEN = "\x1b[32m";
|
|
8
9
|
const YELLOW = "\x1b[33m";
|
|
10
|
+
const RED = "\x1b[31m";
|
|
9
11
|
const CYAN = "\x1b[36m";
|
|
10
12
|
const BOLD = "\x1b[1m";
|
|
11
13
|
const DIM = "\x1b[2m";
|
|
@@ -13,70 +15,129 @@ const DIM = "\x1b[2m";
|
|
|
13
15
|
function log(msg) { console.log(msg); }
|
|
14
16
|
function ok(msg) { log(`${GREEN}+${RESET} ${msg}`); }
|
|
15
17
|
function up(msg) { log(`${YELLOW}~${RESET} ${msg}`); }
|
|
18
|
+
function warn(msg) { log(`${RED}!${RESET} ${msg}`); }
|
|
16
19
|
function info(msg) { log(`${DIM} ${msg}${RESET}`); }
|
|
17
20
|
|
|
18
|
-
|
|
19
|
-
const SYSTEM_FILES = [
|
|
20
|
-
"SISYO.md",
|
|
21
|
-
".claude/rules/docs.md",
|
|
22
|
-
".claude/skills/vibe-docs/SKILL.md",
|
|
23
|
-
];
|
|
21
|
+
const PKG = require(path.join(__dirname, "..", "package.json"));
|
|
24
22
|
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
// Ownership model
|
|
25
|
+
//
|
|
26
|
+
// MANAGED (sisyo-owned) — everything under .claude/ that ships in templates/
|
|
27
|
+
// (rules/docs.md, skills/*). Replaced on --update, but ONLY
|
|
28
|
+
// when the local copy is byte-identical to what sisyo last
|
|
29
|
+
// installed (tracked by hash in the manifest). A locally
|
|
30
|
+
// edited managed file is never overwritten: the new version
|
|
31
|
+
// is written next to it as <file>.sisyo-new instead.
|
|
32
|
+
//
|
|
33
|
+
// USER-OWNED — SISYO.md, CLAUDE.md, docs/**. Created once if missing,
|
|
34
|
+
// never touched again, not even with --force.
|
|
35
|
+
//
|
|
36
|
+
// The manifest (.claude/sisyo.json) records the installed sisyo version and the hash
|
|
37
|
+
// of every managed file as sisyo wrote it.
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
const MANIFEST_REL = ".claude/sisyo.json";
|
|
41
|
+
const NEW_SUFFIX = ".sisyo-new";
|
|
42
|
+
|
|
43
|
+
function toPosix(p) { return p.split(path.sep).join("/"); }
|
|
44
|
+
function isManaged(rel) { return rel.startsWith(".claude/") && rel !== MANIFEST_REL; }
|
|
45
|
+
// Hash with line endings normalized: git autocrlf rewrites LF <-> CRLF on checkout, and
|
|
46
|
+
// that must not make an untouched file look "modified locally".
|
|
47
|
+
function sha256(buf) {
|
|
48
|
+
const text = buf.toString("utf8").replace(/\r\n/g, "\n");
|
|
49
|
+
return crypto.createHash("sha256").update(text).digest("hex");
|
|
50
|
+
}
|
|
51
|
+
function hashFile(p) { return sha256(fs.readFileSync(p)); }
|
|
52
|
+
|
|
53
|
+
function readManifest(target) {
|
|
54
|
+
const p = path.join(target, MANIFEST_REL);
|
|
55
|
+
if (!fs.existsSync(p)) return null;
|
|
56
|
+
try {
|
|
57
|
+
const m = JSON.parse(fs.readFileSync(p, "utf8"));
|
|
58
|
+
return { version: m.version || "unknown", files: m.files || {} };
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function writeManifest(target, files) {
|
|
65
|
+
const p = path.join(target, MANIFEST_REL);
|
|
66
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
67
|
+
const sorted = {};
|
|
68
|
+
for (const k of Object.keys(files).sort()) sorted[k] = files[k];
|
|
69
|
+
fs.writeFileSync(p, JSON.stringify({ version: PKG.version, files: sorted }, null, 2) + "\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function listTemplateFiles(dir, base = dir) {
|
|
73
|
+
const out = [];
|
|
74
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
75
|
+
const full = path.join(dir, entry.name);
|
|
76
|
+
if (entry.isDirectory()) out.push(...listTemplateFiles(full, base));
|
|
77
|
+
else out.push({ rel: toPosix(path.relative(base, full)), src: full });
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
27
80
|
}
|
|
28
81
|
|
|
29
|
-
function ensureClaudeMdImport(target) {
|
|
82
|
+
function ensureClaudeMdImport(target, dryRun) {
|
|
30
83
|
const claudePath = path.join(target, "CLAUDE.md");
|
|
31
84
|
const importLine = "@SISYO.md";
|
|
32
85
|
if (fs.existsSync(claudePath)) {
|
|
33
86
|
const content = fs.readFileSync(claudePath, "utf8");
|
|
34
87
|
if (!content.includes(importLine)) {
|
|
35
|
-
fs.appendFileSync(claudePath, `\n${importLine}\n`);
|
|
88
|
+
if (!dryRun) fs.appendFileSync(claudePath, `\n${importLine}\n`);
|
|
36
89
|
up("CLAUDE.md (added @SISYO.md import)");
|
|
37
90
|
}
|
|
38
91
|
} else {
|
|
39
|
-
fs.writeFileSync(claudePath, `${importLine}\n`);
|
|
92
|
+
if (!dryRun) fs.writeFileSync(claudePath, `${importLine}\n`);
|
|
40
93
|
ok("CLAUDE.md");
|
|
41
94
|
}
|
|
42
95
|
}
|
|
43
96
|
|
|
44
|
-
function
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
info(`skip ${rel} (exists)`);
|
|
59
|
-
}
|
|
60
|
-
continue;
|
|
61
|
-
}
|
|
62
|
-
fs.copyFileSync(srcPath, destPath);
|
|
63
|
-
ok(rel);
|
|
97
|
+
function fillDates(target) {
|
|
98
|
+
const today = new Date().toISOString().split("T")[0];
|
|
99
|
+
const files = [
|
|
100
|
+
"docs/MAP.md",
|
|
101
|
+
"docs/99_progress/handoff.md",
|
|
102
|
+
"docs/99_progress/todo.md",
|
|
103
|
+
"docs/99_progress/features.md",
|
|
104
|
+
];
|
|
105
|
+
for (const rel of files) {
|
|
106
|
+
const p = path.join(target, rel);
|
|
107
|
+
if (!fs.existsSync(p)) continue;
|
|
108
|
+
const content = fs.readFileSync(p, "utf8");
|
|
109
|
+
if (content.includes("YYYY-MM-DD")) {
|
|
110
|
+
fs.writeFileSync(p, content.replace(/YYYY-MM-DD/g, today));
|
|
64
111
|
}
|
|
65
112
|
}
|
|
66
113
|
}
|
|
67
114
|
|
|
115
|
+
function ensureGitignore(target, dryRun) {
|
|
116
|
+
const gitignorePath = path.join(target, ".gitignore");
|
|
117
|
+
if (!fs.existsSync(gitignorePath)) return;
|
|
118
|
+
const gitignore = fs.readFileSync(gitignorePath, "utf8");
|
|
119
|
+
const lines = [];
|
|
120
|
+
if (!gitignore.includes("CLAUDE.local.md")) lines.push("CLAUDE.local.md", ".claude/settings.local.json");
|
|
121
|
+
if (!gitignore.includes(NEW_SUFFIX)) lines.push(`*${NEW_SUFFIX}`);
|
|
122
|
+
if (lines.length === 0) return;
|
|
123
|
+
if (!dryRun) fs.appendFileSync(gitignorePath, "\n# Claude Code local\n" + lines.join("\n") + "\n");
|
|
124
|
+
ok(".gitignore updated");
|
|
125
|
+
}
|
|
126
|
+
|
|
68
127
|
function main() {
|
|
69
128
|
const args = process.argv.slice(2);
|
|
70
129
|
const updateMode = args.includes("--update");
|
|
130
|
+
const force = args.includes("--force");
|
|
131
|
+
const dryRun = args.includes("--dry-run");
|
|
71
132
|
const targetDir = args.find(a => !a.startsWith("-")) || ".";
|
|
72
133
|
const target = path.resolve(targetDir);
|
|
73
134
|
const templatesDir = path.join(__dirname, "..", "templates");
|
|
74
135
|
|
|
75
136
|
log("");
|
|
76
137
|
if (updateMode) {
|
|
77
|
-
log(`${BOLD}${CYAN}sisyo${RESET} ${DIM}
|
|
138
|
+
log(`${BOLD}${CYAN}sisyo${RESET} ${DIM}v${PKG.version} — updating managed files${force ? " (force)" : ""}${dryRun ? " (dry-run)" : ""}${RESET}`);
|
|
78
139
|
} else {
|
|
79
|
-
log(`${BOLD}${CYAN}sisyo${RESET} ${DIM}Smart docs for Claude Code${RESET}`);
|
|
140
|
+
log(`${BOLD}${CYAN}sisyo${RESET} ${DIM}v${PKG.version} — Smart docs for Claude Code${dryRun ? " (dry-run)" : ""}${RESET}`);
|
|
80
141
|
}
|
|
81
142
|
log("");
|
|
82
143
|
|
|
@@ -85,69 +146,107 @@ function main() {
|
|
|
85
146
|
process.exit(1);
|
|
86
147
|
}
|
|
87
148
|
|
|
88
|
-
|
|
89
|
-
|
|
149
|
+
const manifest = readManifest(target);
|
|
150
|
+
const prevFiles = manifest ? manifest.files : {};
|
|
151
|
+
const nextFiles = {};
|
|
152
|
+
const conflicts = [];
|
|
153
|
+
let updated = 0, added = 0, unchanged = 0;
|
|
154
|
+
|
|
155
|
+
if (updateMode && manifest) info(`installed: v${manifest.version} → v${PKG.version}`);
|
|
156
|
+
if (updateMode && !manifest) {
|
|
157
|
+
info("no manifest found (installed before v1.6). Files that differ from the new");
|
|
158
|
+
info("templates are treated as locally modified — review *.sisyo-new or use --force.");
|
|
159
|
+
}
|
|
90
160
|
|
|
91
|
-
|
|
92
|
-
ensureClaudeMdImport(target);
|
|
161
|
+
const templates = listTemplateFiles(templatesDir);
|
|
93
162
|
|
|
94
|
-
|
|
95
|
-
|
|
163
|
+
for (const { rel, src } of templates) {
|
|
164
|
+
const dest = path.join(target, rel);
|
|
165
|
+
const managed = isManaged(rel);
|
|
166
|
+
const srcBuf = fs.readFileSync(src);
|
|
167
|
+
const srcHash = sha256(srcBuf);
|
|
96
168
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
let mapContent = fs.readFileSync(mapPath, "utf8");
|
|
102
|
-
if (mapContent.includes("YYYY-MM-DD")) {
|
|
103
|
-
mapContent = mapContent.replace(/YYYY-MM-DD/g, today);
|
|
104
|
-
fs.writeFileSync(mapPath, mapContent);
|
|
169
|
+
if (!fs.existsSync(dest)) {
|
|
170
|
+
if (!dryRun) {
|
|
171
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
172
|
+
fs.writeFileSync(dest, srcBuf);
|
|
105
173
|
}
|
|
174
|
+
if (managed) nextFiles[rel] = srcHash;
|
|
175
|
+
ok(rel);
|
|
176
|
+
added++;
|
|
177
|
+
continue;
|
|
106
178
|
}
|
|
107
179
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if (content.includes("YYYY-MM-DD")) {
|
|
112
|
-
content = content.replace(/YYYY-MM-DD/g, today);
|
|
113
|
-
fs.writeFileSync(handoffPath, content);
|
|
114
|
-
}
|
|
180
|
+
if (!managed) {
|
|
181
|
+
info(`skip ${rel} (yours)`);
|
|
182
|
+
continue;
|
|
115
183
|
}
|
|
116
184
|
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
185
|
+
const curHash = hashFile(dest);
|
|
186
|
+
const newPath = dest + NEW_SUFFIX;
|
|
187
|
+
|
|
188
|
+
if (curHash === srcHash) {
|
|
189
|
+
nextFiles[rel] = srcHash;
|
|
190
|
+
unchanged++;
|
|
191
|
+
if (fs.existsSync(newPath) && !dryRun) fs.unlinkSync(newPath); // resolved by hand
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (!updateMode) {
|
|
196
|
+
info(`skip ${rel} (exists — run with --update)`);
|
|
197
|
+
nextFiles[rel] = prevFiles[rel] || curHash;
|
|
198
|
+
continue;
|
|
124
199
|
}
|
|
125
200
|
|
|
126
|
-
const
|
|
127
|
-
if (
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
fs.writeFileSync(featuresPath, content);
|
|
201
|
+
const pristine = prevFiles[rel] !== undefined && prevFiles[rel] === curHash;
|
|
202
|
+
if (pristine || force) {
|
|
203
|
+
if (!dryRun) {
|
|
204
|
+
fs.writeFileSync(dest, srcBuf);
|
|
205
|
+
if (fs.existsSync(newPath)) fs.unlinkSync(newPath);
|
|
132
206
|
}
|
|
207
|
+
nextFiles[rel] = srcHash;
|
|
208
|
+
up(`${rel} (updated${force && !pristine ? ", overwrote local edits" : ""})`);
|
|
209
|
+
updated++;
|
|
210
|
+
continue;
|
|
133
211
|
}
|
|
212
|
+
|
|
213
|
+
// Locally modified → keep theirs, drop the new version next to it.
|
|
214
|
+
if (!dryRun) fs.writeFileSync(newPath, srcBuf);
|
|
215
|
+
nextFiles[rel] = prevFiles[rel] || curHash;
|
|
216
|
+
warn(`${rel} modified locally — kept yours, new version at ${rel}${NEW_SUFFIX}`);
|
|
217
|
+
conflicts.push(rel);
|
|
134
218
|
}
|
|
135
219
|
|
|
136
|
-
//
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
)
|
|
144
|
-
|
|
220
|
+
// Managed files sisyo no longer ships: remove only if still pristine.
|
|
221
|
+
if (updateMode) {
|
|
222
|
+
const shipped = new Set(templates.map(t => t.rel));
|
|
223
|
+
for (const rel of Object.keys(prevFiles)) {
|
|
224
|
+
if (shipped.has(rel)) continue;
|
|
225
|
+
const dest = path.join(target, rel);
|
|
226
|
+
if (!fs.existsSync(dest)) continue;
|
|
227
|
+
if (hashFile(dest) === prevFiles[rel]) {
|
|
228
|
+
if (!dryRun) {
|
|
229
|
+
fs.unlinkSync(dest);
|
|
230
|
+
try { fs.rmdirSync(path.dirname(dest)); } catch { /* not empty — keep */ }
|
|
231
|
+
}
|
|
232
|
+
up(`${rel} (removed — no longer shipped)`);
|
|
233
|
+
} else {
|
|
234
|
+
warn(`${rel} no longer shipped by sisyo but modified locally — left in place`);
|
|
235
|
+
nextFiles[rel] = prevFiles[rel];
|
|
236
|
+
}
|
|
145
237
|
}
|
|
146
238
|
}
|
|
147
239
|
|
|
240
|
+
ensureClaudeMdImport(target, dryRun);
|
|
241
|
+
if (!updateMode && !dryRun) fillDates(target);
|
|
242
|
+
ensureGitignore(target, dryRun);
|
|
243
|
+
if (!dryRun) writeManifest(target, nextFiles);
|
|
244
|
+
|
|
148
245
|
log("");
|
|
149
|
-
if (
|
|
150
|
-
log(`${BOLD}
|
|
246
|
+
if (dryRun) {
|
|
247
|
+
log(`${BOLD}Dry run.${RESET} +${added} added, ~${updated} updated, ${unchanged} unchanged, ${conflicts.length} conflicts. Nothing written.`);
|
|
248
|
+
} else if (updateMode) {
|
|
249
|
+
log(`${BOLD}Done!${RESET} +${added} added, ~${updated} updated, ${unchanged} unchanged. Your SISYO.md, CLAUDE.md and docs/ are untouched.`);
|
|
151
250
|
} else {
|
|
152
251
|
log(`${BOLD}Done!${RESET} Next steps:`);
|
|
153
252
|
log("");
|
|
@@ -155,6 +254,15 @@ function main() {
|
|
|
155
254
|
log(` 2. Open Claude Code and start building`);
|
|
156
255
|
log(` 3. Docs auto-update as you work`);
|
|
157
256
|
}
|
|
257
|
+
if (conflicts.length > 0) {
|
|
258
|
+
log("");
|
|
259
|
+
log(`${RED}${conflicts.length} file(s) were modified locally and NOT overwritten:${RESET}`);
|
|
260
|
+
for (const rel of conflicts) log(` ${rel} → ${rel}${NEW_SUFFIX}`);
|
|
261
|
+
log("");
|
|
262
|
+
log(` Review: git diff --no-index <file> <file>${NEW_SUFFIX}`);
|
|
263
|
+
log(` Accept: move the ${NEW_SUFFIX} file over the original, or rerun with ${CYAN}--force${RESET}`);
|
|
264
|
+
log(` Keep: delete the ${NEW_SUFFIX} file (sisyo will offer it again next update)`);
|
|
265
|
+
}
|
|
158
266
|
log("");
|
|
159
267
|
log(`${DIM}Docs system: SISYO.md -> docs/MAP.md -> _summary.md -> detail files${RESET}`);
|
|
160
268
|
log("");
|
package/package.json
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
# Doc Management Rule
|
|
2
|
-
|
|
3
|
-
3-level routing: MAP.md → _summary.md → detail files.
|
|
4
|
-
|
|
5
|
-
When changing code that affects project structure or behavior:
|
|
6
|
-
1. Read docs/MAP.md to find relevant folder
|
|
7
|
-
2. Read _summary.md of that folder (if exists)
|
|
8
|
-
3. Update detail file (or create if new)
|
|
9
|
-
4. Update _summary.md table
|
|
10
|
-
5. Update MAP.md summary line
|
|
11
|
-
|
|
12
|
-
When a feature is completed or added:
|
|
13
|
-
- Log it in docs/99_progress/features.md (date, name, status, link to spec)
|
|
14
|
-
|
|
15
|
-
Before ending session or when context gets large:
|
|
16
|
-
- Write docs/99_progress/handoff.md
|
|
17
|
-
|
|
18
|
-
At session start:
|
|
19
|
-
- Read docs/MAP.md then docs/99_progress/handoff.md
|
|
1
|
+
# Doc Management Rule
|
|
2
|
+
|
|
3
|
+
3-level routing: MAP.md → _summary.md → detail files.
|
|
4
|
+
|
|
5
|
+
When changing code that affects project structure or behavior:
|
|
6
|
+
1. Read docs/MAP.md to find relevant folder
|
|
7
|
+
2. Read _summary.md of that folder (if exists)
|
|
8
|
+
3. Update detail file (or create if new)
|
|
9
|
+
4. Update _summary.md table
|
|
10
|
+
5. Update MAP.md summary line
|
|
11
|
+
|
|
12
|
+
When a feature is completed or added:
|
|
13
|
+
- Log it in docs/99_progress/features.md (date, name, status, link to spec)
|
|
14
|
+
|
|
15
|
+
Before ending session or when context gets large:
|
|
16
|
+
- Write docs/99_progress/handoff.md
|
|
17
|
+
|
|
18
|
+
At session start:
|
|
19
|
+
- Read docs/MAP.md then docs/99_progress/handoff.md
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# One-shot Generate (JSON, grounding, PDF, TTS)
|
|
2
|
+
|
|
3
|
+
Use `client.models.generate_content` on `GEMINI_GENERATE_MODEL` for offline / admin work
|
|
4
|
+
(config generation, Q&A generation, document extraction). Never on the interactive chat path.
|
|
5
|
+
|
|
6
|
+
## JSON output
|
|
7
|
+
|
|
8
|
+
```python
|
|
9
|
+
resp = client.models.generate_content(
|
|
10
|
+
model=settings.GEMINI_GENERATE_MODEL,
|
|
11
|
+
contents=prompt,
|
|
12
|
+
config={
|
|
13
|
+
"system_instruction": SYS,
|
|
14
|
+
"response_mime_type": "application/json",
|
|
15
|
+
"thinking_config": {"thinking_level": "low"},
|
|
16
|
+
},
|
|
17
|
+
)
|
|
18
|
+
data = _parse_json(resp.text or "")
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
def _parse_json(text: str) -> dict:
|
|
23
|
+
text = text.strip()
|
|
24
|
+
try:
|
|
25
|
+
return json.loads(text)
|
|
26
|
+
except Exception:
|
|
27
|
+
pass
|
|
28
|
+
m = re.search(r"\{.*\}", text, flags=re.DOTALL) # tolerate ```json fences / prose
|
|
29
|
+
if m:
|
|
30
|
+
try:
|
|
31
|
+
return json.loads(m.group(0))
|
|
32
|
+
except Exception:
|
|
33
|
+
pass
|
|
34
|
+
return {}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Always parse defensively and have a fallback (empty dict, original order, etc.).
|
|
38
|
+
|
|
39
|
+
## Grounding: Google Search + URL context
|
|
40
|
+
|
|
41
|
+
For "generate an agent config from this business URL" style tasks:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from google.genai import types
|
|
45
|
+
|
|
46
|
+
resp = client.models.generate_content(
|
|
47
|
+
model=settings.GEMINI_GENERATE_MODEL,
|
|
48
|
+
contents=prompt_with_urls,
|
|
49
|
+
config={
|
|
50
|
+
"system_instruction": GENERATE_PROMPT,
|
|
51
|
+
"tools": [
|
|
52
|
+
types.Tool(google_search=types.GoogleSearch()),
|
|
53
|
+
types.Tool(url_context=types.UrlContext()),
|
|
54
|
+
],
|
|
55
|
+
},
|
|
56
|
+
)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
- Tell the model in the system prompt to browse the URLs first and search for the business
|
|
60
|
+
before generating; otherwise it invents data.
|
|
61
|
+
- When regenerating (e.g. "10 more Q&A"), pass the existing items and say "do NOT duplicate".
|
|
62
|
+
- Grounded calls are slow (seconds) — run them from admin endpoints / background jobs only.
|
|
63
|
+
|
|
64
|
+
## PDF / document extraction
|
|
65
|
+
|
|
66
|
+
Send the file bytes inline and ask for Markdown. Cap size (~19 MB inline limit).
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from google.genai import types
|
|
70
|
+
|
|
71
|
+
resp = client.models.generate_content(
|
|
72
|
+
model=settings.GEMINI_GENERATE_MODEL,
|
|
73
|
+
contents=[
|
|
74
|
+
types.Part.from_bytes(data=pdf_bytes, mime_type="application/pdf"),
|
|
75
|
+
"Extract ALL text from this document as clean Markdown. Preserve tables as Markdown "
|
|
76
|
+
"tables and keep headings in reading order. Output only the extracted content.",
|
|
77
|
+
],
|
|
78
|
+
)
|
|
79
|
+
text = (resp.text or "").strip()
|
|
80
|
+
if not text:
|
|
81
|
+
raise ValueError("PDF text extraction returned no text (scanned/empty document?)")
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Raise a `ValueError` with a short message on failure so the upload UI can show it.
|
|
85
|
+
|
|
86
|
+
## TTS (voice sample clips)
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
resp = client.models.generate_content(
|
|
90
|
+
model=settings.GEMINI_TTS_MODEL,
|
|
91
|
+
contents=text,
|
|
92
|
+
config={
|
|
93
|
+
"response_modalities": ["AUDIO"],
|
|
94
|
+
"speech_config": {"voice_config": {"prebuilt_voice_config": {"voice_name": voice_name}}},
|
|
95
|
+
},
|
|
96
|
+
)
|
|
97
|
+
pcm = b"".join(p.inline_data.data for p in resp.candidates[0].content.parts
|
|
98
|
+
if p.inline_data and p.inline_data.data)
|
|
99
|
+
# → wrap as WAV: mono, 16-bit, 24000 Hz
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Rules for TTS previews:
|
|
103
|
+
|
|
104
|
+
- **Pre-generate and cache** (S3 / disk) every voice × language at startup in a background
|
|
105
|
+
thread; the play button must be a URL lookup, never a live TTS wait.
|
|
106
|
+
- Key clips by a version string (`voice-samples/v1/{voice}_{lang}.wav`). Bump the version when
|
|
107
|
+
the sample text or TTS model changes; provide a `--force` regenerate script.
|
|
108
|
+
- Pace calls (`sleep 1s` between, `5s` after a failure) to stay under rate limits; one bad clip
|
|
109
|
+
must not stop the batch.
|
|
110
|
+
- Voice ids: Live API subset (`Kore, Puck, Charon, Aoede, Fenrir, Leda, Orus, Zephyr`).
|
|
111
|
+
Store the Gemini id; show friendly names in the UI. Unknown id → default `Kore`.
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# Live Voice (client-side WebSocket via ephemeral token)
|
|
2
|
+
|
|
3
|
+
Voice runs **in the browser** against the Live API. The backend only mints a constrained
|
|
4
|
+
ephemeral token; tools are still executed by the backend.
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
FE POST /api/live/token?lang= → BE: validate agent → client.auth_tokens.create() → {token, model, voice_name, session_id}
|
|
8
|
+
FE ai.live.connect({model, config, callbacks}) (apiKey = token, apiVersion v1alpha)
|
|
9
|
+
FE mic PCM 16 kHz → sendRealtimeInput({ audio })
|
|
10
|
+
BE→FE audio PCM 24 kHz in serverContent.modelTurn.parts[].inlineData
|
|
11
|
+
FE toolCall → POST /api/tools/execute → sendToolResponse({ functionResponses })
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Backend — mint the token
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from google import genai
|
|
18
|
+
|
|
19
|
+
client = genai.Client(api_key=settings.GEMINI_API_KEY, http_options={"api_version": "v1alpha"})
|
|
20
|
+
|
|
21
|
+
live_config = {
|
|
22
|
+
"response_modalities": ["AUDIO"],
|
|
23
|
+
"system_instruction": system_instruction, # same template as text chat + voice block
|
|
24
|
+
"tools": [{"function_declarations": TOOL_DEFINITIONS}],
|
|
25
|
+
"speech_config": {"voice_config": {"prebuilt_voice_config": {"voice_name": voice_name}}},
|
|
26
|
+
"input_audio_transcription": {}, # server-side STT of the user → live transcript
|
|
27
|
+
"output_audio_transcription": {}, # STT of the model's speech
|
|
28
|
+
}
|
|
29
|
+
if "3.1" in model:
|
|
30
|
+
live_config["thinking_config"] = {"thinking_level": "minimal"} # 3.1 only; NOT thinking_budget
|
|
31
|
+
|
|
32
|
+
token = client.auth_tokens.create(config={
|
|
33
|
+
"uses": 1,
|
|
34
|
+
"expire_time": (now + 30min).isoformat(),
|
|
35
|
+
"new_session_expire_time": (now + 2min).isoformat(),
|
|
36
|
+
"live_connect_constraints": {"model": model, "config": live_config},
|
|
37
|
+
"http_options": {"api_version": "v1alpha"},
|
|
38
|
+
})
|
|
39
|
+
return {"token": token.name, "model": model, "voice_name": voice_name, "session_id": session_id}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Rules:
|
|
43
|
+
|
|
44
|
+
- Validate the agent / feature flag **before** creating a session row or minting — the endpoint
|
|
45
|
+
is public. Raise a dedicated `AgentNotFound` and map ONLY that to 404 (catching the
|
|
46
|
+
`LookupError` base class turned `KeyError`s from deeper code into bogus 404s).
|
|
47
|
+
- Return `voice_name` — the FE **must** pass it again in `live.connect({ speechConfig })`; the
|
|
48
|
+
server ignores the token's voice otherwise.
|
|
49
|
+
- Wrap `auth_tokens.create` in try/except + `logger.exception` — a 402 (billing / Live not
|
|
50
|
+
enabled) or unknown model id otherwise shows up as a silent "connecting…".
|
|
51
|
+
- No API key → return `{"token": "stub-token-no-api-key", ...}`.
|
|
52
|
+
|
|
53
|
+
## Frontend — connect
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { GoogleGenAI, Modality, type LiveServerMessage } from '@google/genai'
|
|
57
|
+
|
|
58
|
+
const ai = new GoogleGenAI({ apiKey: tokenData.token, httpOptions: { apiVersion: 'v1alpha' } })
|
|
59
|
+
const outputCtx = new AudioContext({ sampleRate: 24000 })
|
|
60
|
+
if (outputCtx.state === 'suspended') await outputCtx.resume() // else "connected but silent"
|
|
61
|
+
|
|
62
|
+
const session = await Promise.race([
|
|
63
|
+
ai.live.connect({
|
|
64
|
+
model: tokenData.model,
|
|
65
|
+
config: {
|
|
66
|
+
responseModalities: [Modality.AUDIO],
|
|
67
|
+
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: tokenData.voice_name } } },
|
|
68
|
+
},
|
|
69
|
+
callbacks: { onopen, onmessage, onerror, onclose },
|
|
70
|
+
}),
|
|
71
|
+
timeout(15000, 'WebSocket to Gemini Live did not open (proxy / extension / CSP?)'),
|
|
72
|
+
])
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- `connect()` resolves only on WS `onopen` → always race it with a timeout so the UI never
|
|
76
|
+
hangs on "connecting…".
|
|
77
|
+
- Track a **phase** state (`idle | token | opening | open | recording | ending | ended | error`)
|
|
78
|
+
and log it — a hang is then observable.
|
|
79
|
+
- `onclose`: codes 1000/1005 are normal; anything else → surface `reason` as an error.
|
|
80
|
+
1007 = bad payload (see 2.5 → 3.1 table).
|
|
81
|
+
|
|
82
|
+
## Audio
|
|
83
|
+
|
|
84
|
+
| Direction | Format | API |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| Mic → model | PCM 16-bit mono, **16 kHz** | `sendRealtimeInput({ audio: pcmBlob })` |
|
|
87
|
+
| Model → speaker | PCM 16-bit mono, **24 kHz** | `serverContent.modelTurn.parts[].inlineData.data` |
|
|
88
|
+
|
|
89
|
+
- Schedule output buffers back-to-back on the AudioContext clock (`nextStartTime`), don't play
|
|
90
|
+
each chunk immediately.
|
|
91
|
+
- `serverContent.interrupted` (barge-in) → reset `nextStartTime` and clear speaking state.
|
|
92
|
+
- Route output through an `AnalyserNode` if the UI animates on loudness.
|
|
93
|
+
- Transcripts: `serverContent.inputTranscription.text` / `outputTranscription.text` arrive as
|
|
94
|
+
deltas; append to the current turn's bubble, reset indexes on `turnComplete`.
|
|
95
|
+
|
|
96
|
+
## Tool calls on 3.1 — synchronous
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
if (msg.toolCall) {
|
|
100
|
+
const functionResponses = await Promise.all((msg.toolCall.functionCalls || []).map(async fc => {
|
|
101
|
+
let response: Record<string, unknown>
|
|
102
|
+
try { response = { result: await executeTool(fc.name, fc.args) } }
|
|
103
|
+
catch (e) { response = { error: e instanceof Error ? e.message : 'Tool execution failed' } }
|
|
104
|
+
return { id: fc.id || '', name: fc.name || '', response }
|
|
105
|
+
}))
|
|
106
|
+
session.sendToolResponse({ functionResponses }) // ALL calls, ONE message
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
- The model is **silent until every call is answered** — a thrown tool must still respond.
|
|
111
|
+
- Show a "thinking" indicator from `toolCall` until the next audio chunk arrives.
|
|
112
|
+
|
|
113
|
+
## end_conversation — hang up AFTER the farewell
|
|
114
|
+
|
|
115
|
+
Tool calls are sync, so the farewell audio comes **after** your tool response. Do not close the
|
|
116
|
+
socket inside the tool handler (that produced no farewell + a UI stuck on "Connecting…").
|
|
117
|
+
|
|
118
|
+
1. On `end_conversation`: set `ending = true`, phase `ending`, **stop the mic**, start a 12 s
|
|
119
|
+
grace timer.
|
|
120
|
+
2. Send the tool response normally.
|
|
121
|
+
3. On `turnComplete` while `ending`: wait for the audio queue to drain (+400 ms) → disconnect →
|
|
122
|
+
phase `ended` (show "Call again", not "idle").
|
|
123
|
+
4. Grace timer fires first → disconnect anyway.
|
|
124
|
+
|
|
125
|
+
System prompt line: *"When the customer says goodbye, say ONE short farewell sentence and call
|
|
126
|
+
end_conversation in that same turn."*
|
|
127
|
+
|
|
128
|
+
## Session language + greeting
|
|
129
|
+
|
|
130
|
+
- Widget passes `?lang=` → token endpoint → appended `## Voice Mode` block in the system
|
|
131
|
+
prompt: default language, greeting rule, control-turn rule, farewell rule.
|
|
132
|
+
- The FE's first turn is a control message `[Session start] … Greet them now in {lang}` — **not**
|
|
133
|
+
the greeting text. Sending the greeting as a user turn made the model mirror its language.
|
|
134
|
+
- Tell the model the `[Session start]` turn is a control signal: never read it aloud, never
|
|
135
|
+
mirror its language.
|
|
136
|
+
- Per-language overrides live in `config.locales[lang]` merged over defaults by ONE resolver
|
|
137
|
+
used by both the token endpoint and the public config endpoint.
|
|
138
|
+
|
|
139
|
+
## 2.5 → 3.1 Live differences (branch on `'3.1' in model`)
|
|
140
|
+
|
|
141
|
+
| Item | 2.5 | 3.1 |
|
|
142
|
+
|---|---|---|
|
|
143
|
+
| Mic stream | `sendRealtimeInput({ media })` | `sendRealtimeInput({ audio })` — `media` → close 1007 |
|
|
144
|
+
| Mid-session text | `sendClientContent` | `sendRealtimeInput({ text })` |
|
|
145
|
+
| Latency tuning | `thinking_budget` | `thinking_config.thinking_level = "minimal"` |
|
|
146
|
+
| Server events | 1 part / event | multiple parts / event → loop over all `parts` |
|
|
147
|
+
| Function calling | async (NON_BLOCKING) possible | **sync only** |
|
|
148
|
+
| Proactive audio / affective dialog | yes | not supported |
|
|
149
|
+
|
|
150
|
+
Fallback: `GEMINI_LIVE_MODEL=gemini-2.5-flash-native-audio-preview-12-2025`.
|
|
151
|
+
|
|
152
|
+
## Persisting the voice transcript
|
|
153
|
+
|
|
154
|
+
Create a `live_*` session row when minting the token and return its id. FE flushes new
|
|
155
|
+
transcript entries on `turnComplete`, `onclose` and disconnect — fire-and-forget, watermark
|
|
156
|
+
advances only after a successful save, and persistence must never break the call.
|