@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
@@ -118,6 +118,18 @@ export function createStarportOrchestrator({
118
118
  "Check tldr;",
119
119
  );
120
120
  }
121
+ if (
122
+ welcome?.status === "failed" &&
123
+ typeof welcome.remediation === "string" &&
124
+ welcome.remediation.length > 0
125
+ ) {
126
+ return success(
127
+ "welcome-delivery-failed",
128
+ COMPONENTS,
129
+ "start-supported-session",
130
+ welcome.remediation,
131
+ );
132
+ }
121
133
  return success(
122
134
  "ready-unverified",
123
135
  COMPONENTS,
@@ -131,18 +143,9 @@ export function createStarportOrchestrator({
131
143
  if (preflightFailure) return preflightFailure;
132
144
  const before = await status();
133
145
  if (before.data.state === "onboarding-verified") {
134
- const configured = await native.configure?.();
135
- if (configured?.ok === false) return configured;
136
- const after = await status();
137
- const registrationFailure = await registerReadyEmailChannel(
138
- after.data.state,
139
- );
140
- return registrationFailure ?? after;
146
+ return before;
141
147
  }
142
- if (
143
- before.data.state === "ready-unverified" ||
144
- before.data.state === "onboarding-reconciling"
145
- ) {
148
+ if (before.data.state === "ready-unverified") {
146
149
  const registrationFailure = await registerReadyEmailChannel(
147
150
  before.data.state,
148
151
  );
@@ -150,13 +153,13 @@ export function createStarportOrchestrator({
150
153
  await onboarding.send?.();
151
154
  return status();
152
155
  }
156
+ if (before.data.state === "onboarding-reconciling") return before;
157
+ if (before.data.state === "welcome-delivery-failed") return before;
158
+ const registrationFailure = await registerEmailChannel();
159
+ if (registrationFailure) return registrationFailure;
153
160
  await source?.install?.();
154
161
  await native.setup?.();
155
162
  const after = await status();
156
- const registrationFailure = await registerReadyEmailChannel(
157
- after.data.state,
158
- );
159
- if (registrationFailure) return registrationFailure;
160
163
  if (after.data.state === "ready-unverified") {
161
164
  await onboarding.send?.();
162
165
  return status();
@@ -179,13 +182,11 @@ export function createStarportOrchestrator({
179
182
  async repair() {
180
183
  const preflightFailure = await preflightTightbeam();
181
184
  if (preflightFailure) return preflightFailure;
185
+ const registrationFailure = await registerEmailChannel();
186
+ if (registrationFailure) return registrationFailure;
182
187
  await source?.install?.();
183
188
  await native.repair?.();
184
- const after = await status();
185
- const registrationFailure = await registerReadyEmailChannel(
186
- after.data.state,
187
- );
188
- return registrationFailure ?? after;
189
+ return status();
189
190
  },
190
191
  async uninstall() {
191
192
  const result = await native.uninstall?.();
@@ -11,7 +11,12 @@ import {
11
11
  } from "./identity_state.mjs";
12
12
  import { resolveTldrAgentScope } from "./store.mjs";
13
13
  import { installVerifiedLocalAegisPackage } from "./starport_aegis_package.mjs";
14
- import { createStarportOnboarding } from "./starport_onboarding.mjs";
14
+ import {
15
+ _internals as onboardingInternals,
16
+ createSessionWelcomeDispatcher,
17
+ createStarportOnboarding,
18
+ createWelcomeEvidenceStore,
19
+ } from "./starport_onboarding.mjs";
15
20
  import { createStarportOrchestrator } from "./starport_orchestrator.mjs";
16
21
  import { createTightbeamChannel } from "./tightbeam_channel.mjs";
17
22
 
@@ -131,10 +136,16 @@ function resolveSetupSession(env = process.env) {
131
136
  function unavailableOnboarding() {
132
137
  return Object.freeze({
133
138
  async status() {
134
- return Object.freeze({ status: "failed" });
139
+ return Object.freeze({
140
+ status: "failed",
141
+ remediation: onboardingInternals.SAFE_WELCOME_REMEDIATION,
142
+ });
135
143
  },
136
144
  async send() {
137
- return Object.freeze({ status: "failed" });
145
+ return Object.freeze({
146
+ status: "failed",
147
+ remediation: onboardingInternals.SAFE_WELCOME_REMEDIATION,
148
+ });
138
149
  },
139
150
  });
140
151
  }
@@ -317,6 +328,17 @@ export async function createProductionStarportRuntime({
317
328
  tldrAgentHome: home,
318
329
  });
319
330
  const tightbeamService = tightbeam ?? createTightbeamChannel({ home });
331
+ const welcomeEvidence = createWelcomeEvidenceStore({
332
+ home,
333
+ findProviderAcceptanceByDelivery:
334
+ tightbeamService.findProviderAcceptanceByDelivery,
335
+ });
336
+ const dispatchWelcome = createSessionWelcomeDispatcher({
337
+ command: env.TIGHTBEAM_BIN,
338
+ stateRoot: env.TIGHTBEAM_STATE_ROOT,
339
+ session,
340
+ evidence: welcomeEvidence,
341
+ });
320
342
  const onboardingService =
321
343
  onboarding ??
322
344
  (session
@@ -324,8 +346,8 @@ export async function createProductionStarportRuntime({
324
346
  sessionId: session.sessionId,
325
347
  scope,
326
348
  home,
327
- dispatchMessage: ({ body, idempotencyKey }) =>
328
- tightbeamService.dispatchWelcome({ body, idempotencyKey }),
349
+ readEvidence: () => welcomeEvidence.read(),
350
+ dispatchMessage: dispatchWelcome,
329
351
  })
330
352
  : unavailableOnboarding());
331
353
  const inspector =
@@ -357,4 +379,5 @@ export const _internals = Object.freeze({
357
379
  normalizedArchitecture,
358
380
  resolveSetupSession,
359
381
  shouldInstallBundledAegis,
382
+ unavailableOnboarding,
360
383
  });
@@ -1,21 +1,28 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join, resolve } from "node:path";
3
3
  import { createTightbeamEmailDeliveryChannel } from "./tightbeam_email_delivery_channel.mjs";
4
+ import { createTightbeamInboundPublisher } from "./tightbeam_inbound_publish.mjs";
4
5
  import {
5
6
  APPLICATION,
6
7
  AUTHORITY,
7
8
  ENDPOINT_SESSION,
8
9
  PRINCIPAL_REF,
9
10
  TIGHTBEAM_COMPATIBILITY,
11
+ WELCOME_APPLICATION,
12
+ WELCOME_ENDPOINT_SESSION,
10
13
  commandFailure,
14
+ debugIdentity,
11
15
  defaultIdentityStore,
12
16
  expectedPreflightArgs,
13
- inboundKey,
17
+ identityInvalid,
14
18
  launcherUnavailable,
15
19
  productionRun,
16
20
  unavailable,
17
21
  } from "./tightbeam_channel_runtime.mjs";
18
- import { createTightbeamWelcomeDispatcher } from "./tightbeam_welcome_dispatch.mjs";
22
+ import {
23
+ createTightbeamWelcomeDispatcher,
24
+ createTightbeamWelcomeIdentityManager,
25
+ } from "./tightbeam_welcome_dispatch.mjs";
19
26
 
20
27
  export function createTightbeamChannel({
21
28
  run = productionRun,
@@ -36,6 +43,24 @@ export function createTightbeamChannel({
36
43
  const persistIdentity = saveIdentity ?? ((identity) => store.save(identity));
37
44
  const execute = (options) => run({ command, ...options });
38
45
 
46
+ async function acquireApplicationCredential(application, identityKind) {
47
+ let result = await execute({
48
+ admin: true,
49
+ credentials: null,
50
+ args: ["app", "register", application],
51
+ });
52
+ if (result?.error?.code !== "TIGHTBEAM_APPLICATION_IDENTITY_CONFLICT") {
53
+ return { result, reregistered: false };
54
+ }
55
+ debugIdentity(`${identityKind}_identity_reregistering`, { application });
56
+ result = await execute({
57
+ admin: true,
58
+ credentials: null,
59
+ args: ["app", "reregister", application],
60
+ });
61
+ return { result, reregistered: true };
62
+ }
63
+
39
64
  async function preflight() {
40
65
  const result = await execute({
41
66
  admin: true,
@@ -54,18 +79,26 @@ export function createTightbeamChannel({
54
79
  }
55
80
 
56
81
  async function registerEmailChannel(route) {
57
- let identity = await readIdentity();
82
+ let identity;
83
+ try {
84
+ identity = await readIdentity();
85
+ } catch (error) {
86
+ if (error?.code !== "TLDR_EMAIL_IDENTITY_INVALID") throw error;
87
+ debugIdentity("identity_integrity_failed", { code: error.code });
88
+ return identityInvalid();
89
+ }
58
90
  if (!identity) {
59
- const created = await execute({
60
- admin: true,
61
- credentials: null,
62
- args: ["app", "register", APPLICATION],
63
- });
91
+ const acquisition = await acquireApplicationCredential(
92
+ APPLICATION,
93
+ "bridge",
94
+ );
95
+ const created = acquisition.result;
64
96
  if (
65
97
  commandFailure(created) ||
66
98
  typeof created.result?.app_id !== "string" ||
67
99
  typeof created.result?.app_secret !== "string"
68
100
  ) {
101
+ if (acquisition.reregistered && created?.ok === false) return created;
69
102
  return unavailable();
70
103
  }
71
104
  identity = {
@@ -176,126 +209,29 @@ export function createTightbeamChannel({
176
209
  : Object.freeze({ ok: true });
177
210
  }
178
211
 
179
- async function publishInboundEmail({
180
- binding,
181
- provider_message_id: providerMessageId,
182
- body,
183
- }) {
184
- if (
185
- !binding ||
186
- typeof binding.conversation_id !== "string" ||
187
- typeof binding.route_id !== "string" ||
188
- typeof binding.origin_endpoint_id !== "string" ||
189
- typeof providerMessageId !== "string" ||
190
- typeof body !== "string"
191
- ) {
192
- return Object.freeze({ ok: false, code: "thread_unmapped" });
193
- }
194
- const identity = await readIdentity();
195
- if (!identity) return Object.freeze({ ok: false, code: "not_configured" });
196
-
197
- const principal = await execute({
198
- admin: false,
199
- credentials: identity,
200
- args: [
201
- "principal",
202
- "register",
203
- "--authority",
204
- AUTHORITY,
205
- "--external-ref",
206
- PRINCIPAL_REF,
207
- "--display-name",
208
- "Owner",
209
- ],
210
- });
211
- if (
212
- commandFailure(principal) ||
213
- typeof principal.result?.principal_id !== "string"
214
- ) {
215
- return Object.freeze({ ok: false, code: "identity_unavailable" });
216
- }
217
- const endpoint = await execute({
218
- admin: false,
219
- credentials: identity,
220
- args: [
221
- "endpoint",
222
- "register",
223
- "--authority",
224
- AUTHORITY,
225
- "--principal",
226
- principal.result.principal_id,
227
- "--runtime",
228
- "reference",
229
- "--session",
230
- ENDPOINT_SESSION,
231
- "--reference",
232
- AUTHORITY,
233
- ],
234
- });
235
- if (
236
- commandFailure(endpoint) ||
237
- typeof endpoint.result?.endpoint_id !== "string" ||
238
- !Number.isInteger(endpoint.result?.process_generation)
239
- ) {
240
- return Object.freeze({ ok: false, code: "identity_unavailable" });
241
- }
242
- const routes = await execute({
243
- admin: false,
244
- credentials: identity,
245
- args: ["channel", "route", "list"],
246
- });
247
- const route = routes?.result?.routes?.find(
248
- (candidate) =>
249
- candidate?.selector === "email" &&
250
- candidate?.route_id === binding.route_id,
251
- );
252
- if (commandFailure(routes) || !route) {
253
- return Object.freeze({ ok: false, code: "route_mismatch" });
254
- }
255
- const committed = await execute({
256
- admin: false,
257
- credentials: identity,
258
- args: [
259
- "message",
260
- "commit",
261
- "--conversation",
262
- binding.conversation_id,
263
- "--from",
264
- principal.result.principal_id,
265
- "--body",
266
- body,
267
- "--key",
268
- inboundKey(providerMessageId),
269
- "--origin-channel-route",
270
- binding.route_id,
271
- "--inbound-target-endpoint",
272
- binding.origin_endpoint_id,
273
- "--effect",
274
- "none",
275
- "--sender-endpoint",
276
- endpoint.result.endpoint_id,
277
- "--process-generation",
278
- String(endpoint.result.process_generation),
279
- ],
280
- });
281
- if (
282
- commandFailure(committed) ||
283
- typeof committed.result?.message_id !== "string"
284
- ) {
285
- return Object.freeze({ ok: false, code: "publish_failed" });
286
- }
287
- return Object.freeze({ ok: true, message_id: committed.result.message_id });
288
- }
212
+ const ensureWelcomeIdentity = createTightbeamWelcomeIdentityManager({
213
+ readIdentity,
214
+ persistIdentity,
215
+ execute,
216
+ commandFailure,
217
+ unavailable,
218
+ identityInvalid,
219
+ debugIdentity,
220
+ acquireApplicationCredential,
221
+ application: WELCOME_APPLICATION,
222
+ authority: AUTHORITY,
223
+ });
289
224
 
290
225
  const dispatchWelcome = createTightbeamWelcomeDispatcher({
291
226
  registerEmailChannel,
227
+ ensureWelcomeIdentity,
292
228
  readIdentity,
293
229
  execute,
294
230
  commandFailure,
295
231
  unavailable,
296
232
  authority: AUTHORITY,
297
233
  principalRef: PRINCIPAL_REF,
298
- endpointSession: ENDPOINT_SESSION,
234
+ welcomeEndpointSession: WELCOME_ENDPOINT_SESSION,
299
235
  });
300
236
 
301
237
  const delivery = createTightbeamEmailDeliveryChannel({
@@ -307,6 +243,12 @@ export function createTightbeamChannel({
307
243
  principalRef: PRINCIPAL_REF,
308
244
  endpointSession: ENDPOINT_SESSION,
309
245
  });
246
+ const publishInboundEmail = createTightbeamInboundPublisher({
247
+ execute,
248
+ readIdentity,
249
+ commandFailure,
250
+ delivery,
251
+ });
310
252
 
311
253
  return Object.freeze({
312
254
  preflight,
@@ -323,4 +265,6 @@ export const _internals = Object.freeze({
323
265
  ENDPOINT_SESSION,
324
266
  PRINCIPAL_REF,
325
267
  TIGHTBEAM_COMPATIBILITY,
268
+ WELCOME_APPLICATION,
269
+ WELCOME_ENDPOINT_SESSION,
326
270
  });
@@ -1,8 +1,8 @@
1
1
  import { execFile } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { lstat, mkdir, readFile } from "node:fs/promises";
4
3
  import { join } from "node:path";
5
4
  import { promisify } from "node:util";
5
+ import { writeTextAtomic } from "./durable_file_io.mjs";
6
6
 
7
7
  const execFileAsync = promisify(execFile);
8
8
 
@@ -13,8 +13,10 @@ export const TIGHTBEAM_COMPATIBILITY = Object.freeze({
13
13
  });
14
14
  export const AUTHORITY = "tldr-email";
15
15
  export const APPLICATION = "tldr-email";
16
+ export const WELCOME_APPLICATION = "tldr-welcome";
16
17
  export const PRINCIPAL_REF = "verified-owner";
17
18
  export const ENDPOINT_SESSION = "tldr-email-owner";
19
+ export const WELCOME_ENDPOINT_SESSION = "tldr-welcome-sender";
18
20
 
19
21
  export function unavailable(failedDimensions = []) {
20
22
  const dimensions = [
@@ -53,6 +55,32 @@ export function launcherUnavailable() {
53
55
  });
54
56
  }
55
57
 
58
+ export function identityInvalid() {
59
+ return Object.freeze({
60
+ ok: false,
61
+ data: null,
62
+ error: Object.freeze({
63
+ code: "TLDR_EMAIL_IDENTITY_INVALID",
64
+ message: "tldr; cannot trust its local Tightbeam email identity.",
65
+ retryable: false,
66
+ remediation: "Repair tldr;",
67
+ }),
68
+ });
69
+ }
70
+
71
+ function invalidIdentityState() {
72
+ const error = new Error("TLDR Tightbeam email identity is invalid");
73
+ error.code = "TLDR_EMAIL_IDENTITY_INVALID";
74
+ return error;
75
+ }
76
+
77
+ export function debugIdentity(stage, data = {}) {
78
+ if (process.env.TLDR_AGENT_DEBUG_TIGHTBEAM_IDENTITY !== "1") return;
79
+ process.stderr.write(
80
+ `[🪳 TEMP tldr-enrollment-state-recovery] ${stage} ${JSON.stringify(data)}\n`,
81
+ );
82
+ }
83
+
56
84
  export function commandFailure(result) {
57
85
  return result?.ok !== true || result?.result?.compatible === false;
58
86
  }
@@ -61,20 +89,41 @@ export function defaultIdentityStore(home) {
61
89
  const path = join(home, "tightbeam-email-identity.json");
62
90
  return Object.freeze({
63
91
  async load() {
92
+ let metadata;
93
+ try {
94
+ metadata = await lstat(path);
95
+ } catch (error) {
96
+ if (error?.code === "ENOENT") return null;
97
+ throw invalidIdentityState();
98
+ }
99
+ if (!metadata.isFile()) throw invalidIdentityState();
100
+ let identity;
64
101
  try {
65
- const identity = JSON.parse(await readFile(path, "utf8"));
66
- return typeof identity?.app_id === "string" &&
67
- typeof identity?.app_secret === "string"
68
- ? identity
69
- : null;
102
+ identity = JSON.parse(await readFile(path, "utf8"));
70
103
  } catch {
71
- return null;
104
+ throw invalidIdentityState();
72
105
  }
106
+ if (
107
+ typeof identity?.app_id !== "string" ||
108
+ identity.app_id.length === 0 ||
109
+ typeof identity?.app_secret !== "string" ||
110
+ identity.app_secret.length === 0 ||
111
+ (identity.welcome !== undefined &&
112
+ (typeof identity.welcome?.app_id !== "string" ||
113
+ identity.welcome.app_id.length === 0 ||
114
+ typeof identity.welcome?.app_secret !== "string" ||
115
+ identity.welcome.app_secret.length === 0))
116
+ ) {
117
+ throw invalidIdentityState();
118
+ }
119
+ return identity;
73
120
  },
74
121
  async save(identity) {
75
122
  await mkdir(home, { recursive: true, mode: 0o700 });
76
- await writeFile(path, `${JSON.stringify(identity)}\n`, { mode: 0o600 });
77
- await chmod(path, 0o600);
123
+ writeTextAtomic(path, `${JSON.stringify(identity)}\n`, {
124
+ durable: true,
125
+ mode: 0o600,
126
+ });
78
127
  },
79
128
  });
80
129
  }
@@ -97,6 +146,23 @@ export async function productionRun({ command, admin, credentials, args }) {
97
146
  return JSON.parse(stdout);
98
147
  } catch (error) {
99
148
  const output = `${error?.stderr ?? ""}\n${error?.stdout ?? ""}`;
149
+ const registeredApplication = args[2];
150
+ if (
151
+ admin &&
152
+ args[0] === "app" &&
153
+ args[1] === "register" &&
154
+ [APPLICATION, WELCOME_APPLICATION].includes(registeredApplication) &&
155
+ /identity_conflict/.test(output) &&
156
+ output.includes(
157
+ `application named "${registeredApplication}" is already registered`,
158
+ )
159
+ ) {
160
+ return {
161
+ ok: false,
162
+ data: null,
163
+ error: { code: "TIGHTBEAM_APPLICATION_IDENTITY_CONFLICT" },
164
+ };
165
+ }
100
166
  if (
101
167
  admin &&
102
168
  args[0] === "authority" &&
@@ -145,10 +211,3 @@ export function expectedPreflightArgs() {
145
211
  ]),
146
212
  ];
147
213
  }
148
-
149
- export function inboundKey(providerMessageId) {
150
- return `tldr-email-inbound-${createHash("sha256")
151
- .update(providerMessageId)
152
- .digest("hex")
153
- .slice(0, 32)}`;
154
- }
@@ -44,6 +44,7 @@ export function createTightbeamEmailAdapter({ channel, send } = {}) {
44
44
  async function deliverOnce({
45
45
  sendContext = {},
46
46
  afterProviderAccepted,
47
+ afterReplyBindingRecorded,
47
48
  afterProviderRecorded,
48
49
  } = {}) {
49
50
  const claimed = await channel.claimEmailDelivery();
@@ -52,6 +53,15 @@ export function createTightbeamEmailAdapter({ channel, send } = {}) {
52
53
  if (!validClaim(claim)) {
53
54
  throw new TypeError("Tightbeam returned an invalid claimed delivery");
54
55
  }
56
+ if (typeof claim.reply_binding === "string") {
57
+ if (typeof channel.recordReplyBinding !== "function") {
58
+ throw new TypeError(
59
+ "Tightbeam email channel cannot persist reply bindings",
60
+ );
61
+ }
62
+ await channel.recordReplyBinding({ delivery: claim });
63
+ await afterReplyBindingRecorded?.({ claim });
64
+ }
55
65
  const accepted = await channel.findProviderAcceptanceByDelivery?.(
56
66
  claim.delivery_id,
57
67
  );