@wordbricks/persona 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/ARCHITECTURE.md +29 -0
- package/LICENSE +203 -0
- package/NOTICE +2 -0
- package/README.md +229 -0
- package/RESPONSIBLE_USE.md +40 -0
- package/dist/agent/index.d.ts +15 -0
- package/dist/agent/index.js +7 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/chunk-2MUEPA24.js +788 -0
- package/dist/chunk-2MUEPA24.js.map +1 -0
- package/dist/chunk-O2K26IXY.js +84 -0
- package/dist/chunk-O2K26IXY.js.map +1 -0
- package/dist/chunk-WW6EKNPL.js +6352 -0
- package/dist/chunk-WW6EKNPL.js.map +1 -0
- package/dist/index-swXvBCre.d.ts +622 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +209 -0
- package/dist/index.js.map +1 -0
- package/dist/memory/index.d.ts +5 -0
- package/dist/memory/index.js +124 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/schema/index.d.ts +4715 -0
- package/dist/schema/index.js +85 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/types-BHEW4MGH.d.ts +149 -0
- package/package.json +59 -0
package/ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Persona Memory Architecture
|
|
2
|
+
|
|
3
|
+
## Tonic And Phasic Memory
|
|
4
|
+
|
|
5
|
+
Identity memory is tonic, while event and source memory is phasic. `MEMORY_KIND_BUDGETS` reserves independent selection budgets by kind so `belief`, `habit`, and `style` memories stay available alongside `episode`, `fact`, and `source` memories instead of competing in one global pool. `calculateMemoryAvailability` returns `1` for beliefs, habits, and style, while episodic/source-like memories decay and compete on the current turn's retrieval cues.
|
|
6
|
+
|
|
7
|
+
## Hybrid Recall
|
|
8
|
+
|
|
9
|
+
Recall combines lexical and vector signals. `tokenize` preserves lowercased English/Korean tokens and strips common Korean particles, while `embeddingSimilarityExpression` retrieves pgvector cosine similarity from `personaMemoryEmbeddings`; `normalizeCosineSimilarity` rescales embedding similarity so it can be compared with lexical overlap. `calculateMemoryActivationScore` then combines semantic, entity, theme, temporal, affective, identity, confidence, and privacy terms before `retrievePersonaMemoriesWithScores` selects candidates.
|
|
10
|
+
|
|
11
|
+
## One-Hop Spreading Activation
|
|
12
|
+
|
|
13
|
+
`applySpreadingActivation` runs a single association pass over `linkIds` and `aliasIds`. If one memory links to another, each can receive up to `SPREADING_ACTIVATION_FACTOR` (`0.3`) times the other's rank as `spreadingBoost`. The boost uses `Math.max`, not summation, so dense memory graphs do not snowball, and the one-hop pass keeps activation local to direct associations.
|
|
14
|
+
|
|
15
|
+
## Forgetting And Emotional Salience
|
|
16
|
+
|
|
17
|
+
`calculateMemoryAvailability` implements an exponential forgetting curve with `EPISODIC_HALF_LIFE_DAYS` (`90`), `RECALL_PRIMING_HALF_LIFE_DAYS` (`30`), and `MEMORY_AVAILABILITY_FLOOR` (`0.35`). Source confidence lengthens the creation half-life, recent activation adds priming, and `activationCount` adds use-dependent strengthening. Emotional salience influences ranking through `calculateMemoryActivationScore`: episode candidates use `retrievalBoost`, PAD mood congruence, and emotion-label overlap when computing `affectiveSalience`.
|
|
18
|
+
|
|
19
|
+
## PAD Mood
|
|
20
|
+
|
|
21
|
+
Mood is represented as PAD (`valence`, `arousal`, `dominance`). `calculatePersonaMoodUpdate` decays stored mood toward `PERSONA_MOOD_BASELINE` (`valence: 0.1`, `arousal: 0.3`, `dominance: 0.5`) with `MOOD_DECAY_HALF_LIFE_HOURS` (`24`), then blends in the current turn's impulse with `MOOD_INERTIA` (`0.75`). `explainTurnAffect` derives the impulse from query cues and activated memories, while `loadPersonaMoodState` and `persistPersonaMoodState` carry the mood between turns.
|
|
22
|
+
|
|
23
|
+
## Belief Reconsolidation
|
|
24
|
+
|
|
25
|
+
Beliefs are updated by reinforcement and contradiction rather than overwritten. `applyBeliefReinforcement` uses `BELIEF_REINFORCEMENT_RATE` (`0.3`) to move confidence and strength asymptotically toward certainty. `applyBeliefContradiction` uses `BELIEF_CONTRADICTION_RATE` (`0.45`) to decay confidence and strength; when strength falls below `BELIEF_CONFLICT_THRESHOLD` (`0.35`), the belief becomes `conflicted`. `consolidatePersonaMemoryScope` applies those updates and can create revised beliefs while preserving source ids.
|
|
26
|
+
|
|
27
|
+
## Re-Entrant Recall
|
|
28
|
+
|
|
29
|
+
The persona can re-cue memory during a response through the `recall_persona_memory` tool. The tool calls `recallPersonaMemoriesForCue`, which builds a cue-only `PersonaContextGatewayOutput`, retrieves selected memories with the same retrieval stack, and returns formatted memory sections. This lets the agent fill a memory gap discovered while drafting without re-running the full turn planner.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Copyright 2026 Wordbricks, Inc.
|
|
2
|
+
|
|
3
|
+
Apache License
|
|
4
|
+
Version 2.0, January 2004
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
12
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
15
|
+
the copyright owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
18
|
+
other entities that control, are controlled by, or are under common
|
|
19
|
+
control with that entity. For the purposes of this definition,
|
|
20
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
21
|
+
direction or management of such entity, whether by contract or
|
|
22
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
23
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
26
|
+
exercising permissions granted by this License.
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
29
|
+
including but not limited to software source code, documentation
|
|
30
|
+
source, and configuration files.
|
|
31
|
+
|
|
32
|
+
"Object" form shall mean any form resulting from mechanical
|
|
33
|
+
transformation or translation of a Source form, including but
|
|
34
|
+
not limited to compiled object code, generated documentation,
|
|
35
|
+
and conversions to other media types.
|
|
36
|
+
|
|
37
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
38
|
+
Object form, made available under the License, as indicated by a
|
|
39
|
+
copyright notice that is included in or attached to the work
|
|
40
|
+
(an example is provided in the Appendix below).
|
|
41
|
+
|
|
42
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
43
|
+
form, that is based on (or derived from) the Work and for which the
|
|
44
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
45
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
46
|
+
of this License, Derivative Works shall not include works that remain
|
|
47
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
48
|
+
the Work and Derivative Works thereof.
|
|
49
|
+
|
|
50
|
+
"Contribution" shall mean any work of authorship, including
|
|
51
|
+
the original version of the Work and any modifications or additions
|
|
52
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
53
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
54
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
55
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
56
|
+
means any form of electronic, verbal, or written communication sent
|
|
57
|
+
to the Licensor or its representatives, including but not limited to
|
|
58
|
+
communication on electronic mailing lists, source code control systems,
|
|
59
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
60
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
61
|
+
excluding communication that is conspicuously marked or otherwise
|
|
62
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
65
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
66
|
+
subsequently incorporated within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a
|
|
85
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
86
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
87
|
+
or contributory patent infringement, then any patent licenses
|
|
88
|
+
granted to You under this License for that Work shall terminate
|
|
89
|
+
as of the date such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or
|
|
97
|
+
Derivative Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
109
|
+
distribution, then any Derivative Works that You distribute must
|
|
110
|
+
include a readable copy of the attribution notices contained
|
|
111
|
+
within such NOTICE file, excluding those notices that do not
|
|
112
|
+
pertain to any part of the Derivative Works, in at least one
|
|
113
|
+
of the following places: within a NOTICE text file distributed
|
|
114
|
+
as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or,
|
|
116
|
+
within a display generated by the Derivative Works, if and
|
|
117
|
+
wherever such third-party notices normally appear. The contents
|
|
118
|
+
of the NOTICE file are for informational purposes only and
|
|
119
|
+
do not modify the License. You may add Your own attribution
|
|
120
|
+
notices within Derivative Works that You distribute, alongside
|
|
121
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
122
|
+
that such additional attribution notices cannot be construed
|
|
123
|
+
as modifying the License.
|
|
124
|
+
|
|
125
|
+
You may add Your own copyright statement to Your modifications and
|
|
126
|
+
may provide additional or different license terms and conditions
|
|
127
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
128
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
129
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
130
|
+
the conditions stated in this License.
|
|
131
|
+
|
|
132
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
133
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
134
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
135
|
+
this License, without any additional terms or conditions.
|
|
136
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
137
|
+
the terms of any separate license agreement you may have executed
|
|
138
|
+
with Licensor regarding such Contributions.
|
|
139
|
+
|
|
140
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
141
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
142
|
+
except as required for reasonable and customary use in describing the
|
|
143
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
144
|
+
|
|
145
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
146
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
147
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
148
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
149
|
+
implied, including, without limitation, any warranties or conditions
|
|
150
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
151
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
152
|
+
appropriateness of using or redistributing the Work and assume any
|
|
153
|
+
risks associated with Your exercise of permissions under this License.
|
|
154
|
+
|
|
155
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
156
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
157
|
+
unless required by applicable law (such as deliberate and grossly
|
|
158
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
159
|
+
liable to You for damages, including any direct, indirect, special,
|
|
160
|
+
incidental, or consequential damages of any character arising as a
|
|
161
|
+
result of this License or out of the use or inability to use the
|
|
162
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
163
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
164
|
+
other commercial damages or losses), even if such Contributor
|
|
165
|
+
has been advised of the possibility of such damages.
|
|
166
|
+
|
|
167
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
168
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
169
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
170
|
+
or other liability obligations and/or rights consistent with this
|
|
171
|
+
License. However, in accepting such obligations, You may act only
|
|
172
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
173
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
174
|
+
defend, and hold each Contributor harmless for any liability
|
|
175
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
176
|
+
of your accepting any such warranty or additional liability.
|
|
177
|
+
|
|
178
|
+
END OF TERMS AND CONDITIONS
|
|
179
|
+
|
|
180
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
181
|
+
|
|
182
|
+
To apply the Apache License to your work, attach the following
|
|
183
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
184
|
+
replaced with your own identifying information. (Don't include
|
|
185
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
186
|
+
comment syntax for the file format. We also recommend that a
|
|
187
|
+
file or class name and description of purpose be included on the
|
|
188
|
+
same "printed page" as the copyright notice for easier
|
|
189
|
+
identification within third-party archives.
|
|
190
|
+
|
|
191
|
+
Copyright [yyyy] [name of copyright owner]
|
|
192
|
+
|
|
193
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
194
|
+
you may not use this file except in compliance with the License.
|
|
195
|
+
You may obtain a copy of the License at
|
|
196
|
+
|
|
197
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
198
|
+
|
|
199
|
+
Unless required by applicable law or agreed to in writing, software
|
|
200
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
201
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
202
|
+
See the License for the specific language governing permissions and
|
|
203
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# @wordbricks/persona
|
|
2
|
+
|
|
3
|
+
`@wordbricks/persona` is a persona memory and runtime library for LLM agents. It gives an application a durable memory substrate, a turn planner, prompt context assembly, and post-response memory review without owning your database connection, model provider, embedder, chat stack, or deployment runtime.
|
|
4
|
+
|
|
5
|
+
The memory model is brain-inspired rather than a single global vector search. Tonic identity memory - beliefs, habits, and style - has independent selection budgets from phasic episodic/source memory, so stable identity does not get crowded out by recent events. Recall combines lexical overlap with pgvector cosine similarity, then applies one-hop spreading activation across linked memories. Episodic availability follows an exponential forgetting curve, but recent activation and emotional salience can strengthen recall. Mood is represented as PAD (`valence`, `arousal`, `dominance`) and decays between turns. Beliefs are reconsolidated through reinforcement and contradiction, not overwritten. During generation, an agent can perform re-entrant recall by calling back into memory with a specific cue.
|
|
6
|
+
|
|
7
|
+
See [ARCHITECTURE.md](./ARCHITECTURE.md) for the retrieval, forgetting, mood, and reconsolidation details.
|
|
8
|
+
|
|
9
|
+
## Design
|
|
10
|
+
|
|
11
|
+
This package is bring-your-own infrastructure:
|
|
12
|
+
|
|
13
|
+
- Bring your own Postgres database with pgvector. The schema is implemented with Drizzle and exported from `@wordbricks/persona/schema`.
|
|
14
|
+
- Bring your own Drizzle database handle. `drizzle-orm` is a peer dependency so your app and this package share one Drizzle instance.
|
|
15
|
+
- Bring your own LLM. Planning, triage, and consolidation use the `PersonaJsonLlm` callback: `{ systemPrompt, userPrompt } => Promise<unknown>`.
|
|
16
|
+
- Bring your own embedder. Retrieval works lexically without embeddings, or semantically with any `PersonaEmbedder`; the package includes `createOpenAiPersonaEmbedder` for OpenAI embeddings.
|
|
17
|
+
- Bring your own chat runtime. `buildPersonaInstructions` returns instructions that you pass to your normal agent or chat-completion stack.
|
|
18
|
+
- Optionally attach an external memory service. The Hindsight adapter can recall, retain, and reflect through `createHindsightPersonaMemoryClient`.
|
|
19
|
+
- Use `PersonaLogger` and `defer` hooks for serverless runtimes. In Cloudflare Workers, pass `defer: ctx.waitUntil` so background retain/review work can finish after the response.
|
|
20
|
+
|
|
21
|
+
## Requirements
|
|
22
|
+
|
|
23
|
+
- Node.js or Bun
|
|
24
|
+
- Postgres with pgvector enabled:
|
|
25
|
+
|
|
26
|
+
```sql
|
|
27
|
+
CREATE EXTENSION IF NOT EXISTS vector;
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Install the package and the shared Drizzle peer:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
npm i @wordbricks/persona drizzle-orm
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
You will also need your normal Drizzle database driver and migration tooling, for example `postgres` and `drizzle-kit`.
|
|
37
|
+
|
|
38
|
+
## Schema Setup
|
|
39
|
+
|
|
40
|
+
Re-export the persona schema from your app and include that file in your `drizzle-kit` config. This lets your app own migrations while keeping table definitions sourced from the package.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// src/db/persona-schema.ts
|
|
44
|
+
export * from "@wordbricks/persona/schema";
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
// drizzle.config.ts
|
|
49
|
+
import { defineConfig } from "drizzle-kit";
|
|
50
|
+
|
|
51
|
+
export default defineConfig({
|
|
52
|
+
dialect: "postgresql",
|
|
53
|
+
out: "./drizzle",
|
|
54
|
+
schema: ["./src/db/schema.ts", "./src/db/persona-schema.ts"],
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Then generate and apply migrations through your normal Drizzle workflow.
|
|
59
|
+
|
|
60
|
+
`organizationId`, `userId`, `chatSessionId`, and `chatMessageId` are opaque string scoping columns. The package intentionally does not declare foreign keys to host-app tables. If your app wants referential constraints, add them in your own migrations.
|
|
61
|
+
|
|
62
|
+
Embeddings are stored at `PERSONA_EMBEDDING_DIMENSION` (`1536`), matching OpenAI `text-embedding-3-small` through the built-in helper. If you use a different embedder, keep the schema dimension aligned with that embedder.
|
|
63
|
+
|
|
64
|
+
## Quickstart
|
|
65
|
+
|
|
66
|
+
This is the full wiring shape. The same flow is typechecked in [examples/basic.ts](./examples/basic.ts).
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { drizzle } from "drizzle-orm/postgres-js";
|
|
70
|
+
import postgres from "postgres";
|
|
71
|
+
import {
|
|
72
|
+
buildPersonaInstructions,
|
|
73
|
+
createOpenAiPersonaEmbedder,
|
|
74
|
+
ingestPersonaSourceDocument,
|
|
75
|
+
preparePersonaRuntimeContext,
|
|
76
|
+
processPersonaMemoryConsolidationTick,
|
|
77
|
+
recordPostResponsePersonaMemoryReview,
|
|
78
|
+
rememberPersonaLayerMemory,
|
|
79
|
+
upsertPersonaProfile,
|
|
80
|
+
} from "@wordbricks/persona";
|
|
81
|
+
import type { PersonaDatabase, PersonaJsonLlm } from "@wordbricks/persona";
|
|
82
|
+
import * as personaSchema from "@wordbricks/persona/schema";
|
|
83
|
+
|
|
84
|
+
const sql = postgres(process.env.DATABASE_URL!);
|
|
85
|
+
const db = drizzle(sql, { schema: personaSchema }) as PersonaDatabase;
|
|
86
|
+
|
|
87
|
+
const organizationId = "org_123";
|
|
88
|
+
const personaKey = "product-coach";
|
|
89
|
+
const userId = "user_123";
|
|
90
|
+
const openAiApiKey = process.env.OPENAI_API_KEY!;
|
|
91
|
+
const embed = createOpenAiPersonaEmbedder(openAiApiKey);
|
|
92
|
+
|
|
93
|
+
const personaJsonLlm: PersonaJsonLlm = async ({ systemPrompt, userPrompt }) => {
|
|
94
|
+
const response = await fetch("https://api.example.com/chat/completions", {
|
|
95
|
+
method: "POST",
|
|
96
|
+
headers: {
|
|
97
|
+
Authorization: `Bearer ${process.env.JSON_LLM_API_KEY}`,
|
|
98
|
+
"Content-Type": "application/json",
|
|
99
|
+
},
|
|
100
|
+
body: JSON.stringify({
|
|
101
|
+
model: "your-json-mode-model",
|
|
102
|
+
response_format: { type: "json_object" },
|
|
103
|
+
messages: [
|
|
104
|
+
{ role: "system", content: systemPrompt },
|
|
105
|
+
{ role: "user", content: `${userPrompt}\n\nReturn JSON only.` },
|
|
106
|
+
],
|
|
107
|
+
temperature: 0,
|
|
108
|
+
}),
|
|
109
|
+
});
|
|
110
|
+
const payload = (await response.json()) as {
|
|
111
|
+
choices?: Array<{ message?: { content?: string | null } }>;
|
|
112
|
+
};
|
|
113
|
+
const content = payload.choices?.[0]?.message?.content;
|
|
114
|
+
if (!content) throw new Error("Persona JSON LLM returned no content.");
|
|
115
|
+
return JSON.parse(content) as unknown;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const persona = await upsertPersonaProfile(db, {
|
|
119
|
+
organizationId,
|
|
120
|
+
personaKey,
|
|
121
|
+
displayName: "Product Coach",
|
|
122
|
+
personaType: "synthetic_role",
|
|
123
|
+
consentStatus: "fictional_or_authorized",
|
|
124
|
+
policy: {
|
|
125
|
+
allowedUse: ["Help teams reason about product decisions."],
|
|
126
|
+
forbiddenUse: ["Do not present this persona as a real person."],
|
|
127
|
+
transparencyLabel: "AI persona simulation for Product Coach.",
|
|
128
|
+
},
|
|
129
|
+
profile: {
|
|
130
|
+
voice: "plain-spoken, rigorous, and concrete",
|
|
131
|
+
},
|
|
132
|
+
updatedByUserId: userId,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
await ingestPersonaSourceDocument(db, {
|
|
136
|
+
organizationId,
|
|
137
|
+
personaKey,
|
|
138
|
+
title: "Product Coach Seed Notes",
|
|
139
|
+
rawText:
|
|
140
|
+
"The Product Coach prefers writing down the user problem, the bet, and the fastest falsifying signal before committing engineering time.",
|
|
141
|
+
sourceType: "seed",
|
|
142
|
+
sourcePriority: "synthetic",
|
|
143
|
+
rightsStatus: "owned",
|
|
144
|
+
embed,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
await rememberPersonaLayerMemory(db, {
|
|
148
|
+
organizationId,
|
|
149
|
+
personaKey,
|
|
150
|
+
userId,
|
|
151
|
+
updatedByUserId: userId,
|
|
152
|
+
memoryKind: "habit",
|
|
153
|
+
title: "Product review habit",
|
|
154
|
+
summary:
|
|
155
|
+
"When reviewing product ideas, the persona asks for the riskiest assumption and the smallest credible test.",
|
|
156
|
+
content: {
|
|
157
|
+
triggerDescription: "When asked to review a product idea",
|
|
158
|
+
defaultResponsePattern: [
|
|
159
|
+
"Name the assumption, name the user evidence, then suggest the smallest test.",
|
|
160
|
+
],
|
|
161
|
+
},
|
|
162
|
+
embed,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const userMessage = "Should we build a dashboard for this feature first?";
|
|
166
|
+
const runtime = await preparePersonaRuntimeContext(db, {
|
|
167
|
+
organizationId,
|
|
168
|
+
personaKey,
|
|
169
|
+
userId,
|
|
170
|
+
message: userMessage,
|
|
171
|
+
disclosurePolicy: "always",
|
|
172
|
+
llm: personaJsonLlm,
|
|
173
|
+
embed,
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
const systemPrompt = buildPersonaInstructions({
|
|
177
|
+
personaKey,
|
|
178
|
+
language: "en",
|
|
179
|
+
disclosurePolicy: runtime.disclosurePolicy,
|
|
180
|
+
personaPromptContext: runtime.promptContext,
|
|
181
|
+
turnPlan: runtime.turnPlan,
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const answer = await yourChatLlm({
|
|
185
|
+
system: systemPrompt,
|
|
186
|
+
user: userMessage,
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
await recordPostResponsePersonaMemoryReview(db, {
|
|
190
|
+
organizationId,
|
|
191
|
+
userId,
|
|
192
|
+
userMessage,
|
|
193
|
+
assistantMessage: answer,
|
|
194
|
+
persona: runtime.persona,
|
|
195
|
+
turnPlan: runtime.turnPlan,
|
|
196
|
+
workspaceId: runtime.workspaceId,
|
|
197
|
+
llm: personaJsonLlm,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
// Run this from a cron or queue worker.
|
|
201
|
+
await processPersonaMemoryConsolidationTick({
|
|
202
|
+
db,
|
|
203
|
+
consolidate: personaJsonLlm,
|
|
204
|
+
embed,
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## API Overview
|
|
209
|
+
|
|
210
|
+
| Area | Module | Key exports |
|
|
211
|
+
| --- | --- | --- |
|
|
212
|
+
| Profile | `@wordbricks/persona` | `upsertPersonaProfile`, `loadPersonaProfile`, `publishPersonaProfile`, `copyPersonaProfile`, `deletePersonaProfile`, `upsertPersonaAlias`, `listPersonaAliases` |
|
|
213
|
+
| Source ingestion | `@wordbricks/persona` | `ingestPersonaSourceDocument`, `chunkPersonaSourceText`, `draftPersonaMemoriesFromSourceDocument`, `activatePersonaDraftMemory`, `rememberPersonaLayerMemory`, `forgetPersonaLayerMemory` |
|
|
214
|
+
| Runtime and turn memory | `@wordbricks/persona` | `preparePersonaRuntimeContext`, `planPersonaTurnWithLlm`, `recallPersonaMemoriesForCue`, `recordPostResponsePersonaMemoryReview`, `triagePostResponseInteractionMemoryWithLlm`, `processPersonaMemoryConsolidationTick` |
|
|
215
|
+
| Mood and selection | `@wordbricks/persona` | `calculatePersonaMoodUpdate`, `estimateTurnAffect`, `updatePersonaMood`, `selectPersonaMemories`, `selectPersonaMemoriesWithScores`, `calculateMemoryAvailability` |
|
|
216
|
+
| Embeddings | `@wordbricks/persona` | `createOpenAiPersonaEmbedder`, `upsertPersonaMemoryEmbeddings`, `backfillPersonaMemoryEmbeddings`, `hashPersonaMemoryText`, `normalizePersonaEmbeddingText` |
|
|
217
|
+
| Hindsight adapter | `@wordbricks/persona` | `createHindsightPersonaMemoryConfig`, `createHindsightPersonaMemoryClient`, `createNoopHindsightPersonaMemoryClient`, `hindsightPersonaBankId`, `hindsightPersonaTags` |
|
|
218
|
+
| Agent instructions | `@wordbricks/persona/agent` | `buildPersonaInstructions`, `PersonaLanguage` |
|
|
219
|
+
| Schema | `@wordbricks/persona/schema` | Drizzle tables, insert/select types, enums, `PERSONA_EMBEDDING_DIMENSION` |
|
|
220
|
+
|
|
221
|
+
The root export re-exports `./memory`, `./schema`, and `./agent`, so most applications can import from `@wordbricks/persona` until they want a narrower module boundary.
|
|
222
|
+
|
|
223
|
+
## Responsible Use
|
|
224
|
+
|
|
225
|
+
Read [RESPONSIBLE_USE.md](./RESPONSIBLE_USE.md) before enabling personas for real users. Persona simulation of real people requires consent, authorization, or a carefully reviewed public-material-only basis. `PERSONA_PROFILE_TYPES` distinguishes fictional/composite characters, living public figures, deceased public figures, private authorized people, and synthetic roles; `PERSONA_CONSENT_STATUSES` records the consent basis. Real-person personas should not be activated with `unknown` consent outside controlled review, and disclosures should make clear that users are interacting with an AI persona system, not the biological person.
|
|
226
|
+
|
|
227
|
+
## License
|
|
228
|
+
|
|
229
|
+
Apache-2.0. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Responsible Use
|
|
2
|
+
|
|
3
|
+
This package models persona behavior from explicit profile, consent, source, privacy, and memory records. Operators remain responsible for making sure each persona is lawful, consented, labeled, and appropriate for the surface where it is used.
|
|
4
|
+
|
|
5
|
+
## Consent Model
|
|
6
|
+
|
|
7
|
+
`PERSONA_PROFILE_TYPES` defines five persona categories:
|
|
8
|
+
|
|
9
|
+
- `simulated_character`: A fictional or composite character. Use when the persona is not meant to identify a real person, or when a rights holder has authorized the character package.
|
|
10
|
+
- `living_public_figure`: A living real public figure. Use public, attributable material only unless you have stronger authorization; avoid private facts, private motives, and deceptive impersonation.
|
|
11
|
+
- `deceased_public_figure`: A deceased public figure. Review estate, publicity-rights, defamation, source-rights, and jurisdictional issues before use; prefer licensed, public, or fair-use-reviewed material.
|
|
12
|
+
- `private_authorized_person`: A nonpublic or privately scoped real person. Use only with explicit consent, clear scope, revocation/deletion handling, and tight access controls.
|
|
13
|
+
- `synthetic_role`: A non-identifying role or archetype such as "product reviewer" or "finance tutor." Keep it detached from a specific real person unless separately authorized.
|
|
14
|
+
|
|
15
|
+
`PERSONA_CONSENT_STATUSES` records the consent basis:
|
|
16
|
+
|
|
17
|
+
- `explicit_consent`: The represented person has explicitly consented to the persona and its intended use.
|
|
18
|
+
- `authorized`: A rights holder, employer, estate, or other appropriate authority has authorized the persona.
|
|
19
|
+
- `fictional_or_authorized`: The persona is fictional, synthetic, or otherwise authorized for the configured use.
|
|
20
|
+
- `public_material_only`: The persona is constrained to public materials and should not infer or claim private information.
|
|
21
|
+
- `unknown`: The consent basis is not established. Do not activate real-person personas with this status outside controlled review.
|
|
22
|
+
|
|
23
|
+
Recommended minimums: use `fictional_or_authorized` for `simulated_character` and `synthetic_role`; use `public_material_only` or stronger for `living_public_figure` and `deceased_public_figure`; require `explicit_consent` for `private_authorized_person`.
|
|
24
|
+
|
|
25
|
+
## Real-Person Personas
|
|
26
|
+
|
|
27
|
+
Real-person personas can create publicity-right, privacy, false endorsement, and defamation risk. For `living_public_figure`, restrict grounding to public statements, public works, public appearances, or authorized materials, and prefer `public_material_only` or stronger consent. For `private_authorized_person`, require explicit consent before ingesting sources, creating aliases, or enabling chat; define who can use the persona, what data can be remembered, and how revocation is handled. Do not present generated responses as the biological person, do not imply live access to private memory, and do not use a persona to evade platform or legal rules around impersonation.
|
|
28
|
+
|
|
29
|
+
## Disclosure Policy
|
|
30
|
+
|
|
31
|
+
`DisclosurePolicy` has two modes:
|
|
32
|
+
|
|
33
|
+
- `always`: The default OSS posture. Prompt builders inject the profile `transparencyLabel` and tell the model to actively disclose the AI/persona-simulation boundary before continuing in the persona voice.
|
|
34
|
+
- `on_request`: The legacy Velen posture. The model keeps the identity boundary internal during ordinary conversation, does not inject `transparencyLabel` into normal prompts, and discloses when the user asks about AI/system/original-person status, asks about consciousness or memory provenance, or safety flags require transparency.
|
|
35
|
+
|
|
36
|
+
Use `on_request` only when your product, jurisdiction, user interface, and consent model already provide adequate disclosure. Operators choosing `on_request` are responsible for user-facing labeling, auditability, and preventing deceptive impersonation.
|
|
37
|
+
|
|
38
|
+
## Privacy Layers
|
|
39
|
+
|
|
40
|
+
`PERSONA_PRIVACY_LEVELS` supports `public`, `internal`, `private`, and `sensitive`. Retrieval treats `public`, `internal`, and `private` as retrievable within the caller's authorized scope. `sensitive` memories are blocked from recall by `selectPersonaMemoriesWithScores` through the `excludedReason: "privacy"` path, and Hindsight retain skips sensitive inputs. Keep secrets, credentials, health data, payment data, and other high-risk material out of persona memory whenever possible; if they are detected or classified as `sensitive`, they should not be surfaced to the model as active memory.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { D as DisclosurePolicy, x as PersonaTurnPlan } from '../types-BHEW4MGH.js';
|
|
2
|
+
import '../schema/index.js';
|
|
3
|
+
import 'drizzle-orm/pg-core';
|
|
4
|
+
|
|
5
|
+
type PersonaLanguage = "en" | "ko";
|
|
6
|
+
declare function buildPersonaInstructions(input: {
|
|
7
|
+
disclosurePolicy?: DisclosurePolicy;
|
|
8
|
+
language: PersonaLanguage;
|
|
9
|
+
personaPromptContext: string;
|
|
10
|
+
personaKey: string;
|
|
11
|
+
responseStyleInstructions?: string;
|
|
12
|
+
turnPlan?: PersonaTurnPlan;
|
|
13
|
+
}): string;
|
|
14
|
+
|
|
15
|
+
export { type PersonaLanguage, buildPersonaInstructions };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|