@fastagent-sh/fastagent 0.13.0 → 0.15.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 (238) hide show
  1. package/README.md +5 -5
  2. package/dist/agent.d.ts +20 -0
  3. package/dist/agent.js +9 -0
  4. package/dist/channels/context-buffer.d.ts +30 -0
  5. package/dist/channels/context-buffer.js +98 -0
  6. package/dist/channels/control.d.ts +28 -0
  7. package/dist/channels/control.js +214 -0
  8. package/dist/channels/feishu/card.js +1 -1
  9. package/dist/channels/feishu/context-buffer.d.ts +43 -0
  10. package/dist/channels/feishu/context-buffer.js +72 -0
  11. package/dist/channels/feishu/crypto.d.ts +4 -2
  12. package/dist/channels/feishu/crypto.js +4 -2
  13. package/dist/channels/feishu/feishu-api.d.ts +15 -7
  14. package/dist/channels/feishu/feishu-api.js +22 -4
  15. package/dist/channels/feishu/feishu.d.ts +38 -16
  16. package/dist/channels/feishu/feishu.js +286 -151
  17. package/dist/channels/feishu/invoke-turn.d.ts +24 -31
  18. package/dist/channels/feishu/invoke-turn.js +61 -62
  19. package/dist/channels/feishu/model.d.ts +98 -0
  20. package/dist/channels/feishu/model.js +9 -0
  21. package/dist/channels/feishu/normalize.d.ts +23 -0
  22. package/dist/channels/feishu/normalize.js +132 -0
  23. package/dist/channels/feishu/owned-threads.d.ts +7 -0
  24. package/dist/channels/feishu/owned-threads.js +47 -0
  25. package/dist/channels/feishu/parse.d.ts +21 -103
  26. package/dist/channels/feishu/parse.js +35 -145
  27. package/dist/channels/feishu/preview.d.ts +4 -7
  28. package/dist/channels/feishu/preview.js +26 -142
  29. package/dist/channels/feishu/register-app.d.ts +2 -1
  30. package/dist/channels/feishu/register-webhook.d.ts +2 -1
  31. package/dist/channels/feishu/scaffold/channel.ts +10 -3
  32. package/dist/channels/feishu/setup-mode.d.ts +8 -0
  33. package/dist/channels/feishu/setup-mode.js +2 -0
  34. package/dist/channels/feishu/ws-ingress.d.ts +28 -0
  35. package/dist/channels/feishu/ws-ingress.js +136 -0
  36. package/dist/channels/github/github.js +8 -6
  37. package/dist/channels/http.d.ts +14 -0
  38. package/dist/channels/http.js +35 -2
  39. package/dist/channels/invoke-turn-kit.d.ts +65 -0
  40. package/dist/channels/invoke-turn-kit.js +87 -0
  41. package/dist/channels/lark/lark.d.ts +4 -2
  42. package/dist/channels/lark/lark.js +4 -1
  43. package/dist/channels/lark/onboard.d.ts +8 -4
  44. package/dist/channels/lark/onboard.js +8 -0
  45. package/dist/channels/lark/scaffold/channel.ts +10 -3
  46. package/dist/channels/preview-kit.d.ts +109 -0
  47. package/dist/channels/preview-kit.js +183 -0
  48. package/dist/channels/seen.d.ts +5 -0
  49. package/dist/channels/seen.js +35 -0
  50. package/dist/channels/slack/bot-auth.d.ts +15 -0
  51. package/dist/channels/slack/bot-auth.js +146 -0
  52. package/dist/channels/slack/config-api.d.ts +60 -0
  53. package/dist/channels/slack/config-api.js +149 -0
  54. package/dist/channels/slack/context-buffer.d.ts +24 -0
  55. package/dist/channels/slack/context-buffer.js +37 -0
  56. package/dist/channels/slack/invoke-turn.d.ts +19 -0
  57. package/dist/channels/slack/invoke-turn.js +63 -0
  58. package/dist/channels/slack/manifest.d.ts +49 -0
  59. package/dist/channels/slack/manifest.js +69 -0
  60. package/dist/channels/slack/model.d.ts +67 -0
  61. package/dist/channels/slack/model.js +2 -0
  62. package/dist/channels/slack/onboard.d.ts +41 -0
  63. package/dist/channels/slack/onboard.js +120 -0
  64. package/dist/channels/slack/onboarding-state.d.ts +31 -0
  65. package/dist/channels/slack/onboarding-state.js +69 -0
  66. package/dist/channels/slack/owned-threads.d.ts +6 -0
  67. package/dist/channels/slack/owned-threads.js +43 -0
  68. package/dist/channels/slack/parse.d.ts +23 -0
  69. package/dist/channels/slack/parse.js +81 -0
  70. package/dist/channels/slack/preview.d.ts +24 -0
  71. package/dist/channels/slack/preview.js +359 -0
  72. package/dist/channels/slack/reaction.d.ts +24 -0
  73. package/dist/channels/slack/reaction.js +62 -0
  74. package/dist/channels/slack/register-webhook.d.ts +10 -0
  75. package/dist/channels/slack/register-webhook.js +49 -0
  76. package/dist/channels/slack/scaffold/channel.ts +33 -0
  77. package/dist/channels/slack/scaffold/slack-send.ts +171 -0
  78. package/dist/channels/slack/setup-server.d.ts +17 -0
  79. package/dist/channels/slack/setup-server.js +103 -0
  80. package/dist/channels/slack/slack-api.d.ts +77 -0
  81. package/dist/channels/slack/slack-api.js +415 -0
  82. package/dist/channels/slack/slack.d.ts +58 -0
  83. package/dist/channels/slack/slack.js +451 -0
  84. package/dist/channels/slack/welcomed.d.ts +5 -0
  85. package/dist/channels/slack/welcomed.js +32 -0
  86. package/dist/channels/state.js +3 -3
  87. package/dist/channels/stop-command.d.ts +6 -0
  88. package/dist/channels/stop-command.js +36 -0
  89. package/dist/channels/tasks.d.ts +13 -0
  90. package/dist/channels/tasks.js +10 -0
  91. package/dist/channels/telegram/context-buffer.d.ts +8 -17
  92. package/dist/channels/telegram/context-buffer.js +6 -85
  93. package/dist/channels/telegram/invoke-turn.d.ts +5 -22
  94. package/dist/channels/telegram/invoke-turn.js +11 -58
  95. package/dist/channels/telegram/preview.d.ts +4 -7
  96. package/dist/channels/telegram/preview.js +24 -142
  97. package/dist/channels/telegram/telegram.js +23 -9
  98. package/dist/channels/{feishu/text.d.ts → text.d.ts} +1 -1
  99. package/dist/channels/{feishu/text.js → text.js} +1 -1
  100. package/dist/channels/turn-queue.js +1 -1
  101. package/dist/channels/turn-store.d.ts +1 -1
  102. package/dist/channels/turn-store.js +2 -3
  103. package/dist/cli/add-feishu.d.ts +27 -0
  104. package/dist/{cli-add-feishu.js → cli/add-feishu.js} +167 -44
  105. package/dist/cli/add-slack.d.ts +10 -0
  106. package/dist/cli/add-slack.js +204 -0
  107. package/dist/{cli-auth.d.ts → cli/auth-view.d.ts} +1 -1
  108. package/dist/{cli-auth.js → cli/auth-view.js} +1 -1
  109. package/dist/cli/commands/add.d.ts +13 -0
  110. package/dist/cli/commands/add.js +274 -0
  111. package/dist/cli/commands/attach.d.ts +82 -0
  112. package/dist/cli/commands/attach.js +559 -0
  113. package/dist/cli/commands/chat.d.ts +4 -0
  114. package/dist/cli/commands/chat.js +21 -0
  115. package/dist/cli/commands/deploy.d.ts +15 -0
  116. package/dist/cli/commands/deploy.js +394 -0
  117. package/dist/cli/commands/dev.d.ts +11 -0
  118. package/dist/cli/commands/dev.js +82 -0
  119. package/dist/cli/commands/fire.d.ts +7 -0
  120. package/dist/cli/commands/fire.js +45 -0
  121. package/dist/cli/commands/info.d.ts +7 -0
  122. package/dist/cli/commands/info.js +108 -0
  123. package/dist/cli/commands/init.d.ts +8 -0
  124. package/dist/cli/commands/init.js +81 -0
  125. package/dist/cli/commands/invoke.d.ts +7 -0
  126. package/dist/cli/commands/invoke.js +28 -0
  127. package/dist/cli/commands/login.d.ts +6 -0
  128. package/dist/cli/commands/login.js +52 -0
  129. package/dist/cli/commands/models.d.ts +1 -0
  130. package/dist/cli/commands/models.js +15 -0
  131. package/dist/cli/commands/schedule.d.ts +12 -0
  132. package/dist/cli/commands/schedule.js +89 -0
  133. package/dist/cli/commands/start.d.ts +10 -0
  134. package/dist/cli/commands/start.js +97 -0
  135. package/dist/cli/commands/tool.d.ts +1 -0
  136. package/dist/cli/commands/tool.js +38 -0
  137. package/dist/cli/fail.d.ts +17 -0
  138. package/dist/cli/fail.js +32 -0
  139. package/dist/{invoke-stream.d.ts → cli/invoke-stream.d.ts} +1 -1
  140. package/dist/{invoke-stream.js → cli/invoke-stream.js} +4 -0
  141. package/dist/cli/kernel.d.ts +90 -0
  142. package/dist/cli/kernel.js +190 -0
  143. package/dist/cli/models-view.d.ts +21 -0
  144. package/dist/cli/models-view.js +66 -0
  145. package/dist/cli/program.d.ts +11 -0
  146. package/dist/cli/program.js +479 -0
  147. package/dist/cli/serve.d.ts +48 -0
  148. package/dist/cli/serve.js +248 -0
  149. package/dist/cli/shared.d.ts +44 -0
  150. package/dist/cli/shared.js +246 -0
  151. package/dist/cli.js +8 -1329
  152. package/dist/collect.d.ts +14 -3
  153. package/dist/collect.js +24 -0
  154. package/dist/core.d.ts +3 -1
  155. package/dist/core.js +2 -0
  156. package/dist/deploy/docker/plan.d.ts +45 -0
  157. package/dist/deploy/docker/plan.js +141 -0
  158. package/dist/deploy/docker/run.d.ts +40 -0
  159. package/dist/deploy/docker/run.js +126 -0
  160. package/dist/deploy/fly/plan.d.ts +3 -1
  161. package/dist/deploy/fly/plan.js +12 -7
  162. package/dist/deploy/fly/run.d.ts +5 -4
  163. package/dist/deploy/fly/run.js +16 -5
  164. package/dist/deploy/preflight.d.ts +10 -4
  165. package/dist/deploy/preflight.js +57 -12
  166. package/dist/deploy/railway/plan.d.ts +3 -1
  167. package/dist/deploy/railway/plan.js +12 -4
  168. package/dist/deploy/railway/run.d.ts +5 -4
  169. package/dist/deploy/railway/run.js +15 -5
  170. package/dist/deploy/runner.d.ts +6 -2
  171. package/dist/deploy/runner.js +1 -0
  172. package/dist/deploy/secrets.d.ts +2 -1
  173. package/dist/deploy/secrets.js +23 -3
  174. package/dist/dev-supervisor.d.ts +0 -2
  175. package/dist/dev-supervisor.js +7 -3
  176. package/dist/engines/pi/auth.js +160 -46
  177. package/dist/engines/pi/channel.d.ts +22 -16
  178. package/dist/engines/pi/channel.js +90 -60
  179. package/dist/engines/pi/chat.d.ts +4 -16
  180. package/dist/engines/pi/chat.js +8 -188
  181. package/dist/engines/pi/config.d.ts +23 -9
  182. package/dist/engines/pi/config.js +35 -5
  183. package/dist/engines/pi/create.d.ts +36 -7
  184. package/dist/engines/pi/create.js +63 -22
  185. package/dist/engines/pi/harness.d.ts +65 -1
  186. package/dist/engines/pi/harness.js +166 -2
  187. package/dist/engines/pi/invoke.d.ts +56 -3
  188. package/dist/engines/pi/invoke.js +340 -20
  189. package/dist/engines/pi/login.d.ts +11 -0
  190. package/dist/engines/pi/login.js +17 -5
  191. package/dist/engines/pi/models.d.ts +56 -10
  192. package/dist/engines/pi/models.js +61 -23
  193. package/dist/engines/pi/search-tools.d.ts +10 -0
  194. package/dist/engines/pi/search-tools.js +138 -0
  195. package/dist/engines/pi/session-builder.d.ts +16 -0
  196. package/dist/engines/pi/session-builder.js +308 -0
  197. package/dist/engines/pi/session-control.d.ts +50 -0
  198. package/dist/engines/pi/session-control.js +604 -0
  199. package/dist/engines/pi/sessions.d.ts +17 -2
  200. package/dist/engines/pi/sessions.js +9 -0
  201. package/dist/engines/pi/tool-context.d.ts +46 -11
  202. package/dist/engines/pi/tool-context.js +11 -9
  203. package/dist/engines/pi/tool.d.ts +35 -6
  204. package/dist/engines/pi/tool.js +47 -1
  205. package/dist/engines/pi/wake-tool.d.ts +0 -3
  206. package/dist/engines/pi/wake-tool.js +9 -7
  207. package/dist/engines/pi/workspace.d.ts +56 -1
  208. package/dist/engines/pi/workspace.js +75 -16
  209. package/dist/feishu.d.ts +1 -1
  210. package/dist/feishu.js +1 -1
  211. package/dist/host/node.d.ts +23 -6
  212. package/dist/host/node.js +5 -4
  213. package/dist/index.d.ts +1 -0
  214. package/dist/index.js +1 -0
  215. package/dist/lark.d.ts +1 -1
  216. package/dist/lark.js +1 -1
  217. package/dist/observe.js +3 -0
  218. package/dist/pi.d.ts +6 -4
  219. package/dist/pi.js +2 -1
  220. package/dist/scaffold/add-channel.d.ts +19 -6
  221. package/dist/scaffold/add-channel.js +127 -16
  222. package/dist/scaffold/templates/fastagent.config.mjs +5 -3
  223. package/dist/schedule/wakeups.d.ts +0 -3
  224. package/dist/schedule/wakeups.js +1 -1
  225. package/dist/session-remote.d.ts +53 -0
  226. package/dist/session-remote.js +336 -0
  227. package/dist/session.d.ts +265 -0
  228. package/dist/session.js +37 -0
  229. package/dist/slack.d.ts +2 -0
  230. package/dist/slack.js +2 -0
  231. package/dist/tunnel.d.ts +7 -4
  232. package/dist/tunnel.js +21 -10
  233. package/package.json +22 -7
  234. package/dist/channels/feishu/seen.d.ts +0 -5
  235. package/dist/channels/feishu/seen.js +0 -47
  236. package/dist/cli-add-feishu.d.ts +0 -8
  237. package/dist/cli-models.d.ts +0 -11
  238. package/dist/cli-models.js +0 -20
@@ -0,0 +1,274 @@
1
+ /**
2
+ * `fastagent add <channel>|skill` — scaffold channel glue (`channels/<kind>.ts`) or vendor an Agent
3
+ * Skills skill. slack/feishu/lark additionally CREATE OR RESUME the platform app.
4
+ */
5
+ import { randomBytes } from "node:crypto";
6
+ import { readFile } from "node:fs/promises";
7
+ import { join, relative, resolve } from "node:path";
8
+ import { isCancel, select } from "@clack/prompts";
9
+ import { onboardFeishuCloudApp } from "../add-feishu.js";
10
+ import { loadDotEnv } from "../../env.js";
11
+ import { loadConfig, resolveAgentDir, resolveStateRoot } from "../../engines/pi/config.js";
12
+ import { detectRuntime, readPackageJson } from "../../runtime.js";
13
+ import { appendChannelDotEnv, appendChannelEnv, assertChannelReady, channelExists, channelSetup, scaffoldChannel, } from "../../scaffold/add-channel.js";
14
+ import { exists } from "../../scaffold/init.js";
15
+ import { vendorSkill } from "../../scaffold/vendor-skill.js";
16
+ import { loadRootIgnore } from "../../workspace.js";
17
+ import { failStartup, failUsage } from "../fail.js";
18
+ /** `fastagent add <kind> [dir]`: scaffold `channels/<kind>.ts` — the adapter import plus a starter `on()`. */
19
+ export async function runAddChannel(channelKind, dirArg, opts) {
20
+ const target = resolve(dirArg);
21
+ if (opts.replaceConfig && opts.onboard === false) {
22
+ failUsage("--replace-config replaces onboarding credentials; it cannot be combined with --no-onboard");
23
+ }
24
+ loadDotEnv(target); // onboarding state follows the same FASTAGENT_STATE_DIR as serving/deploy
25
+ // App creation is not a flag — it is what `add feishu` IS (the scan-to-create flow is the default
26
+ // and only path there). The retired --create-app spelling gets a pointer, not silence.
27
+ if (opts.createApp) {
28
+ if (channelKind === "feishu") {
29
+ console.error(`[fastagent] note: --create-app is retired — \`add feishu\` creates the app by default`);
30
+ }
31
+ else if (channelKind === "lark") {
32
+ failStartup(new Error("--create-app is retired — `add lark` now opens the developer console and guides credential setup by default"));
33
+ }
34
+ else {
35
+ failStartup(new Error("--create-app is retired — app creation is the default behavior of `add feishu`"));
36
+ }
37
+ }
38
+ // The channel (glue + companion tool) is agent surface — it lands in agentDir (config.agentDir, or
39
+ // target when flat), the same place dev/start discover channels/. .env(.example) and the secret
40
+ // hygiene stay at the run root, where .env is actually read.
41
+ const { config: addConfig } = await loadConfig(target).catch(failStartup);
42
+ const channelHome = resolveAgentDir(target, addConfig);
43
+ // Preconditions before the write, so a refusal is side-effect-free. slack/feishu/lark are exceptions:
44
+ // their add is scaffold + ONBOARD THE APP, so an existing scaffold skips the write and continues (a
45
+ // failed/cancelled app or OAuth flow must be re-runnable without hand-deleting authored glue).
46
+ const file = join(channelHome, "channels", `${channelKind}.ts`);
47
+ const slackToolFile = join(channelHome, "tools", "slack-send.ts");
48
+ const slackToolExisted = channelKind === "slack" ? await exists(slackToolFile) : false;
49
+ const existsAlready = await channelExists(channelHome, channelKind).catch(failStartup);
50
+ const ingress = await resolveIngress(channelKind, file, existsAlready, opts.ingress);
51
+ const groupBehavior = await resolveGroupBehavior(channelKind, opts.groupBehavior);
52
+ if (existsAlready) {
53
+ if (channelKind !== "slack" && channelKind !== "feishu" && channelKind !== "lark") {
54
+ failStartup(new Error(`${relative(target, file)} already exists — edit it, or remove it to re-scaffold`));
55
+ }
56
+ console.error(`[fastagent] ${relative(target, file)} already exists — keeping it`);
57
+ }
58
+ else {
59
+ await assertChannelReady(channelHome).catch(failStartup);
60
+ await scaffoldChannel(channelHome, channelKind, { ingress, groupBehavior: groupBehavior.behavior }).catch(failStartup);
61
+ console.error(`[fastagent] created ${relative(target, file)}`);
62
+ if (channelKind === "slack") {
63
+ console.error(`[fastagent] ${slackToolExisted ? "kept existing" : "created"} ${relative(target, slackToolFile)}`);
64
+ }
65
+ }
66
+ if (await appendChannelEnv(target, channelKind, ingress).catch(failStartup)) {
67
+ console.error(`[fastagent] added ${channelKind} env vars to .env.example`);
68
+ }
69
+ // Secret hygiene: a channel's GENERATED secret (a random string the user contributes nothing to) is
70
+ // written into `.env` — but only when `.env` is already gitignored: the CLI must never materialize a
71
+ // secret into a committable file. Warn, not refuse, when it is exposed — channel glue may read a real
72
+ // env var instead.
73
+ const envIgnored = (await loadRootIgnore(target).catch(failStartup))?.ignores(".env") ?? false;
74
+ if (!envIgnored) {
75
+ console.error(`[fastagent] warn: .env is not gitignored — a deploy that copies the directory would ship a secret placed there; add .env to .gitignore/.fastagentignore, or use a real env var`);
76
+ }
77
+ // Stateful app onboarding is re-runnable after the scaffold boundary. Slack's internal-app path
78
+ // persists its manifest/OAuth recovery state separately and writes runtime secrets directly.
79
+ let created;
80
+ if (channelKind === "slack" && opts.onboard !== false) {
81
+ const { onboardSlackInternalApp } = await import("../add-slack.js");
82
+ created = await onboardSlackInternalApp({
83
+ target,
84
+ stateRoot: resolveStateRoot(target),
85
+ envIgnored,
86
+ groupBehavior,
87
+ replaceConfig: opts.replaceConfig,
88
+ })
89
+ .then(() => undefined)
90
+ .catch(failStartup);
91
+ }
92
+ else if (channelKind === "feishu" || channelKind === "lark") {
93
+ created = await onboardFeishuCloudApp(target, channelKind, envIgnored, ingress, groupBehavior).catch(failStartup);
94
+ }
95
+ const setup = channelSetup(channelKind, ingress, groupBehavior.behavior);
96
+ const env = setup.env;
97
+ const steps = channelKind === "slack" && opts.onboard !== false
98
+ ? [
99
+ "Slack internal app created/configured/installed through OAuth; runtime credentials are in .env",
100
+ "run fastagent dev --tunnel to replace the temporary Events API URL automatically",
101
+ "invite the app to every channel it should read",
102
+ "the agent can send messages or files by calling the scaffolded {tools}/slack-send.ts tool",
103
+ ]
104
+ : setup.steps;
105
+ const generated = Object.fromEntries(env.filter((e) => e.generate).map((e) => [e.name, randomBytes(24).toString("hex")]));
106
+ // Kind-neutral: every channel's generated secrets get the same treatment (github's webhook secret is
107
+ // the same class of value as telegram's); guided Lark credentials ride the same write as overwrites.
108
+ // Feishu's irreversible credentials were already staged inside add-feishu.ts before bootstrap.
109
+ const dotEnv = envIgnored
110
+ ? await appendChannelDotEnv(target, channelKind, { ...generated, ...created }, Object.keys(created ?? {}), ingress).catch(failStartup)
111
+ : undefined;
112
+ if (dotEnv && dotEnv.written.length > 0) {
113
+ console.error(`[fastagent] wrote ${dotEnv.written.join(", ")} to .env`);
114
+ }
115
+ const install = detectRuntime(channelHome, await readPackageJson(channelHome)).runtime === "bun" ? "bun install" : "npm install";
116
+ // The kit's manifest lives in channelHome (agentDir when set) — point the install there, not the run root.
117
+ const installCmd = channelHome === target ? install : `(cd ${relative(target, channelHome)} && ${install})`;
118
+ console.error(` next steps:`);
119
+ console.error(` ${installCmd} # if @fastagent-sh/fastagent is not installed yet`);
120
+ for (const e of env) {
121
+ if (dotEnv?.alreadySet.includes(e.name))
122
+ continue; // the user already has it — nothing to do
123
+ if (dotEnv?.written.includes(e.name)) {
124
+ // Written, but its hint may still carry an action (github: paste the same value into the webhook
125
+ // UI) — keep the variable visible instead of silently absorbing it.
126
+ console.error(` ${e.name} — ${e.generate ? "generated and " : ""}written to .env # ${e.hint}`);
127
+ continue;
128
+ }
129
+ const value = e.generate ? `=${generated[e.name]}` : "";
130
+ const action = e.required ? "set" : "optionally set";
131
+ console.error(` ${action} ${e.name}${value} in .env${envIgnored ? " (gitignored)" : ""} # ${e.hint}`);
132
+ }
133
+ // Steps carry `{channel}`/`{tools}` path placeholders (their filenames are the scaffold's private
134
+ // knowledge) — resolve them to the real workspace-relative locations (agentDir-aware) here.
135
+ const kitPrefix = channelHome === target ? "" : `${relative(target, channelHome)}/`;
136
+ for (const s of steps) {
137
+ console.error(` ${s.replace("{channel}", relative(target, file)).replace("{tools}", `${kitPrefix}tools`)}`);
138
+ }
139
+ if (ingress === "websocket") {
140
+ console.error(` fastagent dev # no public URL or tunnel required`);
141
+ }
142
+ else if (channelKind === "slack") {
143
+ console.error(` fastagent dev --tunnel # serve locally; ${opts.onboard === false ? "print the Request URL for manual Slack setup" : "auto-update the onboarded Slack Request URL"}`);
144
+ }
145
+ else if (channelKind === "github") {
146
+ console.error(` fastagent dev --tunnel # serve locally + print the URL for manual GitHub webhook setup`);
147
+ }
148
+ else if (channelKind !== "lark") {
149
+ console.error(` fastagent dev --tunnel # serve locally + a public URL, auto-registering the webhook`);
150
+ }
151
+ // App-creation flows leave platform/tunnel sockets behind that would otherwise hold the one-shot
152
+ // scaffold command open after all durable boundaries have completed — exit crisply.
153
+ process.exit(0);
154
+ }
155
+ async function resolveIngress(kind, file, existsAlready, raw) {
156
+ if (raw !== undefined && raw !== "webhook" && raw !== "websocket") {
157
+ failUsage(`--ingress must be "webhook" or "websocket", got "${raw}"`);
158
+ }
159
+ const requested = raw;
160
+ if (kind !== "feishu" && kind !== "lark")
161
+ return "webhook";
162
+ if (existsAlready) {
163
+ const source = await readFile(file, "utf8").catch(failStartup);
164
+ const factory = source.match(/\b(?:feishu|lark)(WebSocket)?Channel\s*\(/);
165
+ const existing = factory
166
+ ? factory[1] === "WebSocket"
167
+ ? "websocket"
168
+ : "webhook"
169
+ : undefined;
170
+ if (!existing) {
171
+ if (!requested) {
172
+ failUsage(`${file} uses an unrecognized channel factory — re-run with --ingress webhook|websocket to confirm its mode`);
173
+ }
174
+ return requested;
175
+ }
176
+ if (requested && requested !== existing) {
177
+ failStartup(new Error(`${file} already selects ${existing} delivery — changing mode is a migration; edit the factory and platform subscription together`));
178
+ }
179
+ return existing;
180
+ }
181
+ if (requested)
182
+ return requested;
183
+ if (!(process.stdin.isTTY && process.stdout.isTTY)) {
184
+ console.error(`[fastagent] no interactive terminal — defaulting ${kind} ingress to webhook (use --ingress websocket)`);
185
+ return "webhook";
186
+ }
187
+ const answer = await select({
188
+ message: `How should ${kind === "feishu" ? "Feishu" : "Lark"} deliver events?`,
189
+ options: [
190
+ {
191
+ value: "websocket",
192
+ label: "WebSocket long connection",
193
+ hint: "no public URL; requires an always-on process",
194
+ },
195
+ {
196
+ value: "webhook",
197
+ label: "Webhook endpoint",
198
+ hint: "supports scale-to-zero; requires a public HTTPS URL",
199
+ },
200
+ ],
201
+ });
202
+ if (isCancel(answer))
203
+ failStartup(new Error(`${kind} onboarding cancelled`));
204
+ return answer;
205
+ }
206
+ async function resolveGroupBehavior(kind, raw) {
207
+ if (raw !== undefined && raw !== "context" && raw !== "mentions") {
208
+ failUsage(`--group-behavior must be "context" or "mentions", got "${raw}"`);
209
+ }
210
+ if (kind !== "feishu" && kind !== "lark" && kind !== "slack")
211
+ return { behavior: "context", explicit: false };
212
+ if (raw !== undefined)
213
+ return { behavior: raw, explicit: true };
214
+ const defaultBehavior = "context";
215
+ if (!(process.stdin.isTTY && process.stdout.isTTY)) {
216
+ console.error(`[fastagent] no interactive terminal — assuming ${kind} group behavior ${defaultBehavior}; pass --group-behavior explicitly to override`);
217
+ return { behavior: defaultBehavior, explicit: false };
218
+ }
219
+ const choices = [
220
+ {
221
+ value: "context",
222
+ label: "Context-aware groups (recommended)",
223
+ hint: kind === "slack"
224
+ ? "bare managed-thread replies + buffer; requires channel/group/mpim history scopes"
225
+ : "bare managed-thread replies + buffer; im:message.group_msg delivers all group messages",
226
+ },
227
+ {
228
+ value: "mentions",
229
+ label: "Mention-only (least privilege)",
230
+ hint: "only explicit @Agent messages; no group-wide message permission",
231
+ },
232
+ ];
233
+ const answer = await select({
234
+ message: "Choose group-chat behavior",
235
+ initialValue: defaultBehavior,
236
+ options: choices,
237
+ });
238
+ if (isCancel(answer))
239
+ failStartup(new Error(`${kind} onboarding cancelled`));
240
+ return { behavior: answer, explicit: true };
241
+ }
242
+ /** `fastagent add skill <source> [dir]`: vendor an Agent Skills skill into <dir>/skills/<name>/. */
243
+ export async function runAddSkill(source, dirArg, opts) {
244
+ const target = resolve(dirArg);
245
+ if (!source) {
246
+ // A missing source is a usage error (exit 2), but the guide is worth more than a bare
247
+ // missing-argument line — the common path (writing your own skill) needs no command at all.
248
+ failUsage(`add a skill — two ways:\n` +
249
+ ` 1. write your own (vibe): create skills/<name>/SKILL.md with name + description\n` +
250
+ ` frontmatter; it's auto-discovered. No command needed — this is the common path.\n` +
251
+ ` 2. vendor an existing Agent Skills skill (copied in, git-tracked):\n` +
252
+ ` fastagent add skill <source> [dir]\n` +
253
+ ` source: a git ref (owner/repo/path, github default), a local path (./x, /abs), or a\n` +
254
+ ` bare name found in your global skill dirs (~/.agents/skills, ~/.pi/agent/skills)\n` +
255
+ ` --update overwrites an existing skill (re-fetch from source); review with git diff`);
256
+ }
257
+ // Skills are agent surface — vendored into agentDir/skills (config.agentDir, or target when flat).
258
+ const { config: skillConfig } = await loadConfig(target).catch(failStartup);
259
+ const skillHome = resolveAgentDir(target, skillConfig);
260
+ const { name, description, dest, hasScripts, diagnostics, overwritten } = await vendorSkill(skillHome, source, {
261
+ update: opts.update ?? false,
262
+ }).catch(failStartup);
263
+ console.error(`[fastagent] ${overwritten ? "updated" : "vendored"} skill "${name}" → ${dest}/`);
264
+ if (overwritten)
265
+ console.error(` overwrote it — \`git diff ${dest}\` to review, \`git checkout ${dest}\` to revert`);
266
+ if (description)
267
+ console.error(` ${description.length > 100 ? `${description.slice(0, 100)}…` : description}`);
268
+ for (const d of diagnostics)
269
+ console.error(` warn: ${d.message}`);
270
+ if (hasScripts) {
271
+ console.error(` warn: this skill ships scripts/ (executable code that runs in your agent) — review it before deploying`);
272
+ }
273
+ console.error(` next: mention "${name}" in persona.md so the model knows when to use it; then \`fastagent dev\``);
274
+ }
@@ -0,0 +1,82 @@
1
+ import type { SessionControl } from "../../session.ts";
2
+ export interface AttachOptions {
3
+ /** Override the control endpoint (skip control.json discovery) — for a remote serve. */
4
+ url?: string;
5
+ token?: string;
6
+ }
7
+ export declare function runAttach(sessionArg: string, dirArg: string | undefined, opts: AttachOptions): Promise<void>;
8
+ /** One round's observed facts, gathered by the loop (IO) and judged by {@link decideRound} (pure). */
9
+ export type RoundOutcome = {
10
+ type: "progress";
11
+ }
12
+ /** Clean end that delivered nothing — indistinguishable from a half-dead proxy closing every stream. */
13
+ | {
14
+ type: "empty";
15
+ } | {
16
+ type: "error";
17
+ error: unknown;
18
+ isAuth: boolean;
19
+ /** discover(dir) compared against the current endpoint; remote endpoints report "unavailable". */
20
+ discovery: "unchanged" | "changed" | "unavailable";
21
+ /** The freshly discovered credentials when {@link discovery} is "changed". */
22
+ fresh?: {
23
+ url: string;
24
+ token: string;
25
+ };
26
+ };
27
+ export type RoundDecision = {
28
+ kind: "reset";
29
+ } | {
30
+ kind: "exit";
31
+ message: string;
32
+ } | {
33
+ kind: "try-reattach";
34
+ fresh: {
35
+ url: string;
36
+ token: string;
37
+ };
38
+ } | {
39
+ kind: "retry";
40
+ warn: string;
41
+ };
42
+ /**
43
+ * The reconnect policy for BOTH phases (`startup` = connectWithGrace, `steady` = the round loop),
44
+ * pure and testable: every exit diagnosis and budget claim lives here. `downMs` is wall-clock time
45
+ * since the phase's anchor (first connect attempt / first non-progress round). The phases differ
46
+ * on priors, not principle: startup has never succeeded (short budget; a remote non-auth error
47
+ * exits at once), steady-state had a working attach (longer budgets); the local-401-unchanged
48
+ * diagnosis and reattach-on-changed-credentials apply identically to both.
49
+ */
50
+ export declare function decideRound(outcome: RoundOutcome, ctx: {
51
+ discovered: boolean;
52
+ downMs: number;
53
+ phase?: "startup" | "steady";
54
+ }): RoundDecision;
55
+ /** What one ROUND prints through (streamed deltas included), so tests can observe every path a
56
+ * round writes. Round output only: stdin-side acceptance/rejection lines print directly — they
57
+ * are immediate feedback to a user action and may interleave with a replay block. Timing knobs
58
+ * travel as their own parameter. */
59
+ export interface AttachIo {
60
+ println: (line: string) => void;
61
+ /** Raw chunk, no newline — the streamed message_delta path. */
62
+ write: (chunk: string) => void;
63
+ warn: (line: string) => void;
64
+ }
65
+ /**
66
+ * ONE attach round: subscribe → backfill (render the durable record since `cursor`) → drain live
67
+ * until the stream drops. Returns the advanced cursor. Subscribing first + the server's eager
68
+ * registration (subscribed before response headers) covers the cursor→subscription window in the
69
+ * normal case; `settleMs` is a HEURISTIC — on a very slow link an event can still land between the
70
+ * backfill and the subscription taking effect, surfacing only at the next round's replay. Live
71
+ * events carry no entry ids, so the cursor advances only on backfill; a replay may overlap what
72
+ * was already seen live — labeled, not silently dropped. A 401 (stale token after a serve restart)
73
+ * is thrown to the caller: unrecoverable here, never retried silently.
74
+ */
75
+ export declare function attachRound(control: SessionControl, session: string, cursor: string | undefined, io: AttachIo,
76
+ /** The subscribe→sync settle heuristic (see the round comment). Tests shrink it. */
77
+ settleMs?: number): Promise<{
78
+ cursor: string | undefined;
79
+ sawProgress: boolean;
80
+ }>;
81
+ /** The cursor a failed round reached, if it recorded one. */
82
+ export declare function roundCursor(error: unknown): string | undefined;