@cydm/pie 2.7.20 → 2.8.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.
- package/dist/builtin/extensions/ask-user/README.md +117 -0
- package/dist/builtin/extensions/ask-user/index.js +3 -3
- package/dist/builtin/extensions/cron/index.js +35 -9
- package/dist/builtin/extensions/im-forward/README.md +297 -0
- package/dist/builtin/extensions/im-forward/index.js +302 -25
- package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
- package/dist/builtin/extensions/memory/index.js +323 -0
- package/dist/builtin/extensions/memory/package.json +18 -0
- package/dist/builtin/extensions/pie-ipc/README.md +21 -0
- package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
- package/dist/builtin/extensions/plan-mode/index.js +149 -82
- package/dist/builtin/extensions/subagent/README.md +315 -0
- package/dist/builtin/extensions/subagent/index.js +7 -5
- package/dist/builtin/extensions/todo/index.js +3 -3
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
- package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
- package/dist/chunks/chunk-5353DEEC.js +130 -0
- package/dist/chunks/{chunk-2H2DD22Z.js → chunk-HGC25NYB.js} +1 -1
- package/dist/chunks/{chunk-X7UO6BA6.js → chunk-JNOFHHLZ.js} +156 -65
- package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-LJXHECZ7.js} +12183 -10951
- package/dist/chunks/{chunk-TGCI5M6R.js → chunk-NEES4EBX.js} +19 -141
- package/dist/chunks/{src-GX4UBAYF.js → src-5XOKRS6F.js} +2 -2
- package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-5SDHKKDB.js} +1 -1
- package/dist/cli.js +26 -19
- package/package.json +2 -2
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Ask User Extension for Pie
|
|
2
|
+
|
|
3
|
+
Interactive question tool with "Other" option, back navigation, and multi-question flow.
|
|
4
|
+
|
|
5
|
+
## Tool
|
|
6
|
+
|
|
7
|
+
### `ask_user_multi`
|
|
8
|
+
|
|
9
|
+
Ask multiple questions with review and edit capability.
|
|
10
|
+
|
|
11
|
+
#### Parameters
|
|
12
|
+
|
|
13
|
+
| Parameter | Type | Default | Description |
|
|
14
|
+
|-----------|------|---------|-------------|
|
|
15
|
+
| `questions` | array | **required** | Array of question objects |
|
|
16
|
+
| `allowReview` | boolean | `true` | Allow review at the end |
|
|
17
|
+
|
|
18
|
+
Each question object:
|
|
19
|
+
```typescript
|
|
20
|
+
{
|
|
21
|
+
id: string, // Unique identifier
|
|
22
|
+
question: string, // Question text
|
|
23
|
+
options?: string[], // Options (if multiple-choice)
|
|
24
|
+
allowOther?: boolean, // Default: true
|
|
25
|
+
placeholder?: string // For Other/open-ended
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
#### Example
|
|
30
|
+
|
|
31
|
+
```json
|
|
32
|
+
{
|
|
33
|
+
"questions": [
|
|
34
|
+
{
|
|
35
|
+
"id": "project_name",
|
|
36
|
+
"question": "What is your project name?",
|
|
37
|
+
"placeholder": "my-awesome-project"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"id": "language",
|
|
41
|
+
"question": "Which programming language?",
|
|
42
|
+
"options": ["Python", "JavaScript", "Go", "Rust"]
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"id": "framework",
|
|
46
|
+
"question": "Which framework?",
|
|
47
|
+
"options": ["React", "Vue", "Svelte"]
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"id": "confirm",
|
|
51
|
+
"question": "Ready to generate?",
|
|
52
|
+
"options": ["Yes", "No, let me change something"],
|
|
53
|
+
"allowOther": false
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
#### Flow
|
|
60
|
+
|
|
61
|
+
1. **Question 1/4**: Project name? → [input field]
|
|
62
|
+
2. **Question 2/4**: Language? → A. Python B. JavaScript C. Go D. Rust E. ✏️ Other F. ← Back
|
|
63
|
+
3. **Question 3/4**: Framework? → [options + Other + Back]
|
|
64
|
+
4. **Question 4/4**: Ready? → [Yes / No + Back]
|
|
65
|
+
5. **Review screen**:
|
|
66
|
+
- A. ✓ Confirm and continue
|
|
67
|
+
- B. ✏️ Edit Q1: Project name?
|
|
68
|
+
- C. ✏️ Edit Q2: Which programming...
|
|
69
|
+
- D. ✏️ Edit Q3: Which framework?
|
|
70
|
+
- E. ✏️ Edit Q4: Ready to generate?
|
|
71
|
+
- F. ↺ Restart all
|
|
72
|
+
|
|
73
|
+
#### Returns
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"project_name": { "answer": "MyApp", "question": "What is your project name?" },
|
|
78
|
+
"language": { "answer": "TypeScript", "question": "Which programming language?", "isOther": true },
|
|
79
|
+
"framework": { "answer": "React", "question": "Which framework?", "selectedIndex": 0 },
|
|
80
|
+
"confirm": { "answer": "Yes", "question": "Ready to generate?", "selectedIndex": 0 }
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## When to Use
|
|
85
|
+
|
|
86
|
+
Use `ask_user_multi` for:
|
|
87
|
+
- Collecting multiple pieces of information
|
|
88
|
+
- Asking a single question
|
|
89
|
+
- Wizard-style flow
|
|
90
|
+
- User might want to go back and change answers
|
|
91
|
+
- Need review before proceeding
|
|
92
|
+
|
|
93
|
+
## UX Features
|
|
94
|
+
|
|
95
|
+
### "Other" Option
|
|
96
|
+
- Always available (unless disabled with `allowOther: false`)
|
|
97
|
+
- Selecting it opens input dialog
|
|
98
|
+
- Answer returned as "Other: [custom text]"
|
|
99
|
+
|
|
100
|
+
### Back Navigation
|
|
101
|
+
- Add `allowBack: true` for single question
|
|
102
|
+
- Always available in multi-question flow (except first question)
|
|
103
|
+
- Selecting "← Back" returns to previous question
|
|
104
|
+
|
|
105
|
+
### Progress Indicator
|
|
106
|
+
Multi-question shows progress: "1/4: Question text?"
|
|
107
|
+
|
|
108
|
+
### Review Phase
|
|
109
|
+
At the end of the flow:
|
|
110
|
+
- See all answers at a glance
|
|
111
|
+
- Edit any specific question
|
|
112
|
+
- Restart entire flow
|
|
113
|
+
- Confirm to proceed
|
|
114
|
+
|
|
115
|
+
## Installation
|
|
116
|
+
|
|
117
|
+
Built-in with Pie CLI. Extension auto-loads from `builtin/extensions/ask-user/`.
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
createAskUserCapability
|
|
4
|
-
} from "../../../chunks/chunk-
|
|
5
|
-
import "../../../chunks/chunk-
|
|
6
|
-
import "../../../chunks/chunk-
|
|
4
|
+
} from "../../../chunks/chunk-LJXHECZ7.js";
|
|
5
|
+
import "../../../chunks/chunk-HGC25NYB.js";
|
|
6
|
+
import "../../../chunks/chunk-JNOFHHLZ.js";
|
|
7
7
|
import "../../../chunks/chunk-XXGYUYXI.js";
|
|
8
8
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
9
9
|
|
|
@@ -35,18 +35,25 @@ function fields(expression) {
|
|
|
35
35
|
});
|
|
36
36
|
}
|
|
37
37
|
function validateSchedule(value) {
|
|
38
|
-
if (!value || typeof value !== "object"
|
|
38
|
+
if (!value || typeof value !== "object") throw new Error("provide exactly one of at, every, cron");
|
|
39
39
|
const s = value;
|
|
40
|
+
const scheduleKeys = ["at", "every", "cron"].filter((k) => k in s);
|
|
41
|
+
if (scheduleKeys.length !== 1) throw new Error("provide exactly one of at, every, cron");
|
|
42
|
+
if (Object.keys(value).length - scheduleKeys.length > 1) throw new Error("only the optional count may accompany at/every/cron");
|
|
43
|
+
const count = s.count;
|
|
44
|
+
const countValid = count === void 0 || typeof count === "number" && Number.isSafeInteger(count) && count >= 1 && count <= 1e3;
|
|
45
|
+
if (!countValid) throw new Error("count must be an integer 1..1000 (total executions)");
|
|
40
46
|
if ("at" in s && typeof s.at === "string") {
|
|
47
|
+
if (count !== void 0) throw new Error("at is one-shot; count applies only to every/cron");
|
|
41
48
|
const m = s.at.match(/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(?:\.\d{1,3})?)?(?:Z|[+-]\d\d:\d\d)$/);
|
|
42
49
|
if (m && +m[1] >= 1970 && +m[2] >= 1 && +m[2] <= 12 && +m[3] >= 1 && +m[3] <= new Date(Date.UTC(+m[1], +m[2], 0)).getUTCDate() && +m[4] < 24 && +m[5] < 60 && +(m[6] ?? 0) < 60 && Number.isFinite(Date.parse(s.at))) return s;
|
|
43
50
|
}
|
|
44
|
-
if ("every" in s && Number.isSafeInteger(s.every) && s.every >= 60 && s.every <= 31536e3) return s;
|
|
45
|
-
if ("cron" in s && typeof s.cron === "string" && s.cron.length <= 256) {
|
|
51
|
+
if ("every" in s && Number.isSafeInteger(s.every) && s.every >= 60 && s.every <= 31536e3 && countValid) return s;
|
|
52
|
+
if ("cron" in s && typeof s.cron === "string" && s.cron.length <= 256 && countValid) {
|
|
46
53
|
fields(s.cron);
|
|
47
54
|
return s;
|
|
48
55
|
}
|
|
49
|
-
throw new Error("invalid schedule (every: integer seconds 60..31536000; at: ISO timestamp with timezone)");
|
|
56
|
+
throw new Error("invalid schedule (every: integer seconds 60..31536000; at: ISO timestamp with timezone; count: integer 1..1000 for every/cron)");
|
|
50
57
|
}
|
|
51
58
|
function nextTime(s, after) {
|
|
52
59
|
if ("at" in s) return Date.parse(s.at) > after ? Date.parse(s.at) : null;
|
|
@@ -115,7 +122,7 @@ var Store = class {
|
|
|
115
122
|
if (Array.isArray(s.owners) || s.jobs.length > 100 || Object.keys(s.owners).length > 1e3) throw new Error("cron state exceeds record limit");
|
|
116
123
|
const ids = /* @__PURE__ */ new Set();
|
|
117
124
|
for (const j of s.jobs) {
|
|
118
|
-
if (!j || typeof j.id !== "string" || ids.has(j.id) || typeof j.sessionId !== "string" || !j.sessionId || j.sessionId.length > 256 || typeof j.cwd !== "string" || !path.isAbsolute(j.cwd) || typeof j.prompt !== "string" || !j.prompt.trim() || j.prompt.length > 16e3 || typeof j.enabled !== "boolean" || !["ready", "running", "blocked"].includes(j.state) || j.next !== null && !Number.isSafeInteger(j.next)) throw new Error("invalid cron job; manual recovery required");
|
|
125
|
+
if (!j || typeof j.id !== "string" || ids.has(j.id) || typeof j.sessionId !== "string" || !j.sessionId || j.sessionId.length > 256 || typeof j.cwd !== "string" || !path.isAbsolute(j.cwd) || typeof j.prompt !== "string" || !j.prompt.trim() || j.prompt.length > 16e3 || typeof j.enabled !== "boolean" || !["ready", "running", "blocked"].includes(j.state) || j.remaining !== void 0 && (!Number.isSafeInteger(j.remaining) || j.remaining < 0 || j.remaining > 1e3) || j.next !== null && !Number.isSafeInteger(j.next)) throw new Error("invalid cron job; manual recovery required");
|
|
119
126
|
ids.add(j.id);
|
|
120
127
|
validateSchedule(j.schedule);
|
|
121
128
|
}
|
|
@@ -166,7 +173,18 @@ var Store = class {
|
|
|
166
173
|
if (typeof prompt !== "string" || !prompt.trim() || prompt.length > 16e3) throw new Error("prompt must contain 1..16000 characters");
|
|
167
174
|
const validated = validateSchedule(schedule), next = nextTime(validated, now);
|
|
168
175
|
if (next === null) throw new Error("at must be in the future");
|
|
169
|
-
const
|
|
176
|
+
const count = validated.count;
|
|
177
|
+
const job = {
|
|
178
|
+
id: randomUUID(),
|
|
179
|
+
sessionId,
|
|
180
|
+
cwd: fs.realpathSync(cwd),
|
|
181
|
+
prompt,
|
|
182
|
+
schedule: validated,
|
|
183
|
+
enabled: true,
|
|
184
|
+
next,
|
|
185
|
+
state: "ready",
|
|
186
|
+
...count !== void 0 ? { remaining: count } : {}
|
|
187
|
+
};
|
|
170
188
|
return this.transaction((s) => {
|
|
171
189
|
if (s.jobs.length >= 100) throw new Error("maximum 100 jobs");
|
|
172
190
|
s.jobs.push(job);
|
|
@@ -202,6 +220,14 @@ function complete(job, error, now = Date.now()) {
|
|
|
202
220
|
}
|
|
203
221
|
job.state = "ready";
|
|
204
222
|
delete job.error;
|
|
223
|
+
if (job.remaining !== void 0) {
|
|
224
|
+
job.remaining -= 1;
|
|
225
|
+
if (job.remaining <= 0) {
|
|
226
|
+
job.enabled = false;
|
|
227
|
+
job.next = "at" in job.schedule ? null : job.next;
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
205
231
|
job.next = "at" in job.schedule ? null : nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
|
|
206
232
|
if (job.next === null) job.enabled = false;
|
|
207
233
|
}
|
|
@@ -763,7 +789,7 @@ function cron(ctx) {
|
|
|
763
789
|
if (!runtime.ready || !runtime.sessionId) throw new Error("wait for an existing session to load and register");
|
|
764
790
|
return JSON.stringify({
|
|
765
791
|
job: store.add(runtime.sessionId, ctx.cwd, prompt, schedule),
|
|
766
|
-
note: "Saved.
|
|
792
|
+
note: "Saved. every/cron schedules repeat until removed unless count limits total executions. Delivery resumes THIS session and each delivered turn runs the prompt once; a running delivery cannot be paused/removed until its turn settles (next poll after idle). Keep at least one cron-enabled Pie open; no execution while all are closed or the computer sleeps."
|
|
767
793
|
});
|
|
768
794
|
}
|
|
769
795
|
if (action === "pause" || action === "resume" || action === "remove") {
|
|
@@ -785,8 +811,8 @@ function cron(ctx) {
|
|
|
785
811
|
ctx.registerTool({
|
|
786
812
|
name: "cron_manage",
|
|
787
813
|
label: "Cron",
|
|
788
|
-
description:
|
|
789
|
-
parameters: Type.Object({ action: Type.Union(["list", "add", "pause", "resume", "remove"].map((s) => Type.Literal(s))), id: Type.Optional(Type.String()), prompt: Type.Optional(Type.String({ maxLength: 16e3 })), schedule: Type.Optional(Type.Union([Type.Object({ at: Type.String() }), Type.Object({ every: Type.Integer({ minimum: 60, maximum: 31536e3 }) }), Type.Object({ cron: Type.String({ maxLength: 256 }) })])) }),
|
|
814
|
+
description: 'Manage persistent scheduled prompts bound to THIS existing session and cwd. No new sessions. Actions list/add/pause/resume/remove. every is seconds (minimum 60) and REPEATS FOREVER until removed; at is one-shot; cron is five numeric UTC fields. Add optional count (integer 1..1000) to every/cron to auto-disable after that many executions \u2014 prefer {"every":60,"count":5} over manual removal for N-time notifications. Missed intervals coalesce; blocked/uncertain tasks require human review before resume. remove/pause fail with "job is running" while a delivery is in flight; retry after the delivered turn settles.',
|
|
815
|
+
parameters: Type.Object({ action: Type.Union(["list", "add", "pause", "resume", "remove"].map((s) => Type.Literal(s))), id: Type.Optional(Type.String()), prompt: Type.Optional(Type.String({ maxLength: 16e3 })), schedule: Type.Optional(Type.Union([Type.Object({ at: Type.String() }), Type.Object({ every: Type.Integer({ minimum: 60, maximum: 31536e3 }), count: Type.Optional(Type.Integer({ minimum: 1, maximum: 1e3 })) }), Type.Object({ cron: Type.String({ maxLength: 256 }), count: Type.Optional(Type.Integer({ minimum: 1, maximum: 1e3 })) })])) }),
|
|
790
816
|
risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
|
|
791
817
|
execute: async (args) => {
|
|
792
818
|
try {
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
# IM forwarding (interactive CLI only)
|
|
2
|
+
|
|
3
|
+
Ctrl+R and `/tools/im-forward` are always available in interactive hosts; Alt+I is an
|
|
4
|
+
optional alias where the terminal delivers Alt. Bare
|
|
5
|
+
`/tools/im-forward` opens the IM forwarding menu; `/tools/im-forward status|setup|toggle|clear`
|
|
6
|
+
are subcommands (also reachable through the hierarchical slash menu).
|
|
7
|
+
`/tools/im-forward clear` removes every configuration layer after an explicit
|
|
8
|
+
confirmation dialog; malformed layers are never silently destroyed (repair them
|
|
9
|
+
first), concurrent edits between confirmation and deletion abort the clear, and
|
|
10
|
+
forwarding stops immediately afterwards. Without usable configuration/dependency,
|
|
11
|
+
Ctrl+R opens **IM forwarding setup**;
|
|
12
|
+
otherwise it toggles the desired enabled flag. Headless hosts register nothing
|
|
13
|
+
and perform no configuration or subprocess IO. Only replies/thread posts associated
|
|
14
|
+
with this process's forwarded messages can enter its originating live session.
|
|
15
|
+
|
|
16
|
+
Feishu (Lark) is the only implemented platform. The wizard always shows a generic
|
|
17
|
+
platform picker with implemented platforms and Cancel, before provider setup. See [Feishu setup and transport](providers/feishu/README.md).
|
|
18
|
+
No model-provider registration, shared framework, daemon, or new dependency is involved.
|
|
19
|
+
|
|
20
|
+
Configure `~/.pie/im-forward.json` (overridden by `<cwd>/.pie/im-forward.json`):
|
|
21
|
+
|
|
22
|
+
```json
|
|
23
|
+
{
|
|
24
|
+
"enabled": true,
|
|
25
|
+
"provider": "feishu",
|
|
26
|
+
"providers": {
|
|
27
|
+
"feishu": {
|
|
28
|
+
"chatId": "oc_your_chat",
|
|
29
|
+
"allowUsers": ["ou_your_open_id"],
|
|
30
|
+
"larkCli": "/path/to/lark-cli"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"retryBackoffMs": 5000
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`chatId` selects a group or a known P2P chat. To direct-message a user instead,
|
|
38
|
+
use `openId` (`ou_...`) in place of `chatId`; DM sends use the official CLI's
|
|
39
|
+
`--user-id`. The wizard also offers to detect the P2P chat from a message the
|
|
40
|
+
user sends to the bot, and then defaults `allowUsers` to that sender. Bots cannot
|
|
41
|
+
enumerate P2P chats, so a group list alone is not a complete target picker.
|
|
42
|
+
|
|
43
|
+
**Per-machine app (lark-cli profiles).** Modern lark-cli (≥1.0.27) keeps several
|
|
44
|
+
apps as named profiles in `~/.lark-cli/config.json`. When more than one profile
|
|
45
|
+
exists, the wizard shows an app picker after resolving the CLI (displaying app
|
|
46
|
+
id, logged-in user and the CLI's active profile) and binds the choice to this
|
|
47
|
+
machine as `larkCliProfile` in the saved settings. Every runtime invocation —
|
|
48
|
+
sends, replies, reactions, metadata, image downloads and the event consumer —
|
|
49
|
+
appends `--profile <name>`, so each machine can forward through its own app
|
|
50
|
+
without touching the CLI's active profile. Choosing "Use the CLI's active app"
|
|
51
|
+
binds no profile (default behavior). Single-app and older lark-cli builds skip
|
|
52
|
+
the picker entirely. New-app browser authorization passes `--name <profile>`
|
|
53
|
+
so it creates or updates a named profile instead of replacing the active one.
|
|
54
|
+
|
|
55
|
+
`allowUsers`, `larkCli` and `retryBackoffMs` are optional. Use an allowlist in shared
|
|
56
|
+
chats. Legacy flat `chatId` (or `receiveId`), `openId`, `allowUsers` and `larkCli`
|
|
57
|
+
are read as implicit Feishu settings. Unknown explicit providers never fall back.
|
|
58
|
+
Provider settings merge only within the same provider, with project precedence.
|
|
59
|
+
|
|
60
|
+
The footer shows `[IM…]` while starting, `[IM]` only after the consumer's ready
|
|
61
|
+
marker, `[IM!]` on configuration/connection failure, and nothing when off.
|
|
62
|
+
Desired enabled state is independent of connection health. Other processes'
|
|
63
|
+
enabled changes are re-read at the next forwarding/input gate; changed provider,
|
|
64
|
+
target or settings fail closed until setup/reload rather than sending to a stale target.
|
|
65
|
+
|
|
66
|
+
Setup is single-flight and abortable; no file is saved before the final summary
|
|
67
|
+
confirmation. It shows the effective save location (existing project override,
|
|
68
|
+
otherwise user file). Save/toggle preserve unrelated fields, use an exclusive
|
|
69
|
+
same-directory temporary file and atomic rename, and reject malformed/unreadable
|
|
70
|
+
configuration. Repair such files yourself; setup never silently overwrites them.
|
|
71
|
+
Concurrent edits during setup are detected. Install/authentication operations may
|
|
72
|
+
have their own external side effects after consent, even if final setup is cancelled.
|
|
73
|
+
Successful setup binds the existing session immediately without restart. Repeat
|
|
74
|
+
setup disposes the old runtime and scopes; host event handlers are not duplicated.
|
|
75
|
+
Session changes and extension disposal cancel pending setup before saving. Once
|
|
76
|
+
saved, retirement reconciles the latest valid configuration with the latest session;
|
|
77
|
+
extension disposal still prevents replacement. Consumers must report ready within
|
|
78
|
+
30 seconds or are stopped and retried with bounded backoff.
|
|
79
|
+
|
|
80
|
+
## Extension-private provider contract
|
|
81
|
+
|
|
82
|
+
`index.ts` owns bootstrap and one central event dispatcher; `config.ts` owns layered
|
|
83
|
+
storage and `onboarding.ts` the generic wizard. `runtime.ts` owns session attribution,
|
|
84
|
+
provider-namespaced route/event state, reply routing, inbox invalidation, retries,
|
|
85
|
+
host `beginUserInput` scopes and atomic multi-image submission. It has no native
|
|
86
|
+
command or provider-specific ID/content assumptions.
|
|
87
|
+
|
|
88
|
+
`providers/types.ts` defines `ImProvider` / `ImConnection`. The static private
|
|
89
|
+
registry contains only implemented adapters. Each adapter validates its settings,
|
|
90
|
+
performs dependency/auth/target setup, constructs native CLI commands, parses raw
|
|
91
|
+
events into normalized text/opaque IDs/image references, downloads and cleans
|
|
92
|
+
images, and owns consumer subprocess lifecycle. Common runtime manages connection
|
|
93
|
+
health and bounded restart policy. A connection supplies its source prefix.
|
|
94
|
+
Only one provider is active; this is not a multi-provider simultaneous forwarding feature.
|
|
95
|
+
`launch.ts` and `lark-cli.ts` preserve the Windows-safe subprocess protections.
|
|
96
|
+
|
|
97
|
+
## Feishu-specific: launching lark-cli (Windows and POSIX)
|
|
98
|
+
|
|
99
|
+
`larkCli` remains a single path string, not a shell command. If omitted, Pie
|
|
100
|
+
searches PATH. Native executables run directly. On Windows, the official npm
|
|
101
|
+
`lark-cli.cmd` installation is resolved to its adjacent `@larksuite/cli` package
|
|
102
|
+
(global `node_modules` or local `.bin` layout); its package name and
|
|
103
|
+
`lark-cli` bin entry must identify `scripts/run.js`. Pie runs that entry using
|
|
104
|
+
its own Node executable, **never the cmd shim or a shell**. Arbitrary `.cmd`/
|
|
105
|
+
`.bat` wrappers are unsupported; use a true `.exe` or an explicit `.js`/`.mjs`
|
|
106
|
+
Node entry instead. Explicit Node entries also support portable offline fixtures.
|
|
107
|
+
Relative explicit paths are anchored to the extension's initial `ctx.cwd`;
|
|
108
|
+
resolved paths are absolute and remain valid in private image-download cwd's.
|
|
109
|
+
|
|
110
|
+
The same launch adapter serves sends/downloads and the event consumer. Consumer
|
|
111
|
+
shutdown first closes stdin (EOF), then applies bounded termination to only its
|
|
112
|
+
owned tree if necessary. Windows uses the system `System32/taskkill.exe /T /F`
|
|
113
|
+
and checks its exit result; concurrent stops share one in-flight operation. An
|
|
114
|
+
already-exited Windows leader is never targeted: its PID may have been recycled,
|
|
115
|
+
and descendants can no longer be safely identified as owned. Retained pipes are
|
|
116
|
+
drained for a bounded grace (consumer: up to 1.5 seconds), then destroyed.
|
|
117
|
+
POSIX uses an owned process group. The shared lark
|
|
118
|
+
event daemon is never targeted. Spawn failures and exit/close races share one
|
|
119
|
+
cleanup/retry path. Streaming UTF-8 lines are bounded (1 MiB event lines, 4 KiB
|
|
120
|
+
stderr lines); oversized lines are discarded. One-shot stdout is capped at
|
|
121
|
+
8 MiB and stderr retains only a short tail. Overflow waits for bounded tree
|
|
122
|
+
termination (Windows taskkill: up to 1.5 seconds) and close (up to one further
|
|
123
|
+
second) before returning the output-limit error; it does not return while its
|
|
124
|
+
termination operation is still pending. Consumer stdout buffered before close
|
|
125
|
+
is processed even after exit; extension shutdown suppresses all further input.
|
|
126
|
+
|
|
127
|
+
## Feishu outbound format
|
|
128
|
+
|
|
129
|
+
Answers are sent with `lark-cli ... --markdown`, i.e. a Feishu **post** message
|
|
130
|
+
whose content is `md` blocks (bold, lists, links, inline code, fenced code and
|
|
131
|
+
tables render natively). The body is:
|
|
132
|
+
|
|
133
|
+
```
|
|
134
|
+
**[Pie] · <session label>**
|
|
135
|
+
> [UserInput] <one-line preview of the triggering input>
|
|
136
|
+
|
|
137
|
+
<assistant markdown body>
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
- The header is bold rather than `[Pie][Session: …]`: adjacent brackets read as
|
|
141
|
+
a markdown reference link and can vanish from the rendered message.
|
|
142
|
+
- Only the quoted user input is markdown-escaped (backslashes and backticks).
|
|
143
|
+
A stray fence there would otherwise turn the answer into code. The assistant
|
|
144
|
+
body is intentionally rendered as markdown.
|
|
145
|
+
- **Length budget is byte-based, not character-based.** Feishu caps a rich-text
|
|
146
|
+
(post) request body at **30 KB**; text messages allow 150 KB. The same markdown
|
|
147
|
+
expands from ~1.0x (one long paragraph) to ~4.6x (hundreds of tiny paragraphs),
|
|
148
|
+
because each block gets its own `md` tag plus a spacer row and JSON escaping
|
|
149
|
+
doubles quotes. `estimatePostRequestBytes` prices that structure against a
|
|
150
|
+
24 KB budget (30 KB minus 6 KB headroom).
|
|
151
|
+
- **Long answers are split, not truncated.** A body over the budget is split by
|
|
152
|
+
`chunkMarkdown` into consecutive messages that each fit BOTH the byte estimate
|
|
153
|
+
and the Windows argv character ceiling. Cuts sit at line boundaries only —
|
|
154
|
+
never inside a code fence's marker lines — and prefer paragraph boundaries; an
|
|
155
|
+
interrupted fence is closed at the cut with its ORIGINAL delimiter (a ````
|
|
156
|
+
opener closes with 4+ backticks) and reopened (same delimiter + language tag)
|
|
157
|
+
on the next part; surrogate pairs are never split; every emitted part —
|
|
158
|
+
synthetic markers included — is validated against both budgets before it is
|
|
159
|
+
accepted (a pathological budget degrades to visible mid-line fragments, never
|
|
160
|
+
an oversized part or a loop). Every part shares the same reply anchor — parts
|
|
161
|
+
land as consecutive siblings in the chat root or inside the thread the anchor
|
|
162
|
+
opened, never chained part-to-part (Feishu threads are single-level). Each
|
|
163
|
+
part registers its own route, so a reply to any part re-enters the session.
|
|
164
|
+
Parts 2..n get one bounded retry (2 s) after a transient send failure; if the
|
|
165
|
+
retry also fails, a short notice names the missing parts and the full text
|
|
166
|
+
stays in the terminal. Disabling forwarding mid-send stops the remaining parts
|
|
167
|
+
quietly — no retry, no failure notice after the toggle.
|
|
168
|
+
- **Referenced files ride along as attachments.** After the text parts,
|
|
169
|
+
`collectFileReferences` mechanically scans the answer OUTSIDE code (fenced
|
|
170
|
+
blocks, fence marker lines, indented code, blockquoted code) for markdown
|
|
171
|
+
links and inline-code paths, resolves them against the session cwd, and sends
|
|
172
|
+
each existing, allow-listed, non-empty file ≤2 MiB (2,097,152 bytes; max 5
|
|
173
|
+
per forward, default on) as a file message on the same anchor. Containment is
|
|
174
|
+
canonical on BOTH sides (realpath of the file AND of the workspace root), so a
|
|
175
|
+
symlinked workspace still attaches its own files while a symlink pointing
|
|
176
|
+
outside cwd is rejected; absolute paths, `~`, URL schemes and `..` traversal
|
|
177
|
+
never qualify; files are deduplicated by canonical path (alias references
|
|
178
|
+
consume one slot). The extension allow-list applies to the REFERENCED name —
|
|
179
|
+
it is a relevance filter, not a content-security boundary. No LLM is involved.
|
|
180
|
+
A failed upload is logged (`attachment upload failed: <path>`), never silent.
|
|
181
|
+
- Idempotency keys stay within lark-cli's 50-character cap; the first part
|
|
182
|
+
keeps the legacy key shape when it fits, later parts fold a SHA-256 digest of
|
|
183
|
+
an unambiguous `tag:index:base` encoding.
|
|
184
|
+
- `truncateMarkdown` remains exported for compatibility, but the forwarding
|
|
185
|
+
path no longer truncates bodies.
|
|
186
|
+
- Failure and cancellation notices use the same format (`⚠️ 任务失败:…` /
|
|
187
|
+
`⛔️ 任务已取消:…`), so they remain reply-routable.
|
|
188
|
+
|
|
189
|
+
## Input safety and limits
|
|
190
|
+
|
|
191
|
+
- **Turn attribution**: an answer quotes and replies to the question that
|
|
192
|
+
actually triggered its turn — matched against the LAST dispatched user
|
|
193
|
+
message, so queued questions cannot steal each other's headers and a
|
|
194
|
+
historical duplicate caption ("继续"/"ok") cannot capture a locally-triggered
|
|
195
|
+
answer. Aborted/errored partial bodies are not forwarded as answers; the
|
|
196
|
+
cancellation/failure notice carries the attribution instead.
|
|
197
|
+
- **Delivery recovery**: a rejected or failed anchored reply drops the dead
|
|
198
|
+
anchor (only when it is the same message) and retries once at the chat root
|
|
199
|
+
(idempotency key unchanged).
|
|
200
|
+
Transient inbound failures (metadata/thread lookups, pipeline warm-up) retry
|
|
201
|
+
with bounded exponential backoff (three retries after the first attempt,
|
|
202
|
+
`retryBackoffMs` base); the dedup entry blocks concurrent redeliveries while a
|
|
203
|
+
retry is pending; exhausted retries send a failure notice — attributed to the
|
|
204
|
+
session the message was bound to when its retry chain started, not whichever
|
|
205
|
+
session is active when the backoff expires — and the retry bookkeeping is
|
|
206
|
+
cleared on any terminal outcome (acceptance,
|
|
207
|
+
not-ours/invalidated rejection, exhaustion, forwarding disabled, extension
|
|
208
|
+
cleanup). A reply chain that walks cleanly to its end with no matching
|
|
209
|
+
forward is ignored, not retried. Events delivered while forwarding is
|
|
210
|
+
globally disabled are dropped WITHOUT being committed to the dedup set, so a
|
|
211
|
+
provider redelivery after re-enabling still processes.
|
|
212
|
+
|
|
213
|
+
- Text and images use a one-shot **session-bound input scope**, captured before
|
|
214
|
+
metadata queries/downloads. Switching sessions (including switching away and
|
|
215
|
+
back), clear/abort/sync invalidation, extension reload, or a local IM toggle
|
|
216
|
+
retires in-flight work. Disk toggles are checked again before accepting input.
|
|
217
|
+
- IM input never reads, inserts mentions into, or clears the editor draft. Local
|
|
218
|
+
typing during a download is preserved. Incoming text uses the provider-supplied
|
|
219
|
+
source prefix (`[Feishu]` for Feishu)
|
|
220
|
+
and submitted as ordinary user content, not a slash or `!!` shell command.
|
|
221
|
+
Normal `@[name](file:id)` mention syntax is still resolved at dispatch; this
|
|
222
|
+
transport is not a separate sandbox for untrusted senders.
|
|
223
|
+
- All unique image keys in a post are prepared as **one** message. Preparation
|
|
224
|
+
failure submits nothing, including the caption. At most 10 unique images,
|
|
225
|
+
each no larger than 10 MiB, are accepted. Unsupported image signatures fail
|
|
226
|
+
closed. The download itself is bounded by the CLI call timeout, not by a
|
|
227
|
+
streaming byte cap. Timed-out calls terminate their process tree and allow
|
|
228
|
+
up to two additional seconds for termination/stdio cleanup before settling.
|
|
229
|
+
- Downloads use a private, unique temporary directory (0700 on POSIX), relative
|
|
230
|
+
output paths and signature-based suffixes. The directory and partial files
|
|
231
|
+
are removed in `finally` after staging or failure. The file cache owns its
|
|
232
|
+
separate retained copy. Historical shared temp directories are not swept.
|
|
233
|
+
- A success reaction and reply-anchor update mean the input was **accepted into
|
|
234
|
+
the session queue**, not that the model has decoded/understood the image or
|
|
235
|
+
completed the task. Failed active-session input gets a retryable failure
|
|
236
|
+
notice instead; invalidated input is discarded without polluting the new
|
|
237
|
+
session. If no input was accepted, invalidation also releases the event's
|
|
238
|
+
dedup marker so a later provider redelivery can recover in the original
|
|
239
|
+
session. Queued input then follows the controller's normal cancellation and
|
|
240
|
+
dispatch semantics. Turning IM off after acceptance does not retract it.
|
|
241
|
+
- Input preparation is atomic per message, not FIFO across messages: a later
|
|
242
|
+
text reply can overtake an earlier multi-image download. Wait for acceptance
|
|
243
|
+
before sending a follow-up that depends on those images.
|
|
244
|
+
|
|
245
|
+
## Extension host API
|
|
246
|
+
|
|
247
|
+
`ctx.beginUserInput(isCurrent?)` is interactive-only and unavailable until the
|
|
248
|
+
session/controller/file pipeline is ready. Capture a scope **before** asynchronous
|
|
249
|
+
IO and dispose it in `finally`:
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
const scope = ctx.beginUserInput?.(() => stillEnabled);
|
|
253
|
+
if (!scope) return;
|
|
254
|
+
try {
|
|
255
|
+
const files = await downloadFiles();
|
|
256
|
+
if (!scope.isCurrent()) return;
|
|
257
|
+
const accepted = await scope.submit("[My transport]\nUser caption", files);
|
|
258
|
+
// files: Array<{ path: string; displayName?: string }>
|
|
259
|
+
// A false result must not be treated as successful attachment delivery.
|
|
260
|
+
} finally {
|
|
261
|
+
scope.dispose();
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
The scope prepares message-owned mentions without editor callbacks, runs
|
|
266
|
+
`terminal:input` interception, checks ownership again, then enqueues a follow-up
|
|
267
|
+
with `clearEditor:false` and no interruption of an active turn. Each scope can
|
|
268
|
+
submit once. Interceptors can consume input, but must retain its attachment
|
|
269
|
+
mentions when transforming it; otherwise attachment submission is rejected.
|
|
270
|
+
|
|
271
|
+
Migration: `attachLocalFileAndSubmit(path, name, text)` is now a compatibility
|
|
272
|
+
wrapper submitting **only** that file and text. It no longer consumes the editor
|
|
273
|
+
draft. To intentionally compose with a local draft, use `attachLocalFile` and
|
|
274
|
+
leave final submission to the user.
|
|
275
|
+
|
|
276
|
+
## Verification
|
|
277
|
+
|
|
278
|
+
From `products/cli`:
|
|
279
|
+
|
|
280
|
+
```sh
|
|
281
|
+
node --test --import tsx test/extension-user-input.test.ts test/im-forward-cli.test.ts test/im-forward-integration.test.ts test/im-forward.test.ts test/document-attachment-extension.test.ts
|
|
282
|
+
npm run build
|
|
283
|
+
node --test --import tsx test/im-forward-dogfood.terminal.test.ts
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
The existing `im-forward-cli.test.ts` entry also loads consumer lifecycle
|
|
287
|
+
regressions, so the normal offline gate covers them without test-runner changes.
|
|
288
|
+
|
|
289
|
+
The dogfood launches the actual dist CLI in a PTY with isolated config, exercises
|
|
290
|
+
its real extension loader/session controller/cache/resolver, and captures the
|
|
291
|
+
provider boundary. Feishu and model responses are controlled: tests never send
|
|
292
|
+
live Feishu messages or require API keys. Integration and dist PTY dogfood use
|
|
293
|
+
portable Node entry fixtures on Windows and POSIX; permission-mode assertions
|
|
294
|
+
are POSIX-only.
|
|
295
|
+
|
|
296
|
+
Host-code updates require restarting the dist process: `/reload` only reloads
|
|
297
|
+
extensions, not already imported host modules.
|