← Catalog

pi-function

Let the model reason from project evidence and propose which plugins, skills, and tools to use. Pi-function validates and applies only the changes you confirm.

Extension

Install

Install with PiG

pig install npm:pi-function

Install with Pi

pi install npm:pi-function
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "image": "https://raw.githubusercontent.com/ppTeyven/pi-function/main/assets/banner.gif",
  "extensions": [
    "./function-menu.js"
  ]
}

README

Written by the package's publisher, shown as published in version 3.0.1 (README.md). PiG does not review it.

Pi-function

Pi-function

Application-scenario + workflow assembly for the Pi coding agent.
Fixed scenario IDs. Per-user capability profile. Nothing runs until you approve.

GitHub stars npm License: MIT Pi extension Node >= 20

Install · Usage guide · Scenarios · Workflows · Profile · Chinese


Pi-function turns your installed Pi extensions into application scenarios — making a webpage, writing an article, building a game, creating a report, and so on. Bare /function asks how to work (workflow), then what to make (scenario). Project resume and free-text requests share the same project-progress report and approval flow; free text adds the current request to the analysis.

Scene and workflow IDs are stable. Project commands give the LLM the host's actual capability inventory; the LLM picks plugins, skills and individual tools. The local profile is retained for the manual preset menu.

The extension is a single file with no additional dependencies or telemetry. It uses the current Pi session model, not a separate provider or service.

Why this exists

After installing a dozen plugins and dozens of skills, the problem is no longer "missing tools" — it is disorder:

  • The tool you need is off, while irrelevant ones eat your context and distort model judgment;
  • The same capability is implemented by three or four plugins, and you don't know which one is live;
  • Every new task starts with manually remembering which tools to enable, and missing one means starting over;
  • The more you install, the more the model drifts — citing tools that don't exist.

Pi-function exists to fix exactly that. The goal is to use every installed skill, plugin and tool in the most convenient, most accurate, fastest and most efficient way:

GoalHow
Most convenientOne /function, or one plain sentence. No plugin names to memorize, no tool list to check — every picker option says when to pick it
Most accurateThe model judges progress, intent, workflow, capability gaps and which plugins, skills and tools to keep, enable or disable. The extension validates and applies only the approved proposal
FastestAssembly applies after approval; model reasoning time depends on the current Pi model. Explicit manual presets do not require a model call
Most efficientAfter assembly only the tools you actually need stay active (built-ins + this scene's plugins); every other optional tool is switched off. The system prompt spells out what is enabled, which skills and commands exist, so the model cannot pretend a missing tool works

The model reports capability gaps rather than claiming unavailable tools are active. /function status shows the session's actual tool set.

Install

pi install npm:pi-function

Pin a version, or use git:

pi install npm:pi-function@3.0.1
pi install git:github.com/ppTeyven/pi-function@v3.0.1

Local development:

pi install ./path/to/pi-function

Or drop function-menu.js into ~/.pi/agent/extensions/. Pi loads it at startup.

If you install it while a session is already running, run /reload or restart. Until then /function ... is a normal prompt and cannot be intercepted.

Requires Node 20+ and a Pi version supporting pi.registerCommand, pi.setActiveTools, and skills in pi.getCommands().

Usage guide

First run

  1. Install the extension, then run /reload (or restart Pi) so /function is recognized.
  2. Run /function. It opens a sub-function picker first; choosing “assemble” opens the workflow and scenario pickers.
  3. Choose a workflow — how this run should proceed (outline/prototype, research, review gate, and so on). The workflow brings its own process bundle; the scenario adds domain capabilities.
  4. Choose an application scenario — what you want to make (webpage, article, game, report, and so on).
  5. Review the assembly proposal. Nothing changes until you approve it.
  6. After assembly, describe the task. The extension never executes your request by itself.

If you only want an execution style, run /function workflow; it asks for a workflow, enables that bundle, and does not bind a task scenario.

Commands

CommandWhat happens
/functionOpens a sub-function picker first (assemble / project-resume / workflow-only / profile / scan / status / stats / restore / assign); assemble asks for a workflow and an application scenario, then shows a confirmation
/function resumeReads project docs (HANDOFF / ROADMAP / decisions), Git state, and the recent session; reports the whole-project stage, open tasks, blockers, next steps, and a recommended assembly; nothing is enabled until you approve
/function workflowAsks only for a workflow, enables its bundle, and does not bind a task scenario
/function <need>Runs the same project-progress analysis as resume, adds the current request, and proposes tools; assembles only after approval
/function profileShows the generated capability profile: roles, scores, unassigned items, and profile path
/function scanRe-scans installed packages, local extensions, and skills, then rebuilds the profile
/function statusShows the active workflow × scenario (or workflow-only mode) and enabled plugin tools
/function assign <name> <scenario-id|none>Manually overrides one profile binding
/function stats, /function stats resetInspect usage; only explicit reset (or clear) clears the counters
/function offRestores global defaults, keeps the assembly entry points available, and clears session skill restrictions

/pi-function is an alias.

/function resume is the project-resume report. The 简历 / 求职 application scenario also uses the stable id resume; select it with /function scenario resume or through the assemble picker.

Workflow rows explain the process and show their bundle plugin/skill counts; scenario rows show domain plugin and skill counts. A typical fixed-menu exchange:

/function

Step 1: choose a workflow (how to execute)
  outline · Outline first — ★ recommended · produce an outline, confirm it, then expand
  direct · Direct output — clear, small scope; act now without a separate plan
  ...

Step 2: choose an application scenario (what to make)
  webpage · Web page / landing page / site — 2 plugins · 3 skills (frontend-design, ...)
  ...

## Assembly: Outline first × Web page / landing page / site
**Workflow**: produce an outline/page list first, confirm it, then build
**Scenario**: marketing site, landing page, responsive page

**Plugins and capabilities to enable**
- ... — capability description, tools, commands, skills
...

Which entry point should I use?

SituationUseWhat happens
You want to browse the available combinations/functionWorkflow → application scenario → approve assembly
You want a workflow without a specific deliverable/function workflowChoose only a workflow; enable it without a task scenario
You already have a one-line request/function "build a product site and write a launch article"LLM reads evidence and the request → proposes a workflow and exact enable/disable list → approve assembly
You are picking up an existing project/function resumeScan project evidence → show progress, blockers, next steps → recommend a whole-project bundle; assemble only after approval

Reading the picker

Each row looks roughly like this:

webpage · Web page / landing page / site — 2 plugins · 3 skills (frontend-design, ...)
  • The leading webpage is a stable scenario ID shared by every user.
  • Plugins and skills come from the current machine's capability profile; another user may see different ones.
  • The proposal lists the plugins, tools, skills, and any commands that still need to be run manually.
  • Project resume and free-text requests both show evidence before model analysis, then require approval of the complete model proposal. Declining leaves active tools unchanged.

Day-to-day commands

NeedCommand
See the active assembly/function status
Inspect how plugins and skills were classified/function profile
Restore globally enabled defaults/function off
Pick up newly installed plugins/skills/function scan
Correct one binding/function assign <package-or-skill> <scenario-id>; use none to exclude it
See the full catalog again/function

Troubleshooting

/function is treated as a normal prompt.

The current session has not loaded the extension. Run /reload or restart Pi.

A newly installed plugin or skill is missing from the picker.

Run /function scan. If it is still missing, verify that the package registers a tool/command or that the skill has a SKILL.md; then bind it with /function assign.

The assembled tool set feels incomplete.

Run /function status to inspect the active combination, choose a different workflow/scenario, or use /function assign to correct the profile binding.

Will /function "need" start working on its own?

No. The model proposes a tool set based on the request and project progress. Your approval enables the tools; give a separate instruction when you want the work to start.

Do multiple projects or sessions interfere?

Tool changes apply to the current session. Restore prefers the active branch, including an explicit off. The capability catalog, manual assignments and usage counters are per-user files, not a project security boundary.

Scenarios

Scenarios are application/output types, not engineering activities.

GroupIDsWhat you are making
ContentarticleArticles, copy, blogs, newsletters
ContentemailEmails, notifications, invitations, campaigns
ContentsocialSocial posts, threads, short-form copy
ContentnovelFiction, stories, scripts, characters, worldbuilding
ContentvideoVideo scripts, podcasts, storyboards, subtitles
ContentmusicLyrics, song structure, scoring direction
ContentcourseCourses, lessons, teaching material, training
ContentresumeResumes, job search, interviews, portfolios
ContenteventEvents, travel, weddings, life planning
ContentreportReports, research, white papers, proposals
ContentpresentationPresentations, slide decks, pitches
ContentdocsDocumentation, tutorials, knowledge bases, handoff
ContentlegalContracts, terms, privacy policies, compliance notes
ProductwebpageWeb pages, landing pages, marketing sites
ProductwebappWeb apps, admin dashboards, SaaS
ProductcommerceEcommerce, product pages, storefronts, checkout
ProductdashboardDashboards, BI, reports, metric monitoring
ProductmobileApps, mini-programs, mobile experiences
ProductgameGames, interactive experiences, mini-games
VisualdesignVisual design, branding, UI mockups
VisualimagePosters, covers, illustrations, assets
VisualdataData, charts, analysis results
VisualspreadsheetSpreadsheets, Excel, formulas, reconciliation
SystemapiAPIs, backends, CLIs, SDKs
SystemautomationAutomation, scraping, scheduled jobs
SystemtoolSmall tools, scripts, CLIs, format conversion
SystemintegrationIntegrations, MCP, external systems
SystemchatbotAI chat, knowledge-base Q&A, support bots
SystempluginPi plugins, extensions, tools
MaintenancemaintainMaintain existing projects, fix bugs, refactor, test
MaintenancelocalizationLocalization, translation, multilingual work
GeneralgeneralEverything else

Workflows

A workflow is a process plus an execution bundle. It binds generic capability roles (not hard-coded package names); your profile resolves those roles into the packages and skills installed on this machine. The application scenario then adds domain capabilities. Bundles may overlap: debug and review-gate both need code intelligence and verification, which is intentional.

idWorkflowProcessBundle roles (resolved from your profile)Use when
directDirect outputRead goal → produce → self-checkCore tools onlyClear, small scope; no separate plan
outlineOutline / prototype firstClarify goal → outline or minimum artifact → confirm → expandPlan review, task tracking, memoryYou need a structure, outline, implementation plan, or a minimum prototype first
researchEvidence firstQuestions → multiple sources → cross-check → cited conclusionWeb, repository knowledge, memory, docsFacts are uncertain, sources must be compared, or claims need provenance
debugDebug and fixReproduce → isolate root cause → minimal fix → regressionCode intelligence, verification, context, simplificationA clear failure, error, or abnormal behavior
parallelParallel explorationPartition work → run in parallel → merge and dedupe → verifySubagents, orchestration, task trackingIndependent slices or alternative solutions
review-gateReview / iteration gateDraft → independent review or feedback → fix key gaps → re-verify → deliverSubagents, orchestration, code intelligence, verification, simplification, plan reviewHigh-risk changes, pre-release checks, important documents, or feedback-driven polish
phasedPhased deliverySpec → plan → staged execution → stage acceptancePhase engine, plan review, task tracking, contextMulti-stage work, complex migrations, ongoing development
offlinePrivacy / offlineInventory local resources → stay offline → finish local work → list network gapsLocal memory only (no network capabilities)Sensitive content, no external sharing, minimal network exposure

The table lists capability roles, not package names. Your profile resolves each role to the packages and skills actually installed on your machine; different users can get different bindings while the workflow IDs and semantics stay fixed.

Per-user profile

On first load and on every scan, Pi-function reads the installed packages, extensions, tools, commands, and skills, scores them against generic capability roles, and writes:

~/.pi/agent/function-menu.profile.json

The profile contains role → package/skill bindings, descriptions, and a fingerprint. When a new plugin or skill appears, the fingerprint changes and the profile is rebuilt automatically. The file is per-user and should not be committed.

The catalog and workflow bundles are hydrated from this profile at runtime. That is why the same webpage or article ID can use different tools on different machines without changing the extension source.

Manual overrides are stored in ~/.pi/agent/function-menu.json and survive profile rebuilds.

How items are organized

Pi-function deliberately avoids a hard-coded plugin list. Each package/skill is scored against capability roles using several independent signals:

  • package or skill name: 5 points;
  • registered tool or command name: 3 points;
  • skill names contributed by a package: 2 points;
  • description terms: 1 point.

A role must reach a minimum score (default 2) before it is considered. Role-level deny rules then reject known false positives — for example, a search skill must not become a testing tool, and a document-formatting skill must not become a design tool. Strong name matches take precedence over description-based denies. Each item is capped at 3 package roles or 2 skill roles, keeping one package from polluting many scenarios. Packages that require an environment variable (such as a cloud browser key) are skipped when the variable is missing; their local skills remain available.

Run /function profile to inspect the result. The report shows every role, the matched packages/skills with scores, the unassigned list, and the profile file path. Manual corrections remain available through /function assign.

Classification uses the same vocabulary as the request side

/function scan rebuilds the profile. It used to score descriptions with the raw text only, so a skill that described itself in another language — or only through verbs and adjectives — ended up in the unassigned list even when the capability was obvious.

Both entry points now share one vocabulary:

const text = expandItemText([name, label, description, tools, commands, skills].join(" "));
const tagHits = tagRoleHits(text);
  • expandItemText appends the other-language forms from ALIASES, so Remove watermark from photos also scores against 水印 / 照片.
  • tagRoleHits counts nouns/verbs/adjectives per role via TAG_VOCAB (润色 / 精简 / 校对 → writing, 极简 / 干净 → design, 去重 / 透视 → data).
  • Evidence is two-tier on purpose: two or more distinct words is base evidence and can establish a role; one word only boosts ordering, so 整体风格偏商务 cannot make a skill a design tool.

Because the profile is cached, the classifier version is bumped (PROFILE_VERSION) whenever the vocabulary changes — otherwise an old profile would keep the old classification forever.

/function scan now reports what it did with the catalog:

扫描完成:没有新插件/技能
未归类 2/29 个(用 /function assign <item> <scenario> 指定):skill:foo、skill:bar

or 全部 29 个条目都归入了能力角色. An item is never dropped: it either has a role or appears in the unassigned list (tests/scan.test.mjs asserts exactly that).

Project resume

/function resume answers “what does this whole project need next?”, not “what does this one sentence need?”. It is the entry point for picking up work after a break, a handoff, or a context reset.

It reads, with bounded limits:

  • HANDOFF.md, DECISIONS.md / ADRs, ROADMAP.md, .planning/ files, README, and other project docs (skips dependencies and build output);
  • Git branch, short HEAD, uncommitted files, and recent commits;
  • the recent user / assistant / compaction messages in the current session.

Project discovery starts at the Pi session workspace, not the pi-web installation directory. The preview lists facts only. The model judges the stage, completed and open tasks, blockers and next steps, then proposes a loadout. The same project can restore its prior approved list on reload without reinterpreting documents.

Dynamic needs

/function "build a product site and write a launch article" differs from resume only by adding the current request to the evidence.

  1. Show a local evidence preview, then the model calls suggest_scenario to read project evidence and the host's actual inventory. The catalog does not rank or recommend scenes.
  2. The model interprets the facts, selects scene(s), workflow(s), and the complete list of plugins, skills and optional tools. It can ask a question instead of proposing a loadout if the answer would materially change it.
  3. The host binds evidence and proposals to the current session, workspace and model turn, without a model-supplied request ID. assemble_scenario validates the resources, shows the enable/keep/disable list and waits for confirmation. Approval applies that exact list without executing the project task. Declining leaves tools unchanged and restores the request to the editor.

Both commands show facts only when the model, tool entry points, or interactive confirmation is unavailable. There is no local matching fallback. In interactive analysis, a hosted Pi model can see the submitted need and bounded excerpts of the project evidence.

When you have no capability for the need

Requests may need capabilities that are not installed (PDF, video, dubbing, OCR). In a model proposal, the model checks the actual inventory and lists gaps explicitly. The following checks describe the manual preset path only:

  1. Need words — NEED_CAPABILITIES maps pdf / slides / docx / xlsx / video / audio / ocr / imagegen to a detector for the request and a pattern for installed items. Direction matters: markdown-converter (PDF → Markdown) does not count as being able to produce a PDF.
  2. Contracts — a required role with no installed member (auditCoverage.missing, not-installed).
**能力缺口(本机没有)**
- ⚠️ PDF 生成 / 转换 — 把内容排成 PDF(版式、字体、分页)(需求提到):没有可用条目
- 装配前会问你:要不要用 find-skill 去找这些能力(是 / 否)

Then, per gap, assembly asks 本机没有「…」能力,要去找吗?:

  • 是 → the request is handed to your own find-skill (skill:skill-finder, or skill:find-skill-skillhub if that is what you have installed) as /<cmd> 缺的能力:… 先确认本机现有技能/插件/命令行是否真的没有;没有就给出 2-3 个候选(各自覆盖哪部分、怎么装),等我确认再装。 Nothing is installed without your confirmation.
  • 否 → the gap is recorded as declinedGaps and injected into the system prompt as 不要假装能做;先说明限制并给替代方案.
  • 是 is also injected as 已征得同意去找, so the model runs the search before planning work it cannot finish.

No new network calls: the search goes through a skill that already exists locally.

Full sweep: check every installed plugin and skill

Automatic selection runs behind a role gate (a request for PPT is not a request for a wiki plugin). A gate that is slightly too tight drops exactly the item you installed for this: 去AI味 matched no scenario, so humanizer scored nothing, and selectByCoverage with no demands returned an empty list — installed, correct, unused.

So after the role-based selection there is a second pass with no gate at all: capabilityScan(need) compares the request against every non-infra item's name, description, tags and role labels.

terms  = needTerms(need) + ascii/CJK runs ("AI味")          // "去除 AI 味" == "AI味"
df     = how many installed items contain the term
terms  = terms where 1 <= df <= max(2, 15% of items)         // "内容"/"处理" prove nothing
score  = termScoreDistinct(terms, item)

The rarity filter is what replaces a hand-tuned stopword list: a word every plugin writes (内容, 文件) is dropped by counting, while a word only one plugin writes (ai味, 公文) is strong evidence even at two characters.

Whatever matched but was not selected is shown and asked about — never added silently:

**全量核对(所有插件与技能)**
- 共核对 146 个条目:与需求相关 3 个;已选 0 个,未选 3 个
- 未选:`skill:humanizer` — 去除文本中的AI写作痕迹…(命中:ai味 / 文字)
- 装配前会逐个问你:要不要也启用            → 是 / 否(最多 3 个)

Answers of 是 land in scenario.auditPicks, scenario.skillIds / scenario.plugins, and in the system prompt as 全量核对后你确认一并启用的 … 这些是本机已有能力,直接用,不要再问“要不要装”.

Also fixed on the way: selectByCoverage returned nothing when the request produced no demands (no scenario, no tags). Candidates had already passed the relevance gate, so dropping them was the silent under-use bug; it now keeps them by score.

Bare capability words are asked, not guessed

视频 alone does not say whether you want a video file or a shot list. So BARE_CAPABILITIES (video / audio / ocr) asks one question when only the bare word appears:

  • 做一条视频 → 需求里提到「视频剪辑 / 合成」:要真的做吗?
  • 剪一条视频,加字幕 → no question (already explicit)
  • 是 and nothing installed → becomes a gap, so find-skill is offered the same way as above.

General rule everywhere in this plugin: a word is either evidenced by the request, or it is a question — never an assumption.

Every word is checked (wordAudit)

The rarity filter above decides what counts as evidence. It must not decide what exists. So the request is also split into words and each word is looked up in every installed item:

wordTokens("帮我把这份报告加上水印并转成二维码")
  → 帮, 我把, 这份, 报告, 加上, 水印, 并转成二维码, 二维码, …
  • Intl.Segmenter('zh', {granularity: 'word'}) does the segmentation — real words, not n-gram shrapnel. Runs of one-character segments (并 转 成 二 维 码) are merged and kept in their prefix-trimmed form (二维码), so a word is never lost to a bad dictionary entry.
  • Every word then lands in exactly one bucket:
bucketmeaningwhat happens
matched1 … 15% of items mention itshown with the strongest item (「ai味」→ skill:humanizer)
genericmore than 15% of items mention itknown, but never used as evidence
unmatchedno item mentions itshown, and asked about (max 2)
**逐词核对(每个词都查过)**
- 拆出 8 个词:有对应条目 0 个、通用词 0 个、本机没提到 3 个
- 本机没提到:「二维码」、「报告」、「水印」(装配前会问你要不要去找)

「水印」要当成需求吗? → 是 turns it into a gap (source: "word") and goes through the same find-skill path; 否 drops it for this turn. Function words are filtered by AUDIT_STOP plus prefix/suffix trimming (把/并/转成/的/了), so the questions stay about nouns you actually named.

Nothing is dropped silently (the completeness invariant)

An earlier version of this file could lose words three ways: single characters were excluded from matching and from questions, generic words were recorded only as "seen" and never used, and the unmatched list was truncated to six before being asked about. "Every word matters" is not something you can claim by inspection — it needs an invariant.

wordAudit now writes every token into a per-token ledger and derives the buckets from it:

byToken.set(term, "matched" | "generic" | "unmatched" | "filler" | "single" | "deed")
accounted = byToken.size        // === total, always
counts    = tally by bucket     // sum(counts) === total, always
bucketwhat it meansasked?
matched1…15% of items mention it, with the strongest one— (evidence)
generic>15% mention it → cannot locate an itemno, but recorded
unmatchedno item mentions ittop 3; the rest stay in pending
filler虚词/量词 after prefix/suffix trimmingno, recorded
singlesingle CJK characters (never used as evidence)no, recorded
deedverb/adjective lexicon hit (incl. single-char 画/剪/译 via SINGLE_DEEDS)via source: "deed" gaps

The invariant is tested, not documented: tests/complete.test.mjs asserts accounted === total and sum(counts) === total over a corpus that includes numbers, English, full-width punctuation and empty input. Lose a word and the suite goes red.

Recorded is not the same as used, so the audit block also goes into the system prompt:

### 逐词核对(需求里每个词都查过)
对得上:水印→skill:watermark-remover、报告→skill:gongwenformat-pro
本机没提到:唢呐、竖琴、皮影、木雕、泥塑(另有 2 个已记录、本次未逐条问)
这些词如果确实要做,先向用户确认或找能力,不要默默忽略。

Cross-language aliases (ALIASES)

Matching is string-based, so a Chinese request and an English skill description never meet: you install a skill that says Remove watermark from photos, you ask for 去水印, and nothing matches. ALIASES closes that hole in both directions:

watermark ↔ 水印     subtitle ↔ 字幕    thumbnail ↔ 缩略图   qrcode ↔ 二维码
translate ↔ 翻译      proofread ↔ 校对    summarize ↔ 摘要     refactor ↔ 重构
scrape ↔ 抓取         deploy ↔ 部署       dashboard ↔ 看板     darkmode ↔ 深色模式
… (~55 pairs)
  • catalogTexts() exposes scan = flattened text plus the other-language forms, so one comparison covers both.
  • wordAudit, capabilityScan and capabilityCovered all read scan, so 去水印 matches watermark and remove the watermark matches 水印.
  • The table only widens matching; it never adds score, never adds tags, never inserts tokens into the audit. A pair that does not exist in the table is simply not matched — which is why the table is data, not logic, and can be extended without touching code.
Verbs and adjectives count too

Nouns are the obvious half. 润色 and 极简 name a capability just as much as 海报 does, and they were being lost two ways: GENERIC_TERMS dropped every verb that appears in many descriptions (生成, 优化), and the segmenter has no reason to treat a verb as important.

So ACTION_ROLES (verbs) and STYLE_ROLES (adjectives) are scanned against the raw text — no segmentation involved — and merged into TAG_VOCAB, which means they also become demands for coverage selection:

润色/精简/校对/摘要 → writing      极简/干净/高级/精致 → design
翻译/本地化         → i18n         正式                → docx
抓取/调度/备份/部署  → automation   可爱/复古/科技感    → design
去重/合并/可视化     → data         幽默/克制/口语      → writing
剪辑/转码/渲染       → video        扁平/拟物           → design
重构/调试/诊断       → code-intel
审查/审计           → plan-review

Each hit carries its part of speech, so the report is honest about what it saw:

- 动作/风格:极简→设计 / 视觉(已覆盖)、剪辑→视频创作(本机没有)

(本机没有) is a gap with source: "deed" — 剪辑 on a machine without any video capability asks 本机没有「剪辑(动作)」能力,要去找吗? in the same flow as everything else. (已覆盖) is just evidence, already folded into selection through the tags.

What assembly changes

  • enables the selected plugin tools;
  • keeps core tools (read, bash, edit, write, grep, find, ls) available;
  • disables optional tools from other plugins;
  • injects the workflow and scenario process into the system prompt;
  • for /function resume and /function "need", recomputes the loadout from blockers, next steps and open tasks rather than completed work. The proposal lists plugin tools and session skills it will remove; approval is required;
  • for those project loadouts, excludes unselected skills from the model's skill list and pauses their /skill:name commands until reassembly or /function off;
  • leaves extensions, skill files and other extension commands installed and managed by Pi. This is session scoping, not an uninstall or a file-access sandbox.

Portability: what is guaranteed, what is not

This plugin never hardcodes plugin or skill names. It classifies whatever is installed into capability roles (code-intel, writing, data, automation, process, docx, …) and assembles by role, so a different plugin set still works — but "works" means "reports honestly", not "always perfect":

  • Adapts by itself: the profile is rebuilt from your install on every start; items are matched by name, tool, command and description patterns. Unknown items land in unassigned and are still reachable by description matching.
  • Shows capability gaps: scene contracts (required / optional / forbidden) are visible to the model as reference. The model reports missing capabilities; the extension does not invent or silently add them to an approved list.
  • Manual override always wins: /function assign <item> <scenario|none|infra> and /function scan correct any misclassification.
  • What is not guaranteed: keyword tables are tuned for Chinese office/dev tasks; a non-Chinese or very domain-specific workflow may need scenario keyword edits. Capability patterns target common naming; a plugin named nothing like its function needs assign.
  • No network calls, no writes outside the agent dir: store and profile live in ~/.pi/agent/ (overridable with PI_FUNCTION_STORE / PI_FUNCTION_PROFILE, and PI_CODING_AGENT_DIR for the root).

Customizing for your domain

Everything the assembler knows is data at the top of function-menu.js — no rebuild, no reinstall, just edit and /reload:

  1. Add or retarget a scenario (SCENARIOS). keywords are what users type; when/brief are what the model reads.
{
  id: "bioinfo", group: "专业", title: "生信分析 / 测序流程",
  when: "测序数据质控、比对、差异表达与结果图",
  keywords: ["测序", "生信", "fastq", "比对", "差异表达", "bioinformatics"],
  brief: "先确认物种与参考基因组,再定质控阈值;结果要能追溯到命令与版本。",
},
  1. Say what must be present (SCENARIO_CONTRACTS). required is a hard gate — missing it prints 漏用 instead of silently assembling; forbidden keeps known noise out.
bioinfo: { required: ["bio-data", "code-intel"], optional: ["data", "docs"], forbidden: ["slides"] },
  1. Define a capability role (CAPABILITIES) so your plugins/skills land somewhere. Patterns are tested against name, tool names, commands and description.
"bio-data": { label: "生信 / 组学数据", package: /bio|genom|bwa|samtools/i, skill: /bio|genom|fastq/i, terms: /测序|生信|基因组|差异表达/i },
  1. Bind roles to the scenario (SCENARIO_CAPABILITIES) and, if it has a fixed run order, add a workflow (WORKFLOWS + WORKFLOW_CAPABILITIES + WORKFLOW_SKILL_PATTERNS).

Check your work:

npm test                                  # fixtures stay green
/function profile                          # which items landed in which role
/function "<your need>"                    # see the proposal, incl. coverage gaps
/function assign skill:your-skill bioinfo  # correct a misclassification; it also boosts future picks

How slots are filled (stages B + C)

Selection is not "top N by score". Each item carries capability tags derived from its name, description, tools, commands and classification role; the need carries tags from the scenario keywords.

TAG_VOCAB = { 表格: "data", 公文: "docx", 爬虫: "automation", 海报: "design", … }

selectByCoverage(candidates, limit, demands):
  demands = required roles of the top scenario + tags parsed from the request
  1. greedily pick the item covering the most uncovered demands
     (a role match counts double — a description that merely says "代码"
      does not make a wiki plugin a code-intelligence tool)
  2. slots left over when all demands are covered stay EMPTY

Why leave slots empty: an unused slot costs nothing; a wrong tool costs a wrong answer. Missing capability is reported by auditCoverage (not-installed / not-selected), so "fewer than 5" is a signal, not a bug.

Measured on the 14 representative needs in the fixture: average precision 1.000, 0.7 packages and 1.0 skills per need (before stages B/C it was ~2.5 packages with precision 0.99).

Learning from your own usage (stage D)

Every assembly records which items it put in (usage in function-menu.json), and /function assign records manual corrections (manualAdds). Both add a bounded bonus when scoring the same scenario again:

bonus = min(1.2,
            0.5 × ln(1 + times_actually_called)      // strongest signal
          + 0.1 × ln(1 + times_assembled)            // weak: picked but maybe never used
          + 0.8  if manually assigned)

Actual calls come from Pi's tool_call hook, mapped back to the owning package by its tool path. The cap is deliberately below a name match (5 points), so feedback nudges ordering and never overrides evidence. Inspect or clear it with /function stats / /function stats reset. Nothing leaves your machine; the counters live in the same local store.

Development

npm test          # Node test runner: tests/*.test.mjs

Ad-hoc verification harnesses (SDK smoke, concurrent-write race) are written, run and discarded when needed; they are not kept in the repository. The counted npm test suite above is the project’s own persistent suite.

The current suite is tests/enable-*.test.mjs plus tests/banner.test.mjs. The following table describes historical test groups; it is not an index or a count of today’s suite:

filelayercases
contracts.test.mjsunit / config integrity29
allocation.test.mjscontracts, golden needs, invariants, persistence44
journeys.test.mjsreal user requests (PPT deck, big project, vague one-liner…)29
feedback.test.mjsusage feedback: real tool calls, boost caps, stats/reset13
tags.test.mjscapability tags + set-cover selection11
gaps.test.mjscapability gaps, find-skill routing, ask flow9
audit.test.mjsfull catalog sweep, bare-word asks, audit picks9
two-problems.test.mjsregression for the two reported issues: installed-but-unused, bare words guessed20
words.test.mjsword segmentation, per-word buckets, unmatched-word asks9
deeds.test.mjsverbs/adjectives → roles, deed gaps, panel wording9
complete.test.mjscompleteness invariant: every token accounted for9
coverage.test.mjsbilingual aliases, scan text, pending words reach the prompt8
scan.test.mjs/function scan classification: aliases, tag evidence, unassigned reporting8
completions.test.mjs/function publishes no argument candidates (by design)4
banner.test.mjsbanner spacing, safe degradation, real looping GIF, letters never vanish10
applied.test.mjsevery feature of this release is actually in the shipped file11
e2e.test.mjscommand handler main + alternate flows9
persist.test.mjsassembly survives /reload: store.active write/read/restore/clear4
refresh.test.mjsstartup + every call rescans the catalog; new plugins/skills become candidates7
migration.test.mjsdead scenario ids are migrated to current ones, overrides untouched6
phrase.test.mjsadjacent words are read as one meaning; asks are per-phrase6

TEST-PLAN.md records historical accuracy and timing targets. A passing current suite is not a new measurement of those benchmarks.

The README banner is generated, not hand-edited:

npm run render:banner                 # assets/banner.svg (static fallback for editors)
npm run render:banner -- --static     # no <style> — what GitHub's sanitiser leaves
node scripts/render-banner-gif.mjs    # assets/banner.gif (README uses this one)

GitHub strips <style> from SVGs, so the CSS animation in banner.svg only runs in a browser or editor. The GIF carries its own timing, so the README animation actually plays; both are drawn from scripts/banner-geometry.mjs, and banner.test.mjs B8 fails if the two ever drift apart. The GIF renderer has no dependencies — it rasterises the same rectangles and writes GIF89a by hand (LZW + NETSCAPE loop), 927×260, ~210 KB, 4.8s loop.

The motion is a travelling wave through the pixel grid: every 26px block of the wordmark rises six pixels on its own phase, so a single letter can have its cells at different heights. The crest is dimmed to 55%, which is what gives the wordmark its surface — blocks tilt and shade as the wave passes, instead of whole letters bobbing together. Letters sit one cell apart (26px), so the word reads tight. Nothing appears, disappears or cross-fades: a per-column cross-fade was tried first and rejected, because half-transparent columns read as a bar sliding over the letters.

banner.test.mjs B10 decodes the GIF's own LZW stream and asserts two things no palette inspection would catch: every frame still has the wordmark (letters never vanish), and every pixel in the text band is a neutral step between white and the background — the dimming is the only grey, no colour fringe rides along. TEXT_Y must stay even, because the 2×2 box filter would otherwise blend half a pixel of grey into every stroke edge.

The test harness in tests/lib/mock-pi.mjs creates a temporary Pi directory, store and profile. No changes to an installed extension or user configuration are needed.

License

MIT