@joenandez/tldr 1.0.1 → 1.1.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.
Files changed (31) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/tldr-agent +3 -2
  4. package/install/tldr-agent-bootstrap.sh +7 -0
  5. package/package.json +7 -6
  6. package/release/activation-manifest.json +6 -6
  7. package/release/payloads/arm64/TldrAgentAegis.pkg +0 -0
  8. package/release/payloads/arm64/tldr-agent.tar.gz +0 -0
  9. package/release/starport-release.json +2 -2
  10. package/skills/tldr/SKILL.md +37 -36
  11. package/src/lib/aegis_native_distribution.mjs +1 -1
  12. package/src/lib/aegis_protocol.mjs +1 -1
  13. package/src/lib/starport_onboarding.mjs +303 -6
  14. package/src/lib/starport_orchestrator.mjs +21 -20
  15. package/src/lib/starport_runtime.mjs +28 -5
  16. package/src/lib/tightbeam_channel.mjs +63 -119
  17. package/src/lib/tightbeam_channel_runtime.mjs +76 -17
  18. package/src/lib/tightbeam_email_adapter.mjs +10 -0
  19. package/src/lib/tightbeam_email_delivery_channel.mjs +107 -133
  20. package/src/lib/tightbeam_email_provider_map.mjs +337 -0
  21. package/src/lib/tightbeam_inbound_publish.mjs +84 -0
  22. package/src/lib/tightbeam_welcome_dispatch.mjs +129 -33
  23. package/src/lib/tldr_agent_diagnostic_schema.mjs +1 -0
  24. package/src/lib/transports/email/render/email.mjs +66 -180
  25. package/src/lib/transports/email/render/html.mjs +37 -80
  26. package/src/lib/transports/email/render/text.mjs +2 -2
  27. package/src/lib/transports/email/render/tldr.mjs +10 -88
  28. package/src/lib/transports/email/render/tokens.mjs +56 -75
  29. package/src/lib/transports/email/templates.mjs +38 -27
  30. package/src/lib/transports/email.mjs +21 -1
  31. package/src/lib/transports/email/render/glyphs.mjs +0 -66
@@ -12,7 +12,7 @@
12
12
  "source": {
13
13
  "source": "npm",
14
14
  "package": "@joenandez/tldr",
15
- "version": "1.0.1"
15
+ "version": "1.1.0"
16
16
  },
17
17
  "category": "productivity",
18
18
  "homepage": "https://github.com/joenandez/tldr#readme"
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "tldr",
4
4
  "displayName": "tldr;",
5
- "version": "1.0.1",
5
+ "version": "1.1.0",
6
6
  "description": "Set up private owner email for Claude Code and continue the same session when the owner replies.",
7
7
  "author": {
8
8
  "name": "Codename, Inc."
package/bin/tldr-agent CHANGED
@@ -30,8 +30,9 @@ case "$operation" in
30
30
  tldr_agent_home=${TLDR_AGENT_HOME:-${HOME}/.tldr-agent}
31
31
  runtime_node="${tldr_agent_home}/install/runtime/bin/node"
32
32
  if [ ! -x "${runtime_node}" ]; then
33
- printf '%s\n' '{"ok":false,"data":null,"error":{"code":"LOCAL_SNAPSHOT_UNAVAILABLE","message":"tldr; local snapshot runtime is unavailable.","retryable":false,"remediation":"Run npm run local:update."}}'
34
- exit 1
33
+ exec "${plugin_root}/install/tldr-agent-bootstrap.sh" \
34
+ --package-root "${plugin_root}" \
35
+ --operation "${operation}" "$@"
35
36
  fi
36
37
  exec "${runtime_node}" "${plugin_root}/src/lib/local_snapshot_front_door.mjs" \
37
38
  "${operation}" "$@"
@@ -41,6 +41,13 @@ installed_manifest="${install_root}/activation-manifest.json"
41
41
  run_installed() {
42
42
  PATH="${install_root}/runtime/bin:/usr/bin:/bin"
43
43
  export PATH TLDR_AGENT_HOME
44
+ if [ -f "${package_root}/LOCAL-SNAPSHOT-MANIFEST.json" ]; then
45
+ TLDR_AGENT_PLUGIN_ROOT=${package_root}
46
+ export TLDR_AGENT_PLUGIN_ROOT
47
+ exec "$runtime_node" \
48
+ "${package_root}/src/lib/local_snapshot_front_door.mjs" \
49
+ "$operation" "$@"
50
+ fi
44
51
  exec "$runtime_node" "$entrypoint" "$operation" "$@"
45
52
  }
46
53
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joenandez/tldr",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "os": [
5
5
  "darwin"
6
6
  ],
@@ -143,6 +143,8 @@
143
143
  "src/lib/tightbeam_channel_runtime.mjs",
144
144
  "src/lib/tightbeam_email_adapter.mjs",
145
145
  "src/lib/tightbeam_email_delivery_channel.mjs",
146
+ "src/lib/tightbeam_email_provider_map.mjs",
147
+ "src/lib/tightbeam_inbound_publish.mjs",
146
148
  "src/lib/tightbeam_welcome_dispatch.mjs",
147
149
  "src/lib/starport_native_lifecycle.mjs",
148
150
  "src/lib/store.mjs",
@@ -163,7 +165,6 @@
163
165
  "src/lib/transports/email/inbound_body.mjs",
164
166
  "src/lib/transports/email/inbound_dead_letter.mjs",
165
167
  "src/lib/transports/email/render/email.mjs",
166
- "src/lib/transports/email/render/glyphs.mjs",
167
168
  "src/lib/transports/email/render/html.mjs",
168
169
  "src/lib/transports/email/render/markdown.mjs",
169
170
  "src/lib/transports/email/render/markdown_inline.mjs",
@@ -180,14 +181,14 @@
180
181
  "scripts": {
181
182
  "pretest": "NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_provenance_manifest.mjs",
182
183
  "test": "npm run test:starport && npm run test:product",
183
- "test:starport": "NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_starport_plugin_contract.mjs tests/test_starport_activation.mjs tests/test_starport_native_lifecycle.mjs tests/test_starport_orchestrator.mjs tests/test_starport_onboarding.mjs tests/test_starport_front_door.mjs tests/test_starport_uninstall.mjs tests/test_starport_release_closure.mjs tests/test_tldr_tightbeam_packed_cross_product.mjs tests/test_tightbeam_channel_real_daemon.mjs tests/test_tightbeam_email_inbound_bridge.mjs tests/test_tightbeam_email_inbound_real_daemon.mjs tests/test_tightbeam_email_outbound_adapter.mjs tests/test_tightbeam_email_outbound_real_daemon.mjs",
184
+ "test:starport": "NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_starport_plugin_contract.mjs tests/test_starport_activation.mjs tests/test_starport_native_lifecycle.mjs tests/test_starport_orchestrator.mjs tests/test_starport_daemon_activation_order.mjs tests/test_starport_onboarding.mjs tests/test_starport_front_door.mjs tests/test_starport_uninstall.mjs tests/test_starport_release_closure.mjs tests/test_tldr_tightbeam_packed_cross_product.mjs tests/test_tldr_tightbeam_packed_welcome.mjs tests/test_tightbeam_channel_real_daemon.mjs tests/test_tightbeam_identity_reregistration.mjs tests/test_tightbeam_email_inbound_bridge.mjs tests/test_tightbeam_email_inbound_real_daemon.mjs tests/test_tightbeam_email_outbound_adapter.mjs tests/test_tightbeam_email_outbound_real_daemon.mjs",
184
185
  "test:release": "node --test tests/test_public_release_export.mjs tests/test_release_skill.mjs",
185
- "test:product": "NODE_OPTIONS=--conditions=tldr-agent-test node --test --test-concurrency=1 tests/test_tldr_agent_tightbeam_retirement.mjs tests/test_aegis_setup_registration_ux.mjs tests/test_aegis_protocol.mjs tests/test_tldr_agent_agentmail_transport.mjs tests/test_tldr_agent_daemon_polling.mjs tests/test_tightbeam_email_outbound_adapter.mjs tests/test_tldr_agent_attachment_behavior.mjs",
186
- "test:tightbeam-cross-product": "TIGHTBEAM_CROSS_PRODUCT_REQUIRED=1 NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_tldr_tightbeam_packed_cross_product.mjs",
186
+ "test:product": "NODE_OPTIONS=--conditions=tldr-agent-test node --test --test-concurrency=1 tests/test_tldr_agent_tightbeam_retirement.mjs tests/test_aegis_setup_registration_ux.mjs tests/test_aegis_protocol.mjs tests/test_tldr_agent_agentmail_transport.mjs tests/test_tldr_agent_daemon_polling.mjs tests/test_tightbeam_email_outbound_adapter.mjs tests/test_tldr_agent_attachment_behavior.mjs tests/test_aegis_setup_theme.mjs",
187
+ "test:tightbeam-cross-product": "TIGHTBEAM_CROSS_PRODUCT_REQUIRED=1 NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_tldr_tightbeam_packed_cross_product.mjs tests/test_tldr_tightbeam_packed_welcome.mjs",
187
188
  "test:packed-acceptance": "node --test tests/test_tldr_agent_packed_acceptance.mjs",
188
189
  "test:tldr-agent-contracts": "NODE_OPTIONS=--conditions=tldr-agent-test node --test --test-reporter=tap tests/contracts/test_tldr_agent_exclusions.mjs",
189
190
  "test:aegis-outbound": "NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_aegis_phase4_outbound.mjs tests/test_aegis_phase8_artifact_verifier.mjs tests/test_aegis_phase8_evidence.mjs",
190
- "test:aegis-integration": "NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_aegis_full_uninstall.mjs tests/test_aegis_package_daemon_activation.mjs tests/test_aegis_setup_registration_ux.mjs tests/test_aegis_three_inbox_live_harness.mjs",
191
+ "test:aegis-integration": "NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/test_aegis_full_uninstall.mjs tests/test_aegis_package_daemon_activation.mjs tests/test_aegis_setup_registration_ux.mjs tests/test_aegis_three_inbox_live_harness.mjs tests/test_aegis_setup_theme.mjs",
191
192
  "test:tldr-agent-wave-contracts": "NODE_OPTIONS=--conditions=tldr-agent-test node --test --test-reporter=tap tests/contracts/test_tldr_agent_email_only_exclusions.mjs tests/contracts/test_tldr_agent_private_resume_prune.mjs tests/contracts/test_tldr_agent_minimum_runtime_closure.mjs",
192
193
  "test:tldr-agent-minimum-runtime": "NODE_OPTIONS=--conditions=tldr-agent-test node --test tests/contracts/test_tldr_agent_minimum_runtime_closure.mjs",
193
194
  "test:tldr-agent-contracts:red": "NODE_OPTIONS=--conditions=tldr-agent-test node scripts/verify-tldr-agent-contract-red.mjs",
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release": "1.0.1",
3
+ "release": "1.1.0",
4
4
  "plugin_manifest": {
5
5
  "path": ".claude-plugin/plugin.json",
6
6
  "bytes": 618,
7
- "sha256": "c70a39f6a330c3700ceeead93380de3740352ba39a1c212c973024a305392502"
7
+ "sha256": "e139bb495f723af5ce5f5ea19afa0c3d40b7dd4ccc59ce68c7e6f1134b5a1544"
8
8
  },
9
9
  "hook_manifest": {
10
10
  "path": "hooks/hooks.json",
@@ -25,13 +25,13 @@
25
25
  },
26
26
  "tldr_agent": {
27
27
  "path": "release/payloads/arm64/tldr-agent.tar.gz",
28
- "bytes": 369860,
29
- "sha256": "6e53dbe587d2e6d8ddc0ebd63a43c7c10b77dc82df44d8d2ab8d48a5de981ed1"
28
+ "bytes": 371077,
29
+ "sha256": "3f5505944fcea137e520d446a3a76e9cf06e7f9badffff8def716c16be9d8f45"
30
30
  },
31
31
  "aegis": {
32
32
  "path": "release/payloads/arm64/TldrAgentAegis.pkg",
33
- "bytes": 291409,
34
- "sha256": "84dfad75baaa6ef2908fa46ff6dd0d976be4e72dd78b4d67a9536e7cddcb6dab"
33
+ "bytes": 307609,
34
+ "sha256": "7aba314597caa3636f03cb6aee4a7626e93b88119e8628b56273c983f736c51b"
35
35
  }
36
36
  }
37
37
  }
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "schema_version": 1,
3
3
  "phase": "source",
4
- "release": "1.0.1",
4
+ "release": "1.1.0",
5
5
  "source_commit": null,
6
6
  "npm": {
7
7
  "package": "@joenandez/tldr",
8
- "version": "1.0.1",
8
+ "version": "1.1.0",
9
9
  "publication": {
10
10
  "status": "pending",
11
11
  "dist_integrity": null,
@@ -1,31 +1,26 @@
1
1
  ---
2
2
  name: tldr
3
- description: "Use tldr; to set up, check, configure, repair, or uninstall the installed plugin. It handles signed Aegis enrollment and Tightbeam email-channel registration without exposing private identity settings."
3
+ description: "Use tldr; to set up, check, configure, repair, or uninstall the installed plugin."
4
4
  version: 3
5
5
  ---
6
6
 
7
7
  # tldr;
8
8
 
9
- tldr; is a lifecycle-only plugin. It owns signed Aegis enrollment, verified-owner
10
- security, rendering, polling, AgentMail integration, and the provider-thread
11
- mapping used by its Tightbeam email channel. Tightbeam is the sole routine
12
- message and delivery authority.
9
+ tldr; is a lifecycle concierge for setup and safe product management. It guides the user through one current lifecycle action at a time; it is not a general messaging interface.
13
10
 
14
11
  ## Lifecycle front door
15
12
 
16
- Run only the bundled plugin launcher. Claude Code resolves its own plugin root:
13
+ Run only the bundled launcher. Use the command block for the current host:
17
14
 
18
15
  ```bash
16
+ # Claude Code
19
17
  "${CLAUDE_PLUGIN_ROOT}/bin/tldr-agent" setup --json
20
18
  "${CLAUDE_PLUGIN_ROOT}/bin/tldr-agent" status --json
21
19
  "${CLAUDE_PLUGIN_ROOT}/bin/tldr-agent" configure --json
22
20
  "${CLAUDE_PLUGIN_ROOT}/bin/tldr-agent" repair --json
23
21
  "${CLAUDE_PLUGIN_ROOT}/bin/tldr-agent" uninstall --json
24
- ```
25
-
26
- Codex resolves its own plugin root:
27
22
 
28
- ```bash
23
+ # Codex
29
24
  "${PLUGIN_ROOT}/bin/tldr-agent" setup --json
30
25
  "${PLUGIN_ROOT}/bin/tldr-agent" status --json
31
26
  "${PLUGIN_ROOT}/bin/tldr-agent" configure --json
@@ -33,31 +28,37 @@ Codex resolves its own plugin root:
33
28
  "${PLUGIN_ROOT}/bin/tldr-agent" uninstall --json
34
29
  ```
35
30
 
36
- Map `set up` and `Continue setting up tldr;` to `setup`; `check` and “is
37
- tldr; ready?” to `status`; owner or provider changes to `configure`; broken,
38
- unavailable, or explicit repair requests to `repair`; and removal to
39
- `uninstall`. Report the returned safe state and its single remediation. Do not
40
- probe private files, invent a second recovery path, or invoke a globally
41
- installed executable. If the host cannot resolve its plugin root, report that
42
- the bundled launcher context is unavailable and stop.
43
-
44
- Setup acquires and verifies the app-owned runtime, then hands private enrollment
45
- to the signed Aegis app. Tell the user before Aegis opens. Email and AgentMail
46
- credentials belong only in that native surface; never ask for them in chat,
47
- arguments, environment variables, or files. When an AgentMail account or key is
48
- needed, direct the user to <https://console.agentmail.to/> and resume only after
49
- they return from Aegis.
50
-
51
- Use these state meanings:
52
-
53
- - `secure-setup-required`: announce the signed Aegis handoff and run setup.
54
- - `confirmation-required`: normal human waiting, not failure. Give only
55
- `Continue setting up tldr;`.
56
- - `ready-unverified`: setup is ready and its Tightbeam email route is registered.
57
- - `onboarding-verified`: setup is complete; repeated setup must not reinstall
58
- components or reopen enrollment.
31
+ Map `set up` and `Continue setting up tldr;` to `setup`; `check` and “is tldr; ready?” to `status`; owner or provider changes to `configure`; broken, unavailable, or explicit repair requests to `repair`; and removal to `uninstall`. Report the returned safe state and its single returned remediation. Do not probe private files, invent another recovery path, or use a globally installed executable. If the host cannot resolve its plugin root, explain that the bundled launcher context is unavailable and stop.
32
+
33
+ ## Guided setup
34
+
35
+ Use this predetermined guidance for a first-time setup. Keep sensitive input in the native tldr; app and never ask for an API key or verification code in chat, command arguments, environment variables, or files.
36
+
37
+ 1. **Introduction:** “Let’s set up tldr;. It takes a few minutes. I’ll open the tldr; app, where you’ll connect AgentMail and verify your email. Your email address, API key, and verification code stay in the app and are never included in this chat.”
38
+ 2. **App handoff:** Start setup, then tell the user to continue in the tldr; app. Wait for its next safe state rather than interpreting private details.
39
+ 3. **Background access:** “macOS needs you to allow tldr; to run in the background so email replies can reach your agent sessions. In the tldr; app, choose **Open Login Items**, turn on **tldr;**, then choose **Continue**.”
40
+ 4. **AgentMail key:** “tldr; needs an AgentMail API key. If you don’t have one, sign in to AgentMail, open **API Keys**, choose **Create New API Key**, name it ‘tldr; on this Mac,’ and copy it. Paste the key only into the tldr; app.”
41
+ 5. **Verification:** “AgentMail is connected. Check your email for the verification code and enter it in the tldr; app. I can’t see or submit that code.”
42
+ 6. **Finalizing:** Tell the user that tldr; finalizes the existing connection and health checks without exposing internal details.
43
+ 7. **Success:** “tldr; is ready. I sent a welcome email from this agent session. Reply with anything—‘hello’ is enough—and this same session will answer to confirm that replies work. Replying is optional; setup is complete.” Then offer these use cases:
44
+ - “Email me a summary when you finish.”
45
+ - “Email me if you need input before continuing.”
46
+ - “Send me the decision and anything still blocked.”
47
+
48
+ ## Returning, repair, and removal
49
+
50
+ - **Returning/ready:** For `status`, give the concise ready result without replaying first-time guidance. An already ready installation stays ready and does not repeat setup or the welcome message. Use `configure` only for the existing product settings.
51
+ - **Repair:** If health says attention is required, say “tldr; needs attention” and give only the returned repair action. Correctable setup input errors stay in the app; do not turn them into a general repair workflow.
52
+ - **Uninstall:** Before `uninstall`, say: “Uninstalling tldr; removes its protected owner and AgentMail key, background service, product-owned agent hooks, and app files from this Mac. I’m opening the tldr; app so you can review and confirm the removal.” Never claim removal completed until `status` confirms it. After confirmed removal, present the exact plugin-removal command returned by tldr;.
53
+
54
+ ## Safe-state guidance
55
+
56
+ - `secure-setup-required`: give the introduction and start setup.
57
+ - `confirmation-required`: normal human waiting, not failure. Give only `Continue setting up tldr;`.
58
+ - `ready-unverified`: setup is ready; continue the current setup guidance.
59
+ - `onboarding-verified`: setup is complete. Repeated setup must not reinstall components, reopen enrollment, or repeat the welcome message.
60
+ - `onboarding-reconciling`: tldr; is ready, but do not claim the welcome message was delivered. Explain that the welcome message needs confirmation and give only the returned remediation; an ambiguous welcome is reconciled before retry.
61
+ - `welcome-delivery-failed`: tldr; is ready. Explain that a definitely failed welcome message can use the single returned remediation without reopening setup.
59
62
  - `repair-required` or `unavailable`: give the returned repair action only.
60
63
 
61
- For configure and uninstall, explain the impact before opening signed Aegis.
62
- After protected uninstall succeeds, present the exact plugin-removal command
63
- returned by tldr;. Never claim cleanup completed until status confirms it.
64
+ If any lifecycle command fails, follow its single remediation when present. Otherwise report the stable error code without probing private state.
@@ -15,7 +15,7 @@ import {
15
15
  requestAegisStatusSafe,
16
16
  } from "./aegis_client.mjs";
17
17
  import { sanitizeInstallerEnvironment } from "./aegis_installer_environment.mjs";
18
- const PACKAGE_RELEASE = "1.0.1";
18
+ const PACKAGE_RELEASE = "1.1.0";
19
19
  const RELEASE_MANIFEST_SCHEMA = 2;
20
20
  const BROKER_PROTOCOL_VERSION = 2;
21
21
  const SETUP_STATE_SCHEMA_VERSION = 2;
@@ -3,7 +3,6 @@ export const PROTOCOL_VERSION = 2;
3
3
  * beside the 32 KiB text body, and JSON escaping expands the markup. Mirrors
4
4
  * native/aegis-core/src/protocol.rs. */
5
5
  export const MAX_FRAME_BYTES = 524_288;
6
-
7
6
  const TRUSTED_TRANSACTION = [
8
7
  ["authorization", "string", 4096, true],
9
8
  ["transaction_id", "string", 256, true],
@@ -89,6 +88,7 @@ const SAFE_ERRORS = new Map([
89
88
  ["INVALID_REQUEST", "The broker request is invalid."],
90
89
  ["UNKNOWN_OPERATION", "The broker operation is not available."],
91
90
  ["UNAUTHORIZED", "The broker operation is not authorized."],
91
+ ["REPLY_PARENT_UNAUTHORIZED", "The reply parent is not authorized."],
92
92
  ["BROKER_UNAVAILABLE", "The protected broker is unavailable."],
93
93
  ["INVALID_TRANSITION", "The broker state transition is invalid."],
94
94
  ["POLICY_CORRUPT", "Protected broker policy is unavailable."],
@@ -1,13 +1,288 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { writeTextAtomic } from "./durable_file_io.mjs";
1
7
  import { renderTldrAgentWelcomeEmail } from "./transports/email/templates.mjs";
2
8
 
3
9
  export const WELCOME_IDEMPOTENCY_KEY = "tldr-agent-welcome:v1";
10
+ export const WELCOME_REASON =
11
+ "Confirm the setup session can receive owner replies";
12
+ const execFileAsync = promisify(execFile);
13
+ const WELCOME_EVIDENCE_VERSION = 1;
14
+ const WELCOME_EVIDENCE_FILE = "welcome-evidence.json";
15
+ const SAFE_WELCOME_REMEDIATION =
16
+ "Start a new supported agent session, then rerun tldr; setup.";
17
+ const DEFINITE_TIGHTBEAM_FAILURE_CODES = new Set([
18
+ "session_unavailable",
19
+ "route_unavailable",
20
+ "permission_denied",
21
+ "bootstrap_required",
22
+ ]);
4
23
 
5
24
  async function noWelcomeEvidence() {
6
25
  return "not-started";
7
26
  }
8
27
 
9
- function status(value) {
10
- return Object.freeze({ status: value });
28
+ function status(value, remediation = null) {
29
+ return Object.freeze({
30
+ status: value,
31
+ ...(typeof remediation === "string" && remediation.length > 0
32
+ ? { remediation }
33
+ : {}),
34
+ });
35
+ }
36
+
37
+ function sessionEnvironment(session) {
38
+ const sessionId = session?.sessionId;
39
+ if (typeof sessionId !== "string" || sessionId.length === 0) return null;
40
+ return session?.identity?.runtime === "codex"
41
+ ? { CODEX_THREAD_ID: sessionId }
42
+ : { CLAUDE_CODE_SESSION_ID: sessionId };
43
+ }
44
+
45
+ function welcomeData(result) {
46
+ const value = result?.result ?? result?.data ?? result;
47
+ if (!value || typeof value !== "object") return {};
48
+ const delivery = Array.isArray(value.channel_deliveries)
49
+ ? value.channel_deliveries.find(
50
+ (item) =>
51
+ item?.selector === "email" && typeof item.delivery_id === "string",
52
+ )
53
+ : null;
54
+ return Object.fromEntries(
55
+ [
56
+ ["message_id", value.message_id],
57
+ ["conversation_id", value.conversation_id],
58
+ ["delivery_id", value.delivery_id ?? delivery?.delivery_id],
59
+ ["outcome", value.outcome],
60
+ ].filter(
61
+ ([, fieldValue]) =>
62
+ typeof fieldValue === "string" && fieldValue.length > 0,
63
+ ),
64
+ );
65
+ }
66
+
67
+ async function productionSessionRun({
68
+ command,
69
+ args,
70
+ env,
71
+ exec = execFileAsync,
72
+ }) {
73
+ try {
74
+ const { stdout } = await exec(command, args, {
75
+ encoding: "utf8",
76
+ maxBuffer: 64 * 1024,
77
+ env,
78
+ });
79
+ return JSON.parse(stdout);
80
+ } catch (error) {
81
+ const output = String(error?.stdout ?? "").trim();
82
+ if (output) {
83
+ try {
84
+ return JSON.parse(output);
85
+ } catch {
86
+ // The launch completed but did not return an interpretable result.
87
+ }
88
+ }
89
+ const stderr = String(error?.stderr ?? "");
90
+ const stableCode = stderr.match(/(?:^|\n)error ([a-z][a-z0-9_]*):/i)?.[1];
91
+ if (
92
+ /(?:^|\n)usage error:/i.test(stderr) ||
93
+ DEFINITE_TIGHTBEAM_FAILURE_CODES.has(stableCode)
94
+ ) {
95
+ return {
96
+ ok: false,
97
+ error: {
98
+ code: stableCode ?? "tightbeam_usage_error",
99
+ ambiguous: false,
100
+ },
101
+ };
102
+ }
103
+ return {
104
+ ok: false,
105
+ error: {
106
+ code:
107
+ error?.code === "ENOENT"
108
+ ? "tightbeam_unavailable"
109
+ : "welcome_send_failed",
110
+ ambiguous: error?.code !== "ENOENT",
111
+ },
112
+ };
113
+ }
114
+ }
115
+
116
+ export function createSessionWelcomeDispatcher({
117
+ command = process.env.TIGHTBEAM_BIN ||
118
+ join(
119
+ process.env.HOME ?? homedir(),
120
+ ".tightbeam",
121
+ "install",
122
+ "bin",
123
+ "tightbeam",
124
+ ),
125
+ stateRoot = process.env.TIGHTBEAM_STATE_ROOT,
126
+ session,
127
+ run = productionSessionRun,
128
+ evidence = null,
129
+ } = {}) {
130
+ const identityEnvironment = sessionEnvironment(session);
131
+ return async ({ subject, body } = {}) => {
132
+ if (!identityEnvironment) {
133
+ return {
134
+ ok: false,
135
+ error: {
136
+ code: "session_unavailable",
137
+ ambiguous: false,
138
+ remediation: SAFE_WELCOME_REMEDIATION,
139
+ },
140
+ };
141
+ }
142
+ try {
143
+ await evidence?.begin();
144
+ } catch {
145
+ return {
146
+ ok: false,
147
+ error: { code: "welcome_evidence_unavailable", ambiguous: true },
148
+ };
149
+ }
150
+ const result = await run({
151
+ command,
152
+ args: [
153
+ "--json",
154
+ "agent",
155
+ "send",
156
+ "--to",
157
+ "user",
158
+ "--channel",
159
+ "email",
160
+ "--subject",
161
+ subject,
162
+ "--reason",
163
+ WELCOME_REASON,
164
+ "--body",
165
+ body,
166
+ ],
167
+ env: {
168
+ PATH: process.env.PATH,
169
+ TIGHTBEAM_STATE_ROOT: stateRoot,
170
+ ...identityEnvironment,
171
+ },
172
+ });
173
+ const unavailable = result?.error?.code === "session_unavailable";
174
+ const normalized = unavailable
175
+ ? {
176
+ ok: false,
177
+ error: {
178
+ code: "session_unavailable",
179
+ ambiguous: false,
180
+ remediation: SAFE_WELCOME_REMEDIATION,
181
+ },
182
+ }
183
+ : result?.ok === true
184
+ ? { ok: true, data: welcomeData(result) }
185
+ : result;
186
+ try {
187
+ await evidence?.complete(normalized);
188
+ } catch {
189
+ return {
190
+ ok: false,
191
+ error: { code: "welcome_evidence_unavailable", ambiguous: true },
192
+ };
193
+ }
194
+ return normalized;
195
+ };
196
+ }
197
+
198
+ function evidenceRecord(value) {
199
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
200
+ const allowed = new Set([
201
+ "version",
202
+ "status",
203
+ "timestamp",
204
+ "message_id",
205
+ "conversation_id",
206
+ "delivery_id",
207
+ "outcome",
208
+ ]);
209
+ if (
210
+ Object.keys(value).some((key) => !allowed.has(key)) ||
211
+ value.version !== WELCOME_EVIDENCE_VERSION ||
212
+ typeof value.status !== "string" ||
213
+ typeof value.timestamp !== "string"
214
+ ) {
215
+ return null;
216
+ }
217
+ return value;
218
+ }
219
+
220
+ export function createWelcomeEvidenceStore({
221
+ home,
222
+ path = join(home || "", WELCOME_EVIDENCE_FILE),
223
+ now = () => new Date().toISOString(),
224
+ write = writeTextAtomic,
225
+ read = readFile,
226
+ findProviderAcceptanceByDelivery = async () => null,
227
+ } = {}) {
228
+ function writeRecord(record) {
229
+ write(path, `${JSON.stringify(record)}\n`, { durable: true, mode: 0o600 });
230
+ }
231
+
232
+ async function readRecord() {
233
+ try {
234
+ return evidenceRecord(JSON.parse(await read(path, "utf8")));
235
+ } catch (error) {
236
+ return error?.code === "ENOENT" ? undefined : null;
237
+ }
238
+ }
239
+
240
+ return Object.freeze({
241
+ path,
242
+ async begin() {
243
+ writeRecord({
244
+ version: WELCOME_EVIDENCE_VERSION,
245
+ status: "dispatching",
246
+ timestamp: now(),
247
+ });
248
+ },
249
+ async complete(result) {
250
+ const data = welcomeData(result);
251
+ const definiteFailure =
252
+ result?.ok === false && result?.error?.ambiguous !== true;
253
+ writeRecord({
254
+ version: WELCOME_EVIDENCE_VERSION,
255
+ status: definiteFailure
256
+ ? "failed"
257
+ : result?.ok === true
258
+ ? "returned"
259
+ : "ambiguous",
260
+ timestamp: now(),
261
+ ...data,
262
+ });
263
+ },
264
+ async read() {
265
+ const record = await readRecord();
266
+ if (record === undefined) return "not-started";
267
+ if (record === null) return "ambiguous";
268
+ if (record.status === "failed") return "failed";
269
+ if (typeof record.delivery_id !== "string") return "ambiguous";
270
+ try {
271
+ return (await findProviderAcceptanceByDelivery(record.delivery_id))
272
+ ? "accepted"
273
+ : "ambiguous";
274
+ } catch {
275
+ return "ambiguous";
276
+ }
277
+ },
278
+ });
279
+ }
280
+
281
+ function debugSetupTemplateDrift(stage, data) {
282
+ if (process.env.TLDR_AGENT_DEBUG_TEMPLATE_DRIFT !== "1") return;
283
+ process.stderr.write(
284
+ `[🪳 TEMP SETUP_EMAIL_TEMPLATE_DRIFT] ${stage} ${JSON.stringify(data)}\n`,
285
+ );
11
286
  }
12
287
 
13
288
  export function createStarportOnboarding({
@@ -22,6 +297,8 @@ export function createStarportOnboarding({
22
297
  throw new TypeError("Starport onboarding requires setup session and scope");
23
298
  }
24
299
 
300
+ let failedRemediation = null;
301
+
25
302
  async function readStatus() {
26
303
  const evidence = await readEvidence({
27
304
  scope,
@@ -37,9 +314,15 @@ export function createStarportOnboarding({
37
314
 
38
315
  async function send() {
39
316
  const before = await readStatus();
40
- if (before.status === "accepted") return before;
317
+ if (before.status === "accepted" || before.status === "ambiguous") {
318
+ return before;
319
+ }
41
320
  if (typeof dispatchMessage !== "function") return status("failed");
42
321
  const template = renderTldrAgentWelcomeEmail();
322
+ debugSetupTemplateDrift("setup-welcome-dispatch", {
323
+ template_version: template.template_version,
324
+ idempotency_key: WELCOME_IDEMPOTENCY_KEY,
325
+ });
43
326
  let delivery;
44
327
  try {
45
328
  delivery = await dispatchMessage({
@@ -60,10 +343,14 @@ export function createStarportOnboarding({
60
343
  return status(error?.ambiguous === true ? "ambiguous" : "failed");
61
344
  }
62
345
  if (delivery?.ok === false && delivery.error?.ambiguous !== true) {
346
+ failedRemediation =
347
+ typeof delivery.error?.remediation === "string"
348
+ ? delivery.error.remediation
349
+ : null;
63
350
  const afterFailure = await readStatus();
64
351
  return afterFailure.status === "not-started"
65
- ? status("failed")
66
- : afterFailure;
352
+ ? status("failed", failedRemediation)
353
+ : status(afterFailure.status, failedRemediation);
67
354
  }
68
355
  if (delivery?.error?.ambiguous === true) return status("ambiguous");
69
356
  const after = await readStatus();
@@ -73,4 +360,14 @@ export function createStarportOnboarding({
73
360
  return Object.freeze({ status: readStatus, send });
74
361
  }
75
362
 
76
- export const _internals = Object.freeze({ noWelcomeEvidence });
363
+ export const _internals = Object.freeze({
364
+ DEFINITE_TIGHTBEAM_FAILURE_CODES,
365
+ noWelcomeEvidence,
366
+ SAFE_WELCOME_REMEDIATION,
367
+ WELCOME_EVIDENCE_FILE,
368
+ WELCOME_EVIDENCE_VERSION,
369
+ evidenceRecord,
370
+ sessionEnvironment,
371
+ productionSessionRun,
372
+ welcomeData,
373
+ });