Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat(skills): smart local HTML serve with context-aware deduplication

Gotcha Contributora0d52217e67a
diff --git a/app/src/main/assets/skills/local_serve.json b/app/src/main/assets/skills/local_serve.json
new file mode 100644
index 0000000..d137838
--- /dev/null
+++ b/app/src/main/assets/skills/local_serve.json
@@ -0,0 +1,9 @@
+{
+ "id": "local_serve",
+ "targetPackageNames": ["com.gotcha"],
+ "title": "Serve Local HTML on Device",
+ "description": "Build an HTML app in Gotcha chats and serve it on a local port via toybox netcat (Operator mode only).",
+ "requiresTools": ["write_file", "run_command"],
+ "keywords": [],
+ "instructions": "Purpose: When the user asks to build/develop/create an app, game, page, or tool and does not specify how to run it, make it immediately usable on this phone as a self-contained HTML page served on a local port. This is the smart default when local execution is possible. If the request is genuinely ambiguous (could be Android APK vs web app vs Python script vs Termux), ask one clarifying question: 'Do you want this runnable on this phone as a web app (HTML on a local port), or as an Android app / Python script / Termux program?' Then act on the answer — do not default to asking when the intent is clearly a web-playable game or page.\n1. Write a single self-contained index.html (inline CSS+JS, CDN via https if needed, no local asset dependencies) to /storage/emulated/0/Gotcha/chats/<Slug>_<shortId>/index.html using write_file. Keep it under 100KB. This is the Gotcha world — do NOT use run_termux_command or Termux's $HOME for this file.\n2. Pick a free port: try 8000, then 7777, 8080, 9000. Test with run_command: `toybox nc -z 127.0.0.1 8000 || echo free` — first free wins. Use timeout_seconds=5 for these probes.\n3. Serve it with run_command (Operator mode only; Monitor cannot run this). Do NOT use run_termux_command for Gotcha-world files. Use a persistent loop with HTTP headers so every connection gets text/html:\n `nohup sh -c 'while true; do { printf \"HTTP/1.1 200 OK\\r\\nContent-Type: text/html; charset=utf-8\\r\\nContent-Length: $(wc -c < \"/storage/emulated/0/Gotcha/chats/<Slug>_<id>/index.html\")\\r\\nCache-Control: no-cache\\r\\nAccess-Control-Allow-Origin: *\\r\\nConnection: close\\r\\n\\r\\n\"; cat \"/storage/emulated/0/Gotcha/chats/<Slug>_<id>/index.html\"; } | toybox nc -L -p <PORT> -q 1; done' > /data/local/tmp/serve_<PORT>.log 2>&1 & echo $!`\n If toybox nc -L is single-connection, the while-true loop keeps it alive for the browser and for a verification curl. If nohup is missing, fallback to `sh -c 'while true; do ...; done' &`.\n4. Verify with run_command: `sleep 1; curl -sI http://127.0.0.1:<PORT> | head -n 20` must show HTTP/1.1 200 and Content-Type: text/html. Use timeout_seconds=5. If it fails, `ps | grep toybox` and retry with next free port.\n5. Return to the user immediately: `http://127.0.0.1:<PORT>` and `http://localhost:<PORT>` (both are secure contexts for camera/mic on Android Chrome) plus the file path. Do not wait for a follow-up 'run it at ...' message. Note: server lives until reboot or `pkill -f \"toybox nc.*<PORT>\"` via run_command.\n6. If the user explicitly asked for Termux/Python/APK (e.g., 'run in Termux', 'make an APK'), do not force the web default — honor that and use the appropriate Termux/proot skill instead.\n"
+}
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index e74a880..ce766a6 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -454,7 +454,7 @@ class AgentEngine(
add(systemPromptMessage(agent))
addAll(cullOldObservations(trimmedHistory()))
add(currentTimestampMessage())
- addAll(activeSkillsMessages())
+ addAll(activeSkillsMessages(agent))
}
val response = try {
llm.chat(
@@ -1017,11 +1017,16 @@ class AgentEngine(
* Injects context-aware skills based on the currently foregrounded package.
* This makes the agent behave optimally for the specific app on screen.
*/
- private fun activeSkillsMessages(): List<ChatMessage> {
+ private fun activeSkillsMessages(agent: AgentMode? = null): List<ChatMessage> {
val currentPackage = ScreenPerception.getCurrentPackageName() ?: return emptyList()
val disabledSkills = settingsProvider().disabledSkills
- val activeSkills = SkillRegistry.getSkillsForPackage(currentPackage, hiddenTools())
+ var activeSkills = SkillRegistry.getSkillsForPackage(currentPackage, hiddenTools())
.filter { !disabledSkills.contains(it.id) }
+ // local_serve is a phone HTML serve default — never in voice-call
+ // brevity mode or when Monitor cannot execute write_file/run_command.
+ if (callMode || agent == AgentMode.MONITOR) {
+ activeSkills = activeSkills.filterNot { it.id == "local_serve" }
+ }
val communityIds = SkillRegistry.getCommunitySkills().map { it.id }.toSet()
val message = SkillPromptBuilder.buildFromHistory(
currentPackage = currentPackage,
@@ -1069,6 +1074,23 @@ class AgentEngine(
"mode restrictions below, or with a format a tool requires."
}
.orEmpty()
+ // Default to HTML-on-port when the user wants something built but did not
+ // say how to run it — make it runnable on this phone without a follow-up.
+ // Operator-only and suppressed in voice-call brevity mode. The skill
+ // local_serve carries the exact run_command/toybox recipe; this nudge
+ // is the cheap index-0 default that causes the agent to fetch it.
+ val serveDirective = if (agent == AgentMode.OPERATOR && !callMode) {
+ "\n\nWhen the user asks you to build, develop, or create an app, game, page, or tool " +
+ "and does not specify how to run it, default to a self-contained HTML page " +
+ "in the Gotcha chats folder and serve it on a free local port with run_command " +
+ "(toybox nc) so it is immediately usable on this phone — do not wait for a " +
+ "follow-up 'run it'. If the request is genuinely ambiguous (could be an Android " +
+ "APK vs a web app vs a Python script vs a Termux program), ask one clarifying " +
+ "question whether they want it runnable on this phone as a web app or elsewhere " +
+ "before choosing."
+ } else {
+ ""
+ }
val core = when (agent) {
AgentMode.MONITOR ->
"You are Gotcha (operating in Monitor mode), a read-only AI assistant " +
@@ -1143,7 +1165,7 @@ class AgentEngine(
} +
"</system-reminder>"
}
- return core + languageDirective + styleDirective + reminder
+ return core + serveDirective + languageDirective + styleDirective + reminder
}
/**
diff --git a/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.kt b/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.kt
index 2883533..979685b 100644
--- a/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.kt
+++ b/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.kt
@@ -19,6 +19,10 @@ object SkillPromptBuilder {
/** Regex matching the tool result header format emitted by ToolExecutor for search_skills. */
val SKILL_RESULT_REGEX = Regex("""Skill \[([^\]]+)\]:""")
+ /** Regex matching the `<available-skills>` summary we inject (`• skill_id: desc` / `• skill_id (community):`). */
+ private val AVAILABLE_SKILL_REGEX =
+ Regex("""^•\s*([a-z0-9_]+)(?:\s*\(community\))?:""", RegexOption.MULTILINE)
+
/**
* Scans conversation history for tool-result messages containing full skill bodies
* previously fetched via `search_skills`.
@@ -31,6 +35,34 @@ object SkillPromptBuilder {
.toSet()
}
+ /**
+ * Skill summaries we injected via `<available-skills>` as `user` messages.
+ * Used to avoid re-pushing the same 60-token summary over and over in the
+ * same chat — e.g. a repeated `run it at ...` cue should not burn context by
+ * re-injecting `local_serve` every turn. We scan the whole history (session
+ * scope) so a summary is pushed once per chat and then suppressed; a new
+ * chat starts with a fresh history and the skill becomes eligible again.
+ */
+ fun extractRecentlyInjectedSkillIds(
+ history: List<ChatMessage>,
+ lookback: Int = Int.MAX_VALUE
+ ): Set<String> {
+ val candidates = history.filter {
+ it.role == "user" && it.textContent.contains("<available-skills>")
+ }
+ val window = if (
+ lookback == Int.MAX_VALUE || lookback >= candidates.size
+ ) {
+ candidates
+ } else {
+ candidates.takeLast(lookback)
+ }
+ return window
+ .flatMap { AVAILABLE_SKILL_REGEX.findAll(it.textContent) }
+ .map { it.groupValues[1] }
+ .toSet()
+ }
+
/**
* Extracts the text of the last genuine user (human) message from history,
* skipping synthetic observation messages (e.g. vision/screenshot observations
@@ -53,12 +85,13 @@ object SkillPromptBuilder {
history: List<ChatMessage>
): ChatMessage? {
val fetchedIds = extractFetchedSkillIds(history)
+ val injectedIds = extractRecentlyInjectedSkillIds(history)
val lastUserMsg = extractLastHumanUserMessage(history)
return build(
currentPackage = currentPackage,
activeSkills = activeSkills,
communityIds = communityIds,
- recentlyFetchedSkillIds = fetchedIds,
+ recentlyFetchedSkillIds = fetchedIds + injectedIds,
lastUserMessage = lastUserMsg
)
}