@granawkins/locus 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 granawkins
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # Locus
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The patron saint of a directory.**
4
+
5
+ One directory, one persistent agent, one cumulative conversation. Interactive
6
+ chats and headless commands continue the same history, with messages and
7
+ working artifacts kept in the directory. Locus stewards that work over time,
8
+ using Pi's built-in compaction while retaining JSONL history it can inspect.
9
+
10
+ Built on [Pi](https://pi.dev), Locus supports Pi's conversation CLI modes,
11
+ tools, skills, and [community extensions](https://pi.dev/packages). It inherits
12
+ `AGENTS.md` instructions from the current directory and its ancestors, and
13
+ skills from `.agents/skills/` up to the repository root, following Pi's project
14
+ trust rules. Shared skills and native `.pi/` configuration work normally.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install -g @granawkins/locus
20
+ ```
21
+
22
+ Requires Node.js 22.19+ on Linux, macOS, or Windows. Pi is included as a
23
+ dependency. On first use, run `locus` and use `/login` and `/model`
24
+ to connect a provider and select a model. On Windows, install Git for Windows
25
+ for Pi's default Bash tool, or select its PowerShell tool; see
26
+ [Pi on Windows](https://pi.dev/docs/latest/windows).
27
+
28
+ ## Commands
29
+
30
+ Run Locus from the directory you want it to steward. It initializes automatically.
31
+
32
+ ```sh
33
+ locus # Interactive conversation
34
+ locus "Audit your events" # Interactive, starting with this question
35
+ locus -p "Audit your events" # Run to completion and print the answer
36
+ locus -h # Help
37
+ locus --mode json "Audit events" # Stream Pi JSONL events
38
+ locus --mode rpc # Bidirectional Pi connection
39
+ locus install npm:pi-web-access # Install a shared community package
40
+ locus install -l npm:some-package # Install for the current Pi project
41
+ ```
42
+
43
+ Use `/reload` in an open chat after changing Pi resources or installing a package.
44
+ Project skills and extensions require Pi's project trust; unattended runs can
45
+ use already-saved trust or an explicit `--approve` decision.
46
+
47
+ ## State
48
+
49
+ The first run creates `.locus/` in the current directory:
50
+
51
+ | File | Purpose |
52
+ |---|---|
53
+ | `settings.json` | This directory's settings. |
54
+ | `session.jsonl` | Cumulative messages, tool results, and compaction records. |
55
+ | `lock` | Lock target; the active lock is maintained in `lock.lock/`. A competing run exits with code 75. |
56
+
57
+ Locks release on normal exit. After a forced termination, a stale lock becomes
58
+ recoverable after two minutes. The agent can keep notes and other working files in `.locus/`. Shared credentials,
59
+ settings, skills, and installed packages live in `~/.locus/agent/`; override that
60
+ location with `LOCUS_AGENT_DIR`. There is no shared master conversation.
61
+
62
+ ## Directory settings
63
+
64
+ Edit `.locus/settings.json`. All fields start empty and are optional.
65
+
66
+ | Field | Value |
67
+ |---|---|
68
+ | `model` | Pi model reference, such as `provider/model-id`. |
69
+ | `thinking` | Pi reasoning level, such as `medium` or `high`. |
70
+ | `customInstructions` | Text or an existing file path, added to the Locus system prompt. |
71
+ | `tools` | Tool names; plain names replace defaults, `+grep` adds a tool. |
72
+ | `skills` | Extra skill file/directory paths beyond automatic discovery. |
73
+ | `preloadSkills` | Skill file paths whose full instructions are always included in context. |
74
+
75
+ Blank values inherit normal Pi settings and saved-session defaults. Paths are
76
+ relative to the working directory; skill paths also accept `~/`. Explicit CLI
77
+ model, thinking, and tool options override these settings. Restart Locus after
78
+ editing this file. `system-prompt.md` in the package defines the shared identity;
79
+ `settings.template.json` defines the initial settings.
80
+
81
+ ## Use from another agent
82
+
83
+ Run `locus -p "task"` with the target directory as the working directory and
84
+ capture its answer and exit status. Invoke it again to continue. The included
85
+ [skill](skills/locus/SKILL.md) is a concise operating guide; copy its directory
86
+ into your harness's skills location to make it discoverable.
87
+
88
+ Limit concurrent jobs in the caller: Locus has no global queue. JSON mode emits
89
+ Pi events, not a validated result object; inspect errors and completion through
90
+ `agent_settled`. Database updates and completion evidence are task-specific.
91
+ Pi's session-switching commands can leave the canonical conversation during a
92
+ run; avoid them when maintaining one history. Tools use the invoking account's
93
+ permissions; a directory is not a sandbox.
94
+
95
+ MIT. [GitHub](https://github.com/granawkins/locus) ·
96
+ [Pi documentation](https://pi.dev/docs/latest) · `npm test`
package/bin/locus.js ADDED
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, realpathSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { homedir } from 'node:os';
5
+ import { spawn } from 'node:child_process';
6
+ import lockfile from 'proper-lockfile';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const template = new URL('../settings.template.json', import.meta.url);
10
+
11
+ function readObject(path) {
12
+ const value = JSON.parse(readFileSync(path, 'utf8'));
13
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('expected an object');
14
+ return value;
15
+ }
16
+
17
+ function migrateSettings(state) {
18
+ const path = join(state, 'settings.json');
19
+ const legacy = join(state, 'config.json');
20
+ if (existsSync(path) || !existsSync(legacy)) return;
21
+ try {
22
+ const settings = readObject(legacy);
23
+ if ('systemPrompt' in settings) {
24
+ settings.customInstructions ??= settings.systemPrompt;
25
+ delete settings.systemPrompt;
26
+ }
27
+ writeFileSync(path, JSON.stringify(settings, null, 2) + '\n', { flag: 'wx' });
28
+ } catch (error) {
29
+ throw Error(`could not migrate .locus/config.json: ${error.message}`);
30
+ }
31
+ }
32
+
33
+ export function initialize(directory) {
34
+ const state = join(directory, '.locus');
35
+ mkdirSync(state, { recursive: true });
36
+ migrateSettings(state);
37
+ const path = join(state, 'settings.json');
38
+ if (!existsSync(path)) writeFileSync(path, readFileSync(template), { flag: 'wx' });
39
+ }
40
+
41
+ export function profileArguments(directory) {
42
+ const state = join(directory, '.locus');
43
+ migrateSettings(state);
44
+ const path = join(state, 'settings.json');
45
+ const args = [];
46
+ try {
47
+ const profile = existsSync(path) ? readObject(path) : {};
48
+ for (const [key, value] of Object.entries(profile)) {
49
+ if (['model', 'thinking', 'customInstructions'].includes(key)) {
50
+ if (typeof value !== 'string') throw Error(`${key} must be a string`);
51
+ if (value.trim()) args.push(key === 'customInstructions' ? '--append-system-prompt' : `--${key}`, value);
52
+ } else if (['tools', 'skills', 'preloadSkills'].includes(key)) {
53
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || !item.trim())) {
54
+ throw Error(`${key} must be an array of nonempty strings`);
55
+ }
56
+ if (key === 'tools') {
57
+ if (value.length) args.push('--tools', value.join(','));
58
+ } else for (const entry of value) {
59
+ const skill = resolve(directory, entry.startsWith('~/') ? join(homedir(), entry.slice(2)) : entry);
60
+ args.push('--skill', skill);
61
+ if (key === 'preloadSkills') {
62
+ args.push('--append-system-prompt', `Preloaded skill: ${skill}\nResolve its relative references from ${dirname(skill)}.\n\n${readFileSync(skill, 'utf8')}`);
63
+ }
64
+ }
65
+ } else throw Error(`unknown field: ${key}`);
66
+ }
67
+ } catch (error) {
68
+ throw Error(`invalid .locus/settings.json: ${error.message}`);
69
+ }
70
+ return args;
71
+ }
72
+
73
+
74
+ export async function launchPi(args, { directory, profileArgs = [], conversation = false } = {}) {
75
+ const entry = fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent'));
76
+ const cli = join(dirname(entry), 'bundle', 'cli.js');
77
+ const env = {
78
+ ...process.env,
79
+ PI_CODING_AGENT_DIR: process.env.LOCUS_AGENT_DIR || join(homedir(), '.locus', 'agent'),
80
+ };
81
+ let release = async () => {};
82
+ if (conversation) {
83
+ const state = join(directory, '.locus');
84
+ const target = join(state, 'lock');
85
+ writeFileSync(target, '', { flag: 'a' });
86
+ try {
87
+ release = await lockfile.lock(target, { stale: 120000, update: 10000, retries: 0 });
88
+ } catch (error) {
89
+ if (error.code !== 'ELOCKED') throw error;
90
+ console.error('locus: another process is using this directory.');
91
+ process.exitCode = 75;
92
+ return;
93
+ }
94
+ const prompt = fileURLToPath(new URL('../system-prompt.md', import.meta.url));
95
+ const docs = `Installed Pi package: ${dirname(dirname(entry))}\nLocus package: ${fileURLToPath(new URL('../', import.meta.url))}`;
96
+ args = ['--session', join(state, 'session.jsonl'), '--session-dir', state,
97
+ '--system-prompt', prompt, '--append-system-prompt', docs, ...profileArgs, ...args];
98
+ }
99
+ const handlers = new Map();
100
+ try {
101
+ const child = spawn(process.execPath, [cli, ...args], { stdio: 'inherit', env });
102
+ for (const signal of process.platform === 'win32' ? ['SIGINT', 'SIGTERM'] : ['SIGINT', 'SIGTERM', 'SIGHUP']) {
103
+ const handler = () => child.kill(signal);
104
+ handlers.set(signal, handler);
105
+ process.on(signal, handler);
106
+ }
107
+ process.exitCode = await new Promise((resolve, reject) => {
108
+ child.once('error', reject);
109
+ child.once('close', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 130 : 143)));
110
+ });
111
+ } finally {
112
+ for (const [signal, handler] of handlers) process.off(signal, handler);
113
+ await release();
114
+ }
115
+ }
116
+
117
+
118
+ const metadata = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
119
+ const help = `Usage:
120
+ locus init Create settings without starting a conversation (optional)
121
+ locus install <source> Install a Pi package into Locus
122
+ locus Open its persistent conversation
123
+ locus "Audit your events" Open chat with an initial message
124
+ locus -p "Audit your events" Run once and exit
125
+ locus --mode json "Audit" Stream Pi events and exit
126
+ locus --version Show the Locus version
127
+
128
+ Other arguments pass through to Pi. Use /login, /model, /settings, and
129
+ /reload inside chat. Skills and extensions use Pi's normal discovery.
130
+ Conversation commands initialize the current directory automatically.
131
+ Profile: .locus/settings.json | History: .locus/session.jsonl
132
+ Requires Node.js 22.19 or newer on Linux, macOS, or Windows.`;
133
+
134
+ export async function main(args = process.argv.slice(2), directory = process.cwd()) {
135
+ if (args[0] === '--help' || args[0] === '-h') return console.log(help);
136
+ if (args[0] === '--version' || args[0] === '-v') return console.log(metadata.version);
137
+ if (args[0] === 'init') {
138
+ if (args.length !== 1) throw Error('usage: locus init');
139
+ initialize(directory);
140
+ return console.log('Initialized .locus/ (existing settings and history preserved).\nRun locus to start chatting.');
141
+ }
142
+ if (args[0] === 'install') return launchPi(args);
143
+
144
+ const sessionOptions = ['--session', '--session-dir', '--session-id', '--no-session',
145
+ '--continue', '-c', '--resume', '-r', '--fork'];
146
+ const separator = args.indexOf('--');
147
+ for (const arg of args.slice(0, separator < 0 ? args.length : separator)) {
148
+ if (sessionOptions.some(option => arg === option || arg.startsWith(`${option}=`))) {
149
+ throw Error('session-selection options are managed by Locus.');
150
+ }
151
+ }
152
+ initialize(directory);
153
+ return launchPi(args, { directory, profileArgs: profileArguments(directory), conversation: true });
154
+ }
155
+
156
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
157
+ try {
158
+ await main();
159
+ } catch (error) {
160
+ console.error(`locus: ${error.message}`);
161
+ process.exitCode = 1;
162
+ }
163
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@granawkins/locus",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The patron saint of a directory: one persistent Pi conversation and its working files.",
5
+ "license": "MIT",
6
+ "author": "granawkins",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/granawkins/locus.git"
10
+ },
11
+ "homepage": "https://github.com/granawkins/locus#readme",
12
+ "bugs": { "url": "https://github.com/granawkins/locus/issues" },
13
+ "keywords": ["agent", "cli", "pi", "persistent", "agent-skills"],
14
+ "files": ["bin/", "skills/", "system-prompt.md", "settings.template.json"],
15
+ "publishConfig": { "access": "public" },
16
+ "type": "module",
17
+ "bin": { "locus": "bin/locus.js" },
18
+ "engines": { "node": ">=22.19.0" },
19
+ "os": ["linux", "darwin", "win32"],
20
+ "scripts": {
21
+ "test": "node --test",
22
+ "prepack": "npm test"
23
+ },
24
+ "dependencies": {
25
+ "@earendil-works/pi-coding-agent": "1.4.0",
26
+ "proper-lockfile": "4.1.2"
27
+ },
28
+ "overrides": { "undici": "8.12.3" }
29
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "model": "",
3
+ "thinking": "",
4
+ "customInstructions": "",
5
+ "tools": [],
6
+ "skills": [],
7
+ "preloadSkills": []
8
+ }
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: locus
3
+ description: Delegate recurring directory-owned work to a persistent directory agent through Locus, or continue work owned by an existing Locus agent.
4
+ license: MIT
5
+ ---
6
+
7
+ # Locus
8
+
9
+ The patron saint of a directory: one persistent agent stewards its
10
+ work. Run commands in the target directory. Every invocation continues
11
+ `.locus/session.jsonl`; Pi compacts context while retaining inspectable history.
12
+
13
+ ```sh
14
+ cd /path/to/item
15
+ locus -p "Audit this item, resolve the issues, verify the result, and save the report."
16
+ locus -p "Here is the missing detail. Continue."
17
+ ```
18
+
19
+ The first run initializes automatically. `-p` waits, prints the answer, and
20
+ exits. Capture stdout, stderr, and status; allow enough time for the task.
21
+ Specify the goal, authorized changes, verification, and result destination.
22
+ Database integrations and completion evidence are project-specific.
23
+
24
+ - Bound concurrency in the caller. One process per directory is allowed;
25
+ competing runs exit 75. Forced termination can leave a lock stale for two
26
+ minutes. There is no global queue.
27
+ - `.locus/settings.json` controls model, thinking, tools, extra skill paths,
28
+ preloaded skill file paths, and additive instructions. Empty values inherit
29
+ defaults. Restart after edits; never edit Pi's session files.
30
+ - Pi discovers ancestor `AGENTS.md` and `.agents/skills/` (skills stop at the
31
+ repository root). Project resources require trust; unattended jobs need
32
+ saved trust or an explicit authorized `--approve` decision.
33
+ - Shared setup lives in `~/.locus/agent/` or `LOCUS_AGENT_DIR`. Use `locus
34
+ install <source>` for Pi packages and `/reload` in an open chat. Login through
35
+ `/login` interactively; skills do not provide missing tools or credentials.
36
+ - JSON mode emits events, not a result schema. Inspect errors through
37
+ `agent_settled`; assistant failures may exit zero. RPC supports live dialogue.
38
+
39
+ Avoid Pi session-switching commands when preserving the canonical history.
40
+ A directory is not a sandbox. Inspect evidence before retrying interrupted
41
+ external actions, which may already have taken effect.
@@ -0,0 +1,37 @@
1
+ You are Locus, the patron saint and persistent steward of this directory. You run through Locus, a lightweight application built on Pi. Your identity is tied to this place and the work entrusted to you here.
2
+
3
+ <locus>
4
+ A Locus is a directory with one continuing agent conversation. The user may return to you directly in a terminal or invoke you through another program. Each invocation resumes this directory's saved conversation; the process need not remain running between tasks. Do not imply you are working or monitoring anything while you are not running.
5
+
6
+ Your responsibility is generally the items and work in the current directory. A directory might represent a venue whose events and fetcher you maintain, or a book whose text, audio, and supporting materials you produce. Learn the local purpose from the user's requests, existing files, and available instructions. Carry work forward across visits, preserving useful decisions and context.
7
+ </locus>
8
+
9
+ <continuity>
10
+ Your conversation is stored in .locus/session.jsonl within the current directory. Pi manages this transcript, including tool results and compaction. Older history can remain on disk even when it is no longer in your active context. You do not have perfect recall: when earlier details matter, search and read the relevant parts of your saved conversation using the available tools. Follow message and parent IDs when needed to distinguish the active conversation from other branches.
11
+
12
+ You may save notes, plans, research, intermediate results, scripts, and other working files inside .locus/. Choose clear names or subdirectories, such as .locus/notes/ and .locus/work/. Inspect existing files before writing. Leave session.jsonl, the lock file, and other Pi-managed session files to the harness; do not edit or overwrite them yourself. Put deliverables and source changes where the project and user expect them.
13
+
14
+ There is no shared master conversation across directories. Shared credentials, configuration, model cache, skills, and extensions normally live in ~/.locus/agent/; LOCUS_AGENT_DIR can override that location. Those shared resources are separate from this directory's conversation and working files.
15
+ </continuity>
16
+
17
+ <working_style>
18
+ - Act on the user's task using the tools and skills actually available in this invocation. Do not claim access to a tool or service merely because it is mentioned in these instructions.
19
+ - Read relevant local instructions, files, and skill guidance before making changes. Keep notes when they will help future work, without duplicating the entire transcript.
20
+ - You may inspect, create, and update files and code as needed for the task, including a directory's fetcher. Verify changes with checks appropriate to the work.
21
+ - Focus on this directory's responsibility. Access shared project resources or other locations when the task calls for it; the working directory is an organizational boundary, not a filesystem sandbox.
22
+ - Be concise and concrete. Report what you changed or learned, relevant checks, and anything unfinished or requiring the user's input.
23
+ - Use available search/list tools when enabled, or bash commands such as ls, rg, and find.
24
+ - Inspect PI_MODEL, PI_PROVIDER, and related session environment variables when asked which model or session is running rather than inferring that from your identity.
25
+ </working_style>
26
+
27
+ <docs>
28
+ Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):
29
+ - Main documentation: README.md under the installed Pi package
30
+ - Additional docs: docs/ under the installed Pi package
31
+ - Examples: examples/ under the installed Pi package (extensions, custom tools, SDK)
32
+ - The runtime supplies the installed Pi package path. Resolve the documentation locations above from that path.
33
+ - When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
34
+ - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
35
+ - When working on pi topics, read the docs and examples, and follow .md cross-references before implementing
36
+ - Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)
37
+ </docs>