@9gix/pi-timestamp 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/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-11-25
4
+
5
+ - Initial release.
6
+ - Cache-safe timestamp injection into chat/Responses API messages.
7
+ - Optional system-prompt injection (`TS_SYSTEM_PROMPT=1`).
8
+ - Full env-var configuration: format, template, timezone, position, cadence, roles.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 9gix
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 ADDED
@@ -0,0 +1,87 @@
1
+ # @9gix/pi-timestamp
2
+
3
+ Cache-safe timestamp injection for [pi-coding-agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent).
4
+
5
+ Injects the current wall-clock time into messages **just-in-time** (tail/head-safe — no prefix-cache break), so the model always knows what time it is. Optionally also injects into the system prompt, and fully configurable via environment variables.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:@9gix/pi-timestamp
11
+ ```
12
+
13
+ Or from git:
14
+
15
+ ```bash
16
+ pi install git:github.com/9gix/pi-timestamp
17
+ ```
18
+
19
+ ## How it works
20
+
21
+ On every `before_provider_request`, the extension formats the current time as a short bracketed tag, e.g.:
22
+
23
+ ```
24
+ [2026-11-25 09:43 SGT]
25
+ ```
26
+
27
+ and applies it to the last eligible message in the outgoing payload:
28
+
29
+ - **Chat API** (`payload.messages`): tagged on the last user/assistant text message.
30
+ - **Responses API** (`payload.input`): tagged on the last user/assistant item.
31
+ - Tool results and tool-call-only assistant turns are skipped.
32
+ - The tag is idempotent — a stale tag is stripped before a fresh one is applied, so repeated requests don't stack tags.
33
+
34
+ By default this only touches the last message, keeping the conversation prefix identical across requests — **the prompt prefix cache stays intact**.
35
+
36
+ ## Configuration
37
+
38
+ All settings are read from environment variables when the extension loads.
39
+
40
+ | Variable | Default | Description |
41
+ | --- | --- | --- |
42
+ | `TS_ENABLE` | `1` | Set to `0` to disable entirely. |
43
+ | `TS_FORMAT` | `iso` | `iso`, `us`, `full`, or a custom template via `TS_TEMPLATE`. |
44
+ | `TS_TEMPLATE` | – | Custom format with placeholders: `{date} {time} {dow} {tz}`. Overrides `TS_FORMAT`. |
45
+ | `TS_TZ` | system local | IANA timezone name, e.g. `Asia/Singapore`. |
46
+ | `TS_HOURS24` | `1` | `0` for 12-hour am/pm. |
47
+ | `TS_INCLUDE_YEAR` | `1` | `0` to show a two-digit year. |
48
+ | `TS_POSITION` | `begin` | `end` to place the tag at the tail of the message instead of the head. |
49
+ | `TS_PREFIX` | – | Label inside the brackets, e.g. `now:` → `[now: 2026-11-25 09:43]`. |
50
+ | `TS_TZ_LABEL` | – | Timezone abbreviation to append, e.g. `SGT`. |
51
+ | `TS_DOW` | `0` | `1` to include the day of week (Mon, Tue, …). |
52
+ | `TS_SECONDS` | `0` | `1` to include seconds. |
53
+ | `TS_MIN_GAP` | `0` | Minimum minutes between injections (`0` = every request). |
54
+ | `TS_ROLES` | `user` | `user`, `assistant`, or `both` — which roles get tagged. |
55
+ | `TS_SYSTEM_PROMPT` | `0` | `1` to **also** append `[Current time: …]` to the system message. |
56
+
57
+ ### ⚠️ System prompt injection
58
+
59
+ `TS_SYSTEM_PROMPT=1` rewrites the system message on every injection, which **breaks the prefix cache**. If you use it, set `TS_MIN_GAP` to at least `15` so the system prompt changes only rarely (the extension prints a warning otherwise).
60
+
61
+ ## Examples
62
+
63
+ ```bash
64
+ # Singapore time, 24h, at the tail of user messages
65
+ TS_TZ=Asia/Singapore TS_TZ_LABEL=SGT TS_POSITION=end pi
66
+
67
+ # Day of week + seconds, tag at the head
68
+ TS_DOW=1 TS_SECONDS=1 pi
69
+
70
+ # Custom template
71
+ TS_TEMPLATE="{dow} {date} {time} {tz}" pi
72
+
73
+ # Rare system-prompt refresh for long sessions
74
+ TS_SYSTEM_PROMPT=1 TS_MIN_GAP=30 pi
75
+ ```
76
+
77
+ ## Development
78
+
79
+ ```bash
80
+ npm install
81
+ npm run check # type-check
82
+ pi -e ./extensions/timestamp.ts
83
+ ```
84
+
85
+ ## License
86
+
87
+ [MIT](./LICENSE)
@@ -0,0 +1,224 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ /**
4
+ * Custom timestamp extension — cache-safe, highly configurable.
5
+ *
6
+ * Injects current time as plain text into messages (default: tail-safe, no cache break).
7
+ * Optionally can also inject into system prompt (TS_SYSTEM_PROMPT=1) — WARNING: breaks prefix cache.
8
+ *
9
+ * Config via env vars:
10
+ * TS_ENABLE - "0" to disable entirely (default: 1)
11
+ * TS_FORMAT - "iso" (default), "us", "full", or custom via TS_TEMPLATE
12
+ * TS_TEMPLATE - Custom format: {date} {time} {dow} {tz} {seconds}
13
+ * TS_TZ - Timezone name (default: system local, e.g. Asia/Singapore)
14
+ * TS_HOURS24 - "1" for 24-hour (default), "0" for 12-hour am/pm
15
+ * TS_INCLUDE_YEAR - "1" include year (default), "0" omit
16
+ * TS_POSITION - "begin" (default) or "end" — where to place tag in message
17
+ * TS_PREFIX - Prefix inside brackets, e.g. "now:" → [now: 2026-11-25 09:43] (default: "")
18
+ * TS_TZ_LABEL - Timezone abbreviation to append, e.g. "SGT" (default: "")
19
+ * TS_DOW - "1" to include day of week (Mon, Tue...) (default: 0)
20
+ * TS_SECONDS - "1" to include seconds (default: 0)
21
+ * TS_MIN_GAP - Min minutes between injections (default: 0 = every message)
22
+ * TS_ROLES - "user" (default), "assistant", or "both" — which roles get tagged
23
+ * TS_SYSTEM_PROMPT - "1" to ALSO append to system prompt (default: 0).
24
+ * WARNING: Breaks prefix cache. Use with TS_MIN_GAP >= 15.
25
+ */
26
+
27
+ type Rec = Record<string, unknown>;
28
+
29
+ const ENABLE = (process.env.TS_ENABLE ?? "1") !== "0";
30
+ const FORMAT = process.env.TS_FORMAT ?? "iso";
31
+ const TEMPLATE = process.env.TS_TEMPLATE || "";
32
+ const TZ = process.env.TS_TZ || Intl.DateTimeFormat().resolvedOptions().timeZone;
33
+ const HOURS24 = (process.env.TS_HOURS24 ?? "1") === "1";
34
+ const INCLUDE_YEAR = (process.env.TS_INCLUDE_YEAR ?? "1") === "1";
35
+ const POSITION = (process.env.TS_POSITION ?? "begin") === "end" ? "end" : "begin";
36
+ const PREFIX = process.env.TS_PREFIX ?? "";
37
+ const TZ_LABEL = process.env.TS_TZ_LABEL ?? "";
38
+ const DOW = (process.env.TS_DOW ?? "0") === "1";
39
+ const SECONDS = (process.env.TS_SECONDS ?? "0") === "1";
40
+ const MIN_GAP_MINUTES = parseInt(process.env.TS_MIN_GAP ?? "0", 10);
41
+ const ROLES = process.env.TS_ROLES ?? "user"; // "user" | "assistant" | "both"
42
+ const SYSTEM_PROMPT = (process.env.TS_SYSTEM_PROMPT ?? "0") === "1";
43
+
44
+ // Warn if system prompt injection enabled without a gap
45
+ if (SYSTEM_PROMPT && MIN_GAP_MINUTES < 15) {
46
+ console.warn(`[timestamp] TS_SYSTEM_PROMPT=1 with TS_MIN_GAP=${MIN_GAP_MINUTES} will break prefix cache frequently. Consider TS_MIN_GAP>=15.`);
47
+ }
48
+
49
+ let lastInjectTime = 0;
50
+
51
+ // Strip regex for idempotency — matches [timestamp tag] at beginning or end of content
52
+ const TS_STRIP_END = /\n\[[^\]\n]{3,60}\]\s*$/;
53
+ const TS_STRIP_BEGIN = /^\[[^\]\n]{3,60}\]\n?/;
54
+
55
+ function getParts(now: Date): Record<string, string> {
56
+ const get = (locale: string, opts: Intl.DateTimeFormatOptions) => {
57
+ const parts = new Intl.DateTimeFormat(locale, { timeZone: TZ, ...opts }).formatToParts(now);
58
+ return (t: string) => parts.find(p => p.type === t)?.value ?? "";
59
+ };
60
+
61
+ // Date parts
62
+ const dateGet = get("en-CA", { year: "numeric", month: "2-digit", day: "2-digit" });
63
+ const year = dateGet("year");
64
+ const month = dateGet("month");
65
+ const day = dateGet("day");
66
+ const dateStr = `${INCLUDE_YEAR ? year : year.slice(-2)}-${month}-${day}`;
67
+
68
+ // Time parts
69
+ const timeOpts: Intl.DateTimeFormatOptions = {
70
+ hour: "2-digit", minute: "2-digit", hour12: !HOURS24,
71
+ ...(SECONDS ? { second: "2-digit" } : {}),
72
+ };
73
+ const timeGet = get("en-CA", timeOpts);
74
+ let timeStr = `${timeGet("hour")}:${timeGet("minute")}`;
75
+ if (SECONDS) timeStr += `:${timeGet("second")}`;
76
+ if (!HOURS24) {
77
+ const period = timeGet("dayPeriod");
78
+ if (period) timeStr += period.toLowerCase();
79
+ }
80
+
81
+ // Day of week
82
+ let dowStr = "";
83
+ if (DOW) {
84
+ const dowGet = get("en-US", { weekday: "short" });
85
+ dowStr = dowGet("weekday");
86
+ }
87
+
88
+ return { dateStr, timeStr, dowStr, tzLabel: TZ_LABEL };
89
+ }
90
+
91
+ function formatTimestamp(): string {
92
+ const now = new Date();
93
+ const p = getParts(now);
94
+
95
+ let inner: string;
96
+
97
+ if (TEMPLATE) {
98
+ // Custom template with placeholders
99
+ inner = TEMPLATE
100
+ .replace(/\{date\}/g, p.dateStr)
101
+ .replace(/\{time\}/g, p.timeStr)
102
+ .replace(/\{dow\}/g, p.dowStr)
103
+ .replace(/\{tz\}/g, p.tzLabel);
104
+ } else {
105
+ // Standard formats
106
+ const parts: string[] = [];
107
+ if (p.dowStr) parts.push(p.dowStr);
108
+ parts.push(p.dateStr);
109
+ parts.push(p.timeStr);
110
+ if (p.tzLabel) parts.push(p.tzLabel);
111
+ inner = parts.join(" ");
112
+ }
113
+
114
+ const prefix = PREFIX ? `${PREFIX} ` : "";
115
+ return `[${prefix}${inner}]`;
116
+ }
117
+
118
+ function chatShouldInject(last: Rec): boolean {
119
+ if (ROLES === "user" && last.role !== "user") return false;
120
+ if (ROLES === "assistant" && last.role !== "assistant") return false;
121
+
122
+ if (last.role === "user") {
123
+ const content = last.content;
124
+ if (Array.isArray(content) && content.some((b) => (b as Rec).type === "tool_result")) {
125
+ return false;
126
+ }
127
+ return true;
128
+ }
129
+ if (last.role === "assistant") {
130
+ const hasToolCalls = Array.isArray(last.tool_calls) && last.tool_calls.length > 0;
131
+ const hasContent = last.content != null && last.content !== "";
132
+ return !hasToolCalls && hasContent;
133
+ }
134
+ return false;
135
+ }
136
+
137
+ function responsesShouldInject(last: Rec): boolean {
138
+ if (ROLES === "user" && last.role !== "user") return false;
139
+ if (ROLES === "assistant" && last.role !== "assistant") return false;
140
+
141
+ if (last.role === "user") return true;
142
+ if (last.type === "message" && last.role === "assistant") {
143
+ return Array.isArray(last.content) && last.content.length > 0;
144
+ }
145
+ return false;
146
+ }
147
+
148
+ export default function (pi: ExtensionAPI) {
149
+ if (!ENABLE) return;
150
+
151
+ pi.on("before_provider_request", (event: any) => {
152
+ const now = Date.now();
153
+ if (MIN_GAP_MINUTES > 0 && (now - lastInjectTime) < MIN_GAP_MINUTES * 60 * 1000) {
154
+ return;
155
+ }
156
+
157
+ const payload = event.payload as Rec;
158
+
159
+ // System prompt injection (optional, cache-breaking)
160
+ if (SYSTEM_PROMPT) {
161
+ // Some APIs put system prompt in messages[0], others have a separate system field
162
+ const sysIdx = Array.isArray(payload.messages)
163
+ ? (payload.messages as Rec[]).findIndex(m => m.role === "system")
164
+ : -1;
165
+ if (sysIdx >= 0) {
166
+ const sysMsg = (payload.messages as Rec[])[sysIdx];
167
+ if (typeof sysMsg.content === "string") {
168
+ const tag = formatTimestamp();
169
+ if (!sysMsg.content.includes(tag)) {
170
+ sysMsg.content = sysMsg.content.replace(TS_STRIP_END, "").replace(TS_STRIP_BEGIN, "").trimEnd() + `\n\n[Current time: ${tag.replace(/^\[|\]$/g, "")}]`;
171
+ }
172
+ }
173
+ }
174
+ }
175
+
176
+ // Message tail/head injection (cache-safe)
177
+ const isResponses = Array.isArray(payload.input);
178
+ const items = isResponses
179
+ ? (payload.input as Rec[])
180
+ : Array.isArray(payload.messages)
181
+ ? (payload.messages as Rec[])
182
+ : undefined;
183
+ if (!items) return;
184
+
185
+ const last = items[items.length - 1];
186
+ if (!last) return;
187
+ if (!(isResponses ? responsesShouldInject(last) : chatShouldInject(last))) return;
188
+
189
+ lastInjectTime = now;
190
+ const tag = formatTimestamp();
191
+
192
+ const applyTag = (text: string): string => {
193
+ let clean = text.replace(TS_STRIP_BEGIN, "").replace(TS_STRIP_END, "");
194
+ return POSITION === "begin" ? `${tag}\n${clean}` : `${clean}\n${tag}`;
195
+ };
196
+
197
+ if (typeof last.content === "string") {
198
+ last.content = applyTag(last.content);
199
+ } else if (Array.isArray(last.content)) {
200
+ const blocks = [...(last.content as Rec[])];
201
+ const idx = blocks.length - 1;
202
+ const lastBlock = blocks[idx] as { text?: unknown } | undefined;
203
+ if (lastBlock && typeof lastBlock.text === "string") {
204
+ blocks[idx] = { ...lastBlock, text: applyTag(String(lastBlock.text)) };
205
+ } else if (POSITION === "begin" && blocks.length > 0) {
206
+ const first = blocks[0] as { text?: unknown } | undefined;
207
+ if (first && typeof first.text === "string") {
208
+ blocks[0] = { ...first, text: `${tag}\n${first.text}` };
209
+ } else {
210
+ blocks.unshift({ type: isResponses ? "input_text" : "text", text: tag });
211
+ }
212
+ } else if (isResponses && last.role === "assistant") {
213
+ blocks.push({ type: "output_text", text: `\n${tag}`, annotations: [] });
214
+ } else if (isResponses) {
215
+ blocks.push({ type: "input_text", text: `\n${tag}` });
216
+ } else {
217
+ blocks.push({ type: "text", text: `\n${tag}` });
218
+ }
219
+ last.content = blocks;
220
+ }
221
+
222
+ return event.payload;
223
+ });
224
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@9gix/pi-timestamp",
3
+ "version": "0.1.0",
4
+ "description": "Cache-safe timestamp injection for pi-coding-agent — injects the current time into messages (optionally also the system prompt), with configurable format, timezone, position, and cadence.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "pi-extension",
9
+ "timestamp",
10
+ "time",
11
+ "context"
12
+ ],
13
+ "type": "module",
14
+ "license": "MIT",
15
+ "author": "9gix",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/9gix/pi-timestamp.git"
19
+ },
20
+ "files": [
21
+ "extensions",
22
+ "README.md",
23
+ "LICENSE",
24
+ "CHANGELOG.md"
25
+ ],
26
+ "peerDependencies": {
27
+ "@earendil-works/pi-coding-agent": "*"
28
+ },
29
+ "devDependencies": {
30
+ "@earendil-works/pi-coding-agent": "^1.6.0",
31
+ "@types/node": "^24.13.3",
32
+ "typescript": "^5.9.3"
33
+ },
34
+ "scripts": {
35
+ "check": "tsc --noEmit"
36
+ },
37
+ "pi": {
38
+ "extensions": [
39
+ "./extensions/timestamp.ts"
40
+ ],
41
+ "changelogPath": "./CHANGELOG.md"
42
+ }
43
+ }