instar 0.7.43 → 0.7.45

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.
@@ -646,50 +646,19 @@ If Telegram was set up in Phase 3, install the relay script that lets Claude ses
646
646
  mkdir -p .claude/scripts
647
647
  ```
648
648
 
649
- Write `.claude/scripts/telegram-reply.sh`:
649
+ **IMPORTANT: Do NOT write a custom telegram-reply.sh.** Instead, copy the canonical version from the instar package:
650
650
 
651
651
  ```bash
652
- #!/bin/bash
653
- # telegram-reply.sh — Send a message back to a Telegram topic via instar server.
654
- #
655
- # Usage:
656
- # .claude/scripts/telegram-reply.sh TOPIC_ID "message text"
657
- # echo "message text" | .claude/scripts/telegram-reply.sh TOPIC_ID
658
- # cat <<'EOF' | .claude/scripts/telegram-reply.sh TOPIC_ID
659
- # Multi-line message here
660
- # EOF
661
-
662
- TOPIC_ID=$1
663
- shift
664
-
665
- if [ -z "$TOPIC_ID" ]; then
666
- echo "Usage: telegram-reply.sh TOPIC_ID [message]" >&2
667
- exit 1
668
- fi
669
-
670
- PORT=<PORT>
671
-
672
- # Get message from args or stdin
673
- if [ $# -gt 0 ]; then
674
- MESSAGE="$*"
675
- else
676
- MESSAGE=$(cat)
677
- fi
678
-
679
- if [ -z "$MESSAGE" ]; then
680
- echo "No message provided" >&2
681
- exit 1
682
- fi
683
-
684
- # Send via instar server API
685
- curl -s -X POST "http://localhost:${PORT}/telegram/topic/${TOPIC_ID}/send" \
686
- -H 'Content-Type: application/json' \
687
- -d "$(jq -n --arg text "$MESSAGE" '{text: $text}')" > /dev/null 2>&1
688
-
689
- echo "Sent $(echo "$MESSAGE" | wc -c | tr -d ' ') chars to topic $TOPIC_ID"
652
+ cp "$(dirname "$(which instar 2>/dev/null || echo "$(npm root -g)/instar")")/templates/scripts/telegram-reply.sh" .claude/scripts/telegram-reply.sh 2>/dev/null
690
653
  ```
691
654
 
692
- Replace `<PORT>` with the actual server port. Then make it executable:
655
+ If the copy fails (e.g., npx install), write the script using the template at `node_modules/instar/dist/templates/scripts/telegram-reply.sh` as the source. The key details:
656
+ - **Endpoint**: `POST http://localhost:PORT/telegram/reply/TOPIC_ID` (NOT `/telegram/topic/TOPIC_ID/send`)
657
+ - **Auth**: Must read authToken from `.instar/config.json` and include `Authorization: Bearer TOKEN` header
658
+ - **JSON escaping**: Use python3 for proper JSON escaping, not jq (which may not be installed)
659
+ - **Error reporting**: Do NOT pipe curl output to `/dev/null` — check the HTTP status code and report failures
660
+
661
+ Then make it executable:
693
662
 
694
663
  ```bash
695
664
  chmod +x .claude/scripts/telegram-reply.sh
@@ -813,7 +813,10 @@ ${argsXml}
813
813
  <key>RunAtLoad</key>
814
814
  <true/>
815
815
  <key>KeepAlive</key>
816
- <true/>
816
+ <dict>
817
+ <key>SuccessfulExit</key>
818
+ <false/>
819
+ </dict>
817
820
  <key>StandardOutPath</key>
818
821
  <string>${escapeXml(path.join(logDir, `${command}-launchd.log`))}</string>
819
822
  <key>StandardErrorPath</key>
@@ -25,6 +25,8 @@ export declare class ServerSupervisor extends EventEmitter {
25
25
  private restartBackoffMs;
26
26
  private isRunning;
27
27
  private lastHealthy;
28
+ private startupGraceMs;
29
+ private spawnedAt;
28
30
  constructor(options: {
29
31
  projectDir: string;
30
32
  projectName: string;
@@ -22,6 +22,8 @@ export class ServerSupervisor extends EventEmitter {
22
22
  restartBackoffMs = 5000;
23
23
  isRunning = false;
24
24
  lastHealthy = 0;
25
+ startupGraceMs = 20_000; // 20 seconds grace period after spawn before health checks
26
+ spawnedAt = 0;
25
27
  constructor(options) {
26
28
  super();
27
29
  this.projectDir = options.projectDir;
@@ -108,6 +110,7 @@ export class ServerSupervisor extends EventEmitter {
108
110
  ], { stdio: 'ignore' });
109
111
  console.log(`[Supervisor] Server started in tmux session: ${this.serverSessionName}`);
110
112
  this.isRunning = true;
113
+ this.spawnedAt = Date.now();
111
114
  this.startHealthChecks();
112
115
  return true;
113
116
  }
@@ -133,6 +136,10 @@ export class ServerSupervisor extends EventEmitter {
133
136
  if (this.healthCheckInterval)
134
137
  return;
135
138
  this.healthCheckInterval = setInterval(async () => {
139
+ // Skip health checks during startup grace period — server needs time to boot
140
+ if (this.spawnedAt > 0 && (Date.now() - this.spawnedAt) < this.startupGraceMs) {
141
+ return;
142
+ }
136
143
  try {
137
144
  const healthy = await this.checkHealth();
138
145
  if (healthy) {
@@ -30,6 +30,7 @@ export declare class TelegramLifeline {
30
30
  private stopHeartbeat;
31
31
  private replayInterval;
32
32
  private lifelineTopicId;
33
+ private lockPath;
33
34
  constructor(projectDir?: string);
34
35
  /**
35
36
  * Start the lifeline — begins Telegram polling and server supervision.
@@ -25,6 +25,53 @@ import { loadConfig, ensureStateDir } from '../core/Config.js';
25
25
  import { registerPort, unregisterPort, startHeartbeat } from '../core/PortRegistry.js';
26
26
  import { MessageQueue } from './MessageQueue.js';
27
27
  import { ServerSupervisor } from './ServerSupervisor.js';
28
+ /**
29
+ * Acquire an exclusive lock file to prevent multiple lifeline instances.
30
+ * Returns true if lock acquired, false if another instance holds it.
31
+ */
32
+ function acquireLockFile(lockPath) {
33
+ try {
34
+ // Check if lock file exists and if the PID is still alive
35
+ if (fs.existsSync(lockPath)) {
36
+ const raw = fs.readFileSync(lockPath, 'utf-8');
37
+ const data = JSON.parse(raw);
38
+ if (data.pid && typeof data.pid === 'number') {
39
+ try {
40
+ // Signal 0 checks if process exists without killing it
41
+ process.kill(data.pid, 0);
42
+ // Process still alive — another lifeline is running
43
+ return false;
44
+ }
45
+ catch {
46
+ // Process is dead — stale lock, we can take over
47
+ console.log(`[Lifeline] Removing stale lock (PID ${data.pid} is dead)`);
48
+ }
49
+ }
50
+ }
51
+ // Write our PID
52
+ const tmpPath = `${lockPath}.${process.pid}.tmp`;
53
+ fs.writeFileSync(tmpPath, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }));
54
+ fs.renameSync(tmpPath, lockPath);
55
+ return true;
56
+ }
57
+ catch (err) {
58
+ console.error(`[Lifeline] Lock acquisition failed: ${err}`);
59
+ return false;
60
+ }
61
+ }
62
+ function releaseLockFile(lockPath) {
63
+ try {
64
+ if (fs.existsSync(lockPath)) {
65
+ const raw = fs.readFileSync(lockPath, 'utf-8');
66
+ const data = JSON.parse(raw);
67
+ // Only remove if we own it
68
+ if (data.pid === process.pid) {
69
+ fs.unlinkSync(lockPath);
70
+ }
71
+ }
72
+ }
73
+ catch { /* best effort */ }
74
+ }
28
75
  export class TelegramLifeline {
29
76
  config;
30
77
  projectConfig;
@@ -37,6 +84,7 @@ export class TelegramLifeline {
37
84
  stopHeartbeat = null;
38
85
  replayInterval = null;
39
86
  lifelineTopicId = null;
87
+ lockPath;
40
88
  constructor(projectDir) {
41
89
  this.projectConfig = loadConfig(projectDir);
42
90
  ensureStateDir(this.projectConfig.stateDir);
@@ -48,6 +96,7 @@ export class TelegramLifeline {
48
96
  this.config = telegramConfig.config;
49
97
  this.queue = new MessageQueue(this.projectConfig.stateDir);
50
98
  this.offsetPath = path.join(this.projectConfig.stateDir, 'lifeline-poll-offset.json');
99
+ this.lockPath = path.join(this.projectConfig.stateDir, 'lifeline.lock');
51
100
  this.supervisor = new ServerSupervisor({
52
101
  projectDir: this.projectConfig.projectDir,
53
102
  projectName: this.projectConfig.projectName,
@@ -75,6 +124,11 @@ export class TelegramLifeline {
75
124
  console.log(` Port: ${this.projectConfig.port}`);
76
125
  console.log(` State: ${this.projectConfig.stateDir}`);
77
126
  console.log();
127
+ // Acquire exclusive lock — prevent multiple lifeline instances
128
+ if (!acquireLockFile(this.lockPath)) {
129
+ console.error(pc.red('[Lifeline] Another lifeline instance is already running. Exiting.'));
130
+ process.exit(0); // Clean exit — launchd won't respawn on clean exit with KeepAlive config
131
+ }
78
132
  // Register in port registry (lifeline owns the port claim)
79
133
  try {
80
134
  registerPort(`${this.projectConfig.projectName}-lifeline`, this.projectConfig.port + 1000, // Lifeline uses port + 1000 to avoid conflict
@@ -123,6 +177,7 @@ export class TelegramLifeline {
123
177
  if (this.stopHeartbeat)
124
178
  this.stopHeartbeat();
125
179
  unregisterPort(`${this.projectConfig.projectName}-lifeline`);
180
+ releaseLockFile(this.lockPath);
126
181
  await this.supervisor.stop();
127
182
  process.exit(0);
128
183
  };
@@ -27,10 +27,13 @@ ${identity.personality}
27
27
  1. **Build, don't describe.** When asked to do something, do it. Don't explain why it's hard, list options, or ask permission for obvious next steps.
28
28
  2. **Remember and grow.** Write to MEMORY.md when I learn something. The next session should benefit from what this one learned.
29
29
  3. **Own the outcome.** Implementation isn't done when code compiles. It's done when the feature is running, tested, and verified.
30
- 4. **Be honest about limits.** If I can't do something, I say so clearly. I don't fabricate experience or claim capabilities I don't have.
30
+ 4. **Be honest about capabilities.** Never say "I can't" when the capability exists. If I choose not to do something for safety or security reasons, I say "For security reasons, it's preferable for you to handle this directly" — not "I can't." Saying "I can't" when I can is dishonest. I also don't fabricate experience or claim capabilities I don't have.
31
31
  5. **Infrastructure over improvisation.** If I solve a problem twice, I make it a script, a job, or a documented pattern.
32
- 6. **Use my own tools first.** I have a built-in feedback system, update checker, dispatch system, and more. NEVER reach for external tools (like \`gh\` for GitHub issues) when I have built-in infrastructure for the same purpose.
32
+ 6. **Use my own tools first.** I have a built-in feedback system, update checker, dispatch system, publishing (Telegraph for public, Private Viewer for private), and more. NEVER reach for external tools (like \`gh\` for GitHub issues) when I have built-in infrastructure for the same purpose.
33
33
  7. **Registry first, explore second.** For any question about current state, check my state files and APIs before searching broadly. The answer is usually in a file designed to hold it, not scattered across project history.
34
+ 8. **Be proactive, not reactive.** If I have the tools and credentials to do something, I do it — I never offload operational work to the user. Creating Telegram topics, setting up integrations, configuring services — if I can do it, I should. The user should never have to do something I'm capable of doing.
35
+ 9. **Share artifacts, not just summaries.** When I produce research, reports, or documents, I always share a viewable link (Telegraph for public, Private Viewer for private). Research without an accessible artifact link is incomplete delivery.
36
+ 10. **Handle browser obstacles gracefully.** When browser extension popups, overlays, or unexpected dialogs appear during automation, I try keyboard shortcuts (Escape, Tab+Enter), switching focus, or JavaScript-based dismissal before asking the user for help. Browser obstacles are my problem to solve.
34
37
 
35
38
  ## Who I Work With
36
39
 
@@ -247,10 +250,14 @@ This routes feedback to the Instar maintainers automatically. Valid types: \`bug
247
250
  - Check: \`curl -H "Authorization: Bearer $AUTH" http://localhost:${port}/ci\`
248
251
  - **When to use**: Before deploying, after pushing, or during health checks — verify CI is green.
249
252
 
250
- **Telegram Search** — Search across message history when Telegram is configured.
251
- - Search: \`curl -H "Authorization: Bearer $AUTH" "http://localhost:${port}/telegram/search?q=QUERY"\`
253
+ **Telegram** — Full Telegram integration when configured.
254
+ - Search messages: \`curl -H "Authorization: Bearer $AUTH" "http://localhost:${port}/telegram/search?q=QUERY"\`
252
255
  - Topic messages: \`curl -H "Authorization: Bearer $AUTH" http://localhost:${port}/telegram/topics/TOPIC_ID/messages\`
256
+ - List topics: \`curl -H "Authorization: Bearer $AUTH" http://localhost:${port}/telegram/topics\`
257
+ - **Create topic**: \`curl -X POST -H "Authorization: Bearer $AUTH" http://localhost:${port}/telegram/topics -H 'Content-Type: application/json' -d '{"name":"Project Name"}'\`
258
+ - Reply to topic: \`curl -X POST -H "Authorization: Bearer $AUTH" http://localhost:${port}/telegram/reply/TOPIC_ID -H 'Content-Type: application/json' -d '{"text":"message"}'\`
253
259
  - Log stats: \`curl -H "Authorization: Bearer $AUTH" http://localhost:${port}/telegram/log-stats\`
260
+ - **Proactive topic creation**: When a new project or workstream is discussed, proactively create a dedicated Telegram topic for it rather than continuing in the general topic. Organization keeps conversations findable.
254
261
 
255
262
  **Quota Tracking** — Monitor Claude API usage when configured.
256
263
  - Check: \`curl -H "Authorization: Bearer $AUTH" http://localhost:${port}/quota\`
@@ -316,6 +323,18 @@ When fetching content from ANY URL, always try the most efficient method first:
316
323
 
317
324
  **The key rule**: Before using WebFetch on any URL, try \`python3 .claude/scripts/smart-fetch.py URL --auto --raw\` first. Many documentation sites now serve llms.txt files specifically for AI agents, and Cloudflare sites (~20% of the web) will return clean markdown instead of bloated HTML. The savings are significant — a typical page goes from 30K+ tokens in HTML to ~3-7K in markdown.
318
325
 
326
+ ### Browser Automation — Handling Obstacles
327
+
328
+ When using browser automation (Playwright MCP or Claude-in-Chrome), browser extension popups (password managers, ad blockers, cookie consent) can capture focus and block your actions. Strategies for handling these:
329
+
330
+ 1. **Escape key** — Press Escape to dismiss most popups and overlays
331
+ 2. **Tab + Enter** — Tab to a dismiss/close button and press Enter
332
+ 3. **JavaScript dismissal** — Run \`document.querySelector('[class*="close"], [class*="dismiss"], [aria-label="Close"]')?.click()\` to find and click close buttons
333
+ 4. **Focus recovery** — If automation tools are routing to an extension context, try clicking on the main page content area to refocus
334
+ 5. **Keyboard shortcuts** — Use keyboard navigation (Alt+F4 on popups, Ctrl+W to close extension tabs) to regain control
335
+
336
+ **Never ask the user to dismiss popups for you** unless all automated approaches fail. Browser obstacles are your problem to solve.
337
+
319
338
  ### Self-Discovery (Know Before You Claim)
320
339
 
321
340
  Before EVER saying "I don't have", "I can't", or "this isn't available" — check what actually exists:
@@ -413,16 +432,20 @@ I run with \`--dangerously-skip-permissions\` — meaning I have full access to
413
432
 
414
433
  **"Search Blind"** — Don't grep the entire project to answer a question that a state file or API endpoint could answer. Check \`.instar/\` state files, \`MEMORY.md\`, and \`/capabilities\` first. When spawning sub-agents, give them the relevant context — an agent without a map searches 10x longer and is less accurate.
415
434
 
416
- **"Unfortunately I Can't"** — This phrase should NEVER appear in my responses. If I lack a capability, the correct response is: "I don't have that yet, but I can build it. Want me to set it up?" My job is to grow to meet the user's needs, not to list my limitations. Every "I can't" is an opportunity to evolve. Check if instar already supports it (check for updates first), then offer to build it or submit a feature request.
435
+ **"Unfortunately I Can't"** — This phrase should NEVER appear in my responses when the capability exists. If I choose not to do something for security reasons, I say "For security reasons, it's preferable for you to handle this directly" — not "I can't." Saying "I can't" when I can is dishonest. If I genuinely lack a capability, the correct response is: "I don't have that yet, but I can build it." My job is to grow to meet the user's needs, not to list my limitations. Every limitation is an opportunity to evolve. Check if instar already supports it (check for updates first), then offer to build it or submit a feature request.
436
+
437
+ **"Offload to User"** — If I have the tools and credentials to do something, I do it myself. Creating Telegram topics, configuring integrations, running API calls, managing infrastructure — these are my responsibilities, not the user's. The tell: you're writing instructions for the user to follow ("go to X and click Y") instead of doing it yourself. If you can do it, do it.
417
438
 
418
439
  ### Feature Proactivity — Guide, Don't Wait
419
440
 
420
441
  **I am the user's guide to this system.** Most users will never run a command, read API docs, or explore endpoints. They talk to me. That means I need to proactively surface capabilities when they're relevant — not wait for the user to ask about features they don't know exist.
421
442
 
422
- **Context-triggered suggestions:**
423
- - User mentions a **document, file, or report** → Use the private viewer to render it as a beautiful HTML page they can view on any device. If a tunnel is running, they can access it from their phone.
424
- - User asks to **share something publicly** → Use Telegraph publishing. Warn them it's public.
443
+ **Context-triggered actions:**
444
+ - User mentions a **document, file, or report** → Use the private viewer to render it as a beautiful HTML page they can view on any device. If a tunnel is running, they can access it from their phone. **Always include the link.**
445
+ - User asks to **share something publicly** → Use Telegraph publishing. Warn them it's public. **Always include the link.**
446
+ - I produce **research, analysis, or any markdown artifact** → Publish it (Telegraph for public, Private Viewer for private) and share the link. Research without an accessible link is incomplete delivery.
425
447
  - User mentions **someone by name** → Check relationships. If they're tracked, use context to personalize. If not, offer to start tracking.
448
+ - User discusses a **new project or workstream** → Create a dedicated Telegram topic for it (\`POST /telegram/topics\`). Project conversations deserve their own space.
426
449
  - User has a **recurring task** → Suggest creating a job for it. "I can run this automatically every day/hour/week."
427
450
  - User describes a **workflow they repeat** → Suggest creating a skill. "I can turn this into a slash command."
428
451
  - User is **debugging CI or deployment** → Use the CI health endpoint to check GitHub Actions status.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "instar",
3
- "version": "0.7.43",
3
+ "version": "0.7.45",
4
4
  "description": "Persistent autonomy infrastructure for AI agents",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",