Looks like we're missing some of the tab completion features that come with pi. In yinshi when I type /resume nothing happens, but I would expect to be able to resume a previous conversation. What do you think?
Assistant· gpt-5.5
Agree. This is a real parity gap, not user error.
What I see:
Pi supports /resume in interactive mode: it opens a previous-session picker.
Yinshi’s chat input has its own slash-command layer.
Current builtins are only /help, /model, /tree, /export, /clear.
Unknown slash commands fall through as prompts to the Pi SDK sidecar.
But Yinshi uses SessionManager.inMemory() for Pi SDK sessions and stores conversations in SQLite, so Pi’s own /resume has nothing useful to resume there.
Best fix: implement /resume as a Yinshi-native command.
Suggested behavior:
Add /resume to slash completion and /help.
Add backend endpoint like GET /api/sessions/recent returning recent sessions with:
session id
repo name
workspace name / branch
updated time
status
last user prompt or message preview
In Session.tsx, handle /resume by opening a small picker overlay.
Selecting a row navigates to /app/session/:id.
If no prior sessions exist, show “No previous sessions found.”
Do not pass /resume to Pi SDK.
Also worth later adding /new, /session, maybe /compact where they map cleanly. But /fork, /tree, /share, /hotkeys, etc. need product decisions because Pi TUI semantics do not all map to Yinshi’s web model.
Short version: /resume should work, but as “resume Yinshi SQLite session,” not “resume Pi JSONL session.”
User
Looks like we're missing some of the tab completion features that come with pi. In yinshi when I type /resume nothing happens, but I would expect to be able to resume a previous conversation. What do you think?
User
So how does pi's compaction work in yinshi's web model?
Assistant· gpt-5.5
Pi compaction works inside Yinshi, but only as runtime Pi SDK state today.
Current flow:
Yinshi creates a Pi SDK session in sidecar/src/sidecar.js.
It uses SessionManager.inMemory().
It enables Pi auto-compaction with:
compaction.enabled = true
retry.enabled = true
Imported Pi settings.json can override compaction settings.
As prompts run, Pi’s SDK session accumulates context in memory.
When context gets too large, Pi auto-compacts old entries into a summary and keeps recent entries.
Future prompts in that same warmed sidecar session see: system prompt + compaction summary + recent turns.
Important catch:
Yinshi stores chat display history in SQLite.
Pi stores actual model context in an in-memory Pi session.
Yinshi does not persist Pi CompactionEntry rows to SQLite.
Yinshi does not rehydrate Pi SDK session state from SQLite after sidecar/container restart.
So compaction helps while the same sidecar activeSessions entry remains alive. It does not currently give durable long-session memory across runtime loss.
Manual /compact likely falls through to Pi because it is not a Yinshi builtin. But it is not in slash completion, and any result is likely minimal because Yinshi only forwards Pi events, then synthesizes a result if Pi command finishes without normal agent_end.
Implication: /resume issue points at a bigger session-model mismatch. Yinshi can display old SQLite messages, but Pi may not have them in model context unless the in-memory Pi session is still alive.
Best fix direction:
Make Pi session state durable per Yinshi session.
Either:
use a persistent Pi SessionManager file per Yinshi session, or
store Pi session entries, including compaction entries, in SQLite.
On session open/warmup, rehydrate Pi from durable state.
Add Yinshi-native /compact command with visible feedback.
Keep SQLite transcript for UI, but treat Pi session entries as the source of model context.
Short version: compaction exists, but today it is an in-memory optimization, not a durable Yinshi web-session feature.
User
So how does pi's compaction work in yinshi's web model?
User
How can we update yinshi to use compaction the way the pi author intended it work? Here, I'm speaking about autocompaction specifically.
Assistant· gpt-5.5
Use Pi’s own SessionManager and lifecycle, not a Yinshi-made summary layer.
Current Yinshi problem:
Sidecar creates Pi sessions with SessionManager.inMemory().
Pi autocompaction writes CompactionEntry into that manager.
Because manager is in-memory, compaction disappears when sidecar/container dies.
Sidecar treats agent_end as final result, but Pi autocompaction can happen after agent_end.
Sidecar listens for auto_compaction_start, but SDK event is compaction_start.
Fix has two parts.
1. Make Pi session state durable per Yinshi session
In sidecar/src/sidecar.js, replace:
js
sessionManager: SessionManager.inMemory(),
with a persistent manager tied to the Yinshi session id:
For host/tenant mode, backend should compute runtime-visible path and pass it through sidecar options:
json
User
How can we update yinshi to use compaction the way the pi author intended it work? Here, I'm speaking about autocompaction specifically.
User
Let's think carefully about the change. What are the risks? How does it impact the BYOC model? How does it impact the user's session saves, terminal, settings, etc.? Are we going to get the exact compaction capability defined in the pi docs?
Assistant· gpt-5.5
I would do this, but with guardrails. Risk is not compaction logic. Risk is session ownership.
Core principle
Yinshi should not reimplement Pi compaction. It should let Pi persist its own session entries.
Correct shape:
SQLite remains Yinshi UI transcript and product metadata.
Pi JSONL becomes model-context source of truth.
Autocompaction entries live in Pi JSONL, not in messages.
That gives Pi’s intended behavior. But it creates a second persisted conversation artifact, so we need handle privacy, BYOC, lifecycle, and migration deliberately.
Main risks
1. Data-at-rest protection can regress
Pi JSONL contains:
user prompts
assistant replies
tool calls
tool results
file snippets read by tools
bash output
compaction summaries
Today, Yinshi tenant messages live in SQLite and may be protected by SQLCipher depending on deployment. A plain JSONL file under user data can weaken that protection.
Mitigation:
Store Pi session files only inside tenant-owned runtime storage, mode 0700.
Update threat model docs: Pi JSONL is sensitive user data.
If SQLCipher is required for chat transcripts, either:
require filesystem/user-data encryption for runtime files, or
build a SQLite-backed Pi-compatible session manager instead of JSONL.
Do not store Pi session files in /tmp.
This is biggest product/security risk.
2. SQLite and Pi JSONL can diverge
Yinshi currently inserts the user message into SQLite before the sidecar prompt. Pi only appends to its session manager through SDK events.
Failure cases:
Backend saves user prompt, sidecar fails before Pi sees it.
Browser disconnects during compaction.
Sidecar crashes after Pi appends but before SQLite finalizes.
Existing sessions have SQLite history but no Pi JSONL.
Mitigation:
Treat SQLite as display transcript, not model context.
Show failed turns accurately.
On sidecar failure before Pi accepts prompt, mark turn failed.
Add health/repair tooling that can compare SQLite last turn vs Pi JSONL last entry.
For old sessions, do one of:
conservative: “old transcript visible, model context resumes from this point,” or
migration: seed Pi JSONL from stored SQLite user/assistant text, with clear “approximate context” semantics.
User
Let's think carefully about the change. What are the risks? How does it impact the BYOC model? How does it impact the user's session saves, terminal, settings, etc.? Are we going to get the exact compaction capability defined in the pi docs?
User
Ok, what questions can I answer for you?
Assistant· gpt-5.5
Key decisions needed:
Old sessions
Option A: Leave old SQLite-only sessions visible, but new prompts start fresh Pi context.
Option B: Seed Pi JSONL from stored SQLite text transcript, approximate context.
Option C: Do not allow prompt resume on old sessions; require clone/new session.
Storage security
Is plain JSONL under tenant runtime storage acceptable if directory is 0700?
Or must Pi session context inherit same protection level as tenant DB/SQLCipher?
BYOC compaction settings
Should imported settings.json be allowed to disable/tune autocompaction?
Or should Yinshi force autocompaction on regardless of imported settings?
Compaction cost visibility
Is “compaction uses your selected BYOC provider/key and may incur cost” enough?
Or do you need exact compaction token/cost accounting in Yinshi usage reports?
Imported Pi sessions
Should Yinshi ignore imported agent/sessions for web chat context? I recommend yes.
Should /resume ever show imported Pi sessions, or only Yinshi SQLite sessions?
Session export
Should export include only browser transcript?
Or include Pi JSONL too for exact future replay/debug?
Terminal access
Is it okay if the workspace terminal can see/edit hidden Pi JSONL files under /home/yinshi/.yinshi/...?
Or should session files live somewhere mounted into sidecar but not exposed to terminal shell?
Failure behavior
If Pi JSONL is missing/corrupt but SQLite transcript exists, should Yinshi:
recreate fresh Pi context and warn,
block prompting,
or try approximate rebuild from SQLite?
Product UX during autocompaction
Should browser show visible “Compacting context...” status?
Or keep it silent unless it fails?
My recommended answers: A, plain JSONL acceptable only with documented sensitive-data caveat, respect imported settings, disclose cost without exact accounting for v1, ignore imported Pi sessions, export both if user asks for full session, terminal visibility acceptable, recreate fresh with warning on corruption, show compacting status.
User
Ok, what questions can I answer for you?
User
I almost think option C makes the most sense? Any opinions or recommendations?
I'm not sure. How do I think through this decision? What would you recommend?
Imported settings should be allowed to disable/tune - that's the pi way.
I think a pi user already knows that compaction uses LLM calls. If they don't like it, they can install the pi-vcc package.
Yes. Just Yinshi sessions from SQLite.
Probably the JSONL too unless you feel strongly otherwise.
Users should have access to them. Obviously no one other than the user themselves should have access.
Recreate and warn.
Definitely show the status. That's how pi does it.
Assistant· gpt-5.5
Your answers point to clean design.
1. Old sessions: I agree with option C
Recommendation: make old SQLite-only sessions read-only for prompting.
Reason: approximate rebuild is worse than honest break. SQLite transcript lacks full Pi session entries: tool calls, tool results, compaction boundaries, branch metadata, custom messages, model/thinking changes. If we seed Pi JSONL from visible transcript, model context looks continuous but is not exact.
Best UX:
Old sessions remain visible as archived transcripts.
Input disabled with banner:
“This session predates durable Pi context and cannot continue with exact model context.”
Actions:
“Start new session in this workspace”
“Export transcript”
Empty old sessions can be upgraded automatically because no context is lost.
1 + missing/corrupt JSONL: recreate and warn, per your answer to 8.
This avoids confusing “old session” with “new session whose JSONL got deleted.”
2. Storage security: how to think about it
Think in terms of “what new plaintext exists, who can read it, and is that consistent with current threat model?”
Pi JSONL will contain sensitive user data:
prompts
assistant output
tool calls
tool results
file snippets
bash output
compaction summaries
That is same sensitivity class as:
workspace repo files
tenant chat messages
imported Pi config
terminal output
Current Yinshi threat model is middle-ground, not zero-knowledge. Server sees plaintext while running work. Docs already say USER_DATA_DIR should be on encrypted storage for production.
My recommendation:
Store Pi JSONL under tenant/user runtime storage, not /tmp, not imported agentDir, not repo workspace.
Use directories.
User
I almost think option C makes the most sense? Any opinions or recommendations?
I'm not sure. How do I think through this decision? What would you recommend?
Imported settings should be allowed to disable/tune - that's the pi way.
I think a pi user already knows that compaction uses LLM calls. If they don't like it, they can install the pi-vcc package.
Yes. Just Yinshi sessions from SQLite.
Probably the JSONL too unless you feel strongly otherwise.
Users should have access to them. Obviously no one other than the user themselves should have access.
Recreate and warn.
Definitely show the status. That's how pi does it.
User
Ok, create a task list and implement.
Assistant· gpt-5.5
Implemented.
Task list:
Done: Added pi_context_version schema field and migrations.
Done: Marked new sessions as durable Pi-context sessions.
Done: Blocked old transcript-only sessions from prompting when exact Pi context cannot be resumed.
Done: Added deterministic per-session Pi JSONL paths.
Done: Switched sidecar from SessionManager.inMemory() to SessionManager.open(...) when a durable file is provided.
Done: Kept BYOC auth in memory; only session context persists.
Done: Respected imported Pi compaction settings.
Done: Forwarded Pi compaction_start / compaction_end as visible browser status events.
Done: Delayed final result emission so autocompaction and overflow retry can complete.
Done: Added missing cancel coverage for compaction/retry aborts.
Done: Cleaned up durable Pi session files when workspaces are deleted.
Done: Documented Pi JSONL sensitivity in docs/security/middle-ground-threat-model.md.
Done: Added backend/frontend tests.
Key behavior now:
New Yinshi sessions get Pi-native durable JSONL session files.
Pi owns autocompaction entries and rebuilds context from its JSONL, as intended.
Legacy sessions with existing messages show a warning and do not pretend to resume exact model context.
Empty legacy sessions upgrade on first prompt.
Missing/corrupt Pi JSONL is reset with warning while visible transcript remains.
/resume should still resume Yinshi SQLite sessions only; imported Pi CLI sessions stay ignored.
Repo-wide mypy src tests still fails on existing unrelated typing debt.
flake8 still fails on existing E501 line-length debt across many files.
Two untracked code_reviews/*.md files were already present; I left them untouched.
User
Ok, create a task list and implement.
User
/skill:code-simplicity-reviewer
Post-implementation cleanup pass.
Changed files:
backend/src/yinshi/api/repos.py
backend/src/yinshi/api/sessions.py
backend/src/yinshi/api/stream.py
backend/src/yinshi/api/workspaces.py
backend/src/yinshi/db.py
backend/src/yinshi/models.py
backend/src/yinshi/services/sidecar_runtime.py
backend/src/yinshi/services/sidecar.py
backend/src/yinshi/services/workspace.py
backend/src/yinshi/tenant.py
backend/tests/test_api.py
backend/tests/test_container.py
backend/tests/test_db.py
backend/tests/test_sidecar.py
frontend/src/api/client.ts
frontend/src/components/AssistantTurn.tsx
frontend/src/components/ChatView.tsx
frontend/src/pages/__tests__/Session.test.tsx
frontend/src/pages/Session.tsx
frontend/src/utils/__tests__/turnEvents.test.ts
frontend/src/utils/turnEvents.ts
sidecar/src/sidecar.js
Use repository state as the source of truth, not the compacted summary. Inspect the listed files and current diff before editing. Apply only small, behavior-preserving simplifications that make the code clearer or more maintainable. Keep changes scoped to the listed files unless a directly related helper must change. If no simplification improves clarity, leave the files unchanged and say so. Run relevant checks after edits when the project exposes clear checks.
Assistant· gpt-5.5
Code Simplicity Pass
Files inspected
backend/src/yinshi/api/repos.py
backend/src/yinshi/api/sessions.py
backend/src/yinshi/api/stream.py
backend/src/yinshi/api/workspaces.py
backend/src/yinshi/db.py
backend/src/yinshi/models.py
backend/src/yinshi/services/sidecar_runtime.py
backend/src/yinshi/services/sidecar.py
backend/src/yinshi/services/workspace.py
backend/src/yinshi/tenant.py
backend/tests/test_api.py
backend/tests/test_container.py
backend/tests/test_db.py
backend/tests/test_sidecar.py
frontend/src/api/client.ts
frontend/src/components/AssistantTurn.tsx
frontend/src/components/ChatView.tsx
frontend/src/pages/__tests__/Session.test.tsx
frontend/src/pages/Session.tsx
frontend/src/utils/__tests__/turnEvents.test.ts
frontend/src/utils/turnEvents.ts
sidecar/src/sidecar.js
Changes made
backend/src/yinshi/api/stream.py: Simplified pi_context_version parsing by removing redundant None and int branches while preserving fallback behavior.
frontend/src/pages/Session.tsx: Extracted the legacy Pi context warning into a named constant so the session guard reads cleaner.
sidecar/src/sidecar.js: Added sendStatusToSocket helper to remove repeated status-message object construction; replaced nullable timer cleanup function with a no-op default; removed unused catch binding in session-manager reset path.
Checks
cd sidecar && node --check src/sidecar.js: passed.
cd backend && PYTHONPATH=src python -m mypy src/yinshi/api/stream.py: passed.
Use repository state as the source of truth, not the compacted summary. Inspect the listed files and current diff before editing. Apply only small, behavior-preserving simplifications that make the code clearer or more maintainable. Keep changes scoped to the listed files unless a directly related helper must change. If no simplification improves clarity, leave the files unchanged and say so. Run relevant checks after edits when the project exposes clear checks.
User
Commit but don't push to the vm yet.
Assistant· gpt-5.5
Committed locally, not pushed.
Commit:
065b754 feat(sessions): persist Pi context for autocompaction
Checks before commit:
Backend pytest: 367 passed
Frontend typecheck: passed
Frontend vitest: 87 passed
Frontend build: passed
Sidecar syntax check: passed
git diff --check: passed
Note: commit guard required /review; you approved bypass. I disabled hooks for this local commit only. Untracked code_reviews/*.md files remain untouched.
User
You are reviewing changed code.
Target files are ``. If none are supplied, use files from git diff --name-only HEAD~1.
Phase 1 - Design Review
Invoke /skill:software-design on the target files.
Evaluate abstraction depth, information hiding, complexity red flags,
interface design, and module boundaries.
Summarize design-level findings before proceeding.
Phase 2 - Implementation Review
The simplifier now lives as /skill:code-simplicity-reviewer. Do not spawn a code-simplifier subagent. The code-simplifier-enforcer extension handles automated cleanup before commit; this review uses the skill only for analysis.
Invoke /skill:code-simplicity-reviewer in analysis-only mode on the target files.
Evaluate duplication, dead code, unnecessary abstractions, naming friction,
and behavior-preserving simplification opportunities.
Apply these review skills in the current session:
python-reviewer
security-sentinel
performance-oracle
Read each skill if needed, apply it to the target paths, and keep findings separated by source. The matching extensions provide standalone /python-reviewer, /security-sentinel, and /performance-oracle commands. Do not use the subagent tool for review.
Collect all findings from both phases.
Present one report grouped by severity.
DESIGN covers architectural and structural issues from software-design.
CRITICAL covers security vulnerabilities from security-sentinel.
MAJOR covers performance issues and convention violations from python-reviewer and performance-oracle.
MINOR covers simplification opportunities from code-simplicity-reviewer.
Phase 3 - Write Review Report
Create the code_reviews/ directory in the project root if it does not exist.
Write the report to code_reviews/YYYY-mm-dd-HHmm-code-review.md
(use the current date and time for the filename, e.g. 2026-02-19-0830-code-review.md).
The report MUST be written for junior engineers who may have little coding experience.
For every finding, explain what changed or was flagged, how the code works, and why the change is needed. Show before/after snippets where useful.
Use this report structure.
Summary
State what was reviewed and the main findings.
Design Findings
(from /skill:software-design Phase 1)
Security Findings
(from /skill:security-sentinel)
Performance Findings
(from /skill:performance-oracle)
Code Quality Findings
(from /skill:python-reviewer)
Simplification Findings
(from /skill:code-simplicity-reviewer)
Changes Applied
List every change that was made, with file paths and explanations.
Confirm the report path to the user when done.
Assistant· gpt-5.5
Review report written and slop check passed.
Report path:
code_reviews/2026-04-27-2057-code-review.md
Slop score:
100/100 clean
User
You are reviewing changed code.
Target files are ``. If none are supplied, use files from git diff --name-only HEAD~1.
Phase 1 - Design Review
Invoke /skill:software-design on the target files.
Evaluate abstraction depth, information hiding, complexity red flags,
interface design, and module boundaries.
Summarize design-level findings before proceeding.
Phase 2 - Implementation Review
The simplifier now lives as /skill:code-simplicity-reviewer. Do not spawn a code-simplifier subagent. The code-simplifier-enforcer extension handles automated cleanup before commit; this review uses the skill only for analysis.
Invoke /skill:code-simplicity-reviewer in analysis-only mode on the target files.
Evaluate duplication, dead code, unnecessary abstractions, naming friction,
and behavior-preserving simplification opportunities.
Apply these review skills in the current session:
python-reviewer
security-sentinel
performance-oracle
Read each skill if needed, apply it to the target paths, and keep findings separated by source. The matching extensions provide standalone /python-reviewer, /security-sentinel, and /performance-oracle commands. Do not use the subagent tool for review.
Collect all findings from both phases.
Present one report grouped by severity.
DESIGN covers architectural and structural issues from software-design.
CRITICAL covers security vulnerabilities from security-sentinel.
MAJOR covers performance issues and convention violations from python-reviewer and performance-oracle.
MINOR covers simplification opportunities from code-simplicity-reviewer.
Phase 3 - Write Review Report
Create the code_reviews/ directory in the project root if it does not exist.
Write the report to code_reviews/YYYY-mm-dd-HHmm-code-review.md
(use the current date and time for the filename, e.g. 2026-02-19-0830-code-review.md).
The report MUST be written for junior engineers who may have little coding experience.
For every finding, explain what changed or was flagged, how the code works, and why the change is needed. Show before/after snippets where useful.
Use this report structure.
Summary
State what was reviewed and the main findings.
Design Findings
(from /skill:software-design Phase 1)
Security Findings
(from /skill:security-sentinel)
Performance Findings
(from /skill:performance-oracle)
Code Quality Findings
(from /skill:python-reviewer)
Simplification Findings
(from /skill:code-simplicity-reviewer)
Changes Applied
List every change that was made, with file paths and explanations.
Confirm the report path to the user when done.
User
Fix every issue in @2026-04-27-2057-code-review.md
Assistant· gpt-5.5
Fixed every issue from code_reviews/2026-04-27-2057-code-review.md.
Changes:
backend/src/yinshi/services/sidecar_runtime.py
Added symlink-safe Pi session cleanup.
Refuses cleanup when home, .yinshi, or pi-sessions is symlinked.
Verifies resolved cleanup path still matches workspace-owned path.
Refuses symlinked Pi session paths during session-file creation too.
backend/tests/test_container.py
Added regression test for hostile .yinshi symlink pointing at another workspace.
backend/src/yinshi/services/workspace.py
Moved Pi cleanup imports to module scope.
sidecar/src/sidecar.js
Removed duplicate piSessionFile normalization.
Renamed variables so normalized/requested session-file flow is clearer.
Checks passed:
cd backend && . .venv/bin/activate && PYTHONPATH=src python -m black --check --quiet ...
cd sidecar && node --test tests/*.test.js: 9 passed, 1 skipped
git diff --check
Not committed.
User
Fix every issue in @2026-04-27-2057-code-review.md
User
/skill:code-simplicity-reviewer
Post-implementation cleanup pass.
Changed files:
backend/src/yinshi/services/sidecar_runtime.py
backend/src/yinshi/services/workspace.py
backend/tests/test_container.py
sidecar/src/sidecar.js
Use repository state as the source of truth, not the compacted summary. Inspect the listed files and current diff before editing. Apply only small, behavior-preserving simplifications that make the code clearer or more maintainable. Keep changes scoped to the listed files unless a directly related helper must change. If no simplification improves clarity, leave the files unchanged and say so. Run relevant checks after edits when the project exposes clear checks.
Assistant· gpt-5.5
Code Simplicity Pass
Files inspected
backend/src/yinshi/services/sidecar_runtime.py
backend/src/yinshi/services/workspace.py
backend/tests/test_container.py
sidecar/src/sidecar.js
Changes made
backend/src/yinshi/services/sidecar_runtime.py: Added _PI_SESSION_PATH_PARTS and _workspace_pi_session_directory() so Pi session directory construction lives in one named helper instead of repeating home_path.joinpath(*_PI_SESSION_DIRECTORY.split("/")).
Checks
cd backend && . .venv/bin/activate && PYTHONPATH=src python -m black --check --quiet src/yinshi/services/sidecar_runtime.py src/yinshi/services/workspace.py tests/test_container.py: passed
No simplifications applied to workspace.py, test_container.py, or sidecar.js; current code is already clear enough for this cleanup pass.
Existing untracked code_reviews/*.md files left untouched.
User
Commit
User
Commit
User
Commit
User
/skill:code-simplicity-reviewer
Post-implementation cleanup pass.
Changed files:
backend/src/yinshi/services/sidecar_runtime.py
backend/src/yinshi/services/workspace.py
backend/tests/test_container.py
sidecar/src/sidecar.js
Use repository state as the source of truth, not the compacted summary. Inspect the listed files and current diff before editing. Apply only small, behavior-preserving simplifications that make the code clearer or more maintainable. Keep changes scoped to the listed files unless a directly related helper must change. If no simplification improves clarity, leave the files unchanged and say so. Run relevant checks after edits when the project exposes clear checks.
Sidecar does not emit final result before compaction_end when compaction starts.
If compaction_end.willRetry === true, sidecar waits for next agent_end.
Deleting a Yinshi session removes its Pi JSONL file.
Bottom line
Best update: make Yinshi a Pi SDK UI over Pi’s durable JSONL session model.
SQLite remains Yinshi’s product transcript. Pi JSONL becomes source of model context. Autocompaction then works as Pi author designed: append compaction entries, rebuild context from summary plus recent messages, and survive resume/restart.
Exact Pi compaction for old SQLite-only sessions is not possible because old tool-result/message-entry structure is incomplete.
3. BYOC credentials get used for compaction calls
Autocompaction is an extra LLM request. It uses the current Pi model and auth.
Impact:
User’s provider key/OAuth gets charged.
The call can happen after visible assistant output finishes.
Usage accounting may miss compaction cost because Pi CompactionResult does not expose token usage.
Mitigation:
UI should show “Compacting context...” so the user understands why work continues.
Do not finalize the stream until compaction and possible retry are done.
Document that autocompaction uses the selected provider credential.
If billing/usage accounting matters, we may need SDK support or an extension hook to capture compaction request usage. Current Pi SDK result does not expose enough.
Credentials themselves should remain safe if we keep AuthStorage.inMemory() as now. Do not use persistent Pi auth.json for Yinshi BYOC credentials.
4. BYOC Pi config must not become session storage
Yinshi imports user Pi config into agentDir. That config can include sessions.
Do not store Yinshi runtime sessions under imported agentDir/sessions.
Reasons:
Imported config may be read-only in narrow container mounts.
Sync/toggle can delete, rename, or overwrite imported session directories.
Imported sessions are user-provided context and should not be auto-resumed into Yinshi web sessions.
Using continueRecent() could attach wrong session history.
Mitigation:
Store Yinshi Pi sessions in a separate runtime directory:
host: tenant data runtime path
container: persistent workspace home, e.g. /home/yinshi/.yinshi/pi-sessions/<session-id>.jsonl
Use SessionManager.open(deterministic_file, deterministic_dir, cwd).
Never use SessionManager.continueRecent() for Yinshi chat sessions.
Imported Pi config remains for skills, prompts, extensions, models, themes, and settings. Yinshi-owned Pi JSONL remains separate.
5. Imported settings can disable autocompaction
Yinshi currently forwards sanitized imported settings.json. Sanitizer does not block compaction.
So if user’s imported settings contain:
json
{
"compaction": {
"enabled": false
}
}
then Pi will not autocompact.
This is Pi-compatible behavior, but product may surprise users.
Choices:
Exact Pi behavior: respect imported compaction settings.
Yinshi product guarantee: force compaction.enabled = true after applying imported settings.
If goal is “use Pi as intended,” respect settings and expose current compaction state in UI/settings.
6. Sidecar currently finalizes too early
Pi autocompaction runs after agent_end. Current sidecar sends result on agent_end.
That can break threshold compaction and especially overflow retry.
Mitigation:
Treat agent_end as candidate completion.
Listen to actual SDK event names:
compaction_start
compaction_end
Keep stream open through compaction.
If compaction_end.willRetry === true, wait for next agent_end.
Only send final result when Pi is idle, not compacting, not retrying.
Deleting workspace/repo must delete all matching Pi JSONL files.
Backups now need include/exclude runtime session files deliberately.
Exports need product choice:
Export UI transcript from SQLite only.
Export exact Pi JSONL too.
Export both.
If user expects “session save” to preserve future model context, Pi JSONL must be backed up.
10. Model/settings changes can create subtle behavior
Current sidecar recreates Pi SDK session when model/settings/auth changes. With persistent SessionManager, recreation is fine if it reopens same JSONL.
Risks:
Model passed in request may disagree with model entries in JSONL.
Imported settings changes may alter compaction thresholds mid-session.
Custom BYOC model may have bad/missing contextWindow, causing Pi threshold behavior to be weird.
Mitigation:
Request model should remain authoritative for current turn.
Persist model changes through Pi APIs where possible, or accept that Yinshi session model column is authoritative.
Validate custom model catalog has context window if possible.
Surface effective compaction settings for debug.
Are we getting exact Pi compaction?
For new sessions: yes, if we do it this way.
We get exact Pi autocompaction semantics when all these are true:
Use Pi SessionManager persistence, not SQLite reconstruction.
Let Pi append message, compaction, model_change, thinking_level_change, and custom entries.
Reopen the same Pi JSONL file for the same Yinshi session.
Do not edit or synthesize compaction entries ourselves.
Keep SettingsManager compaction settings compatible with Pi.
Keep stream open until compaction and overflow retry finish.
Keep Yinshi tool names compatible with Pi file tracking: read, write, edit.
Then Pi gives us:
threshold autocompaction
overflow recovery compaction
split-turn handling
previous-summary iterative updates
firstKeptEntryId semantics
file tracking in details
context rebuild as summary plus kept recent entries
extension session_before_compact hooks
Not exact in these cases:
existing SQLite-only sessions before migration
any custom “summarize SQLite transcript” fallback
if Yinshi finalizes stream before compaction/retry completes
if imported/user settings disable compaction
if custom BYOC models lack correct context metadata
if we store session files somewhere Pi cannot reopen across restarts
Recommendation
Proceed, but define this as “Pi JSONL model-context persistence,” not “add compaction.”
Implementation rule:
Yinshi does not compact. Pi compacts. Yinshi persists and resumes the Pi session manager.
I would make this the plan:
Add deterministic per-Yinshi-session Pi JSONL path.
Pass that path to sidecar warmup/query.
Sidecar uses SessionManager.open(...).
Keep AuthStorage.inMemory() for BYOC credentials.
Keep SettingsManager.inMemory() plus sanitized imported settings.
Store JSONL outside imported BYOC agentDir.
Fix sidecar stream lifecycle around compaction_start/end.
Add delete cleanup.
Decide old-session migration explicitly.
Update security docs for JSONL sensitive data.
If we do those, new sessions get Pi’s intended autocompaction. Existing sessions can only be approximate unless we already have full Pi session entries, which we do not.
0700
Mount only the needed user/workspace/session runtime path into sidecar.
Let the user’s terminal see it, because same user should own their session files.
Document Pi JSONL as sensitive stored user data.
For production, rely on USER_DATA_ENCRYPTION=required or encrypted VM/fscrypt/LUKS.
I would not add app-layer encrypted JSONL in v1.
Why: Pi’s intended compaction uses SessionManager JSONL directly. If we encrypt/decrypt around it, we either:
create plaintext temp files anyway,
risk corruption during compaction,
diverge from Pi’s exact session manager semantics,
or need a custom SessionManager, which is bigger and less “Pi-native.”
Important caveat: SQLCipher only protects tenant SQLite. It will not protect Pi JSONL. So production guidance must say: if you care about durable Pi context protection, encrypt USER_DATA_DIR.
3. Imported settings
Agreed. Respect imported settings.json.
If imported settings say:
json
{
"compaction": {
"enabled": false
}
}
Yinshi should not override it.
That is the Pi way. Exact Pi behavior means users can tune or disable autocompaction.
4. BYOC cost/accounting
Agreed.
Autocompaction uses the selected provider/model/key. Pi users should understand this. Yinshi should show status, not build a cost subsystem for compaction v1.
One caveat: if Yinshi usage reports exist, they may undercount compaction because Pi SDK CompactionResult does not expose summary-call usage. That is acceptable if documented.
5. Imported Pi sessions
Agreed. /resume should show only Yinshi SQLite sessions.
Imported agent/sessions should be ignored for web chat context.
Reason: imported Pi sessions are CLI-owned state. Mixing them with Yinshi sessions creates wrong-context risk and cross-workspace confusion.
6. Export
I agree with including JSONL, but I would separate export modes:
Normal export: current browser transcript HTML/Markdown, good for reading.
Full export: transcript plus Pi JSONL, good for replay/debug/audit.
If there is only one export button, make it a zip:
Security requirement: no other tenant can mount or read that path. Same user terminal can inspect/edit/delete it. If they corrupt it, Yinshi recreates and warns.
8. Missing/corrupt JSONL
Good answer, with one distinction:
New durable session (pi_context_version=1) and JSONL missing/corrupt: recreate and warn.
Legacy session (pi_context_version=0) with messages: do not recreate silently; mark read-only archive.
Warning text:
“Pi session context was missing or unreadable, so Yinshi started a fresh model context. The visible transcript is still preserved.”
9. Compaction status
Agreed. Show it.
Sidecar should forward Pi SDK events:
text
compaction_start
compaction_end
UI can show:
“Compacting context...”
“Context compacted”
“Compaction failed: ...”
Also important: sidecar must not finalize the stream at first agent_end if compaction starts. For overflow recovery, Pi may compact and retry after agent_end.
BYOC impact summary
This change should not weaken BYOC credential handling if we keep current pattern:
AuthStorage.inMemory() stays.
No provider secrets written to Pi auth.json.
Imported models.json can still define models.
Imported settings can tune compaction.
Imported extensions can hook compaction if Yinshi loads them.
Pi JSONL stores conversation/tool data, not provider secrets.
Main BYOC risk is custom models with wrong/missing contextWindow. Pi threshold compaction depends on context-window metadata. We should warn or validate when a selected model has no usable context window.
Exact Pi compaction answer
For new pi_context_version=1 sessions: yes, we can get exact Pi autocompaction semantics from the docs.
That includes:
threshold autocompaction
context-overflow recovery
split-turn handling
previous-summary iterative compaction
firstKeptEntryId
file tracking in details
session_before_compact extension hooks
context rebuild from summary plus kept recent entries
Not exact for:
legacy SQLite-only sessions
corrupted/missing JSONL after reset
imported settings that disable compaction, because exact Pi behavior means disabled
custom models with bad context metadata
So final recommendation:
Build durable Pi JSONL for all new sessions, mark old sessions as archived/read-only, respect imported settings, store JSONL in encrypted per-user runtime storage, and show Pi compaction status in the browser.
cd frontend && npx tsc --noEmit
cd frontend && npx vitest run src/pages/__tests__/Session.test.tsx src/utils/__tests__/turnEvents.test.ts: passed, 11 tests.
cd backend && PYTHONPATH=src python -m black --check --quiet src/yinshi/api/stream.py: passed.
Left broader sidecar session construction intact. Refactoring _createPiSession into an options object would reduce signature width, but it is more than a cleanup tweak and could obscure behavior.
Current repo still has two untracked code_reviews/*.md files; not touched.